diff --git a/environments/.gitignore b/environments/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3bbe7b6f921890134bd22373cfdd89e91d5e788f --- /dev/null +++ b/environments/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +*.pyo diff --git a/environments/LICENSE b/environments/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9cd205d2a58c0326a490e1151baef4a6e87b2d6d --- /dev/null +++ b/environments/LICENSE @@ -0,0 +1,30 @@ +GameDojo Non-Commercial Research License 1.0 + +Copyright (c) 2026 the GameDojo authors + +The GameDojo authors grant permission to use, reproduce, modify, and share +original GameDojo environment code and the accompanying configuration, +documentation, and training and evaluation code in this directory solely for +non-commercial scientific research, including reproduction of research results. + +Non-commercial scientific research is work whose primary purpose is scientific +inquiry and whose use of these materials is neither primarily directed toward +commercial advantage nor intended for monetary compensation. Commercial use +requires separate written permission from the applicable rights holders. + +Copies and substantial portions of the covered materials, including modified +copies, must retain this copyright notice and license. Modified copies must +identify their changes and may be shared only under these terms. + +All copyrights, trademarks, and other intellectual property rights in the +original games, including their titles, characters, artwork, and audio, remain +exclusively with their respective original game companies and rights holders. +GameDojo has no affiliation, endorsement, or sponsorship from those parties. +This license grants no rights in third-party material. Separately licensed +components remain subject to their own terms. See THIRD_PARTY_NOTICES.md. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE, AND NON-INFRINGEMENT. TO THE EXTENT PERMITTED BY LAW, THE AUTHORS ARE +NOT LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY ARISING FROM THE MATERIALS +OR THEIR USE. diff --git a/environments/README.md b/environments/README.md new file mode 100644 index 0000000000000000000000000000000000000000..519544f8450764d7e01f9a6c8eb452245cd07894 --- /dev/null +++ b/environments/README.md @@ -0,0 +1,43 @@ +# GameDojo environments + +GameDojo contains 120 boss encounters across 20 games. The environment package provides browser play, Gymnasium interfaces, scripted reference controllers, and a model evaluation harness. + +## Setup + +From this directory, install Python 3.12 dependencies and a Chromium browser for RGB observations. Install Node.js and put `node` on `PATH` to use the symbolic back end for the shared web games. Minecraft RGB observations require a working OpenGL context through ModernGL. + +```sh +python -m pip install -r requirements-games.txt +python -m playwright install chromium +``` + +## Play in a browser + +Serve the game launcher at `http://127.0.0.1:8766/`. + +```sh +python -m http.server 8766 --bind 127.0.0.1 --directory games/web +``` + +Start the Minecraft play server in another terminal. Its page is available directly at `http://127.0.0.1:8765/`. + +```sh +python games/prototype/bossbench/play_server.py +``` + +## Train and evaluate + +Set `PYTHONPATH=games/prototype` when importing `bossbench`. The `BENCH_CASES` registry in `bossbench.scope` lists the official encounters. Use `bossbench.make_policy_env` for 200 ms keyboard and mouse actions, `bossbench.make_compact_env` for discrete semantic actions, and `bossbench.make_training_env` for the step-damage reward wrapper. + +```sh +python check_games.py --game terraria_remake --out terraria-check.json +python run_model.py --case doom/cyberdemon --tier normal --policy noop --max-steps 1 +``` + +`run_model.py` accepts `--format lumine` for CUA or `--format semantic` for semantic actions, and `--time paused` or `--time realtime`. For model evaluation, use `--policy chat` and set `--base-url` and `--model` to your OpenAI-compatible endpoint and model. Run `python run_model.py --help` for the available options. + +## Copyright and license + +All copyrights, trademarks, and other intellectual property rights in the original games, including their titles, characters, artwork, and audio, remain exclusively with their respective original game companies and rights holders. + +Original GameDojo materials in this directory are available for non-commercial scientific research under the [GameDojo Non-Commercial Research License](LICENSE). See the [third-party notices](THIRD_PARTY_NOTICES.md) and the [project copyright and use statement](https://gamedojo-benchmark.github.io/). diff --git a/environments/THIRD_PARTY_NOTICES.md b/environments/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000000000000000000000000000000000000..992e2941524a68ec8d56896acbabb670f0b8700d --- /dev/null +++ b/environments/THIRD_PARTY_NOTICES.md @@ -0,0 +1,8 @@ +# Third-party notices + +- Three.js r160 is bundled as `games/web/games/_boss3d/vendor/three.min.js`. Copyright © 2010–2023 Three.js authors. The [MIT license](games/web/games/_boss3d/vendor/LICENSE) applies to that component. +- All copyrights, trademarks, and other intellectual property rights in the original games, including their titles, characters, artwork, and audio, remain exclusively with their respective original game companies and rights holders. The GameDojo license grants rights in original GameDojo material only. +- Quake II’s deterministic trigonometry in `q2core.js` adapts [fdlibm](https://www.netlib.org/fdlibm/). Copyright © 1993 Sun Microsystems, Inc. See the [fdlibm permission notice](games/web/games/quake2_remake/LICENSE.fdlibm). +- The Battle City environment includes stage layouts and spawn order transcribed from the reference game via an [annotated disassembly](https://github.com/cyneprepou4uk/NES-Games-Disassembly/blob/6c145873e0f344ac4f132f451ac2dc7ea95cea6b/Battle%20City/bank_FF.asm) and the [vgrichina/battlecity reference implementation](https://github.com/vgrichina/battlecity). The Mega Man environment includes weapon and boss tables transcribed via an [annotated disassembly](https://github.com/plasticsmoke/megaman1-disassembly-ca65/tree/2771fb3). The GameDojo license does not grant rights in the original games or their data. +- The Kirby encounters reference the [Kirby's Dream Land disassembly](https://github.com/ElectroDeoxys/kirbydreamland/tree/dba74416a66e4641204073276c0330f07b30cf12) and WiKirby. The source-game graphics and audio are excluded from the package. +- Upstream references for Need for Speed: Most Wanted, Hexen II, Quake II, and Tomb Raider are recorded in their game manifests. diff --git a/environments/check_games.py b/environments/check_games.py new file mode 100644 index 0000000000000000000000000000000000000000..0a0a3046f57c367acf7135c9e418edbefd8c103b --- /dev/null +++ b/environments/check_games.py @@ -0,0 +1,44 @@ +"""Run from the delivered package in a clean Python environment. No model calls.""" +import argparse, hashlib, json, os, sys, time, traceback +from pathlib import Path + +parser = argparse.ArgumentParser() +parser.add_argument('--game', required=True) +parser.add_argument('--out', required=True) +args = parser.parse_args() +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT / 'games/prototype')) +import bossbench +from bossbench.scope import BENCH_CASES +from bossbench_llm import lumine, prompting +cases = sorted(k for k,v in BENCH_CASES.items() if v['game']==args.game) +report = {'game':args.game,'python':sys.version,'checks':[], 'started':time.time(), 'test':'reset + RGB + one valid 200ms action; not a win/performance evaluation'} +for case in cases: + for tier in ('easy','normal','hard'): + env = None + start = time.time() + try: + env = bossbench.make_policy_env(case) + obs, info = env.reset(seed=1, options={'tier':tier}) + assert obs.shape == (480,854,3), obs.shape + assert str(obs.dtype) == 'uint8', obs.dtype + kind = prompting.mouse_kind(args.game) + action = lumine.from_packet(bossbench.NOOP, mouse_kind=kind) + parsed = lumine.parse('\n\n\n\n'+action, mouse_kind=kind) + assert parsed.ok, parsed + nxt, reward, terminated, truncated, step_info = env.step(parsed.packet) + assert nxt.shape == (480,854,3) + assert prompting.system_prompt(args.game, case, 'lumine', 'en') + report['checks'].append({'case':case,'tier':tier,'passed':True,'rgb_sha256':hashlib.sha256(obs.tobytes()).hexdigest(),'reward':float(reward),'seconds':time.time()-start}) + except Exception: + report['checks'].append({'case':case,'tier':tier,'passed':False,'error':traceback.format_exc(),'seconds':time.time()-start}) + finally: + if env is not None: + try: env.close() + except Exception: pass + Path(args.out).write_text(json.dumps(report,indent=2),encoding='utf-8') +report['passed'] = len(report['checks']) == 18 and all(c['passed'] for c in report['checks']) +report['finished'] = time.time() +Path(args.out).write_text(json.dumps(report,indent=2),encoding='utf-8') +print(json.dumps({'game':args.game,'passed':report['passed'],'checks':len(report['checks'])}), flush=True) +sys.exit(0 if report['passed'] else 1) diff --git a/environments/games/prototype/bossbench/__init__.py b/environments/games/prototype/bossbench/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..147d193bf0321f29c46b6909a1c225f88731ac8c --- /dev/null +++ b/environments/games/prototype/bossbench/__init__.py @@ -0,0 +1,127 @@ +"""BossBench: every case behind one Gymnasium interface (unified.py), whatever engine runs it. + + import bossbench + bossbench.ENVS # {"2d/needle_warden": "web", "3d/minecraft_wither": "py", ...} + env = bossbench.make("2d/needle_warden", obs_mode="symbolic", time_mode="virtual_rt", latency=0.3) + obs, info = env.reset(seed=0, options={"difficulty": 0.5}) + obs, r, term, trunc, info = env.step("<|action_start|> 0 0 0 ; D ; D ; D,Space ; D ; J ; J <|action_end|>") + env.verifier() # {reward in [-1,1], win, outcome, boss_damage, ...} + gymnasium.make("BossBench/2d-needle_warden-v0") # same env through the gymnasium registry + +Engines: "web" = web/engine + one folder per game under web/games/ (JavaScript, 60 Hz; HK-style 2D cases), +"py" = this package (Minecraft). WEB_GAME maps each web case id to its game folder. +Those engines run at 60 Hz. Independent backends declare their own native clocks. + +The retired Python tank demo and its aliases are no longer registered. +""" +import os +import re + +from . import mc4d +from .core import FPS, RES, Arena, Body, Boss, BossBenchEnv, Case, Knobs +from .keymouse import NOOP, format_packet, parse_packet +from .unified import PyCaseEnv, UnifiedEnv + +PY_CASES = {f"3d/minecraft_{m}": (mc4d.make, {"mob": m}) for m in mc4d.MOBS} + + +def _web_cases(): + """{case id: game folder} for every BB.CASES['...'] = registration under web/games//, found without + starting Node. Folders starting with "_" (the template) or without an index.html, and tests/ shots/, are skipped.""" + games = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "web", "games") + out = {} + for game in sorted(os.listdir(games)) if os.path.isdir(games) else []: + if game.startswith(("_", ".")) or not os.path.isfile(os.path.join(games, game, "index.html")): + continue + for d, sub, files in os.walk(os.path.join(games, game)): + sub[:] = [s for s in sub if s not in ("tests", "shots")] + for f in files: + if f.endswith(".js"): + src = open(os.path.join(d, f), encoding="utf-8").read() + for i in re.findall(r"BB\.CASES\['([^']+)'\]\s*=", src): + if out.setdefault(i, game) != game: + raise RuntimeError(f"web case {i!r} registered by two games: {out[i]}, {game}") + return out + + +WEB_GAME = _web_cases() +WEB_CASES = sorted(WEB_GAME) +ENVS = {**{i: "web" for i in WEB_CASES}, **{i: "py" for i in PY_CASES}} +ENGINE_BACKENDS = {} + + +def register_backend(case_id, factory): + """Explicitly register an independent GameBackend factory; this does not enroll it in training. + + Call in the integration module on each process, including spawned workers. + Each factory call must create an independent backend and own its resources. + """ + if not isinstance(case_id, str) or not re.fullmatch(r'[a-z0-9_]+/[a-z0-9_]+', case_id): + raise ValueError('case_id must be namespace/name using lowercase letters, digits or underscores') + if case_id in ENVS: + raise ValueError(f'case already registered: {case_id}') + if case_id in ('2d/tank_battle', 'tank_battle_1v1'): + raise ValueError('retired case cannot be registered again') + if not callable(factory): + raise TypeError('backend factory must be callable') + import gymnasium as gym + gym.register(gym_id(case_id), entry_point=make, kwargs={'name': case_id}) + ENGINE_BACKENDS[case_id] = factory + ENVS[case_id] = 'native' + + +def make(name, **kw): + """Unified env for any id in ENVS; kw: obs_mode, time_mode, latency, difficulty, reward_mode, action_mode, + (web) transport, (py) case_kw for the case constructor (e.g. {"camera": "first"}).""" + if name in ENGINE_BACKENDS: + from .engine_env import EngineEnv + backend_options = dict(kw.pop('backend_options', {}) or {}) + backend = ENGINE_BACKENDS[name](**backend_options) + return EngineEnv(name, backend, **kw) + if name in PY_CASES: + factory, fixed = PY_CASES[name] + extra = dict(kw.pop("case_kw", {}) or {}) + if any(key in extra and extra[key] != value for key, value in fixed.items()): + raise ValueError(f"case_kw cannot override the registered case identity: {fixed}") + case_kw = {**extra, **fixed} + return PyCaseEnv(name, lambda **k: factory(**case_kw, **k), **kw) + if name in WEB_CASES: + from .webenv import WebCaseEnv + return WebCaseEnv(name, **kw) + raise KeyError(f"unknown case {name!r}; known: {sorted(ENVS)}") + + +def gym_id(name): + return "BossBench/" + name.replace("/", "-") + "-v0" + + +from .policy_env import PolicyEnv, make_policy_env, policy_gym_id + + +try: # gymnasium.make("BossBench/2d-needle_warden-v0") + import gymnasium as gym + for _n in ENVS: + gym.register(gym_id(_n), entry_point=make, kwargs={"name": _n}) + from .scope import FORMAL_CASES, PUBLIC_WEB_CASES + for _n in (*FORMAL_CASES, *PUBLIC_WEB_CASES): + gym.register(policy_gym_id(_n), entry_point=make_policy_env, kwargs={"case_id": _n}) +except Exception: + pass + +from .native_games import NATIVE_CASES, backend_factory +for _n in NATIVE_CASES: + register_backend(_n, backend_factory(_n)) + gym.register(policy_gym_id(_n), entry_point=make_policy_env, kwargs={'case_id': _n}) + +# 2026-11-10: compact discrete action spaces (bossbench/compact-actions@1, compact.py). Registered for every public +# case whose game ships web/games//compact_actions.json; the raw key/mouse contract above is unchanged. +from . import compact +from .compact import make_compact_env, compact_gym_id +from .step_reward import StepDamageReward, make_training_env +try: + from .scope import POLICY_CASES as _PC + for _n, _v in _PC.items(): + if compact.declaration_path(_v['game']).is_file(): + gym.register(compact_gym_id(_n), entry_point=make_compact_env, kwargs={'case_id': _n}) +except Exception: + pass diff --git a/environments/games/prototype/bossbench/compact.py b/environments/games/prototype/bossbench/compact.py new file mode 100644 index 0000000000000000000000000000000000000000..8086e601af03a2e1003d92b93a95977912594361 --- /dev/null +++ b/environments/games/prototype/bossbench/compact.py @@ -0,0 +1,315 @@ +"""Compact discrete action spaces for the public BossBench env: bossbench/compact-actions@1. + +Most games use fewer than 1,000 action combinations. Terraria has a separate action space. +A game declares a few independent heads (move, turn, attack, ...), each a short list of options. One action +picks one option per head and is held for one 200 ms packet, which is the ViZDoom frame-skip analogue. The +action count is the product of the head sizes and must be below 1000. + +Nothing underneath changes. An action is translated into an ordinary key/mouse packet before env.step, so the +simulation, the recordings, the verifier and the raw packet contract (bossbench/policy-gym@2) are all untouched. + +Declaration: web/games//compact_actions.json + + {"schema": "bossbench/compact-actions@1", "game": "doom_remake", "version": "doom-compact@1", + "heads": [ + {"name": "move", "zh": "movement", "options": [ + {"label": "none"}, {"label": "forward", "zh": "forward", "keys": ["W", "Shift"]}, ...]}, + {"name": "turn", "zh": "turn", "options": [ + {"label": "none"}, {"label": "left_10", "zh": "turn left 10 degrees", "dx": -60}, ...]}]} + +Option fields: label (required, [a-z0-9_]+, unique within its head); zh; note; and at most one of + keys: [...] held in all six sub-steps + tap: [...] held in the first sub-step only, so the key is pressed afresh every packet + subs: [[...] x 6] an explicit per-sub-step pattern (motion inputs, combos) +plus optional relative mouse counts dx, dy, dz for the packet. + +Rules: +- Option 0 of every head is neutral (no keys, no mouse), so action [0, 0, ...] is the no-op packet. +- Heads never share a key or a mouse axis. +- Every combination must be a legal packet (at most 4 keys per sub-step). +""" +from __future__ import annotations + +from collections.abc import Mapping +import itertools +import json +import math +from pathlib import Path +import re + +import gymnasium as gym +import numpy as np + +from . import keymouse as km + +SCHEMA = 'bossbench/compact-actions@1' +CONTRACT = 'bossbench/policy-compact@1' +MAX_ACTIONS = 1000 +EXEMPT_GAMES = frozenset({'terraria_remake'}) +ROOT = Path(__file__).resolve().parents[2] +_FOLDER = {'minecraft': 'minecraft_remake'} +_LABEL = re.compile(r'[a-z0-9_]+\Z') +_HEAD = re.compile(r'[a-z][a-z0-9_]*\Z') +_AXES = ('dx', 'dy', 'dz') +_LIMIT = (1000, 1000, 5) +_FIELDS = {'label', 'zh', 'note', 'keys', 'tap', 'subs', 'dx', 'dy', 'dz'} +INVALID = 'invalid compact action' # executed as a malformed packet: no-op, counted in format_errors + + +def declaration_path(game): + return ROOT / 'web' / 'games' / _FOLDER.get(game, game) / 'compact_actions.json' + + +def _keyset(value, where): + if not isinstance(value, list) or any(not isinstance(k, str) for k in value): + raise ValueError(f'{where}: keys must be a list of key names') + if len(set(value)) != len(value): + raise ValueError(f'{where}: duplicate key') + bad = [k for k in value if k not in km.KEYS] + if bad: + raise ValueError(f'{where}: unknown key(s) {bad}; allowed {list(km.KEYS)}') + if len(value) > km.MAX_KEYS: + raise ValueError(f'{where}: more than {km.MAX_KEYS} keys in one sub-step') + return frozenset(value) + + +class CompactSpec: + """A validated compact action declaration. Indices are per head; flat indices are mixed-radix, first head + most significant, so flat 0 is the no-op.""" + + def __init__(self, data, where='declaration'): + if not isinstance(data, dict) or data.get('schema') != SCHEMA: + raise ValueError(f'{where}: schema must be {SCHEMA!r}') + self.where, self.game, self.version = where, data.get('game'), data.get('version') + if not isinstance(self.game, str) or not isinstance(self.version, str) or not self.version: + raise ValueError(f'{where}: game and version must be non-empty strings') + heads = data.get('heads') + if not isinstance(heads, list) or not heads: + raise ValueError(f'{where}: heads must be a non-empty list') + self.raw, self.heads, keys_owner, axes_owner = data, [], {}, {} + for h in heads: + name = h.get('name') if isinstance(h, dict) else None + if not isinstance(name, str) or not _HEAD.match(name) or any(x['name'] == name for x in self.heads): + raise ValueError(f'{where}: head names must match [a-z][a-z0-9_]* and be unique: {name!r}') + opts = h.get('options') + if not isinstance(opts, list) or len(opts) < 2: + raise ValueError(f'{where}: head {name!r} needs at least two options') + parsed, labels = [], set() + for i, o in enumerate(opts): + at = f'{where}: {name}[{i}]' + if not isinstance(o, dict) or set(o) - _FIELDS: + raise ValueError(f'{at}: unknown fields {sorted(set(o) - _FIELDS) if isinstance(o, dict) else o}') + label = o.get('label') + if not isinstance(label, str) or not _LABEL.match(label) or label in labels: + raise ValueError(f'{at}: label must match [a-z0-9_]+ and be unique in the head: {label!r}') + labels.add(label) + kinds = [k for k in ('keys', 'tap', 'subs') if k in o] + if len(kinds) > 1: + raise ValueError(f'{at}: use only one of keys / tap / subs') + subs = [frozenset()] * km.SUBSTEPS + if 'keys' in o: + subs = [_keyset(o['keys'], at)] * km.SUBSTEPS + elif 'tap' in o: + subs = [_keyset(o['tap'], at)] + [frozenset()] * (km.SUBSTEPS - 1) + elif 'subs' in o: + if not isinstance(o['subs'], list) or len(o['subs']) != km.SUBSTEPS: + raise ValueError(f'{at}: subs must list {km.SUBSTEPS} sub-steps') + subs = [_keyset(s, f'{at} sub {j + 1}') for j, s in enumerate(o['subs'])] + mouse = [] + for axis, limit in zip(_AXES, _LIMIT): + v = o.get(axis, 0) + if isinstance(v, bool) or not isinstance(v, int) or abs(v) > limit: + raise ValueError(f'{at}: {axis} must be an integer within +-{limit}') + mouse.append(v) + if i == 0 and (any(subs) or any(mouse)): + raise ValueError(f'{at}: option 0 must be neutral (no keys, no mouse)') + parsed.append({'label': label, 'zh': o.get('zh'), 'subs': tuple(subs), 'mouse': tuple(mouse)}) + uni = frozenset().union(*(frozenset().union(*p['subs']) for p in parsed)) + axes = frozenset(a for p in parsed for a, v in zip(range(3), p['mouse']) if v) + for k in uni: + if k in keys_owner: + raise ValueError(f'{where}: key {k} is used by heads {keys_owner[k]!r} and {name!r}') + keys_owner[k] = name + for a in axes: + if a in axes_owner: + raise ValueError(f'{where}: mouse {_AXES[a]} is used by heads {axes_owner[a]!r} and {name!r}') + axes_owner[a] = name + self.heads.append({'name': name, 'zh': h.get('zh'), 'options': parsed, 'keys': uni, 'axes': axes}) + self.nvec = [len(h['options']) for h in self.heads] + self.size = math.prod(self.nvec) + if self.size >= MAX_ACTIONS and self.game not in EXEMPT_GAMES: + raise ValueError(f'{where}: {self.size} actions ({" x ".join(map(str, self.nvec))}), must be below {MAX_ACTIONS}') + bad = None + for idx in itertools.islice(itertools.product(*(range(n) for n in self.nvec)), 200000): + if km.parse_packet(self.compose(idx)) is None: + bad = idx + break + if bad is not None: + raise ValueError(f'{where}: action {self.named(bad)} is not a legal packet (more than 4 keys in a sub-step?)') + + # ---- conversions + def compose(self, idx): + subs, mouse = [set() for _ in range(km.SUBSTEPS)], [0, 0, 0] + for head, i in zip(self.heads, idx): + option = head['options'][i] + for j in range(km.SUBSTEPS): + subs[j] |= option['subs'][j] + for a in range(3): + mouse[a] += option['mouse'][a] + return km.format_packet([sorted(s, key=km.KEYS.index) for s in subs], mouse) + + def unflat(self, i): + if not 0 <= i < self.size: + raise ValueError(f'flat action {i} outside [0, {self.size})') + out = [] + for n in reversed(self.nvec): + i, r = divmod(i, n) + out.append(r) + return tuple(reversed(out)) + + def flat(self, idx): + i = 0 + for n, v in zip(self.nvec, idx): + i = i * n + v + return i + + def named(self, idx): + return {h['name']: h['options'][i]['label'] for h, i in zip(self.heads, idx)} + + def parse(self, action): + """Action -> per-head indices. Accepts None (no-op), a flat int, a sequence of per-head ints, a mapping + {head: label or index} (missing heads = option 0), or text "move=forward; turn=left_10" (same rule).""" + if action is None: + return (0,) * len(self.heads) + if isinstance(action, (bool, np.bool_)): + raise ValueError('a boolean is not an action') + if isinstance(action, (int, np.integer)): + return self.unflat(int(action)) + if isinstance(action, str): + text = action.strip() + for mark in ('<|compact_start|>', '<|compact_end|>'): + text = text.replace(mark, '') + pairs = {} + for part in re.split(r'[;,\n]', text): + part = part.strip() + if not part: + continue + if '=' not in part and ':' not in part: + raise ValueError(f'expected head=label, got {part!r}') + head, _, label = part.replace(':', '=', 1).partition('=') + head, label = head.strip(), label.strip() + if head in pairs: + raise ValueError(f'head {head!r} given twice') + pairs[head] = label + return self.parse(pairs) + if isinstance(action, Mapping): + names = [h['name'] for h in self.heads] + unknown = set(action) - set(names) + if unknown: + raise ValueError(f'unknown head(s) {sorted(unknown)}; heads are {names}') + out = [] + for h in self.heads: + v = action.get(h['name'], 0) + if isinstance(v, str): + labels = [o['label'] for o in h['options']] + if v not in labels: + raise ValueError(f'head {h["name"]!r} has no option {v!r}; options are {labels}') + out.append(labels.index(v)) + elif isinstance(v, (int, np.integer)) and not isinstance(v, (bool, np.bool_)) and 0 <= v < len(h['options']): + out.append(int(v)) + else: + raise ValueError(f'head {h["name"]!r}: bad value {v!r}') + return tuple(out) + arr = np.asarray(action) + if arr.ndim != 1 or arr.shape[0] != len(self.heads) or arr.dtype.kind not in 'iu': + raise ValueError(f'expected {len(self.heads)} integer head indices') + if any(not 0 <= int(v) < n for v, n in zip(arr, self.nvec)): + raise ValueError(f'head index out of range for {self.nvec}') + return tuple(int(v) for v in arr) + + def project(self, packet): + """Nearest compact action to a packet (packet text or parse_packet() dict), head by head. + + Key heads: Hamming distance over the 6 sub-steps x the head's own keys. + Mouse: |difference| / 100 per axis the head owns. Ties go to the lowest index, so neutral wins a tie and + option order matters: list the richer of two equally close options first (cuphead v3 lost jumps this way).""" + p = km.parse_packet(packet) if isinstance(packet, str) else packet + if p is None: + return (0,) * len(self.heads) + out = [] + for h in self.heads: + best, best_d = 0, None + for i, o in enumerate(h['options']): + d = sum(len((p['subs'][j] & h['keys']) ^ o['subs'][j]) for j in range(km.SUBSTEPS)) + d += sum(abs(p['mouse'][a] - o['mouse'][a]) / 100 for a in h['axes']) + if best_d is None or d < best_d - 1e-12: + best, best_d = i, d + out.append(best) + return tuple(out) + + def table(self): + """What an agent's manual shows: every head and option with its meaning.""" + heads = [] + for h, raw in zip(self.heads, self.raw['heads']): + heads.append({'name': h['name'], 'zh': h['zh'], 'options': [ + {'index': i, **{k: v for k, v in o.items() if k in ('label', 'zh', 'note', 'keys', 'tap', 'subs', 'dx', 'dy', 'dz')}} + for i, o in enumerate(raw['options'])]}) + return {'schema': SCHEMA, 'contract': CONTRACT, 'game': self.game, 'version': self.version, + 'size': self.size, 'nvec': list(self.nvec), 'decision_seconds': km.PACKET_SECONDS, + 'text_form': 'head=label; head=label (missing heads = option 0)', 'heads': heads} + + +def load(game=None, path=None): + p = Path(path) if path else declaration_path(game) + if not p.is_file(): + raise FileNotFoundError(f'no compact action declaration for {game!r}: {p}') + spec = CompactSpec(json.loads(p.read_text(encoding='utf-8')), where=str(p)) + if game and spec.game != game: + raise ValueError(f'{p}: declares game {spec.game!r}, expected {game!r}') + return spec + + +class CompactActionEnv(gym.Wrapper): + """The public policy env with a small MultiDiscrete action space; each action becomes one ordinary packet.""" + + def __init__(self, env, spec): + super().__init__(env) + self.compact_spec = spec # not `spec`: gym.Wrapper.spec is the registry EnvSpec (read-only) + self.action_space = gym.spaces.MultiDiscrete(spec.nvec) + self.metadata = {**env.metadata, 'action_contract': CONTRACT, 'compact_version': spec.version, + 'compact_size': spec.size} + + def manual(self): + manual = self.env.manual() + manual['compact_actions'] = self.compact_spec.table() + return manual + + def reset(self, *, seed=None, options=None): + obs, info = self.env.reset(seed=seed, options=options) + if 'manual' in info: + info = {**info, 'manual': self.manual()} + return obs, info + + def step(self, action, latency=None): + try: + idx = self.compact_spec.parse(action) + packet = self.compact_spec.compose(idx) + except (ValueError, TypeError, OverflowError): + idx, packet = None, INVALID + obs, reward, terminated, truncated, info = self.env.step(packet, latency=latency) + info = {**info, 'compact_action': None if idx is None else self.compact_spec.named(idx)} + return obs, reward, terminated, truncated, info + + +def make_compact_env(case_id, decl_path=None, **kwargs): + """make_policy_env(case_id) with the game's compact action space (MultiDiscrete, fewer than 1000 actions).""" + from .policy_env import make_policy_env + from .scope import POLICY_CASES + if case_id not in POLICY_CASES: + raise ValueError(f'case is not registered for the public policy interface: {case_id!r}') + spec = load(POLICY_CASES[case_id]['game'], decl_path) + return CompactActionEnv(make_policy_env(case_id, **kwargs), spec) + + +def compact_gym_id(case_id): + return 'BossBenchCompact/' + case_id.replace('/', '-') + '-v0' diff --git a/environments/games/prototype/bossbench/core.py b/environments/games/prototype/bossbench/core.py new file mode 100644 index 0000000000000000000000000000000000000000..a7d19933524b5ef728c63fd2ff1abdc7084ab52b --- /dev/null +++ b/environments/games/prototype/bossbench/core.py @@ -0,0 +1,252 @@ +"""BossBench core. + +A Case is the composition Arena (environment) + Body (embodiment) + Boss. +Every component declares a difficulty TABLE; one scalar d in [0, 1] sets all knobs. +BossBenchEnv wraps a Case as a Gymnasium env with three time modes. +""" +from __future__ import annotations + +import math +from collections.abc import Mapping +from numbers import Integral, Real +import os +import time + +import gymnasium as gym +import numpy as np + +# fixed simulation tick: 60 Hz = 2 ticks per 33 ms sub-step of the 200 ms packet, as the web engine +# (proposal 4.4). Rules are written per second (or per vanilla 20 Hz Minecraft tick, converted in mc4d), so the +# game plays the same at any rate >= 30; BOSSBENCH_FPS overrides it for equivalence checks only. +FPS = int(os.environ.get("BOSSBENCH_FPS", 60)) +RES = (854, 480) # every case and every renderer outputs 480p, 16:9 (W, H) + + +class Knobs: + """d in [0,1] -> named parameters. A row is (easy, hard) or (easy, normal, hard).""" + + def __init__(self, table: dict, d: float): + self._names = list(table) + d = float(np.clip(d, 0.0, 1.0)) + for name, row in table.items(): + setattr(self, name, float(np.interp(d, np.linspace(0, 1, len(row)), row))) + + def as_dict(self) -> dict: + return {n: round(getattr(self, n), 4) for n in self._names} + + +class Component: + TABLE: dict = {} + + def reset(self, case: "Case") -> None: + self.k = Knobs(self.TABLE, case.d) + + def update(self, case: "Case") -> None: + pass + + +class Arena(Component): + """Static geometry + transient entities (projectiles, hazards).""" + + +class Body(Component): + """The agent's embodiment: action space, kinematics, health.""" + action_space: gym.Space + max_hp = 1.0 + + def noop(self): + raise NotImplementedError + + def parse(self, text: str): + """'up+fire' -> action; lets LLM agents act with words.""" + raise NotImplementedError + + def apply(self, case: "Case", action) -> None: + raise NotImplementedError + + # key/mouse packets (keymouse.py): what each key means is up to the body (proposal 4.3) + manual: tuple = () + + def keys(self, case: "Case", held: frozenset, pressed: frozenset, mouse: tuple): + """Keys held this tick (+ those newly pressed, + this tick's share of the mouse motion) -> native action.""" + raise NotImplementedError + + +class Boss(Component): + """Opponent: a state machine over MOVES (Boss-Spec DSL subset).""" + MOVES: dict = {} + SKILLS: tuple = () + max_hp = 1.0 + + +class Case: + """Arena + Body + Boss, stepped at FPS. Subclasses add observe/state/render.""" + name = "case" + max_seconds = 120.0 + obs_dim = 0 + + def __init__(self, arena: Arena, body: Body, boss: Boss): + self.arena, self.body, self.boss = arena, body, boss + self.observation_space = gym.spaces.Box(-np.inf, np.inf, (self.obs_dim,), np.float32) + + def reset(self, seed: int, d: float) -> None: + self.rng = np.random.default_rng(seed) + self.d, self.t, self.events = float(d), 0, [] + for c in (self.arena, self.body, self.boss): + c.reset(self) + + def tick(self, action) -> None: + self.body.apply(self, action) + self.boss.update(self) + self.arena.update(self) + self.interact() + self.t += 1 + + def interact(self) -> None: + """Case-specific body/boss contact rules.""" + + def outcome(self): + if self.boss.hp <= 0: + return "win" + if self.body.hp <= 0: + return "loss" + return None + + def describe(self) -> dict: + """Difficulty knobs + boss spec: what an LLM generator/verifier sees.""" + return {"case": self.name, "d": self.d, + "knobs": {type(c).__name__: c.k.as_dict() for c in (self.arena, self.body, self.boss)}, + "moves": self.boss.MOVES, "skills_tested": self.boss.SKILLS} + + def observe(self) -> np.ndarray: + raise NotImplementedError + + def state(self) -> dict: + raise NotImplementedError + + def render(self) -> np.ndarray: + raise NotImplementedError + + +class BossBenchEnv(gym.Env): + """Gymnasium wrapper. + + time_mode: + paused - the world waits for the agent (turn-based upper bound) + virtual - before each action the world runs ceil(latency*FPS) no-op ticks + (set env.latency per step to the agent's measured think time) + realtime - same, but the lag is measured on the wall clock between steps + reward: terminal win=+1, loss/timeout=-1+boss_damage_fraction (+ optional dense shaping) + """ + metadata = {"render_modes": ["rgb_array"], "render_fps": FPS} + + def __init__(self, case: Case, difficulty=0.5, time_mode="paused", latency=0.0, + frame_skip=1, reward_mode="sparse", render_mode=None, max_seconds=None): + assert time_mode in ("paused", "virtual", "realtime") + self.case, self.difficulty, self.time_mode, self.latency = case, difficulty, time_mode, latency + self.frame_skip, self.reward_mode, self.render_mode = frame_skip, reward_mode, render_mode + seconds = case.max_seconds if max_seconds is None else max_seconds + if (isinstance(seconds, (bool, np.bool_)) or not isinstance(seconds, Real) or + not math.isfinite(seconds) or not math.isfinite(seconds * FPS) or seconds < 1 / FPS): + raise ValueError("max_seconds must be finite and allow at least one simulation tick") + self.max_ticks = int(seconds * FPS) + self.action_space = case.body.action_space + self.observation_space = case.observation_space + self.renderer = None # None -> case.render(); or a callable(env) -> frame (e.g. skin.GodotRenderer) + self.episode = 0 + self._closed = False + self._has_reset, self._done = False, True + + # -- gym API --------------------------------------------------------- + def reset(self, *, seed=None, options=None): + self._ensure_open() + if options is not None and not isinstance(options, Mapping): + raise ValueError("reset options must be a mapping") + d = (options or {}).get("difficulty", self.difficulty) + if isinstance(d, (bool, np.bool_)) or not isinstance(d, Real) or not math.isfinite(d) or not 0 <= d <= 1: + raise ValueError("difficulty must be a finite number in [0, 1]") + if seed is not None: + if isinstance(seed, (bool, np.bool_)) or not isinstance(seed, Integral) or seed < 0: + raise ValueError("seed must be a nonnegative integer or None") + seed = int(seed) + super().reset(seed=seed) + self.case.reset(int(self.np_random.integers(2**31 - 1)), d) + self._has_reset, self._done = True, False + self.episode += 1 + self._prev = self._progress() + self._lag_ticks = 0 + self._t_return = time.perf_counter() + return self.case.observe(), self._info() + + def step(self, action): + self._ensure_reset() + if self._done: + raise RuntimeError("episode is over; call reset()") + c = self.case + if isinstance(action, str): + action = c.body.parse(action) + c.events.clear() + self._lag_ticks = self._lag() + for a in [c.body.noop()] * self._lag_ticks + [action] * self.frame_skip: + c.tick(a) + if c.outcome() or c.t >= self.max_ticks: + break + terminated = c.outcome() is not None + truncated = not terminated and c.t >= self.max_ticks + prog, reward = self._progress(), 0.0 + if self.reward_mode == "dense": + reward += (prog[0] - self._prev[0]) - (prog[1] - self._prev[1]) + self._prev = prog + if terminated or truncated: + reward += self.verifier()["reward"] + self._done = True + obs, info = c.observe(), self._info() + self._t_return = time.perf_counter() + return obs, float(reward), terminated, truncated, info + + def render(self): + self._ensure_reset() + img = self.renderer(self) if self.renderer else self.case.render() + assert img.shape == (RES[1], RES[0], 3), f"render must be 480p {RES}, got {img.shape}" + return img + + def close(self): + if not self._closed: + try: + close = getattr(self.case, "close", None) + if close is not None: + close() + finally: + self._closed = True + + def _ensure_open(self): + if self._closed: + raise RuntimeError("environment is closed; create a new environment") + + def _ensure_reset(self): + self._ensure_open() + if not self._has_reset: + raise RuntimeError("environment has not been reset; call reset()") + + # -- BossBench extras ---------------------------------------------------- + def verifier(self) -> dict: + self._ensure_reset() + boss_frac, _ = self._progress() + win = self.case.outcome() == "win" + return {"reward": 1.0 if win else -1.0 + boss_frac, "win": win, + "boss_damage": round(boss_frac, 4), "seconds": self.case.t / FPS, "d": self.case.d} + + def _progress(self): + b, p = self.case.boss, self.case.body + return (1 - max(b.hp, 0) / b.max_hp, 1 - max(p.hp, 0) / p.max_hp) + + def _lag(self) -> int: + if self.time_mode == "virtual": + return math.ceil(self.latency * FPS - 1e-9) + if self.time_mode == "realtime": + return int((time.perf_counter() - self._t_return) * FPS) + return 0 + + def _info(self) -> dict: + return {"t": self.case.t / FPS, "state": self.case.state(), "events": list(self.case.events), + "lag_ticks": self._lag_ticks, "difficulty": self.case.d} diff --git a/environments/games/prototype/bossbench/engine_contract.py b/environments/games/prototype/bossbench/engine_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..316f134d1b6728964bda7544b1c6456cce571922 --- /dev/null +++ b/environments/games/prototype/bossbench/engine_contract.py @@ -0,0 +1,130 @@ +"""External engine boundary. No Arena/Body/Boss/Case or renderer library required.""" +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Protocol + +import numpy as np + +API_VERSION = 'bossbench/engine@1' + + +@dataclass(frozen=True) +class EngineSpec: + engine_id: str + dimension: str + native_hz: int + max_seconds: float + renderer: str + render_kind: str # raster | perspective + rule_version: str = '1' + resolution: tuple[int, int] = (854, 480) + + def __post_init__(self): + if self.dimension not in ('2d', '3d') or self.render_kind not in ('raster', 'perspective'): + raise ValueError('invalid engine dimension or render_kind') + if isinstance(self.native_hz, bool) or not isinstance(self.native_hz, int) or not 5 <= self.native_hz <= 1000: + raise ValueError('native_hz must be an integer in [5, 1000]') + if not math.isfinite(self.max_seconds) or self.max_seconds <= 0: + raise ValueError('max_seconds must be positive and finite') + if not self.engine_id or not self.renderer or not self.rule_version: + raise ValueError('engine identity, renderer and rules must be declared') + if len(self.resolution) != 2 or any(type(v) is not int or v <= 0 for v in self.resolution): + raise ValueError('resolution must contain positive integer width/height') + + +@dataclass(frozen=True) +class RenderStatus: + renderer: str + kind: str + ready: bool + error: str | None = None + + +@dataclass(frozen=True) +class InputPacket: + """200ms of input; six equally spaced held-key samples and total relative mouse delta.""" + mouse: tuple[float, float, float] + holds: tuple[frozenset[str], ...] + + @classmethod + def noop(cls): + return cls((0, 0, 0), (frozenset(),) * 6) + + +@dataclass(frozen=True) +class TickInput: + held: frozenset[str] + pressed: frozenset[str] + mouse: tuple[float, float, float] + + +class NativeClock: + """Optional integer scheduler: sample holds at each native tick, without clock drift. + + The right endpoint belongs to the preceding input interval. Thus 35Hz uses + 7 ticks per packet while 24Hz alternates 4/5, executing exactly 24 per second. + Engines with their own native input queue may implement this boundary themselves. + """ + def __init__(self, hz): + self.hz = hz + self.reset() + + def reset(self): + self.packets = 0 + self.ticks = 0 + self.held = frozenset() + + def schedule(self, packet: InputPacket): + end = (self.packets + 1) * self.hz // 5 + count = end - self.ticks + result = [] + for tick in range(self.ticks + 1, end + 1): + sub = (tick * 30 + self.hz - 1) // self.hz - 1 - self.packets * 6 + held = packet.holds[max(0, min(5, sub))] + pressed = held - self.held + mouse = tuple(v / count for v in packet.mouse) + result.append(TickInput(held, pressed, mouse)) + self.held = held + self.packets += 1 + self.ticks = end + return result + + +@dataclass +class EngineSnapshot: + """Normalized diagnostics, owned by the trusted adapter; never a model observation. + + ticks is absolute native time, frames is the number executed by this call. + Multipart bosses report aggregate remaining progress as hp/max_hp here. + state must include all replay-relevant game state/RNG/input state. + """ + ticks: int + frames: int + outcome: str | None + player_hp: float + player_max_hp: float + boss_hp: float + boss_max_hp: float + state: dict + events: tuple = () + + +class GameBackend(Protocol): + """A game may be an in-process engine, subprocess, RPC client or browser client. + + validate_options must be pure. reset must establish a fresh independent + episode. advance executes one packet and stops on the exact terminal tick. + render is read-only and returns a perspective RGB for a 3D game. close must + release resources and be idempotent. The adapter owns process isolation. + """ + spec: EngineSpec + + def validate_options(self, options: dict) -> None: ... + def reset(self, seed: int, difficulty: float, options: dict) -> EngineSnapshot: ... + def advance(self, packet: InputPacket) -> EngineSnapshot: ... + def render(self) -> np.ndarray: ... + def render_status(self) -> RenderStatus: ... + def manual(self) -> dict: ... + def close(self) -> None: ... diff --git a/environments/games/prototype/bossbench/engine_env.py b/environments/games/prototype/bossbench/engine_env.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d531d9726ef26d32a44aa787f070188dc5b84c --- /dev/null +++ b/environments/games/prototype/bossbench/engine_env.py @@ -0,0 +1,119 @@ +"""Gym adapter for independent game backends (engine_contract.GameBackend).""" +from __future__ import annotations + +from dataclasses import asdict +import copy +import json +import math + +from . import keymouse as km +from .engine_contract import EngineSnapshot, InputPacket +from .unified import UnifiedEnv + + +class EngineEnv(UnifiedEnv): + """No access to a game world, Body, Boss or a specific rendering library.""" + def __init__(self, case_id, backend, **kwargs): + self.backend = backend + try: + super().__init__(case_id, **kwargs) + if self.action_mode != 'keymouse': + raise ValueError('independent engine adapter accepts keymouse; native actions stay inside the backend') + self.fps = self.engine_spec.native_hz + self.max_seconds = self.engine_spec.max_seconds + self.max_ticks = math.ceil(self.max_seconds * self.fps) + self.observation_space = self._obs_space() + except BaseException: + backend.close() + raise + + @property + def engine_spec(self): + return self.backend.spec + + def render_status(self): + return self.backend.render_status() + + def _declared_tiers(self): + declared = getattr(self.backend, 'declared_tiers', None) + return declared() if callable(declared) else None + + def _difficulty_band(self, d): + band = getattr(self.backend, 'difficulty_band', None) + return band(d) if callable(band) else None + + def _validate_options(self, options): + super()._validate_options(options) + self.backend.validate_options(copy.deepcopy(options)) + + def _snapshot(self, value, *, previous=None, reset=False): + if not isinstance(value, EngineSnapshot): + raise TypeError('backend must return EngineSnapshot') + if type(value.ticks) is not int or type(value.frames) is not int or min(value.ticks, value.frames) < 0: + raise ValueError('backend ticks/frames must be nonnegative integers') + if reset and (value.ticks != 0 or value.frames != 0 or value.outcome is not None): + raise ValueError('reset must return a fresh live episode at tick zero') + if previous is not None: + expected = round(previous['t'] * self.fps) + value.frames + if value.ticks != expected or value.frames > math.ceil(self.fps * km.PACKET_SECONDS): + raise ValueError('backend native time does not match the executed packet') + if not value.frames and value.outcome is None: + raise ValueError('live packet did not advance simulation') + if value.outcome not in (None, 'win', 'loss', 'timeout'): + raise ValueError('unknown backend outcome') + if value.ticks >= self.max_ticks and value.outcome is None: + raise ValueError('backend exceeded its declared episode deadline') + for hp, maximum in ((value.player_hp,value.player_max_hp),(value.boss_hp,value.boss_max_hp)): + if not math.isfinite(hp) or not math.isfinite(maximum) or maximum <= 0 or not 0 <= hp <= maximum: + raise ValueError('invalid normalized backend health/progress') + if not isinstance(value.state, dict): + raise ValueError('backend diagnostics state must be a JSON object') + result = asdict(value) + json.dumps(result, allow_nan=False) + result.pop('ticks') + result['t'] = value.ticks / self.fps + return copy.deepcopy(result) + + def _engine_reset(self, seed, d, options=None): + return self._snapshot(self.backend.reset(seed, d, copy.deepcopy(options or {})), reset=True) + + def _engine_packet(self, packet, lag, ok): + try: + return self._advance_packets(packet, lag, ok) + except BaseException: + # A failed backend may have advanced privately; never expose the stale snapshot as live. + self.snap, self.done = None, True + raise + + def _advance_packets(self, packet, lag, ok): + parsed = km.parse_packet(packet) if ok else None + action = (InputPacket(tuple(parsed['mouse']),tuple(frozenset(h) for h in parsed['subs'])) + if parsed is not None else InputPacket.noop()) + snapshot = self.snap + frames = lag_frames = 0 + events = [] + for _ in range(lag): + if snapshot['outcome']: + break + snapshot = self._snapshot(self.backend.advance(InputPacket.noop()),previous=snapshot) + frames += snapshot['frames'] + lag_frames += snapshot['frames'] + events.extend(snapshot['events']) + if not snapshot['outcome']: + snapshot = self._snapshot(self.backend.advance(action),previous=snapshot) + frames += snapshot['frames'] + events.extend(snapshot['events']) + return {**snapshot,'frames':frames,'events':events,'lag_frames':lag_frames} + + def _manual(self): + return copy.deepcopy(self.backend.manual()) + + def _render(self): + return self.backend.render() + + def close(self): + if not self._closed: + try: + self.backend.close() + finally: + super().close() diff --git a/environments/games/prototype/bossbench/keymouse.py b/environments/games/prototype/bossbench/keymouse.py new file mode 100644 index 0000000000000000000000000000000000000000..da507c86ef1f41dbef3fd5f31b054ba70e0023a9 --- /dev/null +++ b/environments/games/prototype/bossbench/keymouse.py @@ -0,0 +1,211 @@ +"""The key/mouse action packet shared by every BossBench case (proposal 4.4), Python side. + + <|action_start|> dx dy dz ; K1 ; K2 ; K3 ; K4 ; K5 ; K6 <|action_end|> + +One packet = 200 ms = 6 sub-steps of 33 ms; K_j = 0-4 keys held during sub-step j. The parser is a +line-for-line port of web/engine/case.js BB.parsePacket, so a +packet means the same thing whether the case runs in Python or in the browser engine. + +Both engines tick at 60 Hz (2 ticks per sub-step); `schedule` spreads a packet over any number of +ticks per 200 ms all the same: a key counts as held in a tick if it is held during any +sub-step overlapping that tick, and a press (released -> held between sub-steps) lands in the tick +where that sub-step starts. At 60 Hz this is exactly the web engine's 2 ticks per sub-step. +""" +from __future__ import annotations + +from collections.abc import Mapping +import re + +import gymnasium as gym +import numpy as np + +KEYS = ("W", "A", "S", "D", "Space", "Shift", "J", "K", "L", "Q", "E", "R", "LMB", "RMB") +_UP = {k.upper(): k for k in KEYS} +SUBSTEPS = 6 +PACKET_SECONDS = 0.2 +MAX_KEYS = 4 +_PACKET = re.compile(r"\s*<\|action_start\|>([\s\S]*)<\|action_end\|>\s*") +_INT = re.compile(r"-?[0-9]+") + + +def parse_packet(text): + """-> {"mouse": (dx, dy, dz), "subs": [frozenset(keys)] * 6}, or None if the packet is malformed.""" + m = _PACKET.fullmatch("" if text is None else str(text)) + if not m: + return None + parts = m.group(1).split(";") + if len(parts) != 1 + SUBSTEPS: + return None + mouse = parts[0].split() + if len(mouse) != 3 or not all(_INT.fullmatch(v) for v in mouse): + return None + # Canonicalize leading zeros before int(): Python limits decimal input size, + # whereas JS rejects enormous values as out of range. Neither may crash. + normalized = [] + for value in mouse: + digits = value.lstrip("-").lstrip("0") or "0" + if len(digits) > 4: + return None + normalized.append(("-" if value.startswith("-") else "") + digits) + dx, dy, dz = (int(v) for v in normalized) + if abs(dx) > 1000 or abs(dy) > 1000 or abs(dz) > 5: + return None + subs = [] + for s in parts[1:]: + s, held = s.strip(), set() + if s: + ks = s.split(",") + if len(ks) > MAX_KEYS: + return None + for k in ks: + k = _UP.get(k.strip().upper()) + if k is None or k in held: + return None + held.add(k) + subs.append(frozenset(held)) + return {"mouse": (dx, dy, dz), "subs": subs} + + +def format_packet(subs, mouse=(0, 0, 0)) -> str: + """subs: 6 iterables of key names. Does not validate: too many keys gives a packet the env rejects.""" + return "<|action_start|> " + " ".join(str(int(v)) for v in mouse) + " ; " + \ + " ; ".join(",".join(_UP.get(str(k).upper(), str(k)) for k in s) for s in subs) + " <|action_end|>" + + +NOOP = format_packet([()] * SUBSTEPS) + + +def to_packet(action) -> str: + """Anything an agent may hand to env.step -> packet text. + + str the packet itself (LLM agents) + None NOOP + {"mouse": (dx,dy,dz), "keys": 6x14} KeyMouse space sample: 0/1 per sub-step and key, in KEYS order + {"mouse": ..., "keys": [["D"], ["D", "Space"], ...]} key names per sub-step + """ + if action is None: + return NOOP + if isinstance(action, str): + return action + # Invalid structured output has the same semantics as invalid packet text: + # the env executes a no-op and counts it, without coercing fractions to ints. + if not isinstance(action, Mapping) or set(action) - {"mouse", "keys"}: + return "invalid structured action" + try: + mouse = np.asarray(action.get("mouse", (0, 0, 0))) + if (mouse.shape != (3,) or mouse.dtype.kind not in "iuf" or + not np.isfinite(mouse).all() or not (mouse == np.trunc(mouse)).all() or + not (np.abs(mouse) <= (1000, 1000, 5)).all()): + return "invalid structured action" + rows = action.get("keys", [()] * SUBSTEPS) + if isinstance(rows, (str, bytes)) or len(rows) != SUBSTEPS: + return "invalid structured action" + if any(isinstance(row, (str, bytes)) for row in rows): + return "invalid structured action" + try: + matrix = np.asarray(rows) + except ValueError: # ragged lists of key names + matrix = None + if matrix is not None and matrix.shape == (SUBSTEPS, len(KEYS)) and matrix.dtype.kind in "biuf": + if not ((matrix == 0) | (matrix == 1)).all(): + return "invalid structured action" + rows = [[KEYS[i] for i in np.flatnonzero(row)] for row in matrix] + elif not all(all(isinstance(key, str) for key in row) for row in rows): + return "invalid structured action" + return format_packet(rows, mouse) + except (TypeError, ValueError, OverflowError): + return "invalid structured action" + + +def schedule(packet, n_ticks, prev=frozenset()): + """Spread a parsed packet (None = no-op) over n_ticks engine ticks. + + -> ([(held, pressed, (dx, dy, dz)) per tick], held during the last sub-step) + `prev` is the last sub-step of the previous packet, so a key held across packets is not re-pressed. + """ + subs = packet["subs"] if packet else [frozenset()] * SUBSTEPS + mouse = np.asarray(packet["mouse"] if packet else (0, 0, 0), float) / n_ticks + held = [set() for _ in range(n_ticks)] + pressed = [set() for _ in range(n_ticks)] + last = prev + for j, s in enumerate(subs): + for k in range(n_ticks): # sub-step [j/6, (j+1)/6) overlaps tick [k/n, (k+1)/n) + if j * n_ticks < SUBSTEPS * (k + 1) and k * SUBSTEPS < (j + 1) * n_ticks: + held[k] |= s + pressed[j * n_ticks // SUBSTEPS] |= s - last + last = s + return [(frozenset(h), frozenset(p), tuple(mouse)) for h, p in zip(held, pressed)], last + + +class KeyMouse(gym.spaces.Dict): + """Structured form of a packet for RL: mouse (dx, dy, dz) + a 6 x 14 hold matrix (sub-step x KEYS). + + env.step also accepts the packet text directly. Samples respect the 0-4 keys per sub-step rule; + an action that breaks it is a malformed packet (executed as no-op, counted in format_errors).""" + + def __init__(self, seed=None): + super().__init__({"mouse": gym.spaces.Box(np.array([-1000, -1000, -5]), np.array([1000, 1000, 5]), + dtype=np.int64), + "keys": gym.spaces.MultiBinary([SUBSTEPS, len(KEYS)])}, seed=seed) + + def sample(self, mask=None, probability=None): + out = super().sample(mask, probability) + out["keys"] = _constrained_keys(out["keys"], self.np_random, + None if mask is None else mask["keys"], + None if probability is None else probability["keys"]) + return out + + def contains(self, x) -> bool: + return super().contains(x) and bool((np.asarray(x["keys"]).sum(1) <= MAX_KEYS).all()) + + +def _constrained_keys(sample, rng, mask=None, probability=None): + keys = np.asarray(sample).copy() + rows = keys.reshape(-1, len(KEYS)) + if mask is None and probability is None: + rows.fill(0) + for row in rows: + row[rng.choice(len(KEYS), rng.integers(0, MAX_KEYS + 1), replace=False)] = 1 + else: + forced = (mask == 1) if mask is not None else (probability == 1) + for row, fixed in zip(rows, np.asarray(forced).reshape(-1, len(KEYS))): + if fixed.sum() > MAX_KEYS: + raise ValueError("key mask/probability forces more than four keys in a substep") + candidates = np.flatnonzero(row & ~fixed) + keep = MAX_KEYS - int(fixed.sum()) + if len(candidates) > keep: + row[rng.choice(candidates, len(candidates) - keep, replace=False)] = 0 + return keys + + +class BatchedKeyMouse(gym.spaces.Dict): + """Gym's vector action space preserving KeyMouse's per-substep constraint.""" + + def __init__(self, single, n): + from gymnasium.vector.utils import batch_space + base = batch_space(gym.spaces.Dict(dict(single.spaces)), n) + spaces = dict(base.spaces) + # Gym batches MultiBinary as Box, which loses mask/probability support. + # Keep binary semantics as well as the leading member dimension. + spaces["keys"] = gym.spaces.MultiBinary([n, SUBSTEPS, len(KEYS)]) + super().__init__(spaces) + + def sample(self, mask=None, probability=None): + out = super().sample(mask, probability) + out["keys"] = _constrained_keys(out["keys"], self.np_random, + None if mask is None else mask["keys"], + None if probability is None else probability["keys"]) + return out + + def contains(self, x): + return super().contains(x) and bool((np.asarray(x["keys"]).sum(-1) <= MAX_KEYS).all()) + + +# Default Dict batching drops subclass invariants. Register the real batch +# space so SyncVectorEnv/AsyncVectorEnv samplers still emit legal actions. +from gymnasium.vector.utils import batch_space + + +@batch_space.register(KeyMouse) +def _batch_keymouse(space, n=1): + return BatchedKeyMouse(space, n) diff --git a/environments/games/prototype/bossbench/mc4d.py b/environments/games/prototype/bossbench/mc4d.py new file mode 100644 index 0000000000000000000000000000000000000000..a97d80199e73baf420c7229d87d8785bff63a57c --- /dev/null +++ b/environments/games/prototype/bossbench/mc4d.py @@ -0,0 +1,2346 @@ +"""3D Minecraft 1v1 v2: one voxel arena, seven boss cases, one shared rig. + + 3d/minecraft_iron_golem ground melee: telegraphed slam that flings, knockback immune, walks around walls + 3d/minecraft_zombie fast light melee, relentless pressure (legacy case) + 3d/minecraft_ender_dragon aerial phases: circling, fireball strafes, perching with breath; healing end crystals + 3d/minecraft_wither hovering artillery: three heads of skulls, spawn blast, arrow-proof armor at half health + 3d/minecraft_warden blind juggernaut of the deep dark: crushing melee, darkness, a sonic boom for out-of-reach + targets that ignores armor and walls + 3d/minecraft_skeleton strafing archer: telegraphed bow draws, inaccurate arrows, line of sight behind ruins + 3d/minecraft_zombie_leader a leader zombie whose hits call reinforcements: a horde to manage at night + +Rules stay on the Java-edition numbers the prototype already used (attack cooldown multiplier, +crit conditions, 10-tick hurt immunity, armor, mob melee reach, knockback, mob auto-jump, fall +damage, friction/gravity). Those numbers are per vanilla tick (20 Hz): TABLE speeds are blocks/tick, +cooldowns are ticks. The simulation runs at core.FPS (60 Hz) and converts at use (per_vt / ticks / decay / +gain below), so a fight lasts the same seconds and covers the same blocks at any tick rate. Every knob is interpolated by the single scalar d, and every boss runs +the same 4-state machine so the observation vector keeps one layout across mobs. + +Rendering is a skin: boxes come from bossbench.rig, which the simulation poses once per tick; +textures, per-state poses, particles, renderer and HUD all live in bossbench.mcskin. + +Replay compatibility is tracked by the RULES identifier. +""" +from __future__ import annotations + +import math + +import gymnasium as gym +import numpy as np + +from .core import FPS, RES, Arena, Body, Boss, BossBenchEnv, Case +from . import mcskin +from .rig import Rigged + +RULES = "minecraft-arena@7" +# Public difficulty tiers: every TABLE row below is (easy, normal, hard), so a tier +# reads exactly one knot of each row. The continuous d in [0, 1] still interpolates between them for fine control. +TIERS = {"easy": 0.0, "normal": 0.5, "hard": 1.0} +S = 34 # arena side in blocks +MID = S / 2 # arena centre line (z of both spawns) +AREA_K = (S - 2) ** 2 / 22 ** 2 # obstacle counts scale with floor area so density matches the 24 layout +VT = 20 / FPS # one simulation tick in vanilla Minecraft ticks +TURNS = np.radians([-30, -10, 0, 10, 30]) * VT # native turn action, per vanilla tick + + +def per_vt(x): + """A per-vanilla-tick velocity, step or rate -> per simulation tick.""" + return x * VT + + +def ticks(n): + """A duration in vanilla ticks -> simulation ticks.""" + return int(round(n / VT)) + + +def decay(f): + """A per-vanilla-tick multiplier (friction, drag) -> per simulation tick, same decay per second.""" + return f ** VT + + +def push(v, f): + """A one-off vanilla impulse (b/t) decaying under per-vanilla-tick friction f -> the per-sim-tick + impulse that carries the body the same distance.""" + F = decay(f) + return v * f / (1 - f) * (1 - F) / F + + +def gain(k): + """A per-vanilla-tick approach fraction (lerp toward a target) -> per simulation tick.""" + return 1 - (1 - k) ** VT + + +# Per simulation tick, chosen so that every third 60 Hz tick lands exactly on the vanilla 20 Hz trajectory: +# ground friction keeps vanilla's terminal speed (= accel b/t) and time constant, air drag keeps the terminal +# 0.02 / 0.09 b/t, gravity the terminal fall 3.92 b/t. +GROUND_F, AIR_F, FALL_F = decay(0.546), decay(0.91), decay(0.98) +AIR_A = 0.02 / 0.09 * (1 - AIR_F) * VT +V_FALL = -0.08 * 0.98 / 0.02 # vanilla terminal fall speed (b/t) +GRAVITY = -V_FALL * VT * (1 - FALL_F) / FALL_F + + +def vy_sim(v): + """A vanilla vertical velocity set at a tick (jump, fling) -> the sim-tick value giving the same arc.""" + return V_FALL * VT + (v - V_FALL) * (1 - FALL_F) / (1 - 0.98) + + +def vy_vanilla(u): + """Inverse of vy_sim.""" + return V_FALL + (u - V_FALL * VT) * (1 - 0.98) / (1 - FALL_F) + + +JUMP = vy_sim(0.42) +# sprint-jump boost: vanilla decays it once by ground friction (the take-off tick), then by air drag; +# the sim value travels the same distance under one sim tick of ground friction, then air drag +SPRINT_JUMP = 0.2 * 0.546 / (1 - 0.91) * (1 - AIR_F) / GROUND_F +PLAYER_W, PLAYER_H, EYE = 0.6, 1.8, 1.62 +PLAYER_REACH = 3.0 +WALL_CAP = 8 +# SPEED_NOTE (minecraft-arena@5): a Java mob's ground speed scales with the *square* of (movement_speed attribute x its +# goal's speed modifier): MoveControl sets the forward input to that value and LivingEntity.travel scales the input by the +# same speed again; the player's input is 0.98 at attribute 0.1. Relative to the walking player (0.216 b/t here): +# v = 0.216 x (attribute x modifier)^2 / 0.098. Zombie 0.23 -> 0.117 b/t (2.3 m/s, the commonly measured value), +# skeleton 0.25 -> 0.138, warden 0.3 x its 1.2 fight modifier -> 0.286 (a sprinting player's 0.281: it cannot be +# outrun). The new scenes use these (the leader zombie 0.117); the @4 bosses, the formal zombie included, keep their +# tuned values. + +WEAPONS = ('sword', 'bow') +BOW_RULES = { + 'version': 'bossbench/minecraft-bow@2', + 'draw_seconds': 1.0, 'minimum_power': 0.1, + 'maximum_speed_blocks_per_vanilla_tick': 3.0, + 'gravity_blocks_per_vanilla_tick_squared': 0.05, + 'drag_per_vanilla_tick': 0.99, 'base_damage_per_speed': 2.0, + 'maximum_life_seconds': 60.0, 'ammunition': 'unlimited', + 'aim_assist': False, 'arrow_radius_blocks': 0.025, +} + + +def _weapon(value): + if not isinstance(value, str) or value not in WEAPONS: + raise ValueError(f'weapon must be one of {WEAPONS}, got {value!r}') + return value + + +def _camera(value): + if value not in ('first', 'third'): + raise ValueError("camera must be 'first' or 'third'") + return value + + +def _segment_box(start, end, low, high): + """First intersection fraction of a swept arrow segment and an AABB.""" + lower, upper = 0.0, 1.0 + direction = end - start + for axis in range(3): + if abs(direction[axis]) < 1e-12: + if start[axis] < low[axis] or start[axis] > high[axis]: + return None + continue + a = (low[axis] - start[axis]) / direction[axis] + b = (high[axis] - start[axis]) / direction[axis] + lower, upper = max(lower, min(a, b)), min(upper, max(a, b)) + if lower > upper: + return None + return lower + + +class Entity: + def __init__(self, x, y, z, yaw, w, h): + self.pos, self.vel = np.array([x, y, z], float), np.zeros(3) + self.yaw, self.w, self.h, self.on_ground, self.fall_from = yaw, w, h, True, 0.0 + self.pitch = 0.0 # bow aiming; positive pitch looks up + + @property + def fwd(self): + return np.array([math.cos(self.yaw), 0.0, math.sin(self.yaw)]) + + @property + def right(self): + return np.array([-math.sin(self.yaw), 0.0, math.cos(self.yaw)]) + + +# ---------------------------------------------------------------- arena +class VoxelArena(Arena): + """Layouts. 'field' is the ground fight (low cover, one climbable pillar); 'towers' adds tall columns so an aerial + boss can be broken off and its line of sight cut. minecraft-arena@5 adds three themed layouts that draw the field's + cover first (same random stream, so a seed gives the same base layout) and then their own pieces: + 'night' (no extra pieces: the field at night, for the leader zombie and its reinforcements), 'deep_dark' + (deepslate pillars 3-4 high: tempting perches that the warden answers with its sonic boom) and 'ruins' + (broken stone-brick walls 2-3 high that stop arrows both ways: cover for a bow duel).""" + TABLE = {"cover_clusters": (8, 5, 2), # 1-high blocks: jumpable, block a ground mob's path + "safe_pillars": (2, 1, 0), # 3-high pillars: the classic "pillar up" cheese + "towers": (2, 3, 4), # tall columns, towers layout only + "dark_pillars": (3, 3, 3), # deep_dark only (minecraft-arena@5) + "ruin_walls": (6, 6, 6)} # ruins only (minecraft-arena@5) + + def __init__(self, style="field"): + self.style = style + + def reset(self, case): + super().reset(case) + rng, H = case.rng, np.zeros((S, S), np.int8) + H[0, :] = H[-1, :] = H[:, 0] = H[:, -1] = WALL_CAP # arena wall + for _ in range(int(round(self.k.cover_clusters * AREA_K))): + x, z = rng.integers(3, S - 4, 2) + H[x:x + rng.integers(1, 3), z:z + rng.integers(1, 3)] = 1 + for _ in range(int(round(self.k.safe_pillars * AREA_K))): + x, z = rng.integers(4, S - 4, 2) + H[x, z] = 3 + H[x + 1, z] = max(H[x + 1, z], 1) + H[x + 1, z + 1] = max(H[x + 1, z + 1], 2) + if self.style == "towers": + for _ in range(int(round(self.k.towers * AREA_K))): + x, z = rng.integers(3, S - 5, 2) + H[x, z] = 4 + int(rng.integers(0, 3)) + H[x, z + 1] = max(H[x, z + 1], 1) + H[x + 1, z] = max(H[x + 1, z], int(H[x, z]) - 1) + elif self.style == "deep_dark": + for _ in range(int(round(self.k.dark_pillars * AREA_K))): + x, z = (int(v) for v in rng.integers(5, S - 5, 2)) + h = 3 + int(rng.integers(0, 2)) + H[x:x + 2, z:z + 2] = h # 2x2 deepslate column + for i in range(1, h): # a staircase: the top can be reached + H[x - i, z] = max(H[x - i, z], h - i) + elif self.style == "ruins": + for _ in range(int(round(self.k.ruin_walls * AREA_K))): + x, z = (int(v) for v in rng.integers(4, S - 9, 2)) + n, h = int(rng.integers(3, 7)), 2 + int(rng.integers(0, 2)) + gap = int(rng.integers(1, n - 1)) # a breach somewhere along the wall + for i in range(n): + if i == gap: + continue + if rng.random() < 0.5: + H[x + i, z] = max(H[x + i, z], h) + else: + H[x, z + i] = max(H[x, z + i], h) + m = int(MID) + H[m - 8:m - 3, m - 2:m + 2] = H[m + 3:m + 8, m - 2:m + 2] = 0 # spawn pads + self.H = H + + def ground(self, p, w): + h = w / 2 - 1e-6 + x0, x1, z0, z1 = int(p[0] - h), int(p[0] + h), int(p[2] - h), int(p[2] + h) + if p[0] - h < 0 or p[2] - h < 0 or x1 >= S or z1 >= S: + return 99.0 + return float(self.H[x0:x1 + 1, z0:z1 + 1].max()) + + def los(self, a, b, eye_h=1.5): + """Coarse line of sight: sampled columns between two entity centres.""" + a, b = np.asarray(a, float), np.asarray(b, float) + n = min(int(np.hypot(*(b - a)[[0, 2]]) * 2) + 1, 32) + for u in np.linspace(0.06, 0.94, n): + p = a + (b - a) * u + ix, iz = int(p[0]), int(p[2]) + if not (0 <= ix < S and 0 <= iz < S): + continue + if self.H[ix, iz] > p[1] + eye_h: + return False + return True + + +def physics(case, e, wish, accel, step=0.6, vertical=True): + """Minecraft-style integration: ground friction 0.546, air drag 0.91, gravity (per vanilla tick, converted + to the simulation tick); per-axis collision. accel is the vanilla walk speed in b/t; e.vel is per sim tick.""" + A = case.arena + if e.on_ground: + e.vel[[0, 2]] = e.vel[[0, 2]] * GROUND_F + wish[[0, 2]] * per_vt(accel) * (1 - GROUND_F) + else: + e.vel[[0, 2]] = e.vel[[0, 2]] * AIR_F + wish[[0, 2]] * AIR_A + blocked = False + for ax in (0, 2): + new = e.pos.copy() + new[ax] += e.vel[ax] + if A.ground(new, e.w) > e.pos[1] + step: + e.vel[ax], blocked = 0.0, True + else: + e.pos = new + landed_from = None + if not vertical: + return blocked, landed_from + e.pos[1] += e.vel[1] + e.vel[1] = (e.vel[1] - GRAVITY) * FALL_F + g = A.ground(e.pos, e.w) + if e.pos[1] <= g: + if not e.on_ground: + landed_from = e.fall_from - g + e.pos[1], e.vel[1], e.on_ground = g, 0.0, True + e.fall_from = g + else: + if e.on_ground: + e.fall_from = e.pos[1] + e.fall_from = max(e.fall_from, e.pos[1]) + e.on_ground = False + return blocked, landed_from + + +def armor_reduce(dmg, armor, tough): + return dmg * (1 - min(20.0, max(armor / 5, armor - 4 * dmg / (tough + 8))) / 25) + + +# ---------------------------------------------------------------- ground navigation (minecraft-arena@4) +# Pure functions of the arena heights, cached by their bytes: shared by every clone the scripted controller makes +# and by the live case, so a lookahead never pays twice for the same field. +_NAV_CACHE: dict = {} +_STEPS = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)) + + +def _cached(key, make): + hit = _NAV_CACHE.get(key) + if hit is None: + if len(_NAV_CACHE) > 512: + _NAV_CACHE.clear() + hit = _NAV_CACHE[key] = make() + return hit + + +def nav_free(H, r, step): + """Cells whose centre a mob of grid radius r (0: 0.6 wide, 1: 1.4 wide) can stand on: no column taller than + `step` (the auto-jump height) within r cells, and not the arena wall.""" + def make(): + wall = H > step + grown = wall.copy() + for dx in range(-r, r + 1): + for dz in range(-r, r + 1): + grown |= np.roll(np.roll(wall, dx, 0), dz, 1) + grown[[0, -1], :] = True + grown[:, [0, -1]] = True + return ~grown + return _cached(("free", H.tobytes(), r, step), make) + + +def _steps(free, cell): + """8-connected moves from cell onto free cells, without cutting a wall corner.""" + x, z = cell + for dx, dz in _STEPS: + a, b = x + dx, z + dz + if not (0 < a < S - 1 and 0 < b < S - 1) or not free[a, b]: + continue + if dx and dz and not (free[x + dx, z] and free[x, z + dz]): + continue + yield a, b + + +def nav_field(H, r, step, goal): + """Breadth-first step counts from every free cell to the goal cell (10**6 where unreachable).""" + def make(): + free = nav_free(H, r, step) + dist = np.full(free.shape, 10 ** 6, np.int32) + dist[goal] = 0 + frontier, n = [goal], 0 + while frontier: + n += 1 + nxt = [] + for cell in frontier: + for a, b in _steps(free, cell): + if dist[a, b] > n: + dist[a, b] = n + nxt.append((a, b)) + frontier = nxt + return dist + return _cached(("field", H.tobytes(), r, step, goal), make) + + +def _walkable(free, start, seg, own, goal): + """True when every cell the straight segment crosses (except the two end cells) is free.""" + length = math.hypot(seg[0], seg[2]) + k = int(length / 0.35) + 2 + x0, z0, sx, sz = float(start[0]), float(start[2]), float(seg[0]) / (k - 1), float(seg[2]) / (k - 1) + for i in range(1, k - 1): + c = (min(max(int(x0 + sx * i), 0), S - 1), min(max(int(z0 + sz * i), 0), S - 1)) + if c != own and c != goal and not free[c]: + return False + return True + + +# ---------------------------------------------------------------- body +# The player's loadout is part of a scene, identical on every tier (minecraft-arena@5): (sword attack damage, armor points, +# armor toughness). Diamond against the end-game bosses (iron golem, ender dragon, wither, warden) and on the formal +# zombie case (its @4 kit), iron against the overworld night mobs (leader zombie horde, skeleton archer): Java iron +# sword 6, iron armor 15 / 0; diamond sword 7, 20 / 8. +KITS = {"diamond": (7.0, 20.0, 8.0), "iron": (6.0, 15.0, 0.0)} +SCENE_KIT = {"iron_golem": "diamond", "zombie": "diamond", "ender_dragon": "diamond", "wither": "diamond", + "warden": "diamond", "skeleton": "iron", "zombie_leader": "iron"} + + +class Steve(Body, Rigged): + # One fixed loadout per scene on every tier (only the boss scales with the tier): the TABLE is the @4 diamond kit, + # replaced at reset by the scene's KITS entry (identical floats for the diamond scenes). + TABLE = {"sword_dmg": (7, 7, 7), + "armor": (20, 20, 20), + "toughness": (8, 8, 8)} + MOVES = ("none", "forward", "back", "left", "right") + action_space = gym.spaces.MultiDiscrete([5, 5, 2, 2, 2]) # move, turn, jump, attack, sprint + max_hp = 20.0 + T_ATTACK = FPS / 1.6 # ticks to a full attack charge (sword attack speed 1.6 -> 12.5 vanilla ticks) + T_FIST = FPS / 4.0 # empty hand / bow in hand: attack speed 4 -> 5 vanilla ticks + CRIT_CHARGE = 0.9 # Java: f2 > 0.9, i.e. the 84.8 % damage multiplier + HOTBAR = ('sword', 'bow') + + def __init__(self, weapon='sword'): + self.weapon = _weapon(weapon) + self.rig = None + self.ph = 0.0 + + def reset(self, case): + super().reset(case) + self.kit = SCENE_KIT.get(getattr(case, "mob_name", ""), "diamond") + self.k.sword_dmg, self.k.armor, self.k.toughness = KITS[self.kit] + self.e = Entity(MID - 5.5, 0.0, MID, 0.0, PLAYER_W, PLAYER_H) + self.hp, self.since_swing, self.iframes, self.sprinting = self.max_hp, 5 * FPS, 0, False + self.last_hurt, self.wither_t = 0.0, 0 + self.ph, self.swing_t = 0.0, -5 * FPS + self.bow_draw_ticks, self.bow_drawing = 0, False + self.arrows_fired, self.arrows_hit, self.arrow_damage = 0, 0, 0.0 + self.wheel, self.notches, self.switches, self.melee_damage = 0.0, 0, 0, 0.0 + self._build_rig() + + # -- rig --------------------------------------------------------------- + def _build_rig(self): + self.rig = mcskin.steve_rig() + + def pose(self, case): + mcskin.pose_steve(self, case) + + def noop(self): + return np.array([0, 2, 0, 0, 0]) + + MOUSE_DEG = 0.15 # camera yaw/pitch per mouse unit (dx = 200 in one packet turns 30 deg) + MANUAL = ( + "W forward, S back, A strafe left, D strafe right (one direction at a time; W > S > A > D)", + "mouse dx turns right and dy looks down, 0.15 deg per unit (dx 200 = 30 deg); pitch is limited to +-89 deg; " + "there is no aim assist for any weapon (since rules minecraft-arena@2)", + "Space jump (while held, whenever on the ground); Shift sprint (only while holding W)", + "hotbar: slot 1 sword (diamond against the end-game bosses, iron against the night mobs), slot 2 bow; mouse " + "wheel dz switches slots (each notch one slot); " + "switching resets the attack cooldown and cancels a bow draw", + "sword in hand: LMB or J swings once per press, 3 blocks reach along the view ray; damage scales with the " + "attack-cooldown charge (1.6 swings/s); a falling hit with charge > 90 %, not sprinting, is a crit (x1.5); " + "a sprinting hit at > 90 % adds knockback", + "bow in hand: hold RMB to draw across packets, release to fire (1 s = full draw, critical arrow); drawing " + "slows movement and stops sprinting; arrows fall with gravity and stop on terrain; LMB/J punch for 1", + "every hit gives 10 vanilla ticks (0.5 s) of damage immunity; a stronger hit inside it deals only the difference", + ) + SWORD_MANUAL = MANUAL # kept for older imports + + @property + def manual(self): + return self.MANUAL + + def keys(self, case, held, pressed, mouse): + self.e.yaw = (self.e.yaw + math.radians(mouse[0] * self.MOUSE_DEG)) % (2 * math.pi) + self.e.pitch = float(np.clip(self.e.pitch - math.radians(mouse[1] * self.MOUSE_DEG), + math.radians(-89), math.radians(89))) + if len(mouse) > 2 and mouse[2]: + # The packet's wheel motion is spread over its ticks; a notch lands on the first tick that starts it. + self.wheel += mouse[2] + a = self.wheel + target = math.ceil(a - 1e-6) if a > 1e-6 else (-math.ceil(-a - 1e-6) if a < -1e-6 else 0) + while self.notches != target: + step = 1 if target > self.notches else -1 + self.notches += step + self.select(case, self.HOTBAR[(self.HOTBAR.index(self.weapon) + step) % len(self.HOTBAR)]) + move = next((i for i, k in ((1, "W"), (2, "S"), (3, "A"), (4, "D")) if k in held), 0) + swing = bool(pressed & {"LMB", "J"}) + if self.weapon == 'bow': + return np.array([move, 2, "Space" in held, 'RMB' in held, "Shift" in held, swing]) + return np.array([move, 2, "Space" in held, swing, "Shift" in held, 0]) + + def select(self, case, weapon): + """Hotbar switch: Java resets the attack strength ticker whenever the held item changes.""" + if weapon == self.weapon: + return + if self.bow_drawing: + case.events.append('bow_cancel') + self.weapon, self.since_swing = weapon, 0 + self.bow_drawing, self.bow_draw_ticks = False, 0 + self.switches += 1 + case.events.append(('hotbar', weapon)) + + def parse(self, text): + w = set(text.lower().replace(",", "+").replace(" ", "+").split("+")) + move = next((i for i, m in enumerate(self.MOVES) if m in w), 0) + turn = 0 if "turn_left_big" in w else 1 if "turn_left" in w else 4 if "turn_right_big" in w else \ + 3 if "turn_right" in w else 2 + return np.array([move, turn, "jump" in w, "attack" in w, "sprint" in w]) + + @property + def attack_charge(self): + """Java attack strength scale f2 = clamp((t + 0.5) / T) for the item in hand.""" + return min(1.0, (self.since_swing + 0.5) / (self.T_ATTACK if self.weapon == 'sword' else self.T_FIST)) + + @property + def charge(self): + if self.weapon == 'bow': + return self.bow_charge + return self.attack_charge + + @property + def bow_charge(self): + return min(1.0, self.bow_draw_ticks / (FPS * BOW_RULES['draw_seconds'])) + + def apply(self, case, action): + move, turn, jump, attack, sprint = (int(a) for a in action[:5]) + punch = len(action) > 5 and bool(action[5]) + e = self.e + self.iframes, self.since_swing = max(self.iframes - 1, 0), self.since_swing + 1 + e.yaw = (e.yaw + TURNS[turn]) % (2 * math.pi) + wish = {0: 0 * e.fwd, 1: e.fwd, 2: -e.fwd, 3: -e.right, 4: e.right}[move] + drawing = self.weapon == 'bow' and bool(attack) + self.sprinting = bool(sprint) and move == 1 and not drawing + if jump and e.on_ground: + e.vel[1] = JUMP + if self.sprinting: + e.vel += e.fwd * SPRINT_JUMP + speed = 0.281 if self.sprinting else 0.216 + if drawing: + wish = wish * 0.2 + _, fell = physics(case, e, wish, speed) + if fell and fell > 3: + case.hurt_player(fell - 3, armor=False) + case.events.append("fall_damage") + if self.wither_t > 0: # Wither II: 1 damage per 20 vanilla ticks, ignores armor + self.wither_t -= 1 + if self.wither_t % ticks(20) == 0: + case.hurt_player(1.0, armor=False) + case.events.append("wither_effect") + if self.weapon == 'bow': + self._update_bow(case, bool(attack)) + if punch: + self._swing(case) + elif attack: + self._swing(case) + + def _update_bow(self, case, held): + if held: + if not self.bow_drawing: + case.events.append('bow_draw') + self.bow_drawing = True + self.bow_draw_ticks += 1 + return + if not self.bow_drawing: + return + charge = self.bow_charge + power = min(1.0, (charge * charge + 2.0 * charge) / 3.0) + self.bow_drawing, self.bow_draw_ticks = False, 0 + if power < BOW_RULES['minimum_power']: + case.events.append('bow_cancel') + return + e = self.e + direction = self.look() + speed = BOW_RULES['maximum_speed_blocks_per_vanilla_tick'] * power + self.arrows_fired += 1 + case.arrows.append({'id': self.arrows_fired, + 'pos': e.pos + [0, EYE, 0] + direction * 0.1, + 'vel': direction * per_vt(speed), 'age': 0, + 'damage': float(math.ceil(speed * BOW_RULES['base_damage_per_speed'])), + 'critical': power >= 1.0}) + case.events.append(('bow_release', self.arrows_fired, round(power, 4))) + + def look(self): + e = self.e + return np.array([math.cos(e.yaw) * math.cos(e.pitch), math.sin(e.pitch), + math.sin(e.yaw) * math.cos(e.pitch)]) + + def ray_hit(self, case): + """Nearest target box along the view ray within the 3 block attack range: (distance, kind, payload) or + None. Terrain in front of the target blocks the swing.""" + eye = self.e.pos + [0, EYE, 0] + ray = self.look() + best = None + for kind, lo, hi, payload in case._targets(): + with np.errstate(divide="ignore", invalid="ignore"): + t1, t2 = (lo - eye) / ray, (hi - eye) / ray + tn, tf = np.nanmax(np.minimum(t1, t2)), np.nanmin(np.maximum(t1, t2)) + if tn <= tf and tf >= 0 and tn <= PLAYER_REACH and (best is None or tn < best[0]): + best = (max(float(tn), 0.0), kind, payload) + if best is not None and best[0] > 0.05: + wall, _ = case._arrow_world_hit(eye, eye + ray * best[0]) + if wall is not None and wall < 0.999: + return None + return best + + def _swing(self, case): + """Ray vs the mob hitbox along the player's own yaw and pitch (no aim assist since minecraft-arena@2).""" + g, e = case.boss, self.e + charge, self.since_swing = self.attack_charge, 0 + self.swing_t = case.t + target = self.ray_hit(case) + if target is None: + case.events.append("miss") + return + base = self.k.sword_dmg if self.weapon == 'sword' else 1.0 + mult = 0.2 + min(charge, 1.0) ** 2 * 0.8 + strong = charge > self.CRIT_CHARGE + living = target[1] in ("boss", "minion") and not hasattr(g, "hitboxes") # Java: crits need a LivingEntity + crit = strong and living and not e.on_ground and e.vel[1] < 0 and not self.sprinting + sprint_hit = strong and self.sprinting + dmg = base * mult * (1.5 if crit else 1.0) + self.melee_damage += case._damage(target[1], target[2], dmg, "crit" if crit else "normal", + bonus_knockback=0.5 if sprint_hit else 0.0) + if sprint_hit: # Java: the attacker stops sprinting, keeps 60 % speed + e.vel[[0, 2]] *= 0.6 + self.sprinting = False + case.events.append("sprint_hit") + + +# ---------------------------------------------------------------- mobs +class Mob(Boss, Rigged): + """Shared machinery: hitboxes, knockback, hit flash, hit posing, rig bookkeeping.""" + STATES = ("chase", "windup", "swing", "recover") + aim_h = 1.35 # where the player's aim assist points + half = (0.7, 0.7) # hitbox half extents in x/z + knockback = 1.0 # 0 = knockback immune (vanilla iron golem) + hover = False + armor = 0.0 # natural armor points (Java: zombie 2, wither 4) + hit_event = "boss_hit" # event name a landed hit records ("minion_hit" for zombie reinforcements, @5) + last_hurt = 0.0 + + def __init__(self): + self.rig = None + self.tint_t = 0 + + def reset(self, case): + super().reset(case) + self._steer_t, self._steer_dir = -9, np.zeros(3) # steer() memo: last vanilla-tick plan + + # -- geometry ---------------------------------------------------------- + def hit_lo(self): + return self.e.pos - [self.half[0], 0.0 if not self.hover else 0.75, self.half[1]] + + def hit_hi(self): + return self.e.pos + [self.half[0], self.height if not self.hover else -0.75, self.half[1]] + + def dist_to(self, case): + return case.body.e.pos - self.e.pos + + ATTACK_INFLATE = math.sqrt(2.04) - 0.6 # Java 1.20.2+: attack box = collision box + 0.828 horizontally + + def in_reach(self, case): + """Java 1.20.2+ mob melee: the collision box expanded horizontally by 0.828 must intersect the + target's box, with line of sight (no hits through walls). Replaces the pre-1.20.2 reach^2 test.""" + p, r = case.body.e, self.ATTACK_INFLATE + lo = self.e.pos - [self.half[0] + r, 0.0, self.half[1] + r] + hi = self.e.pos + [self.half[0] + r, self.height, self.half[1] + r] + plo, phi = p.pos - [PLAYER_W / 2, 0.0, PLAYER_W / 2], p.pos + [PLAYER_W / 2, PLAYER_H, PLAYER_W / 2] + if not (np.all(lo <= phi) and np.all(plo <= hi)): + return False + return case.arena.los(self.e.pos + [0, 1.0, 0], p.pos + [0, 1.0, 0], eye_h=0.0) + + def immune(self, case, kind): + """Hits this mob ignores outright (wither spawn charge, wither armor vs arrows).""" + return False + + # -- ground pathing (minecraft-arena@4) ---------------------------------------------------------------- + NAV_STEP = 1 # columns up to this height are walkable (auto-jump); taller ones are walls + + def steer(self, case): + """Unit xz walking direction toward the player. Straight while the line to the player is walkable (Java + mobs walk at a visible target); around walls along the step field otherwise (Java mobs path-find; without it + a pillar between the two pinned the mob in place forever: a soft-lock, found 2026-11-02). Re-planned once + per vanilla tick, like Java's 20 Hz mob AI; the two sim ticks in between keep the last direction.""" + if case.t % 3 and case.t - 2 <= getattr(self, "_steer_t", -9) <= case.t: + return self._steer_dir + self._steer_t, self._steer_dir = case.t, self._plan_steer(case) + return self._steer_dir + + def _plan_steer(self, case): + e, p = self.e, case.body.e + to = p.pos - e.pos + to[1] = 0.0 + n = math.hypot(to[0], to[2]) + if n < 1e-6: + return to + H = case.arena.H + r = int(math.ceil(self.half[0] - 0.5 - 1e-9)) + free = nav_free(H, r, self.NAV_STEP) + own = (int(e.pos[0]), int(e.pos[2])) + goal = (min(max(int(p.pos[0]), 1), S - 2), min(max(int(p.pos[2]), 1), S - 2)) + if _walkable(free, e.pos, to, own, goal): + return to / n + dist = nav_field(H, r, self.NAV_STEP, goal) + cell, path = own, [] + for _ in range(4): # follow the field downhill a few cells + here = dist[cell] if free[cell] else 10 ** 6 + best = None + for a, b in _steps(free, cell): + if dist[a, b] < here and (best is None or dist[a, b] < dist[best]): + best = (a, b) + if best is None: + break + path.append(best) + cell = best + if dist[cell] == 0: + break + if not path: + return to / n # nowhere better: lean on the wall toward the target + aim = np.array([path[0][0] + 0.5, 0.0, path[0][1] + 0.5]) + for c in reversed(path[1:]): # string-pull to the farthest cell in a straight line + target = np.array([c[0] + 0.5, 0.0, c[1] + 0.5]) + seg = target - e.pos + seg[1] = 0.0 + if _walkable(free, e.pos, seg, own, c): + aim = target + break + d = aim - e.pos + d[1] = 0.0 + return d / (float(np.linalg.norm(d)) + 1e-9) + + def on_hurt(self, case, amount, kind): + pass + + def take_hit(self, case, dmg, kind="normal", bonus_knockback=0.0): + """Java LivingEntity.hurt: a hit starts 10 vanilla ticks of immunity; inside the window only a stronger + hit lands and deals the difference (no knockback, no new window). Armor applies to what lands.""" + if self.immune(case, kind): + case.events.append(("boss_immune", kind)) + return 0.0 + fresh = self.iframes <= 0 + if fresh: + amount, self.last_hurt = dmg, dmg + self.iframes = ticks(10) + self.tint_t = ticks(8) + elif dmg > self.last_hurt: + amount, self.last_hurt = dmg - self.last_hurt, dmg + else: + return 0.0 + if self.armor: + amount = armor_reduce(amount, self.armor, 0.0) + amount = amount * (1.0 - float(getattr(self, "guard", 0.0))) + self.hp -= amount + if fresh and self.knockback > 0 and not self.hover: + d = self.e.pos - case.body.e.pos + n = float(np.linalg.norm(d[[0, 2]])) + 1e-6 + self.e.vel[[0, 2]] += d[[0, 2]] / n * push(0.4 + bonus_knockback, 0.546) * self.knockback + case.events.append((self.hit_event, round(amount, 2), kind)) + self.on_hurt(case, amount, kind) + return amount + + def hurt_player(self, case, dmg, fling=0.0, iframes=True, share=1.0, armor=True, origin=None, lift=0.0): + """Damage the player; a fresh (non-immune) hit knocks the player away from origin (default: this mob). + Java knockback: horizontal velocity halved plus the push; on the ground vy = min(0.4, vy / 2 + 0.4); + lift adds the iron golem's extra +0.4 b/t launch.""" + p = case.body.e + landed = case.hurt_player(dmg, armor=armor, iframes=iframes, share=share) + if not landed: + return False + if fling and landed == "fresh": + d = p.pos - (self.e.pos if origin is None else np.asarray(origin, float)) + n = float(np.linalg.norm(d[[0, 2]])) + 1e-6 + p.vel[[0, 2]] = p.vel[[0, 2]] / 2 + d[[0, 2]] / n * push(fling, 0.546 if self.hover else 0.91) + if not self.hover or lift: + p.vel[1] = vy_sim(min(0.4, vy_vanilla(p.vel[1]) / 2 + 0.4) + lift) + p.on_ground = False + return True + + # -- rig --------------------------------------------------------------- + def rigs(self): + return [self.rig] if self.rig is not None else [] + + def extra(self, case): + """Transient hazard visuals owned by the simulation (skulls), drawn as world-axis boxes.""" + return [] + + def fx(self, case): + """Particle visuals. Uses case.fxrng, never case.rng: rendering must not consume the + gameplay random stream.""" + return [] + + +class IronGolem(Mob): + TABLE = { # (easy, normal, hard) = TIERS + "hp": (380, 1000, 2700), # TIER calibration for ~25 s / 1 min / 3 min (Java: 100 on every difficulty) + "speed": (0.11, 0.13, 0.15), # vanilla b/t chase, below the player's 0.216 walk (Java ~0.14) + "dmg_min": (4.75, 7.5, 11.25), # Java easy / normal / hard + "dmg_max": (11.75, 21.5, 32.25), + "cooldown": (30, 24, 20), # vanilla ticks between slams (Java 20) + "windup": (0.60, 0.45, 0.35), # EXT seconds of raised arms before the hit + "jitter": (0.0, 0.05, 0.10), # EXT tempo variance + } + MOVES = {"swing": {"atoms": ["melee_area", "grab/fling"], "telegraph": "both arms raised", + "damage": "U[dmg_min, dmg_max] then armor", "range": "reach^2=(2*1.4)^2+0.6", + "punish": "cooldown (vanilla ticks) after each swing; cannot reach targets >=2.75 above"}} + SKILLS = ("spacing", "attack_timing", "crit_jump", "kiting", "terrain_use", "reaction") + name = "iron_golem" + height, aim_h, reach, reach_up = 2.7, 1.35, 2.9, 2.75 + half = (0.7, 0.7) + knockback = 0.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 5.5, 0.0, MID, math.pi, 1.4, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0 + self.ph, self.tint_t, self.arm = 0.0, 0, 0.0 + self.rig = golem_rig() + + @property + def enraged(self): + return False # the @1-@3 below-half-HP enrage is not Java; dropped in @4 + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + to = p.pos - e.pos + wish = self.steer(case) + e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw + speed = k.speed + if self.state == "chase": + if self.cd == 0 and self.in_reach(case): + self.state = "windup" + self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter)) + case.events.append("golem_windup") + elif self.state == "windup": + speed *= 0.3 + if self.timer <= 0: + self.state, self.timer = "swing", 0.15 + if self.in_reach(case): + if self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max), fling=0.4, lift=0.4): + case.events.append(("golem_hit",)) + else: + case.events.append("golem_whiff") + elif self.state == "swing": + speed = 0.0 + if self.timer <= 0: + self.state, self.cd = "recover", ticks(k.cooldown) + elif self.state == "recover" and self.cd == 0: + self.state = "chase" + if np.hypot(to[0], to[2]) < 0.75: + wish = 0 * wish + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP # mobs auto-jump 1-block steps + self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 0.75) % 1.0 + self.pose(case) + + def pose(self, case): + mcskin.pose_golem(self, case) + + + +class Zombie(Mob): + TABLE = { + "hp": (14, 20, 26), + "speed": (0.13, 0.19, 0.26), + "dmg_min": (2.5, 3.0, 4.5), # Java easy / normal / hard (fixed per difficulty) + "dmg_max": (2.5, 3.0, 4.5), + "cooldown": (30, 20, 14), + "windup": (0.45, 0.28, 0.10), + "jitter": (0.0, 0.12, 0.3), + "enrage_speed": (1.0, 1.0, 1.3), # EXT: below half hp + "flail": (0.0, 0.0, 0.0), # EXT follow-up swipe, disabled since minecraft-arena@2 (not in Java) + } + MOVES = {"swipe": {"atoms": ["melee_single"], "telegraph": "arm cocked back", + "damage": "Java 2.5 / 3 / 4.5 then armor", "range": "reach 2.4", + "punish": "short cooldown; takes knockback on every hit; natural armor 2"}} + SKILLS = ("spacing", "attack_timing", "kiting", "target_priority", "reaction") + name = "zombie" + height, aim_h, reach, reach_up = 1.95, 1.05, 2.4, 2.6 + half = (0.3, 0.3) + knockback = 1.0 + armor = 2.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 2.0, 0.0, MID, math.pi, 0.6, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0 + self.ph, self.tint_t, self.swipes = 0.0, 0, 0 + self.rig = zombie_rig() + + @property + def enraged(self): + return self.hp <= self.max_hp / 2 + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + to = p.pos - e.pos + wish = self.steer(case) + e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw + speed = k.speed * (k.enrage_speed if self.enraged else 1.0) + if self.state == "chase": + if self.cd == 0 and self.in_reach(case): + self.state = "windup" + self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter)) + case.events.append("zombie_windup") + elif self.state == "windup": + speed *= 0.35 + if self.timer <= 0: + self.state, self.timer, self.swipes = "swing", 0.1, 0 + if self.in_reach(case): + self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max), fling=0.4) + self.swipes = 1 + int(case.rng.random() < k.flail * 0.5) + else: + case.events.append("zombie_whiff") + elif self.state == "swing": + speed = 0.0 + if self.timer <= 0: + self.swipes -= 1 + if self.swipes > 0 and self.in_reach(case): + self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max) * 0.7, fling=0.4) + self.timer = 0.1 + case.events.append("zombie_flail") + else: + self.state, self.cd = "recover", ticks(k.cooldown) + elif self.state == "recover" and self.cd == 0: + self.state = "chase" + if np.hypot(to[0], to[2]) < 0.45: + wish = 0 * wish + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP + self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0 + self.pose(case) + + def pose(self, case): + mcskin.pose_zombie(self, case) + + + +class ZombieLeader(Mob): + """Java Edition 1.21 *leader zombie* as a boss fight (minecraft.wiki/w/Zombie, read 2026-11-02; Java: + up to 5 % spawn on Normal / Hard, max health x2-5, reinforcement chance +50-75 %) on a night field. Every hit it takes + may call a reinforcement: a plain zombie (20 HP, armor 2, 0.23 speed attribute) spawned 7-12 blocks away, out of + the player's reach, that joins the chase at once; the leader's chance drops 5 % per summon, as in Java. The case is won + by killing the leader; reinforcements only add pressure (their hits on the player, their bodies blocking the way). + + Its own case since minecraft-arena@6 (3d/minecraft_zombie_leader): @5 had put it under 3d/minecraft_zombie, a + FORMAL_CASES scene that keeps its @4 rules (class Zombie above). + + Deliberate deviations (minecraft-arena@5): reinforcements are on every tier (Java: Hard only), with the chance and the + number alive scaled by tier, because a public tier must be the same fight paced differently; the spawn search is the + arena's free floor 7-12 blocks from the player instead of Java's 0 / +-7-40 blocks in darkness. + """ + TABLE = { # (easy, normal, hard) = TIERS + "hp": (215, 520, 1650), # TIER calibration (Java leader: 40-100 = 2-5x a zombie's 20) + "speed": (0.105, 0.117, 0.135), # vanilla b/t chase; Java 0.117 (see SPEED_NOTE), slower than a walk + "dmg_min": (2.5, 3.0, 4.5), # Java easy / normal / hard (fixed per difficulty) + "dmg_max": (2.5, 3.0, 4.5), + "cooldown": (30, 20, 20), # vanilla ticks between swings (Java 20) + "windup": (0.45, 0.30, 0.20), # EXT seconds of raised arms before the hit + "jitter": (0.0, 0.10, 0.15), # EXT tempo variance + "reinforce": (0.55, 0.60, 0.70), # leader's chance to call a reinforcement when hurt (Java +50-75 %) + "minions": (2, 3, 4), # reinforcements alive at once (EXT cap) + "minion_hp": (20, 20, 20), # Java zombie + "minion_dmg": (2.5, 3.0, 4.5), # Java easy / normal / hard + } + MOVES = {"swipe": {"atoms": ["melee_single"], "telegraph": "arms raised high, a lunge", + "damage": "Java 2.5 / 3 / 4.5 then armor", "range": "attack box 0.83 around its body", + "punish": "20-tick cooldown; takes knockback on every hit; natural armor 2"}, + "reinforcements": {"atoms": ["summon_adds"], "telegraph": "smoke where a helper climbs out of the ground", + "damage": "each reinforcement swipes like its caller", + "range": "spawns 7-12 blocks from you", "punish": "kill the caller: the adds stay, the fight ends"}} + SKILLS = ("spacing", "attack_timing", "kiting", "target_priority", "crowd_control", "reaction") + name = "zombie_leader" + height, aim_h, reach, reach_up = 1.95, 1.05, 2.4, 2.6 + half = (0.3, 0.3) + knockback = 1.0 + armor = 2.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 4.0, 0.0, MID, math.pi, 0.6, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0 + self.ph, self.tint_t, self.swipes = 0.0, 0, 0 + self.chance = float(self.k.reinforce) + self.minions, self.summoned = [], 0 + self.rig = zombie_rig(leader=True) + + @property + def enraged(self): + return False # the @1-@4 below-half-HP speed-up is not Java; dropped in @5 + + def update(self, case): + self.melee(case, self.k.dmg_min, self.k.dmg_max) + self.minions = [z for z in self.minions if z.hp > 0] # the dead leave the fight (their puff is an event) + for z in self.minions: + z.update(case) + self.pose(case) + + def melee(self, case, dmg_min, dmg_max): + """One tick of the zombie melee AI (shared by the leader and its reinforcements).""" + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + to = p.pos - e.pos + wish = self.steer(case) + e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw + speed = k.speed + if self.state == "chase": + if self.cd == 0 and self.in_reach(case): + self.state = "windup" + self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter)) + case.events.append("zombie_windup") + elif self.state == "windup": + speed *= 0.35 + if self.timer <= 0: + self.state, self.timer = "swing", 0.1 + if self.in_reach(case): + self.hurt_player(case, case.rng.uniform(dmg_min, dmg_max), fling=0.4) + else: + case.events.append("zombie_whiff") + elif self.state == "swing": + speed = 0.0 + if self.timer <= 0: + self.state, self.cd = "recover", ticks(k.cooldown) + elif self.state == "recover" and self.cd == 0: + self.state = "chase" + if np.hypot(to[0], to[2]) < 0.45: + wish = 0 * wish + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP + self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0 + + def on_hurt(self, case, amount, kind): + """Java hurt(): a hurt mob may call a reinforcement; each summon lowers its own chance by 5 %.""" + alive = [z for z in self.minions if z.hp > 0] + if self.hp > 0 and len(alive) < int(round(self.k.minions)) and case.rng.random() < self.chance: + spot = self._reinforcement_spot(case) + if spot is not None: + self.chance = max(0.0, self.chance - 0.05) + self.summoned += 1 + z = Reinforcement(self, spot, self.summoned) + z.reset(case) + self.minions = alive + [z] + case.events.append(("zombie_reinforce", self.summoned, [round(float(v), 2) for v in spot])) + + def _reinforcement_spot(self, case): + """A free floor cell 7-12 blocks from the player (Java: 7-40 blocks away, never within 7 of a player).""" + H, p = case.arena.H, case.body.e.pos + for _ in range(24): + ang = case.rng.uniform(0.0, 2.0 * math.pi) + r = case.rng.uniform(7.0, 12.0) + x, z = p[0] + math.cos(ang) * r, p[2] + math.sin(ang) * r + if not (2.0 <= x <= S - 2.0 and 2.0 <= z <= S - 2.0): + continue + ix, iz = int(x), int(z) + if H[ix - 1:ix + 2, iz - 1:iz + 2].max() > 0: + continue + return np.array([ix + 0.5, 0.0, iz + 0.5]) + return None + + def rigs(self): + return [self.rig] + [z.rig for z in self.minions if z.rig is not None] + + def pose(self, case): + mcskin.pose_zombie(self, case) + + def pose_child(self, case, z): + """Posing of a reinforcement goes through its leader, so a lookahead clone can switch all posing off at once.""" + mcskin.pose_zombie(z, case) + + +class Reinforcement(ZombieLeader): + """A plain Java zombie called by the leader: 20 HP, armor 2, Java damage, the same melee AI. It climbs out of the + ground for 0.8 s (cannot move or attack), then joins the chase. It takes the player's hits through MobFight._targets + (kind "minion") and leaves the fight at 0 HP; it never calls reinforcements itself (Java's summoned zombie keeps a + 5 %-lower chance: two generations would flood a one-on-one arena).""" + hit_event = "minion_hit" + CLIMB = 16 # vanilla ticks climbing out of the ground + + def __init__(self, leader, spot, n): + super().__init__() + self.leader, self.spot, self.n = leader, np.asarray(spot, float), int(n) + + def reset(self, case): + Mob.reset(self, case) + self.k = self.leader.k + self.max_hp = self.hp = float(self.k.minion_hp) + to = case.body.e.pos - self.spot + self.e = Entity(self.spot[0], 0.0, self.spot[2], math.atan2(to[2], to[0]), 0.6, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0 + self.ph, self.tint_t, self.swipes, self.summoned, self.minions = 0.0, 0, 0, 0, [] + self.born = case.t + self.rig = zombie_rig() + + def update(self, case): + if self.hp <= 0: + return + if case.t - self.born < ticks(self.CLIMB): + self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0) + else: + self.melee(case, self.k.minion_dmg, self.k.minion_dmg) + self.leader.pose_child(case, self) + + def on_hurt(self, case, amount, kind): + if self.hp <= 0: + case.events.append(("minion_killed", self.n, [round(float(v), 2) for v in self.e.pos])) + + + +class EnderDragon(Mob): + """Java Edition 1.21 ender dragon phases (minecraft.wiki/w/Ender_Dragon, read 2026-11-01), at arena scale. + + holding circles the portal; every `decide` vanilla ticks it lands with chance 1 / (3 + crystals alive), + otherwise strafes the player with chance 1/2 + strafe flies at the player; lined up with line of sight it charges a fireball for `windup` and fires + (also right after an end crystal is destroyed); the fireball leaves a dragon's breath cloud + landing descends onto the portal at the arena centre + scanning perched: turns to the player; a player within 20 blocks after 1.25 s -> roar (2 s) -> flaming + (3 s breath cloud under its head, Harming I); after 4 flames, or > 50 damage taken while perched, it + takes off; nobody within 20 blocks for 5 s -> charge + charge rushes the player's position, then returns to holding + Hits to the head deal full damage, body/wing hits damage / 4 + min(damage, 1); arrows bounce off a perched + dragon. The nearest end crystal heals 1 HP every 10 vanilla ticks; destroying the healing crystal deals 10. + Contact: the head deals ram_dmg, the wings wing_dmg and a shove, only while the dragon was not hurt within + the last 10 vanilla ticks. The model, arena and clouds are scaled down (34-block arena instead of the island). + """ + TABLE = { + "hp": (150, 320, 1350), # TIER calibration for ~25 s / 1 min / 3 min (Java: 200 on every difficulty) + "speed": (0.40, 0.50, 0.60), # vanilla b/t cruise + "turn": (1.6, 2.2, 3.0), # rad/s + "ram_dmg": (6.0, 10.0, 15.0), # Java head contact easy / normal / hard + "wing_dmg": (3.5, 5.0, 7.5), # Java wing contact + "breath_dmg": (3.0, 3.0, 3.0), # Harming I per 20 vanilla ticks inside the perched breath + "cloud_dmg": (6.0, 6.0, 6.0), # Harming II per 20 vanilla ticks inside a fireball cloud + "cloud_s": (8.0, 10.0, 12.0), # APPROX fireball cloud life (Java 30 s, growing radius 3 -> 7) + "decide": (70, 50, 34), # vanilla ticks between holding-pattern decisions (path nodes) + "altitude": (9.0, 8.5, 8.0), # holding height above the floor + "windup": (0.55, 0.40, 0.25), # EXT fireball telegraph (Java fireball charge 5 ticks) + "bank": (24.0, 40.0, 58.0), # EXT roll into turns + "crystals": (2, 6, 8), # end crystals on the tallest towers (Java 10 on the island) + "crystal_blast": (43.5, 85.0, 127.5), # power-6 explosion peak damage (easy / normal / hard) + "land_base": (1.5, 3.0, 3.0), # landing chance per decision 1 / (land_base + crystals alive); Java 3 + "fire_min": (12.0, 10.0, 8.0), # APPROX nearest fireball shot, blocks from mouth to chest + } + MOVES = {"fireball": {"atoms": ["projectile_linear", "area_cloud"], "telegraph": "lines up on you, mouth glows", + "damage": "cloud_dmg per second inside the purple cloud (magic: armor does not help)", + "range": "fired from up to 20 blocks with line of sight", + "punish": "after firing it returns to circling"}, + "perch": {"atoms": ["phase_land", "cone_dot"], "telegraph": "lands on the portal, roars for 2 s", + "damage": "breath_dmg per second in the cloud under its head", + "range": "breath under the head, about 2 blocks around", + "punish": "arrows bounce off, but sword hits on the head deal full damage; > 50 damage makes it take off"}, + "charge": {"atoms": ["charge_ram"], "telegraph": "after 5 s perched with nobody close it lifts and rushes", + "damage": "ram_dmg head contact, wing_dmg + shove from the wings", + "range": "body contact", "punish": "it flies past and climbs back to circling"}, + "crystals": {"atoms": ["heal_source"], "telegraph": "a white beam from the nearest crystal", + "damage": "the crystal explodes when hit (power 6)", + "range": "on top of the towers", "punish": "breaking the healing crystal deals 10 to the flyer"}} + SKILLS = ("aim_tracking", "target_priority", "weapon_switch", "dodge_dive", "dps_windows", "reaction") + STATES = ("circle", "strafe", "perch", "charge") + COARSE = {"holding": "circle", "takeoff": "circle", "strafe": "strafe", "landing": "perch", + "scanning": "perch", "roar": "perch", "flaming": "perch", "charge": "charge"} + SITTING = ("scanning", "roar", "flaming") + name = "ender_dragon" + height = 1.6 + hover = True + knockback = 0.0 + half = (1.25, 1.25) + PERCH_Y = 1.7 # body centre above the portal floor while perched + + @property + def aim_h(self): + return 0.0 # pos is already the body centre + + def hit_lo(self): + return self.e.pos - [1.25, 0.6, 1.25] + + def hit_hi(self): + return self.e.pos + [1.25, 0.6, 1.25] + + def head_center(self): + drop = -0.95 if self.phase in self.SITTING else 0.25 + return self.e.pos + self.e.fwd * 3.2 + [0.0, drop, 0.0] + + def hitboxes(self): + h = self.head_center() + return [("head", h - [0.55, 0.45, 0.55], h + [0.55, 0.45, 0.55]), + ("body", self.hit_lo(), self.hit_hi())] + + def in_reach(self, case): + return bool(np.linalg.norm(self.dist_to(case)) <= 3.4) + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 5.0, float(self.k.altitude), MID, math.pi, 2.6, self.height) + self.phase, self.state, self.timer, self.cd, self.iframes = "holding", "circle", 0.0, ticks(self.k.decide), 0 + self.flap, self.bank, self.tint_t, self.hurt_t = 0.0, 0.0, 0, 0 + self.phase_t, self.flames, self.sit_damage, self.orbit = 0, 0, 0.0, 1.0 + self.fireballs, self.clouds, self.goal = [], [], None + self.heal_from, self.last_hurt = None, 0.0 + self.crystals = self._place_crystals(case) + self.rig = dragon_rig() + + def _place_crystals(self, case): + """End crystals on the tallest tower tops (deterministic from the seeded layout; no RNG).""" + H, tops = case.arena.H, [] + for x in range(1, S - 1): + for z in range(1, S - 1): + h = int(H[x, z]) + if h >= 4 and h >= H[x - 1:x + 2, z - 1:z + 2].max(): + if all(abs(x - a) > 1 or abs(z - b) > 1 for a, b, _ in tops): + tops.append((x, z, h)) + tops.sort(key=lambda t: (-t[2], t[0], t[1])) + return [{"id": i, "pos": np.array([x + 0.5, h + 1.0, z + 0.5]), "alive": True} + for i, (x, z, h) in enumerate(tops[:int(round(self.k.crystals))])] + + @property + def crystals_alive(self): + return sum(c["alive"] for c in self.crystals) + + @property + def enraged(self): + return self.crystals_alive == 0 + + def _go(self, case, phase, timer=0.0): + self.phase, self.state, self.timer, self.phase_t = phase, self.COARSE[phase], timer, 0 + case.events.append(("dragon_phase", phase)) + + # -- damage -------------------------------------------------------------------------------------------- + def take_hit(self, case, dmg, kind="normal", bonus_knockback=0.0, part="body"): + if kind.startswith("arrow") and self.phase in self.SITTING: + case.events.append("arrow_deflected") + return 0.0 + if part != "head": + dmg = dmg / 4.0 + min(dmg, 1.0) + before = self.hp + amount = super().take_hit(case, dmg, kind if part == "head" else kind + "_body") + if amount > 0: + self.hurt_t = ticks(10) + if self.phase in self.SITTING: + self.sit_damage += before - self.hp + if self.sit_damage > 0.25 * self.max_hp: + self.sit_damage = 0.0 + self._go(case, "takeoff", 2.0) + return amount + + def crystal_destroyed(self, case, crystal): + crystal["alive"] = False + case.events.append(("crystal_destroyed", crystal["id"])) + p = case.body.e + r = float(np.linalg.norm(p.pos + [0, PLAYER_H / 2, 0] - crystal["pos"])) + impact = 1.0 - r / 12.0 + if impact > 0: + exposure = 1.0 if case.arena.los(crystal["pos"], p.pos + [0, 1.0, 0], eye_h=0.0) else 0.25 + dmg = self.k.crystal_blast * ((impact * impact + impact) / 2 * 84 + 1) / 85 * exposure + self.hurt_player(case, dmg, fling=0.5 * impact, origin=crystal["pos"]) + if self.heal_from is crystal: + self.heal_from = None + super().take_hit(case, 10.0, "crystal") + self.hurt_t = ticks(10) + if self.phase == "holding": + self._go(case, "strafe", 6.0) + + # -- flight ---------------------------------------------------------------------------------------------- + def _fly(self, case, goal, speed, rate): + e = self.e + to = goal - e.pos + want = math.atan2(to[2], to[0]) + d = (want - e.yaw + math.pi) % (2 * math.pi) - math.pi + turn = float(np.clip(d, -rate, rate)) + e.yaw = (e.yaw + turn) % (2 * math.pi) + self.bank = float(np.clip(-math.degrees(turn * FPS) * 45 / 400, -self.k.bank, self.k.bank)) + horiz = np.hypot(to[0], to[2]) + step = e.fwd * min(speed, horiz + 0.02) if horiz > 0.05 else np.zeros(3) + e.vel[1] = float(np.clip(to[1] * gain(0.12), per_vt(-0.45), per_vt(0.45))) + new = e.pos + step + if case.arena.ground(new, 2.2) > new[1] - 0.6 and self.phase not in ("landing",) + self.SITTING: + e.vel[1] = per_vt(0.45) # climb over a tower instead of flying through it + new = e.pos.copy() + e.pos[[0, 2]] = new[[0, 2]] + e.pos[1] = float(np.clip(e.pos[1] + e.vel[1], 1.0, 16.0)) + return float(np.linalg.norm(goal - e.pos)), abs(d) + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0) + self.hurt_t = max(self.hurt_t - 1, 0) + self.cd = max(self.cd - 1, 0) + self.timer -= 1 / FPS + self.phase_t += 1 + rate, speed = k.turn / FPS, per_vt(k.speed) + centre = np.array([MID, 0.0, MID]) + self._heal(case) + self._projectiles(case) + if self.phase == "holding": + radial = e.pos - centre + radial[1] = 0.0 + ang = math.atan2(radial[2], radial[0]) + 0.9 * self.orbit + goal = centre + [math.cos(ang) * 10.5, k.altitude, math.sin(ang) * 10.5] + self._fly(case, goal, speed, rate) + if self.cd == 0: + self.cd = ticks(k.decide) + # Java: nextInt(3 + crystals alive) == 0 lands; land_base is that 3 (BossBench easy perches sooner) + if case.rng.random() * (k.land_base + self.crystals_alive) < 1.0: + self._go(case, "landing", 8.0) + elif case.rng.random() < 0.5: + self._go(case, "strafe", 6.0) + elif self.phase == "strafe": + goal = p.pos + [0.0, 5.0, 0.0] + dist, err = self._fly(case, goal, speed, rate * 1.2) + flat = float(np.hypot(*(p.pos - e.pos)[[0, 2]])) + aim = math.atan2((p.pos - e.pos)[2], (p.pos - e.pos)[0]) + facing = abs((aim - e.yaw + math.pi) % (2 * math.pi) - math.pi) < math.radians(15) + mouth = e.pos + e.fwd * 3.6 + if facing and flat < 20.0 and case.arena.los(mouth, p.pos + [0, 1.0, 0], eye_h=0.0): + if self.goal is None: + self.goal = case.t + ticks(20 * k.windup) + case.events.append("dragon_lineup") + elif case.t >= self.goal: + if float(np.linalg.norm(p.pos + [0, 0.9, 0] - mouth)) >= k.fire_min: + self._fireball(case, mouth, p.pos + [0, 0.9, 0]) + self.goal = None + self._go(case, "holding") + self.orbit = -self.orbit + else: + # Java's dragon breaks off a strafe within 10 blocks of its target, so its fireballs come + # from across the island. The scaled arena would let it fire point-blank (a cloud nobody can + # outrun: found 2026-11-02), so a too-close shot is called off and the lineup starts over. + self.goal = None + case.events.append("dragon_hold_fire") + if self.phase == "strafe" and (self.timer <= 0 or flat < 3.0): + self.goal = None + self._go(case, "holding") + elif self.phase == "landing": + perch = centre + [0.0, self.PERCH_Y, 0.0] + flat = float(np.hypot(*(perch - e.pos)[[0, 2]])) + goal = perch + [0.0, min(6.0, flat * 0.5), 0.0] + self._fly(case, goal, speed * (0.6 if flat < 6 else 1.0), rate * 1.5) + if flat < 0.6 and e.pos[1] - perch[1] < 0.4 or self.timer <= 0: + e.pos[:] = perch + e.vel[:] = 0.0 + self.flames, self.sit_damage = 0, 0.0 + self._go(case, "scanning") + elif self.phase in self.SITTING: + to = p.pos - e.pos + want = math.atan2(to[2], to[0]) + d = (want - e.yaw + math.pi) % (2 * math.pi) - math.pi + e.yaw = (e.yaw + float(np.clip(d, -rate * 0.6, rate * 0.6))) % (2 * math.pi) + self.bank = 0.0 + near = float(np.hypot(*(p.pos - centre)[[0, 2]])) <= 20.0 + if self.phase == "scanning": + if near and self.phase_t >= ticks(25) and abs(d) < math.radians(20): + self._go(case, "roar") + case.events.append("dragon_roar") + elif self.phase_t >= ticks(100): + self.goal = p.pos.copy() + [0, 1.0, 0] + self._go(case, "charge", 4.0) + elif self.phase == "roar" and self.phase_t >= ticks(40): + self._go(case, "flaming") + c = self.head_center() + g = case.arena.ground(c, 0.6) + self.clouds.append({"pos": np.array([c[0], g, c[2]]) + self.e.fwd * 1.2, "r": 2.0, "dmg": k.breath_dmg, + "life": 3.0, "life0": 3.0, "kind": "breath", "next": {}}) + elif self.phase == "flaming" and self.phase_t >= ticks(60): + self.flames += 1 + if self.flames >= 4: + self._go(case, "takeoff", 2.5) + else: + self._go(case, "scanning") + elif self.phase == "takeoff": + out = e.pos - centre + out[1] = 0.0 + out = out / (np.linalg.norm(out) + 1e-6) if np.linalg.norm(out) > 0.5 else e.fwd + goal = centre + out * 10.0 + [0, k.altitude, 0] + self._fly(case, goal, speed * 0.7, rate) + if self.timer <= 0: + self.cd = ticks(k.decide) + self._go(case, "holding") + elif self.phase == "charge": + dist, _ = self._fly(case, self.goal, speed * 1.8, rate * 2.0) + if dist < 1.5 or self.timer <= 0: + self.goal = None + self.cd = ticks(k.decide) + self._go(case, "holding") + self._contact(case) + self.flap = (self.flap + (per_vt(0.35) + speed) * 0.55 * (0.2 if self.phase in self.SITTING else 1.0)) % 1.0 + self.pose(case) + + def _heal(self, case): + alive = [c for c in self.crystals if c["alive"]] + if self.heal_from is not None and not self.heal_from["alive"]: + self.heal_from = None + if self.heal_from is None and alive and case.rng.random() < 1 - 0.9 ** VT: + self.heal_from = min(alive, key=lambda c: float(np.linalg.norm(c["pos"] - self.e.pos))) + if self.heal_from is not None and case.t % ticks(10) == 0 and self.hp < self.max_hp: + self.hp = min(self.max_hp, self.hp + 1.0) + + def _contact(self, case): + """Java aiStep: head/neck hurt and wing shove, only while hurtTime == 0.""" + if self.hurt_t > 0: + return + p = case.body.e + lo, hi = p.pos - [0.3, 0.0, 0.3], p.pos + [0.3, PLAYER_H, 0.3] + h = self.head_center() + if np.all(hi >= h - 1.55) and np.all(lo <= h + 1.55): + if self.hurt_player(case, self.k.ram_dmg, fling=0.6, origin=h): + case.events.append("dragon_ram") + return + if self.phase in self.SITTING: + return + b = self.e.pos + flat = float(np.hypot(*(p.pos - b)[[0, 2]])) + if flat < 3.2 and -2.5 < p.pos[1] + 0.9 - b[1] < 1.0: + if self.hurt_player(case, self.k.wing_dmg, fling=1.0, origin=b): + p.vel[1] = vy_sim(0.2 + 0.2) + p.on_ground = False + case.events.append("dragon_wing") + + # -- fireballs and clouds -------------------------------------------------------------------------------- + def _fireball(self, case, start, target): + direction = np.asarray(target, float) - start + direction /= float(np.linalg.norm(direction)) + 1e-9 + self.fireballs.append({"pos": start.copy(), "vel": direction * per_vt(0.1), "dir": direction, "life": 8.0}) + case.events.append("dragon_fireball") + + def _projectiles(self, case): + p, keep = case.body.e, [] + lo, hi = p.pos - [0.45, 0.15, 0.45], p.pos + [0.45, PLAYER_H + 0.15, 0.45] + F = decay(0.95) + for f in self.fireballs: + f["vel"] = f["vel"] * F + f["dir"] * per_vt(1.9) * (1 - F) + start, end = f["pos"], f["pos"] + f["vel"] + f["life"] -= 1 / FPS + hp_ = _segment_box(start, end, lo, hi) + hw, _ = case._arrow_world_hit(start, end) + if hp_ is not None or hw is not None or f["life"] <= 0: + u = min(x for x in (hp_, hw, 1.0) if x is not None) + at = start + (end - start) * u + g = case.arena.ground(at, 0.2) + self.clouds.append({"pos": np.array([at[0], g, at[2]]), "r": 3.0, "dmg": self.k.cloud_dmg, + "life": self.k.cloud_s, "life0": self.k.cloud_s, "kind": "fireball", "next": {}}) + case.events.append("dragon_cloud") + continue + f["pos"] = end + keep.append(f) + self.fireballs = keep + alive = [] + for c in self.clouds: + c["life"] -= 1 / FPS + if c["kind"] == "fireball": + c["r"] = 3.0 + 1.0 * (1 - c["life"] / c["life0"]) + if c["life"] <= 0: + continue + inside = float(np.hypot(*(p.pos - c["pos"])[[0, 2]])) <= c["r"] and -0.5 < p.pos[1] - c["pos"][1] < 1.5 + if inside and case.t >= c["next"].get("p", 0): + c["next"]["p"] = case.t + ticks(20) + if self.hurt_player(case, c["dmg"], armor=False): + case.events.append("dragon_breath") + alive.append(c) + self.clouds = alive + + def extra(self, case): + return [] + + def pose(self, case): + mcskin.pose_dragon(self, case) + + def fx(self, case): + return [] # breath and ender particles: mcskin.fx_ambient + + +class Wither(Mob): + """Java Edition 1.21 wither (minecraft.wiki/w/Wither, read 2026-11-01). + + spawn 220 vanilla ticks of invulnerable charging (health bar fills), then a power-7 blast at its body + hover above half health: keeps its feet 5 blocks over the target and flies to within 3 blocks + horizontally; the main head fires a wither skull every 40 vanilla ticks with line of sight, each + side head 40-59 ticks after its last shot; an idle side head (counter > 15, +3 per hit taken, + Normal/Hard) lobs a slow blue skull at a random spot + armored at or below half health: wither armor makes it immune to arrows and it comes down to the + target's height (melee range); the armor goes away if it regenerates above half + nolos no line of sight from the main head: it stops firing and closes in + Regenerates 1 HP every 20 vanilla ticks; a damaged wither breaks the blocks of a 3x4x3 box around itself + 20 ticks later (the arena wall is immune). There is no dash in Java (the dash is Bedrock-only). + Black skulls accelerate 0.1 b/t^2 with inertia 0.95 (terminal 1.9 b/t), blue skulls inertia 0.73 + (terminal 0.27 b/t). A hit deals skull_dmg (armor applies) and Wither II; the power-1 explosion + deals up to blast_dmg within 2 blocks. + """ + TABLE = { + "hp": (100, 250, 600), # TIER calibration for ~25 s / 1 min / 3 min (Java: 300 on every difficulty) + "regen": (0.5, 1.0, 1.0), # HP per 20 vanilla ticks (Java 1) + "altitude": (4.0, 5.0, 5.0), # phase 1: feet above the target's feet (Java 5) + "speed": (0.30, 0.43, 0.43), # vanilla b/t approach when > 3 blocks away (Java ~0.43 steady) + "skull_dmg": (5.0, 8.0, 12.0), # Java Easy / Normal / Hard + "blast_dmg": (3.5, 5.0, 7.5), # power-1 skull explosion at its centre (scaled with the skull) + "wither_s": (0.0, 10.0, 40.0), # Wither II seconds (Java Easy none, Normal 10, Hard 40) + "cd_main": (60, 40, 40), # vanilla ticks between main-head skulls (Java 40; easy slower) + "cd_side": (100, 40, 40), # side head pause after a shot, + 0-19 (Java 40-59; easy slower) + "blue_idle": (1e9, 15, 15), # side-head idle counter limit for blue skulls (Normal/Hard only) + "spawn_blast": (35.5, 69.0, 103.5), # power-7 spawn explosion peak damage (Java easy / normal / hard) + } + MOVES = {"shell": {"atoms": ["projectile_linear", "explosion_small", "dot_drain"], + "telegraph": "a head turns to the player; black shells fly fast, blue shells slowly", + "damage": "shell damage (armor) + black-heart drain; explosion up to blast damage within 2 blocks", + "range": "main head 40 ticks, side heads 40-59 ticks, line of sight needed", + "punish": "break line of sight with cover; it stops firing"}, + "spawn": {"atoms": ["charge_invulnerable", "explosion_large"], + "telegraph": "11 s of flickering blue while its health bar fills", + "damage": "spawn_blast at the centre, falling to 0 at 14 blocks (armor applies)", + "range": "power 7 (14 blocks)", "punish": "run far away before the blast"}, + "armor": {"atoms": ["phase_shield"], "telegraph": "a translucent armor shell at half health", + "damage": "-", "range": "arrows bounce off; it descends to melee height", + "punish": "switch to the sword (hotbar) and fight it on the ground"}} + SKILLS = ("projectile_dodge", "cover_use", "weapon_switch", "aim_tracking", "spacing", "reaction") + STATES = ("spawn", "hover", "armored", "nolos") + name = "wither" + height, reach, reach_up, aim_h = 3.5, 3.0, 3.0, 0.0 + half = (0.45, 0.45) + hover = True + knockback = 0.0 + armor = 4.0 + FEET = 1.5 # pos is the chest: hitbox [pos - 1.5, pos + 2.0], 0.9 wide + SPAWN_TICKS = 220 # vanilla ticks + + def reset(self, case): + super().reset(case) + self.max_hp = float(self.k.hp) + self.hp = self.max_hp / 3 # Java: the bar fills during the spawn charge + p = case.body.e + self.e = Entity(MID + 4.0, self.FEET + 0.0, MID, math.pi, 0.9, self.height) + self.state, self.timer, self.cd, self.iframes = "spawn", self.SPAWN_TICKS / 20, ticks(self.k.cd_main), 0 + self.side_next, self.idle = [ticks(20), ticks(30)], [0, 0] + self.skulls, self.tint_t, self.tilt, self.guard = [], 0, 0.0, 0.0 + self.blocks_t, self.shots, self.blue_shots, self.last_hurt = -1, 0, 0, 0.0 + self.armored = False + self.rig = wither_rig() + + @property + def enraged(self): + return self.armored + + def hit_lo(self): + return self.e.pos - [self.half[0], self.FEET, self.half[1]] + + def hit_hi(self): + return self.e.pos + [self.half[0], self.height - self.FEET, self.half[1]] + + def in_reach(self, case): + return bool(np.linalg.norm(self.dist_to(case)) <= 3.6) + + def immune(self, case, kind): + if self.state == "spawn": + return True + return self.armored and kind.startswith("arrow") + + def on_hurt(self, case, amount, kind): + self.idle = [i + 3 for i in self.idle] + if self.blocks_t < 0: + self.blocks_t = ticks(20) + + def head_pos(self, i): + side = (0.0, -0.85, 0.85)[i] + return self.e.pos + [0.0, 1.05 - (0.1 if i else 0.0), 0.0] + self.e.right * side + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0) + self.cd = max(self.cd - 1, 0) + self.timer = max(self.timer - 1 / FPS, 0.0) + self._skulls(case) + flat = np.array([p.pos[0] - e.pos[0], 0.0, p.pos[2] - e.pos[2]]) + dist = float(np.linalg.norm(flat)) + e.yaw = math.atan2(flat[2], flat[0]) + if self.state == "spawn": + self.hp = min(self.max_hp, self.hp + self.max_hp * 2 / 3 / ticks(self.SPAWN_TICKS)) + e.vel[:] = 0.0 + if self.timer <= 0: + self.hp = self.max_hp + self._explode(case, e.pos, 7.0, k.spawn_blast, fling=1.2, name="wither_spawn_blast") + self.state = "hover" + self.pose(case) + return + if case.t % ticks(20) == 0 and self.hp < self.max_hp: + self.hp = min(self.max_hp, self.hp + k.regen) + if self.blocks_t >= 0: + self.blocks_t -= 1 + if self.blocks_t < 0: + self._break_blocks(case) + self.armored = self.hp <= self.max_hp / 2 + main = self.head_pos(0) + target = p.pos + [0, PLAYER_H * 0.45, 0] + sees = case.arena.los(main, target, eye_h=0.0) + self.state = "armored" if self.armored else "hover" + if not sees: + self.state = "nolos" + # -- movement: Java WitherBoss.aiStep, per vanilla tick converted to the simulation tick ---------- + feet, goal = e.pos[1] - self.FEET, p.pos[1] + (0.0 if self.armored else k.altitude) + if feet < goal: + e.vel[1] = max(e.vel[1], 0.0) + e.vel[1] += (per_vt(0.3) - e.vel[1]) * gain(0.6) + elif self.armored and feet > goal + 0.25: + e.vel[1] += (per_vt(-0.15) - e.vel[1]) * gain(0.4) + else: + e.vel[1] *= decay(0.546) + if dist > 3.0 or (not sees and dist > 1.0): + e.vel[[0, 2]] += (flat[[0, 2]] / (dist + 1e-6) * per_vt(k.speed) - e.vel[[0, 2]]) * gain(0.636) + else: + e.vel[[0, 2]] *= decay(0.91) + new = e.pos + e.vel + if case.arena.ground(new, e.w) <= new[1] - self.FEET + 0.05: + e.pos[[0, 2]] = new[[0, 2]] + else: # flying pathing: rise over the column instead of stalling at it + e.vel[[0, 2]] *= decay(0.5) + e.vel[1] = max(e.vel[1], per_vt(0.3)) + new[1] = e.pos[1] + e.vel[1] + floor = case.arena.ground(e.pos, e.w) + self.FEET + e.pos[1] = float(np.clip(new[1], floor, 16.0)) + # -- heads ------------------------------------------------------------------------------------------- + if sees and self.cd == 0 and float(np.linalg.norm(target - main)) <= 20.0: + self._fire(case, 0, target, blue=bool(case.rng.random() < 0.001)) + self.cd = ticks(k.cd_main) + for i in (0, 1): + if case.t < self.side_next[i]: + continue + self.side_next[i] = case.t + ticks(10 + int(case.rng.integers(0, 10))) + if k.blue_idle < 1e8: + count, self.idle[i] = self.idle[i], self.idle[i] + 1 + if count > k.blue_idle: + spot = np.array([e.pos[0] + case.rng.normal(0, 6.0), 0.0, e.pos[2] + case.rng.normal(0, 6.0)]) + self._fire(case, i + 1, spot, blue=True) + self.idle[i] = 0 + head = self.head_pos(i + 1) + if case.arena.los(head, target, eye_h=0.0) and float(np.linalg.norm(target - head)) <= 30.0: + self._fire(case, i + 1, target) + self.side_next[i] = case.t + ticks(k.cd_side + int(case.rng.integers(0, 20))) + self.idle[i] = 0 + self.pose(case) + + # -- projectiles and explosions --------------------------------------------------------------------- + def _fire(self, case, head, target, blue=False): + start = self.head_pos(head) + aim = np.asarray(target, float) - start + direction = aim / (float(np.linalg.norm(aim)) + 1e-9) + self.shots += 1 + self.skulls.append({"pos": start + direction * 0.4, "vel": direction * per_vt(0.1), "dir": direction, + "blue": bool(blue), "life": 12.0, "head": int(head), "n": self.shots}) + self.blue_shots += int(blue) + case.events.append(("wither_fire", int(head), "blue" if blue else "black")) + + def _explode(self, case, at, power, peak, fling=0.0, name="explosion"): + """Java explosion falloff (impact = 1 - r / 2 power) scaled so the centre deals `peak`; armor applies.""" + p = case.body.e + r = float(np.linalg.norm(p.pos + [0, PLAYER_H / 2, 0] - at)) + impact = 1.0 - r / (2.0 * power) + case.events.append((name, round(r, 2), [round(float(v), 2) for v in at])) + if impact <= 0: + return False + dmg = peak * ((impact * impact + impact) / 2 * 7 * 2 * power + 1) / (7 * 2 * power + 1) + return self.hurt_player(case, dmg, fling=fling * impact, origin=at) + + def _skulls(self, case): + p, keep = case.body.e, [] + lo, hi = p.pos - [PLAYER_W / 2 + 0.16, 0.16, PLAYER_W / 2 + 0.16], p.pos + [PLAYER_W / 2 + 0.16, PLAYER_H + 0.16, PLAYER_W / 2 + 0.16] + for s in self.skulls: + inertia = 0.73 if s["blue"] else 0.95 + F = decay(inertia) + s["vel"] = s["vel"] * F + s["dir"] * per_vt(0.1 * inertia / (1 - inertia)) * (1 - F) + start, end = s["pos"], s["pos"] + s["vel"] + s["life"] -= 1 / FPS + hit_player = _segment_box(start, end, lo, hi) + hit_world, reason = case._arrow_world_hit(start, end) + if hit_player is not None and (hit_world is None or hit_player <= hit_world): + at = start + (end - start) * hit_player + if self.hurt_player(case, self.k.skull_dmg, fling=0.3, origin=at): + if self.k.wither_s > 0: + case.body.wither_t = max(case.body.wither_t, ticks(20 * self.k.wither_s)) + case.events.append("skull_hit") + self._explode(case, at, 1.0, self.k.blast_dmg, name="skull_blast") + continue + if hit_world is not None: + at = start + (end - start) * hit_world + case.events.append(("skull_ground", reason)) + self._explode(case, at, 1.0, self.k.blast_dmg, name="skull_blast") + continue + s["pos"] = end + if s["life"] <= 0 or end[1] > 30: + continue + keep.append(s) + self.skulls = keep + + def _break_blocks(self, case): + """Java: 20 ticks after damage, blocks in x/z +-1, y floor(feet)..+3 around the wither break (not the wall).""" + H, e = case.arena.H, self.e + base = int(math.floor(e.pos[1] - self.FEET)) + broke = 0 + for x in range(int(e.pos[0]) - 1, int(e.pos[0]) + 2): + for z in range(int(e.pos[2]) - 1, int(e.pos[2]) + 2): + if not (1 <= x < S - 1 and 1 <= z < S - 1): + continue # the arena wall is wither-immune (bedrock-like) + if base < H[x, z] <= base + 4: + H[x, z] = max(base, 0) + broke += 1 + if broke: + case.events.append(("wither_break", broke)) + + def extra(self, case): + return [{"pos": s["pos"], "size": (0.32, 0.32, 0.32), "color": (0.2, 0.18, 0.22), "blue": s["blue"]} + for s in self.skulls] + + def fx(self, case): + return [] # skull smoke and aura: mcskin.fx_ambient + + def pose(self, case): + mcskin.pose_wither(self, case) + + +class Warden(Mob): + """Java Edition 1.21 warden (minecraft.wiki/w/Warden, read 2026-11-02), as a fight in the deep dark. + + emerge it climbs out of the floor (Java ~6.7 s; arena 3 s), invulnerable except to /kill + roar 4.2 s roar before the chase (Java: when anger reaches 80; skipped when attacked from within 5 blocks) + chase melee: Java 16 / 30 / 45 per hit (armor applies), 36-tick cooldown, disables a raised shield; a warden + is never knocked back. It walks at a player's pace, so out-walking it is not an option, but it + pivots slowly after a missed swing (the 'opening'). + boom sonic boom when it cannot reach its target (Java: a pillar perch or across a gap): 1.7 s charge, then a + hit that ignores armor, shields and walls (Java 6 / 10 / 15) with knockback; 1.3 s recovery; in Java it + needs 5 s since its last attack. Range 15 horizontal / 20 vertical. + darkness every 6 s, 13 s of Darkness within 20 blocks (Java; visual only here: the screen dims in pulses) + Java's anger and sniffing decide *who* it hunts; a one-on-one arena gives it the player from the start. + + BossBench deviations (minecraft-arena@5): health per tier (Java 500 on every difficulty); the sonic boom also fires + when the player has merely stayed out of melee reach for boom_every seconds (Java: when the target is unreachable, + 5 s after its last attack), so kiting in the open is answered as Java answers a pillar perch. The tiers span Java + Easy to Java *Normal* damage: Java Hard's 45-damage smash leaves 29 after unenchanted diamond armor, more than a + full 20-HP bar, so a three-minute hard tier would be a single-mistake test (Java players fight wardens in enchanted + netherite, which this arena does not model). Hard keeps every other Java Hard trait: 36-tick cooldown, 4.2 s roar. + """ + TABLE = { # (easy, normal, hard) = TIERS + "hp": (260, 820, 2100), # TIER calibration (Java 500 on every difficulty) + "speed": (0.22, 0.26, 0.286), # vanilla b/t chase; Java 0.286 = attribute 0.3 x 1.2 (SPEED_NOTE), + # a sprinting player's pace (walk 0.216, sprint 0.281) + "dmg": (16.0, 23.0, 30.0), # melee before armor: Java Easy 16, midway, Java Normal 30 (see below) + "cooldown": (44, 40, 36), # vanilla ticks between swings (Java 36) + "windup": (0.80, 0.65, 0.55), # EXT raised-arms telegraph: long enough to back out of its attack box + # from contact range (it out-walks a backpedalling player) + "boom_dmg": (6.0, 8.0, 10.0), # sonic boom, ignores armor: Java Easy 6, midway, Java Normal 10 + "boom_every": (9.0, 7.0, 5.0), # seconds out of reach before a boom (Java: 5 s since the last attack) + "emerge_s": (3.0, 3.0, 3.0), # APPROX (Java ~6.7 s) + "roar_s": (2.0, 3.0, 4.2), # EXT on easy / normal (Java 4.2 s) + } + MOVES = {"smash": {"atoms": ["melee_single"], "telegraph": "arms raised, chest glowing", + "damage": "16 / 23 / 30 then armor (Java 16 / 30 / 45)", "range": "attack box 0.83 around its body", + "punish": "36-44 tick cooldown; it keeps walking, so back off between swings"}, + "shockwave": {"atoms": ["ranged_hitscan"], "telegraph": "1.7 s charge: chest lights, rings gather", + "damage": "6 / 8 / 10 (Java 6 / 10 / 15), ignores armor and walls, knocks back", + "range": "15 blocks horizontally, 20 vertically", + "punish": "1.3 s recovery after the boom; the timer only runs while you stay out of reach"}, + "vision_dim": {"atoms": ["vision_dot"], "telegraph": "a heartbeat pulse", "damage": "-", + "range": "20 blocks", "punish": "-"}} + SKILLS = ("spacing", "attack_timing", "reaction", "resource_management", "terrain_use") + STATES = ("emerge", "chase", "windup", "boom") + name = "warden" + height, aim_h = 2.9, 1.45 + half = (0.45, 0.45) + knockback = 0.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 6.0, 0.0, MID, math.pi, 0.9, self.height) + self.state, self.timer, self.cd, self.iframes = "emerge", float(self.k.emerge_s), 0, 0 + self.phase = "emerge" + self.ph, self.tint_t = 0.0, 0 + self.out_of_reach = 0 # sim ticks the player has spent out of melee reach + self.boom_cd = 0 + self.dark_t = 0 + self.booms = 0 + self.rig = warden_rig() + + @property + def enraged(self): + return False + + def in_reach(self, case): + """Java 1.20.2+ attack box, plus the warden's vertical reach of 2 blocks (22w16a lowered it from 3): a player + standing more than 2 blocks above its feet is out of reach even while it jumps against the block below - the + perch its sonic boom exists for. APPROX: measured feet to feet.""" + if case.body.e.pos[1] - self.e.pos[1] > 2.0: + return False + return super().in_reach(case) + + def immune(self, case, kind): + return self.phase == "emerge" # Java: only /kill hurts an emerging warden + + def on_hurt(self, case, amount, kind): + if self.phase == "roar" and float(np.linalg.norm(case.body.e.pos - self.e.pos)) <= 5.0: + self._go(case, "chase") # Java: attacked from within 5 blocks, it skips the roar + + def _go(self, case, phase, timer=0.0): + self.phase, self.timer = phase, timer + self.state = {"emerge": "emerge", "roar": "emerge", "chase": "chase", "windup": "windup", + "smash": "windup", "recover": "chase", "boom": "boom", "boom_recover": "boom"}[phase] + case.events.append(("warden_phase", phase)) + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.boom_cd = max(self.boom_cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + if case.t % ticks(120) == 0: # Java: Darkness to players within 20 blocks every 6 s + if float(np.linalg.norm(p.pos - e.pos)) <= 20.0: + self.dark_t = ticks(260) + case.events.append("warden_darkness") + self.dark_t = max(self.dark_t - 1, 0) + to = p.pos - e.pos + flat = float(math.hypot(to[0], to[2])) + wish, speed = np.zeros(3), 0.0 + reach = self.in_reach(case) + if self.phase == "emerge": + if self.timer <= 0: + self._go(case, "roar", float(k.roar_s)) + case.events.append("warden_roar") + elif self.phase == "roar": + e.yaw = math.atan2(to[2], to[0]) + if self.timer <= 0: + self._go(case, "chase") + elif self.phase in ("chase", "recover"): + wish = self.steer(case) + e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw + speed = k.speed * (0.45 if self.phase == "recover" else 1.0) + self.out_of_reach = 0 if reach else self.out_of_reach + 1 + if self.phase == "recover" and self.timer <= 0: + self.phase = "chase" + if self.cd == 0 and reach: + self._go(case, "windup", max(0.05, float(k.windup))) + case.events.append("warden_windup") + elif (self.boom_cd == 0 and self.out_of_reach >= ticks(20 * k.boom_every) + and flat <= 15.0 and abs(to[1]) <= 20.0): + self._go(case, "boom", 1.7) + case.events.append("warden_boom_charge") + elif self.phase == "windup": + e.yaw = math.atan2(to[2], to[0]) + speed = k.speed * 0.2 + wish = e.fwd + if self.timer <= 0: + if self.in_reach(case): + if self.hurt_player(case, k.dmg, fling=0.5): + case.events.append("warden_smash") + else: + case.events.append("warden_whiff") + self.cd = ticks(k.cooldown) + self.out_of_reach = 0 + self._go(case, "recover", 0.6) # turns slowly after a swing: the opening + elif self.phase == "boom": + e.yaw = math.atan2(to[2], to[0]) + if self.timer <= 0: + self.booms += 1 + if flat <= 15.0 and abs(to[1]) <= 20.0: + # Java: lands at once if the target is still in range; ignores armor, shields and walls + if self.hurt_player(case, k.boom_dmg, fling=1.2, armor=False, lift=0.1): + case.events.append("warden_boom_hit") + else: + case.events.append("warden_boom_miss") + self.out_of_reach, self.boom_cd = 0, ticks(20 * 5) + self._go(case, "boom_recover", 1.3) + elif self.phase == "boom_recover": + if self.timer <= 0: + self._go(case, "chase") + if flat < 0.6: + wish = 0 * wish + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP + self.ph = (self.ph + float(math.hypot(e.vel[0], e.vel[2])) * 0.7) % 1.0 + self.pose(case) + + def pose(self, case): + mcskin.pose_warden(self, case) + + +class Skeleton(Mob): + """Java Edition 1.21 skeleton (minecraft.wiki/w/Skeleton, read 2026-11-02) as a boss: an armoured archer in ruins. + + It keeps its distance and circles: it backs off when the player comes within 4 blocks, strafes around at mid range + (switching direction now and then) and closes in when the player is 14+ blocks away. With line of sight within + 15 blocks it draws (visible: bow up, string back) and fires; Java fires every 3 s on Easy / Normal and every 2 s on + Hard, aims 0.2 blocks higher per block of range and has an arrow 'error' of 10 / 6 / 2 (the player's is 1). + Arrows are real projectiles (gravity, drag, stopped by terrain): side-stepping and cover work. Java arrow damage + 2-4 / 3-5 / 4-8. It has no melee while it holds its bow. + + BossBench deviations (minecraft-arena@5): health per tier (Java 20); it wears armor (iron on easy / normal pieces, + Java's armor-spawn chances made certain) so that the fight lasts; its draw time is a telegraph knob. + """ + TABLE = { # (easy, normal, hard) = TIERS + "hp": (200, 500, 1050), # TIER calibration (Java 20) + "speed": (0.12, 0.138, 0.16), # vanilla b/t; Java 0.138 = attribute 0.25 (SPEED_NOTE); strafes at half + "interval": (60, 60, 40), # vanilla ticks between shots (Java 3 s / 3 s / 2 s) + "draw": (1.0, 0.85, 0.7), # EXT seconds of visible draw before the release + "error": (10.0, 6.0, 2.0), # Java arrow inaccuracy (player 1) + "arrow_min": (2.0, 3.0, 4.0), # Java arrow damage range per difficulty + "arrow_max": (4.0, 5.0, 8.0), + "armor": (8.0, 12.0, 15.0), # worn iron pieces (Java armor-spawn chance made certain): helmet + + # chestplate / + leggings / full set + } + MOVES = {"arrow": {"atoms": ["projectile_arc"], "telegraph": "bow raised and drawn back for most of a second", + "damage": "Java 2-4 / 3-5 / 4-8 then armor", "range": "up to 15 blocks with line of sight", + "punish": "3 s (2 s on hard) between shots; arrows fly in an arc and stop on walls"}, + "kite": {"atoms": ["retreat", "strafe"], "telegraph": "-", "damage": "-", + "range": "backs off inside 4 blocks, closes in beyond 14", + "punish": "corner it against the ruins or the arena wall"}} + SKILLS = ("projectile_dodge", "cover_use", "aim_tracking", "chase", "weapon_switch") + STATES = ("chase", "windup", "swing", "recover") + name = "skeleton" + height, aim_h = 1.99, 1.0 + half = (0.3, 0.3) + knockback = 1.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.armor = float(self.k.armor) + self.e = Entity(MID + 8.0, 0.0, MID, math.pi, 0.6, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, ticks(40), 0 + self.ph, self.tint_t = 0.0, 0 + self.strafe_dir, self.strafe_t = 1.0, 0 + self.draw_t, self.shots, self.arrows = 0.0, 0, [] + self.rig = skeleton_rig() + + @property + def enraged(self): + return False + + def sees(self, case): + eye = self.e.pos + [0, 1.74, 0] + return case.arena.los(eye, case.body.e.pos + [0, 1.2, 0], eye_h=0.0) + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + self._arrows(case) + to = p.pos - e.pos + flat = float(math.hypot(to[0], to[2])) + e.yaw = math.atan2(to[2], to[0]) + sees = self.sees(case) + # -- movement (Java RangedBowAttackGoal: approach beyond range, back off inside 4 blocks, strafe otherwise) -- + self.strafe_t -= 1 + if self.strafe_t <= 0: + self.strafe_t = ticks(20 + int(case.rng.integers(0, 40))) + if case.rng.random() < 0.3: + self.strafe_dir = -self.strafe_dir + if not sees or flat >= 14.0: + wish, speed = self.steer(case), k.speed + elif flat < 4.0: + wish = -e.fwd + e.right * self.strafe_dir * 0.5 + speed = k.speed + else: + wish, speed = e.right * self.strafe_dir, k.speed * 0.5 + n = float(math.hypot(wish[0], wish[2])) + wish = wish / n if n > 1e-9 else wish + # -- bow -- + if self.state == "chase": + if self.cd == 0 and sees and flat <= 15.0: + self.state, self.timer = "windup", float(k.draw) + case.events.append("skeleton_draw") + elif self.state == "windup": + speed *= 0.5 + if not sees or flat > 16.0: # lost sight: keeps the bow drawn, fires when it sees again (Java) + self.timer = max(self.timer, 1 / FPS) + elif self.timer <= 0: + self._shoot(case) + self.state, self.timer = "swing", 0.15 + elif self.state == "swing": + if self.timer <= 0: + self.state, self.cd = "recover", ticks(k.interval - 20 * k.draw) + elif self.state == "recover" and self.cd == 0: + self.state = "chase" + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP + self.strafe_dir = -self.strafe_dir # cornered against cover: strafe the other way + self.ph = (self.ph + float(math.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0 + self.pose(case) + + def _shoot(self, case): + """Java AbstractSkeleton.performRangedAttack: aims at a third of the target's height, 0.2 blocks higher per block + of horizontal range, speed 1.6 b/t, inaccuracy 14 - 4 x difficulty (10 / 6 / 2): each axis of the unit + direction gets a triangular deviation of 0.0172275 x inaccuracy (Projectile.getMovementToShoot).""" + k, e, p = self.k, self.e, case.body.e + start = e.pos + [0, 1.6, 0] + e.fwd * 0.4 + target = p.pos + [0, PLAYER_H / 3, 0] + d = target - start + horiz = float(math.hypot(d[0], d[2])) + d[1] += horiz * 0.2 + n = float(np.linalg.norm(d)) + 1e-9 + spread = 0.0172275 * k.error + direction = d / n + (case.rng.random(3) - case.rng.random(3)) * spread + direction /= float(np.linalg.norm(direction)) + 1e-9 + self.shots += 1 + self.arrows.append({"id": self.shots, "pos": start, "vel": direction * per_vt(1.6), "age": 0, + "damage": float(case.rng.uniform(k.arrow_min, k.arrow_max))}) + case.events.append(("skeleton_shot", self.shots)) + + def _arrows(self, case): + p, keep = case.body.e, [] + lo, hi = p.pos - [PLAYER_W / 2, 0.0, PLAYER_W / 2], p.pos + [PLAYER_W / 2, PLAYER_H, PLAYER_W / 2] + for a in self.arrows: + start, end = a["pos"], a["pos"] + a["vel"] + hit_p = _segment_box(start, end, lo, hi) + hit_w, _ = case._arrow_world_hit(start, end) + if hit_p is not None and (hit_w is None or hit_p <= hit_w): + if self.hurt_player(case, a["damage"], fling=0.3, origin=start): + case.events.append("skeleton_arrow_hit") + continue + if hit_w is not None or a["age"] > FPS * 6: + case.events.append("skeleton_arrow_blocked") + continue + a["pos"] = end + a["vel"] = a["vel"] * decay(0.99) + a["vel"][1] -= 0.05 * VT * VT + a["age"] += 1 + keep.append(a) + self.arrows = keep + + def pose(self, case): + mcskin.pose_skeleton(self, case) + + def extra(self, case): + return [] # arrows are drawn by mcskin.arrow_rows (same look as the player's) + + +# ---------------------------------------------------------------- rigs +golem_rig, zombie_rig = mcskin.golem_rig, mcskin.zombie_rig +dragon_rig, wither_rig = mcskin.dragon_rig, mcskin.wither_rig +warden_rig, skeleton_rig = mcskin.warden_rig, mcskin.skeleton_rig + + +# ---------------------------------------------------------------- case +MOBS = {"iron_golem": IronGolem, "zombie": Zombie, "ender_dragon": EnderDragon, "wither": Wither, + "warden": Warden, "skeleton": Skeleton, "zombie_leader": ZombieLeader} + + +class MobFight(Case): + """Arena + player + one mob. One class serves every boss; `mob` picks the boss.""" + R = 3 + obs_dim = 12 + 14 + (2 * R + 1) ** 2 + # per-boss observation extras: wither 3 nearest skulls x 7, skeleton 3 nearest arrows x 7, leader zombie 3 nearest + # reinforcements x 4, warden boom charge / time out of reach / darkness (the last three since minecraft-arena@5; + # the formal zombie case has none, as in @4) + EXTRA_OBS = {"wither": 21, "skeleton": 21, "zombie_leader": 12, "warden": 3} + + # The camera changes only the image. Third-person is available through the reset options. + def __init__(self, mob="iron_golem", style="field", width=RES[0], height=RES[1], camera="first", + max_seconds=120.0, weapon='sword'): + self.default_weapon, self.default_camera = _weapon(weapon), _camera(camera) + self.mob_name = mob + self.max_seconds = max_seconds + self.obs_dim = MobFight.obs_dim + self.EXTRA_OBS.get(mob, 0) + super().__init__(VoxelArena(style), Steve(weapon), MOBS[mob]()) + self.name = f"minecraft_{mob}_1v1" + self.size, self.camera, self._gl = (width, height), camera, None + self.render_error = None + + def reset(self, seed, d, options=None): + options = dict(options or {}) + weapon = _weapon(options.get('weapon', self.default_weapon)) + camera = _camera(options.get('camera', self.default_camera)) + self.body.weapon, self.camera = weapon, camera + self.render_error = None + self.arrows = [] + super().reset(seed, d) + self.fxrng = np.random.default_rng((int(seed) * 2654435761 + 0x9E3779B9) % (2 ** 32)) + self.fx = [] + if self.body.weapon == 'bow': + self.body.pose(self) # establish visible bow pose before frame zero + + def hurt_player(self, dmg, armor=True, iframes=True, share=1.0): + """Java LivingEntity.hurt for the player. A hit starts 10 vanilla ticks of immunity; inside the window + only a stronger raw hit lands, dealing the difference (no knockback, no new window). Returns "fresh", + "partial" or False. share < 1: this tick's part of a per-vanilla-tick damage (armor sees the whole hit); + iframes=False: damage that neither starts nor respects the window (fall, Wither effect, breath).""" + b = self.body + landed = "fresh" + if iframes: + if b.iframes > 0: + if dmg <= b.last_hurt: + return False + dmg, b.last_hurt, landed = dmg - b.last_hurt, dmg, "partial" + else: + b.last_hurt, b.iframes = dmg, ticks(10) + if armor: + dmg = armor_reduce(dmg, b.k.armor, b.k.toughness) + dmg *= share + b.hp -= dmg + self.events.append(("player_hit", round(float(dmg), 2))) + return landed + + + def interact(self): + p = self.body.e + if self.boss.hover: + return + # bodies push the player out (the boss, and since minecraft-arena@5 any living reinforcement); a zombie horde + # can pin a player against cover this way + for mob in [self.boss] + [z for z in getattr(self.boss, "minions", ()) if z.hp > 0]: + g = mob.e + d = p.pos[[0, 2]] - g.pos[[0, 2]] + dist, need = float(np.linalg.norm(d)), (PLAYER_W + 2 * mob.half[0]) / 2 + if dist < need and abs(p.pos[1] - g.pos[1]) < mob.height: + push = d / (dist + 1e-6) * (need - dist) + new = p.pos.copy() + new[[0, 2]] += push + if self.arena.ground(new, PLAYER_W) <= p.pos[1] + 0.6: + p.pos = new + + def track(self): + """Advance visual-only state after the rules ran: pose the player, step particles. Draws + from case.fxrng only, never touches gameplay state.""" + self.body.pose(self) + mcskin.step_fx(self) + + def tick(self, action): + self._ev0 = len(self.events) # first event of this tick (fx juice reads only new ones) + self.body.apply(self, action) + self.boss.update(self) + if self.arrows: + self._update_arrows() + self.arena.update(self) + self.interact() + self.track() + self.t += 1 + + def _arrow_world_hit(self, start, end): + """Swept collision against actual voxel columns and the arena floor.""" + radius = BOW_RULES['arrow_radius_blocks'] + first, reason = None, None + for axis in (0, 2): + if start[axis] < 0 or start[axis] > S: + return 0.0, 'bounds' + if end[axis] < 0 or end[axis] > S: + boundary = 0.0 if end[axis] < 0 else float(S) + value = (boundary - start[axis]) / (end[axis] - start[axis]) + if first is None or value < first: + first, reason = value, 'bounds' + low = np.floor(np.minimum(start, end)[[0, 2]] - radius).astype(int) + high = np.floor(np.maximum(start, end)[[0, 2]] + radius).astype(int) + for x in range(max(0, low[0]), min(S - 1, high[0]) + 1): + for z in range(max(0, low[1]), min(S - 1, high[1]) + 1): + height = float(self.arena.H[x, z]) + hit = _segment_box(start, end, + np.array([x - radius, -radius, z - radius]), + np.array([x + 1 + radius, height + radius, z + 1 + radius])) + if hit is not None and (first is None or hit < first): + first, reason = hit, 'ground' if height == 0 else 'voxel' + return first, reason + + def _targets(self): + """Damageable boxes for arrows and the sword ray: (kind, lo, hi, payload).""" + g, out = self.boss, [] + if hasattr(g, "hitboxes"): + out += [("boss", lo, hi, part) for part, lo, hi in g.hitboxes()] + else: + out.append(("boss", g.hit_lo(), g.hit_hi(), "body")) + for c in getattr(g, "crystals", ()): + if c["alive"]: + out.append(("crystal", c["pos"] - [0.5, 0.0, 0.5], c["pos"] + [0.5, 1.6, 0.5], c)) + for z in getattr(g, "minions", ()): # zombie reinforcements (minecraft-arena@5) + if z.hp > 0: + out.append(("minion", z.hit_lo(), z.hit_hi(), z)) + return out + + def _damage(self, kind, payload, dmg, how, bonus_knockback=0.0): + g = self.boss + if kind == "crystal": + g.crystal_destroyed(self, payload) + return 0.0 + if kind == "minion": # a reinforcement's health is not the boss's health + payload.take_hit(self, dmg, how, bonus_knockback=bonus_knockback) + return 0.0 + before = max(0.0, float(g.hp)) + if hasattr(g, "hitboxes"): + g.take_hit(self, dmg, how, bonus_knockback=bonus_knockback, part=payload) + else: + g.take_hit(self, dmg, how, bonus_knockback=bonus_knockback) + return max(0.0, before - max(0.0, float(g.hp))) + + def _update_arrows(self): + kept = [] + radius = BOW_RULES['arrow_radius_blocks'] + for arrow in self.arrows: + if arrow['age'] >= FPS * BOW_RULES['maximum_life_seconds']: + self.events.append(('arrow_expired', arrow['id'])) + continue + start, end = arrow['pos'], arrow['pos'] + arrow['vel'] + world_hit, reason = self._arrow_world_hit(start, end) + best = None + for kind, lo, hi, payload in self._targets(): + u = _segment_box(start, end, lo - radius, hi + radius) + if u is not None and (best is None or u < best[0]): + best = (u, kind, payload) + if world_hit is not None and (best is None or world_hit <= best[0]): + self.events.append(('arrow_blocked', arrow['id'], reason)) + continue + if best is not None: + _, kind, payload = best + damage = math.ceil(float(np.linalg.norm(arrow['vel'])) / VT + * BOW_RULES['base_damage_per_speed']) + if arrow['critical']: + damage += int(self.rng.integers(0, damage // 2 + 2)) + actual = self._damage(kind, payload, damage, 'arrow_critical' if arrow['critical'] else 'arrow') + if actual > 0: + self.body.arrows_hit += 1 + self.body.arrow_damage += actual + self.events.append(('arrow_hit', arrow['id'], round(actual, 4), kind)) + continue + arrow['pos'] = end + arrow['vel'] *= decay(BOW_RULES['drag_per_vanilla_tick']) + arrow['vel'][1] -= BOW_RULES['gravity_blocks_per_vanilla_tick_squared'] * VT * VT + arrow['age'] += 1 + kept.append(arrow) + self.arrows = kept + + + # -- observation ------------------------------------------------------- + def _rel(self): + p, g = self.body.e, self.boss.e + d = g.pos - p.pos + bearing = math.atan2(d[2], d[0]) - p.yaw + return d, math.hypot(d[0], d[2]), math.atan2(math.sin(bearing), math.cos(bearing)) + + def observe(self): + b, g, p = self.body, self.boss, self.body.e + d, dist, bearing = self._rel() + H = np.pad(self.arena.H, self.R, constant_values=WALL_CAP).astype(np.float32) + ix, iz = int(p.pos[0]) + self.R, int(p.pos[2]) + self.R + local = (H[max(ix - self.R, 0):ix + self.R + 1, max(iz - self.R, 0):iz + self.R + 1] - p.pos[1]) / 4 + mine = [p.pos[0] / S, p.pos[1] / 4, p.pos[2] / S, *p.vel / VT * 4, math.sin(p.yaw), math.cos(p.yaw), + b.hp / b.max_hp, b.charge, float(p.on_ground)] + states = type(g).STATES + hot = g.state in ("windup", "lineup", "charge") + boss = [*d / 8, dist / 8, math.sin(bearing), math.cos(bearing), g.hp / g.max_hp, + *np.eye(4)[states.index(g.state)], max(g.timer, 0) if hot else 0, + min(g.cd / FPS, 2.0), float(g.enraged), float(g.in_reach(self))] + extra = [] + skulls = getattr(g, "skulls", None) + if skulls is not None: # three nearest skulls, in player-relative terms + order = sorted(skulls, key=lambda s: float(np.linalg.norm(s["pos"] - p.pos)))[:3] + for s in order: + rel = s["pos"] - p.pos + extra += [*rel / 8, *s["vel"] / VT / 2, float(s["life"])] + extra += [0.0] * (3 - len(order)) * 7 + if isinstance(g, Skeleton): # three nearest skeleton arrows + order = sorted(g.arrows, key=lambda a: float(np.linalg.norm(a["pos"] - p.pos)))[:3] + for a in order: + rel = a["pos"] - p.pos + extra += [*rel / 8, *a["vel"] / VT / 2, a["age"] / FPS] + extra += [0.0] * (3 - len(order)) * 7 + if isinstance(g, ZombieLeader): # three nearest live reinforcements + live = sorted((z for z in g.minions if z.hp > 0), key=lambda z: float(np.linalg.norm(z.e.pos - p.pos)))[:3] + for z in live: + extra += [*(z.e.pos - p.pos) / 8, z.hp / z.max_hp] + extra += [0.0] * (3 - len(live)) * 4 + if isinstance(g, Warden): + extra += [max(g.timer, 0.0) if g.phase == "boom" else 0.0, min(g.out_of_reach / FPS, 10.0) / 10.0, + g.dark_t / ticks(260)] + return np.concatenate([mine, boss, extra, local.ravel()]).astype(np.float32) + + def state(self): + b, g = self.body, self.boss + d, dist, bearing = self._rel() + mob = {"pos": g.e.pos.round(2).tolist(), "hp": round(g.hp, 2), "max_hp": round(g.max_hp, 1), + "state": g.state, "timer": round(max(g.timer, 0), 2), "cooldown_s": round(g.cd / FPS, 2), + "enraged": bool(g.enraged), "distance": round(dist, 2), + "distance3d": round(float(np.linalg.norm(d)), 2), + "bearing_deg": round(math.degrees(bearing), 1), "in_reach": g.in_reach(self), + "iframes": int(g.iframes), "yaw_deg": round(math.degrees(g.e.yaw), 1)} + if g.state == "windup": + mob["windup_left"] = round(max(g.timer, 0), 2) + if getattr(g, "skulls", None): + mob["skulls"] = [{"pos": s["pos"].round(2).tolist(), "vel": (s["vel"] * FPS).round(2).tolist(), # b/s + "blue": bool(s.get("blue", False))} for s in g.skulls] + if hasattr(g, "phase"): + mob["phase"] = g.phase + if hasattr(g, "armored"): + mob["armored"] = bool(g.armored) + if hasattr(g, "crystals"): + mob["crystals"] = [{"id": c["id"], "pos": c["pos"].round(2).tolist(), "alive": bool(c["alive"])} + for c in g.crystals] + mob["healing_from"] = None if g.heal_from is None else g.heal_from["id"] + mob["fireballs"] = [{"pos": f["pos"].round(2).tolist()} for f in g.fireballs] + mob["clouds"] = [{"pos": c["pos"].round(2).tolist(), "r": round(c["r"], 2), "kind": c["kind"], + "life": round(c["life"], 2)} for c in g.clouds] + if isinstance(g, ZombieLeader): + mob["minions"] = [{"n": z.n, "pos": z.e.pos.round(2).tolist(), "hp": round(z.hp, 2), "state": z.state} + for z in g.minions if z.hp > 0] + mob["reinforce_chance"] = round(g.chance, 4) + mob["summoned"] = g.summoned + if isinstance(g, Warden): + mob["darkness_s"] = round(g.dark_t / FPS, 2) + mob["out_of_reach_s"] = round(g.out_of_reach / FPS, 2) + mob["booms"] = g.booms + if isinstance(g, Skeleton): + mob["arrows"] = [{"id": a["id"], "pos": a["pos"].round(3).tolist(), "vel": (a["vel"] * FPS).round(3).tolist()} + for a in g.arrows] + mob["shots"] = g.shots + result = {"rules": RULES, + "player": {"pos": b.e.pos.round(2).tolist(), "yaw_deg": round(math.degrees(b.e.yaw), 1), + "pitch_deg": round(math.degrees(b.e.pitch), 4), "weapon": b.weapon, + "hp": round(b.hp, 2), "max_hp": b.max_hp, "attack_charge": round(b.attack_charge, 2), + "on_ground": b.e.on_ground, "sprinting": bool(b.sprinting), + "iframes": int(b.iframes), "wither_effect_s": round(b.wither_t / FPS, 2)}, + "boss": mob, + "boss_kind": self.mob_name, "boss_skills": list(self.boss.SKILLS)} + result['player'].update(bow_charge=round(b.bow_charge, 6), bow_drawing=b.bow_drawing, + arrows_fired=b.arrows_fired, arrows_hit=b.arrows_hit, + arrow_damage=round(b.arrow_damage, 6), melee_damage=round(b.melee_damage, 6)) + result['arrows'] = [{'id': arrow['id'], 'pos': arrow['pos'].round(4).tolist(), + 'vel': (arrow['vel'] * FPS).round(4).tolist(), 'age': arrow['age'], + 'damage': arrow['damage'], 'critical': arrow['critical']} for arrow in self.arrows] + result['weapon_rules'] = dict(BOW_RULES) + return result + + + # -- rendering --------------------------------------------------------- + def render(self, t=None): + try: + if self._gl is None: + self._gl = mcskin.VoxelRenderer(*self.size) + img = self._gl.draw(self, t) + self.render_error = None + except Exception as ex: # no GL context: top-down map, reason kept for debugging + self.render_error = repr(ex) + renderer, self._gl = self._gl, None + if renderer is not None: + try: + renderer.close() + except Exception as close_ex: + self.render_error += f"; cleanup: {close_ex!r}" + img = self._topdown() + return mcskin.hud(img, self) + + def close(self): + """Release the lazy renderer; a later render can create a fresh context.""" + renderer, self._gl = self._gl, None + if renderer is not None: + renderer.close() + + def _topdown(self): + W, H = self.size + T = H // S + img = np.zeros((H, W, 3), np.uint8) + pal = np.array([[90, 150, 60], [150, 110, 60], [120, 120, 120], [100, 100, 110], [60, 60, 60], + [70, 70, 75], [80, 80, 85], [95, 95, 100], [110, 110, 115]], np.uint8) + ox = (W - S * T) // 2 + world = img[:S * T, ox:ox + S * T] + world[:] = pal[np.clip(self.arena.H.T, 0, 8)].repeat(T, 0).repeat(T, 1) + for e, c in ((self.boss.e, (220, 215, 205)), (self.body.e, (40, 120, 230))): + x, z, r = int(e.pos[0] * T), int(e.pos[2] * T), int(e.w * T / 2) + world[max(z - r, 0):z + r, max(x - r, 0):x + r] = c + return img + + +# ---------------------------------------------------------------- factories +STYLES = {"iron_golem": "field", "zombie": "field", "ender_dragon": "towers", "wither": "towers", + "warden": "deep_dark", "skeleton": "ruins", "zombie_leader": "night"} +SECONDS = {"iron_golem": 300.0, "zombie": 90.0, "ender_dragon": 300.0, "wither": 300.0, # hard tier ~3 min (@4) + "warden": 300.0, "skeleton": 300.0, "zombie_leader": 300.0} + + +def make(mob="iron_golem", **kw) -> BossBenchEnv: + case_kw = {k: kw.pop(k) for k in ("style", "width", "height", "camera", "weapon") if k in kw} + case_kw.setdefault("style", STYLES.get(mob, "field")) + seconds = kw.pop("max_seconds", SECONDS.get(mob, 120.0)) + return BossBenchEnv(MobFight(mob, max_seconds=seconds, **case_kw), max_seconds=seconds, **kw) diff --git a/environments/games/prototype/bossbench/mc_scripted.py b/environments/games/prototype/bossbench/mc_scripted.py new file mode 100644 index 0000000000000000000000000000000000000000..c7334ce6f49a941fb209951acf56eacda9f6907d --- /dev/null +++ b/environments/games/prototype/bossbench/mc_scripted.py @@ -0,0 +1,1102 @@ +"""Standard trusted scripted controller for the Minecraft remake (bossbench.mc4d), overnight PROTOCOL section 3. + + from bossbench import mc_scripted + packet = mc_scripted.scripted(case) # case: the live mc4d.MobFight -> one legal 200 ms packet (text) + +It reads privileged simulation state (it is a reference controller, never shown to a policy) and emits only legal +packets (<= 4 keys per hold set, |dx|,|dy| <= 1000, |dz| <= 5). It never mutates the live case: every lookahead +runs on a light clone (deep copy with its own RNG state and arena heights; renderer, rigs and particles are not +copied and posing is disabled), so it is deterministic for a given (case, seed, options, packet history). Memory +lives in a WeakKeyDictionary keyed by the case and is reset when the episode tick is 0. + +Strategy per packet: decide the weapon (hotbar wheel), an aim point and a few candidate packets (movement x +attack timing x jump/draw/release), roll every candidate forward 2-4 packets on a clone (the later packets are a +greedy continuation), and keep the best score = 10 x boss damage - taken_w x player damage + shaping, with a small +bonus for progress made sooner (breaks the "release now" vs "release next packet" tie that held full bow draws). +minecraft-arena@4 (2026-11-02, three tiers): the iron golem gets its own planner (attack-box gap, room to back off, +4-packet lookahead pricing a slam like the hit it is); the dragon aims only at crystals it can see, leaves their +blast radius, sidesteps a fireball line-up and walks into sword reach of a perched head; the wither looks 3 packets +ahead when a skull closes in at melee range. +""" +from __future__ import annotations + +import copy +import math +import types +import weakref + +import numpy as np + +from . import keymouse as km +from . import mc4d + +TICKS = 12 # 60 Hz simulation ticks per 200 ms packet +DEG = mc4d.Steve.MOUSE_DEG +_MEM: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary() +MOVES = ("", "W", "S", "A", "D") +# minecraft-arena@7 removed natural regeneration: a hit taken at 10 s still counts at 170 s. Price player damage at +# least at this fraction of the rate the fight affords (boss health left per player health left); short fights +# keep their own taken_w, long hard fights get more careful as health runs down. Measured on seeds 1-32 (hard wins, +# floor off -> on): dragon 28 -> 31, golem 13 -> 14, skeleton 0 -> 8, zombie leader 20 -> 32, warden 30 -> 30, but +# wither 25 -> 20 (careful play stretched its fights until the skulls wore the player down), so the wither keeps 0. +HP_BUDGET = 0.05 +HP_BUDGET_BY_BOSS = {"wither": 0.0} + + +# ------------------------------------------------------------------------------------------- simulation helpers +def clone(case): + """Gameplay-only deep copy. Shares the read-only difficulty knobs, drops renderer/rigs/particles.""" + memo = {id(case.fx): []} + minions = list(getattr(case.boss, "minions", ())) # zombie reinforcements (minecraft-arena@5) + for obj in (getattr(case, "_gl", None), case.body.rig, case.boss.rig, getattr(case, "fxrng", None), + *(z.rig for z in minions)): + if obj is not None: + memo[id(obj)] = None + for comp in (case.arena, case.body, case.boss): + memo[id(comp.k)] = comp.k + arena = copy.copy(case.arena) + arena.H = case.arena.H.copy() + memo[id(case.arena)] = arena + sim = copy.deepcopy(case, memo) + # Harness wrappers (e.g. bossbench.scripted.FrameCapture) patch bound methods onto the live instance; deepcopy + # keeps function objects as-is, so a copied wrapper would still drive the LIVE case. Restore class methods. + for obj in (sim, sim.body, sim.boss, sim.arena, *getattr(sim.boss, "minions", ())): + for key in [k for k, v in vars(obj).items() if isinstance(v, (types.FunctionType, types.MethodType))]: + del vars(obj)[key] + sim.track = lambda: None + sim.body.pose = lambda c: None + sim.boss.pose = lambda c: None + sim.boss.pose_child = lambda c, z: None + return sim + + +def run_packet(sim, packet, last): + """Execute one parsed packet exactly as PyCaseEnv does (keymouse.schedule over 12 ticks).""" + sched, last = km.schedule(packet, TICKS, last) + for held, pressed, mouse in sched: + if sim.outcome(): + break + sim.tick(sim.body.keys(sim, held, pressed, mouse)) + return last + + +def packet(subs, mouse=(0, 0, 0)): + subs = [frozenset(s) for s in subs] + assert len(subs) == 6 and all(len(s) <= km.MAX_KEYS for s in subs) + mouse = (int(np.clip(mouse[0], -1000, 1000)), int(np.clip(mouse[1], -1000, 1000)), int(np.clip(mouse[2], -5, 5))) + return {"mouse": mouse, "subs": subs} + + +def text(p): + order = {k: i for i, k in enumerate(km.KEYS)} + return km.format_packet([sorted(s, key=order.get) for s in p["subs"]], p["mouse"]) + + +def wrap(a): + return (a + math.pi) % (2 * math.pi) - math.pi + + +def aim_to(body, point, frac=1.0): + """Mouse (dx, dy) that turns the view onto point by the end of the packet (frac < 1: by that fraction).""" + e = body.e + d = np.asarray(point, float) - (e.pos + [0, mc4d.EYE, 0]) + yaw = math.atan2(d[2], d[0]) + pitch = math.atan2(d[1], math.hypot(d[0], d[2])) + dyaw, dpitch = wrap(yaw - e.yaw), pitch - e.pitch + return math.degrees(dyaw) / DEG / frac, -math.degrees(dpitch) / DEG / frac + + +def view_error(body, point): + dx, dy = aim_to(body, point) + return math.hypot(dx, dy) * DEG # degrees + + +def flat(v): + return np.array([v[0], 0.0, v[2]]) + + +def hdist(a, b): + return float(math.hypot(a[0] - b[0], a[2] - b[2])) + + +# ------------------------------------------------------------------------------------------- memory +def memory(case): + m = _MEM.get(case) + if m is None or (case.t == 0 and m.get("t", -1) != 0) or case.t < m.get("t", -1): + m = {"last": frozenset(), "t": case.t, "crit_wait": 0} + _MEM[case] = m + m["t"] = case.t + return m + + +def scripted(case): + """One legal packet (text) for the live MobFight; deterministic, read-only.""" + m = memory(case) + planner = PLANNERS[case.boss.name] + p = planner(case, m) + m["last"] = frozenset(p["subs"][-1]) + return text(p) + + +# ------------------------------------------------------------------------------------------- packet building +def build(move="", jump=(), swing=None, rmb=None, sprint=False, mouse=(0, 0, 0), wheel=0, last=frozenset()): + """Six hold sets. move: '' or one of W/S/A/D (held all packet); jump: substeps holding Space; + swing: substep index of one LMB/J press (the key not held in the previous substep); + rmb: None (released), 'hold' (held all packet) or an int j (held for substeps < j, released from j).""" + subs = [] + prev = set(last) + for j in range(6): + s = set() + if move: + s.add(move) + if j in jump: + s.add("Space") + if sprint and move == "W": + s.add("Shift") + if rmb == "hold" or (isinstance(rmb, int) and not isinstance(rmb, bool) and j < rmb): + s.add("RMB") + if swing is not None and j == swing: + s.add("J" if "LMB" in prev else "LMB") + subs.append(s) + prev = s + return packet(subs, (mouse[0], mouse[1], wheel)) + + +def weapon_wheel(case, want): + return 0 if case.body.weapon == want else 1 + + +def swing_slots(body): + """Sub-steps worth trying a full-charge swing at: the first charged one and every other one after it (the + in-between timings rarely differ; pruning them keeps the lookahead fast enough for the live demo).""" + ready = [j for j in range(6) if charge_at(body, 2 * j) > 0.9] + return ready[::2] + + +def charge_at(body, ticks_ahead, weapon=None): + weapon = weapon or body.weapon + T = body.T_ATTACK if weapon == "sword" else body.T_FIST + return min(1.0, (body.since_swing + ticks_ahead + 0.5) / T) + + +# ------------------------------------------------------------------------------------------- evaluation +def evaluate(case, m, cand, cont, shape, horizon=2, taken_w=8.0): + """Roll cand then (horizon - 1) greedy continuation packets on a clone; return (score, sim). + taken_w prices player damage against boss damage (x10): long fights must not trade hits. Since minecraft-arena@7 + (no natural regeneration) health is a budget for the whole fight, so the price never drops below HP_BUDGET of + the exchange rate the fight affords: 10 x boss health left / player health left (see HP_BUDGET).""" + b = case.body + budget = HP_BUDGET_BY_BOSS.get(case.boss.name, HP_BUDGET) + taken_w = max(taken_w, budget * 10.0 * max(float(case.boss.hp), 0.0) / max(float(b.hp), 1.0)) + sim = clone(case) + boss0, hp0 = float(sim.boss.hp), float(sim.body.hp) + wither0 = sim.body.wither_t + + def alive(): + return sum(c["alive"] for c in getattr(sim.boss, "crystals", ())) + alive0 = alive() + last = run_packet(sim, cand, m["last"]) + first = (float(sim.boss.hp), float(sim.body.hp)) + # Progress made sooner is worth a little more. Without it a full bow draw held "for later" ties with a release + # now (the continuation releases anyway), the tie goes to holding, and the next packet repeats it: found + # 2026-11-02, an easy dragon with a crystal in plain sight and the bow held at full draw for 15 s. + sooner, hp_prev, alive_prev = 0.0, boss0, alive0 + for k in range(horizon): + if k: + if sim.outcome(): + break + last = run_packet(sim, cont(sim, last), last) + hp_now, alive_now = float(sim.boss.hp), alive() + sooner += (1 - k / horizon) * (1.0 * (hp_prev - hp_now) + 3.0 * (alive_prev - alive_now)) + hp_prev, alive_prev = hp_now, alive_now + dealt = boss0 - float(sim.boss.hp) + taken = hp0 - float(sim.body.hp) + max(0, sim.body.wither_t - wither0) / mc4d.FPS * 0.7 + crystals = alive0 - alive() + score = 10 * dealt - taken_w * taken + 25 * crystals + 4 * (boss0 - first[0]) - 4 * (hp0 - first[1]) + sooner + if sim.outcome() == "win": + score += 1000 + elif sim.outcome() == "loss": + score -= 1000 + return score + shape(sim), sim + + +def best_of(case, m, cands, cont, shape, horizon=2, taken_w=8.0): + """cands: packets, or (packet, own continuation) pairs; the best first packet wins.""" + best, best_score = None, -math.inf + for cand in cands: + own = cont + if isinstance(cand, tuple): + cand, own = cand + s, _ = evaluate(case, m, cand, own, shape, horizon, taken_w) + if s > best_score + 1e-9: + best, best_score = cand, s + return best + + +def greedy_melee(target_fn, band=(2.4, 3.2)): + """Continuation: keep aiming, keep the distance band, swing when charged and on target.""" + def cont(sim, last): + b = sim.body + point = target_fn(sim) + dx, dy = aim_to(b, point) + dist = hdist(b.e.pos, point) + move = "S" if dist < band[0] else ("W" if dist > band[1] else "") + swing = None + if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None: + swing = 0 + return build(move, swing=swing, mouse=(dx, dy), last=last) + return cont + + +# ------------------------------------------------------------------------------------------- terrain helpers +def open_space(case, pos): + """Distance to the arena wall and number of tall columns nearby (a crude 'room to retreat' measure).""" + H = case.arena.H + x, z = pos[0], pos[2] + wall = min(x - 1, z - 1, mc4d.S - 1 - x, mc4d.S - 1 - z) + ix, iz = int(x), int(z) + near = H[max(ix - 1, 0):ix + 2, max(iz - 1, 0):iz + 2] + return wall, int((near > pos[1] + 1).sum()) + + +def safe_shape(case_sim, centre_weight=0.15): + wall, tall = open_space(case_sim, case_sim.body.e.pos) + return -centre_weight * max(0.0, 4.0 - wall) ** 2 - 0.4 * tall + + +# ------------------------------------------------------------------------------------------- melee (golem, zombie) +def mob_centre(sim): + g = sim.boss + return (g.hit_lo() + g.hit_hi()) / 2 + + +def plan_melee(case, m, band, threat_reach, threat=None, taken_w=8.0, horizon=2): + b, g = case.body, case.boss + wheel = weapon_wheel(case, "sword") + lead = g.e.pos + g.e.vel * TICKS * 0.5 + point = (g.hit_lo() + g.hit_hi()) / 2 + (lead - g.e.pos) + dx, dy = aim_to(b, point) + dist = hdist(b.e.pos, g.e.pos) + + def shape(sim): + d = hdist(sim.body.e.pos, sim.boss.e.pos) + s = -1.2 * abs(d - (band[0] + band[1]) / 2) + safe_shape(sim) + if sim.boss.state in ("windup", "swing") and d < threat_reach: + s -= 6.0 + if threat is not None: + s += threat(sim) + s -= 0.02 * view_error(sim.body, mob_centre(sim)) + return s + + cont = greedy_melee(mob_centre, band) + cands = [] + swings = [None] + if wheel == 0 and dist < 5.5: + swings += swing_slots(b) + for move in MOVES: + for jump in ((), (0, 1, 2)): + if jump and move not in ("", "W", "S"): + continue + for sw in swings: + if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0): + continue + cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"])) + # turn and sprint away (sprint 0.281 b/t outruns a mob that is faster than walking backwards) + away = math.atan2(b.e.pos[2] - g.e.pos[2], b.e.pos[0] - g.e.pos[0]) + for off in (-0.6, 0.0, 0.6): + turn = math.degrees(wrap(away + off - b.e.yaw)) / DEG + cands.append(build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"])) + return best_of(case, m, cands, cont, shape, horizon=horizon, taken_w=taken_w) + + +def golem_gap(sim): + """Blocks between the player's box and the golem's attack box (Chebyshev; negative = inside). The 1.20.2 attack + box is the collision box grown 0.828 horizontally, axis-aligned, so on a diagonal it reaches 2.6 blocks.""" + g, p = sim.boss, sim.body.e + r = g.half[0] + g.ATTACK_INFLATE + mc4d.PLAYER_W / 2 + return max(abs(p.pos[0] - g.e.pos[0]), abs(p.pos[2] - g.e.pos[2])) - r + + +def box_reach(sim): + """Distance from the player's eye to the golem's hitbox; the sword ray reaches 3.""" + g, b = sim.boss, sim.body + eye = b.e.pos + [0, mc4d.EYE, 0] + return float(np.linalg.norm(eye - np.clip(eye, g.hit_lo(), g.hit_hi()))) + + +def golem_danger(sim, soon=10): + g = sim.boss + return g.state == "windup" or (g.state in ("chase", "recover") and g.cd <= mc4d.ticks(soon)) + + +def golem_threat(sim): + """Slams beyond the rollout horizon: the golem winds up the moment the player is inside its attack box with the + cooldown done. Keep a margin while it can swing and never be airborne next to it then (no air control). + Priced near the cost of eating a slam (taken_w x a mid-range hit): a crit is never worth one.""" + g, b = sim.boss, sim.body + gap = golem_gap(sim) + s = 0.0 + if g.state == "windup": + s -= 70.0 * max(0.0, 0.45 - gap) + elif golem_danger(sim, 8): + s -= 35.0 * max(0.0, 0.55 - gap) + if not b.e.on_ground: + s -= 15.0 * max(0.0, 1.2 - gap) + return s + + +def retreat_room(sim, direction=None, limit=8.0): + """Free floor (blocks) behind the player when backing straight away from the boss (or along direction): + the arena wall and any column the player would have to jump end it. Backing into a corner is how a + near-walking-speed golem pins a player.""" + p = sim.body.e.pos + if direction is None: + direction = flat(p - sim.boss.e.pos) + n = float(np.linalg.norm(direction)) + if n < 1e-6: + return limit + u, H = direction / n, sim.arena.H + step = 0.0 + while step < limit: + q = p + u * (step + 0.5) + if not (1.3 <= q[0] <= mc4d.S - 1.3 and 1.3 <= q[2] <= mc4d.S - 1.3) or H[int(q[0]), int(q[2])] > p[1] + 0.5: + break + step += 0.5 + return step + + +def golem_cont(sim, last): + """Continuation that fights like a careful player: face the golem, step back out of its box while it can + swing (sideways when the wall is behind), close in when out of sword reach, swing on a full charge.""" + b = sim.body + dx, dy = aim_to(b, mob_centre(sim)) + gap, reach = golem_gap(sim), box_reach(sim) + back = "S" + if retreat_room(sim) < 1.5: + left, right = -b.e.right, b.e.right + back = "A" if retreat_room(sim, left) >= retreat_room(sim, right) else "D" + if golem_danger(sim) and gap < 0.7: + move = back + elif reach > 2.8: + move = "W" + elif gap < 0.35: + move = back + else: + move = "" + swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None + return build(move, swing=swing, mouse=(dx, dy), last=last) + + +def plan_golem(case, m): + b, g = case.body, case.boss + wheel = weapon_wheel(case, "sword") + lead = g.e.pos + g.e.vel * TICKS * 0.5 + dx, dy = aim_to(b, mob_centre(case) + (lead - g.e.pos)) + + def shape(sim): + gap, reach = golem_gap(sim), box_reach(sim) + s = -1.2 * max(0.0, reach - 2.7) - 1.2 * max(0.0, 0.6 - gap) + safe_shape(sim) + golem_threat(sim) + if gap < 2.0: # keep open floor behind: circle away from walls and corners + s += 1.5 * min(retreat_room(sim), 6.0) + return s - 0.02 * view_error(sim.body, mob_centre(sim)) + + swings = [None] + if wheel == 0 and box_reach(case) < 4.0: + swings += swing_slots(b) + cands = [] + for move in MOVES: + for jump in ((), (0, 1, 2)): + if jump and move not in ("", "W", "S"): + continue + for sw in swings: + if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0): + continue + cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"])) + # turn and sprint away (0.281 b/t sprint vs the golem's 0.11-0.15 b/t chase); the continuation keeps running + # so the rollout prices the escape, not a turn back into the slam + away = math.atan2(b.e.pos[2] - g.e.pos[2], b.e.pos[0] - g.e.pos[0]) + for off in (-0.6, 0.0, 0.6): + turn = math.degrees(wrap(away + off - b.e.yaw)) / DEG + run = lambda sim, last: build("W", sprint=True, last=last) + cands.append((build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]), run)) + return best_of(case, m, cands, golem_cont, shape, horizon=4, taken_w=24.0) + + +def plan_zombie(case, m): + return plan_melee(case, m, band=(2.5, 3.1), threat_reach=2.5) + + +def plan_zombie_leader(case, m): + """Leader zombie with reinforcements (minecraft-arena@5; its own case since @6): fight at the edge of the horde, hit the leader on full + charges and cut down a reinforcement that comes into the sword's reach first (an add swipes as hard as the leader + but dies in two crits; the leader's hits on the player are what lose the fight). Priced like the golem, per zombie.""" + b, g = case.body, case.boss + wheel = weapon_wheel(case, "sword") + target = horde_target(case) + lead = target.e.pos + target.e.vel * TICKS * 0.5 + dx, dy = aim_to(b, mob_centre_of(target) + (lead - target.e.pos)) + adds0 = {z.n: max(z.hp, 0.0) for z in g.minions if z.hp > 0} + + def shape(sim): + gap, reach = mob_gap(sim, sim.boss), mob_reach(sim, sim.boss) + s = -0.8 * max(0.0, reach - 2.7) - 1.0 * max(0.0, 0.5 - gap) + safe_shape(sim) + horde_threat(sim) + alive = {z.n: max(z.hp, 0.0) for z in sim.boss.minions if z.hp > 0} + s += 6.0 * sum(hp - alive.get(n, 0.0) for n, hp in adds0.items()) # thinning the horde + s += 40.0 * sum(1 for n in adds0 if n not in alive) # a dead add stops swinging for good + s += 1.0 * min(retreat_room(sim), 6.0) * min(horde_near(sim), 3) # keep open floor behind when crowded + t = horde_target(sim) + return s - 0.02 * view_error(sim.body, mob_centre_of(t)) + + swings = [None] + if wheel == 0 and any(mob_reach(case, z) < 3.6 for z in horde(case)): + swings += swing_slots(b) + cands = [] + for move in MOVES: + for jump in ((), (0, 1, 2)): + if jump and move not in ("", "W", "S"): + continue + for sw in swings: + if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0): + continue + cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"])) + centre = np.mean([z.e.pos for z in horde(case)], axis=0) + away = math.atan2(b.e.pos[2] - centre[2], b.e.pos[0] - centre[0]) + for off in (-0.9, 0.0, 0.9): + turn = math.degrees(wrap(away + off - b.e.yaw)) / DEG + run = lambda sim, last: build("W", sprint=True, last=last) + cands.append((build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]), run)) + return best_of(case, m, cands, horde_cont, shape, horizon=3, taken_w=14.0) + + +def mob_centre_of(mob): + return (mob.hit_lo() + mob.hit_hi()) / 2 + + +def horde_target(sim): + """Whom to aim at: a reinforcement in sword reach that one full-charge hit kills (it would otherwise keep swinging + for 2.5-4.5 a time), else a reinforcement clearly closer than the leader, else the leader.""" + g = sim.boss + one_hit = mc4d.armor_reduce(sim.body.k.sword_dmg * 1.5, g.armor, 0.0) + best, best_key = g, (2, mob_reach(sim, g)) + for z in g.minions: + if z.hp <= 0: + continue + r = mob_reach(sim, z) + if r < 2.9 and z.hp <= one_hit: + key = (0, r) + elif r < 2.9 and r < mob_reach(sim, g) - 0.3: + key = (1, r) + else: + continue + if key < best_key: + best, best_key = z, key + return best + + +# ------------------------------------------------------------------------------------------- shared melee helpers (@5) +def mob_gap(sim, mob): + """Blocks between the player's box and this mob's 1.20.2 attack box (Chebyshev; negative = inside).""" + p = sim.body.e + r = mob.half[0] + mob.ATTACK_INFLATE + mc4d.PLAYER_W / 2 + return max(abs(p.pos[0] - mob.e.pos[0]), abs(p.pos[2] - mob.e.pos[2])) - r + + +def mob_reach(sim, mob): + """Distance from the player's eye to this mob's hitbox (the sword ray reaches 3).""" + eye = sim.body.e.pos + [0, mc4d.EYE, 0] + return float(np.linalg.norm(eye - np.clip(eye, mob.hit_lo(), mob.hit_hi()))) + + +def horde(sim): + return [sim.boss] + [z for z in getattr(sim.boss, "minions", ()) if z.hp > 0] + + +def horde_near(sim, within=3.0): + return sum(mob_gap(sim, z) < within for z in horde(sim)) + + +def horde_threat(sim): + """Swings beyond the rollout horizon, for every zombie: inside an attack box while its cooldown runs out.""" + s = 0.0 + for z in horde(sim): + gap = mob_gap(sim, z) + if z.state == "windup": + s -= 16.0 * max(0.0, 0.45 - gap) + elif z.state in ("chase", "recover") and z.cd <= mc4d.ticks(6): + s -= 6.0 * max(0.0, 0.5 - gap) + return s + + +def horde_cont(sim, last): + """Continuation: face the current target (an add in reach, else the leader), back away from whichever zombie is + about to swing, close in when the leader is out of sword reach, swing on a full charge.""" + b, g = sim.body, sim.boss + target = horde_target(sim) + dx, dy = aim_to(b, mob_centre_of(target)) + threat = min(horde(sim), key=lambda z: mob_gap(sim, z)) + tgap = mob_gap(sim, threat) + back = "S" + if retreat_room(sim, flat(b.e.pos - threat.e.pos)) < 1.5: + back = "A" if retreat_room(sim, -b.e.right) >= retreat_room(sim, b.e.right) else "D" + hot = threat.state == "windup" or (threat.state in ("chase", "recover") and threat.cd <= mc4d.ticks(8)) + if hot and tgap < 0.6: + move = back + elif mob_reach(sim, g) > 2.8: + move = "W" + else: + move = "" + swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None + return build(move, swing=swing, mouse=(dx, dy), last=last) + + +# ------------------------------------------------------------------------------------------- warden (@5) +def warden_threat(sim): + """The warden's smash lands on anything in its attack box when the windup ends; it out-walks a backpedalling + player, so the only escape is backing out *during* the windup, from the edge of its box. One smash costs 8-15 HP. + Price being deep inside the box while its cooldown runs out (no escape from there) and being airborne then.""" + g, b = sim.boss, sim.body + gap = mob_gap(sim, g) + s = 0.0 + if g.phase == "windup": + s -= 90.0 * max(0.0, 0.5 - gap) + elif g.phase in ("chase", "recover"): + soon = max(0.0, 1.0 - g.cd / mc4d.ticks(24)) # 0 with 24+ vanilla ticks of cooldown left, 1 at 0 + s -= 60.0 * soon * max(0.0, 0.45 - gap - 0.55 * (1.0 - soon)) + if not b.e.on_ground and soon > 0.5: + s -= 20.0 * max(0.0, 1.3 - gap) + return s + + +def warden_cont(sim, last): + """Continuation: face the warden; while it winds up, backpedal (sideways at a wall); in its recovery and early + cooldown stay in sword reach; as the cooldown runs out, drift to the edge of its attack box; swing on full charge.""" + b, g = sim.body, sim.boss + dx, dy = aim_to(b, mob_centre(sim)) + gap, reach = mob_gap(sim, g), mob_reach(sim, g) + back = "S" + if retreat_room(sim) < 1.5: + back = "A" if retreat_room(sim, -b.e.right) >= retreat_room(sim, b.e.right) else "D" + if g.phase == "windup" and gap < 0.6: + move = back + elif g.phase in ("chase", "recover") and g.cd <= mc4d.ticks(12) and gap < 0.1: + move = back + elif reach > 2.8: + move = "W" + else: + move = "" + swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None + return build(move, swing=swing, mouse=(dx, dy), last=last) + + +def plan_warden(case, m): + b, g = case.body, case.boss + wheel = weapon_wheel(case, "sword") + dx, dy = aim_to(b, mob_centre(case)) + + def shape(sim): + w = sim.boss + gap, reach = mob_gap(sim, w), mob_reach(sim, w) + s = -1.0 * max(0.0, reach - 2.7) + safe_shape(sim) + warden_threat(sim) + if gap < 2.0: + s += 1.5 * min(retreat_room(sim), 6.0) + s -= 0.3 * max(0.0, w.out_of_reach / mc4d.FPS - 2.0) # staying out of reach invites a sonic boom + return s - 0.02 * view_error(sim.body, mob_centre(sim)) + + swings = [None] + if wheel == 0 and mob_reach(case, g) < 4.0: + swings += swing_slots(b) + # No crit jumps once its cooldown is nearly over: a player in the air when the smash winds up cannot back out of + # the attack box (no air control), and the smash lands after the rollout horizon (found 2026-11-03, hard seed 2). + jump_ok = g.phase in ("recover", "boom_recover") or (g.phase == "chase" and g.cd > mc4d.ticks(24)) + cands = [] + for move in MOVES: + for jump in ((), (0, 1, 2)): + if jump and (move not in ("", "W", "S") or not jump_ok): + continue + for sw in swings: + if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0): + continue + cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"])) + away = math.atan2(b.e.pos[2] - g.e.pos[2], b.e.pos[0] - g.e.pos[0]) + for off in (-0.6, 0.0, 0.6): + turn = math.degrees(wrap(away + off - b.e.yaw)) / DEG + run = lambda sim, last: build("W", sprint=True, last=last) + cands.append((build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]), run)) + return best_of(case, m, cands, warden_cont, shape, horizon=4, taken_w=24.0) + + +# ------------------------------------------------------------------------------------------- skeleton (@5) +def arrow_threat(sim): + """Boss arrows closing on the player beyond the rollout horizon.""" + p = sim.body.e.pos + [0, 0.9, 0] + pen = 0.0 + for a in getattr(sim.boss, "arrows", ()): + rel = p - a["pos"] + dist = float(np.linalg.norm(rel)) + v = a["vel"] + speed = float(np.linalg.norm(v)) + 1e-9 + if dist < 12 and float(rel @ v) / (dist * speed + 1e-9) > 0.6: + pen += max(0.0, 1.0 - float(np.linalg.norm(np.cross(rel, v / speed)))) * 2.0 + return pen + + +def skeleton_cont(sim, last): + """Continuation: when the draw is about to release, strafe across the line of fire (a Java skeleton does not lead + its target, so a side-step beats the arrow beyond ~2.5 blocks); otherwise close in (sprinting when far) and + swing on a full charge.""" + b, g = sim.body, sim.boss + dx, dy = aim_to(b, mob_centre(sim)) + if g.state == "windup" and g.timer < 0.45: + side = "A" if retreat_room(sim, -b.e.right) >= retreat_room(sim, b.e.right) else "D" + return build(side, mouse=(dx, dy), last=last) + reach = mob_reach(sim, g) + if reach > 6.0: + return build("W", sprint=True, mouse=(dx, dy), last=last) + move = "W" if reach > 2.6 else "" + swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None + return build(move, swing=swing, mouse=(dx, dy), last=last) + + +def plan_skeleton(case, m): + b, g = case.body, case.boss + wheel = weapon_wheel(case, "sword") + lead = g.e.pos + g.e.vel * TICKS * 0.5 + dx, dy = aim_to(b, mob_centre(case) + (lead - g.e.pos)) + + def shape(sim): + s_ = sim.boss + drawing = s_.state == "windup" + s = -(0.25 if drawing else 0.8) * max(0.0, mob_reach(sim, s_) - 2.6) - arrow_threat(sim) + safe_shape(sim) + return s - 0.02 * view_error(sim.body, mob_centre(sim)) + + swings = [None] + if wheel == 0 and mob_reach(case, g) < 4.0: + swings += swing_slots(b) + cands = [] + for move in MOVES: + for jump in ((), (0, 1, 2)): + if jump and move not in ("", "W"): + continue + for sw in swings: + if jump and sw is not None and not (not b.e.on_ground and b.e.vel[1] < 0): + continue + cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"])) + for jump in ((), (0, 1)): # sprint (and sprint-jump) straight at it + cands.append(build("W", jump=jump, sprint=True, mouse=(dx, dy), wheel=wheel, last=m["last"])) + if g.state == "windup": # sprint across the line of fire (5.6 b/s vs walking 4.3) + to = math.atan2(g.e.pos[2] - b.e.pos[2], g.e.pos[0] - b.e.pos[0]) + for off in (-math.pi / 2, math.pi / 2): + turn = math.degrees(wrap(to + off - b.e.yaw)) / DEG + run = lambda sim, last: build("W", sprint=True, last=last) + cands.append((build("W", sprint=True, mouse=(turn, 0), wheel=wheel, last=m["last"]), run)) + # An arrow costs more than a crit gains: Java Hard arrows (every 2 s, 4-8) out-damage natural regeneration ten to + # one, so trading hits loses any fight longer than a minute (found 2026-11-03: hard 1/3 at a weight of 10). + return best_of(case, m, cands, skeleton_cont, shape, horizon=3, taken_w=20.0) + + +# ------------------------------------------------------------------------------------------- bow helpers +def ballistic_pitch(dx_h, dy, power=1.0): + """Pitch (rad) that makes a bow arrow of this power pass (dx_h, dy) relative to the eye (vanilla physics).""" + speed = mc4d.BOW_RULES['maximum_speed_blocks_per_vanilla_tick'] * power + g, drag = mc4d.BOW_RULES['gravity_blocks_per_vanilla_tick_squared'], mc4d.BOW_RULES['drag_per_vanilla_tick'] + + def height_at(pitch): + vx, vy, x, y = speed * math.cos(pitch), speed * math.sin(pitch), 0.0, 0.0 + for n in range(200): + if x + vx >= dx_h: + u = (dx_h - x) / max(vx, 1e-9) + return y + vy * u, n + u + x, y = x + vx, y + vy + vx, vy = vx * drag, vy * drag - g + return -1e9, 200 + + lo, hi = -1.45, 1.45 + pitch = math.atan2(dy, max(dx_h, 1e-6)) + for _ in range(18): + h, _ = height_at(pitch) + if h < dy: + lo = pitch + else: + hi = pitch + pitch = (lo + hi) / 2 + return pitch, height_at(pitch)[1] + + +def bow_aim(case, point_fn, sim_future=None): + """Mouse to aim a full-power arrow at a moving point. point_fn(sim) gives the aim point in a state; + sim_future: list of (tick offset, point) predictions used for the lead.""" + b = case.body + eye = b.e.pos + [0, mc4d.EYE, 0] + point = point_fn(case) + flight = 0.0 + for _ in range(3): + target = point + if sim_future: + k = min(len(sim_future) - 1, int(round(flight / mc4d.VT)) + TICKS) + target = sim_future[k] + d = target - eye + pitch, flight = ballistic_pitch(math.hypot(d[0], d[2]), d[1]) + yaw = math.atan2(d[2], d[0]) + return math.degrees(wrap(yaw - b.e.yaw)) / DEG, -math.degrees(pitch - b.e.pitch) / DEG, target + + +def predict(case, m, point_fn, n_packets=3, move=""): + """Future aim points (per tick) if the player stands (or keeps `move`), from a clone rollout.""" + sim = clone(case) + out = [point_fn(sim)] + last = m["last"] + for _ in range(n_packets): + held = build(move, rmb="hold" if sim.body.bow_drawing else None, last=last) + sched, last = km.schedule(held, TICKS, last) + for h, p, mo in sched: + if sim.outcome(): + break + sim.tick(sim.body.keys(sim, h, p, mo)) + out.append(point_fn(sim)) + return out + + +def bow_cands(case, m, point_fn, moves=MOVES, wheel=0, extra_shape=None, allow_release=True): + """Candidates while using the bow: keep drawing (with each movement) or release at substep j.""" + b = case.body + future = predict(case, m, point_fn) + dx, dy, _ = bow_aim(case, point_fn, future) + cands = [] + full_in = max(0, int(mc4d.FPS * mc4d.BOW_RULES['draw_seconds']) - b.bow_draw_ticks) + for move in moves: + cands.append(build(move, rmb="hold", mouse=(dx, dy), wheel=wheel, last=m["last"])) + if b.bow_drawing and allow_release: + for j in range(6): + if 2 * j >= full_in: + cands.append(build(move, rmb=j, mouse=(dx, dy), wheel=wheel, last=m["last"])) + return cands, (dx, dy) + + +def bow_cont(point_fn): + def cont(sim, last): + b = sim.body + point = point_fn(sim) + eye = b.e.pos + [0, mc4d.EYE, 0] + d = point - eye + pitch, _ = ballistic_pitch(math.hypot(d[0], d[2]), d[1]) + yaw = math.atan2(d[2], d[0]) + dx, dy = math.degrees(wrap(yaw - b.e.yaw)) / DEG, -math.degrees(pitch - b.e.pitch) / DEG + full = b.bow_draw_ticks >= mc4d.FPS * mc4d.BOW_RULES['draw_seconds'] + return build("", rmb=0 if full else "hold", mouse=(dx, dy), last=last) + return cont + + +def arrow_score_horizon(case): + return 3 # arrows need ~1-3 packets to land + + +# ------------------------------------------------------------------------------------------- wither +def wither_body(sim): + g = sim.boss + return (g.hit_lo() + g.hit_hi()) / 2 + [0, 0.3, 0] + + +def skull_threat(sim): + """Penalty for skulls closing on the player (predicts hits beyond the rollout horizon).""" + p = sim.body.e.pos + [0, 0.9, 0] + pen = 0.0 + for s in sim.boss.skulls: + rel = p - s["pos"] + dist = float(np.linalg.norm(rel)) + v = s["vel"] + speed = float(np.linalg.norm(v)) + 1e-9 + closing = float(rel @ v) / (dist * speed + 1e-9) + if closing > 0.6 and dist < 8: + miss = float(np.linalg.norm(np.cross(rel, v / speed))) + pen += max(0.0, 1.2 - miss) * 3.0 + return pen + + +def plan_wither(case, m): + b, g = case.body, case.boss + if g.state == "spawn": + # run to the far side and face the wither; the power-7 blast reaches 14 blocks + wheel = weapon_wheel(case, "bow") + away = flat(b.e.pos - g.e.pos) + away /= np.linalg.norm(away) + 1e-9 + goal = np.clip(g.e.pos + away * 20.0, 2.5, mc4d.S - 2.5) + dist_goal = hdist(b.e.pos, goal) + face = goal if dist_goal > 1.5 else g.e.pos + [0, 1.0, 0] + dx, dy = aim_to(b, face + [0, mc4d.EYE if dist_goal > 1.5 else 0, 0]) + mv = "W" if dist_goal > 1.0 else "" + + def shape(sim): + return -1.5 * max(0.0, 15.5 - hdist(sim.body.e.pos, sim.boss.e.pos)) + safe_shape(sim, 0.05) + cands = [build(mv, jump=j, sprint=True, mouse=(dx, dy), wheel=wheel, last=m["last"]) for j in ((), (0, 1))] + cands += [build(k, mouse=(dx, dy), wheel=wheel, last=m["last"]) for k in ("A", "D")] + return best_of(case, m, cands, lambda sim, last: build(mv, sprint=True, mouse=(0, 0), last=last), shape) + + if g.armored: + # phase 2: sword on the ground, keep 2.2-2.8 blocks, dodge skulls + wheel = weapon_wheel(case, "sword") + point = wither_body(case) - [0, 0.6, 0] + dx, dy = aim_to(b, point) + dist = hdist(b.e.pos, g.e.pos) + + def shape(sim): + d = hdist(sim.body.e.pos, sim.boss.e.pos) + return -1.0 * abs(d - 2.5) - skull_threat(sim) + safe_shape(sim) - 0.02 * view_error(sim.body, wither_body(sim)) + swings = [None] + if wheel == 0 and dist < 4.5: + swings += swing_slots(b) + cands = [] + for move in MOVES: + for jump in ((), (0, 1, 2)): + if jump and move not in ("", "W"): + continue + for sw in swings: + cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"])) + # A skull fired from 2-3 blocks lands within a packet, before the 2-packet rollout can price a dodge, and on + # Java Hard each one carries 40 s of Wither II. When one is closing in, look 3 packets ahead and value + # health like the long fight it is (found 2026-11-02: hard-tier losses were all to skulls at melee range). + incoming = skull_threat(case) > 0.0 + return best_of(case, m, cands, greedy_melee(lambda s: wither_body(s) - [0, 0.6, 0], (2.2, 2.8)), shape, + horizon=3 if incoming else 2, taken_w=16.0 if incoming else 8.0) + + # phase 1: bow, keep 4-9 blocks horizontally, dodge skulls between draws + wheel = weapon_wheel(case, "bow") + if wheel: + dx, dy = aim_to(b, wither_body(case)) + return build("S", mouse=(dx, dy), wheel=wheel, last=m["last"]) + + def shape(sim): + d = hdist(sim.body.e.pos, sim.boss.e.pos) + eye = sim.body.e.pos + [0, mc4d.EYE, 0] + sight = 0.0 if sim.arena.los(eye, wither_body(sim), eye_h=0.0) else -2.5 + # a wither directly overhead fires straight down: keep 5-9 blocks of horizontal distance + return (-0.2 * max(0.0, d - 10) - 0.8 * max(0.0, 5.0 - d) - 0.25 * skull_threat(sim) + safe_shape(sim) + sight + + 0.05 * min(sim.body.bow_draw_ticks, 60)) + cands, _ = bow_cands(case, m, wither_body, moves=("", "A", "D", "S", "W")) + look = aim_to(b, wither_body(case)) + if not b.bow_drawing or b.bow_draw_ticks <= 15: # releasing a longer draw would waste it on a weak arrow + cands += [build(mv, mouse=look, last=m["last"]) for mv in ("A", "D", "S", "W")] + elif g.skulls: # a skull is coming: release now and sidestep at full speed + for mv in ("A", "D"): + keep = lambda sim, last, mv=mv: build(mv, mouse=aim_to(sim.body, wither_body(sim)), last=last) + cands.append((build(mv, mouse=look, last=m["last"]), keep)) + return best_of(case, m, cands, bow_cont(wither_body), shape, horizon=3) + + +# ------------------------------------------------------------------------------------------- ender dragon +def dragon_head(sim): + return sim.boss.head_center() + + +def head_reach(sim): + """Distance from the player's eye to the dragon's head box; the sword ray reaches 3.""" + h = sim.boss.head_center() + eye = sim.body.e.pos + [0, mc4d.EYE, 0] + return float(np.linalg.norm(eye - np.clip(eye, h - [0.55, 0.45, 0.55], h + [0.55, 0.45, 0.55]))) + + +def perch_cont(sim, last): + """Continuation at a perched dragon: walk into sword reach of the head (never into its contact box), step out + of a breath cloud sideways, swing on a full charge.""" + b, g = sim.body, sim.boss + h = g.head_center() + dx, dy = aim_to(b, h) + gap = max(abs(b.e.pos[0] - h[0]), abs(b.e.pos[2] - h[2])) - 1.85 + inside = [c for c in g.clouds if hdist(b.e.pos, c["pos"]) < c["r"] + 0.3] + if inside: + c = inside[0] + side = float(np.dot(flat(b.e.pos - c["pos"]), b.e.right)) + move = "D" if side >= 0 else "A" + elif gap < 0.3: + move = "S" + elif head_reach(sim) > 2.7: + move = "W" + else: + move = "" + swing = 0 if b.weapon == "sword" and charge_at(b, 0) > 0.9 and b.ray_hit(sim) is not None else None + return build(move, swing=swing, mouse=(dx, dy), last=last) + + +def dragon_body(sim): + return sim.boss.e.pos.copy() + + +def clear_shot(sim, point): + """True when the straight line from the player's eye to point crosses no terrain (a cheap proxy for the + ballistic arc, which only rises above it).""" + eye = sim.body.e.pos + [0, mc4d.EYE, 0] + wall, _ = sim._arrow_world_hit(eye, np.asarray(point, float)) + return wall is None or wall >= 0.999 + + +BLAST_SAFE = 12.5 # power-6 crystal blast reaches 12 blocks (mc4d.crystal_destroyed) + + +def crystal_dist(sim, c): + return float(np.linalg.norm(sim.body.e.pos + [0, 0.9, 0] - c["pos"])) + + +def crystal_target(case): + """Only the crystal that is shot explodes. Prefer one in the clear and already outside its blast: the healing + crystal first (breaking it also hurts the dragon), then the one nearest 13 blocks away.""" + g = case.boss + alive = [c for c in g.crystals if c["alive"]] + if not alive: + return None + p = case.body.e.pos + + def key(c): + clear = clear_shot(case, c["pos"] + [0, 0.8, 0]) + return (not clear, crystal_dist(case, c) < BLAST_SAFE, c is not g.heal_from, abs(hdist(p, c["pos"]) - 13.0), + c["id"]) + return min(alive, key=key) + + +def plan_dragon(case, m): + b, g = case.body, case.boss + sitting = g.phase in g.SITTING + clouds = g.clouds + + def cloud_pen(sim): + p = sim.body.e.pos + pen = 0.0 + for c in sim.boss.clouds: + d = hdist(p, c["pos"]) + pen += max(0.0, c["r"] + 1.0 - d) * 2.0 + for f in sim.boss.fireballs: + rel = p + [0, 0.9, 0] - f["pos"] + dist = float(np.linalg.norm(rel)) + if dist < 12: + miss = float(np.linalg.norm(np.cross(rel, f["dir"]))) + pen += max(0.0, 3.5 - miss) * 0.8 + return pen + + if sitting and g.phase != "landing": + # perched: sword on the head (full damage). The perched dragon keeps turning to face the player, so the + # head is always attacked from the front: inside sword reach, outside the head's contact box, and out of the + # breath cloud it drops in front of its head (the cloud stays where it fell; a sidestep leaves it). + wheel = weapon_wheel(case, "sword") + head = g.head_center() + dx, dy = aim_to(b, head) + + def shape(sim): + h = sim.boss.head_center() + p = sim.body.e.pos + gap = max(abs(p[0] - h[0]), abs(p[2] - h[2])) - 1.85 # > 0: outside the contact box + return (-1.5 * max(0.0, head_reach(sim) - 2.6) - cloud_pen(sim) - 0.03 * view_error(sim.body, h) + - 12.0 * max(0.0, 0.25 - gap)) + swings = [None] + if wheel == 0 and head_reach(case) < 3.6: + swings += swing_slots(b) + cands = [] + for move in MOVES: + for jump in ((), (0, 1, 2)): + if jump and move not in ("", "W"): + continue + for sw in swings: + cands.append(build(move, jump=jump, swing=sw, mouse=(dx, dy), wheel=wheel, last=m["last"])) + return best_of(case, m, cands, perch_cont, shape, horizon=3) + + danger = any(hdist(b.e.pos, c["pos"]) < c["r"] + 0.6 for c in clouds) or any( + _fireball_lands_near(case, f) for f in g.fireballs) + if danger: + return flee(case, m, cloud_pen) + if g.phase == "strafe" and g.goal is not None: + return lineup_dodge(case, m, cloud_pen) + wheel = weapon_wheel(case, "bow") + crystal = crystal_target(case) + if crystal is not None: + point_fn = lambda sim, cid=crystal["id"]: sim.boss.crystals[cid]["pos"] + [0, 0.8, 0] + want = 13.0 + else: + point_fn = dragon_head + want = 9.0 + if wheel: + dx, dy = aim_to(b, point_fn(case)) + return build("", mouse=(dx, dy), wheel=wheel, last=m["last"]) + + def shape(sim): + s = -cloud_pen(sim) + safe_shape(sim) + if crystal is not None: + c = sim.boss.crystals[crystal["id"]] + s -= 0.3 * abs(hdist(sim.body.e.pos, c["pos"]) - want) + s -= 3.0 * max(0.0, BLAST_SAFE - crystal_dist(sim, c)) + if not clear_shot(sim, point_fn(sim)): # a draw held at a hidden crystal is wasted time + s -= 3.0 + else: + s -= 0.1 * abs(hdist(sim.body.e.pos, [mc4d.MID, 0, mc4d.MID]) - 6.0) + return s + too_close = crystal is not None and crystal_dist(case, crystal) < BLAST_SAFE + cands, _ = bow_cands(case, m, point_fn, allow_release=not too_close) + if too_close: # run out of the power-6 blast before shooting: 8 headings + cands = [] + for k in range(8): + turn = math.degrees(wrap(2 * math.pi * k / 8 - b.e.yaw)) / DEG + run = lambda sim, last: build("W", sprint=True, last=last) + cands.append((build("W", sprint=True, mouse=(turn, 0), last=m["last"]), run)) + return best_of(case, m, cands, None, shape, horizon=2) + return best_of(case, m, cands, bow_cont(point_fn), shape, horizon=3) + + +def _fireball_lands_near(case, f, radius=3.6): + p = case.body.e.pos + rel = p + [0, 0.9, 0] - f["pos"] + along = float(rel @ f["dir"]) + if along < 0 or along > 14: + return False + return float(np.linalg.norm(rel - f["dir"] * along)) < radius + + +def flee(case, m, penalty): + """Sprint out of a hazard: 8 headings, continuation keeps running; bow draw is dropped.""" + b = case.body + cands = [] + for k in range(8): + yaw = 2 * math.pi * k / 8 + dx = math.degrees(wrap(yaw - b.e.yaw)) / DEG + cands.append(build("W", jump=(0, 1) if k % 2 else (), sprint=True, mouse=(dx, 0), last=m["last"])) + return best_of(case, m, cands, lambda sim, last: build("W", sprint=True, last=last), + lambda sim: -2.0 * penalty(sim) + safe_shape(sim), horizon=3) + + +def lineup_dodge(case, m, penalty): + """The dragon is lining up a fireball (mouth glow, HUD flash): the shot goes where the player stands when it + fires and its cloud is 3 blocks wide, so drop the draw and sprint across the dragon's line of approach.""" + b, g = case.body, case.boss + p0 = b.e.pos.copy() + line = flat(p0 - g.e.pos) + line /= float(np.linalg.norm(line)) + 1e-9 + + def shape(sim): + moved = flat(sim.body.e.pos - p0) + across = abs(moved[0] * line[2] - moved[2] * line[0]) + return 2.0 * min(across, 4.0) - 2.0 * penalty(sim) + safe_shape(sim) + cands = [] + for k in range(8): + dx = math.degrees(wrap(2 * math.pi * k / 8 - b.e.yaw)) / DEG + cands.append(build("W", jump=(0, 1) if k % 2 else (), sprint=True, mouse=(dx, 0), last=m["last"])) + return best_of(case, m, cands, lambda sim, last: build("W", sprint=True, last=last), shape, horizon=3) + + +PLANNERS = {"iron_golem": plan_golem, "zombie": plan_zombie, "ender_dragon": plan_dragon, "wither": plan_wither, + "warden": plan_warden, "skeleton": plan_skeleton, "zombie_leader": plan_zombie_leader} + + +# ------------------------------------------------------------------------------------------- self-check +def play(mob, seed=1, d=0.5, weapon="sword", max_packets=None, verbose=False): + """Run the controller on a bare MobFight (no renderer) to the terminal outcome; for quick tuning.""" + case = mc4d.MobFight(mob, style=mc4d.STYLES[mob], weapon=weapon, max_seconds=mc4d.SECONDS[mob]) + case.reset(seed, d) + last = frozenset() + limit = max_packets or int(mc4d.SECONDS[mob] * 5) + for i in range(limit): + p = km.parse_packet(scripted(case)) + assert p is not None + case.events.clear() + last = run_packet(case, p, last) + if verbose and i % 25 == 0: + print(i, case.boss.state, round(case.boss.hp, 1), round(case.body.hp, 1), case.body.weapon) + if case.outcome(): + break + return {"mob": mob, "seed": seed, "d": d, "weapon": weapon, "outcome": case.outcome() or "timeout", + "seconds": round(case.t / mc4d.FPS, 2), "boss_hp": round(float(case.boss.hp), 1), + "player_hp": round(float(case.body.hp), 1)} diff --git a/environments/games/prototype/bossbench/mcskin.py b/environments/games/prototype/bossbench/mcskin.py new file mode 100644 index 0000000000000000000000000000000000000000..4debe08dab0baba3afb5c74d5222ffa01fb76f98 --- /dev/null +++ b/environments/games/prototype/bossbench/mcskin.py @@ -0,0 +1,1885 @@ +"""Minecraft skin for mc4d: textures, rigs, per-state poses, particles, renderer and HUD. + +Everything here is drawing. Pose functions read simulation state and write only to the rig +(keyframes and rig.mem); particle helpers draw from case.fxrng; nothing reads or advances +case.rng, so drawing cannot change an episode’s simulation state. + +Borrowed from the 2D web client (web/games/hollowknight_remake/draw/wanderer.js + web/engine/renderer.js): + * one pose table per boss state, with anticipation / follow-through keyed to state entry + * a white hit flash that hands over to the red hurt tint + * telegraph glow (eyes, mouth) and an additive halo pass for emissive parts + * event-driven juice (sparks, dust, smoke) on its own random stream + * a static world baked once (terrain instances), only actors re-uploaded per frame +""" +from __future__ import annotations + +import math +import os + +import numpy as np + +from .core import FPS +from .rig import Bones, Rig, q_to_mat + +# Pose and particle constants below were tuned per vanilla Minecraft tick (20 Hz). The simulation ticks at +# core.FPS; keyframes stay in simulation ticks, everything time-based is read through VT so animation, +# fades and particle drift run at the same speed in seconds whatever the tick rate. +VT = 20 / FPS + + +def _every(case, n): + """True once every n vanilla ticks (spawn cadence independent of the tick rate).""" + return case.t % max(1, round(n / VT)) == 0 + + +def ticks_hit(mob): + """A mob's tint_t right after a fresh hit (mc4d sets ticks(8)): picks the minion hurt this very tick.""" + return round(8 / VT) + +# ================================================================ textures +# 16x16 RGBA tiles in one texture array. Faces are 8x8 Minecraft-style pixel art doubled, the +# rest is procedural noise from a fixed generator (visual only, built once at import). +_TR = np.random.default_rng(20261012) +TILES: dict = {} +_LAYERS: list = [] + + +def _c(*rgb): + return np.array(rgb, float) + + +def _tile(name, img): + img = np.clip(np.asarray(img, float), 0, 1) + if img.shape[2] == 3: + img = np.concatenate([img, np.ones((16, 16, 1))], 2) + TILES[name] = len(_LAYERS) + _LAYERS.append((img * 255).astype(np.uint8)) + + +def _noise(base, amt=0.08): + return np.broadcast_to(base, (16, 16, 3)) * (1 + _TR.normal(0, amt, (16, 16, 1))) + + +def _art(rows, pal, amt=0.05): + """Rows of palette chars -> 16x16 rgba ('_' transparent); art narrower than 16 is scaled up.""" + h, w = len(rows), len(rows[0]) + img = np.zeros((h, w, 4)) + for y, row in enumerate(rows): + for x, ch in enumerate(row): + if ch != "_": + img[y, x, :3], img[y, x, 3] = pal[ch], 1 + img = img.repeat(16 // h, 0).repeat(16 // w, 1) + img[..., :3] *= 1 + _TR.normal(0, amt, (16, 16, 1)) + return img + + +def _rgba(rgb, a): + return np.concatenate([rgb, a[..., None]], 2) + + +def _bricks(base, mortar, h=4, w=8, amt=0.07): + img = _noise(base, amt).copy() + for y in range(16): + off = (w // 2) * ((y // h) % 2) + for x in range(16): + if y % h == h - 1 or (x + off) % w == w - 1: + img[y, x] = mortar * (1 + _TR.normal(0, 0.05)) + return img + + +def _cells(base, edge, n=9, amt=0.09): + """Cobblestone: wrapped Voronoi cells, one shade per cell, dark borders.""" + pts = _TR.uniform(0, 16, (n, 2)) + yy, xx = np.mgrid[0:16, 0:16] + 0.5 + d = np.stack([np.hypot(np.minimum(abs(xx - px), 16 - abs(xx - px)), + np.minimum(abs(yy - py), 16 - abs(yy - py))) for px, py in pts]) + near = np.argmin(d, 0) + ds = np.sort(d, 0) + shade = (1 + _TR.normal(0, 0.13, n))[near] + img = _noise(base, amt) * shade[..., None] + img[(ds[1] - ds[0]) < 1.1] = edge + return img + + +def _specks(img, color, k=10): + img = img.copy() + for _ in range(k): + x, y = _TR.integers(0, 16, 2) + img[y, x] = color + return img + + +def _cracks(n): + a = np.zeros((16, 16, 4)) + for _ in range(n): + x, y = (int(v) for v in _TR.integers(1, 15, 2)) + for _ in range(int(_TR.integers(4, 9))): + a[y, x] = (0.28, 0.26, 0.25, 1.0) + x = int(np.clip(x + _TR.integers(-1, 2), 0, 15)) + y = int(np.clip(y + _TR.choice([-1, 1]), 0, 15)) + return a + + +def TEX_FLIP(layer): + """A built tile mirrored left-right, back as float rgba.""" + return layer[:, ::-1].astype(float) / 255 + + +def _build_tiles(): + yy, xx = np.mgrid[0:16, 0:16] + 0.5 + r = np.hypot(xx - 8, yy - 8) / 8 + # -- terrain ---------------------------------------------------------- + grass, dirt = _c(0.45, 0.68, 0.3), _c(0.55, 0.39, 0.26) + _tile("grass_top", _specks(_noise(grass, 0.11), grass * 0.78, 20)) + side = _specks(_noise(dirt, 0.1), dirt * 0.7, 14) + for x in range(16): + dd = 3 + int(_TR.integers(0, 3)) + side[:dd, x] = grass * (0.9 + _TR.normal(0, 0.07, (dd, 1))) + _tile("grass_side", side) + _tile("dirt", _specks(_noise(dirt, 0.1), dirt * 0.7, 18)) + _tile("stone", _specks(_noise(_c(0.52, 0.52, 0.52), 0.07), _c(0.41, 0.41, 0.42), 22)) + _tile("cobble", _cells(_c(0.53, 0.53, 0.53), _c(0.3, 0.3, 0.31))) + _tile("stone_brick", _bricks(_c(0.5, 0.5, 0.5), _c(0.33, 0.33, 0.34), 8, 16)) + moss = _cells(_c(0.5, 0.5, 0.5), _c(0.3, 0.3, 0.31)) + mask = _TR.random((16, 16)) < 0.32 + moss[mask] = _noise(_c(0.33, 0.46, 0.22), 0.12)[mask] + _tile("mossy_cobble", moss) + es = _c(0.87, 0.88, 0.64) + _tile("end_stone", _specks(_noise(es, 0.06), es * 0.84, 28)) + _tile("end_brick", _bricks(es, es * 0.72, 4, 8, 0.05)) + obs = _noise(_c(0.08, 0.06, 0.12), 0.22).copy() + for _ in range(7): + x, y = _TR.integers(0, 15, 2) + obs[y, x:x + 2] = _c(0.26, 0.13, 0.36) + _tile("obsidian", obs) + _tile("bedrock", _cells(_c(0.34, 0.34, 0.34), _c(0.12, 0.12, 0.12), 14, 0.2)) + # -- misc ------------------------------------------------------------- + _tile("shadow", _rgba(np.zeros((16, 16, 3)), np.clip(1 - r, 0, 1) ** 1.2 * 0.85)) + sw = (np.sin((xx + yy) * 0.8) * 0.5 + 0.5) * (np.sin((xx - yy) * 0.45 + 1) * 0.5 + 0.5) + _tile("shell", _rgba(np.stack([sw * 0.5 + 0.35, sw * 0.5 + 0.55, np.ones_like(sw)], 2), 0.3 + 0.7 * sw)) + _tile("white", np.ones((16, 16, 3))) + _tile("glow", _rgba(np.ones((16, 16, 3)), np.clip(1 - r, 0, 1) ** 1.6)) + _tile("puff", _rgba(np.ones((16, 16, 3)) * (0.85 + 0.15 * (1 - r))[..., None], + (np.clip(1.15 - r, 0, 1) > 0.25 + 0.2 * _TR.random((16, 16))).astype(float))) + for i in (1, 2, 3): + _tile(f"crack{i}", _cracks(3 * i)) + # -- iron golem ------------------------------------------------------- + iron, idark = _c(0.87, 0.85, 0.81), _c(0.63, 0.61, 0.58) + vine, vdark = _c(0.32, 0.52, 0.2), _c(0.2, 0.36, 0.13) + + def iron_t(rivets=True, vine_col=None): + t = _specks(_noise(iron, 0.05), idark, 16) + if rivets: + for x, y in ((2, 2), (13, 2), (2, 13), (13, 13)): + t[y, x], t[y - 1, x] = idark * 0.85, iron * 1.08 + if vine_col is not None: + x = vine_col + for y in range(16): + x = int(np.clip(x + _TR.integers(-1, 2), 0, 14)) + t[y, x:x + 2] = (vine if _TR.random() < 0.7 else vdark) * (1 + _TR.normal(0, 0.1)) + if _TR.random() < 0.4: + t[y, int(np.clip(x + _TR.choice([-1, 2]), 0, 15))] = vine * 1.2 + return t + _tile("iron", iron_t()) + _tile("iron_plain", iron_t(False)) + _tile("iron_vine", iron_t(True, 5)) + _tile("iron_chest", iron_t(True, 11)) + P = {".": iron, ":": idark, "#": _c(0.46, 0.44, 0.42), "r": _c(0.8, 0.12, 0.1), "k": _c(0.2, 0.19, 0.19), + "m": _c(0.52, 0.5, 0.47)} + _tile("golem_face", _art(["..:.....", "........", "########", ".kr..rk.", "........", + "........", "..mmmm..", ".:....:."], P, 0.04)) + _tile("golem_hand", _noise(idark, 0.06)) + # -- zombie / steve --------------------------------------------------- + Z = {"g": _c(0.36, 0.6, 0.32), "d": _c(0.24, 0.43, 0.22), "k": _c(0.05, 0.06, 0.05), + "n": _c(0.27, 0.45, 0.25), "m": _c(0.16, 0.26, 0.15)} + _tile("zombie_face", _art(["dgdddgdd", "gdgggdgg", "gggggggg", "gggggggg", "gkkggkkg", + "gggnnggg", "ggmmmmgg", "gggggggg"], Z, 0.05)) + _tile("zombie_head", _art(["dgdddgdd", "gdgggdgg", "gggdgggg", "gggggggg", "ggggggdg", + "gdgggggg", "gggggdgg", "gggggggg"], Z, 0.06)) + _tile("zombie_skin", _noise(Z["g"], 0.07)) + teal, tdark = _c(0.0, 0.62, 0.62), _c(0.0, 0.46, 0.48) + T = {"t": teal, "u": tdark, "g": Z["g"], "b": _c(0.27, 0.25, 0.62), "v": _c(0.2, 0.18, 0.48), + "s": _c(0.36, 0.36, 0.4)} + _tile("zombie_shirt", _art(["tttttttt", "tttutttt", "tttttttt", "tutttttt", "tttttutt", + "tttttttt", "ttttttut", "uutuuttu"], T, 0.06)) + _tile("zombie_arm", _art(["tttt", "tuuu", "gggg", "gggg", "gggg", "gggg", "gggg", "gggg"], T, 0.06)) + _tile("zombie_leg", _art(["bbbb", "bbvb", "bbbb", "bvbb", "bbbb", "bbbb", "vbbv", "ssss"], T, 0.06)) + skin, hair = _c(0.78, 0.58, 0.44), _c(0.3, 0.2, 0.12) + S_ = {"h": hair, "s": skin, "w": _c(0.95, 0.95, 0.95), "b": _c(0.3, 0.25, 0.62), "n": _c(0.62, 0.42, 0.3), + "m": _c(0.45, 0.27, 0.17), "t": teal, "u": tdark, "p": _c(0.25, 0.23, 0.6), "q": _c(0.2, 0.18, 0.5), + "o": _c(0.42, 0.42, 0.44)} + _tile("steve_face", _art(["hhhhhhhh", "hhhhhhhh", "hssssssh", "ssssssss", "swbssbws", + "sssnnsss", "ssmmmmss", "ssssssss"], S_, 0.03)) + _tile("steve_side", _art(["hhhhhhhh", "hhhhhhhh", "hhhhhhss", "hhhhssss", "hhhsssss", + "hhssssss", "hsssssss", "ssssssss"], S_, 0.04)) + _tile("steve_hair", _noise(hair, 0.08)) + _tile("steve_shirt", _art(["tttttttt", "tttttttt", "ttuttutt", "tttttttt", "tttttttt", + "tttttttt", "tttttttt", "uuuuuuuu"], S_, 0.04)) + _tile("steve_arm", _art(["tttt", "tttt", "uuuu", "ssss", "ssss", "ssss", "ssss", "ssss"], S_, 0.04)) + _tile("steve_leg", _art(["pppp", "pppp", "pqpp", "pppp", "pppp", "ppqp", "oooo", "oooo"], S_, 0.04)) + _tile("steve_skin", _noise(skin, 0.04)) + B = {"_": None, "w": _c(0.62, 0.9, 0.95), "l": _c(0.85, 1.0, 1.0), "d": _c(0.2, 0.55, 0.6), + "h": _c(0.42, 0.29, 0.16), "k": _c(0.25, 0.17, 0.1)} + _tile("sword", _art(["____________lw__", "___________lwd__", "__________lwd___", "_________lwd____", + "________lwd_____", "_______lwd______", "______lwd_______", "__d__lwd________", + "___dlwd_________", "____dd__________", "___hkd__________", "__hk_dd_________", + "_hk_____________", "kh______________", "k_______________", "________________"], + {k: v for k, v in B.items() if v is not None}, 0.02)) + _tile("sword_m", TEX_FLIP(_LAYERS[TILES["sword"]])) + _tile("eye_pair", _art(["_ww__ww_"], {"w": _c(1, 1, 1)}, 0.0)) + # -- ender dragon ----------------------------------------------------- + sc, sc2 = _c(0.14, 0.13, 0.16), _c(0.22, 0.21, 0.25) + scale = _noise(sc, 0.12).copy() + for y in range(16): + for x in range(16): + o = (x + 2 * ((y // 4) % 2)) % 4 + if y % 4 == 3 and o != 0: + scale[y, x] = sc * 0.55 + elif y % 4 == 0: + scale[y, x] = sc2 + _tile("dragon_scale", scale) + _tile("dragon_belly", _bricks(_c(0.25, 0.23, 0.27), _c(0.14, 0.13, 0.16), 4, 16, 0.08)) + D = {"s": sc, "d": sc * 0.5, "k": _c(0.02, 0.02, 0.03), "l": sc2, "t": _c(0.66, 0.64, 0.58)} + _tile("dragon_snout", _art(["llllllll", "skksskks", "ssssssss", "sdssssds", "ssssssss", + "tststtst", "ssssssss", "dddddddd"], D, 0.08)) + _tile("dragon_jaw", _art(["tstststs", "ssssssss", "ssssssss", "sdssssds", "ssssssss", + "ssssssss", "ssssssss", "dddddddd"], D, 0.08)) + _tile("dragon_spike", _noise(_c(0.3, 0.29, 0.33), 0.1)) + mem, rib = _c(0.2, 0.17, 0.24), _c(0.36, 0.33, 0.39) + m = _noise(mem, 0.12).copy() + a = np.ones((16, 16)) + for x in range(16): + k = min(abs(x - 1), abs(x - 8), abs(x - 15)) + if k == 0: + m[:, x] = rib * (1 + _TR.normal(0, 0.06, (16, 1))) + else: # scalloped trailing edge between ribs + cut = int(k * 1.1 + 0.5) + a[16 - cut:, x] = 0 + m[0:2] = rib + _tile("wing_membrane", _rgba(m, a)) + _tile("wing_bone", _noise(rib * 0.9, 0.06)) + # -- wither ----------------------------------------------------------- + ch, cd = _c(0.21, 0.21, 0.22), _c(0.12, 0.12, 0.13) + W = {"c": ch, "d": cd, "k": _c(0.02, 0.02, 0.02), "w": _c(0.4, 0.39, 0.38), "l": _c(0.28, 0.28, 0.29)} + _tile("wither_face", _art(["cccccccc", "cdcclcdc", "cccccccc", "ckkcckkc", "ckkcckkc", + "ccckkccc", "ckwkwkwc", "cdccccdc"], W, 0.06)) + _tile("wither_skull", _art(["cccccccc", "cdcclccc", "ccccccdc", "clcccccc", "ccccdccc", + "cccccccl", "cdcccccc", "cccccccc"], W, 0.07)) + _tile("wither_bone", _bricks(_c(0.25, 0.25, 0.26), cd, 4, 16, 0.08)) + _tile("wither_eye", _art(["kkkk", "krrk", "krrk", "kkkk"], {"k": _c(0.02, 0.02, 0.02), "r": _c(1.0, 1.0, 1.0)}, 0.0)) + # -- minecraft-arena@5: night field, deep dark, ruins; warden, skeleton, leader zombie --------------- + _build_tiles_arena5(yy, xx, r) + + +def _build_tiles_arena5(yy, xx, r): + """Original 16x16 pixel art for the scenes added in minecraft-arena@5 (appended after the @4 layers, so every + earlier layer keeps its index and its random draws).""" + # -- terrain ---------------------------------------------------------- + ngrass, ndirt = _c(0.26, 0.42, 0.24), _c(0.36, 0.27, 0.2) + _tile("night_grass", _specks(_noise(ngrass, 0.1), ngrass * 0.75, 20)) + side = _specks(_noise(ndirt, 0.1), ndirt * 0.7, 14) + for x in range(16): + dd = 3 + int(_TR.integers(0, 3)) + side[:dd, x] = ngrass * (0.9 + _TR.normal(0, 0.07, (dd, 1))) + _tile("night_grass_side", side) + _tile("night_dirt", _specks(_noise(ndirt, 0.1), ndirt * 0.7, 18)) + ds, dsd = _c(0.21, 0.21, 0.24), _c(0.14, 0.14, 0.17) + deep = _noise(ds, 0.08).copy() + for y in range(16): # deepslate: horizontal strata + if y % 4 == 3: + deep[y] = dsd * (1 + _TR.normal(0, 0.06, (16, 1))) + _tile("deepslate", deep) + _tile("deepslate_tiles", _bricks(ds * 1.05, dsd * 0.8, 8, 8, 0.07)) + sk, skd = _c(0.04, 0.12, 0.16), _c(0.02, 0.06, 0.09) + sculk = _noise(sk, 0.18).copy() + for _ in range(9): # glowing veins + x, y = (int(v) for v in _TR.integers(0, 16, 2)) + for _ in range(int(_TR.integers(3, 7))): + sculk[y, x] = _c(0.05, 0.45, 0.5) * (1 + _TR.normal(0, 0.1)) + x = int(np.clip(x + _TR.integers(-1, 2), 0, 15)) + y = int(np.clip(y + _TR.integers(-1, 2), 0, 15)) + _tile("sculk", sculk) + _tile("sculk_dark", _specks(_noise(skd, 0.2), _c(0.03, 0.25, 0.3), 12)) + sb, sbm = _c(0.47, 0.47, 0.46), _c(0.3, 0.3, 0.31) + cracked = _bricks(sb, sbm, 8, 16) + for _ in range(3): + x, y = (int(v) for v in _TR.integers(1, 15, 2)) + for _ in range(int(_TR.integers(3, 6))): + cracked[y, x] = sbm * 0.8 + x = int(np.clip(x + _TR.choice([-1, 1]), 0, 15)) + y = int(np.clip(y + _TR.integers(0, 2), 0, 15)) + _tile("cracked_brick", cracked) + mossy = _bricks(sb, sbm, 8, 16).copy() + mask = _TR.random((16, 16)) < 0.28 + mossy[mask] = _noise(_c(0.3, 0.43, 0.2), 0.12)[mask] + _tile("mossy_brick", mossy) + gravel = _cells(_c(0.5, 0.47, 0.45), _c(0.36, 0.34, 0.33), 18, 0.12) + _tile("gravel", gravel) + # -- warden ----------------------------------------------------------- + # brighter than the deep-dark floor on purpose: a benchmark boss must stay readable in its own arena + wb, wd, wt = _c(0.13, 0.33, 0.40), _c(0.07, 0.19, 0.24), _c(0.45, 0.88, 0.9) + W = {"b": wb, "d": wd, "t": wt, "k": _c(0.01, 0.03, 0.05), "c": _c(0.75, 1.0, 1.0), "m": _c(0.2, 0.45, 0.5)} + _tile("warden_face", _art(["dbbbbbbd", "bbmbbmbb", "bbbbbbbb", "bkkbbkkb", "bbbbbbbb", + "bktttkbb", "bbktkbbb", "dbbbbbbd"], W, 0.06)) + _tile("warden_skin", _specks(_noise(wb, 0.1), wd, 18)) + chest = _specks(_noise(wb, 0.1), wd, 10).copy() + for y in range(4, 12): + for x in range(4, 12): + q = abs(x - 7.5) + abs(y - 7.5) + if q < 3.2: + chest[y, x] = wt * (1.15 - q * 0.12) # the glowing soul core in the ribcage + elif q < 4.2: + chest[y, x] = _c(0.02, 0.06, 0.08) + _tile("warden_chest", chest) + _tile("warden_rib", _art(["bdbdbdbd", "dddddddd", "bdbdbdbd", "dddddddd", "bdbdbdbd", + "dddddddd", "bdbdbdbd", "dddddddd"], W, 0.08)) + _tile("warden_horn", _art(["cccc", "ctct", "cccc", "tctc"], W, 0.04)) + # -- skeleton --------------------------------------------------------- + bone, bdark = _c(0.78, 0.77, 0.72), _c(0.55, 0.54, 0.5) + K = {"w": bone, "d": bdark, "k": _c(0.08, 0.08, 0.08), "g": _c(0.38, 0.37, 0.35)} + _tile("skeleton_face", _art(["wwwwwwww", "wdwwwwdw", "wwwwwwww", "wkkwwkkw", "wwwgwwww", + "wwwkkwww", "wkwkwkww", "wwwwwwww"], K, 0.05)) + _tile("skeleton_head", _art(["wwwwwwww", "wdwwwwww", "wwwwwdww", "wwwwwwww", "wwdwwwww", + "wwwwwwdw", "wwwwwwww", "wdwwwwww"], K, 0.06)) + _tile("skeleton_rib", _art(["wwwwwwww", "kwkkkkwk", "wwwwwwww", "kwkkkkwk", "wwwwwwww", + "kkkwwkkk", "kkkwwkkk", "kkkwwkkk"], K, 0.05)) + _tile("skeleton_bone", _art(["wwww", "wdww", "wwww", "wwdw", "wwww", "wwww", "wdww", "wwww"], K, 0.05)) + ir, ird = _c(0.78, 0.78, 0.78), _c(0.56, 0.56, 0.58) + _tile("iron_armor", _specks(_noise(ir, 0.05), ird, 14)) + # -- leader zombie: a darker, torn variant (the reinforcements keep the plain zombie skin) ----- + Z = {"g": _c(0.3, 0.52, 0.28), "d": _c(0.2, 0.36, 0.18), "k": _c(0.05, 0.06, 0.05), + "n": _c(0.24, 0.4, 0.22), "m": _c(0.45, 0.08, 0.06), "r": _c(0.85, 0.15, 0.1)} + _tile("zombie_leader_face", _art(["dgdddgdd", "gdgggdgg", "gggggggg", "gddggddg", "grkggkrg", + "gggnnggg", "gmmmmmmg", "gggggggg"], Z, 0.05)) + + +_build_tiles() +TEX = np.stack(_LAYERS) # (n, 16, 16, 4) uint8 + + +# ================================================================ rig building +# A part: size, a face spec (tile names for +x front, sides, top, bottom), the pivot inside its +# bone frame, flags. "glow" parts are emissive and get the additive halo; "alpha" parts are +# blended after the opaque pass. +def part(size, front, side=None, top=None, bottom=None, pivot=(0, 0, 0), color=(1, 1, 1), glow=0.0, + alpha=False, crack=False, back=None): + side = side or front + top = top or side + return {"size": tuple(size), "color": tuple(color), "pivot": tuple(pivot), + "tiles": (front, side, top, bottom or top, back or side), "glow": glow, "alpha": alpha, + "crack": crack} + + +BOW_PARTS = ("bow_grip", "bow_upper_inner", "bow_upper_outer", "bow_lower_inner", + "bow_lower_outer", "bow_string_upper", "bow_string_lower", + "bow_nocked_arrow", "bow_nocked_tip") + + +def steve_rig(): + sp, sk = "steve_shirt", "steve_skin" + parts = { + "head": part((0.5, 0.5, 0.5), "steve_face", "steve_side", "steve_hair", sk, (0, 0.25, 0), back="steve_hair"), + "torso": part((0.25, 0.75, 0.5), sp, sp, sp, sp), + "arm_r": part((0.25, 0.75, 0.25), "steve_arm", "steve_arm", "steve_shirt", sk, (0, -0.31, 0)), + "arm_l": part((0.25, 0.75, 0.25), "steve_arm", "steve_arm", "steve_shirt", sk, (0, -0.31, 0)), + "sword": part((0.03, 0.95, 0.95), "sword", "sword", "sword", "sword", (0, 0.21, 0.33), back="sword_m"), + "leg_r": part((0.25, 0.75, 0.25), "steve_leg", "steve_leg", "steve_leg", "steve_leg", (0, -0.375, 0)), + "leg_l": part((0.25, 0.75, 0.25), "steve_leg", "steve_leg", "steve_leg", "steve_leg", (0, -0.375, 0)), + } + # Actual articulated limbs and string, rather than a weapon icon. These + # parts are hidden for the original sword loadout and use existing tiles. + for name in BOW_PARTS: + string = "string" in name + arrow = "nocked" in name + color = (0.90, 0.88, 0.78) if string else (0.42, 0.26, 0.10) + if name == "bow_nocked_tip": + color = (0.65, 0.65, 0.62) + width = 0.015 if string else 0.028 if arrow else 0.055 + parts[name] = part((0.1, width, width), "white", color=color) + rig = Rig(parts) + rig.hide.update(BOW_PARTS) + return rig + + +def golem_rig(): + """Vanilla proportions in pixels/16: legs 6x16x5, waist 9x5x6, chest 18x12x11, head 8x10x8, arms 4x30x6.""" + I, V = "iron", "iron_vine" + return Rig({ + "leg_l": part((0.31, 1.0, 0.375), I, I, I, "iron_plain", (0, -0.5, 0), crack=True), + "leg_r": part((0.31, 1.0, 0.375), V, V, I, "iron_plain", (0, -0.5, 0), crack=True), + "waist": part((0.375, 0.31, 0.56), "iron_plain", I, I, I, (0, 0.155, 0), crack=True), + "chest": part((0.69, 0.75, 1.125), "iron_chest", I, I, I, (0, 0.375, 0), crack=True), + "head": part((0.5, 0.62, 0.5), "golem_face", "iron_plain", "iron_plain", pivot=(0.08, 0.31, 0), crack=True), + "nose": part((0.125, 0.25, 0.125), "iron_plain", pivot=(0.06, 0, 0)), + "eyes": part((0.02, 0.078, 0.5), "eye_pair", color=(1.0, 0.25, 0.15), glow=1.0), + "arm_l": part((0.375, 1.875, 0.25), I, I, I, "golem_hand", (0, -0.88, 0), crack=True), + "arm_r": part((0.375, 1.875, 0.25), V, V, I, "golem_hand", (0, -0.88, 0), crack=True), + "flower": part((0.04, 0.22, 0.22), "white", color=(0.9, 0.2, 0.22), pivot=(0.04, 0, 0)), + }) + + +def zombie_rig(leader=False): + face = "zombie_leader_face" if leader else "zombie_face" + return Rig({ + "head": part((0.5, 0.5, 0.5), face, "zombie_head", "zombie_head", pivot=(0, 0.25, 0)), + "torso": part((0.25, 0.75, 0.5), "zombie_shirt", "zombie_shirt", "zombie_shirt", "zombie_leg"), + "arm_l": part((0.25, 0.75, 0.25), "zombie_arm", "zombie_arm", "zombie_shirt", "zombie_skin", (0, -0.31, 0)), + "arm_r": part((0.25, 0.75, 0.25), "zombie_arm", "zombie_arm", "zombie_shirt", "zombie_skin", (0, -0.31, 0)), + "leg_l": part((0.25, 0.75, 0.25), "zombie_leg", pivot=(0, -0.375, 0)), + "leg_r": part((0.25, 0.75, 0.25), "zombie_leg", pivot=(0, -0.375, 0)), + }) + + +def warden_rig(): + """Vanilla proportions (pixels/16): body 18x21x11, head 16x16x10, arms 8x28x8, legs 6x13x6; 2.9 tall; two + 'tendril' horns that flare with the heartbeat, and the glowing soul core in the chest.""" + S, R = "warden_skin", "warden_rib" + return Rig({ + "leg_l": part((0.375, 0.81, 0.375), S, pivot=(0, -0.405, 0)), + "leg_r": part((0.375, 0.81, 0.375), S, pivot=(0, -0.405, 0)), + "body": part((0.69, 1.31, 1.125), "warden_chest", R, S, S, (0, 0.655, 0), back=R), + "core": part((0.04, 0.5, 0.5), "white", color=(0.5, 1.0, 1.0), glow=0.6, pivot=(0.36, 0.75, 0)), + "head": part((0.625, 1.0, 1.0), "warden_face", S, S, S, (0.06, 0.5, 0)), + "horn_l": part((0.08, 0.6, 0.55), "warden_horn", color=(0.7, 1.0, 1.0), glow=0.3, pivot=(0, 0.28, 0)), + "horn_r": part((0.08, 0.6, 0.55), "warden_horn", color=(0.7, 1.0, 1.0), glow=0.3, pivot=(0, 0.28, 0)), + "arm_l": part((0.5, 1.75, 0.5), S, pivot=(0, -0.82, 0)), + "arm_r": part((0.5, 1.75, 0.5), S, pivot=(0, -0.82, 0)), + }) + + +def skeleton_rig(): + """Vanilla proportions: head 8x8x8, body 8x12x4, thin 2-pixel limbs; a bow in the left hand and an iron + chestplate/helmet (the BossBench boss wears armour).""" + B, H = "skeleton_bone", "skeleton_head" + parts = { + "head": part((0.5, 0.5, 0.5), "skeleton_face", H, H, pivot=(0, 0.25, 0)), + "helmet": part((0.56, 0.2, 0.56), "iron_armor", pivot=(0, 0.42, 0)), + "torso": part((0.25, 0.75, 0.5), "skeleton_rib", "skeleton_rib", B, B), + "chestplate": part((0.3, 0.5, 0.56), "iron_armor", pivot=(0, 0.12, 0)), + "arm_l": part((0.125, 0.75, 0.125), B, pivot=(0, -0.31, 0)), + "arm_r": part((0.125, 0.75, 0.125), B, pivot=(0, -0.31, 0)), + "leg_l": part((0.125, 0.75, 0.125), B, pivot=(0, -0.375, 0)), + "leg_r": part((0.125, 0.75, 0.125), B, pivot=(0, -0.375, 0)), + } + for name in BOW_PARTS: + string = "string" in name + arrow = "nocked" in name + color = (0.90, 0.88, 0.78) if string else (0.42, 0.26, 0.10) + if name == "bow_nocked_tip": + color = (0.65, 0.65, 0.62) + width = 0.015 if string else 0.028 if arrow else 0.055 + parts[name] = part((0.1, width, width), "white", color=color) + return Rig(parts) + + +NECK, TAIL = 5, 8 + + +def dragon_rig(): + s, b, sp = "dragon_scale", "dragon_belly", "dragon_spike" + parts = { + "body": part((2.4, 1.15, 1.25), s, s, s, b), + "head": part((0.8, 0.6, 0.75), s, s, s, b, (0.2, 0.05, 0)), + "snout": part((0.62, 0.3, 0.5), "dragon_snout", s, s, b, (0.31, 0, 0)), + "jaw": part((0.66, 0.16, 0.46), "dragon_jaw", s, b, b, (0.33, -0.08, 0)), + "horn_l": part((0.36, 0.14, 0.1), sp, pivot=(-0.16, 0, 0)), + "horn_r": part((0.36, 0.14, 0.1), sp, pivot=(-0.16, 0, 0)), + "nostril": part((0.08, 0.08, 0.36), sp), + "eye_l": part((0.04, 0.08, 0.18), "white", color=(0.85, 0.35, 1.0), glow=1.0), + "eye_r": part((0.04, 0.08, 0.18), "white", color=(0.85, 0.35, 1.0), glow=1.0), + "mouth": part((0.4, 0.06, 0.34), "white", color=(0.95, 0.45, 1.0), glow=0.0), + } + for i in range(NECK): + parts[f"neck{i}"] = part((0.42, 0.42, 0.42), s, s, s, b, (0.21, 0, 0)) + parts[f"nspike{i}"] = part((0.1, 0.18, 0.06), sp, pivot=(0.21, 0.3, 0)) + for i in range(TAIL): + k = 1.0 - 0.06 * i + parts[f"tail{i}"] = part((0.5, 0.42 * k, 0.42 * k), s, s, s, b, (-0.25, 0, 0)) + parts[f"tspike{i}"] = part((0.12, 0.2 * k, 0.06), sp, pivot=(-0.25, 0.21 * k + 0.08, 0)) + for i in range(3): + parts[f"bspike{i}"] = part((0.16, 0.32, 0.08), sp, pivot=(0, 0.72, 0)) + for side, sg in (("l", -1), ("r", 1)): + parts[f"wing_{side}"] = part((0.18, 0.18, 2.0), "wing_bone", pivot=(0, 0, sg * 1.0)) + parts[f"memb_{side}"] = part((1.9, 0.03, 2.0), "wing_membrane", "wing_bone", "wing_membrane", + pivot=(-0.95, 0, sg * 1.0), alpha=True) + parts[f"wtip_{side}"] = part((0.12, 0.12, 2.0), "wing_bone", pivot=(0, 0, sg * 1.0)) + parts[f"mtip_{side}"] = part((1.6, 0.03, 2.0), "wing_membrane", "wing_bone", "wing_membrane", + pivot=(-0.8, 0, sg * 1.0), alpha=True) + for seg in ("thigh", "shin", "fore", "foreshin"): + big = seg in ("thigh", "shin") + parts[f"{seg}_{side}"] = part((0.3, 0.6 if big else 0.42, 0.3) if big else (0.22, 0.42, 0.22), + s, pivot=(0, -0.3 if big else -0.21, 0)) + return Rig(parts) + + +def wither_rig(): + bn, sk = "wither_bone", "wither_skull" + p = { + "shoulders": part((0.38, 0.38, 2.0), bn, bn, bn, bn), + "spine": part((0.2, 1.0, 0.2), bn, pivot=(0, -0.5, 0)), + "tail": part((0.24, 0.78, 0.24), bn, pivot=(0, -0.39, 0)), + "head_m": part((0.5, 0.5, 0.5), "wither_face", sk, sk, pivot=(0, 0.25, 0)), + "head_l": part((0.38, 0.38, 0.38), "wither_face", sk, sk, pivot=(0, 0.19, 0)), + "head_r": part((0.38, 0.38, 0.38), "wither_face", sk, sk, pivot=(0, 0.19, 0)), + "eyes_m": part((0.02, 0.07, 0.3), "wither_eye", color=(1.0, 0.85, 0.75), pivot=(0.26, 0.28, 0), glow=0.4), + "eyes_l": part((0.02, 0.055, 0.23), "wither_eye", color=(1.0, 0.85, 0.75), pivot=(0.2, 0.21, 0), glow=0.4), + "eyes_r": part((0.02, 0.055, 0.23), "wither_eye", color=(1.0, 0.85, 0.75), pivot=(0.2, 0.21, 0), glow=0.4), + } + for i in range(3): + p[f"rib{i}"] = part((0.18, 0.13, 0.9 - 0.08 * i), bn, pivot=(0.08, 0, 0)) + p["armor"] = part((0.9, 1.4, 1.1), "shell", alpha=True, color=(0.6, 0.8, 1.0), pivot=(0, -0.35, 0)) + return Rig(p) + + +# ================================================================ pose helpers +def _ease(u): + u = min(max(u, 0.0), 1.0) + return u * u * (3 - 2 * u) + + +def _out_back(u, s=1.7): + u = min(max(u, 0.0), 1.0) - 1 + return 1 + u * u * ((s + 1) * u + s) + + +def _entered(rig, state, t): + """Vanilla ticks since the current state began (pose memory; the sim keeps no such counter).""" + m = rig.mem + if m.get("state") != state: + m["state"], m["since"] = state, t + return (t - m["since"]) * VT + + +def _smooth(rig, key, target, k): + """Approach target by fraction k per vanilla tick.""" + v = rig.mem.get(key, target) + v += (target - v) * (1 - (1 - k) ** VT) + rig.mem[key] = v + return v + + +def _hit_overlay(rig, tint_t, flash_from=7): + """White flash for the first two hurt ticks, then fading red (render.js hit flash). tint_t: sim ticks.""" + tint_t *= VT + if tint_t >= flash_from: + rig.overlay = (1.0, 1.0, 1.0, 0.5) + elif tint_t > 0: + rig.overlay = (1.0, 0.1, 0.05, 0.45 * tint_t / flash_from + 0.1) + else: + rig.overlay = (0.0, 0.0, 0.0, 0.0) + rig.tint = (1.0, 0.45, 0.45) if tint_t > 3 else (1.0, 1.0, 1.0) + + +def _look(e, target_pos, limit=45.0): + """Yaw and pitch (deg) from entity facing toward a point, clamped like a mob's head.""" + d = np.asarray(target_pos, float) - e.pos + yaw = math.degrees(math.atan2(d[2], d[0]) - e.yaw) + yaw = (yaw + 180) % 360 - 180 + return float(np.clip(yaw, -limit, limit)), float(np.clip(math.degrees(math.atan2(d[1], math.hypot(d[0], d[2]))), -40, 40)) + + +# ================================================================ poses +def pose_steve(body, case): + e, t, rig = body.e, case.t, body.rig + _hit_overlay(rig, max(body.iframes - 2 / VT, 0), 7) + speed = float(np.hypot(e.vel[0], e.vel[2])) / VT # vanilla b/t + if e.on_ground: + body.ph = (body.ph + speed * 0.55 * VT) % 1.0 + amp = min(1.0, speed / 0.2) * (50.0 if body.sprinting else 38.0) + a = 2 * math.pi * body.ph + leg = math.sin(a) * amp if e.on_ground else 0.0 + sw = (t - body.swing_t) * VT / 6.0 + # three-beat swing: cock back, slash across, settle + if 0 <= sw <= 1: + if sw < 0.25: + u = _ease(sw / 0.25) + raise_, cross, twist = 150 * u + 20, -20 * u, -25 * u + else: + u = _out_back((sw - 0.25) / 0.75, 1.2) + raise_, cross, twist = 170 - 140 * u, -20 + 55 * u, -25 + 45 * u + else: + raise_, cross, twist = 0.0, 0.0, 0.0 + bob = abs(math.sin(a)) * 0.05 * amp / 40 + lean = 6.0 if body.sprinting else 0.0 + b = Bones() + hip = 0.75 + bob + b.bone("hips", None, (0, hip, 0), yaw=twist * 0.3, boxes=()) + b.bone("torso", "hips", (0, 0.375, 0), yaw=twist * 0.4, pitch=-lean) + hy, hp = _look(e, case.boss.e.pos + [0, case.boss.aim_h, 0], 35) + b.bone("head", "torso", (0, 0.375, 0), yaw=hy * 0.6 - twist * 0.5, pitch=hp * 0.6) + if getattr(body, "weapon", "sword") == "bow": + charge = float(body.bow_charge) + pitch = math.degrees(body.e.pitch) + rig.hide.add("sword") + rig.hide.difference_update(BOW_PARTS) + if not body.bow_drawing: + rig.hide.update(("bow_nocked_arrow", "bow_nocked_tip")) + # Left hand holds the grip; the right arm retracts as the actual draw + # counter rises. Aim pitch follows the simulation, without auto-aim. + b.bone("head", "torso", (0, 0.375, 0), pitch=pitch) + b.bone("arm_l", "torso", (0, 0.31, -0.37), pitch=88 + pitch, yaw=10, roll=4) + b.bone("arm_r", "torso", (0, 0.31, 0.37), pitch=82 + pitch - 35 * charge, + yaw=-30 - 15 * charge, roll=-4) + _pose_bow(b, rig, charge, pitch) + else: + rig.hide.update(BOW_PARTS) + rig.hide.discard("sword") + b.bone("arm_r", "torso", (0, 0.31, 0.37), yaw=cross, pitch=-leg * 0.7 + raise_, roll=-4 - cross * 0.2) + b.bone("sword", "arm_r", (0.02, -0.64, 0), yaw=-90, roll=-20, boxes=("sword",)) + b.bone("arm_l", "torso", (0, 0.31, -0.37), pitch=leg * 0.7 + raise_ * 0.15, roll=4) + air = 0.0 if e.on_ground else 1.0 + b.bone("leg_r", "hips", (0, 0, 0.125), pitch=leg - 18 * air) + b.bone("leg_l", "hips", (0, 0, -0.125), pitch=-leg + 22 * air) + rig.pose(t, b.spans, e.pos, e.yaw) + + +def _pose_bow(bones, rig, charge, pitch): + """Six wooden/string segments with a nock that moves toward the player.""" + bones.bone("bow_frame", None, (0.72, 1.35, -0.20), pitch=pitch, boxes=()) + tip_x = -0.14 - 0.07 * charge + tip_y = 0.54 - 0.045 * charge + nock = (-0.14 - 0.40 * charge, 0.0, 0.0) + upper, lower = (tip_x, tip_y, 0.0), (tip_x, -tip_y, 0.0) + sections = { + "bow_grip": ((0.0, -0.10, 0.0), (0.0, 0.10, 0.0)), + "bow_upper_inner": ((0.0, 0.10, 0.0), (0.01, 0.29, 0.0)), + "bow_upper_outer": ((0.01, 0.29, 0.0), upper), + "bow_lower_inner": ((0.0, -0.10, 0.0), (0.01, -0.29, 0.0)), + "bow_lower_outer": ((0.01, -0.29, 0.0), lower), + "bow_string_upper": (upper, nock), + "bow_string_lower": (lower, nock), + "bow_nocked_arrow": (nock, (0.44, 0.0, 0.0)), + "bow_nocked_tip": ((0.44, 0.0, 0.0), (0.53, 0.0, 0.0)), + } + for name, (start, end) in sections.items(): + delta = np.asarray(end) - start + length = float(np.linalg.norm(delta)) + width = rig.parts[name]["size"][1] + rig.parts[name]["size"] = (length, width, width) + middle = tuple((np.asarray(start) + end) * 0.5) + bones.bone(name, "bow_frame", middle, + pitch=math.degrees(math.atan2(delta[1], delta[0]))) + + +def pose_golem(g, case): + e, t, rig = g.e, case.t, g.rig + _hit_overlay(rig, g.tint_t) + k = g.hp / g.max_hp + rig.variant = "" if k > 0.75 else "crack1" if k > 0.5 else "crack2" if k > 0.25 else "crack3" + since = _entered(rig, g.state, t) + speed = float(np.hypot(e.vel[0], e.vel[2])) / VT + amp = min(1.0, speed / 0.12) * 30.0 + a = 2 * math.pi * g.ph + leg = math.sin(a) * amp + breathe = math.sin(t * VT * 0.12) + # arm pitch / body lean per state; windup builds slowly, swing snaps, recover lingers low + if g.state == "windup": + u = _ease(since / 6.0) + arms, lean, sq = 180 * u, -12 * u, 0.04 * u + spread = 10 * u + elif g.state == "swing": + u = _out_back(since / 2.0, 2.2) + arms, lean, sq = 180 - 205 * u, 14 * u, -0.02 + spread = 10 - 10 * u + elif g.state == "recover": + u = _ease(since / 10.0) + arms, lean, sq = -25 * (1 - u), 14 * (1 - u), 0.0 + spread = 0.0 + else: + arms, lean, sq, spread = 0.0, 3.0 * min(1.0, speed / 0.1), 0.0, 0.0 + arms = _smooth(rig, "arms", arms, 0.75) + lean = _smooth(rig, "lean", lean, 0.5) + hurt = 6.0 * g.tint_t * VT / 8.0 + rig.glow = 1.0 if g.state == "windup" else 0.0 + b = Bones() + hip = 1.0 - sq + abs(math.sin(a)) * 0.04 * amp / 30 + b.bone("hips", None, (0, hip, 0), boxes=("waist",)) + b.bone("chest", "hips", (0, 0.31, 0), pitch=-lean - hurt, roll=math.sin(a) * 2.5, yaw=math.sin(a) * 4) + hy, hp = _look(e, case.body.e.pos + [0, 1.5, 0], 40) + b.bone("head", "chest", (0.1, 0.66, 0), yaw=hy, pitch=hp * 0.5 + lean * 0.5 + breathe) + b.bone("nose", "head", (0.33, 0.2, 0)) + b.bone("eyes", "head", (0.335, 0.35, 0)) + sway = 0.0 if g.state != "chase" else math.sin(a) * amp * 0.9 + b.bone("arm_l", "chest", (0.0, 0.62, -0.75), pitch=arms + sway + breathe * 2, roll=spread + 4) + b.bone("arm_r", "chest", (0.0, 0.62, 0.75), pitch=arms - sway + breathe * 2, roll=-spread - 4) + b.bone("flower", "chest", (0.345, 0.5, 0.3), boxes=("flower",)) + b.bone("leg_l", None, (0, hip, -0.25), pitch=leg) + b.bone("leg_r", None, (0, hip, 0.25), pitch=-leg) + rig.pose(t, b.spans, e.pos, e.yaw) + + +def pose_zombie(z, case): + e, t, rig = z.e, case.t, z.rig + _hit_overlay(rig, z.tint_t) + since = _entered(rig, z.state, t) + speed = float(np.hypot(e.vel[0], e.vel[2])) / VT + amp = min(1.0, speed / 0.14) * 40.0 + a = 2 * math.pi * z.ph + leg = math.sin(a) * amp + vt = t * VT + shamble = math.sin(vt * 0.21) * 6 + # a reinforcement climbs out of the ground for its first 0.8 s (minecraft-arena@5; it cannot act meanwhile) + born = getattr(z, "born", None) + sink = 0.0 if born is None else 1.9 * max(0.0, 1.0 - (t - born) * VT / 16.0) + if z.state == "windup": + u = _ease(since / 4.0) + ar, al, lean, tw = 90 + 60 * u, 90 - 30 * u, -10 * u, -25 * u + elif z.state == "swing": + u = _out_back(since / 2.0, 2.0) + ar, al, lean, tw = 150 - 110 * u, 60 + 50 * u, 16 * u, -25 + 50 * u + elif z.state == "recover": + u = _ease(since / 8.0) + ar, al, lean, tw = 40 + 50 * u, 110 - 20 * u, 16 * (1 - u), 25 * (1 - u) + else: + ar, al, lean, tw = 90 + shamble, 90 - shamble, 6.0, 0.0 + ar, al = _smooth(rig, "ar", ar, 0.7), _smooth(rig, "al", al, 0.7) + hurt = 10.0 * z.tint_t * VT / 8.0 + b = Bones() + b.bone("hips", None, (0, 0.75 + abs(math.sin(a)) * 0.04, 0), yaw=tw * 0.3, boxes=()) + b.bone("torso", "hips", (0, 0.375, 0), pitch=-lean - hurt, yaw=tw * 0.5, roll=math.sin(a) * 3) + hy, hp = _look(e, case.body.e.pos + [0, 1.5, 0], 50) + b.bone("head", "torso", (0, 0.375, 0), yaw=hy - tw * 0.4, pitch=hp * 0.7 + math.sin(vt * 0.09) * 4, + roll=math.sin(vt * 0.07) * 6) + b.bone("arm_r", "torso", (0, 0.31, 0.37), pitch=ar, yaw=-tw * 0.3) + b.bone("arm_l", "torso", (0, 0.31, -0.37), pitch=al) + b.bone("leg_r", "hips", (0, 0, 0.125), pitch=leg) + b.bone("leg_l", "hips", (0, 0, -0.125), pitch=-leg) + rig.pose(t, b.spans, e.pos - [0, sink, 0], e.yaw) + + +def pose_warden(w, case): + """Heavy stalk; arms raised overhead for the smash; chest core and horn tendrils flare for the sonic boom and pulse + with the heartbeat; climbs out of the floor while emerging, throws its head back to roar.""" + e, t, rig = w.e, case.t, w.rig + _hit_overlay(rig, w.tint_t) + phase = w.phase + since = _entered(rig, phase, t) + vt = t * VT + speed = float(np.hypot(e.vel[0], e.vel[2])) / VT + amp = min(1.0, speed / 0.12) * 22.0 + a = 2 * math.pi * w.ph + leg = math.sin(a) * amp + beat = 0.5 + 0.5 * math.sin(vt * (0.63 if phase in ("chase", "windup", "recover", "boom") else 0.16)) + sink, arms, lean, head_p, horns, core = 0.0, 0.0, 4.0 * min(1.0, speed / 0.1), 0.0, 10.0 * beat, 0.25 + 0.35 * beat + if phase == "emerge": + u = min(1.0, since / (20.0 * float(w.k.emerge_s))) + sink = 2.9 * (1.0 - _ease(u)) + arms, lean, head_p = 150 * (1 - u) + 30, -20 * (1 - u), -10 + elif phase == "roar": + u = _ease(since / 10.0) + arms, lean, head_p, horns, core = -40 * u, -18 * u, 35 * u, 45 * u, 0.9 + elif phase == "windup": + u = _ease(since / 6.0) + arms, lean, head_p, horns, core = 175 * u, -14 * u, 10 * u, 30 * u, 0.7 + elif phase == "recover": + u = _ease(since / 8.0) + arms, lean, head_p = -30 * (1 - u), 18 * (1 - u), -12 * (1 - u) + elif phase == "boom": + u = _ease(since / 34.0) # 1.7 s charge + arms, lean, head_p, horns, core = -55 * u, 10 * u, -15 * u, 55 * u, 0.6 + 0.6 * u + elif phase == "boom_recover": + u = _ease(since / 26.0) + arms, lean, head_p, horns, core = -55 * (1 - u), 10 * (1 - u), 0.0, 20 * (1 - u), 0.6 * (1 - u) + 0.3 + arms, lean = _smooth(rig, "arms", arms, 0.6), _smooth(rig, "lean", lean, 0.5) + rig.glow = 1.0 if phase in ("windup", "boom") else 0.0 + rig.parts["core"]["glow"] = core + rig.parts["horn_l"]["glow"] = rig.parts["horn_r"]["glow"] = 0.2 + 0.6 * (horns / 55.0) + hurt = 6.0 * w.tint_t * VT / 8.0 + b = Bones() + hip = 0.81 + abs(math.sin(a)) * 0.05 * amp / 22 + b.bone("hips", None, (0, hip, 0), boxes=()) + b.bone("body", "hips", (0, 0.0, 0), pitch=-lean - hurt, roll=math.sin(a) * 2.0) + b.bone("core", "body", (0, 0, 0)) + hy, hp = _look(e, case.body.e.pos + [0, 1.5, 0], 35) + b.bone("head", "body", (0.05, 1.18, 0), yaw=hy, pitch=hp * 0.4 + head_p) + b.bone("horn_l", "head", (0.0, 0.85, -0.42), roll=20 + horns) + b.bone("horn_r", "head", (0.0, 0.85, 0.42), roll=-20 - horns) + sway = math.sin(a) * amp * 0.8 if phase == "chase" else 0.0 + b.bone("arm_l", "body", (0.0, 1.12, -0.82), pitch=arms + sway, roll=6) + b.bone("arm_r", "body", (0.0, 1.12, 0.82), pitch=arms - sway, roll=-6) + b.bone("leg_l", None, (0, hip, -0.3), pitch=leg) + b.bone("leg_r", None, (0, hip, 0.3), pitch=-leg) + rig.pose(t, b.spans, e.pos - [0, sink, 0], e.yaw) + + +def pose_skeleton(s, case): + """Strafing archer: the bow arm points at the player, the draw arm pulls the string back over the visible draw; + the nocked arrow shows only while drawing.""" + e, t, rig = s.e, case.t, s.rig + _hit_overlay(rig, s.tint_t) + speed = float(np.hypot(e.vel[0], e.vel[2])) / VT + amp = min(1.0, speed / 0.12) * 32.0 + a = 2 * math.pi * s.ph + leg = math.sin(a) * amp + drawing = s.state == "windup" + charge = 0.0 + if drawing: + charge = float(np.clip(1.0 - max(s.timer, 0.0) / max(float(s.k.draw), 1e-6), 0.0, 1.0)) + charge = _smooth(rig, "charge", charge, 0.5) + rig.hide.difference_update(BOW_PARTS) + if not drawing: + rig.hide.update(("bow_nocked_arrow", "bow_nocked_tip")) + rig.glow = 1.0 if drawing and charge > 0.6 else 0.0 + d = case.body.e.pos + [0, 1.0, 0] - (e.pos + [0, 1.5, 0]) + pitch = math.degrees(math.atan2(d[1], math.hypot(d[0], d[2]))) + hurt = 8.0 * s.tint_t * VT / 8.0 + b = Bones() + b.bone("hips", None, (0, 0.75 + abs(math.sin(a)) * 0.03, 0), boxes=()) + b.bone("torso", "hips", (0, 0.375, 0), pitch=-hurt, boxes=("torso", "chestplate")) + b.bone("head", "torso", (0, 0.375, 0), pitch=pitch * 0.8, boxes=("head", "helmet")) + b.bone("arm_l", "torso", (0, 0.31, -0.3), pitch=88 + pitch, yaw=10, roll=4) + b.bone("arm_r", "torso", (0, 0.31, 0.3), pitch=82 + pitch - 35 * charge, yaw=-30 - 15 * charge, roll=-4) + _pose_bow(b, rig, charge, pitch) + b.bone("leg_r", "hips", (0, 0, 0.1), pitch=leg) + b.bone("leg_l", "hips", (0, 0, -0.1), pitch=-leg) + rig.pose(t, b.spans, e.pos, e.yaw) + + +def pose_dragon(dg, case): + e, t, rig = dg.e, case.t, dg.rig + _hit_overlay(rig, dg.tint_t) + phase = getattr(dg, "phase", dg.state) + since = _entered(rig, phase, t) + vt = t * VT + sitting = phase in ("scanning", "roar", "flaming") + dive = phase == "charge" + breath = phase == "flaming" + a = 2 * math.pi * dg.flap + # wing beat: fast downstroke, slow upstroke; folded in a charge, half-open and resting when perched + beat = math.sin(a - 0.6 * math.sin(a)) + if dive: + fold = _ease(since / 4.0) + shoulder, elbow, sweep = -10 - 5 * beat * (1 - fold), 60 * fold, 50 * fold + elif sitting: + shoulder, elbow, sweep = 18 + 6 * beat, 40.0, 25.0 + elif phase in ("takeoff", "landing"): + shoulder, elbow, sweep = 40 * beat, -20 * beat + 10, 0.0 + else: + shoulder, elbow, sweep = 32 * beat + 4, -26 * math.sin(a + 1.0) + 6, 6 * math.sin(a) + rear = 0.0 + if phase == "roar": + rear = _ease(since / 6.0) + elif breath: + rear = 0.4 + elif phase == "strafe" and getattr(dg, "goal", None) is not None: + rear = 0.5 + rear = _smooth(rig, "rear", rear, 0.4) + mouth = 0.0 + if phase == "roar": + mouth = 40 * _ease(since / 4.0) + elif breath: + mouth = 30.0 + elif phase == "strafe" and getattr(dg, "goal", None) is not None: + mouth = 24.0 + elif dive: + mouth = 22.0 + mouth = _smooth(rig, "mouth", mouth, 0.5) + hot = phase in ("roar", "flaming") or (phase == "strafe" and getattr(dg, "goal", None) is not None) + rig.glow = 1.0 if hot else 0.0 + rig.parts["mouth"]["glow"] = 1.2 if hot else 0.0 + base_pitch = 30.0 if dive else float(np.clip(-e.vel[1] / VT * 30.0, -20.0, 25.0)) + if sitting: + base_pitch = -6.0 + base_pitch = _smooth(rig, "pitch", base_pitch, 0.3) + bank = _smooth(rig, "bank", dg.bank, 0.3) + bodybob = -0.12 * beat * (0.3 if sitting else 1.0) + b = Bones() + b.bone("body", None, (0, bodybob, 0), pitch=-rear * 8) + hy, hp = _look(e, case.body.e.pos + [0, 0.9, 0], 60) + b.bone("n0", "body", (1.15, 0.2, 0), boxes=()) + prev = "n0" + for i in range(NECK): + u = i / (NECK - 1) + pitch = (14 - 30 * u) * (1 - rear) + (26 - 10 * i) * rear * 1.4 + math.sin(vt * 0.15 - i * 0.6) * 3 + if dive: + pitch = -4.0 + if sitting and not phase == "roar": + pitch = -14.0 + 4 * i * 0.5 + b.bone(f"neck{i}", prev, (0.42 if i else 0.0, 0, 0), yaw=hy / NECK, pitch=pitch + hp / NECK * 0.8, + boxes=(f"neck{i}", f"nspike{i}")) + prev = f"neck{i}" + b.bone("head", prev, (0.42, 0, 0), pitch=-10 * rear + hp * 0.2 - (18 if breath else 0)) + b.bone("snout", "head", (0.55, -0.08, 0), boxes=("snout", "nostril")) + b.bone("nost", "snout", (0.58, 0.14, 0), boxes=("nostril",)) + b.bone("jaw", "head", (0.5, -0.2, 0), pitch=-mouth) + b.bone("mouth", "head", (0.82, -0.2, 0), pitch=-mouth * 0.5) + b.bone("horn_l", "head", (0.0, 0.32, -0.22), pitch=18, yaw=12) + b.bone("horn_r", "head", (0.0, 0.32, 0.22), pitch=18, yaw=-12) + b.bone("eye_l", "head", (0.62, 0.22, -0.3), yaw=-60) + b.bone("eye_r", "head", (0.62, 0.22, 0.3), yaw=60) + for i, x in enumerate((0.7, 0.0, -0.7)): + b.bone(f"bspike{i}", "body", (x, 0, 0), boxes=(f"bspike{i}",)) + b.bone("t0", "body", (-1.2, 0.05, 0), boxes=()) + prev = "t0" + for i in range(TAIL): + w = math.sin(vt * 0.18 - i * 0.7) + b.bone(f"tail{i}", prev, (-0.5 if i else 0.0, 0, 0), yaw=w * (6 + i) + (-bank * 0.08), + pitch=(-3 if dive else 4 + 3 * math.sin(a - i * 0.5)) - rear * 3 - (6 if sitting else 0), + boxes=(f"tail{i}", f"tspike{i}")) + prev = f"tail{i}" + for side, sg in (("l", -1), ("r", 1)): + b.bone(f"wing_{side}", "body", (0.55, 0.45, sg * 0.6), yaw=-sg * sweep, roll=sg * -shoulder, + boxes=(f"wing_{side}", f"memb_{side}")) + b.bone(f"wtip_{side}", f"wing_{side}", (0, 0, sg * 2.0), yaw=-sg * sweep * 0.6, roll=sg * -elbow, + boxes=(f"wtip_{side}", f"mtip_{side}")) + tuck = 85 if dive else (10 if sitting else 60) + b.bone(f"thigh_{side}", "body", (-0.7, -0.45, sg * 0.5), pitch=-tuck + 6 * math.sin(a)) + b.bone(f"shin_{side}", f"thigh_{side}", (0, -0.56, 0), pitch=-50 if not sitting else 30) + b.bone(f"fore_{side}", "body", (0.75, -0.45, sg * 0.45), pitch=(-50 if not sitting else 5) + 6 * math.sin(a + 1)) + b.bone(f"foreshin_{side}", f"fore_{side}", (0, -0.4, 0), pitch=-60 if not sitting else 20) + rig.pose(t, b.spans, e.pos, e.yaw, base=(base_pitch, bank)) + + +def pose_wither(w, case): + e, t, rig = w.e, case.t, w.rig + _hit_overlay(rig, w.tint_t) + since = _entered(rig, w.state, t) + vt = t * VT + spawn = w.state == "spawn" + # recoil per head: a head that just fired snaps back (rig memory only) + shots = rig.mem.setdefault("shots", {}) + for s in w.skulls: + key = s.get("n", 0) # serial number: id() is reused by CPython and is not reproducible + if key not in shots: + shots[key] = (t, s.get("head", 0)) + recent = {h: tt for tt, h in shots.values()} + if len(shots) > 64: + for k in sorted(shots)[:len(shots) - 64]: + del shots[k] + rec = {h: max(0.0, 1.0 - (t - recent.get(h, -10 * FPS)) * VT / 6.0) for h in (0, 1, 2)} + rig.glow = 0.35 + 0.65 * max(rec.values()) + if spawn: + rig.glow = 0.6 + 0.4 * math.sin(vt * 0.9) + for nm in ("eyes_m", "eyes_l", "eyes_r"): + rig.parts[nm]["glow"] = rig.glow + armored = bool(getattr(w, "armored", w.hp <= w.max_hp / 2)) + rig.hide = set() if armored else {"armor"} + rig.shell = 0.0 + if spawn: # flickering blue charge shell while invulnerable + rig.shell = 0.25 + 0.25 * (math.sin(vt * 1.7) > 0) + rig.shell_color = (0.35, 0.55, 1.0) + elif armored: + rig.shell = 0.18 + 0.06 * math.sin(vt * 0.5) + rig.shell_color = (0.55, 0.7, 1.0) + bob = math.sin(vt * 0.1) * 0.1 + sway = math.sin(vt * 0.05) * 6 + lean = float(np.clip(np.hypot(e.vel[0], e.vel[2]) / VT * 30.0, 0.0, 12.0)) + b = Bones() + shrink = 0.0 if not spawn else -0.15 * (1 - since / max(1.0, w.SPAWN_TICKS)) + b.bone("spine", None, (0, 0.55 + bob + shrink, 0), pitch=-lean * 0.3, roll=math.sin(vt * 0.07) * 3) + b.bone("shoulders", "spine", (0, 0.05, 0), yaw=sway * 0.3) + for i in range(3): + b.bone(f"rib{i}", "spine", (0, -0.2 - 0.26 * i, 0), yaw=math.sin(vt * 0.1 + i) * 2) + b.bone("tail", "spine", (0, -1.0, 0), pitch=-20 - lean * 0.6 + math.sin(vt * 0.09) * 12, + roll=math.sin(vt * 0.06) * 10) + b.bone("armor", "spine", (0, 0.1, 0)) + target = case.body.e.pos + [0, 1.0, 0] + for idx, (nm, z, y, ph) in enumerate((("m", 0.0, 0.2, 0.0), ("l", -0.85, 0.2, 1.7), ("r", 0.85, 0.2, 3.4))): + hy, hp = _look(e, target, 60) + scan = 0.0 if nm == "m" else math.sin(vt * 0.04 + ph) * 18 * (1.0 - rec[idx]) + if spawn: + hy, hp, scan = 0.0, -25.0 + 10 * math.sin(vt * 0.2 + ph), 0.0 + pitch = hp - 18 * rec[idx] + b.bone(f"head_{nm}", "shoulders", (0.02 - 0.08 * rec[idx], y, z), yaw=hy + scan, pitch=pitch, + roll=math.sin(vt * 0.05 + ph) * 4, boxes=(f"head_{nm}", f"eyes_{nm}")) + rig.pose(t, b.spans, e.pos, e.yaw, base=(-lean * 0.5, 0.0)) + + +# ================================================================ particles (case.fxrng only) +def _p(pos, vel, life, size, color, tile="puff", grav=0.0, glow=0.0): + return {"pos": np.asarray(pos, float), "vel": np.asarray(vel, float), "life": float(life), "life0": float(life), + "size": float(size), "color": tuple(color), "tile": tile, "grav": grav, "glow": glow} + + +def fx_events(case): + """Juice keyed to this tick's events, spawned from case.fxrng. Particle vel / grav are per vanilla tick.""" + r, out = case.fxrng, [] + g, p = case.boss, case.body + for ev in case.events[getattr(case, "_ev0", 0):]: + name = ev[0] if isinstance(ev, tuple) else ev + if name == "boss_hit": + c = g.e.pos + [0, 0.0 if g.hover else g.aim_h, 0] + n = 12 if (isinstance(ev, tuple) and ev[2] == "crit") else 6 + for _ in range(n): + v = r.normal(0, 1, 3) + v = v / (np.linalg.norm(v) + 1e-6) * r.uniform(0.08, 0.22) + col = (1.0, 0.95, 0.6) if n > 6 else (0.95, 0.95, 0.95) + out.append(_p(c + r.normal(0, 0.25, 3), v + [0, 0.08, 0], 0.4, 0.09, col, "white", -0.012, 1.0)) + elif name == "player_hit": + c = p.e.pos + [0, 1.0, 0] + for _ in range(6): + out.append(_p(c + r.normal(0, 0.2, 3), r.normal(0, 0.06, 3) + [0, 0.06, 0], 0.5, 0.1, + (0.75, 0.08, 0.06), "white", -0.01)) + elif name in ("golem_hit", "golem_whiff", "dragon_ram", "wither_ram", "skull_ground", "skull_hit"): + if name.startswith("skull"): + c = p.e.pos + [0, 0.9, 0] if name == "skull_hit" else None + if c is None: + continue + for _ in range(10): + out.append(_p(c + r.normal(0, 0.3, 3), r.normal(0, 0.05, 3), 0.7, 0.35, (0.2, 0.2, 0.22))) + continue + c = g.e.pos + g.e.fwd * (1.4 if name.startswith("golem") else 0.0) + gy = case.arena.ground(c, 0.6) + for _ in range(10): + ang = r.uniform(0, 2 * math.pi) + v = np.array([math.cos(ang), 0, math.sin(ang)]) * r.uniform(0.05, 0.12) + out.append(_p([c[0], gy + 0.1, c[2]], v + [0, 0.03, 0], 0.6, r.uniform(0.2, 0.35), (0.55, 0.45, 0.35))) + elif name in ("skull_blast", "wither_spawn_blast", "crystal_destroyed"): + if name == "crystal_destroyed": + cid = ev[1] if isinstance(ev, tuple) else 0 + c = next((x["pos"] for x in getattr(g, "crystals", ()) if x["id"] == cid), g.e.pos) + elif isinstance(ev, tuple) and len(ev) > 2: + c = np.asarray(ev[2], float) + else: + c = g.e.pos + big = name != "skull_blast" + for _ in range(26 if big else 8): + v = r.normal(0, 1, 3) + v = v / (np.linalg.norm(v) + 1e-6) * r.uniform(0.05, 0.3 if big else 0.12) + out.append(_p(np.asarray(c, float) + r.normal(0, 0.3, 3), v + [0, 0.04, 0], r.uniform(0.4, 0.9), + r.uniform(0.35, 0.9) if big else r.uniform(0.25, 0.45), + (0.95, 0.85, 0.7) if big else (0.55, 0.52, 0.5), "puff", -0.004, 0.5 if big else 0.2)) + elif name == "fall_damage": + c = p.e.pos + for _ in range(6): + ang = r.uniform(0, 2 * math.pi) + out.append(_p(c + [0, 0.1, 0], [math.cos(ang) * 0.08, 0.02, math.sin(ang) * 0.08], 0.5, 0.2, + (0.55, 0.45, 0.35))) + elif name == "zombie_reinforce": # a zombie digs out of the ground (minecraft-arena@5) + c = np.asarray(ev[2], float) if isinstance(ev, tuple) else g.e.pos + for _ in range(16): + ang = r.uniform(0, 2 * math.pi) + out.append(_p(c + [math.cos(ang) * 0.4, 0.1, math.sin(ang) * 0.4], + [math.cos(ang) * 0.06, r.uniform(0.04, 0.1), math.sin(ang) * 0.06], 0.9, + r.uniform(0.2, 0.4), (0.33, 0.27, 0.2), "puff", -0.006)) + elif name == "minion_killed" and isinstance(ev, tuple) and len(ev) > 2: + c = np.asarray(ev[2], float) + [0, 1.0, 0] + for _ in range(12): + v = r.normal(0, 1, 3) + v = v / (np.linalg.norm(v) + 1e-6) * r.uniform(0.04, 0.12) + out.append(_p(c + r.normal(0, 0.3, 3), v + [0, 0.04, 0], 0.7, r.uniform(0.25, 0.4), + (0.5, 0.5, 0.5), "puff", -0.004)) + elif name == "minion_hit": + for z in getattr(g, "minions", ()): + if z.tint_t >= ticks_hit(z): + c = z.e.pos + [0, 1.0, 0] + for _ in range(5): + v = r.normal(0, 1, 3) + v = v / (np.linalg.norm(v) + 1e-6) * r.uniform(0.06, 0.16) + out.append(_p(c + r.normal(0, 0.2, 3), v + [0, 0.06, 0], 0.4, 0.09, (0.95, 0.95, 0.95), + "white", -0.012, 1.0)) + elif name == "warden_boom_hit" or name == "warden_boom_miss": # the sonic boom: rings along the line + a_, b_ = g.e.pos + [0, 1.9, 0], p.e.pos + [0, 1.0, 0] + for i in range(12): + u = (i + 0.5) / 12 + out.append(_p(a_ + (b_ - a_) * u, [0, 0, 0], 0.45 + 0.02 * i, 0.5 + 0.06 * i, + (0.55, 0.95, 1.0), "glow", 0.0, 1.0)) + elif name == "warden_smash": + c = g.e.pos + g.e.fwd * 1.0 + gy = case.arena.ground(c, 0.6) + for _ in range(12): + ang = r.uniform(0, 2 * math.pi) + v = np.array([math.cos(ang), 0, math.sin(ang)]) * r.uniform(0.06, 0.14) + out.append(_p([c[0], gy + 0.1, c[2]], v + [0, 0.04, 0], 0.6, r.uniform(0.25, 0.4), (0.1, 0.18, 0.2))) + elif name in ("skeleton_arrow_blocked",): + pass + return out + + +def fx_ambient(case): + """Per-tick continuous effects: footstep dust, dragon breath, skull smoke, wither aura.""" + r, out, g = case.fxrng, [], case.boss + for ent, w in ((case.body.e, 0.3), (g.e, getattr(g.e, "w", 1.0) * 0.4)): + if g.hover and ent is g.e: + continue + if ent.on_ground and np.hypot(ent.vel[0], ent.vel[2]) > 0.12 * VT and _every(case, 3): + out.append(_p(ent.pos + r.normal(0, w, 3) * [1, 0, 1] + [0, 0.05, 0], [0, 0.02, 0], 0.5, + r.uniform(0.1, 0.18), (0.62, 0.55, 0.45))) + name = g.name + if name == "ender_dragon": + head = _dragon_mouth(g) + phase = getattr(g, "phase", "") + for c in getattr(g, "clouds", ()): # dragon's breath clouds: low purple haze + if _every(case, 1): + for _ in range(2 if c["kind"] == "breath" else 3): + ang, rad = r.uniform(0, 2 * math.pi), c["r"] * math.sqrt(r.uniform(0, 1)) + pos = c["pos"] + [math.cos(ang) * rad, r.uniform(0.05, 0.6), math.sin(ang) * rad] + out.append(_p(pos, [0, 0.015, 0], r.uniform(0.5, 0.9), r.uniform(0.25, 0.45), + (0.72, 0.28, 0.9), "puff", 0.0, 0.6)) + if phase == "flaming" and _every(case, 1): + for _ in range(4): + down = np.array([0.0, -1.0, 0.0]) + g.e.fwd * 0.5 + out.append(_p(head + r.normal(0, 0.15, 3), down * 0.18 + r.normal(0, 0.04, 3), r.uniform(0.4, 0.7), + r.uniform(0.3, 0.55), (0.82, 0.32, 0.98), "puff", 0.0, 0.8)) + elif (phase == "roar" or (phase == "strafe" and getattr(g, "goal", None) is not None)) and _every(case, 1): + out.append(_p(head + r.normal(0, 0.1, 3), r.normal(0, 0.02, 3), 0.4, 0.18, (0.95, 0.5, 1.0), "glow", 0, 1)) + for f in getattr(g, "fireballs", ()): + if _every(case, 1): + out.append(_p(f["pos"] + r.normal(0, 0.1, 3), r.normal(0, 0.01, 3), 0.5, r.uniform(0.2, 0.35), + (0.75, 0.3, 0.95), "puff", 0.0, 0.9)) + for c in getattr(g, "crystals", ()): # crystal sparkle + if c["alive"] and _every(case, 6): + out.append(_p(c["pos"] + [0, 0.8, 0] + r.normal(0, 0.35, 3), [0, 0.02, 0], 0.8, 0.07, + (1.0, 0.75, 0.95), "white", 0.0, 1.0)) + if _every(case, 4): # ender particles drifting off the body + out.append(_p(g.e.pos + r.normal(0, 1.0, 3), r.normal(0, 0.01, 3), 1.2, 0.07, (0.7, 0.3, 0.9), + "white", 0.0, 1.0)) + elif name == "wither": + for s in g.skulls if _every(case, 1) else (): + col = (0.35, 0.5, 0.85) if s.get("blue") else (0.18, 0.17, 0.2) + out.append(_p(s["pos"] + r.normal(0, 0.06, 3), r.normal(0, 0.01, 3), 0.45, r.uniform(0.14, 0.24), col)) + if _every(case, 2): + out.append(_p(g.e.pos + r.normal(0, 0.5, 3) + [0, 0.3, 0], [0, 0.02, 0], 0.9, r.uniform(0.15, 0.25), + (0.15, 0.14, 0.16))) + if g.state == "spawn" and _every(case, 1): + for _ in range(2): + v = r.normal(0, 1, 3) + v /= np.linalg.norm(v) + 1e-6 + out.append(_p(g.e.pos + v * 1.8 + [0, 0.4, 0], -v * 0.09, 0.35, 0.1, (0.5, 0.7, 1.0), "white", 0, 1)) + elif name == "iron_golem" and g.state == "windup" and _every(case, 2): + out.append(_p(g.e.pos + r.normal(0, 0.4, 3) * [1, 0, 1] + [0, 0.05, 0], [0, 0.01, 0], 0.5, 0.2, + (0.6, 0.55, 0.45))) + elif name == "warden": + if g.phase == "boom" and _every(case, 1): # charge: cyan motes drawn into the chest + for _ in range(2): + v = r.normal(0, 1, 3) + v /= np.linalg.norm(v) + 1e-6 + core = g.e.pos + [0, 1.6, 0] + g.e.fwd * 0.4 + out.append(_p(core + v * 1.6, -v * 0.1, 0.35, 0.12, (0.5, 1.0, 1.0), "white", 0.0, 1.0)) + if g.phase == "emerge" and _every(case, 1): # earth breaking where it climbs out + ang = r.uniform(0, 2 * math.pi) + out.append(_p(g.e.pos + [math.cos(ang) * 0.8, 0.1, math.sin(ang) * 0.8], + [math.cos(ang) * 0.05, r.uniform(0.05, 0.12), math.sin(ang) * 0.05], 0.8, r.uniform(0.2, 0.35), + (0.06, 0.12, 0.14), "puff", -0.01)) + if _every(case, 5): # sculk spores drifting up + out.append(_p(g.e.pos + r.normal(0, 4.0, 3) * [1, 0, 1] + [0, 0.2, 0], [0, 0.015, 0], 2.0, 0.06, + (0.3, 0.85, 0.9), "white", 0.0, 1.0)) + elif name == "skeleton" and g.state == "windup" and _every(case, 3): + out.append(_p(g.e.pos + [0, 1.6, 0] + g.e.fwd * 0.5, [0, 0.01, 0], 0.3, 0.08, (1.0, 0.9, 0.6), "glow", 0, 1)) + return out + + +def _dragon_mouth(g): + rig = g.rig + if rig.kf.get("mouth"): + return rig.kf["mouth"][-1][1].copy() + return g.e.pos + g.e.fwd * 3.2 + + +def step_fx(case): + """Advance particles. Called once per tick by MobFight.track; visual-only state.""" + case.fx += fx_events(case) + fx_ambient(case) + keep = [] + for p in case.fx: + p["pos"] = p["pos"] + p["vel"] * VT + p["vel"] = p["vel"] * 0.94 ** VT + [0, p.get("grav", 0.0) * VT, 0] + p["life"] -= 1 / FPS + if p["life"] > 0: + keep.append(p) + case.fx = keep[-260:] + + +# ================================================================ renderer +VS = """#version 330 +in vec3 in_pos; in vec3 in_norm; +in vec3 i_center; in vec3 i_size; in vec4 i_q; in vec4 i_color; in vec4 i_tiles; in vec4 i_tiles2; +in vec4 i_over; in vec2 i_fx; +uniform mat4 mvp; uniform vec3 eye; +out vec3 v_norm; out vec3 v_lnorm; out vec2 v_uv; out float v_dist; flat out float v_layer; +out vec4 v_color; out vec4 v_over; out vec2 v_fx; out vec3 v_world; +vec3 rot(vec4 q, vec3 v) { vec3 t = 2.0 * cross(q.xyz, v); return v + q.w * t + cross(q.xyz, t); } +void main() { + vec3 lp = in_pos * i_size; + vec3 p = rot(i_q, lp) + i_center; + v_norm = rot(i_q, in_norm); v_lnorm = in_norm; + vec3 a = abs(in_norm); + // texel density: one tile per box face, but tiled per metre on big terrain faces (i_fx.y > 0) + vec2 uv; float layer; + if (a.y > 0.5) { uv = vec2(in_pos.x, in_pos.z); layer = in_norm.y > 0.0 ? i_tiles.z : i_tiles.w; + if (i_fx.y > 0.0) uv = vec2(lp.x, lp.z); } + else if (a.x > 0.5) { uv = vec2(in_pos.z * sign(in_norm.x), -in_pos.y); layer = in_norm.x > 0.0 ? i_tiles.x : i_tiles2.x; + if (i_fx.y > 0.0) uv = vec2(lp.z * sign(in_norm.x), -lp.y); } + else { uv = vec2(-in_pos.x * sign(in_norm.z), -in_pos.y); layer = i_tiles.y; + if (i_fx.y > 0.0) uv = vec2(-lp.x * sign(in_norm.z), -lp.y); } + v_uv = (i_fx.y > 0.0) ? uv : uv + 0.5; + v_layer = layer; v_color = i_color; v_over = i_over; v_fx = i_fx; v_world = p; + v_dist = length(p - eye); + gl_Position = mvp * vec4(p, 1.0); +}""" +FS = """#version 330 +in vec3 v_norm; in vec3 v_lnorm; in vec2 v_uv; in float v_dist; flat in float v_layer; +in vec4 v_color; in vec4 v_over; in vec2 v_fx; in vec3 v_world; +uniform sampler2DArray tex; uniform float crack; uniform vec3 fog_col; uniform vec2 fog_rng; +uniform float alpha_pass; uniform vec3 sun; +out vec4 f; +void main() { + vec4 c = texture(tex, vec3(fract(v_uv), v_layer)); + if (alpha_pass < 0.5 && c.a < 0.5) discard; + if (alpha_pass > 0.5 && c.a < 0.02) discard; + vec3 n = normalize(v_norm); + // Minecraft face shading (top 1.0, z faces 0.8, x faces 0.6, bottom 0.5) blended with a sun term + float mc = n.y > 0.5 ? 1.0 : (n.y < -0.5 ? 0.5 : mix(0.6, 0.8, abs(n.z))); + float l = mix(mc, 0.5 + 0.5 * max(dot(n, sun), 0.0), 0.35) * (0.92 + 0.08 * n.y); + vec3 col = c.rgb * v_color.rgb * l; + col = mix(col, c.rgb * v_color.rgb * 1.25, v_fx.x); // emissive + col = mix(col, v_over.rgb, v_over.a); // hurt flash + float fog = clamp((v_dist - fog_rng.x) / (fog_rng.y - fog_rng.x), 0.0, 1.0); + col = mix(col, fog_col, fog * (1.0 - 0.6 * v_fx.x)); + f = vec4(col, c.a * v_color.a); +}""" +SKY_VS = """#version 330 +in vec2 in_pos; out vec2 v; void main() { v = in_pos; gl_Position = vec4(in_pos, 0.999, 1.0); }""" +SKY_FS = """#version 330 +in vec2 v; uniform vec3 top; uniform vec3 bot; uniform mat3 inv_rot; uniform vec2 tanf; +uniform float stars; out vec4 f; +float h(vec3 p) { return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453); } +void main() { + vec3 d = normalize(inv_rot * vec3(v.x * tanf.x, v.y * tanf.y, -1.0)); + float k = clamp(d.y * 1.6 + 0.15, 0.0, 1.0); + vec3 col = mix(bot, top, sqrt(k)); + if (stars > 0.0) { vec3 q = floor(d * 160.0); if (h(q) > 0.996 && d.y > -0.05) col += vec3(0.8) * stars; } + f = vec4(col, 1.0); +}""" + +SUN = np.array([0.45, 0.85, 0.3]) / np.linalg.norm([0.45, 0.85, 0.3]) +THEMES = { # sky top, sky bottom / fog + "field": ((0.44, 0.62, 0.98), (0.73, 0.84, 1.0)), + "towers": ((0.04, 0.02, 0.07), (0.16, 0.1, 0.2)), + "wither": ((0.16, 0.15, 0.2), (0.38, 0.35, 0.4)), + "night": ((0.02, 0.03, 0.09), (0.13, 0.16, 0.27)), # minecraft-arena@5 + "deep_dark": ((0.01, 0.02, 0.04), (0.09, 0.13, 0.17)), + "ruins": ((0.55, 0.52, 0.66), (0.86, 0.72, 0.6)), # dusk +} +FOG = {"field": (28.0, 76.0), "towers": (22.0, 62.0), "night": (20.0, 56.0), "deep_dark": (18.0, 52.0), + "ruins": (24.0, 68.0)} +STARS = {"towers": 1.0, "night": 1.0} +# third-person camera height above the player's feet, per arena style (default 2.6): the overworld night mobs are as tall +# as Steve, so from 2.6 a zombie or skeleton straight ahead hides behind the player's own body, bow draw included. +CAM_UP = {"night": 3.5, "ruins": 3.5} + + +def _cube(): + v = [] + for ax in range(3): + for sgn in (-1, 1): + n = np.zeros(3) + n[ax] = sgn + u, w = np.eye(3)[(ax + 1) % 3], np.eye(3)[(ax + 2) % 3] + if sgn < 0: + u, w = w, u + q = [n * 0.5 + (a * u + b * w) * 0.5 for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))] + for i in (0, 1, 2, 0, 2, 3): + v.append([*q[i], *n]) + return np.array(v, "f4") + + +def perspective(fovy, aspect, near, far): + f = 1 / math.tan(math.radians(fovy) / 2) + return np.array([[f / aspect, 0, 0, 0], [0, f, 0, 0], + [0, 0, (far + near) / (near - far), 2 * far * near / (near - far)], [0, 0, -1, 0]]) + + +def look_at(eye, target, up=(0, 1, 0)): + f = target - eye + f = f / (float(np.linalg.norm(f)) + 1e-9) + r = np.cross(f, up) + r = r / (float(np.linalg.norm(r)) + 1e-9) + u = np.cross(r, f) + m = np.eye(4) + m[0, :3], m[1, :3], m[2, :3] = r, u, -f + m[:3, 3] = -m[:3, :3] @ eye + return m + + +QI = (0.0, 0.0, 0.0, 1.0) +NOFX = (0.0, 0.0, 0.0, 0.0) +ROW = 3 + 3 + 4 + 4 + 4 + 4 + 4 + 2 # floats per instance + + +def _tid(n): + return float(TILES[n]) + + +def _row(c, size, q, color, tiles, over=NOFX, glow=0.0, world_uv=0.0): + f, s, tp, bt, bk = tiles + return [*c, *size, *q, *color, _tid(f), _tid(s), _tid(tp), _tid(bt), _tid(bk), 0.0, 0.0, 0.0, + *over, glow, world_uv] + + +def part_rows(rig, t, crack_layer=None, excluded=()): + """Instances for one rig at fractional tick t. Pivot-aware: box centre = o + R(q) @ pivot.""" + opaque, alpha, glows, cracks = [], [], [], [] + shell = rig.shell + for name, (o, q) in rig.sample(t).items(): + if name in rig.hide or name in excluded: + continue + p = rig.parts[name] + piv = p.get("pivot") or (0, 0, 0) + c = o + q_to_mat(q) @ np.asarray(piv, float) if any(piv) else o + tiles = p.get("tiles") or ("white",) * 5 + col = (*p["color"], 1.0) + g = float(p.get("glow", 0.0)) + g = g * max(rig.glow, 0.35) if g else 0.0 + row = _row(c, p["size"], q, col, tiles, rig.overlay, min(g, 1.0)) + (alpha if p.get("alpha") else opaque).append(row) + if g > 0.5: + s = min(0.7, sum(p["size"]) / 3 * (1.4 + 0.8 * rig.glow)) + glows.append(_row(c, (s, s, s), QI, (*p["color"], 0.55 * g), ("glow",) * 5, glow=1.0)) + if crack_layer and p.get("crack"): + sz = tuple(v + 0.004 for v in p["size"]) + cracks.append(_row(c, sz, q, (1, 1, 1, 1), (crack_layer,) * 5, rig.overlay)) + if shell > 0 and name not in ("armor",) and not p.get("alpha"): + sz = tuple(v + 0.18 for v in p["size"]) + alpha.append(_row(c, sz, q, (*rig.shell_color, shell), ("shell",) * 5, glow=0.6)) + return opaque + cracks, alpha, glows + + +def arrow_rows(arrows): + """Draw simulated arrow positions and velocity directions; no state/RNG changes.""" + rows = [] + for arrow in arrows: + velocity = np.asarray(arrow["vel"], dtype=float) + speed = float(np.linalg.norm(velocity)) + if speed < 1e-12: + continue + direction = velocity / speed + # Quaternion rotating the box's +x shaft onto its actual velocity. + if direction[0] < -1 + 1e-10: + rotation = np.array((0.0, 1.0, 0.0, 0.0)) + else: + rotation = np.array((0.0, -direction[2], direction[1], 1 + direction[0])) + rotation /= np.linalg.norm(rotation) + tip = np.asarray(arrow["pos"], dtype=float) + rows.append(_row(tip - direction * 0.34, (0.68, 0.025, 0.025), rotation, + (0.48, 0.31, 0.14, 1), ("white",) * 5)) + rows.append(_row(tip, (0.11, 0.08, 0.08), rotation, + (0.68, 0.68, 0.65, 1), ("white",) * 5)) + tail = tip - direction * 0.61 + for size in ((0.13, 0.11, 0.015), (0.13, 0.015, 0.11)): + rows.append(_row(tail, size, rotation, (0.90, 0.87, 0.78, 1), ("white",) * 5)) + return rows + + +def _terrain_rows(H, style): + """Column tops and exposed side runs, baked once per arena. Faces tile the texture per metre.""" + S = H.shape[0] + rows = [] + end = style == "towers" + # minecraft-arena@5 themes: (wall, tall column, mid column, low block, floor) as (top, side, bottom) tiles + themed = { + "night": (("stone_brick",) * 3, ("cobble",) * 3, ("mossy_cobble", "mossy_cobble", "cobble"), + ("night_grass", "night_grass_side", "night_dirt"), ("night_grass", "night_grass_side", "night_dirt")), + "deep_dark": (("deepslate_tiles",) * 3, ("sculk", "deepslate", "deepslate"), ("sculk", "deepslate", "deepslate"), + ("sculk_dark", "deepslate", "deepslate"), ("sculk_dark", "deepslate", "deepslate")), + "ruins": (("stone_brick",) * 3, ("cracked_brick",) * 3, ("mossy_brick", "cracked_brick", "cracked_brick"), + ("gravel",) * 3, ("grass_top", "grass_side", "dirt")), + }.get(style) + for (x, z), h in np.ndenumerate(H): + h = int(h) + if themed is not None: + top, side, bot = themed[0 if h >= 8 else 1 if h >= 4 else 2 if h >= 2 else 3 if h == 1 else 4] + elif h >= 8: # arena wall + top, side, bot = ("end_brick", "end_brick", "end_brick") if end else ("stone_brick",) * 3 + elif h >= 4: + top, side, bot = ("obsidian",) * 3 if end else ("cobble", "cobble", "cobble") + elif h >= 2: + top, side, bot = ("end_stone",) * 3 if end else ("mossy_cobble", "mossy_cobble", "cobble") + elif h == 1: + top, side, bot = ("end_stone",) * 3 if end else ("grass_top", "grass_side", "dirt") + else: + top, side, bot = ("end_stone",) * 3 if end else ("grass_top", "grass_side", "dirt") + if h == 0: + rows.append(_row((x + 0.5, -0.5, z + 0.5), (1, 1, 1), QI, (1, 1, 1, 1), + (side, side, top, bot, side), world_uv=1.0)) + continue + # a grass-topped single block keeps its grass_side band on the top metre only + if side in ("grass_side", "night_grass_side"): + rows.append(_row((x + 0.5, h - 0.5, z + 0.5), (1, 1, 1), QI, (1, 1, 1, 1), + (side, side, top, bot, side), world_uv=1.0)) + if h > 1: + rows.append(_row((x + 0.5, (h - 1) / 2, z + 0.5), (1, h - 1, 1), QI, (1, 1, 1, 1), + (bot,) * 5, world_uv=1.0)) + else: + rows.append(_row((x + 0.5, h / 2, z + 0.5), (1, h, 1), QI, (1, 1, 1, 1), + (side, side, top, bot, side), world_uv=1.0)) + return rows + + +class VoxelRenderer: + """Headless MSAA renderer: sky gradient, textured instanced boxes (opaque, then alpha, then an + additive glow pass), blob shadows, distance fog. A frame is a pure function of the case state + and the fractional tick t.""" + + def __init__(self, w, h, samples=8): + samples = int(os.environ.get("BB_MSAA", samples)) + import moderngl + self.mgl = moderngl + self.w, self.h = w, h + self.ctx, self._resources, self._closed = None, [], False + self.terrain, self.terrain_key = None, None + self.cam, self.cam_override = None, None + backend = os.environ.get("BOSSBENCH_GL_BACKEND") + try: + ctx = self.ctx = moderngl.create_standalone_context(**({"backend": backend} if backend else {})) + self.prog = self._own(ctx.program(vertex_shader=VS, fragment_shader=FS)) + self.sky = self._own(ctx.program(vertex_shader=SKY_VS, fragment_shader=SKY_FS)) + self.vbo = self._own(ctx.buffer(_cube().tobytes())) + quad = np.array([-1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1], "f4") + self.sky_vbo = self._own(ctx.buffer(quad.tobytes())) + self.sky_vao = self._own(ctx.vertex_array(self.sky, [(self.sky_vbo, "2f", "in_pos")])) + self.tex = self._own(ctx.texture_array((16, 16, len(TEX)), 4, TEX.tobytes())) + self.tex.filter = (moderngl.NEAREST, moderngl.NEAREST) + samples = min(samples, ctx.max_samples) + mscolor = self._own(ctx.renderbuffer((w, h), 4, samples=samples)) + msdepth = self._own(ctx.depth_renderbuffer((w, h), samples=samples)) + self.msfbo = self._own(ctx.framebuffer(color_attachments=[mscolor], depth_attachment=msdepth)) + color = self._own(ctx.renderbuffer((w, h), 4)) + depth = self._own(ctx.depth_renderbuffer((w, h))) + self.fbo = self._own(ctx.framebuffer(color_attachments=[color], depth_attachment=depth)) + self.ibo = self._own(ctx.buffer(reserve=ROW * 4 * 4096, dynamic=True)) + self.vao = self._own(ctx.vertex_array(self.prog, [ + (self.vbo, "3f 3f", "in_pos", "in_norm"), + (self.ibo, "3f 3f 4f 4f 4f 4f 4f 2f/i", "i_center", "i_size", "i_q", "i_color", "i_tiles", + "i_tiles2", "i_over", "i_fx")])) + except BaseException: + try: + self.close() + except Exception: + pass # preserve the initialization failure after best-effort cleanup + raise + + def _own(self, resource): + self._resources.append(resource) + return resource + + def close(self): + """Release every owned GL object, including a partially initialized renderer.""" + if self._closed: + return + self._closed = True + resources, self._resources = self._resources, [] + errors = [] + if self.ctx is not None: + try: + with self.ctx: + for resource in reversed(resources): + try: + resource.release() + except Exception as ex: + errors.append(ex) + except Exception as ex: + errors.append(ex) + finally: + try: + self.ctx.release() + except Exception as ex: + errors.append(ex) + self.terrain, self.terrain_key, self.cam = None, None, None + if errors: + raise RuntimeError("OpenGL renderer cleanup failed") from errors[0] + + def _upload(self, rows): + data = np.asarray(rows, "f4") + if data.nbytes > self.ibo.size: + self.ibo.orphan(data.nbytes * 2) + self.ibo.write(data.tobytes()) + return len(data) + + def _draw_each(self, rows): + """Blended passes: one instance per draw call, in list order. With 8x MSAA the local GPU (RTX 5070 Ti) blended + the overlapping translucent instances of a single instanced draw in a varying order, so repeated renders of + one state differed by +-1 in a few pixels (the renderer_contract purity flake of 2026-11-01: 10 of 300 + identical renders; 0 of 300 drawn one per call, 0 without MSAA). Costs < 1 ms for the ~20-30 blended rows.""" + for row in rows: + self._upload((row,)) + self.vao.render(instances=1) + + def draw(self, c, t=None): + if self._closed: + raise RuntimeError("OpenGL renderer is closed") + # An RL group can own multiple standalone contexts in the same thread. + with self.ctx: + return self._draw(c, t) + + def _draw(self, c, t=None): + mgl, ctx = self.mgl, self.ctx + t = float(c.t if t is None else t) + A, p, g = c.arena, c.body.e, c.boss.e + theme = THEMES["wither" if c.boss.name == "wither" else A.style] + terrain_key = (A.style, A.H.shape, A.H.dtype.str, A.H.tobytes()) + if self.terrain_key != terrain_key or self.terrain is None: + self.terrain, self.terrain_key = _terrain_rows(A.H, A.style), terrain_key + # Billboards must use this frame's camera, independent of draw history. + eye, target = self._camera(c, p, g, t) + opaque, alpha, glow = list(self.terrain), [], [] + for rig in [c.body.rig] + c.boss.rigs(): + excluded = () + if rig is c.body.rig and c.camera == "first": + # The eye lies inside the player head; keep arms/weapon, expose the world. + excluded = ("head", "torso", "leg_r", "leg_l") + o, a, gl = part_rows(rig, t, rig.variant or None, excluded=excluded) + opaque += o + alpha += a + glow += gl + opaque += arrow_rows(getattr(c, "arrows", ())) + opaque += arrow_rows(getattr(c.boss, "arrows", ())) # skeleton arrows (minecraft-arena@5) + for cr in getattr(c.boss, "crystals", ()): # end crystals: spinning cube in a glass cage + if not cr["alive"]: + continue + spin = (t * VT * 0.12 + cr["id"]) % (2 * math.pi) + centre = cr["pos"] + [0, 0.8 + 0.18 * math.sin(t * VT * 0.1 + cr["id"]), 0] + q1 = (math.sin(spin / 2) * 0.38, math.sin(spin / 2) * 0.6, math.sin(spin / 2) * 0.7, math.cos(spin / 2)) + n = math.sqrt(sum(v * v for v in q1)) + q1 = tuple(v / n for v in q1) + opaque.append(_row(centre, (0.42, 0.42, 0.42), q1, (0.95, 0.45, 0.85, 1), ("white",) * 5, glow=0.9)) + alpha.append(_row(centre, (0.85, 0.85, 0.85), (q1[1], q1[0], q1[3], q1[2]), (0.85, 0.85, 1.0, 0.35), + ("shell",) * 5, glow=0.4)) + opaque.append(_row(cr["pos"] + [0, 0.12, 0], (0.9, 0.24, 0.9), QI, (1, 1, 1, 1), ("bedrock",) * 5)) + glow.append(_row(centre, (1.4, 1.4, 1.4), QI, (1.0, 0.5, 0.9, 0.45), ("glow",) * 5, glow=1.0)) + if getattr(c.boss, "heal_from", None) is cr: # healing beam to the dragon + a_, b_ = centre, c.boss.e.pos + d = b_ - a_ + L = float(np.linalg.norm(d)) + dirn = d / (L + 1e-9) + if dirn[0] < -1 + 1e-9: + qb = (0.0, 1.0, 0.0, 0.0) + else: + qb = np.array((0.0, -dirn[2], dirn[1], 1 + dirn[0])) + qb = tuple(qb / np.linalg.norm(qb)) + glow.append(_row((a_ + b_) / 2, (L, 0.12, 0.12), qb, (1.0, 0.9, 1.0, 0.8), ("white",) * 5, glow=1.0)) + for fb in getattr(c.boss, "fireballs", ()): # dragon fireball + opaque.append(_row(fb["pos"], (0.5, 0.5, 0.5), QI, (0.6, 0.2, 0.75, 1), ("white",) * 5, glow=1.0)) + glow.append(_row(fb["pos"], (1.2, 1.2, 1.2), QI, (0.8, 0.35, 1.0, 0.6), ("glow",) * 5, glow=1.0)) + for cl in getattr(c.boss, "clouds", ()): # dragon's breath area cloud (flat disc) + k = min(1.0, cl["life"] / 0.6) + alpha.append(_row(cl["pos"] + [0, 0.05, 0], (cl["r"] * 2, 0.04, cl["r"] * 2), QI, + (0.7, 0.25, 0.85, 0.35 * k), ("shadow",) * 5)) + for q in c.boss.extra(c): # wither skulls: textured, spinning + spin = (t * VT * 0.35 + float(q["pos"][0])) % (2 * math.pi) + qq = (0.0, math.sin(spin / 2), 0.0, math.cos(spin / 2)) + blue = q.get("blue", False) + opaque.append(_row(q["pos"], q.get("size", (0.42, 0.42, 0.42)), qq, (0.55, 0.75, 1.0, 1) if blue else (1, 1, 1, 1), + ("wither_face", "wither_skull", "wither_skull", "wither_skull", "wither_skull"))) + glow.append(_row(q["pos"], (1.0, 1.0, 1.0), QI, (0.3, 0.25, 0.35, 0.5), ("glow",) * 5, glow=1.0)) + for q in c.fx: + life = q["life"] / q.get("life0", q["life"] or 1) + s = q["size"] * (0.5 + 0.5 * life) if q.get("tile") != "puff" else q["size"] * (1.4 - 0.6 * life) + tile = q.get("tile", "puff") + col = (*q["color"], min(1.0, life * 1.6)) + r = _row(q["pos"], (s, s, s), self._billboard(), col, (tile,) * 5, glow=float(q.get("glow", 0))) + (glow if tile == "glow" else alpha).append(r) + shadows = [(p, 0.45), (g, max(0.7, g.w * 0.75))] + shadows += [(z.e, 0.45) for z in getattr(c.boss, "minions", ()) if z.hp > 0] + for e, rad in shadows: + gy = A.ground(e.pos, rad) + hgt = e.pos[1] - gy + if hgt < 12: + k = max(0.25, 1 - hgt / 12) + alpha.append(_row((e.pos[0], gy + 0.015, e.pos[2]), (rad * 2.2 * (1.3 - 0.3 * k), 0.01, rad * 2.2 * (1.3 - 0.3 * k)), + QI, (1, 1, 1, k), ("shadow",) * 5)) + V = look_at(eye, target) + fov = 70.0 + mvp = perspective(fov, self.w / self.h, 0.05, 120) @ V + self.msfbo.use() + ctx.clear(*theme[1], 1.0) + ctx.disable(mgl.DEPTH_TEST) + tf = math.tan(math.radians(fov) / 2) + self.sky["top"].value, self.sky["bot"].value = theme + self.sky["inv_rot"].write(np.ascontiguousarray(V[:3, :3]).astype("f4").tobytes()) + self.sky["tanf"].value = (tf * self.w / self.h, tf) + self.sky["stars"].value = STARS.get(A.style, 0.0) + self.sky_vao.render() + ctx.enable(mgl.DEPTH_TEST) + pr = self.prog + pr["mvp"].write(mvp.T.astype("f4").tobytes()) + pr["eye"].value = tuple(float(v) for v in eye) + pr["fog_col"].value = theme[1] + pr["fog_rng"].value = FOG.get(A.style, (22.0, 62.0)) + pr["sun"].value = tuple(SUN) + self.tex.use(0) + pr["tex"].value = 0 + pr["alpha_pass"].value = 0.0 + ctx.disable(mgl.BLEND) + self.vao.render(instances=self._upload(opaque)) + if alpha: + ctx.enable(mgl.BLEND) + ctx.blend_func = mgl.SRC_ALPHA, mgl.ONE_MINUS_SRC_ALPHA + pr["alpha_pass"].value = 1.0 + ctx.depth_mask = False + # far-to-near so translucent shadows/smoke/membranes overlap sensibly + alpha.sort(key=lambda r: -float(np.sum((np.array(r[:3]) - eye) ** 2))) + self._draw_each(alpha) + ctx.depth_mask = True + if glow: + ctx.enable(mgl.BLEND) + ctx.blend_func = mgl.SRC_ALPHA, mgl.ONE + pr["alpha_pass"].value = 1.0 + ctx.depth_mask = False + self._draw_each(glow) + ctx.depth_mask = True + ctx.disable(mgl.BLEND) + ctx.copy_framebuffer(self.fbo, self.msfbo) + img = np.frombuffer(self.fbo.read(components=3), np.uint8).reshape(self.h, self.w, 3)[::-1] + return np.ascontiguousarray(img) + + def _billboard(self): + """Camera-facing quaternion (yaw only) so particle quads read as sprites.""" + if self.cam is None: + return QI + f = self.cam[1] - self.cam[0] + yaw = math.atan2(f[2], f[0]) + a = -yaw / 2 + return (0.0, math.sin(a), 0.0, math.cos(a)) + + def _camera(self, c, p, g, t): + if self.cam_override is not None: # debug / turntable views + self.cam = self.cam_override + return self.cam + A = c.arena + rig = c.body.rig + kf = rig.kf.get("torso") + base = p.pos.copy() + if kf and len(kf) >= 2: # interpolated player position + o = rig.sample(t)["torso"][0] + base = np.array([o[0], p.pos[1], o[2]]) + pitch = c.body.e.pitch # real view pitch for every weapon (arena@2) + aim = p.fwd * math.cos(pitch) + np.array([0.0, math.sin(pitch), 0.0]) + if c.camera == "first": + eye = base + [0, 1.62, 0] + self.cam = (eye, eye + aim * 3) + return self.cam + lift = float(np.clip(g.pos[1] - p.pos[1], 0.0, 11.0)) * 0.30 + back, up = 4.4, CAM_UP.get(A.style, 2.6) + lift + pivot = base + [0, 1.6, 0] + + def clear(want): + # raymarch from the pivot toward the wanted eye; stop short of the first solid column + d = want - pivot + L = float(np.linalg.norm(d)) + s = 0.0 + while s < L: + q = pivot + d * (s / L) + ix, iz = int(math.floor(q[0])), int(math.floor(q[2])) + if not (0 <= ix < A.H.shape[0] and 0 <= iz < A.H.shape[1]) or A.H[ix, iz] > q[1] - 0.25: + return d, L, max(0.0, s - 0.35) + s += 0.1 + return d, L, L + + # a pillar or wall right behind the player: crane up over it before pulling in + best = None + for extra in (0.0, 1.5, 3.0, 4.5): + d, L, ok = clear(base + [0, up + extra, 0] - p.fwd * back) + if best is None or ok > best[2] + 0.5: + best = (d, L, ok) + if ok >= L * 0.85: + break + d, L, ok = best + eye = pivot + d * (ok / L) if ok >= 0.9 else pivot + p.fwd * 0.2 # boxed in: over the shoulder + # look along the player's own aim, far enough that a boss overhead stays in frame + target = base + [0, 1.62, 0] + aim * (2.2 + 3.0 * max(0.0, math.sin(pitch))) + self.cam = (eye, target) + return eye, target + + +# ================================================================ HUD +_FONTS = {} + + +def _font(size, bold=False): + key = (size, bold) + if key not in _FONTS: + from PIL import ImageFont + for path in (("C:/Windows/Fonts/consolab.ttf" if bold else "C:/Windows/Fonts/consola.ttf"), + "DejaVuSansMono-Bold.ttf" if bold else "DejaVuSansMono.ttf"): + try: + _FONTS[key] = ImageFont.truetype(path, size) + break + except OSError: + continue + else: + _FONTS[key] = ImageFont.load_default() + return _FONTS[key] + + +STATE_HUD = {"windup": "WIND UP", "lineup": "TELEGRAPH", "charge": "CHARGE", "swing": "SWING", + "strike": "STRIKE", "dash": "DASH", "recover": "RECOVER", "chase": "CHASE", + "circle": "CIRCLING", "climb": "CLIMBING", "hover": "HOVERING", "spawn": "SPAWNING - INVULNERABLE", + "armored": "SHELL UP - ARROWS BOUNCE", "nolos": "NO LINE OF SIGHT", "strafe": "STRAFING", + "perch": "PERCHED"} +PHASE_HUD = {"holding": "CIRCLING", "strafe": "STRAFING", "landing": "LANDING", "scanning": "PERCHED - SCANNING", + "roar": "PERCHED - ROAR", "flaming": "PERCHED - BREATH", "takeoff": "TAKING OFF", "charge": "CHARGING YOU"} +# the warden's phases (minecraft-arena@5); its 'roar' must not read as the dragon's perched roar +WARDEN_HUD = {"emerge": "EMERGING - INVULNERABLE", "roar": "ROARING", "chase": "HUNTING", "windup": "SMASH - BACK OFF", + "recover": "RECOVERING - OPENING", "boom": "SHOCKWAVE CHARGING", "boom_recover": "RECOVERING - OPENING"} +TITLES = {"iron_golem": "Hurling Brute", "zombie": "Green Brawler", "ender_dragon": "Violet Breath Flyer", + "wither": "Three-Headed Hover Gun", "warden": "Blind Shockwave Beast", "skeleton": "Strafing Bowman", + "zombie_leader": "Horde Caller"} +BAR = {"iron_golem": (230, 225, 215), "zombie": (90, 170, 80), "ender_dragon": (200, 60, 220), "wither": (60, 60, 70), + "warden": (40, 160, 170), "skeleton": (215, 212, 200), "zombie_leader": (90, 170, 80)} + + +def _darkness(out, c, h, w): + """Java Darkness: the world dims in slow pulses while the effect lasts (warden, minecraft-arena@5). Drawn over the + rendered frame, under the HUD, so health and timers stay readable.""" + g = c.boss + left = getattr(g, "dark_t", 0) + if left <= 0: + return out + pulse = 0.5 + 0.5 * math.sin(c.t * VT * 0.21) + fade = min(1.0, left / max(1.0, 40 / VT)) + yy, xx = np.mgrid[0:h, 0:w] + r = np.hypot((xx - w / 2) / (w / 2), (yy - h / 2) / (h / 2)) + # strong at the edges, light in the middle: the warden (who is usually in front of the player) stays readable + k = (0.25 + 0.35 * pulse) * fade * np.clip(r * 0.9, 0.08, 1.0)[..., None] + return out * (1 - k) + + +def hud(img, c): + """Minecraft-flavoured HUD: boss bar with name on top, hearts + attack indicator at the bottom, + telegraph banner and a red vignette pulse on damage.""" + from PIL import Image, ImageDraw + h, w = img.shape[:2] + u = h / 480.0 + b, g = c.body, c.boss + out = img.astype(np.float32) + out = _darkness(out, c, h, w) + hurt = b.iframes * VT # vanilla ticks of hurt immunity left + if hurt > 6: # hurt vignette + yy, xx = np.mgrid[0:h, 0:w] + r = np.hypot((xx - w / 2) / (w / 2), (yy - h / 2) / (h / 2)) + k = np.clip(r - 0.55, 0, 1)[..., None] * 0.9 * (hurt - 6) / 4 + out = out * (1 - k) + np.array([170, 0, 0]) * k + phase = getattr(g, "phase", None) + hot = g.state in ("windup", "lineup", "spawn") or phase in ("roar", "charge", "boom") or ( + phase == "strafe" and getattr(g, "goal", None) is not None) + if hot and int(c.t * VT // 2) % 2 == 0: + out[:int(3 * u)] = out[:int(3 * u)] * 0.4 + np.array([255, 200, 40]) * 0.6 + im = Image.fromarray(out.clip(0, 255).astype(np.uint8)) + d = ImageDraw.Draw(im) + # boss bar + bw, bh, by = int(w * 0.46), max(3, int(7 * u)), int(26 * u) + bx = (w - bw) // 2 + flag = {"wither": " [SHELL UP]", "ender_dragon": " [NO CRYSTALS]"}.get(g.name, " [ENRAGED]") + title = TITLES.get(g.name, g.name) + (flag if g.enraged else "") + f = _font(max(10, int(16 * u)), True) + tw = d.textlength(title, font=f) + d.text(((w - tw) / 2 + 1, by - int(20 * u) + 1), title, font=f, fill=(40, 40, 40)) + d.text(((w - tw) / 2, by - int(20 * u)), title, font=f, fill=(255, 255, 255)) + d.rectangle([bx - 1, by - 1, bx + bw + 1, by + bh + 1], fill=(20, 20, 20)) + frac = max(g.hp, 0) / g.max_hp + col = (255, 70, 60) if g.enraged else BAR.get(g.name, (200, 60, 200)) + d.rectangle([bx, by, bx + int(bw * frac), by + bh], fill=col) + for i in range(1, 20): # notches + x = bx + bw * i // 20 + d.line([x, by + bh // 2, x, by + bh], fill=(0, 0, 0)) + # numeric boss health: the tiers differ in maximum health (2026-11-02), which the bar alone does not show + f4 = _font(max(9, int(12 * u)), True) + hp_txt = f"{max(g.hp, 0):.0f} / {g.max_hp:.0f}" + d.text((bx + bw + int(8 * u) + 1, by - int(4 * u) + 1), hp_txt, font=f4, fill=(0, 0, 0)) + d.text((bx + bw + int(8 * u), by - int(4 * u)), hp_txt, font=f4, fill=(235, 235, 235)) + # state tag + if g.name == "warden": + tag = WARDEN_HUD.get(phase, phase.upper()) + else: + tag = PHASE_HUD.get(phase, None) if phase else None + tag = tag or STATE_HUD.get(g.state, g.state.upper()) + if hasattr(g, "crystals"): + tag += f" CRYSTALS {sum(x['alive'] for x in g.crystals)}" + if g.name == "zombie_leader": + tag += f" REINFORCEMENTS {sum(z.hp > 0 for z in g.minions)}" + if g.name == "skeleton" and g.state == "windup": + tag = "DRAWING - TAKE COVER" + f2 = _font(max(9, int(13 * u)), True) + tc = (255, 210, 60) if hot else (255, 120, 90) if g.state in ("swing", "strike", "dash", "armored") else (210, 210, 210) + tw = d.textlength(tag, font=f2) + d.text(((w - tw) / 2 + 1, by + bh + int(5 * u) + 1), tag, font=f2, fill=(0, 0, 0)) + d.text(((w - tw) / 2, by + bh + int(5 * u)), tag, font=f2, fill=tc) + # fight clock + native simulation rate, top right + f5 = _font(max(9, int(12 * u)), True) + clock = f"{c.t / FPS:6.1f} s {FPS}Hz" + cw5 = d.textlength(clock, font=f5) + d.rectangle([w - cw5 - int(14 * u), int(6 * u), w - int(6 * u), int(24 * u)], fill=(16, 16, 20)) + d.text((w - cw5 - int(10 * u), int(8 * u)), clock, font=f5, fill=(235, 235, 235)) + # hearts (pixel art; black while the Wither effect drains, white outline blink while hurt-immune) + px = max(1, int(round(u))) + hw = 9 * px + px + hx, hy = int(w / 2 - 10 * hw / 2), h - int(44 * u) + heart = (".XXX.XXX.", "XXXXXXXXX", "XXXXXXXXX", "XXXXXXXXX", ".XXXXXXX.", "..XXXXX..", "...XXX...", "....X....") + withered = getattr(b, "wither_t", 0) > 0 + blink = b.iframes > 0 and int(c.t * VT / 3) % 2 == 0 + fill = (40, 34, 34) if withered else (214, 28, 28) + shine = (120, 110, 110) if withered else (255, 150, 150) + edge = (250, 250, 250) if blink else (24, 8, 8) + empty = (60, 18, 18) + pts = {"edge": [], "fill": [], "shine": [], "empty": []} + for i in range(10): + ox = hx + i * hw + full = b.hp - 2 * i + for y, row in enumerate(heart): + for x, ch in enumerate(row): + if ch != "X": + continue + for ex, ey in ((-1, 0), (1, 0), (0, -1), (0, 1)): + pts["edge"].append((ox + (x + ex) * px, hy + (y + ey) * px)) + for y, row in enumerate(heart): + for x, ch in enumerate(row): + if ch != "X": + continue + lit = full >= 2 or (full >= 1 and x <= 4) + key = ("shine" if (x, y) in ((2, 1), (1, 2)) else "fill") if lit else "empty" + pts[key].append((ox + x * px, hy + y * px)) + for key, col in (("edge", edge), ("empty", empty), ("fill", fill), ("shine", shine)): + for (x0, y0) in pts[key]: + d.rectangle([x0, y0, x0 + px - 1, y0 + px - 1], fill=col) + # armor points above the hearts (2 points per icon, grey chestplates) + armor = float(b.k.armor) + ay = hy - int(11 * u) + for i in range(10): + ox = hx + i * hw + level = armor - 2 * i + if level <= 0: + continue + col = (205, 210, 215) + d.rectangle([ox + px, ay, ox + 8 * px, ay + 6 * px], fill=(40, 40, 44)) + right = ox + (8 if level >= 2 else 4) * px + d.rectangle([ox + 2 * px, ay + px, right - px, ay + 5 * px], fill=col) + # attack charge (crosshair indicator) + cw = int(16 * u) + cx, cy = w // 2, h // 2 + d.line([cx - 5, cy, cx + 5, cy], fill=(240, 240, 240)) + d.line([cx, cy - 5, cx, cy + 5], fill=(240, 240, 240)) + is_bow = getattr(b, "weapon", "sword") == "bow" + if b.charge < 1.0 or is_bow: + d.rectangle([cx - cw // 2, cy + int(10 * u), cx + cw // 2, cy + int(12 * u)], fill=(60, 60, 60)) + d.rectangle([cx - cw // 2, cy + int(10 * u), cx - cw // 2 + int(cw * b.charge), cy + int(12 * u)], + fill=(235, 185, 70) if is_bow else (230, 230, 230)) + if is_bow: + draw_status = f"BOW {round(b.bow_charge * 100):d}%" if b.bow_drawing else "BOW / HOLD RMB" + f3 = _font(max(9, int(11 * u))) + tw = d.textlength(draw_status, font=f3) + d.text(((w - tw) / 2, h - int(66 * u)), draw_status, font=f3, fill=(255, 218, 128)) + if b.bow_drawing: + d.text((int(10 * u), h - int(26 * u)), "Release RMB to fire", font=f3, fill=(255, 218, 128)) + # hotbar: slot 1 sword, slot 2 bow, frame on the held slot (mouse wheel switches) + slot = int(20 * u) + sx, sy = int(w / 2 - 4.5 * slot), h - int(26 * u) + for i in range(9): + d.rectangle([sx + i * slot, sy, sx + (i + 1) * slot - 1, sy + slot - 1], outline=(30, 30, 30), + fill=(118, 118, 118) if i < 2 else (96, 96, 96)) + held = 1 if is_bow else 0 + d.rectangle([sx + held * slot - 1, sy - 1, sx + (held + 1) * slot, sy + slot], outline=(255, 255, 255), + width=max(1, int(round(1.5 * u)))) + bx = sx + slot + d.line([(bx + 5, sy + 3), (bx + slot - 5, sy + slot // 2), (bx + 5, sy + slot - 4)], + fill=(205, 146, 65), width=max(1, int(2 * u))) + d.line([(bx + 5, sy + 3), (bx + 4, sy + slot // 2), (bx + 5, sy + slot - 4)], fill=(235, 230, 205), width=1) + d.line([sx + 4, sy + slot - 5, sx + slot - 5, sy + 4], fill=(120, 225, 235), width=max(1, int(2 * u))) + d.line([sx + 4, sy + slot - 5, sx + 8, sy + slot - 9], fill=(110, 75, 40), width=max(1, int(2 * u))) + if is_bow and getattr(c, "arrows", None): + f3 = _font(max(9, int(12 * u))) + d.text((int(10 * u), int(27 * u) if getattr(g, "skulls", None) else int(10 * u)), + f"arrows in flight: {len(c.arrows)}", font=f3, fill=(245, 220, 170)) + if getattr(g, "skulls", None): + f3 = _font(max(9, int(12 * u))) + d.text((int(10 * u), int(10 * u)), f"shells in flight: {len(g.skulls)}", font=f3, fill=(220, 200, 255)) + return np.asarray(im) diff --git a/environments/games/prototype/bossbench/native_games.py b/environments/games/prototype/bossbench/native_games.py new file mode 100644 index 0000000000000000000000000000000000000000..21c3e700770ae0e6512205dae0d37cb1aed2227c --- /dev/null +++ b/environments/games/prototype/bossbench/native_games.py @@ -0,0 +1,249 @@ +"""Optional browser-backed integrations; no dependency on a game's internal world classes. + +The protocol also permits other implementations (native executable, RPC, Python). +Only this integration knows JavaScript and Canvas. All instances have isolated pages. +""" +from __future__ import annotations + +import base64 +import io +import json +import os +from pathlib import Path + +import numpy as np +from PIL import Image + +from .engine_contract import EngineSpec, EngineSnapshot, RenderStatus + +WEB = Path(__file__).resolve().parents[2] / 'web' + + +def _discover_native_games(): + """Every web/games//manifest.json with engine "independent" is a native game. + + New games register themselves by adding their own manifest; no shared file has to change. + """ + games = [] + for manifest in sorted((WEB / 'games').glob('*/manifest.json')): + if manifest.parent.name.startswith(('_', '.')): + continue + try: + data = json.loads(manifest.read_text(encoding='utf8')) + except (OSError, ValueError): + continue + if data.get('engine') == 'independent': + games.append(manifest.parent.name) + return tuple(games) + + +NATIVE_GAMES = _discover_native_games() + + +def _load_manifests(): + """Each independent game declares itself in web/games//manifest.json (bossbench/game-manifest@1). + + The JS module's own declaration (hz, version, renderer) is checked against it when a backend starts, + so a game folder can bump its rule version or add script files without editing this module. + """ + cases = {} + for game in NATIVE_GAMES: + manifest = json.loads((WEB / 'games' / game / 'manifest.json').read_text(encoding='utf8')) + if manifest.get('schema') != 'bossbench/game-manifest@1' or manifest.get('game') != game: + raise RuntimeError(f'{game}: invalid manifest.json') + for case_id in manifest['cases']: + if case_id in cases: + raise RuntimeError(f'native case declared twice: {case_id}') + cases[case_id] = {'game': game, 'dimension': manifest['dimension'], 'hz': manifest['native_hz'], + 'module': manifest['module'], 'renderer': manifest['renderer'], + 'seconds': manifest['max_seconds'], 'version': manifest['rules'], + 'scripts': tuple(manifest['scripts'])} + return cases + + +NATIVE_CASES = _load_manifests() + + +def source_paths(case_id): + spec = NATIVE_CASES[case_id] + return [Path(__file__), *(WEB / 'games' / path for path in spec['scripts'])] + + +class JavaScriptBackend: + def __init__(self, case_id): + from .webenv import BrowserTransport + self.case_id = case_id + entry = NATIVE_CASES[case_id] + self.spec = EngineSpec(entry['game'], entry['dimension'], entry['hz'], entry['seconds'], + entry['renderer'], 'perspective' if entry['dimension'] == '3d' else 'raster', + rule_version=entry['version']) + self.page = None + self._pid = os.getpid() + self._ready = False + self._error = None + self._reset = False + try: + self.page = BrowserTransport._launch().new_page(viewport={'width': 854, 'height': 480}) + self.page.set_content('') + for script in source_paths(case_id)[1:]: + self.page.add_script_tag(path=str(script)) + self.page.evaluate('name => { window.backendModule=window[name]; window.backendCanvas=document.querySelector("canvas"); }', entry['module']) + declaration = self.page.evaluate('() => [backendModule.hz,backendModule.version,backendModule.renderer]') + if declaration != [self.spec.native_hz, self.spec.rule_version, self.spec.renderer]: + raise RuntimeError('Python/JavaScript engine declaration mismatch') + from .tiers import validate_declared + self._tiers = validate_declared(self.page.evaluate('() => backendModule.tiers || null'), + where=f'{entry["module"]}.tiers') + # A game that declares validateOptions opts in to game-specific reset options (loadouts etc.); + # one that does not keeps refusing anything beyond the harness's own keys. + self._accepts_options = bool(self.page.evaluate( + '() => typeof backendModule.validateOptions === "function"')) + self._has_band = bool(self.page.evaluate( + '() => typeof backendModule.difficultyBand === "function"')) + except BaseException: + self.close() + raise + + def _open(self): + if self.page is None: + raise RuntimeError('backend is closed') + if self._pid != os.getpid(): + raise RuntimeError('backend belongs to another process; use spawned workers') + + # Reset options the shared harness itself understands. Anything else is a *game* option: it is forwarded + # only when the game declares a validator (Module.validateOptions) and is rejected by that validator's own + # rules, so a typo still fails loudly instead of being silently ignored. 2026-11-03, requested by + # isaac_remake (item loadouts); games without a validator keep the old behaviour of refusing extras. + HARNESS_OPTIONS = frozenset({'difficulty', 'latency', 'engine_seed', 'resolved_from_tier'}) + + def game_options(self, options): + """Split reset options into the harness's own and the game's, validating the latter in the game.""" + extra = {k: v for k, v in (options or {}).items() if k not in self.HARNESS_OPTIONS} + if not extra: + return None + if not self._accepts_options: + raise ValueError(f'unsupported {self.spec.engine_id} reset options: {sorted(extra)}') + try: + self.page.evaluate('a => backendModule.validateOptions(a)', extra) + except Exception as error: # the game's own message is the useful one + raise ValueError(f'{self.spec.engine_id} rejected reset options {sorted(extra)}: ' + f'{str(error).splitlines()[0][:160]}') from None + return extra + + def validate_options(self, options): + self.game_options(options) + + def _snapshot(self, expression, argument=None): + # JSON canonicalization matches the Node validation path, including -0. + result = json.loads(self.page.evaluate(f'a => JSON.stringify({expression})', argument)) + result['events'] = tuple(result['events']) + return EngineSnapshot(**result) + + def reset(self, seed, difficulty, options): + self._open() + extra = self.game_options(options) + self.page.evaluate('a => { window.backendSession=new NativeBench.Session(backendModule,a.id,a.seed,a.d,a.options);' + ' backendSession.recording=false; }', + {'id': self.case_id, 'seed': seed, 'd': difficulty, 'options': extra}) + self._reset = True + self._ready, self._error = False, None + return self._snapshot('backendSession.snapshot()') + + def advance(self, packet): + self._open() + if not self._reset: + raise RuntimeError('reset before advancing') + return self._snapshot('backendSession.packet(a)', + {'holds': [sorted(h) for h in packet.holds], 'mouse': list(packet.mouse)}) + + def render(self): + self._open() + if not self._reset: + raise RuntimeError('reset before rendering') + try: + result = self.page.evaluate('''() => { + const context=backendCanvas.getContext("2d"); + backendModule.draw(backendSession.game,context); + return {png:backendCanvas.toDataURL("image/png").split(",")[1], + status:backendModule.renderStatus ? backendModule.renderStatus(context) : null}; + }''') + status = result['status'] + if status is not None and (not status.get('ready') or status.get('error') + or status.get('kind') != self.spec.render_kind + or status.get('renderer') != self.spec.renderer): + raise RuntimeError(f"game renderer not ready: {status}") + png = result['png'] + with Image.open(io.BytesIO(base64.b64decode(png))) as image: + rgb = np.asarray(image.convert('RGB'), dtype=np.uint8).copy() + if rgb.shape != (480, 854, 3): + raise RuntimeError('renderer returned an incorrect resolution') + self._ready, self._error = True, None + return rgb + except Exception as error: + self._ready, self._error = False, str(error) + raise + + def render_status(self): + return RenderStatus(self.spec.renderer, self.spec.render_kind, self._ready, self._error) + + def declared_tiers(self): + """The module's own Module.tiers = {easy, normal, hard} -> difficulty, validated at startup.""" + return getattr(self, '_tiers', None) + + def difficulty_band(self, d): + """Module.difficultyBand(d) -> the game's own name for the segment d falls in, or None. + + Optional. Pure function of d, so it exposes nothing the public info does not already carry, and so + it is cached per difficulty — _info() runs every step, and querying the page each time wasted a + measurable share of a step (measured by the Cuphead session on the web route, 2026-11-03). + """ + if not getattr(self, '_has_band', False): + return None + key = float(d) + cache = getattr(self, '_band_cache', None) + if cache is None: + cache = self._band_cache = {} + if key not in cache: + from .unified import _clean_band + cache[key] = _clean_band( + self.page.evaluate('d => backendModule.difficultyBand(d) ?? null', key), + f'{self.case_id}.difficultyBand') + return cache[key] + + def scripted(self): + """Trusted reference controller (Module.scripted, else Module.oracle) for the current state. + + Returns {holds: 6 key arrays, mouse: [dx, dy, dz]}; it must not change the simulation. + """ + self._open() + if not self._reset: + raise RuntimeError('reset before asking the scripted controller') + return self.page.evaluate('''() => { + const M=backendModule, f=M.scripted||M.oracle; + if(typeof f!=='function') throw Error(M.id+': no scripted controller (Module.scripted)'); + const before=NativeBench.hash(backendSession.state()); + const out=f.call(M, backendSession.game); + if(NativeBench.hash(backendSession.state())!==before) throw Error('scripted controller changed the simulation'); + return {holds:out.holds.map(h=>[...h]), mouse:[...(out.mouse||[0,0,0])]}; + }''') + + def manual(self): + self._open() + return self.page.evaluate('''() => ({controls:Array.isArray(backendModule.controls) + ? backendModule.controls : Object.entries(backendModule.controls).map(([key,value])=>key+": "+value)})''') + + def close(self): + page, self.page = self.page, None + self._ready = False + if page is not None and self._pid == os.getpid() and not page.is_closed(): + try: + page.evaluate('''() => { + if(window.backendModule && backendModule.closeRenderer && window.backendCanvas) + backendModule.closeRenderer(backendCanvas.getContext("2d")); + }''') + finally: + page.close() + + +def backend_factory(case_id): + return lambda: JavaScriptBackend(case_id) diff --git a/environments/games/prototype/bossbench/play_server.py b/environments/games/prototype/bossbench/play_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2d6d81696ba420543e14af430a84c3324d5f90bd --- /dev/null +++ b/environments/games/prototype/bossbench/play_server.py @@ -0,0 +1,404 @@ +"""Human play server for the Minecraft remake: the real mc4d simulation + ModernGL renderer behind a browser page. + + python games/prototype/bossbench/play_server.py # http://127.0.0.1:8765/ + python games/prototype/bossbench/play_server.py --port 8770 --open + +Standard library only (http.server on 127.0.0.1). Each browser tab owns one session = one public-interface style +environment (bossbench.make(case, obs_mode="symbolic") -> PyCaseEnv -> mc4d.MobFight), so a human packet is decoded +by exactly the same keymouse.schedule + Steve.keys path as bossbench.make_policy_env. The page streams its own input +as legal `bossbench/policy-replay@1` packets: one packet = 200 ms = 6 hold sets of <= 4 keys + mouse dx dy dz. + + GET / -> web/games/minecraft_remake/index.html (and its static files) + GET /api/meta -> rules, tiers, cases, options, controls, protocol + POST /api/new {case, seed, tier | difficulty, weapon, camera} -> {sid, state} + POST /api/step {sid, packets:[text,...]} -> {state, outcome, ...} (<= 5 packets) + POST /api/scripted {sid, n} -> runs the standard scripted controller n packets + GET /api/frame?sid=..&t=.. -> image/jpeg of the current state from the real renderer (+HUD) + GET /api/replay?sid=.. -> the session's packets as bossbench/policy-replay@1 + POST /api/import {replay} -> new session, re-simulated packet by packet, checked against rules/outcome/hash + +The world never advances on its own: the browser sends a packet every 200 ms (pause = stop sending), so the +simulation stays a pure function of (case, seed, options, packets) and every play can be exported and re-verified. +""" +from __future__ import annotations + +import argparse +import io +import json +import os +import pathlib +import secrets +import sys +import threading +import time +import traceback +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +ROOT = pathlib.Path(__file__).resolve().parents[2] +if str(ROOT / "prototype") not in sys.path: + sys.path.insert(0, str(ROOT / "prototype")) + +import numpy as np # noqa: E402 + +import bossbench # noqa: E402 +from bossbench import keymouse as km, mc4d, mc_scripted, tiers # noqa: E402 + +PAGE = ROOT / "web" / "games" / "minecraft_remake" +CASES = tuple(f"3d/minecraft_{m}" for m in mc4d.MOBS) +# 2026-11-10 (user: "remove the Green Brawler"): the scene list the page offers is the benchmark's six. The retired green zombie +# stays playable by id (old replays, the frozen formal case); it is just not offered in the dropdown. +from bossbench.scope import BENCH_RETIRED # noqa: E402 +LISTED = tuple(c for c in CASES if c not in BENCH_RETIRED) +NAMES = {"3d/minecraft_iron_golem": "Hurling Brute", "3d/minecraft_zombie": "Green Brawler", + "3d/minecraft_ender_dragon": "Violet Breath Flyer", "3d/minecraft_wither": "Three-Headed Hover Gun", + "3d/minecraft_warden": "Blind Shockwave Beast", "3d/minecraft_skeleton": "Strafing Bowman", + "3d/minecraft_zombie_leader": "Horde Caller"} +TIER_LABELS = {"easy": "Easy", "normal": "Normal", "hard": "Hard"} # as the shared page shells +REPLAY_FORMAT = "bossbench/policy-replay@1" +MAX_SESSIONS = 6 +TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", + ".json": "application/json; charset=utf-8", ".png": "image/png", ".jpg": "image/jpeg", ".svg": "image/svg+xml", + ".md": "text/plain; charset=utf-8", ".mp4": "video/mp4"} + + +class Session: + """One live episode. All access is serialized by the session lock (GL contexts are not thread-safe).""" + + def __init__(self, case_id, seed, difficulty, options, tier=None): + self.lock = threading.RLock() + self.case_id = case_id + self.env = bossbench.make(case_id, obs_mode="symbolic") + self.used = time.time() + self.reset(seed, difficulty, options, tier) + + def reset(self, seed, difficulty, options, tier=None): + # A public tier is resolved by the env from mc4d.TIERS (bossbench.tiers), exactly as make_policy_env does; + # the session then pins the concrete difficulty plus resolved_from_tier, like a harness replay. + opts = {"tier": tier} if tier is not None else {"difficulty": float(difficulty)} + opts["engine_seed"] = int(seed) + opts.update({k: v for k, v in options.items() if k in ("weapon", "camera")}) + self.seed = int(seed) + _, info = self.env.reset(seed=int(seed), options=dict(opts)) + if tier is not None: + opts.pop("tier") + opts["difficulty"], opts["resolved_from_tier"] = float(info["difficulty"]), tier + self.options = opts + self.packets, self.outcome, self.scripted_packets = [], None, 0 + + @property + def case(self): + return self.env.unwrapped.case + + def step(self, packet, shots=None, every=2): + """Run one packet; with shots=[] also render a frame every `every` ticks (30 fps at 60 Hz) into it. + Rendering only reads the state (renderer contract), so frames never change the simulation.""" + if self.outcome is not None: + return False + if km.parse_packet(packet) is None: + raise ValueError("illegal packet: " + repr(packet)[:200]) + case = self.case + if shots is not None: + tick, inner = type(case).tick, self.env.unwrapped.inner + + def wrapped(action, _case=case): + tick(_case, action) + if _case.t % every == 0 or _case.outcome(): + shots.append(self.jpeg(inner.render())) + case.tick = wrapped + try: + _, _, terminated, truncated, info = self.env.step(packet) + finally: + case.__dict__.pop("tick", None) + self.packets.append(packet) + if terminated or truncated: + self.outcome = info["outcome"] + return True + + @staticmethod + def jpeg(image, quality=74, data_url=True): + from PIL import Image + import base64 + buffer = io.BytesIO() + Image.fromarray(image).save(buffer, "JPEG", quality=quality) + raw = buffer.getvalue() + return "data:image/jpeg;base64," + base64.b64encode(raw).decode("ascii") if data_url else raw + + def frame(self, quality=78): + return self.jpeg(self.env.unwrapped.inner.render(), quality, data_url=False) + + def summary(self): + c, raw = self.case, self.env.unwrapped + b, g = c.body, c.boss + boss = {"name": NAMES.get(self.case_id, g.name), "kind": g.name, "hp": round(max(float(g.hp), 0.0), 2), + "max_hp": float(g.max_hp), "state": g.state, "phase": getattr(g, "phase", g.state), + "armored": bool(getattr(g, "armored", False)), + "crystals": sum(x["alive"] for x in getattr(g, "crystals", ())) if hasattr(g, "crystals") else None, + "minions": sum(z.hp > 0 for z in getattr(g, "minions", ())) if hasattr(g, "minions") else None, + "darkness_s": round(getattr(g, "dark_t", 0) / mc4d.FPS, 1) if hasattr(g, "dark_t") else None} + player = {"hp": round(max(float(b.hp), 0.0), 2), "max_hp": float(b.max_hp), "weapon": b.weapon, + "kit": getattr(b, "kit", "diamond"), + "attack_charge": round(float(b.attack_charge), 3), "bow_charge": round(float(b.bow_charge), 3), + "bow_drawing": bool(b.bow_drawing), "arrows_fired": b.arrows_fired, "arrows_hit": b.arrows_hit, + "wither_effect_s": round(b.wither_t / mc4d.FPS, 2), "yaw_deg": round(float(np.degrees(b.e.yaw)), 1), + "pitch_deg": round(float(np.degrees(b.e.pitch)), 1)} + return {"case": self.case_id, "seed": self.seed, "options": self.options, "rules": mc4d.RULES, + "t": round(c.t / mc4d.FPS, 3), "ticks": int(c.t), "packets": len(self.packets), + "max_seconds": raw.max_seconds, "outcome": self.outcome, "player": player, "boss": boss, + "last_swing_t": round(b.swing_t / mc4d.FPS, 3), + "scripted_packets": self.scripted_packets, "camera": c.camera} + + def replay(self): + raw = self.env.unwrapped + ver = raw.verifier() + return {"format": REPLAY_FORMAT, "case_id": self.case_id, "game": "minecraft", "contract": "bossbench/policy-gym@2", + "rules": mc4d.RULES, "native_hz": raw.fps, "gym_seed": self.seed, "engine_seed": int(raw.engine_seed), + "options": self.options, + "controller": "human (play page)" if self.scripted_packets == 0 else + f"mixed: {self.scripted_packets} of {len(self.packets)} packets from the scripted controller", + "packets": list(self.packets), "steps": len(self.packets), "ticks": int(self.case.t), + "seconds": round(self.case.t / raw.fps, 4), "outcome": ver["outcome"], + "terminated": ver["outcome"] in ("win", "loss"), "truncated": ver["outcome"] == "timeout", + "verifier": ver, "final_hash": raw.state_hash()} + + def close(self): + try: + self.env.close() + except Exception: + pass + + +SESSIONS: dict = {} +SLOCK = threading.Lock() +# WGL/GLX contexts are bound to the thread that made them current; http.server answers every request on a new +# thread. All simulation + rendering therefore runs on this one worker thread (requests are serialized). +from concurrent.futures import ThreadPoolExecutor # noqa: E402 +GL = ThreadPoolExecutor(max_workers=1, thread_name_prefix="bossbench-gl") + + +def _session(sid): + with SLOCK: + s = SESSIONS.get(sid) + if s is None: + raise KeyError("unknown or expired session; press Start again") + s.used = time.time() + return s + + +def _new_session(body): + case_id = body.get("case", LISTED[0]) + if case_id not in CASES: + raise ValueError(f"unknown case {case_id!r}") + seed = int(body.get("seed", 1)) + if not 0 <= seed < 2 ** 32: + raise ValueError("seed must be in [0, 2**32)") + tier = body.get("tier") + if tier is not None and "difficulty" in body: + raise ValueError("pass either tier or difficulty, not both") + if tier is not None and tier not in tiers.TIER_NAMES: + raise ValueError(f"tier must be one of {tiers.TIER_NAMES}") + difficulty = float(body.get("difficulty", 0.5)) + if not 0.0 <= difficulty <= 1.0: + raise ValueError("difficulty must be in [0, 1]") + options = {k: body[k] for k in ("weapon", "camera") if k in body} + sid = secrets.token_hex(8) + s = Session(case_id, seed, difficulty, options, tier=tier) + if tier is None and body.get("resolved_from_tier") in tiers.TIER_NAMES: # an imported tier recording + s.options["resolved_from_tier"] = body["resolved_from_tier"] + with SLOCK: + SESSIONS[sid] = s + while len(SESSIONS) > MAX_SESSIONS: # drop the least recently used session + old = min(SESSIONS, key=lambda k: SESSIONS[k].used) + SESSIONS.pop(old).close() + return sid, s + + +def meta(): + body = mc4d.Steve() + declared = tiers.validate_declared(getattr(mc4d, "TIERS", None), "mc4d") or dict(tiers.DEFAULT_TIERS) + return {"rules": mc4d.RULES, "native_hz": mc4d.FPS, "packet_seconds": km.PACKET_SECONDS, "substeps": km.SUBSTEPS, + "keys": list(km.KEYS), "max_keys": km.MAX_KEYS, "protocol": bossbench.unified.PROTOCOL, + "cases": [{"id": c, "name": NAMES[c], "max_seconds": mc4d.SECONDS[c.split("_", 1)[1]]} for c in LISTED], + "tiers": [{"name": t, "label": TIER_LABELS[t], "difficulty": declared[t], + "target_seconds": list(tiers.TARGET_SECONDS[t])} for t in tiers.TIER_NAMES], + "default_tier": "normal", + "weapons": list(mc4d.WEAPONS), "cameras": ["first", "third"], "controls": list(body.MANUAL), + "replay_format": REPLAY_FORMAT} + + +class Handler(BaseHTTPRequestHandler): + server_version = "BossBenchMinecraft/1" + + def log_message(self, fmt, *args): # quiet: one line per error only + if args and str(args[1]).startswith(("4", "5")): + sys.stderr.write("%s %s\n" % (self.address_string(), fmt % args)) + + def _send(self, code, payload, ctype="application/json; charset=utf-8", extra=None): + data = payload if isinstance(payload, bytes) else json.dumps(payload, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.send_header("Access-Control-Allow-Origin", "*") # the lobby / file:// page talks to 127.0.0.1 + for k, v in (extra or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(data) + + def _json(self): + n = int(self.headers.get("Content-Length") or 0) + if n > 16_000_000: + raise ValueError("request too large") + return json.loads(self.rfile.read(n) or b"{}") + + def do_OPTIONS(self): + self.send_response(204) + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + self.send_header("Access-Control-Allow-Headers", "Content-Type") + self.end_headers() + + def do_GET(self): + return GL.submit(self._get).result() + + def do_POST(self): + return GL.submit(self._post).result() + + def _get(self): + url = urlparse(self.path) + q = parse_qs(url.query) + try: + if url.path == "/api/meta": + return self._send(200, meta()) + if url.path == "/api/frame": + s = _session(q.get("sid", [""])[0]) + with s.lock: + data = s.frame(int(q.get("q", ["78"])[0])) + return self._send(200, data, "image/jpeg") + if url.path == "/api/state": + s = _session(q.get("sid", [""])[0]) + with s.lock: + return self._send(200, s.summary()) + if url.path == "/api/replay": + s = _session(q.get("sid", [""])[0]) + with s.lock: + return self._send(200, s.replay()) + return self._static(url.path) + except KeyError as ex: + return self._send(404, {"error": str(ex).strip("'")}) + except Exception as ex: + traceback.print_exc() + return self._send(500, {"error": repr(ex)}) + + def _static(self, path): + rel = path.lstrip("/") or "index.html" + if rel.endswith("/"): + rel += "index.html" + target = (PAGE / rel).resolve() + if not str(target).startswith(str(PAGE.resolve())) or not target.is_file(): + return self._send(404, {"error": "not found: " + path}) + return self._send(200, target.read_bytes(), TYPES.get(target.suffix.lower(), "application/octet-stream")) + + def _post(self): + url = urlparse(self.path) + try: + body = self._json() + if url.path == "/api/new": + sid, s = _new_session(body) + with s.lock: + return self._send(200, {"sid": sid, "state": s.summary()}) + if url.path == "/api/step": + s = _session(body.get("sid", "")) + packets = body.get("packets") or [] + if len(packets) > 5: + raise ValueError("at most 5 packets per request (1 s of play)") + with s.lock: + shots = [] if body.get("frames") else None + for p in packets: + s.step(p, shots) + return self._send(200, {"state": s.summary(), "frames": shots or []}) + if url.path == "/api/scripted": + s = _session(body.get("sid", "")) + n = max(1, min(int(body.get("n", 1)), 5)) + with s.lock: + shots = [] if body.get("frames") else None + for _ in range(n): + if s.outcome is not None: + break + s.step(mc_scripted.scripted(s.case), shots) + s.scripted_packets += 1 + return self._send(200, {"state": s.summary(), "frames": shots or []}) + if url.path == "/api/import": + data = body.get("replay") or {} + problems = [] + if data.get("format") != REPLAY_FORMAT: + problems.append("not a bossbench/policy-replay@1 file") + if data.get("rules") != mc4d.RULES: + problems.append(f"rules mismatch: recording {data.get('rules')!r}, engine {mc4d.RULES!r}") + if data.get("case_id") not in CASES: + problems.append(f"unknown case {data.get('case_id')!r}") + if problems: + return self._send(400, {"error": "; ".join(problems)}) + opts = dict(data.get("options") or {}) + sid, s = _new_session({"case": data["case_id"], "seed": opts.get("engine_seed", data.get("engine_seed", 1)), + "difficulty": opts.get("difficulty", 0.5), + **{k: opts[k] for k in ("weapon", "camera", "resolved_from_tier") if k in opts}}) + return self._send(200, {"sid": sid, "packets": len(data.get("packets") or []), + "expect": {"outcome": data.get("outcome"), "final_hash": data.get("final_hash"), + "ticks": data.get("ticks")}, "state": s.summary()}) + if url.path == "/api/still": + s = _session(body.get("sid", "")) + with s.lock: + return self._send(200, {"state": s.summary(), "frame": s.jpeg(s.env.unwrapped.inner.render())}) + if url.path == "/api/verify": + s = _session(body.get("sid", "")) + with s.lock: + raw = s.env.unwrapped + return self._send(200, {"final_hash": raw.state_hash(), "ticks": int(s.case.t), + "outcome": raw.verifier()["outcome"]}) + if url.path == "/api/close": + with SLOCK: + s = SESSIONS.pop(body.get("sid", ""), None) + if s is not None: + with s.lock: + s.close() + return self._send(200, {"closed": s is not None}) + return self._send(404, {"error": "unknown endpoint"}) + except KeyError as ex: + return self._send(404, {"error": str(ex).strip("'")}) + except ValueError as ex: + return self._send(400, {"error": str(ex)}) + except Exception as ex: + traceback.print_exc() + return self._send(500, {"error": repr(ex)}) + + +def main(argv=None): + parser = argparse.ArgumentParser(description="BossBench Minecraft human play server (127.0.0.1 only)") + parser.add_argument("--port", type=int, default=int(os.environ.get("BOSSBENCH_MC_PORT", 8765))) + parser.add_argument("--open", action="store_true", help="open the page in the default browser") + args = parser.parse_args(argv) + server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler) + server.daemon_threads = True + url = f"http://127.0.0.1:{args.port}/" + print(f"Minecraft remake ({mc4d.RULES}) play server: {url}", flush=True) + if args.open: + import webbrowser + webbrowser.open(url) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + def shutdown(): + with SLOCK: + for s in SESSIONS.values(): + s.close() + SESSIONS.clear() + GL.submit(shutdown).result() + GL.shutdown() + + +if __name__ == "__main__": + main() diff --git a/environments/games/prototype/bossbench/policy_env.py b/environments/games/prototype/bossbench/policy_env.py new file mode 100644 index 0000000000000000000000000000000000000000..54a9fc199905f6f7ea477071623a821ce44096bd --- /dev/null +++ b/environments/games/prototype/bossbench/policy_env.py @@ -0,0 +1,151 @@ +"""Public Gymnasium contract shared by visual models and RL, for 2D and 3D. + +The underlying simulations and privileged diagnostics remain accessible through +``unwrapped`` for trusted collectors. This wrapper is an input boundary, not a +security sandbox; policies receive ``rl.rollout.Context``, never the env object. +""" +from __future__ import annotations + +import copy + +import gymnasium as gym +import numpy as np + +from . import keymouse as km +from .core import RES +from .scope import POLICY_CASES + +CONTRACT_VERSION = "bossbench/policy-gym@2" +PUBLIC_INFO_KEYS = frozenset({ + "case_id", "contract", "t", "steps", "frames", "lag_packets", "format_ok", + "format_errors", "difficulty", "engine_seed", "outcome", "terminated", + "truncated", "timing", "renderer", + # 2026-11-03: the game's own name for the segment `difficulty` falls in, when it declares one. + # Present only for such games, and safe to expose because it is a pure function of `difficulty`, + # which this info already carries — a label on a number the policy can already see, not live state. + # It exists so a d* sweep can explain the steps it measures at mode boundaries instead of + # re-deriving them from each game's source. + "difficulty_band", +}) +_RAW_PUBLIC_KEYS = ("t", "steps", "frames", "lag_packets", "format_ok", "format_errors", + "difficulty", "engine_seed", "outcome") +_RAW_OPTIONAL_KEYS = ("difficulty_band",) + + +class PolicyEnv(gym.Wrapper): + """RGB + legal key/mouse packets + sparse reward + public-only info. + + One step holds six key sets over 200 ms, using the declared native engine clock. + Text and structured actions share the same parser and rejection semantics. + Actual perspective 3D is mandatory: a fallback image raises an error. + """ + + def __init__(self, env): + raw = env.unwrapped + if raw.case_id not in POLICY_CASES: + raise ValueError(f"case is not registered for the public policy interface: {raw.case_id!r}") + if (raw.obs_mode, raw.action_mode, raw.reward_mode) != ("rgb", "keymouse", "sparse"): + raise ValueError("public policy env requires rgb/keymouse/sparse") + spec = raw.engine_spec + if raw.fps != spec.native_hz: + raise ValueError(f"engine clock must match declared {spec.native_hz} Hz; remove runtime FPS overrides") + if spec.dimension != POLICY_CASES[raw.case_id]['dimension']: + raise ValueError('engine dimension differs from the registered case') + if tuple(spec.resolution) != RES: + raise ValueError("public policy contract requires a renderer size of 854 x 480") + if spec.dimension == '3d' and spec.render_kind != 'perspective': + raise ValueError('3D policy observations require perspective rendering') + super().__init__(env) + self.metadata = {**env.metadata, "contract": CONTRACT_VERSION, "simulation_fps": raw.fps} + self._closed = False + self._elapsed_frames = 0 + + def _open(self): + if self._closed: + raise RuntimeError("environment is closed; create a new environment") + + def _frame(self, image): + if not isinstance(image, np.ndarray) or image.shape != (RES[1], RES[0], 3) or image.dtype != np.uint8: + raise RuntimeError("policy observation must be RGB uint8 (480, 854, 3)") + if POLICY_CASES[self.unwrapped.case_id]["dimension"] == "3d": + status = self.unwrapped.render_status() + if (not status.ready or status.kind != 'perspective' or status.error is not None + or status.renderer != self.unwrapped.engine_spec.renderer): + raise RuntimeError(f"{self.unwrapped.case_id}: real 3D renderer unavailable: {status.error or 'no perspective renderer'}") + # Neither reused engine buffers nor policy mutation may change history. + return image.copy() + + def _info(self, info, terminated=False, truncated=False): + raw = self.unwrapped + frames, lag = int(info["frames"]), int(info["lag_packets"]) + lag_frames = int(raw.snap.get('lag_frames', min(frames, lag * round(raw.fps * km.PACKET_SECONDS)))) + out = {k: copy.deepcopy(info[k]) for k in _RAW_PUBLIC_KEYS} + out.update({k: copy.deepcopy(info[k]) for k in _RAW_OPTIONAL_KEYS if k in info}) + out.update(case_id=raw.case_id, contract=CONTRACT_VERSION, + terminated=bool(terminated), truncated=bool(truncated), + renderer=raw.engine_spec.renderer, + timing={"fps": raw.fps, "tick_seconds": 1 / raw.fps, + "packet_seconds": km.PACKET_SECONDS, "substeps": km.SUBSTEPS, + "ticks_per_substep": raw.fps * km.PACKET_SECONDS / km.SUBSTEPS, + "simulation_seconds": frames / raw.fps, + "elapsed_seconds": self._elapsed_frames / raw.fps, + "lag_frames": lag_frames, "action_frames": frames - lag_frames}) + if "manual" in info: + out["manual"] = self.manual() + return out + + def manual(self): + self._open() + manual = self.unwrapped.manual() + return {"protocol": str(manual["protocol"]), "controls": copy.deepcopy(manual["controls"])} + + def reset(self, *, seed=None, options=None): + self._open() + obs, info = self.env.reset(seed=seed, options=options) + self._elapsed_frames = 0 + return self._frame(obs), self._info(info) + + def step(self, action, latency=None): + self._open() + obs, reward, terminated, truncated, info = self.env.step(action, latency=latency) + self._elapsed_frames += int(info["frames"]) + return self._frame(obs), reward, terminated, truncated, self._info(info, terminated, truncated) + + def render(self): + self._open() + return self._frame(self.env.render()) + + def close(self): + if not self._closed: + try: + self.env.close() + finally: + self._closed = True + + +def make_policy_env(case_id, **kwargs): + """Create the same public Gym env for model evaluation and RL collection. + + Pass engine-specific experiment conditions in reset(options=...), e.g. + Minecraft weapon/camera or Terraria dawn_in_seconds; engine_seed imports a + recording seed exactly. Raw symbolic/native/dense ablations use make(). + """ + if case_id not in POLICY_CASES: + raise ValueError(f"case is not registered for the public policy interface: {case_id!r}; known: {sorted(POLICY_CASES)}") + for key, value in (("obs_mode", "rgb"), ("action_mode", "keymouse"), ("reward_mode", "sparse")): + if key in kwargs and kwargs[key] != value: + raise ValueError(f"public policy contract requires {key}={value!r}") + kwargs[key] = value + kwargs.setdefault("time_mode", "paused") + kwargs.setdefault("render_mode", "rgb_array") + from . import make + env = make(case_id, **kwargs) + try: + return PolicyEnv(env) + except Exception: + env.close() + raise + + +def policy_gym_id(case_id): + return "BossBenchPolicy/" + case_id.replace("/", "-") + "-v0" diff --git a/environments/games/prototype/bossbench/progress_reward.py b/environments/games/prototype/bossbench/progress_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..b881d594b55d6823226b3ad97e2e81e5834950a8 --- /dev/null +++ b/environments/games/prototype/bossbench/progress_reward.py @@ -0,0 +1,102 @@ +"""Versioned high-water progress reward; trusted scoring only, never policy input.""" +from __future__ import annotations + +import math +import gymnasium as gym + +REWARD_CONTRACT = 'bossbench/step-progress-highwater@1' + + +def unit(value): + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise RuntimeError('progress must be numeric') + value = float(value) + if not math.isfinite(value) or not 0 <= value <= 1: + raise RuntimeError('progress must be finite and in [0,1]') + return value + + +class HighWaterProgress: + def __init__(self, initial): + self.initial = self.peak = self.final = unit(initial) + self.steps = 0 + + def step(self, current): + current = unit(current) + peak = max(self.peak, current) + reward = peak - self.peak + self.peak, self.final = peak, current + self.steps += 1 + return reward + + def diagnostics(self): + return dict(contract=REWARD_CONTRACT, initial_progress=self.initial, + peak_progress=self.peak, final_progress=self.final, + episode_return=self.peak - self.initial, steps=self.steps) + + +def objective_progress(snapshot, case_id): + """Read scoring fields while preserving the original game's HP and outcome.""" + from .step_reward import objective_progress as hp_progress + if case_id == 'cuphead/root_pack': + boss = snapshot['state']['boss'] + score = boss['reward_objective'] + if score['version'] != 'root-pack-fixed-phase@1': + raise RuntimeError('Root Pack fixed phase scoring unavailable') + return unit(score['progress']) + if case_id == 'nfsmw/speedtrap': + game = snapshot['state']['game'] + score, target = game['you'], game['reward_target_score'] + if game['reward_target_version'] != 'speedtrap-reachable-profile@1': + raise RuntimeError('Speedtrap calibration unavailable') + if not math.isfinite(score) or score < 0 or not math.isfinite(target) or target <= 0: + raise RuntimeError('Invalid speedtrap score/target') + return unit(min(1.0, score / target)) + return unit(hp_progress(snapshot)) + + +class StepProgressReward(gym.Wrapper): + """Reward new peaks at env.step boundaries, including each step's lag window. + + No reward rescaling by batch, terminal bonus, time/death/format penalty, or + repeated credit after healing. Imported initial progress is not rewarded. + """ + def __init__(self, env, case_id): + super().__init__(env) + self.case_id = case_id + self.metadata = dict(env.metadata, reward_contract=REWARD_CONTRACT) + self.scorer = None + self._closed, self._done = False, True + + def reset(self, *, seed=None, options=None): + if self._closed: + raise RuntimeError('environment is closed') + obs, info = self.env.reset(seed=seed, options=options) + self._done = True + self.scorer = HighWaterProgress(objective_progress(self.unwrapped.snap, self.case_id)) + self._done = False + return obs, dict(info, reward_contract=REWARD_CONTRACT) + + def step(self, action, latency=None): + if self._closed or self._done or self.scorer is None: + raise RuntimeError('reset required before step') + try: + obs, _, terminated, truncated, info = self.env.step(action, latency=latency) + reward = self.scorer.step(objective_progress(self.unwrapped.snap, self.case_id)) + except BaseException: + self._done = True + raise + self._done = bool(terminated or truncated) + return obs, reward, terminated, truncated, dict(info, reward_contract=REWARD_CONTRACT) + + def reward_diagnostics(self): + if self.scorer is None: + raise RuntimeError('reset required') + return dict(self.scorer.diagnostics(), done=self._done) + + def close(self): + if not self._closed: + try: + self.env.close() + finally: + self._closed = self._done = True diff --git a/environments/games/prototype/bossbench/rig.py b/environments/games/prototype/bossbench/rig.py new file mode 100644 index 0000000000000000000000000000000000000000..5e4978d77433052621e7b942bc5bf77268fa9b86 --- /dev/null +++ b/environments/games/prototype/bossbench/rig.py @@ -0,0 +1,235 @@ +"""Rig: the single animation channel that every renderer reads. + +A rig is a set of named boxes ("parts") attached to an entity's report frame. Once per tick the +simulation poses it: each part gets a world origin and a rotation, built from a local offset in +the entity's own frame (x = forward, y = up, z = right) plus three angles in degrees +(yaw about up, pitch about right = limb raise, roll about forward = wing flap). + + rig.pose(case.t, {"arm_l": (0, 2.05, -0.95, 0, 166), ...}, e.pos, e.yaw) + +Renderers interpolate between ticks instead of animating on their own clock:: + + origin(t) = origin[k] + (origin[k+1] - origin[k]) * u u = (t - tick_k) / (tick_k1 - tick_k) + +so a pose is an exact function of the simulation tick, not of the renderer's frame timer, and +drawing two ticks or twenty between two keyframes gives the same picture at the same fractional +time. Rotations travel as quaternions, which removes every Euler-order ambiguity between three.js, +Godot and the numpy box renderer. + +Nothing here feeds back into the rules: a rig only ever describes what the simulation already did +(architecture rule 1). +""" +from __future__ import annotations + +import math + +import numpy as np + +_PI = np.pi + + +def q_y(deg: float) -> np.ndarray: + a = np.radians(deg) * 0.5 + return np.array([0.0, np.sin(a), 0.0, np.cos(a)]) + + +def q_z(deg: float) -> np.ndarray: + a = np.radians(deg) * 0.5 + return np.array([0.0, 0.0, np.sin(a), np.cos(a)]) + + +def q_x(deg: float) -> np.ndarray: + a = np.radians(deg) * 0.5 + return np.array([np.sin(a), 0.0, 0.0, np.cos(a)]) + + +def q_mul(a: np.ndarray, b: np.ndarray) -> np.ndarray: + x1, y1, z1, w1 = a + x2, y2, z2, w2 = b + return np.array([w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, + w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, + w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2]) + + +def q_norm(q: np.ndarray) -> np.ndarray: + n = np.linalg.norm(q) + return q / n if n > 1e-12 else np.array([0.0, 0.0, 0.0, 1.0]) + + +def q_slerp(a: np.ndarray, b: np.ndarray, u: float) -> np.ndarray: + """Shortest-arc slerp; u is clamped by the caller.""" + d = float(np.dot(a, b)) + if d < 0.0: + b, d = -b, -d + if d > 0.9995: + return q_norm(a + (b - a) * u) + th = np.arccos(np.clip(d, -1.0, 1.0)) + s = np.sin(th) + return q_norm(np.sin((1 - u) * th) / s * a + np.sin(u * th) / s * b) + + +def q_to_mat(q: np.ndarray) -> np.ndarray: + x, y, z, w = q + return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + + +# -- tuple quaternions: Bones runs every tick inside the simulation step, so it stays off numpy -- +def _qm(a, b): + x1, y1, z1, w1 = a + x2, y2, z2, w2 = b + return (w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, + w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2) + + +def _qe(yaw, pitch, roll): + """q_y(-yaw) * q_z(pitch) * q_x(roll): yaw turns +x toward +z (right), pitch raises +x, roll + lowers +z. Same order the entity frame uses, so a chain of these composes like a skeleton.""" + a, b, c = math.radians(-yaw) * 0.5, math.radians(pitch) * 0.5, math.radians(roll) * 0.5 + q = (0.0, math.sin(a), 0.0, math.cos(a)) + if b: + q = _qm(q, (0.0, 0.0, math.sin(b), math.cos(b))) + if c: + q = _qm(q, (math.sin(c), 0.0, 0.0, math.cos(c))) + return q + + +def _qv(q, v): + x, y, z, w = q + tx, ty, tz = 2 * (y * v[2] - z * v[1]), 2 * (z * v[0] - x * v[2]), 2 * (x * v[1] - y * v[0]) + return (v[0] + w * tx + y * tz - z * ty, v[1] + w * ty + z * tx - x * tz, v[2] + w * tz + x * ty - y * tx) + + +class Bones: + """Forward kinematics in the entity frame, feeding Rig.pose. + + b = Bones() + b.bone("body", None, (0, 1.0, 0), pitch=lean) + b.bone("arm_r", "body", (0, 0.62, 0.69), pitch=raise_, boxes=("arm_r", "vine_r")) + rig.pose(t, b.spans, e.pos, e.yaw) + + A bone's offset and angles are relative to its parent; every box listed in `boxes` takes the + bone's frame (the box's own "pivot" then places it inside that frame). + """ + + def __init__(self): + self.f, self.spans = {}, {} + + def bone(self, name, parent=None, at=(0.0, 0.0, 0.0), yaw=0.0, pitch=0.0, roll=0.0, boxes=None): + p, q = self.f[parent] if parent else ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0)) + o = _qv(q, at) + pos = (p[0] + o[0], p[1] + o[1], p[2] + o[2]) + ql = _qm(q, _qe(yaw, pitch, roll)) + self.f[name] = (pos, ql) + for b in (boxes if boxes is not None else (name,)): + self.spans[b] = (pos[0], pos[1], pos[2], ql) + return pos + + def point(self, name, v): + """A point given in bone `name`'s frame, in the entity frame.""" + p, q = self.f[name] + o = _qv(q, v) + return (p[0] + o[0], p[1] + o[1], p[2] + o[2]) + + +class Rig: + """Boxes for one entity. Parts are declared once; only their pose changes per tick. + + parts: name -> {"size": (sx, sy, sz), "color": (r, g, b), "pivot": (px, py, pz) or None, + "fwd": bool} pivot is the box centre inside the part frame (default the + origin); fwd=False means the box keeps world-aligned axes and only follows the + entity's position (legs of a diagonally-standing golem, for instance). + """ + + def __init__(self, parts: dict, tint=(1.0, 1.0, 1.0)): + self.parts = parts + self.tint = tuple(float(c) for c in tint) + self.kf: dict[str, list] = {} + self.hide: set = set() # parts not drawn this tick (e.g. wither armour above half hp) + self.variant = "" # texture variant suffix (golem cracks, wither eye glow) + self.overlay = (0.0, 0.0, 0.0, 0.0) # rgb + amount mixed over the lit colour (hurt red) + self.glow = 0.0 # boost for emissive texels (eyes flaring on a telegraph) + self.shell = 0.0 # alpha of a translucent shell around every part (wither guard) + self.shell_color = (0.55, 0.7, 1.0) + self.mem: dict = {} # pose-only memory (smoothed angles, state entry ticks) + + # -- posing ---------------------------------------------------------- + def reset(self) -> None: + self.kf = {n: [] for n in self.parts} + + def pose(self, tick: int, spans: dict, root, yaw: float, base=(0.0, 0.0), h_floor: float = 0.0, + trim: int = 64) -> None: + """spans: name -> (lx, ly, lz[, yaw_deg, pitch_deg, roll_deg]) in the entity frame, or + (lx, ly, lz, q) with q a local quaternion (what Bones produces). + + base = (pitch_deg, roll_deg) tilts the whole rig about the entity's right/forward axes, + which is how the dragon banks into a turn or the wither leans into a strafe. + """ + Ry = q_y(-np.degrees(yaw)) + QB = q_mul(Ry, q_mul(q_z(base[0]), q_x(base[1]))) + M = q_to_mat(QB) + qb = tuple(QB) + root = np.asarray(root, float) + np.array([0.0, h_floor, 0.0]) + for name, span in spans.items(): + p = self.parts[name] + if len(span) == 4 and isinstance(span[3], tuple): # (lx, ly, lz, local quaternion) + lx, ly, lz, ql = span + origin = root + M @ np.array([lx, ly, lz]) + q = np.array(_qm(qb, ql)) + else: + lx, ly, lz, lyaw, pitch, roll = (tuple(span) + (0.0, 0.0, 0.0))[:6] + origin = root + M @ np.array([lx, ly, lz]) + if p.get("fwd", True): # part frame follows the entity's facing + q = np.array(_qm(qb, _qe(lyaw, pitch, roll))) + else: # box keeps world axes, only its origin moves + q = np.array(_qe(lyaw, pitch, roll)) + kf = self.kf.setdefault(name, []) + kf.append((int(tick), origin, q)) + if len(kf) > trim: + del kf[:len(kf) - trim] + + # -- reading --------------------------------------------------------- + def sample(self, t: float) -> dict: + """Pose at fractional tick t, interpolated between the two surrounding keyframes.""" + out = {} + for name, kfs in self.kf.items(): + if not kfs: + continue + if t <= kfs[0][0]: + _, o, q = kfs[0] + out[name] = (o, q) + continue + if t >= kfs[-1][0]: + _, o, q = kfs[-1] + out[name] = (o, q) + continue + i = 1 + while i < len(kfs) and kfs[i][0] <= t: + i += 1 + t0, o0, q0 = kfs[i - 1] + t1, o1, q1 = kfs[i] + u = 0.0 if t1 == t0 else (t - t0) / (t1 - t0) + out[name] = (o0 + (o1 - o0) * u, q_slerp(q0, q1, u)) + return out + + +class Rigged: + """Mixin: an entity that owns one or more rigs and reports their current state.""" + + def rigs(self) -> list: + return [] + + def rig_state(self, t) -> list: + out = [] + for r in self.rigs(): + out.append({"parts": r.parts, "pose": {n: [list(o), list(q)] for n, (o, q) in r.sample(t).items()}, + "tint": list(getattr(r, "tint", (1.0, 1.0, 1.0)))}) + return out + + +def walk_cycle(phase: float, amp: float = 26.0, roll: float = 0.0) -> tuple: + """Two-leg walk: returns (left_pitch, right_pitch) in degrees for a phase in [0, 1).""" + a = 2 * _PI * phase + return (float(np.sin(a) * amp), float(np.sin(a + _PI) * amp)) diff --git a/environments/games/prototype/bossbench/scope.py b/environments/games/prototype/bossbench/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..505b223ecfe0cc7749b708dd3a224ba21dd20ac0 --- /dev/null +++ b/environments/games/prototype/bossbench/scope.py @@ -0,0 +1,81 @@ +"""Formal BossBench scope, separate from the backwards-compatible registry. + +Never discover training/evaluation scope by blindly iterating bossbench.ENVS. This manifest is +explicit so a newly added game cannot silently enter an existing experiment. +""" +from __future__ import annotations + +from types import MappingProxyType + + +FORMAL_GAMES = MappingProxyType({ + "hollowknight_remake": "2d", + "kirby_remake": "2d", + "terraria_remake": "2d", + "minecraft": "3d", +}) + +FORMAL_CASES = MappingProxyType({ + **{f"2d/{boss}": {"game": "hollowknight_remake", "dimension": "2d", "engine": "web"} for boss in ( + "needle_warden", "iron_bulwark", "hollow_vessel", "sickle_sisters", "pale_vessel")}, + **{f"kirby/{boss}": {"game": "kirby_remake", "dimension": "2d", "engine": "web"} for boss in ( + "whispy_woods", "kracko", "king_dedede")}, + **{f"terraria/{boss}": {"game": "terraria_remake", "dimension": "2d", "engine": "web"} for boss in ( + "king_slime", "eye_of_cthulhu", "skeletron", "eater_of_worlds")}, + **{f"3d/minecraft_{boss}": {"game": "minecraft", "dimension": "3d", "engine": "py"} for boss in ( + "iron_golem", "zombie", "ender_dragon", "wither")}, +}) + +RETIRED_CASES = ("2d/tank_battle", "tank_battle_1v1") +# Public cases are discovered from registrations. Frozen evaluation cases are listed above. +from . import WEB_GAME +PUBLIC_WEB_CASES = MappingProxyType({ + case_id: {"game": game, "dimension": "2d", "engine": "web"} + for case_id, game in WEB_GAME.items() if case_id not in FORMAL_CASES +}) +# Python-route scenes (mc4d.MOBS) are discovered the same way, so Minecraft can add bosses without editing +# this file. Their ids are "3d/_"; the game name is read from the id rather than assumed, so a +# second Python game would be routed correctly instead of silently labelled Minecraft. +from . import PY_CASES +PUBLIC_PY_CASES = MappingProxyType({ + case_id: {"game": case_id.split("/", 1)[1].split("_", 1)[0], "dimension": "3d", "engine": "py"} + for case_id in PY_CASES if case_id not in FORMAL_CASES +}) +from .native_games import NATIVE_CASES +POLICY_CASES = MappingProxyType({**FORMAL_CASES, **PUBLIC_WEB_CASES, **PUBLIC_PY_CASES, **{ + key: {'game': value['game'], 'dimension': value['dimension'], 'engine': 'native'} + for key, value in NATIVE_CASES.items() +}}) +# Retired cases retain their IDs for replay compatibility and are omitted from the benchmark registry. +BENCH_RETIRED = frozenset({ + "3d/minecraft_zombie", # Minecraft had 7; its tier calibration is the separate 3d/minecraft_zombie_leader +}) +BENCH_SCENES_PER_GAME = 6 +BENCH_CASES = MappingProxyType({k: v for k, v in POLICY_CASES.items() if k not in BENCH_RETIRED}) +# Every game, including Minecraft (Python), with its dimension; used by the media/scripted harness. +GAMES = MappingProxyType({spec["game"]: spec["dimension"] for spec in POLICY_CASES.values()}) +FIRST_CASE = "kirby/whispy_woods" +COLD_START_CASE = "2d/needle_warden" +SCOPE_VERSION = "bossbench/formal-scope@1" + + +def case_ids(*, dimension: str | None = None, game: str | None = None) -> tuple[str, ...]: + """Return stable, sorted formal IDs, optionally restricted by game or dimension.""" + if dimension is not None and dimension not in ("2d", "3d"): + raise ValueError("dimension must be '2d' or '3d'") + if game is not None and game not in FORMAL_GAMES: + raise ValueError(f"unknown formal game: {game!r}") + return tuple(sorted(i for i, spec in FORMAL_CASES.items() + if (dimension is None or spec["dimension"] == dimension) + and (game is None or spec["game"] == game))) + + +def validate_registry() -> None: + """Reject missing/misrouted formal cases without changing the legacy registry.""" + from . import ENVS, WEB_GAME + + for case_id, spec in {**FORMAL_CASES, **PUBLIC_WEB_CASES, **PUBLIC_PY_CASES}.items(): + if ENVS.get(case_id) != spec["engine"]: + raise RuntimeError(f"formal case {case_id!r} has missing or incorrect engine registration") + if spec["engine"] == "web" and WEB_GAME.get(case_id) != spec["game"]: + raise RuntimeError(f"formal case {case_id!r} has incorrect game registration") diff --git a/environments/games/prototype/bossbench/scripted.py b/environments/games/prototype/bossbench/scripted.py new file mode 100644 index 0000000000000000000000000000000000000000..d60d408e399e92c2025f48b0a02896cd6bd49e31 --- /dev/null +++ b/environments/games/prototype/bossbench/scripted.py @@ -0,0 +1,355 @@ +"""Standard trusted scripted controller + frame capture for every BossBench case (all 12 games). + +One API over the three engine routes, used by web/tools/bench_media.py and any trusted collector: + + env = bossbench.make_policy_env(case_id) # public RGB interface (or bossbench.make(...) symbolic) + ctrl = scripted.controller(env) # reads env.unwrapped; never handed to a policy + obs, info = env.reset(seed=1, options={"difficulty": 0.5, "engine_seed": 1}) + cap = scripted.FrameCapture(env) # optional: frames of this same run at native-tick cadence + while True: + obs, reward, terminated, truncated, info = env.step(ctrl()) + frames = cap.drain() # [(tick, jpeg bytes), ...] produced during that step + if terminated or truncated: break + +Game hooks (one per engine route): + * BB.Case web games BB.GAME.scripted(case) -> packet (bridge cmd "scripted", web/engine/case.js scriptedPacket) + * independent JS Module.scripted(game) -> {holds, mouse} (fallback Module.oracle) + * Minecraft (Python) bossbench.mc_scripted.scripted(case) -> packet text +Every controller must be deterministic and must not change the simulation; both are checked here or in JS. + +HAZARD for any Python-route controller that plans on a deep copy of the live case (found 2026-11-01 in +mc_scripted): FrameCapture below installs an *instance-level* `case.tick` wrapper, and `copy.deepcopy` copies +instance attributes — so a naive clone carries that wrapper with it and the controller's lookahead then drives +the real episode while still reporting a legal packet. Strip bound functions from the clone's own __dict__ +before simulating it, e.g. + + clone = copy.deepcopy(case) + for name, value in list(vars(clone).items()): + if callable(value) and not isinstance(value, type): + del vars(clone)[name] # drop instance-level patches; class methods are unaffected + +The state-hash check around each controller call catches this only if the lookahead happens to change the +hash before the call returns, so do not rely on it as the guard. +""" +from __future__ import annotations + +import base64 +import hashlib +import io +import json +from pathlib import Path + +import numpy as np + +from . import keymouse as km + +ROOT = Path(__file__).resolve().parents[2] +WEB = ROOT / 'web' +REPLAY_FORMAT = 'bossbench/policy-replay@1' + + +def route(env): + """'web' (BB.Case), 'native' (independent JS backend) or 'py' (Minecraft) for a make()/make_policy_env() env.""" + raw = env.unwrapped + from .webenv import WebCaseEnv + from .engine_env import EngineEnv + from .unified import PyCaseEnv + if isinstance(raw, WebCaseEnv): + return 'web' + if isinstance(raw, EngineEnv): + if not hasattr(raw.backend, 'page'): + raise TypeError(f'{raw.case_id}: backend has no scripted controller hook') + return 'native' + if isinstance(raw, PyCaseEnv): + return 'py' + raise TypeError(f'unsupported env type {type(raw).__name__}') + + +def _page(env): + raw = env.unwrapped + kind = route(env) + if kind == 'web': + if raw.transport != 'browser': + return None + return raw.t.page + if kind == 'native': + return raw.backend.page + return None + + +def controller(env): + """Callable returning the next legal packet text for the env's current (live) state.""" + raw = env.unwrapped + kind = route(env) + if kind == 'web': + def ask(): + return raw._call({'cmd': 'scripted'})['packet'] + elif kind == 'native': + def ask(): + out = raw.backend.scripted() + return km.format_packet([tuple(h) for h in out['holds']], tuple(int(round(v)) for v in out['mouse'])) + else: + from . import mc_scripted + + def ask(): + before = raw.state_hash() if raw.snap is not None else None + packet = mc_scripted.scripted(raw.case) + if before is not None and raw.state_hash() != before: + raise RuntimeError('scripted controller changed the simulation') + return packet if isinstance(packet, str) else km.to_packet(packet) + + def next_packet(): + packet = ask() + if km.parse_packet(packet) is None: + raise RuntimeError(f'{raw.case_id}: scripted controller returned an illegal packet: {packet!r}') + return packet + return next_packet + + +def rules(env): + """Rule/version string the engine declares for this case (None if the game has none).""" + raw = env.unwrapped + kind = route(env) + if kind == 'web': + return raw._call({'cmd': 'meta'}).get('rules') + if kind == 'native': + return raw.engine_spec.rule_version + from . import mc4d + return getattr(mc4d, 'RULES', None) + + +def state_hash(env): + """Engine-native final-state hash (BB.hashState / NativeBench.hash / sha1 of the Python state).""" + raw = env.unwrapped + kind = route(env) + if kind == 'web': + return raw._call({'cmd': 'hash'})['hash'] + if kind == 'native': + return raw.backend.page.evaluate('() => NativeBench.hash(backendSession.state())') + return raw.state_hash() + + +def game_of(env): + raw = env.unwrapped + from .scope import POLICY_CASES + return POLICY_CASES[raw.case_id]['game'] + + +def source_files(env): + """Files that define this case's rules and pictures (fingerprinted in media provenance).""" + raw = env.unwrapped + kind = route(env) + if kind == 'web': + from .webenv import game_scripts + files = [Path(p) for p in game_scripts(raw.game)] + files += [WEB / 'games' / raw.game / 'index.html', WEB / 'engine' / 'bridge.js'] + elif kind == 'native': + from .native_games import source_paths + files = source_paths(raw.case_id) + else: + pkg = Path(__file__).resolve().parent + files = [pkg / name for name in ('mc4d.py', 'mcskin.py', 'rig.py', 'core.py', 'unified.py', 'mc_scripted.py')] + out = {} + for path in files: + if path.is_file(): + out[path.resolve().relative_to(ROOT).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() + return out + + +_WEB_CAPTURE = r'''a => { + const env = BB.bridgeEnv(), c = env.case; + if (!BB.Renderer) throw Error('capture needs the browser renderer'); + const canvas = document.createElement('canvas'); + const cap = window.__bbCapture = {R: new BB.Renderer(canvas), every: a.every, quality: a.quality, frames: [], ticks: [], case: c}; + cap.grab = () => { + const before = BB.hashState(c); + cap.R.draw(c, c.t / BB.FPS, ''); + if (BB.hashState(c) !== before) throw Error('renderer changed the simulation'); + cap.frames.push(cap.R.canvas.toDataURL('image/jpeg', cap.quality).split(',')[1]); cap.ticks.push(c.t); + }; + if (!c.__bbCaptureWrapped) { + const tick = c.tick; + c.tick = function (keys, mouse) { + const t0 = this.t; tick.call(this, keys, mouse); + const k = window.__bbCapture; + if (k && k.case === this && this.t !== t0 && (this.t % k.every === 0 || this.result)) k.grab(); + }; + c.__bbCaptureWrapped = true; + } + cap.grab(); + return {w: cap.R.canvas.width, h: cap.R.canvas.height, hz: BB.FPS}; +}''' + +_NATIVE_CAPTURE = r'''a => { + const s = backendSession, M = backendModule; + const canvas = document.createElement('canvas'); canvas.width = 854; canvas.height = 480; + const ctx = canvas.getContext('2d'); + const cap = window.__bbCapture = {every: a.every, quality: a.quality, frames: [], ticks: [], session: s, ctx, canvas}; + cap.grab = () => { + const before = NativeBench.hash(s.state()); + M.draw(s.game, ctx); + if (NativeBench.hash(s.state()) !== before) throw Error('renderer changed the simulation'); + cap.frames.push(canvas.toDataURL('image/jpeg', cap.quality).split(',')[1]); cap.ticks.push(s.game.t); + }; + const tick = s.tick.bind(s); + s.tick = function (keys, mouse) { + const ok = tick(keys, mouse), k = window.__bbCapture; + if (ok && k && k.session === s && (s.game.t % k.every === 0 || s.game.outcome)) k.grab(); + return ok; + }; + cap.grab(); + return {w: 854, h: 480, hz: M.hz}; +}''' + +_DRAIN = '''() => { const k = window.__bbCapture; if (!k) return {frames: [], ticks: []}; + const out = {frames: k.frames, ticks: k.ticks}; k.frames = []; k.ticks = []; return out; }''' + +_CLOSE_NATIVE = '''() => { const k = window.__bbCapture; if (k && k.ctx && backendModule.closeRenderer) backendModule.closeRenderer(k.ctx); + window.__bbCapture = null; }''' + + +class FrameCapture: + """Frames of the live episode every `every` native ticks (default: 30 fps at 60 Hz, every tick below 40 Hz). + + Install right after reset; frames come from a private renderer/canvas reading the same simulation, so the + policy observation, gameplay RNG and physics are untouched. The terminal tick is always captured. + """ + + def __init__(self, env, every=None, quality=0.92): + self.env, self.kind, self.raw = env, route(env), env.unwrapped + fps = int(self.raw.fps) + self.every = int(every or (2 if fps >= 40 else 1)) + self.fps = fps / self.every + self.quality = float(quality) + self._py_frames = [] + if self.kind in ('web', 'native'): + page = _page(env) + if page is None: + raise RuntimeError('frame capture needs the browser transport (obs_mode="rgb")') + self.page = page + script = _WEB_CAPTURE if self.kind == 'web' else _NATIVE_CAPTURE + self.size = page.evaluate(script, {'every': self.every, 'quality': self.quality}) + else: + case, inner, frames, every = self.raw.case, self.raw.inner, self._py_frames, self.every + tick = type(case).tick + + def wrapped(action, _case=case): + t0 = _case.t + tick(_case, action) + if _case.t != t0 and (_case.t % every == 0 or _case.outcome()): + frames.append((_case.t, inner.render())) + case.tick = wrapped + self._unwrap = lambda: case.__dict__.pop('tick', None) + frames.append((case.t, inner.render())) + self.size = {'w': case.size[0], 'h': case.size[1], 'hz': fps} + + def drain(self): + """-> [(tick, jpeg bytes)] captured since the last drain.""" + if self.kind in ('web', 'native'): + got = self.page.evaluate(_DRAIN) + return [(t, base64.b64decode(f)) for t, f in zip(got['ticks'], got['frames'])] + from PIL import Image + out = [] + for t, rgb in self._py_frames: + buffer = io.BytesIO() + Image.fromarray(np.ascontiguousarray(rgb)).save(buffer, 'JPEG', quality=int(self.quality * 100)) + out.append((t, buffer.getvalue())) + self._py_frames.clear() + return out + + def close(self): + try: + if self.kind == 'native': + self.page.evaluate(_CLOSE_NATIVE) + elif self.kind == 'web': + self.page.evaluate('() => { window.__bbCapture = null; }') + else: + self._unwrap() + except Exception: + pass + + +def play(env, *, seed=1, options=None, max_steps=None, on_step=None, capture=None): + """Run the scripted controller to the terminal outcome on an existing env; returns a policy-replay dict. + + options are forwarded to reset (difficulty, engine-specific keys); engine_seed defaults to seed so the replay + and the human play page share the same world. on_step(index, packet, info, frames) is called after each step. + """ + options = dict(options or {}) + if 'tier' not in options: + options.setdefault('difficulty', 0.5) + options.setdefault('engine_seed', int(seed)) + obs, info = env.reset(seed=int(seed), options=options) + # A replay must pin what was actually played. A `tier` is resolved by the game's declaration at reset + # time; store the concrete difficulty it produced (plus the tier name as provenance), so the recording + # still reproduces exactly if that game later recalibrates its tiers. + if 'tier' in options: + tier = options.pop('tier') + options['difficulty'] = float(info['difficulty']) + options['resolved_from_tier'] = tier + cap = FrameCapture(env, **capture) if capture is not None else None + if cap is not None and on_step is not None: + on_step(-1, None, info, cap.drain()) + ctrl = controller(env) + raw = env.unwrapped + packets, terminated, truncated = [], False, False + limit = max_steps or int(raw.max_seconds / km.PACKET_SECONDS) + 2 + try: + for index in range(limit): + packet = ctrl() + obs, reward, terminated, truncated, info = env.step(packet) + packets.append(packet) + if on_step is not None: + on_step(index, packet, info, cap.drain() if cap is not None else []) + if terminated or truncated: + break + finally: + if cap is not None: + cap.close() + verifier = raw.verifier() + ticks = int(round(raw.snap['t'] * raw.fps)) + return { + 'format': REPLAY_FORMAT, 'case_id': raw.case_id, 'game': game_of(env), 'contract': 'bossbench/policy-gym@2', + 'rules': rules(env), 'native_hz': raw.fps, 'gym_seed': int(seed), 'engine_seed': int(raw.engine_seed), + 'options': options, 'controller': 'scripted (standard trusted reference controller; privileged state; not a model)', + 'packets': packets, 'steps': len(packets), 'ticks': ticks, 'seconds': round(ticks / raw.fps, 4), + 'outcome': verifier['outcome'], 'terminated': bool(terminated), 'truncated': bool(truncated), + 'verifier': verifier, 'final_hash': state_hash(env), 'source_sha256': source_files(env), + } + + +def replay(env, data): + """Re-run a policy-replay through env; returns (outcome, final_hash, ticks, problems).""" + problems = [] + raw = env.unwrapped + if data.get('format') != REPLAY_FORMAT: + problems.append('not a bossbench/policy-replay@1 file') + if data.get('case_id') != raw.case_id: + problems.append(f"case mismatch: {data.get('case_id')} vs {raw.case_id}") + current = rules(env) + if data.get('rules') != current: + problems.append(f"rules mismatch: recording {data.get('rules')!r}, engine {current!r}") + env.reset(seed=int(data['gym_seed']), options=dict(data['options'])) + done = False + for index, packet in enumerate(data['packets']): + if done: + problems.append(f'packet {index} after terminal outcome') + break + _, _, terminated, truncated, _ = env.step(packet) + done = terminated or truncated + if not done: + problems.append('recording ended before a terminal outcome') + outcome = raw.verifier()['outcome'] + final = state_hash(env) + ticks = int(round(raw.snap['t'] * raw.fps)) + if outcome != data.get('outcome'): + problems.append(f"outcome mismatch: {outcome} vs {data.get('outcome')}") + if final != data.get('final_hash'): + problems.append(f"final hash mismatch: {final} vs {data.get('final_hash')}") + if ticks != data.get('ticks'): + problems.append(f"tick mismatch: {ticks} vs {data.get('ticks')}") + return outcome, final, ticks, problems + + +def dumps(data): + return json.dumps(data, ensure_ascii=False, indent=1) + '\n' diff --git a/environments/games/prototype/bossbench/step_reward.py b/environments/games/prototype/bossbench/step_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..24aecbb6ad69aa209e9c706738fc28ff5ce5b1b5 --- /dev/null +++ b/environments/games/prototype/bossbench/step_reward.py @@ -0,0 +1,105 @@ +"""Damage/progress-only rewards per Gym step, shared by every registered game. + +The engine's aggregate objective HP/progress is trusted scoring data. It is never +added to the image observation or the model prompt. +""" +from __future__ import annotations + +import math +import gymnasium as gym + +REWARD_CONTRACT = 'bossbench/step-damage@1' + + +def objective_progress(snapshot): + """Use the existing aggregate objective, including all phases/required parts.""" + if not isinstance(snapshot, dict): + raise RuntimeError('reward requires a valid current engine snapshot') + hp, maximum = float(snapshot['boss_hp']), float(snapshot['boss_max_hp']) + if not math.isfinite(hp) or not math.isfinite(maximum) or maximum <= 0 or not 0 <= hp <= maximum: + raise RuntimeError('invalid aggregate objective HP/progress') + return 1.0 - hp / maximum + + +class StepDamageReward(gym.Wrapper): + """Replace sparse/dense return with the signed increment of objective progress. + + A hit gives positive reward; a heal or objective regression gives negative + reward. No clipping, player-health penalty, step cost or terminal bonus is + added. Delay windows belong to the same step. Across a complete episode, + sum(reward) = final progress - reset progress. + """ + def __init__(self, env): + super().__init__(env) + self.metadata = dict(env.metadata, reward_contract=REWARD_CONTRACT) + self._reward_previous = None + self._reward_total = 0.0 + self._reward_steps = 0 + self._reward_closed = False + self._reward_done = True + + def reset(self, *, seed=None, options=None): + if self._reward_closed: + raise RuntimeError('environment is closed') + obs, info = self.env.reset(seed=seed, options=options) + self._reward_previous = objective_progress(self.unwrapped.snap) + self._reward_total = 0.0 + self._reward_steps = 0 + self._reward_done = False + return obs, dict(info, reward_contract=REWARD_CONTRACT) + + def step(self, action, latency=None): + if self._reward_closed or self._reward_done or self._reward_previous is None: + raise RuntimeError('reset required before step') + try: + obs, _, terminated, truncated, info = self.env.step(action, latency=latency) + current = objective_progress(self.unwrapped.snap) + except BaseException: + self._reward_done = True + raise + reward = current - self._reward_previous + self._reward_previous = current + self._reward_total += reward + self._reward_steps += 1 + self._reward_done = bool(terminated or truncated) + return obs, float(reward), terminated, truncated, dict(info, reward_contract=REWARD_CONTRACT) + + def reward_diagnostics(self): + """Collector-only summary, not part of the visual observation.""" + return dict(contract=REWARD_CONTRACT, episode_return=self._reward_total, + steps=self._reward_steps, done=self._reward_done) + + def close(self): + if not self._reward_closed: + try: + self.env.close() + finally: + self._reward_closed = self._reward_done = True + + +def make_training_env(case_id, *, action_format='keymouse', **kwargs): + """Public RGB environment; new calls default to versioned high-water progress. + + action_format='compact' selects the game's declared MultiDiscrete interface. + All reset options, engine clocks, terminal flags and replay rules are kept. + The raw engine remains sparse internally; this wrapper replaces that scalar. + Explicit 'boss_damage' or 'bossbench/step-damage@1' retains legacy signed + delta behavior. New releases use 'bossbench/step-progress-highwater@1'. + """ + from .progress_reward import StepProgressReward, REWARD_CONTRACT as HIGHWATER + mode = kwargs.pop('reward_mode', HIGHWATER) + if mode not in ('boss_damage', REWARD_CONTRACT, HIGHWATER): + raise ValueError('unknown versioned training reward') + if action_format == 'keymouse': + from .policy_env import make_policy_env + env = make_policy_env(case_id, **kwargs) + elif action_format == 'compact': + from .compact import make_compact_env + env = make_compact_env(case_id, **kwargs) + else: + raise ValueError('action_format must be keymouse or compact') + try: + return StepDamageReward(env) if mode in ('boss_damage', REWARD_CONTRACT) else StepProgressReward(env, case_id) + except BaseException: + env.close() + raise diff --git a/environments/games/prototype/bossbench/tiers.py b/environments/games/prototype/bossbench/tiers.py new file mode 100644 index 0000000000000000000000000000000000000000..800a6042c91ad5fb06a69a2195c9a7a91ecca7d1 --- /dev/null +++ b/environments/games/prototype/bossbench/tiers.py @@ -0,0 +1,97 @@ +"""Three public difficulty tiers shared by every BossBench game. + +The standard interface takes one of three named tiers. Use continuous difficulty for finer control. + + env.reset(seed=1, options={"tier": "easy"}) # public: one of three tiers + env.reset(seed=1, options={"difficulty": 0.37}) # still allowed: direct continuous control + +Each game declares its own tier -> difficulty mapping next to its rule version, so the simulation, the play +page and this public interface all read one source of truth: + + BB.Case games BB.GAME.tiers = {easy: 0.15, normal: 0.5, hard: 0.85} (game.js) + native JS games Module.tiers = {easy: ..., normal: ..., hard: ...} (game.js) + Minecraft mc4d.TIERS = {"easy": ..., "normal": ..., "hard": ...} + +A game that declares nothing uses DEFAULT_TIERS. Passing both `tier` and `difficulty` is rejected, so a +recording can never be ambiguous about which one produced it. + +""" +from __future__ import annotations + +import math +from numbers import Real +from types import MappingProxyType + +TIER_NAMES = ("easy", "normal", "hard") + +DEFAULT_TIERS = MappingProxyType({"easy": 0.2, "normal": 0.5, "hard": 0.8}) +TIERS = DEFAULT_TIERS # backwards-compatible name + +# Reference-controller completion windows in seconds. +TARGET_SECONDS = MappingProxyType({ + "easy": (20.0, 30.0), + "normal": (45.0, 90.0), + "hard": (150.0, 240.0), +}) + + +def validate_declared(declared, where="game"): + """Return a clean {tier: difficulty} from a game's declaration, or raise with a precise reason. + + A declaration must name exactly easy/normal/hard, each a finite number in [0, 1], strictly increasing + from easy to hard. A broken declaration fails when the env is created, inside the game that wrote it. + """ + if declared is None: + return None + if not isinstance(declared, dict): + raise ValueError(f"{where}: tiers must be an object with keys {TIER_NAMES}") + if set(declared) != set(TIER_NAMES): + raise ValueError(f"{where}: tiers must declare exactly {TIER_NAMES}, got {sorted(declared)}") + clean = {} + for name in TIER_NAMES: + value = declared[name] + if isinstance(value, bool) or not isinstance(value, Real) or not math.isfinite(value) or not 0 <= value <= 1: + raise ValueError(f"{where}: tier {name!r} must be a finite number in [0, 1], got {value!r}") + clean[name] = float(value) + if not clean["easy"] < clean["normal"] < clean["hard"]: + raise ValueError(f"{where}: tiers must increase strictly easy < normal < hard, got {clean}") + return clean + + +def difficulty_for(tier, declared=None): + """Continuous difficulty for a public tier, using the game's own declaration when it has one.""" + if tier not in TIER_NAMES: + raise ValueError(f"tier must be one of {TIER_NAMES}, got {tier!r}") + table = declared if declared else DEFAULT_TIERS + return float(table[tier]) + + +def resolve_options(options, declared=None): + """Replace a public `tier` with the concrete `difficulty` the engines already understand. + + Returns a new dict; the original is not modified. `tier` and `difficulty` are mutually exclusive so a + replay's options always say exactly one thing about how hard the fight was. + """ + if not options or "tier" not in options: + return dict(options or {}) + resolved = dict(options) + tier = resolved.pop("tier") + if "difficulty" in resolved: + raise ValueError("pass either tier or difficulty, not both: a recording must be unambiguous") + resolved["difficulty"] = difficulty_for(tier, declared) + resolved["resolved_from_tier"] = tier # provenance: which tier the caller asked for + return resolved + + +def tier_of(difficulty, declared=None, tolerance=1e-9): + """The tier that maps to this difficulty, or None when it is a custom continuous value.""" + for tier in TIER_NAMES: + if abs(difficulty_for(tier, declared) - float(difficulty)) <= tolerance: + return tier + return None + + +def within_target(tier, seconds): + """True when a scripted run's duration falls inside the reference-controller window for that tier.""" + low, high = TARGET_SECONDS[tier] + return low <= float(seconds) <= high diff --git a/environments/games/prototype/bossbench/unified.py b/environments/games/prototype/bossbench/unified.py new file mode 100644 index 0000000000000000000000000000000000000000..ed8c63abbaf1b6f89ab28302dd262878cd9be162 --- /dev/null +++ b/environments/games/prototype/bossbench/unified.py @@ -0,0 +1,488 @@ +"""One Gymnasium interface for every BossBench case, whatever engine runs it (proposal 4.4). + + import bossbench + env = bossbench.make("2d/needle_warden", # web engine (JS, 60 Hz) + obs_mode="symbolic", # "rgb" | "symbolic" | "vector" + time_mode="virtual_rt", # "paused" | "virtual_rt" | "wallclock_rt" + latency=0.3) + env = bossbench.make("3d/minecraft_wither") # Python engine (60 Hz) - same API + obs, info = env.reset(seed=0, options={"difficulty": 0.5}) + obs, reward, terminated, truncated, info = env.step( + "<|action_start|> 120 0 0 ; W ; W ; W,Space ; W ; LMB ; LMB <|action_end|>") + +What is identical across cases (and is all an agent or trainer needs to know): + step one 200 ms key/mouse packet (keymouse.py): str, or a dict from env.action_space + action_space keymouse.KeyMouse() (mouse dx dy dz + 6 x 14 hold matrix); the key *meaning* is per + body and is spelled out in info["manual"]["controls"] + obs rgb: 480 x 854 x 3 uint8 | symbolic: the case's state dict | vector: float32 Box + time paused: the world waits; virtual_rt: ceil(latency / 0.2) no-op packets run first; + wallclock_rt: floor(wall time since the last return / 0.2) no-op packets run first + reward sparse: verifier reward at the end only; dense: + d(boss damage) - d(player damage) + info t, state, events, outcome, player_hp, player_max_hp, boss_hp, boss_max_hp, format_ok, + format_errors, steps, frames, lag_packets, difficulty, engine_seed + (+ manual at reset, verifier on the last step) + verifier() {reward in [-1, 1], win, outcome, boss_damage, seconds, d, player_hp} + end win / loss -> terminated; time cap -> truncated; stepping a finished episode raises + +info["state"] is always filled so oracles and loggers can read it; an rgb-only agent harness must not +pass it to the agent (that is the perception-gap ablation's job, not the env's). + +action_mode="native" (Python engine only) keeps the body's own action space (e.g. MultiDiscrete for +Steve) for RL ablations; one step is still one 200 ms packet with that action held throughout. +""" +from __future__ import annotations + +import hashlib +import copy +from collections.abc import Mapping +import json +import math +from numbers import Integral, Real +import time + +import gymnasium as gym +import numpy as np + +from . import keymouse as km +from .core import RES +from .engine_contract import EngineSpec, RenderStatus + +OBS_MODES = ("rgb", "symbolic", "vector") +TIME_MODES = ("paused", "virtual_rt", "wallclock_rt") +PROTOCOL = ("one step = one 200 ms packet: <|action_start|> dx dy dz ; K1 ; K2 ; K3 ; K4 ; K5 ; K6 <|action_end|>; " + "K_j = 0-4 keys from W A S D Space Shift J K L Q E R LMB RMB held during the j-th 33 1/3 ms sub-step (2 ticks at 60 Hz), " + "comma separated; dx dy in [-1000, 1000] mouse motion, dz in [-5, 5] wheel; " + "a malformed packet runs as no-op and counts as a format error") + + +class Json(gym.Space): + """Observation space of obs_mode='symbolic': a JSON-serialisable dict (the case's state()).""" + + def __init__(self, seed=None): + super().__init__(None, None, seed) + + def contains(self, x) -> bool: + return isinstance(x, dict) + + def sample(self, mask=None, probability=None): + return {} + + def __repr__(self): + return "Json()" + + def __eq__(self, other): + return isinstance(other, Json) + + +def event_names(events): + return [e[0] if isinstance(e, (tuple, list)) else e for e in events] + + +def _plain(o): + if isinstance(o, np.generic): + return o.item() + if isinstance(o, np.ndarray): + return o.tolist() + raise TypeError(type(o)) + + +def _finite_number(value, name, *, upper=None): + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real): + raise ValueError(f"{name} must be a finite number >= 0" + (f" and <= {upper}" if upper is not None else "")) + value = float(value) + if not math.isfinite(value) or value < 0 or (upper is not None and value > upper): + raise ValueError(f"{name} must be a finite number >= 0" + (f" and <= {upper}" if upper is not None else "")) + return value + + +def _clean_band(value, where): + """Validate a game's difficulty_band declaration: a short plain name, or None for 'no segmentation'.""" + if value is None: + return None + if not isinstance(value, str) or not value.strip() or len(value) > 40 or '\n' in value: + raise ValueError(f"{where}: difficulty_band must return a short non-empty string or None, " + f"got {value!r}") + return value.strip() + + +def _reset_options(options): + if options is not None and not isinstance(options, Mapping): + raise ValueError("reset options must be a mapping") + return copy.deepcopy(dict(options or {})) + + +class UnifiedEnv(gym.Env): + """Engine-independent half: action decoding, time modes, reward, info/verifier schema. + + An engine adapter implements _engine_reset(seed, d, options) and _engine_packet(packet, lag, ok), both returning a + snapshot dict {state, events, outcome (None | win | loss | timeout), t, frames, player_hp, player_max_hp, + boss_hp, boss_max_hp}, plus _render / _vector / _manual, and sets fps and max_seconds. + """ + metadata = {"render_modes": ["rgb_array"], "render_fps": round(1 / km.PACKET_SECONDS)} + + def __init__(self, case_id, obs_mode="symbolic", action_mode="keymouse", time_mode="paused", latency=0.0, + difficulty=0.5, reward_mode="sparse", render_mode=None): + for name, value, choices in (("obs_mode", obs_mode, OBS_MODES), ("time_mode", time_mode, TIME_MODES), + ("action_mode", action_mode, ("keymouse", "native")), + ("reward_mode", reward_mode, ("sparse", "dense")), + ("render_mode", render_mode, (None, "rgb_array"))): + if value not in choices: + raise ValueError(f"{name} must be one of {choices}") + self.case_id, self.obs_mode, self.action_mode, self.time_mode = case_id, obs_mode, action_mode, time_mode + self.latency = self._default_latency = _finite_number(latency, "latency") + self.difficulty = _finite_number(difficulty, "difficulty", upper=1) + self.reward_mode = reward_mode + self.render_mode = render_mode + self.action_space = km.KeyMouse() + self.snap, self.done, self.d, self.engine_seed = None, True, self.difficulty, None + self._closed = False + + def _obs_space(self, vector_space=None): + if self.obs_mode == "rgb": + return gym.spaces.Box(0, 255, (RES[1], RES[0], 3), np.uint8) + if self.obs_mode == "vector": + if vector_space is None: + raise ValueError(f"{self.case_id}: obs_mode='vector' is not available for this engine") + return vector_space + return Json() + + @property + def engine_spec(self): + """Default for the existing web engine; independent backends override it.""" + return EngineSpec('web-canvas', '2d', 60, self.max_seconds, 'canvas', 'raster') + + def render_status(self): + return RenderStatus(self.engine_spec.renderer, self.engine_spec.render_kind, True) + + # -- gym API ------------------------------------------------------------- + def reset(self, *, seed=None, options=None): + """Reset using Gym's seed, or an explicit uint32 engine_seed for imported replays. + + Ordinary seed handling is unchanged. options are forwarded to the web + game so its initial world settings match browser play. + """ + self._ensure_open() + options = _reset_options(options) + # A public `tier` (easy/normal/hard) resolves to the continuous difficulty the engines understand, + # using the game's own declared mapping (see tiers.py), so the play page and this interface agree. + from .tiers import resolve_options + options = resolve_options(options, self._declared_tiers()) + d = _finite_number(options.get("difficulty", self.difficulty), "difficulty", upper=1) + latency = _finite_number(options.get("latency", self._default_latency), "latency") + options["difficulty"] = d + if "latency" in options: + options["latency"] = latency + if seed is not None: + if isinstance(seed, (bool, np.bool_)) or not isinstance(seed, Integral) or seed < 0: + raise ValueError("seed must be a nonnegative integer or None") + seed = int(seed) + if "engine_seed" in options: + explicit_seed = options["engine_seed"] + if isinstance(explicit_seed, (bool, np.bool_)) or not isinstance(explicit_seed, Integral) or not 0 <= explicit_seed < 2 ** 32: + raise ValueError("engine_seed must be an integer in [0, 2**32)") + options["engine_seed"] = int(explicit_seed) + self._validate_options(options) + # Invalid reset conditions must not consume RNG or alter a live episode. + super().reset(seed=seed) + self.engine_seed = options.get("engine_seed", None) + if self.engine_seed is None: + self.engine_seed = int(self.np_random.integers(2 ** 31 - 1)) + self.latency = latency + self.d, self.steps, self.format_errors, self.done = d, 0, 0, False + try: + self.snap = self._engine_reset(self.engine_seed, d, options) + except Exception: + self.snap, self.done = None, True + raise + self._prev = self._progress(self.snap) + info = self._info(True, 0) + info["manual"] = self.manual() + obs = self._observe() + self._t_return = time.perf_counter() + return obs, info + + def step(self, action, latency=None): + """latency (s, virtual_rt only) overrides env.latency for this step: the agent's measured think time.""" + self._ensure_reset() + if self.done: + raise RuntimeError("episode is over; call reset()") + latency = self.latency if latency is None else _finite_number(latency, "latency") + if self.time_mode == "virtual_rt": + # Bound work at the episode deadline, including huge but finite latency. + remaining = max(0, math.ceil(self.max_seconds / km.PACKET_SECONDS)) + lag = remaining if latency >= self.max_seconds else math.ceil(latency / km.PACKET_SECONDS - 1e-9) + elif self.time_mode == "wallclock_rt": + lag = max(0, int((time.perf_counter() - self._t_return) / km.PACKET_SECONDS)) + else: + lag = 0 + if self.action_mode == "native": + packet, ok = action, True + else: + packet = km.to_packet(action) + ok = km.parse_packet(packet) is not None + if not ok: + self.format_errors += 1 + self.snap = self._engine_packet(packet, lag, ok) + self.steps += 1 + out = self.snap["outcome"] + terminated, truncated = out in ("win", "loss"), out == "timeout" + prog, reward = self._progress(self.snap), 0.0 + if self.reward_mode == "dense": + reward += (prog[0] - self._prev[0]) - (prog[1] - self._prev[1]) + self._prev = prog + info = self._info(ok, lag) + if terminated or truncated: + self.done = True + info["verifier"] = self.verifier() + reward += info["verifier"]["reward"] + obs = self._observe() + self._t_return = time.perf_counter() + return obs, float(reward), terminated, truncated, info + + def render(self): + self._ensure_reset() + img = self._render() + if not isinstance(img, np.ndarray) or img.shape != (RES[1], RES[0], 3) or img.dtype != np.uint8: + raise RuntimeError(f"render must be RGB uint8 with shape {(RES[1], RES[0], 3)}") + return img + + def verifier(self) -> dict: + self._ensure_reset() + s = self.snap + frac = 1 - max(s["boss_hp"], 0) / s["boss_max_hp"] + win = s["outcome"] == "win" + return {"reward": 1.0 if win else round(-1.0 + frac, 4), "win": win, "outcome": s["outcome"], + "boss_damage": round(frac, 4), "seconds": round(s["t"], 4), "d": self.d, + "player_hp": s["player_hp"]} + + def manual(self) -> dict: + """Prompt context (proposal 4.4): packet protocol, this body's key meanings, this boss's skill table.""" + self._ensure_open() + m = self._manual() + protocol = PROTOCOL + if getattr(self, 'fps', 60) != 60: + protocol = PROTOCOL.replace('(2 ticks at 60 Hz)', + f'(input sampled on native {self.fps} Hz ticks; actual executed time is reported)') + return {"protocol": protocol, "controls": list(m["controls"]), "skills": list(m.get("skills", []))} + + def state_hash(self) -> str: + """sha1 of the symbolic state, for determinism checks across runs and transports.""" + self._ensure_reset() + return hashlib.sha1(json.dumps(self.snap["state"], sort_keys=True, default=_plain).encode()).hexdigest() + + def _ensure_open(self): + if self._closed: + raise RuntimeError("environment is closed; create a new environment") + + def _ensure_reset(self): + self._ensure_open() + if self.snap is None: + raise RuntimeError("environment has not been reset; call reset()") + + def _validate_options(self, options): + try: + json.dumps(options, allow_nan=False, default=_plain) + except (TypeError, ValueError) as ex: + raise ValueError("reset options must be finite JSON data") from ex + + def close(self): + self._closed, self.done = True, True + + # -- shared helpers ---------------------------------------------------------- + def _progress(self, s): + return (1 - max(s["boss_hp"], 0) / s["boss_max_hp"], 1 - max(s["player_hp"], 0) / s["player_max_hp"]) + + def _info(self, ok, lag): + s = self.snap + info = {"t": round(s["t"], 4), "state": s["state"], "events": event_names(s["events"]), + "outcome": s["outcome"], "player_hp": s["player_hp"], "player_max_hp": s["player_max_hp"], + "boss_hp": s["boss_hp"], "boss_max_hp": s["boss_max_hp"], "format_ok": ok, + "format_errors": self.format_errors, "steps": self.steps, "frames": s["frames"], + "lag_packets": lag, "difficulty": self.d, "engine_seed": self.engine_seed} + band = self._difficulty_band(self.d) + if band is not None: + info["difficulty_band"] = band + return info + + def _observe(self): + if self.obs_mode == "rgb": + return self.render() + if self.obs_mode == "vector": + return self._vector() + return self.snap["state"] + + # -- engine adapter -------------------------------------------------------- + def _declared_tiers(self): + """The game's own {easy, normal, hard} -> difficulty mapping, or None to use tiers.DEFAULT_TIERS.""" + return None + + def _difficulty_band(self, d): + """The game's own name for the segment `d` falls in, or None if it declares no segmentation. + + 2026-11-03, requested by the Cuphead session. Several games map the continuous difficulty onto the + original's own modes (Cuphead Simple/Regular/Expert at 0.25 and 0.75, DOOM's skill levels, Terraria's + Classic/Expert gate at 0.75). Behaviour therefore steps at those boundaries: Cuphead measured the + scripted controller's median duration jumping +8%..+24% across d=0.25, and hits taken rising (Cagney + 0.13 -> 1.13) across d=0.75. Anyone sweeping d to find d* sees a discontinuous curve, and until now + had to re-derive the boundaries from the game's own source to know why. + + This leaks nothing: the band is a pure function of `difficulty`, which the public info already + carries. It is a label on a number the policy can already see — not live state. + """ + return None + + def _engine_reset(self, seed, d, options=None): + raise NotImplementedError + + def _engine_packet(self, packet, lag, ok): + raise NotImplementedError + + def _render(self): + raise NotImplementedError + + def _vector(self): + raise NotImplementedError + + def _manual(self): + raise NotImplementedError + + +class PyCaseEnv(UnifiedEnv): + """Adapter for the existing Python Case engine: the Case ticks at its own FPS (60 Hz -> 12 ticks per + packet, 2 per sub-step) and the body's keys() maps each tick's held keys onto its native action.""" + + def __init__(self, case_id, factory, case_kw=None, **kw): + super().__init__(case_id, **kw) + self.inner = factory(difficulty=self.difficulty, **(case_kw or {})) # BossBenchEnv: owns case + renderer + self.case = self.inner.case + self.fps = self.inner.metadata["render_fps"] + self.ticks = round(self.fps * km.PACKET_SECONDS) + self.max_ticks = self.inner.max_ticks + self.max_seconds = self.max_ticks / self.fps + if self.action_mode == "native": + self.action_space = self.case.body.action_space + self.observation_space = self._obs_space(self.case.observation_space) + + @property + def engine_spec(self): + return EngineSpec('minecraft-python', '3d', 60, self.max_seconds, 'moderngl', 'perspective', + resolution=tuple(self.case.size)) + + def render_status(self): + error = getattr(self.case, 'render_error', None) + ready = getattr(self.case, '_gl', None) is not None and error is None + return RenderStatus('moderngl', 'perspective' if ready else 'raster', ready, error) + + def _validate_options(self, options): + super()._validate_options(options) + # Minecraft loadout/camera are public experiment conditions, passed + # through the same Gym reset contract as the web games' options. + # Validate before UnifiedEnv changes the live episode or RNG state. + if self.case_id.startswith("3d/minecraft_"): + for key, choices in (("weapon", ("sword", "bow")), + ("camera", ("first", "third"))): + if key in options and options[key] not in choices: + raise ValueError(f"Minecraft {key} must be one of {choices}") + + def reset(self, *, seed=None, options=None): + obs, info = super().reset(seed=seed, options=options) + return obs, self._visual_info(info) + + def step(self, action, latency=None): + obs, reward, terminated, truncated, info = super().step(action, latency) + return obs, reward, terminated, truncated, self._visual_info(info) + + def _visual_info(self, info): + # UnifiedEnv builds info before rendering. Inspect the renderer only + # after _observe returned so a fallback cannot masquerade as 3D RGB. + if self.case_id.startswith("3d/minecraft_"): + info = dict(info) + info.update(camera=self.case.camera, + weapon=getattr(self.case.body, "weapon", "sword")) + if self.obs_mode == "rgb": + error = getattr(self.case, "render_error", None) + renderer = getattr(self.case, "_gl", None) + info["render_error"] = error + info["renderer"] = "moderngl" if renderer is not None and error is None else "topdown" + if info["renderer"] == "moderngl": + info["render_backend"] = renderer.ctx.info.get("GL_RENDERER") + return info + + def _snapshot(self, frames): + c = self.case + out = c.outcome() or ("timeout" if c.t >= self.max_ticks else None) + return {"state": c.state(), "events": list(c.events), "outcome": out, "t": c.t / self.fps, + "player_hp": round(max(float(c.body.hp), 0.0), 4), "player_max_hp": float(c.body.max_hp), + "boss_hp": round(max(float(c.boss.hp), 0.0), 4), "boss_max_hp": float(c.boss.max_hp), "frames": frames} + + def _engine_reset(self, seed, d, options=None): + if self.case_id.startswith("3d/minecraft_"): + self.case.reset(seed, d, options=dict(options or {})) + else: + self.case.reset(seed, d) + self.inner._has_reset, self.inner._done = True, False + self._held = frozenset() + return self._snapshot(0) + + def _tick_all(self, actions): + c, n = self.case, 0 + for a in actions: + if c.outcome() or c.t >= self.max_ticks: + break + c.tick(a() if callable(a) else a) # keys() runs at tick time: it may read the current state + n += 1 + return n + + def _key_ticks(self, packet): + sched, self._held = km.schedule(packet, self.ticks, self._held) + body, c = self.case.body, self.case + return [lambda h=h, p=p, m=m: body.keys(c, h, p, m) for h, p, m in sched] + + def _engine_packet(self, packet, lag, ok): + c, frames = self.case, 0 + c.events.clear() + native = self.action_mode == "native" + for _ in range(lag): # the world did not wait + if c.outcome() or c.t >= self.max_ticks: + break + frames += self._tick_all([c.body.noop()] * self.ticks if native else self._key_ticks(None)) + if c.outcome() or c.t >= self.max_ticks: + return self._snapshot(frames) + if native: + a = c.body.parse(packet) if isinstance(packet, str) else packet + frames += self._tick_all([a] * self.ticks) + else: + frames += self._tick_all(self._key_ticks(km.parse_packet(packet) if ok else None)) + return self._snapshot(frames) + + def _render(self): + return self.inner.render() + + def _vector(self): + return self.case.observe() + + def _manual(self): + skills = [{"move": n, "cue": m.get("cue") or m.get("telegraph"), "punish": m.get("punish"), + "damage": m.get("damage")} for n, m in self.case.boss.MOVES.items()] + return {"controls": self.case.body.manual, "skills": skills} + + def _declared_tiers(self): + # The case's own module declares TIERS (e.g. mc4d.TIERS) next to its RULES constant. + import sys + from .tiers import validate_declared + module = sys.modules.get(type(self.case).__module__) + return validate_declared(getattr(module, "TIERS", None), where=self.case_id) + + def _difficulty_band(self, d): + # Optional, same pattern as TIERS: the case's module may declare difficulty_band(d) -> str. + import sys + module = sys.modules.get(type(self.case).__module__) + fn = getattr(module, "difficulty_band", None) + return _clean_band(fn(d), self.case_id) if callable(fn) else None + + def close(self): + if not self._closed: + try: + self.inner.close() + finally: + super().close() diff --git a/environments/games/prototype/bossbench/webenv.py b/environments/games/prototype/bossbench/webenv.py new file mode 100644 index 0000000000000000000000000000000000000000..53369d7934bd7d37d05563207d2ad55eb634723b --- /dev/null +++ b/environments/games/prototype/bossbench/webenv.py @@ -0,0 +1,260 @@ +"""Gymnasium binding for the web engine (web/engine + web/games//, 60 Hz): the Hollow-Knight-style 2D cases. + +The simulation stays in JavaScript (one source of truth for the browser game, the Node tests and +training). Each case belongs to one game folder (bossbench.WEB_GAME), whose index.html fixes the script order. +This module drives it through web/engine/bridge.js over one of two transports: + + node `node web/tools/gym_server.js `, JSON lines on stdin/stdout. symbolic only, fast, no browser. + browser a headless Chromium page (Playwright) with the game's scripts + renderer loaded; needed for obs_mode="rgb". + BB_CHANNEL=msedge|chrome picks an installed browser instead of Playwright's own build. + +transport="auto" picks browser for rgb and node otherwise. Both transports load the same game rules. +""" +from __future__ import annotations + +import atexit +import base64 +import json +import os +import re +import shutil +import subprocess + +import numpy as np + +from .unified import UnifiedEnv, _finite_number, _plain + +WEB = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "web") +NO_PAGE = ("engine/input.js", "engine/app.js") # browser-app UI: needs the game's DOM, not part of the env + +DEFAULT_GAME = "hollowknight_remake" + + +def game_of(case_id): + from . import WEB_GAME + if case_id not in WEB_GAME: + raise KeyError(f"no web game registers {case_id!r}; known: {sorted(WEB_GAME)}") + return WEB_GAME[case_id] + + +def game_scripts(game): + """Absolute paths of web/games//index.html's scripts in page order, minus the browser-app layer.""" + gdir = os.path.join(WEB, "games", game) + with open(os.path.join(gdir, "index.html"), encoding="utf-8") as source: + html = source.read() + out = [os.path.normpath(os.path.join(gdir, s)) for s in re.findall(r')") + self.p = subprocess.Popen([node, os.path.join(WEB, "tools", "gym_server.js"), game], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, text=True, encoding="utf-8", bufsize=1) + + def __call__(self, msg): + self.p.stdin.write(json.dumps(msg, allow_nan=False, default=_plain) + "\n") + line = self.p.stdout.readline() + if not line: + raise RuntimeError(f"web gym server exited (code {self.p.poll()})") + return json.loads(line) + + def close(self): + if self.p.poll() is None: + self.p.stdin.close() + try: + self.p.wait(timeout=5) + except subprocess.TimeoutExpired: + self.p.terminate() + try: + self.p.wait(timeout=5) + except subprocess.TimeoutExpired: + self.p.kill() + self.p.wait(timeout=5) + elif not self.p.stdin.closed: + self.p.stdin.close() + if not self.p.stdout.closed: + self.p.stdout.close() + + +class BrowserTransport: + """One shared headless browser per process, one page per env.""" + _pw = _browser = None + _owner_pid = None + + @classmethod + def _launch(cls): + if cls._browser is not None and cls._owner_pid != os.getpid(): + raise RuntimeError("browser runtime belongs to another process; use AsyncVectorEnv(context='spawn')") + if cls._browser is None: + from playwright.sync_api import sync_playwright + cls._pw = sync_playwright().start() + cls._owner_pid = os.getpid() + want = os.environ.get("BB_CHANNEL") + errors = [] + for ch in ([want] if want else [None, "chrome", "msedge"]): + try: + cls._browser = cls._pw.chromium.launch(channel=ch, args=["--no-sandbox"]) + break + except Exception as ex: # this channel is not installed; try the next one + errors.append(f"{ch or 'playwright chromium'}: {str(ex).splitlines()[0]}") + if cls._browser is None: + cls._pw.stop() + cls._pw = None + raise RuntimeError("no headless browser for rgb web cases (run `playwright install chromium` " + "or set BB_CHANNEL):\n " + "\n ".join(errors)) + atexit.register(cls._shutdown) + return cls._browser + + @classmethod + def _shutdown(cls): + if cls._owner_pid is not None and cls._owner_pid != os.getpid(): + # A forked child's atexit must not close the parent's browser/pipes. + cls._browser = cls._pw = cls._owner_pid = None + return + try: + if cls._browser is not None: + cls._browser.close() + except Exception: + pass + try: + if cls._pw is not None: + cls._pw.stop() + except Exception: + pass + cls._browser = cls._pw = cls._owner_pid = None + + def __init__(self, game=DEFAULT_GAME): + self.page = self._launch().new_page() + self._pid = os.getpid() + try: + for path in game_scripts(game): + self.page.add_script_tag(path=path) + self.page.add_script_tag(path=os.path.join(WEB, "engine", "bridge.js")) + except Exception: + self.close() + raise + + def __call__(self, msg): + if self._pid != os.getpid(): + raise RuntimeError("browser page belongs to another process; create env in a spawn worker") + # JSON.stringify on the page, as the Node transport does (Playwright's own serializer keeps -0 apart from 0) + return json.loads(self.page.evaluate( + "m => { try { return JSON.stringify(BB.bridge(m)); } catch (e) { return JSON.stringify({ error: String(e.stack || e) }); } }", + msg)) + + def close(self): + if self._pid != os.getpid(): + return + try: + self.page.close() + except Exception: + pass + + +def list_cases(game=DEFAULT_GAME): + t = NodeTransport(game) + try: + return t({"cmd": "cases"})["cases"] + finally: + t.close() + + +class WebCaseEnv(UnifiedEnv): + fps = 60 + + def __init__(self, case_id, transport="auto", game=None, **kw): + super().__init__(case_id, **kw) + if self.action_mode != "keymouse": + raise ValueError("web cases only take key/mouse packets (action_mode='keymouse')") + self.observation_space = self._obs_space(None) + if transport not in ("auto", "browser", "node"): + raise ValueError("transport must be 'auto', 'browser' or 'node'") + if transport == "auto": + transport = "browser" if self.obs_mode == "rgb" else "node" + if self.obs_mode == "rgb" and transport != "browser": + raise ValueError("RGB observations require browser transport") + self.transport, self.game = transport, game or game_of(case_id) + self.t = BrowserTransport(self.game) if transport == "browser" else NodeTransport(self.game) + try: + meta = self._call({"cmd": "make", "id": case_id, "rgb": transport == "browser"}) + from .tiers import validate_declared + self._tiers = validate_declared(self._call({"cmd": "meta"}).get("tiers"), + where=f"{self.game} BB.GAME.tiers") + except Exception: + self.close() + raise + self.fps, self.max_seconds, self._man = meta["fps"], meta["max_seconds"], meta["manual"] + self._frame = None + + def _declared_tiers(self): + return self._tiers + + def _difficulty_band(self, d): + """The game's own BB.GAME.difficultyBand(d), read through the bridge like `tiers`. + + Cached per difficulty: the band is a pure function of d, but _info() runs on every step, so querying + the page each time cost ~25% of a symbolic step (0.095 ms of 0.39 ms) and 2.3% of an RGB step. Found + and measured by the Cuphead session, 2026-11-03. A dict keyed by d keeps `reset(difficulty=...)` + correct across difficulties within one episode-sequence without re-querying. + """ + key = float(d) + cache = getattr(self, '_band_cache', None) + if cache is None: + cache = self._band_cache = {} + if key not in cache: + from .unified import _clean_band + try: + value = self._call({'cmd': 'band', 'd': key}).get('band') + except Exception: + value = None + cache[key] = _clean_band(value, f'{self.case_id}.difficultyBand') + return cache[key] + + def _validate_options(self, options): + super()._validate_options(options) + if self.case_id.startswith("terraria/") and "dawn_in_seconds" in options: + options["dawn_in_seconds"] = _finite_number(options["dawn_in_seconds"], "dawn_in_seconds", upper=540) + + def _call(self, msg): + res = self.t(msg) + if "error" in res: + raise RuntimeError(f"{self.case_id}: {res['error']}") + return res + + def _snapshot(self, res): + if "frame" in res: + f = res["frame"] + self._frame = np.frombuffer(base64.b64decode(f["b64"]), np.uint8).reshape(f["shape"]) + i = res["info"] + return {"state": res["state"], "events": i["events"], "outcome": i["outcome"], "t": i["t"], + "frames": i["frames"], "player_hp": i["player_hp"], "player_max_hp": i["player_max_hp"], + "boss_hp": i["boss_hp"], "boss_max_hp": i["boss_max_hp"]} + + def _engine_reset(self, seed, d, options=None): + # Game options (e.g. Terraria's dawn_in_seconds) must reach the same reset + # as human play. Keep the top-level difficulty for older bridge clients. + return self._snapshot(self._call({"cmd": "reset", "seed": seed, "difficulty": d, + "options": dict(options or {})})) + + def _engine_packet(self, packet, lag, ok): + return self._snapshot(self._call({"cmd": "step", "packet": packet, "lag": lag})) + + def _render(self): + if self.transport != "browser": + raise RuntimeError(f"{self.case_id}: rgb frames need transport='browser' (obs_mode='rgb' picks it)") + return self._frame + + def _manual(self): + return self._man + + def close(self): + if not self._closed: + try: + if getattr(self, "t", None) is not None: + self.t.close() + finally: + self.t = None + super().close() diff --git a/environments/games/prototype/bossbench_llm/__init__.py b/environments/games/prototype/bossbench_llm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c16d0dd18c6952ed19339ac23191e43964406e8 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/__init__.py @@ -0,0 +1,6 @@ +"""LLM harness for BossBench: Lumine-format and semantic-format agents on the BossBench games. + +Modules: lumine (action text <-> packets), semantic (named actions), prompting (system prompts, zh/en), +session (Lumine sliding-window chat), frames (JPEG), client (OpenAI-compatible), policies, envs, run, verify. +""" +__version__ = "bossbench-llm@1" diff --git a/environments/games/prototype/bossbench_llm/client.py b/environments/games/prototype/bossbench_llm/client.py new file mode 100644 index 0000000000000000000000000000000000000000..565f1d9e5bd748f32708aaacae06cc2accd15e90 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/client.py @@ -0,0 +1,66 @@ +"""Minimal OpenAI-compatible chat client (standard library only): vLLM, SGLang, OpenAI, any /v1/chat/completions. + +Notes for Lumine-style models served by vLLM: <|action_start|> / <|action_end|> are special tokens and vLLM drops +special tokens from the returned text by default. Pass --extra-body '{"skip_special_tokens": false}' (the harness +also accepts an action body without markers and counts it as `bare`). +""" +from __future__ import annotations + +import json +import os +import time +import urllib.error +import urllib.request + + +class ChatError(RuntimeError): + """The endpoint could not produce a reply (network / HTTP / malformed response): an infrastructure failure, + never scored as a model action.""" + + +class ChatClient: + def __init__(self, base_url, model, *, api_key=None, api_key_env="OPENAI_API_KEY", temperature=1.0, top_p=1.0, + max_tokens=128, timeout=120.0, retries=3, extra_body=None, headers=None): + self.url = base_url.rstrip("/") + "/chat/completions" + self.model = model + self.api_key = api_key if api_key is not None else os.environ.get(api_key_env or "", "") + self.params = {"temperature": temperature, "top_p": top_p, "max_tokens": max_tokens} + self.extra_body = dict(extra_body or {}) + self.timeout, self.retries = float(timeout), int(retries) + self.headers = {"Content-Type": "application/json", **(headers or {})} + if self.api_key: + self.headers["Authorization"] = "Bearer " + self.api_key + + def describe(self): + """Public settings for the run log (never the key).""" + return {"endpoint": self.url, "model": self.model, **self.params, "extra_body": self.extra_body} + + def complete(self, messages): + """-> (reply text, metadata). Raises ChatError after `retries` failed attempts.""" + body = json.dumps({"model": self.model, "messages": messages, "stream": False, **self.params, + **self.extra_body}).encode("utf-8") + last = None + for attempt in range(self.retries + 1): + start = time.perf_counter() + try: + request = urllib.request.Request(self.url, data=body, headers=self.headers, method="POST") + with urllib.request.urlopen(request, timeout=self.timeout) as response: + payload = json.loads(response.read().decode("utf-8")) + choice = payload["choices"][0] + content = choice["message"].get("content") + if isinstance(content, list): # some servers return content parts + content = "".join(p.get("text", "") for p in content if isinstance(p, dict)) + reasoning = choice["message"].get("reasoning_content") + return (content or ""), {"seconds": time.perf_counter() - start, "attempts": attempt + 1, + "finish_reason": choice.get("finish_reason"), "usage": payload.get("usage"), + "reasoning_content": reasoning} + except urllib.error.HTTPError as e: + detail = e.read().decode("utf-8", "replace")[:500] + last = f"HTTP {e.code}: {detail}" + if 400 <= e.code < 500 and e.code not in (408, 409, 429): + break # a request error will not fix itself + except (urllib.error.URLError, TimeoutError, OSError, KeyError, IndexError, ValueError) as e: + last = f"{type(e).__name__}: {e}" + if attempt < self.retries: + time.sleep(min(30.0, 2.0 ** attempt)) + raise ChatError(last or "unknown error") diff --git a/environments/games/prototype/bossbench_llm/envs.py b/environments/games/prototype/bossbench_llm/envs.py new file mode 100644 index 0000000000000000000000000000000000000000..d64f689ad60c9141b862ab2ebaa1a5a67f481a7a --- /dev/null +++ b/environments/games/prototype/bossbench_llm/envs.py @@ -0,0 +1,196 @@ +"""One game episode behind the LLM harness: reset, execute a parsed model action, trusted result, replay record. + +Three routes, all on the project's public interfaces (nothing here edits or monkey-patches game code): +* LumineGame Lumine text -> BossBench packet -> bossbench.make_policy_env (every registered case). +* CompactGame semantic JSON -> compact action -> bossbench.make_compact_env (18 games). +* TerrariaSemantic semantic JSON -> terraria-semantic@1 (web/games/terraria_remake/semantic_ppo_v1), 2 x 100 ms. + +Only the public RGB frame goes to the model. Results (verifier, final hash) are read on the trusted side for the +log and are never put into the model's context. +""" +from __future__ import annotations + +from pathlib import Path +import sys + +import bossbench +from bossbench import keymouse as km, scripted +from bossbench.scope import POLICY_CASES + +from . import lumine +from .semantic import TERRARIA, Vocabulary + +ROOT = Path(bossbench.__file__).resolve().parents[2] +INVALID = "invalid model action" # any non-packet text: the env runs a no-op and counts a format error + + +def game_of(case_id): + if case_id not in POLICY_CASES: + raise KeyError(f"unknown case {case_id!r}; known: {sorted(POLICY_CASES)}") + return POLICY_CASES[case_id]["game"] + + +def _resolve_options(options, info): + """Pin a tier to the concrete difficulty it produced, as bossbench.scripted.play does.""" + options = dict(options) + if "tier" in options: + options["resolved_from_tier"] = options.pop("tier") + options["difficulty"] = float(info["difficulty"]) + return options + + +class _PacketGame: + """Shared by the two routes that end in ordinary 200 ms BossBench packets (replayable by make_policy_env).""" + fmt = None + + def __init__(self, case_id): + self.case_id, self.game = case_id, game_of(case_id) + self.env = None + self.packets, self.terminated, self.truncated = [], False, False + + def reset(self, seed, options): + options = dict(options or {}) + options.setdefault("engine_seed", int(seed)) # same world as the play page / scripted replays + obs, info = self.env.reset(seed=int(seed), options=options) + self.gym_seed, self.options = int(seed), _resolve_options(options, info) + self.packets, self.terminated, self.truncated = [], False, False + return obs, info + + def _run(self, action, packet): + obs, _, terminated, truncated, info = self.env.step(action) + self.packets.append(packet) + self.terminated, self.truncated = bool(terminated), bool(truncated) + return obs, terminated or truncated, info + + def noop(self): + return self._step_packet(km.NOOP) + + def result(self): + raw = self.env.unwrapped + v = raw.verifier() + return {"outcome": v["outcome"], "win": bool(v["win"]), "boss_damage": v["boss_damage"], + "seconds": v["seconds"], "difficulty": v.get("d"), "player_hp": v.get("player_hp"), + "format_errors": int(getattr(raw, "format_errors", 0))} + + def replay(self): + raw = self.env.unwrapped + v = raw.verifier() + ticks = int(round(raw.snap["t"] * raw.fps)) + return {"format": scripted.REPLAY_FORMAT, "case_id": self.case_id, "game": self.game, + "contract": "bossbench/policy-gym@2", "rules": scripted.rules(self.env), "native_hz": raw.fps, + "gym_seed": self.gym_seed, "engine_seed": int(raw.engine_seed), "options": self.options, + "controller": f"bossbench_llm ({self.fmt} actions, see episode.json)", + "packets": list(self.packets), "steps": len(self.packets), "ticks": ticks, + "seconds": round(ticks / raw.fps, 4), "outcome": v["outcome"], "terminated": self.terminated, + "truncated": self.truncated, "verifier": v, "final_hash": scripted.state_hash(self.env), + "source_sha256": scripted.source_files(self.env)} + + def provenance(self): + return {"rules": scripted.rules(self.env), "route": scripted.route(self.env), + "native_hz": self.env.unwrapped.fps, "max_seconds": getattr(self.env.unwrapped, "max_seconds", None)} + + def close(self): + if self.env is not None: + self.env.close() + self.env = None + + +class LumineGame(_PacketGame): + fmt = "lumine" + + def __init__(self, case_id, mouse_kind): + super().__init__(case_id) + self.mouse_kind = mouse_kind + self.env = bossbench.make_policy_env(case_id) + + def _step_packet(self, packet): + return self._run(packet, packet) + + def step(self, parsed): + """parsed: lumine.Parsed. Format errors run a no-op that the env counts as a format error.""" + return self._step_packet(parsed.packet if parsed.ok else INVALID) + + +class CompactGame(_PacketGame): + fmt = "semantic" + + def __init__(self, case_id): + super().__init__(case_id) + self.vocab = Vocabulary.for_game(self.game) + self.env = bossbench.make_compact_env(case_id) + self.spec = self.env.compact_spec + + def _step_packet(self, packet): + # A packet given to the compact wrapper is not a compact action; run it on the inner policy env. + obs, _, terminated, truncated, info = self.env.env.step(packet) + self.packets.append(packet) + self.terminated, self.truncated = bool(terminated), bool(truncated) + return obs, terminated or truncated, info + + def step(self, parsed): + if not parsed.ok: + return self._run(INVALID, INVALID) + packet = self.spec.compose(self.spec.parse(parsed.action)) + return self._run(dict(parsed.action), packet) + + +class TerrariaSemantic: + fmt = "semantic" + + def __init__(self, case_id): + if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + from web.games.terraria_remake.semantic_ppo_v1 import make_semantic_env + self.case_id, self.game = case_id, TERRARIA + self.vocab = Vocabulary.for_game(TERRARIA) + self.env = make_semantic_env(case_id) + self.windows = round(0.2 / self.vocab.window_seconds) + + def reset(self, seed, options): + options = dict(options or {}) + options.setdefault("engine_seed", int(seed)) + obs, info = self.env.reset(seed=int(seed), options=options) + self.gym_seed, self.options = int(seed), dict(options) + return obs, info + + def _windows(self, action): + done, obs, info = False, None, None + for _ in range(self.windows): + obs, _, terminated, truncated, info = self.env.step(action) + done = terminated or truncated + if done: + break + return obs, done, info + + def noop(self): + return self._windows(None) + + def step(self, parsed): + return self._windows(dict(parsed.action) if parsed.ok else "INVALID") + + def result(self): + d = self.env.diagnostic() + v = d.get("verifier", {}) + return {"outcome": v.get("outcome"), "win": bool(v.get("win")), "boss_damage": v.get("boss_damage"), + "seconds": v.get("seconds"), "difficulty": v.get("d"), "player_hp": v.get("player_hp"), + "format_errors": None} + + def replay(self, path): + return self.env.save_replay(path) + + def provenance(self): + return {"rules": self.env.meta.get("rules"), "route": "terraria-semantic@1", + "native_hz": 60, "max_seconds": self.env.meta.get("max_seconds")} + + def close(self): + if self.env is not None: + self.env.close() + self.env = None + + +def open_game(case_id, fmt, mouse_kind="none"): + if fmt == "lumine": + return LumineGame(case_id, mouse_kind) + if fmt == "semantic": + return TerrariaSemantic(case_id) if game_of(case_id) == TERRARIA else CompactGame(case_id) + raise ValueError("format must be 'lumine' or 'semantic'") diff --git a/environments/games/prototype/bossbench_llm/frames.py b/environments/games/prototype/bossbench_llm/frames.py new file mode 100644 index 0000000000000000000000000000000000000000..6f47b19251b293c48abdafaeeb108fed4fc8d606 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/frames.py @@ -0,0 +1,23 @@ +"""Frame encoding for the model (Lumine: one 1280x720 JPEG per 200 ms, sent as base64).""" +from __future__ import annotations + +import base64 +import io + +import numpy as np +from PIL import Image + +DEFAULT_SIZE = (1280, 720) + + +def encode(frame, size=DEFAULT_SIZE, quality=90): + """RGB uint8 (H, W, 3) -> (jpeg bytes, data URL). size=None keeps the native 854x480.""" + if not isinstance(frame, np.ndarray) or frame.ndim != 3 or frame.shape[2] != 3 or frame.dtype != np.uint8: + raise ValueError("expected an RGB uint8 frame") + image = Image.fromarray(frame, "RGB") + if size is not None and image.size != tuple(size): + image = image.resize(tuple(size), Image.BICUBIC) + buf = io.BytesIO() + image.save(buf, format="JPEG", quality=int(quality), optimize=False) + data = buf.getvalue() + return data, "data:image/jpeg;base64," + base64.b64encode(data).decode("ascii") diff --git a/environments/games/prototype/bossbench_llm/lumine.py b/environments/games/prototype/bossbench_llm/lumine.py new file mode 100644 index 0000000000000000000000000000000000000000..35add36b8e501805a0d39a0871db824a9b57c4ee --- /dev/null +++ b/environments/games/prototype/bossbench_llm/lumine.py @@ -0,0 +1,194 @@ +"""Lumine-format action text <-> BossBench key/mouse packets. + +Lumine (arXiv 2511.08892; internal CPT preprocessing `get_lumine_token`) emits one action per 200 ms: + + <|action_start|>X Y Z ; K1 ; K2 ; K3 ; K4 ; K5 ; K6<|action_end|> + +* X, Y: relative mouse displacement, integers in [-1000, 1000] (X > 0 right, Y > 0 down), in units of 1/1000 of + the screen width / height. Z: scroll steps in [-5, 5] (Z > 0 up). +* K1..K6: six 33 ms chunks; each holds 0-4 key names separated by spaces. A key listed in consecutive chunks + stays held (not pressed again); an unlisted key is released. +* Key names: capital letters A-Z; Space Shift Ctrl Alt Tab Esc Caps; number keys as words zero..nine; + F1-F12 as One..Twelve; mouse buttons LB RB MB. +* Optional reasoning before the action: <|thought_start|> ... <|thought_end|>. + +BossBench executes "<|action_start|> dx dy dz ; K1 ; ... ; K6 <|action_end|>" with comma-separated keys from +W A S D Space Shift J K L Q E R LMB RMB (prototype/bossbench/keymouse.py). This module is the only translation +between the two; it never changes timing (both are 6 x 33 ms per 200 ms) and never reads game state. + +Mouse units: on "pointer" games (an on-screen crosshair follows the mouse) X/Y are screen-normalised exactly as in +Lumine, so X = 1000 moves the crosshair one full screen width (854 game pixels). On "camera" and "none" games X/Y +are passed through unchanged (1 unit = 1 game mouse count), which keeps every turn rate the game allows reachable. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from fractions import Fraction +import re + +from bossbench import keymouse as km + +FORMAT = "lumine-action@1" +SCREEN = (854, 480) # Game coordinate size; model image preprocessing is configured separately. + +LETTERS = tuple(chr(c) for c in range(ord("A"), ord("Z") + 1)) +NUMBER_WORDS = ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") +FKEY_WORDS = ("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve") +SPECIAL = ("Space", "Shift", "Ctrl", "Alt", "Tab", "Esc", "Caps") +MOUSE_BUTTONS = ("LB", "RB", "MB") +LUMINE_KEYS = frozenset(LETTERS + NUMBER_WORDS + FKEY_WORDS + SPECIAL + MOUSE_BUTTONS) + +# Lumine key name -> BossBench key name. Valid Lumine keys missing here have no binding in any BossBench game. +TO_BOSSBENCH = {k: k for k in ("W", "A", "S", "D", "J", "K", "L", "Q", "E", "R", "Space", "Shift")} +TO_BOSSBENCH.update({"LB": "LMB", "RB": "RMB"}) +FROM_BOSSBENCH = {v: k for k, v in TO_BOSSBENCH.items()} + +# Lenient mode only: unambiguous case variants and the BossBench spellings of the mouse buttons. +_LENIENT = {k.upper(): k for k in LETTERS + SPECIAL + MOUSE_BUTTONS} +_LENIENT.update({"LMB": "LB", "RMB": "RB", "MMB": "MB", "SPACEBAR": "Space", "CONTROL": "Ctrl", "ESCAPE": "Esc"}) + +_THOUGHT = re.compile(r"<\|thought_start\|>([\s\S]*?)<\|thought_end\|>") +_THINK = re.compile(r"([\s\S]*?)") +_ACTION = re.compile(r"<\|action_start\|>([\s\S]*?)<\|action_end\|>") +_INT = re.compile(r"[+-]?[0-9]{1,6}") +_TRAILERS = ("<|im_end|>", "<|endoftext|>", "", "<|eot_id|>") + + +def mouse_scale(kind): + """(sx, sy): game mouse counts per Lumine unit for this game's mouse kind.""" + if kind == "pointer": + return Fraction(SCREEN[0], 1000), Fraction(SCREEN[1], 1000) + return Fraction(1), Fraction(1) + + +def _round_scaled(value, scale): + """round(value * scale), halves away from zero, in exact integer arithmetic.""" + scale = Fraction(scale) + num, den = scale.numerator, scale.denominator + q = (2 * abs(value) * num + den) // (2 * den) + return -q if value < 0 else q + + +@dataclass +class Parsed: + ok: bool # a format-valid Lumine action was found + packet: str | None = None # BossBench packet to execute; None -> run a no-op (format error) + mouse: tuple = (0, 0, 0) # Lumine X Y Z as written + groups: list = field(default_factory=list) # Lumine key tokens per chunk (canonical names) + thought: str | None = None + unbound: list = field(default_factory=list) # valid Lumine keys with no BossBench binding (dropped) + bare: bool = False # the <|action_*|> markers were missing (e.g. stripped by the server) + lenient_fixes: int = 0 # tokens accepted only by lenient normalisation + error: str | None = None + + @property + def text(self): + """Canonical Lumine text of what was parsed (None when not ok).""" + return format_action(self.mouse, self.groups) if self.ok else None + + +def format_action(mouse, groups): + """Canonical Lumine text: 'X Y Z ; g1 ; ... ; g6' wrapped in the action markers.""" + x, y, z = (int(v) for v in mouse) + if len(groups) != km.SUBSTEPS: + raise ValueError("Lumine actions have exactly 6 chunks") + return "<|action_start|>%d %d %d ; " % (x, y, z) + " ; ".join(" ".join(g) for g in groups) + "<|action_end|>" + + +def strip_thoughts(text): + """-> (text without reasoning blocks, last reasoning text or None). Accepts Lumine and blocks.""" + thought = None + for pattern in (_THOUGHT, _THINK): + found = pattern.findall(text) + if found: + thought = found[-1].strip() or thought + text = pattern.sub(" ", text) + return text, thought + + +def _canonical_token(token, lenient): + if token in LUMINE_KEYS: + return token, False + if lenient: + fixed = _LENIENT.get(token.upper()) + if fixed is not None: + return fixed, True + return None, False + + +def parse(reply, *, mouse_kind="none", lenient=False, accept_bare=True): + """Model reply text -> Parsed (with the BossBench packet to run). Never raises on model output.""" + text = "" if reply is None else str(reply) + text, thought = strip_thoughts(text) + found = _ACTION.findall(text) + bare = False + if len(found) > 1: + return Parsed(False, thought=thought, error=f"{len(found)} action blocks in one reply") + if found: + body = found[0] + else: + if "<|action_start|>" in text: + return Parsed(False, thought=thought, error="unterminated action (no <|action_end|>)") + body = text.strip() + for trailer in _TRAILERS: + body = body.replace(trailer, "") + body = body.strip() + if not accept_bare or not body: + return Parsed(False, thought=thought, error="no <|action_start|>...<|action_end|> block") + bare = True + parts = body.split(";") + if len(parts) != 1 + km.SUBSTEPS: + return Parsed(False, thought=thought, bare=bare, + error=f"expected mouse + 6 chunks separated by ';', got {len(parts)} fields") + mouse_tokens = parts[0].split() + if len(mouse_tokens) != 3 or not all(_INT.fullmatch(v) for v in mouse_tokens): + return Parsed(False, thought=thought, bare=bare, error=f"mouse field must be 3 integers, got {parts[0].strip()!r}") + x, y, z = (int(v) for v in mouse_tokens) + if abs(x) > 1000 or abs(y) > 1000 or abs(z) > 5: + return Parsed(False, thought=thought, bare=bare, error=f"mouse out of range: {x} {y} {z}") + groups, unbound, fixes = [], [], 0 + for index, part in enumerate(parts[1:], 1): + raw = part.replace(",", " ").split() if lenient else part.split() + if len(raw) > km.MAX_KEYS: + return Parsed(False, thought=thought, bare=bare, error=f"chunk {index} has {len(raw)} keys (max 4)") + group = [] + for token in raw: + name, fixed = _canonical_token(token, lenient) + if name is None: + return Parsed(False, thought=thought, bare=bare, error=f"chunk {index}: unknown key name {token!r}") + if name in group: + return Parsed(False, thought=thought, bare=bare, error=f"chunk {index}: key {name} repeated") + fixes += fixed + group.append(name) + if name not in TO_BOSSBENCH: + unbound.append(name) + groups.append(group) + sx, sy = mouse_scale(mouse_kind) + subs = [[TO_BOSSBENCH[k] for k in g if k in TO_BOSSBENCH] for g in groups] + packet = km.format_packet(subs, (_round_scaled(x, sx), _round_scaled(y, sy), z)) + if km.parse_packet(packet) is None: # cannot happen for valid input; keep the contract explicit + return Parsed(False, thought=thought, bare=bare, error="internal: converted packet rejected") + return Parsed(True, packet=packet, mouse=(x, y, z), groups=groups, thought=thought, unbound=unbound, + bare=bare, lenient_fixes=fixes) + + +def from_packet(packet, *, mouse_kind="none"): + """BossBench packet text -> canonical Lumine text that converts back to exactly the same packet. + + Raises ValueError if the packet is invalid or its mouse cannot be expressed in Lumine units for this game.""" + p = km.parse_packet(packet if packet is not None else km.NOOP) + if p is None: + raise ValueError(f"not a valid BossBench packet: {packet!r}") + sx, sy = mouse_scale(mouse_kind) + dx, dy, dz = p["mouse"] + x, y = _round_scaled(dx, 1 / sx), _round_scaled(dy, 1 / sy) + if abs(x) > 1000 or abs(y) > 1000 or _round_scaled(x, sx) != dx or _round_scaled(y, sy) != dy: + raise ValueError(f"mouse {dx} {dy} is not expressible in Lumine units for a {mouse_kind!r} game") + groups = [sorted(FROM_BOSSBENCH[k] for k in sub) for sub in p["subs"]] + return format_action((x, y, dz), groups) + + +def same_packet(a, b): + """True when two BossBench packet texts parse to the same action.""" + pa, pb = km.parse_packet(a), km.parse_packet(b) + return pa is not None and pb is not None and pa["mouse"] == pb["mouse"] and pa["subs"] == pb["subs"] diff --git a/environments/games/prototype/bossbench_llm/mock_server.py b/environments/games/prototype/bossbench_llm/mock_server.py new file mode 100644 index 0000000000000000000000000000000000000000..93e16ec6d8cf4c7a66bffa41a2b639bad2d24e06 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/mock_server.py @@ -0,0 +1,89 @@ +"""A stand-in OpenAI-compatible endpoint for checking the harness without a model. + + python -m bossbench_llm.mock_server --port 8009 + python -m bossbench_llm.run --case terraria/king_slime --tier easy --policy chat \ + --base-url http://127.0.0.1:8009/v1 --model mock --max-steps 20 + +It checks each request the way a real server would see it (system prompt first, one image per user turn, +alternating turns) and answers with a fixed-pattern action in the format the system prompt asks for. It is not a +policy: it does not look at the image. +""" +from __future__ import annotations + +import argparse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import sys + +LUMINE = ["<|action_start|>0 0 0 ; D ; D ; D ; D ; D ; D<|action_end|>", + "<|action_start|>40 0 0 ; A Space ; A Space ; A ; A ; LB ; LB<|action_end|>", + "<|action_start|>-40 0 0 ; J ; J ; ; ; Space ; Space<|action_end|>"] + + +def check(messages): + if not messages or messages[0].get("role") != "system": + return "first message must be the system prompt" + roles = [m.get("role") for m in messages[1:]] + if not roles or roles[-1] != "user": + return "last message must be a user turn" + for a, b in zip(roles, roles[1:]): + if a == b: + return "user/assistant turns must alternate" + for m in messages[1:]: + if m["role"] == "user": + images = [p for p in m.get("content", []) if isinstance(p, dict) and p.get("type") == "image_url"] + if len(images) != 1 or not images[0]["image_url"]["url"].startswith("data:image/jpeg;base64,"): + return "each user turn must carry exactly one JPEG data URL" + return None + + +class Handler(BaseHTTPRequestHandler): + counter = 0 + + def log_message(self, *args): + pass + + def do_POST(self): + if not self.path.endswith("/chat/completions"): + self.send_error(404) + return + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) + problem = check(body.get("messages", [])) + if problem: + out = json.dumps({"error": {"message": problem}}).encode() + self.send_response(400) + else: + Handler.counter += 1 + system = body["messages"][0]["content"] + if "<|action_start|>" in system: + text = LUMINE[Handler.counter % len(LUMINE)] + else: + text = "{}" + out = json.dumps({"id": f"mock-{Handler.counter}", "object": "chat.completion", "model": body.get("model"), + "choices": [{"index": 0, "finish_reason": "stop", + "message": {"role": "assistant", "content": text}}], + "usage": {"prompt_tokens": 0, "completion_tokens": 0, + "images": sum(1 for m in body["messages"] if m["role"] == "user")}}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(out))) + self.end_headers() + self.wfile.write(out) + + +def main(argv=None): + p = argparse.ArgumentParser(prog="python -m bossbench_llm.mock_server") + p.add_argument("--host", default="127.0.0.1") + p.add_argument("--port", type=int, default=8009) + args = p.parse_args(argv) + server = ThreadingHTTPServer((args.host, args.port), Handler) + print(f"mock endpoint on http://{args.host}:{args.port}/v1", flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/environments/games/prototype/bossbench_llm/policies.py b/environments/games/prototype/bossbench_llm/policies.py new file mode 100644 index 0000000000000000000000000000000000000000..4caeda760dc77e38f55da59f4330b50991d0020a --- /dev/null +++ b/environments/games/prototype/bossbench_llm/policies.py @@ -0,0 +1,111 @@ +"""Policies the harness can drive. Every policy sees only the chat messages (system prompt, frames, its own +replies) plus a small public `turn` record (index, case, format, the game's key names / action vocabulary). + +* chat an OpenAI-compatible endpoint (the real thing) +* python your own code: --policy python --policy-factory my_module:make -> object with act(messages, turn) +* replay a recorded scripted win, converted to the chosen format (pipeline self-test; lumine is lossless) +* noop / random baselines and smoke tests +""" +from __future__ import annotations + +import importlib +import json +import random + +from bossbench import keymouse as km + +from . import lumine + + +class Turn(dict): + """Public per-turn context: index, case_id, game, format, lumine_keys, vocab (semantic only).""" + __getattr__ = dict.get + + +class ChatPolicy: + name = "chat" + + def __init__(self, client): + self.client = client + + def act(self, messages, turn): + return self.client.complete(messages) + + def describe(self): + return {"policy": self.name, **self.client.describe()} + + +class PythonPolicy: + name = "python" + + def __init__(self, factory, config=None): + module, _, attr = factory.partition(":") + self.factory = factory + self.impl = getattr(importlib.import_module(module), attr or "make")(dict(config or {})) + + def act(self, messages, turn): + out = self.impl.act(messages, turn) + return out if isinstance(out, tuple) else (out, {}) + + def describe(self): + info = getattr(self.impl, "describe", None) + return {"policy": self.name, "factory": self.factory, **(info() if callable(info) else {})} + + +class ReplayPolicy: + """Replays a bossbench/policy-replay@1 recording. Lumine text converts back to exactly the recorded packets, so + a lumine replay must reproduce the recording's final hash; semantic replays use the nearest compact action + (compact.CompactSpec.project) and are a smoke test only.""" + name = "replay" + + def __init__(self, path, fmt, mouse_kind="none", spec=None): + with open(path, encoding="utf-8") as f: + self.data = json.load(f) + self.path, self.fmt, self.mouse_kind, self.spec = str(path), fmt, mouse_kind, spec + self.index = 0 + + def act(self, messages, turn): + packets = self.data["packets"] + packet = packets[self.index] if self.index < len(packets) else km.NOOP + self.index += 1 + if self.fmt == "lumine": + return lumine.from_packet(packet, mouse_kind=self.mouse_kind), {"seconds": 0.0} + idx = self.spec.project(packet) + return json.dumps(self.spec.named(idx)), {"seconds": 0.0} + + def describe(self): + return {"policy": self.name, "replay": self.path, "case_id": self.data.get("case_id"), + "rules": self.data.get("rules"), "outcome": self.data.get("outcome")} + + +class NoopPolicy: + name = "noop" + + def __init__(self, fmt): + self.fmt = fmt + + def act(self, messages, turn): + return (lumine.format_action((0, 0, 0), [[]] * km.SUBSTEPS) if self.fmt == "lumine" else "{}"), {"seconds": 0.0} + + def describe(self): + return {"policy": self.name} + + +class RandomPolicy: + """Uniform over this game's own keys (lumine: each chunk 0-2 keys, mouse +-100) or over its action options.""" + name = "random" + + def __init__(self, fmt, seed=0): + self.fmt, self.rng, self.seed = fmt, random.Random(seed), seed + + def act(self, messages, turn): + if self.fmt == "lumine": + keys = list(turn.lumine_keys or []) + groups = [sorted(self.rng.sample(keys, min(len(keys), self.rng.randint(0, 2)))) for _ in range(km.SUBSTEPS)] + mouse = (self.rng.randint(-100, 100), self.rng.randint(-100, 100), 0) if turn.mouse_kind != "none" else (0, 0, 0) + return lumine.format_action(mouse, groups), {"seconds": 0.0} + vocab = turn.vocab + return json.dumps({h["name"]: self.rng.choice(h["options"])["label"] for h in vocab.heads}), {"seconds": 0.0} + + def describe(self): + return {"policy": self.name, "seed": self.seed} diff --git a/environments/games/prototype/bossbench_llm/prompting.py b/environments/games/prototype/bossbench_llm/prompting.py new file mode 100644 index 0000000000000000000000000000000000000000..81c5529aa968f6176d60c5aec9884865d68287f9 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompting.py @@ -0,0 +1,236 @@ +"""System prompts for the LLM harness: Lumine format and semantic format, English only. + +The Lumine-format prompt copies the Lumine / CPT system prompt (6 x 33 ms chunks, space-separated key names, +LB/RB mouse buttons) and appends what this game needs: the keys that do something here, what the mouse does, and +the boss's moves. Health bars and other status are not described: the model reads them from the screen. + +Per-game text lives in prompts/games/.json (schema bossbench-llm/game-prompt@1); the semantic action groups +are read live from the game's own declaration (semantic.Vocabulary). A prompt is a fixed concatenation of parts +(intro, format, game, boss, footer); the HTML page joins the same parts with the same separator. +""" +from __future__ import annotations +import json +import os +import re +from functools import lru_cache +from pathlib import Path +from . import lumine +from .semantic import TERRARIA, Vocabulary +DATA = Path(os.environ.get('BOSSBENCH_LLM_PROMPTS') or Path(__file__).resolve().parent / 'prompts' / 'games') +SCHEMA = 'bossbench-llm/game-prompt@1' +SEP = '\n\n' +LANGS = ('en',) +FORMATS = ('lumine', 'semantic') + +@lru_cache(maxsize=None) +def load_game(game): + path = DATA / f'{game}.json' + data = json.loads(path.read_text(encoding='utf-8')) + if data.get('schema') != SCHEMA or data.get('game') != game: + raise ValueError(f'{path}: not a {SCHEMA} file for {game}') + return data + +def available_games(): + return sorted((p.stem for p in DATA.glob('*.json'))) + +def scene(game_data, case_id): + for s in game_data['scenes']: + if s['case_id'] == case_id: + return s + raise KeyError(f"{case_id} not in {game_data['game']} prompt data") + +def mouse_kind(game): + return load_game(game).get('mouse', {}).get('kind', 'none') + +def _t(pair, lang): + if pair is None: + return '' + if isinstance(pair, str): + return pair + return (pair.get(lang) or pair.get('en') or pair.get('zh') or '').strip() + +def _sentence(text, lang): + # Prompts are English only; lang is kept so existing callers do not change. + text = text.strip() + if text and text[-1] == ')' and text[-2:-1] not in '.!?': + text += '.' + elif text and text[-1] not in '.!?;:)"': + text += '.' + return text +_INTRO = {('lumine', 'zh'): 'You are an experienced PC game player, proficient in keyboard and mouse operations. You are playing "{title}". Based on the current game screen and the corresponding historical trajectory, plan the next 200ms of actions, consisting of 6 steps. Each step is spaced 33ms apart. Every step lasts 33ms from its start time until the next step begins.', ('lumine', 'en'): 'You are an experienced PC game player, proficient in keyboard and mouse operations. You are playing "{title}". Based on the current game screen and the corresponding historical trajectory, plan the next 200ms of actions, consisting of 6 steps. Each step is spaced 33ms apart. Every step lasts 33ms from its start time until the next step begins.', ('semantic', 'zh'): 'You are an experienced PC game player. You are playing "{title}". Based on the current game screen and the corresponding historical trajectory, choose the action for the next 200ms.', ('semantic', 'en'): 'You are an experienced PC game player. You are playing "{title}". Based on the current game screen and the corresponding historical trajectory, choose the action for the next 200ms.'} +_LUMINE_FORMAT = {'zh': '**Output Format**\n<|action_start|>X Y Z ; k1 k2 k3 ; k4 k5 ; k6 ; k7 ; k8 ; k9 k10<|action_end|>\n**Explanation**\n1. **Mouse Movement**: First, specify the relative displacement X, Y (X>0 means move right, Y>0 means move down) and scroll amount Z (Z>0 means scroll up). X and Y are integers in [-1000, 1000]; Z is an integer in [-5, 5].\n2. **Key Sequence**: Then list 6 groups of keys; within each group, keys are separated by spaces, and groups are separated by semicolons.\n- Each group can contain up to 4 keys.\n- If a group has no keys, leave it empty but keep the `;`.\n- A key listed in consecutive groups stays held down and is not pressed again; a key that is not listed is released.\n3. Only output a plain string that conforms to the above format — no line breaks and no quotation marks.\n**Key Naming Rules**\n- Letter keys: the capital letter, e.g., `W`, `A`.\n- Other keys (Space, Shift, etc.): the real key name with an initial capital letter, e.g., `Space`, `Shift`.\n- Mouse buttons: `LB` (left button), `RB` (right button).', 'en': '**Output Format**\n<|action_start|>X Y Z ; k1 k2 k3 ; k4 k5 ; k6 ; k7 ; k8 ; k9 k10<|action_end|>\n**Explanation**\n1. **Mouse Movement**: First, specify the relative displacement X, Y (X>0 means move right, Y>0 means move down) and scroll amount Z (Z>0 means scroll up). X and Y are integers in [-1000, 1000]; Z is an integer in [-5, 5].\n2. **Key Sequence**: Then list 6 groups of keys; within each group, keys are separated by spaces, and groups are separated by semicolons.\n- Each group can contain up to 4 keys.\n- If a group has no keys, leave it empty but keep the `;`.\n- A key listed in consecutive groups stays held down and is not pressed again; a key that is not listed is released.\n3. Only output a plain string that conforms to the above format — no line breaks and no quotation marks.\n**Key Naming Rules**\n- Letter keys: the capital letter, e.g., `W`, `A`.\n- Other keys (Space, Shift, etc.): the real key name with an initial capital letter, e.g., `Space`, `Shift`.\n- Mouse buttons: `LB` (left button), `RB` (right button).'} +_THINKING = {('lumine', 'zh'): '**Reasoning (optional)**: when the situation changes (a new attack starts, your plan fails), you may first write a short thought as <|thought_start|>your reasoning<|thought_end|> and then the action; otherwise output only the action.', ('lumine', 'en'): '**Reasoning (optional)**: when the situation changes (a new attack starts, your plan fails), you may first write a short thought as <|thought_start|>your reasoning<|thought_end|> and then the action; otherwise output only the action.', ('semantic', 'zh'): '**Reasoning (optional)**: when the situation changes, you may write a short thought as <|thought_start|>your reasoning<|thought_end|> before the JSON; otherwise output only the JSON.', ('semantic', 'en'): '**Reasoning (optional)**: when the situation changes, you may write a short thought as <|thought_start|>your reasoning<|thought_end|> before the JSON; otherwise output only the JSON.'} + +def _semantic_example(vocab): + if vocab.game == TERRARIA: + return '{"move": "left", "vert": "jump", "attack": "shoot 135"}' + pick = {} + for h in vocab.heads[:2]: + pick[h['name']] = h['options'][min(1, len(h['options']) - 1)]['label'] + return json.dumps(pick, ensure_ascii=False) + +def _option_text(game_data, vocab, head, option, lang): + if lang == 'zh': + return option.get('zh') or option['label'] + glossary = game_data.get('compact_glossary', {}).get(head['name'], {}).get('options', {}) + return glossary.get(option['label']) or option.get('en') or option['label'].replace('_', ' ') + +def _head_text(game_data, head, lang): + if lang == 'zh': + return head.get('zh') or head['name'] + return game_data.get('compact_glossary', {}).get(head['name'], {}).get('en') or head.get('en') or head['name'] + +def _semantic_format(game_data, vocab, lang): + zh = lang == 'zh' + lines = ['**Output Format**', 'Output one JSON object on a single line that picks one option for each action group, for example:', _semantic_example(vocab)] + lines += ['- All groups act at the same time, for the next 200ms.', '- A group you leave out takes its first option (none = do nothing).', '- Use the option names exactly as listed; do not output option indices or any other text.'] + lines.append('**Action groups**') + for head in vocab.heads: + if vocab.game == TERRARIA and head['name'] == 'attack': + opts = [o for o in head['options'] if not o['label'].startswith('shoot ')] + shoot = '`shoot ` (shoot an arrow toward that angle; integer degrees 0-359, 0° = right, 90° = up, rounded to multiples of 22.5°)' + items = [f"`{o['label']}` ({_option_text(game_data, vocab, head, o, lang)})" for o in opts[:1]] + items.append(shoot) + items += [f"`{o['label']}` ({_option_text(game_data, vocab, head, o, lang)})" for o in opts[1:]] + else: + items = [f"`{o['label']}` ({_option_text(game_data, vocab, head, o, lang)})" for o in head['options']] + sep = '; ' + lines.append(f"- `{head['name']}` ({_head_text(game_data, head, lang)}): " + sep.join(items)) + return '\n'.join(lines) +_DEG = re.compile('(\\d+(?:\\.\\d+)?)\\s*°') + +def _camera_sign(vocab): + """+1 when X > 0 turns the view right (normal), -1 when this game turns it left; None if unknown.""" + if vocab is None: + return None + for h in vocab.heads: + for o in h['options']: + dx = o.get('dx', 0) + if dx: + label = (o['label'] + ' ' + (o.get('zh') or '')).lower() + left = 'left' in label or 'left' in label + right = 'right' in label or 'right' in label + if left != right: + return 1 if (dx < 0) == left else -1 + return None + +def _deg_per_count(vocab): + """Degrees per mouse count from the game's own semantic options ("turn left 10 degrees" with dx -152), or None.""" + if vocab is None: + return None + best = None + for h in vocab.heads: + for o in h['options']: + dx, text = (o.get('dx', 0), o.get('zh') or '') + m = _DEG.search(text) + if dx and m and ('lock' not in text) and ('look down' not in text) and ('look up' not in text): + rate = float(m.group(1)) / abs(dx) + if best is None or abs(dx) > best[0]: + best = (abs(dx), rate) + return best[1] if best else None + +def _mouse_line(game_data, vocab, lang): + m = game_data.get('mouse', {}) + kind, zh = (m.get('kind', 'none'), lang == 'zh') + extra = _t(m, lang) + if kind == 'none': + return '- Mouse: not used in this game; write X Y Z as 0 0 0.' + if kind == 'pointer': + base = '- Mouse: X/Y move the crosshair; X = 1000 moves it one full screen width to the right, Y = 1000 one full screen height down.' + return base + (' ' + _sentence(extra, lang) if extra else '') + deg = _deg_per_count(vocab) or m.get('deg_per_count_x') + sign = _camera_sign(vocab) + if deg: + x = round(10 / float(deg)) + right = (sign or 1) > 0 + base = f"- Mouse: X/Y turn the view; X = {x} turns about 10° to the {('right' if right else 'left')}" + (' (note: in this game X > 0 turns LEFT)' if not right else '') + '.' + else: + base = '- Mouse: X/Y turn the view.' + return base + (' ' + _sentence(extra, lang) if extra else '') + +def game_block(game, fmt, lang): + data, zh = (load_game(game), lang == 'zh') + vocab = None + if fmt == 'semantic' or data.get('mouse', {}).get('kind') == 'camera': + try: + vocab = Vocabulary.for_game(game) + except (FileNotFoundError, ValueError): + if fmt == 'semantic': + raise + lines = ['**Game**'] + for key in ('view', 'goal'): + if data.get(key): + lines.append(_sentence(_t(data[key], lang), lang)) + if fmt == 'lumine': + lines.append('**Controls** (only these keys do anything in this game)') + for k in data['keys']: + name = lumine.FROM_BOSSBENCH.get(k['key'], k['key']) + lines.append(f'- `{name}`: {_t(k, lang)}') + lines.append(_mouse_line(data, vocab, lang)) + notes = [n for n in data.get('notes', []) if _t(n, lang)] + if notes: + lines.append('**Mechanics**') + lines += [f'- {_sentence(_t(n, lang), lang)}' for n in notes] + return '\n'.join(lines) + +def boss_block(game, case_id, lang, counters=False): + s, zh = (scene(load_game(game), case_id), lang == 'zh') + lines = [f"**Boss: {_t(s['boss'], lang)}**"] + if s.get('summary'): + lines.append(_sentence(_t(s['summary'], lang), lang)) + lines.append('Moves:') + for i, mv in enumerate(s['moves'], 1): + body = ' '.join((x for x in (_sentence(_t(mv.get('tell'), lang), lang), _sentence(_t(mv.get('effect'), lang), lang)) if x)) + tag = _t(mv.get('only'), lang) + name = f"{_t(mv['name'], lang)} [{tag}]" if tag else _t(mv['name'], lang) + line = f'{i}. {name}: {body}' + if counters and _t(mv.get('counter'), lang): + line += f" How to deal with it: {_sentence(_t(mv['counter'], lang), lang)}" + lines.append(line) + phases = [p for p in s.get('phases', []) if _t(p, lang)] + if phases: + lines.append('Phases:') + lines += [f'- {_sentence(_t(p, lang), lang)}' for p in phases] + return '\n'.join(lines) +FOOTER = {'zh': 'Health bars and other status are shown on the screen; read them yourself.', 'en': 'Health bars and other status are shown on the screen; read them yourself.'} + +def parts(game, case_id, fmt='lumine', lang='en', *, thinking=False, counters=False): + """The prompt as ordered parts; system_prompt() joins them with SEP. The HTML page uses the same parts.""" + if fmt not in FORMATS or lang not in LANGS: + raise ValueError(f'fmt must be one of {FORMATS}, lang one of {LANGS}') + data = load_game(game) + intro = _INTRO[fmt, lang].format(title=_t(data['title'], lang)) + if fmt == 'lumine': + fmt_text = _LUMINE_FORMAT[lang] + else: + fmt_text = _semantic_format(data, Vocabulary.for_game(game), lang) + if thinking: + fmt_text += '\n' + _THINKING[fmt, lang] + return [intro + '\n' + fmt_text, game_block(game, fmt, lang), boss_block(game, case_id, lang, counters), FOOTER[lang]] + +def system_prompt(game, case_id, fmt='lumine', lang='en', *, thinking=False, counters=False): + return SEP.join(parts(game, case_id, fmt, lang, thinking=thinking, counters=counters)) + +def lumine_keys(game): + """Lumine key names this game binds (for the random baseline and the docs).""" + return [lumine.FROM_BOSSBENCH[k['key']] for k in load_game(game)['keys'] if k['key'] in lumine.FROM_BOSSBENCH] + +def main(argv=None): + """python -m bossbench_llm.prompting --case terraria/king_slime --format lumine --lang zh [--thinking] [--counters]""" + import argparse + import sys + from bossbench.scope import POLICY_CASES + p = argparse.ArgumentParser(prog='python -m bossbench_llm.prompting', description='print a system prompt') + p.add_argument('--case', required=True) + p.add_argument('--format', choices=FORMATS, default='lumine') + p.add_argument('--lang', choices=LANGS, default='en') + p.add_argument('--thinking', action='store_true') + p.add_argument('--counters', action='store_true') + args = p.parse_args(argv) + if hasattr(sys.stdout, 'reconfigure'): + sys.stdout.reconfigure(encoding='utf-8') + game = POLICY_CASES[args.case]['game'] + print(system_prompt(game, args.case, args.format, args.lang, thinking=args.thinking, counters=args.counters)) + return 0 +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/environments/games/prototype/bossbench_llm/prompts/games/battlecity_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/battlecity_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..ddfd8e1665b512395c5433ca20c2131c95ce5956 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/battlecity_remake.json @@ -0,0 +1,423 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "battlecity_remake", + "rules": "battlecity-nes-rom-20261102-r6", + "title": { + "en": "Top-Down Tank Battle: Defend the Eagle Base" + }, + "dimension": "2d", + "view": { + "en": "Top-down 2D grid battlefield with brick, steel, water, ice and forest terrain. You drive a player tank, and the eagle base at the bottom must be protected; the side panel shows remaining enemy tanks and your lives" + }, + "goal": { + "en": "Destroy every enemy tank to clear the stage (10 on easy, 20 on medium, 60 on hard). Protect the eagle base at the bottom: any shell, including your own, that hits it is an instant loss; losing all lives also loses (4 on easy, 3 on medium, 2 on hard). Lives do not regenerate except via the extra-life pickup" + }, + "mouse": { + "kind": "none", + "en": "" + }, + "keys": [ + { + "key": "W", + "en": "Drive up" + }, + { + "key": "A", + "en": "Drive left" + }, + { + "key": "S", + "en": "Drive down" + }, + { + "key": "D", + "en": "Drive right" + }, + { + "key": "J", + "en": "Fire" + }, + { + "key": "K", + "en": "Fire (same as J)" + }, + { + "key": "Space", + "en": "Fire (same as J)" + }, + { + "key": "LMB", + "en": "Fire (same as J)" + } + ], + "notes": [ + { + "en": "The tank moves in four directions only; with several direction keys held, only one is used (right > left > down > up); perpendicular turns snap to the 8px grid." + }, + { + "en": "Each shot needs a fresh key press; holding does not auto-fire. Only one of your shells can be on the field at first, two from two stars." + }, + { + "en": "Brick, steel, water, the base and other tanks block movement; water blocks tanks but not shells; forest hides tanks but not shells; on ice you slide in a locked direction after starting." + }, + { + "en": "Each shot removes one layer of brick; only three-star shells break steel; never fire toward your own base." + }, + { + "en": "Flashing red tanks drop pickups when hit: star (upgrade), shield (invulnerable about 10.7 s), fortify (base wall becomes steel), freeze (enemies halt), blast (destroys all enemies on screen), extra life." + }, + { + "en": "Four enemy types: light, swift (fast), long-gun (strong shells) and heavy (four hits, colour changes with armour)." + } + ], + "compact_glossary": { + "move": { + "en": "Tank driving, one 200 ms packet (12 frames) per action", + "options": { + "none": "stand still", + "up": "drive up all 12 frames", + "down": "drive down all 12 frames", + "left": "drive left all 12 frames", + "right": "drive right all 12 frames", + "face_up": "turn to face up only (first sub-step, no travel)", + "up_early": "drive up for sub-steps 1-3 then stop", + "up_late": "drive up for sub-steps 4-6 only", + "face_down": "turn to face down only (first sub-step, no travel)", + "down_early": "drive down for sub-steps 1-3 then stop", + "down_late": "drive down for sub-steps 4-6 only", + "face_left": "turn to face left only (first sub-step, no travel)", + "left_early": "drive left for sub-steps 1-3 then stop", + "left_late": "drive left for sub-steps 4-6 only", + "face_right": "turn to face right only (first sub-step, no travel)", + "right_early": "drive right for sub-steps 1-3 then stop", + "right_late": "drive right for sub-steps 4-6 only", + "up_then_left_1": "drive up for 1 sub-steps, then turn and drive left", + "up_then_left_2": "drive up for 2 sub-steps, then turn and drive left", + "up_then_left_3": "drive up for 3 sub-steps, then turn and drive left", + "up_then_left_4": "drive up for 4 sub-steps, then turn and drive left", + "up_then_left_5": "drive up for 5 sub-steps, then turn and drive left", + "up_then_right_1": "drive up for 1 sub-steps, then turn and drive right", + "up_then_right_2": "drive up for 2 sub-steps, then turn and drive right", + "up_then_right_3": "drive up for 3 sub-steps, then turn and drive right", + "up_then_right_4": "drive up for 4 sub-steps, then turn and drive right", + "up_then_right_5": "drive up for 5 sub-steps, then turn and drive right", + "down_then_left_1": "drive down for 1 sub-steps, then turn and drive left", + "down_then_left_2": "drive down for 2 sub-steps, then turn and drive left", + "down_then_left_3": "drive down for 3 sub-steps, then turn and drive left", + "down_then_left_4": "drive down for 4 sub-steps, then turn and drive left", + "down_then_left_5": "drive down for 5 sub-steps, then turn and drive left", + "down_then_right_1": "drive down for 1 sub-steps, then turn and drive right", + "down_then_right_2": "drive down for 2 sub-steps, then turn and drive right", + "down_then_right_3": "drive down for 3 sub-steps, then turn and drive right", + "down_then_right_4": "drive down for 4 sub-steps, then turn and drive right", + "down_then_right_5": "drive down for 5 sub-steps, then turn and drive right", + "left_then_up_1": "drive left for 1 sub-steps, then turn and drive up", + "left_then_up_2": "drive left for 2 sub-steps, then turn and drive up", + "left_then_up_3": "drive left for 3 sub-steps, then turn and drive up", + "left_then_up_4": "drive left for 4 sub-steps, then turn and drive up", + "left_then_up_5": "drive left for 5 sub-steps, then turn and drive up", + "left_then_down_1": "drive left for 1 sub-steps, then turn and drive down", + "left_then_down_2": "drive left for 2 sub-steps, then turn and drive down", + "left_then_down_3": "drive left for 3 sub-steps, then turn and drive down", + "left_then_down_4": "drive left for 4 sub-steps, then turn and drive down", + "left_then_down_5": "drive left for 5 sub-steps, then turn and drive down", + "right_then_up_1": "drive right for 1 sub-steps, then turn and drive up", + "right_then_up_2": "drive right for 2 sub-steps, then turn and drive up", + "right_then_up_3": "drive right for 3 sub-steps, then turn and drive up", + "right_then_up_4": "drive right for 4 sub-steps, then turn and drive up", + "right_then_up_5": "drive right for 5 sub-steps, then turn and drive up", + "right_then_down_1": "drive right for 1 sub-steps, then turn and drive down", + "right_then_down_2": "drive right for 2 sub-steps, then turn and drive down", + "right_then_down_3": "drive right for 3 sub-steps, then turn and drive down", + "right_then_down_4": "drive right for 4 sub-steps, then turn and drive down", + "right_then_down_5": "drive right for 5 sub-steps, then turn and drive down" + } + }, + "fire": { + "en": "Fire button taps within the packet", + "options": { + "none": "no firing", + "fire": "press fire on sub-steps 1/3/5", + "fire_odd": "press fire on sub-steps 2/4/6 (pairs with turning)" + } + } + }, + "scenes": [ + { + "case_id": "battlecity/brick_front", + "boss": { + "en": "Brick Lane Front" + }, + "summary": { + "en": "A brick-heavy open field with the base at the bottom; enemy tanks spawn from three points along the top." + }, + "moves": [ + { + "id": "wave", + "name": { + "en": "Enemy tank waves" + }, + "tell": { + "en": "The left, middle and right spawn points at the top flash in turn; up to four tanks are on the field." + }, + "effect": { + "en": "Enemy tanks shoot at you or the eagle base; a hit on your tank costs a life and a hit on the base is an instant loss." + }, + "counter": { + "en": "Each shot chips only one layer of brick; line up on the spawn points at the lane mouths in advance, and never fire toward the base." + } + }, + { + "id": "powerup", + "name": { + "en": "Flashing carrier and pickups" + }, + "tell": { + "en": "The 4th, 11th and 18th tanks flash red." + }, + "effect": { + "en": "Does no damage; shooting a flashing tank drops a pickup that you collect by driving onto it." + }, + "counter": { + "en": "Fortify turns the base brick wall to steel for about 21 seconds; stars give speed, twin shots, then steel-breaking." + } + } + ], + "phases": [ + { + "en": "Tanks get more aggressive over time: on medium they hunt you after about 26 s and rush the base after about 50 s; on hard after about 7 s and 14 s." + } + ] + }, + { + "case_id": "battlecity/jungle_ambush", + "boss": { + "en": "Jungle Ambush" + }, + "summary": { + "en": "Dense forest hides tanks and shells; swift tanks make up over half the wave; a steel block above the base stops shells." + }, + "moves": [ + { + "id": "wave", + "name": { + "en": "Enemy tank waves" + }, + "tell": { + "en": "Tanks are hidden in the forest; swift tanks move fast and dash out of the trees." + }, + "effect": { + "en": "Enemy tanks shoot at you or the eagle base; a hit on your tank costs a life and a hit on the base is an instant loss." + }, + "counter": { + "en": "Hold the clearing exits and shoot swift tanks as they leave the trees; enemies mostly circle down the side forests." + } + }, + { + "id": "powerup", + "name": { + "en": "Flashing carrier and pickups" + }, + "tell": { + "en": "The 4th, 11th and 18th tanks flash red (swift, light, swift)." + }, + "effect": { + "en": "Does no damage; shooting a flashing tank drops a pickup that you collect by driving onto it." + }, + "counter": { + "en": "Freeze lasts about 10.7 seconds; use it to clear tanks hiding in the forest." + } + } + ], + "phases": [ + { + "en": "On easy and medium enemies hunt you after about 13 s and rush the base after about 26 s; on hard after about 7 s and 14 s." + } + ] + }, + { + "case_id": "battlecity/river_delta", + "boss": { + "en": "River Delta" + }, + "summary": { + "en": "Two north-south rivers split the field into three lanes, crossable only at three fords; shells fly over water." + }, + "moves": [ + { + "id": "wave", + "name": { + "en": "Enemy tank waves" + }, + "tell": { + "en": "Long-gun tanks fire across the rivers from the side lanes; enemies cross at the fords." + }, + "effect": { + "en": "Enemy tanks shoot at you or the eagle base; a hit on your tank costs a life and a hit on the base is an instant loss." + }, + "counter": { + "en": "Hold the middle brick island and shoot across the water; the fords are chokepoints." + } + }, + { + "id": "powerup", + "name": { + "en": "Flashing carrier and pickups" + }, + "tell": { + "en": "The 4th, 11th and 18th tanks flash red (light, long-gun, swift)." + }, + "effect": { + "en": "Does no damage; shooting a flashing tank drops a pickup that you collect by driving onto it." + }, + "counter": { + "en": "Fortify turns the base wall to steel for about 21 seconds; stars give speed, twin shots, then steel-breaking." + } + } + ], + "phases": [ + { + "en": "On easy and medium enemies hunt you after about 17 s and rush the base after about 34 s; on hard after about 7 s and 14 s." + } + ] + }, + { + "case_id": "battlecity/river_ice", + "boss": { + "en": "Ice River Woods" + }, + "summary": { + "en": "Ice, water and forest mixed; forest hides tanks but shells still fly." + }, + "moves": [ + { + "id": "wave", + "name": { + "en": "Enemy tank waves" + }, + "tell": { + "en": "On ice a tank locks its direction and slides after starting; tanks in woods are hidden." + }, + "effect": { + "en": "Enemy tanks shoot at you or the eagle base; a hit on your tank costs a life and a hit on the base is an instant loss." + }, + "counter": { + "en": "Release keys early to avoid sliding too far; guard the ice lane above the base." + } + }, + { + "id": "powerup", + "name": { + "en": "Flashing carrier and pickups" + }, + "tell": { + "en": "A flashing carrier drops a pickup at one of 16 fixed points when hit." + }, + "effect": { + "en": "Does no damage; shooting a flashing tank drops a pickup that you collect by driving onto it." + }, + "counter": { + "en": "Freeze and shield each last about 10.7 seconds and help you push through the woods." + } + } + ], + "phases": [ + { + "en": "On easy and medium enemies hunt you after about 11 s and rush the base after about 21 s; on hard after about 7 s and 14 s." + } + ] + }, + { + "case_id": "battlecity/steel_fort", + "boss": { + "en": "Steel Fortress" + }, + "summary": { + "en": "A fortress of steel walls and water; swift tanks open, followed by heavy tanks." + }, + "moves": [ + { + "id": "wave", + "name": { + "en": "Enemy tank waves" + }, + "tell": { + "en": "Swift tanks open, then heavy tanks that take four hits and change colour as armour drops." + }, + "effect": { + "en": "Enemy tanks shoot at you or the eagle base; a hit on your tank costs a life and a hit on the base is an instant loss." + }, + "counter": { + "en": "Water blocks tanks but not shells, so shoot across it; only three-star shells break steel." + } + }, + { + "id": "powerup", + "name": { + "en": "Flashing carrier and pickups" + }, + "tell": { + "en": "A flashing carrier drops a pickup when hit; a red heavy tank drops only on its first hit." + }, + "effect": { + "en": "Does no damage; shooting a flashing tank drops a pickup that you collect by driving onto it." + }, + "counter": { + "en": "At three stars you can shoot through steel to open shortcuts." + } + } + ], + "phases": [ + { + "en": "On easy and medium enemies hunt you after about 12 s and rush the base after about 23 s; on hard after about 7 s and 14 s." + } + ] + }, + { + "case_id": "battlecity/steel_maze", + "boss": { + "en": "Steel Maze" + }, + "summary": { + "en": "A steel maze with only a few brick seams; the base has a steel roof, so enemies must reach the bottom two rows and hit the brick wall from the sides." + }, + "moves": [ + { + "id": "wave", + "name": { + "en": "Enemy tank waves" + }, + "tell": { + "en": "Enemies circle to the bottom two rows and hit the base brick wall from left and right." + }, + "effect": { + "en": "Enemy tanks shoot at you or the eagle base; a hit on your tank costs a life and a hit on the base is an instant loss." + }, + "counter": { + "en": "Guard the two bottom-row corridors beside the base; three-star shells break steel for shortcuts." + } + }, + { + "id": "powerup", + "name": { + "en": "Flashing carrier and pickups" + }, + "tell": { + "en": "The 4th, 11th and 18th tanks flash red (long-gun, heavy, light); a red heavy tank drops only on its first hit." + }, + "effect": { + "en": "Does no damage; shooting a flashing tank drops a pickup that you collect by driving onto it." + }, + "counter": { + "en": "Shoot red tanks first for stars; at three stars the maze becomes straight roads." + } + } + ], + "phases": [ + { + "en": "On easy and medium enemies hunt you after about 10 s and rush the base after about 19 s; on hard after about 7 s and 14 s." + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/cuphead_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/cuphead_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..8bd489a792923a81944ee50c8eb297717ecc16af --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/cuphead_remake.json @@ -0,0 +1,668 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "cuphead_remake", + "rules": "cuphead-tiers-v5", + "title": { + "en": "Side-scrolling shooter: boss fights (on foot and by plane)" + }, + "dimension": "2d", + "view": { + "en": "Side-view 2D. You control a reel gunner, on foot or in a small plane for the flying scenes; your health and cards are shown at the bottom of the screen, and the boss's state is shown on screen; read the health bar yourself." + }, + "goal": { + "en": "Empty the boss's health bar in its last phase to win (the screen shows 'A KNOCKOUT!'). You have 3 health points and lose when they run out; a timeout is not a win. Health does not regenerate." + }, + "mouse": { + "kind": "none", + "en": "The mouse does not aim in this game; left and right click only duplicate fire and EX." + }, + "keys": [ + { + "key": "W", + "en": "ground: aim up; plane: fly up" + }, + { + "key": "A", + "en": "left (run or fly)" + }, + { + "key": "S", + "en": "ground: crouch / aim down (crouched shots go straight ahead); plane: fly down" + }, + { + "key": "D", + "en": "right (run or fly)" + }, + { + "key": "Space", + "en": "ground: jump, press again in the air to parry pink objects (bounce and gain 1 card); plane: parry pink objects any time" + }, + { + "key": "Shift", + "en": "ground: dash (no invulnerability); plane: hold to shrink, smaller and faster but only short weak shots, no EX or super" + }, + { + "key": "J", + "en": "hold to fire rapidly (plane default: auto gun)" + }, + { + "key": "K", + "en": "EX move for 1 card; with 5 cards the super: a sweep ray on the ground, blast form in the plane" + }, + { + "key": "L", + "en": "ground: hold to stand still and aim in 8 directions (cannot run)" + }, + { + "key": "Q", + "en": "plane: swap auto gun and drop bombs (higher damage, slower, arcing fall)" + }, + { + "key": "E", + "en": "release the super at 5 cards (same as K)" + }, + { + "key": "LMB", + "en": "fire (same as J)" + }, + { + "key": "RMB", + "en": "EX (same as K)" + } + ], + "notes": [ + { + "en": "Four scenes are ground fights (seed bloom, bouncing blob, boxing frogs, garden trio) and two are plane fights (zodiac shifter, chick). Key meanings differ by scene; you play the reel gunner, on foot or in a plane." + }, + { + "en": "Ground: W/S combined with A/D aims in 8 directions; crouching with S shoots straight ahead; holding L locks you in place, standing, unable to run." + }, + { + "en": "Plane: W/A/S/D fly in 8 directions and L does nothing; Q swaps auto gun and drop bombs; holding Shift shrinks you, with no EX or super." + }, + { + "en": "Pink objects can be parried: on the ground press jump (Space) again in the air, in the plane press Space any time; each parry gives 1 card, each card powers one EX, and 5 cards give the super." + }, + { + "en": "Super: on the ground a horizontal sweep ray; in the plane a blast form that explodes on contact or timeout, followed by about 3 seconds of invulnerability." + }, + { + "en": "Dash gives no invulnerability, so do not dash through attacks. You are briefly invulnerable after being hit." + }, + { + "en": "In the action options, a sub-step is one of six slices of a 200 ms packet; jump, parry and dash only count on a new press, which is why options differ in press timing." + } + ], + "compact_glossary": { + "move": { + "en": "Movement and aiming; every option except none also holds shoot. On the ground W/S aim up/down and S crouches; in the plane W/S fly.", + "options": { + "none": "no movement, no shooting", + "fire": "stand and shoot", + "right": "move/aim right while shooting", + "right_short": "move/aim right for the first 2 sub-steps only, shooting", + "up_right": "move/aim up-right while shooting", + "up_right_short": "move/aim up-right for the first 2 sub-steps only, shooting", + "up": "move/aim up while shooting", + "up_short": "move/aim up for the first 2 sub-steps only, shooting", + "up_left": "move/aim up-left while shooting", + "up_left_short": "move/aim up-left for the first 2 sub-steps only, shooting", + "left": "move/aim left while shooting", + "left_short": "move/aim left for the first 2 sub-steps only, shooting", + "down_left": "move/aim down-left while shooting", + "down_left_short": "move/aim down-left for the first 2 sub-steps only, shooting", + "down": "move/aim down while shooting", + "down_short": "move/aim down for the first 2 sub-steps only, shooting", + "down_right": "move/aim down-right while shooting", + "down_right_short": "move/aim down-right for the first 2 sub-steps only, shooting", + "left_turn_1": "run left 1 sub-step(s) then turn to face right, shooting", + "right_turn_1": "run right 1 sub-step(s) then turn to face left, shooting", + "left_turn_2": "run left 2 sub-step(s) then turn to face right, shooting", + "right_turn_2": "run right 2 sub-step(s) then turn to face left, shooting", + "left_turn_3": "run left 3 sub-step(s) then turn to face right, shooting", + "right_turn_3": "run right 3 sub-step(s) then turn to face left, shooting", + "left_turn_4": "run left 4 sub-step(s) then turn to face right, shooting", + "right_turn_4": "run right 4 sub-step(s) then turn to face left, shooting", + "left_turn_5": "run left 5 sub-step(s) then turn to face right, shooting", + "right_turn_5": "run right 5 sub-step(s) then turn to face left, shooting" + } + }, + "act": { + "en": "Jump / parry / EX / dash / aim-lock / weapon swap, one key action per sub-step.", + "options": { + "none": "nothing", + "jump_tap": "jump (plane: parry), press in sub-step 1 only", + "jump": "jump (plane: parry), held 4 sub-steps", + "jump_hold_parry": "jump held 2 sub-steps, then hold for an air parry from sub-step 4", + "jump_parry": "jump, then air parry at sub-step 4", + "press_2": "press jump at sub-step 2", + "press_3": "press jump at sub-step 3 (air parry timing)", + "press_4": "press jump at sub-step 4 (air parry timing)", + "press_5": "press jump at sub-step 5 (air parry timing)", + "lock_jump_parry": "hold aim-lock, jump, parry at sub-step 4", + "lock_jump": "hold aim-lock and jump", + "lock_press_4": "aim-lock, press jump at sub-step 4", + "lock_press_5": "aim-lock, press jump at sub-step 5", + "lock": "hold aim-lock (stand still, 8-way aim)", + "lock_from_2": "aim-lock from sub-step 2", + "lock_half": "aim-lock for the second half", + "lock_late": "aim-lock for the last two sub-steps", + "lock_end": "aim-lock at the last sub-step", + "ex": "EX shot (1 card; super at 5 cards)", + "dash": "dash (plane: hold to shrink)", + "dash_tap": "dash at sub-step 1", + "dash_2": "dash at sub-step 2", + "dash_3": "dash at sub-step 3", + "dash_mid": "dash at sub-step 4", + "dash_5": "dash at sub-step 5", + "dash_6": "dash at sub-step 6", + "jump_dash": "jump, then air dash at sub-step 4", + "jump3_dash6": "jump at sub-step 3, air dash at sub-step 6", + "swap": "plane: swap machine gun / drop bombs" + } + } + }, + "scenes": [ + { + "case_id": "cuphead/goopy", + "boss": { + "en": "Bouncing Blob" + }, + "summary": { + "en": "Ground fight in a forest clearing: a blue blob bounces around, grows to throw punches, and finally drops tombstones." + }, + "moves": [ + { + "id": "bounce", + "name": { + "en": "Bounce" + }, + "tell": { + "en": "It squashes down before each leap; small and big forms jump to different heights." + }, + "effect": { + "en": "Landing on you deals 1 damage." + }, + "counter": { + "en": "Track the landing spot and shoot it in the air; it rebounds off side walls." + } + }, + { + "id": "punch", + "name": { + "en": "Punch" + }, + "tell": { + "en": "It faces you and winds up; the giant form blinks before its first punch." + }, + "effect": { + "en": "The fist deals 1 damage on hit." + }, + "counter": { + "en": "Crouch under the punch; dash has no invulnerability." + } + }, + { + "id": "transform", + "name": { + "en": "Transform" + }, + "tell": { + "en": "It swallows a candy and three pink question marks appear." + }, + "effect": { + "en": "Contact deals 1 damage." + }, + "counter": { + "en": "Press jump again in the air to parry the pink marks; this is the only parry in this fight." + } + }, + { + "id": "tombstone", + "name": { + "en": "Tombstone" + }, + "tell": { + "en": "A tombstone slides back and forth in the background, then pauses." + }, + "effect": { + "en": "Its slam deals 1 damage; the slide itself is harmless." + }, + "counter": { + "en": "Leave the spot it has locked on to." + } + } + ], + "phases": [ + { + "en": "Small form first, then big form, and tombstones join in the last phase." + } + ] + }, + { + "case_id": "cuphead/root_pack", + "boss": { + "en": "Garden Trio" + }, + "summary": { + "en": "Ground fight against three vegetables in turn: potato, onion, carrot; not attacking the onion for about six seconds leads to the hidden-radish branch." + }, + "moves": [ + { + "id": "dirt_worm", + "name": { + "en": "Dirt Worm" + }, + "tell": { + "en": "The potato spits several dirt balls, the last one a pink worm." + }, + "effect": { + "en": "Dirt balls deal 1 damage." + }, + "counter": { + "en": "Jump over the balls; parry the pink worm in mid-air." + } + }, + { + "id": "tears", + "name": { + "en": "Tears" + }, + "tell": { + "en": "The onion cries once hit; pink tears are mixed into the rain." + }, + "effect": { + "en": "Tears deal 1 damage." + }, + "counter": { + "en": "Watch the drop points above; about six seconds without attacking enters the hidden-radish branch." + } + }, + { + "id": "homing_carrots", + "name": { + "en": "Homing Carrots" + }, + "tell": { + "en": "The big carrot in the background summons homing mini carrots." + }, + "effect": { + "en": "Mini carrots deal 1 damage on contact; the big background body is harmless." + }, + "counter": { + "en": "Shoot the mini carrots down; they take only a few hits." + } + }, + { + "id": "eye_laser", + "name": { + "en": "Eye Rings" + }, + "tell": { + "en": "The third eye charges up, then fires rings aimed at you." + }, + "effect": { + "en": "Rings deal 1 damage." + }, + "counter": { + "en": "Keep repositioning; three shots in regular mode, two in simple and expert." + } + } + ], + "phases": [ + { + "en": "Potato, onion and carrot appear in order; a hidden-radish branch may follow." + } + ] + }, + { + "case_id": "cuphead/hilda", + "boss": { + "en": "Zodiac Shifter" + }, + "summary": { + "en": "Plane fight in the sky: the boss turns into a bull, twins and an archer in turn, ending with a moon phase." + }, + "moves": [ + { + "id": "laughter", + "name": { + "en": "Laughter" + }, + "tell": { + "en": "In normal form it laughs and fires HA letters, then small planes enter." + }, + "effect": { + "en": "The shots deal 1 damage." + }, + "counter": { + "en": "Parry every fourth pink shot from purple planes; green fans cannot be parried." + } + }, + { + "id": "horn_jab", + "name": { + "en": "Horn Jab" + }, + "tell": { + "en": "The bull lines up with your height, pauses, then thrusts its horns." + }, + "effect": { + "en": "The thrust deals 1 damage." + }, + "counter": { + "en": "Dodge up or down once its height locks." + } + }, + { + "id": "rotating_vortex", + "name": { + "en": "Rotating Vortex" + }, + "tell": { + "en": "The twins summon rotating lines of bullets on your side." + }, + "effect": { + "en": "Touching the lines deals 1 damage." + }, + "counter": { + "en": "Stay clear of the lines and never cross the centre." + } + }, + { + "id": "arrow_stars", + "name": { + "en": "Arrow and Stars" + }, + "tell": { + "en": "The archer charges an arrow, then three blue stars follow." + }, + "effect": { + "en": "The arrow or stars deal 1 damage." + }, + "counter": { + "en": "The arrow keeps a fixed direction, so leave early; the blue stars can be shot down." + } + }, + { + "id": "ufo_laser", + "name": { + "en": "UFO Laser" + }, + "tell": { + "en": "In the moon phase a UFO slides sideways, changes colour, charges, then fires." + }, + "effect": { + "en": "The laser deals 1 damage." + }, + "counter": { + "en": "Red fires straight below you, gold fires ahead; shrink to slip through gaps." + } + } + ], + "phases": [ + { + "en": "Normal form, bull, twins, archer, and finally the moon with the UFO." + } + ] + }, + { + "case_id": "cuphead/cagney", + "boss": { + "en": "Seed Bloom" + }, + "summary": { + "en": "Ground fight in a garden with an upper and lower platform layer; in phase two the floor grows thorns and vines block paths." + }, + "moves": [ + { + "id": "lunge", + "name": { + "en": "Lunge" + }, + "tell": { + "en": "Its face and arms sweep along the upper platform or the lower floor." + }, + "effect": { + "en": "Being swept deals 1 damage." + }, + "counter": { + "en": "Jump up or leave the platform to switch layers." + } + }, + { + "id": "hands", + "name": { + "en": "Magic Hands" + }, + "tell": { + "en": "Magic hands launch boomerang sycamore seeds, or 3-4 acorns aimed at you." + }, + "effect": { + "en": "Seeds or acorns deal 1 damage." + }, + "counter": { + "en": "Switch layers against seeds; move before the acorns are thrown." + } + }, + { + "id": "gatling", + "name": { + "en": "Seed Gatling" + }, + "tell": { + "en": "The head becomes a gun spitting seeds: blue homes in, purple becomes a small plant on the floor, pink can be parried." + }, + "effect": { + "en": "Seeds and plants deal 1 damage." + }, + "counter": { + "en": "Shoot homing seeds; parry pink seeds and pink shots from floating flowers." + } + }, + { + "id": "pollen", + "name": { + "en": "Pollen" + }, + "tell": { + "en": "In phase two the floor grows thorns, dandelions drift by and vines intermittently block platforms." + }, + "effect": { + "en": "Thorns, dandelions and vines deal 1 damage." + }, + "counter": { + "en": "Stay on platforms; switch when a vine shows its growth warning." + } + } + ], + "phases": [ + { + "en": "Phase two adds thorns, dandelions and vines." + } + ] + }, + { + "case_id": "cuphead/ribby_croaks", + "boss": { + "en": "Boxing Frogs" + }, + "summary": { + "en": "Ground fight: the left frog punches, the right frog spits fireflies, over three phases ending with a slot machine." + }, + "moves": [ + { + "id": "fists", + "name": { + "en": "Fists" + }, + "tell": { + "en": "The left frog throws low, mid and high punch waves, some pink, going back and forth in phase one." + }, + "effect": { + "en": "Punch waves deal 1 damage." + }, + "counter": { + "en": "Jump or crouch under; pink punches can be parried." + } + }, + { + "id": "firefly", + "name": { + "en": "Firefly" + }, + "tell": { + "en": "The right frog spits fireflies that slowly close in." + }, + "effect": { + "en": "Contact deals 1 damage." + }, + "counter": { + "en": "One shot kills one." + } + }, + { + "id": "roll", + "name": { + "en": "Roll" + }, + "tell": { + "en": "At the end of a phase the left frog rolls along the floor across the arena." + }, + "effect": { + "en": "Contact deals 1 damage." + }, + "counter": { + "en": "Jump over it." + } + }, + { + "id": "balls", + "name": { + "en": "Bouncing Balls" + }, + "tell": { + "en": "In phase two the left frog slaps out three bouncing balls while the right frog turns and blows you toward it." + }, + "effect": { + "en": "Balls deal 1 damage." + }, + "counter": { + "en": "Run or dash against the wind and pass through gaps between balls." + } + }, + { + "id": "slot", + "name": { + "en": "Slot Machine" + }, + "tell": { + "en": "In phase three it spits coins first; the lever turns pink before it can be hurt; tiger, snake and bull spiked chip platforms." + }, + "effect": { + "en": "Coins, spikes and fire deal 1 damage." + }, + "counter": { + "en": "Parry the lever; jump over, stand on or dodge fire depending on the chip." + } + } + ], + "phases": [ + { + "en": "Three phases: fists and fireflies, wind and balls, slot machine." + } + ] + }, + { + "case_id": "cuphead/wally", + "boss": { + "en": "Chick" + }, + "summary": { + "en": "Plane fight against a birdhouse; phase two is the chick's egg shield and phase three is a stretcher." + }, + "moves": [ + { + "id": "eggs", + "name": { + "en": "Eggs" + }, + "tell": { + "en": "The birdhouse spits eggs that burst into fragments at the screen edge." + }, + "effect": { + "en": "Fragments deal 1 damage." + }, + "counter": { + "en": "Predict the fragment directions." + } + }, + { + "id": "finger", + "name": { + "en": "Finger" + }, + "tell": { + "en": "The head becomes a three-fingered hand and, after a delay, fires three big shots in a fan." + }, + "effect": { + "en": "The shots deal 1 damage." + }, + "counter": { + "en": "Move out of the fan centre during the wind-up." + } + }, + { + "id": "whistle", + "name": { + "en": "Whistle" + }, + "tell": { + "en": "A whistle scream, then flapping that fires feathers in eight directions; it rests when tired." + }, + "effect": { + "en": "Feathers deal 1 damage." + }, + "counter": { + "en": "Slip through feather gaps; focus fire while it rests." + } + }, + { + "id": "chick_shield", + "name": { + "en": "Egg Shield" + }, + "tell": { + "en": "In phase two spiked eggs orbit the chick, extend and retract and block bullets; electric shots are always pink." + }, + "effect": { + "en": "Spiked eggs and electric shots deal 1 damage." + }, + "counter": { + "en": "Shoot through gaps when eggs retract; parry the electric shots." + } + }, + { + "id": "stretcher", + "name": { + "en": "Stretcher" + }, + "tell": { + "en": "In phase three the stretcher spits junk (pink boots can be parried), a heart rises, and the nurse bird's pills split and home in." + }, + "effect": { + "en": "Junk and pills deal 1 damage; only the heart can be hurt once it appears." + }, + "counter": { + "en": "Use bombs from above or up close; shoot the heart when it appears." + } + } + ], + "phases": [ + { + "en": "Three phases: birdhouse, chick egg shield, stretcher." + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/doom_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/doom_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..b70c709cd2eb18cc79298ad8da7db223450650a3 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/doom_remake.json @@ -0,0 +1,429 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "doom_remake", + "rules": "doom-arena@11", + "title": { + "en": "First-Person Shooter: Hall Boss Fights" + }, + "dimension": "3d", + "view": { + "en": "First-person 3D shooter: the crosshair is at the centre, your weapon is at the bottom, and the status bar shows ammo, health, armour and the current weapon. The arena is a hall with pillars and low walls, with medical, armour and ammo pickups on the floor. Your gunner can only turn left and right: no looking up or down, no jumping" + }, + "goal": { + "en": "Defeat every boss in the arena to win; you lose if your health reaches zero; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate; only pickups restore it" + }, + "mouse": { + "kind": "camera", + "en": "The mouse only turns the view left and right (X>0 turns right); there is no pitch" + }, + "keys": [ + { + "key": "W", + "en": "move forward" + }, + { + "key": "S", + "en": "move backward" + }, + { + "key": "A", + "en": "strafe left" + }, + { + "key": "D", + "en": "strafe right" + }, + { + "key": "Shift", + "en": "hold to run (about twice as fast)" + }, + { + "key": "Q", + "en": "turn left" + }, + { + "key": "E", + "en": "turn right" + }, + { + "key": "J", + "en": "fire, hold for continuous fire" + }, + { + "key": "LMB", + "en": "fire (same as J)" + }, + { + "key": "K", + "en": "switch to the next weapon" + }, + { + "key": "RMB", + "en": "switch to the next weapon (same as K)" + }, + { + "key": "L", + "en": "switch to the previous weapon" + } + ], + "notes": [ + { + "en": "Weapon order: shotgun, chaingun, plus a rocket launcher in scenes that have one. Switching lowers then raises the weapon, taking about a second during which you cannot fire" + }, + { + "en": "Shots go along the line through the crosshair, so turn to face the enemy first. The shotgun hits hard but fires slowly, the chaingun fires fast, and the rocket launcher does heavy damage with a blast radius, so avoid firing it point-blank" + }, + { + "en": "Fireballs and rockets are visible projectiles that you can dodge by strafing sideways; pillars and low walls block them and break line of sight" + }, + { + "en": "You can fire and turn while running. Enemies on the field may hurt each other, and each pickup can be taken only once" + } + ], + "compact_glossary": { + "move": { + "en": "movement (run is always held)", + "options": { + "none": "stand still", + "forward": "run forward", + "back": "run backward", + "left": "strafe left", + "right": "strafe right", + "forward_left": "run forward-left", + "forward_right": "run forward-right", + "back_left": "run backward-left", + "back_right": "run backward-right" + } + }, + "turn": { + "en": "horizontal turn by a fixed angle (no pitch)", + "options": { + "none": "do not turn", + "left_3": "turn left 3 degrees", + "right_3": "turn right 3 degrees", + "left_10": "turn left 10 degrees", + "right_10": "turn right 10 degrees", + "left_30": "turn left 30 degrees", + "right_30": "turn right 30 degrees", + "left_60": "turn left 60 degrees", + "right_60": "turn right 60 degrees" + } + }, + "attack": { + "en": "fire or change weapon", + "options": { + "none": "do not fire", + "fire": "hold fire", + "fire_fresh": "release then press fire (a fresh trigger pull)", + "next_weapon": "switch to the next weapon", + "prev_weapon": "switch to the previous weapon" + } + } + }, + "scenes": [ + { + "case_id": "doom/cyberdemon", + "boss": { + "en": "Rocket Colossus" + }, + "summary": { + "en": "A huge hooved rocket gunner alone at the far end of a pillared hall, attacking only at range. You have a shotgun, chaingun and rocket launcher" + }, + "moves": [ + { + "id": "rocket_volley", + "name": { + "en": "Triple rocket volley" + }, + "tell": { + "en": "It aims an arm at you, then fires a rocket about every third of a second, three in total" + }, + "effect": { + "en": "Rockets fly straight and explode on hitting you or a wall, hurting everything in the blast; the damage is high" + }, + "counter": { + "en": "Strafe sideways or duck behind a pillar when you see the arm rise; rockets take time to arrive, so a step or two sideways misses" + } + }, + { + "id": "pain_stagger", + "name": { + "en": "Hit stagger" + }, + "tell": { + "en": "When hit it sometimes stops and flinches briefly" + }, + "effect": { + "en": "It does not attack during the stagger, which interrupts what it was doing" + }, + "counter": { + "en": "Keep firing during the stagger; heavy weapons trigger it more often" + } + } + ], + "phases": [] + }, + { + "case_id": "doom/barons", + "boss": { + "en": "Green-Flame Horned Fiends" + }, + "summary": { + "en": "Two horned fiends with green flame appear together; they spit fireballs at range and claw up close. The hall is fairly open with a few pieces of cover" + }, + "moves": [ + { + "id": "fireball", + "name": { + "en": "Green fireball" + }, + "tell": { + "en": "It stops facing you for about half a second, then throws a green fireball" + }, + "effect": { + "en": "The fireball flies straight and does moderate damage on hit; both may fire at once" + }, + "counter": { + "en": "Strafe sideways or hide behind a pillar; fireballs do not home" + } + }, + { + "id": "claw", + "name": { + "en": "Claw swipe" + }, + "tell": { + "en": "When you are right in front of it, it swipes instead of throwing a fireball" + }, + "effect": { + "en": "Melee damage is very high and can take a large chunk of health in one hit" + }, + "counter": { + "en": "Do not stand next to it; keep your distance and shoot while backing off" + } + }, + { + "id": "fast_fireball", + "name": { + "en": "Fast fireball" + }, + "tell": { + "en": "Looks like the normal fireball but flies noticeably faster" + }, + "effect": { + "en": "Same damage, but you have less time to react" + }, + "counter": { + "en": "Strafe earlier or take cover in advance" + }, + "only": { + "en": "highest difficulty only" + } + } + ], + "phases": [ + { + "en": "After one falls the other keeps attacking; both must be defeated to win" + } + ] + }, + { + "case_id": "doom/spider_mastermind", + "boss": { + "en": "Four-Legged Gun Platform" + }, + "summary": { + "en": "A very large four-legged machine with a rapid-fire gun that walks slowly through a pillar-ringed arena. Its wide body is easy to hit" + }, + "moves": [ + { + "id": "burst_fire", + "name": { + "en": "Three-pellet burst" + }, + "tell": { + "en": "It stops and aims at you for about a third of a second, then the muzzle flashes and it fires a stream, three pellets each time" + }, + "effect": { + "en": "Hits instantly with no flight time; each pellet is weak but hits add up fast" + }, + "counter": { + "en": "Strafing does not help; break line of sight behind a pillar, and it stops firing and walks after you" + } + }, + { + "id": "sustained_fire", + "name": { + "en": "Sustained suppression" + }, + "tell": { + "en": "As long as it can see you it keeps firing with almost no pause" + }, + "effect": { + "en": "Standing in the open for long keeps draining your health" + }, + "counter": { + "en": "Fight around the pillars: step out, fire a few shots, step back behind cover" + } + } + ], + "phases": [] + }, + { + "case_id": "doom/archvile", + "boss": { + "en": "Flame-Caller Sorcerer" + }, + "summary": { + "en": "A fast flame-casting sorcerer accompanied by a few fire-throwing minions. The courtyard is full of pillars and low walls, which are the key to avoiding its flame" + }, + "moves": [ + { + "id": "flame_strike", + "name": { + "en": "Flame strike" + }, + "tell": { + "en": "It raises its hands and a column of flame appears next to you and follows you; about a second and a half later it bursts" + }, + "effect": { + "en": "If it can still see you at the moment of the burst you take damage and are thrown up, with area damage around the flame" + }, + "counter": { + "en": "Get behind a pillar or wall before the burst so it cannot see you; running in the open does not help" + } + }, + { + "id": "raise_minion", + "name": { + "en": "Raise minion" + }, + "tell": { + "en": "It walks to a fallen fire-throwing minion, waves a hand, and the body rises again" + }, + "effect": { + "en": "The revived minion returns at full health and keeps attacking" + }, + "counter": { + "en": "Prioritise the sorcerer itself, and keep it away from bodies" + } + }, + { + "id": "minion_fireball", + "name": { + "en": "Minion fireball" + }, + "tell": { + "en": "A fire-throwing minion stops and throws a fireball; up close it claws instead" + }, + "effect": { + "en": "Fireballs and claws do low damage" + }, + "counter": { + "en": "Strafe past fireballs; minions have little health and drop to one or two shotgun blasts" + } + } + ], + "phases": [] + }, + { + "case_id": "doom/mancubus", + "boss": { + "en": "Twin-Cannon Brute" + }, + "summary": { + "en": "A slow, huge-bellied brute with a cannon on each arm, alone in an open hall with pillars at the corners. You only have a shotgun and a chaingun" + }, + "moves": [ + { + "id": "fan_volley", + "name": { + "en": "Three-round fan volley" + }, + "tell": { + "en": "It raises both cannons and pauses about half a second, then fires three rounds of two fireballs each, about a third of a second apart" + }, + "effect": { + "en": "Fireballs fan out: one round leans left, one leans right, one brackets your position; each hit does moderate damage" + }, + "counter": { + "en": "Strafe widely as it raises the cannons to slip through the gaps, or hide behind a pillar" + } + }, + { + "id": "slow_advance", + "name": { + "en": "Slow advance" + }, + "tell": { + "en": "Between volleys it walks slowly toward you" + }, + "effect": { + "en": "Its only attack is the volley; it has no melee" + }, + "counter": { + "en": "Shoot while backing up, then strafe when it raises its cannons" + } + } + ], + "phases": [] + }, + { + "case_id": "doom/revenant", + "boss": { + "en": "Shoulder-Cannon Skeleton" + }, + "summary": { + "en": "A skeleton with shoulder-mounted rocket launchers: little health but quick. The arena is a cloister of pillar rows, with several fire-throwing minions around. You only have a shotgun and a chaingun" + }, + "moves": [ + { + "id": "homing_missile", + "name": { + "en": "Homing missile" + }, + "tell": { + "en": "It raises the shoulder launcher, pauses about a third of a second, then releases a smoking missile that flies slowly" + }, + "effect": { + "en": "The missile slowly turns to chase you and does moderate damage on hit" + }, + "counter": { + "en": "Put a pillar between you and the missile so it hits the pillar; you can also shoot it down" + } + }, + { + "id": "fist", + "name": { + "en": "Fist punch" + }, + "tell": { + "en": "When you are very close it winds up an arm and swings about half a second later" + }, + "effect": { + "en": "Moderate melee damage" + }, + "counter": { + "en": "Do not stay in melee range; back away" + } + }, + { + "id": "minion_fireball", + "name": { + "en": "Minion fireball" + }, + "tell": { + "en": "The surrounding fire-throwing minions stop and throw fireballs" + }, + "effect": { + "en": "Fireballs do low damage; minions and the skeleton may hurt each other by accident" + }, + "counter": { + "en": "Strafe aside, and clear nearby minions first if needed" + } + } + ], + "phases": [] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/genshin_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/genshin_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..d745224ef476bbf81db7c0a7b98140c3a7734f38 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/genshin_remake.json @@ -0,0 +1,1214 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "genshin_remake", + "rules": "genshin-bosses@8", + "title": { + "en": "Third-Person 3D: Four-Character Party Boss Fights" + }, + "dimension": "3d", + "view": { + "en": "Third-person 3D: the camera follows behind the active character. The boss name, status line and health bar are at the top; a side panel shows the four party members (health, energy ring, skill cooldown); the active character's health and stamina are below, with skill and burst rings, the timer and the lock-on state." + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose when the whole party is down; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate by itself; only the healer's abilities or healing effects restore it." + }, + "mouse": { + "kind": "camera", + "en": "The mouse turns the camera, but only while lock-on is off. The fight opens with the camera unlocked (free camera); press R to lock onto the target. In this game dx > 0 turns the view RIGHT and dx < 0 turns it left; dy > 0 lowers the aim pitch, which only affects unlocked bow aiming." + }, + "keys": [ + { + "key": "W", + "en": "move forward relative to the camera" + }, + { + "key": "A", + "en": "move left relative to the camera" + }, + { + "key": "S", + "en": "move backward relative to the camera" + }, + { + "key": "D", + "en": "move right relative to the camera" + }, + { + "key": "Space", + "en": "jump; clears ground rings" + }, + { + "key": "Shift", + "en": "dash: brief invulnerability on press; holding runs and drains stamina" + }, + { + "key": "J", + "en": "normal attack, hold to chain; pressed in the air it is a plunge attack" + }, + { + "key": "LMB", + "en": "hold to charge a heavy attack; the archer taps for one arrow and fully charges for a fire arrow" + }, + { + "key": "K", + "en": "elemental skill; the archer can hold it to set the decoy throw distance" + }, + { + "key": "RMB", + "en": "elemental skill (same as K)" + }, + { + "key": "L", + "en": "elemental burst; needs full energy and no cooldown" + }, + { + "key": "Q", + "en": "swap to the previous living character" + }, + { + "key": "E", + "en": "swap to the next living character" + }, + { + "key": "R", + "en": "toggle target lock-on; off at the start" + } + ], + "notes": [ + { + "en": "You control a party of four, one active at a time: swordsman (sword, ice), archer (bow, fire), spearman (polearm, fire) and healer (catalyst, water). Q / E swap, with a shared cooldown of about 1 s; fallen characters are skipped." + }, + { + "en": "Each character has their own skill (K) and burst (L) with separate cooldowns and energy; energy builds from normal attacks and skills. Skill names are not shown; read the cooldown and energy rings." + }, + { + "en": "Ice is useless against the wolf and some elements do nothing to the cube, so swap by scene: bosses and water creatures have different weak elements." + }, + { + "en": "Elemental reactions: hitting a target with different elements in turn triggers reactions (overload, superconduct, vaporize, melt, freeze and so on) for bonus damage or effects." + }, + { + "en": "Stamina is shared by the whole party; dashing, sprinting and swimming drain it, and without stamina you cannot dash." + }, + { + "en": "J, LMB and the archer's K work while held; E, Q, R, L, Shift, Space and the other characters' K take effect on a press." + }, + { + "en": "Archer: unlocked, holding LMB gives an over-the-shoulder aim and arrows follow the crosshair, able to hit the colossus's eye and back weak points. Locked, arrows aim at the target automatically." + }, + { + "en": "When locked the camera and facing follow the target and strafing does not turn the camera; when unlocked you steer the camera with the mouse." + } + ], + "compact_glossary": { + "move": { + "en": "Movement relative to the camera (WASD)", + "options": { + "none": "stand still", + "forward": "W", + "back": "S", + "left": "A", + "right": "D", + "forward_left": "W+A", + "forward_right": "W+D", + "back_left": "S+A", + "back_right": "S+D" + } + }, + "action": { + "en": "Attack, skill and dodge for the active character", + "options": { + "none": "no action", + "attack": "hold J for normal attack chain", + "charge": "hold LMB to charge a heavy attack", + "charge_release": "hold LMB for 3 sub-steps then release", + "shot": "tap LMB: one arrow, or a normal attack", + "shot_up": "tap LMB and raise aim ~5 degrees", + "shot_down": "tap LMB and lower aim ~5 degrees", + "skill": "tap skill key K", + "skill_hold": "hold skill key K", + "burst": "tap ultimate L", + "dash": "tap Shift to dash", + "jump": "tap Space to jump" + } + }, + "view": { + "en": "Camera, lock-on and character swap", + "options": { + "none": "no change", + "next": "swap to next character (E)", + "prev": "swap to previous character (Q)", + "lock": "toggle lock-on (R)", + "lock_left_18": "toggle lock and turn left 18 degrees", + "left_5": "turn view left 5 degrees", + "right_5": "turn view right 5 degrees", + "left_45": "turn view left 45 degrees", + "right_45": "turn view right 45 degrees" + } + } + }, + "scenes": [ + { + "case_id": "genshin/electro_hypostasis", + "boss": { + "en": "Floating Square Array" + }, + "summary": { + "en": "A floating cube boss that alternates between a closed shell and an exposed core, in a flat arena." + }, + "moves": [ + { + "id": "fist", + "name": { + "en": "Block Punch" + }, + "tell": { + "en": "The cube raises a block fist and winds up for about 0.7 s" + }, + "effect": { + "en": "Lunges forward with a punch that damages on hit" + }, + "counter": { + "en": "Sidestep or dash through" + } + }, + { + "id": "clap", + "name": { + "en": "Twin-Plate Clap" + }, + "tell": { + "en": "Two plates swing open, then snap shut after about 0.9 s" + }, + "effect": { + "en": "Frontal fan-shaped clamp" + }, + "counter": { + "en": "Back out of the fan or circle behind" + } + }, + { + "id": "rps", + "name": { + "en": "Three-Shape Combo" + }, + "tell": { + "en": "The body morphs in turn into scissors, fist and palm shapes" + }, + "effect": { + "en": "Each shape has a different reach, hit in a row" + }, + "counter": { + "en": "Read the current shape: scissors are narrow and long, palm is widest; keep moving" + } + }, + { + "id": "drill", + "name": { + "en": "Spiral Dash" + }, + "tell": { + "en": "Spins into a spiral and charges up for about 0.8 s" + }, + "effect": { + "en": "Charges at speed in a straight line" + }, + "counter": { + "en": "Dodge perpendicular to the line" + } + }, + { + "id": "lasers", + "name": { + "en": "Rotating Beams" + }, + "tell": { + "en": "Four beam ports light up, then rotate for several seconds after about 1 s" + }, + "effect": { + "en": "Rotating beams sweep the floor and hurt on contact" + }, + "counter": { + "en": "Jump or dash through the gaps between beams" + } + }, + { + "id": "missiles", + "name": { + "en": "Diamond Barrage" + }, + "tell": { + "en": "A ring of diamond crystals floats up, then fires after about 1 s" + }, + "effect": { + "en": "Projectiles fly at your position and explode" + }, + "counter": { + "en": "Keep strafing and leave your spot before the blasts" + } + }, + { + "id": "cage", + "name": { + "en": "Eight-Pillar Cage" + }, + "tell": { + "en": "Eight light pillars rise around the edge, warning for about 1.6 s" + }, + "effect": { + "en": "Pillars link into a lasting energy net that traps you" + }, + "counter": { + "en": "Stay in the safe zone inside; do not touch the pillars" + } + }, + { + "id": "waves", + "name": { + "en": "Ground Rings" + }, + "tell": { + "en": "The boss drops down and rings start to spread on the ground" + }, + "effect": { + "en": "Spreading rings that hurt along the ground" + }, + "counter": { + "en": "Jump with Space as a ring reaches you" + } + }, + { + "id": "prism", + "name": { + "en": "Crystal Blocks" + }, + "tell": { + "en": "Three crystal blocks are left after the shell closes" + }, + "effect": { + "en": "The blocks carry shields and keep the boss protected until broken" + }, + "counter": { + "en": "Use a character or element that counters them; break the blocks, then hit the exposed core" + } + } + ], + "phases": [ + { + "en": "The boss is mostly closed and cannot be damaged; the core is exposed only after certain moves. Burst it then." + }, + { + "en": "One kind of element does nothing to this boss, so swap characters." + } + ] + }, + { + "case_id": "genshin/ruin_guard", + "boss": { + "en": "Back-Cannon Colossus" + }, + "summary": { + "en": "A large mechanical colossus with weak points on the eye and back; its body is tough." + }, + "moves": [ + { + "id": "stomp", + "name": { + "en": "Stomp Quake" + }, + "tell": { + "en": "Lifts one foot, then stomps after about 0.6 s" + }, + "effect": { + "en": "Small circular quake around the foot" + }, + "counter": { + "en": "Move away from the foot or dash out" + } + }, + { + "id": "clap", + "name": { + "en": "Arm Slam" + }, + "tell": { + "en": "Raises an arm, then slams forward after about 0.5 s" + }, + "effect": { + "en": "Narrow frontal heavy hit" + }, + "counter": { + "en": "Sidestep" + } + }, + { + "id": "combo", + "name": { + "en": "Punch and Leap-Slam" + }, + "tell": { + "en": "Two punches, then a leap and landing" + }, + "effect": { + "en": "Two punches followed by a wide landing slam" + }, + "counter": { + "en": "Back away or dash and avoid the landing point" + } + }, + { + "id": "spin", + "name": { + "en": "Spin Crush" + }, + "tell": { + "en": "Crouches and spins, then marches while spinning after about 0.7 s" + }, + "effect": { + "en": "Repeatedly hits nearby targets while spinning" + }, + "counter": { + "en": "Keep a good distance" + } + }, + { + "id": "volley", + "name": { + "en": "Back-Cannon Volley" + }, + "tell": { + "en": "Back cannons swivel and open; six missiles in about 2 s" + }, + "effect": { + "en": "Homing missiles that curve" + }, + "counter": { + "en": "Run in circles so they miss; hit the back weak point to interrupt" + } + } + ], + "phases": [ + { + "en": "Two quick aimed hits on the eye or back weak point paralyse it; burst then." + }, + { + "en": "Its body strongly resists physical damage; use elemental damage." + } + ] + }, + { + "case_id": "genshin/oceanid", + "boss": { + "en": "Tidepool Summoner" + }, + "summary": { + "en": "A 3x3 platform in a pond. The boss itself cannot be hit; defeat the water creatures it summons." + }, + "moves": [ + { + "id": "summon", + "name": { + "en": "Summon Water Creatures" + }, + "tell": { + "en": "Water swells and forms animal shapes in about 1 s" + }, + "effect": { + "en": "Five waves; each kind has a different weak element and some heal, explode or fly" + }, + "counter": { + "en": "Swap to the character that counters the element; kill healers first" + } + }, + { + "id": "sink", + "name": { + "en": "Platform Sinks" + }, + "tell": { + "en": "Some platforms bubble and begin sinking, warning for about 1.7 s" + }, + "effect": { + "en": "Sunken tiles become deep water; swimming drains stamina" + }, + "counter": { + "en": "Jump to a tile that is still above water" + } + }, + { + "id": "torrent", + "name": { + "en": "Chasing Whirlpool" + }, + "tell": { + "en": "If the fight drags on, a whirlpool forms on the water" + }, + "effect": { + "en": "The whirlpool follows you and hurts on contact" + }, + "counter": { + "en": "Keep moving and clear the wave fast" + } + } + ], + "phases": [ + { + "en": "There are five waves; platforms sink after waves 2 and 4 are cleared." + }, + { + "en": "Use the archer's arrows against flying or in-water targets." + } + ] + }, + { + "case_id": "genshin/maguu_kenki", + "boss": { + "en": "Masked Dual-Blade" + }, + "summary": { + "en": "A fast melee boss. Attacks from far away are deflected by the mask, so you must close in." + }, + "moves": [ + { + "id": "ichimonji", + "name": { + "en": "Triple Slash" + }, + "tell": { + "en": "Raises a blade, then slashes three times after about 0.4 s" + }, + "effect": { + "en": "Each slash lunges a little, frontal fan" + }, + "counter": { + "en": "Back off or sidestep; close in during the gaps" + } + }, + { + "id": "rush", + "name": { + "en": "Straight Dash-Slash" + }, + "tell": { + "en": "Crouches, then dashes in a line after about 0.6 s" + }, + "effect": { + "en": "Line damage with another blade strike at the end" + }, + "counter": { + "en": "Dodge perpendicular to the line" + } + }, + { + "id": "sweeper", + "name": { + "en": "Pulling Sweep" + }, + "tell": { + "en": "Raises the blade for about 1 s while air pulls inward" + }, + "effect": { + "en": "Pulls you in, then sweeps in a circle" + }, + "counter": { + "en": "Dash through, or keep distance during the wind-up" + } + }, + { + "id": "pushMask", + "name": { + "en": "Thrown Mask" + }, + "tell": { + "en": "Throws a mask forward after about 0.5 s" + }, + "effect": { + "en": "Mask flies in a straight line and hurts" + }, + "counter": { + "en": "Move sideways" + } + }, + { + "id": "explodeMask", + "name": { + "en": "Mask Blast" + }, + "tell": { + "en": "A mask lands and detonates after about 1.4 s" + }, + "effect": { + "en": "Explosion around the landing point" + }, + "counter": { + "en": "Leave the mask area before it explodes" + } + }, + { + "id": "taunt", + "name": { + "en": "Standing Challenge" + }, + "tell": { + "en": "The boss stands still for about 2 s" + }, + "effect": { + "en": "No attack; a damage window" + }, + "counter": { + "en": "Close in and attack" + } + }, + { + "id": "dash", + "name": { + "en": "Hop Dash" + }, + "tell": { + "en": "Five short hops in a row" + }, + "effect": { + "en": "Its position keeps changing" + }, + "counter": { + "en": "Keep chasing it" + } + }, + { + "id": "transition", + "name": { + "en": "Ground-Pound Ice Ring" + }, + "tell": { + "en": "Slams the ground after about 1.2 s; invulnerable then" + }, + "effect": { + "en": "Large ice ring" + }, + "counter": { + "en": "Get away or prepare to jump before it lands" + } + }, + { + "id": "dualBurst", + "name": { + "en": "Dual-Blade Ice Ring" + }, + "tell": { + "en": "Plants both blades in the ground after about 1 s" + }, + "effect": { + "en": "Large ice ring" + }, + "counter": { + "en": "Keep distance" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "shadowIchimonji", + "name": { + "en": "Clone Triple Slash" + }, + "tell": { + "en": "Clone adds a delayed slash after the main body's" + }, + "effect": { + "en": "Two waves of attacks offset in time" + }, + "counter": { + "en": "The second wave arrives slightly later; dodge again" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "shadowSweeper", + "name": { + "en": "Clone Pulling Sweep" + }, + "tell": { + "en": "Main body winds up while a clone adds an outer sweep" + }, + "effect": { + "en": "Inner and outer hits" + }, + "counter": { + "en": "Evade the inner ring, then the outer" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "shadowBlade", + "name": { + "en": "Clone Blade Throw" + }, + "tell": { + "en": "Clones fire three blades one after another" + }, + "effect": { + "en": "Straight blades" + }, + "counter": { + "en": "Strafe" + }, + "only": { + "en": "later phase only" + } + } + ], + "phases": [ + { + "en": "At around 70% health the boss turns invulnerable and changes phase; clone and dual-blade moves appear." + }, + { + "en": "From a distance, all your attacks are deflected by the mask." + } + ] + }, + { + "case_id": "genshin/andrius", + "boss": { + "en": "Tundra Wolf" + }, + "summary": { + "en": "A huge tundra wolf in a round arena, immune to ice and wind; phase 2 starts around half health." + }, + "moves": [ + { + "id": "slash", + "name": { + "en": "Claw Slash" + }, + "tell": { + "en": "Lifts a paw, swipes forward after about 0.4 s" + }, + "effect": { + "en": "Frontal melee fan" + }, + "counter": { + "en": "Sidestep" + } + }, + { + "id": "leap", + "name": { + "en": "Leaping Pounce" + }, + "tell": { + "en": "Crouches, then leaps onto your position after about 0.7 s" + }, + "effect": { + "en": "Circular damage at the landing point" + }, + "counter": { + "en": "Leave the landing spot while it is airborne" + } + }, + { + "id": "charge", + "name": { + "en": "Straight Charge" + }, + "tell": { + "en": "Backs up and winds up for about 0.9 s" + }, + "effect": { + "en": "Charges in a line leaving a trail" + }, + "counter": { + "en": "Run perpendicular" + } + }, + { + "id": "tail", + "name": { + "en": "Tail Ice Spikes" + }, + "tell": { + "en": "Turns and flicks 5 ice spikes that explode a few seconds later" + }, + "effect": { + "en": "Spikes land and then explode" + }, + "counter": { + "en": "Leave the spikes before they pop" + } + }, + { + "id": "tailMelee", + "name": { + "en": "Close Tail Swing" + }, + "tell": { + "en": "Swings its tail when you are close" + }, + "effect": { + "en": "Wide close-range fan" + }, + "counter": { + "en": "Back off or dash through" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "spin", + "name": { + "en": "Spinning Ice Ring" + }, + "tell": { + "en": "Spins, then releases an ice ring after about 0.9 s" + }, + "effect": { + "en": "Large circle around its body" + }, + "counter": { + "en": "Get outside the circle or dash" + } + }, + { + "id": "interlude", + "name": { + "en": "Arena Run" + }, + "tell": { + "en": "At about half health it leaves and runs around the arena" + }, + "effect": { + "en": "Cannot be targeted; leads to phase 2" + }, + "counter": { + "en": "Keep distance and wait" + } + }, + { + "id": "storm", + "name": { + "en": "Falling Ice" + }, + "tell": { + "en": "Howls up; ice falls in 3 waves after about 1.1 s" + }, + "effect": { + "en": "Several drop circles per wave" + }, + "counter": { + "en": "Leave each circle as it appears" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "roar", + "name": { + "en": "Arena Roar" + }, + "tell": { + "en": "Roars, then the whole arena hurts for a while after about 1 s" + }, + "effect": { + "en": "Continuous damage across the arena and detonates ice pillars" + }, + "counter": { + "en": "Hide behind an ice pillar or dash" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "blades", + "name": { + "en": "Fan Air Slashes" + }, + "tell": { + "en": "Raises a paw, then fires 3 fan air slashes after about 0.6 s" + }, + "effect": { + "en": "Three blades travelling far" + }, + "counter": { + "en": "Step into the gaps or move to the side" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "iceWave", + "name": { + "en": "Straight Ice Wave" + }, + "tell": { + "en": "Ice lines appear on the ground, a wave moves along them after about 0.8 s" + }, + "effect": { + "en": "A long wave that slows" + }, + "counter": { + "en": "Leave the line" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "wolves", + "name": { + "en": "Summon Wolves" + }, + "tell": { + "en": "At low health it howls and calls small wolves" + }, + "effect": { + "en": "Small wolves chase and bite" + }, + "counter": { + "en": "Clear the wolves first or keep dodging while hitting the boss" + }, + "only": { + "en": "later phase only" + } + } + ], + "phases": [ + { + "en": "Immune to ice and wind, so the swordsman is nearly useless; use fire and other elements." + }, + { + "en": "Around half health there is an arena-run interlude, then phase 2 adds ice pillars and more moves." + }, + { + "en": "Fire melts ice pillars; roars or air slashes detonate them." + } + ] + }, + { + "case_id": "genshin/signora", + "boss": { + "en": "Frost-Flame Caster" + }, + "summary": { + "en": "A two-phase caster that fights with ice first, then fire. There are beacons at the four corners and a temperature gauge on screen." + }, + "moves": [ + { + "id": "wheel", + "name": { + "en": "Ice Shard Fan" + }, + "tell": { + "en": "Raises a hand, fires a spread of ice shards after about 0.5 s" + }, + "effect": { + "en": "Shards flying in a fan" + }, + "counter": { + "en": "Dodge to the side" + } + }, + { + "id": "hail", + "name": { + "en": "Targeted Ice Fall" + }, + "tell": { + "en": "A circle shows on the ground; ice falls after about 0.7 s" + }, + "effect": { + "en": "Damage in the circle" + }, + "counter": { + "en": "Step out of the circle" + } + }, + { + "id": "flower", + "name": { + "en": "Triple Ice Burst" + }, + "tell": { + "en": "Three frost blooms appear and explode after about 1.5 s" + }, + "effect": { + "en": "Three area explosions" + }, + "counter": { + "en": "Stay away from all three" + } + }, + { + "id": "biting", + "name": { + "en": "Homing Ice Spears" + }, + "tell": { + "en": "Fires 5 homing ice spears in sequence" + }, + "effect": { + "en": "They track but turn slowly" + }, + "counter": { + "en": "Run in circles so they cannot turn" + } + }, + { + "id": "snowfall", + "name": { + "en": "Close Ice Burst" + }, + "tell": { + "en": "At close range she gathers ice and bursts after about 0.7 s" + }, + "effect": { + "en": "Medium area around her" + }, + "counter": { + "en": "Back off" + } + }, + { + "id": "benevolence", + "name": { + "en": "Underfoot Ice Array" + }, + "tell": { + "en": "An ice array forms under you, warning for about 1.3 s" + }, + "effect": { + "en": "Damage after the array finishes" + }, + "counter": { + "en": "Leave during the warning" + } + }, + { + "id": "frozenVoid", + "name": { + "en": "Delayed Giant Spear" + }, + "tell": { + "en": "Hurls a giant spear that stays in the ground and explodes after about 4 s" + }, + "effect": { + "en": "Delayed explosion" + }, + "counter": { + "en": "Get away before it blows" + } + }, + { + "id": "cocoon", + "name": { + "en": "Ice Shell Charge" + }, + "tell": { + "en": "At low health she is encased in an ice shell while flames float around" + }, + "effect": { + "en": "The shell has a large shield and normal damage fails" + }, + "counter": { + "en": "Pick up a floating flame and hit the shell with it" + } + }, + { + "id": "lash", + "name": { + "en": "Fire Whip Slash" + }, + "tell": { + "en": "A fire whip appears, swings after about 0.4 s" + }, + "effect": { + "en": "Frontal fire fan" + }, + "counter": { + "en": "Back off or sidestep" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "lashLong", + "name": { + "en": "Fire Whip Thrust" + }, + "tell": { + "en": "The whip straightens and thrusts after about 0.5 s" + }, + "effect": { + "en": "Long narrow line" + }, + "counter": { + "en": "Dodge sideways" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "lashTriple", + "name": { + "en": "Triple Fire Whip" + }, + "tell": { + "en": "Three fire whips lash out in different directions and then pop" + }, + "effect": { + "en": "Three arcs plus a blast" + }, + "counter": { + "en": "Stand in the gap between whips" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "warp", + "name": { + "en": "Close-Range Dash" + }, + "tell": { + "en": "Her form turns to fire and rushes at you" + }, + "effect": { + "en": "Collides with you" + }, + "counter": { + "en": "Dash away" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "fireball", + "name": { + "en": "Slow Fireball" + }, + "tell": { + "en": "A fireball forms and launches after about 0.5 s" + }, + "effect": { + "en": "A slow fireball that keeps going" + }, + "counter": { + "en": "Walk or jump away" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "wrath", + "name": { + "en": "Falling Fire Pillars" + }, + "tell": { + "en": "Markers appear in the sky; fire pillars fall in 3 waves after about 0.8 s" + }, + "effect": { + "en": "Five circles per wave" + }, + "counter": { + "en": "Leave each wave's circles at once" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "onslaught", + "name": { + "en": "Floating Flame Volley" + }, + "tell": { + "en": "Releases 6 floating flames at once" + }, + "effect": { + "en": "The flames fly toward you" + }, + "counter": { + "en": "Strafe so they miss" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "moth", + "name": { + "en": "Homing Flame" + }, + "tell": { + "en": "A slow homing flame" + }, + "effect": { + "en": "Follows you for a long time" + }, + "counter": { + "en": "Walk around it" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "blaze", + "name": { + "en": "Patrol Fire Whirl" + }, + "tell": { + "en": "A fire whirl patrols the arena and sheds small flames" + }, + "effect": { + "en": "Large whirl and small flames" + }, + "counter": { + "en": "Keep moving and avoid its path" + }, + "only": { + "en": "later phase only" + } + }, + { + "id": "counter", + "name": { + "en": "Retaliation" + }, + "tell": { + "en": "When she is hit hard in some states she retaliates" + }, + "effect": { + "en": "Area damage around her; painful" + }, + "counter": { + "en": "Do not burst her down all at once; shoot from outside its range" + } + } + ], + "phases": [ + { + "en": "The temperature gauge is the arena clock: you bleed when it is full; use the beacons (ice lamps and fire braziers) to adjust it." + }, + { + "en": "At about 20% health she is covered in an ice shell; you need to pick up a floating flame to break it." + }, + { + "en": "Phase 2 uses fire moves and resists fire strongly." + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/hexen2_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/hexen2_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..121d59b39934fca3640d44fdb8ee3b7040c2e50c --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/hexen2_remake.json @@ -0,0 +1,611 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "hexen2_remake", + "rules": "hexen2-arena@4", + "title": { + "en": "First-Person Fantasy Arena: Riders and Serpent" + }, + "dimension": "3d", + "view": { + "en": "First-person 3D: you are a heavily armoured swordsman with a crosshair at the centre and your weapon below. The HUD shows the boss name and health bar and your health, mana, armour and current weapon. The arena is round with pillars and cover, and mana and life crystals lie on the floor" + }, + "goal": { + "en": "Empty the boss health bar to win; you lose when your health reaches zero; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate and each life crystal can be taken once; mana crystals respawn over time" + }, + "mouse": { + "kind": "camera", + "en": "X>0 turns right, Y>0 looks down; look up for flying or very large bosses" + }, + "keys": [ + { + "key": "W", + "en": "move ahead" + }, + { + "key": "S", + "en": "move back" + }, + { + "key": "A", + "en": "strafe left" + }, + { + "key": "D", + "en": "strafe right" + }, + { + "key": "Shift", + "en": "hold to run (double speed)" + }, + { + "key": "Space", + "en": "jump" + }, + { + "key": "L", + "en": "crouch" + }, + { + "key": "Q", + "en": "turn left (keyboard turn, slow)" + }, + { + "key": "E", + "en": "turn right (keyboard turn, slow)" + }, + { + "key": "J", + "en": "attack, hold to repeat" + }, + { + "key": "LMB", + "en": "attack (same as J)" + }, + { + "key": "K", + "en": "next weapon (about 0.3 s select delay, no firing)" + }, + { + "key": "RMB", + "en": "next weapon (same as K)" + }, + { + "key": "R", + "en": "previous weapon" + } + ], + "notes": [ + { + "en": "Four weapons: gauntlet (melee), long sword (melee, uses mana), throwing axe (bounces back) and fire-orb wand (ranged rapid fire, uses mana). Pick up mana crystals when you run dry." + }, + { + "en": "Hold attack to repeat; switching weapons blocks firing for about 0.3 s, so do not switch in danger." + }, + { + "en": "Aim ranged weapons before firing; boss homing shots turn slowly, so sidestepping behind cover works best." + }, + { + "en": "Boss attacks have visible wind-ups: a glow at the release point, a shrinking ring and an on-screen banner. Dodge when you see them." + }, + { + "en": "Your projectiles are sky blue and boss projectiles never are; bosses have an outline glow found nowhere else in the arena." + }, + { + "en": "Each rider follows a fixed route; pillars on it can block shots." + } + ], + "compact_glossary": { + "move": { + "en": "Movement, 8 directions; every non-idle option also holds Shift (run)", + "options": { + "none": "stand still", + "forward": "run ahead", + "back": "run back", + "left": "strafe left", + "right": "strafe right", + "forward_left": "run ahead-left", + "forward_right": "run ahead-right", + "back_left": "run back-left", + "back_right": "run back-right" + } + }, + "turn": { + "en": "Horizontal view turn by a fixed angle (mouse X), negative is left", + "options": { + "none": "no turn", + "left_3": "turn left 3 deg", + "right_3": "turn right 3 deg", + "left_10": "turn left 10 deg", + "right_10": "turn right 10 deg", + "left_30": "turn left 30 deg", + "right_30": "turn right 30 deg", + "left_60": "turn left 60 deg", + "right_60": "turn right 60 deg" + } + }, + "pitch": { + "en": "Vertical view tilt (mouse Y), for flying or tall enemies", + "options": { + "none": "no tilt", + "up_3": "look up 3 deg", + "down_3": "look down 3 deg" + } + }, + "attack": { + "en": "Attack or weapon switch; never combined in one packet", + "options": { + "none": "no attack", + "fire": "hold the attack button", + "next_weapon": "switch to next weapon", + "prev_weapon": "switch to previous weapon" + } + } + }, + "scenes": [ + { + "case_id": "hexen2/airborne_bone_rider", + "boss": { + "en": "Airborne Bone-Rain Rider" + }, + "summary": { + "en": "A rider on a flying mount circles above the arena along a fixed route and chains three ranged attacks. You often need to look up to aim." + }, + "moves": [ + { + "id": "death_bones", + "name": { + "en": "Bone-Rain Missile" + }, + "tell": { + "en": "The rider launches a slow homing missile that can be shot down." + }, + "effect": { + "en": "If it hits you, bones rain on you from above for about 4 to 6 seconds; each does little damage but there are many." + }, + "counter": { + "en": "Shoot the missile before it lands, or keep strafing so the bones miss." + } + }, + { + "id": "death_fire_circle", + "name": { + "en": "Fire Ring" + }, + "tell": { + "en": "A missile flies at you and bursts into flames where it lands." + }, + "effect": { + "en": "The flames spin and widen for about 1.2 seconds, burning anyone inside, harder over time." + }, + "counter": { + "en": "Run out of the ring as soon as the missile lands; do not stay near the impact point." + } + }, + { + "id": "death_missiles", + "name": { + "en": "Triple Missile Volley" + }, + "tell": { + "en": "The rider fires left, centre and right homing missiles at once." + }, + "effect": { + "en": "Each hit deals moderate damage and the missiles steer at you for about 3 seconds." + }, + "counter": { + "en": "Run sideways and get behind cover so the missiles hit the wall." + } + } + ], + "phases": [ + { + "en": "After each attack there is a few seconds of cooldown and only one attack is active at a time." + } + ] + }, + { + "case_id": "hexen2/axe_hurling_rider", + "boss": { + "en": "Axe-Hurling Armoured Rider" + }, + "summary": { + "en": "A heavily armoured rider gallops along a route and hurls a batch of axes after every lap. It is big and tramples." + }, + "moves": [ + { + "id": "war_axe", + "name": { + "en": "Side Axes" + }, + "tell": { + "en": "After each lap the rider throws two to four axes that fly out sideways, then curve at you." + }, + "effect": { + "en": "Each axe deals moderate damage; the slower the rider gallops, the more axes per throw." + }, + "counter": { + "en": "The axes turn slowly; strafe or hide behind a pillar, then attack in the gap." + } + }, + { + "id": "war_big_axe", + "name": { + "en": "Rearing Heavy Axe" + }, + "tell": { + "en": "The mount rears up, then the rider throws one larger axe." + }, + "effect": { + "en": "This axe tracks more tightly and hits very hard, and explodes on walls." + }, + "counter": { + "en": "Start strafing as soon as it rears and lead the axe into cover." + } + }, + { + "id": "war_trample", + "name": { + "en": "Trample" + }, + "tell": { + "en": "The rider gallops straight at you." + }, + "effect": { + "en": "Contact deals moderate damage and knocks you far back, worse from the front." + }, + "counter": { + "en": "Step aside early and do not stand in its path." + } + } + ], + "phases": [ + { + "en": "A sharp turn makes the next lap faster; gentle turns slow it and it throws more axes." + } + ] + }, + { + "case_id": "hexen2/blinking_tether_rider", + "boss": { + "en": "Blinking Tether Rider" + }, + "summary": { + "en": "A rider gallops on a route. It does not trample, but pulls you in, fires homing missiles, and blinks next to you after rearing." + }, + "moves": [ + { + "id": "famine_pull", + "name": { + "en": "Tether Pull" + }, + "tell": { + "en": "The rider stops and a string of glowing orbs links at you." + }, + "effect": { + "en": "The beam lasts several seconds, drags you steadily at the rider and deals small damage each second." + }, + "counter": { + "en": "Cover that blocks the beam cancels the pull; get behind a pillar." + } + }, + { + "id": "famine_missiles", + "name": { + "en": "Triple Missile Volley" + }, + "tell": { + "en": "The rider raises an arm and fires left, centre and right missiles." + }, + "effect": { + "en": "The missiles home for about 2 seconds, each hit moderate." + }, + "counter": { + "en": "Run sideways and use cover so the missiles cannot turn in time." + } + }, + { + "id": "famine_blink", + "name": { + "en": "Rear and Blink" + }, + "tell": { + "en": "The mount rears and its body fades out." + }, + "effect": { + "en": "While gone it cannot be hit; after about 0.5 to 3 seconds it reappears at the route point nearest you and may fire another volley." + }, + "counter": { + "en": "Do not waste shots while it is gone; guess where it will reappear and aim there." + } + } + ], + "phases": [ + { + "en": "The more hurt it is, the more it rears and blinks." + } + ] + }, + { + "case_id": "hexen2/boar_archer_rider", + "boss": { + "en": "Boar-Riding Poison Archer" + }, + "summary": { + "en": "An archer on a huge boar. It starts awake, chases you on sight, tramples up close and shoots poison arrows and throws hives from range." + }, + "moves": [ + { + "id": "pest_arrow", + "name": { + "en": "Poison Arrow" + }, + "tell": { + "en": "The archer turns at you and draws the bow." + }, + "effect": { + "en": "The homing arrow flies for about 2 seconds, hits for moderate damage and poisons you, dealing damage each second; stacks." + }, + "counter": { + "en": "Strafe away; poison lasts 5 to 10 seconds, so avoid getting hit." + } + }, + { + "id": "pest_hive", + "name": { + "en": "Hive Throw" + }, + "tell": { + "en": "The archer lobs a hive that bounces along the ground." + }, + "effect": { + "en": "When it lands or is shot, it releases three insect clouds that drift after you for about 20 seconds, chipping small damage on contact." + }, + "counter": { + "en": "Shoot the hive in the air; the clouds are slow, so keep moving." + } + }, + { + "id": "pest_charge", + "name": { + "en": "Charge" + }, + "tell": { + "en": "The boar lowers its head, speeds up sharply and runs straight at you." + }, + "effect": { + "en": "Contact deals moderate damage and heavy knockback; it may also shoot or throw during the charge." + }, + "counter": { + "en": "Dodge sideways early; do not run straight back." + } + }, + { + "id": "pest_trample", + "name": { + "en": "Body Slam" + }, + "tell": { + "en": "The boar closes in and rams you." + }, + "effect": { + "en": "Moderate damage with knockback, at most once every half second." + }, + "counter": { + "en": "Keep distance and shoot while backing away." + } + } + ], + "phases": [ + { + "en": "It attacks more eagerly after being hurt; if stuck on a wall it backs up for a few seconds." + } + ] + }, + { + "case_id": "hexen2/orb_warded_serpent", + "boss": { + "en": "Orb-Shielded Serpent" + }, + "summary": { + "en": "A destructible orb in the arena shields the serpent. You must break the orb first, then defeat the serpent itself, over several phases." + }, + "moves": [ + { + "id": "eidolon_magic", + "name": { + "en": "Small-Form Bolts" + }, + "tell": { + "en": "In its small form the serpent raises a hand and fires one or more fast bolts." + }, + "effect": { + "en": "The bolts are fast and moderately damaging." + }, + "counter": { + "en": "Keep moving around pillars instead of backing straight away." + } + }, + { + "id": "eidolon_fireball", + "name": { + "en": "Fireball" + }, + "tell": { + "en": "In its large form it opens its mouth and fires fireballs in pairs." + }, + "effect": { + "en": "A direct hit is extremely damaging, one can cripple you, and the blast splashes." + }, + "counter": { + "en": "Dodge sideways the moment it opens its mouth and get behind cover." + } + }, + { + "id": "eidolon_flames", + "name": { + "en": "Flame Breath" + }, + "tell": { + "en": "At mid range it lowers its head and breathes a stream of flames." + }, + "effect": { + "en": "The flames are slower and hurt noticeably, and push you away when close." + }, + "counter": { + "en": "Strafe aside, or move closer or farther than its breath range." + } + }, + { + "id": "eidolon_lightning", + "name": { + "en": "Roar Lightning" + }, + "tell": { + "en": "The serpent throws back its head and roars, the sky darkens, and lightning strikes random spots." + }, + "effect": { + "en": "A direct strike is nearly fatal; positions are random." + }, + "counter": { + "en": "During the roar head to a corner away from the centre and do not stand still." + } + }, + { + "id": "eidolon_grow", + "name": { + "en": "Growth" + }, + "tell": { + "en": "After the small form is beaten the sky darkens, the ground shakes and the serpent swells." + }, + "effect": { + "en": "Standing close during growth pushes you away and hurts you steadily." + }, + "counter": { + "en": "Back off during growth and attack after the roar." + } + } + ], + "phases": [ + { + "en": "Small form: unkillable; enough damage makes it fake a collapse." + }, + { + "en": "Large form with the orb intact: the serpent cannot die; breaking the orb is the only way ahead." + }, + { + "en": "After the orb breaks, the real fight begins and it can be killed." + } + ] + }, + { + "case_id": "hexen2/star_volley_sorcerer", + "boss": { + "en": "Star Volley Sorcerer" + }, + "summary": { + "en": "A tall sorcerer casting in an open hall: star bolts at range, fire pillars under your feet, fire walls and an arena-wide storm; he also teleports and blocks shots with a shield. Each time his health drops another step he becomes briefly invulnerable and recharges." + }, + "moves": [ + { + "id": "praevus_star", + "name": { + "en": "Triple Star Bolt" + }, + "tell": { + "en": "He points at you and a 'triple star bolt' cue appears on screen, firing almost immediately" + }, + "effect": { + "en": "Three star bolts fly at you in a narrow fan and hurt on hit; they only spark against walls" + }, + "counter": { + "en": "Strafe through a gap in the fan or duck behind a pillar" + } + }, + { + "id": "praevus_pillar", + "name": { + "en": "Fire Pillar" + }, + "tell": { + "en": "A 'fire pillar' marker appears under your feet and the pillar rises about 0.2 s later" + }, + "effect": { + "en": "A pillar of fire erupts where you stand and hurts while you are inside it" + }, + "counter": { + "en": "Move away the moment the marker appears under you" + } + }, + { + "id": "praevus_firewall", + "name": { + "en": "Fire Wall" + }, + "tell": { + "en": "He charges for about 1.6 s with a 'fire wall' cue on screen" + }, + "effect": { + "en": "He releases a wall of fire that sweeps across the arena at you and hurts on contact" + }, + "counter": { + "en": "Get sideways out of its path while he is still charging" + } + }, + { + "id": "praevus_conjure", + "name": { + "en": "Summon Storm" + }, + "tell": { + "en": "He raises his hands with a 'summon storm' cue and a storm forms over the middle of the arena" + }, + "effect": { + "en": "The storm covers a large area and keeps striking anyone inside it, each bolt hurting a lot" + }, + "counter": { + "en": "Run to the edge of the storm or into a corner quickly" + } + }, + { + "id": "praevus_teleport", + "name": { + "en": "Teleport" + }, + "tell": { + "en": "He spins faster and shrinks with a 'teleport' cue, then vanishes" + }, + "effect": { + "en": "He reappears a few seconds later at another teleport point in the arena" + }, + "counter": { + "en": "Use the gap to pick up supplies and reposition, then turn to find where he reappears" + } + }, + { + "id": "praevus_shield", + "name": { + "en": "Shield" + }, + "tell": { + "en": "Six shield plates circle around him" + }, + "effect": { + "en": "The plates block your shots; each can be shattered and does not regrow" + }, + "counter": { + "en": "Break the plates between you and him first" + } + } + ], + "phases": [ + { + "en": "At the start he spins and slows down; he can only be hurt once he has turned to face you" + }, + { + "en": "Each time he loses another fifth of his health he goes invulnerable for about 6 s to recharge (no healing), then follows with a fire wall" + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/hollowknight_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/hollowknight_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..91fb5d1c0b386d9b9a74d4678d20b60f9bba4314 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/hollowknight_remake.json @@ -0,0 +1,993 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "hollowknight_remake", + "rules": "hk-arena-20261103-r5", + "title": { + "en": "Side-View Blade Boss Fights" + }, + "dimension": "2d", + "view": { + "en": "Side-view 2D: a cloaked swordsman stands in a closed room facing a boss. Your health points and energy are shown at the top or corner of the screen, and the boss's health bar at the top" + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose when your health points reach zero; each fight has a time limit and a timeout is not a win. Health does not regenerate by itself; you must build energy by hitting the boss and then channel healing" + }, + "mouse": { + "kind": "none", + "en": "" + }, + "keys": [ + { + "key": "W", + "en": "hold to slash upward; used with the slash button" + }, + { + "key": "A", + "en": "move left" + }, + { + "key": "S", + "en": "hold in the air and slash to strike downward; hitting the boss or a bounceable attack bounces you up (pogo)" + }, + { + "key": "D", + "en": "move right" + }, + { + "key": "Space", + "en": "jump: hold for height, release to cut it short" + }, + { + "key": "Shift", + "en": "dash: once per air time, about 0.6 s cooldown" + }, + { + "key": "J", + "en": "slash" + }, + { + "key": "LMB", + "en": "slash (same as J)" + }, + { + "key": "K", + "en": "hold on the ground to heal: standing still for about 1.1 s spends 33 energy for 1 health" + } + ], + "notes": [ + { + "en": "Each hit on the boss stores 11 energy; healing needs 33 and takes about 1.1 s holding K on the ground; moving, leaving the ground or being hit cancels it" + }, + { + "en": "Side slashes alternate between two swings, resetting after 0.5 s; slashes have about a 0.41 s cooldown" + }, + { + "en": "Early presses are buffered: jump about 0.04 s, slash about 0.1 s, dash about 0.2 s" + }, + { + "en": "A downward hit on the boss or a bounceable attack bounces you up and refreshes the air dash (not the dash cooldown), so you can chain pogos" + }, + { + "en": "You cannot dash during the first 0.1 s of a slash" + }, + { + "en": "Each boss's stagger (collapsing when pressured) is the time to deal concentrated damage" + } + ], + "compact_glossary": { + "move": { + "en": "left/right movement", + "options": { + "none": "stand still", + "left": "walk left, whole packet", + "right": "walk right, whole packet", + "left_tap": "tap left once at sub-step 1 (to turn around)", + "right_tap": "tap right once at sub-step 1 (to turn around)" + } + }, + "jump": { + "en": "jumping", + "options": { + "none": "do not jump", + "hold": "hold jump for the whole packet (high jump; only starts if jump was not held at the end of the previous packet)", + "press2_hold": "press jump at sub-step 2 and hold (use after holding jump in the previous packet)", + "tap1": "short hop, tap at sub-step 1", + "tap2": "short hop, tap at sub-step 2", + "tap3": "short hop, tap at sub-step 3", + "tap4": "short hop, tap at sub-step 4", + "tap5": "short hop, tap at sub-step 5", + "tap6": "short hop, tap at sub-step 6" + } + }, + "action": { + "en": "slash / dash / heal", + "options": { + "none": "do not attack", + "down_1": "downward slash, repeated presses from sub-step 1 (air only)", + "down_2": "downward slash, repeated presses from sub-step 2 (air only)", + "down_3": "downward slash, repeated presses from sub-step 3 (air only)", + "down_4": "downward slash, repeated presses from sub-step 4 (air only)", + "down_5": "downward slash, repeated presses from sub-step 5 (air only)", + "down_6": "downward slash, repeated presses from sub-step 6 (air only)", + "slash_101010": "side slash, press timing 101010", + "slash_010101": "side slash, press timing 010101", + "slash_100000": "side slash, press timing 100000", + "slash_010000": "side slash, press timing 010000", + "slash_001010": "side slash, press timing 001010", + "slash_000101": "side slash, press timing 000101", + "slash_000010": "side slash, press timing 000010", + "slash_000001": "side slash, press timing 000001", + "up_1": "upward slash, press timing 101010", + "up_2": "upward slash, press timing 010101", + "up_3": "upward slash, press timing 100000", + "up_5": "upward slash, press timing 000010", + "dash": "dash at sub-steps 1-2", + "dash_mid": "dash at sub-step 4 (pair with a jump for an air dash)", + "heal": "channel healing, held the whole packet (stand still on the ground)" + } + } + }, + "scenes": [ + { + "case_id": "2d/hollow_vessel", + "boss": { + "en": "Orange-Ooze Berserker" + }, + "summary": { + "en": "A closed room duel against a blade-wielding berserker who dashes, leaps, and pours orange ooze from the walls and roof." + }, + "moves": [ + { + "id": "dash", + "name": { + "en": "Dash" + }, + "tell": { + "en": "Steps back and crouches with the blade drawn back, then crosses most of the room in one dash" + }, + "effect": { + "en": "Contact damage along the ground" + }, + "counter": { + "en": "Jump over it or stay clear; the 0.25 s recovery after the dash is your opening" + } + }, + { + "id": "air_dash", + "name": { + "en": "Air dash" + }, + "tell": { + "en": "Jumps and hangs in the air with the blade drawn, then dashes at head height" + }, + "effect": { + "en": "Dashes sideways at head height; contact hurts" + }, + "counter": { + "en": "Stay low, out of its height line; it falls after the dash with about 0.25 s of recovery to punish" + } + }, + { + "id": "jump", + "name": { + "en": "Leap" + }, + "tell": { + "en": "Crouches, then jumps to a random point in the room" + }, + "effect": { + "en": "Landing on you hurts" + }, + "counter": { + "en": "Move off the landing point; it has about 0.17 s of landing recovery" + } + }, + { + "id": "downstab", + "name": { + "en": "Plunge stab" + }, + "tell": { + "en": "Jumps over you, hangs with the blade pointing down, then plunges and splashes four blobs along the floor" + }, + "effect": { + "en": "The plunge and the blobs both hurt" + }, + "counter": { + "en": "Leave the landing spot and jump the blobs; the roughly 0.9 s of recovery after landing is your opening" + } + }, + { + "id": "overhead", + "name": { + "en": "Overhead flail" + }, + "tell": { + "en": "Raises the blade and flails it over its head while you are above it" + }, + "effect": { + "en": "Hits you when you are above it" + }, + "counter": { + "en": "Do not hover above it; about 0.17 s of recovery afterwards" + } + }, + { + "id": "evade", + "name": { + "en": "Hop back" + }, + "tell": { + "en": "Hops backwards away from a close player" + }, + "effect": { + "en": "Not an attack, but often leads into one" + }, + "counter": { + "en": "Do not chase; anticipate the follow-up" + } + }, + { + "id": "cascade", + "name": { + "en": "Ooze cascade" + }, + "tell": { + "en": "Jumps to the middle and shakes; orange blobs pour from both walls and the roof for about four seconds" + }, + "effect": { + "en": "Falling blobs hurt on contact" + }, + "counter": { + "en": "Weave through gaps between blobs; do not stand under falling ones" + } + }, + { + "id": "balloon", + "name": { + "en": "Balloons" + }, + "tell": { + "en": "Once its health bar is below about four fifths, balloons drift in every 4-5 seconds and chase you" + }, + "effect": { + "en": "Balloons that reach you hurt" + }, + "counter": { + "en": "One strike pops them; do not let them pile up" + } + } + ], + "phases": [ + { + "en": "Below about four fifths health, chasing balloons are added." + } + ] + }, + { + "case_id": "2d/iron_bulwark", + "boss": { + "en": "Iron-Bell Mace Soldier" + }, + "summary": { + "en": "A heavily armoured mace soldier hunts you on flat ground while barrels drop from the roof." + }, + "moves": [ + { + "id": "leap", + "name": { + "en": "Leap" + }, + "tell": { + "en": "Crouches with the mace on its shoulder, then leaps toward you (half of the leaps go to a random spot)" + }, + "effect": { + "en": "Landing on you hurts" + }, + "counter": { + "en": "Step away from the landing; about 0.5 s of landing recovery is your opening" + } + }, + { + "id": "bludgeon", + "name": { + "en": "Bludgeon" + }, + "tell": { + "en": "Leaps with the mace raised and brings it down in front of it on landing" + }, + "effect": { + "en": "Slams in front of it; the area hurts" + }, + "counter": { + "en": "Stay out of the front of its landing; about 0.25 s of recoil after the slam" + } + }, + { + "id": "smash", + "name": { + "en": "Wind-up smash" + }, + "tell": { + "en": "Jumps back, then winds the mace far behind its head for over a second" + }, + "effect": { + "en": "The smash sends a shockwave along the floor" + }, + "counter": { + "en": "Jump the shockwave; about 0.42 s of recovery after the smash" + } + }, + { + "id": "charge", + "name": { + "en": "Charge" + }, + "tell": { + "en": "When you are far away it runs at you and follows up with the leaping slam" + }, + "effect": { + "en": "Both the run and the slam hurt" + }, + "counter": { + "en": "Do not stay far away; jump the run, then dodge the slam" + } + }, + { + "id": "rage", + "name": { + "en": "Rage slams" + }, + "tell": { + "en": "After the exposed rider is beaten back into the armour, it jumps to the middle and slams left and right" + }, + "effect": { + "en": "Slams the floor on both sides in succession" + }, + "counter": { + "en": "Move and jump in the gaps between slams" + } + }, + { + "id": "barrel", + "name": { + "en": "Falling barrel" + }, + "tell": { + "en": "Dust trickles from the roof where a barrel is about to drop" + }, + "effect": { + "en": "The barrel hurts if it lands on you" + }, + "counter": { + "en": "Leave the spot as soon as dust appears" + } + } + ], + "phases": [ + { + "en": "When the armour breaks an exposed rider appears; beating it back into the armour triggers the rage slams." + } + ] + }, + { + "case_id": "2d/lumen_moth", + "boss": { + "en": "Four-Winged Sword Wielder" + }, + "summary": { + "en": "A glowing four-winged boss fills the arena with light orbs, sword patterns and beams; later the floor turns into an abyss." + }, + "moves": [ + { + "id": "orbs", + "name": { + "en": "Light orbs" + }, + "tell": { + "en": "Her core flares and up to three orbs of light peel away from her, then home in" + }, + "effect": { + "en": "Orbs deal 2 damage on contact" + }, + "counter": { + "en": "Lead them into the floor or a wall so they burst" + } + }, + { + "id": "sword_burst", + "name": { + "en": "Sword ring" + }, + "tell": { + "en": "Twelve swords stand in a ring around her, points outward" + }, + "effect": { + "en": "Swords shoot outward and deal 2 damage" + }, + "counter": { + "en": "Stand between two swords' lines; farther away is safer" + } + }, + { + "id": "sword_rain", + "name": { + "en": "Sword rain" + }, + "tell": { + "en": "Rows of swords hang along the ceiling, points down, with two wide gaps" + }, + "effect": { + "en": "Swords fall and deal 2 damage" + }, + "counter": { + "en": "Stand under a gap; she teleports half-way through" + } + }, + { + "id": "sword_wall", + "name": { + "en": "Sword wall" + }, + "tell": { + "en": "A column of swords forms along one side wall, with one gap open at the floor or at full-jump height" + }, + "effect": { + "en": "The wall sweeps across, dealing 2 damage" + }, + "counter": { + "en": "Stand in a floor gap; for a high gap, jump as it arrives" + } + }, + { + "id": "beam_burst", + "name": { + "en": "Beam burst" + }, + "tell": { + "en": "Thin lines of light spread from her in eight directions" + }, + "effect": { + "en": "Beams deal 2 damage" + }, + "counter": { + "en": "Stand between two lines; the next burst turns half a step" + } + }, + { + "id": "beam_sweep", + "name": { + "en": "Beam sweep" + }, + "tell": { + "en": "Light gathers along one side wall" + }, + "effect": { + "en": "A wall of light sweeps the arena for 2 damage" + }, + "counter": { + "en": "Run to the far end; it fades just short of the far wall" + } + }, + { + "id": "spikes", + "name": { + "en": "Floor spikes" + }, + "tell": { + "en": "One half of the floor glows, then spikes rise there" + }, + "effect": { + "en": "Spikes deal 1 damage" + }, + "counter": { + "en": "Stand on the other half" + } + }, + { + "id": "abyss", + "name": { + "en": "Abyss" + }, + "tell": { + "en": "After the stagger the floor darkens into an abyss between four pale footholds" + }, + "effect": { + "en": "Falling into the abyss deals 1 damage" + }, + "counter": { + "en": "Stay on the footholds and jump the gaps" + } + }, + { + "id": "big_beam", + "name": { + "en": "Big beam" + }, + "tell": { + "en": "A thin line of light drops where you stand" + }, + "effect": { + "en": "The light pillar deals 2 damage" + }, + "counter": { + "en": "Step aside; after the third beam she sinks within reach and one strike ends her" + } + }, + { + "id": "teleport", + "name": { + "en": "Teleport" + }, + "tell": { + "en": "She dissolves into light and re-forms elsewhere" + }, + "effect": { + "en": "No direct damage" + }, + "counter": { + "en": "Re-locate her; do not chase blindly" + } + }, + { + "id": "scream", + "name": { + "en": "Scream" + }, + "tell": { + "en": "She screams and the arena changes" + }, + "effect": { + "en": "No direct damage, but marks a phase change" + }, + "counter": { + "en": "Use the moment to reposition for the new arena" + } + } + ], + "phases": [ + { + "en": "After a stagger the arena becomes an abyss with footholds; after the last big beams she sinks low and can be finished with one strike." + } + ] + }, + { + "case_id": "2d/needle_warden", + "boss": { + "en": "Green-Robed Lancer" + }, + "summary": { + "en": "An agile green-robed fighter attacks with a spear, dashes and whirlwinds; her pause after throwing gives you an opening." + }, + "moves": [ + { + "id": "g_dash", + "name": { + "en": "Ground dash" + }, + "tell": { + "en": "Crouches low facing you with the spear drawn back" + }, + "effect": { + "en": "Contact damage during the dash" + }, + "counter": { + "en": "Jump over her and pogo; she slides to a stop for about 0.33 s" + } + }, + { + "id": "a_dash", + "name": { + "en": "Aerial dash" + }, + "tell": { + "en": "Jumps, then freezes mid-air and aims at your feet; the aim is locked when the freeze starts" + }, + "effect": { + "en": "Dives along the locked line" + }, + "counter": { + "en": "Move once she freezes; the 0.5 s hard landing is your opening" + } + }, + { + "id": "throw", + "name": { + "en": "Spear throw" + }, + "tell": { + "en": "Rears back with the spear; always thrown horizontally" + }, + "effect": { + "en": "The spear flies horizontally and hurts on its way out and back" + }, + "counter": { + "en": "Jump it; she stands still until the spear returns (about 1 s), so attack her then" + } + }, + { + "id": "g_sphere", + "name": { + "en": "Ground whirlwind" + }, + "tell": { + "en": "Plants her feet while a whirlwind gathers around her" + }, + "effect": { + "en": "The whirlwind hurts when it bursts" + }, + "counter": { + "en": "Keep away from her; about 0.17 s of recovery after the burst" + } + }, + { + "id": "a_sphere", + "name": { + "en": "Aerial whirlwind" + }, + "tell": { + "en": "Stalls on the way down while a whirlwind gathers" + }, + "effect": { + "en": "The whirlwind hurts when it bursts" + }, + "counter": { + "en": "Go around; do not stand right below her" + } + }, + { + "id": "evade", + "name": { + "en": "Back-step" + }, + "tell": { + "en": "Short crouch, then a fast back-step when you are close" + }, + "effect": { + "en": "Not an attack" + }, + "counter": { + "en": "Do not chase; wait for her next move" + } + } + ], + "phases": [ + { + "en": "While she throws she stands still, and stagger does not accumulate during that time." + } + ] + }, + { + "case_id": "2d/pale_vessel", + "boss": { + "en": "Split-Chest Swordsman" + }, + "summary": { + "en": "A pale swordsman with a split chest and a huge move set: it teleports, counters and sprays orange blobs, and changes forms as its health drops." + }, + "moves": [ + { + "id": "slash", + "name": { + "en": "Triple slash" + }, + "tell": { + "en": "Plants the blade behind its shoulder, then three wide swings stepping forward; the 2nd and 3rd also reach behind it" + }, + "effect": { + "en": "All three swings have a wide reach" + }, + "counter": { + "en": "Back off or jump; about 0.33 s of recovery after the third swing" + } + }, + { + "id": "dash", + "name": { + "en": "Lunge dash" + }, + "tell": { + "en": "Crouches with the blade pointed forward, then lunges along the ground" + }, + "effect": { + "en": "Contact damage along the ground" + }, + "counter": { + "en": "Jump it; it slides to a stop for about 0.45 s, your opening" + } + }, + { + "id": "counter", + "name": { + "en": "Counter stance" + }, + "tell": { + "en": "Raises the blade; when it shines, a frontal hit is blocked and answered by a fast sliding riposte" + }, + "effect": { + "en": "Hitting the front gets you riposted" + }, + "counter": { + "en": "Do not hit the front while the blade shines; it lowers the guard after about 0.75 s" + } + }, + { + "id": "evade", + "name": { + "en": "Hop back" + }, + "tell": { + "en": "Hops backwards away from a close player, often straight into another attack" + }, + "effect": { + "en": "Not an attack itself" + }, + "counter": { + "en": "Anticipate the follow-up on landing" + } + }, + { + "id": "jump", + "name": { + "en": "Leap" + }, + "tell": { + "en": "Crouches and leaps across the room" + }, + "effect": { + "en": "Landing on you hurts" + }, + "counter": { + "en": "Dodge the landing; about 0.33 s of landing recovery" + } + }, + { + "id": "tele", + "name": { + "en": "Teleport" + }, + "tell": { + "en": "Fades out and reappears at a distance (or high above you) ready to attack" + }, + "effect": { + "en": "Attacks right after reappearing" + }, + "counter": { + "en": "Watch where it appears and prepare to dodge" + } + }, + { + "id": "dstab", + "name": { + "en": "Plunge stab" + }, + "tell": { + "en": "Leaps (or teleports) above you, hangs with the blade pointing down, then slams into the floor" + }, + "effect": { + "en": "The slam hurts and the pillars burst" + }, + "counter": { + "en": "Leave the spot; it stands for about 1.1 s after landing while the pillars burst" + } + }, + { + "id": "plume", + "name": { + "en": "Fire columns" + }, + "tell": { + "en": "Orange glows spread across the floor from where it landed; columns of fire shoot up from every glow at once" + }, + "effect": { + "en": "Fire columns deal 2 damage" + }, + "counter": { + "en": "Stand in the gaps between glows, or jump" + } + }, + { + "id": "barrage", + "name": { + "en": "Blob barrage" + }, + "tell": { + "en": "Opens its cloak and sprays 9-10 blobs in a sweeping arc over about three quarters of the room" + }, + "effect": { + "en": "Blobs hurt on contact" + }, + "counter": { + "en": "Find gaps or the uncovered side; about 0.36 s of recovery" + } + }, + { + "id": "outbreak", + "name": { + "en": "Chest outbreak" + }, + "tell": { + "en": "Rises to the middle of the room and blobs burst out of its chest in arcs to both sides and downward" + }, + "effect": { + "en": "Blobs hurt on contact" + }, + "counter": { + "en": "Slip between the arcs; it can be hit from below the whole time, including its fall" + } + }, + { + "id": "puppet", + "name": { + "en": "Puppet slams" + }, + "tell": { + "en": "Jerked up like a puppet, it floats after you and slams down 2-5 times" + }, + "effect": { + "en": "Each slam hurts" + }, + "counter": { + "en": "Sidestep each slam; after the last it collapses for about 1.6 s" + } + }, + { + "id": "self_stab", + "name": { + "en": "Self stab" + }, + "tell": { + "en": "Turns the blade on itself and stabs its own chest; hits only deal 1 meanwhile, then it collapses" + }, + "effect": { + "en": "No direct attack on you" + }, + "counter": { + "en": "Save your damage for the full stagger after the collapse (about 2.25 s)" + } + }, + { + "id": "weak_slash", + "name": { + "en": "Weak slash" + }, + "tell": { + "en": "Staggers toward you, raises the blade for one swing and falls to its knees" + }, + "effect": { + "en": "One swing" + }, + "counter": { + "en": "Dodge the swing; it kneels for a full stagger of about 2.25 s" + } + }, + { + "id": "roar", + "name": { + "en": "Roar" + }, + "tell": { + "en": "Screams at each phase change" + }, + "effect": { + "en": "No direct damage; marks a phase change" + }, + "counter": { + "en": "Use it to reposition" + } + } + ], + "phases": [ + { + "en": "As health drops it changes form and uses moves such as self stab and weak slash, each phase change marked by a roar." + } + ] + }, + { + "case_id": "2d/sickle_sisters", + "boss": { + "en": "Triple Lancers" + }, + "summary": { + "en": "Three lance fighters take turns attacking with dashes, plunges, boomerang blades and two-person combos." + }, + "moves": [ + { + "id": "dash", + "name": { + "en": "Floor-crossing dash" + }, + "tell": { + "en": "Appears crouched at one end of the floor with the lance drawn back, then crosses the whole floor" + }, + "effect": { + "en": "The whole floor is the damage path" + }, + "counter": { + "en": "Jump it; it stands at the far end for about 0.63 s, your opening" + } + }, + { + "id": "dstab", + "name": { + "en": "Plunge stab" + }, + "tell": { + "en": "Appears high above you pointing the lance down, then drops straight onto the floor" + }, + "effect": { + "en": "Drops straight on you" + }, + "counter": { + "en": "Move sideways when it appears; about 0.67 s of landing pose" + } + }, + { + "id": "throw", + "name": { + "en": "Blade throw" + }, + "tell": { + "en": "Clings to a side wall high (blade will sink) or low (blade will rise) and winds up a throw" + }, + "effect": { + "en": "Throws a boomerang blade" + }, + "counter": { + "en": "Anticipate the rise or sink; she hangs on the wall about 1.2 s after the throw, so strike then" + } + }, + { + "id": "blade", + "name": { + "en": "Spinning blade" + }, + "tell": { + "en": "A spinning blade crosses the room, slows, and flies back to the thrower" + }, + "effect": { + "en": "Hurts both going and returning" + }, + "counter": { + "en": "Jump it and watch for the return" + } + }, + { + "id": "high_throw", + "name": { + "en": "High throw" + }, + "tell": { + "en": "When you hug a wall, a fighter appears on the far wall at your height and throws" + }, + "effect": { + "en": "Throws a blade at your height" + }, + "counter": { + "en": "Do not hug the wall; move up or down off the line" + } + }, + { + "id": "duo", + "name": { + "en": "Duo combo" + }, + "tell": { + "en": "Two fighters at once: dash + plunge combos, a pincer dash from both ends, or blades from both walls" + }, + "effect": { + "en": "Attacks from two directions at once" + }, + "counter": { + "en": "Read both positions first; jump in the gap between the two attacks" + } + } + ], + "phases": [ + { + "en": "As health drops, the fight goes from one fighter at a time to two at once, and finally only one remains." + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/isaac_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/isaac_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..10a1ecc2811396ae15d2876adc6666b5498a5366 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/isaac_remake.json @@ -0,0 +1,534 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "isaac_remake", + "rules": "isaac-basement@3", + "title": { + "en": "Tear Kid: Basement Boss Rooms" + }, + "dimension": "2d", + "view": { + "en": "Top-down 2D sealed boss room shown on one screen, possibly with rocks inside. You control a bald child, the Tear Kid, with twin-stick controls: one set of keys moves, another set shoots tears in four directions. Your hearts (half-heart steps) are at the top left and the boss's health bar is at the top" + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose when all your hearts are gone; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate. A versus banner shows at the start and the boss only starts acting after about 1.3 seconds" + }, + "mouse": { + "kind": "none", + "en": "The mouse is not used" + }, + "keys": [ + { + "key": "W", + "en": "move up (eight directions, with inertia)" + }, + { + "key": "A", + "en": "move left" + }, + { + "key": "S", + "en": "move down" + }, + { + "key": "D", + "en": "move right" + }, + { + "key": "J", + "en": "hold to shoot tears left" + }, + { + "key": "K", + "en": "hold to shoot tears down" + }, + { + "key": "L", + "en": "hold to shoot tears right" + }, + { + "key": "Shift", + "en": "hold to shoot tears up" + }, + { + "key": "E", + "en": "place a bomb: you start with only 1; it deals big damage but costs you a whole heart if it hits you" + } + ], + "notes": [ + { + "en": "Moving and shooting are independent: you can retreat left while shooting right. When several shoot keys are held only the most recent direction counts, so hold one at a time" + }, + { + "en": "Tears only go in four directions with no aiming; to hit the boss, line yourself up with its row or column, and tears have limited range" + }, + { + "en": "After a hit you are invulnerable for a while (about 1 second for half a heart, about 2 seconds for a full heart) and are pushed away; you cannot be hurt during it" + }, + { + "en": "Most contact and small shots cost half a heart; large tears and your own bomb cost a full heart; at high difficulty half-heart hits also become full hearts. At zero health you fall and lose after about a second" + }, + { + "en": "You carry a fixed set of passive upgrades (fire rate, damage, range, special tears such as multi-shot, piercing, homing, bouncing) that apply automatically; there is no active item to use" + }, + { + "en": "The bomb is a one-off burst of heavy damage; save it for when the boss is close, and step away yourself" + } + ], + "compact_glossary": { + "move": { + "en": "eight-direction movement with WASD held for the whole 200 ms", + "options": { + "none": "stand still", + "up": "walk up", + "up_right": "walk up-right", + "right": "walk right", + "down_right": "walk down-right", + "down": "walk down", + "down_left": "walk down-left", + "left": "walk left", + "up_left": "walk up-left" + } + }, + "fire": { + "en": "shoot tears in one of four directions, held for the whole 200 ms", + "options": { + "none": "do not shoot", + "up": "shoot up", + "down": "shoot down", + "left": "shoot left", + "right": "shoot right" + } + }, + "bomb": { + "en": "place the single starting bomb", + "options": { + "none": "no bomb", + "place": "place a bomb under you" + } + } + }, + "scenes": [ + { + "case_id": "isaac/monstro", + "boss": { + "en": "Hopping Blob" + }, + "summary": { + "en": "A huge blob in an open room that hops at you, spits shot spreads and leaps to crash down on you. It is dangerous up close, so keep your distance and circle while shooting" + }, + "moves": [ + { + "id": "hop", + "name": { + "en": "Small hops" + }, + "tell": { + "en": "It crouches briefly, then hops, 1 to 3 times in a row" + }, + "effect": { + "en": "It lands toward where you were at takeoff; it is harmless in the air, and its body costs half a heart on contact after landing" + }, + "counter": { + "en": "Sidestep the landing spot and shoot it during its short pause after landing" + } + }, + { + "id": "spit", + "name": { + "en": "Spit spread" + }, + "tell": { + "en": "Its cheeks puff up, then about half a second later it fires a fan of shots at once" + }, + "effect": { + "en": "A scattered fan aimed toward you with varied speeds and ranges; most are small shots costing half a heart, a few are big tears costing a full heart" + }, + "counter": { + "en": "While it puffs, move sideways into a gap of the fan, or back off so the shots spread out" + } + }, + { + "id": "slam", + "name": { + "en": "Leap slam" + }, + "tell": { + "en": "It crouches deep and leaps up off the screen; a shadow follows you on the ground, then locks as a red dashed circle" + }, + "effect": { + "en": "Anything inside the circle is hurt when it lands, then it sprays a ring of shots outward" + }, + "counter": { + "en": "Run out of the circle once it locks, then dodge the ring and shoot after landing" + } + } + ], + "phases": [] + }, + { + "case_id": "isaac/larry_jr", + "boss": { + "en": "Segment Worm" + }, + "summary": { + "en": "A long worm made of many segments that crawls along the grid in right-angle turns, leaving dung piles behind. Every segment can be shot, and cutting it splits it in two" + }, + "moves": [ + { + "id": "crawl", + "name": { + "en": "Grid crawl" + }, + "tell": { + "en": "The head advances along the grid centre lines and the body segments follow its path" + }, + "effect": { + "en": "Any segment touching you costs half a heart; it has no ranged attack" + }, + "counter": { + "en": "Stand in a row or column it will not turn into, and shoot approaching segments from the side" + } + }, + { + "id": "chase_turn", + "name": { + "en": "Turning toward you" + }, + "tell": { + "en": "At a grid centre the head may suddenly turn toward your row or column" + }, + "effect": { + "en": "Changes its route and heads straight at you" + }, + "counter": { + "en": "Do not stay on one row or column for long; keep moving and leave an escape route" + } + }, + { + "id": "dung", + "name": { + "en": "Dung piles" + }, + "tell": { + "en": "A dung pile appears on the cell behind its tail" + }, + "effect": { + "en": "Piles block the way; the worm smashes one and turns when it hits it, and piles also block your movement and tears" + }, + "counter": { + "en": "Use piles to force turns, and do not trap yourself between a pile and a wall" + } + }, + { + "id": "split", + "name": { + "en": "Cut and split" + }, + "tell": { + "en": "After you kill a middle segment, the worm breaks into two that crawl on separately" + }, + "effect": { + "en": "If both parts are long enough they become two separate worms; if the head dies the next segment becomes the new head" + }, + "counter": { + "en": "Shoot the nearest segments first and watch for two heads chasing you at once" + } + } + ], + "phases": [ + { + "en": "At higher difficulty the worm is longer, faster and turns toward you more often" + } + ] + }, + { + "case_id": "isaac/duke_of_flies", + "boss": { + "en": "Swarm Host" + }, + "summary": { + "en": "A big bug body drifting diagonally and bouncing off walls, constantly releasing flies. Flies orbit it to block shots or chase you; you must clear all flies and the body" + }, + "moves": [ + { + "id": "drift", + "name": { + "en": "Diagonal drift" + }, + "tell": { + "en": "The body moves slowly on a diagonal and bounces off walls; tears nudge it along their direction" + }, + "effect": { + "en": "Body contact costs half a heart" + }, + "counter": { + "en": "Read its diagonal and shoot from a line not covered by flies" + } + }, + { + "id": "summon_orbit", + "name": { + "en": "Summon orbiting flies" + }, + "tell": { + "en": "Its body swells for about 0.4 seconds, then three flies appear circling it" + }, + "effect": { + "en": "Orbiting flies block tears aimed at the body; they are sturdy, and a fly costs half a heart on touching you and then dies" + }, + "counter": { + "en": "Shoot down some orbiters before the body, and do not let them pile up to four or five" + } + }, + { + "id": "big_fly", + "name": { + "en": "Big fly" + }, + "tell": { + "en": "The same swelling tell, then a larger fly appears and chases you" + }, + "effect": { + "en": "The big fly chases you and costs half a heart on contact" + }, + "counter": { + "en": "Retreat while shooting it down" + } + }, + { + "id": "release", + "name": { + "en": "Swarm release" + }, + "tell": { + "en": "When five or six orbit it, it swells and they all break away at once" + }, + "effect": { + "en": "All orbiting flies turn into chasers at the same time" + }, + "counter": { + "en": "Break up the orbiters beforehand, or keep distance and shoot them down piece by piece" + } + } + ], + "phases": [ + { + "en": "When the body dies, remaining orbiters turn into chasers; you only win after every fly is dead" + } + ] + }, + { + "case_id": "isaac/gemini", + "boss": { + "en": "Tethered Pair" + }, + "summary": { + "en": "A large and a small body joined by a cord: the big one chases and charges, the small one trails behind and shoots at you. Four symmetric rocks serve as cover" + }, + "moves": [ + { + "id": "big_chase", + "name": { + "en": "Big one chases" + }, + "tell": { + "en": "The big one walks slowly toward you" + }, + "effect": { + "en": "Touching its body at the feet costs half a heart" + }, + "counter": { + "en": "Circle around the rocks and shoot from a distance" + } + }, + { + "id": "big_charge", + "name": { + "en": "Big one charge" + }, + "tell": { + "en": "After chasing for a while it suddenly speeds up and rushes at you, turning only slowly" + }, + "effect": { + "en": "A high-speed hit costs half a heart; after hitting a rock or finishing it stops to pant for a moment" + }, + "counter": { + "en": "Sidestep or hide behind a rock when the charge starts, and pour damage in while it pants" + } + }, + { + "id": "small_shot", + "name": { + "en": "Small one's shot" + }, + "tell": { + "en": "The small one pauses to charge for about 0.3 seconds; it does not shoot when a rock blocks the line" + }, + "effect": { + "en": "Fires one shot at you, costing half a heart" + }, + "counter": { + "en": "Move during the charge and use rocks for cover" + } + }, + { + "id": "small_rush", + "name": { + "en": "Freed small one rush" + }, + "tell": { + "en": "After the big one dies, the small one breaks free and accelerates at you with heavy inertia, overshooting" + }, + "effect": { + "en": "Contact costs half a heart; being hit by tears actually speeds it up" + }, + "counter": { + "en": "Circle it, and shoot from the side or behind after it overshoots" + } + } + ], + "phases": [ + { + "en": "Killing the big one first frees the small one to rush; killing the small one first leaves the big one unchanged" + } + ] + }, + { + "case_id": "isaac/famine", + "boss": { + "en": "Charging Rider" + }, + "summary": { + "en": "A horse and rider that charge along horizontal lanes and summon shot-spitting flies. At low health only a head remains and creeps toward you. Contact costs a full heart in both phases" + }, + "moves": [ + { + "id": "charge", + "name": { + "en": "Lane charge" + }, + "tell": { + "en": "When you stand in the red horizontal lane at its level it rears for about half a second, then dashes across the screen and returns from the other side" + }, + "effect": { + "en": "Hitting you costs a full heart, and it also crushes the flies" + }, + "counter": { + "en": "Avoid staying in its lane; move up or down out of the red lane when it rears" + } + }, + { + "id": "summon_fly", + "name": { + "en": "Summon spitting flies" + }, + "tell": { + "en": "It stops for a summoning pose of about half a second and a fly appears beside it" + }, + "effect": { + "en": "The fly drifts slowly toward you and, at close range, charges and spits one shot costing half a heart; it does no contact damage and at most 2 exist" + }, + "counter": { + "en": "Shoot the flies first, or lure the rider into charging through them" + } + }, + { + "id": "align", + "name": { + "en": "Line up and retreat" + }, + "tell": { + "en": "When the flies are at the limit it moves to your row and backs to the far end" + }, + "effect": { + "en": "Sets up the next lane charge" + }, + "counter": { + "en": "Change rows as soon as you see it line up" + } + }, + { + "id": "head_fan", + "name": { + "en": "Head triple shot" + }, + "tell": { + "en": "In the second phase only the head creeps closer, stops for about 0.4 seconds, then fires" + }, + "effect": { + "en": "Fires a three-shot fan toward you" + }, + "counter": { + "en": "Step sideways when it stops, and shoot it between volleys" + } + } + ], + "phases": [ + { + "en": "At low health the horse and body burst apart, leaving only a head that approaches and fires triple shots; no more lane charges" + } + ] + }, + { + "case_id": "isaac/envy", + "boss": { + "en": "Splitting Head" + }, + "summary": { + "en": "A big head always flies on 45-degree diagonals and bounces off walls. Each time it dies it splits into two smaller, faster heads, for three generations, so more and more heads fill the room" + }, + "moves": [ + { + "id": "bounce", + "name": { + "en": "Diagonal bounce" + }, + "tell": { + "en": "The head flies diagonally and bounces off walls, sometimes bouncing toward you" + }, + "effect": { + "en": "Contact costs half a heart; no ranged attack" + }, + "counter": { + "en": "Predict the diagonal path and shoot from outside it" + } + }, + { + "id": "home_in", + "name": { + "en": "Steering toward you" + }, + "tell": { + "en": "Every second or two its diagonal suddenly turns toward you at the same speed" + }, + "effect": { + "en": "A player standing still is easily hit" + }, + "counter": { + "en": "Do not stand in doorways or corners; keep moving and keep space around you" + } + }, + { + "id": "split", + "name": { + "en": "Split on death" + }, + "tell": { + "en": "When a head dies it becomes two smaller heads that fly apart" + }, + "effect": { + "en": "The smaller they are, the faster and harder to hit" + }, + "counter": { + "en": "Break the big head from far away so you have time to react to the small ones" + } + } + ], + "phases": [ + { + "en": "Three splits in total: big head into two medium, each into two small, each into two tiny ones; you win only when all are gone" + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/kirby_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/kirby_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..daac04e1fdfcfc40cafb76ed30ea6b7c74030b0e --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/kirby_remake.json @@ -0,0 +1,508 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "kirby_remake", + "rules": "kdl-bosses-2026-11-05-r8", + "title": { + "en": "Round Hero: Inhale-and-Spit Boss Fights" + }, + "dimension": "2d", + "view": { + "en": "Side-view 2D single-screen arena. You control a small round pink creature that walks, jumps, puffs up to float, inhales and spits stars; your health bars and the boss's name and health bar are shown at the top of the screen" + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose when your health bars run out; each fight has a time limit and a timeout is not a win. Health does not regenerate. After a hit you blink and are invulnerable for about 1.5 seconds" + }, + "mouse": { + "kind": "none", + "en": "The mouse is not used; LMB does the same as J" + }, + "keys": [ + { + "key": "A", + "en": "walk left (fly left in the airship fight)" + }, + { + "key": "D", + "en": "walk right (fly right in the airship fight)" + }, + { + "key": "W", + "en": "puff up and float and rise in the air; stops an inhale that pulls nothing; rises in the airship fight" + }, + { + "key": "S", + "en": "duck on the ground with an empty mouth; swallows a full mouthful; sinks in the airship fight" + }, + { + "key": "Space", + "en": "jump, higher the longer you hold; press again in the air to puff and float" + }, + { + "key": "J", + "en": "hold to inhale what is in front; with a full mouth press to spit a star; while floating press to blow a puff (harmless to bosses); in the airship fight press to blow an air bullet to the right" + }, + { + "key": "LMB", + "en": "same as J" + } + ], + "notes": [ + { + "en": "In the ground scenes only a spat star hurts the boss: first inhale something the boss throws (an apple, a walker, a bomb, a box), then spit it back at the boss. You cannot walk while inhaling; reach is about 5 units, about 2.5 units of vertical tolerance" + }, + { + "en": "The airship fight controls differ: you fly the whole fight, with no jumping or inhaling. A/D move horizontally and stop at once, W rises fast, S sinks slower, and with neither you hang in the air; you always face right, and each J/LMB press blows one air bullet to the right (about one every 0.25 s, at most two in the air). Stay on the left of the airship to hit it" + }, + { + "en": "J and jump trigger on the press: inhale, spit, jump and puff all start the moment the key goes down; holding J keeps inhaling and holding Space makes the jump higher" + }, + { + "en": "Pressing J while floating blows a puff and ends the float; holding W keeps flapping upward. A hit knocks you sideways but keeps your mouthful and your float" + }, + { + "en": "Some things cannot be inhaled (spiky balls, air puffs) and still hurt you; dodge them. Most hits cost 1 health bar, spiky balls cost 3. Some moves appear only in the extended mode and are tagged expert mode only" + } + ], + "compact_glossary": { + "mouth": { + "en": "mouth action (J): inhale, spit, swallow timing", + "options": { + "none": "no J", + "hold": "hold J for the whole packet (inhale, or spit when full)", + "press_1": "tap J in sub-step 1", + "press_2": "tap J in sub-step 2", + "press_3": "tap J in sub-step 3", + "press_4": "tap J in sub-step 4", + "press_5": "tap J in sub-step 5", + "press_6": "tap J in sub-step 6", + "triple_odd": "tap J in sub-steps 1, 3 and 5", + "hold_from_2": "hold J from sub-step 2 on" + } + }, + "walk": { + "en": "horizontal movement (A/D)", + "options": { + "none": "stand still", + "left": "hold A the whole packet", + "right": "hold D the whole packet", + "left_tap": "tap A in sub-step 1", + "right_tap": "tap D in sub-step 1", + "left_half": "hold A for sub-steps 1-3", + "right_half": "hold D for sub-steps 1-3", + "left_2": "hold A for sub-steps 1-2", + "right_2": "hold D for sub-steps 1-2" + } + }, + "vertical": { + "en": "jump / float / duck (Space, W, S)", + "options": { + "none": "no vertical key", + "jump": "hold Space (high jump; rises when puffing in the air)", + "jump_tap": "tap Space in sub-step 1", + "jump_late": "press and hold Space from sub-step 2", + "float": "hold W (puff and rise; rise while flying)", + "float_tap": "tap W in sub-step 1", + "float_flap": "tap W in sub-steps 2 and 5", + "down": "hold S (duck; sink while flying)", + "down_tap": "tap S (swallow / drop through a thin platform)", + "down_alt": "tap S in sub-steps 1, 3 and 5", + "jump_half": "hold Space for the first half (medium jump)" + } + } + }, + "scenes": [ + { + "case_id": "kirby/kaboola", + "boss": { + "en": "Armed Airship" + }, + "summary": { + "en": "A shooter-style fight high in the sky: you fly throughout and can only blow air bullets to the right, so stay on the airship's left. A hit gives about 1.5 seconds of blinking with no knockback" + }, + "moves": [ + { + "id": "shoot", + "name": { + "en": "Cannon Fire" + }, + "tell": { + "en": "The cannon opens under the hull (or over it after the blimp rolls over), then fires one bullet, three in a row, or a fan of three" + }, + "effect": { + "en": "A bullet hit costs 1 health bar; the straight shots fly about 16 px above or below its centre" + }, + "counter": { + "en": "Level with its middle, only the fan's slanted bullets come at you; your air bullets pass through its bullets, so keep firing while dodging" + } + }, + { + "id": "ram", + "name": { + "en": "Ram Dash" + }, + "tell": { + "en": "The blimp backs away and tips toward your side (up, level or down), then dashes across the screen and floats back" + }, + "effect": { + "en": "Contact costs 1 health bar, and you cannot outrun it sideways" + }, + "counter": { + "en": "Move out of its line up or down (rising is twice as fast as sinking) and keep firing as it floats back" + } + } + ] + }, + { + "case_id": "kirby/king_dedede", + "boss": { + "en": "Arena Hammer Brute" + }, + "summary": { + "en": "A close-quarters fight on a ring stage: he has four moves, each aimed at where you were. You must inhale things he throws or drops and spit them back" + }, + "moves": [ + { + "id": "walk", + "name": { + "en": "Waddle and Belly Slide" + }, + "tell": { + "en": "Steps back a little, waddles toward you, and within about 3 units throws himself into a belly slide" + }, + "effect": { + "en": "The slide costs 1 health bar on contact; he has super armour during the slide and while lying there" + }, + "counter": { + "en": "Jump or float over him as the slide starts; a star still hurts him while he lies there" + } + }, + { + "id": "jump", + "name": { + "en": "High Leap Slam" + }, + "tell": { + "en": "Crouches, then leaps high toward you (straight up if you are overhead) and crashes down" + }, + "effect": { + "en": "The landing costs 1 health bar, and two stars pop out beside him, lasting only about 0.6 seconds" + }, + "counter": { + "en": "Be inhaling next to the landing spot, then inhale a star and spit it back" + } + }, + { + "id": "inhale", + "name": { + "en": "Suction" + }, + "tell": { + "en": "Backs off, walks to where you were, opens his mouth and sucks for up to about 1.7 seconds" + }, + "effect": { + "en": "If caught you are spat into the ropes for 1 health bar" + }, + "counter": { + "en": "Stay out of the roughly 5.75-unit cone in front of his mouth; above or behind him is safe" + } + }, + { + "id": "hammer", + "name": { + "en": "Hammer Swing" + }, + "tell": { + "en": "Hops in place, walks to where you were, raises the hammer behind him and swings it over his head into the floor in front" + }, + "effect": { + "en": "The swing covers his back, his head and about 4 units of floor in front for 1 health bar; one star drops in front of him on the ground hit" + }, + "counter": { + "en": "Stand off, then inhale the dropped star and spit it back" + } + } + ] + }, + { + "case_id": "kirby/kracko", + "boss": { + "en": "One-Eyed Thundercloud" + }, + "summary": { + "en": "An aerial fight above the clouds: the cloud floats high and your ammunition is the one-eyed walkers it drops (bombs in the extended mode). It is easiest to hit at the bottom of a swoop" + }, + "moves": [ + { + "id": "move", + "name": { + "en": "Drift and Swoop" + }, + "tell": { + "en": "Drifts about 12 units to the other side; if you are below on that side it rises, then swoops down near the floor and back up" + }, + "effect": { + "en": "Touching the cloud costs 1 health bar; a swoop passes about 1.1 units above the floor" + }, + "counter": { + "en": "Duck (S) under it or get out of the way; mid-swoop is the best moment to hit it" + } + }, + { + "id": "beam", + "name": { + "en": "Spark Beams" + }, + "tell": { + "en": "The cloud crackles; sparks shoot out from two opposite points and turn half a circle around it" + }, + "effect": { + "en": "Touching a spark costs 1 health bar; they reach about 8.75 units from the centre" + }, + "counter": { + "en": "Keep a long horizontal distance and stay off the diagonals" + } + }, + { + "id": "doo", + "name": { + "en": "Release Walker" + }, + "tell": { + "en": "A one-eyed walker pops out of the cloud and walks toward your side; one in two stops, flashes and sweeps a beam from overhead to the floor in front" + }, + "effect": { + "en": "Contact or the beam costs 1 health bar" + }, + "counter": { + "en": "This is your ammunition: face it, hold J to inhale it, then jump and spit it straight up at the cloud" + } + }, + { + "id": "bombs", + "name": { + "en": "Bomb Drop" + }, + "only": { + "en": "expert mode only" + }, + "tell": { + "en": "The cloud loops out and back across the arena dropping three bombs that fall and burst above the floor" + }, + "effect": { + "en": "A bomb burst that reaches you costs 1 health bar" + }, + "counter": { + "en": "Inhale a falling bomb before it bursts; in this mode bombs are the only ammunition, and the far corner is out of reach" + } + }, + { + "id": "charge", + "name": { + "en": "Dive Charge" + }, + "only": { + "en": "expert mode only" + }, + "tell": { + "en": "Rears back away from you, then dives fast down to the floor on your side and loops back" + }, + "effect": { + "en": "Contact costs 1 health bar; it is the only attack in this mode that reaches the corner" + }, + "counter": { + "en": "Duck under it with S" + } + } + ] + }, + { + "case_id": "kirby/lololo_lalala", + "boss": { + "en": "Box-Pushing Twins" + }, + "summary": { + "en": "A fight in castle corridors: two brothers come out of gates at the ends of a corridor to push a box. The key is turning the box into your weapon" + }, + "moves": [ + { + "id": "push", + "name": { + "en": "Box Push" + }, + "tell": { + "en": "A brother pops out of a gate at one end of the corridor with a box in front of him, stands a moment, then starts pushing" + }, + "effect": { + "en": "The box is pushed down the corridor and costs 1 health bar if it hits you" + }, + "counter": { + "en": "Get into that corridor ahead of the box, inhale it, and spit the star straight back down the corridor; the brother is right behind it" + } + }, + { + "id": "gate", + "name": { + "en": "Gate Change" + }, + "tell": { + "en": "After a push ends, the brother goes back through his gate and the gate at the other end opens for the next one" + }, + "effect": { + "en": "It does no damage itself, it only changes the direction of the push" + }, + "counter": { + "en": "Watch which gate opens and move to that corridor to inhale the box" + } + } + ] + }, + { + "case_id": "kirby/poppy_bros_sr", + "boss": { + "en": "Bomb-Throwing Jester" + }, + "summary": { + "en": "A one-on-one on flat ground: he stays near his spot, and the threat comes from his bombs and big leaps. Bombs are your ammunition" + }, + "moves": [ + { + "id": "hop", + "name": { + "en": "Small Hops" + }, + "tell": { + "en": "Small hops on the spot, back and forth, in two pairs" + }, + "effect": { + "en": "His body costs 1 health bar on contact" + }, + "counter": { + "en": "He only hops in place; stay a few units away and wait for the bomb" + } + }, + { + "id": "throw", + "name": { + "en": "Bomb Throw" + }, + "tell": { + "en": "Jumps straight up with a bomb overhead; either lobs it from the top of the jump, or hangs there, lands and rolls it along the floor" + }, + "effect": { + "en": "The bomb comes toward you and bursts in a 5 by 5 unit blast where its path ends, costing 1 health bar" + }, + "counter": { + "en": "Inhale the bomb first, then spit it back at him" + } + }, + { + "id": "leap", + "name": { + "en": "Huge Leap" + }, + "tell": { + "en": "A medium hop toward you and back, then a huge leap across the room; he always returns to his spot" + }, + "effect": { + "en": "Contact near the landing costs 1 health bar; he drops no bomb during the leap" + }, + "counter": { + "en": "Get clear of the landing, or duck (his box stops about 9 px above his feet)" + } + }, + { + "id": "dash", + "name": { + "en": "Floor Dash" + }, + "only": { + "en": "expert mode only" + }, + "tell": { + "en": "Backs up a step and dashes across the floor at full speed, then runs back" + }, + "effect": { + "en": "Contact costs 1 health bar" + }, + "counter": { + "en": "Jump or float over the dash, or duck under his box" + } + } + ] + }, + { + "case_id": "kirby/whispy_woods", + "boss": { + "en": "Ancient Apple Tree" + }, + "summary": { + "en": "A stationary target on a grassy field: the tree stands at one end and attacks with air puffs and falling apples. Inhale its apples and spit them at the trunk" + }, + "moves": [ + { + "id": "puffs", + "name": { + "en": "Air Puff" + }, + "tell": { + "en": "The mouth opens into an O, then an air puff shoots out low along the floor, drifting up or down" + }, + "effect": { + "en": "A puff costs 1 health bar on contact and cannot be inhaled" + }, + "counter": { + "en": "Hop or float over it, or duck under one drifting up" + } + }, + { + "id": "puff_burst", + "name": { + "en": "Puff Burst" + }, + "tell": { + "en": "Four puffs in quick succession, the mouth snapping open each time" + }, + "effect": { + "en": "Each puff costs 1 health bar on contact" + }, + "counter": { + "en": "Float above the floor until the burst passes" + } + }, + { + "id": "apples", + "name": { + "en": "Falling Apples" + }, + "tell": { + "en": "An apple blinks among the leaves, drops, then bounces along the floor toward you" + }, + "effect": { + "en": "An apple hitting you costs 1 health bar" + }, + "counter": { + "en": "Face it, hold J to inhale it, then spit it at the trunk; this is the only way to hurt the tree" + } + }, + { + "id": "drop", + "name": { + "en": "Mixed Drop" + }, + "only": { + "en": "expert mode only" + }, + "tell": { + "en": "A spiky ball, then an apple, then either one, are dropped in turn" + }, + "effect": { + "en": "A spiky ball costs 3 health bars on contact and cannot be inhaled" + }, + "counter": { + "en": "Only the apples are ammunition; dodge the spiky balls" + } + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/kof_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/kof_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..8236574c70bee4ab20c730e6e41370757ddb225b --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/kof_remake.json @@ -0,0 +1,811 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "kof_remake", + "rules": "kof97-advanced-v8", + "title": { + "en": "Fighting Arena: One-on-One Duels" + }, + "dimension": "2d", + "view": { + "en": "Side-view 2D fighting: you control the Flame Fist against one opponent on a flat stage. Health bars and power gauges are at the top left and right, with the round timer in the middle; the mouse is not used." + }, + "goal": { + "en": "Empty the opponent's health bar to win; you lose if yours reaches zero. Each round is timed and, on timeout, the fighter with the larger share of health wins. Health does not regenerate by itself; only after knocking out an opponent do you recover a share depending on remaining time." + }, + "mouse": { + "kind": "none", + "en": "" + }, + "keys": [ + { + "key": "W", + "en": "jump (same as Space)" + }, + { + "key": "A", + "en": "move left; held while facing right it blocks" + }, + { + "key": "S", + "en": "crouch; back-down blocks low attacks" + }, + { + "key": "D", + "en": "move right; held while facing left it blocks" + }, + { + "key": "Space", + "en": "jump (same as W)" + }, + { + "key": "J", + "en": "light punch" + }, + { + "key": "K", + "en": "light kick" + }, + { + "key": "L", + "en": "heavy punch" + }, + { + "key": "Q", + "en": "heavy kick" + }, + { + "key": "Shift", + "en": "roll (same as J+K pressed together); while blocking, a one-gauge guard cancel" + }, + { + "key": "E", + "en": "enter MAX mode (one gauge, same as J+K+L together)" + }, + { + "key": "R", + "en": "super helper key (needs one gauge): triggers the charged flame sweep" + } + ], + "notes": [ + { + "en": "Directions are absolute left/right and do not flip with facing; read which way you face from the screen, then convert forward/back. When facing left, mirror the left/right in the commands below." + }, + { + "en": "Your command specials (key sequences facing right; middle diagonals may be omitted): down, down-forward, forward + punch = dash punch (heavy punch = heavy dash punch); forward, down, down-forward + punch = rising fire punch (anti-air, brief invulnerability on start-up); down, down-forward, forward + kick = two-hit kick; back, down, down-back + kick = leaping downward kick; forward, down-forward, down, down-back, back + kick = dash kick." + }, + { + "en": "Supers need one gauge: down, down-forward, forward, down, down-forward, forward + punch = multi-hit rush combo; down, down-back, back, down-back, down, down-forward, forward + punch = charged flame sweep, or simply press R. Without a gauge the same input only produces the final special." + }, + { + "en": "Commands are lenient: middle diagonals may be skipped and the button may be pressed about 50 ms before the direction. Normal attacks can only cancel into specials or supers." + }, + { + "en": "Block by holding back: standing back blocks mid attacks and jump-ins, back-down blocks lows; holding back in the air blocks air attacks and projectiles. Command throws cannot be blocked or teched." + }, + { + "en": "Up close, forward or back plus heavy punch/kick is a throw; press heavy punch or kick to tech a normal throw. Heavy punch + heavy kick is a launcher, and while blocking it is a one-gauge guard cancel. Combo keys must be pressed within about 50 ms." + }, + { + "en": "Power gauge: it rises when you hit, when you are blocked and when you are hit, and carries over between rounds. Supers in MAX mode are stronger. Both fighters pause briefly when a super starts." + }, + { + "en": "Depending on difficulty a match can be 1 to 3 opponents in a row, one round each; after a knockout there is a short swap, and more remaining time restores more health (limited fraction)." + } + ], + "compact_glossary": { + "direction": { + "en": "direction or command direction sequence (absolute left/right); the attack button below is pressed on the last sub-step of a sequence", + "options": { + "none": "no direction", + "left": "hold left", + "right": "hold right", + "down": "hold down (crouch)", + "down_left": "hold down-left (crouch block when facing right)", + "down_right": "hold down-right (crouch block when facing left)", + "down_short": "down for two sub-steps then release", + "tap_left": "tap left on sub-step 1 (for roll / close throw)", + "tap_right": "tap right on sub-step 1 (for roll / close throw)", + "dash_left": "double-tap left and hold (run when facing left)", + "dash_right": "double-tap right and hold (run when facing right)", + "double_left": "double-tap left (back hop when facing right)", + "double_right": "double-tap right (back hop when facing left)", + "jump_up": "vertical jump (up for 3 sub-steps)", + "jump_left": "jump left", + "jump_right": "jump right", + "hop_left": "short hop left (up on sub-step 1 only)", + "hop_right": "short hop right (up on sub-step 1 only)", + "superjump_left": "down then up-left: high jump left", + "superjump_right": "down then up-right: high jump right", + "qcf_left": "quarter-circle motion toward the left, done on sub-step 3", + "qcf_right": "quarter-circle motion toward the right, done on sub-step 3", + "dp_left": "rising-punch motion toward the left, done on sub-step 3", + "dp_right": "rising-punch motion toward the right, done on sub-step 3", + "hcb_left": "half-circle motion ending left, done on sub-step 5", + "hcb_right": "half-circle motion ending right, done on sub-step 5", + "double_qcf_left": "simplified double quarter-circle leftward, done on sub-step 4", + "double_qcf_right": "simplified double quarter-circle rightward, done on sub-step 4" + } + }, + "button": { + "en": "attack button and press timing within the 200 ms packet; combine with a command direction to perform a special", + "options": { + "none": "no attack button", + "lp_1": "light punch pressed on sub-step 1", + "lp_3": "light punch pressed on sub-step 3", + "lp_4": "light punch pressed on sub-step 4", + "lp_5": "light punch pressed on sub-step 5", + "lk_1": "light kick pressed on sub-step 1", + "lk_3": "light kick pressed on sub-step 3", + "lk_4": "light kick pressed on sub-step 4", + "lk_5": "light kick pressed on sub-step 5", + "hp_1": "heavy punch pressed on sub-step 1", + "hp_3": "heavy punch pressed on sub-step 3", + "hp_4": "heavy punch pressed on sub-step 4", + "hp_5": "heavy punch pressed on sub-step 5", + "hk_1": "heavy kick pressed on sub-step 1", + "hk_3": "heavy kick pressed on sub-step 3", + "hk_4": "heavy kick pressed on sub-step 4", + "hk_5": "heavy kick pressed on sub-step 5", + "lp_x3": "light punch three times (sub-steps 1,3,5)", + "lk_x3": "light kick three times (sub-steps 1,3,5)", + "super": "super helper key R (needs one gauge)", + "roll": "roll (Shift); guard cancel while blocking", + "max": "enter MAX mode (E, needs one gauge)", + "blowaway": "launcher: heavy punch + heavy kick together" + } + } + }, + "scenes": [ + { + "case_id": "kof97/iori", + "boss": { + "en": "Violet Claw" + }, + "summary": { + "en": "A close-pressure fighter with ground flame shots, claw chains and an invulnerable rising anti-air; with gauge it unleashes a rush frenzy." + }, + "moves": [ + { + "id": "ground_flame", + "name": { + "en": "Ground Violet Flame" + }, + "tell": { + "en": "He crouches and pushes out a violet flame along the ground." + }, + "effect": { + "en": "Projectile with medium damage." + }, + "counter": { + "en": "Jump over it and close in; punish the recovery." + } + }, + { + "id": "claw_chain", + "name": { + "en": "Triple Claw Chain" + }, + "tell": { + "en": "He leans forward and claws, possibly for three hits." + }, + "effect": { + "en": "Close multi-hit attack of medium damage." + }, + "counter": { + "en": "Punish after blocking the last hit; when pinned, use a one-gauge guard-cancel roll." + } + }, + { + "id": "rising_flame", + "name": { + "en": "Rising Flame" + }, + "tell": { + "en": "His body spins upward, invulnerable for a moment on start-up." + }, + "effect": { + "en": "Anti-air counter with high damage." + }, + "counter": { + "en": "Do not jump in carelessly; bait it and strike in the long landing recovery." + } + }, + { + "id": "close_grab", + "name": { + "en": "Close Grab" + }, + "tell": { + "en": "He opens both arms at close range." + }, + "effect": { + "en": "A command throw that cannot be blocked or teched." + }, + "counter": { + "en": "Jump or keep your distance." + } + }, + { + "id": "dash_elbow", + "name": { + "en": "Dash Elbow" + }, + "tell": { + "en": "He drops low and dashes forward with an elbow." + }, + "effect": { + "en": "Dashing attack with high damage." + }, + "counter": { + "en": "Block it; his long recovery lets you counter." + } + }, + { + "id": "binding_flame", + "name": { + "en": "Binding Flame" + }, + "tell": { + "en": "He spends one gauge and slowly pushes a blue-violet flame along the ground." + }, + "effect": { + "en": "If it hits, you are pinned until the next hit; low damage." + }, + "counter": { + "en": "It is slow with long recovery: jump or block, then counter." + } + }, + { + "id": "rush_frenzy", + "name": { + "en": "Rush Frenzy" + }, + "tell": { + "en": "After spending gauge he dashes into a flurry of strikes." + }, + "effect": { + "en": "High-damage super." + }, + "counter": { + "en": "Block back and wait for recovery; it hurts more in MAX mode." + } + } + ] + }, + { + "case_id": "kof97/orochi", + "boss": { + "en": "Radiant Deity" + }, + "summary": { + "en": "A ranged deity who controls space with huge shock waves, an energy mirror, light pillars and a barrier, plus a pull grab and screen-wide flash when he has gauge." + }, + "moves": [ + { + "id": "triple_wave", + "name": { + "en": "Triple Shock Wave" + }, + "tell": { + "en": "Light gathers in front of his palm, then three large waves are pushed out." + }, + "effect": { + "en": "Projectile with a tall hitbox." + }, + "counter": { + "en": "Superjump over or roll through; a short hop gets hit." + } + }, + { + "id": "mirror", + "name": { + "en": "Energy Mirror" + }, + "tell": { + "en": "An energy mirror appears with almost no wind-up." + }, + "effect": { + "en": "Reflects projectiles." + }, + "counter": { + "en": "Attack after the mirror ends." + } + }, + { + "id": "pillar", + "name": { + "en": "Light Pillar" + }, + "tell": { + "en": "He raises a hand; a ring appears on the ground, then a pillar of light rises through the screen." + }, + "effect": { + "en": "Strikes the position where you were seen; high damage." + }, + "counter": { + "en": "Leave the spot during the wind-up; the pillar does not keep tracking." + } + }, + { + "id": "barrier", + "name": { + "en": "Barrier" + }, + "tell": { + "en": "A barrier opens in front of him; an angled one catches air attacks." + }, + "effect": { + "en": "Catches ground attacks and counters." + }, + "counter": { + "en": "Hold back when you see it and wait for recovery; throws and projectiles are not caught." + } + }, + { + "id": "pull_grab", + "name": { + "en": "Pull Grab" + }, + "tell": { + "en": "He spends one gauge and pulls a grounded opponent in from mid range." + }, + "effect": { + "en": "A super with very high damage." + }, + "counter": { + "en": "Stay out of range or jump and it whiffs, leaving long recovery." + } + }, + { + "id": "close_throw", + "name": { + "en": "Close Throw" + }, + "tell": { + "en": "He grabs at close range." + }, + "effect": { + "en": "A throw that cannot be teched." + }, + "counter": { + "en": "Do not linger up close." + } + }, + { + "id": "screen_flash", + "name": { + "en": "Screen Flash" + }, + "tell": { + "en": "He spends one gauge, spreads both arms and gathers a screen-wide flash." + }, + "effect": { + "en": "A super with very high damage." + }, + "counter": { + "en": "The wind-up is long: block back to reduce damage or roll on timing." + } + } + ] + }, + { + "case_id": "kof97/orochi_chris", + "boss": { + "en": "Blaze Youth" + }, + "summary": { + "en": "A fire fighter mixing slow fireballs, a hopping fire arm, an anti-air rising arm and an unblockable strike throw." + }, + "moves": [ + { + "id": "slow_fireball", + "name": { + "en": "Slow Fireball" + }, + "tell": { + "en": "A slow multi-part fireball with short range." + }, + "effect": { + "en": "Projectile of medium damage." + }, + "counter": { + "en": "Jump forward or roll when you see the start." + } + }, + { + "id": "hop_arm", + "name": { + "en": "Hopping Fire Arm" + }, + "tell": { + "en": "A short hop then a downward swing of a flaming arm." + }, + "effect": { + "en": "Dashing attack." + }, + "counter": { + "en": "Crouch under it (it misses crouching) or block and counter." + } + }, + { + "id": "rising_arm", + "name": { + "en": "Rising Fire Arm" + }, + "tell": { + "en": "He swings a flaming arm upward as an anti-air." + }, + "effect": { + "en": "Anti-air with medium-high damage." + }, + "counter": { + "en": "Do not jump in head-on; his landing recovery is long." + } + }, + { + "id": "strike_throw", + "name": { + "en": "Unblockable Punch Throw" + }, + "tell": { + "en": "Up close: five fire punches then an upward kick." + }, + "effect": { + "en": "An effectively unblockable strike throw with high damage." + }, + "counter": { + "en": "Leave close range or jump." + } + }, + { + "id": "fire_rush", + "name": { + "en": "Fireball Rush" + }, + "tell": { + "en": "He spends one gauge and rushes in wrapped in fireballs." + }, + "effect": { + "en": "A super." + }, + "counter": { + "en": "Block, then punish." + } + }, + { + "id": "dark_sweep", + "name": { + "en": "Dark Flame Sweep" + }, + "tell": { + "en": "A one-gauge dark flame sweep that can be charged." + }, + "effect": { + "en": "A super." + }, + "counter": { + "en": "Block or back away." + } + } + ] + }, + { + "case_id": "kof97/orochi_iori", + "boss": { + "en": "Frenzied Claw" + }, + "summary": { + "en": "A berserk version of the Violet Claw with the same toolkit but more pressure; it also needs gauge for supers." + }, + "moves": [ + { + "id": "ground_flame", + "name": { + "en": "Ground Violet Flame" + }, + "tell": { + "en": "He crouches and pushes a violet flame along the ground." + }, + "effect": { + "en": "Projectile of medium damage." + }, + "counter": { + "en": "Jump over it and punish the recovery." + } + }, + { + "id": "claw_chain", + "name": { + "en": "Triple Claw Chain" + }, + "tell": { + "en": "A berserk three-hit claw chain." + }, + "effect": { + "en": "Close multi-hit attack." + }, + "counter": { + "en": "Block the last hit and keep a low guard." + } + }, + { + "id": "rising_flame", + "name": { + "en": "Rising Flame" + }, + "tell": { + "en": "A rising violet-flame anti-air." + }, + "effect": { + "en": "Anti-air with high damage." + }, + "counter": { + "en": "Jump safely or counter on landing." + } + }, + { + "id": "close_grab", + "name": { + "en": "Close Grab" + }, + "tell": { + "en": "A close-range command grab." + }, + "effect": { + "en": "Command throw that cannot be teched." + }, + "counter": { + "en": "Avoid it by jumping or spacing." + } + }, + { + "id": "dash_elbow", + "name": { + "en": "Dash Elbow" + }, + "tell": { + "en": "He drops low and dashes with an elbow." + }, + "effect": { + "en": "Dashing attack, high damage." + }, + "counter": { + "en": "Block, then counter his long recovery." + } + }, + { + "id": "binding_flame", + "name": { + "en": "Binding Flame" + }, + "tell": { + "en": "One gauge: a slow blue-violet flame along the ground." + }, + "effect": { + "en": "If it hits, you are pinned until the next hit." + }, + "counter": { + "en": "Slow with long recovery: jump or block, then counter." + } + }, + { + "id": "rush_frenzy", + "name": { + "en": "Rush Frenzy" + }, + "tell": { + "en": "After spending gauge he dashes at high speed." + }, + "effect": { + "en": "High-damage super." + }, + "counter": { + "en": "Block, then punish." + } + } + ] + }, + { + "case_id": "kof97/orochi_shermie", + "boss": { + "en": "Storm Dancer" + }, + "summary": { + "en": "A fighter who places lingering electric orbs and uses lightning kicks; with gauge she has an anti-air spark punch and multi-hit flying kicks." + }, + "moves": [ + { + "id": "placed_orb", + "name": { + "en": "Placed Lightning Orb" + }, + "tell": { + "en": "She blows, then an orb appears far away; its position depends on the button." + }, + "effect": { + "en": "The orb lingers a long time and hurts on contact." + }, + "counter": { + "en": "Roll through or wait until it disappears; do not stand on it." + } + }, + { + "id": "spark_shot", + "name": { + "en": "Close Spark Shot" + }, + "tell": { + "en": "Two chops, then a short-range electric shot." + }, + "effect": { + "en": "Short-range multi-part attack." + }, + "counter": { + "en": "Block, then close in." + } + }, + { + "id": "spin_kick", + "name": { + "en": "Lightning Spin Kick" + }, + "tell": { + "en": "A spin kick with lightning wrapped on the leg." + }, + "effect": { + "en": "Close kick attack." + }, + "counter": { + "en": "Block, then counter." + } + }, + { + "id": "air_heel", + "name": { + "en": "Aerial Heel Drop" + }, + "tell": { + "en": "A downward heel chop in the air." + }, + "effect": { + "en": "Aerial downward chop." + }, + "counter": { + "en": "Hit her out of the air." + } + }, + { + "id": "anti_air_spark", + "name": { + "en": "Anti-air Spark Punch" + }, + "tell": { + "en": "A one-gauge lightning punch with fast start-up." + }, + "effect": { + "en": "Anti-air super with high damage." + }, + "counter": { + "en": "Do not jump around when she has gauge." + } + }, + { + "id": "flying_kicks", + "name": { + "en": "Multi-hit Flying Kicks" + }, + "tell": { + "en": "A one-gauge horizontal flying kick." + }, + "effect": { + "en": "Multi-hit but does not knock down." + }, + "counter": { + "en": "Block, then punish." + } + } + ] + }, + { + "case_id": "kof97/orochi_yashiro", + "boss": { + "en": "Grappler" + }, + "summary": { + "en": "A heavyweight built around command throws: nearly every close move is a grab, plus a charged beam and a super slam when he has gauge." + }, + "moves": [ + { + "id": "instant_grab", + "name": { + "en": "One-frame Command Throw" + }, + "tell": { + "en": "A grab at close range, possibly after a normal attack." + }, + "effect": { + "en": "Command throw with high damage; cannot be teched." + }, + "counter": { + "en": "Keep your distance; jump or step back." + } + }, + { + "id": "back_slam", + "name": { + "en": "Back Slam" + }, + "tell": { + "en": "A close-range slam command throw." + }, + "effect": { + "en": "Command throw." + }, + "counter": { + "en": "Same as above." + } + }, + { + "id": "dash_suplex", + "name": { + "en": "Dash Suplex" + }, + "tell": { + "en": "He dashes forward and follows with a suplex." + }, + "effect": { + "en": "Dashing grab." + }, + "counter": { + "en": "Interrupt the dash with a punch, or jump back." + } + }, + { + "id": "leap_wrap", + "name": { + "en": "Leaping Wrap Grab" + }, + "tell": { + "en": "He leaps, grabs and ends up behind you." + }, + "effect": { + "en": "No damage itself; a throw follows." + }, + "counter": { + "en": "Block right away once he is behind you." + } + }, + { + "id": "charge_beam", + "name": { + "en": "Charged Beam" + }, + "tell": { + "en": "He spends one gauge, charges, then fires a beam." + }, + "effect": { + "en": "Unblockable when fully charged; high damage." + }, + "counter": { + "en": "Close in or jump over when you see him charging." + } + }, + { + "id": "super_slam", + "name": { + "en": "Super Slam" + }, + "tell": { + "en": "A one-gauge close-range super throw." + }, + "effect": { + "en": "His most painful move." + }, + "counter": { + "en": "Do not throw out attacks at close range." + } + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/mario64_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/mario64_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..b9ba6c2a25d947a961a6efc4cc1cc419d711b1fe --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/mario64_remake.json @@ -0,0 +1,646 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "mario64_remake", + "rules": "sm64-bosses@5", + "title": { + "en": "3D Platformer: Boss Trials" + }, + "dimension": "3d", + "view": { + "en": "Third-person 3D: a follow camera behind the player, a capped jumper. The HUD shows boss info and a pie-shaped power meter in a corner; arenas are floating platforms with a drop or lava beyond the edges." + }, + "goal": { + "en": "Defeat the boss (each fight counts differently: hits or lava dunks until zero) to win; you lose when your power meter empties; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate" + }, + "mouse": { + "kind": "camera", + "en": "Dragging the mouse rotates the camera continuously (double-click the screen to lock it); Q/E turn it 45 degrees at a time and R recenters. The compact actions offer only Q/E/R" + }, + "keys": [ + { + "key": "W", + "en": "move forward relative to the camera (full stick)" + }, + { + "key": "A", + "en": "move left" + }, + { + "key": "S", + "en": "move back" + }, + { + "key": "D", + "en": "move right" + }, + { + "key": "Space", + "en": "jump; press again on landing for a double then triple jump; while crouching it is a backflip; during a sharp turn a side flip; held longer jumps higher" + }, + { + "key": "Shift", + "en": "crouch; while running it is a slide, then Space is a long jump; in the air it is the slam-down" + }, + { + "key": "RMB", + "en": "same as Shift: crouch / slide / mid-air slam-down" + }, + { + "key": "J", + "en": "punch-punch-kick combo; dive when running fast; flying kick in the air; grabs a grabbable target when close, throws when holding" + }, + { + "key": "LMB", + "en": "same as J: attack / grab / throw" + }, + { + "key": "K", + "en": "hold to walk slowly (half stick)" + }, + { + "key": "Q", + "en": "turn camera left 45 degrees" + }, + { + "key": "E", + "en": "turn camera right 45 degrees" + }, + { + "key": "R", + "en": "snap camera behind you, facing the boss" + }, + { + "key": "L", + "en": "toggle camera distance" + } + ], + "notes": [ + { + "en": "Movement is relative to the camera: W is where the camera faces, so turning the camera changes what each key does" + }, + { + "en": "Triple jump, long jump, backflip, side flip and slam-down are available; slam-down is Shift in mid-air and attacks on landing" + }, + { + "en": "After being hurt you are briefly invulnerable; falling into lava or a deep drop is a heavy hit" + }, + { + "en": "When grabbed, mash Space or flick the stick to break free" + }, + { + "en": "A compact packet of 200 ms has 6 sub-steps; punching on a sub-step where the stick is released gives a punch instead of a dive" + } + ], + "compact_glossary": { + "move": { + "en": "stick direction for the whole 200 ms packet (relative to the camera), or a camera turn (Q/E/R); one packet is either movement or a camera turn", + "options": { + "none": "stand still", + "cam_left": "camera turns left 45 degrees (Q), stand still", + "cam_right": "camera turns right 45 degrees (E), stand still", + "cam_reset": "camera snaps behind you, facing the boss (R), stand still", + "w": "move forward", + "wa": "move forward-left", + "a": "move left", + "as": "move back-left", + "s": "move back", + "sd": "move back-right", + "d": "move right", + "wd": "move forward-right", + "m_w_a_s_d_w_a": "6 sub-steps of stick: forward, left, back, right, forward, left", + "m_wa_as_sd_wd_wa_as": "6 sub-steps of stick: forward-left, back-left, back-right, forward-right, forward-left, back-left", + "m_a_s_d_w_a_s": "6 sub-steps of stick: left, back, right, forward, left, back", + "m_as_sd_wd_wa_as_sd": "6 sub-steps of stick: back-left, back-right, forward-right, forward-left, back-left, back-right", + "m_s_d_w_a_s_d": "6 sub-steps of stick: back, right, forward, left, back, right", + "m_sd_wd_wa_as_sd_wd": "6 sub-steps of stick: back-right, forward-right, forward-left, back-left, back-right, forward-right", + "m_d_w_a_s_d_w": "6 sub-steps of stick: right, forward, left, back, right, forward", + "m_wd_wa_as_sd_wd_wa": "6 sub-steps of stick: forward-right, forward-left, back-left, back-right, forward-right, forward-left", + "m_w_x_w_w_w_w": "6 sub-steps of stick: forward, stop, forward, forward, forward, forward (a release lets a punch land as a punch instead of a dive)", + "m_wa_x_wa_wa_wa_wa": "6 sub-steps of stick: forward-left, stop, forward-left, forward-left, forward-left, forward-left (a release lets a punch land as a punch instead of a dive)", + "m_a_x_a_a_a_a": "6 sub-steps of stick: left, stop, left, left, left, left (a release lets a punch land as a punch instead of a dive)", + "m_as_x_as_as_as_as": "6 sub-steps of stick: back-left, stop, back-left, back-left, back-left, back-left (a release lets a punch land as a punch instead of a dive)", + "m_s_x_s_s_s_s": "6 sub-steps of stick: back, stop, back, back, back, back (a release lets a punch land as a punch instead of a dive)", + "m_sd_x_sd_sd_sd_sd": "6 sub-steps of stick: back-right, stop, back-right, back-right, back-right, back-right (a release lets a punch land as a punch instead of a dive)", + "m_d_x_d_d_d_d": "6 sub-steps of stick: right, stop, right, right, right, right (a release lets a punch land as a punch instead of a dive)", + "m_wd_x_wd_wd_wd_wd": "6 sub-steps of stick: forward-right, stop, forward-right, forward-right, forward-right, forward-right (a release lets a punch land as a punch instead of a dive)", + "m_w_w_x_w_w_w": "6 sub-steps of stick: forward, forward, stop, forward, forward, forward (a release lets a punch land as a punch instead of a dive)", + "m_wa_wa_x_wa_wa_wa": "6 sub-steps of stick: forward-left, forward-left, stop, forward-left, forward-left, forward-left (a release lets a punch land as a punch instead of a dive)", + "m_a_a_x_a_a_a": "6 sub-steps of stick: left, left, stop, left, left, left (a release lets a punch land as a punch instead of a dive)", + "m_s_s_x_s_s_s": "6 sub-steps of stick: back, back, stop, back, back, back (a release lets a punch land as a punch instead of a dive)", + "m_d_d_x_d_d_d": "6 sub-steps of stick: right, right, stop, right, right, right (a release lets a punch land as a punch instead of a dive)", + "m_wd_wd_x_wd_wd_wd": "6 sub-steps of stick: forward-right, forward-right, stop, forward-right, forward-right, forward-right (a release lets a punch land as a punch instead of a dive)", + "m_w_w_w_x_w_w": "6 sub-steps of stick: forward, forward, forward, stop, forward, forward (a release lets a punch land as a punch instead of a dive)", + "m_wa_wa_wa_x_wa_wa": "6 sub-steps of stick: forward-left, forward-left, forward-left, stop, forward-left, forward-left (a release lets a punch land as a punch instead of a dive)", + "m_a_a_a_x_a_a": "6 sub-steps of stick: left, left, left, stop, left, left (a release lets a punch land as a punch instead of a dive)", + "m_as_as_as_x_as_as": "6 sub-steps of stick: back-left, back-left, back-left, stop, back-left, back-left (a release lets a punch land as a punch instead of a dive)", + "m_s_s_s_x_s_s": "6 sub-steps of stick: back, back, back, stop, back, back (a release lets a punch land as a punch instead of a dive)", + "m_sd_sd_sd_x_sd_sd": "6 sub-steps of stick: back-right, back-right, back-right, stop, back-right, back-right (a release lets a punch land as a punch instead of a dive)", + "m_d_d_d_x_d_d": "6 sub-steps of stick: right, right, right, stop, right, right (a release lets a punch land as a punch instead of a dive)", + "m_wd_wd_wd_x_wd_wd": "6 sub-steps of stick: forward-right, forward-right, forward-right, stop, forward-right, forward-right (a release lets a punch land as a punch instead of a dive)", + "m_w_w_w_w_x_w": "6 sub-steps of stick: forward, forward, forward, forward, stop, forward (a release lets a punch land as a punch instead of a dive)", + "m_wa_wa_wa_wa_x_wa": "6 sub-steps of stick: forward-left, forward-left, forward-left, forward-left, stop, forward-left (a release lets a punch land as a punch instead of a dive)", + "m_a_a_a_a_x_a": "6 sub-steps of stick: left, left, left, left, stop, left (a release lets a punch land as a punch instead of a dive)", + "m_as_as_as_as_x_as": "6 sub-steps of stick: back-left, back-left, back-left, back-left, stop, back-left (a release lets a punch land as a punch instead of a dive)", + "m_s_s_s_s_x_s": "6 sub-steps of stick: back, back, back, back, stop, back (a release lets a punch land as a punch instead of a dive)", + "m_sd_sd_sd_sd_x_sd": "6 sub-steps of stick: back-right, back-right, back-right, back-right, stop, back-right (a release lets a punch land as a punch instead of a dive)", + "m_d_d_d_d_x_d": "6 sub-steps of stick: right, right, right, right, stop, right (a release lets a punch land as a punch instead of a dive)", + "m_wd_wd_wd_wd_x_wd": "6 sub-steps of stick: forward-right, forward-right, forward-right, forward-right, stop, forward-right (a release lets a punch land as a punch instead of a dive)", + "m_w_w_w_w_w_x": "6 sub-steps of stick: forward, forward, forward, forward, forward, stop (a release lets a punch land as a punch instead of a dive)", + "m_wa_wa_wa_wa_wa_x": "6 sub-steps of stick: forward-left, forward-left, forward-left, forward-left, forward-left, stop (a release lets a punch land as a punch instead of a dive)", + "m_a_a_a_a_a_x": "6 sub-steps of stick: left, left, left, left, left, stop (a release lets a punch land as a punch instead of a dive)", + "m_as_as_as_as_as_x": "6 sub-steps of stick: back-left, back-left, back-left, back-left, back-left, stop (a release lets a punch land as a punch instead of a dive)", + "m_s_s_s_s_s_x": "6 sub-steps of stick: back, back, back, back, back, stop (a release lets a punch land as a punch instead of a dive)", + "m_sd_sd_sd_sd_sd_x": "6 sub-steps of stick: back-right, back-right, back-right, back-right, back-right, stop (a release lets a punch land as a punch instead of a dive)", + "m_d_d_d_d_d_x": "6 sub-steps of stick: right, right, right, right, right, stop (a release lets a punch land as a punch instead of a dive)", + "m_wd_wd_wd_wd_wd_x": "6 sub-steps of stick: forward-right, forward-right, forward-right, forward-right, forward-right, stop (a release lets a punch land as a punch instead of a dive)", + "m_x_x_x_w_w_w": "6 sub-steps of stick: stop, stop, stop, forward, forward, forward (a release lets a punch land as a punch instead of a dive)", + "m_w_w_x_x_x_x": "6 sub-steps of stick: forward, forward, stop, stop, stop, stop (a release lets a punch land as a punch instead of a dive)", + "m_wd_wd_wd_d_d_d": "6 sub-steps of stick: forward-right, forward-right, forward-right, right, right, right", + "m_wa_wa_wa_a_a_a": "6 sub-steps of stick: forward-left, forward-left, forward-left, left, left, left", + "m_x_x_x_wd_wd_wd": "6 sub-steps of stick: stop, stop, stop, forward-right, forward-right, forward-right (a release lets a punch land as a punch instead of a dive)", + "m_d_d_d_sd_sd_sd": "6 sub-steps of stick: right, right, right, back-right, back-right, back-right", + "m_w_x_x_x_x_x": "6 sub-steps of stick: forward, stop, stop, stop, stop, stop (a release lets a punch land as a punch instead of a dive)", + "m_w_w_w_wa_wa_wa": "6 sub-steps of stick: forward, forward, forward, forward-left, forward-left, forward-left", + "m_wa_wa_wa_w_w_w": "6 sub-steps of stick: forward-left, forward-left, forward-left, forward, forward, forward", + "m_sd_sd_s_x_x_x": "6 sub-steps of stick: back-right, back-right, back, stop, stop, stop (a release lets a punch land as a punch instead of a dive)", + "m_x_x_x_x_x_w": "6 sub-steps of stick: stop, stop, stop, stop, stop, forward (a release lets a punch land as a punch instead of a dive)", + "m_x_x_x_x_wa_wa": "6 sub-steps of stick: stop, stop, stop, stop, forward-left, forward-left (a release lets a punch land as a punch instead of a dive)", + "m_d_d_d_wd_wd_wd": "6 sub-steps of stick: right, right, right, forward-right, forward-right, forward-right", + "m_a_a_a_as_as_as": "6 sub-steps of stick: left, left, left, back-left, back-left, back-left", + "m_a_a_a_wa_wa_wa": "6 sub-steps of stick: left, left, left, forward-left, forward-left, forward-left", + "m_w_w_w_s_s_s": "6 sub-steps of stick: forward, forward, forward, back, back, back", + "m_wd_wd_wd_w_w_w": "6 sub-steps of stick: forward-right, forward-right, forward-right, forward, forward, forward", + "m_x_w_x_w_x_w": "6 sub-steps of stick: stop, forward, stop, forward, stop, forward (a release lets a punch land as a punch instead of a dive)", + "m_w_w_w_wd_wd_wd": "6 sub-steps of stick: forward, forward, forward, forward-right, forward-right, forward-right", + "m_x_x_x_x_s_s": "6 sub-steps of stick: stop, stop, stop, stop, back, back (a release lets a punch land as a punch instead of a dive)", + "m_s_s_s_x_x_x": "6 sub-steps of stick: back, back, back, stop, stop, stop (a release lets a punch land as a punch instead of a dive)", + "m_x_x_wa_wa_wa_wa": "6 sub-steps of stick: stop, stop, forward-left, forward-left, forward-left, forward-left (a release lets a punch land as a punch instead of a dive)", + "m_w_x_w_x_w_x": "6 sub-steps of stick: forward, stop, forward, stop, forward, stop (a release lets a punch land as a punch instead of a dive)", + "m_s_s_s_sd_sd_sd": "6 sub-steps of stick: back, back, back, back-right, back-right, back-right", + "m_x_x_w_w_w_w": "6 sub-steps of stick: stop, stop, forward, forward, forward, forward (a release lets a punch land as a punch instead of a dive)", + "m_sd_sd_sd_d_d_d": "6 sub-steps of stick: back-right, back-right, back-right, right, right, right", + "m_x_x_x_x_wd_wd": "6 sub-steps of stick: stop, stop, stop, stop, forward-right, forward-right (a release lets a punch land as a punch instead of a dive)", + "m_x_x_x_x_w_w": "6 sub-steps of stick: stop, stop, stop, stop, forward, forward (a release lets a punch land as a punch instead of a dive)", + "m_x_w_w_w_w_w": "6 sub-steps of stick: stop, forward, forward, forward, forward, forward", + "m_w_w_w_x_x_x": "6 sub-steps of stick: forward, forward, forward, stop, stop, stop (a release lets a punch land as a punch instead of a dive)", + "m_x_x_wd_wd_wd_wd": "6 sub-steps of stick: stop, stop, forward-right, forward-right, forward-right, forward-right (a release lets a punch land as a punch instead of a dive)", + "m_wa_wa_x_x_x_x": "6 sub-steps of stick: forward-left, forward-left, stop, stop, stop, stop (a release lets a punch land as a punch instead of a dive)" + } + }, + "action": { + "en": "action buttons within the packet (punch/grab/throw, jump, slam-down); jump and punch trigger on press", + "options": { + "none": "no action", + "punch_s1": "punch/kick/grab/throw pressed at sub-step 1", + "punch_s2": "punch/kick/grab/throw pressed at sub-step 2", + "punch_s3": "punch/kick/grab/throw pressed at sub-step 3", + "punch_s4": "punch/kick/grab/throw pressed at sub-step 4", + "punch_s5": "punch/kick/grab/throw pressed at sub-step 5", + "punch_s6": "punch/kick/grab/throw pressed at sub-step 6", + "jump_hold": "jump held for the whole packet (high jump)", + "jump_pound_s2": "jump 1 sub-step, then slam-down (Shift) at sub-step 2", + "jump_pound_s3": "jump 2 sub-steps, then slam-down (Shift) at sub-step 3", + "jump_short": "short jump, held 2 sub-steps (low hop)" + } + } + }, + "scenes": [ + { + "case_id": "mario64/whomp_king", + "boss": { + "en": "Toppling Slab" + }, + "summary": { + "en": "On a stone-brick platform you face a huge slab that chases you and topples forward; beyond the edge is a deep drop." + }, + "moves": [ + { + "id": "chase", + "name": { + "en": "Chase" + }, + "tell": { + "en": "The slab stands and walks toward you, speeding up as you get close" + }, + "effect": { + "en": "It only closes in; no contact damage" + }, + "counter": { + "en": "Stay at its front side to lure the jump" + } + }, + { + "id": "slam", + "name": { + "en": "Topple slam" + }, + "tell": { + "en": "At close range it stops, rocks back, jumps and falls flat toward you" + }, + "effect": { + "en": "Anyone under the fallen slab is crushed for heavy damage" + }, + "counter": { + "en": "Once it jumps the landing is fixed: run sideways out of its width, or stay in the gap right in front of its feet" + } + }, + { + "id": "lie", + "name": { + "en": "Lying flat" + }, + "tell": { + "en": "After the slam it lies still for a second or two; its back is a platform you can stand on" + }, + "effect": { + "en": "This is the only opening" + }, + "counter": { + "en": "Jump onto its back and slam down in the air; jump off before it rises" + } + }, + { + "id": "rise", + "name": { + "en": "Rise up" + }, + "tell": { + "en": "It shakes, then slowly stands up" + }, + "effect": { + "en": "Anyone standing on its back is thrown off" + }, + "counter": { + "en": "Leave its back before it stands" + } + } + ], + "phases": [ + { + "en": "On higher tiers it chases faster and lies flat for less time" + } + ] + }, + { + "case_id": "mario64/king_bobomb", + "boss": { + "en": "Grappler Orb" + }, + "summary": { + "en": "On a grassy hilltop you face a big black iron ball that grabs you; you must grab it from behind and throw it." + }, + "moves": [ + { + "id": "walk", + "name": { + "en": "Walk toward you" + }, + "tell": { + "en": "It walks toward you and keeps turning" + }, + "effect": { + "en": "It tries to grab you once close" + }, + "counter": { + "en": "Circle behind it and avoid standing in front" + } + }, + { + "id": "grab", + "name": { + "en": "Grab and throw" + }, + "tell": { + "en": "If it touches you while facing you, it lifts you, carries you toward the edge, then throws you" + }, + "effect": { + "en": "You may land off the hilltop; on harder tiers the throw itself hurts" + }, + "counter": { + "en": "While held, mash Space or flick the stick to break free" + } + }, + { + "id": "held", + "name": { + "en": "Picked up by you" + }, + "tell": { + "en": "A punch from behind lifts it" + }, + "effect": { + "en": "This starts your counter" + }, + "counter": { + "en": "After lifting it, throw with J so it lands on the hilltop to score; landing off the hill does not count" + } + }, + { + "id": "hurt", + "name": { + "en": "Hurt and stomping" + }, + "tell": { + "en": "After a hit it shudders, then turns to you" + }, + "effect": { + "en": "Touching it now hurts" + }, + "counter": { + "en": "Wait for the animation to end before approaching" + } + } + ], + "phases": [ + { + "en": "On harder tiers it walks and turns faster and the throw hurts more" + } + ] + }, + { + "case_id": "mario64/big_bully", + "boss": { + "en": "Horned Rammer" + }, + "summary": { + "en": "On a small platform over lava you must knock a horned round opponent into the lava; there is no health bar, each lava dunk is one hit." + }, + "moves": [ + { + "id": "patrol", + "name": { + "en": "Patrol" + }, + "tell": { + "en": "It paces slowly around the platform" + }, + "effect": { + "en": "Switches to chasing when you come close" + }, + "counter": { + "en": "Hold your ground and watch its facing" + } + }, + { + "id": "charge", + "name": { + "en": "Charge" + }, + "tell": { + "en": "It turns slowly toward you, then dashes suddenly" + }, + "effect": { + "en": "A collision swaps momentum: you are knocked back softly, no damage" + }, + "counter": { + "en": "Hit it with punch, kick, slam-down or land on it to send it flying along your facing toward the lava" + } + }, + { + "id": "knock", + "name": { + "en": "Knocked back" + }, + "tell": { + "en": "It slides, then resumes chasing when it slows" + }, + "effect": { + "en": "If you are knocked off the edge you fall into lava and take heavy damage" + }, + "counter": { + "en": "Stand between it and the lava rather than with your back to the edge" + } + } + ], + "phases": [] + }, + { + "case_id": "mario64/eyerok", + "boss": { + "en": "Twin Sandstone Fists" + }, + "summary": { + "en": "On a desert plateau two sandstone fists attack in turn; you can hurt them only while a hand is open and its eye is showing." + }, + "moves": [ + { + "id": "pound", + "name": { + "en": "Fist pound" + }, + "tell": { + "en": "A fist rises high over your position and drops after a pause" + }, + "effect": { + "en": "Being caught under it crushes you for heavy damage" + }, + "counter": { + "en": "Run sideways before it lands" + } + }, + { + "id": "push", + "name": { + "en": "Push and sweep" + }, + "tell": { + "en": "A fist slides along the ground to you, then sweeps sideways" + }, + "effect": { + "en": "Being swept to the edge drops you off the plateau" + }, + "counter": { + "en": "Dodge the sweep and stay away from the edge" + } + }, + { + "id": "double", + "name": { + "en": "Double pound" + }, + "tell": { + "en": "Both fists lift and slam in sequence" + }, + "effect": { + "en": "Wider coverage" + }, + "counter": { + "en": "Slip through the gap between the two" + } + }, + { + "id": "eye", + "name": { + "en": "Open hand" + }, + "tell": { + "en": "After a pound the fist opens to show an eye; it blinks, then closes" + }, + "effect": { + "en": "The only opening" + }, + "counter": { + "en": "Punch or kick the open hand while it is open" + } + } + ], + "phases": [ + { + "en": "With one hand down, the other chases you with pushes and slams" + } + ] + }, + { + "case_id": "mario64/wiggler", + "boss": { + "en": "Frenzy Crawler" + }, + "summary": { + "en": "In a closed square cave room, a segmented crawler that keeps getting faster chases you; only stomping its head works." + }, + "moves": [ + { + "id": "walk", + "name": { + "en": "Crawl" + }, + "tell": { + "en": "It crawls around the room, getting faster with each stomp" + }, + "effect": { + "en": "Touching its body or head knocks you away for light damage" + }, + "counter": { + "en": "Keep your distance and wait for its head" + } + }, + { + "id": "stomp", + "name": { + "en": "Stomped" + }, + "tell": { + "en": "When its head is stomped it swells, shrinks and goes dazed" + }, + "effect": { + "en": "This is the only effective attack" + }, + "counter": { + "en": "Use a short jump onto the head; a hit counts after the daze ends" + } + }, + { + "id": "fury", + "name": { + "en": "Fury" + }, + "tell": { + "en": "Before the last hit it hops and sprints" + }, + "effect": { + "en": "Very fast; contact hurts" + }, + "counter": { + "en": "Run in loops and avoid corners" + } + } + ], + "phases": [ + { + "en": "Each stomp makes it faster; the last stretch is the fastest" + } + ] + }, + { + "case_id": "mario64/bowser_dark_world", + "boss": { + "en": "Fire Shell Beast" + }, + "summary": { + "en": "On a void octagon you grab a fire-breathing beast by the tail, spin it, and throw it into mines at the platform edge; beyond the edge is a bottomless void." + }, + "moves": [ + { + "id": "breath", + "name": { + "en": "Fire breath" + }, + "tell": { + "en": "Facing you it lowers its head and spews a line of fireballs" + }, + "effect": { + "en": "Flames burn you, cost health and bounce you up" + }, + "counter": { + "en": "Run out of the line sideways; do not stand in front" + } + }, + { + "id": "quickjump", + "name": { + "en": "Quick jump" + }, + "tell": { + "en": "It crouches, then leaps, landing near you" + }, + "effect": { + "en": "The shockwave hurts if close and stuns if farther" + }, + "counter": { + "en": "Run away before it lands or hop over it" + } + }, + { + "id": "walk", + "name": { + "en": "Walk" + }, + "tell": { + "en": "It walks toward you and turns" + }, + "effect": { + "en": "Body contact knocks you back and costs health" + }, + "counter": { + "en": "Stay at its side and use the gap when it turns" + } + }, + { + "id": "tail", + "name": { + "en": "Tail grab and spin" + }, + "tell": { + "en": "From behind, punch or dive at its tail to grab it, then press W A S D in order to spin faster" + }, + "effect": { + "en": "The faster the spin, the farther the throw" + }, + "counter": { + "en": "Press J toward a mine; a mine hit counts, and the tail is untouchable for a while" + } + }, + { + "id": "dance", + "name": { + "en": "Stomp dance" + }, + "tell": { + "en": "Occasionally it stomps in place" + }, + "effect": { + "en": "No attack" + }, + "counter": { + "en": "Use it to get behind" + } + } + ], + "phases": [ + { + "en": "After a mine hit the tail cannot be grabbed until it recovers" + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/megaman_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/megaman_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..710c81ae04b09b64858a579354d58151099c3606 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/megaman_remake.json @@ -0,0 +1,517 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "megaman_remake", + "rules": "megaman-nes-20261105-r4", + "title": { + "en": "Blue Gunner: Boss Gauntlet" + }, + "dimension": "2d", + "view": { + "en": "Side-view single-screen 2D room; you control the blue gunner with an arm gun and any weapons won; your health bar and the boss's health bar are at the top of the screen" + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose if your health reaches zero; there is a time limit and a timeout is not a win. Health does not regenerate" + }, + "mouse": { + "kind": "none", + "en": "" + }, + "keys": [ + { + "key": "A", + "en": "move left (slow start, slides after release)" + }, + { + "key": "D", + "en": "move right (slow start, slides after release)" + }, + { + "key": "Space", + "en": "jump; hold to go higher, releasing mid-rise slows it at once" + }, + { + "key": "J", + "en": "fire, one shot per press" + }, + { + "key": "LMB", + "en": "fire (same as J)" + }, + { + "key": "Q", + "en": "previous weapon" + }, + { + "key": "E", + "en": "next weapon" + } + ], + "notes": [ + { + "en": "Firing counts new presses, so release and press again for each shot; the arm gun allows at most 3 shots on screen, with no charge shot and no slide" + }, + { + "en": "Defeating a boss wins its weapon; each shot costs weapon energy, fuse lob and block toss cost more; you cannot switch while a fuse lob or boulder is out" + }, + { + "en": "For block toss, stand against a block facing it, press fire to lift and again to throw; only the blade tosser and quake hurler rooms have blocks" + }, + { + "en": "After a hit you are knocked back about 0.5 s then flash invulnerable for about 2 s; weapons have strengths and weaknesses against different bosses" + }, + { + "en": "One action packet lasts 200 ms and is split into 6 sub-steps" + } + ], + "compact_glossary": { + "move": { + "en": "Horizontal movement; half/4-substep options are short nudges (walking starts slow, then slides after release)", + "options": { + "none": "stand still", + "left": "hold left whole packet", + "right": "hold right whole packet", + "left_half": "left for first 3 sub-steps", + "right_half": "right for first 3 sub-steps", + "left_4": "left for first 4 sub-steps", + "right_4": "right for first 4 sub-steps" + } + }, + "jump": { + "en": "Jump timing; holding longer jumps higher, releasing early cuts the rise", + "options": { + "none": "no jump", + "hold": "hold whole packet (highest)", + "tap": "press sub-step 1 only (lowest)", + "from_2": "hold from sub-step 2", + "from_3": "hold from sub-step 3", + "from_4": "hold from sub-step 4", + "from_5": "hold from sub-step 5", + "at_6": "press sub-step 6 only", + "first_2": "hold first 2 sub-steps (low)", + "first_5": "hold first 5 sub-steps", + "first_3": "hold first 3 sub-steps", + "first_4": "hold first 4 sub-steps", + "tap_rehold": "tap at sub-step 1, hold again from 3", + "tap_tap6": "tap at sub-step 1, press again at 6", + "tap_hold5": "tap at sub-step 1, hold again from 5" + } + }, + "fire": { + "en": "Fire or switch weapon", + "options": { + "none": "no fire", + "fire": "fire 3 shots (sub-steps 1, 3, 5)", + "next_weapon": "next weapon (sub-step 1)", + "prev_weapon": "previous weapon (sub-step 1)" + } + } + }, + "scenes": [ + { + "case_id": "megaman/bomb_man", + "boss": { + "en": "Shard Lobber" + }, + "summary": { + "en": "A flat small room; the opponent lobs bombs and leaps in, and each bomb bursts into shards on landing." + }, + "moves": [ + { + "id": "lob_bomb", + "name": { + "en": "Bomb lob" + }, + "tell": { + "en": "After landing he holds a bomb up for about 0.25 s and lobs it at you; it lands slightly short of you, 1-3 per round" + }, + "effect": { + "en": "The bomb explodes on landing or on hitting a wall and hurts; shots cannot destroy it" + }, + "counter": { + "en": "Watch the landing spot and jump the shards or back off; he waits for one to burst before throwing the next" + } + }, + { + "id": "shrapnel", + "name": { + "en": "Shards" + }, + "tell": { + "en": "The bomb bursts into 12 pieces: fast ones up/down/left/right, diagonals and four slow ones" + }, + "effect": { + "en": "Shards hurt on contact" + }, + "counter": { + "en": "Ground-level shards are low, so jumping avoids them; stay away from the landing spot" + } + }, + { + "id": "leap", + "name": { + "en": "Leap" + }, + "tell": { + "en": "Each round starts with a random jump: a big leap at you or a small hop closer; after a small-hop round he hops away facing back" + }, + "effect": { + "en": "Touching him during a leap hurts" + }, + "counter": { + "en": "A big leap goes over you, so walk under it; he only charges after settling, which is your opening" + } + }, + { + "id": "close_guard", + "name": { + "en": "Close-range pounce" + }, + "tell": { + "en": "When you get very close he drops the bomb throw and jumps at you" + }, + "effect": { + "en": "It breaks his rhythm but he jumps over you with contact damage" + }, + "counter": { + "en": "Use it to break his throws, but mind where he lands" + } + } + ], + "phases": [] + }, + { + "case_id": "megaman/cut_man", + "boss": { + "en": "Blade Tosser" + }, + "summary": { + "en": "The room has a step and blocks; the opponent throws a returning blade and leaps at close range." + }, + "moves": [ + { + "id": "return_blade", + "name": { + "en": "Returning blade" + }, + "tell": { + "en": "He plants his feet and raises the blade for about 0.3 s, then throws it at you; it turns at the room edge and speeds back to his hand" + }, + "effect": { + "en": "The return path also sweeps through your position and hurts" + }, + "counter": { + "en": "While the blade is out he has no weapon, so close in and shoot; do not stand between him and the blade" + } + }, + { + "id": "leap", + "name": { + "en": "Close leap" + }, + "tell": { + "en": "When you are close he jumps; usually over you, sometimes right onto you or in front of you" + }, + "effect": { + "en": "Landing on you does contact damage; he may throw the blade in mid-air" + }, + "counter": { + "en": "When he jumps, walk under him or the other way" + } + }, + { + "id": "chase", + "name": { + "en": "Wait-and-throw" + }, + "tell": { + "en": "When you stand on the step and he is on the ground, he runs in place for about 1 s then throws" + }, + "effect": { + "en": "After the wait the blade flies at you" + }, + "counter": { + "en": "The step is a safe place to watch, but dodge once the blade is thrown" + } + }, + { + "id": "hop_back", + "name": { + "en": "Hit-and-hop" + }, + "tell": { + "en": "After being hit he flashes for about 1 second and hops away from you for the first half second" + }, + "effect": { + "en": "Shots pass through him while he flashes; touching him still hurts" + }, + "counter": { + "en": "Do not waste shots while he flashes; wait until he stops" + } + } + ], + "phases": [] + }, + { + "case_id": "megaman/elec_man", + "boss": { + "en": "Pouncer" + }, + "summary": { + "en": "The opponent paces, firing at him triggers a counter-pounce, and his main damage is the zigzag arc." + }, + "moves": [ + { + "id": "zigzag_arc", + "name": { + "en": "Zigzag arc" + }, + "tell": { + "en": "He stops and raises a hand for about 0.25 s, then releases a five-part zigzag arc that jumps forward and changes shape every moment" + }, + "effect": { + "en": "The arc deals heavy damage on contact" + }, + "counter": { + "en": "High arcs pass over you when standing; jump low arcs before they arrive, toward him is easier" + } + }, + { + "id": "counter_leap", + "name": { + "en": "Counter-pounce" + }, + "tell": { + "en": "If you fire while he paces, he pounces at once, sometimes as a feint in the other direction" + }, + "effect": { + "en": "Landing on you does contact damage" + }, + "counter": { + "en": "Do not fire while he paces; wait until he stands and discharges" + } + }, + { + "id": "air_arc", + "name": { + "en": "Air arc" + }, + "tell": { + "en": "If you fire while he is airborne, he charges in the air and releases one arc" + }, + "effect": { + "en": "The arc deals heavy damage and its height follows his" + }, + "counter": { + "en": "Watch the landing and fire less while he is airborne" + } + }, + { + "id": "hop_back", + "name": { + "en": "Hit-and-hop" + }, + "tell": { + "en": "After being hit he flashes for about 1 second and hops away from you for the first half second" + }, + "effect": { + "en": "Shots pass through him while he flashes; touching him still hurts" + }, + "counter": { + "en": "Do not waste shots while he flashes; wait until he stops" + } + } + ], + "phases": [] + }, + { + "case_id": "megaman/fire_man", + "boss": { + "en": "Wave Keeper" + }, + "summary": { + "en": "The opponent keeps a fixed distance, sending ground waves that leave fire pillars." + }, + "moves": [ + { + "id": "ground_wave", + "name": { + "en": "Ground wave" + }, + "tell": { + "en": "From a distance he gathers fire in his hand for about 0.4 s, then sends it along the ground; up to five per round, about one per second" + }, + "effect": { + "en": "The wave hurts on contact" + }, + "counter": { + "en": "Prepare to jump when the fire gathers and clear the wave near the top of your jump" + } + }, + { + "id": "fire_pillar", + "name": { + "en": "Fire pillar" + }, + "tell": { + "en": "When a wave passes under your feet, a fire pillar rises there for about 2 s" + }, + "effect": { + "en": "The pillar hurts on contact" + }, + "counter": { + "en": "Avoid pillars when landing; the old one dies when he sends the next wave" + } + }, + { + "id": "keep_distance", + "name": { + "en": "Distance control" + }, + "tell": { + "en": "He backs off when you approach and closes in when you retreat; cornered at a wall he turns and walks through you" + }, + "effect": { + "en": "Walking through you does contact damage" + }, + "counter": { + "en": "Shoot while he backs off; beware contact near walls" + } + }, + { + "id": "retaliate", + "name": { + "en": "Retaliation" + }, + "tell": { + "en": "About 0.23 s after being hit he starts a new round of fire" + }, + "effect": { + "en": "He then sends waves" + }, + "counter": { + "en": "Be ready to jump right after landing a hit" + } + }, + { + "id": "stand_down", + "name": { + "en": "Stand-down after five" + }, + "tell": { + "en": "After five shots he holds a pose and stops; any input from you or leaving the range band restarts him" + }, + "effect": { + "en": "He does not attack while stopped" + }, + "counter": { + "en": "This is a rule quirk; do not rely on it to win" + } + } + ], + "phases": [] + }, + { + "case_id": "megaman/guts_man", + "boss": { + "en": "Quake Hurler" + }, + "summary": { + "en": "The room has a step; the opponent attacks with quaking leaps and thrown boulders." + }, + "moves": [ + { + "id": "quake_leap", + "name": { + "en": "Quake leap" + }, + "tell": { + "en": "He crouches for about 0.25 s, jumps high, and the screen shakes for about 0.5 s on landing" + }, + "effect": { + "en": "While the screen shakes, you are stunned for about 0.8 s if standing on the ground; contact also hurts" + }, + "counter": { + "en": "Jump just as he lands and stay airborne until the shake ends; he is slow, so you can walk under him" + } + }, + { + "id": "boulder_throw", + "name": { + "en": "Boulder throw" + }, + "tell": { + "en": "He hops once, a boulder drops onto his hands, and after about 0.25 s of holding it he throws it straight at your feet" + }, + "effect": { + "en": "The boulder hurts on contact; shots cannot destroy it" + }, + "counter": { + "en": "He stands still while holding it, so shoot then; jump or move as he throws" + } + }, + { + "id": "chunks", + "name": { + "en": "Chunks" + }, + "tell": { + "en": "When the boulder hits a wall, floor or step it breaks into four pieces that keep flying the same way, two angling upward" + }, + "effect": { + "en": "Chunks hurt on contact" + }, + "counter": { + "en": "Chunks appear to the lower right of the impact and fly onward; walk back or jump once the boulder lands" + } + } + ], + "phases": [] + }, + { + "case_id": "megaman/ice_man", + "boss": { + "en": "V Gunner" + }, + "summary": { + "en": "The opponent paces between fixed spots and fires piercing darts in a V pattern that speeds up over time." + }, + "moves": [ + { + "id": "v_volley", + "name": { + "en": "V volley" + }, + "tell": { + "en": "At his spot he charges for about 0.25 s and jumps straight up; he fires one dart at each of three heights on the way down, hangs at the floor, then fires three more going up" + }, + "effect": { + "en": "The darts deal heavy damage on contact" + }, + "counter": { + "en": "Only the ground-level dart needs a jump; the middle and high ones pass over you; do not jump too high into the upper one" + } + }, + { + "id": "patrol", + "name": { + "en": "Patrol" + }, + "tell": { + "en": "He walks between four spots; every three landings the darts and hover timing speed up one level, four levels in all" + }, + "effect": { + "en": "He does not attack while walking and has no hit reaction" + }, + "counter": { + "en": "Walking and charging are the safest windows to shoot" + } + } + ], + "phases": [ + { + "en": "Every three landings speed up one level, four in total" + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/minecraft.json b/environments/games/prototype/bossbench_llm/prompts/games/minecraft.json new file mode 100644 index 0000000000000000000000000000000000000000..6ffd4694234a8b4177fb674168b2cf73f8489dd8 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/minecraft.json @@ -0,0 +1,448 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "minecraft", + "rules": "minecraft-arena@7", + "title": { + "en": "Blocky World: Boss Duel" + }, + "dimension": "3d", + "view": { + "en": "3D blocky world, first person by default: the crosshair is at the centre and the sword or bow in hand at the lower right (third person can be chosen at reset, showing the Voxel Wanderer). The HUD shows the boss's name and health bar, your health and armor, and the hotbar (slot 1 sword, slot 2 bow)." + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose if your health hits zero; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate." + }, + "mouse": { + "kind": "camera", + "en": "X>0 turns right, Y>0 looks down; there is no aim assist; pitch is limited to about ±89°. The wheel Z switches the hotbar slot, one notch per slot (1 sword, 2 bow)" + }, + "keys": [ + { + "key": "W", + "en": "move forward" + }, + { + "key": "S", + "en": "move backward" + }, + { + "key": "A", + "en": "strafe left" + }, + { + "key": "D", + "en": "strafe right" + }, + { + "key": "Space", + "en": "jump (hold to keep jumping)" + }, + { + "key": "Shift", + "en": "sprint (only while holding W)" + }, + { + "key": "J", + "en": "swing the sword; punches only when holding the bow" + }, + { + "key": "LMB", + "en": "swing (same as J); punches only when holding the bow" + }, + { + "key": "RMB", + "en": "hold to draw the bow, release to fire" + } + ], + "notes": [ + { + "en": "At reset you choose the weapon (sword or bow) and the camera (first person by default, third person optional); in play the mouse wheel (Z in the action) switches between sword and bow, which resets the attack cooldown and cancels a draw." + }, + { + "en": "The sword swings once per press and its damage scales with the attack cooldown charge (full in about 0.6 s), so mashing is weak. A fully charged, non-sprinting hit while falling is a critical; a sprinting full-charge hit adds knockback." + }, + { + "en": "The bow needs RMB held across steps; about 1 second is a full, critical draw. Drawing slows you and stops sprinting. Arrows drop with gravity and stop on terrain." + }, + { + "en": "Each hit gives about 0.5 seconds of damage immunity; a stronger hit inside it deals only the difference." + }, + { + "en": "You can walk in only one direction at a time (W over S, A, D), so there is no diagonal movement." + } + ], + "compact_glossary": { + "move": { + "en": "Walking direction (one at a time; W > S > A > D)", + "options": { + "none": "stand still", + "forward": "walk forward", + "back": "walk backward", + "left": "strafe left", + "right": "strafe right", + "sprint": "sprint forward (W+Shift)" + } + }, + "action": { + "en": "Attack, jump or switch weapon", + "options": { + "none": "do nothing", + "swing": "sword swing at the start of the 200 ms step", + "swing_late": "sword swing late in the step", + "draw": "hold the bow draw (RMB) for the step", + "jump": "jump", + "switch": "switch between sword and bow" + } + }, + "aim": { + "en": "Camera turn and pitch; dx>0 turns right, dy>0 looks down", + "options": { + "none": "no camera change", + "r8_c0": "turn right 1.2 deg", + "l8_c0": "turn left 1.2 deg", + "c0_d40": "look down 6 deg", + "c0_u40": "look up 6 deg", + "r25_c0": "turn right 3.75 deg", + "r25_d40": "turn right 3.75 deg, look down 6 deg", + "r25_u40": "turn right 3.75 deg, look up 6 deg", + "l25_c0": "turn left 3.75 deg", + "l25_d40": "turn left 3.75 deg, look down 6 deg", + "l25_u40": "turn left 3.75 deg, look up 6 deg", + "r60_c0": "turn right 9 deg", + "r60_d40": "turn right 9 deg, look down 6 deg", + "r60_u40": "turn right 9 deg, look up 6 deg", + "l60_c0": "turn left 9 deg", + "l60_d40": "turn left 9 deg, look down 6 deg", + "l60_u40": "turn left 9 deg, look up 6 deg", + "r150_c0": "turn right 22.5 deg", + "r150_d40": "turn right 22.5 deg, look down 6 deg", + "r150_u40": "turn right 22.5 deg, look up 6 deg", + "l150_c0": "turn left 22.5 deg", + "l150_d40": "turn left 22.5 deg, look down 6 deg", + "l150_u40": "turn left 22.5 deg, look up 6 deg", + "r300_c0": "turn right 45 deg", + "l300_c0": "turn left 45 deg", + "r600_c0": "turn right 90 deg", + "l600_c0": "turn left 90 deg" + } + } + }, + "scenes": [ + { + "case_id": "3d/minecraft_ender_dragon", + "boss": { + "en": "Violet Breath Flyer" + }, + "summary": { + "en": "A huge flying boss circling over the tower platform; stone pillars topped with healing crystals stand around the arena." + }, + "moves": [ + { + "id": "fireball", + "name": { + "en": "Violet Fireball" + }, + "tell": { + "en": "It lines up on you and its mouth glows." + }, + "effect": { + "en": "Fires a ball that leaves a purple cloud; standing in it deals steady magic damage that armor ignores." + }, + "counter": { + "en": "Step out of the cloud; after firing it returns to circling." + } + }, + { + "id": "perch", + "name": { + "en": "Perch and Roar" + }, + "tell": { + "en": "It lands on the central platform and roars for about 2 seconds." + }, + "effect": { + "en": "A purple cloud under its head deals damage over time." + }, + "counter": { + "en": "Arrows bounce off, but sword hits on the head deal full damage; enough damage makes it take off." + } + }, + { + "id": "charge", + "name": { + "en": "Charging Rush" + }, + "tell": { + "en": "After about 5 seconds perched with nobody close, it lifts off to rush." + }, + "effect": { + "en": "Head contact and wing sweeps both hurt and shove you." + }, + "counter": { + "en": "Sidestep; it flies past and climbs back to circling." + } + }, + { + "id": "crystals", + "name": { + "en": "Healing Crystals" + }, + "tell": { + "en": "A white beam links the nearest crystal to it." + }, + "effect": { + "en": "Crystals heal it; a crystal explodes when broken and hurts nearby." + }, + "counter": { + "en": "Shoot crystals with the bow to damage it, staying clear of the blast." + } + } + ], + "phases": [] + }, + { + "case_id": "3d/minecraft_iron_golem", + "boss": { + "en": "Hurling Brute" + }, + "summary": { + "en": "A huge melee guardian with a single heavy swing; kite it in circles." + }, + "moves": [ + { + "id": "swing", + "name": { + "en": "Two-Arm Swing" + }, + "tell": { + "en": "Both arms are raised high." + }, + "effect": { + "en": "Random damage within a range, reduced by armor, and it throws you." + }, + "counter": { + "en": "It has a cooldown after each swing, so strike then; it cannot reach targets well above it." + } + }, + { + "id": "chase", + "name": { + "en": "Closing In" + }, + "tell": { + "en": "It walks straight at you." + }, + "effect": { + "en": "It can only swing once you are in reach." + }, + "counter": { + "en": "Back off and circle out of reach, then dash in after a miss." + } + } + ], + "phases": [] + }, + { + "case_id": "3d/minecraft_skeleton", + "boss": { + "en": "Strafing Bowman" + }, + "summary": { + "en": "A ranged enemy that strafes while drawing its bow; ruins in the arena give cover." + }, + "moves": [ + { + "id": "arrow", + "name": { + "en": "Bow Shot" + }, + "tell": { + "en": "The bow is raised and drawn for most of a second." + }, + "effect": { + "en": "Fires an arcing arrow; damage rises with difficulty and armor reduces it." + }, + "counter": { + "en": "About 3 seconds between shots (about 2 on hard); walls stop arrows, so strafe or hide." + } + }, + { + "id": "kite", + "name": { + "en": "Kiting" + }, + "tell": { + "en": "It backs off and strafes as you approach." + }, + "effect": { + "en": "Deals no damage itself but makes melee hard." + }, + "counter": { + "en": "Corner it against the ruins or arena wall, then press with the sword." + } + } + ], + "phases": [] + }, + { + "case_id": "3d/minecraft_warden", + "boss": { + "en": "Blind Shockwave Beast" + }, + "summary": { + "en": "A heavy melee beast stalking through the dark cavern, able to release a ranged shockwave." + }, + "moves": [ + { + "id": "smash", + "name": { + "en": "Overhead Smash" + }, + "tell": { + "en": "Arms rise and its chest glows." + }, + "effect": { + "en": "A heavy close-range hit that armor reduces." + }, + "counter": { + "en": "There is a cooldown but it keeps walking, so back off between swings." + } + }, + { + "id": "shockwave", + "name": { + "en": "Charged Shockwave" + }, + "tell": { + "en": "About 1.7 seconds of charging: chest lights up and rings gather." + }, + "effect": { + "en": "The boom deals damage and knockback, ignoring armor and walls." + }, + "counter": { + "en": "It only charges while you stay out of reach; about 1.3 seconds of recovery after the boom is your opening." + } + }, + { + "id": "vision_dim", + "name": { + "en": "Vision Dim" + }, + "tell": { + "en": "The screen pulses dark like a heartbeat." + }, + "effect": { + "en": "Only impairs vision; no direct damage." + }, + "counter": { + "en": "Slow down and rely on its outline and the HUD." + } + } + ], + "phases": [] + }, + { + "case_id": "3d/minecraft_wither", + "boss": { + "en": "Three-Headed Hover Gun" + }, + "summary": { + "en": "A hovering three-headed cannon with a long spawn-in charge; it gains a shell at half health." + }, + "moves": [ + { + "id": "shell", + "name": { + "en": "Shell" + }, + "tell": { + "en": "A head turns to you; black shells fly fast, blue shells slowly." + }, + "effect": { + "en": "A hit hurts and applies black-heart drain; the blast also hurts within about 2 blocks." + }, + "counter": { + "en": "Break line of sight behind cover and it stops firing; sidestep the slow blue shells." + } + }, + { + "id": "spawn", + "name": { + "en": "Spawn Blast" + }, + "tell": { + "en": "About 11 seconds of flickering blue while its health bar fills." + }, + "effect": { + "en": "Explodes at its centre when done, weaker with distance and harmless beyond about 14 blocks." + }, + "counter": { + "en": "Run far away before the blast." + } + }, + { + "id": "armor", + "name": { + "en": "Half-Health Shell" + }, + "tell": { + "en": "A translucent shell appears around it at half health." + }, + "effect": { + "en": "The shell makes arrows ineffective." + }, + "counter": { + "en": "Switch to the sword and fight it up close on the ground." + } + } + ], + "phases": [ + { + "en": "At half health it enters the shell phase and must be fought with the sword." + } + ] + }, + { + "case_id": "3d/minecraft_zombie_leader", + "boss": { + "en": "Horde Caller" + }, + "summary": { + "en": "A melee boss that keeps calling helpers to surround you." + }, + "moves": [ + { + "id": "swipe", + "name": { + "en": "Lunging Swipe" + }, + "tell": { + "en": "Arms rise high and it lunges." + }, + "effect": { + "en": "Damage rises with difficulty and armor reduces it." + }, + "counter": { + "en": "About a 1-second cooldown after each swipe; it is knocked back on every hit, so use that to space." + } + }, + { + "id": "reinforcements", + "name": { + "en": "Call Reinforcements" + }, + "tell": { + "en": "Smoke appears and a helper climbs out of the ground." + }, + "effect": { + "en": "Each helper swipes just like its caller." + }, + "counter": { + "en": "Kill the caller first: the helpers remain but the fight ends." + } + } + ], + "phases": [] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/nfsmw_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/nfsmw_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..d8f59415fd27e2a711a905ae4b8f803d34c90422 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/nfsmw_remake.json @@ -0,0 +1,519 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "nfsmw_remake", + "rules": "nfsmw-arena@2", + "title": { + "en": "Street Racing: Original Sports Car in an Original Seaside City" + }, + "dimension": "3d", + "view": { + "en": "Third-person view behind an original sports car. Speed and rev gauges are at the bottom; the top shows how far the event has come, rival gap or bust meter. Edge arrows point to rivals and police cars that are off screen" + }, + "goal": { + "en": "Each event has its own win: finish the route, beat the rival, score a higher total, avoid finishing last, or escape the police. Running out of time, a rival finishing first, being caught or a wrecked car loses; each run lasts at most 300 seconds and a timeout is not a win. Nothing recovers by itself" + }, + "mouse": { + "kind": "none", + "en": "This game does not use the mouse" + }, + "keys": [ + { + "key": "W", + "en": "throttle" + }, + { + "key": "S", + "en": "brake; reverse at low speed" + }, + { + "key": "A", + "en": "steer left (the longer held, the more angle; less angle at high speed; in drag races, change to the left lane)" + }, + { + "key": "D", + "en": "steer right (in drag races, change to the right lane)" + }, + { + "key": "Space", + "en": "handbrake, for drifting" + }, + { + "key": "Shift", + "en": "nitrous" + }, + { + "key": "J", + "en": "slow motion on / off (the world slows and downforce rises)" + }, + { + "key": "K", + "en": "shift up (manual gearbox in drag races)" + }, + { + "key": "L", + "en": "shift down (manual gearbox in drag races)" + }, + { + "key": "R", + "en": "reset onto the route; for about 2 s afterwards (flashing) the police catch you more easily" + } + ], + "notes": [ + { + "en": "A / D must be held for a while to wind the wheel on, and it eases back when released; at higher speed the angle is smaller." + }, + { + "en": "Drag races use a manual gearbox: press K when the rev gauge reaches the green zone. A / D change lanes there instead of steering." + }, + { + "en": "Nitrous is limited and takes time to recover. In toll and speed-trap events it pays most just before the key points." + }, + { + "en": "Slow motion slows the world and adds downforce, which helps in tight corners; it drains with use, and J turns it off." + }, + { + "en": "Walls and crashes scrub speed; staying on the route is usually fastest, and a reset costs time." + } + ], + "compact_glossary": { + "pedal": { + "en": "Throttle and brake", + "options": { + "none": "release, coast", + "throttle_light": "light throttle (1 of 6 sub-steps)", + "throttle": "full throttle", + "brake": "brake; reverse at low speed" + } + }, + "steer": { + "en": "Steering as a duty cycle over the 6 sub-steps (no mouse)", + "options": { + "none": "no steering, wheel returns to centre", + "left_tap": "tap left (drag: change to the left lane)", + "left_ease": "left for 2 of 6 sub-steps: wheel slowly returns", + "left_hold": "left for 3 of 6: keep the current angle", + "left_hold_late": "left for 3 of 6, offset half a beat: keep the angle", + "left_more": "left for 4 of 6: wind more angle on", + "left_full": "left held fully", + "right_tap": "tap right (drag: change to the right lane)", + "right_ease": "right for 2 of 6 sub-steps: wheel slowly returns", + "right_hold": "right for 3 of 6: keep the current angle", + "right_hold_late": "right for 3 of 6, offset half a beat: keep the angle", + "right_more": "right for 4 of 6: wind more angle on", + "right_full": "right held fully" + } + }, + "nitrous": { + "en": "Nitrous", + "options": { + "none": "off", + "nitrous": "nitrous on" + } + }, + "press": { + "en": "Gear shift, slow motion, reset, handbrake", + "options": { + "none": "nothing", + "shift_up": "shift up (drag only)", + "shift_down": "shift down (drag only)", + "slowmo": "toggle slow motion", + "reset": "reset onto the route", + "handbrake": "handbrake held, drift" + } + } + }, + "scenes": [ + { + "case_id": "nfsmw/tollbooth", + "boss": { + "en": "Toll-gate time trial" + }, + "summary": { + "en": "A solo run along the coast road through toll gates; each gate adds time, and you lose when the clock runs out. Traffic is on the road" + }, + "moves": [ + { + "id": "gate", + "name": { + "en": "Toll gate" + }, + "tell": { + "en": "A gate and light beam on the road ahead" + }, + "effect": { + "en": "Passing adds time to the clock; clearing the last gate wins" + }, + "counter": { + "en": "Keep speed on the ideal line and use nitrous to gain time" + } + }, + { + "id": "traffic", + "name": { + "en": "Road traffic" + }, + "tell": { + "en": "Civilian cars driving slowly on the road ahead" + }, + "effect": { + "en": "A crash scrubs a lot of speed or stops you" + }, + "counter": { + "en": "Move to the clear side early; do not force an overtake in a corner" + } + } + ] + }, + { + "case_id": "nfsmw/drag", + "boss": { + "en": "Drag rival" + }, + "summary": { + "en": "Several drag races in a row against one rival on a straight four-lane strip. The car holds its line by itself; you change lanes and handle throttle, nitrous and gears" + }, + "moves": [ + { + "id": "launch", + "name": { + "en": "Launch" + }, + "tell": { + "en": "The rev needle during the countdown" + }, + "effect": { + "en": "Launching with revs in the target band gives a boost; too high spins the clutch" + }, + "counter": { + "en": "Hold the throttle during the countdown and keep revs a little below the redline" + } + }, + { + "id": "shift", + "name": { + "en": "Shift timing" + }, + "tell": { + "en": "The rev gauge enters the green zone" + }, + "effect": { + "en": "A well-timed upshift gives a bonus; sitting on the limiter builds heat and a blown engine loses" + }, + "counter": { + "en": "Press K as soon as the gauge is in the green; do not sit on the limiter" + } + }, + { + "id": "rival_nitrous", + "name": { + "en": "Rival nitrous" + }, + "tell": { + "en": "Blue flame behind the rival's car" + }, + "effect": { + "en": "The rival speeds up for a while and gains ground" + }, + "counter": { + "en": "Use your own nitrous at a good moment" + } + }, + { + "id": "crash", + "name": { + "en": "Crash wreck" + }, + "tell": { + "en": "Traffic or an obstacle appears in your lane" + }, + "effect": { + "en": "A hard hit at high speed drops too much speed and wrecks the car, losing the heat" + }, + "counter": { + "en": "Change lanes early with A / D" + } + } + ] + }, + { + "case_id": "nfsmw/speedtrap", + "boss": { + "en": "Speed-trap rival" + }, + "summary": { + "en": "Drive through speed cameras along the coast road; the speeds at each camera add up and are compared with one rival. Cameras sit where speed is easiest to reach" + }, + "moves": [ + { + "id": "camera", + "name": { + "en": "Speed camera" + }, + "tell": { + "en": "A roadside camera and gate; a light beam marks the next one" + }, + "effect": { + "en": "Records your speed as you pass and adds it to your total" + }, + "counter": { + "en": "Start nitrous 1 to 3 seconds before a camera and do not brake before it" + } + }, + { + "id": "rival_boost", + "name": { + "en": "Rival boost at camera" + }, + "tell": { + "en": "Blue flame behind the rival as it nears a camera" + }, + "effect": { + "en": "The rival posts a higher speed at the camera and widens the gap" + }, + "counter": { + "en": "Save nitrous for the cameras; you lose if the margin runs out" + } + }, + { + "id": "traffic", + "name": { + "en": "Road traffic" + }, + "tell": { + "en": "Civilian cars on the road" + }, + "effect": { + "en": "A crash cuts speed and so the reading at that camera" + }, + "counter": { + "en": "Change lanes early and do not get stuck behind a car before a camera" + } + } + ] + }, + { + "case_id": "nfsmw/knockout", + "boss": { + "en": "Knockout field" + }, + "summary": { + "en": "A night-time downtown circuit with several rivals; the last car over the line each lap is knocked out and you must not be last. You start on the back row" + }, + "moves": [ + { + "id": "knock", + "name": { + "en": "Lap knockout" + }, + "tell": { + "en": "After cars finish the lap, the last rival disappears" + }, + "effect": { + "en": "Finishing last means you lose" + }, + "counter": { + "en": "Pass at least one rival every lap and do not lose speed in corners" + } + }, + { + "id": "rival_pack", + "name": { + "en": "Rival pack" + }, + "tell": { + "en": "Other cars driving the route ahead; the further forward, the faster" + }, + "effect": { + "en": "They do not yield and nudge aside on contact; once far ahead they are hard to catch" + }, + "counter": { + "en": "Take the inside line, get on the throttle early out of corners and use nitrous to catch up" + } + }, + { + "id": "traffic", + "name": { + "en": "Road traffic" + }, + "tell": { + "en": "A few civilian cars on the circuit" + }, + "effect": { + "en": "A crash scrubs speed and drops you to the back" + }, + "counter": { + "en": "Steer around them as soon as you see them" + }, + "only": { + "en": "normal and hard tiers only" + } + } + ] + }, + { + "case_id": "nfsmw/pursuit", + "boss": { + "en": "Police pursuit" + }, + "summary": { + "en": "Free roam in the city: first raise a bounty, then lose the police; each cleared stage raises the heat and brings stronger police. You lose when the bust meter fills" + }, + "moves": [ + { + "id": "chase", + "name": { + "en": "Police chase" + }, + "tell": { + "en": "Police cars behind or beside you with flashing lights" + }, + "effect": { + "en": "When a cop is close and you are slow, the bust meter fills and you lose" + }, + "counter": { + "en": "Keep speed high and open a gap; stay out of sight to build the escape" + } + }, + { + "id": "pit", + "name": { + "en": "Cop ram" + }, + "tell": { + "en": "A cop closes beside your rear, a red warning bar appears and the mirror frame turns red" + }, + "effect": { + "en": "The hit spins you and bleeds speed" + }, + "counter": { + "en": "Accelerate away on the warning, or steer outwards" + } + }, + { + "id": "roadblock", + "name": { + "en": "Roadblock" + }, + "tell": { + "en": "Police cars blocking the road ahead, with a distance warning bar at the bottom" + }, + "effect": { + "en": "Hitting it slows you a lot, and its cops then join the chase" + }, + "counter": { + "en": "Aim for the gap" + } + }, + { + "id": "spikes", + "name": { + "en": "Spike strip" + }, + "tell": { + "en": "A spike strip on the road, with a warning bar at the bottom" + }, + "effect": { + "en": "Tyres are punctured and burst after about half a second; grip drops sharply" + }, + "counter": { + "en": "Change lane early to avoid it" + } + }, + { + "id": "trap", + "name": { + "en": "Destructible building trap" + }, + "tell": { + "en": "A roadside structure that can be knocked down" + }, + "effect": { + "en": "When knocked down it lands on cops behind you" + }, + "counter": { + "en": "Speed past it so the cops follow into its collapse" + } + }, + { + "id": "heli", + "name": { + "en": "Helicopter" + }, + "tell": { + "en": "A helicopter and spotlight overhead" + }, + "effect": { + "en": "It sees far, so hiding behind buildings is harder" + }, + "counter": { + "en": "Keep moving fast until it runs out of fuel and leaves" + }, + "only": { + "en": "higher heat stages only" + } + } + ], + "phases": [ + { + "en": "Each escape raises the heat: more and faster police cars" + } + ] + }, + { + "case_id": "nfsmw/street_champion", + "boss": { + "en": "Street champion" + }, + "summary": { + "en": "A race through city streets against the street champion while police chase you too. You lose if the rival reaches the end first or you are caught" + }, + "moves": [ + { + "id": "champ_nitrous", + "name": { + "en": "Champion's nitrous" + }, + "tell": { + "en": "Blue flame behind the rival's car" + }, + "effect": { + "en": "It speeds up noticeably for a while and pulls ahead" + }, + "counter": { + "en": "Use your own nitrous and take a shorter line to catch up" + } + }, + { + "id": "cop", + "name": { + "en": "Police chase" + }, + "tell": { + "en": "Police cars behind or beside you with flashing lights" + }, + "effect": { + "en": "The bust meter fills when a cop is close; full means loss" + }, + "counter": { + "en": "Keep speed up, avoid walls and keep moving forward" + } + }, + { + "id": "block", + "name": { + "en": "Roadblocks and spikes" + }, + "tell": { + "en": "Police cars blocking the road or a spike strip, with a warning bar at the bottom" + }, + "effect": { + "en": "Hitting them slows you or bursts a tyre, letting the rival catch up" + }, + "counter": { + "en": "Change lane early to go around" + } + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/quake2_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/quake2_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..c0d53e45ef5c403cc1f0cbfeeaeca98ccda207f4 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/quake2_remake.json @@ -0,0 +1,459 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "quake2_remake", + "rules": "q2-arena@4", + "title": { + "en": "First-Person Shooter: Boss Arena" + }, + "dimension": "3d", + "view": { + "en": "First-person 3D shooter: the crosshair is at the centre and your weapon at the lower right. The boss's name, phase and health bar are at the top; ammo, health, armour and the current weapon at the bottom. The arena has pillars, crates and other cover, with ammo, medical and armour pickups on the floor" + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose if your health reaches zero; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate: each medical or armour pickup can be taken only once, while ammo respawns over time" + }, + "mouse": { + "kind": "camera", + "en": "Y > 0 looks down; pitch is limited to about ±89°" + }, + "keys": [ + { + "key": "W", + "en": "move forward" + }, + { + "key": "S", + "en": "move backward" + }, + { + "key": "A", + "en": "strafe left" + }, + { + "key": "D", + "en": "strafe right" + }, + { + "key": "Shift", + "en": "hold to run (move faster)" + }, + { + "key": "Space", + "en": "jump" + }, + { + "key": "L", + "en": "crouch (move slower)" + }, + { + "key": "Q", + "en": "turn left with the keyboard" + }, + { + "key": "E", + "en": "turn right with the keyboard" + }, + { + "key": "J", + "en": "fire; hold for continuous fire" + }, + { + "key": "LMB", + "en": "fire (same as J)" + }, + { + "key": "K", + "en": "next weapon" + }, + { + "key": "RMB", + "en": "next weapon (same as K)" + }, + { + "key": "R", + "en": "previous weapon" + } + ], + "notes": [ + { + "en": "Each fight starts with a fixed set of weapons (such as shotguns, machine guns, a rocket launcher or a coilgun, depending on the fight); switch weapons when ammo runs low" + }, + { + "en": "Most boss attacks travel in straight lines: strafing and ducking behind cover work best" + }, + { + "en": "Bosses flinch briefly when hit; heavy weapons such as rockets interrupt them more easily" + }, + { + "en": "Coilgun-type attacks first lock onto where you are; a red warning appears at the centre of the screen, and strafing right after the lock dodges the shot" + } + ], + "compact_glossary": { + "move": { + "en": "movement (always running)", + "options": { + "none": "stand still", + "forward": "run forward", + "back": "run backward", + "left": "strafe left", + "right": "strafe right", + "forward_left": "run forward-left", + "forward_right": "run forward-right", + "back_left": "run backward-left", + "back_right": "run backward-right" + } + }, + "turn": { + "en": "horizontal turn", + "options": { + "none": "no turn", + "left_3": "turn left 3°", + "right_3": "turn right 3°", + "left_10": "turn left 10°", + "right_10": "turn right 10°", + "left_30": "turn left 30°", + "right_30": "turn right 30°" + } + }, + "pitch": { + "en": "look up / down", + "options": { + "none": "no pitch change", + "up_2": "look up 2°", + "down_2": "look down 2°" + } + }, + "action": { + "en": "fire / jump / weapon", + "options": { + "none": "nothing", + "fire": "fire for the whole 200 ms", + "fire_late": "fire, starting late in the 200 ms", + "jump": "jump", + "next_weapon": "next weapon" + } + } + }, + "scenes": [ + { + "case_id": "quake2/supertank", + "boss": { + "en": "Tracked Gun Carrier" + }, + "summary": { + "en": "A heavy tracked machine armed with a chain gun and rocket launchers rolls at you across an open-air arena." + }, + "moves": [ + { + "id": "attack1", + "name": { + "en": "Chain-gun burst" + }, + "tell": { + "en": "It turns toward you; it always uses this at close range" + }, + "effect": { + "en": "A stream of instant-hit bullets that continues as long as it can see you" + }, + "counter": { + "en": "Break line of sight behind cover" + } + }, + { + "id": "attack2", + "name": { + "en": "Triple rockets" + }, + "tell": { + "en": "At longer range it turns toward you and fires three rockets about 0.3 s apart" + }, + "effect": { + "en": "The rockets fly straight at where you were when fired and splash on impact" + }, + "counter": { + "en": "Strafe so they miss, and stay off walls" + } + } + ], + "phases": [] + }, + { + "case_id": "quake2/hornet", + "boss": { + "en": "Flying Gunship" + }, + "summary": { + "en": "A heavy gunship hovering above you attacks with twin machine guns and rocket salvos; cover only blocks low shots." + }, + "moves": [ + { + "id": "attack_mg", + "name": { + "en": "Twin machine guns" + }, + "tell": { + "en": "About 0.9 s of wind-up as it turns; it always uses this at close range" + }, + "effect": { + "en": "Both guns fire continuously, and it keeps firing more often while you are in front of it" + }, + "counter": { + "en": "Get to its side or put a full-height pillar between you" + } + }, + { + "id": "attack_rocket", + "name": { + "en": "Rocket salvo" + }, + "tell": { + "en": "After about 1.2 s of wind-up it launches four rockets at once" + }, + "effect": { + "en": "Each rocket aims at you and hits hard" + }, + "counter": { + "en": "Start strafing as soon as you see the wind-up" + } + } + ], + "phases": [ + { + "en": "It always flies a little above you, so low cover does not block its fire" + } + ] + }, + { + "case_id": "quake2/makron", + "boss": { + "en": "Twin-Cannon Mech → Armoured Pilot" + }, + "summary": { + "en": "A two-phase fight: first a twin chain-gun mech, then the pilot that jumps out of it when it is destroyed; the two share one health bar." + }, + "moves": [ + { + "id": "jorg_attack1", + "name": { + "en": "Twin chain guns (mech)" + }, + "tell": { + "en": "After about 0.8 s of wind-up both chain guns fire together" + }, + "effect": { + "en": "Instant-hit bullets that continue while it can see you" + }, + "counter": { + "en": "Break line of sight with a pillar" + } + }, + { + "id": "jorg_attack2", + "name": { + "en": "Energy orb (mech)" + }, + "tell": { + "en": "After a short wind-up it launches a slow, large green orb" + }, + "effect": { + "en": "In flight the orb zaps visible targets nearby, and its hit or blast is extremely damaging" + }, + "counter": { + "en": "Get far from it and behind cover" + } + }, + { + "id": "makron_attack3", + "name": { + "en": "Energy orb (pilot)" + }, + "tell": { + "en": "The pilot in the second phase also launches the large green orb" + }, + "effect": { + "en": "Same as above, extremely damaging" + }, + "counter": { + "en": "Get away and behind cover" + } + }, + { + "id": "makron_attack4", + "name": { + "en": "Pulse sweep (pilot)" + }, + "tell": { + "en": "After a short wind-up it fires a stream of blue energy bolts sweeping from one side to the other" + }, + "effect": { + "en": "The bolts are fast and hit everything along the sweep" + }, + "counter": { + "en": "Strafe or back behind cover before the sweep reaches you" + } + }, + { + "id": "makron_attack5", + "name": { + "en": "Coilgun (pilot)" + }, + "tell": { + "en": "While charging, a coilgun-charging warning appears, then it locks onto your position at that moment (red aim line / warning)" + }, + "effect": { + "en": "An instant piercing shot along the locked line, very damaging" + }, + "counter": { + "en": "Strafe the moment the lock warning appears" + } + } + ], + "phases": [ + { + "en": "Phase one is the twin-cannon mech; once it is destroyed the pilot appears and phase two begins" + } + ] + }, + { + "case_id": "quake2/tank_commander", + "boss": { + "en": "Chain-Gun Heavy Trooper" + }, + "summary": { + "en": "A humanoid heavy machine in a factory arena that attacks with energy-gun triple shots, rockets and a sweeping chain gun." + }, + "moves": [ + { + "id": "attack_blast", + "name": { + "en": "Energy-gun triple shot" + }, + "tell": { + "en": "It turns toward you, steps back slightly and fires three energy bolts" + }, + "effect": { + "en": "The bolts fly straight at you" + }, + "counter": { + "en": "Strafe out of the way" + } + }, + { + "id": "attack_rocket", + "name": { + "en": "Triple rockets" + }, + "tell": { + "en": "At longer range it winds up for about 2 seconds, then fires three rockets" + }, + "effect": { + "en": "The rockets hit and splash hard" + }, + "counter": { + "en": "The long wind-up is a good window to attack; dodge once it fires" + } + }, + { + "id": "attack_chain", + "name": { + "en": "Chain-gun sweep" + }, + "tell": { + "en": "After briefly turning it fires for about 2 seconds without turning further" + }, + "effect": { + "en": "A stream of instant-hit bullets" + }, + "counter": { + "en": "It does not track you while firing, so run sideways out of its line" + } + } + ], + "phases": [] + }, + { + "case_id": "quake2/gladiator", + "boss": { + "en": "Blade-Arm Gunner" + }, + "summary": { + "en": "A heavy soldier with a giant blade on one arm and a coilgun on the other, fighting at both ranges in an arena ringed by pillars." + }, + "moves": [ + { + "id": "attack_melee", + "name": { + "en": "Blade slash" + }, + "tell": { + "en": "Up close it raises its blade, with a swing sound and motion" + }, + "effect": { + "en": "Two heavy slashes that knock you back" + }, + "counter": { + "en": "Do not stand next to it; keep a medium distance" + } + }, + { + "id": "attack_gun", + "name": { + "en": "Coilgun" + }, + "tell": { + "en": "When you are a little away, it first locks onto your position (the HUD shows the lock and an aim line), then fires about 0.4 s later" + }, + "effect": { + "en": "An instant piercing shot along the locked line, very damaging" + }, + "counter": { + "en": "Strafe as soon as you see the lock; it does not use this when you are very close" + } + } + ], + "phases": [] + }, + { + "case_id": "quake2/mutant", + "boss": { + "en": "Clawed Pouncer" + }, + "summary": { + "en": "An agile clawed beast that leaps across a lab arena to close in, then strikes with both claws." + }, + "moves": [ + { + "id": "attack", + "name": { + "en": "Claw combo" + }, + "tell": { + "en": "Up close it swings its left and right claws in turn" + }, + "effect": { + "en": "Each claw hurts and pushes you back slightly; it keeps clawing while you stay in reach" + }, + "counter": { + "en": "Back away and shoot while retreating" + } + }, + { + "id": "jump", + "name": { + "en": "Pounce" + }, + "tell": { + "en": "When it is some distance away at a similar height, it leaps at you" + }, + "effect": { + "en": "The pounce hurts on hit; it cannot be interrupted until it lands" + }, + "counter": { + "en": "Move sideways right after it takes off, then hit it as it lands" + } + } + ], + "phases": [] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/sekiro_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/sekiro_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..c39ee8d88f2cfb88ee27ce4e450f97d4668f0e38 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/sekiro_remake.json @@ -0,0 +1,1008 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "sekiro_remake", + "rules": "sekiro@12", + "title": { + "en": "Third-person Swordplay: Six Boss Duels" + }, + "dimension": "3d", + "view": { + "en": "Third-person 3D: you control a shinobi. Top left: boss name, execution points and health bar; top centre: boss posture bar; bottom left: your health, revive points, gourd and poison/dread gauges; bottom centre: your posture bar. A red danger mark appears over you before a perilous attack." + }, + "goal": { + "en": "Empty the boss's health bars and land the required executions to win; you lose if health reaches zero with no revive left; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate; only the gourd restores it." + }, + "mouse": { + "kind": "camera", + "en": "The camera starts free: horizontal mouse (dx) turns it at any time, X>0 turns right. After E locks on, the camera follows the boss and mouse movement has no effect." + }, + "keys": [ + { + "key": "W", + "en": "move forward relative to the camera" + }, + { + "key": "A", + "en": "move left" + }, + { + "key": "S", + "en": "move backward" + }, + { + "key": "D", + "en": "move right" + }, + { + "key": "Shift", + "en": "tap to dash-step (short dodge with invulnerable start); hold while moving to run; tap during a posture-break stagger to recover faster" + }, + { + "key": "Space", + "en": "jump; press again in the air to kick (used to clear low sweeps)" + }, + { + "key": "J", + "en": "tap to slash, hold to charge a thrust; a fresh press up close when a red dot shows on the enemy is an execution" + }, + { + "key": "LMB", + "en": "slash (same as J)" + }, + { + "key": "K", + "en": "hold to guard; a fresh press just before impact is a deflect" + }, + { + "key": "RMB", + "en": "guard/deflect (same as K)" + }, + { + "key": "Q", + "en": "drink the gourd to restore health; you cannot attack while drinking" + }, + { + "key": "E", + "en": "toggle lock-on to the boss (starts unlocked)" + }, + { + "key": "R", + "en": "revive after death (limited uses)" + } + ], + "notes": [ + { + "en": "Fights are won through posture: deflects and hits fill the enemy's posture bar; when full they stagger and can be executed. Your own full posture bar breaks your guard." + }, + { + "en": "Guarding is held; a deflect needs a fresh guard press just before impact. The window is short and mashing shortens it." + }, + { + "en": "Perilous attacks show a red danger mark: dash toward thrusts, jump low sweeps, dash sideways or back out of grabs; none can be guarded." + }, + { + "en": "When lightning strikes, jump to catch it and press attack again before landing to return it." + }, + { + "en": "Full poison or dread gauges drain health or kill instantly; stay away from the source." + }, + { + "en": "Actions are chosen per 200 ms packet, split into 6 sub-steps; press timing is counted in sub-steps." + } + ], + "compact_glossary": { + "move": { + "en": "Movement and camera turn (12 options)", + "options": { + "none": "no movement", + "forward": "hold W", + "forward_start": "W in first half of the packet", + "forward_end": "W in second half", + "forward_tap": "one short W step", + "back": "hold S", + "left": "hold A", + "right": "hold D", + "back_left": "S+A", + "back_right": "S+D", + "turn_left_30": "turn camera left about 30 degrees", + "turn_right_30": "turn camera right about 30 degrees" + } + }, + "act": { + "en": "Action: slash, guard, deflect, dash, jump, items (one per packet)", + "options": { + "none": "no action", + "attack_0": "slash pressed at sub-step 1", + "deflect_0": "fresh guard press (deflect) at sub-step 1", + "jump_0": "jump/air kick pressed at sub-step 1", + "attack_1": "slash pressed at sub-step 2", + "deflect_1": "fresh guard press (deflect) at sub-step 2", + "jump_1": "jump/air kick pressed at sub-step 2", + "attack_2": "slash pressed at sub-step 3", + "deflect_2": "fresh guard press (deflect) at sub-step 3", + "jump_2": "jump/air kick pressed at sub-step 3", + "attack_3": "slash pressed at sub-step 4", + "deflect_3": "fresh guard press (deflect) at sub-step 4", + "jump_3": "jump/air kick pressed at sub-step 4", + "attack_4": "slash pressed at sub-step 5", + "deflect_4": "fresh guard press (deflect) at sub-step 5", + "jump_4": "jump/air kick pressed at sub-step 5", + "attack_5": "slash pressed at sub-step 6", + "deflect_5": "fresh guard press (deflect) at sub-step 6", + "jump_5": "jump/air kick pressed at sub-step 6", + "step_0": "dash-step at sub-step 1", + "step_1": "dash-step at sub-step 2", + "step_2": "dash-step at sub-step 3", + "step_3": "dash-step at sub-step 4", + "step_4": "dash-step at sub-step 5", + "deflect_attack_0_1": "guard at sub-step 1, slash at 2", + "deflect_attack_0_2": "guard at sub-step 1, slash at 3", + "deflect_attack_0_3": "guard at sub-step 1, slash at 4", + "deflect_attack_0_4": "guard at sub-step 1, slash at 5", + "deflect_attack_0_5": "guard at sub-step 1, slash at 6", + "deflect_attack_1_2": "guard at sub-step 2, slash at 3", + "deflect_attack_1_3": "guard at sub-step 2, slash at 4", + "deflect_attack_1_4": "guard at sub-step 2, slash at 5", + "deflect_attack_1_5": "guard at sub-step 2, slash at 6", + "deflect_attack_2_3": "guard at sub-step 3, slash at 4", + "deflect_attack_2_4": "guard at sub-step 3, slash at 5", + "deflect_attack_2_5": "guard at sub-step 3, slash at 6", + "deflect_attack_3_4": "guard at sub-step 4, slash at 5", + "deflect_attack_3_5": "guard at sub-step 4, slash at 6", + "deflect_attack_4_5": "guard at sub-step 5, slash at 6", + "deflect_0_4": "two deflect presses at sub-steps 1 and 5", + "deflect_0_5": "two deflect presses at sub-steps 1 and 6", + "deflect_2_4": "two deflect presses at sub-steps 3 and 5", + "deflect_2_5": "two deflect presses at sub-steps 3 and 6", + "deflect_3_5": "two deflect presses at sub-steps 4 and 6", + "deflect_2_4_5": "deflect presses at sub-steps 3, 5 and 6", + "step_alt_0": "repeated dash-steps from sub-step 1, every other", + "step_alt_1": "repeated dash-steps from sub-step 2, every other", + "jump_kick_0": "jump then air kick starting sub-step 1", + "jump_kick_1": "jump then air kick starting sub-step 2", + "jump_kick_2": "jump then air kick starting sub-step 3", + "jump_kick_3": "jump then air kick starting sub-step 4", + "jump_attack_0_1": "jump at sub-step 1, slash (lightning return) at 2", + "jump_attack_0_2": "jump at sub-step 1, slash (lightning return) at 3", + "jump_attack_0_3": "jump at sub-step 1, slash (lightning return) at 4", + "jump_attack_1_2": "jump at sub-step 2, slash (lightning return) at 3", + "jump_attack_1_3": "jump at sub-step 2, slash (lightning return) at 4", + "jump_attack_1_4": "jump at sub-step 2, slash (lightning return) at 5", + "jump_attack_2_3": "jump at sub-step 3, slash (lightning return) at 4", + "jump_attack_2_4": "jump at sub-step 3, slash (lightning return) at 5", + "jump_attack_2_5": "jump at sub-step 3, slash (lightning return) at 6", + "jump_attack_3_4": "jump at sub-step 4, slash (lightning return) at 5", + "jump_attack_3_5": "jump at sub-step 4, slash (lightning return) at 6", + "jump_attack_4_5": "jump at sub-step 5, slash (lightning return) at 6", + "guard_hold_2": "hold guard sub-steps 1-2", + "guard_hold_3": "hold guard sub-steps 1-3", + "guard_hold_6": "hold guard the whole packet", + "guard_hold_late": "hold guard sub-steps 4-6", + "run": "hold Shift to run", + "heal_0": "drink gourd at sub-step 1", + "heal_2": "drink at sub-step 3", + "heal_4": "drink at sub-step 5", + "revive": "revive after death", + "lock_toggle": "toggle boss lock-on" + } + } + }, + "scenes": [ + { + "case_id": "sekiro/demon", + "boss": { + "en": "Flame Behemoth" + }, + "summary": { + "en": "A circular yard before a burning gate. The boss never guards and has hyper armour; it only staggers when its poise breaks. Standing under its belly dodges most attacks." + }, + "moves": [ + { + "id": "arm_swing", + "name": { + "en": "Arm swing" + }, + "tell": { + "en": "Raises an arm then sweeps forward" + }, + "effect": { + "en": "Single melee hit that costs health and posture" + }, + "counter": { + "en": "Deflect or guard it, or move in under the belly" + } + }, + { + "id": "stomp", + "name": { + "en": "Stomp" + }, + "tell": { + "en": "Lifts a foot and holds about a second" + }, + "effect": { + "en": "Ground impact with heavy damage" + }, + "counter": { + "en": "Sidestep or dash before it lands, then counterattack" + } + }, + { + "id": "fire_combo", + "name": { + "en": "Fire arm" + }, + "tell": { + "en": "An arm ignites then slams down" + }, + "effect": { + "en": "Cannot be deflected; guarding only reduces damage and builds burn" + }, + "counter": { + "en": "Dash or back away; do not guard it" + } + }, + { + "id": "fireballs", + "name": { + "en": "Fireballs" + }, + "tell": { + "en": "Hands wave and each wave lobs a fireball" + }, + "effect": { + "en": "Bursts on landing and leaves fire on the ground" + }, + "counter": { + "en": "Dash through or stay clear of landing spots" + } + }, + { + "id": "blast_leap", + "name": { + "en": "Blast leap" + }, + "tell": { + "en": "Crouches then leaps high" + }, + "effect": { + "en": "Large explosion on landing; cannot be guarded" + }, + "counter": { + "en": "Run away or be airborne at landing; about a second of opening afterwards" + } + }, + { + "id": "charge", + "name": { + "en": "Perilous charge" + }, + "tell": { + "en": "A red danger mark appears and the boss rushes" + }, + "effect": { + "en": "Perilous attack with heavy damage" + }, + "counter": { + "en": "Jump over it" + } + }, + { + "id": "fire_ring", + "name": { + "en": "Fire ring" + }, + "tell": { + "en": "A ring of fire spreads on the ground (third phase)" + }, + "effect": { + "en": "Touching it knocks you back and burns you; comes with a perilous sweep" + }, + "counter": { + "en": "Jump over the ring" + }, + "only": { + "en": "some phases only" + } + } + ], + "phases": [ + { + "en": "Once burn fills, health drains continuously and posture stops recovering" + }, + { + "en": "The third phase adds the fire ring, homing fireballs and a whip of fire" + } + ] + }, + { + "case_id": "sekiro/genichiro", + "boss": { + "en": "Bow-and-Blade Swordsman" + }, + "summary": { + "en": "A rectangular rooftop arena. He mixes sword and bow and has several health bars; in the last he becomes a lightning-calling swordsman." + }, + "moves": [ + { + "id": "slash", + "name": { + "en": "Slash" + }, + "tell": { + "en": "Raises his sword for a straight cut" + }, + "effect": { + "en": "Single hit costing health and posture" + }, + "counter": { + "en": "Best deflected; guarding also works" + } + }, + { + "id": "passage", + "name": { + "en": "String of cuts" + }, + "tell": { + "en": "Two opening cuts, a spin, then many cuts ending in an uppercut" + }, + "effect": { + "en": "Multi-hit string; the last hit pushes both back" + }, + "counter": { + "en": "Deflect each cut; do not mash" + } + }, + { + "id": "thrust", + "name": { + "en": "Perilous thrust" + }, + "tell": { + "en": "Red danger mark, blade pointed forward" + }, + "effect": { + "en": "Thrust with heavy damage" + }, + "counter": { + "en": "Dash toward him to stomp the thrust for big posture damage" + } + }, + { + "id": "sweep", + "name": { + "en": "Perilous sweep" + }, + "tell": { + "en": "Red danger mark, blade sweeps low" + }, + "effect": { + "en": "Low sweep" + }, + "counter": { + "en": "Jump it; kick in the air" + } + }, + { + "id": "grab", + "name": { + "en": "Perilous grab" + }, + "tell": { + "en": "Red danger mark, he reaches out" + }, + "effect": { + "en": "Grab that cannot be blocked" + }, + "counter": { + "en": "Dash sideways or backwards" + } + }, + { + "id": "volley", + "name": { + "en": "Bow shots" + }, + "tell": { + "en": "Backs off and draws his bow, firing single or charged arrows" + }, + "effect": { + "en": "Arrows hurt; charged shots have armour" + }, + "counter": { + "en": "Dash aside, then close in" + } + }, + { + "id": "lightning_slash", + "name": { + "en": "Lightning strike" + }, + "tell": { + "en": "Final bar: he crouches and leaps, then lightning strikes (danger mark)" + }, + "effect": { + "en": "Bolt along a line or arc; very heavy damage" + }, + "counter": { + "en": "Jump to catch the bolt in the air, then press attack before landing to return it" + }, + "only": { + "en": "some phases only" + } + }, + { + "id": "heal_punish", + "name": { + "en": "Punishes healing" + }, + "tell": { + "en": "You drink while he is idle" + }, + "effect": { + "en": "He always answers with a charged shot or a dive thrust" + }, + "counter": { + "en": "Do not drink while he stands idle" + } + } + ], + "phases": [ + { + "en": "The first two bars are the swordsman; the last becomes the lightning swordsman with bolts" + }, + { + "en": "Each bar needs an execution to finish" + } + ] + }, + { + "case_id": "sekiro/guardian_ape", + "boss": { + "en": "Valley Giant Ape" + }, + "summary": { + "en": "A round valley pool. First form: a hyper-armoured four-legged beast with poison. Second form: a headless apparition with a sword." + }, + "moves": [ + { + "id": "slam_combo", + "name": { + "en": "Slam combo" + }, + "tell": { + "en": "Raises fists and slams four times" + }, + "effect": { + "en": "Multi-hit slams" + }, + "counter": { + "en": "Guardable; deflect each if possible" + } + }, + { + "id": "swipe_grab", + "name": { + "en": "Perilous grab" + }, + "tell": { + "en": "Red danger mark, a huge arm sweeps to grab" + }, + "effect": { + "en": "Ground grab; cannot be guarded" + }, + "counter": { + "en": "Jump over it" + } + }, + { + "id": "belly_flop", + "name": { + "en": "Belly flop" + }, + "tell": { + "en": "Danger mark, it throws itself down" + }, + "effect": { + "en": "Body slam that cannot be jumped" + }, + "counter": { + "en": "Back away" + } + }, + { + "id": "fart", + "name": { + "en": "Poison gas and dung" + }, + "tell": { + "en": "Releases a gas cloud then flees and throws dung" + }, + "effect": { + "en": "Fills the poison gauge; once full, health drains" + }, + "counter": { + "en": "Leave the cloud and dodge the throw" + } + }, + { + "id": "sword4", + "name": { + "en": "Four cuts" + }, + "tell": { + "en": "Headless form chops four times" + }, + "effect": { + "en": "Multi-hit melee, deflectable" + }, + "counter": { + "en": "Deflect each cut" + }, + "only": { + "en": "some phases only" + } + }, + { + "id": "diving_lunge", + "name": { + "en": "Diving lunge" + }, + "tell": { + "en": "Headless form leaps and dives" + }, + "effect": { + "en": "Heavy hit; afterwards its neck is exposed" + }, + "counter": { + "en": "Deflect or dodge, then attack the exposed neck" + }, + "only": { + "en": "some phases only" + } + }, + { + "id": "scream_long", + "name": { + "en": "Blood roar" + }, + "tell": { + "en": "Headless form throws back its head and roars (danger mark)" + }, + "effect": { + "en": "Fills the dread gauge; full means instant death; guarding is useless" + }, + "counter": { + "en": "Get out of range" + }, + "only": { + "en": "some phases only" + } + }, + { + "id": "overhead_slam", + "name": { + "en": "Perilous slam" + }, + "tell": { + "en": "Danger mark, jump then heavy slam" + }, + "effect": { + "en": "Heavy damage; deflect for big posture damage" + }, + "counter": { + "en": "Deflect or dodge" + }, + "only": { + "en": "some phases only" + } + } + ], + "phases": [ + { + "en": "The first execution is fake; it rises again with a hidden bar" + }, + { + "en": "The second form drops poison and uses the roar to build dread" + } + ] + }, + { + "case_id": "sekiro/gyoubu", + "boss": { + "en": "Mounted Spear General" + }, + "summary": { + "en": "A large circular yard before a gate. The mounted boss never guards and has hyper armour until poise breaks; there is no grappling hook, and after riding off he always charges back." + }, + "moves": [ + { + "id": "combo3", + "name": { + "en": "Three cuts" + }, + "tell": { + "en": "Three close cuts" + }, + "effect": { + "en": "The third is heavy; deflecting it staggers him" + }, + "counter": { + "en": "Deflect the third cut" + } + }, + { + "id": "thrust_near", + "name": { + "en": "Perilous thrust" + }, + "tell": { + "en": "Danger mark, close spear thrust" + }, + "effect": { + "en": "Heavy thrust" + }, + "counter": { + "en": "Dash toward him to stomp it" + } + }, + { + "id": "horse_kick", + "name": { + "en": "Horse kick" + }, + "tell": { + "en": "Hooves rise when you stand directly behind" + }, + "effect": { + "en": "Kick that staggers" + }, + "counter": { + "en": "Stay out of the rear" + } + }, + { + "id": "charge_sweep", + "name": { + "en": "Perilous charge" + }, + "tell": { + "en": "Danger mark, he gallops at you" + }, + "effect": { + "en": "Rides through, then rides off and turns back" + }, + "counter": { + "en": "Jump or sidestep" + } + }, + { + "id": "figure8", + "name": { + "en": "Figure-eight" + }, + "tell": { + "en": "Circles you with repeated strikes" + }, + "effect": { + "en": "Multiple hits" + }, + "counter": { + "en": "Deflect each or back off" + } + }, + { + "id": "rope_sweep", + "name": { + "en": "Rope-spear sweep" + }, + "tell": { + "en": "Swings a roped spearhead in wide circles" + }, + "effect": { + "en": "Three wide circles; guardable" + }, + "counter": { + "en": "Guard or deflect" + } + }, + { + "id": "rope_thrust", + "name": { + "en": "Rope-spear thrust" + }, + "tell": { + "en": "Danger mark, spearhead shot in a line" + }, + "effect": { + "en": "Line attack that cannot be guarded" + }, + "counter": { + "en": "Deflect only, or sidestep" + } + }, + { + "id": "jump_attack", + "name": { + "en": "Jump attack" + }, + "tell": { + "en": "Leaps then slams twice" + }, + "effect": { + "en": "Two heavy slams" + }, + "counter": { + "en": "Deflect or back away" + } + } + ], + "phases": [ + { + "en": "Hits land but cannot interrupt him; jumping cuts above the waist deal large posture damage" + } + ] + }, + { + "case_id": "sekiro/isshin", + "boss": { + "en": "Old Sword-and-Spear Master" + }, + "summary": { + "en": "A circular grass field. First a lightning swordsman, then the old master with sword, with spear and matchlock, and finally with lightning added." + }, + "moves": [ + { + "id": "cross", + "name": { + "en": "Cross cut" + }, + "tell": { + "en": "Two crossing cuts" + }, + "effect": { + "en": "Two hits" + }, + "counter": { + "en": "Deflect both" + } + }, + { + "id": "dragon_flash", + "name": { + "en": "Ranged slash" + }, + "tell": { + "en": "Red blade wave at range (unblockable)" + }, + "effect": { + "en": "Long-range slash" + }, + "counter": { + "en": "Dash or run away" + } + }, + { + "id": "mortal_blade", + "name": { + "en": "Dark blade" + }, + "tell": { + "en": "Black-red blade spreads out" + }, + "effect": { + "en": "Unblockable, twice" + }, + "counter": { + "en": "Dash through or run" + } + }, + { + "id": "wind_v", + "name": { + "en": "Energy blade" + }, + "tell": { + "en": "Sword launches a wave" + }, + "effect": { + "en": "Guarding bleeds health; deflecting does not hurt posture" + }, + "counter": { + "en": "Sidestep vertical waves; jump flat ones" + } + }, + { + "id": "pose_thrust", + "name": { + "en": "Perilous thrust" + }, + "tell": { + "en": "Pose then perilous thrust" + }, + "effect": { + "en": "Heavy damage" + }, + "counter": { + "en": "Dash toward him to stomp it" + } + }, + { + "id": "spear_sweep", + "name": { + "en": "Perilous spear sweep" + }, + "tell": { + "en": "Spear danger-mark sweep" + }, + "effect": { + "en": "Low sweep" + }, + "counter": { + "en": "Jump" + }, + "only": { + "en": "some phases only" + } + }, + { + "id": "quad_shot", + "name": { + "en": "Four-shot volley" + }, + "tell": { + "en": "Backs off and fires four times, the last delayed" + }, + "effect": { + "en": "Guarding costs much posture; deflecting costs less" + }, + "counter": { + "en": "Dash or deflect; a perilous attack always follows" + }, + "only": { + "en": "some phases only" + } + }, + { + "id": "thunder_chop", + "name": { + "en": "Lightning chop" + }, + "tell": { + "en": "Cannot be interrupted while charging; bolt falls" + }, + "effect": { + "en": "Heavy lightning damage" + }, + "counter": { + "en": "Jump and return the bolt" + }, + "only": { + "en": "some phases only" + } + } + ], + "phases": [ + { + "en": "Lightning swordsman, sword, spear and matchlock, then lightning added; several bars" + }, + { + "en": "Each bar needs an execution" + } + ] + }, + { + "case_id": "sekiro/lady_butterfly", + "boss": { + "en": "Thread Kunoichi" + }, + "summary": { + "en": "A courtyard with rows of pillars. She uses threads, kunai and aerial grabs; the second phase adds illusions and homing butterflies." + }, + "moves": [ + { + "id": "kunai_throw", + "name": { + "en": "Kunai throw" + }, + "tell": { + "en": "Throws two kunai in quick succession" + }, + "effect": { + "en": "Ranged damage" + }, + "counter": { + "en": "Sidestep or deflect" + } + }, + { + "id": "three_strike", + "name": { + "en": "Three strikes" + }, + "tell": { + "en": "Two cuts then a downward strike" + }, + "effect": { + "en": "Multi-hit" + }, + "counter": { + "en": "Deflect each" + } + }, + { + "id": "sweep", + "name": { + "en": "Perilous sweep" + }, + "tell": { + "en": "Danger mark, two low sweeps" + }, + "effect": { + "en": "Low, heavy damage" + }, + "counter": { + "en": "Jump-kick for large posture damage" + } + }, + { + "id": "drop_grab", + "name": { + "en": "Perilous aerial grab" + }, + "tell": { + "en": "She climbs a thread, then dives with a danger mark" + }, + "effect": { + "en": "Grab that cannot be jumped" + }, + "counter": { + "en": "Back away" + } + }, + { + "id": "illusion", + "name": { + "en": "Illusions" + }, + "tell": { + "en": "Summons decoys that become homing butterflies" + }, + "effect": { + "en": "Butterflies chase you" + }, + "counter": { + "en": "Slash decoys; run straight and use pillars to block butterflies" + }, + "only": { + "en": "some phases only" + } + }, + { + "id": "flurry", + "name": { + "en": "Flurry" + }, + "tell": { + "en": "Kick then many cuts, ending in a perilous sweep" + }, + "effect": { + "en": "Multi-hit with a perilous finish" + }, + "counter": { + "en": "Deflect cuts, jump the finish" + }, + "only": { + "en": "some phases only" + } + } + ], + "phases": [ + { + "en": "After the first execution she rises into the illusion phase" + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/soulknight_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/soulknight_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..2440d48a8e491e6d72167cd45fcd65f7ad9c95b0 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/soulknight_remake.json @@ -0,0 +1,652 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "soulknight_remake", + "rules": "knight-arena@6", + "title": { + "en": "Pixel Dungeon: Boss Rooms" + }, + "dimension": "2d", + "view": { + "en": "Top-down 2D dungeon room with crates, pillars or trees as cover. You control an armoured gunner, and the mouse moves a crosshair; your health (red), armour (grey) and energy (blue) are at the top left, the boss's name, health bar and phase at the top centre, and your current weapon at the bottom right" + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose if your health reaches zero; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate" + }, + "mouse": { + "kind": "pointer", + "en": "Weapons attack toward the crosshair; if you leave the mouse still for about 2 seconds while the boss is in sight, the crosshair pulls toward the boss automatically" + }, + "keys": [ + { + "key": "W", + "en": "move up" + }, + { + "key": "A", + "en": "move left" + }, + { + "key": "S", + "en": "move down" + }, + { + "key": "D", + "en": "move right" + }, + { + "key": "J", + "en": "hold to attack: guns keep firing, the broad blade swings; with a gun at point-blank range you stab with a knife automatically" + }, + { + "key": "LMB", + "en": "hold to attack (same as J)" + }, + { + "key": "K", + "en": "skill \"duplicate weapon\": wield a second copy of the current weapon for 5 seconds, then a 10-second cooldown" + }, + { + "key": "RMB", + "en": "skill \"duplicate weapon\" (same as K)" + }, + { + "key": "Q", + "en": "switch to the next weapon: basic pistol → repeater gun → bullet-clearing broad blade" + } + ], + "notes": [ + { + "en": "WASD combine into eight directions; you move slower while holding attack" + }, + { + "en": "Armour absorbs damage before health; after about 3 seconds without being hit, armour regenerates 1 point per second" + }, + { + "en": "The repeater gun and the broad blade use energy per attack; the basic pistol is free, so switch back to it when energy runs out" + }, + { + "en": "The broad blade's swing destroys ordinary bullets inside its arc" + }, + { + "en": "Switching weapons ends \"duplicate weapon\" immediately" + }, + { + "en": "At half health the boss enters its second phase (enraged): it attacks faster, its bullets fly faster, and it gains new attacks" + }, + { + "en": "There is no roll or jump; dodge by moving and using cover" + } + ], + "compact_glossary": { + "move": { + "en": "movement", + "options": { + "none": "stand still", + "right": "walk right", + "down_right": "walk down-right", + "down": "walk down", + "down_left": "walk down-left", + "left": "walk left", + "up_left": "walk up-left", + "up": "walk up", + "up_right": "walk up-right" + } + }, + "aim": { + "en": "crosshair", + "options": { + "none": "keep the crosshair still (after 2 s it auto-aims at a visible boss)", + "right_40": "move the crosshair 40 px right", + "down_right_40": "move the crosshair 40 px down-right", + "down_40": "move the crosshair 40 px down", + "down_left_40": "move the crosshair 40 px down-left", + "left_40": "move the crosshair 40 px left", + "up_left_40": "move the crosshair 40 px up-left", + "up_40": "move the crosshair 40 px up", + "up_right_40": "move the crosshair 40 px up-right" + } + }, + "act": { + "en": "attack / skill / weapon", + "options": { + "none": "do not attack", + "fire": "hold attack", + "fire_skill": "hold attack and use the duplicate-weapon skill", + "switch": "switch to the next weapon (then keep attacking)" + } + } + }, + "scenes": [ + { + "case_id": "soulknight/goblin_priest", + "boss": { + "en": "Meteor Caller" + }, + "summary": { + "en": "A caster walks around an open room, calling meteors, orbiting orbs, turrets and star bullets." + }, + "moves": [ + { + "id": "meteor", + "name": { + "en": "Meteors" + }, + "tell": { + "en": "Several impact markers appear on the ground (more when enraged)" + }, + "effect": { + "en": "Meteors hit the marked spots" + }, + "counter": { + "en": "Leave the marked spots as soon as they appear" + } + }, + { + "id": "orbs", + "name": { + "en": "Orbiting orbs" + }, + "tell": { + "en": "Two orbs circle the boss and can stack up" + }, + "effect": { + "en": "Touching an orb hurts" + }, + "counter": { + "en": "Keep your distance from the boss" + } + }, + { + "id": "turrets", + "name": { + "en": "Turrets" + }, + "tell": { + "en": "It fires a shot that leaves a line of turrets behind it" + }, + "effect": { + "en": "The turrets fire sideways, perpendicular to the line" + }, + "counter": { + "en": "Do not stand beside the turret line; the broad blade can destroy turrets" + } + }, + { + "id": "stars", + "name": { + "en": "Star burst" + }, + "tell": { + "en": "It releases a ring of six stars" + }, + "effect": { + "en": "Each star splits into three smaller bullets" + }, + "counter": { + "en": "Slip through the gaps between the stars" + } + } + ], + "phases": [ + { + "en": "When enraged it calls four meteors instead of three and attacks faster" + } + ] + }, + { + "case_id": "soulknight/christmas_treant", + "boss": { + "en": "Ram Timber" + }, + "summary": { + "en": "A walking tree that hides among two rings of crates; it holds up an energy ball that sprays bullets, sends shockwaves, and rams you once enraged." + }, + "moves": [ + { + "id": "hold", + "name": { + "en": "Held energy ball" + }, + "tell": { + "en": "It raises a big energy ball overhead" + }, + "effect": { + "en": "The ball sprays bullets in every direction" + }, + "counter": { + "en": "Hide behind crates" + } + }, + { + "id": "throw", + "name": { + "en": "Ball throw" + }, + "tell": { + "en": "It throws the held ball at you" + }, + "effect": { + "en": "It sprays bullets in flight and explodes on impact" + }, + "counter": { + "en": "Sidestep its flight path" + } + }, + { + "id": "waves", + "name": { + "en": "Shockwaves" + }, + "tell": { + "en": "Lines appear on the ground and shockwaves travel along them" + }, + "effect": { + "en": "The shockwaves hurt" + }, + "counter": { + "en": "Step off the drawn lines" + } + }, + { + "id": "charge", + "name": { + "en": "Ram" + }, + "tell": { + "en": "A charge band toward you appears on the ground; when it brightens the direction is locked" + }, + "effect": { + "en": "It dashes straight along the band, smashing through crates, and takes no damage while charging" + }, + "counter": { + "en": "Leave the band as soon as it brightens" + } + }, + { + "id": "homing", + "name": { + "en": "Homing shots" + }, + "tell": { + "en": "It releases five homing shots that start chasing you after a short pause" + }, + "effect": { + "en": "They hurt on hit" + }, + "counter": { + "en": "Circle around cover so they hit obstacles" + } + }, + { + "id": "cross", + "name": { + "en": "Cross bullets" + }, + "tell": { + "en": "It fires big cross-shaped bullets all around" + }, + "effect": { + "en": "They hurt on hit" + }, + "counter": { + "en": "Stand in the gaps between them" + } + }, + { + "id": "line", + "name": { + "en": "Shockwave line" + }, + "tell": { + "en": "It sends a line of shockwaves toward you" + }, + "effect": { + "en": "The shockwaves hurt" + }, + "counter": { + "en": "Move sideways off the line" + } + } + ], + "phases": [ + { + "en": "Entering the enraged phase it sends shockwaves in seven directions, then adds the ram, homing shots, cross bullets and the shockwave line" + } + ] + }, + { + "case_id": "soulknight/devils_snare", + "boss": { + "en": "Spin Bloom" + }, + "summary": { + "en": "A poison flower that almost always sits in its own poison pool, pressing you with slow bubbles, rotating bullet streams and poison shots; it sprouts tentacles when enraged." + }, + "moves": [ + { + "id": "bubbles", + "name": { + "en": "Slow bubbles" + }, + "tell": { + "en": "It blows a ring of slow bubbles that fade after a few seconds" + }, + "effect": { + "en": "Bubbles hurt on contact" + }, + "counter": { + "en": "Weave slowly between them" + } + }, + { + "id": "rotate", + "name": { + "en": "Rotating streams" + }, + "tell": { + "en": "Bullet streams fire from four points in four directions and rotate; they are slower than you" + }, + "effect": { + "en": "The streams hurt on hit" + }, + "counter": { + "en": "Circle in the same direction as the rotation" + } + }, + { + "id": "beams", + "name": { + "en": "Poison beams" + }, + "tell": { + "en": "It fires green beam-like bullets all around" + }, + "effect": { + "en": "They hurt and poison you" + }, + "counter": { + "en": "Get behind cover or back off" + } + }, + { + "id": "pool", + "name": { + "en": "Poison pool" + }, + "tell": { + "en": "It spreads a poison pool beneath itself" + }, + "effect": { + "en": "Standing in it poisons and slows you" + }, + "counter": { + "en": "Do not fight up close; attack from outside the pool" + } + }, + { + "id": "corner", + "name": { + "en": "Corner shots" + }, + "tell": { + "en": "Four fast bullets fly toward the room's corners, leaving spreading bubble trails" + }, + "effect": { + "en": "Both the bullets and the bubbles hurt" + }, + "counter": { + "en": "Stay off the lines toward the corners" + } + }, + { + "id": "pull", + "name": { + "en": "Pulling wave" + }, + "tell": { + "en": "It releases a wave that pulls you toward it" + }, + "effect": { + "en": "It deals no damage but drags you toward danger; walls partly block it" + }, + "counter": { + "en": "Move away from it and hug a wall" + } + } + ], + "phases": [ + { + "en": "When enraged the flower opens and four tentacles appear; it then adds corner shots and the pulling wave, and mixes poison shots into the rotating streams" + } + ] + }, + { + "case_id": "soulknight/grand_slime", + "boss": { + "en": "Swell Jelly" + }, + "summary": { + "en": "A big jelly boss in a room with slowing and speeding floor tiles: it slams the ground for bullets, summons small jellies, and once enraged swells up and explodes after taking enough hits." + }, + "moves": [ + { + "id": "slam", + "name": { + "en": "Ground slam" + }, + "tell": { + "en": "It slams the ground twice" + }, + "effect": { + "en": "Clusters of red bullets fly out in random directions at random speeds" + }, + "counter": { + "en": "Back off and find gaps between the bullets" + } + }, + { + "id": "rings", + "name": { + "en": "Bullet rings" + }, + "tell": { + "en": "It fires four rings of bullets in quick succession" + }, + "effect": { + "en": "The bullets stop mid-air after a distance and slowly form a flower shape" + }, + "counter": { + "en": "Pass through the gaps between the petals" + } + }, + { + "id": "spawn", + "name": { + "en": "Summon small jellies" + }, + "tell": { + "en": "It spawns a small jelly beside itself" + }, + "effect": { + "en": "Small jellies hurt on contact" + }, + "counter": { + "en": "Clear them as you go" + } + }, + { + "id": "goo", + "name": { + "en": "Goo slam" + }, + "tell": { + "en": "It slams the ground, leaving a green poison pool and lingering bullets" + }, + "effect": { + "en": "The pool poisons you and the bullets hurt" + }, + "counter": { + "en": "Stay out of the pool" + } + } + ], + "phases": [ + { + "en": "Once enraged it explodes right away (the expanding circle is the blast radius), and again after about 15 more hits; the slow and boost tiles affect the boss too" + } + ] + }, + { + "case_id": "soulknight/varkolyn_leader", + "boss": { + "en": "Violet Sweeper" + }, + "summary": { + "en": "A cloaked boss in a room with no cover at all, casting purple poison pools, tentacles and a sweeping laser; it is invulnerable while standing in a pool." + }, + "moves": [ + { + "id": "pools", + "name": { + "en": "Purple pools" + }, + "tell": { + "en": "It lays four purple pools in a line toward you" + }, + "effect": { + "en": "The pools poison and slow you; the boss is invulnerable while it stands in one" + }, + "counter": { + "en": "Avoid the pools; while it is in one, dodge and wait until it steps out" + } + }, + { + "id": "tentacles", + "name": { + "en": "Tentacles" + }, + "tell": { + "en": "Four tentacles sprout at random spots in the room" + }, + "effect": { + "en": "The tentacles attack you when you are near" + }, + "counter": { + "en": "Keep away from them, or destroy them first" + } + }, + { + "id": "ring", + "name": { + "en": "Bullet ring" + }, + "tell": { + "en": "It fires small bullets in every direction" + }, + "effect": { + "en": "They hurt on hit" + }, + "counter": { + "en": "Find the gaps between them" + } + }, + { + "id": "laser", + "name": { + "en": "Sweeping laser" + }, + "tell": { + "en": "It rings a sharp chime, and the starting line and the swept sector are drawn on the floor" + }, + "effect": { + "en": "The laser sweeps through the sector for heavy damage; it does nothing else while firing" + }, + "counter": { + "en": "Leave the drawn sector at the chime, then counterattack after the sweep" + } + }, + { + "id": "orb", + "name": { + "en": "Spiral orb" + }, + "tell": { + "en": "It fires a large bullet that keeps spinning out spirals of small bullets" + }, + "effect": { + "en": "Both hurt; the spirals stop only when the large bullet is destroyed" + }, + "counter": { + "en": "Destroy the large bullet first" + } + } + ], + "phases": [ + { + "en": "When enraged it attacks more often, and the laser charges faster and sweeps faster" + } + ] + }, + { + "case_id": "soulknight/volcanic_sandworm", + "boss": { + "en": "Burrow Bomber" + }, + "summary": { + "en": "A big worm in a room with stacked crates in the corners fires explosive shells and spreads, burrows underground, and surfaces near you." + }, + "moves": [ + { + "id": "explosive", + "name": { + "en": "Explosive shell" + }, + "tell": { + "en": "It leans back and fires a large explosive shell; its blast radius is drawn around it in flight" + }, + "effect": { + "en": "It explodes on hitting a wall, a crate or you, over a wide area" + }, + "counter": { + "en": "Sidestep it and leave the drawn blast circle" + } + }, + { + "id": "spread", + "name": { + "en": "Wide spread" + }, + "tell": { + "en": "It fires a wide fan of big bullets that slow down as they travel" + }, + "effect": { + "en": "They burst in a small blast on impact" + }, + "counter": { + "en": "Back off and slip between them" + } + }, + { + "id": "dig", + "name": { + "en": "Burrow" + }, + "tell": { + "en": "It sinks underground and only a moving dirt mound is visible (the HUD shows that it cannot be attacked)" + }, + "effect": { + "en": "Burrowing and surfacing cause shockwaves, and it leaves stars that fire bullets around" + }, + "counter": { + "en": "Stay away from the mound and attack after it surfaces" + } + } + ], + "phases": [ + { + "en": "When enraged it burrows faster and makes several quick dives, briefly surfacing between them, and leaves more bullets each time it comes up" + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/terraria_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/terraria_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..66e21dc1cb9f438980b756f09e8fd41066168b4a --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/terraria_remake.json @@ -0,0 +1,462 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "terraria_remake", + "rules": "terraria-1458-arena-r7", + "title": { + "en": "Pixel Arena: Sword and Bow" + }, + "dimension": "2d", + "view": { + "en": "Side-view 2D arena: two wooden platforms you can stand on above the ground, with pillars at both edges. You control an adventurer with a sword and a bow, and the mouse moves a crosshair; your health, flight and mana bars are at the top left, the boss's name, health bar and phase at the top right" + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose if your health reaches zero; each fight lasts at most 300 seconds and a timeout is not a win. Health does not regenerate on its own; only hearts sometimes dropped by defeated minions or boss segments restore it" + }, + "mouse": { + "kind": "pointer", + "en": "The bow fires toward the crosshair; the crosshair starts at the centre of the arena" + }, + "keys": [ + { + "key": "A", + "en": "move left (speeds up to a sprint)" + }, + { + "key": "D", + "en": "move right (speeds up to a sprint)" + }, + { + "key": "Space", + "en": "jump, higher the longer you hold it; holding it in the air flies for a short time, and once flight runs out holding it glides" + }, + { + "key": "S", + "en": "drop down through the wooden platform you stand on" + }, + { + "key": "J", + "en": "use the current weapon (sword or bow)" + }, + { + "key": "LMB", + "en": "use the current weapon (same as J)" + }, + { + "key": "Q", + "en": "switch the current weapon between sword and bow" + }, + { + "key": "E", + "en": "shoot the bow at the crosshair directly" + }, + { + "key": "RMB", + "en": "swing the sword directly" + } + ], + "notes": [ + { + "en": "Flight refills when you land and lasts about 1.5 seconds" + }, + { + "en": "The bow fires about every 0.33 s and the sword swings about every 0.38 s; holding the attack key repeats automatically" + }, + { + "en": "The sword sweeps an arc in the direction you face and can hit several targets at once; arrows fly toward the crosshair and stop at the first target. Both can destroy the boss's projectiles" + }, + { + "en": "You are briefly invulnerable after being hit; attacking or flying gives no invulnerability" + }, + { + "en": "The easy, normal and hard tiers all use classic rules; moves tagged [expert mode only] appear only at difficulty 0.75 or above" + } + ], + "compact_glossary": {}, + "scenes": [ + { + "case_id": "terraria/king_slime", + "boss": { + "en": "Bouncing Gel Giant" + }, + "summary": { + "en": "A giant gel creature keeps leaping to crush you, sheds small gel blobs when hit, and sometimes vanishes and reappears near you." + }, + "moves": [ + { + "id": "jump", + "name": { + "en": "Leap" + }, + "tell": { + "en": "Watch the direction and arc of its jump" + }, + "effect": { + "en": "It lands on you with its body; touching it hurts" + }, + "counter": { + "en": "Step aside from the landing spot and attack while it pauses after landing" + } + }, + { + "id": "low_jump", + "name": { + "en": "Low leap" + }, + "tell": { + "en": "The third of every four jumps is lower and faster sideways" + }, + "effect": { + "en": "It rushes in low and fast; touching it hurts" + }, + "counter": { + "en": "Jump over it, or fly briefly and let it pass underneath" + } + }, + { + "id": "high_jump", + "name": { + "en": "High leap" + }, + "tell": { + "en": "The fourth of every four jumps goes very high" + }, + "effect": { + "en": "It comes down from high up over a wide area" + }, + "counter": { + "en": "Run along the ground away from where it is heading" + } + }, + { + "id": "teleport", + "name": { + "en": "Teleport" + }, + "tell": { + "en": "Its body fades out over about a second, then reappears over half a second, usually not far from you" + }, + "effect": { + "en": "Once it reappears it can hit you again" + }, + "counter": { + "en": "Keep moving once it starts fading, then attack after it reappears" + } + } + ], + "phases": [ + { + "en": "It shrinks and jumps more often as it loses health, and spawns small gel blobs when damaged" + } + ] + }, + { + "case_id": "terraria/eye_of_cthulhu", + "boss": { + "en": "Charging Giant Eye" + }, + "summary": { + "en": "A huge floating eyeball that summons small eyes and then charges at you repeatedly; after losing half its health it transforms and charges harder." + }, + "moves": [ + { + "id": "dash", + "name": { + "en": "Triple charge" + }, + "tell": { + "en": "It hovers, then charges at you three times; each charge keeps its direction once it starts" + }, + "effect": { + "en": "Contact damage" + }, + "counter": { + "en": "Move sideways once it commits, then attack as it slows at the end of the charge" + } + }, + { + "id": "transform", + "name": { + "en": "Transformation" + }, + "tell": { + "en": "It spins in place and its pupil turns into a mouth (in expert mode it also summons extra small eyes)" + }, + "effect": { + "en": "Afterwards it enters its second form and charges faster" + }, + "counter": { + "en": "You can hit it while it transforms; watch the small eyes still around" + } + }, + { + "id": "chain_dash", + "name": { + "en": "Rapid charges" + }, + "tell": { + "en": "In its second form it adds faster rushes after the three normal charges, almost nonstop at low health" + }, + "effect": { + "en": "Contact damage" + }, + "counter": { + "en": "Keep changing direction; never stand still" + }, + "only": { + "en": "expert mode only" + } + } + ], + "phases": [ + { + "en": "In the first form it summons small eyes that ram you; it transforms into the second form at about half health" + } + ] + }, + { + "case_id": "terraria/skeletron", + "boss": { + "en": "Twin-Handed Giant Skull" + }, + "summary": { + "en": "A giant skull with two independent hands: the hands slam and sweep, and the skull periodically spins after you." + }, + "moves": [ + { + "id": "hand_sweep", + "name": { + "en": "Hand slams" + }, + "tell": { + "en": "Each hand rises and slams down, or lines up with you and sweeps sideways" + }, + "effect": { + "en": "The hands hurt on contact" + }, + "counter": { + "en": "Destroy the hands first; the skull becomes weaker and spins slower" + } + }, + { + "id": "spin", + "name": { + "en": "Spinning chase" + }, + "tell": { + "en": "After hovering for a while it roars, then spins after you for several seconds" + }, + "effect": { + "en": "The spinning skull hurts on contact" + }, + "counter": { + "en": "Its defence drops while spinning; dodge and hit it" + } + }, + { + "id": "skull_shot", + "name": { + "en": "Homing skulls" + }, + "tell": { + "en": "Once the skull is hurt enough or a hand is destroyed, it fires skulls that home in on you; not while spinning" + }, + "effect": { + "en": "The projectiles hurt on hit" + }, + "counter": { + "en": "Change direction to shake them off" + }, + "only": { + "en": "expert mode only" + } + } + ], + "phases": [] + }, + { + "case_id": "terraria/eater_of_worlds", + "boss": { + "en": "Burrowing Great Worm" + }, + "summary": { + "en": "A long worm made of dozens of segments that tunnels through the ground and platforms after you; breaking a middle segment splits it in two." + }, + "moves": [ + { + "id": "burrow", + "name": { + "en": "Burrowing chase" + }, + "tell": { + "en": "It speeds toward you while inside the ground or a platform and falls under gravity when it leaves them; there is no extra warning" + }, + "effect": { + "en": "Both head and body hurt on contact; the head hurts most" + }, + "counter": { + "en": "Avoid the head and attack the body as it passes" + } + }, + { + "id": "split", + "name": { + "en": "Splitting" + }, + "tell": { + "en": "When a middle segment is destroyed the worm breaks into two, each growing a new head and tail" + }, + "effect": { + "en": "More worms chase you" + }, + "counter": { + "en": "Focus heads and tails, or use the sword to hit several segments at once" + } + }, + { + "id": "acid_spit", + "name": { + "en": "Corrosive spit" + }, + "tell": { + "en": "Segments that can see you spit projectiles at you; the tail does not" + }, + "effect": { + "en": "The projectiles hurt on hit" + }, + "counter": { + "en": "Any attack destroys a spit in one hit" + }, + "only": { + "en": "expert mode only" + } + } + ], + "phases": [ + { + "en": "You win when every segment is gone; dying segments sometimes drop hearts" + } + ] + }, + { + "case_id": "terraria/queen_bee", + "boss": { + "en": "Charging Giant Bee" + }, + "summary": { + "en": "A giant bee that charges back and forth horizontally, summons small bees, or fires stingers from above you." + }, + "moves": [ + { + "id": "charge", + "name": { + "en": "Horizontal charges" + }, + "tell": { + "en": "It flies to your left or right at your height, then charges horizontally back and forth three times; it always opens with this" + }, + "effect": { + "en": "Contact damage" + }, + "counter": { + "en": "Once you see the height it lines up at, jump or switch platform level, then hit it from behind after it passes" + } + }, + { + "id": "summon", + "name": { + "en": "Bee swarm" + }, + "tell": { + "en": "It hovers above you and releases a swarm of small bees" + }, + "effect": { + "en": "The small bees chase you and hurt on contact" + }, + "counter": { + "en": "The small bees are fragile, so clear them with arrows or the sword; she is an easy target while hovering" + } + }, + { + "id": "stingers", + "name": { + "en": "Stinger volley" + }, + "tell": { + "en": "She drifts left and right above you, firing yellow stingers" + }, + "effect": { + "en": "Stingers hurt on hit and may poison you" + }, + "counter": { + "en": "Move sideways out of the spread and attack while she repositions" + } + } + ], + "phases": [] + }, + { + "case_id": "terraria/brain_of_cthulhu", + "boss": { + "en": "Teleporting Flesh Brain" + }, + "summary": { + "en": "A translucent brain ringed by guardian eyes; only after you clear the eyes does it expose its heart and take damage, and then it teleports after you." + }, + "moves": [ + { + "id": "guard_charge", + "name": { + "en": "Guardian eye lunges" + }, + "tell": { + "en": "About 20 guardian eyes circle the translucent brain and take turns lunging at you; the brain cannot be hurt meanwhile" + }, + "effect": { + "en": "The eyes hurt on contact" + }, + "counter": { + "en": "Clear the eyes first: they are fragile, the sword can hit several at once, and the one lunging at you is easiest to hit" + } + }, + { + "id": "teleport", + "name": { + "en": "Teleport" + }, + "tell": { + "en": "At first it drifts closer, flickers and teleports to another spot near you; once its heart is exposed it fades in and out often and chases you closely" + }, + "effect": { + "en": "Contact damage" + }, + "counter": { + "en": "It cannot touch you until it has fully faded in; spot the new position and turn to attack at once" + } + }, + { + "id": "illusions", + "name": { + "en": "Mirror decoys" + }, + "tell": { + "en": "In the second phase three mirror-image decoys appear around you, more convincing as its health drops" + }, + "effect": { + "en": "The decoys deal no damage; they only confuse you" + }, + "counter": { + "en": "Only the real brain flashes when hit; the decoys mirror around you, so follow the real one's movement" + }, + "only": { + "en": "expert mode only" + } + } + ], + "phases": [ + { + "en": "In the first phase the guardian eyes protect the brain from damage; once they are cleared the second phase begins and the exposed brain can be hurt" + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/tombraider_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/tombraider_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..a16a1b07db8771076f79df124ba97510b638a999 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/tombraider_remake.json @@ -0,0 +1,499 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "tombraider_remake", + "rules": "tr1-arena@3", + "title": { + "en": "Third-Person Ruins: Tank-Control Boss Fights" + }, + "dimension": "3d", + "view": { + "en": "Third-person 3D: the camera sits behind the explorer, who carries a pistol in each hand, and swings toward the boss when locked on. The HUD shows the boss's name and health bar and your own health bar. An orange ring or edge arrow marks the boss's position and its outline shows through walls; a green cross marks the muzzle direction straight ahead; a red patch on the ground and a banner at the top show the move the boss is charging" + }, + "goal": { + "en": "Empty the boss's health bar to win; you lose if your health reaches zero; each fight lasts at most 300 seconds and a timeout is not a win. Health never regenerates by itself; the only recovery is the small medipacks you carry (each heals part of your health, you start with 2)" + }, + "mouse": { + "kind": "camera", + "en": "Mouse X turns the explorer left/right (the camera follows), but never faster than the keyboard: at most about 36 degrees per 200 ms standing or running, about 24 in a back hop, about 6 in the air, and no turning while sidestepping, crouching for a jump, landing or rolling. Mouse Y only tilts the camera and does not affect the guns; the camera frames the boss by itself, so it is rarely needed" + }, + "keys": [ + { + "key": "W", + "en": "run forward" + }, + { + "key": "S", + "en": "back hop (hold to hop repeatedly)" + }, + { + "key": "A", + "en": "turn left on the spot (tank turning, about 180 degrees/s standing)" + }, + { + "key": "D", + "en": "turn right on the spot" + }, + { + "key": "Q", + "en": "sidestep left" + }, + { + "key": "E", + "en": "sidestep right" + }, + { + "key": "Space", + "en": "jump; the direction is read from W/S/A/D shortly after take-off: forward, back, left or right side jump, nothing for a straight-up jump" + }, + { + "key": "Shift", + "en": "hold to walk (slow, never falls off edges)" + }, + { + "key": "J", + "en": "fire; hold for continuous fire, auto-aimed at the boss" + }, + { + "key": "LMB", + "en": "fire (same as J)" + }, + { + "key": "K", + "en": "draw / holster the guns (drawn at the start)" + }, + { + "key": "RMB", + "en": "draw / holster (same as K)" + }, + { + "key": "L", + "en": "roll: turn 180 degrees on the spot" + }, + { + "key": "R", + "en": "use one small medipack to heal part of your health" + } + ], + "notes": [ + { + "en": "This is mid-1990s tank control: A/D rotate in place instead of strafing; use Q/E sidesteps or side jumps to dodge sideways." + }, + { + "en": "Firing auto-aims at a boss inside a cone of about 60 degrees ahead and within about 8 tiles; holding J keeps shooting and you can move while firing. If the boss leaves the cone, turn to face it first." + }, + { + "en": "A jump has a short crouch: after Space goes down you crouch for about 0.1 s before leaving the ground, and the direction is read then; you cannot steer or start other actions in the air." + }, + { + "en": "There is no invulnerability after being hit, so repeated hits stack; rolling and jumping do not grant immunity, you dodge by position only." + }, + { + "en": "Arenas are flat rooms, some with pillars: pillars block a gunman's line of sight but not the splash of an explosive bomb." + }, + { + "en": "Each 200 ms action packet combines one option from each of three groups: move, turn and fire/action; the fire + jump options start the jump at the chosen sub-step." + } + ], + "compact_glossary": { + "move": { + "en": "movement keys held for the whole packet", + "options": { + "none": "stand still", + "forward": "run forward (W)", + "back": "back hop, repeated while held (S)", + "step_left": "sidestep left (Q)", + "step_right": "sidestep right (E)" + } + }, + "turn": { + "en": "turning, by keyboard (A/D) for the whole packet or part of it, or by a mouse angle", + "options": { + "none": "no turn", + "left": "turn left the whole packet (A, about 36 degrees standing)", + "right": "turn right the whole packet (D, about 36 degrees standing)", + "left_25": "turn left during the middle 4 sub-steps only", + "left_14": "turn left during the first 4 sub-steps only", + "left_12": "turn left during the first 2 sub-steps only", + "left_11": "turn left during sub-step 1 only (a small nudge)", + "right_25": "turn right during the middle 4 sub-steps only", + "right_14": "turn right during the first 4 sub-steps only", + "right_12": "turn right during the first 2 sub-steps only", + "right_11": "turn right during sub-step 1 only (a small nudge)", + "mouse_left_10": "mouse turn left by 10 degrees", + "mouse_right_10": "mouse turn right by 10 degrees", + "mouse_left_30": "mouse turn left by 30 degrees", + "mouse_right_30": "mouse turn right by 30 degrees" + } + }, + "act": { + "en": "the trigger and one-off actions", + "options": { + "none": "no fire, no action", + "fire": "hold fire the whole packet (J), auto-aimed", + "fire_jump_1": "fire and start a jump at sub-step 1", + "fire_jump_2": "fire and start a jump at sub-step 2", + "fire_jump_3": "fire and start a jump at sub-step 3", + "fire_jump_4": "fire and start a jump at sub-step 4", + "fire_jump_5": "fire and start a jump at sub-step 5", + "fire_jump_6": "fire and start a jump at sub-step 6", + "fire_once": "a single shot (J pressed at sub-step 1 only)", + "fire_roll": "fire and roll (turn 180 degrees on the spot)", + "fire_medipack": "fire and use one small medipack" + } + } + }, + "scenes": [ + { + "case_id": "tombraider/giant_lizard", + "boss": { + "en": "Giant-Fanged Lizard Beast" + }, + "summary": { + "en": "A huge two-legged lizard beast in an open valley with flat ground and no steps to hide on. It is fast and lethal at close range, so survival depends on spacing and movement." + }, + "moves": [ + { + "id": "bite", + "name": { + "en": "Gaping bite" + }, + "tell": { + "en": "It stops, draws its head back and opens its jaws for about 0.3 s; the ground patch and banner warn you." + }, + "effect": { + "en": "A bite at close range kills the explorer almost instantly." + }, + "counter": { + "en": "When it draws back, hop back or sidestep out of range, then fire as soon as the bite misses." + } + }, + { + "id": "trample", + "name": { + "en": "Charging trample" + }, + "tell": { + "en": "It lowers its head and runs at you, with no wind-up." + }, + "effect": { + "en": "Touching you while it runs deals heavy continuous damage, far more than touching you while it walks." + }, + "counter": { + "en": "Do not wait head-on; sidestep out of its charge line and shoot while backing off." + } + }, + { + "id": "roar", + "name": { + "en": "Roar" + }, + "tell": { + "en": "It stands still with its head thrown back for about 0.8 s." + }, + "effect": { + "en": "Deals no damage itself, but it stays put during this time." + }, + "counter": { + "en": "Keep firing while it roars." + } + } + ], + "phases": [] + }, + { + "case_id": "tombraider/lone_gunman", + "boss": { + "en": "Lone Mercenary Gunman" + }, + "summary": { + "en": "A single-gun human opponent in a colonnade hall with pillars for cover. His hit chance depends on distance, so he misses you when far away, and when hurt he may run off." + }, + "moves": [ + { + "id": "shot", + "name": { + "en": "Aimed shot" + }, + "tell": { + "en": "He stops and raises his gun for about 0.2 s, then the muzzle flashes." + }, + "effect": { + "en": "An instant hit with heavy damage per shot; the farther you are, the more likely it misses." + }, + "counter": { + "en": "Keep your distance or hide behind a pillar to break line of sight; sidestep while he aims." + } + }, + { + "id": "approach", + "name": { + "en": "Walk and run" + }, + "tell": { + "en": "He walks when you are close and runs when you are far away or out of sight." + }, + "effect": { + "en": "Does no damage but closes the distance into his effective range." + }, + "counter": { + "en": "Back-hop while firing to stay at a range where his shots miss." + } + }, + { + "id": "flee", + "name": { + "en": "Wounded flight" + }, + "tell": { + "en": "After being hit he may suddenly turn and run, then come back after a while." + }, + "effect": { + "en": "He does not shoot while fleeing, which drags the fight out." + }, + "counter": { + "en": "Chase and keep firing so he cannot recover." + } + } + ], + "phases": [] + }, + { + "case_id": "tombraider/twin_pistols", + "boss": { + "en": "Twin-Pistol Duelist" + }, + "summary": { + "en": "A dual-wielding opponent in a four-pier stone hall, like the lone gunman but each volley fires one shot from each gun. The room has pillars." + }, + "moves": [ + { + "id": "shot", + "name": { + "en": "Twin-gun volley" + }, + "tell": { + "en": "He stops and raises both guns for about 0.2 s, then two muzzle flashes." + }, + "effect": { + "en": "Each gun rolls its own hit; each shot is lighter, but together they add up when both land." + }, + "counter": { + "en": "Keep far away, use pillars to block sight, and move sideways while he aims." + } + }, + { + "id": "approach", + "name": { + "en": "Walk and run" + }, + "tell": { + "en": "Between shots he walks or runs closer and occasionally poses." + }, + "effect": { + "en": "Does no damage but shortens the range, raising his hit chance." + }, + "counter": { + "en": "Back-hop to regain distance and keep firing." + } + }, + { + "id": "flee", + "name": { + "en": "Wounded flight" + }, + "tell": { + "en": "After being hit he may turn and flee, and may come back later." + }, + "effect": { + "en": "He does not shoot while fleeing, and the fight can run very long." + }, + "counter": { + "en": "Chase and keep firing so the fight does not run into the time limit." + } + } + ], + "phases": [] + }, + { + "case_id": "tombraider/cannon_quadruped", + "boss": { + "en": "Cannon-Armed Quadruped" + }, + "summary": { + "en": "A four-legged beast, awake from the start, in a sarcophagus tomb. Its arm is a cannon that fires explosive bombs at range, and it rears up and kicks when you are close." + }, + "moves": [ + { + "id": "bomb", + "name": { + "en": "Cannon bomb" + }, + "tell": { + "en": "It stops, raises the cannon and charges the muzzle with a red ground warning, then fires a bomb that flies toward you." + }, + "effect": { + "en": "The bomb hits or explodes on landing for heavy splash damage that grows the closer you are to the blast." + }, + "counter": { + "en": "Once the bomb is in flight, run or jump sideways out of the impact area." + } + }, + { + "id": "rear", + "name": { + "en": "Rear-up kick" + }, + "tell": { + "en": "Its front rises up and the kick lands after about 0.7 s." + }, + "effect": { + "en": "A kick that connects deals very heavy single-hit damage." + }, + "counter": { + "en": "Hop back or sidestep out of close range the moment it rears." + } + }, + { + "id": "run", + "name": { + "en": "Running pursuit" + }, + "tell": { + "en": "When not aiming it gallops toward you and may rear up suddenly mid-run." + }, + "effect": { + "en": "Closes to kicking range; no direct damage." + }, + "counter": { + "en": "Hold a mid range, keep firing and be ready to sidestep." + } + } + ], + "phases": [] + }, + { + "case_id": "tombraider/legless_giant", + "boss": { + "en": "Legless Flesh Giant" + }, + "summary": { + "en": "A huge legless monster that drops from above into a fleshy pit. It must face you to advance and turns slowly, but its arms reach very far." + }, + "moves": [ + { + "id": "attackR", + "name": { + "en": "Right-arm sweep" + }, + "tell": { + "en": "It raises one arm and about half a second later hooks it in an arc from the side to the front, with a red warning." + }, + "effect": { + "en": "A hit deals heavy single-hit damage and the sweep reaches several tiles." + }, + "counter": { + "en": "Hop out of range as the arm rises, or move round to the side it does not cover." + } + }, + { + "id": "attackB", + "name": { + "en": "Two-arm slam" + }, + "tell": { + "en": "Both arms rise together and slam down about half a second later." + }, + "effect": { + "en": "Both arms' swept areas deal heavy damage." + }, + "counter": { + "en": "Leave the area in front of it and hop backward." + } + }, + { + "id": "grab", + "name": { + "en": "Grab" + }, + "tell": { + "en": "When your health is very low and you are close, it performs a grab whose wind-up looks like an arm strike." + }, + "effect": { + "en": "A grab that connects is fatal." + }, + "counter": { + "en": "Stay far away when your health is low, and use a medipack before approaching if needed." + } + } + ], + "phases": [] + }, + { + "case_id": "tombraider/winged_matriarch", + "boss": { + "en": "Winged Matriarch" + }, + "summary": { + "en": "The final boss in a golden relic chamber, fought in two stages: first ground triple bombs and aerial bomb drops, then after she collapses and rises, a running, shooting second stage." + }, + "moves": [ + { + "id": "volley", + "name": { + "en": "Triple bomb volley" + }, + "tell": { + "en": "She lands, stops and raises a hand, then shoots three bombs with a small spread." + }, + "effect": { + "en": "Each bomb explodes with splash damage; three in a row hurt badly." + }, + "counter": { + "en": "Run sideways as soon as she raises a hand and stay away from the impact points." + } + }, + { + "id": "flybomb", + "name": { + "en": "Aerial bomb drop" + }, + "tell": { + "en": "She flies and drops a bomb about once a second with no wind-up; you see only the bomb and its landing ring." + }, + "effect": { + "en": "Splash damage from the explosion, the main source of damage in this fight." + }, + "counter": { + "en": "Keep moving and avoid the landing rings; fire hard whenever she touches down." + } + }, + { + "id": "shard", + "name": { + "en": "Shard shots" + }, + "only": { + "en": "stage 2 only" + }, + "tell": { + "en": "In stage 2 she fires a shard about every 0.3 s while running, with no wind-up." + }, + "effect": { + "en": "Each shard hurts little and flies only into a cone of about 30 degrees in front of her." + }, + "counter": { + "en": "Step out of her frontal cone, moving to her side or back before firing." + } + } + ], + "phases": [ + { + "en": "Stage 1: when her health falls to half she collapses for about 16 s and does not attack, so you can fire freely." + }, + { + "en": "Stage 2: she rises and shoots while running, using shards instead of bombs." + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/touhou_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/touhou_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..eb3442ab606eac645c55719c8c60580e8d84d4e2 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/touhou_remake.json @@ -0,0 +1,810 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "touhou_remake", + "rules": "scarlet-practice@8", + "title": { + "en": "Bullet Hell: Boss Practice" + }, + "dimension": "2d", + "view": { + "en": "Fixed-screen 2D bullet-hell; the play area fills the whole frame. You control a twin-type shooter (type A homing shots / type B needle shots) and a tiny hit-point dot shows while moving slowly; the boss moves in the upper part; lives, bombs and power are overlaid at the corners, with the boss's health bar and card name at the top." + }, + "goal": { + "en": "Defeat every attack phase of the boss to win; you lose when all lives are spent. Each phase has a timer and a timeout only moves on to the next phase; lives do not regenerate." + }, + "mouse": { + "kind": "none", + "en": "The mouse does not steer; LMB is the same as fire and RMB the same as the screen-clearing bomb" + }, + "keys": [ + { + "key": "W", + "en": "Move up" + }, + { + "key": "A", + "en": "Move left" + }, + { + "key": "S", + "en": "Move down" + }, + { + "key": "D", + "en": "Move right" + }, + { + "key": "Shift", + "en": "Slow movement; shows the hit-point dot and pulls the options in" + }, + { + "key": "J", + "en": "Hold to fire" + }, + { + "key": "LMB", + "en": "Fire (same as J)" + }, + { + "key": "K", + "en": "Screen-clearing bomb; pressing it right after being hit cancels the death" + }, + { + "key": "RMB", + "en": "Bomb (same as K)" + }, + { + "key": "Q", + "en": "Switch ship type (A / B)" + }, + { + "key": "E", + "en": "Switch ship type (same as Q)" + } + ], + "notes": [ + { + "en": "Only the tiny hit-point dot is hurt by bullets; grazing is harmless. Slow movement is precise, fast movement is for big repositioning." + }, + { + "en": "Hold fire continuously. Type A shots home in on the boss; type B needle shots go straight ahead, so line up with the boss." + }, + { + "en": "Bombs are limited: type A releases homing orbs and type B cross-shaped bars. A bomb grants invulnerability and clears bullets, and pressing it just after being hit cancels the loss of a life." + }, + { + "en": "During spell cards shots do much less damage, so sustained fire is needed; bombs do comparatively more against cards." + }, + { + "en": "After being hit you respawn at the bottom with brief invulnerability and bullets are cleared for a while." + }, + { + "en": "There is a short pause between phases, with the boss returning to the centre and no bullets." + }, + { + "en": "The easy tier gives more lives (5) and has fewer phases; the hard tier has denser cards." + } + ], + "compact_glossary": { + "move": { + "en": "movement", + "options": { + "none": "stand still", + "up": "move up", + "down": "move down", + "left": "move left", + "right": "move right", + "up_left": "move up-left", + "up_right": "move up-right", + "down_left": "move down-left", + "down_right": "move down-right" + } + }, + "action": { + "en": "fire / slow / bomb", + "options": { + "none": "do not fire, fast movement", + "bomb_focus": "bomb (fire + slow)", + "bomb_fast": "bomb (fire + fast)", + "bomb_hold": "last-chance bomb held for the whole packet", + "fire_fast": "fire with fast movement", + "fire_focus": "fire with slow movement" + } + } + }, + "scenes": [ + { + "case_id": "touhou/cirno", + "boss": { + "en": "Shard Sprayer" + }, + "summary": { + "en": "Stage-two boss that sprays showers of crystal shards and freezes them in place before releasing them again." + }, + "moves": [ + { + "id": "c_icicle", + "name": { + "en": "Side Arcs" + }, + "tell": { + "en": "Columns of shards fall from both sides and curve into arcs" + }, + "effect": { + "en": "Arcing bullets cover both sides, leaving a big gap in the middle; the normal tier adds yellow five-way aimed shots" + }, + "counter": { + "en": "Stay near the middle and watch the yellow aimed shots" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "c_hail", + "name": { + "en": "Hanging Shard Rings" + }, + "tell": { + "en": "Small rings of shards fly out, slow to a stop, then each group leaves in turn on a downward arc" + }, + "effect": { + "en": "Stopped rings act as obstacles and then leave as downward arcs" + }, + "counter": { + "en": "Do not hug stopped rings; move to a gap before they set off" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "c_freeze", + "name": { + "en": "Stall and Scatter" + }, + "tell": { + "en": "Colourful bullets spray in random directions, then all stop and turn white" + }, + "effect": { + "en": "Several rounds of blue multi-way aimed shots follow, then each white bullet slowly accelerates off in a random direction" + }, + "counter": { + "en": "Find open ground while bullets are stopped, sidestep the aimed shots, and keep clear of white bullets before they scatter" + } + }, + { + "id": "c_blizzard", + "name": { + "en": "Drifting Shard Bursts" + }, + "tell": { + "en": "The boss keeps jumping around while bursts of shards pop out around her" + }, + "effect": { + "en": "She changes position every moment and bursts several shards near herself" + }, + "counter": { + "en": "Keep your distance and re-judge your position after every reposition" + }, + "only": { + "en": "normal tier and above" + } + } + ], + "phases": [ + { + "en": "Non-spell 1, Side Arcs (easy/normal) or Hanging Shard Rings (hard), Non-spell 2, Stall and Scatter, Drifting Shard Bursts (normal and above). The easy tier only has Non-spell 1 and Stall and Scatter." + } + ] + }, + { + "case_id": "touhou/meiling", + "boss": { + "en": "Spiral Weaver" + }, + "summary": { + "en": "Stage-three boss who barely moves, firing two counter-rotating streams of bullets that weave into a net." + }, + "moves": [ + { + "id": "m_chime", + "name": { + "en": "Fixed Angle Streams" + }, + "tell": { + "en": "Streams of many colours fire continuously from fixed angles" + }, + "effect": { + "en": "The streams keep fixed directions, leaving lane-like gaps between them" + }, + "counter": { + "en": "Stand in a lane and fine-tune your position with slow moves" + } + }, + { + "id": "m_vine", + "name": { + "en": "Drifting Scatter" + }, + "tell": { + "en": "Bullets alternate between sparse and dense while drifting slowly" + }, + "effect": { + "en": "A scatter that spreads outward; the dense stretches leave almost no gap" + }, + "counter": { + "en": "Take position when sparse; hold still or bomb when dense" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "m_rain", + "name": { + "en": "Side Accel Shards" + }, + "tell": { + "en": "Shards come in from both sides, accelerating as they travel" + }, + "effect": { + "en": "They get faster over time, blocking both sides" + }, + "counter": { + "en": "Stay near the middle and avoid the corners" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "m_dance", + "name": { + "en": "Burst and Curve" + }, + "tell": { + "en": "Radial bursts alternate with curving streams" + }, + "effect": { + "en": "Radial parts have clear gaps between spokes; curving parts bend toward you" + }, + "counter": { + "en": "Slip between the spokes during bursts and strafe during curves" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "m_typhoon", + "name": { + "en": "Crossing Spirals" + }, + "tell": { + "en": "Two spiral streams rotate in opposite directions and cross each other" + }, + "effect": { + "en": "The crossing points are the densest, and both streams keep rotating" + }, + "counter": { + "en": "Move with the rotation and avoid the crossing points" + }, + "only": { + "en": "normal tier and above" + } + } + ], + "phases": [ + { + "en": "Non-spell 1, Fixed Angle Streams, Non-spell 2, Drifting Scatter (hard), Non-spell 3, Side Accel Shards (easy/normal) or Burst and Curve (hard), Crossing Spirals (normal and above). The easy tier only has Non-spell 1 and Side Accel Shards." + } + ] + }, + { + "case_id": "touhou/patchouli", + "boss": { + "en": "Beam Elementalist" + }, + "summary": { + "en": "Stage-four boss with rotating beams; each beam also emits element-themed bullet patterns." + }, + "moves": [ + { + "id": "p_agni", + "name": { + "en": "Wavering Fall" + }, + "tell": { + "en": "Fiery bullets fall while swaying side to side" + }, + "effect": { + "en": "Bullets rain from above and the sway makes landing spots hard to read" + }, + "counter": { + "en": "Move side to side with the sway; do not stand still" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "p_agni_hl", + "name": { + "en": "Wavering Fall Dense" + }, + "tell": { + "en": "The same wavering fall but with more, denser bullets" + }, + "effect": { + "en": "Narrower gaps" + }, + "counter": { + "en": "Make small slow corrections and bomb at the densest moment" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "p_trilithon_hl", + "name": { + "en": "Stall and Turn" + }, + "tell": { + "en": "Yellow bullets fly out, stall, then turn and head in a new direction" + }, + "effect": { + "en": "Stalled bullets are temporary obstacles and become a new pattern after turning" + }, + "counter": { + "en": "Stand in open ground while they stall and predict the new direction" + }, + "only": { + "en": "normal tier only" + } + }, + { + "id": "p_shake", + "name": { + "en": "Stall Turn and Heavy Shots" + }, + "tell": { + "en": "Stall-and-turn bullets plus large heavy shots" + }, + "effect": { + "en": "The large bullets shrink the room you can dodge in" + }, + "counter": { + "en": "Dodge the large ones first, then read the gaps in the small ones" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "p_lava", + "name": { + "en": "Rings and Stalls" + }, + "tell": { + "en": "All-direction rings alternate with stalled bullets that restart later" + }, + "effect": { + "en": "Rings force you to move and stalled bullets set off when you think it is safe" + }, + "counter": { + "en": "Do not stay beside stalled bullets; use the gaps between rings" + } + }, + { + "id": "p_mercury", + "name": { + "en": "Twin Curving Streams" + }, + "tell": { + "en": "Two emitters fire curving streams in opposite directions" + }, + "effect": { + "en": "The two curving streams cross each other" + }, + "counter": { + "en": "Stay between the streams and move along the curve" + }, + "only": { + "en": "normal tier and above" + } + }, + { + "id": "p_forest", + "name": { + "en": "Corner Stream and Sparks" + }, + "tell": { + "en": "Green streams come diagonally from above, with scattered fire bullets" + }, + "effect": { + "en": "The diagonal stream covers one side while fire bullets fall sparsely" + }, + "counter": { + "en": "Stay on the open side and watch for the scattered bullets" + }, + "only": { + "en": "hard tier only" + } + } + ], + "phases": [ + { + "en": "Non-spell 1 (rotating beams that also emit bullets), Wavering Fall, Non-spell 2, Stall and Turn or Stall Turn and Heavy Shots, Rings and Stalls, Twin Curving Streams, Corner Stream and Sparks. The easy tier only has Non-spell 1 and Rings and Stalls." + } + ] + }, + { + "case_id": "touhou/remilia", + "boss": { + "en": "Web Bombardier" + }, + "summary": { + "en": "Stage-six boss that weaves nets of beams and fires large shells that leave trails; in her last cards she turns into bats." + }, + "moves": [ + { + "id": "r6_david", + "name": { + "en": "Beam Web" + }, + "tell": { + "en": "Beams interweave into a net and bullets are released from it" + }, + "effect": { + "en": "The net divides the field and bullets come out along it" + }, + "counter": { + "en": "Stay off the beams and choose an open cell" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "r6_demon", + "name": { + "en": "Static Web Shells" + }, + "tell": { + "en": "The beam net stays still while large shells are fired" + }, + "effect": { + "en": "The net does not move and large shells keep coming" + }, + "counter": { + "en": "Memorise the net first, then dodge the shells" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "r6_nether", + "name": { + "en": "Falling Slivers" + }, + "tell": { + "en": "Thin bullets fall while crossing bullets cut diagonally" + }, + "effect": { + "en": "Many thin bullets plus crossing bullets that block your route" + }, + "counter": { + "en": "Sidestep the crossing bullets and use slow moves for the thin ones" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "r6_needles", + "name": { + "en": "Bouncing Slivers" + }, + "tell": { + "en": "Thin bullets bounce off walls and blade-shaped bullets cross" + }, + "effect": { + "en": "Bounces keep bullets in play for longer" + }, + "counter": { + "en": "Keep away from the walls" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "r6_tepes", + "name": { + "en": "Spiral Blades" + }, + "tell": { + "en": "Blue blade bullets spiral out and leave red bullets behind" + }, + "effect": { + "en": "Red bullets remain and accumulate" + }, + "counter": { + "en": "Do not reuse the same route; reposition to avoid getting boxed in" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "r6_fantasy", + "name": { + "en": "Even Way Shells" + }, + "tell": { + "en": "Even-numbered ways of large shells fly out leaving trail bullets" + }, + "effect": { + "en": "An even way count leaves a gap straight ahead" + }, + "counter": { + "en": "Stand between two ways" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "r6_shoot", + "name": { + "en": "Fast Aimed Shells" + }, + "tell": { + "en": "Fast large shells aimed right at you" + }, + "effect": { + "en": "Fast, with little reaction time" + }, + "counter": { + "en": "Sidestep early and do not back up in a straight line" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "r6_meister", + "name": { + "en": "Led Volleys" + }, + "tell": { + "en": "A leading large shell comes with a ring of bullets in volleys" + }, + "effect": { + "en": "The leader sets where the ring goes" + }, + "counter": { + "en": "Track the leader and hide between rings" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "r6_magic", + "name": { + "en": "Bouncing Trail Shells" + }, + "tell": { + "en": "Large shells bounce off walls leaving trails, and the boss turns into bats" + }, + "effect": { + "en": "Trails accumulate; bombs work differently in this card" + }, + "counter": { + "en": "Stay off walls and do not rely on bombs" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "r6_gensokyo", + "name": { + "en": "Trail Shells and Ring" + }, + "tell": { + "en": "Large shells leave trails while a ring is added; the boss turns into bats" + }, + "effect": { + "en": "Trails plus rings leave narrow gaps" + }, + "counter": { + "en": "Find the ring gaps and avoid the trails" + }, + "only": { + "en": "hard tier only" + } + } + ], + "phases": [ + { + "en": "Each tier has four non-spells and five cards; the easy tier only has Non-spell 1 and Bouncing Trail Shells. Cards come from the easy/normal set or the hard set." + } + ] + }, + { + "case_id": "touhou/rumia", + "boss": { + "en": "Fan Caster" + }, + "summary": { + "en": "Stage-one boss who spreads her arms and sweeps rings and fans of bullets; plain bullet attacks alternate with spell cards." + }, + "moves": [ + { + "id": "r_bird", + "name": { + "en": "Alternating Sweep" + }, + "tell": { + "en": "Light-blue and blue bullets alternate and sweep left and right like wings, aimed at you" + }, + "effect": { + "en": "Each volley is a few fan-shaped wings sweeping a wide arc; she moves between volleys" + }, + "counter": { + "en": "Slip through the gap between wings and stay off the aim line; the repositioning moment is safest" + } + }, + { + "id": "r_demarc", + "name": { + "en": "Counter Rings" + }, + "tell": { + "en": "Several waves of red and blue rings expand and rotate in opposite directions; after a pause a row of aimed bullets follows" + }, + "effect": { + "en": "The rings expand slowly, then the aimed bullets grow in number" + }, + "counter": { + "en": "Follow the gap between rings and sidestep when the aimed bullets come" + } + } + ], + "phases": [ + { + "en": "Non-spell 1, Alternating Sweep, Non-spell 2 (laser, yellow counter rings, aimed green rings), Counter Rings. The easy tier only has Non-spell 1, Alternating Sweep and Counter Rings." + } + ] + }, + { + "case_id": "touhou/sakuya", + "boss": { + "en": "Stoptime Knifer" + }, + "summary": { + "en": "Stage-five boss who stops time and lays knives meanwhile, releasing them when time resumes; you, your shots and enemy bullets are frozen during a stop." + }, + "moves": [ + { + "id": "s_corpse", + "name": { + "en": "Stop and Lay Knives" + }, + "tell": { + "en": "Small bullets scatter, then the screen freezes while she crosses it laying knives" + }, + "effect": { + "en": "Knives aimed at you and parabolic ones are laid; all move when time resumes" + }, + "counter": { + "en": "Note the knives during the freeze and move to the side without knives" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "s_jack", + "name": { + "en": "Trail Knives" + }, + "tell": { + "en": "Random bullets drift down, then time stops and she moves leaving knives on her way" + }, + "effect": { + "en": "Knives aim at you and surround you" + }, + "counter": { + "en": "Leave through a gap you noted as soon as time resumes" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "s_luna", + "name": { + "en": "Knife Lanes" + }, + "tell": { + "en": "Fixed all-direction bullets, then time stops and lines of knives appear between her and you, some turning green" + }, + "effect": { + "en": "Knife lines fly toward you when time resumes, and green knives turn" + }, + "counter": { + "en": "Take the gaps between lines and leave early for green knives" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "s_world", + "name": { + "en": "Surround Knives" + }, + "tell": { + "en": "A random knife curtain; the closer you are to her, the farther away knives appear" + }, + "effect": { + "en": "During the stop knives are placed in a ring around you" + }, + "counter": { + "en": "Stay moderately far from her for larger gaps" + }, + "only": { + "en": "hard tier only" + } + }, + { + "id": "s_doll", + "name": { + "en": "Turning Ricochet Knives" + }, + "tell": { + "en": "Slow four-way blue and red knives that turn into scattered green knives after a time stop, some bouncing off side walls" + }, + "effect": { + "en": "Green knives scatter in all directions after the stop" + }, + "counter": { + "en": "Dodge the slow knives first, then read gaps in the green ones" + }, + "only": { + "en": "easy and normal tiers only" + } + }, + { + "id": "s_killing", + "name": { + "en": "Rest and Aim Rings" + }, + "tell": { + "en": "A ring of knives appears; blue ones slow to a halt, red ones stop and then aim, some turn green in the time stop" + }, + "effect": { + "en": "Knives pause and then fly at you" + }, + "counter": { + "en": "Stay away from resting knives and prepare to sidestep before red ones aim" + }, + "only": { + "en": "hard tier only" + } + } + ], + "phases": [ + { + "en": "Non-spell 1, Stop and Lay Knives (easy/normal) or Trail Knives (hard), Non-spell 2 (four magic circles shooting walls of kunai, plus knife rings), Knife Lanes or Surround Knives, Non-spell 3, Turning Ricochet Knives or Rest and Aim Rings. The easy tier only has Non-spell 1 and Turning Ricochet Knives." + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/prompts/games/zelda_oot_remake.json b/environments/games/prototype/bossbench_llm/prompts/games/zelda_oot_remake.json new file mode 100644 index 0000000000000000000000000000000000000000..8033d0b697136727d9ec68d8da0d53b62f78b73c --- /dev/null +++ b/environments/games/prototype/bossbench_llm/prompts/games/zelda_oot_remake.json @@ -0,0 +1,591 @@ +{ + "schema": "bossbench-llm/game-prompt@1", + "game": "zelda_oot_remake", + "rules": "oot-arena@5", + "title": { + "en": "Third-Person Lock-On Sword and Shield: Boss Trials" + }, + "dimension": "3d", + "view": { + "en": "Third-person 3D: the camera is behind the green-clad swordsman and follows the boss or lock target. The HUD shows the boss health bar, your life and this fight item; ground warnings appear on the arena floor." + }, + "goal": { + "en": "Empty the boss health bar to win; you lose if your life reaches zero. There is a time limit and a timeout is not a win. Life does not regenerate." + }, + "mouse": { + "kind": "camera", + "en": "Mouse movement turns the camera; when unlocked, vertical movement adjusts aiming pitch. Q / E also turn the camera 45° at a time." + }, + "keys": [ + { + "key": "W", + "en": "run forward (camera-relative)" + }, + { + "key": "A", + "en": "run left" + }, + { + "key": "S", + "en": "run backward" + }, + { + "key": "D", + "en": "run right" + }, + { + "key": "Space", + "en": "roll / jump: unlocked = directional roll (invulnerable mid-roll); locked: forward or still = jump slash, back = back hop, left/right = side hop" + }, + { + "key": "Shift", + "en": "lock-on: hold to lock the nearest target; you face and track it" + }, + { + "key": "J", + "en": "sword slash; tap repeatedly for a three-hit combo" + }, + { + "key": "LMB", + "en": "sword slash (same as J)" + }, + { + "key": "K", + "en": "hold to raise the shield and block frontal attacks; the mirrored shield absorbs blasts" + }, + { + "key": "RMB", + "en": "raise shield (same as K)" + }, + { + "key": "L", + "en": "use this fight item (auto-aims at the target when locked)" + }, + { + "key": "Q", + "en": "turn the camera 45° left" + }, + { + "key": "E", + "en": "turn the camera 45° right" + }, + { + "key": "R", + "en": "reset the camera" + } + ], + "notes": [ + { + "en": "While Shift is held you always face the target and the item auto-aims; movement stays camera-relative." + }, + { + "en": "Rolling is invulnerable mid-roll; when locked, Space becomes a jump slash, back hop or side hop." + }, + { + "en": "The shield blocks only frontal attacks; blasts cannot be blocked, only absorbed by the mirrored shield." + }, + { + "en": "Which logic frame of a 200 ms packet an action lands on matters; the shield must be up on the exact frame an attack arrives." + }, + { + "en": "When grabbed use struggle; about ten packets of alternating presses frees you." + }, + { + "en": "Each fight has one item (slingshot, explosive fruit, hammer or grapple line); press L." + } + ], + "compact_glossary": { + "lock": { + "en": "Lock-on (held)", + "options": { + "none": "nothing", + "hold": "hold Shift to lock on" + } + }, + "move": { + "en": "8-way camera-relative movement; *_step = held only the first half of the packet, *_f1/f3/f4 = held on one logic frame only (small alignment steps)", + "options": { + "none": "nothing", + "forward": "move forward", + "back": "move back", + "left": "move left", + "right": "move right", + "forward_left": "move forward left", + "forward_right": "move forward right", + "back_left": "move back left", + "back_right": "move back right", + "forward_step": "forward held first half of packet", + "back_step": "back held first half of packet", + "left_step": "left held first half of packet", + "right_step": "right held first half of packet", + "forward_left_step": "forward left held first half of packet", + "forward_right_step": "forward right held first half of packet", + "back_left_step": "back left held first half of packet", + "back_right_step": "back right held first half of packet", + "forward_f1": "forward held on logic frame 1 only", + "forward_left_f1": "forward left held on logic frame 1 only", + "forward_right_f1": "forward right held on logic frame 1 only", + "forward_f3": "forward held on logic frame 3 only", + "forward_left_f3": "forward left held on logic frame 3 only", + "forward_right_f3": "forward right held on logic frame 3 only", + "forward_f4": "forward held on logic frame 4 only" + } + }, + "act": { + "en": "One action per packet: slash, shield, roll/jump, item, struggle free, or camera step", + "options": { + "none": "nothing", + "slash_f1": "press slash on logic frame 1", + "slash_f2": "press slash on logic frame 2", + "slash_f3": "press slash on logic frame 3", + "slash_f4": "press slash on logic frame 4", + "shield": "hold shield for the whole packet", + "shield_late": "shield in second half of packet", + "shield_early": "shield in first half of packet", + "jump_f1": "press roll/jump on logic frame 1", + "jump_f2": "press roll/jump on logic frame 2", + "jump_f3": "press roll/jump on logic frame 3", + "jump_f4": "press roll/jump on logic frame 4", + "item_f1": "press item on logic frame 1", + "item_f2": "press item on logic frame 2", + "item_f3": "press item on logic frame 3", + "item_f4": "press item on logic frame 4", + "struggle": "mash to break free when grabbed", + "cam_left": "camera 45° left", + "cam_right": "camera 45° right", + "cam_reset": "reset camera offset" + } + } + }, + "scenes": [ + { + "case_id": "zelda/armored_spider_queen", + "boss": { + "en": "One-Eyed Carapace Queen" + }, + "summary": { + "en": "A giant one-eyed spider queen in a cave that lays eggs, spawns larvae and slams, and can drop from the ceiling." + }, + "moves": [ + { + "id": "foreleg_slam", + "name": { + "en": "Foreleg slam" + }, + "tell": { + "en": "She rears up, her eye turns red and a red fan fills in front of her (about 1.65 s)." + }, + "effect": { + "en": "Hits inside the fan; can be blocked." + }, + "counter": { + "en": "Roll or side-hop out of the fan, then close in and slash." + } + }, + { + "id": "body_contact", + "name": { + "en": "Body contact" + }, + "tell": { + "en": "No warning; the body itself is the cue." + }, + "effect": { + "en": "Continuous contact damage." + }, + "counter": { + "en": "Stay at the edge of sword range." + } + }, + { + "id": "egg_laying", + "name": { + "en": "Egg laying" + }, + "tell": { + "en": "Egg sacs on the ceiling pulse red and the eye glows, about 3.5 s; a yellow ring marks where an egg will land." + }, + "effect": { + "en": "Eggs drop and hatch larvae." + }, + "counter": { + "en": "Step out of the yellow ring and clear the larvae." + } + }, + { + "id": "larva_pounce", + "name": { + "en": "Larva pounce" + }, + "tell": { + "en": "A larva crouches and flashes red; a red strip shows its lunge (about 1.5 s)." + }, + "effect": { + "en": "Damages you if it lands." + }, + "counter": { + "en": "Side-hop off the strip or cut it down." + } + }, + { + "id": "ceiling_drop", + "name": { + "en": "Ceiling drop" + }, + "tell": { + "en": "She climbs the ceiling, a downward arrow appears at the screen edge, and she falls in about 1 s." + }, + "effect": { + "en": "Contact damage on landing." + }, + "counter": { + "en": "Roll away from the landing point." + } + } + ] + }, + { + "case_id": "zelda/lava_lizard_king", + "boss": { + "en": "Magma Cave Lizard King" + }, + "summary": { + "en": "A giant lizard in a magma cave that breathes fire, rolls and swallows explosive fruit." + }, + "moves": [ + { + "id": "fire_breath", + "name": { + "en": "Fire breath" + }, + "tell": { + "en": "He inhales: the mouth brightens and air streams in while a fire line on the ground fades in; about 5.9 s in total." + }, + "effect": { + "en": "A straight stream along the line; can be blocked." + }, + "counter": { + "en": "Step off the line, or use the inhale to attack." + } + }, + { + "id": "roll", + "name": { + "en": "Roll" + }, + "tell": { + "en": "He curls into a ball glowing red; a red strip on the ground points to where he rolls (about 1.35 s)." + }, + "effect": { + "en": "Damages on contact; cannot be blocked." + }, + "counter": { + "en": "Roll or side-hop away from the strip." + } + }, + { + "id": "contact_lava", + "name": { + "en": "Contact and lava" + }, + "tell": { + "en": "No warning; lava pits glow." + }, + "effect": { + "en": "Touching the body or lava hurts." + }, + "counter": { + "en": "Stay out of lava and off his body." + } + }, + { + "id": "own_bomb", + "name": { + "en": "His own bomb" + }, + "tell": { + "en": "A fuse sparks; in the last ~1.2 s a flashing blast radius is drawn on the ground." + }, + "effect": { + "en": "The explosion hurts." + }, + "counter": { + "en": "Leave the circle; the fruit can also be fed into his mouth." + } + } + ], + "phases": [ + { + "en": "Throw explosive fruit into his open mouth to stun him, then slash." + } + ] + }, + { + "case_id": "zelda/specter_rider", + "boss": { + "en": "Gallery Specter" + }, + "summary": { + "en": "A ghost-horse rider in a gallery who throws energy orbs and bats them back." + }, + "moves": [ + { + "id": "energy_orb", + "name": { + "en": "Energy orb" + }, + "tell": { + "en": "He raises a trident and a green orb grows at its tip (about 1.25 s)." + }, + "effect": { + "en": "The orb flies at you and hurts on hit." + }, + "counter": { + "en": "Slash the orb back with correct timing." + } + }, + { + "id": "orb_return", + "name": { + "en": "Orb return" + }, + "tell": { + "en": "He swings the trident to return it; the orb turns green again (about 0.4 s)." + }, + "effect": { + "en": "The returned orb arrives fast and hurts." + }, + "counter": { + "en": "Hit it back again or roll aside." + } + }, + { + "id": "charge", + "name": { + "en": "Charge" + }, + "tell": { + "en": "He leans back, cape and eyes turn red and a red strip points at you (about 1 s)." + }, + "effect": { + "en": "A straight-line ram." + }, + "counter": { + "en": "Side-hop or roll off the strip." + }, + "only": { + "en": "low-health phase only" + } + } + ], + "phases": [ + { + "en": "At low health he starts to charge." + } + ] + }, + { + "case_id": "zelda/burrowing_fire_dragon", + "boss": { + "en": "Burrowing Fire Dragon" + }, + "summary": { + "en": "A fire dragon that pops in and out of burrows, with surfacing blasts, claws, fire and falling rocks." + }, + "moves": [ + { + "id": "surface_burst", + "name": { + "en": "Surfacing burst" + }, + "tell": { + "en": "A hole glows and smokes with a ring; on a real surfacing the outer ring turns red, and he sometimes fakes then switches holes." + }, + "effect": { + "en": "Heavy knockback damage; cannot be blocked." + }, + "counter": { + "en": "Leave the ring when it turns red, then strike." + } + }, + { + "id": "claw_swipe", + "name": { + "en": "Claw swipe" + }, + "tell": { + "en": "A claw lifts and a red fan appears, brightening on the hit frame." + }, + "effect": { + "en": "Triggers when you come near." + }, + "counter": { + "en": "Leave the fan, then slash after the miss." + } + }, + { + "id": "ground_fire", + "name": { + "en": "Ground fire" + }, + "tell": { + "en": "Fire glows in the mouth and a ground fan appears (about 1.25 s)." + }, + "effect": { + "en": "Fire damage in the fan; can be blocked." + }, + "counter": { + "en": "Leave the fan or raise the shield." + } + }, + { + "id": "flying_fire", + "name": { + "en": "Flying fire" + }, + "tell": { + "en": "He flies up, an arrow shows at the screen edge and red fans appear with the flames." + }, + "effect": { + "en": "Fire sprays toward you from the air." + }, + "counter": { + "en": "Run out of the fans." + } + }, + { + "id": "rockfall", + "name": { + "en": "Rockfall" + }, + "tell": { + "en": "A red ring and shrinking outer ring mark the spot; the rock falls in about 1 s." + }, + "effect": { + "en": "Damages on impact; cannot be blocked." + }, + "counter": { + "en": "Roll out of the ring." + } + } + ], + "phases": [ + { + "en": "At lower health surfacing and idle times shorten and attacks come faster." + } + ] + }, + { + "case_id": "zelda/water_core_amoeba", + "boss": { + "en": "Water-Core Amoeba" + }, + "summary": { + "en": "A giant water mass in a pool with a core hidden inside and tentacles that rise from the floor." + }, + "moves": [ + { + "id": "tentacle_rise", + "name": { + "en": "Tentacle rise" + }, + "tell": { + "en": "A water ripple ring with a red outer ring appears at the root (about 3.5 s)." + }, + "effect": { + "en": "Contact damage when it surfaces." + }, + "counter": { + "en": "Step out of the ring first." + } + }, + { + "id": "tentacle_lash", + "name": { + "en": "Tentacle lash" + }, + "tell": { + "en": "The water column glows red and a red strip fills as the swing counts down." + }, + "effect": { + "en": "Damages on hit; can be blocked." + }, + "counter": { + "en": "Leave the strip or roll." + } + }, + { + "id": "tentacle_grab", + "name": { + "en": "Grab" + }, + "tell": { + "en": "A red ring marks the grab point; when caught a tightening water ring appears (about 2 s wind-up)." + }, + "effect": { + "en": "You take repeated damage while held." + }, + "counter": { + "en": "When caught, use struggle to break free in about ten packets." + } + }, + { + "id": "core_contact", + "name": { + "en": "Core contact" + }, + "tell": { + "en": "No warning; the core glows red even underwater." + }, + "effect": { + "en": "Touching the core hurts." + }, + "counter": { + "en": "Only close to sword range to hit it." + } + } + ] + }, + { + "case_id": "zelda/twin_flame_frost_witches", + "boss": { + "en": "Twin Flame-Frost Witches" + }, + "summary": { + "en": "Two witches, one flame and one frost, who fire flame or frost blasts; only one staff glows each time." + }, + "moves": [ + { + "id": "elemental_blast", + "name": { + "en": "Elemental blast" + }, + "tell": { + "en": "The target sigil lights, the staff glows and a ground line connects to you; about 3.35 s before release, and only the chosen staff glows." + }, + "effect": { + "en": "High damage; cannot be blocked, but the mirrored shield absorbs it." + }, + "counter": { + "en": "Raise the mirrored shield on the frame it arrives." + } + }, + { + "id": "body_contact", + "name": { + "en": "Body contact" + }, + "tell": { + "en": "No warning." + }, + "effect": { + "en": "Touching a witch hurts." + }, + "counter": { + "en": "Do not stand on them." + } + } + ] + } + ] +} diff --git a/environments/games/prototype/bossbench_llm/run.py b/environments/games/prototype/bossbench_llm/run.py new file mode 100644 index 0000000000000000000000000000000000000000..9262fa0fbb244203058ca83ec0e14161182a8892 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/run.py @@ -0,0 +1,273 @@ +"""Run LLM (or baseline) episodes on BossBench games with a Lumine-style loop. + +Each 200 ms of game time: one frame -> the model (same chat session, sliding window) -> one action (Lumine text or +semantic JSON) -> executed in the game. Default time mode is `paused`: the game waits for the model, so results do +not depend on inference speed and every run is replayable. `realtime`: every full 200 ms the model takes inserts +one empty 200 ms window before its action (latency under 200 ms costs nothing). + +Examples (run from the package root with PYTHONPATH=games/prototype): + python -m bossbench_llm.run --case terraria/king_slime --tier easy --seeds 1-3 --format lumine --lang en \ + --policy chat --base-url http://127.0.0.1:8000/v1 --model my-model + python -m bossbench_llm.run --case terraria/queen_bee --tier easy --format semantic --policy random --max-steps 50 +""" +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import statistics +import sys +import time + +from . import __version__, envs, frames, lumine, prompting +from .client import ChatClient, ChatError +from .policies import ChatPolicy, NoopPolicy, PythonPolicy, RandomPolicy, ReplayPolicy, Turn +from .session import Session + +TIERS = ("easy", "normal", "hard") + + +def parse_seeds(text): + out = [] + for part in str(text).split(","): + part = part.strip() + if not part: + continue + if "-" in part: + a, b = part.split("-", 1) + out += list(range(int(a), int(b) + 1)) + else: + out.append(int(part)) + if not out or any(s < 0 for s in out): + raise argparse.ArgumentTypeError("seeds must be non-negative integers, e.g. 1-5 or 1,4,9") + return out + + +def _stats(values): + if not values: + return None + values = sorted(values) + return {"mean": round(statistics.fmean(values), 4), "p50": round(values[len(values) // 2], 4), + "p95": round(values[min(len(values) - 1, int(0.95 * len(values)))], 4), "max": round(values[-1], 4)} + + +def _slug(case_id): + return case_id.replace("/", "__") + + +def run_episode(case_id, seed, options, args, policy, out_dir): + game = envs.game_of(case_id) + kind = prompting.mouse_kind(game) + system = prompting.system_prompt(game, case_id, args.format, args.lang, thinking=args.thinking, + counters=args.counters) + out_dir.mkdir(parents=True, exist_ok=False) + (out_dir / "system_prompt.txt").write_text(system, encoding="utf-8", newline="\n") + if args.save_frames: + (out_dir / "frames").mkdir() + size = None if args.image_size == "native" else tuple(int(v) for v in args.image_size.split("x")) + turns_file = (out_dir / "turns.jsonl").open("w", encoding="utf-8") + counts = {"decisions": 0, "format_errors": 0, "bare": 0, "lenient_fixes": 0, "unbound_keys": 0, "thoughts": 0, + "lag_packets": 0} + latencies, status, error = [], "finished", None + g, provenance, result, final_hash, sources = None, {}, {}, None, None + try: + g = envs.open_game(case_id, args.format, kind) + obs, info = g.reset(seed, options) + provenance = g.provenance() + max_steps = args.max_steps or int(math.ceil((provenance.get("max_seconds") or 600) / 0.2)) + 2 + session = Session(system, window=args.history, user_text=args.user_text) + turn = Turn(case_id=case_id, game=game, format=args.format, mouse_kind=kind, + lumine_keys=prompting.lumine_keys(game), vocab=getattr(g, "vocab", None)) + done = False + for index in range(max_steps): + start = time.perf_counter() + jpeg, url = frames.encode(obs, size, args.jpeg_quality) + if args.save_frames: + (out_dir / "frames" / f"{index:05d}.jpg").write_bytes(jpeg) + turn["index"] = index + try: + reply, meta = policy.act(session.messages(url), turn) + except ChatError as e: + status, error = "infra_error", str(e) + break + latency = time.perf_counter() - start + latencies.append(latency) + if args.format == "lumine": + parsed = lumine.parse(reply, mouse_kind=kind, lenient=args.lenient, accept_bare=not args.no_bare) + extra = {"bare": parsed.bare, "unbound": parsed.unbound, "mouse": list(parsed.mouse)} + counts["bare"] += parsed.bare + counts["unbound_keys"] += len(parsed.unbound) + else: + parsed = g.vocab.parse(reply, lenient=True) + extra = {} + counts["decisions"] += 1 + counts["format_errors"] += not parsed.ok + counts["lenient_fixes"] += parsed.lenient_fixes + counts["thoughts"] += bool(parsed.thought) + game_t = float(info.get("t", 0.0)) + lag = int(latency // 0.2) if args.time == "realtime" else 0 + for _ in range(lag): + obs, done, info = g.noop() + counts["lag_packets"] += 1 + if done: + break + if not done: + obs, done, info = g.step(parsed) + executed = g.packets[-1] if hasattr(g, "packets") and g.packets else (parsed.action if parsed.ok else None) + session.record(url, reply) + record = {"i": index, "t": game_t, "latency_s": round(latency, 4), "lag_packets": lag, "reply": reply, + "thought": parsed.thought, "ok": parsed.ok, "error": parsed.error, "action": parsed.text, + "executed": executed, "lenient_fixes": parsed.lenient_fixes, **extra, + "finish_reason": meta.get("finish_reason"), "usage": meta.get("usage")} + if meta.get("reasoning_content"): + record["reasoning_content"] = meta["reasoning_content"] + turns_file.write(json.dumps(record, ensure_ascii=False) + "\n") + if done: + break + else: + status = "collector_cut" # max_steps reached before the game ended: not a game outcome + result = g.result() + if hasattr(g, "packets"): + replay = g.replay() + (out_dir / "replay.json").write_text(json.dumps(replay, ensure_ascii=False), encoding="utf-8") + final_hash, sources = replay["final_hash"], replay["source_sha256"] + else: + replay = g.replay(out_dir / "semantic_replay.json") + final_hash, sources = None, replay.get("source") + except Exception as e: # noqa: BLE001 - record and continue with the next episode + status, error = "harness_error", f"{type(e).__name__}: {e}" + finally: + turns_file.close() + if g is not None: + g.close() + episode = { + "schema": "bossbench-llm/episode@1", "harness": __version__, + "created": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "case_id": case_id, "game": game, **(provenance or {}), "format": args.format, "lang": args.lang, + "thinking": args.thinking, "counters": args.counters, "history": args.history, + "image_size": args.image_size, "jpeg_quality": args.jpeg_quality, "time_mode": args.time, + "lenient": args.lenient if args.format == "lumine" else True, "mouse_kind": kind, + "seed": seed, "options": options, "policy": policy.describe(), + "prompt_sha256": hashlib.sha256(system.encode("utf-8")).hexdigest(), + "status": status, "error": error, **result, **counts, "latency_s": _stats(latencies), + "final_hash": final_hash, "source_sha256": sources, + } + (out_dir / "episode.json").write_text(json.dumps(episode, ensure_ascii=False, indent=2), encoding="utf-8") + return episode + + +def build_policy(args, case_id, fmt): + if args.policy == "chat": + if not args.base_url or not args.model: + raise SystemExit("--policy chat needs --base-url and --model") + extra = json.loads(args.extra_body) if args.extra_body else None + client = ChatClient(args.base_url, args.model, api_key_env=args.api_key_env, temperature=args.temperature, + top_p=args.top_p, max_tokens=args.max_tokens, timeout=args.timeout, retries=args.retries, + extra_body=extra) + return ChatPolicy(client) + if args.policy == "python": + if not args.policy_factory: + raise SystemExit("--policy python needs --policy-factory module:function") + return PythonPolicy(args.policy_factory, json.loads(args.policy_config) if args.policy_config else None) + if args.policy == "replay": + game = envs.game_of(case_id) + spec = None + if fmt == "semantic": + from bossbench import compact + spec = compact.load(game) + return ReplayPolicy(args.replay, fmt, prompting.mouse_kind(game), spec) + if args.policy == "noop": + return NoopPolicy(fmt) + return RandomPolicy(fmt, seed=args.policy_seed) + + +def main(argv=None): + p = argparse.ArgumentParser(prog="python -m bossbench_llm.run", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--case", action="append", help="case id, e.g. terraria/king_slime (repeatable)") + p.add_argument("--tier", choices=TIERS, help="difficulty tier (default normal unless --difficulty)") + p.add_argument("--difficulty", type=float, help="continuous difficulty in [0, 1] instead of a tier") + p.add_argument("--seeds", type=parse_seeds, default=[1], help="e.g. 1-5 or 1,3,7 (default 1)") + p.add_argument("--options", help="extra reset options as JSON, e.g. '{\"weapon\": \"bow\"}'") + p.add_argument("--format", choices=("lumine", "semantic"), default="lumine") + p.add_argument("--lang", choices=("en",), default="en") + p.add_argument("--thinking", action="store_true", help="allow <|thought_start|>...<|thought_end|> reasoning") + p.add_argument("--counters", action="store_true", help="include how to counter each boss move in the prompt") + p.add_argument("--policy", choices=("chat", "python", "replay", "noop", "random"), default="chat") + p.add_argument("--base-url"), p.add_argument("--model") + p.add_argument("--api-key-env", default="OPENAI_API_KEY", help="environment variable holding the API key") + p.add_argument("--temperature", type=float, default=1.0), p.add_argument("--top-p", type=float, default=1.0) + p.add_argument("--max-tokens", type=int, help="default 128, or 512 with --thinking") + p.add_argument("--extra-body", help="JSON merged into each request, e.g. '{\"skip_special_tokens\": false}'") + p.add_argument("--timeout", type=float, default=120.0), p.add_argument("--retries", type=int, default=3) + p.add_argument("--policy-factory"), p.add_argument("--policy-config") + p.add_argument("--policy-seed", type=int, default=0) + p.add_argument("--replay", help="bossbench/policy-replay@1 file for --policy replay (sets case/seed/options)") + p.add_argument("--history", type=int, default=20, help="image-action pairs kept in context (Lumine: 20)") + p.add_argument("--image-size", default="1280x720", help="WxH sent to the model, or 'native' (854x480)") + p.add_argument("--jpeg-quality", type=int, default=90) + p.add_argument("--user-text", help="optional text placed before each frame (Lumine sends the image only)") + p.add_argument("--time", choices=("paused", "realtime"), default="paused") + p.add_argument("--max-steps", type=int, help="decision cap per episode (default: the game's time limit)") + p.add_argument("--lenient", action="store_true", help="lumine: accept unambiguous key-name variants (counted)") + p.add_argument("--no-bare", action="store_true", help="lumine: reject actions without <|action_*|> markers") + p.add_argument("--save-frames", action="store_true", help="keep every JPEG sent to the model") + p.add_argument("--out", default="runs", help="output directory (a new timestamped folder is created inside)") + args = p.parse_args(argv) + if args.max_tokens is None: + args.max_tokens = 512 if args.thinking else 128 + jobs = [] + if args.policy == "replay": + if not args.replay: + raise SystemExit("--policy replay needs --replay FILE") + data = json.loads(Path(args.replay).read_text(encoding="utf-8")) + jobs.append((data["case_id"], int(data["gym_seed"]), dict(data["options"]))) + else: + if not args.case: + raise SystemExit("give at least one --case") + base = json.loads(args.options) if args.options else {} + if args.tier and args.difficulty is not None: + raise SystemExit("use --tier or --difficulty, not both") + if args.difficulty is not None: + base["difficulty"] = args.difficulty + else: + base["tier"] = args.tier or "normal" + for case_id in args.case: + envs.game_of(case_id) + for seed in args.seeds: + jobs.append((case_id, seed, dict(base))) + stamp = datetime.now().strftime("%Y%m%d-%H%M%S") + root = Path(args.out) / f"{stamp}-{args.format}-{args.policy}" + root.mkdir(parents=True, exist_ok=False) + (root / "command.json").write_text(json.dumps({"argv": sys.argv if argv is None else argv, + "args": {k: v for k, v in vars(args).items()}}, + ensure_ascii=False, indent=2, default=str), encoding="utf-8") + episodes = [] + for case_id, seed, options in jobs: + policy = build_policy(args, case_id, args.format) + tag = options.get("tier") or options.get("resolved_from_tier") or f"d{options.get('difficulty')}" + ep = run_episode(case_id, seed, options, args, policy, root / f"{_slug(case_id)}__{tag}__s{seed}") + episodes.append(ep) + print(f"{case_id:34s} {str(tag):7s} seed {seed:<4d} {ep['status']:13s} outcome={ep.get('outcome')!s:8s} " + f"boss_damage={ep.get('boss_damage')!s:7s} t={ep.get('seconds')!s:7s} decisions={ep['decisions']:<5d} " + f"format_errors={ep['format_errors']}", flush=True) + if ep["status"] == "harness_error": + print(" harness error:", ep["error"], file=sys.stderr) + keys = ("case_id", "seed", "status", "outcome", "win", "boss_damage", "seconds", "decisions", "format_errors", + "bare", "unbound_keys", "lag_packets") + (root / "summary.json").write_text(json.dumps(episodes, ensure_ascii=False, indent=2), encoding="utf-8") + with (root / "summary.csv").open("w", encoding="utf-8") as f: + f.write(",".join(keys) + "\n") + for ep in episodes: + f.write(",".join(str(ep.get(k, "")) for k in keys) + "\n") + wins = sum(bool(ep.get("win")) for ep in episodes) + print(f"{wins}/{len(episodes)} wins -> {root}") + return 0 if all(ep["status"] in ("finished", "collector_cut") for ep in episodes) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/environments/games/prototype/bossbench_llm/semantic.py b/environments/games/prototype/bossbench_llm/semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..4524efe92fbf1a9fe43621cfe2ecd1b03e62fb1a --- /dev/null +++ b/environments/games/prototype/bossbench_llm/semantic.py @@ -0,0 +1,161 @@ +"""Semantic (named) actions: one JSON object per 200 ms decision, e.g. {"move": "forward", "turn": "left_10"}. + +The vocabulary of every game is read from the game's own declaration, never re-typed here: +* 18 games: web/games//compact_actions.json (bossbench/compact-actions@1, the 2026-11-10 ViZDoom-style + action heads). One semantic action = one ordinary 200 ms key/mouse packet (bossbench.make_compact_env). +* terraria_remake (exempt from compact actions): its LLM semantic interface terraria-semantic@1 + (web/games/terraria_remake/semantic_ppo_v1): move / vert / attack, where attack "shoot " aims relative to + the player's own body. Its native window is 100 ms, so one 200 ms decision runs two identical windows. + +Model output: a JSON object {head: option label}; omitted heads take option 0 ("none"). The text form +"head=label; head=label" is accepted too. Anything else runs a no-op and counts as a format error. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +import json +import math +import re + +from .lumine import strip_thoughts + +FORMAT = "semantic-action@1" +TERRARIA = "terraria_remake" + +_TERRARIA_HEADS = [ + {"name": "move", "en": "horizontal movement", "options": [ + {"label": "none", "en": "stay"}, {"label": "left", "en": "move left"}, + {"label": "right", "en": "move right"}]}, + {"name": "vert", "en": "jump / drop", "options": [ + {"label": "none", "en": "nothing"}, + {"label": "jump", "en": "jump; keep choosing it to fly or glide"}, + {"label": "drop", "en": "drop through the platform below"}]}, + {"name": "attack", "en": "attack", "options": ( + [{"label": "none", "en": "no attack"}] + + [{"label": f"shoot {i * 22.5:g}", + "en": f"shoot an arrow toward {i * 22.5:g}° (0° = right, 90° = up)"} for i in range(16)] + + [{"label": "slash left", "en": "swing the sword to the left"}, + {"label": "slash right", "en": "swing the sword to the right"}])}, +] +_SHOOT = re.compile(r"shoot[\s_]*([+-]?\d+(?:\.\d+)?)\s*(?:°|deg|degrees)?", re.I) + + +def _norm(label): + return re.sub(r"[\s\-_]+", "_", str(label).strip().lower()) + + +@dataclass +class SemParsed: + ok: bool + action: dict | None = None # canonical {head: label} for every head + thought: str | None = None + lenient_fixes: int = 0 + error: str | None = None + + @property + def text(self): + return json.dumps(self.action, ensure_ascii=False) if self.ok else None + + +class Vocabulary: + """The named action heads of one game.""" + + def __init__(self, game, heads, *, window_seconds=0.2, version=None, source=None): + self.game, self.heads, self.window_seconds = game, heads, window_seconds + self.version, self.source = version, source + self.names = [h["name"] for h in heads] + + @classmethod + def for_game(cls, game): + if game == TERRARIA: + return cls(game, _TERRARIA_HEADS, window_seconds=0.1, version="terraria-semantic@1", + source="web/games/terraria_remake/semantic_ppo_v1/actions.py") + from bossbench import compact + spec = compact.load(game) + heads = [{"name": h["name"], "zh": h.get("zh"), + "options": [{k: v for k, v in o.items() if k in ("label", "zh", "en", "note", "keys", "tap", "subs", "dx", "dy", "dz")} + for o in h["options"]]} + for h in spec.raw["heads"]] + return cls(game, heads, version=spec.version, + source=compact.declaration_path(game).relative_to(compact.ROOT).as_posix()) + + @property + def size(self): + return math.prod(len(h["options"]) for h in self.heads) + + def labels(self, head): + return [o["label"] for o in next(h for h in self.heads if h["name"] == head)["options"]] + + def neutral(self): + return {h["name"]: h["options"][0]["label"] for h in self.heads} + + def _label(self, head, value, lenient): + labels = self.labels(head) + if not isinstance(value, str): + if isinstance(value, int) and not isinstance(value, bool) and lenient and 0 <= value < len(labels): + return labels[value], True + raise ValueError(f"{head}: option must be a label string, got {value!r}") + if value in labels: + return value, False + if self.game == TERRARIA and head == "attack": + m = _SHOOT.fullmatch(value.strip()) + if m: + k = math.floor(float(m.group(1)) / 22.5 + 0.5) % 16 # nearest 22.5 deg, ties upward, wraps + return f"shoot {k * 22.5:g}", True + by_norm = {_norm(x): x for x in labels} + if _norm(value) in by_norm: + return by_norm[_norm(value)], True + raise ValueError(f"{head}: no option {value!r}; options are {labels}") + + def canonical(self, mapping, lenient=True): + unknown = [k for k in mapping if k not in self.names] + if unknown: + raise ValueError(f"unknown action group(s) {unknown}; groups are {self.names}") + action, fixes = self.neutral(), 0 + for head, value in mapping.items(): + label, fixed = self._label(head, value, lenient) + action[head] = label + fixes += fixed + return action, fixes + + def parse(self, reply, *, lenient=True): + """Model reply -> SemParsed. Never raises on model output.""" + text, thought = strip_thoughts("" if reply is None else str(reply)) + for mark in ("<|semantic_start|>", "<|semantic_end|>", "<|compact_start|>", "<|compact_end|>"): + text = text.replace(mark, " ") + mapping = None + decoder = json.JSONDecoder() + for i, ch in enumerate(text): + if ch == "{": + try: + obj, _ = decoder.raw_decode(text, i) + except ValueError: + continue + if isinstance(obj, dict): + mapping = obj + break + if mapping is None: + body = text.strip().strip("`").strip() + if body and ("=" in body or ":" in body): + mapping = {} + try: + for part in re.split(r"[;\n,]", body): + part = part.strip() + if not part: + continue + head, sep, label = part.replace(":", "=", 1).partition("=") + if not sep: + raise ValueError(f"expected group=option, got {part!r}") + head, label = head.strip().strip('"\''), label.strip().strip('"\'') + if head in mapping: + raise ValueError(f"group {head!r} given twice") + mapping[head] = label + except ValueError as e: + return SemParsed(False, thought=thought, error=str(e)) + if mapping is None: + return SemParsed(False, thought=thought, error="no JSON object in the reply") + try: + action, fixes = self.canonical(mapping, lenient) + except ValueError as e: + return SemParsed(False, thought=thought, error=str(e)) + return SemParsed(True, action=action, thought=thought, lenient_fixes=fixes) diff --git a/environments/games/prototype/bossbench_llm/session.py b/environments/games/prototype/bossbench_llm/session.py new file mode 100644 index 0000000000000000000000000000000000000000..70b246b6d52506beb7a7ac868f8bf727d83e7b1c --- /dev/null +++ b/environments/games/prototype/bossbench_llm/session.py @@ -0,0 +1,53 @@ +"""One chat session per episode, kept the way Lumine keeps it. + +Context = system prompt (+ the latest reasoning, if any) followed by the most recent `window` image-action pairs as +alternating user / assistant turns; the oldest pair is dropped first (FIFO). When the model writes new reasoning +(<|thought_start|>...<|thought_end|>), the pairs are flushed and re-accumulate from that turn, and the reasoning +moves to the head of the context. window=0 sends only the current frame (Lumine's non-history setting). +""" +from __future__ import annotations + +from collections import deque + +from .lumine import strip_thoughts + + +class Session: + def __init__(self, system_prompt, window=20, user_text=None): + if window < 0: + raise ValueError("window must be >= 0") + self.system_prompt, self.window, self.user_text = system_prompt, int(window), user_text + self.pairs = deque() + self.thought = None + self.flushes = 0 + + def _user(self, data_url): + content = [] + if self.user_text: + content.append({"type": "text", "text": self.user_text}) + content.append({"type": "image_url", "image_url": {"url": data_url}}) + return {"role": "user", "content": content} + + def messages(self, data_url): + """Messages for the current turn: history + the new frame.""" + system = self.system_prompt + if self.thought: + system += "\n\n<|thought_start|>" + self.thought + "<|thought_end|>" + out = [{"role": "system", "content": system}] + for url, reply in self.pairs: + out.append(self._user(url)) + out.append({"role": "assistant", "content": reply}) + out.append(self._user(data_url)) + return out + + def record(self, data_url, reply): + """Store the finished turn. The reasoning (if any) moves to the head; the pair keeps only the action.""" + action_only, thought = strip_thoughts(reply or "") + if thought: + self.thought = thought + self.pairs.clear() + self.flushes += 1 + if self.window: + self.pairs.append((data_url, action_only.strip())) + while len(self.pairs) > self.window: + self.pairs.popleft() diff --git a/environments/games/prototype/bossbench_llm/verify.py b/environments/games/prototype/bossbench_llm/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee7ab60eab51019d455e65ca7df8d7059744fc0 --- /dev/null +++ b/environments/games/prototype/bossbench_llm/verify.py @@ -0,0 +1,107 @@ +"""Re-run recorded episodes and check they reproduce exactly (outcome, ticks, engine final-state hash). + + python -m bossbench_llm.verify runs// [more dirs or replay files ...] + python -m bossbench_llm.verify replays/*.replay.json + +Accepts episode folders written by bossbench_llm.run (replay.json or semantic_replay.json inside) and plain +bossbench/policy-replay@1 files. Also reports source files whose bytes differ from +the ones recorded (a different game version), which is the usual reason a replay stops reproducing. +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +import bossbench +from bossbench import scripted + +from .envs import ROOT + + +def _replay(env, data): + """scripted.replay, but a recording cut before the game ended (collector_cut) is compared where it stopped.""" + if data.get("outcome") is not None: + return scripted.replay(env, data) + raw, problems = env.unwrapped, [] + if data.get("rules") != scripted.rules(env): + problems.append(f"rules mismatch: recording {data.get('rules')!r}, engine {scripted.rules(env)!r}") + env.reset(seed=int(data["gym_seed"]), options=dict(data["options"])) + for index, packet in enumerate(data["packets"]): + _, _, terminated, truncated, _ = env.step(packet) + if (terminated or truncated) and index != len(data["packets"]) - 1: + problems.append(f"game ended at packet {index}, recording continues") + break + final, ticks = scripted.state_hash(env), int(round(raw.snap["t"] * raw.fps)) + if final != data.get("final_hash"): + problems.append(f"final hash mismatch: {final} vs {data.get('final_hash')}") + if ticks != data.get("ticks"): + problems.append(f"tick mismatch: {ticks} vs {data.get('ticks')}") + return raw.verifier()["outcome"], final, ticks, problems + + +def verify_policy_replay(path): + data = json.loads(Path(path).read_text(encoding="utf-8")) + env = bossbench.make_policy_env(data["case_id"]) + try: + current = scripted.source_files(env) if data.get("source_sha256") else {} + drift = sorted(k for k, v in (data.get("source_sha256") or {}).items() if current.get(k) != v) + outcome, final, ticks, problems = _replay(env, data) + finally: + env.close() + return {"file": str(path), "case_id": data["case_id"], "outcome": outcome, "ticks": ticks, "final_hash": final, + "ok": not problems, "problems": problems, "source_drift": drift} + + +def verify_semantic_replay(path): + if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + from web.games.terraria_remake.semantic_ppo_v1.env import verify_replay + data = json.loads(Path(path).read_text(encoding="utf-8")) + try: + out = verify_replay(path) + return {"file": str(path), "case_id": data.get("case_id"), "ok": True, "detail": out} + except Exception as e: # noqa: BLE001 + return {"file": str(path), "case_id": data.get("case_id"), "ok": False, "problems": [f"{type(e).__name__}: {e}"]} + + +def verify(target): + target = Path(target) + if target.is_dir(): + if (target / "replay.json").is_file(): + return verify_policy_replay(target / "replay.json") + if (target / "semantic_replay.json").is_file(): + return verify_semantic_replay(target / "semantic_replay.json") + return {"file": str(target), "ok": False, "problems": ["no replay.json / semantic_replay.json in this folder"]} + data = json.loads(target.read_text(encoding="utf-8")) + if data.get("format") == scripted.REPLAY_FORMAT: + return verify_policy_replay(target) + if str(data.get("schema", "")).startswith("terraria/semantic-replay"): + return verify_semantic_replay(target) + return {"file": str(target), "ok": False, "problems": ["unknown replay format"]} + + +def main(argv=None): + p = argparse.ArgumentParser(prog="python -m bossbench_llm.verify", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("targets", nargs="+") + p.add_argument("--json", help="write the results to this file") + args = p.parse_args(argv) + results = [] + for t in args.targets: + r = verify(t) + results.append(r) + state = "OK " if r["ok"] else "FAIL" + print(f"{state} {r.get('case_id') or ''} {r['file']}" + ("" if r["ok"] else f" {r.get('problems')}")) + if r.get("source_drift"): + print(f" source files changed since recording: {r['source_drift']}") + if args.json: + Path(args.json).write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8") + bad = sum(not r["ok"] for r in results) + print(f"{len(results) - bad}/{len(results)} reproduced exactly") + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/environments/games/web/engine/app.js b/environments/games/web/engine/app.js new file mode 100644 index 0000000000000000000000000000000000000000..f08f7e4937c627f16c55de6763a37dd15aad48d8 --- /dev/null +++ b/environments/games/web/engine/app.js @@ -0,0 +1,220 @@ +// Browser app shell shared by every game: boss select, human play loop, and the agent-facing API (window.BossBench). +// Game-specific content comes from the manifest BB.GAME = {id, title, roster: [{id, name, arch}], defaultCase} +// (games//game.js); the page (games//index.html) supplies the DOM and the controls help. +(function (g) { + var BB = g.BB, doc = g.document; + var GAME = BB.GAME || {}, ROSTER = GAME.roster || Object.keys(BB.CASES).sort().map(function (id) { return { id: id, name: BB.CASES[id].title, arch: '' }; }); + var $ = function (id) { return doc.getElementById(id); }; + var canvas = $('view'), R = new BB.Renderer(canvas), input = new BB.Input(g); + input.bindMouse(canvas); + input.enabled = false; + var sel = { id: GAME.defaultCase || ROSTER.filter(function (b) { return BB.CASES[b.id]; })[0].id, d: 0.5, seed: 0 }; + var game = null; // {case, subs, packets, acc, hold, paused, done} + var mode = 'select'; + + // ---------- select screen ---------- + var grid = $('grid'); + ROSTER.forEach(function (b) { b.playable = !!BB.CASES[b.id]; }); + ROSTER.forEach(function (b) { + var el = doc.createElement('button'); + el.className = 'card' + (b.id === sel.id ? ' on' : '') + (b.playable ? '' : ' locked'); + el.setAttribute('aria-pressed', String(b.id === sel.id)); + el.innerHTML = '
'; + el.querySelector('.nm').textContent = b.name; + el.querySelector('.ar').textContent = b.arch; + el.querySelector('.tag').textContent = b.playable ? 'PLAYABLE' : 'LOCKED'; + el.dataset.id = b.id; + if (!b.playable) { el.disabled = true; el.title = 'Not implemented: planned 2D scene'; } + el.addEventListener('click', function () { + if (!b.playable) return; + sel.id = b.id; + [].forEach.call(grid.children, function (c) { c.classList.toggle('on', c.dataset.id === b.id); c.setAttribute('aria-pressed', String(c.dataset.id === b.id)); }); + skillTable(); preview = new BB.Case(sel.id); preview.reset(3, 0.5); R.juice.reset(); + }); + grid.appendChild(el); + }); + function setD(d) { + sel.d = Math.round(d * 100) / 100; $('dslider').value = sel.d; $('dval').textContent = sel.d.toFixed(2); + [].forEach.call(doc.querySelectorAll('[data-d]'), function (b) { b.classList.toggle('on', +b.dataset.d === sel.d); }); + } + // Public difficulty = three tiers (2026-11-02). When the game declares BB.GAME.tiers, the page's preset + // buttons are rebuilt from that declaration so the page and bossbench.make_policy_env(tier=...) agree. + if (GAME.tiers) { + var presets = doc.querySelectorAll('[data-d]'), names = { easy: 'Easy', normal: 'Normal', hard: 'Hard' }; + if (presets.length) { + var host = presets[0].parentNode, cls = presets[0].className.replace(/\bon\b/, '').trim(); + [].forEach.call(presets, function (b) { b.parentNode.removeChild(b); }); + ['easy', 'normal', 'hard'].forEach(function (t) { + var b = doc.createElement('button'); b.className = cls; b.dataset.d = String(GAME.tiers[t]); b.dataset.tier = t; + b.textContent = names[t] + ' ' + GAME.tiers[t]; host.appendChild(b); + }); + } + sel.d = GAME.tiers.normal; + } + [].forEach.call(doc.querySelectorAll('[data-d]'), function (b) { b.addEventListener('click', function () { setD(+b.dataset.d); }); }); + if (GAME.tiers) setD(GAME.tiers.normal); + $('dslider').addEventListener('input', function () { setD(+this.value); }); + $('start').addEventListener('click', function () { sel.seed = (+$('seed').value) >>> 0; start(); }); + // Standard live scripted demo (BB.GAME.scripted): the same trusted controller the harness drives through + // bossbench.make_policy_env; packets are recorded exactly like a human run. + if (typeof GAME.scripted === 'function' && !$('scripted-start')) { + var scriptedButton = doc.createElement('button'); + scriptedButton.id = 'scripted-start'; scriptedButton.type = 'button'; + scriptedButton.className = $('start').className; scriptedButton.textContent = 'Scripted Demo'; + scriptedButton.title = 'Reference script controller: reads internal state and is only for demos and replays, not model performance'; + $('start').insertAdjacentElement('afterend', scriptedButton); + scriptedButton.addEventListener('click', function () { sel.seed = (+$('seed').value) >>> 0; start(true); }); + } + $('again').addEventListener('click', function () { start(); }); + $('back').addEventListener('click', toSelect); + function skillTable() { + var ul = $('skilllist'), def = BB.CASES[sel.id], spec = new def.Boss().spec; + ul.textContent = ''; doc.querySelector('#skills h3').textContent = 'Move list:' + def.title; + spec.moves.forEach(function (m) { + var li = doc.createElement('li'); + var local = GAME.skillText && GAME.skillText[sel.id] && GAME.skillText[sel.id][m.name]; + li.textContent = local || m.name + ': ' + m.cue + (m.punish ? ' → ' + m.punish : ''); + ul.appendChild(li); + }); + } + skillTable(); + + function start(auto) { + var options = typeof GAME.resetOptions === 'function' ? GAME.resetOptions() : {}; + var c = new BB.Case(sel.id); c.reset(sel.seed, sel.d, options); + R.juice.reset(); + game = { c: c, options: options, subs: [], packets: [], acc: 0, hold: 0, paused: false, keys: {}, mouse: [0, 0, 0], t0: performance.now(), + auto: !!auto, autoPacket: null }; + mode = 'play'; + input.clear(); input.enabled = !auto; + if ($('play-actions')) $('play-actions').classList.remove('hidden'); + if ($('pausepanel')) $('pausepanel').classList.add('hidden'); + if ($('pause')) $('pause').textContent = 'Pause'; + $('select').classList.add('hidden'); $('result').classList.add('hidden'); $('pausehint').classList.remove('hidden'); + canvas.focus && canvas.focus(); + } + function toSelect() { + mode = 'select'; game = null; + input.clear(); input.enabled = false; + if ($('play-actions')) $('play-actions').classList.add('hidden'); + if ($('pausepanel')) $('pausepanel').classList.add('hidden'); + $('result').classList.add('hidden'); $('select').classList.remove('hidden'); $('pausehint').classList.add('hidden'); + } + function finish() { + mode = 'result'; + input.clear(); input.enabled = false; + if ($('play-actions')) $('play-actions').classList.add('hidden'); + var c = game.c, v = c.verifier(); + var messages = GAME.results || {win: 'VICTORY', loss: 'DEFEATED', timeout: 'TIME UP'}; + $('rtitle').textContent = messages[v.outcome]; + $('rtitle').style.color = v.outcome === 'win' ? 'var(--gold)' : (GAME.results ? '#c63061' : '#ff8a7a'); + $('rsub').textContent = 'Boss damage ' + Math.round(v.boss_damage * 100) + '% · time: ' + v.seconds.toFixed(1) + ' s · remaining health: ' + v.player_hp; + $('rjson').textContent = 'verifier = ' + JSON.stringify(v) + '\npackets recorded = ' + game.packets.length; + $('result').classList.remove('hidden'); $('pausehint').classList.add('hidden'); + g.BossBench.lastRun = { case: sel.id, seed: sel.seed, d: sel.d, packets: game.packets.slice(), verifier: v, final_hash: BB.hashState(c) }; + if (GAME.rules) g.BossBench.lastRun.rules = GAME.rules; + if (typeof GAME.resetOptions === 'function') g.BossBench.lastRun.options = game.options; + } + function pause() { + if (mode !== 'play') return; + game.paused = !game.paused; input.clear(); input.enabled = !game.paused; + if ($('pausepanel')) $('pausepanel').classList.toggle('hidden', !game.paused); + if ($('pause')) $('pause').textContent = game.paused ? 'Resume' : 'Pause'; + } + if ($('pause')) $('pause').addEventListener('click', pause); + if ($('resume')) $('resume').addEventListener('click', pause); + if ($('quit')) $('quit').addEventListener('click', toSelect); + if ($('download')) $('download').addEventListener('click', function () { + if (!g.BossBench.lastRun) return; + var url = URL.createObjectURL(new Blob([JSON.stringify(g.BossBench.lastRun, null, 2)], {type: 'application/json'})); + var a = doc.createElement('a'); a.href = url; a.download = GAME.id + '-replay.json'; a.click(); + setTimeout(function () { URL.revokeObjectURL(url); }, 1000); + }); + g.addEventListener('keydown', function (e) { + if (e.repeat) return; + if (mode === 'play' && (e.code === 'Escape' || e.code === 'KeyP')) { pause(); e.preventDefault(); } + else if (mode === 'result' && e.code === 'KeyR') start(); + else if (mode === 'result' && e.code === 'Escape') toSelect(); + else if (mode === 'select' && e.code === 'Enter') $('start').click(); + if (mode === 'play' && game.paused && e.code === 'KeyQ') toSelect(); + }); + g.addEventListener('blur', function () { if (mode === 'play' && !game.paused) pause(); }); + + // ---------- human loop: fixed 60 Hz ticks; input sampled once per 33 ms sub-step (= packet K(j)) ---------- + var last = performance.now(), idleT = 0; + var preview = new BB.Case(sel.id); preview.reset(3, 0.5); + function frame(now) { + var dt = Math.min(0.1, (now - last) / 1000); last = now; + if (mode === 'play' && !game.paused) { + var c = game.c; + if (game.hold > 0) game.hold -= dt; // hit-stop: wall-clock pause, the tick sequence is unchanged + else { + game.acc += dt; + while (game.acc >= BB.DT && !c.result) { + if (!game.auto && typeof c.body.mouse === 'function') { + // Aim is sampled once per packet: live play and packet replay distribute the same integer delta. + if (c.t % (BB.SUBSTEPS * BB.TICKS_PER_SUB) === 0) { + game.packetMouse = [0, 0, 0]; + if (input.pointer && typeof c.body.pointerDelta === 'function') game.packetMouse = c.body.pointerDelta(input.pointer, BB.VIEW); + game.mouse = game.packetMouse.map(function (v) { return v / (BB.SUBSTEPS * BB.TICKS_PER_SUB); }); + } + } + if (game.auto && c.t % (BB.SUBSTEPS * BB.TICKS_PER_SUB) === 0) { + game.autoPacket = BB.parsePacket(BB.scriptedPacket(c)); + game.packetMouse = game.autoPacket.mouse.slice(); + game.mouse = game.packetMouse.map(function (v) { return v / (BB.SUBSTEPS * BB.TICKS_PER_SUB); }); + } + if (c.t % BB.TICKS_PER_SUB === 0) { + game.keys = game.auto ? game.autoPacket.subs[(c.t % (BB.SUBSTEPS * BB.TICKS_PER_SUB)) / BB.TICKS_PER_SUB] : input.sample(); + game.subs.push(game.keys); + if (game.subs.length === BB.SUBSTEPS) { game.packets.push(BB.formatPacket(game.subs, game.packetMouse)); game.subs = []; } + } + c.tick(game.keys, game.mouse); game.acc -= BB.DT; + } + } + R.draw(c, c.t / BB.FPS, game.paused ? 'PAUSED' : ''); + var hs = R.juice.takeHitstop(); if (hs > 0) { game.hold = Math.max(game.hold, hs); game.acc = 0; } + if (c.result) { if (game.subs.length) game.packets.push(BB.formatPacket(game.subs.concat([{}, {}, {}, {}, {}, {}]).slice(0, 6), game.packetMouse)); finish(); } + } else if (mode === 'play') { + R.draw(game.c, game.c.t / BB.FPS, 'PAUSED (Esc Resume · Q Exit)'); + } else if (mode === 'select') { + idleT += dt; // attract mode behind the menu: boss alone, no player input + while (idleT >= BB.DT) { preview.tick({}); idleT -= BB.DT; if (preview.result) { preview.reset(preview.seed + 1, 0.5); R.juice.reset(); } } + R.draw(preview, preview.t / BB.FPS, ''); + } + g.__bb_ready = true; + g.requestAnimationFrame(frame); + } + g.requestAnimationFrame(frame); + + // ---------- agent-facing API (proposal 4.4) ---------- + // env = BossBench.make('2d/needle_warden', {obs_mode:'rgb'|'symbolic', time_mode:'paused'|'virtual_rt'|'wallclock_rt', latency}) + // r = env.reset(seed, {difficulty}); r = env.step('<|action_start|> 0 0 0 ; D ; D ; D,Space ; ; J ; J <|action_end|>') + // rgb obs = PNG data URL of the 854x480 frame, rendered on a private canvas (deterministic: shake uses sim time). + function rgbRenderer() { + var cv = doc.createElement('canvas'), rr = new BB.Renderer(cv); + return function (c) { rr.draw(c, c.t / BB.FPS, ''); return cv.toDataURL('image/png'); }; + } + g.BossBench = { + game: GAME.id, cases: ROSTER, + make: function (id, opts) { + opts = Object.assign({ obs_mode: 'rgb' }, opts || {}); + if (opts.obs_mode === 'rgb' && !opts.renderer) opts.renderer = rgbRenderer(); + return BB.make(id, opts); + }, + NOOP: BB.NOOP, parsePacket: BB.parsePacket, formatPacket: BB.formatPacket, + // show an env's case on the main canvas (for watching an agent play) + watch: function (env, label) { + mode = 'watch'; input.clear(); input.enabled = false; + sel.id = env.case.id; + [].forEach.call(grid.children, function (card) { card.classList.toggle('on', card.dataset.id === sel.id); card.setAttribute('aria-pressed', String(card.dataset.id === sel.id)); }); + skillTable(); + $('select').classList.add('hidden'); $('result').classList.add('hidden'); $('pausehint').classList.add('hidden'); + if ($('play-actions')) $('play-actions').classList.add('hidden'); if ($('pausepanel')) $('pausepanel').classList.add('hidden'); + R.juice.reset(); this._watched = env; this._watchLabel = label || 'AGENT'; R.draw(env.case, env.case.t / BB.FPS, this._watchLabel); + }, + takeHitstop: function () { return R.juice.takeHitstop(); }, + redraw: function () { if (this._watched) R.draw(this._watched.case, this._watched.case.t / BB.FPS, this._watchLabel || 'AGENT'); }, + lastRun: null + }; +})(window); diff --git a/environments/games/web/engine/art_kit.js b/environments/games/web/engine/art_kit.js new file mode 100644 index 0000000000000000000000000000000000000000..95c1da5bdb037cc80257c3812c44a51a2d9e5ad0 --- /dev/null +++ b/environments/games/web/engine/art_kit.js @@ -0,0 +1,112 @@ +// Art kit: drawing helpers for figures and scenes, plus a per-renderer pose smoother (BB.ART). Game-agnostic: +// no layout and no colours here. Pure presentation: reads the Case, never writes it. Everything is procedural +// and seeded (BB.RNG) or a function of presentation time t, so frames are reproducible. +(function (g) { + var BB = g.BB, TAU = Math.PI * 2; + var ART = BB.ART = BB.ART || {}; + + // ---------- small maths ---------- + function c01(v) { return v < 0 ? 0 : v > 1 ? 1 : v; } + ART.c01 = c01; + ART.mix = function (a, b, k) { return a + (b - a) * k; }; + ART.easeOut = function (k) { k = c01(k); return 1 - (1 - k) * (1 - k) * (1 - k); }; + ART.easeIn = function (k) { k = c01(k); return k * k; }; + ART.easeInOut = function (k) { k = c01(k); return k * k * (3 - 2 * k); }; + // hit flash: tint a fill most of the way to warm white (keeps the form readable instead of a flat white cut-out) + var litCache = {}; + ART.lit = function (on, col) { + if (!on) return col; + if (typeof col !== 'string' || col.charAt(0) !== '#') return '#f2ece2'; + if (litCache[col]) return litCache[col]; + var h = col.length === 4 ? col.replace(/#(.)(.)(.)/, '#$1$1$2$2$3$3') : col, out = '#'; + for (var i = 0; i < 3; i++) { var v = parseInt(h.substr(1 + i * 2, 2), 16); v = Math.round(v + (255 - v) * 0.55); out += (v < 16 ? '0' : '') + v.toString(16); } + return (litCache[col] = out); + }; + ART.rgba = function (rgb, a) { return 'rgba(' + rgb + ',' + (+a).toFixed(3) + ')'; }; + ART.hash = function (i) { var s = Math.sin(i * 127.1 + 311.7) * 43758.5453; return s - Math.floor(s); }; + + // ---------- pose smoothing ---------- + // The renderer calls begin() once per frame with its own store; smooth() then eases numeric pose fields toward the + // target of the current FSM state, so a state change blends over a few frames instead of snapping. + // A new case, a rewind or a long gap resets the store (first frame = exact target pose). + ART.begin = function (store, c, t) { + store.fresh = store.c !== c || store.t == null || t < store.t || t - store.t > 0.5; + if (store.fresh) { store.c = c; store.p = {}; } + store.dt = store.fresh ? 0 : t - store.t; store.t = t; ART.store = store; + }; + ART.smooth = function (key, tgt, rate) { + var st = ART.store, cur = st.p[key], k; + if (!cur) { cur = st.p[key] = {}; k = 1; } else k = 1 - Math.exp(-st.dt * (rate || 20)); + for (var n in tgt) { + var v = tgt[n]; + if (typeof v !== 'number' || cur[n] == null || typeof cur[n] !== 'number') cur[n] = v; + else cur[n] += (v - cur[n]) * k; + } + return cur; + }; + ART.dt = function () { return ART.store ? ART.store.dt : 0; }; + + // ---------- path helpers ---------- + ART.bez = function (p0, p1, p2, p3, n) { + var out = []; + for (var i = 0; i <= n; i++) { + var t = i / n, u = 1 - t, a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t; + out.push([a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]]); + } + return out; + }; + // closed ribbon along a polyline, width w0 -> w1 (roots, vines, horns, tails, cloth strips) + ART.ribbon = function (x, pts, w0, w1) { + var n = pts.length, L = [], R = [], i; + for (i = 0; i < n; i++) { + var a = pts[Math.max(0, i - 1)], b = pts[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], d = Math.sqrt(dx * dx + dy * dy) || 1; + var w = (w0 + (w1 - w0) * i / Math.max(1, n - 1)) / 2; + L.push([pts[i][0] - dy / d * w, pts[i][1] + dx / d * w]); R.push([pts[i][0] + dy / d * w, pts[i][1] - dx / d * w]); + } + x.moveTo(L[0][0], L[0][1]); + for (i = 1; i < n; i++) x.lineTo(L[i][0], L[i][1]); + for (i = n - 1; i >= 0; i--) x.lineTo(R[i][0], R[i][1]); + x.closePath(); + }; + ART.poly = function (x, pts) { x.moveTo(pts[0][0], pts[0][1]); for (var i = 1; i < pts.length; i++) x.lineTo(pts[i][0], pts[i][1]); x.closePath(); }; + // smooth closed shape through points (quadratic midpoints) + ART.blobPath = function (x, pts) { + var n = pts.length, m = function (i) { var p = pts[i % n], q = pts[(i + 1) % n]; return [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2]; }; + var s = m(n - 1); x.moveTo(s[0], s[1]); + for (var i = 0; i < n; i++) { var e = m(i); x.quadraticCurveTo(pts[i][0], pts[i][1], e[0], e[1]); } + x.closePath(); + }; + // fill the current path, then an ink outline + ART.ink = function (x, fill, lw, ink) { + x.fillStyle = fill; x.fill(); + if (lw) { x.lineJoin = 'round'; x.lineCap = 'round'; x.lineWidth = lw; x.strokeStyle = ink || '#05070a'; x.stroke(); } + }; + ART.glow = function (x, cx, cy, r, rgb, a) { // soft additive light + if (!(r > 0) || !(a > 0)) return; + var gr = x.createRadialGradient(cx, cy, 0, cx, cy, r); + gr.addColorStop(0, ART.rgba(rgb, a)); gr.addColorStop(0.4, ART.rgba(rgb, a * 0.45)); gr.addColorStop(1, ART.rgba(rgb, 0)); + var o = x.globalCompositeOperation; x.globalCompositeOperation = 'lighter'; + x.fillStyle = gr; x.fillRect(cx - r, cy - r, 2 * r, 2 * r); + x.globalCompositeOperation = o; + }; + ART.shade = function (x, cx, cy, rx, ry, a) { // contact shadow on the floor + if (!(rx > 0) || !(a > 0)) return; + var gr = x.createRadialGradient(cx, cy, 0, cx, cy, rx); + gr.addColorStop(0, 'rgba(0,0,0,' + a.toFixed(3) + ')'); gr.addColorStop(1, 'rgba(0,0,0,0)'); + x.save(); x.translate(cx, cy); x.scale(1, ry / rx); x.translate(-cx, -cy); + x.fillStyle = gr; x.beginPath(); x.arc(cx, cy, rx, 0, TAU); x.fill(); x.restore(); + }; + // tattered hem: lineTo points from (x0,y) to (x1,y), alternating long / short tongues, waving with ph + ART.hem = function (x, x0, x1, y, n, depth, wave, ph, seed) { + for (var i = 0; i <= n; i++) { + var k = i / n, h = ART.hash(i + (seed || 0)), d = (i % 2 ? depth : depth * 0.25) * (0.7 + 0.6 * h); + x.lineTo(x0 + (x1 - x0) * k + Math.sin(ph + i * 1.7) * wave, y + d + Math.cos(ph * 0.8 + i) * wave * 0.4); + } + }; + // four-point star sparkle + ART.spark = function (x, cx, cy, s, col) { + x.fillStyle = col; x.beginPath(); + x.moveTo(cx - s, cy); x.quadraticCurveTo(cx, cy, cx, cy - s); x.quadraticCurveTo(cx, cy, cx + s, cy); + x.quadraticCurveTo(cx, cy, cx, cy + s); x.quadraticCurveTo(cx, cy, cx - s, cy); x.fill(); + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/engine/boss_kit.js b/environments/games/web/engine/boss_kit.js new file mode 100644 index 0000000000000000000000000000000000000000..e81d5227710704cee52e82e62b1531488621a072 --- /dev/null +++ b/environments/games/web/engine/boss_kit.js @@ -0,0 +1,47 @@ +// Shared helpers for boss modules of any game (load before the game's bosses/*.js). +// pick() = PlayMaker SendRandomEventV3: an event past its repeat cap is re-rolled, an event missed missMax times in a +// row is forced; with probability (1 - entropy) the choice is a fixed cycle instead (spec select.policy entropy_cycle). +(function (g) { + var BB = g.BB; + BB.bossKit = function (P, SPEC, ROLE) { + P.spec = SPEC; + P.role = function () { return ROLE[this.st] || 'idle'; }; + P.tele = function (c, base) { + var tm = SPEC.timing.telegraph, t = base * this.k[tm.knob]; + if (tm.jitter && this.k[tm.jitter] > 0) t += c.rng.uniform(-this.k[tm.jitter], this.k[tm.jitter]); + return Math.max(tm.min || 0, t); + }; + P.rec = function (base) { return base * this.k[SPEC.timing.recovery.knob]; }; + P.spd = function () { return this.k[SPEC.locomotion.knob]; }; + P.face = function (c) { var hx = c.body.x; if (hx > this.x + 1e-6) this.f = 1; else if (hx < this.x - 1e-6) this.f = -1; }; + P.go = function (c, st, timer, move) { + if (move !== undefined) this.move = move; + this.st = st; this.timer = timer == null ? 0 : timer; this.stT = 0; + if (ROLE[st] === 'telegraph' && SPEC.announce && this.move) { this.stamp = (this.stamp || 0) + 1; this.lastActive = null; c.emit(SPEC.announce.telegraph.replace('{move}', this.move)); } + else if (ROLE[st] === 'active' && SPEC.announce && this.move && this.lastActive !== this.move + this.stamp) { + this.lastActive = this.move + this.stamp; c.emit(SPEC.announce.active.replace('{move}', this.move)); + } + }; + P.pick = function (c, key, evs, w, maxRep, missMax) { + var tr = this.track || (this.track = {}), i, n = evs.length, ev = null; + evs.forEach(function (e) { if (!tr[key + e]) tr[key + e] = { ct: 0, ms: 0 }; }); + if (c.rng.random() < this.k[SPEC.select.knob]) { + if (missMax) for (i = 0; i < n && ev === null; i++) if (tr[key + evs[i]].ms >= missMax[i]) ev = evs[i]; + for (var guard = 0; ev === null && guard < 64; guard++) { + var j = c.rng.pick(w); + if (w[j] > 0 && (!maxRep || tr[key + evs[j]].ct < maxRep[j])) ev = evs[j]; + } + if (ev === null) ev = evs[0]; + } else { + var cy = this.cycle || (this.cycle = {}), live = evs.filter(function (e, i2) { return w[i2] > 0; }); + cy[key] = (cy[key] || 0) + 1; ev = live[(cy[key] - 1) % live.length]; + } + evs.forEach(function (e) { var t = tr[key + e]; if (e === ev) { t.ct++; t.ms = 0; } else { t.ct = 0; t.ms++; } }); + return ev; + }; + P.flash = function (dt) { if (this.hitFlash > 0) this.hitFlash = Math.max(0, this.hitFlash - dt); }; + }; + BB.clamp = function (v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; }; + // per-tick exponential factor: "multiply by f every `step` seconds" + BB.perTick = function (f, step) { return Math.pow(f, BB.DT / step); }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/engine/bridge.js b/environments/games/web/engine/bridge.js new file mode 100644 index 0000000000000000000000000000000000000000..5d5a5c1345e367bd7530c0bb9a4eb6ad605a2084 --- /dev/null +++ b/environments/games/web/engine/bridge.js @@ -0,0 +1,67 @@ +// JSON command handler behind the Python gymnasium binding (prototype/bossbench/webenv.py). +// The same function serves two transports: tools/gym_server.js (Node, stdin/stdout JSON lines, symbolic only) +// and a headless browser page (Playwright) where BB.Renderer exists and 'rgb' frames come back as base64 RGB. +// Time modes are handled on the Python side: the env here always runs virtual_rt and is told how many +// no-op packets to run first (latency = lag * 0.2 s), so every engine shares one lag rule. +(function (g) { + var BB = g.BB, env = null, R = null, rgb = false; + + function frame() { + var W = BB.VIEW.W, H = BB.VIEW.H; + R.draw(env.case, env.case.t / BB.FPS, ''); + var px = R.ctx.getImageData(0, 0, W, H).data, n = W * H, out = new Uint8Array(n * 3); + for (var i = 0, j = 0; i < n * 4; i += 4) { out[j++] = px[i]; out[j++] = px[i + 1]; out[j++] = px[i + 2]; } + var s = '', CH = 0x8000; + for (var k = 0; k < out.length; k += CH) s += String.fromCharCode.apply(null, out.subarray(k, k + CH)); + return { b64: g.btoa(s), shape: [H, W, 3] }; + } + function pack(r) { + var c = env.case; + r.info.player_max_hp = c.body.max_hp; + var res = { state: r.obs, reward: r.reward, terminated: r.terminated, truncated: r.truncated, info: r.info, + verifier: c.verifier() }; + if (rgb) res.frame = frame(); + return res; + } + + BB.bridge = function (m) { + switch (m.cmd) { + case 'cases': + return { cases: Object.keys(BB.CASES).sort().map(function (id) { return { id: id, title: BB.CASES[id].title }; }) }; + case 'make': + env = BB.make(m.id, { obs_mode: 'symbolic', time_mode: 'virtual_rt' }); + rgb = !!m.rgb; + if (rgb && !BB.Renderer) throw new Error('rgb needs the browser renderer (engine/renderer.js); Node has no canvas'); + return { fps: BB.FPS, max_seconds: BB.MAX_SECONDS, packet_seconds: BB.PACKET_SECONDS, manual: env.case.manual() }; + case 'reset': + if (rgb) R = new BB.Renderer(g.document.createElement('canvas')); // fresh juice/art state per episode + var options = Object.assign({}, m.options || {}); + if (m.difficulty != null) options.difficulty = m.difficulty; // legacy top-level value takes precedence + var r = env.reset(m.seed, options); + return pack({ obs: r.obs, reward: 0, terminated: false, truncated: false, info: r.info }); + case 'step': + return pack(env.step(m.packet, (m.lag || 0) * BB.PACKET_SECONDS)); + case 'render': + return { frame: frame() }; + case 'hash': + return { hash: BB.hashState(env.case) }; + case 'band': // optional: the game's own name for d's segment + return { band: (BB.GAME && typeof BB.GAME.difficultyBand === 'function') + ? (BB.GAME.difficultyBand(m.d) || null) : null }; + case 'parse': // packet parity tests against the Python parser + var p = BB.parsePacket(m.text); + return { packet: p && { mouse: p.mouse, subs: p.subs.map(function (h) { return Object.keys(h).sort(); }) } }; + case 'scripted': // trusted reference controller (bossbench/scripted.py) + return { packet: BB.scriptedPacket(env.case) }; + case 'meta': + return { game: BB.GAME && BB.GAME.id || null, rules: BB.GAME && BB.GAME.rules || null, + scripted: !!(BB.GAME && typeof BB.GAME.scripted === 'function'), + tiers: BB.GAME && BB.GAME.tiers || null }; + default: + throw new Error('unknown cmd ' + m.cmd); + } + }; + // Trusted harness access (video capture, scripted play); never exposed to a policy. + BB.bridgeEnv = function () { return env; }; + +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/engine/case.js b/environments/games/web/engine/case.js new file mode 100644 index 0000000000000000000000000000000000000000..7bd7434c7fc75108bafbc254b9f29f597cffd0dd --- /dev/null +++ b/environments/games/web/engine/case.js @@ -0,0 +1,244 @@ +// Case = Arena + Body + Boss stepped at 60 Hz, and the Gym-style env of proposal 4.4 on top of it. +// No DOM here: the same file runs in the browser and in Node. +// Game-agnostic: a game registers BB.CASES[id] = {title, Body, Boss} and provides BB.ARENA {W, H}. +// Body contract: id, keys {action: 'K1|K2'}, manual [..], NAIL (damage per hit), reset, update(c, input), box, +// hurtBox, centre, slashBox() -> {pts, tink, dir} | null, slashHits {}, slashFacing, onSlashContact(c, kind), +// hurt(c, dmg, fromX) -> bool, hp, max_hp, state(). +// Boss contract: spec (BB.SPECS), reset, update(c), st, x, hp, max_hp, dmg, bodyBox | hitTargets, tinkBox (opt.), +// onNailHit(c, dmg, dir, facing, partId) -> contact kind, hazards() -> [{kind, box | seg + r | circle, dmg?}], state(). +(function (g) { + var BB = g.BB; + var KEYS = ['W', 'A', 'S', 'D', 'SPACE', 'SHIFT', 'J', 'K', 'L', 'Q', 'E', 'R', 'LMB', 'RMB']; + var CANON = { SPACE: 'Space', SHIFT: 'Shift' }; + + // ---------------- Case ---------------- + function Case(id) { + var def = BB.CASES[id]; + if (!def) throw new Error('unknown case ' + id); + this.id = id; this.def = def; + this.arena = def.bounds || BB.ARENA; + this.body = new def.Body(); this.boss = new def.Boss(); + } + Case.prototype.reset = function (seed, d, options) { + this.seed = seed >>> 0; this.d = Math.min(1, Math.max(0, +d)); + this.rng = new BB.RNG(this.seed); this.t = 0; this.events = []; this.trauma = 0; + this.options = options || {}; + this.body.reset(this); this.boss.reset(this); + this.result = null; + }; + Case.prototype.emit = function (name, x, y) { // x, y: optional world position for presentation cues + var e = { t: this.t, name: name }; if (x != null) { e.x = x; e.y = y; } this.events.push(e); + }; + Case.prototype.shake = function (a) { this.events.push({ t: this.t, name: 'shake', a: a }); }; // render-only cue + // keys: a Set-like object {Space:true, D:true, ...} held during this tick + Case.prototype.input = function (keys) { + var m = this.body.keys, out = {}; + Object.keys(m).forEach(function (act) { + out[act] = m[act].split('|').some(function (k) { return !!keys[k]; }); + }); + return out; + }; + Case.prototype.tick = function (keys, mouse) { + if (this.result) return; + if (mouse && typeof this.body.mouse === 'function') this.body.mouse(this, mouse); + this.body.update(this, this.input(keys || {})); + this.boss.update(this); + this.interact(); + this.t++; + this.result = this.outcome(); + }; + Case.prototype.interact = function () { + if (typeof this.body.resolveInteractions === 'function') return this.body.resolveInteractions(this); + var body = this.body, boss = this.boss, sb = body.slashBox(); + if (sb && boss.st !== 'dead') { + // a boss may expose several hittable parts (hitTargets: [{id, box}]); default = one body box + var tg = boss.hitTargets ? boss.hitTargets() : [{ id: 'boss', box: boss.bodyBox() }]; + var tb = boss.tinkBox ? boss.tinkBox() : null, landed = false; + for (var t = 0; t < tg.length; t++) { + var tid = tg[t].id; + if (!tg[t].box || body.slashHits[tid] || !BB.polyBox(sb.pts, tg[t].box)) continue; + body.slashHits[tid] = true; landed = true; + var kind = boss.onNailHit(this, body.NAIL, sb.dir, body.slashFacing, tid); + if (kind) body.onSlashContact(this, kind); + if (!body.multiTargetSlash) break; + } + if (!landed && !body.slashHits.needle && tb && BB.polyBox(sb.tink, tb)) { + body.slashHits.needle = true; this.emit('tink'); + body.onSlashContact(this, 'tink'); + } + } + if (body.hp <= 0 || boss.st === 'dead') return; + var hb = body.hurtBox(), hz = boss.hazards(); + for (var i = 0; i < hz.length; i++) { + var h = hz[i], hit = false; + if (h.box) hit = BB.overlap(h.box, hb); + else if (h.seg) hit = BB.segBox(h.seg[0], h.seg[1], h.seg[2], h.seg[3], h.r, hb); + else if (h.circle) hit = BB.circleBox(h.circle[0], h.circle[1], h.circle[2], hb); + if (hit && body.hurt(this, h.dmg || boss.dmg, h.fromX != null ? h.fromX : boss.x, h)) { this.events.push({ t: this.t, name: 'hurt_by', by: h.kind }); this.shake(0.6); break; } + } + }; + Case.prototype.outcome = function () { + // A game can express its own victory conditions (e.g. a timed duel) without falsifying HP. + if (typeof this.def.outcome === 'function') { + var custom = this.def.outcome(this); + // undefined delegates to the default; null keeps this game running, subject to the shared cap. + if (custom !== undefined) return custom == null && this.t >= BB.MAX_SECONDS * BB.FPS ? 'timeout' : custom; + } + if (this.boss.hp <= 0) return 'win'; + if (this.body.hp <= 0) return 'loss'; + if (this.boss.despawned) return 'timeout'; + if (this.t >= BB.MAX_SECONDS * BB.FPS) return 'timeout'; + return null; + }; + Case.prototype.state = function () { + return { t: BB.r4(this.t / BB.FPS), d: this.d, arena: { w: BB.r4(this.arena.W), h: this.arena.H }, + body: this.body.state(), boss: this.boss.state() }; + }; + Case.prototype.verifier = function () { // = prototype/bossbench/core.py verifier + var boss = this.boss, frac = 1 - boss.hp / boss.max_hp, win = this.result === 'win'; + return { reward: win ? 1 : BB.r4(-1 + frac), win: win, outcome: this.result, boss_damage: BB.r4(frac), + seconds: BB.r4(this.t / BB.FPS), d: this.d, player_hp: this.body.hp }; + }; + // proposal 4.4: control manual + boss skill table, as optional prompt context + Case.prototype.manual = function () { + var spec = this.boss.spec; + return { + controls: this.body.manual.slice(), + skills: spec.moves.map(function (m) { return { move: m.name, cue: m.cue, punish: m.punish || null, damage: m.damage }; }) + }; + }; + BB.Case = Case; + + // ---------------- packets ---------------- + // "<|action_start|> dx dy dz ; K1 ; ... ; K6 <|action_end|>", K = 0-4 keys joined by ',' + BB.parsePacket = function (text) { + var m = /^\s*<\|action_start\|>([\s\S]*)<\|action_end\|>\s*$/.exec(String(text == null ? '' : text)); + if (!m) return null; + var parts = m[1].split(';'); + if (parts.length !== 1 + BB.SUBSTEPS) return null; + var mouse = parts[0].trim().split(/\s+/); + if (mouse.length !== 3 || !mouse.every(function (v) { return /^-?\d+$/.test(v); })) return null; + var dx = +mouse[0], dy = +mouse[1], dz = +mouse[2]; + if (Math.abs(dx) > 1000 || Math.abs(dy) > 1000 || Math.abs(dz) > 5) return null; + var subs = []; + for (var i = 1; i < parts.length; i++) { + var s = parts[i].trim(), held = {}; + if (s) { + var ks = s.split(','); + if (ks.length > 4) return null; + for (var j = 0; j < ks.length; j++) { + var k = ks[j].trim().toUpperCase(); + if (KEYS.indexOf(k) < 0 || held[CANON[k] || k]) return null; + held[CANON[k] || k] = true; + } + } + subs.push(held); + } + return { mouse: [dx, dy, dz], subs: subs }; + }; + BB.formatPacket = function (subs, mouse) { + mouse = mouse || [0, 0, 0]; + return '<|action_start|> ' + mouse.join(' ') + ' ; ' + + subs.map(function (h) { return Object.keys(h).filter(function (k) { return h[k]; }).join(','); }).join(' ; ') + + ' <|action_end|>'; + }; + BB.NOOP = BB.formatPacket([{}, {}, {}, {}, {}, {}]); + // Standard scripted-controller hook for every BB.Case game: BB.GAME.scripted(case) returns a text packet, + // {subs|holds: 6 key sets, mouse: [dx, dy, dz]}, or 6 key sets. It may read privileged state but must + // not change the simulation; the result is normalized and validated like any policy packet. + BB.scriptedPacket = function (c) { + if (!BB.GAME || typeof BB.GAME.scripted !== 'function') throw new Error('this game has no BB.GAME.scripted controller'); + var before = BB.hashState(c), out = BB.GAME.scripted(c); + if (BB.hashState(c) !== before) throw new Error('scripted controller changed the simulation state'); + var text = out; + if (typeof out !== 'string') { + var subs = Array.isArray(out) ? out : (out.subs || out.holds), mouse = (!Array.isArray(out) && out.mouse) || [0, 0, 0]; + if (!Array.isArray(subs) || subs.length !== BB.SUBSTEPS) throw new Error('scripted controller must return 6 key sets'); + text = BB.formatPacket(subs.map(function (h) { + if (Array.isArray(h)) { var o = {}; h.forEach(function (k) { o[k] = true; }); return o; } + return h || {}; + }), mouse.map(function (v) { return Math.round(v); })); + } + if (!BB.parsePacket(text)) throw new Error('scripted controller returned an illegal packet: ' + text); + return text; + }; + BB.PACKET_SECONDS = BB.SUBSTEPS * BB.TICKS_PER_SUB / BB.FPS; // 0.2 + + // ---------------- Env (Gymnasium semantics) ---------------- + // opts: obs_mode 'rgb'|'symbolic', time_mode 'paused'|'virtual_rt'|'wallclock_rt', latency (s, virtual_rt), + // renderer: function(case) -> frame (browser); now: clock in ms (wallclock_rt) + function Env(id, opts) { + opts = opts || {}; + this.id = id; this.case = new Case(id); + this.obs_mode = opts.obs_mode || 'rgb'; + this.time_mode = opts.time_mode || 'paused'; + if (['paused', 'virtual_rt', 'wallclock_rt'].indexOf(this.time_mode) < 0) throw new Error('bad time_mode'); + this.latency = +opts.latency || 0; + this.renderer = opts.renderer || null; + this.now = opts.now || function () { return Date.now(); }; + this.with_text = !!opts.with_text; + } + Env.prototype.reset = function (seed, options) { + options = options || {}; + var d = options.difficulty != null ? options.difficulty : 0.5; + if (options.latency != null) this.latency = +options.latency; + this.case.reset(seed || 0, d, options); + this.steps = 0; this.format_errors = 0; this.trace = []; this.lastReturn = this.now(); + var info = this.info(true, 0, []); + info.manual = this.case.manual(); + return { obs: this.observe(), info: info }; + }; + Env.prototype.observe = function () { + if (this.obs_mode === 'symbolic') return this.case.state(); + return this.renderer ? this.renderer(this.case) : null; + }; + Env.prototype.info = function (ok, frames, events) { + var c = this.case; + return { outcome: c.result, player_hp: c.body.hp, boss_hp: c.boss.hp, boss_max_hp: c.boss.max_hp, + format_ok: ok, frames: frames, t: BB.r4(c.t / BB.FPS), events: events, steps: this.steps, + format_errors: this.format_errors }; + }; + Env.prototype.runPacket = function (p) { // 6 sub-steps x 2 ticks, keys held per sub-step + var c = this.case, n = 0; + for (var s = 0; s < BB.SUBSTEPS; s++) for (var k = 0; k < BB.TICKS_PER_SUB; k++) { + if (c.result) return n; + c.tick(p ? p.subs[s] : null, p ? p.mouse.map(function (v) { return v / (BB.SUBSTEPS * BB.TICKS_PER_SUB); }) : null); n++; + } + return n; + }; + // latency (optional, virtual_rt): this step's think time in seconds, overrides env.latency + Env.prototype.step = function (action, latency) { + var c = this.case, ev0 = c.events.length, frames = 0, lag = 0; + if (c.result) throw new Error('episode is over; call reset()'); + if (this.time_mode === 'virtual_rt') lag = Math.ceil((latency != null ? latency : this.latency) / BB.PACKET_SECONDS - 1e-9); + else if (this.time_mode === 'wallclock_rt') lag = Math.floor((this.now() - this.lastReturn) / 1000 / BB.PACKET_SECONDS); + for (var i = 0; i < lag && !c.result; i++) frames += this.runPacket(null); // the world did not wait + var p = BB.parsePacket(action), ok = !!p; + if (!ok) this.format_errors++; + this.trace.push(ok ? action : BB.NOOP); + frames += this.runPacket(p); + this.steps++; + var term = c.result === 'win' || c.result === 'loss', trunc = c.result === 'timeout'; + var reward = 0; + if (term || trunc) reward = c.verifier().reward; + var info = this.info(ok, frames, c.events.slice(ev0).filter(function (e) { return e.name !== 'shake'; }).map(function (e) { return e.name; })); + info.noop_packets = lag; + if (term || trunc) info.verifier = c.verifier(); + var obs = this.observe(); + this.lastReturn = this.now(); + return { obs: obs, reward: reward, terminated: term, truncated: trunc, info: info }; + }; + Env.prototype.verifier = function () { return this.case.verifier(); }; + BB.Env = Env; + + // FNV-1a over the symbolic state, for determinism checks + BB.hashState = function (c) { + var s = JSON.stringify(c.state()), h = 0x811c9dc5; + for (var i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193); } + return (h >>> 0).toString(16); + }; + + // ---------------- registry ---------------- + BB.CASES = BB.CASES || {}; + BB.make = function (id, opts) { return new Env(id, opts); }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/engine/core.js b/environments/games/web/engine/core.js new file mode 100644 index 0000000000000000000000000000000000000000..8949ae5a073035ca742c11571bae03667b97a4f1 --- /dev/null +++ b/environments/games/web/engine/core.js @@ -0,0 +1,90 @@ +// BossBench web core: seeded RNG, difficulty knobs, geometry helpers. No DOM - runs in Node too. +(function (g) { + var BB = g.BB = g.BB || {}; + + BB.FPS = 60; // fixed physics tick (proposal 4.4) + BB.DT = 1 / 60; + BB.SUBSTEPS = 6; // one 200 ms action packet = 6 sub-steps of 33 ms + BB.TICKS_PER_SUB = 2; // = 2 ticks each + BB.RES = [854, 480]; // every frame is 480p + BB.MAX_SECONDS = 300; // 5 min episode cap -> truncated + + // sfc32: small, fast, fully deterministic (integer ops only). + function RNG(seed) { + seed = (seed >>> 0) || 0; + this.a = 0x9e3779b9; this.b = 0x243f6a88; this.c = 0xb7e15162; this.d = seed ^ 0xdeadbeef; + for (var i = 0; i < 15; i++) this.u32(); + } + RNG.prototype.u32 = function () { + var a = this.a, b = this.b, c = this.c, d = this.d; + var t = (a + b | 0) + d | 0; + d = d + 1 | 0; a = b ^ (b >>> 9); b = c + (c << 3) | 0; c = (c << 21) | (c >>> 11); c = c + t | 0; + this.a = a; this.b = b; this.c = c; this.d = d; + return t >>> 0; + }; + RNG.prototype.random = function () { return this.u32() / 4294967296; }; + RNG.prototype.uniform = function (lo, hi) { return lo + (hi - lo) * this.random(); }; + RNG.prototype.int = function (n) { return Math.floor(this.random() * n); }; + RNG.prototype.chance = function (p) { return this.random() < p; }; + RNG.prototype.pick = function (weights) { // index by weight + var s = 0, i; for (i = 0; i < weights.length; i++) s += weights[i]; + var r = this.random() * s; + for (i = 0; i < weights.length; i++) { r -= weights[i]; if (r < 0) return i; } + return weights.length - 1; + }; + BB.RNG = RNG; + + // d in [0,1] -> named parameters; a row is (easy, hard) or (easy, normal, hard) (= core.Knobs in Python) + BB.knobs = function (table, d) { + d = Math.min(1, Math.max(0, +d || 0)); + var out = {}; + Object.keys(table).forEach(function (k) { + var row = table[k], n = row.length - 1, x = d * n, i = Math.min(Math.floor(x), n - 1), f = x - i; + out[k] = row[i] + (row[i + 1] - row[i]) * f; + }); + return out; + }; + + // axis-aligned boxes are {x, y, w, h} with (x, y) = centre + BB.overlap = function (a, b) { + return Math.abs(a.x - b.x) * 2 < a.w + b.w && Math.abs(a.y - b.y) * 2 < a.h + b.h; + }; + BB.circleBox = function (cx, cy, r, b) { + var dx = Math.max(Math.abs(cx - b.x) - b.w / 2, 0), dy = Math.max(Math.abs(cy - b.y) - b.h / 2, 0); + return dx * dx + dy * dy < r * r; + }; + BB.segBox = function (x0, y0, x1, y1, r, b) { // capsule (segment + radius) vs box, sampled + var e = { x: b.x, y: b.y, w: b.w + 2 * r, h: b.h + 2 * r }; + for (var i = 0; i <= 8; i++) { + var t = i / 8, px = x0 + (x1 - x0) * t, py = y0 + (y1 - y0) * t; + if (Math.abs(px - e.x) * 2 < e.w && Math.abs(py - e.y) * 2 < e.h) return true; + } + return false; + }; + BB.inPoly = function (px, py, pts) { // even-odd rule + var inside = false; + for (var i = 0, j = pts.length - 1; i < pts.length; j = i++) { + var xi = pts[i][0], yi = pts[i][1], xj = pts[j][0], yj = pts[j][1]; + if ((yi > py) !== (yj > py) && px < (xj - xi) * (py - yi) / (yj - yi) + xi) inside = !inside; + } + return inside; + }; + // polygon [[x,y],...] vs box: a vertex inside the box, the box centre inside the polygon, or an edge crossing the box + BB.polyBox = function (pts, b) { + var l = b.x - b.w / 2, r = b.x + b.w / 2, lo = b.y - b.h / 2, hi = b.y + b.h / 2, i, j; + for (i = 0; i < pts.length; i++) if (pts[i][0] > l && pts[i][0] < r && pts[i][1] > lo && pts[i][1] < hi) return true; + if (BB.inPoly(b.x, b.y, pts)) return true; + for (i = 0, j = pts.length - 1; i < pts.length; j = i++) { // Liang-Barsky clip of each edge against the box + var x0 = pts[j][0], y0 = pts[j][1], dx = pts[i][0] - x0, dy = pts[i][1] - y0, t0 = 0, t1 = 1, ok = true; + [[-dx, x0 - l], [dx, r - x0], [-dy, y0 - lo], [dy, hi - y0]].forEach(function (pq) { + if (!ok) return; + if (pq[0] === 0) { if (pq[1] < 0) ok = false; return; } + var t = pq[1] / pq[0]; + if (pq[0] < 0) { if (t > t1) ok = false; else if (t > t0) t0 = t; } else { if (t < t0) ok = false; else if (t < t1) t1 = t; } + }); + if (ok && t0 < t1) return true; + } + return false; + }; + BB.r4 = function (v) { return Math.round(v * 1e4) / 1e4; }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/engine/input.js b/environments/games/web/engine/input.js new file mode 100644 index 0000000000000000000000000000000000000000..99f0d014d7f217bbe104a9999afaa3be59a5dc16 --- /dev/null +++ b/environments/games/web/engine/input.js @@ -0,0 +1,41 @@ +// Keyboard / mouse -> held-key set in the packet vocabulary (W A S D Space Shift J K L Q E R LMB RMB). +// Human play samples it every 33 ms sub-step, so a human session can be recorded as action packets and replayed. +(function (g) { + var BB = g.BB; + var MAP = { KeyW: 'W', KeyA: 'A', KeyS: 'S', KeyD: 'D', Space: 'Space', ShiftLeft: 'Shift', ShiftRight: 'Shift', + KeyJ: 'J', KeyK: 'K', KeyL: 'L', KeyQ: 'Q', KeyE: 'E', KeyR: 'R', + ArrowUp: 'W', ArrowLeft: 'A', ArrowDown: 'S', ArrowRight: 'D', KeyZ: 'Space', KeyX: 'J', KeyC: 'Shift', KeyV: 'K' }; + function Input(target) { + var held = this.held = {}, self = this; + this.taps = {}; // pressed-and-released within one sub-step still count once + this.pointer = null; + target.addEventListener('keydown', function (e) { + var k = MAP[e.code]; if (!k) return; + if (!self.enabled) return; + e.preventDefault(); + if (!held[k]) self.taps[k] = true; held[k] = true; + }); + target.addEventListener('keyup', function (e) { var k = MAP[e.code]; if (k) held[k] = false; }); + target.addEventListener('blur', function () { for (var k in held) held[k] = false; }); + this.enabled = true; + } + Input.prototype.bindMouse = function (el) { + var held = this.held, self = this; + el.addEventListener('mousedown', function (e) { if (!self.enabled) return; var k = e.button === 0 ? 'LMB' : e.button === 2 ? 'RMB' : null; if (k) { if (!held[k]) self.taps[k] = true; held[k] = true; } }); + g.addEventListener('mouseup', function (e) { var k = e.button === 0 ? 'LMB' : e.button === 2 ? 'RMB' : null; if (k) held[k] = false; }); + el.addEventListener('mousemove', function (e) { + var rect = el.getBoundingClientRect(); + if (rect.width && rect.height) self.pointer = [(e.clientX - rect.left) * el.width / rect.width, (e.clientY - rect.top) * el.height / rect.height]; + }); + el.addEventListener('contextmenu', function (e) { e.preventDefault(); }); + }; + Input.prototype.clear = function () { for (var k in this.held) this.held[k] = false; this.taps = {}; }; + // keys held during the next sub-step (max 4, as in the packet format) + Input.prototype.sample = function () { + var out = {}, n = 0, order = ['A', 'D', 'W', 'S', 'Space', 'J', 'LMB', 'Shift', 'K', 'L', 'Q', 'E', 'R', 'RMB']; + for (var i = 0; i < order.length && n < 4; i++) { var k = order[i]; if (this.held[k] || this.taps[k]) { out[k] = true; n++; } } + this.taps = {}; + return out; + }; + BB.Input = Input; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/engine/juice.js b/environments/games/web/engine/juice.js new file mode 100644 index 0000000000000000000000000000000000000000..ba7c329ce70fe201f5b43c36339487ba95133f15 --- /dev/null +++ b/environments/games/web/engine/juice.js @@ -0,0 +1,106 @@ +// Juice: screen shake, flashes, particles, hit-stop requests. Presentation only - it reads case events and +// never writes simulation state. Hit-stop is honoured by the *human play loop* as a wall-clock pause between +// ticks, so the tick sequence (and every replay / agent rollout) is identical with or without it. +(function (g) { + var BB = g.BB; + function Juice() { this.reset(); } + Juice.prototype.reset = function () { + this.seen = 0; this.trauma = 0; this.flash = 0; this.redFlash = 0; this.parts = []; this.flares = []; this.hitstop = 0; + this.rng = new BB.RNG(12345); this.lastT = null; this.caseRef = null; + }; + Juice.prototype.burst = function (x, y, n, col, spd, life, grav) { + for (var i = 0; i < n; i++) { + var a = this.rng.uniform(0, Math.PI * 2), v = this.rng.uniform(0.3, 1) * spd; + this.parts.push({ x: x, y: y, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life: life * this.rng.uniform(0.6, 1), max: life, col: col, g: grav || 0, r: this.rng.uniform(1.5, 3.5), streak: spd >= 200 }); + } + }; + Juice.prototype.flare = function (x, y, size, life, rgb) { // impact star: two crossed tapered rays + glow + this.flares.push({ x: x, y: y, s: size, life: life, max: life, a: this.rng.uniform(-0.6, 0.6), rgb: rgb || '255,250,235' }); + }; + Juice.prototype.dust = function (x, y, n, col, spd) { // soft rising puffs, mostly sideways + for (var i = 0; i < n; i++) { + var dir = i % 2 ? 1 : -1, v = this.rng.uniform(0.3, 1) * spd; + this.parts.push({ x: x + dir * this.rng.uniform(0, 8), y: y, vx: dir * v, vy: -this.rng.uniform(10, 40), life: this.rng.uniform(0.35, 0.6), max: 0.6, + col: col, g: -20, r: this.rng.uniform(3, 6), puff: true }); + } + }; + Juice.prototype.consume = function (c, R) { + if (this.caseRef !== c || c.events.length < this.seen) { // new / reset case: only react to the last 0.2 s + this.caseRef = c; this.parts = []; this.flares = []; this.seen = c.events.length; + while (this.seen > 0 && c.events[this.seen - 1].t > c.t - 12) this.seen--; + } + var b = c.body, w = c.boss; + for (; this.seen < c.events.length; this.seen++) { + var e = c.events[this.seen], n = e.name; + if (n === 'shake') this.trauma = Math.min(1, this.trauma + e.a); + else if (n === 'boss_hit') { + var sb = b.centre(), hx = R.sx(e.x != null ? e.x : (sb.x + w.x) / 2), hy = R.sy(e.y != null ? e.y : sb.y); + this.burst(hx, hy, 10, '#f4ead2', 260, 0.35, 300); this.flare(hx, hy, 38, 0.16); this.hitstop = Math.max(this.hitstop, 0.05); this.trauma = Math.min(1, this.trauma + 0.12); + } else if (n === 'player_hit') { + this.burst(R.sx(b.x), R.sy(b.y + 0.7), 18, '#ffffff', 340, 0.5, 200); this.flare(R.sx(b.x), R.sy(b.y + 0.7), 60, 0.22, '255,235,235'); this.redFlash = 1; this.hitstop = Math.max(this.hitstop, b.HITSTOP || 0); + } else if (n === 'tink') { this.burst(R.sx(e.x != null ? e.x : w.needle ? w.needle.x : b.x), R.sy(e.y != null ? e.y : w.needle ? w.needle.y : b.y), 8, '#fff2a0', 300, 0.25, 0); this.hitstop = Math.max(this.hitstop, 0.04); } + else if (n === 'pogo') this.burst(R.sx(b.x), R.sy(b.y - 0.2), 6, '#d9f6ff', 180, 0.25, 0); + else if (n === 'land' || n === 'boss_land' || n === 'boss_land_hard') { + var lx = n === 'land' ? b.x : e.x != null ? e.x : w.x; + this.dust(R.sx(lx), R.sy(0) - 3, n === 'boss_land_hard' ? 12 : n === 'boss_land' ? 6 : 4, 'rgba(190,200,195,0.5)', n === 'boss_land_hard' ? 140 : 70); + } else if (n === 'dash') this.dust(R.sx(b.x), R.sy(b.y + 0.3), 4, 'rgba(200,220,255,0.45)', 60); + else if (n === 'heal') { this.burst(R.sx(b.x), R.sy(b.y + 0.8), 16, '#bfefff', 160, 0.6, -80); this.flash = 0.4; } + else if (n === 'boss_stun') { this.burst(R.sx(e.x != null ? e.x : w.x), R.sy(e.y != null ? e.y : w.y), 20, '#ffe9a0', 280, 0.6, 250); this.flash = 0.5; this.hitstop = 0.12; this.flare(R.sx(e.x != null ? e.x : w.x), R.sy(e.y != null ? e.y : w.y + 1), 90, 0.3); } + else if (n === 'boss_dead') { this.burst(R.sx(e.x != null ? e.x : w.x), R.sy(e.y != null ? e.y : w.y), 50, '#f4ead2', 420, 1.2, 150); this.flash = 1; this.hitstop = 0.4; this.flare(R.sx(e.x != null ? e.x : w.x), R.sy(e.y != null ? e.y : w.y + 1), 160, 0.6); } + else if (n === 'boss_parry') { this.burst(R.sx(e.x != null ? e.x : w.x + (w.f || 0) * 0.6), R.sy(e.y != null ? e.y : w.y), 12, '#fff2a0', 300, 0.3, 0); this.flash = 0.3; this.flare(R.sx(e.x != null ? e.x : w.x + (w.f || 0) * 0.6), R.sy(e.y != null ? e.y : w.y), 50, 0.18, '255,240,180'); } + else if (n === 'boss_escalate') this.flash = 0.25; + } + }; + Juice.prototype.offset = function (t) { + var dt = this.lastT == null ? 0 : Math.max(0, Math.min(0.1, t - this.lastT)); this.lastT = t; + this.trauma = Math.max(0, this.trauma - dt * 1.6); this.flash = Math.max(0, this.flash - dt * 3); this.redFlash = Math.max(0, this.redFlash - dt * 3); + for (var i = this.parts.length - 1; i >= 0; i--) { + var p = this.parts[i]; p.life -= dt; if (p.life <= 0) { this.parts.splice(i, 1); continue; } + p.vy += p.g * dt; p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.96; + } + for (i = this.flares.length - 1; i >= 0; i--) { this.flares[i].life -= dt; if (this.flares[i].life <= 0) this.flares.splice(i, 1); } + var s = this.trauma * this.trauma * 9; // trauma^2 shake + return [Math.sin(t * 91.3) * s, Math.cos(t * 73.7) * s]; + }; + Juice.prototype.drawParticles = function (x) { + x.save(); + for (var i = 0; i < this.parts.length; i++) { + var p = this.parts[i], k = Math.max(0, p.life / p.max); + if (p.puff) { // dust: grows and fades + x.globalCompositeOperation = 'source-over'; x.globalAlpha = k * 0.8; x.fillStyle = p.col; + x.beginPath(); x.arc(p.x, p.y, p.r * (2 - k), 0, Math.PI * 2); x.fill(); + } else if (p.streak) { // spark: additive streak along its velocity, thinning out + var sp = Math.sqrt(p.vx * p.vx + p.vy * p.vy) || 1, L = Math.min(22, 4 + sp * 0.045) * (0.4 + 0.6 * k); + x.globalCompositeOperation = 'lighter'; x.globalAlpha = k; x.strokeStyle = p.col; x.lineCap = 'round'; x.lineWidth = p.r * k + 0.6; + x.beginPath(); x.moveTo(p.x, p.y); x.lineTo(p.x - p.vx / sp * L, p.y - p.vy / sp * L); x.stroke(); + } else { + x.globalCompositeOperation = 'lighter'; x.globalAlpha = k; x.fillStyle = p.col; + x.beginPath(); x.arc(p.x, p.y, p.r * (0.5 + 0.5 * k), 0, Math.PI * 2); x.fill(); + } + } + x.globalCompositeOperation = 'lighter'; + for (i = 0; i < this.flares.length; i++) { + var f = this.flares[i], q = f.life / f.max, S = f.s * (0.6 + 0.4 * (1 - q)); + x.globalAlpha = 1; + var gr = x.createRadialGradient(f.x, f.y, 0, f.x, f.y, S * 0.6); + gr.addColorStop(0, 'rgba(' + f.rgb + ',' + (0.8 * q).toFixed(3) + ')'); gr.addColorStop(1, 'rgba(' + f.rgb + ',0)'); + x.fillStyle = gr; x.beginPath(); x.arc(f.x, f.y, S * 0.6, 0, Math.PI * 2); x.fill(); + x.fillStyle = 'rgba(' + f.rgb + ',' + q.toFixed(3) + ')'; + for (var r = 0; r < 2; r++) { + var a = f.a + r * Math.PI / 2, L2 = S * (r ? 0.55 : 1), wd = 2.5 + 3 * q; + x.save(); x.translate(f.x, f.y); x.rotate(a); + x.beginPath(); x.moveTo(-L2, 0); x.quadraticCurveTo(0, -wd, L2, 0); x.quadraticCurveTo(0, wd, -L2, 0); x.fill(); x.restore(); + } + } + x.restore(); + }; + // Wall-clock hit-stop is presentation only. A game whose player hits many times a second (e.g. a run-and-gun) + // can scale or disable it with BB.GAME.hitstop = false | 0..1; the tick sequence is identical either way. + Juice.prototype.takeHitstop = function () { + var h = this.hitstop, scale = BB.GAME && BB.GAME.hitstop; + this.hitstop = 0; + if (scale === false) return 0; + return typeof scale === 'number' ? h * scale : h; + }; + BB.Juice = Juice; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/engine/load.js b/environments/games/web/engine/load.js new file mode 100644 index 0000000000000000000000000000000000000000..2b2668528236a6bdf827fb73fc8493ee7c242ebc --- /dev/null +++ b/environments/games/web/engine/load.js @@ -0,0 +1,20 @@ +// Node loader for one game: runs every + diff --git a/environments/games/web/games/battlecity_remake/scripted.js b/environments/games/web/games/battlecity_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..ea19999b8270286b77b4dd0fd33f5a1258531eec --- /dev/null +++ b/environments/games/web/games/battlecity_remake/scripted.js @@ -0,0 +1,124 @@ +// The reference controller plans on copies. It compares a heuristic firing-lane packet and ten uniform packets, rolls each forward for 32 follow-up packets, and returns the best first packet. +(function(g){ + var BB=g.BB,BC=BB.BC,KEY=['W','A','S','D'],H=+(g.BC_H!=null?g.BC_H:32),GUARD=+(g.BC_GUARD!=null?g.BC_GUARD:.6); // dir 0 up,1 left,2 down,3 right + var PILLPATH=g.BC_PILLPATH!=null?+g.BC_PILLPATH:2; // pill pull: 0 straight line (r5), 1 always path length, 2 path length only around walls (r6) + var DETOUR=+(g.BC_DETOUR!=null?g.BC_DETOUR:24); // mode 2: px a wall must add to the straight line before the path length is used + var TANKPATH=g.BC_TANKPATH!=null?+g.BC_TANKPATH:2,GUARDPATH=g.BC_GUARDPATH!=null?+g.BC_GUARDPATH:2; // same 0 / 2 modes, hidden-tank and base pulls + var GDETOUR=+(g.BC_GDETOUR!=null?g.BC_GDETOUR:48); // base pull: detour (px) beyond the straight line before it counts + var ALIGN=g.BC_ALIGN!=null?!!+g.BC_ALIGN:true; // r6: shorten a move that ends in a turn so the ROM turn-snap lands on the node + var FORT={};BC.FORT.concat(BC.EAGLE_CELLS).forEach(function(p){FORT[BC.idx(p[0],p[1])]=1;}); + function copy(v){return v&&typeof v==='object'?JSON.parse(JSON.stringify(v)):v;} + function cloneCase(c){ + var n=new BB.Case(c.id);n.seed=c.seed;n.d=c.d;n.t=c.t;n.options=c.options;n.result=c.result;n.trauma=0;n.events=[]; + n.rng=new BB.RNG(0);n.rng.a=c.rng.a;n.rng.b=c.rng.b;n.rng.c=c.rng.c;n.rng.d=c.rng.d; + [['body',c.body,n.body],['boss',c.boss,n.boss]].forEach(function(q){Object.keys(q[1]).forEach(function(k){if(typeof q[1][k]!=='function')q[2][k]=copy(q[1][k]);});}); + return n; + } + function run(c,subs){for(var s=0;s<6&&!c.result;s++)for(var k=0;k<2&&!c.result;k++)c.tick(subs[s]);} + function pack(dir,fire,turnOnly){var s=[];for(var i=0;i<6;i++){var k={};if(dir>=0&&(!turnOnly||i===0))k[KEY[dir]]=true;if(fire&&(i%2===(turnOnly?1:0)))k.J=true;s.push(k);}return s;} + function solidFor(w,i,steel){var v=w.map[i];return v===2?!steel:v===6||(v===1&&w.bits[i]!==0);} + // walk a bullet lane from (x,y): returns {hit:'enemy'|'eagle'|'fort'|'wall'|'edge', bricks, e, d} + function lane(c,x,y,dir,steel){ + var w=c.boss,dx=BC.DX[dir],dy=BC.DY[dir],px=x+dx*8,py=y+dy*8,bricks=0,last=-1; + for(var n=0;n<60;n++,px+=dx*4,py+=dy*4){ + if(px<0||py<0||px>=208||py>=208)return {hit:'edge',bricks:bricks}; + for(var k=0;k<4;k++){var e=w.tanks[k];if(e&&(BC.active(e)||e.st==='spawn')&&Math.abs(e.x-px)<10&&Math.abs(e.y-py)<10)return {hit:'enemy',bricks:bricks,e:e,d:Math.abs(px-x)+Math.abs(py-y)};} + var i=BC.idx(px>>3,py>>3); + if(FORT[i]&&(w.map[i]===1||w.map[i]===2||w.map[i]===6)&&(w.map[i]!==1||w.bits[i]))return {hit:w.map[i]===6?'eagle':'fort',bricks:bricks}; + var v=w.map[i];if(v===2&&!steel)return {hit:'wall',bricks:bricks}; + if(v===1&&w.bits[i]&&i!==last){bricks++;last=i;}if(v===2&&steel&&i!==last){bricks++;last=i;} + if(bricks>6)return {hit:'wall',bricks:bricks}; + } + return {hit:'edge',bricks:bricks}; + } + function nodeFree(w,x,y){var cx=x>>3,cy=y>>3;for(var a=-1;a<=0;a++)for(var b=-1;b<=0;b++){var i=BC.idx(cx+a,cy+b),v=w.map[i];if(v===2||v===3||v===6||(v===1&&w.bits[i]))return false;}return true;} + // Use a BFS distance when obstacles make the route to the target substantially longer than the straight-line distance. + function bfs(w,src,key){var d={},q=[];src.forEach(function(p){var x=p[0],y=p[1],k=key(x,y);if(x<8||y<8||x>200||y>200||d[k]!=null||!nodeFree(w,x,y))return;d[k]=0;q.push([x,y]);}); + for(var h=0;h200||ny>200||d[nk]!=null||!nodeFree(w,nx,ny))continue;d[nk]=dd+1;q.push([nx,ny]);}} + return d;} + function pillField(w,key){var p=w.pill,s=[];for(var x=(p.x-11+7)&~7;x 108 px for 7 s (river_delta normal seed 3). Hold the first direction only until the + // coordinate is within 3 px of that node, then press the turn: the snap puts the tank exactly on the node. + function alignPack(c,b,sx,sy,d1,d2){ + if(d2<0||(d1&1)===(d2&1))return pack(d1,false); + var vert=(d1&1)===0,v=vert?b.y:b.x,snap=d1!==b.dir&&(d1^2)!==b.dir;if(snap)v=(v+4)&~7; + var node=(vert?sy:sx)+(vert?BC.DY[d1]:BC.DX[d1])*8,need=Math.max(0,Math.abs(node-v)-3); + var ticks=0,moved=0;while(moved=6)return pack(d1,false); + var out=[];for(var i=0;i<6;i++){var k={};k[KEY[i120)s+=30;if(e.y>160)s+=30;if(Math.abs(e.x-104)<12&&e.dir===2)s+=40;if(Math.abs(e.y-200)<12&&(e.dir===1||e.dir===3))s+=40;return s;} + function bulletDanger(c,x,y){var w=c.boss,r=0;for(var i=2;i<=5;i++){var p=w.bullets[i];if(!p||p.st!=='fly')continue; + var ax=x-p.x,ay=y-p.y,v=p.dir;if((v===0&&ay<0&&ay>-64&&Math.abs(ax)<12)||(v===2&&ay>0&&ay<64&&Math.abs(ax)<12)||(v===1&&ax<0&&ax>-64&&Math.abs(ay)<12)||(v===3&&ax>0&&ax<64&&Math.abs(ay)<12))r+=80;}return r;} + BC.heuristic=function(c){ + var b=c.body,w=c.boss,steel=b.stars>=3;if(b.st!=='active')return pack(-1,false); + // 1. shoot from here: facing lane first, then a quick turn + var best=null; + for(var d=0;d<4;d++){var L=lane(c,b.x,b.y,d,steel);if(L.hit!=='enemy')continue;var v=200-L.bricks*20-L.d/8+threat(c,L.e)+(d===b.dir?30:0);if(!best||v>best.v)best={v:v,d:d};} + // counter-fire an enemy shell coming down our lane + for(var i=2;i<=5;i++){var p=w.bullets[i];if(!p||p.st!=='fly')continue;var back=(p.dir+2)&3; + if(back===b.dir&&Math.abs((b.dir&1?p.y-b.y:p.x-b.x))<6){var L2=lane(c,b.x,b.y,b.dir,steel);if(L2.hit!=='eagle'&&L2.hit!=='fort')return pack(-1,true);}} + if(best&&best.v>60){if(best.d===b.dir)return pack(-1,true);return pack(best.d,true,true);} + // 2. BFS over 8 px nodes + var sx=(b.x+4)&~7,sy=(b.y+4)&~7,key=function(x,y){return (y>>3)*32+(x>>3);},dist={},first={},second={},q=[[sx,sy]],bestN=null; + dist[key(sx,sy)]=0;first[key(sx,sy)]=-1;second[key(sx,sy)]=-1; + var targets=w.tanks.filter(function(e){return e&&(BC.active(e)||e.st==='spawn');}); + // once the AI clock sends tanks at the eagle (DE72), hold near the base; with no lane anywhere, close in on a tank + var baseMode=(w.ai>>2)<((c.t>>6)&255),PF=PILLPATH&&w.pill&&!w.pill.flash?pillField(w,key):null,GF=GUARDPATH&&baseMode?guardField(w,key):null,TF=null; + for(var h=0;hval)val=v;}); + if(w.pill&&!w.pill.flash){var pd=PF?(PF[kk]!=null?PF[kk]*8:null):Math.abs(x-w.pill.x)+Math.abs(y-w.pill.y); + if(PILLPATH===2&&PF){var md0=Math.abs(x-w.pill.x)+Math.abs(y-w.pill.y);pd=pd!=null&&pd>md0+DETOUR?pd:md0;} + if(pd!=null){var pv=(w.pill.kind==='shovel'||w.pill.kind==='star'||w.pill.kind==='grenade'||w.pill.kind==='helmet'||w.pill.kind==='timer'||w.pill.kind==='life'?140:60)-pd*1.2;if(pv>val)val=pv;}} + if(!targets.length&&!w.pill)val=20-(Math.abs(x-104)+Math.abs(y-168))/16; + if(val<-1e8&&targets.length){var md=1e9;targets.forEach(function(e){md=Math.min(md,Math.abs(x-e.x)+Math.abs(y-e.y));}); + if(TANKPATH){if(!TF)TF=bfs(w,targets.map(function(e){return [(e.x+4)&~7,(e.y+4)&~7];}),key);if(TF[kk]!=null&&TF[kk]*8>md+DETOUR)md=TF[kk]*8;} + val=-300-md;} + if(baseMode){var gd=Math.abs(x-104)+Math.abs(y-176); + if(GF){var gp=GF[kk];if(gp==null)gd+=400;else{var gx=gp*8-rectDist(x,y);if(gx>GDETOUR)gd+=gx;}} + val-=gd*GUARD;} + val-=dd*6+bulletDanger(c,x,y); + if(first[kk]>=0&&(!bestN||val>bestN.v))bestN={v:val,d:first[kk],d2:second[kk]}; + if(dd>=40)continue; + for(var a=0;a<4;a++){var nx=x+BC.DX[a]*8,ny=y+BC.DY[a]*8,nk=key(nx,ny);if(nx<8||ny<8||nx>200||ny>200||dist[nk]!=null||!nodeFree(w,nx,ny))continue; + dist[nk]=dd+1;first[nk]=dd===0?a:first[kk];second[nk]=dd===0?-1:dd===1?a:second[kk];q.push([nx,ny]);} + } + if(bestN)return ALIGN?alignPack(c,b,sx,sy,bestN.d,bestN.d2):pack(bestN.d,false); + return pack(-1,false); + }; + function score(n,c0){ + if(n.result==='loss')return -1e9+n.t; + var b=n.body,w=n.boss,s=0;if(n.result==='win')s+=1e6; + s+=(w.kills-c0.boss.kills)*500+(w.tanks.filter(function(e){return e&&e.st==='dying';}).length)*400+b.lives*4000-(b.st==='dying'||b.st==='spawn'?3000:0); + BC.FORT.forEach(function(p){var i=BC.idx(p[0],p[1]);if(w.map[i]===2)s+=60;else if(w.map[i]===1){var m=w.bits[i];s+=15*((m&1)+(m>>1&1)+(m>>2&1)+(m>>3&1));}}); + for(var i=2;i<=5;i++){var p=w.bullets[i];if(!p||p.st!=='fly')continue;var ax=104-p.x,ay=200-p.y,v=p.dir; + if((v===2&&ay>0&&ay<80&&Math.abs(ax)<14)||(v===1&&ax<0&&ax>-80&&Math.abs(ay)<14)||(v===3&&ax>0&&ax<80&&Math.abs(ay)<14))s-=600;} + w.tanks.forEach(function(e){if(e&&BC.active(e))s-=Math.max(0,90-(Math.abs(e.x-104)+Math.abs(e.y-200)))*8;}); + if(w.pill&&!w.pill.flash)s-=(Math.abs(b.x-w.pill.x)+Math.abs(b.y-w.pill.y))*2; + s+=b.stars*300+(b.shield?200:0)+w.shovel*30+w.freeze*20; + return s; + } + function norm(subs){return subs.map(function(h){var o={};Object.keys(h).forEach(function(k){if(h[k])o[k]=true;});return o;});} + BB.BattleCityScripted=function(c){ + var b=c.body;if(b.st!=='active')return {subs:pack(-1,false),mouse:[0,0,0]}; + var cands=[{subs:BC.heuristic(c),bonus:150}]; + for(var d=-1;d<4;d++)for(var f=0;f<2;f++)cands.push({subs:pack(d,!!f),bonus:0}); + var best=null; + cands.forEach(function(cd){ + var n=cloneCase(c);run(n,cd.subs); + for(var k=0;kbest.s)best={s:s,subs:cd.subs}; + }); + return {subs:norm(best.subs),mouse:[0,0,0]}; + }; + if(BB.GAME)BB.GAME.scripted=BB.BattleCityScripted; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/battlecity_remake/specs/bc_brick_front.spec.js b/environments/games/web/games/battlecity_remake/specs/bc_brick_front.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..379ee19809676da385b9bf394ccda30be39a1623 --- /dev/null +++ b/environments/games/web/games/battlecity_remake/specs/bc_brick_front.spec.js @@ -0,0 +1,114 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["bc_brick_front"] = { + "schema": "bossbench/boss-spec@1", + "id": "bc_brick_front", + "dims": "2d", + "family": "battlecity2d", + "archetype": "Original Famicom stage 1: brick corridors; ROM roster 18 basic + 2 fast; tiers easy/normal/hard = 10/20/60 tanks (10/20/60 shell hits)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "spawn", + "active": "attack", + "recovery": "clear" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "timed_spawn", + "policy": "first", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "enemy_spawn", + "active": "tank_fire" + }, + "moves": [ + { + "name": "wave", + "atoms": [ + "spawn", + "projectile", + "terrain" + ], + "damage": 1, + "cue": "Tanks spawn in turn from the left, center, and right points at the top, with at most four on the field. On normal they chase you after about 26 seconds and rush the base after about 50; on hard, about 7 and 14 seconds", + "punish": "Each shot chips only 4 px of brick. Aim at the spawn points from the brick-lane mouths ahead of time, and do not fire toward the base" + }, + { + "name": "powerup", + "atoms": [ + "resource" + ], + "damage": 0, + "cue": "Tanks 4, 11, and 18 flash red and drop a power-up at one of 16 fixed points when hit", + "punish": "The fortify power-up turns the base into steel for about 21 seconds. Stars step up speed, then double shot, then steel-breaking shots" + } + ], + "difficulty": { + "hp": [ + 6, + 20, + 80 + ], + "dmg": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "idle_gap": [ + 0, + 0, + 0 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 2, + 2, + 2 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/battlecity_remake/specs/bc_jungle_ambush.spec.js b/environments/games/web/games/battlecity_remake/specs/bc_jungle_ambush.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..55f7feee3818ac1a5e68bdc66751f8cd3dd66442 --- /dev/null +++ b/environments/games/web/games/battlecity_remake/specs/bc_jungle_ambush.spec.js @@ -0,0 +1,114 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["bc_jungle_ambush"] = { + "schema": "bossbench/boss-spec@1", + "id": "bc_jungle_ambush", + "dims": "2d", + "family": "battlecity2d", + "archetype": "Self-made stage S2 (BossBench original layout, no Namco data): 31% forest hiding tanks and shells, fast-tank heavy roster 7 fast/5 basic/7 fast/1 armor; tiers easy/normal/hard = 10/20/60 tanks (13/23/69 shell hits)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "spawn", + "active": "attack", + "recovery": "clear" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "timed_spawn", + "policy": "first", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "enemy_spawn", + "active": "tank_fire" + }, + "moves": [ + { + "name": "wave", + "atoms": [ + "spawn", + "projectile", + "terrain" + ], + "damage": 1, + "cue": "Wide woods hide tanks and shells. Fast tanks (1 pixel per frame) are more than half the wave. Easy and normal chase you after about 13 seconds and rush the base after about 26 (this layout uses stage 24 timing); hard is about 7 and 14 seconds", + "punish": "Hold the clearing mouths and wait for fast tanks to leave the woods. A steel block in the center above the base stops shells, so enemies usually come down through the woods on either side" + }, + { + "name": "powerup", + "atoms": [ + "resource" + ], + "damage": 0, + "cue": "Tanks 4, 11, and 18 flash red (fast, light, fast) and drop a power-up when hit", + "punish": "The freeze power-up lasts about 10.7 seconds and can clear tanks hiding in the woods" + } + ], + "difficulty": { + "hp": [ + 6, + 23, + 92 + ], + "dmg": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "idle_gap": [ + 0, + 0, + 0 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 2, + 2, + 2 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/battlecity_remake/specs/bc_river_delta.spec.js b/environments/games/web/games/battlecity_remake/specs/bc_river_delta.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..6591830a4a85536265541c1179963a95fe07922f --- /dev/null +++ b/environments/games/web/games/battlecity_remake/specs/bc_river_delta.spec.js @@ -0,0 +1,114 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["bc_river_delta"] = { + "schema": "bossbench/boss-spec@1", + "id": "bc_river_delta", + "dims": "2d", + "family": "battlecity2d", + "archetype": "Self-made stage S1 (BossBench original layout, no Namco data): two north-south rivers with fords splitting the field into three lanes; brick islands in the middle lane, power-tank heavy roster 8 basic/8 power/3 fast/1 armor; tiers easy/normal/hard = 10/20/60 tanks (13/23/69 shell hits)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "spawn", + "active": "attack", + "recovery": "clear" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "timed_spawn", + "policy": "first", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "enemy_spawn", + "active": "tank_fire" + }, + "moves": [ + { + "name": "wave", + "atoms": [ + "spawn", + "projectile", + "terrain" + ], + "damage": 1, + "cue": "Two north-south rivers split the field into three lanes. Tanks can cross only at three fords, but shells fly across the water. Easy and normal chase you after about 17 seconds and rush the base after about 34 (this layout uses stage 16 timing); hard is about 7 and 14 seconds", + "punish": "Hold the center brick island and snipe the long-cannon tanks in the side lanes across the river. The ford mouths are the only places enemy tanks can cross" + }, + { + "name": "powerup", + "atoms": [ + "resource" + ], + "damage": 0, + "cue": "Tanks 4, 11, and 18 flash red (light, long cannon, fast) and drop a power-up when hit", + "punish": "The fortify power-up turns the base into steel for about 21 seconds. Stars step up speed, then double shot, then steel-breaking shots" + } + ], + "difficulty": { + "hp": [ + 6, + 23, + 92 + ], + "dmg": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "idle_gap": [ + 0, + 0, + 0 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 2, + 2, + 2 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/battlecity_remake/specs/bc_river_ice.spec.js b/environments/games/web/games/battlecity_remake/specs/bc_river_ice.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..f91e7a5e8716d9fa293579838db7990d342463e8 --- /dev/null +++ b/environments/games/web/games/battlecity_remake/specs/bc_river_ice.spec.js @@ -0,0 +1,114 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["bc_river_ice"] = { + "schema": "bossbench/boss-spec@1", + "id": "bc_river_ice", + "dims": "2d", + "family": "battlecity2d", + "archetype": "Original Famicom stage 28: ice lake ringed by forest; ROM roster 15 basic/2 fast/2 power/1 armor; tiers easy/normal/hard = 10/20/60 tanks (10/23/69 shell hits)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "spawn", + "active": "attack", + "recovery": "clear" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "timed_spawn", + "policy": "first", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "enemy_spawn", + "active": "tank_fire" + }, + "moves": [ + { + "name": "wave", + "atoms": [ + "spawn", + "projectile", + "terrain" + ], + "damage": 1, + "cue": "On easy and normal, enemies chase you after about 11 seconds and rush the base after about 21 seconds (original stage 28 timing); on hard, about 7 and 14 seconds. Woods hide tanks, but shells still fly", + "punish": "Starting on ice locks your direction into a slide, so release the key early. Hold the ice lane above the base" + }, + { + "name": "powerup", + "atoms": [ + "resource" + ], + "damage": 0, + "cue": "A flashing carrier drops a power-up as soon as it is hit, at one of 16 fixed points", + "punish": "The freeze power-up lasts about 10.7 seconds and the shield about 10.7 seconds; use them to break through the woods" + } + ], + "difficulty": { + "hp": [ + 6, + 23, + 92 + ], + "dmg": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "idle_gap": [ + 0, + 0, + 0 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 2, + 2, + 2 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/battlecity_remake/specs/bc_steel_fort.spec.js b/environments/games/web/games/battlecity_remake/specs/bc_steel_fort.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..511670b85f4ac79e9faf0325a23c5a6bd231a861 --- /dev/null +++ b/environments/games/web/games/battlecity_remake/specs/bc_steel_fort.spec.js @@ -0,0 +1,114 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["bc_steel_fort"] = { + "schema": "bossbench/boss-spec@1", + "id": "bc_steel_fort", + "dims": "2d", + "family": "battlecity2d", + "archetype": "Original Famicom stage 26: steel blocks and water channels; ROM roster 4 basic/6 fast/4 power/6 armor; tiers easy/normal/hard = 10/20/60 tanks (19/38/114 shell hits)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "spawn", + "active": "attack", + "recovery": "clear" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "timed_spawn", + "policy": "first", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "enemy_spawn", + "active": "tank_fire" + }, + "moves": [ + { + "name": "wave", + "atoms": [ + "spawn", + "projectile", + "terrain" + ], + "damage": 1, + "cue": "Fast tanks open, then armored tanks (four hits, color changes with remaining armor). Easy and normal chase you after about 12 seconds and rush the base after about 23; hard is about 7 and 14 seconds", + "punish": "Water stops tanks but not shells, so shoot across it. Only a three-star shell can break a steel wall" + }, + { + "name": "powerup", + "atoms": [ + "resource" + ], + "damage": 0, + "cue": "A flashing carrier drops a power-up when hit. A red armored tank drops one only on the first hit", + "punish": "At three stars you can break steel walls and open a shortcut" + } + ], + "difficulty": { + "hp": [ + 9, + 38, + 152 + ], + "dmg": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "idle_gap": [ + 0, + 0, + 0 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 2, + 2, + 2 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/battlecity_remake/specs/bc_steel_maze.spec.js b/environments/games/web/games/battlecity_remake/specs/bc_steel_maze.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5b5a2972c7b6ea2ad41c9063a065e4ae61c59646 --- /dev/null +++ b/environments/games/web/games/battlecity_remake/specs/bc_steel_maze.spec.js @@ -0,0 +1,114 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["bc_steel_maze"] = { + "schema": "bossbench/boss-spec@1", + "id": "bc_steel_maze", + "dims": "2d", + "family": "battlecity2d", + "archetype": "Self-made stage S3 (BossBench original layout, no Namco data): steel maze (29% steel), steel roof over the eagle so attacks come from the sides, armor-heavy roster 3 fast/5 power/5 armor/7 basic; tiers easy/normal/hard = 10/20/60 tanks (16/35/105 shell hits)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "spawn", + "active": "attack", + "recovery": "clear" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "timed_spawn", + "policy": "first", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "enemy_spawn", + "active": "tank_fire" + }, + "moves": [ + { + "name": "wave", + "atoms": [ + "spawn", + "projectile", + "terrain" + ], + "damage": 1, + "cue": "The steel maze has only a few brick gaps you can shoot through. The base has a steel roof, so enemy tanks must go around to the bottom two rows and break the brick walls from the left or right. Easy and normal chase you after about 10 seconds and rush the base after about 19 (this layout uses stage 30 timing); hard is about 7 and 14 seconds", + "punish": "A three-star shell breaks steel and opens a shortcut. Hold the two bottom lanes on either side of the base" + }, + { + "name": "powerup", + "atoms": [ + "resource" + ], + "damage": 0, + "cue": "Tanks 4, 11, and 18 in the spawn list flash red (long cannon, armor, light). They drop a power-up when hit. A red armored tank drops one only on the first hit", + "punish": "Shoot red tanks first for stars; at three stars the maze becomes straight roads" + } + ], + "difficulty": { + "hp": [ + 9, + 35, + 140 + ], + "dmg": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "idle_gap": [ + 0, + 0, + 0 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 2, + 2, + 2 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/arena.js b/environments/games/web/games/cuphead_remake/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..3dd439658082d9928f087a45c7338d4e7ddcd942 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/arena.js @@ -0,0 +1,46 @@ +(function(g){ + var B=g.BB; B.ARENA={W:27,H:15}; + var C=B.CUP={}; + C.snapshot=function(v){if(typeof v==='number')return B.r4(v);if(Array.isArray(v))return v.map(C.snapshot);if(v&&typeof v==='object'){var o={};Object.keys(v).forEach(function(k){o[k]=C.snapshot(v[k]);});return o;}return v;}; + C.mode=function(d){return d<.25?0:d<.75?1:2;}; + // v3 tiers: benchmark total HP of the encounter [easy, normal, hard] at the difficulties declared in BB.GAME.tiers. + // Each phase keeps the source share of its mode's total (C.init); minion/projectile HP (4, 10, 9999) is not scaled. + // Any other d interpolates geometrically between the neighbouring tiers and is clamped outside easy..hard. + C.TOTAL={goopy:[750,2000,6300],root_pack:[900,1950,7000],hilda:[600,1950,5400], + cagney:[900,2200,5300],ribby_croaks:[900,2400,6800],wally:[700,2100,4800]}; // v5 scenes, calibrated with the scripted controller + // v4: Horace Radiche, the chaser that joins Chauncey mid-fight on the secret branch, keeps his source HP per mode + // (Simple has no secret branch). Shots reach him at a third of the usual damage rate (he must be jumped every 2-3 s), + // so scaling him with the encounter stretched that section past the tier window. + C.HORACE_HP=[0,230,260]; + C.tierD=function(){var t=B.GAME&&B.GAME.tiers||{easy:.2,normal:.5,hard:.8};return [t.easy,t.normal,t.hard];}; + C.total=function(id,d){var T=C.TOTAL[id],k=C.tierD();if(d<=k[0])return T[0];if(d>=k[2])return T[2];var i=dm+h)return null;} + else{var t0=(m-h-p)/d,t1=(m+h-p)/d;if(t0>t1){var z=t0;t0=t1;t1=z;}lo=Math.max(lo,t0);hi=Math.min(hi,t1);if(lo>hi)return null;}} + return lo; + }; + C.sweep=function(a,b,r,box){return C.sweepTime(a,b,r,box)!==null;}; + C.hit=function(h,b){return h.box?B.overlap(h.box,b):h.circle?B.circleBox(h.circle[0],h.circle[1],h.circle[2],b):h.seg?C.sweep({x:h.seg[0],y:h.seg[1]},{x:h.seg[2],y:h.seg[3]},h.r||0,b):false;}; + C.init=function(o,c,parts){o.mode=C.mode(c.d);var src=parts.map(function(v){return v[o.mode];});o.sourceParts=src;o.hpScale=C.total(o.id,c.d)/src.reduce(function(a,b){return a+b;},0);o.parts=src.map(function(v){return Math.round(v*o.hpScale);});o.max_hp=o.hp=o.parts.reduce(function(a,b){return a+b;},0);o.phase=0;o.phaseHp=o.parts[0];o.dmg=1;o.st='idle';o.timer=1;o.stT=0;o.move=null;o.hitFlash=0;o.projectiles=[];o.nextId=1;o.phaseT=0;o.deadT=0;}; + C.projectile=function(o,p){p.id=o.nextId++;p.px=p.x;p.py=p.y;p.life=p.life||10;p.r=p.r||.3;p.hp=p.hp||0;p.dmg=1;o.projectiles.push(p);return p;}; + C.stepProjectiles=function(o,c){o.projectiles.forEach(function(p){p.px=p.x;p.py=p.y;p.life-=B.DT;p.age=(p.age||0)+B.DT; + if(p.home&&p.life>p.homeEnd&&p.age>=(p.homeDelay||0)){var dx=c.body.x-p.x,dy=c.body.centre().y-p.y,dist=Math.hypot(dx,dy)||1,rate=p.turn||2;p.vx+=(dx/dist*p.speed-p.vx)*Math.min(1,rate*B.DT);p.vy+=(dy/dist*p.speed-p.vy)*Math.min(1,rate*B.DT);} + p.x+=(p.vx||0)*B.DT;p.y+=(p.vy||0)*B.DT;p.vy+=(p.gravity||0)*B.DT; + // v2: a fired UFO first charges for C.UFO_CHARGE s (harmless, drawn as a guide line), then lights its laser. + if(p.kind==='ufo'){var trigger=p.red?Math.abs(c.body.x-p.x)<.7: c.body.xp.x-2.3;if(!p.fired&&trigger){p.fired=true;p.charge=C.UFO_CHARGE;c.emit('ufo_charge',p.x,p.y);} + if(p.charge>0){p.charge-=B.DT;if(p.charge<=1e-9){p.charge=0;p.beam=o.mode===2?1.1:.8;c.emit('ufo_laser',p.x,0);}}else if(p.beam>0)p.beam-=B.DT;} + });o.projectiles=o.projectiles.filter(function(p){return !p.removed&&p.life>0&&p.x>-4&&p.x<31&&p.y>-3&&p.y<19;});}; + C.hazards=function(o){var out=[];o.projectiles.forEach(function(p){if(p.removed)return;out.push({kind:p.kind,circle:[p.x,p.y,p.r],pink:!!p.pink,ref:p,fromX:p.x});if(p.kind==='ufo'&&p.beam>0)out.push({kind:'ufo_laser',box:C.box(p.x,p.y/2,.75,p.y),fromX:p.x});});return out;}; + C.damage=function(o,c,dmg,tid){if(o.st==='dead'||o.st==='transition')return null; + if(tid&&tid!=='boss'){var p=o.projectiles.find(function(q){return String(q.id)===tid;});if(!p||p.removed)return null;p.hp-=dmg;if(p.hp<=0)p.removed=true;return 'flesh';} + var d=Math.min(o.phaseHp,dmg);o.phaseHp-=d;o.hp=Math.max(0,o.hp-d);o.hitFlash=.07;c.emit('boss_hit',o.x,o.y||2); + if(o.phaseHp<=0){if(o.phase+10&&!p.removed)a.push({id:String(p.id),box:C.box(p.x,p.y,p.r*2,p.r*2)});});return a;}; + C.state=function(o,extra){var a={x:B.r4(o.x),y:B.r4(o.y||0),hp:B.r4(o.hp),max_hp:o.max_hp,fsm:o.st,role:o.role(),move:o.move,phase:o.phase,phase_hp:B.r4(o.phaseHp),mode:['simple','regular','expert'][o.mode],timer:B.r4(o.timer),phase_time:B.r4(o.phaseT),telegraph_left:o.role()==='telegraph'?B.r4(Math.max(0,o.timer)):0,hp_scale:B.r4(o.hpScale),projectiles:o.projectiles};return C.snapshot(Object.assign(a,extra||{}));}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/art/scenes.js b/environments/games/web/games/cuphead_remake/art/scenes.js new file mode 100644 index 0000000000000000000000000000000000000000..f1950ab2246984d12feafb15b6039cba6511970a --- /dev/null +++ b/environments/games/web/games/cuphead_remake/art/scenes.js @@ -0,0 +1,109 @@ +// Original procedural backgrounds for the three Cuphead cases: watercolour-paper skies, inked 1930s-cartoon forest, +// garden and cloudscape. Cached per case (drawn once); ambient() adds slow presentation-time motion only. +(function (g) { + var B = g.BB, A = B.ART, V = B.VIEW, TAU = Math.PI * 2, INK = '#1d1815'; + V.PAL = { boss: '#446493', bossEdge: '#28252b', tele: '#e16462', floor: '#b28755' }; + function H(i) { var s = Math.sin(i * 91.7 + 17.3) * 43758.5453; return s - Math.floor(s); } + function stroke(x, w, c) { x.lineWidth = w; x.strokeStyle = c || INK; x.lineCap = 'round'; x.lineJoin = 'round'; x.stroke(); } + function paper(x, seed) { // watercolour blotches + paper fibres, deterministic + for (var i = 0; i < 26; i++) { var px = H(seed + i) * 854, py = H(seed + i * 3.3) * 480, r = 40 + H(seed + i * 7.1) * 120; var gr = x.createRadialGradient(px, py, 0, px, py, r); gr.addColorStop(0, 'rgba(255,248,226,.16)'); gr.addColorStop(1, 'rgba(255,248,226,0)'); x.fillStyle = gr; x.fillRect(px - r, py - r, r * 2, r * 2); } + x.fillStyle = 'rgba(54,40,25,.045)'; for (var k = 0; k < 2200; k++) x.fillRect((k * 433 + seed) % 854, (k * 179) % 480, 1 + (k % 3 === 0), 1); + } + function sky(x, top, bot) { var gr = x.createLinearGradient(0, 0, 0, 480); gr.addColorStop(0, top); gr.addColorStop(1, bot); x.fillStyle = gr; x.fillRect(0, 0, 854, 480); } + function puffCloud(x, cx, cy, w, fill, edge) { + x.beginPath(); var n = 5; for (var i = 0; i < n; i++) { var a = Math.PI + (i + .5) / n * Math.PI; x.arc(cx + Math.cos(a) * w * .62, cy + Math.sin(a) * w * .22, w * (.22 + .1 * H(cx + i)), 0, TAU); } + x.rect(cx - w * .8, cy - 2, w * 1.6, w * .18); x.fillStyle = fill; x.fill(); if (edge) { x.beginPath(); x.moveTo(cx - w * .82, cy + w * .16); x.lineTo(cx + w * .82, cy + w * .16); stroke(x, 2, edge); } + } + function tree(x, px, h, w, col, dark, seed) { // rubber-hose tree with a face-less knot and drooping branches + x.beginPath(); x.moveTo(px - w, 446); x.bezierCurveTo(px - w * .55, 446 - h * .4, px - w * .7, 446 - h * .8, px - w * .3, 446 - h); x.lineTo(px + w * .3, 446 - h); x.bezierCurveTo(px + w * .7, 446 - h * .8, px + w * .55, 446 - h * .4, px + w, 446); x.closePath(); x.fillStyle = col; x.fill(); stroke(x, 2.4, dark); + for (var b = 0; b < 3; b++) { var by = 446 - h * (.45 + b * .18), s = b % 2 ? 1 : -1; x.beginPath(); x.moveTo(px, by); x.quadraticCurveTo(px + s * w * 2.2, by - 40, px + s * w * 3, by - 10 + H(seed + b) * 20); stroke(x, 7 - b * 1.5, col); x.beginPath(); x.moveTo(px, by); x.quadraticCurveTo(px + s * w * 2.2, by - 40, px + s * w * 3, by - 10 + H(seed + b) * 20); stroke(x, 1.4, dark); } + x.beginPath(); x.ellipse(px + w * .1, 446 - h * .3, w * .2, w * .32, 0, 0, TAU); x.fillStyle = dark; x.fill(); + for (var q = 0; q < 5; q++) { var ca = q / 5 * TAU + seed, cr = w * (2.2 + H(seed + q * 2) * 1.1); x.beginPath(); x.arc(px + Math.cos(ca) * w * 2.1, 446 - h - 10 + Math.sin(ca) * w * 1.3, cr, 0, TAU); x.fillStyle = q % 2 ? '#6f8f6c' : '#86a583'; x.fill(); stroke(x, 2, dark); } + x.beginPath(); x.arc(px, 446 - h - 14, w * 2.6, 0, TAU); x.fillStyle = '#7c9b78'; x.fill(); stroke(x, 2, dark); + } + function forest(x) { + sky(x, '#c9dcc6', '#efe2b9'); + var sun = x.createRadialGradient(640, 90, 0, 640, 90, 260); sun.addColorStop(0, 'rgba(255,246,206,.85)'); sun.addColorStop(1, 'rgba(255,246,206,0)'); x.fillStyle = sun; x.fillRect(0, 0, 854, 480); + for (var i = 0; i < 7; i++) { x.beginPath(); x.ellipse(i * 150 - 30, 360, 160, 110 + H(i) * 40, 0, 0, TAU); x.fillStyle = i % 2 ? '#a9bc9a' : '#b9c9a6'; x.fill(); } + for (var t = 0; t < 7; t++) tree(x, t * 138 + 20 + H(t) * 30, 210 + H(t + 4) * 70, 14 + H(t + 8) * 6, '#7f9a7c', '#4d6a55', t); + for (var m = 0; m < 9; m++) { x.beginPath(); x.ellipse(m * 104 + 30, 438, 70, 26, 0, Math.PI, TAU); x.fillStyle = '#6f8f5f'; x.fill(); stroke(x, 2, '#4d6a45'); } + for (var f = 0; f < 14; f++) { var fx = H(f * 3) * 854, fy = 430 + H(f * 5) * 10; for (var p = 0; p < 5; p++) { x.beginPath(); x.ellipse(fx + Math.cos(p / 5 * TAU) * 3.5, fy + Math.sin(p / 5 * TAU) * 3.5, 2.6, 2.6, 0, 0, TAU); x.fillStyle = f % 3 ? '#f3e6c8' : '#f0a6a0'; x.fill(); } } + } + function garden(x) { + sky(x, '#d3dcae', '#f1dfb4'); + for (var i = 0; i < 6; i++) { x.beginPath(); x.ellipse(i * 180 - 10, 350, 175, 120, 0, 0, TAU); x.fillStyle = i % 2 ? '#a3ad84' : '#b5bd92'; x.fill(); } + x.fillStyle = '#e8dcc0'; for (var p = 0; p < 22; p++) { var px = p * 40 + 4; x.beginPath(); x.moveTo(px, 400); x.lineTo(px, 300); x.lineTo(px + 9, 290); x.lineTo(px + 18, 300); x.lineTo(px + 18, 400); x.closePath(); x.fill(); stroke(x, 2, '#8d7d5e'); } + x.fillRect(0, 318, 854, 9); x.fillRect(0, 368, 854, 9); x.beginPath(); x.rect(0, 318, 854, 9); x.rect(0, 368, 854, 9); stroke(x, 1.6, '#8d7d5e'); + for (var r = 0; r < 4; r++) { var by = 418 + r * 7; x.beginPath(); x.moveTo(0, by); for (var k = 0; k <= 30; k++) x.lineTo(k * 29, by + Math.sin(k * 1.3 + r) * 3); stroke(x, 2, 'rgba(90,60,35,.35)'); } + for (var s = 0; s < 16; s++) { var sx = s * 56 + 12; x.beginPath(); x.moveTo(sx, 432); x.quadraticCurveTo(sx - 8, 414, sx - 12, 408); stroke(x, 3, '#5f8a4a'); x.beginPath(); x.moveTo(sx, 432); x.quadraticCurveTo(sx + 6, 412, sx + 12, 406); stroke(x, 3, '#5f8a4a'); } + } + function floor(x, col, top) { + x.fillStyle = col; x.fillRect(0, 446, 854, 34); x.fillStyle = top; x.fillRect(0, 440, 854, 8); + x.beginPath(); x.moveTo(0, 441); for (var k = 0; k <= 60; k++) x.lineTo(k * 14.3, 441 + Math.sin(k * 2.1) * 1.4); stroke(x, 2.6); + for (var a = 0; a < 70; a++) { x.fillStyle = 'rgba(40,28,18,.16)'; x.fillRect((a * 197) % 854, 452 + (a * 37) % 24, 6, 1.5); } + } + function skyScene(x, night) { + if (night) { + sky(x, '#0f1633', '#30416a'); + for (var s = 0; s < 120; s++) { var px = H(s) * 854, py = H(s + 50) * 420, r = .6 + H(s + 9) * 1.4; x.fillStyle = 'rgba(255,244,210,' + (.4 + H(s + 3) * .6) + ')'; x.beginPath(); x.arc(px, py, r, 0, TAU); x.fill(); } + for (var c = 0; c < 7; c++) puffCloud(x, H(c + 70) * 854, 360 + H(c + 80) * 120, 90 + H(c) * 40, 'rgba(58,74,118,.6)'); + } else { + sky(x, '#8fcbe0', '#f4dfb0'); + for (var i = 0; i < 5; i++) puffCloud(x, i * 210 + 40, 400 + H(i) * 40, 150, '#fbefd4', 'rgba(190,150,110,.5)'); + for (var j = 0; j < 9; j++) puffCloud(x, H(j + 20) * 854, 90 + H(j + 30) * 220, 50 + H(j + 40) * 50, 'rgba(255,250,232,.85)'); + x.beginPath(); x.arc(700, 70, 34, 0, TAU); x.fillStyle = 'rgba(255,240,190,.7)'; x.fill(); + } + } + function make(doc, id, night) { + var cv = doc.createElement('canvas'); cv.width = 854; cv.height = 480; var x = cv.getContext('2d'); + if (id === 'cuphead/hilda') skyScene(x, night); + else if (id === 'cuphead/wally') aviary(x); + else if (id === 'cuphead/root_pack') { garden(x); floor(x, '#8f6440', '#a8794d'); } + else if (id === 'cuphead/cagney') { flowerBed(x); floor(x, '#6d7f4a', '#88995a'); } + else if (id === 'cuphead/ribby_croaks') { clubStage(x); floor(x, '#5c3a2c', '#7a5038'); } + else { forest(x); floor(x, '#7f8f58', '#97a868'); } + paper(x, id.length * 13 + (night ? 7 : 0)); return cv; + } + // v5 scenes (Cagney's flower bed, Ribby & Croaks' nightclub stage, Wally's cuckoo-clock sky): same paper + ink style + function flowerBed(x) { + sky(x, '#f1d9b8', '#f6e6c4'); + for (var i = 0; i < 6; i++) { x.beginPath(); x.ellipse(i * 170 - 20, 380, 170, 120, 0, 0, TAU); x.fillStyle = i % 2 ? '#c9b98c' : '#d6c79a'; x.fill(); } + for (var s = 0; s < 18; s++) { // tall background flowers on hose stems + var fx = 20 + s * 48 + H(s) * 20, fh = 150 + H(s + 3) * 120, top = 440 - fh; + x.beginPath(); x.moveTo(fx, 440); x.quadraticCurveTo(fx + 14 * Math.sin(s), top + fh * .5, fx, top); stroke(x, 5, '#7b9a5c'); stroke(x, 1.4, '#4f6a3a'); + var col = ['#f2a65a', '#e87a6f', '#f6d36b', '#c98fd1'][s % 4]; + for (var p = 0; p < 6; p++) { var a = p / 6 * TAU; x.beginPath(); x.ellipse(fx + Math.cos(a) * 11, top + Math.sin(a) * 11, 9, 6, a, 0, TAU); x.fillStyle = col; x.fill(); stroke(x, 1.4, 'rgba(70,40,25,.6)'); } + x.beginPath(); x.arc(fx, top, 6, 0, TAU); x.fillStyle = '#7a4a2c'; x.fill(); + } + } + function clubStage(x) { + sky(x, '#3b2333', '#7a4a3a'); + for (var b = 0; b < 9; b++) { var bx = b * 100 + 20; x.fillStyle = b % 2 ? 'rgba(160,40,40,.55)' : 'rgba(120,28,32,.55)'; x.fillRect(bx, 0, 60, 330); } // curtains + x.beginPath(); x.moveTo(0, 330); x.lineTo(854, 330); stroke(x, 3, 'rgba(240,200,120,.7)'); + for (var l = 0; l < 14; l++) { x.beginPath(); x.arc(30 + l * 61, 22, 7, 0, TAU); x.fillStyle = l % 2 ? '#ffe9a3' : '#ffd36b'; x.fill(); stroke(x, 1.6, '#5a3a20'); } // marquee bulbs + var spot = x.createRadialGradient(427, 300, 20, 427, 300, 340); spot.addColorStop(0, 'rgba(255,236,190,.35)'); spot.addColorStop(1, 'rgba(255,236,190,0)'); x.fillStyle = spot; x.fillRect(0, 0, 854, 480); + for (var t = 0; t < 7; t++) { var tx = 60 + t * 120; x.beginPath(); x.ellipse(tx, 410, 34, 9, 0, 0, TAU); x.fillStyle = '#3c2a22'; x.fill(); stroke(x, 2, '#1d1815'); x.fillRect(tx - 3, 410, 6, 30); } // tables + } + function aviary(x) { + sky(x, '#a9d3df', '#f2e1b6'); + for (var i = 0; i < 6; i++) puffCloud(x, i * 190 + 30, 420 + H(i) * 30, 140, '#fbefd4', 'rgba(190,150,110,.5)'); + for (var j = 0; j < 8; j++) puffCloud(x, H(j + 60) * 854, 70 + H(j + 31) * 230, 46 + H(j + 41) * 46, 'rgba(255,250,232,.85)'); + for (var k = 0; k < 5; k++) { var kx = 80 + k * 180, ky = 120 + H(k + 9) * 160; x.beginPath(); x.moveTo(kx - 12, ky); x.quadraticCurveTo(kx - 5, ky - 7, kx, ky); x.quadraticCurveTo(kx + 5, ky - 7, kx + 12, ky); stroke(x, 2, 'rgba(70,60,60,.5)'); } // far birds + } + A.scene = function (doc, id) { + var bg = make(doc, id, false), fg = doc.createElement('canvas'); fg.width = 854; fg.height = 480; var x = fg.getContext('2d'); + x.strokeStyle = 'rgba(29,24,21,.85)'; x.lineWidth = 6; x.strokeRect(3, 3, 848, 474); x.strokeStyle = 'rgba(244,232,204,.6)'; x.lineWidth = 1.5; x.strokeRect(8, 8, 838, 464); + var night = id === 'cuphead/hilda' ? make(doc, id, true) : null; + return { bg: bg, fg: fg, background: function (c) { return night && (c.boss.form === 'moon' || (c.boss.phase === 5 && c.boss.st === 'transition')) ? night : bg; } }; + }; + A.ambient = function (x, id, t) { + var cur = A.store && A.store.c, night = id === 'cuphead/hilda' && cur && cur.id === id && cur.boss.form === 'moon'; + x.save(); + if (id === 'cuphead/hilda' || id === 'cuphead/wally') { // drifting cloud bands (parallax), presentation time only + for (var i = 0; i < 6; i++) { var px = ((1100 - i * 193 - t * (14 + i * 4)) % 1100 + 1100) % 1100 - 120; x.globalAlpha = .45; x.beginPath(); x.ellipse(px, 130 + i * 52, 80 + i * 9, 11, 0, 0, TAU); x.fillStyle = night ? '#55648f' : '#fff8e6'; x.fill(); } + } else { // floating pollen motes + for (var k = 0; k < 14; k++) { var mx = (H(k) * 854 + t * (6 + H(k + 1) * 10)) % 854, my = 120 + H(k + 2) * 260 + Math.sin(t * .8 + k) * 12; x.globalAlpha = .35; x.beginPath(); x.arc(mx, my, 1.6, 0, TAU); x.fillStyle = '#fff6d8'; x.fill(); } + } + x.restore(); + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/body_cup.js b/environments/games/web/games/cuphead_remake/body_cup.js new file mode 100644 index 0000000000000000000000000000000000000000..99de96eb034bfa3e760aad95835c2b1d90bf9aae --- /dev/null +++ b/environments/games/web/games/cuphead_remake/body_cup.js @@ -0,0 +1,76 @@ +(function(g){ + var B=g.BB,C=B.CUP,DT=B.DT; + function Cup(){} function Plane(){} Plane.prototype=Object.create(Cup.prototype);Plane.prototype.constructor=Plane; + Cup.prototype.id='cup';Plane.prototype.id='cup_plane';Plane.prototype.plane=true; + Cup.prototype.NAIL=0;Cup.prototype.HITSTOP=0; + Cup.prototype.keys={left:'A',right:'D',up:'W',down:'S',jump:'Space',dash:'Shift',shoot:'J|LMB',ex:'K|RMB',lock:'L',weapon:'Q',super:'E'}; + Cup.prototype.manual=['Ground: A/D to run; combine W/S with A/D to aim in eight directions; S to crouch and shoot horizontally forward; hold L to stand still and aim in eight directions (you cannot run while locked)','Space to jump; press Space again in the air to parry pink objects, bounce, and gain one card; Shift to dash on the ground or in the air (without charms, dashes grant no invulnerability)','J/left mouse button to fire continuously; K/right mouse button for EX (costs one card); with five cards, K or E fires a horizontal sweeping super beam','3 HP; brief invulnerability after taking damage; reduce the boss’s final-phase HP to zero for a KNOCKOUT victory']; + Plane.prototype.manual=['Plane: W/A/S/D to fly in eight directions; J/left mouse button to shoot (machine gun by default); Q switches between machine gun and small bombs (higher damage, slower fire, downward arc)','Hold Shift to shrink: smaller hitbox and faster movement, but only short-range weak shots and no EX or super','Space to parry pink objects at any time (gain one card); K/right mouse button for EX (costs one card); with five cards, K or E transforms into a bomb that explodes on contact or timeout and grants three seconds of invulnerability','3 HP; brief invulnerability after taking damage; in the moon phase, UFOs charge before firing lasers: red triggers directly below, gold ahead']; + Cup.prototype.reset=function(c){this.x=3.5;this.y=this.plane?7:0;this.vx=this.vy=0;this.facing=1;this.grounded=!this.plane;this.hp=this.max_hp=3;this.invul=0;this.dashT=this.dashCd=0;this.dashF=1;this.airDash=false;this.parryT=0;this.parries=0;this.meter=0;this.shotCd=0;this.exCd=0;this.superT=0;this.superKind=null;this.exHits={};this.shrink=false;this.weapon='gun';this.crouch=false;this.prev={};this.shots=[];this.nextShot=1;this.aim={x:1,y:0};this.slashHits={};this.slashFacing=1;this.dropT=0; + // v5: a boss may supply thin platforms; onPlat stays undefined otherwise, so the v4 state (and hash) is unchanged. + this.onPlat=c.boss&&c.boss.platforms?null:undefined;}; + Cup.prototype.hurtBox=function(){var h=this.plane?(this.shrink?.48:.78):this.crouch?.63:1.45,w=this.plane?(this.shrink?.6:1.25):.7;return C.box(this.x,this.plane?this.y:this.y+h/2,w,h);}; + Cup.prototype.box=Cup.prototype.hurtBox;Cup.prototype.centre=function(){var b=this.hurtBox();return {x:b.x,y:b.y};}; + Cup.prototype.slashBox=function(){return null;};Cup.prototype.onSlashContact=function(){}; + Cup.prototype.addShot=function(c,kind,ax,ay){var b=this.centre(),plane=this.plane,v=kind==='ex'?24:plane?31:40,damage=kind==='ex'?8.333333:plane?(this.shrink?2:this.weapon==='bomb'?11.5:4):4; + var p={id:this.nextShot++,kind:kind,x:b.x+ax*.7,y:b.y+ay*.35,px:b.x,py:b.y,vx:ax*v,vy:ay*v,life:this.shrink?.24:plane&&this.weapon==='bomb'?3:2.1,r:kind==='ex'?.52:.13,damage:damage,hits:{},ticks:0}; + if(plane&&!this.shrink&&this.weapon==='bomb'&&kind!=='ex'){p.kind='bomb';p.vx=7;p.vy=-2;p.gravity=-20;p.r=.25;}if(plane&&kind==='ex'){p.kind='missile';p.damage=15;p.r=.48;} + this.shots.push(p);c.emit(kind==='ex'?'cup_ex':'cup_shoot',p.x,p.y); + }; + Cup.prototype.startSuper=function(c){this.meter-=5;this.superT=this.plane?2.0:1.1;this.superKind=this.plane?'bomb_morph':'beam';this.exHits={};this.invul=Math.max(this.invul,this.superT);c.emit('cup_super',this.x,this.y);}; + Cup.prototype.update=function(c,i){var p=this.prev,dx=(i.right?1:0)-(i.left?1:0),dy=(i.up?1:0)-(i.down?1:0); + this.invul=Math.max(0,this.invul-DT);this.shotCd=Math.max(0,this.shotCd-DT);this.exCd=Math.max(0,this.exCd-DT);this.dashCd=Math.max(0,this.dashCd-DT);this.parryT=Math.max(0,this.parryT-DT);this.dropT=Math.max(0,this.dropT-DT); + if(this.superT>0){this.superT-=DT;if(this.superT<=0&&this.superKind==='bomb_morph')this.explode(c);} + if(this.plane){this.shrink=!!i.dash&&this.superT<=0;var speed=this.shrink?11:8.2,len=Math.hypot(dx,dy)||1;this.vx=dx/len*speed;this.vy=dy/len*speed;this.x=B.clamp(this.x+this.vx*DT,.7,26.3);this.y=B.clamp(this.y+this.vy*DT,.65,14.2);this.aim={x:1,y:0}; + if(i.weapon&&!p.weapon)this.weapon=this.weapon==='gun'?'bomb':'gun';if(i.jump&&!p.jump)this.parryT=.18; + }else if(this.onPlat!==undefined){this.groundV5(c,i,p,dx,dy); + }else{this.crouch=!!i.down&&this.grounded&&!i.lock;this.aim={x:dx,y:dy};if(dx)this.facing=dx;if(this.crouch||!dx&&!dy)this.aim={x:this.facing,y:0};var len=Math.hypot(this.aim.x,this.aim.y)||1;this.aim={x:this.aim.x/len,y:this.aim.y/len}; + if(i.dash&&!p.dash&&this.dashCd<=0&&!this.airDash&&this.superT<=0){this.dashT=.2;this.dashCd=.5;this.dashF=dx||this.facing;if(!this.grounded)this.airDash=true;c.emit('cup_dash',this.x,this.y);} + if(i.jump&&!p.jump&&this.superT<=0){if(this.grounded){this.vy=16;this.grounded=false;if(i.down)this.dropT=.2;c.emit('jump',this.x,this.y);}else this.parryT=.18;} + if(this.dashT>0){this.dashT-=DT;this.vx=this.dashF*19;this.vy=0;}else{this.vx=this.superT>0||i.lock||this.crouch?0:dx*7.2;this.vy=Math.max(-22,this.vy-44*DT);} + this.x=B.clamp(this.x+this.vx*DT,.4,26.6);this.y+=this.vy*DT;if(this.y<=0){if(!this.grounded)c.emit('land',this.x,0);this.y=0;this.vy=0;this.grounded=true;this.airDash=false;} + } + if(i.shoot&&this.shotCd<=1e-9&&this.superT<=0&&this.dashT<=0){this.addShot(c,'shot',this.aim.x,this.aim.y);this.shotCd=this.plane&&!this.shrink&&this.weapon==='bomb'?.35:8/60;} + if((i.ex&&!p.ex||i.super&&!p.super)&&this.exCd<=0&&this.superT<=0&&!this.shrink){if(this.meter>=5)this.startSuper(c);else if(i.ex&&this.meter>=1){this.meter-=1;this.addShot(c,'ex',this.aim.x,this.aim.y);this.exCd=.3;}} + this.shots.forEach(function(s){s.px=s.x;s.py=s.y;s.x+=s.vx*DT;s.y+=s.vy*DT;s.vy+=(s.gravity||0)*DT;s.life-=DT;s.ticks++;});this.shots=this.shots.filter(function(s){return s.life>0&&s.x>-3&&s.x<30&&s.y>-2&&s.y<17;});this.prev=Object.assign({},i); + }; + Cup.prototype.explode=function(c){var b=c.boss,targets=b.hitTargets(),centre=this.centre();targets.forEach(function(t){if(B.circleBox(centre.x,centre.y,4,t.box))b.onNailHit(c,152,'side',1,t.id);});this.invul=3;this.superT=0;this.superKind=null;c.emit('cup_explosion',this.x,this.y);c.shake(.6);}; + // v5: ground movement for scenes whose boss supplies platforms(c) (Cagney, Ribby & Croaks). The plain ground branch + // plus one-way thin platforms (land only while falling from above; S + Space on one drops through, source + // "Duck / Descend"), being carried by a moving platform, and an optional horizontal wind push windAt(c) that adds to + // running and dashing (source: Croaks' fan blows the players toward Ribby, who can still run or dash away). + Cup.prototype.groundV5=function(c,i,p,dx,dy){var o=c.boss,plats=o.platforms(c)||[],wind=o.windAt?o.windAt(c):0,on=null,k; + for(k=0;k0){this.dashT-=DT;this.vx=this.dashF*19;this.vy=0;}else{this.vx=this.superT>0||i.lock||this.crouch?0:dx*7.2;this.vy=Math.max(-22,this.vy-44*DT);} + var y0=this.y,land=null;this.x=B.clamp(this.x+(this.vx+wind+(on&&on.vx||0))*DT,.4,26.6);this.y+=this.vy*DT; + if(this.vy<=0&&this.dropT<=0)for(k=0;k=q.y-1e-6&&this.y<=q.y&&Math.abs(this.x-q.x)<=q.w/2+.2&&(!land||q.y>land.y))land=q;} + if(land){if(!this.grounded)c.emit('land',this.x,land.y);this.y=land.y;this.vy=0;this.grounded=true;this.airDash=false;this.onPlat=land.id;} + else if(this.y<=0){if(!this.grounded)c.emit('land',this.x,0);this.y=0;this.vy=0;this.grounded=true;this.airDash=false;this.onPlat=null;} + else{this.grounded=false;this.onPlat=null;} + }; + Cup.prototype.resolveInteractions=function(c){var self=this,b=c.boss,hb=this.hurtBox(),targets=b.hitTargets(); + // Shots interact with the first target along their path. Three timed EX hits on a large target. v5: a target may + // answer 'block' (Willy's spiked eggs): the shot is consumed and, dealing no damage, gives no super meter. + this.shots.forEach(function(s){var contacts=targets.map(function(t){return {target:t,time:C.sweepTime({x:s.px,y:s.py},s,s.r,t.box)};}).filter(function(t){return t.time!==null;}).sort(function(a,b){return a.time-b.time;});for(var j=0;j=5))continue; + var r=b.onNailHit(c,s.damage,'side',self.facing,t.id);if(r){s.hits[t.id]=n+1;s.lastHit=s.ticks;if(r!=='block')self.meter=Math.min(5,self.meter+s.damage/100);if(s.kind!=='ex'||n>=2||r==='block')s.life=0;break;}} + });this.shots=this.shots.filter(function(s){return s.life>0;}); + if(this.superT>0&&this.superKind==='beam'){var beam=C.box(this.x+this.facing*12,this.centre().y,24,2.25);targets.forEach(function(t){if(B.overlap(beam,t.box)&&!self.exHits[t.id]){self.exHits[t.id]=true;b.onNailHit(c,87,'side',self.facing,t.id);}});} + if(this.superT>0&&this.superKind==='bomb_morph'&&targets.some(function(t){return B.overlap(t.box,hb);})){this.explode(c);} + if(this.hp<=0||b.st==='dead')return; + // v5 hazard flags (never set by the first three cases): noCount = a progress parry that does not count toward the + // parry total (source: the slot-machine lever), onParry(c) = the boss reacts to it, harmless = touching it unparried + // does no damage (a lever is an object, not a projectile). + var hz=b.hazards();for(var k=0;k0){if(h.ref)h.ref.removed=true;this.parryT=0;this.meter=Math.min(5,this.meter+1);if(!h.noCount)this.parries++;if(!this.plane){this.vy=16;this.grounded=false;this.airDash=false;if(this.onPlat!==undefined)this.onPlat=null;}if(h.onParry)h.onParry(c);c.emit('cup_parry',this.x,this.centre().y);continue;} + if(h.harmless)continue; + if(this.hurt(c,h.dmg||1,h.fromX)){c.events.push({t:c.t,name:'hurt_by',by:h.kind});break;} + } + }; + Cup.prototype.hurt=function(c,dmg){if(this.invul>0||this.hp<=0)return false;this.hp=Math.max(0,this.hp-dmg);this.invul=1.2;c.emit('player_hit',this.x,this.y);return true;}; + Cup.prototype.state=function(){return C.snapshot({x:B.r4(this.x),y:B.r4(this.y),vx:B.r4(this.vx),vy:B.r4(this.vy),hp:this.hp,max_hp:3,facing:this.facing,grounded:this.grounded,crouch:this.crouch,shrink:this.shrink,weapon:this.weapon,invul:B.r4(this.invul),dash:B.r4(this.dashT),dash_cd:B.r4(this.dashCd),dash_facing:this.dashF,air_dash:this.airDash,drop_left:B.r4(this.dropT),parry:B.r4(this.parryT),parries:this.parries,meter:B.r4(this.meter),aim:this.aim,super:this.superKind,super_left:B.r4(this.superT),shot_cd:B.r4(this.shotCd),ex_cd:B.r4(this.exCd),shots:this.shots,previous:this.prev,next_shot:this.nextShot,super_hits:this.exHits,on_platform:this.onPlat});}; + B.Cup=Cup;B.CupPlane=Plane; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/bosses/cagney.js b/environments/games/web/games/cuphead_remake/bosses/cagney.js new file mode 100644 index 0000000000000000000000000000000000000000..14f7a54ad0bf62b807e524f009b64d4f98996851 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/bosses/cagney.js @@ -0,0 +1,97 @@ +(function(g){var B=g.BB,BB=B,C=B.CUP; + // Cagney Carnation (Floral Fury), source: cuphead.wiki.gg "Cagney Carnation" oldid=67692 (2026-07-31). Ground fight + // with three thin floating platforms. Phase 1 HP 1000/702/810; phase 2 -/598/690 (Simple ends after phase 1: "he will + // simply pull on his petals without spreading his thorny vines"). + // Phase 1 Lunge: face and arms lash along the upper (platform) or lower (floor) lane; dodge by getting on or off the + // platforms; Expert "much less of a delay". + // Magic Hands: one boomerang sycamore seed (across over the platforms, back under them) or three acorns + // "shot out from top to bottom, moving toward where the player(s) was" (Expert four); chains up to three + // (Simple two); Simple slower, Expert much faster. + // Seed Gatling: blue -> homing Toothy Terror Chaser (4/4/10 HP), purple -> ground Baby Toothy Terror + // (5/5/8 HP, never on Expert), pink -> parryable seed that grows a Toothy Terror Floater (3/4/4 HP, max one, + // Expert rarely two, extra pink seeds become chasers) firing parryable pink bullets; the Floater can only be + // shot while it attacks. Simple seeds fall slower. + // Sub-phases: Simple lunge only -> lunge + Gatling (each volley opens with three purple seeds) -> Magic Hands + // only -> Gatling with blue/pink only; Expert rapid Gatling only -> Magic Hands / lunge alternating. + // Phase 2 The floor turns to thorns (stand on the platforms); dandelion pollen drifts across (Expert slower, so it + // stays longer); vines grow under 1-2 platforms and briefly encase them (Expert grow faster); every Toothy + // Terror but the Floaters disappears. + // Speeds, timings, lanes and boxes are engineering values (the page has no frame data); see + // Platforms sit 2.4 u up so a jump from the floor (apex 2.91 u) reaches them; the two lanes are a standing player's + // centre on a platform (high) and on the floor (low). + var PLATS=[{id:'p0',x:5.4,y:2.4,w:3.4},{id:'p1',x:9.6,y:2.4,w:3.4},{id:'p2',x:13.8,y:2.4,w:3.4}],LANE_HIGH=3.15,LANE_LOW=.75; + function Cagney(){} Cagney.prototype.id='cagney';Cagney.prototype.spec=B.SPECS.cagney; + Cagney.prototype.role=function(){return /antic|transition/.test(this.st)?'telegraph':this.st==='rest'||this.st==='dead'?'recovery':'active';}; + Cagney.prototype.reset=function(c){C.init(this,c,[[1000,702,810]].concat(C.mode(c.d)?[[0,598,690]]:[]));this.x=23.5;this.y=0;this.st='rest';this.timer=1.4; + this.chain=0;this.maxChain=0;this.cycle=0;this.lungeHigh=false;this.attack=null;this.fireT=0;this.seedQueue=[];this.vineT=2.2;this.vines={};this.pollenT=1.2;}; + Cagney.prototype.platforms=function(){var v=this.vines;return PLATS.map(function(p){return {id:p.id,x:p.x,y:p.y,w:p.w,vine:v[p.id]?v[p.id].st:null};});}; + Cagney.prototype.bodyBox=function(){return C.box(this.x,5.25,3,9.5);}; + Cagney.prototype.floaterCount=function(){return this.projectiles.filter(function(p){return p.kind==='floater'&&!p.removed;}).length;}; + Cagney.prototype.onNailHit=function(c,dmg,d,f,tid){var old=this.phase,keep=this.projectiles.filter(function(p){return p.kind==='floater'&&!p.removed;}),k=C.damage(this,c,dmg,tid); + if(this.phase!==old){this.projectiles=keep;this.timer=1.6;this.vineT=2.2;this.pollenT=1.2;this.vines={};this.move='transform';c.emit('flower_transform',this.x,6);}return k;}; + // share of phase-1 HP still left: drives the Simple / Expert sub-phase schedules (source) + Cagney.prototype.p1Left=function(){return this.phase?0:this.phaseHp/this.parts[0];}; + Cagney.prototype.schedule=function(){var m=this.mode,f=this.p1Left(); + if(m===0)return f>.75?'lunge_only':f>.5?'lunge_gatling':f>.25?'hands_only':'gatling_bp'; + return m===2?(f>.5?'gatling_rapid':'hands_lunge'):'mixed';}; + Cagney.prototype.pick=function(c){var s=this.schedule();this.cycle++; + if(s==='lunge_only')return 'lunge';if(s==='hands_only')return 'hands';if(s==='gatling_bp'||s==='gatling_rapid')return 'gatling'; + if(s==='lunge_gatling')return this.cycle%2?'lunge':'gatling';if(s==='hands_lunge')return this.cycle%2?'hands':'lunge'; + var r=c.rng.random();return r<.36?'lunge':r<.7?'hands':'gatling';}; + Cagney.prototype.begin=function(c){var m=this.mode,s=this.schedule();this.attack=this.pick(c);this.move=this.attack;this.chain=0; + if(this.attack==='lunge'){this.lungeHigh=c.body.y>1.2;this.st='lunge_antic';this.timer=[1,.8,.55][m];c.emit('flower_lunge_antic',this.x,this.lungeHigh?LANE_HIGH:LANE_LOW);} + else if(this.attack==='hands'){this.maxChain=1+c.rng.int(m===0?2:3);this.st='hands_antic';this.timer=[1,.8,.6][m];c.emit('flower_hands_antic',this.x,7);} + else{var q=s==='lunge_gatling'?['purple','purple','purple']:[],n=[3,4,4][m]; + while(q.length=(m===2&&c.rng.chance(.15)?2:1))kind='blue'; + if(kind==='blue')C.projectile(this,{kind:'chaser',x:p.x,y:.8,vx:0,vy:3,home:true,homeDelay:[.9,.6,.4][m],homeEnd:0,speed:[3.2,4,5][m],turn:[.9,1.3,1.8][m],hp:[4,4,10][m],r:.42,life:7}); + else if(kind==='purple')C.projectile(this,{kind:'baby_terror',x:p.x,y:.45,vx:0,vy:0,walk:[2,2.6,3][m],hp:[5,5,8][m],r:.45,life:30}); + else C.projectile(this,{kind:'floater',x:B.clamp(p.x,2,19),y:12.6,vx:2.2,vy:0,hp:[3,4,4][m],r:.6,life:9999,fire:2.2}); + c.emit('flower_sprout',p.x,0);}; + Cagney.prototype.hands=function(c){var m=this.mode; + if(c.rng.chance(.5))C.projectile(this,{kind:'sycamore',x:23,y:LANE_HIGH,vx:0,vy:0,r:.55,life:20,dur:[4.2,3.4,2.6][m],t:0}); + else for(var a=0,n=m===2?4:3;a0){p.hold-=dt;p.vx=p.vy=0;if(p.hold<=0){var ax=bc.x-p.x,ay=bc.y-p.y,ad=Math.hypot(ax,ay)||1;p.vx=ax/ad*p.speed;p.vy=ay/ad*p.speed;}} + if(p.kind==='baby_terror')p.vx=(bc.x19&&p.vx>0)p.vx=-p.vx;p.fire-=dt;if(p.fire<=0){var fx=bc.x-p.x,fy=bc.y-p.y,fd=Math.hypot(fx,fy)||1,sp=[5,6,6.5][m];C.projectile(self,{kind:'floater_shot',x:p.x,y:p.y-.5,vx:fx/fd*sp,vy:fy/fd*sp,r:.28,pink:true,life:5});p.fire=[3.2,2.6,2.2][m];c.emit('flower_floater_shot',p.x,p.y);}} + if(p.kind==='sycamore'){p.t+=dt;var u=p.t/p.dur;if(u>=1)p.removed=true;else{p.x=u<.5?23-u*50:-2+(u-.5)*50;p.y=u<.5?LANE_HIGH:LANE_LOW;}} + if(p.kind==='pollen'){p.wob+=dt;p.vy=Math.cos(p.wob*2.2)*1.4;} + }); + C.stepProjectiles(this,c); + this.projectiles.forEach(function(p){if(p.kind==='chaser'&&p.y<.4)p.y=.4;}); + if(this.st==='dead')return; + if(this.st==='transition'){if(this.timer<=0){this.st='p2';this.phaseT=0;}return;} + if(this.phase===1){this.st='p2';this.move='pollen';this.pollenT-=dt;this.vineT-=dt; + if(this.pollenT<=0){C.projectile(this,{kind:'pollen',x:this.x-2.2,y:c.rng.uniform(1.5,11),vx:-[0,4.6,3.4][m],vy:0,r:.42,life:[0,7,9.5][m],wob:c.rng.uniform(0,6),pink:c.rng.chance(1/3)});this.pollenT=[0,2,1.7][m];c.emit('flower_pollen',this.x,8);} + Object.keys(this.vines).forEach(function(k){var v=self.vines[k];v.t-=dt;if(v.t<=0){if(v.st==='grow'){v.st='encased';v.t=1.6;c.emit('flower_vine',0,0);}else delete self.vines[k];}}); + if(this.vineT<=0&&!Object.keys(this.vines).length){var n=c.rng.chance(.5)?2:1,free=PLATS.map(function(p){return p.id;}).filter(function(id){return !self.vines[id];});n=Math.min(n,free.length-1); + for(var j=0;j0&&!p.removed&&(p.kind!=='floater'||p.fire<.7))a.push({id:String(p.id),box:C.box(p.x,p.y,p.r*2,p.r*2)});});return a;}; + Cagney.prototype.state=function(){return C.state(this,{schedule:this.schedule(),attack:this.attack,chain:this.chain,max_chain:this.maxChain,lunge_high:this.lungeHigh,fire_time:B.r4(this.fireT),seed_queue:this.seedQueue,vines:this.vines,vine_time:B.r4(this.vineT),pollen_time:B.r4(this.pollenT),cycle:this.cycle,next_projectile:this.nextId});}; + B.CAGNEY_PLATS=PLATS; + BB.CASES['cuphead/cagney'] = {title:'Seed Bloom',Body:B.Cup,Boss:Cagney,arena:'flowers'}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/bosses/goopy.js b/environments/games/web/games/cuphead_remake/bosses/goopy.js new file mode 100644 index 0000000000000000000000000000000000000000..9d879862cea579b9e51579169fd5a6b2728b41e6 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/bosses/goopy.js @@ -0,0 +1,29 @@ +(function(g){var B=g.BB,BB=B,C=B.CUP; + function Goopy(){} Goopy.prototype.id='goopy';Goopy.prototype.spec=B.SPECS.goopy; + Goopy.prototype.role=function(){return /antic|transform|transition/.test(this.st)?'telegraph':/bounce|punch|slam/.test(this.st)?'active':this.st==='wait'?'recovery':'idle';}; + Goopy.prototype.reset=function(c){C.init(this,c,[[440,288,336],[560,540,560]].concat(C.mode(c.d)?[[0,372,504]]:[]));this.x=19;this.y=0;this.f=-1;this.vx=this.vy=0;this.bounces=0;this.passes=0;this.passGoal=3;this.slamX=19;this.firstPunch=true;this.questionSpawned=false;this.high=false;}; + Goopy.prototype.radius=function(){return this.phase===0?1.35:2.15;}; + Goopy.prototype.bodyBox=function(){if(this.phase===2)return C.box(this.x,2.5,2.3,2.7);return C.box(this.x,this.y+this.radius(),this.radius()*2,this.radius()*2);}; + Goopy.prototype.hitTargets=function(){return this.st==='transition'||this.st==='dead'?[]:C.targets(this,this.bodyBox());}; + Goopy.prototype.onNailHit=function(c,dmg,dir,f,tid){var phase=this.phase,k=C.damage(this,c,dmg,tid);if(this.phase!==phase){this.vx=this.vy=0;this.y=0;this.firstPunch=true;this.questionSpawned=false;if(this.phase===1){for(var j=-1;j<=1;j++)C.projectile(this,{kind:'question',x:this.x+j*1.5,y:4.7,vx:j*.4,vy:.08,r:.43,pink:true,life:7});this.questionSpawned=true;}else{this.passes=0;this.passGoal=this.mode===2?1:2+c.rng.int(2);}}return k;}; + // v2 (source: Expert "higher acceleration when jumping, and he falls faster"): Expert gravity x1.35 with the launch + // speed scaled by sqrt(1.35), so both jump heights keep their apex but the airtime is shorter. + Goopy.prototype.gravity=function(){return 35*[1,1,1.35][this.mode];}; + Goopy.prototype.launch=function(c){var high=this.mode===0&&this.phase===0?false:c.rng.chance(.5);this.vx=this.f*[7,8.5,10][this.mode]*(this.phase?1.1:1);this.vy=(high?19:14.5)*Math.sqrt(this.gravity()/35);this.high=high;this.st='bounce';this.move='bounce';this.timer=3;this.bounces++;c.emit('boss_bounce',this.x,this.y);}; + Goopy.prototype.update=function(c){var dt=B.DT;this.hitFlash=Math.max(0,this.hitFlash-dt);this.timer-=dt;this.stT+=dt;this.phaseT+=dt;C.stepProjectiles(this,c);if(this.st==='dead')return; + if(this.st==='transition'){if(this.timer<=0){this.st='wait';this.timer=.8;this.y=0;}return;} + if(this.phase===2){this.move='tombstone';if(this.st==='slam_antic'){this.x+=(this.slamX-this.x)*Math.min(1,dt*9);if(this.timer<=0){this.x=this.slamX;this.st='slam';this.timer=.35;c.emit('boss_slam',this.x,0);c.shake(.4);}} + else if(this.st==='slam'){if(this.timer<=0){this.st='slide';this.timer=8;this.passes=0;this.passGoal=this.mode===2?1+c.rng.int(2):2+c.rng.int(2);}} + else{this.st='slide';this.x+=this.f*[8,10,12][this.mode]*dt;if(this.x<2||this.x>25){this.x=B.clamp(this.x,2,25);this.f=-this.f;this.passes++;}if(this.passes>=this.passGoal){this.st='slam_antic';this.timer=[.8,.65,.5][this.mode];this.slamX=c.body.x;c.emit('boss_slam_antic',this.slamX,0);}} + return; + } + if(this.st==='idle'||this.st==='wait'){if(this.timer<=0){if(this.bounces>=2&&c.rng.chance(.35)){this.f=c.body.x27-r){this.x=B.clamp(this.x,r,27-r);if(this.vy>0){this.vx=-this.vx;this.f=this.vx>0?1:-1;}else this.vx=0;} + if(this.y<=0){this.y=0;this.vx=this.vy=0;this.st='wait';this.timer=(c.rng.chance(.22)?.7:.25)*[1.3,1,.8][this.mode]*(this.phase?1.15:1);c.emit('boss_land',this.x,0);}} + else if(this.st==='punch_antic'&&this.timer<=0){this.st='punch';this.timer=.33;this.firstPunch=false;c.emit('boss_punch',this.x,1);} + else if(this.st==='punch'&&this.timer<=0){this.st='wait';this.timer=.7;} + }; + Goopy.prototype.hazards=function(){if(this.st==='dead')return [];var a=C.hazards(this);if(this.phase!==2){a.push({kind:'goopy_body',circle:[this.x,this.y+this.radius(),this.radius()]});if(this.st==='punch')a.push({kind:'glove',box:C.box(this.x+this.f*(this.phase?4:2.5),1.3,this.phase?6.5:3.8,1.15)});}else if(this.st==='slam')a.push({kind:'tombstone_slam',box:C.box(this.slamX,4,3.2,8)});return a;}; + Goopy.prototype.state=function(){return C.state(this,{vx:B.r4(this.vx),vy:B.r4(this.vy),facing:this.f,bounces:this.bounces,passes:this.passes,pass_goal:this.passGoal,slam_x:this.slamX,first_punch:this.firstPunch,question_spawned:this.questionSpawned,high_jump:!!this.high,st_time:B.r4(this.stT),next_projectile:this.nextId});}; + B.CASES=B.CASES||{};BB.CASES['cuphead/goopy'] = {title:'Bouncing Blob',Body:B.Cup,Boss:Goopy,arena:'forest'}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/bosses/hilda.js b/environments/games/web/games/cuphead_remake/bosses/hilda.js new file mode 100644 index 0000000000000000000000000000000000000000..57597d6232ff16d20e8e9afb2c33276098a9fd83 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/bosses/hilda.js @@ -0,0 +1,36 @@ +(function(g){var B=g.BB,BB=B,C=B.CUP; + function Hilda(){}Hilda.prototype.id='hilda';Hilda.prototype.spec=B.SPECS.hilda;Hilda.prototype.role=function(){return /antic|transition/.test(this.st)?'telegraph':this.st==='rest'?'recovery':this.st==='dead'?'recovery':'active';}; + Hilda.prototype.reset=function(c){var parts=[[220,130,150],[550,468,450],[440,338,390],[550,468,480],[440,312,360]];if(C.mode(c.d)!==0)parts.push([0,884,1170]);C.init(this,c,parts);this.x=23;this.y=8;this.f=-1;this.form='normal';this.constellations=[this.mode===2?'gemini':'taurus',this.mode===0?'gemini':this.mode===2?'sagittarius':c.rng.chance(.5)?'gemini':'sagittarius'];this.fireT=1.8;this.minionT=2.2;this.tornadoT=4;this.purple=0;this.attackT=1;this.targetY=7;this.angle=0;this.vortexX=5;this.faceT=0;this.faceOut=false;this.ufoT=1.5;this.starT=1;this.st='normal';}; + Hilda.prototype.bodyBox=function(){return this.form==='moon'?C.box(this.faceOut?21.7:24,7.8,this.faceOut?7.2:3.9,12.5):this.form==='taurus'?C.box(this.x,this.y,4.1,3.6):C.box(this.x,this.y,3.8,4);}; + Hilda.prototype.hitTargets=function(){return this.st==='transition'||this.st==='dead'?[]:C.targets(this,this.bodyBox());}; + Hilda.prototype.onNailHit=function(c,dmg,d,f,tid){var old=this.phase,k=C.damage(this,c,dmg,tid);if(this.phase!==old){this.form=this.phase===5?'moon':this.phase%2?this.constellations[(this.phase-1)/2]:'normal';this.attackT=1.3;this.fireT=1.8;this.minionT=2.2;this.tornadoT=3;this.faceT=0;this.faceOut=false;this.x=23;this.y=8;this.angle=0;this.ufoT=1.5;this.starT=1;}return k;}; + // v2 minion mix (source "In-between Transformations"): Simple/Regular phase 1 purple only, after the 1st transformation + // purple + increasingly many green, after the 2nd green stops and purple come in pairs; Expert greens also in phase 1, + // only green after the 1st transformation, green paired with purple after the 2nd. + Hilda.prototype.minionKinds=function(c){var m=this.mode,ph=this.phase;if(ph===0)return m===2?[c.rng.chance(.5)?'green':'purple']:['purple']; + if(ph===2)return m===2?['green']:[c.rng.chance(Math.min(.65,.3+this.phaseT/40))?'green':'purple'];return m===2?['green','purple']:['purple','purple'];}; + Hilda.prototype.minions=function(c){var kinds=this.minionKinds(c),self=this;kinds.forEach(function(k,i){var green=k==='green';C.projectile(self,{kind:green?'green_plane':'purple_plane',x:28+i*1.4,y:c.rng.uniform(2,13),vx:-4.4,vy:0,r:.55,hp:10,life:8,fire:.8,green:green});});}; + Hilda.prototype.update=function(c){var dt=B.DT,self=this;this.timer-=dt;this.phaseT+=dt;this.stT+=dt;this.hitFlash=Math.max(0,this.hitFlash-dt); + this.projectiles.slice().forEach(function(p){if(/_plane$/.test(p.kind)){p.fire-=dt;if(p.fire<=0){p.fire=99;if(p.green){var n=[3,4,5][self.mode];for(var j=0;j=2&&this.tornadoT<=0){C.projectile(this,{kind:'tornado',x:this.x-1,y:this.y,vx:-6,vy:0,r:.8,home:true,homeEnd:0,speed:[5,6,7][this.mode],turn:.7,life:4.5});this.tornadoT=6;this.move='tornado';c.emit('zodiac_tornado',this.x,this.y);} + }else if(this.form==='taurus'){if(this.st==='taurus'||this.st==='rest'){this.y+=(c.body.y-this.y)*Math.min(1,dt*3);if(this.attackT<=0){this.targetY=this.y;this.st='horn_antic';this.timer=.65;this.move='horn_jab';c.emit('zodiac_horn_antic',this.x,this.y);}} + else if(this.st==='horn_antic'&&this.timer<=0){this.st='horn';this.timer=.55;c.emit('zodiac_horn',this.x,this.targetY);} + else if(this.st==='horn'&&this.timer<=0){this.st='rest';this.attackT=1.1;} + }else if(this.form==='gemini'){this.st='gemini';this.y=8;var period=this.mode===2?3.8:5;if(this.attackT<=0){this.st='vortex';this.vortexX=c.body.x<13.5?6:17;this.angle=0;this.fireT=0;this.attackT=period+1.7;this.move='rotating_vortex';c.emit('zodiac_vortex',this.vortexX,8);} + // v2: one full rotation then the vortex vanishes; Expert rotates faster (source). + if(this.attackT>1.7){this.angle+=dt*Math.PI*2/period;if(this.fireT<=0){var a=this.angle;for(var j=0;j<3;j++)C.projectile(this,{kind:'vortex_bullet',x:this.vortexX+Math.cos(a)*(.55+j*.58),y:8+Math.sin(a)*(.55+j*.58),vx:Math.cos(a)*7,vy:Math.sin(a)*7,r:.22,life:5});this.fireT=.14;}} + }else if(this.form==='sagittarius'){this.y=8+Math.sin(this.phaseT)*2;if(this.attackT<=0&&this.st!=='arrow_antic'){this.st='arrow_antic';this.timer=.7;this.targetY=c.body.y;this.move='arrow_stars';this.attackT=3.6;c.emit('zodiac_arrow_antic',this.x,this.targetY);} + if(this.st==='arrow_antic'&&this.timer<=0){C.projectile(this,{kind:'arrow',x:21,y:this.targetY,vx:-18,vy:0,r:.62,life:3});for(var k=0;k<3;k++)C.projectile(this,{kind:'blue_star',x:23+k*.5,y:this.y+(k-1)*1.3,vx:-5,vy:0,home:true,homeEnd:this.mode===2?1.5:3.5,speed:6.5,turn:1.1,hp:10,r:.4,life:7});this.st='sagittarius';}} + else{this.st='moon';this.x=24;this.y=8;this.faceT+=dt;this.faceOut=this.faceT%5>3.7;if(this.faceT%5>3.1&&this.faceT%5<3.7){this.move='moon_face';} + this.ufoT-=dt;this.starT-=dt;if(this.ufoT<=0){C.projectile(this,{kind:'ufo',x:29,y:c.rng.uniform(10.7,13.5),vx:-5.2,vy:0,r:.65,hp:9999,red:c.rng.chance(.5),life:8,beam:0});this.ufoT=this.mode===2?1.35:1.7;this.move='ufo_laser';} + if(this.starT<=0){C.projectile(this,{kind:'shooting_star',x:29,y:c.rng.uniform(1.5,13.5),vx:-9,vy:0,speed:this.mode===2?13:9,r:.34,pink:c.rng.chance(.18),life:5});this.starT=this.mode===2?.5:.7;}} + }; + Hilda.prototype.hazards=function(){if(this.st==='dead')return [];var a=C.hazards(this);if(this.st!=='transition')a.push({kind:this.form+'_body',box:this.bodyBox()});if(this.st==='horn')a.push({kind:'horn_jab',box:C.box(12,this.targetY,24,1.25)});return a;}; + Hilda.prototype.state=function(){return C.state(this,{form:this.form,constellations:this.constellations,fire_time:B.r4(this.fireT),minion_time:B.r4(this.minionT),tornado_time:B.r4(this.tornadoT),purple_count:this.purple,attack_time:B.r4(this.attackT),target_y:B.r4(this.targetY),vortex_x:this.vortexX,angle:B.r4(this.angle),face_time:B.r4(this.faceT),face_out:this.faceOut,ufo_time:B.r4(this.ufoT),star_time:B.r4(this.starT),next_projectile:this.nextId});}; + BB.CASES['cuphead/hilda'] = {title:'Zodiac Shifter',Body:B.CupPlane,Boss:Hilda,arena:'sky'}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/bosses/ribby_croaks.js b/environments/games/web/games/cuphead_remake/bosses/ribby_croaks.js new file mode 100644 index 0000000000000000000000000000000000000000..00ba05efe8dc63306596775fec0761d533a02605 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/bosses/ribby_croaks.js @@ -0,0 +1,116 @@ +(function(g){var B=g.BB,BB=B,C=B.CUP; + // Ribby and Croaks (Clip Joint Calamity), source: cuphead.wiki.gg "Ribby and Croaks" oldid=67707 (2026-07-31). + // HP 1400/1700/1900: phase 1 546/408/494, phase 2 854/714/741, phase 3 (slot machine) -/578/665 (Simple ends after + // phase 2: "Croaks pounding his fists to the floor, and Ribby crying"). Both frogs take hits for one shared total. + // Phase 1 Both frogs on the right. Croaks spits fireflies (4 HP; they "slowly inch closer"); Ribby throws fist + // waves low / middle / high, reversing after the third, some parryable; the whole pattern twice (Simple and + // Expert once: Simple slower, Expert faster). Expert: both attack in unison. Ends with Ribby rolling across + // the floor at the player (Simple slower, Expert faster) and coming back on the left. + // Phase 2 Pincer: Ribby (left) slaps three bouncing ringed balls toward the player; Croaks (right) spins as a fan, + // blowing the player toward Ribby (escape by running or dashing; Expert faster balls, stronger wind). Simple + // and Expert Ribby also throws non-reversing fist sets, alternating with 1-3 ball slaps. Ends with Ribby rolling + // across the floor into Croaks' mouth. + // Phase 3 Slot machine: "initially invulnerable", spews coins; parrying its lever (not counted toward the parry + // total) makes it vulnerable and spins the reels; its hatch then fires spiked chips: Tiger (orange, a ball + // bouncing out of the centre: jump over it or go under it), Snake (green, low, must be jumped on, sides hurt, + // accelerating), Bison (red, float mid-screen, then a fire jet in an indicated direction); spawn rate rises; + // Expert more coins, faster chips. + // Conflict: Simple phase-1 HP 546 exceeds Regular 408 (infobox and text agree, totals add up): kept as written. + // Approximations (not documented): the lever drops after 2 coins (Expert 4: a strategy guide) and stays down until + // parried; the machine stays vulnerable after the first parry ("initially invulnerable"); one chip round ~9-10 s. + // Speeds, timings, heights and boxes are engineering values. + var FIST_Y=[.7,1.75,2.9],LEVER={x:20.4,y:3.4},HATCH=21.2; + function Frogs(){} Frogs.prototype.id='ribby_croaks';Frogs.prototype.spec=B.SPECS.ribby_croaks; + Frogs.prototype.role=function(){return /transition|roll/.test(this.st)||this.leverDown?'telegraph':this.st==='dead'?'recovery':'active';}; + Frogs.prototype.reset=function(c){C.init(this,c,[[546,408,494],[854,714,741]].concat(C.mode(c.d)?[[0,578,665]]:[]));this.x=21;this.y=0; + this.st='p1';this.timer=1.4;this.turn='croaks';this.fistSeq=[];this.fistT=0;this.flyT=0;this.flies=0;this.roll=null; + this.ribbyX=18.6;this.croaksX=23.4;this.fan=0;this.fanT=2.2;this.ribbyT=1.4;this.ribbyMode='balls'; + this.slot='closed';this.slotT=1.6;this.coins=0;this.leverDown=false;this.opened=false;this.reel=null;this.chipT=0;this.rounds=0;}; + Frogs.prototype.ribbyBox=function(){return this.roll?C.box(this.roll.x,.8,1.8,1.6):C.box(this.ribbyX,1.7,2.2,3.4);}; + Frogs.prototype.croaksBox=function(){return C.box(this.croaksX,2.3,3.4,4.6);}; + Frogs.prototype.slotBox=function(){return C.box(23.9,4.4,5,8.8);}; + // chips are thin platforms the player may stand on (and is carried by); the frogs are not + Frogs.prototype.platforms=function(){return this.projectiles.filter(function(p){return p.chip&&!p.removed;}).map(function(p){return {id:'chip'+p.id,x:p.x,y:p.y+.3,w:p.w,vx:p.vx};});}; + Frogs.prototype.windAt=function(){return this.phase===1&&this.fan>0&&this.st==='p2'?-[3,3.6,4.8][this.mode]:0;}; + Frogs.prototype.hitTargets=function(){if(this.st==='dead'||this.st==='transition')return [];var a=[]; + if(this.phase<2){a.push({id:'boss',box:this.ribbyBox()});a.push({id:'croaks',box:this.croaksBox()});} + else if(this.opened)a.push({id:'boss',box:this.slotBox()}); + this.projectiles.forEach(function(p){if(p.hp>0&&!p.removed)a.push({id:String(p.id),box:C.box(p.x,p.y,p.r*2,p.r*2)});});return a;}; + Frogs.prototype.onNailHit=function(c,dmg,d,f,tid){var old=this.phase,k=C.damage(this,c,dmg,tid==='croaks'?'boss':tid),m=this.mode; + if(this.phase!==old){this.fistSeq=[];this.flies=0;this.fan=0;this.timer=.8; + if(this.phase===1){this.roll={x:this.ribbyX,vx:-[7,9,11][m],to:-2};this.move='roll';c.emit('frog_left_roll',this.ribbyX,1);} + else{this.roll={x:1.8,vx:[7,9,11][m],to:this.croaksX-1.2};this.move='roll_into_croaks';c.emit('frog_left_roll',1.8,1);}} + return k;}; + Frogs.prototype.fists=function(c,reverse){var seq=reverse?[0,1,2,2,1,0]:[0,1,2],reps=this.mode===1&&this.phase===0?2:1,out=[]; + for(var r=0;r0){p.jet-=dt;if(p.jet<=0)p.vx=-[0,5,6.5][m];}} + }); + C.stepProjectiles(this,c); + if(this.st==='dead')return; + if(this.st==='transition'||this.roll){this.st='transition'; + if(this.roll){this.roll.x+=this.roll.vx*dt;if(this.roll.vx<0?this.roll.x<=this.roll.to:this.roll.x>=this.roll.to){this.roll=null;this.timer=Math.max(this.timer,.6);if(this.phase===1)this.ribbyX=1.8;}} + if(!this.roll&&this.timer<=0){this.st=['p1','p2','p3'][this.phase];this.phaseT=0;this.ribbyT=1.2;this.fanT=1.6;this.slotT=1.2;} + return;} + if(this.phase===0)this.p1(c,dt);else if(this.phase===1)this.p2(c,dt);else this.p3(c,dt); + }; + // phase 1: fireflies and the fist pattern take turns (Expert: together) + Frogs.prototype.p1=function(c,dt){var m=this.mode,busy=this.fistSeq.length>0||this.flies>0;this.st='p1'; + if(this.fistSeq.length){this.fistT-=dt;if(this.fistT<=0){this.throwFist(c);this.fistT=[.85,.62,.48][m];}} + if(this.flies>0){this.flyT-=dt;if(this.flyT<=0){C.projectile(this,{kind:'firefly',x:this.croaksX-1.8,y:3.4,vx:-2,vy:.4,home:true,homeDelay:.5,homeEnd:0,speed:[1.5,1.9,2.4][m],turn:.9,hp:4,r:.4,life:14});this.flies--;this.flyT=.5;c.emit('frog_right_spit',this.croaksX,3.4);}} + if(busy&&!this.fistSeq.length&&this.flies<=0)this.timer=[1.6,1.3,1.1][m]; + if(busy||this.timer>0)return; + if(m===2){this.fists(c,true);this.flies=3;this.flyT=0;this.move='unison';} + else if(this.turn==='croaks'){this.flies=m===0?2:3;this.flyT=0;this.turn='ribby';this.move='firefly';} + else{this.fists(c,true);this.turn='croaks';this.move='fists';} + }; + // phase 2: Ribby (left) ball slaps, Simple/Expert alternating with fist sets; Croaks (right) fan wind + Frogs.prototype.p2=function(c,dt){var m=this.mode;this.st='p2'; + if(this.fan>0){this.fan-=dt;if(this.fan<=0)this.fanT=[3.2,2.6,2.2][m];}else{this.fanT-=dt;if(this.fanT<=0){this.fan=[2.4,2.8,3.2][m];c.emit('frog_right_fan',this.croaksX,3);}} + if(this.fistSeq.length){this.fistT-=dt;if(this.fistT<=0){this.throwFist(c);this.fistT=[.85,.62,.48][m];}return;} + this.ribbyT-=dt;if(this.ribbyT>0)return; + if(m!==1&&this.ribbyMode==='balls'){this.ribbyMode='fists';this.fists(c,false);this.ribbyT=1.4;this.move='fists';return;} + this.ribbyMode='balls';this.move='balls';var n=m===1?1:1+c.rng.int(3),sp=[3.4,4.2,5.2][m]; + for(var j=0;j spin -> open (chips + // for one round) -> closed. Vulnerable from the first parry on. + Frogs.prototype.p3=function(c,dt){var m=this.mode;this.st='slot_'+this.slot;this.slotT-=dt; + if(this.slot==='closed'){if(this.slotT<=0){C.projectile(this,{kind:'coin',x:HATCH,y:6.4,vx:-c.rng.uniform(3,9),vy:c.rng.uniform(.5,5),gravity:-9,r:.32,life:6});this.coins++;this.slotT=[0,1.3,.95][m];c.emit('slot_coin',HATCH,6.4); + if(!this.leverDown&&this.coins>=[0,2,4][m]){this.leverDown=true;c.emit('slot_lever_down',LEVER.x,LEVER.y);}}} + else if(this.slot==='spin'){if(this.slotT<=0){this.slot='open';this.slotT=[0,9,10][m];this.chipT=.3;this.rounds++;c.emit('slot_open',HATCH,1);}} + else{this.chipT-=dt;if(this.chipT<=0){var k=1-Math.max(0,this.slotT)/[1,9,10][m];this.chip(c);this.chipT=[0,2.1,1.7][m]*(1-.35*k);} + if(this.slotT<=0){this.slot='closed';this.slotT=1;this.coins=0;c.emit('slot_close',HATCH,4);}} + }; + Frogs.prototype.chip=function(c){var m=this.mode,sp=[0,4.2,5.4][m]; + if(this.reel==='tiger'){var ch=C.projectile(this,{kind:'chip_tiger',chip:true,x:HATCH,y:.3,vx:-sp,vy:0,w:2.4,r:.3,life:9});C.projectile(this,{kind:'tiger_ball',host:ch.id,x:HATCH,y:.9,vx:-sp,vy:[0,14,15][m],gravity:-20,bounce:[0,14,15][m],r:.5,life:9});} + else if(this.reel==='snake')C.projectile(this,{kind:'chip_snake',chip:true,x:HATCH,y:.3,vx:-sp*.9,vy:0,w:2.4,r:.3,life:12}); + else C.projectile(this,{kind:'chip_bison',chip:true,x:HATCH,y:c.rng.uniform(2.8,4.2),vx:-sp*1.2,vy:0,w:2.4,r:.3,life:14,stopX:c.rng.uniform(5,17),parked:false,fired:false,fireT:0,jet:0,jetUp:c.rng.chance(.5)}); + c.emit('slot_chip',HATCH,1);}; + Frogs.prototype.leverParried=function(c){this.leverDown=false;this.opened=true;this.slot='spin';this.slotT=1.4;this.reel=['tiger','snake','bison'][c.rng.int(3)];this.move='slot_'+this.reel;c.emit('slot_spin',23.9,6);}; + Frogs.prototype.hazards=function(){if(this.st==='dead')return [];var self=this,a=[]; + this.projectiles.forEach(function(p){if(p.removed)return; + if(p.chip){a.push({kind:p.kind+'_spikes',box:C.box(p.x-p.w/2,p.y,.34,.7),fromX:p.x},{kind:p.kind+'_spikes',box:C.box(p.x+p.w/2,p.y,.34,.7),fromX:p.x}); + if(p.jet>0)a.push({kind:'bison_jet',box:p.jetUp?C.box(p.x,(p.y+15)/2,1,15-p.y):C.box(p.x,p.y/2,1,p.y),fromX:p.x});return;} + a.push({kind:p.kind,circle:[p.x,p.y,p.r],pink:!!p.pink,ref:p,fromX:p.x});}); + if(this.roll)a.push({kind:'ribby_roll',box:C.box(this.roll.x,.8,1.8,1.6),fromX:this.roll.x}); + else if(this.phase<2&&this.st!=='transition'){a.push({kind:'ribby_body',box:C.box(this.ribbyX,1.7,2,3.4)});a.push({kind:'croaks_body',box:C.box(this.croaksX,2.3,3,4.6)});} + if(this.phase===2&&this.st!=='transition'){a.push({kind:'slot_body',box:C.box(24.1,4.4,4.6,8.8)}); + if(this.leverDown)a.push({kind:'slot_lever',box:C.box(LEVER.x,LEVER.y,1,1.4),pink:true,noCount:true,harmless:true,onParry:function(cc){self.leverParried(cc);}});} + return a;}; + Frogs.prototype.state=function(){return C.state(this,{turn:this.turn,fists:this.fistSeq,fist_time:B.r4(this.fistT),flies:this.flies,fly_time:B.r4(this.flyT),roll:this.roll,ribby_x:this.ribbyX,fan:B.r4(this.fan),fan_time:B.r4(this.fanT),ribby_time:B.r4(this.ribbyT),ribby_mode:this.ribbyMode,slot:this.slot,slot_time:B.r4(this.slotT),coins:this.coins,lever_down:this.leverDown,opened:this.opened,reel:this.reel,chip_time:B.r4(this.chipT),rounds:this.rounds,next_projectile:this.nextId});}; + B.RIBBY_GEOM={FIST_Y:FIST_Y,LEVER:LEVER,HATCH:HATCH}; + BB.CASES['cuphead/ribby_croaks'] = {title:'Boxing Frogs',Body:B.Cup,Boss:Frogs,arena:'club'}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/bosses/root_pack.js b/environments/games/web/games/cuphead_remake/bosses/root_pack.js new file mode 100644 index 0000000000000000000000000000000000000000..084aa23e2e92208e24a6f851f961584a683a9f04 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/bosses/root_pack.js @@ -0,0 +1,39 @@ +(function(g){var B=g.BB,BB=B,C=B.CUP; + function Root(){}Root.prototype.id='root_pack';Root.prototype.spec=B.SPECS.root_pack; + Root.prototype.role=function(){return /antic|transition|look/.test(this.st)?'telegraph':this.st==='rest'?'recovery':this.st==='dead'?'recovery':'active';}; + Root.prototype.reset=function(c){var simple=C.mode(c.d)===0;C.init(this,c,simple?[[450,360,400],[450,475,475]]:[[450,360,400],[0,400,425],[450,475,475]]);this.forms=simple?['potato','carrot']:['potato','onion','carrot'];this.x=23;this.y=0;this.shot=0;this.volley=0;this.fireT=.3;this.waveT=2;this.eyeCount=0;this.angry=false;this.secret=false;this.onionLocked=false;this.radishHp=0;this.radishX=13;this.radishF=-1;this.radishVx=0;this.radishT=0;this.carrotDead=false;this.st='spit_antic';this.timer=1;}; + Root.prototype.form=function(){return this.forms[this.phase];};Root.prototype.bodyBox=function(){return this.form()==='potato'?C.box(23,2.4,4.3,4.8):this.form()==='onion'?C.box(13.5,2.6,3.5,5.2):C.box(21,7.8,5.5,11);}; + Root.prototype.hitTargets=function(){if(this.st==='dead'||this.st==='transition')return [];var a=C.targets(this,this.carrotDead?null:this.bodyBox());if(this.radishHp>0)a.push({id:'radish',box:C.box(this.radishX,1.1,1.4,2.2)});return a;}; + Root.prototype.secretEnd=function(c){if(this.carrotDead&&this.radishHp<=0){this.hp=0;this.st='dead';this.projectiles=[];c.emit('boss_dead',this.x,7);}}; + Root.prototype.onNailHit=function(c,dmg,d,f,tid){if(this.st==='dead'||this.st==='transition')return null; + if(tid==='radish'){var dealt=Math.min(this.radishHp,dmg);this.radishHp-=dealt;this.hp-=dealt;this.secretEnd(c);return dealt?'flesh':null;} + if(this.secret&&tid==='boss'){if(this.carrotDead)return null;var dealt=Math.min(this.phaseHp,dmg);this.phaseHp-=dealt;this.hp-=dealt;this.hitFlash=.07;c.emit('boss_hit',this.x,8);if(this.phaseHp<=0){this.carrotDead=true;this.projectiles=[];}this.secretEnd(c);return 'flesh';} + if(this.form()==='onion'){if(this.onionLocked&&this.secret)return null;if(!this.angry){this.angry=true;this.st='cry';this.fireT=.8;c.emit('onion_cry',13.5,4);}} + var old=this.phase,k=C.damage(this,c,dmg,tid);if(old!==this.phase){this.shot=this.volley=0;this.phaseT=0;this.fireT=1;this.waveT=2;this.eyeCount=0;}return k;}; + Root.prototype.update=function(c){var dt=B.DT;this.hitFlash=Math.max(0,this.hitFlash-dt);this.timer-=dt;this.phaseT+=dt;this.stT+=dt;C.stepProjectiles(this,c);if(this.st==='dead')return; + if(this.radishHp>0){this.radishT+=dt;if(this.radishT>(this.mode===2?.5:.8)){this.radishF=c.body.xcount){this.volley=(this.volley+1)%3;this.st='rest';this.timer=1.1;}}} + if(this.st==='rest'&&this.timer<=0){this.st='spit_antic';this.timer=.5;this.move='dirt_worm';} + }else if(form==='onion'){if(this.st==='look'&&this.phaseT>=6&&!this.angry){this.onionLocked=true;this.secret=true;this.radishHp=C.HORACE_HP[this.mode];this.phase++;this.phaseHp=this.parts[this.phase];this.max_hp=this.parts[0]+this.phaseHp+this.radishHp;this.hp=this.phaseHp+this.radishHp;this.st='transition';this.timer=1.4;this.phaseT=0;c.emit('root_secret',13.5,4);return;} + if(this.angry){this.st='cry';this.move='tears';this.fireT-=dt;if(this.fireT<=0){var n=this.mode===2?3:2;for(var j=0;j=(this.mode===1?3:2)){this.st='carrots';this.waveT=4.5;}}} + else if(this.st==='carrots'&&this.fireT<=0){var count=[2,3,4][this.mode];for(var k=0;k0)a.push({kind:'horace_radish',box:C.box(this.radishX,1.1,1.4,2.2)});return a;}; + // Scoring only: keep original combat HP, secret-route mechanics and victory rules. + Root.prototype.rewardObjective=function(){ + var total=this.parts.reduce(function(a,b){return a+b;},0),completed; + if(this.secret){ + completed=this.parts[0]+this.parts[1]*(1-this.radishHp/C.HORACE_HP[this.mode])+this.parts[2]-this.phaseHp; + }else completed=total-this.hp; + return {version:'root-pack-fixed-phase@1',progress:B.clamp(completed/total,0,1),total:total,phase_weights:this.parts.slice()}; + }; + Root.prototype.state=function(){return C.state(this,{reward_objective:this.rewardObjective(),form:this.form(),forms:this.forms,shot:this.shot,volley:this.volley,fire_time:B.r4(this.fireT),wave_time:B.r4(this.waveT),eye_count:this.eyeCount,angry:this.angry,secret:this.secret,onion_locked:this.onionLocked,radish_hp:B.r4(this.radishHp),radish_x:B.r4(this.radishX),radish_facing:this.radishF,radish_vx:this.radishVx,radish_time:B.r4(this.radishT),carrot_dead:this.carrotDead,next_projectile:this.nextId});}; + BB.CASES['cuphead/root_pack'] = {title:'Garden Trio',Body:B.Cup,Boss:Root,arena:'garden'}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/bosses/wally.js b/environments/games/web/games/cuphead_remake/bosses/wally.js new file mode 100644 index 0000000000000000000000000000000000000000..92b7c31f819793d25bf208eff106aa3ff7f4797f --- /dev/null +++ b/environments/games/web/games/cuphead_remake/bosses/wally.js @@ -0,0 +1,91 @@ +(function(g){var B=g.BB,BB=B,C=B.CUP; + // Wally Warbles (Aviary Action!), source: cuphead.wiki.gg "Wally Warbles" oldid=67703 (2026-07-31) and its + // "Willy Warbles" page. Plane fight. HP 2000/2400/2800: + // phase 1 before the whistle 1000/600/700, after the whistle 500/552/700, phase 2 (Willy) 500/552/532, + // phase 3 (stretcher) -/696/868 (Simple ends when Willy cries for help). + // Phase 1a Eggs flying straight that burst at the screen edge (Simple 2 fragments, Regular 3, Expert 5); Trigger + // Finger: three large bullets in a spread after a short delay (Simple longer delay / slower / wider, Expert + // shorter / faster / tighter). + // Phase 1b Steam whistle in rage, then radial bursts of eight feathers (never parryable), resting when tired + // (Simple longer rest, slower bursts; Expert shorter bursts, faster, quicker recovery). + // Throughout phase 1: rows of four nail birds (8 HP), the fourth always pink; near the top or the bottom; + // Simple rows of three that stop after the whistle; Expert from the start, faster, at the player's height. + // Phase 2 Willy floats around with orbiting spiked eggs (Simple 4, Regular 5, Expert 6) that block bullets and + // periodically expand / contract; an electric bullet at the player, always parryable. + // Phase 3 Wally on a stretcher carried by two paramedic birds, moving back and forth (Expert faster). Trash Talk + // (fish bone, mini bomb, apple core, magnet; occasionally a pink parryable boot; Expert longer), Heart Attack + // (the heart rises, fires a 3-bullet spread, Expert two; while it is out only the heart takes damage), + // paramedic pills that split with one half homing to the player's position (sometimes pink). Bombs reach him + // from above; he can be shot from below unless the stretcher is on the left. + // Conflict: the Willy page lists Simple HP 550, the Wally page 500 (Simple total 2000 = 1000+500+500): 500 kept. + // Speeds, timings, sizes and boxes are engineering values (the page has no frame data). + function Wally(){} Wally.prototype.id='wally';Wally.prototype.spec=B.SPECS.wally; + Wally.prototype.role=function(){return /antic|transition|whistle/.test(this.st)?'telegraph':this.st==='rest'||this.st==='tired'||this.st==='dead'?'recovery':'active';}; + Wally.prototype.reset=function(c){C.init(this,c,[[1000,600,700],[500,552,700],[500,552,532]].concat(C.mode(c.d)?[[0,696,868]]:[])); + this.x=22.5;this.y=7.5;this.st='rest';this.timer=1.6;this.atk=0;this.birdT=this.mode===2?1:4;this.birdRow=0; + this.burstN=0;this.burstT=0;this.featherA=0;this.willyX=18;this.willyY=7.5;this.willyT=0;this.eggR=1.6;this.eggA=0;this.eggPhase=0;this.zapT=2; + this.sx=17;this.sDir=1;this.trashT=2;this.heart=null;this.pillT=3;this.trash=0;}; + // phase 3: Wally lies on the stretcher; the paramedic birds at both ends block shots from the side, so he is reached + // with bombs from above (source: "Bombs are nearly required for this stage"); approximation of the documented layout + Wally.prototype.bodyBox=function(){if(this.phase<=1)return C.box(this.x,this.y,3.6,4.6);if(this.phase===2)return C.box(this.willyX,this.willyY,1.8,1.8);return C.box(this.sx+.3,5.4,3.4,1);}; + Wally.prototype.medics=function(){return [C.box(this.sx-2.5,4.9,1.3,2),C.box(this.sx+2.5,4.9,1.3,2)];}; + Wally.prototype.eggs=function(){var n=[4,5,6][this.mode],out=[];for(var k=0;k0&&!p.removed)a.push({id:String(p.id),box:C.box(p.x,p.y,p.r*2,p.r*2)});});return a;}; + // eggs block shots: consumed, no damage, no meter + Wally.prototype.onNailHit=function(c,dmg,d,f,tid){if(/^(egg|medic)/.test(tid))return 'block';var old=this.phase,k=C.damage(this,c,dmg,tid); + if(this.phase!==old){this.timer=1.6;this.atk=0;this.heart=null;this.move=['','whistle','willy','stretcher'][this.phase];c.emit('nest_transform',this.x,this.y); + if(this.phase===2){this.willyX=18;this.willyY=7.5;this.eggA=0;this.zapT=2;}if(this.phase===3){this.sx=17;this.trashT=2.2;this.pillT=3;}}return k;}; + Wally.prototype.birds=function(c){var m=this.mode,n=m===0?3:4,top=this.birdRow++%2===0,y=m===2?B.clamp(c.body.y,1.2,13.6):top?12.6:2.2,sp=[4.4,5.2,6.6][m]; + for(var k=0;k=.7){p.split=true;p.removed=true;var dx=bc.x-p.x,dy=bc.y-p.y,dd=Math.hypot(dx,dy)||1;C.projectile(self,{kind:'pill_half',x:p.x,y:p.y,vx:dx/dd*7,vy:dy/dd*7,r:.3,pink:p.pink,life:4});C.projectile(self,{kind:'pill_half',x:p.x,y:p.y,vx:0,vy:4.5,r:.3,life:3});}} + }); + C.stepProjectiles(this,c); + if(this.st==='dead')return; + if(this.st==='transition'){if(this.timer<=0){this.st='rest';this.timer=.6;}return;} + if(this.phase<=1){this.y=7.5+2.2*Math.sin(this.phaseT*.7);this.birdT-=dt;if(this.birdT<=0&&(m!==0||this.phase===0)){this.birds(c);this.birdT=[5,4.2,3.4][m];}} + if(this.phase===0)this.p1a(c,dt);else if(this.phase===1)this.p1b(c,dt);else if(this.phase===2)this.p2(c,dt);else this.p3(c,dt); + }; + Wally.prototype.p1a=function(c,dt){var m=this.mode,bc=c.body; + if(this.st==='rest'){if(this.timer<=0){this.atk++;if(this.atk%2){this.st='eggs';this.burstN=3;this.burstT=0;this.move='eggs';}else{this.st='finger_antic';this.timer=[1,.75,.55][m];this.move='finger';c.emit('nest_finger_antic',this.x,this.y);}}return;} + if(this.st==='eggs'){this.burstT-=dt;if(this.burstT<=0){C.projectile(this,{kind:'egg',x:this.x-2,y:this.y,vx:-[7,8.5,10][m],vy:0,r:.45,life:6});this.burstN--;this.burstT=.55;c.emit('nest_egg',this.x,this.y);}if(this.burstN<=0){this.st='rest';this.timer=[1.4,1.1,.9][m];}return;} + if(this.st==='finger_antic'&&this.timer<=0){var dx=bc.x-(this.x-2),dy=bc.y-this.y,a0=Math.atan2(dy,dx),sp=[6.5,8,10][m],spread=[.32,.24,.16][m]; + for(var k=-1;k<=1;k++)C.projectile(this,{kind:'big_bullet',x:this.x-2,y:this.y,vx:Math.cos(a0+k*spread)*sp,vy:Math.sin(a0+k*spread)*sp,r:.62,life:6}); + this.st='rest';this.timer=[1.6,1.2,1][m];c.emit('nest_finger',this.x,this.y);} + }; + Wally.prototype.p1b=function(c,dt){var m=this.mode; + if(this.st==='rest'){if(this.timer<=0){this.st='whistle';this.timer=1;this.move='whistle';c.emit('nest_whistle',this.x,this.y);}return;} + if(this.st==='whistle'){if(this.timer<=0){this.st='flap';this.timer=[3,3,2.3][m];this.burstT=0;}return;} + if(this.st==='flap'){this.burstT-=dt;if(this.burstT<=0){for(var k=0;k<8;k++){var a=this.featherA+k*Math.PI/4;C.projectile(this,{kind:'feather',x:this.x,y:this.y,vx:Math.cos(a)*5.5,vy:Math.sin(a)*5.5,r:.26,life:6});}this.featherA+=.2;this.burstT=[.75,.6,.45][m];c.emit('nest_feathers',this.x,this.y);} + if(this.timer<=0){this.st='tired';this.timer=[2.6,2,1.4][m];c.emit('nest_tired',this.x,this.y);}return;} + if(this.st==='tired'&&this.timer<=0){this.st='flap';this.timer=[3,3,2.3][m];this.burstT=0;} + }; + Wally.prototype.p2=function(c,dt){var m=this.mode,bc=c.body;this.st='willy';this.move='willy';this.willyT+=dt;var sp=[.55,.7,.9][m]; + this.willyX=16+4.5*Math.sin(this.willyT*sp);this.willyY=7.5+4*Math.sin(this.willyT*sp*1.6+.7); + var cyc=(this.willyT*[.35,.42,.5][m])%1,expand=cyc<.5,s=expand?(m===2?2.6:2):(m===2?1.4:1.8);this.eggPhase=cyc;this.eggR=1.4+1.6*Math.sin(cyc*Math.PI);this.eggA+=dt*s; + this.zapT-=dt;if(this.zapT<=0){var dx=bc.x-this.willyX,dy=bc.y-this.willyY,dd=Math.hypot(dx,dy)||1;C.projectile(this,{kind:'zap',x:this.willyX,y:this.willyY,vx:dx/dd*7.5,vy:dy/dd*7.5,r:.32,pink:true,life:5});this.zapT=[2.8,2.3,1.9][m];c.emit('chick_zap',this.willyX,this.willyY);} + }; + Wally.prototype.p3=function(c,dt){var m=this.mode,bc=c.body,self=this;this.st='stretcher';this.move='stretcher'; + this.sx+=this.sDir*[0,2.2,3.2][m]*dt;if(this.sx>21.5||this.sx<10){this.sDir=-this.sDir;this.sx=B.clamp(this.sx,10,21.5);} + if(this.heart){this.heart.t+=dt;var h=this.heart;h.y=h.t<.8?4.6+h.t*7:10.2;h.x=this.sx;if(h.t>=.9&&h.shots<(m===2?2:1)&&h.t>=.9+h.shots*.8){var dx=bc.x-h.x,dy=bc.y-h.y,a0=Math.atan2(dy,dx);for(var k=-1;k<=1;k++)C.projectile(this,{kind:'heart_bullet',x:h.x,y:h.y,vx:Math.cos(a0+k*.3)*6.5,vy:Math.sin(a0+k*.3)*6.5,r:.3,life:5});h.shots++;c.emit('nest_heart_shot',h.x,h.y);} + if(h.t>=(m===2?3:2.2))this.heart=null;} + this.trashT-=dt;if(this.trashT<=0&&!this.heart){if(this.trash<=0){this.trash=[0,6,9][m];} + var dx2=bc.x-this.sx,dy2=bc.y-5,dd2=Math.hypot(dx2,dy2)||1,pink=c.rng.chance(.12);C.projectile(this,{kind:pink?'boot':'trash',x:this.sx-1,y:5,vx:dx2/dd2*6+c.rng.uniform(-1,1),vy:dy2/dd2*6+c.rng.uniform(-1,1),r:.4,pink:pink,life:5});this.trash--; + this.trashT=this.trash>0?.38:(c.rng.chance(.45)?.01:[0,2.4,1.8][m]);if(this.trash<=0&&this.trashT<.1){this.heart={x:this.sx,y:4.6,t:0,shots:0};this.trashT=[0,3,2.4][m];c.emit('nest_heart',this.sx,4.6);}c.emit('nest_trash',this.sx,5);} + this.pillT-=dt;if(this.pillT<=0){[-1.6,1.6].forEach(function(o){C.projectile(self,{kind:'pill',x:self.sx+o,y:3.6,vx:0,vy:5,r:.32,pink:c.rng.chance(.2),life:3});});this.pillT=[0,3.8,2.8][m];c.emit('medic_pills',this.sx,3.6);} + }; + Wally.prototype.hazards=function(){if(this.st==='dead')return [];var a=C.hazards(this); + if(this.phase<=1&&this.st!=='transition')a.push({kind:'wally_body',box:C.box(this.x,this.y,3.2,4.2)}); + if(this.phase===2&&this.st!=='transition'){a.push({kind:'willy_body',circle:[this.willyX,this.willyY,.8]});this.eggs().forEach(function(e){a.push({kind:'spiked_egg',circle:[e.x,e.y,.45]});});} + if(this.phase===3&&this.st!=='transition'){a.push({kind:'stretcher',box:C.box(this.sx,4.6,6.4,1.6)});if(this.heart)a.push({kind:'heart',circle:[this.heart.x,this.heart.y,.55]});} + return a;}; + Wally.prototype.state=function(){return C.state(this,{attack:this.atk,burst:this.burstN,burst_time:B.r4(this.burstT),bird_time:B.r4(this.birdT),bird_row:this.birdRow,willy:[B.r4(this.willyX),B.r4(this.willyY)],egg_r:B.r4(this.eggR),egg_a:B.r4(this.eggA),zap_time:B.r4(this.zapT),stretcher_x:B.r4(this.sx),stretcher_dir:this.sDir,heart:this.heart,trash:this.trash,trash_time:B.r4(this.trashT),pill_time:B.r4(this.pillT),next_projectile:this.nextId});}; + BB.CASES['cuphead/wally'] = {title:'Egg-Spitting Bird',Body:B.CupPlane,Boss:Wally,arena:'aviary'}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/compact_actions.json b/environments/games/web/games/cuphead_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..5ef8bce6cd975e42be3f3d67474f4008c19cba96 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/compact_actions.json @@ -0,0 +1,1004 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "cuphead_remake", + "version": "cuphead-compact@2", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "keys": [ + "J" + ] + }, + { + "label": "right", + "keys": [ + "J", + "D" + ] + }, + { + "label": "up_right", + "keys": [ + "J", + "W", + "D" + ] + }, + { + "label": "up", + "keys": [ + "J", + "W" + ] + }, + { + "label": "up_left", + "keys": [ + "J", + "W", + "A" + ] + }, + { + "label": "left", + "keys": [ + "J", + "A" + ] + }, + { + "label": "down_left", + "keys": [ + "J", + "S", + "A" + ] + }, + { + "label": "down", + "keys": [ + "J", + "S" + ] + }, + { + "label": "down_right", + "keys": [ + "J", + "S", + "D" + ] + }, + { + "label": "right_short", + "subs": [ + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "up_right_short", + "subs": [ + [ + "J", + "W", + "D" + ], + [ + "J", + "W", + "D" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "up_short", + "subs": [ + [ + "J", + "W" + ], + [ + "J", + "W" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "up_left_short", + "subs": [ + [ + "J", + "W", + "A" + ], + [ + "J", + "W", + "A" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "left_short", + "subs": [ + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "down_left_short", + "subs": [ + [ + "J", + "S", + "A" + ], + [ + "J", + "S", + "A" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "down_short", + "subs": [ + [ + "J", + "S" + ], + [ + "J", + "S" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "down_right_short", + "subs": [ + [ + "J", + "S", + "D" + ], + [ + "J", + "S", + "D" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "left_turn_1", + "subs": [ + [ + "J", + "A" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ] + ] + }, + { + "label": "left_turn_2", + "subs": [ + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ] + ] + }, + { + "label": "left_turn_3", + "subs": [ + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ] + ] + }, + { + "label": "left_turn_4", + "subs": [ + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ] + ] + }, + { + "label": "left_turn_5", + "subs": [ + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "D" + ] + ] + }, + { + "label": "right_turn_1", + "subs": [ + [ + "J", + "D" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ] + ] + }, + { + "label": "right_turn_2", + "subs": [ + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ] + ] + }, + { + "label": "right_turn_3", + "subs": [ + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ] + ] + }, + { + "label": "right_turn_4", + "subs": [ + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "A" + ], + [ + "J", + "A" + ] + ] + }, + { + "label": "right_turn_5", + "subs": [ + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "D" + ], + [ + "J", + "A" + ] + ] + } + ] + }, + { + "name": "act", + "options": [ + { + "label": "none" + }, + { + "label": "jump_tap", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "jump", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "jump_hold_parry", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [], + [ + "Space" + ], + [ + "Space" + ], + [] + ] + }, + { + "label": "jump_parry", + "subs": [ + [ + "Space" + ], + [], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "press_2", + "subs": [ + [], + [ + "Space" + ], + [], + [], + [], + [] + ] + }, + { + "label": "press_3", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "press_4", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "press_5", + "subs": [ + [], + [], + [], + [], + [ + "Space" + ], + [] + ] + }, + { + "label": "lock_jump_parry", + "subs": [ + [ + "Space" + ], + [ + "L" + ], + [ + "L" + ], + [ + "Space" + ], + [ + "L" + ], + [ + "L" + ] + ] + }, + { + "label": "lock_jump", + "subs": [ + [ + "Space" + ], + [ + "L" + ], + [ + "L" + ], + [ + "L" + ], + [ + "L" + ], + [ + "L" + ] + ] + }, + { + "label": "lock_press_4", + "subs": [ + [ + "L" + ], + [ + "L" + ], + [ + "L" + ], + [ + "Space" + ], + [ + "L" + ], + [ + "L" + ] + ] + }, + { + "label": "lock_press_5", + "subs": [ + [ + "L" + ], + [ + "L" + ], + [ + "L" + ], + [ + "L" + ], + [ + "Space" + ], + [ + "L" + ] + ] + }, + { + "label": "lock", + "keys": [ + "L" + ] + }, + { + "label": "lock_from_2", + "subs": [ + [], + [ + "L" + ], + [ + "L" + ], + [ + "L" + ], + [ + "L" + ], + [ + "L" + ] + ] + }, + { + "label": "lock_half", + "subs": [ + [], + [], + [], + [ + "L" + ], + [ + "L" + ], + [ + "L" + ] + ] + }, + { + "label": "lock_late", + "subs": [ + [], + [], + [], + [], + [ + "L" + ], + [ + "L" + ] + ] + }, + { + "label": "lock_end", + "subs": [ + [], + [], + [], + [], + [], + [ + "L" + ] + ] + }, + { + "label": "ex", + "keys": [ + "K" + ] + }, + { + "label": "dash", + "keys": [ + "Shift" + ] + }, + { + "label": "dash_tap", + "subs": [ + [ + "Shift" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "dash_2", + "subs": [ + [], + [ + "Shift" + ], + [], + [], + [], + [] + ] + }, + { + "label": "dash_3", + "subs": [ + [], + [], + [ + "Shift" + ], + [], + [], + [] + ] + }, + { + "label": "dash_mid", + "subs": [ + [], + [], + [], + [ + "Shift" + ], + [], + [] + ] + }, + { + "label": "dash_5", + "subs": [ + [], + [], + [], + [], + [ + "Shift" + ], + [] + ] + }, + { + "label": "dash_6", + "subs": [ + [], + [], + [], + [], + [], + [ + "Shift" + ] + ] + }, + { + "label": "jump_dash", + "subs": [ + [ + "Space" + ], + [], + [], + [ + "Shift" + ], + [], + [] + ] + }, + { + "label": "jump3_dash6", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [ + "Shift" + ] + ] + }, + { + "label": "swap", + "subs": [ + [ + "Q" + ], + [ + "Q" + ], + [], + [], + [], + [] + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/cuphead_remake/draw/figures.js b/environments/games/web/games/cuphead_remake/draw/figures.js new file mode 100644 index 0000000000000000000000000000000000000000..4adae601b98180346f08697851b52c42c1685d52 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/draw/figures.js @@ -0,0 +1,412 @@ +// Original procedural "1930s rubber-hose" art for the three Cuphead cases. Pure presentation: reads the Case, never +// writes simulation state, never consumes game RNG (all jitter/grain comes from the local hash H and presentation time). +(function (g) { + var B = g.BB, A = B.ART, TAU = Math.PI * 2; + var INK = '#1d1815', PAPER = '#f4e8cc', WHITE = '#fbf6e8', RED = '#cf3a2c', DRED = '#8e2219', PINK = '#ff4fa3', PINK_HI = '#ffd3ea', + BLUE = '#5b8fd6', SHOE = '#7a4630', GOLD = '#e0a93a', PURPLE = '#8e63b8', GREEN = '#6aa66d'; + function H(i) { var s = Math.sin(i * 127.1 + 311.7) * 43758.5453; return s - Math.floor(s); } + var VIEW = B.CUP_VIEW = { last: null }; + function lit(on, col) { if (!on || typeof col !== 'string' || col.charAt(0) !== '#') return col; var h = col.length === 4 ? col.replace(/#(.)(.)(.)/, '#$1$1$2$2$3$3') : col, o = '#'; for (var i = 0; i < 3; i++) { var v = parseInt(h.substr(1 + i * 2, 2), 16); v = Math.round(v + (255 - v) * .22); o += (v < 16 ? '0' : '') + v.toString(16); } return o; } // last drawn case: read-only handle for browser UI tests + var boil = 0; // hand-drawn line boil, 12 changes per second of presentation time + function jit(k, a) { return (H(boil * 13.37 + k) - 0.5) * 2 * (a || 0.6); } + + // ---------- primitives ---------- + function inkStroke(x, lw, col) { x.lineWidth = lw; x.strokeStyle = col || INK; x.lineCap = 'round'; x.lineJoin = 'round'; x.stroke(); } + function fillInk(x, fill, lw) { x.fillStyle = fill; x.fill(); if (lw !== 0) inkStroke(x, lw || 2.6); } + function ell(x, cx, cy, rx, ry, fill, lw, rot) { + x.beginPath(); x.ellipse(cx + jit(cx * 1.3 + cy, .45), cy + jit(cx - cy * 1.7, .45), Math.max(.5, rx), Math.max(.5, ry), rot || 0, 0, TAU); fillInk(x, fill, lw); + } + function hose(x, ax, ay, bx, by, bend, lw, col) { // rubber-hose limb: one smooth bulging curve + var mx = (ax + bx) / 2, my = (ay + by) / 2, dx = bx - ax, dy = by - ay, l = Math.hypot(dx, dy) || 1; + x.beginPath(); x.moveTo(ax, ay); x.quadraticCurveTo(mx - dy / l * bend + jit(ax + by, .4), my + dx / l * bend, bx, by); inkStroke(x, lw || 4, col); + } + function rrect(x, l, t, w, h, r) { x.beginPath(); x.moveTo(l + r, t); x.arcTo(l + w, t, l + w, t + h, r); x.arcTo(l + w, t + h, l, t + h, r); x.arcTo(l, t + h, l, t, r); x.arcTo(l, t, l + w, t, r); x.closePath(); } + function pieEyes(x, cx, cy, s, look, blink, angry) { // pie-cut eyes: tall ink ovals with a wedge highlight + for (var k = -1; k <= 1; k += 2) { + var ex = cx + k * 6.2 * s + (look || 0) * 1.6 * s, ey = cy; + if (blink) { x.beginPath(); x.moveTo(ex - 3.4 * s, ey + s); x.quadraticCurveTo(ex, ey - 2 * s, ex + 3.4 * s, ey + s); inkStroke(x, 2.2 * s); continue; } + x.beginPath(); x.ellipse(ex, ey, 3.2 * s, 6.2 * s, 0, 0, TAU); x.fillStyle = INK; x.fill(); + x.beginPath(); x.moveTo(ex + .3 * s, ey - 1.6 * s); x.lineTo(ex + 3 * s, ey - 4.6 * s); x.lineTo(ex + 3.3 * s, ey - .4 * s); x.closePath(); x.fillStyle = WHITE; x.fill(); + if (angry) { x.beginPath(); x.moveTo(ex - 4.2 * s * k * -1, ey - 8.5 * s); x.lineTo(ex + 4 * s * k * -1, ey - 6 * s); inkStroke(x, 2.6 * s); } + } + } + function dazed(x, cx, cy, s) { for (var k = -1; k <= 1; k += 2) { var ex = cx + k * 6.2 * s; x.beginPath(); x.moveTo(ex - 3 * s, cy - 3 * s); x.lineTo(ex + 3 * s, cy + 3 * s); x.moveTo(ex + 3 * s, cy - 3 * s); x.lineTo(ex - 3 * s, cy + 3 * s); inkStroke(x, 2.2 * s); } } + function smile(x, cx, cy, w, open) { + x.beginPath(); if (open) { x.ellipse(cx, cy + w * .2, w * .45, w * .5, 0, 0, TAU); fillInk(x, '#5a1d18', 2); return; } + x.moveTo(cx - w, cy); x.quadraticCurveTo(cx, cy + w * .9, cx + w, cy - w * .1); inkStroke(x, 2.4); + } + function star(x, cx, cy, r1, r2, n, rot, fill, lw) { + x.beginPath(); for (var i = 0; i < n * 2; i++) { var a = (rot || -Math.PI / 2) + i * Math.PI / n, r = i % 2 ? r2 : r1; if (!i) x.moveTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); else x.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); } + x.closePath(); fillInk(x, fill, lw); + } + function pinkGlow(x, px, py, r, t) { // every parryable object gets the same pulsing halo + x.save(); x.globalAlpha = .28 + .14 * Math.sin(t * 9); x.beginPath(); x.arc(px, py, r * 1.65, 0, TAU); x.fillStyle = PINK; x.fill(); x.restore(); + } + function glove(x, gx, gy, r, fill, dir) { // cartoon glove / boxing glove + ell(x, gx, gy, r, r * .82, fill, 2.4); ell(x, gx - dir * r * .55, gy + r * .45, r * .42, r * .3, fill, 2); + x.beginPath(); x.moveTo(gx - dir * r * .3, gy - r * .55); x.quadraticCurveTo(gx + dir * r * .1, gy - r * .1, gx - dir * r * .2, gy + r * .3); inkStroke(x, 1.4); + } + function cupHead(x, hx, hy, s, look, mood) { // Cuphead's cup head: rim, straw, handle, pie eyes + x.save(); x.translate(hx, hy); x.scale(s, s); + x.beginPath(); x.moveTo(-1, -12); x.lineTo(-6, -27); x.lineTo(-11, -28); inkStroke(x, 6.5); x.beginPath(); x.moveTo(-1, -12); x.lineTo(-6, -27); x.lineTo(-11, -28); inkStroke(x, 4, WHITE); + for (var k = 0; k < 3; k++) { x.beginPath(); var a = .25 + k * .3; x.moveTo(-1 - 5 * a - 1, -12 - 15 * a); x.lineTo(-1 - 5 * (a + .1), -12 - 15 * (a + .1)); inkStroke(x, 4, RED); } + x.beginPath(); x.ellipse(-13, 0, 4.5, 6, 0, 0, TAU); inkStroke(x, 2.6); x.beginPath(); x.ellipse(-13, 0, 4.5, 6, 0, 0, TAU); inkStroke(x, 1.2, WHITE); + x.beginPath(); x.moveTo(-12, -10); x.quadraticCurveTo(-12.5, 6, -6, 11); x.quadraticCurveTo(0, 13.5, 6, 11); x.quadraticCurveTo(12.5, 6, 12, -10); x.closePath(); fillInk(x, WHITE, 2.6); + ell(x, 0, -10, 12.2, 3.6, '#efe1bf', 2.4); ell(x, 0, -10.4, 9, 2, '#6f4a37', 0); + pieEyes(x, 2.5 + (look || 0), -1, .72, 0, mood === 'blink'); + ell(x, 7.5, 3.5, 2.6, 2, RED, 1.4); ell(x, -4, 5.5, 2.4, 1.4, '#f2a7a0', 0); smile(x, 3.5, 7, 4, mood === 'open'); + x.restore(); + } + + // ---------- film overlay, banners and HUD ---------- + var film = null; + function filmAssets(doc) { + if (film && film.doc === doc) return film; + var n = doc.createElement('canvas'); n.width = n.height = 160; var nx = n.getContext('2d'), img = nx.createImageData(160, 160); + for (var i = 0; i < 160 * 160; i++) { var v = H(i * .731 + 7) * 255 | 0, a = H(i * 1.917 + 3) < .55 ? 0 : 22 + (H(i * 3.1) * 26 | 0); img.data[i * 4] = v * .55 + 40; img.data[i * 4 + 1] = v * .45 + 30; img.data[i * 4 + 2] = v * .3 + 20; img.data[i * 4 + 3] = a; } + nx.putImageData(img, 0, 0); + var vg = doc.createElement('canvas'); vg.width = 854; vg.height = 480; var vx = vg.getContext('2d'), gr = vx.createRadialGradient(427, 250, 170, 427, 240, 560); + gr.addColorStop(0, 'rgba(60,38,18,0)'); gr.addColorStop(.62, 'rgba(60,38,18,.10)'); gr.addColorStop(1, 'rgba(38,22,10,.55)'); vx.fillStyle = gr; vx.fillRect(0, 0, 854, 480); + film = { doc: doc, noise: n, vignette: vg, pattern: null }; return film; + } + function filmOverlay(x, c) { + // Static grain (paper/film texture) + vignette; only sparse scratches/dust (changing every 1/3 s) and a faint + // global flicker move. A per-frame noise field made the H.264 videos ~23x larger and fed noise to RGB policies. + var F = filmAssets(x.canvas.ownerDocument || g.document), k = Math.floor(c.t / 20); + if (!F.pattern) F.pattern = x.createPattern(F.noise, 'repeat'); + x.save(); x.drawImage(F.vignette, 0, 0); x.fillStyle = F.pattern; x.fillRect(0, 0, 854, 480); + for (var s = 0; s < 2; s++) if (H(k * 5.3 + s) < .4) { var sx = H(k * 9.1 + s * 3) * 854; x.fillStyle = 'rgba(52,36,22,' + (.1 + .14 * H(k + s)).toFixed(3) + ')'; x.fillRect(sx, 0, 1.5, 480); } + for (var d = 0; d < 3; d++) { var dx = H(k * 11.3 + d) * 854, dy = H(k * 4.7 + d * 2) * 480; x.fillStyle = 'rgba(40,28,18,.3)'; x.beginPath(); x.arc(dx, dy, 1 + H(k + d * 7) * 1.4, 0, TAU); x.fill(); } + x.fillStyle = 'rgba(255,236,190,' + (.02 * H(Math.floor(c.t / 6) * 2.9)).toFixed(3) + ')'; x.fillRect(0, 0, 854, 480); + x.restore(); + } + function banner(x, text, sub, k, color) { + var s = .85 + .15 * Math.min(1, k * 4); + x.save(); x.translate(427, 200); x.scale(s, s); + x.fillStyle = 'rgba(29,24,21,.18)'; star(x, 0, 6, 250, 175, 14, -Math.PI / 2, 'rgba(255,240,205,.55)', 0); + x.font = 'italic 900 70px Georgia, "Times New Roman", serif'; x.textAlign = 'center'; x.textBaseline = 'middle'; + x.lineJoin = 'round'; x.lineWidth = 12; x.strokeStyle = INK; x.strokeText(text, 4, 6); x.fillStyle = color || RED; x.fillText(text, 4, 6); + x.lineWidth = 9; x.strokeText(text, 0, 0); x.fillStyle = PAPER; x.fillText(text, 0, 0); + if (sub) { x.font = 'bold 18px Georgia, serif'; x.lineWidth = 5; x.strokeText(sub, 0, 58); x.fillStyle = PAPER; x.fillText(sub, 0, 58); } + x.restore(); + } + function hud(x, c, V, extra) { + var b = c.body, o = c.boss, blink = b.hp === 1 && (c.t >> 4) % 2; + x.save(); x.textBaseline = 'alphabetic'; + // player: HP card + five super-meter cards, bottom left (Cuphead layout) + rrect(x, 12, 437, 52, 30, 4); fillInk(x, blink ? '#e8574a' : PAPER, 2.4); + x.fillStyle = INK; x.font = 'bold 16px Georgia, serif'; x.textAlign = 'center'; x.fillText('HP. ' + b.hp, 38, 458); + for (var i = 0; i < 5; i++) { + var cx = 72 + i * 17, fillK = Math.max(0, Math.min(1, b.meter - i)); + rrect(x, cx, 439, 14, 26, 2.5); fillInk(x, '#e6d3ad', 1.8); + if (fillK > 0) { x.save(); rrect(x, cx, 439, 14, 26, 2.5); x.clip(); x.fillStyle = fillK >= 1 ? WHITE : '#d9574b'; x.fillRect(cx, 465 - 26 * fillK, 14, 26 * fillK); x.restore(); rrect(x, cx, 439, 14, 26, 2.5); inkStroke(x, 1.8); } + if (fillK >= 1) { star(x, cx + 7, 452, 5, 2.2, 4, 0, b.meter >= 5 ? GOLD : RED, 1); } + } + x.textAlign = 'left'; x.font = 'bold 11px Georgia, serif'; x.fillStyle = INK; + var tag = b.plane ? (b.superT > 0 ? 'BLAST FORM' : b.shrink ? 'SHRUNK' : b.weapon === 'bomb' ? 'DROP BOMBS' : 'AUTO GUN') : (b.superT > 0 ? 'SWEEP RAY' : 'RAPID GUN'); + rrect(x, 158, 438, 104, 28, 4); fillInk(x, 'rgba(244,232,204,.92)', 1.8); x.fillStyle = INK; x.fillText(tag, 164, 450); x.fillStyle = '#c2186b'; x.fillText('PARRY ' + b.parries, 164, 462); + // boss: name ribbon, health bar with phase dividers, mode / phase / timer (top right) + var bx = 530, by = 12, bw = 308, fr = Math.max(0, o.hp / o.max_hp); + rrect(x, bx, by, bw, 44, 5); fillInk(x, 'rgba(244,232,204,.94)', 2.2); + x.fillStyle = INK; x.font = 'bold italic 14px Georgia, serif'; x.fillText(c.def.title, bx + 10, by + 17); + var secs = c.t / B.FPS, mm = Math.floor(secs / 60), ss = Math.floor(secs % 60); + x.textAlign = 'right'; x.font = 'bold 12px Georgia, serif'; x.fillText('60Hz · ' + mm + ':' + (ss < 10 ? '0' : '') + ss, bx + bw - 10, by + 16); + x.fillStyle = '#d8c39c'; x.fillRect(bx + 10, by + 23, bw - 20, 7); x.fillStyle = RED; x.fillRect(bx + 10, by + 23, (bw - 20) * fr, 7); + var acc = 0; for (var p = 0; p < o.parts.length - 1; p++) { acc += o.parts[p]; var dx = bx + 10 + (bw - 20) * (1 - acc / o.max_hp); if (o.secret) break; x.fillStyle = INK; x.fillRect(dx - 1, by + 21, 2, 11); } + x.strokeStyle = INK; x.lineWidth = 1.4; x.strokeRect(bx + 10, by + 23, bw - 20, 7); + x.textAlign = 'left'; x.font = '10px Georgia, serif'; x.fillStyle = INK; + x.fillText(B.CUP.tierName(c.d) + ' · ' + ['SIMPLE', 'REGULAR', 'EXPERT'][o.mode] + ' · PHASE ' + (o.phase + 1) + '/' + o.parts.length + (o.secret ? ' · SECRET' : '') + ' · ' + Math.ceil(o.hp) + ' HP', bx + 10, by + 41); + if (extra) { x.textAlign = 'center'; x.font = 'bold 12px Georgia, serif'; x.fillText(extra, 427, 26); } + x.restore(); + } + function fullHud(x, c, V, extra) { + VIEW.last = c; + filmOverlay(x, c); hud(x, c, V, extra); + var t = c.t / B.FPS; + if (!c.result && c.t < 96) { if (c.t < 48) banner(x, 'READY?', null, c.t / 48); else banner(x, 'WALLOP!', null, (c.t - 48) / 48); } + // Simple is the original's short fight (source: Goopy ends before the tombstone, Hilda before the moon, Ollie is + // skipped); the KO card says so, so an easy-tier win is never mistaken for the full Regular/Expert battle. + var simple = c.boss.mode === 0 ? ' · SIMPLE: ' + ({ goopy: 'NO TOMBSTONE', root_pack: 'ONION SKIPPED', hilda: 'NO MOON', cagney: 'NO THORNS', ribby_croaks: 'NO SLOT MACHINE', wally: 'NO STRETCHER' }[c.boss.id] || 'SHORT FIGHT') : ''; + if (c.result === 'win') banner(x, 'A KNOCKOUT!', c.def.title + ' · ' + t.toFixed(1) + ' s' + simple, 1); + else if (c.result === 'loss') banner(x, 'YOU DIED', 'Boss ' + Math.round((1 - c.boss.hp / c.boss.max_hp) * 100) + '% · ' + t.toFixed(1) + ' s', 1, '#5c4a8a'); + else if (c.result === 'timeout') banner(x, 'TIME UP', null, 1, '#5c4a8a'); + } + + // ---------- player ---------- + function drawShots(x, b, t, V) { + b.shots.forEach(function (p) { + var px = V.sx(p.x), py = V.sy(p.y); + if (p.kind === 'bomb') { ell(x, px, py, 7, 7, INK, 1.5); x.beginPath(); x.moveTo(px + 3, py - 6); x.lineTo(px + 6, py - 11); inkStroke(x, 2, GOLD); return; } + var a = Math.atan2(-p.vy, p.vx); x.save(); x.translate(px, py); x.rotate(a); + if (p.kind === 'ex' || p.kind === 'missile') { // Mega Blast: blue fireball with a flame tail + x.beginPath(); x.moveTo(14, 0); x.bezierCurveTo(12, -16, -10, -14, -34, -6 + Math.sin(t * 40) * 3); x.quadraticCurveTo(-22, 0, -34, 6 - Math.sin(t * 40) * 3); x.bezierCurveTo(-10, 14, 12, 16, 14, 0); x.closePath(); fillInk(x, '#6fc3e3', 2.6); + ell(x, 3, 0, 9, 7, '#d8f6ff', 0); ell(x, 5, -2, 4, 3, WHITE, 0); x.restore(); return; } + x.beginPath(); x.moveTo(8, 0); x.quadraticCurveTo(4, -4.2, -18, -1.6); x.lineTo(-18, 1.6); x.quadraticCurveTo(4, 4.2, 8, 0); x.closePath(); fillInk(x, '#7fd0ea', 1.6); + x.beginPath(); x.ellipse(2, 0, 5, 1.6, 0, 0, TAU); x.fillStyle = WHITE; x.fill(); x.restore(); + }); + } + function drawCup(x, c, t, V) { + var b = c.body, px = V.sx(b.x), py = V.sy(b.y), f = b.facing, run = b.grounded && Math.abs(b.vx) > .1, ph = t * 15; + var dash = b.dashT > 0, crouch = b.crouch, air = !b.grounded; + x.save(); x.translate(px, py); x.scale(f, 1); + if (dash) { x.scale(1.22, .86); for (var k = 0; k < 3; k++) { x.beginPath(); x.moveTo(-14 - k * 9, -12 - k * 7); x.lineTo(-30 - k * 12, -12 - k * 7); inkStroke(x, 2, 'rgba(29,24,21,.55)'); } } + var bob = b.grounded ? (run ? -Math.abs(Math.sin(ph)) * 2.6 : Math.sin(t * 4.2) * 1.1) : 0, sq = crouch ? .62 : 1, hipY = -14 * sq + bob, la = run ? Math.sin(ph) * 8 : 0; + if (air) { hose(x, -3, hipY, -7, hipY + 9, -4, 4.2); hose(x, 3, hipY, 6, hipY + 8, 4, 4.2); ell(x, -9, hipY + 10, 6.5, 3.4, SHOE, 2); ell(x, 8, hipY + 9, 6.5, 3.4, SHOE, 2); } + else { hose(x, -3, hipY, -3 - la, -3, 4, 4.2); hose(x, 3, hipY, 3 + la, -3, -4, 4.2); ell(x, -1 - la, -2.5, 7, 3.6, SHOE, 2); ell(x, 6 + la, -2.5, 7, 3.6, SHOE, 2); } + rrect(x, -7.5, hipY - 6, 15, 8, 3); fillInk(x, RED, 2.2); + ell(x, 0, hipY - 10 * sq, 7.4, 7.6 * sq, INK, 0); + var sh = { x: 2, y: hipY - 13 * sq }, aim = b.plane ? { x: 1, y: 0 } : b.aim, ax = aim.x * f, ay = -aim.y, swing = run ? Math.sin(ph + 1.5) * 6 : 0; + hose(x, -2, sh.y + 1, -10 + swing * .3, sh.y + 8 + Math.abs(swing) * .2, 3, 3.6); glove(x, -10 + swing * .3, sh.y + 9, 3.6, WHITE, -1); + var hx = sh.x + ax * 11, hy = sh.y + ay * 11; hose(x, sh.x, sh.y, hx, hy, -2, 3.6); glove(x, hx, hy, 3.8, WHITE, 1); + var mood = b.invul > 0 && b.hp < 3 && b.invul > .9 ? 'open' : (Math.floor(t * 1.3) % 5 === 0 && H(Math.floor(t * 1.3)) < .5 ? 'blink' : ''); + cupHead(x, 1, hipY - 27 * (crouch ? .82 : 1), 1, ax * 1.2, mood); + x.restore(); + if (b.parryT > 0) { x.save(); x.globalAlpha = .55; star(x, px, V.sy(b.y + .9), 26, 13, 8, t * 6, PINK, 2); x.restore(); } + } + function drawPlane(x, c, t, V) { + var b = c.body, px = V.sx(b.x), py = V.sy(b.y), s = b.shrink ? .57 : 1; + x.save(); x.translate(px, py); x.scale(s, s); x.rotate(Math.max(-.18, Math.min(.18, -b.vy * .015))); + if (b.superT > 0 && b.superKind === 'bomb_morph') { + ell(x, 0, 0, 27, 25, '#2a2422', 2.6); ell(x, -9, -10, 7, 5, '#6b625c', 0); + x.beginPath(); x.moveTo(12, -20); x.quadraticCurveTo(20, -30, 26, -27); inkStroke(x, 3, GOLD); star(x, 27, -28, 6 + 2 * Math.sin(t * 30), 2.5, 5, t * 9, '#ffd75e', 1); + x.save(); x.scale(.75, .75); pieEyes(x, 4, -2, 1, 0, false, true); x.restore(); x.restore(); return; + } + ell(x, 2, 9, 26, 4.6, '#f1e4c4', 2.2); + x.beginPath(); x.moveTo(-28, -2); x.quadraticCurveTo(-14, -15, 14, -10); x.quadraticCurveTo(30, -6, 30, 1); x.quadraticCurveTo(26, 9, 4, 9); x.quadraticCurveTo(-18, 9, -28, 4); x.closePath(); fillInk(x, RED, 2.6); + x.beginPath(); x.moveTo(-24, -4); x.lineTo(-34, -15); x.lineTo(-27, 2); x.closePath(); fillInk(x, RED, 2.2); + x.beginPath(); x.moveTo(-6, 2); x.lineTo(22, 0); inkStroke(x, 1.6, DRED); + ell(x, 31, 0, 3, 3, INK, 0); x.save(); x.globalAlpha = .55; ell(x, 33, 0, 2.2, 4 + 9 * Math.abs(Math.sin(t * 41)), '#e9dfc8', 1.2); x.restore(); + cupHead(x, 0, -16, .62, 1, ''); + x.restore(); + if (b.parryT > 0) { x.save(); x.globalAlpha = .55; star(x, px, py, 30 * s + 6, 15 * s + 3, 8, t * 6, PINK, 2); x.restore(); } + } + var player = { + draw: function (x, c, t, V) { + boil = Math.floor(t * 12); var b = c.body; + drawShots(x, b, t, V); + if (b.superT > 0 && b.superKind === 'beam') { + var cy = V.sy(b.centre().y), px = V.sx(b.x), f = b.facing, w = f > 0 ? 854 - px : px, l = f > 0 ? px : 0, k = .75 + .25 * Math.sin(t * 50); + x.save(); x.globalAlpha = .85; x.fillStyle = '#e9fbff'; x.fillRect(l, cy - 31 * k, w, 62 * k); x.globalAlpha = 1; x.fillStyle = WHITE; x.fillRect(l, cy - 14 * k, w, 28 * k); + x.strokeStyle = '#6ac3dd'; x.lineWidth = 5; x.strokeRect(l, cy - 31 * k, w, 62 * k); x.restore(); + } + x.save(); if (b.invul > 0 && b.superT <= 0 && (c.t >> 2) % 2) x.globalAlpha = .4; + if (b.plane) drawPlane(x, c, t, V); else drawCup(x, c, t, V); + x.restore(); + }, fullHud: fullHud + }; + B.BODY_DRAW.cup = player; B.BODY_DRAW.cup_plane = player; + + // ---------- enemy projectiles (shared by the three cases) ---------- + function tearPath(x, px, py, r) { x.beginPath(); x.moveTo(px, py - r * 2.1); x.quadraticCurveTo(px + r * 1.3, py - r * .2, px, py + r); x.quadraticCurveTo(px - r * 1.3, py - r * .2, px, py - r * 2.1); } + function zeppelin(x, px, py, fill, t) { + x.beginPath(); x.moveTo(px + 15, py - 6); x.lineTo(px + 24, py - 13); x.lineTo(px + 22, py); x.closePath(); fillInk(x, fill, 2); + ell(x, px, py, 19, 11, fill, 2.4); ell(x, px - 2, py - 4, 9, 3, 'rgba(255,255,255,.35)', 0); + pieEyes(x, px - 6, py - 1, .5, -1); ell(x, px + 2, py + 13, 4, 3, '#efe1bf', 1.6); + } + function hazards(x, c, t, V) { + boil = Math.floor(t * 12); + c.boss.projectiles.forEach(function (p) { + if (p.removed) return; + var px = V.sx(p.x), py = V.sy(p.y), r = p.r * 30; + if (p.pink) pinkGlow(x, px, py, Math.max(r, 12), t); + switch (p.kind) { + case 'question': + x.save(); x.translate(px, py + Math.sin(t * 5 + p.id) * 3); x.font = 'italic 900 44px Georgia, serif'; x.textAlign = 'center'; x.textBaseline = 'middle'; + x.lineWidth = 7; x.lineJoin = 'round'; x.strokeStyle = INK; x.strokeText('?', 0, 0); x.fillStyle = PINK; x.fillText('?', 0, 0); x.fillStyle = PINK_HI; x.fillText('·', -6, -10); x.restore(); break; + case 'ha': + x.save(); x.translate(px, py); x.rotate(Math.sin(t * 6 + p.id) * .12); x.font = 'italic 900 34px Georgia, serif'; x.textAlign = 'center'; x.textBaseline = 'middle'; + x.lineWidth = 7; x.lineJoin = 'round'; x.strokeStyle = INK; x.strokeText('HA', 0, 0); x.fillStyle = '#ffe9cf'; x.fillText('HA', 0, 0); x.restore(); break; + case 'dirt': + x.beginPath(); for (var i = 0; i < 7; i++) { var a = i / 7 * TAU + p.id, rr = r * (.8 + .3 * H(p.id * 7 + i)); x.lineTo(px + Math.cos(a) * rr, py + Math.sin(a) * rr); } x.closePath(); fillInk(x, '#7c5232', 2.2); + ell(x, px - r * .3, py - r * .25, r * .2, r * .14, '#a8794e', 0); ell(x, px + r * .3, py + r * .2, r * .16, r * .12, '#4f321d', 0); break; + case 'worm': + x.beginPath(); x.moveTo(px - r * 1.4, py + 2); x.bezierCurveTo(px - r * .6, py - r * 1.4, px + r * .2, py + r * 1.2, px + r * 1.3, py - 2); inkStroke(x, r * .95 + 3); x.beginPath(); x.moveTo(px - r * 1.4, py + 2); x.bezierCurveTo(px - r * .6, py - r * 1.4, px + r * .2, py + r * 1.2, px + r * 1.3, py - 2); inkStroke(x, r * .95, PINK); + ell(x, px - r * 1.35, py + 1, 3.4, 3.4, PINK, 1.6); pieEyes(x, px - r * 1.35, py, .28, -1); break; + case 'tear': + tearPath(x, px, py, r); fillInk(x, p.pink ? PINK : '#7cc3e6', 2.2); ell(x, px - r * .3, py - r * .7, r * .22, r * .35, p.pink ? PINK_HI : WHITE, 0); break; + case 'homing_carrot': + x.save(); x.translate(px, py); x.rotate(Math.atan2(-p.vy, p.vx) - Math.PI / 2); x.beginPath(); x.moveTo(-8, 10); x.quadraticCurveTo(0, 15, 8, 10); x.lineTo(0, -15); x.closePath(); fillInk(x, '#ee8a33', 2.2); + x.beginPath(); x.moveTo(-4, 2); x.lineTo(3, 0); x.moveTo(-3, -5); x.lineTo(2, -6); inkStroke(x, 1.2, '#a65a1f'); hose(x, 0, 12, -5, 20, 2, 3, '#4f8a43'); hose(x, 0, 12, 5, 20, -2, 3, '#4f8a43'); x.restore(); break; + case 'eye_ring': + for (var k2 = 0; k2 < 3; k2++) { x.beginPath(); x.ellipse(px, py, r * (1 - k2 * .28), r * (1 - k2 * .28) * 1.25, Math.atan2(-p.vy, p.vx), 0, TAU); inkStroke(x, k2 ? 2.4 : 4, k2 % 2 ? '#e8d8ff' : '#9b6ad6'); } break; + case 'purple_plane': zeppelin(x, px, py, '#9a6bc0', t); break; + case 'green_plane': zeppelin(x, px, py, '#6fae73', t); break; + case 'minion_bullet': ell(x, px, py, r + 1, r + 1, p.pink ? PINK : '#c9a1e2', 2); ell(x, px - 1.5, py - 1.5, 2, 2, WHITE, 0); break; + case 'crescent': x.beginPath(); x.arc(px, py, r + 2, .6, TAU - .6); x.arc(px + 3, py, r - 1, TAU - .9, .9, true); x.closePath(); fillInk(x, '#a3d39a', 1.8); break; + case 'vortex_bullet': ell(x, px, py, r + 1.5, r + 1.5, '#b8a6f0', 1.8); break; + case 'tornado': + for (var q = 0; q < 6; q++) { var yy = py + (q - 2.5) * 8, w = 6 + q * 4.2; x.beginPath(); x.ellipse(px + Math.sin(t * 9 + q) * 4, yy, w, 4.2, 0, 0, TAU); fillInk(x, q % 2 ? '#c7cfd3' : '#a9b4ba', 1.8); } break; + case 'arrow': + x.beginPath(); x.moveTo(px + 34, py); x.lineTo(px - 22, py); inkStroke(x, 7); x.beginPath(); x.moveTo(px + 34, py); x.lineTo(px - 22, py); inkStroke(x, 4, GOLD); + x.beginPath(); x.moveTo(px - 34, py); x.lineTo(px - 18, py - 10); x.lineTo(px - 18, py + 10); x.closePath(); fillInk(x, GOLD, 2.2); + x.beginPath(); x.moveTo(px + 30, py); x.lineTo(px + 40, py - 9); x.moveTo(px + 30, py); x.lineTo(px + 40, py + 9); inkStroke(x, 3, WHITE); break; + case 'blue_star': star(x, px, py, r + 4, (r + 4) * .45, 5, t * 3 + p.id, '#6fb6e8', 2.2); pieEyes(x, px, py, .28); break; + case 'shooting_star': + x.beginPath(); x.moveTo(px + 6, py); x.lineTo(px + 34, py - 3); x.lineTo(px + 34, py + 3); x.closePath(); x.fillStyle = p.pink ? 'rgba(255,79,163,.45)' : 'rgba(255,231,140,.55)'; x.fill(); + star(x, px, py, r + 5, (r + 5) * .45, 5, t * 5 + p.id, p.pink ? PINK : '#ffe27a', 2.2); break; + case 'ufo': + if (p.charge > 0) { x.save(); x.setLineDash([6, 6]); x.beginPath(); x.moveTo(px, py + 8); x.lineTo(px, V.FLOOR); inkStroke(x, 2, p.red ? '#d64e4e' : '#c99a1f'); x.restore(); ell(x, px, py + 8, 8 + 3 * Math.sin(t * 40), 4, '#fff1a8', 0); } + if (p.beam > 0) { x.fillStyle = 'rgba(255,236,120,.75)'; x.fillRect(px - 11, py + 6, 22, V.FLOOR - py); x.fillStyle = 'rgba(255,255,240,.9)'; x.fillRect(px - 4, py + 6, 8, V.FLOOR - py); x.strokeStyle = p.red ? '#c33' : '#b8861a'; x.lineWidth = 2; x.strokeRect(px - 11, py + 6, 22, V.FLOOR - py); } + ell(x, px, py - 6, 10, 9, '#bfe3ef', 2); ell(x, px, py + 2, 24, 7, p.red ? '#d64e4e' : '#e2b23a', 2.4); for (var u = -1; u <= 1; u++) ell(x, px + u * 11, py + 3, 2, 2, '#fff3b0', 0); break; + default: ell(x, px, py, r, r, p.pink ? PINK : '#e7cf96', 2); + } + }); + } + + // ---------- Goopy Le Grande ---------- + function goopyBody(x, c, t, V) { + var o = c.boss, f = o.f || -1, px = V.sx(o.x); + if (o.phase === 2) return tombstone(x, c, t, V); + var R = o.radius() * 30, air = o.st === 'bounce', vy = o.vy || 0, giant = o.phase === 1, dead = o.st === 'dead'; + var sq = dead ? { sx: 1.18, sy: .78 } : A.smooth('goopy-sq', { sx: air ? 1 - Math.min(.12, Math.abs(vy) * .007) : o.st === 'punch_antic' ? 1.08 : 1.1, sy: air ? 1 + Math.min(.15, Math.abs(vy) * .009) : o.st === 'punch_antic' ? .94 : .9 }, 16); + var base = V.sy(o.y), lean = o.st === 'punch_antic' ? -f * 8 : o.st === 'punch' ? f * 6 : 0, cx = px + lean, h = 2 * R * sq.sy, w = R * sq.sx; + A.shade(x, px, V.FLOOR, R * .9, 8, .25); + if (!dead && (o.st === 'punch' || o.st === 'punch_antic')) { // glove geometry follows the glove hazard box + var reach = o.st === 'punch' ? (giant ? 7.25 : 4.4) : (giant ? .9 : .6), gy = V.sy(1.3), gx = V.sx(o.x + f * reach) - f * (giant ? 18 : 16); + if (o.st === 'punch') hose(x, cx, base - h * .45, gx, gy, f * 8, giant ? 22 : 30, giant ? '#4f7fc4' : BLUE); + glove(x, gx, gy, giant ? 22 : 20, giant ? RED : BLUE, f); + if (o.st === 'punch_antic') { x.save(); x.globalAlpha = .22; x.fillStyle = RED; var bx0 = V.sx(o.x + f * (giant ? .75 : .6)), bx1 = V.sx(o.x + f * (giant ? 7.25 : 4.4)); x.fillRect(Math.min(bx0, bx1), V.sy(1.875), Math.abs(bx1 - bx0), 1.15 * 30); x.restore(); } + } + x.beginPath(); x.moveTo(cx - w, base); x.bezierCurveTo(cx - w * 1.05, base - h * .7, cx - w * .55, base - h, cx, base - h); x.bezierCurveTo(cx + w * .55, base - h, cx + w * 1.05, base - h * .7, cx + w, base); x.quadraticCurveTo(cx, base + 4, cx - w, base); x.closePath(); + var gr = x.createLinearGradient(0, base - h, 0, base); gr.addColorStop(0, lit(o.hitFlash > 0, '#79aeea')); gr.addColorStop(1, lit(o.hitFlash > 0, '#3f6fb8')); fillInk(x, gr, 3); + ell(x, cx - w * .42, base - h * .78, w * .2, h * .08, 'rgba(255,255,255,.75)', 0, -.5); + var fx = cx + f * w * .2, fy = base - h * .56, s = R / 36; + if (dead) dazed(x, fx, fy, s); else pieEyes(x, fx, fy, s, f, giant && o.st === 'punch_antic' && o.firstPunch && (c.t >> 3) % 2, o.st === 'punch_antic'); + if (giant) { for (var k = -1; k <= 1; k += 2) { x.beginPath(); x.moveTo(fx + k * 3 * s, fy - 10 * s); x.lineTo(fx + k * 11 * s, fy - 12 * s + (o.st === 'punch_antic' ? k * -2 * s : 0)); inkStroke(x, 4 * s, '#6b3f22'); } } + ell(x, fx + f * 3 * s, fy + 8 * s, 3 * s, 2.4 * s, '#d9473c', 1.6); smile(x, fx, fy + 13 * s, 7 * s, o.st === 'punch' || dead); + } + function tombstone(x, c, t, V) { + var o = c.boss, px = V.sx(o.x), slide = o.st === 'slide', antic = o.st === 'slam_antic', dead = o.st === 'dead'; + var lift = antic ? 3.4 * 30 * Math.min(1, 1.6 - o.timer * 1.6) : 0, base = V.FLOOR - (slide ? 6 : 0) - lift, sc = slide ? .9 : 1; + if (antic || o.st === 'slam') { var shx = V.sx(o.slamX); x.save(); x.globalAlpha = antic ? .5 : .25; x.fillStyle = INK; x.beginPath(); x.ellipse(shx, V.FLOOR - 2, 48, 7, 0, 0, TAU); x.fill(); x.restore(); if (antic) { x.save(); x.setLineDash([5, 5]); x.strokeStyle = RED; x.lineWidth = 2; x.strokeRect(shx - 48, V.FLOOR - 240, 96, 240); x.restore(); } } + x.save(); x.translate(px, base); x.scale(sc, sc); x.globalAlpha = slide ? .8 : 1; + x.beginPath(); x.moveTo(-6, -142); x.lineTo(6, -142); x.lineTo(6, -128); x.lineTo(18, -128); x.lineTo(18, -118); x.lineTo(6, -118); x.lineTo(6, -100); x.lineTo(-6, -100); x.lineTo(-6, -118); x.lineTo(-18, -118); x.lineTo(-18, -128); x.lineTo(-6, -128); x.closePath(); fillInk(x, '#8f9a98', 2.4); + if (dead) { // R.I.P. literally: the stone is torn in half (source) + var wob = Math.sin(t * 9) * .05; + for (var hk = -1; hk <= 1; hk += 2) { x.save(); x.translate(hk * 10, 0); x.rotate(hk * (.12 + wob)); x.beginPath(); x.moveTo(0, 0); x.lineTo(hk * 50, 0); x.lineTo(hk * 50, -62); x.quadraticCurveTo(hk * 50, -104, 0, -104); x.lineTo(hk * 4, -78); x.lineTo(hk * -3, -52); x.lineTo(hk * 4, -26); x.closePath(); fillInk(x, '#a8b3b0', 3.2); x.restore(); } + } else { x.beginPath(); x.moveTo(-50, 0); x.lineTo(-50, -62); x.quadraticCurveTo(-50, -104, 0, -104); x.quadraticCurveTo(50, -104, 50, -62); x.lineTo(50, 0); x.closePath(); fillInk(x, lit(o.hitFlash > 0, '#a8b3b0'), 3.2); } + x.font = 'bold 15px Georgia, serif'; x.textAlign = 'center'; x.fillStyle = '#5a6462'; x.fillText('R.I.P.', 0, -84); + if (dead) { dazed(x, -26, -55, 1.2); dazed(x, 26, -55, 1.2); } else { pieEyes(x, 0, -55, 1.55, 0, false, true); x.beginPath(); x.moveTo(-14, -30); x.quadraticCurveTo(0, -40, 14, -30); inkStroke(x, 3); } + x.restore(); + } + B.BOSS_DRAW['cuphead/goopy'] = { hazards: hazards, body: goopyBody }; + + // ---------- The Root Pack ---------- + function mound(x, cx, w) { x.beginPath(); x.moveTo(cx - w, B.VIEW.FLOOR + 2); x.quadraticCurveTo(cx, B.VIEW.FLOOR - 26, cx + w, B.VIEW.FLOOR + 2); x.closePath(); fillInk(x, '#6e4a2c', 2.6); } + function rootBody(x, c, t, V) { + var o = c.boss, form = o.form(), F = V.FLOOR, dead = o.st === 'dead'; + if (form === 'carrot') { // Chauncey: large, in the background, no contact damage + var cx = V.sx(21), top = V.sy(13.3), bot = V.sy(2.3), sway = Math.sin(t * 1.3) * 3; + x.save(); x.globalAlpha = o.carrotDead ? .45 : .92; + hose(x, cx - 5, top + 8, cx - 30 + sway, top - 30, -6, 12, '#5e9a52'); hose(x, cx + 5, top + 8, cx + 34 + sway, top - 34, 6, 12, '#5e9a52'); hose(x, cx, top + 6, cx + sway, top - 40, 0, 10, '#4f8a43'); + x.beginPath(); x.moveTo(cx - 80, top + 18); x.quadraticCurveTo(cx, top - 16, cx + 80, top + 18); x.quadraticCurveTo(cx + 40, bot - 60, cx + 4, bot + 60); x.quadraticCurveTo(cx - 40, bot - 60, cx - 80, top + 18); x.closePath(); fillInk(x, lit(o.hitFlash > 0, '#ec8f3b'), 3.4); + for (var k = 0; k < 3; k++) { x.beginPath(); x.moveTo(cx - 34 + k * 3, top + 36 + k * 9); x.quadraticCurveTo(cx, top + 30 + k * 9, cx + 34 - k * 3, top + 36 + k * 9); inkStroke(x, 2.4, '#a3561d'); } + var eyeOpen = o.st === 'eye_antic' ? 1 - Math.max(0, o.timer) / .8 : o.st === 'eye' ? 1 : 0, ey = top + 70; + if (eyeOpen > 0) { A.glow(x, cx, ey, 46 * eyeOpen, '255,240,150', .7 * eyeOpen); ell(x, cx, ey, 16, 12 * eyeOpen + .5, '#fff6c9', 2.4); ell(x, cx, ey, 6, 7 * eyeOpen + .5, '#7b3fb3', 0); } + else { x.beginPath(); x.moveTo(cx - 14, ey); x.quadraticCurveTo(cx, ey + 6, cx + 14, ey); inkStroke(x, 2.6); } + if (dead || o.carrotDead) dazed(x, cx, top + 112, 1.7); else pieEyes(x, cx, top + 112, 1.7, 0, false, true); + smile(x, cx, top + 140, 16, o.st === 'carrots'); + if (o.st === 'carrots') { hose(x, cx - 60, top + 120, cx - 22, top + 46, 10, 5); glove(x, cx - 22, top + 46, 7, WHITE, 1); hose(x, cx + 60, top + 120, cx + 22, top + 46, -10, 5); glove(x, cx + 22, top + 46, 7, WHITE, -1); } + x.restore(); + } else if (form === 'potato') { + var pxp = V.sx(23), spit = o.st === 'spit' && o.fireT > .12, puff = o.st === 'spit_antic'; + mound(x, pxp + 6, 96); + x.beginPath(); x.moveTo(pxp - 62, F - 6); x.bezierCurveTo(pxp - 76, F - 120, pxp - 30, F - 150, pxp + 10, F - 146); x.bezierCurveTo(pxp + 66, F - 140, pxp + 78, F - 70, pxp + 62, F - 6); x.closePath(); fillInk(x, lit(o.hitFlash > 0, '#b98955'), 3.2); + for (var i = 0; i < 6; i++) ell(x, pxp - 30 + H(i) * 80, F - 120 + H(i + 9) * 90, 5, 3, '#8a6338', 0); + if (dead) dazed(x, pxp - 22, F - 92, 2); else pieEyes(x, pxp - 22, F - 92, 2, -1, false, true); + ell(x, pxp - 50, F - 70, 9, 7, '#a77546', 2); + if (spit) { ell(x, pxp - 58, F - 28, 13, 11, '#4a2416', 2.6); } else { x.beginPath(); x.moveTo(pxp - 62, F - 36); x.quadraticCurveTo(pxp - 48, F - (puff ? 26 : 42), pxp - 30, F - 34); inkStroke(x, 3); if (puff) ell(x, pxp - 44, F - 40, 14, 10, '#c99766', 2); } + } else if (form === 'onion') { + var pxo = V.sx(13.5), cry = o.angry, look = o.st === 'look' ? Math.sin(t * 1.6) : 0; + mound(x, pxo, 80); + x.beginPath(); x.moveTo(pxo, F - 168); x.bezierCurveTo(pxo + 10, F - 140, pxo + 62, F - 120, pxo + 54, F - 50); x.quadraticCurveTo(pxo + 44, F - 4, pxo, F - 4); x.quadraticCurveTo(pxo - 44, F - 4, pxo - 54, F - 50); x.bezierCurveTo(pxo - 62, F - 120, pxo - 10, F - 140, pxo, F - 168); x.closePath(); fillInk(x, lit(o.hitFlash > 0, '#efe2bf'), 3.2); + for (var s2 = -1; s2 <= 1; s2 += 2) { x.beginPath(); x.moveTo(pxo, F - 160); x.quadraticCurveTo(pxo + s2 * 44, F - 100, pxo + s2 * 24, F - 8); inkStroke(x, 2, '#c7ae7a'); } + hose(x, pxo, F - 166, pxo - 14, F - 196, -5, 7, '#6e9a5e'); hose(x, pxo, F - 166, pxo + 16, F - 190, 5, 7, '#6e9a5e'); + pieEyes(x, pxo + look * 6, F - 100, 1.8, look, false, false); + if (cry) for (var e = -1; e <= 1; e += 2) { x.save(); x.globalAlpha = .8; x.fillStyle = '#7cc3e6'; x.fillRect(pxo + e * 11 + look * 6 - 3, F - 92, 6, 60 + 8 * Math.sin(t * 20 + e)); x.restore(); for (var b2 = -1; b2 <= 1; b2 += 2) { x.beginPath(); x.moveTo(pxo + e * 4 + look * 6, F - 118); x.lineTo(pxo + e * 16 + look * 6, F - 112); inkStroke(x, 3); } } + ell(x, pxo + look * 8, F - 80, 12, 9, '#9a5bb0', 2.4); + if (cry) { x.beginPath(); x.moveTo(pxo - 14, F - 56); x.quadraticCurveTo(pxo - 7, F - 64, pxo, F - 56); x.quadraticCurveTo(pxo + 7, F - 64, pxo + 14, F - 56); inkStroke(x, 3); } else smile(x, pxo + look * 4, F - 62, 10, false); + } + if (o.radishHp > 0 || (o.secret && dead)) { // Horace Radiche: spinning chaser + var rx = V.sx(o.radishX), spin = t * 14, ry = F - 34; + for (var l = 0; l < 3; l++) { var a = spin + l * TAU / 3; hose(x, rx, ry - 26, rx + Math.cos(a) * 30, ry - 26 + Math.sin(a) * 9 - 14, 5, 6, '#5e9a52'); } + ell(x, rx, ry, 23, 31, lit(o.hitFlash > 0, '#d65a7a'), 3); pieEyes(x, rx, ry - 6, .9, o.radishF, false, true); ell(x, rx + o.radishF * 4, ry + 4, 5, 4, '#7e3d8a', 1.6); + x.beginPath(); x.moveTo(rx - 10, ry + 14); for (var z = 0; z < 5; z++) x.lineTo(rx - 10 + z * 5 + 2.5, ry + (z % 2 ? 14 : 20)); x.lineTo(rx + 12, ry + 14); x.closePath(); fillInk(x, WHITE, 1.6); + } + } + B.BOSS_DRAW['cuphead/root_pack'] = { hazards: hazards, body: rootBody }; + + // ---------- Hilda Berg ---------- + function constellationDots(x, pts, t) { x.save(); x.globalAlpha = .7; x.beginPath(); pts.forEach(function (p, i) { if (i) x.lineTo(p[0], p[1]); else x.moveTo(p[0], p[1]); }); x.setLineDash([3, 5]); inkStroke(x, 1.4, '#fff3c4'); x.restore(); pts.forEach(function (p, i) { star(x, p[0], p[1], 4 + Math.sin(t * 5 + i), 1.6, 4, 0, '#fff3c4', 0); }); } + function cloud(x, cx, cy, w, h, fill) { // outline only on the silhouette: wide stroke, then fill on top + var path = function () { x.beginPath(); for (var i = 0; i <= 8; i++) { var a = Math.PI + i / 8 * Math.PI, bx = cx + Math.cos(a) * w, by = cy + Math.sin(a) * h; x.moveTo(bx + h * .55, by); x.arc(bx, by, h * .55, 0, TAU); } x.moveTo(cx + w, cy + h * .25); x.ellipse(cx, cy + h * .25, w, h * .6, 0, 0, TAU); }; + path(); inkStroke(x, 5); path(); x.fillStyle = fill; x.fill(); + } + function hildaFace(x, hx, hy, s, laugh, look) { + x.save(); x.translate(hx, hy); x.scale(s, s); + ell(x, 0, 0, 15, 17, '#f6c9b6', 2.4); + x.beginPath(); x.moveTo(-13, -2); x.lineTo(-30, 3); x.lineTo(-12, 7); fillInk(x, '#f6c9b6', 2.2); + x.beginPath(); x.moveTo(-16, -6); x.quadraticCurveTo(-12, -24, 6, -20); x.quadraticCurveTo(18, -17, 16, -4); x.quadraticCurveTo(8, -12, 2, -10); x.quadraticCurveTo(-6, -16, -16, -6); x.closePath(); fillInk(x, '#6a2430', 2.2); + pieEyes(x, -3, -3, .55, -1); smile(x, -6, 9, 5, laugh); ell(x, 6, 4, 3, 2, '#ef9a8f', 0); + x.restore(); + } + function hildaBody(x, c, t, V) { + var o = c.boss, px = V.sx(o.x), py = V.sy(o.y), dead = o.st === 'dead', flash = o.hitFlash > 0; + if (o.st === 'transition') { x.save(); x.globalAlpha = .75; star(x, px, py, 46, 20, 5, t * 4, '#fff3c4', 2); x.restore(); return; } + if (dead && o.form !== 'moon') { x.save(); x.translate(px, py + 30 + Math.sin(t * 7) * 4); x.rotate(.25 + Math.sin(t * 5) * .08); ell(x, 4, 8, 50, 18, '#b9473c', 3); hildaFace(x, -10, -24, 1, true, -1); dazed(x, -13, -27, .6); x.restore(); return; } + if (o.form === 'moon') { + var mx = V.sx(27.6), my = V.sy(7.8), out = o.faceOut; + x.beginPath(); x.arc(mx, my, 190, Math.PI * .5, Math.PI * 1.5); x.quadraticCurveTo(V.sx(25.2), my, mx, my + 190); x.closePath(); fillInk(x, lit(flash, '#c8402f'), 3.6); + for (var cr = 0; cr < 5; cr++) ell(x, V.sx(23.2) + H(cr) * 36, my - 130 + cr * 60, 9 + H(cr + 3) * 8, 7 + H(cr + 5) * 5, '#a83526', 1.6); + var fx = V.sx(out ? 19.6 : 22.6), fy = my; + if (out) for (var gq = 0; gq < 3; gq++) star(x, fx + 40 + gq * 22, fy - 20 + gq * 22, 13, 9, 8, t * 3 * (gq % 2 ? -1 : 1), GOLD, 2); + x.save(); x.translate(fx, fy); ell(x, 0, 0, 40, 62, lit(flash, '#f2c7b4'), 3); x.beginPath(); x.moveTo(-30, -6); x.lineTo(-70, 18); x.lineTo(-26, 16); fillInk(x, '#f2c7b4', 2.6); + if (dead) dazed(x, -6, -14, 2.2); else pieEyes(x, -6, -14, 2.2, -1, false, true); smile(x, -10, 30, 16, !dead && Math.sin(t * 8) > 0); x.restore(); + return; + } + if (o.form === 'taurus') { + cloud(x, px + 10, py + 10, 52, 30, lit(flash, '#eef1f6')); + x.save(); x.translate(px - 34, py - 8); var lower = o.st === 'horn_antic' ? .2 : 0; x.rotate(lower); + x.beginPath(); x.moveTo(-8, -20); x.quadraticCurveTo(-40, -44, -54, -30); x.quadraticCurveTo(-34, -32, -20, -10); fillInk(x, GOLD, 2.2); + ell(x, 0, 0, 26, 22, lit(flash, '#f2b9ad'), 2.6); pieEyes(x, -4, -4, .8, -1, false, true); ell(x, -18, 8, 9, 7, '#e79c8f', 2); x.beginPath(); x.arc(-20, 16, 6, 0, TAU); inkStroke(x, 2.4, GOLD); x.restore(); + if (o.st === 'horn_antic') { x.save(); x.setLineDash([8, 6]); x.strokeStyle = RED; x.lineWidth = 2; x.strokeRect(0, V.sy(o.targetY) - 19, V.sx(24), 38); x.restore(); } + if (o.st === 'horn') { var hy = V.sy(o.targetY); x.beginPath(); x.moveTo(px - 30, hy - 18); x.lineTo(V.sx(0), hy); x.lineTo(px - 30, hy + 18); x.closePath(); fillInk(x, GOLD, 2.6); x.beginPath(); x.moveTo(px - 30, hy - 9); x.lineTo(V.sx(1.2), hy); inkStroke(x, 2, '#fff1b8'); } + constellationDots(x, [[px - 60, py - 46], [px - 20, py - 30], [px + 30, py - 24], [px + 58, py + 4], [px + 20, py + 34]], t); + return; + } + if (o.form === 'gemini') { + cloud(x, px, py + 22, 54, 26, lit(flash, '#eef1f6')); + for (var j2 = -1; j2 <= 1; j2 += 2) { var ang = t * 1.4 + (j2 > 0 ? Math.PI : 0), tx = px + Math.cos(ang) * 28, ty = py - 12 + Math.sin(ang) * 8; hildaFace(x, tx, ty, .9, false, -1); } + ell(x, px, py + 4, 15, 15, '#b9a3ee', 2.6); ell(x, px - 5, py - 1, 5, 4, 'rgba(255,255,255,.7)', 0); + if (o.st === 'vortex' && o.attackT > 1.7) { var vx = V.sx(o.vortexX), vy = V.sy(8); for (var q = 0; q < 4; q++) { x.beginPath(); x.arc(vx, vy, 10 + q * 7, o.angle * (q % 2 ? -1 : 1) + q, o.angle * (q % 2 ? -1 : 1) + q + 4.4); inkStroke(x, 3, q % 2 ? '#e8ddff' : '#8f78d8'); } } + constellationDots(x, [[px - 40, py - 40], [px - 10, py - 54], [px + 26, py - 44], [px + 50, py - 12]], t); + return; + } + if (o.form === 'sagittarius') { + cloud(x, px + 12, py + 20, 50, 28, lit(flash, '#eef1f6')); + ell(x, px - 8, py - 18, 17, 22, lit(flash, '#f2b9ad'), 2.6); hildaFace(x, px - 12, py - 46, .9, false, -1); + var pull = o.st === 'arrow_antic' ? Math.min(1, (.7 - Math.max(0, o.timer)) / .7) : 0; + x.beginPath(); x.arc(px - 38, py - 20, 34, Math.PI * .6, Math.PI * 1.4); inkStroke(x, 4, GOLD); + x.beginPath(); x.moveTo(px - 38 + Math.cos(Math.PI * .6) * 34, py - 20 + Math.sin(Math.PI * .6) * 34); x.lineTo(px - 46 + pull * 22, py - 20); x.lineTo(px - 38 + Math.cos(Math.PI * 1.4) * 34, py - 20 + Math.sin(Math.PI * 1.4) * 34); inkStroke(x, 1.4, '#fff3c4'); + if (o.st === 'arrow_antic') { x.save(); x.setLineDash([8, 6]); x.strokeStyle = RED; x.lineWidth = 2; x.beginPath(); x.moveTo(px - 60, V.sy(o.targetY)); x.lineTo(0, V.sy(o.targetY)); x.stroke(); x.restore(); } + constellationDots(x, [[px - 50, py - 60], [px - 14, py - 70], [px + 20, py - 40], [px + 56, py + 6]], t); + return; + } + // normal blimp form: Hilda riding her zeppelin body + var bob = Math.sin(t * 3) * 2; + x.save(); x.translate(px, py + bob); + x.beginPath(); x.moveTo(44, -8); x.lineTo(66, -30); x.lineTo(62, -2); x.closePath(); fillInk(x, '#a82a22', 2.4); x.beginPath(); x.moveTo(44, 10); x.lineTo(66, 30); x.lineTo(60, 6); x.closePath(); fillInk(x, '#a82a22', 2.4); + ell(x, 66, 0, 3, 3, INK, 0); x.save(); x.globalAlpha = .55; ell(x, 69, 0, 2.5, 6 + 12 * Math.abs(Math.sin(t * 37)), '#efe3c9', 1.2); x.restore(); + ell(x, 4, 8, 58, 28, lit(flash, RED), 3); x.beginPath(); x.ellipse(4, 14, 54, 18, 0, .1, Math.PI - .1); inkStroke(x, 2, DRED); + ell(x, 2, 44, 10, 10, WHITE, 2.4); ell(x, 2, 44, 3, 3, INK, 0); hose(x, 2, 34, 2, 44, 0, 3); + ell(x, -14, -22, 13, 12, '#c84434', 2.4); + hildaFace(x, -16, -44, 1.1, o.move === 'laughter' && o.fireT > (o.mode === 2 ? 1.1 : 1.4), -1); + x.beginPath(); x.moveTo(-14, -68); x.lineTo(-14, -84); inkStroke(x, 2.4); x.beginPath(); x.moveTo(-24, -84); x.lineTo(-4, -84); x.lineTo(-10, -90); inkStroke(x, 2.4, GOLD); + hose(x, -24, -24, -42, -30, -4, 4); glove(x, -44, -31, 4.5, WHITE, -1); + if (dead) { x.save(); x.globalAlpha = .7; for (var sp = 0; sp < 3; sp++) ell(x, -60 - sp * 16, -10 + Math.sin(t * 10 + sp) * 8, 7 - sp, 5 - sp, '#cfc6b8', 1.6); x.restore(); } + x.restore(); + } + B.BOSS_DRAW['cuphead/hilda'] = { hazards: hazards, body: hildaBody }; + B.CUP_DRAW = { ell: ell, hose: hose, pieEyes: pieEyes, star: star, banner: banner, glove: glove, smile: smile, dazed: dazed, rrect: rrect, lit: lit, pinkGlow: pinkGlow, cloud: cloud, hazards: hazards, + inkStroke: inkStroke, fillInk: fillInk, H: H, setBoil: function (t) { boil = Math.floor(t * 12); }, C: { INK: INK, PAPER: PAPER, WHITE: WHITE, RED: RED, DRED: DRED, PINK: PINK, PINK_HI: PINK_HI, BLUE: BLUE, GOLD: GOLD, PURPLE: PURPLE, GREEN: GREEN } }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/draw/figures_v5.js b/environments/games/web/games/cuphead_remake/draw/figures_v5.js new file mode 100644 index 0000000000000000000000000000000000000000..e3f25fc8f2fb849446c138e7f0e251a96479b1b6 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/draw/figures_v5.js @@ -0,0 +1,193 @@ +// v5: original procedural "1930s rubber-hose" art for the three expansion cases (Cagney Carnation, Ribby and Croaks, +// Wally Warbles). Pure presentation like draw/figures.js: reads the Case, never writes simulation state, never consumes +// game RNG. Shared enemy projectiles fall back to figures.js hazards(); the kinds new in v5 are drawn here. +(function (g) { + var B = g.BB, D = B.CUP_DRAW, A = B.ART, TAU = Math.PI * 2, K = D.C, INK = K.INK, WHITE = K.WHITE, PINK = K.PINK, GOLD = K.GOLD; + var ell = D.ell, hose = D.hose, pieEyes = D.pieEyes, star = D.star, glove = D.glove, smile = D.smile, dazed = D.dazed, lit = D.lit, H = D.H; + function stroke(x, w, c) { D.inkStroke(x, w, c); } + function fill(x, f, w) { D.fillInk(x, f, w); } + + // ---------- projectiles new in v5 (unknown kinds fall through to the shared drawer) ---------- + function hazards(x, c, t, V) { + D.setBoil(t); + var rest = []; + c.boss.projectiles.forEach(function (p) { + if (p.removed) return; + var px = V.sx(p.x), py = V.sy(p.y), r = p.r * 30; + if (p.pink) D.pinkGlow(x, px, py, Math.max(r, 12), t); + switch (p.kind) { + case 'seed_blue': case 'seed_purple': case 'seed_pink': + ell(x, px, py, r + 2, r + 5, p.kind === 'seed_blue' ? '#5aa2d8' : p.kind === 'seed_purple' ? '#8e63b8' : PINK, 2, Math.atan2(-p.vy, p.vx)); break; + case 'chaser': // green toothy terror on a vine, homing + ell(x, px, py, 15, 12, '#6fae5a', 2.4); x.beginPath(); x.moveTo(px - 10, py + 1); for (var k = 0; k < 5; k++) x.lineTo(px - 8 + k * 4, py + (k % 2 ? 6 : 1)); stroke(x, 2); pieEyes(x, px + 2, py - 5, .45, 0, false, true); break; + case 'baby_terror': + ell(x, px, py + 2, 14, 11, '#4f8f45', 2.4); x.beginPath(); x.moveTo(px - 11, py + 2); for (var q = 0; q < 6; q++) x.lineTo(px - 10 + q * 4, py + (q % 2 ? -4 : 2)); stroke(x, 2, WHITE); hose(x, px - 6, py + 12, px - 12, py + 18, -2, 3, '#3f6a35'); hose(x, px + 6, py + 12, px + 12, py + 18, 2, 3, '#3f6a35'); break; + case 'floater': + for (var f = 0; f < 4; f++) { var a = f / 4 * TAU + t * 2; ell(x, px + Math.cos(a) * 14, py + Math.sin(a) * 10, 10, 6, '#f39a3a', 2, a); } + ell(x, px, py, 11, 11, p.fire < .7 ? '#ffe36b' : '#e9b84a', 2.4); if (p.fire < .7) ell(x, px, py + 2, 5, 5 * (1 - p.fire / .7) + 1, '#6b2a1a', 0); break; + case 'floater_shot': case 'zap': + ell(x, px, py, r + 2, r + 2, PINK, 2); ell(x, px - 2, py - 2, 2.4, 2.4, K.PINK_HI, 0); break; + case 'sycamore': + x.save(); x.translate(px, py); x.rotate(t * 12); for (var w = 0; w < 2; w++) { x.rotate(Math.PI); x.beginPath(); x.moveTo(0, 0); x.quadraticCurveTo(10, -18, 26, -6); x.quadraticCurveTo(14, -2, 0, 0); fill(x, '#c99a52', 2); } ell(x, 0, 0, 7, 7, '#8a5a2c', 2); x.restore(); pieEyes(x, px, py, .35); break; + case 'acorn': + ell(x, px, py + 2, r + 2, r + 4, '#b9773d', 2.2); ell(x, px, py - r + 1, r + 4, r * .55 + 2, '#6b4426', 2); break; + case 'pollen': + for (var s = 0; s < 8; s++) { var sa = s / 8 * TAU + t; x.beginPath(); x.moveTo(px, py); x.lineTo(px + Math.cos(sa) * 14, py + Math.sin(sa) * 14); stroke(x, 1.4, p.pink ? PINK : '#e8e2d0'); } + ell(x, px, py, 5, 5, p.pink ? PINK : '#f7f1df', 1.6); break; + case 'firefly': + x.save(); x.globalAlpha = .45; ell(x, px, py, 15, 15, '#ffe36b', 0); x.restore(); ell(x, px, py, 9, 10, '#ffd34a', 2.2); pieEyes(x, px, py - 3, .35); break; + case 'fist': + glove(x, px, py, 15, p.pink ? PINK : '#f0a63a', p.vx > 0 ? 1 : -1); x.save(); x.globalAlpha = .5; for (var tr = 1; tr <= 3; tr++) ell(x, px - (p.vx > 0 ? 1 : -1) * tr * 12, py, 9 - tr * 2, 7 - tr * 1.5, p.pink ? PINK : '#f7c870', 0); x.restore(); break; + case 'ball': + ell(x, px, py, r + 2, r + 2, '#5d8fd0', 2.6); x.beginPath(); x.ellipse(px, py, r + 2, (r + 2) * .35, t * 3, 0, TAU); stroke(x, 2, '#e9eef8'); break; + case 'coin': + ell(x, px, py, r + 3, r + 3, GOLD, 2.2); x.font = 'bold 10px Georgia, serif'; x.textAlign = 'center'; x.textBaseline = 'middle'; x.fillStyle = '#7a5418'; x.fillText('¢', px, py + 1); break; + case 'tiger_ball': + ell(x, px, py, r + 2, r + 2, '#f08a2c', 2.6); for (var tb = -1; tb <= 1; tb++) { x.beginPath(); x.moveTo(px + tb * 6, py - 12); x.lineTo(px + tb * 5, py - 4); stroke(x, 2.4); } break; + case 'chip_tiger': case 'chip_snake': case 'chip_bison': + var col = p.kind === 'chip_tiger' ? '#f08a2c' : p.kind === 'chip_snake' ? '#5fae58' : '#d24c3c', w2 = p.w * 30; + x.beginPath(); x.ellipse(px, py, w2 / 2, 10, 0, 0, TAU); fill(x, col, 2.6); x.beginPath(); x.ellipse(px, py - 3, w2 / 2 - 8, 4, 0, 0, TAU); fill(x, 'rgba(255,255,255,.35)', 0); + for (var sp = -1; sp <= 1; sp += 2) { x.beginPath(); x.moveTo(px + sp * (w2 / 2 - 2), py - 9); x.lineTo(px + sp * (w2 / 2 + 11), py); x.lineTo(px + sp * (w2 / 2 - 2), py + 9); x.closePath(); fill(x, '#d9d4c4', 2); } + if (p.kind === 'chip_bison') { + var up = p.jetUp, yEnd = up ? V.sy(15) : V.FLOOR; + if (p.parked && !p.fired) { x.save(); x.setLineDash([6, 6]); x.beginPath(); x.moveTo(px, py + (up ? -10 : 10)); x.lineTo(px, yEnd); stroke(x, 2, '#d64e4e'); x.restore(); } + if (p.jet > 0) { x.fillStyle = 'rgba(255,170,60,.85)'; x.fillRect(px - 14, Math.min(py, yEnd), 28, Math.abs(yEnd - py)); x.fillStyle = 'rgba(255,240,170,.9)'; x.fillRect(px - 5, Math.min(py, yEnd), 10, Math.abs(yEnd - py)); } + } + break; + case 'egg': ell(x, px, py, r + 3, r + 6, '#f4ead2', 2.2, Math.PI / 2); break; + case 'egg_shard': x.beginPath(); x.moveTo(px - 6, py - 4); x.lineTo(px + 6, py - 2); x.lineTo(px - 2, py + 6); x.closePath(); fill(x, '#f4ead2', 1.8); break; + case 'big_bullet': ell(x, px, py, r + 1, r + 1, '#d9544a', 2.6); ell(x, px - 5, py - 5, 4, 3, 'rgba(255,255,255,.6)', 0); break; + case 'feather': x.save(); x.translate(px, py); x.rotate(Math.atan2(-p.vy, p.vx)); x.beginPath(); x.ellipse(0, 0, 13, 4, 0, 0, TAU); fill(x, '#6c86c9', 1.8); x.beginPath(); x.moveTo(-13, 0); x.lineTo(13, 0); stroke(x, 1.2, '#dfe7fb'); x.restore(); break; + case 'nail_bird': + ell(x, px, py, 14, 10, p.pink ? PINK : '#f2cf45', 2.2); x.beginPath(); x.moveTo(px - 14, py); x.lineTo(px - 22, py + 3); x.lineTo(px - 14, py + 4); x.closePath(); fill(x, '#e88a2c', 1.6); + x.beginPath(); x.moveTo(px, py + 10); x.lineTo(px, py + 24); stroke(x, 2.4, '#8b8f96'); x.beginPath(); x.moveTo(px - 4, py + 24); x.lineTo(px + 4, py + 24); stroke(x, 2.4, '#8b8f96'); pieEyes(x, px - 4, py - 2, .3, -1); break; + case 'pill': case 'pill_half': + x.save(); x.translate(px, py); x.rotate(Math.atan2(-p.vy, p.vx)); x.beginPath(); x.ellipse(0, 0, p.kind === 'pill' ? 13 : 8, 6, 0, 0, TAU); fill(x, p.pink ? PINK : '#9fc4ef', 2); if (p.kind === 'pill') { x.fillStyle = WHITE; x.fillRect(0, -5, 12, 10); } x.restore(); break; + case 'trash': ell(x, px, py, r + 2, r + 2, ['#9aa3a0', '#c25b3c', '#b9b28c'][p.id % 3], 2); break; + case 'boot': x.beginPath(); x.moveTo(px - 10, py - 10); x.lineTo(px + 2, py - 10); x.lineTo(px + 4, py + 2); x.lineTo(px + 12, py + 4); x.lineTo(px + 12, py + 10); x.lineTo(px - 10, py + 10); x.closePath(); fill(x, PINK, 2.2); break; + case 'heart_bullet': ell(x, px, py, r + 2, r + 2, '#d8443c', 2); break; + default: rest.push(p); + } + }); + if (rest.length) { var hold = c.boss.projectiles; c.boss.projectiles = rest; try { D.hazards(x, c, t, V); } finally { c.boss.projectiles = hold; } } + } + + // ---------- Cagney Carnation ---------- + function platformsArt(x, c, t, V) { + var o = c.boss; + (B.CAGNEY_PLATS || []).forEach(function (p) { + var l = V.sx(p.x - p.w / 2), r2 = V.sx(p.x + p.w / 2), y = V.sy(p.y), v = o.vines && o.vines[p.id]; + x.beginPath(); x.ellipse((l + r2) / 2, y + 7, (r2 - l) / 2, 9, 0, 0, TAU); fill(x, '#d9473c', 2.6); + for (var d = 0; d < 5; d++) ell(x, l + 12 + d * ((r2 - l - 24) / 4), y + 6, 4, 3, WHITE, 0); + if (v) { // vine telegraph (grow) and encasing vines + var h = v.st === 'grow' ? 14 : 64; + for (var k = 0; k < 4; k++) { var vx2 = l + 10 + k * ((r2 - l - 20) / 3); x.beginPath(); x.moveTo(vx2, y + 16); x.quadraticCurveTo(vx2 + 10 * Math.sin(t * 6 + k), y - h / 2, vx2, y - h + 10); stroke(x, v.st === 'grow' ? 3 : 6, '#3f7a35'); } + if (v.st === 'encased') for (var th = 0; th < 6; th++) { x.beginPath(); x.moveTo(l + 8 + th * 14, y - 10 - (th % 2) * 18); x.lineTo(l + 14 + th * 14, y - 18 - (th % 2) * 18); stroke(x, 2, '#e8d58a'); } + } + }); + if (o.phase === 1 && o.st !== 'transition') { // thorn floor + for (var q = 0; q < 40; q++) { var tx = 4 + q * 21.6; x.beginPath(); x.moveTo(tx - 9, V.FLOOR); x.lineTo(tx, V.FLOOR - 12 - 3 * Math.sin(q)); x.lineTo(tx + 9, V.FLOOR); x.closePath(); fill(x, '#3f6a2f', 1.6); } + } + } + function cagneyBody(x, c, t, V) { + var o = c.boss, cx = V.sx(o.x), base = V.FLOOR, dead = o.st === 'dead', angry = o.phase === 1, flash = o.hitFlash > 0, sway = dead ? 0 : Math.sin(t * 2.4) * 8; + platformsArt(x, c, t, V); + hose(x, cx, base, cx + sway * .4, base - 150, sway, 16, '#4f8a43'); hose(x, cx, base, cx + sway * .4, base - 150, sway, 10, angry ? '#3d6d33' : '#5fa04f'); + if (angry) for (var th = 0; th < 6; th++) { var ty = base - 20 - th * 22; x.beginPath(); x.moveTo(cx + sway * .3 + 6, ty); x.lineTo(cx + sway * .3 + 16, ty - 5); stroke(x, 2.4, '#e8d58a'); } + for (var lf = -1; lf <= 1; lf += 2) { x.beginPath(); x.ellipse(cx + lf * 26, base - 30, 22, 9, lf * .5, 0, TAU); fill(x, '#6fae5a', 2.2); } + var hx = cx + sway * .6, hy = base - 175, lunge = o.st === 'lunge' || o.st === 'lunge_antic'; + if (lunge) { // face and arms lash along the chosen lane + var lane = V.sy(o.lungeBox().y), reach = o.st === 'lunge' ? V.sx(o.lungeBox().x - o.lungeBox().w / 2) : hx - 30; + if (o.st === 'lunge_antic') { var lb = o.lungeBox(); x.save(); x.globalAlpha = .22; x.fillStyle = K.RED; x.fillRect(V.sx(lb.x - lb.w / 2), V.sy(lb.y + lb.h / 2), lb.w * 30, lb.h * 30); x.restore(); } + hose(x, hx, hy + 40, reach + 30, lane, 20, 14, '#5fa04f'); glove(x, reach + 22, lane - 12, 14, '#6fae5a', -1); glove(x, reach + 22, lane + 12, 14, '#6fae5a', -1); + hx = reach + 60; hy = lane; + } + var petals = angry ? 8 : 6, pr = angry ? 46 : 40; + for (var p = 0; p < petals; p++) { var a = p / petals * TAU + (angry ? Math.sin(t * 6) * .05 : 0); x.save(); x.translate(hx + Math.cos(a) * pr * .72, hy + Math.sin(a) * pr * .72); x.rotate(a); + x.beginPath(); x.moveTo(-pr * .5, -16); x.quadraticCurveTo(pr * .3, -24, pr * .55, 0); x.quadraticCurveTo(pr * .3, 24, -pr * .5, 16); x.closePath(); fill(x, lit(flash, angry ? '#ef6f3a' : '#f59b3e'), 2.4); x.restore(); } + ell(x, hx, hy, 34, 36, lit(flash, angry ? '#f6d24a' : '#f7dd6a'), 3); + if (dead) { x.beginPath(); x.ellipse(hx - 10, hy - 6, 8, 10, 0, 0, TAU); x.fillStyle = INK; x.fill(); x.beginPath(); x.ellipse(hx + 10, hy - 6, 8, 10, 0, 0, TAU); x.fill(); } + else pieEyes(x, hx - 4, hy - 8, angry ? 1.35 : 1.1, -1, false, angry); + x.beginPath(); x.moveTo(hx - 4, hy + 2); x.lineTo(hx - (angry ? 30 : 18), hy + (angry ? -2 : 6)); x.lineTo(hx - 2, hy + 10); fill(x, angry ? '#f2c23a' : '#f5cf5a', 2); + if (angry || o.st === 'gatling' || o.st === 'p2') { x.beginPath(); x.ellipse(hx + 2, hy + 18, 16, 10, 0, 0, Math.PI); fill(x, '#7a1d1a', 2.4); for (var tt = 0; tt < 6; tt++) { x.beginPath(); x.moveTo(hx - 12 + tt * 5, hy + 18); x.lineTo(hx - 10 + tt * 5, hy + 24); stroke(x, 2, WHITE); } } + else smile(x, hx + 2, hy + 16, 12, false); + if (o.st === 'hands_antic') { glove(x, hx - 52, hy + 30, 12, '#6fae5a', -1); glove(x, hx - 38, hy + 40, 12, '#6fae5a', -1); star(x, hx - 56, hy + 16, 8 + 3 * Math.sin(t * 20), 3, 4, t * 4, '#fff3b0', 0); } + } + B.BOSS_DRAW['cuphead/cagney'] = { hazards: hazards, body: cagneyBody }; + + // ---------- Ribby and Croaks ---------- + function frog(x, fx, base, s, col, belly, look, open, flash, dead, spin) { + x.save(); x.translate(fx, base); x.scale(s * (spin ? Math.cos(spin) : 1), s); + hose(x, -18, -14, -30, 0, -6, 7, col); hose(x, 18, -14, 30, 0, 6, 7, col); ell(x, -32, -2, 10, 4, col, 2); ell(x, 32, -2, 10, 4, col, 2); + x.beginPath(); x.moveTo(-30, -10); x.bezierCurveTo(-36, -70, 36, -70, 30, -10); x.quadraticCurveTo(0, 4, -30, -10); x.closePath(); fill(x, lit(flash, col), 3); + ell(x, 0, -28, 18, 16, belly, 0); + ell(x, -12, -70, 12, 12, lit(flash, col), 2.6); ell(x, 12, -70, 12, 12, lit(flash, col), 2.6); + if (dead) { dazed(x, 0, -70, 1.1); } else pieEyes(x, look * 2, -70, 1.1, look); + if (open) { x.beginPath(); x.ellipse(0, -46, 18, 9, 0, 0, TAU); fill(x, '#5a1d18', 2.4); } else smile(x, 0, -48, 14, false); + x.restore(); + } + function ribbyBody(x, c, t, V) { + var o = c.boss, base = V.FLOOR, dead = o.st === 'dead', flash = o.hitFlash > 0; + if (o.phase === 2 && o.st !== 'transition') return slotMachine(x, c, t, V); + var rx = V.sx(o.roll ? o.roll.x : o.ribbyX), cx = V.sx(o.croaksX), look = o.phase === 0 ? -1 : 1; + if (o.roll) { x.save(); x.translate(rx, base - 24); x.rotate(t * 14 * Math.sign(o.roll.vx)); ell(x, 0, 0, 26, 24, '#79b65a', 3); x.beginPath(); x.arc(0, 0, 18, 0, 4); stroke(x, 2.4, '#4f8a43'); x.restore(); } + else frog(x, rx, base, 1, '#79b65a', '#e8e0b0', look, o.fistSeq.length > 0 && o.fistT < .25, flash, dead); + var fan = o.phase === 1 && o.fan > 0 ? t * 30 : 0; + frog(x, cx, base, 1.35, '#5f9a7a', '#dfe6c4', -1, o.flies > 0 || o.move === 'roll_into_croaks', flash, dead, fan); + if (fan) { x.save(); x.globalAlpha = .35; for (var w = 0; w < 5; w++) { var wy = base - 30 - w * 34, ph = (t * 3 + w * .3) % 1; x.beginPath(); x.moveTo(cx - 70 - ph * 200, wy); x.lineTo(cx - 130 - ph * 200, wy); stroke(x, 3, '#eaf2f8'); } x.restore(); } + } + function slotMachine(x, c, t, V) { + var o = c.boss, sx = V.sx(23.9), base = V.FLOOR, top = V.sy(8.8), flash = o.hitFlash > 0, dead = o.st === 'dead', open = o.opened; + x.beginPath(); x.moveTo(sx - 76, base); x.lineTo(sx - 76, top + 40); x.quadraticCurveTo(sx - 76, top, sx - 36, top); x.lineTo(sx + 76, top); x.lineTo(sx + 76, base); x.closePath(); fill(x, lit(flash, '#5f9a7a'), 3.4); + for (var r = -1; r <= 1; r++) { // reels + var rx = sx + r * 38 - 6, ry = top + 70; x.beginPath(); x.rect(rx - 15, ry - 22, 30, 44); fill(x, '#f6efd8', 2.4); + var sym = o.slot === 'spin' ? ['T', 'S', 'B'][Math.floor(t * 18 + r) % 3] : o.reel ? { tiger: 'T', snake: 'S', bison: 'B' }[o.reel] : '7'; + x.font = 'bold 20px Georgia, serif'; x.textAlign = 'center'; x.textBaseline = 'middle'; x.fillStyle = sym === 'T' ? '#e07a22' : sym === 'S' ? '#3f8f3a' : sym === 'B' ? '#c43c32' : '#7a5418'; x.fillText(sym, rx, ry + 1); + } + if (dead) { dazed(x, sx - 6, top + 130, 1.6); } else pieEyes(x, sx - 6, top + 130, 1.6, -1, !open, !open); + x.beginPath(); x.rect(sx - 46, base - 70, 70, 44); fill(x, o.slot === 'open' ? '#2a1712' : '#7a5038', 2.6); // hatch + var lx = V.sx(B.RIBBY_GEOM.LEVER.x), ly = V.sy(B.RIBBY_GEOM.LEVER.y), down = o.leverDown; + hose(x, sx - 76, top + 60, lx, down ? ly : top + 20, -6, 6, '#c9c2ae'); + if (down) D.pinkGlow(x, lx, ly, 14, t); + ell(x, lx, down ? ly : top + 20, 11, 11, down ? PINK : '#d9473c', 2.4); + } + B.BOSS_DRAW['cuphead/ribby_croaks'] = { hazards: hazards, body: ribbyBody }; + + // ---------- Wally Warbles ---------- + function wallyBody(x, c, t, V) { + var o = c.boss, flash = o.hitFlash > 0, dead = o.st === 'dead'; + if (o.phase <= 1) { + var px = V.sx(o.x), py = V.sy(o.y), whistle = o.st === 'whistle', tired = o.st === 'tired', flap = o.st === 'flap'; + x.beginPath(); x.moveTo(px - 54, py + 66); x.lineTo(px - 54, py - 30); x.lineTo(px, py - 76); x.lineTo(px + 54, py - 30); x.lineTo(px + 54, py + 66); x.closePath(); fill(x, lit(flash, '#a8643c'), 3); // birdhouse + x.beginPath(); x.moveTo(px - 66, py - 26); x.lineTo(px, py - 86); x.lineTo(px + 66, py - 26); stroke(x, 8, '#6a3a22'); + ell(x, px, py - 6, 30, 30, '#f4e8cc', 2.4); for (var hr = 0; hr < 12; hr++) { var ha = hr / 12 * TAU; x.beginPath(); x.moveTo(px + Math.cos(ha) * 24, py - 6 + Math.sin(ha) * 24); x.lineTo(px + Math.cos(ha) * 28, py - 6 + Math.sin(ha) * 28); stroke(x, 1.6); } + if (flap) for (var w = -1; w <= 1; w += 2) { x.save(); x.translate(px + w * 50, py + 10); x.rotate(w * (.4 + .5 * Math.sin(t * 30))); x.beginPath(); x.ellipse(w * 26, 0, 30, 12, 0, 0, TAU); fill(x, '#6c86c9', 2.4); x.restore(); } + var hx = px - 44, hy = py - 4; + if (whistle) { x.beginPath(); x.rect(hx - 14, hy - 30, 28, 40); fill(x, '#b9b5ad', 2.4); for (var s = 0; s < 3; s++) ell(x, hx - 6 + s * 8, hy - 44 - s * 10 - (t * 40) % 10, 8, 6, 'rgba(240,240,240,.8)', 0); } + else { ell(x, hx, hy, 24, 20, lit(flash, '#e04a3c'), 2.6); x.beginPath(); x.moveTo(hx - 18, hy + 2); x.lineTo(hx - 40, hy + (o.st === 'finger_antic' ? -6 : 6)); x.lineTo(hx - 16, hy + 10); x.closePath(); fill(x, GOLD, 2); + if (tired || dead) dazed(x, hx + 2, hy - 6, .8); else pieEyes(x, hx + 2, hy - 6, .8, -1, false, true); + if (o.st === 'finger_antic') for (var f = -1; f <= 1; f++) hose(x, hx - 30, hy, hx - 54, hy + f * 14, -3, 6, '#f2c9a0'); } + hose(x, px - 12, py + 66, px - 18, py + 96, -4, 4, GOLD); hose(x, px + 12, py + 66, px + 18, py + 96, 4, 4, GOLD); + return; + } + if (o.phase === 2) { + var wx = V.sx(o.willyX), wy = V.sy(o.willyY); + ell(x, wx, wy + 18, 30, 10, '#8a6a3a', 2.4); for (var n = 0; n < 6; n++) { x.beginPath(); x.moveTo(wx - 26 + n * 10, wy + 14); x.lineTo(wx - 22 + n * 10, wy + 22); stroke(x, 1.6, '#5a4224'); } + ell(x, wx, wy - 4, 18, 18, lit(flash, '#e04a3c'), 2.6); ell(x, wx, wy - 18, 13, 9, '#f2c9a0', 2); pieEyes(x, wx - 4, wy - 4, .7, -1); x.beginPath(); x.moveTo(wx - 12, wy + 2); x.lineTo(wx - 28, wy + 4); x.lineTo(wx - 12, wy + 8); fill(x, GOLD, 1.8); + o.eggs().forEach(function (e, k) { var ex = V.sx(e.x), ey = V.sy(e.y); ell(x, ex, ey, 13, 15, '#f4ead2', 2.2); for (var sp = 0; sp < 6; sp++) { var sa = sp / 6 * TAU + k; x.beginPath(); x.moveTo(ex + Math.cos(sa) * 12, ey + Math.sin(sa) * 14); x.lineTo(ex + Math.cos(sa) * 19, ey + Math.sin(sa) * 21); stroke(x, 2.2); } }); + return; + } + var sxp = V.sx(o.sx), sy = V.sy(4.4); + for (var m = -1; m <= 1; m += 2) { // paramedic birds + var bx = sxp + m * 70, by = sy + 6 + Math.sin(t * 12 + m) * 4; ell(x, bx, by, 18, 14, '#6c9ad6', 2.4); ell(x, bx, by - 14, 10, 6, WHITE, 2); x.beginPath(); x.moveTo(bx - 6, by - 16); x.lineTo(bx + 6, by - 16); stroke(x, 2, '#d9473c'); + x.save(); x.translate(bx + m * 16, by - 2); x.rotate(m * (.5 + .4 * Math.sin(t * 30))); x.beginPath(); x.ellipse(m * 12, 0, 14, 6, 0, 0, TAU); fill(x, '#86aee3', 2); x.restore(); + } + x.beginPath(); x.rect(sxp - 78, sy - 6, 156, 12); fill(x, '#efe6d2', 2.4); + ell(x, sxp + 10, sy - 18, 46, 14, lit(flash, '#f2c9a0'), 2.6); + var headX = sxp - 36, headY = sy - 26; + if (o.trash > 0) { x.beginPath(); x.rect(headX - 16, headY - 22, 32, 30); fill(x, '#9aa3a0', 2.4); ell(x, headX, headY - 22, 18, 6, '#b9c0bd', 2); } + else { ell(x, headX, headY, 20, 18, '#e04a3c', 2.6); if (dead) dazed(x, headX, headY - 4, .8); else pieEyes(x, headX, headY - 4, .8, -1, false, true); x.beginPath(); x.moveTo(headX - 16, headY + 2); x.lineTo(headX - 34, headY + 6); x.lineTo(headX - 14, headY + 10); fill(x, GOLD, 2); } + if (o.heart) { var hx2 = V.sx(o.heart.x), hy2 = V.sy(o.heart.y); x.beginPath(); x.moveTo(hx2, hy2 + 14); x.bezierCurveTo(hx2 - 26, hy2 - 6, hx2 - 10, hy2 - 22, hx2, hy2 - 8); x.bezierCurveTo(hx2 + 10, hy2 - 22, hx2 + 26, hy2 - 6, hx2, hy2 + 14); fill(x, lit(flash, '#d8443c'), 2.6); x.save(); x.setLineDash([4, 4]); x.beginPath(); x.moveTo(sxp + 10, sy - 18); x.lineTo(hx2, hy2 + 14); stroke(x, 1.6, '#8e2219'); x.restore(); } + } + B.BOSS_DRAW['cuphead/wally'] = { hazards: hazards, body: wallyBody }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/game.js b/environments/games/web/games/cuphead_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..141baf1a066cb03cd8c5bea3753a52755b255386 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/game.js @@ -0,0 +1,11 @@ +// v3 (2026-11-02): three public tiers. Each tier is one of the original modes (B.CUP.mode: easy = Simple, normal = Regular, +// hard = Expert), so patterns, phase lists and aggression stay the source values; only the encounter's total HP is +// calibrated per tier for the reference-controller time windows (B.CUP.TOTAL in arena.js, read at these difficulties). +// v4 (same day, user decision): Horace Radiche on the secret branch keeps his source HP (B.CUP.HORACE_HP). +// v5 (2026-11-03, expansion to 6 scenes): Cagney Carnation, Ribby and Croaks, Wally Warbles. The shared player code +// gained guarded paths (thin / moving platforms, wind, a progress-only lever parry, shot-blocking targets) that the +// first three cases never enter: their v4 recordings replay bit-identically under v5. +// 2026-11-03 (rules unchanged): difficultyBand(d) names the original mode a continuous difficulty plays, the same +// clamp and B.CUP.mode the case uses at reset, so the shared public info carries it as `difficulty_band`. A pure +// function of d (no case state): behaviour steps at 0.25 and 0.75 because the mode switches there. +(function(g){g.BB.GAME={id:'cuphead_remake',title:'Cuphead · Ink & Air',rules:'cuphead-tiers-v5',tiers:{easy:0.15,normal:0.5,hard:0.85},difficultyBand:function(d){return ['simple','regular','expert'][g.BB.CUP.mode(Math.min(1,Math.max(0,+d)))];},defaultCase:'cuphead/goopy',results:{win:'A KNOCKOUT!',loss:'YOU DIED',timeout:'TIME UP'},roster:[{id:'cuphead/goopy',name:'Bouncing Blob',arch:'Forest · three phases of jumps, punches, and tombstones'},{id:'cuphead/root_pack',name:'Garden Trio',arch:'Underground garden · potato, onion, and a third eye'},{id:'cuphead/hilda',name:'Zodiac Shifter',arch:'Flight stage · Taurus, Gemini, Sagittarius, and the moon'},{id:'cuphead/cagney',name:'Seed Bloom',arch:'Garden platform · sweeping attacks, magic hands, rapid seeds, and thorns'},{id:'cuphead/ribby_croaks',name:'Boxing Frogs',arch:'Nightclub · punch waves, wind traps, and a slot machine'},{id:'cuphead/wally',name:'Egg-Spitting Bird',arch:'Flight stage · birdhouse, chicks, egg shield, and stretcher'}]};})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/cuphead_remake/index.html b/environments/games/web/games/cuphead_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a3136d587805b30c0dfd4a73819f17362a9bf0bb --- /dev/null +++ b/environments/games/web/games/cuphead_remake/index.html @@ -0,0 +1,12 @@ +Cuphead · Ink & Air — BossBench +
BOSSBENCH / 2DSix reels · Ground & Air

Cuphead Ink & Air

One old movie ticket, six tough fights. Four ground stages and two flight stages pit you against a bouncing blob, vegetables, a giant flower, boxing frogs, zodiac forms, and a giant bird. Learn each phase, dodge, shoot, and parry pink targets.

+

Choose a Reel · SELECT A REEL

0.50

Three tiers match the original modes: Easy = Simple (shorter fights that skip final phases or the onion), Normal = Regular, and Hard = Expert. Health scales by tier; moves and phases stay the same. Slider: d < 0.25 Simple, 0.25–0.74 Regular, ≥ 0.75 Expert.

+
+ +

Controls · Ground / Flight

  • A/D to run; W/S to aim in eight directions. Hold L to stand still and aim. S crouches on the ground; crouch shots fire horizontally.
  • Space to jump; press again in the air to parry a pink target, bounce up, and gain one card.
  • Shift to dash (no default invulnerability); J / left mouse button for rapid fire; K / right mouse button for EX (one card).
  • With five cards, K or E unleashes a super: a horizontal beam on the ground or a bomb transformation in flight.
  • In flight, WASD moves in eight directions. Hold Shift to shrink and move faster, with weaker short-range shots. Q switches between gun and bomb; Space parries.
  • P/Esc pauses; Q returns to the menu while paused; R restarts after a result. Scripted Demo runs BB.GAME.scripted.

Move List

    +
    Film Room · Replay and Step-through
    One input packet every 200 ms; deterministic replay with the same seed and rules
    +
    All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
    + + diff --git a/environments/games/web/games/cuphead_remake/scripted.js b/environments/games/web/games/cuphead_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..41a5395cf817fc11d31417ce260a4ed13fd1b9f9 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/scripted.js @@ -0,0 +1,348 @@ +// Standard scripted reference controller for the three Cuphead cases (BossBench overnight protocol section 3). +// BB.GAME.scripted(c) is called once per 200 ms packet with the live BB.Case. It reads privileged state, predicts on +// deep copies of the case (the live case, its RNG and its event list are never touched), and returns one legal packet +// (six hold sets, <= 4 keys each). Deterministic: no Math.random, no wall clock. Not a pixel/model policy. +(function (g) { + var B = g.BB; + if (!B || !B.GAME) return; + var GROUND_DIRS = [{}, { A: true }, { D: true }, { S: true }, { W: true }, { A: true, W: true }, { D: true, W: true }, { A: true, S: true }, { D: true, S: true }]; + var PLANE_DIRS = [{}, { A: true }, { D: true }, { W: true }, { S: true }, { A: true, W: true }, { A: true, S: true }, { D: true, W: true }, { D: true, S: true }]; + var MEMORY = typeof WeakMap === 'function' ? new WeakMap() : null; + + function clone(o) { return JSON.parse(JSON.stringify(o)); } + // Deep copy of everything a tick can write (body, boss, rng, t, result, events); definitions are shared read-only. + function copyCase(c) { + var n = Object.create(Object.getPrototypeOf(c)); Object.assign(n, c); + n.body = Object.assign(Object.create(Object.getPrototypeOf(c.body)), clone(c.body)); + n.boss = Object.assign(Object.create(Object.getPrototypeOf(c.boss)), clone(c.boss)); + n.rng = Object.assign(Object.create(Object.getPrototypeOf(c.rng)), c.rng); + n.events = []; return n; + } + function merge(a, b) { return Object.assign({}, a, b); } + function hold(keys) { var out = []; for (var i = 0; i < 6; i++) out.push(merge(keys)); return out; } + // Space held in the listed sub-steps only (a released->held edge is a new press: jump on the ground, parry in the air). + function withSpace(keys, subs) { var out = hold(keys); subs.forEach(function (i) { out[i].Space = true; }); return out; } + function nkeys(o) { return Object.keys(o).length; } + + function centre(h) { + if (h.box) return h.box; + if (h.circle) return { x: h.circle[0], y: h.circle[1], w: h.circle[2] * 2, h: h.circle[2] * 2 }; + return null; + } + function margin(h, box) { + var b = centre(h); if (!b) return 4; + return Math.hypot(Math.max(0, Math.abs(b.x - box.x) - (b.w + box.w) / 2), Math.max(0, Math.abs(b.y - box.y) - (b.h + box.h) / 2)); + } + function pinkNear(c, dist) { + var hb = c.body.hurtBox(); + return c.boss.hazards().some(function (h) { return h.pink && !(h.ref && h.ref.removed) && margin(h, hb) < dist; }); + } + + function candidates(c, mem) { + var out = [], b = c.body, o = c.boss, plane = !!b.plane, fire = mem.spare ? {} : { J: true }; + var dirs = plane ? PLANE_DIRS : GROUND_DIRS; + dirs.forEach(function (dir) { + var a = merge(fire, dir); out.push(hold(a)); + if (plane && nkeys(dir)) [1, 2].forEach(function (n) { out.push(hold(fire).map(function (s, i) { return i < n ? merge(a) : s; })); }); + if (nkeys(a) < 4) { out.push(withSpace(a, [0, 1, 2, 3])); out.push(hold(merge(a, { Shift: true }))); } + }); + if (!plane && !mem.spare) { + var side = o.x < b.x ? 'A' : 'D'; + [{}, { W: true }, { S: true }].forEach(function (aim) { var k = { J: true, L: true }; k[side] = true; out.push(hold(merge(k, aim))); }); + } + if (b.meter >= 1 && !b.shrink && !mem.spare) [{}, { A: true }, { D: true }, { W: true }, { S: true }].forEach(function (dir) { out.push(hold(merge({ J: true, K: true }, dir))); }); + // Parry timing variants only when a pink object is close: press at different sub-steps of the packet. + if (pinkNear(c, 4.5)) { + var horiz = plane ? [{}, { W: true }, { S: true }, { A: true }, { D: true }] : [{}, { A: true }, { D: true }]; + var pats = plane ? [[0, 1], [2, 3], [4, 5]] : b.grounded ? [[0, 1, 3, 4], [0, 1, 4, 5]] : [[0, 1], [1, 2], [2, 3], [4, 5]]; + horiz.forEach(function (dir) { pats.forEach(function (p) { out.push(withSpace(merge(fire, dir), p)); }); }); + } + // v5: drop through a thin platform (S + Space while standing on one, source "Duck / Descend") + if (!plane && b.onPlat) [{}, { A: true }, { D: true }].forEach(function (dir) { out.push(withSpace(merge(fire, merge(dir, { S: true })), [0, 1])); }); + // v5: plane weapon swap (Q) where the source wants bombs (Wally's stretcher) or the gun back + if (plane && o.id === 'wally') out.push(hold(merge(fire, { Q: true })).map(function (s, i) { return i < 2 ? s : merge(fire); })); + return out; + } + function followUps(n, mem) { + var fire = mem.spare ? {} : { J: true }; + if (n.body.plane) return PLANE_DIRS.map(function (d) { return hold(merge(fire, d)); }); + var out = [{}, { A: true }, { D: true }, { S: true }].map(function (d) { return hold(merge(fire, d)); }) + .concat([{}, { A: true }, { D: true }].map(function (d) { return withSpace(merge(fire, d), [0, 1, 2, 3]); })); + if (n.body.onPlat) out.push(withSpace(merge(fire, { S: true }), [0, 1])); + return out; + } + + // Telegraph shaping beyond the lookahead: locked targets that the copy cannot yet see as hazards. + // v5 (Cagney): is the player above a standable platform (so a fall lands on it, not on the thorns)? + function overPlatform(b) { + return (B.CAGNEY_PLATS || []).some(function (p) { return Math.abs(b.x - p.x) <= p.w / 2 && b.y >= p.y - .05; }); + } + function telegraphs(n, b, o, hb) { + var s = 0; + if (o.id === 'goopy' && o.st === 'slam_antic') s -= Math.max(0, 2.7 - Math.abs(b.x - o.slamX)) * 60; + // v5: Cagney's lunge lane is fixed at the telegraph; a vine-grow mark means the platform is about to be encased + if (o.id === 'cagney') { + if (o.st === 'lunge_antic') s -= (o.lungeHigh ? (b.y > 1.2 && b.y < 4.5 ? 70 : 0) : (b.y < 1.7 ? 70 : 0)); + if (b.onPlat && o.vines && o.vines[b.onPlat]) s -= o.vines[b.onPlat].st === 'grow' ? 45 : 90; + } + // v5: a parked Bison chip is about to fire a jet straight up or down from itself + if (o.id === 'ribby_croaks') o.projectiles.forEach(function (p) { + if (p.kind === 'chip_bison' && p.parked && !p.fired && Math.abs(b.x - p.x) < 1.3 && (p.jetUp ? b.y + 1.4 > p.y : b.y < p.y)) s -= 70; + }); + if (o.id === 'hilda') { + if (o.st === 'horn_antic') s -= Math.max(0, 1.5 - Math.abs(b.y - o.targetY)) * 60; + if (o.st === 'arrow_antic') s -= Math.max(0, 1.5 - Math.abs(b.y - o.targetY)) * 60; + if (o.form === 'moon') o.projectiles.forEach(function (p) { + if (p.kind !== 'ufo' || p.removed || b.y > p.y + .2) return; + var dx = b.x - p.x; + if (p.fired && (p.charge > 0 || p.beam > 0)) s -= Math.max(0, 1.6 - Math.abs(dx - (p.charge > 0 ? -.9 : 0))) * 90; + else if (!p.fired) { if (p.red) s -= Math.max(0, 1.5 - Math.abs(dx)) * 25; else if (dx < .4 && dx > -3.2) s -= 25; } + }); + } + return s; + } + function minionHp(o) { var s = 0; o.projectiles.forEach(function (p) { if (!p.removed && p.hp > 0 && p.hp < 100 && p.kind !== 'floater') s += p.hp; }); return s; } + function quality(n, c) { + var b = n.body, o = n.boss; + if (n.result === 'win') return 1e6 - n.t; + if (b.hp <= 0 || n.result === 'loss') return -1e6; + var s = (b.hp - c.body.hp) * 12000 + (c.boss.hp - o.hp) * 14 + (b.meter - c.body.meter) * 40; + if (o.radishHp != null && c.boss.radishHp > 0) s += (c.boss.radishHp - o.radishHp) * 22; // kill the chaser first + // v5 (new scenes only): destructible minions (Cagney's chasers / terrors, Croaks' fireflies) are worth killing -- + // a good player thins them before they swarm; spawns lower every candidate's score equally + if (o.id === 'cagney' || o.id === 'ribby_croaks') s += (minionHp(c.boss) - minionHp(o)) * 16; + var hb = b.hurtBox(), near = 4; + o.hazards().forEach(function (h) { if (h.ref && h.ref.removed) return; near = Math.min(near, margin(h, hb)); }); + if (b.invul <= 0) s -= Math.max(0, 1.7 - near) * 24; + s += telegraphs(n, b, o, hb); + if (b.plane) { + s -= Math.max(0, b.x - (o.form === 'moon' ? 15 : 13)) * 5; s -= Math.max(0, 1.3 - b.y) * 15; + if (o.form === 'moon') { s -= Math.abs(b.y - 7.5) * 2; s -= Math.max(0, b.y - 9.4) * 30; s -= Math.max(0, 3 - b.x) * 6; if (b.x > 16) s -= 80; } + else if (o.id === 'wally' && o.phase === 3) { // v5: stretcher -- drop bombs onto him from above + var bombY = 8.6, fall = bombY - 5.4, tl = (-2 + Math.sqrt(4 + 40 * fall)) / 20, vx = o.sDir * [0, 2.2, 3.2][o.mode], + land = o.sx + vx * tl, bombX = land - 7 * tl; + s -= Math.abs(b.x - bombX) * 4 + Math.abs(b.y - bombY) * 3; + if (b.weapon !== 'bomb') s -= 30; + } + else { var target = o.bodyBox(); s -= Math.max(0, Math.abs(b.y - target.y) - target.h / 2 + .4) * 3; s -= Math.max(0, b.y - 13.3) * 15; } + if (o.id === 'wally' && o.phase !== 3 && b.weapon !== 'gun') s -= 30; + } else { + if (o.id === 'cagney') { // v5: thorn floor in phase 2; never stand near him + if (o.phase === 1 && b.onPlat == null) s -= 40 + (b.y < 1.3 ? 9000 : b.vy < 0 && !overPlatform(b) ? 2500 : 0); + s -= Math.max(0, b.x - 16) * 12; + s -= Math.abs(b.x - 9.6) * .5; + } + if (o.id === 'ribby_croaks') { + if (o.phase === 2 && o.leverDown) s -= Math.hypot(b.x - B.RIBBY_GEOM.LEVER.x + 1.2, b.y - B.RIBBY_GEOM.LEVER.y + .6) * 3; + if (o.phase === 2) s -= Math.max(0, b.x - 20.4) * 20; + else s -= Math.abs(b.x - (o.phase === 0 ? 8 : 12)) * .8; + } + if (o.id === 'root_pack') { + var goal = o.form() === 'carrot' ? 7 : 4; + if (o.radishHp > 0) { // Horace: keep running room on the far side; cross him with a jump + var side = b.x >= o.radishX ? 1 : -1, room = side > 0 ? 26.6 - b.x : b.x - .4; + s += Math.min(room, 9) * 5; + s -= Math.max(0, 2.6 - Math.abs(b.x - o.radishX)) * 16 * (b.y < 1.8 ? 1 : .25); + goal = side > 0 ? Math.min(26, o.radishX + 6) : Math.max(1, o.radishX - 6); + } + s -= Math.abs(b.x - goal) * 1.6; + } + if (o.id === 'goopy' && o.phase < 2) s -= Math.max(0, 4.8 - Math.abs(b.x - o.x)) * 10; + s -= Math.max(0, 1 - b.x) * 2 + Math.max(0, b.x - 26) * 2; + } + return s; + } + function cost(subs) { + var s = 0; subs.forEach(function (h) { if (h.Shift) s += 2 / 6; if (h.Space) s += .3 / 6; }); return s; + } + function run(n, subs, ticks) { for (var t = 0; t < ticks && !n.result; t++) n.tick(subs[Math.floor((t % 12) / 2)]); } + + // ---------- Horace Radiche (Root Pack secret branch) ---------- + // Source: he chases the player, who "would have to jump over him to dodge him". He accelerates to 7 / 8 u/s + // (Regular / Expert), about the 7.2 u/s run, and turns round within ~1 u once crossed, so running away only delays + // him. A crossing lasts about a second -- longer than the 0.6 s general search sees -- and only some take-off times + // clear him: a jump toward him with an air dash 6-8 sub-steps after take-off (the dash holds altitude for 0.2 s) works + // from a wide range of distances, and against Expert speed only re-jumping on the landing tick keeps enough room for + // the next crossing. So while he is alive the controller chooses among crossing policies -- lock-shoot him (or run at + // him) until sub-step k, take off toward him, air-dash when the take-off speed has decayed to the chosen value, then + // either face him again or re-jump on landing; while above him it aims down at him. Ground dashes, jumps away and + // the super are offered as escapes. Each policy is a pure function of the simulated state, simulated 1.7 s on an + // exact copy with every other attack included. Among policies that stay hit-free for at least the first second, the + // one dealing most damage wins (a predicted later hit costs by how early it comes; being pinned between him and a + // wall costs too). The chosen policy keeps running while its rollout stays hit-free (no new search: cheaper on the + // live page and steadier than re-choosing every packet); otherwise everything is searched again, and with nothing + // safe the general search below takes over. 16 secret-branch seeds (2026-11-02): normal 16/16 (was 7/16), Expert at + // the source HP 16/16 (was 11/16), hard tier 0/16 -- see + var MAN = 51, DASH_VY = { 6: 16 - 44 * .2, 7: 16 - 44 * 7 / 30, 8: 16 - 44 * 8 / 30, 0: 99 }; + function horaceActive(c) { var o = c.boss; return o.id === 'root_pack' && o.radishHp > 0 && !c.body.plane; } + function sideOf(n) { return n.boss.radishX < n.body.x ? 'A' : 'D'; } + function crossing(pre, k, q, again) { + return function (n, i) { + var b = n.body, h = { J: true }, T = sideOf(n); + if (i < k) { if (pre === 'face') h.L = true; h[pre === 'flee' ? (T === 'A' ? 'D' : 'A') : T] = true; return h; } + if (b.grounded) { + if (i - k < 2 || again) { h.Space = true; h[T] = true; } else { h.L = true; h[T] = true; } + return h; + } + h[b.facing > 0 ? 'D' : 'A'] = true; + if ((n.boss.radishX - b.x) * b.facing > .3 && b.y > 1.2) h.S = true; + if (q != null && !b.airDash && b.dashCd <= 0 && b.vy <= DASH_VY[q]) h.Shift = true; + return h; + }; + } + // full meter: the Energy Beam (super) on sub-step s while facing him -- 87 damage, and this engine keeps the player + // invulnerable while it lasts (body_cup.js startSuper), so he can pass through once + function superArt(s) { + return function (n, i) { var h = { J: true, L: true }; h[sideOf(n)] = true; if (i === s) { delete h.J; h.K = true; } return h; }; + } + // a ground dash on sub-step e (away from him or toward him), then face him with the lock and shoot + function groundDash(e, dir) { + return function (n, i) { + var h = { J: true, L: true }, T = sideOf(n), W = T === 'A' ? 'D' : 'A'; + h[T] = true; + if (i >= e && i < e + 2) { delete h.L; delete h[T]; h[dir === 'away' ? W : T] = true; h.Shift = true; } + return h; + }; + } + function simulate(c, fn, offset) { + var n = copyCase(c), hp = c.body.hp, subs = []; + for (var i = 0; i < MAN && !n.result; i++) { + var h = fn(n, offset + i); if (i < 6) subs.push(h); + n.tick(h); if (!n.result) n.tick(h); + if (n.body.hp < hp || n.result === 'loss') { for (var j = i + 1; j < 6; j++) subs.push(fn(n, offset + j)); return { hit: i, subs: subs, at: n }; } + } + while (subs.length < 6) subs.push(merge(subs[subs.length - 1] || {})); + return { n: n, subs: subs }; + } + function maneuverScore(n, c) { + if (n.result === 'win') return 1e6 - n.t; + var b = n.body, o = n.boss, s = (c.boss.hp - o.hp) * 14 + (o.radishHp != null ? (c.boss.radishHp - o.radishHp) * 22 : 0) + (b.meter - c.body.meter) * 40; + if (o.radishHp > 0 && b.grounded) s -= Math.max(0, 4 - Math.abs(b.x - o.radishX)) * 20; + // corner trap: a crossing needs ~5 u of floor beyond him; being pinned between him and a wall is penalised + if (o.radishHp > 0) { var side = b.x >= o.radishX ? 1 : -1, room = side > 0 ? 26.6 - b.x : b.x - .4; s -= Math.max(0, 5 - room) * 40; } + return s - Math.max(0, 2 - b.x) * 15 - Math.max(0, b.x - 25) * 15; + } + function decideHorace(c, mem) { + if (mem.lastT === c.t) return mem.lastSubs; // a repeated call on one tick gets the same answer + var cands = []; + function add(fn, offset) { var r = simulate(c, fn, offset || 0); r.fn = fn; r.offset = offset || 0; cands.push(r); return r; } + if (mem.plan && mem.planT + 12 === c.t) { + var kept = add(mem.plan, mem.planOffset + 6); + // the kept plan is still hit-free for the whole 1.7 s: keep executing it without a new search (live-page cost) + if (kept.hit == null) { mem.planOffset += 6; mem.planT = c.t; mem.lastT = c.t; return (mem.lastSubs = kept.subs); } + } + ['face', 'run'].forEach(function (pre) { + var base = add(crossing(pre, 99, null, false)), until = base.hit == null ? 30 : Math.min(30, base.hit + 1); + for (var k = 0; k < until; k += k < 12 ? 1 : 2) [[null, false], [6, false], [7, false], [8, false], [6, true], [7, true], [0, true]].forEach(function (v) { add(crossing(pre, k, v[0], v[1])); }); + }); + add(crossing('flee', 99, null, false)); + for (var e = 0; e < 12; e += 2) { add(groundDash(e, 'away')); add(groundDash(e, 'toward')); add(crossing('flee', e, null, false)); add(crossing('flee', e, 7, false)); } + if (c.body.meter >= 5 && c.body.grounded) for (var s = 0; s < 18; s += 2) add(superArt(s)); + var best = null, bestScore = -Infinity; + cands.forEach(function (r) { + if (r.hit != null && r.hit < 30) return; + var sc = r.hit == null ? maneuverScore(r.n, c) : maneuverScore(r.at, c) - (MAN - r.hit) * 400; + if (sc > bestScore) { bestScore = sc; best = r; } + }); + mem.lastT = c.t; + if (!best) { mem.plan = null; return (mem.lastSubs = null); } + mem.plan = best.fn; mem.planOffset = best.offset; mem.planT = c.t; + return (mem.lastSubs = best.subs); + } + + // ---------- Cagney phase 2 (thorn floor) ---------- + // whole-maneuver planning while the thorn floor is out (phase 2) and while a lunge is telegraphed / active (its lane is + // fixed at the telegraph; the source dodge is to change level: onto a platform for the low lane, off for the high one) + function cagneyActive(c) { var o = c.boss; return o.id === 'cagney' && o.st !== 'dead' && !c.body.plane && (o.phase === 1 || o.st === 'lunge_antic' || o.st === 'lunge' || (o.st === 'rest' && o.timer < .8)); } + function hop(goal, k, q, par, drop) { + return function (n, i) { + var b = n.body, h = { J: true }, dx = goal - b.x; + if (Math.abs(dx) > .35) h[dx < 0 ? 'A' : 'D'] = true; else { h.L = true; h[n.boss.x < b.x ? 'A' : 'D'] = true; } + if (drop && i >= k && i < k + 2 && b.onPlat) { h = { J: true, S: true, Space: true }; return h; } + if (!drop && k != null && i >= k && i < k + 4 && b.grounded) { delete h.L; h.Space = true; } + if (q != null && i >= k + q && i < k + q + 2 && !b.grounded && !b.airDash) { delete h.L; h.Shift = true; } + if (par && !b.grounded && b.vy < 6 && (i % 3) === 0) h.Space = true; + return h; + }; + } + function decideCagney(c, mem) { + if (mem.lastT === c.t) return mem.lastSubs; + var cands = []; + function add(fn, offset) { var r = simulate(c, fn, offset || 0); r.fn = fn; r.offset = offset || 0; cands.push(r); return r; } + if (mem.plan && mem.planT + 12 === c.t) { var kept = add(mem.plan, mem.planOffset + 6); if (kept.hit == null) { mem.planOffset += 6; mem.planT = c.t; mem.lastT = c.t; return (mem.lastSubs = kept.subs); } } + var thorns = c.boss.phase === 1; + (B.CAGNEY_PLATS || []).forEach(function (p) { + add(hop(p.x)); + for (var k = 0; k < 14; k += 2) { [null, 3, 6].forEach(function (q) { add(hop(p.x, k, q)); }); add(hop(p.x, k, null, true)); } + }); + if (!thorns) [2, 6, 9.6, 14, 18].forEach(function (gx) { add(hop(gx)); for (var k = 0; k < 6; k += 2) add(hop(gx, k, null, false, true)); }); + var best = null, bestScore = -Infinity; + cands.forEach(function (r) { if (r.hit != null) return; var sc = maneuverScore(r.n, c) - (thorns && r.n.body.y < 1.3 ? 1e5 : 0) - Math.max(0, r.n.body.x - 16) * 40; if (sc > bestScore) { bestScore = sc; best = r; } }); + if (!best && c.boss.st !== 'rest') cands.forEach(function (r) { if (r.hit != null && r.hit >= 6 && (!best || r.hit > best.hit)) best = r; }); + mem.lastT = c.t; + if (!best) { mem.plan = null; return (mem.lastSubs = null); } + mem.plan = best.fn; mem.planOffset = best.offset; mem.planT = c.t; + return (mem.lastSubs = best.subs); + } + + // ---------- Ribby and Croaks: slot-machine lever ---------- + function leverActive(c) { var o = c.boss; return o.id === 'ribby_croaks' && o.phase === 2 && o.leverDown && !c.body.plane; } + function leverPlan(gx, k) { + return function (n, i) { + var b = n.body, h = { J: true }, dx = gx - b.x; + if (Math.abs(dx) > .15 && b.grounded) h[dx < 0 ? 'A' : 'D'] = true; + if (i >= k && b.grounded && i < k + 3) h.Space = true; + else if (!b.grounded && i >= k + 3 && (i - k) % 2 === 1) h.Space = true; + return h; + }; + } + function decideLever(c, mem) { + if (mem.lastT === c.t) return mem.lastSubs; + var cands = []; + function add(fn, offset) { var r = simulate(c, fn, offset || 0); r.fn = fn; r.offset = offset || 0; cands.push(r); return r; } + if (mem.plan && mem.planT + 12 === c.t) { var kept = add(mem.plan, mem.planOffset + 6); if (kept.hit == null && kept.n && kept.n.boss.slot !== 'closed') { mem.planOffset += 6; mem.planT = c.t; mem.lastT = c.t; return (mem.lastSubs = kept.subs); } } + [19.8, 20.1, 20.4, 20.7].forEach(function (gx) { for (var k = 0; k < 16; k += 2) add(leverPlan(gx, k)); }); + var best = null, bestScore = -Infinity; + cands.forEach(function (r) { if (r.hit != null) return; var sc = maneuverScore(r.n, c) + (r.n.boss.slot !== 'closed' ? 5000 : 0); if (sc > bestScore) { bestScore = sc; best = r; } }); + mem.lastT = c.t; + if (!best || best.n.boss.slot === 'closed') { mem.plan = null; return (mem.lastSubs = null); } + mem.plan = best.fn; mem.planOffset = best.offset; mem.planT = c.t; + return (mem.lastSubs = best.subs); + } + + function decide(c, mem) { + if (leverActive(c)) { var ls = decideLever(c, mem); if (ls) return ls; } + if (cagneyActive(c)) { var cs = decideCagney(c, mem); if (cs) return cs; } + if (horaceActive(c) && !mem.spare) { var hs = decideHorace(c, mem); if (hs) return hs; } else mem.plan = null; + var scored = candidates(c, mem).map(function (subs, index) { + var n = copyCase(c); run(n, subs, 12); + var q12 = quality(n, c), mid = n.result ? null : copyCase(n); + run(n, subs, 12); + return { subs: subs, index: index, q12: q12, mid: mid, s: q12 * .6 + quality(n, c) * .4 - cost(subs) }; + }); + scored.sort(function (a, b) { return b.s - a.s || a.index - b.index; }); + var best = scored[0], bestScore = -Infinity; + scored.slice(0, 6).forEach(function (cand) { + var follow = -Infinity; + if (!cand.mid) follow = cand.q12; + else followUps(cand.mid, mem).forEach(function (f) { var m = copyCase(cand.mid); run(m, f, 24); follow = Math.max(follow, quality(m, c)); }); + var score = cand.q12 * .45 + follow * .55 - cost(cand.subs); + if (score > bestScore) { bestScore = score; best = cand; } + }); + return best.subs; + } + + // Presentation only: the shared Juice requests a 50 ms wall-clock hit-stop per boss_hit, which Peashooter fire + // triggers 7.5 times a second, so the human page would run at ~70% speed. Cuphead has no per-bullet hit-stop, + // so this game opts out through the engine's shared switch (engine/juice.js takeHitstop). Flash and particles stay. + B.GAME.hitstop = false; + B.GAME.scripted = function (c) { + var mem = MEMORY ? MEMORY.get(c) : null; + if (!mem || c.t === 0) { mem = { spare: false, spareSeed: (c.seed >>> 0) % 4 === 3 }; if (MEMORY) MEMORY.set(c, mem); } + // Seeds = 3 (mod 4) spare Ollie Bulb (never shoot him) to take the documented secret Horace Radiche branch. + var o = c.boss; + mem.spare = !!(mem.spareSeed && o.id === 'root_pack' && o.forms && o.forms[o.phase] === 'onion' && !o.angry && !o.secret); + return B.formatPacket(decide(c, mem)); + }; + B.CUP_SCRIPTED = { decide: decide, copyCase: copyCase, quality: quality, candidates: candidates, followUps: followUps, simulate: simulate, hop: hop, maneuverScore: maneuverScore, decideCagney: decideCagney }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/specs/cagney.spec.js b/environments/games/web/games/cuphead_remake/specs/cagney.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..2f0494ecee41e9bfdbc70e960ea8710fdbb2aabb --- /dev/null +++ b/environments/games/web/games/cuphead_remake/specs/cagney.spec.js @@ -0,0 +1,138 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["cagney"] = { + "schema": "bossbench/boss-spec@1", + "id": "cagney", + "dims": "2d", + "family": "pogo2d", + "archetype": "Cuphead cagney source-phase encounter (platforms)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.15 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "lunge", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The face and both arms sweep along the upper level (platforms) or the lower level (ground)", + "punish": "Jump onto a platform or leave it to change levels" + }, + { + "name": "hands", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "Magic hands: spinning seeds that go above the platforms and return below, or 3-4 aimed acorns", + "punish": "Change level for the seeds; move before the acorns are released" + }, + { + "name": "gatling", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The flower head becomes a gun and spits seeds: blue homes in, purple becomes a small ground plant, pink is a parryable seed that becomes a floating flower", + "punish": "Shoot the homing seeds. Parry the pink seeds and the pink shots from the floating flowers" + }, + { + "name": "pollen", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "Phase 2: thorns cover the ground, dandelions drift past, and vines periodically seal the platforms", + "punish": "Stay on the platforms. Watch the vine growth warning and switch platforms" + } + ], + "difficulty": { + "hp": [ + 1000, + 1300, + 1500 + ], + "telegraph": [ + 1.2, + 1, + 0.8 + ], + "recovery": [ + 1.2, + 1, + 0.8 + ], + "idle_gap": [ + 1.2, + 1, + 0.8 + ], + "entropy": [ + 1, + 1, + 1 + ], + "speed": [ + 0.8, + 1, + 1.2 + ], + "dmg": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/specs/goopy.spec.js b/environments/games/web/games/cuphead_remake/specs/goopy.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..0913bc74d69c87515db73e46f5b79acedf55f372 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/specs/goopy.spec.js @@ -0,0 +1,138 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["goopy"] = { + "schema": "bossbench/boss-spec@1", + "id": "goopy", + "dims": "2d", + "family": "pogo2d", + "archetype": "Cuphead goopy source-phase encounter", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.15 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "bounce", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "He flattens before jumping; the small and large forms have two jump heights", + "punish": "Track the landing spot and shoot in the air. Rising along a side wall makes him bounce" + }, + { + "name": "punch", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "He faces you and charges. The giant form winks before the first punch", + "punish": "Crouch the punch. The default dash has no invulnerability" + }, + { + "name": "transform", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "He swallows a candy and three pink question marks appear", + "punish": "Press jump again in the air to parry a question mark. This is the only parry in the fight" + }, + { + "name": "tombstone", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The tombstones travel back and forth in the background, then pause", + "punish": "The slide does not hurt. Leave the spot the slam has locked onto" + } + ], + "difficulty": { + "hp": [ + 1000, + 1200, + 1400 + ], + "telegraph": [ + 1.2, + 1, + 0.8 + ], + "recovery": [ + 1.2, + 1, + 0.8 + ], + "idle_gap": [ + 1.2, + 1, + 0.8 + ], + "entropy": [ + 1, + 1, + 1 + ], + "speed": [ + 0.8, + 1, + 1.2 + ], + "dmg": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/specs/hilda.spec.js b/environments/games/web/games/cuphead_remake/specs/hilda.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..adefe13e0a466f829591d8385a107e8d1442a98a --- /dev/null +++ b/environments/games/web/games/cuphead_remake/specs/hilda.spec.js @@ -0,0 +1,149 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["hilda"] = { + "schema": "bossbench/boss-spec@1", + "id": "hilda", + "dims": "2d", + "family": "pogo2d", + "archetype": "Cuphead hilda source-phase encounter", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.15 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "laughter", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "In her normal form she laughs and fires HA shots, then the small planes come in", + "punish": "Every fourth pink shot from the purple plane can be parried. The green plane's fan cannot" + }, + { + "name": "horn_jab", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "Taurus lines up with your height, pauses, then extends its horns", + "punish": "Once the height is locked, dodge up or down" + }, + { + "name": "rotating_vortex", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "Gemini summons a spinning bullet line on one side of you", + "punish": "Go around the spinning line and do not cross the vortex center" + }, + { + "name": "arrow_stars", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "Sagittarius draws an arrow, then three blue stars follow", + "punish": "The arrow keeps its direction. The blue stars have 10 HP and can be shot down" + }, + { + "name": "ufo_laser", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "In the moon phase the UFO moves sideways and the ship changes color", + "punish": "Red triggers directly below you and gold triggers ahead. Shrink to fit through the gaps" + } + ], + "difficulty": { + "hp": [ + 2200, + 2600, + 3000 + ], + "telegraph": [ + 1.2, + 1, + 0.8 + ], + "recovery": [ + 1.2, + 1, + 0.8 + ], + "idle_gap": [ + 1.2, + 1, + 0.8 + ], + "entropy": [ + 1, + 1, + 1 + ], + "speed": [ + 0.8, + 1, + 1.2 + ], + "dmg": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/specs/ribby_croaks.spec.js b/environments/games/web/games/cuphead_remake/specs/ribby_croaks.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c55382513840ace1166186566674632892658eab --- /dev/null +++ b/environments/games/web/games/cuphead_remake/specs/ribby_croaks.spec.js @@ -0,0 +1,149 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["ribby_croaks"] = { + "schema": "bossbench/boss-spec@1", + "id": "ribby_croaks", + "dims": "2d", + "family": "pogo2d", + "archetype": "Cuphead ribby_croaks source-phase encounter (two frogs, slot machine)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.15 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "fists", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The left frog sends low, mid, and high punch waves, some of them pink, and travels back and forth in phase 1", + "punish": "Jump or crouch them. Pink punches can be parried" + }, + { + "name": "firefly", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The right frog spits fireflies that slowly close in", + "punish": "One shot each" + }, + { + "name": "roll", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "At the end of a phase the left frog rolls across the ground through the whole stage", + "punish": "Jump over it" + }, + { + "name": "balls", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "In phase 2 the left frog slaps out three bouncing ring balls, and the right frog turns and blows you toward the left frog", + "punish": "Run or dash against the wind and pass through the gaps between the balls" + }, + { + "name": "slot", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "Phase 3 is a slot machine: it spits coins first, and the lever can be hit only after it turns pink and you parry it. Tiger, snake, and bull platforms have different spike chips", + "punish": "Parry the lever. Depending on the chip, jump over it, land on it, or dodge the fire" + } + ], + "difficulty": { + "hp": [ + 1400, + 1700, + 1900 + ], + "telegraph": [ + 1.2, + 1, + 0.8 + ], + "recovery": [ + 1.2, + 1, + 0.8 + ], + "idle_gap": [ + 1.2, + 1, + 0.8 + ], + "entropy": [ + 1, + 1, + 1 + ], + "speed": [ + 0.8, + 1, + 1.2 + ], + "dmg": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/specs/root_pack.spec.js b/environments/games/web/games/cuphead_remake/specs/root_pack.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..66abceae2e4966a5e38830e5d168cc4894ac431c --- /dev/null +++ b/environments/games/web/games/cuphead_remake/specs/root_pack.spec.js @@ -0,0 +1,138 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["root_pack"] = { + "schema": "bossbench/boss-spec@1", + "id": "root_pack", + "dims": "2d", + "family": "pogo2d", + "archetype": "Cuphead root_pack source-phase encounter", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.15 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "dirt_worm", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The potato spits dirt balls in a row, ending with a pink worm", + "punish": "Jump the dirt balls. The pink worm can be parried in the air" + }, + { + "name": "tears", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "After you hit the onion it starts crying, and pink tears mix into the rain", + "punish": "Watch the landing spots above. Leaving it unhurt for about six seconds opens the hidden radish branch" + }, + { + "name": "homing_carrots", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The background carrot summons small carrots that track you", + "punish": "The small carrots have 4 HP and can be destroyed. The large body in the background does not hurt you" + }, + { + "name": "eye_laser", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The third eye charges, aims at you, and fires rings", + "punish": "Regular fires three; Simple and Expert fire two. Keep changing position" + } + ], + "difficulty": { + "hp": [ + 900, + 1235, + 1300 + ], + "telegraph": [ + 1.2, + 1, + 0.8 + ], + "recovery": [ + 1.2, + 1, + 0.8 + ], + "idle_gap": [ + 1.2, + 1, + 0.8 + ], + "entropy": [ + 1, + 1, + 1 + ], + "speed": [ + 0.8, + 1, + 1.2 + ], + "dmg": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/cuphead_remake/specs/wally.spec.js b/environments/games/web/games/cuphead_remake/specs/wally.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..40a7497948fb3e1737e4e17b07c6d380d538c3e5 --- /dev/null +++ b/environments/games/web/games/cuphead_remake/specs/wally.spec.js @@ -0,0 +1,149 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["wally"] = { + "schema": "bossbench/boss-spec@1", + "id": "wally", + "dims": "2d", + "family": "pogo2d", + "archetype": "Cuphead wally source-phase encounter (plane)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.15 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "eggs", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The birdhouse spits eggs that burst into fragments at the screen edge", + "punish": "Read the fragment direction ahead of time" + }, + { + "name": "finger", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "The head becomes a three-fingered hand, then after a delay fires three large shots in a fan", + "punish": "Move out of the fan's center during the wind-up" + }, + { + "name": "whistle", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "After a whistle scream it flaps: feathers fire in eight directions, then it rests when tired", + "punish": "Pass through the gaps between feathers. Concentrate your shots during the rest" + }, + { + "name": "chick_shield", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "Phase 2 chicks: circling spiked eggs block shots and extend and retract. The electric shots are always pink", + "punish": "Shoot through the gaps when the eggs retract. Parry the electric shots" + }, + { + "name": "stretcher", + "atoms": [ + "projectile" + ], + "telegraph_scale": 1, + "params": {}, + "damage": 1, + "cue": "Phase 3 stretcher: it spits trash (the pink boot can be parried). After the heart rises, only the heart can be hurt. The medic birds' pills split and home in", + "punish": "Use bombs from above or up close. Shoot the heart when it appears" + } + ], + "difficulty": { + "hp": [ + 2000, + 2400, + 2800 + ], + "telegraph": [ + 1.2, + 1, + 0.8 + ], + "recovery": [ + 1.2, + 1, + 0.8 + ], + "idle_gap": [ + 1.2, + 1, + 0.8 + ], + "entropy": [ + 1, + 1, + 1 + ], + "speed": [ + 0.8, + 1, + 1.2 + ], + "dmg": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/doom_remake/compact_actions.json b/environments/games/web/games/doom_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..69a15e467a150d631bb6fdd32b4fec183944018c --- /dev/null +++ b/environments/games/web/games/doom_remake/compact_actions.json @@ -0,0 +1,164 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "doom_remake", + "version": "doom-compact@1", + "note": "A 200 ms packet combines eight-way running, fixed-angle turning, and one fire or weapon action. One mouse count turns the view 0.0025 radians.", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W", + "Shift" + ] + }, + { + "label": "back", + "keys": [ + "S", + "Shift" + ] + }, + { + "label": "left", + "keys": [ + "A", + "Shift" + ] + }, + { + "label": "right", + "keys": [ + "D", + "Shift" + ] + }, + { + "label": "forward_left", + "keys": [ + "W", + "A", + "Shift" + ] + }, + { + "label": "forward_right", + "keys": [ + "W", + "D", + "Shift" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A", + "Shift" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D", + "Shift" + ] + } + ] + }, + { + "name": "turn", + "options": [ + { + "label": "none" + }, + { + "label": "left_3", + "dx": -21 + }, + { + "label": "right_3", + "dx": 21 + }, + { + "label": "left_10", + "dx": -70 + }, + { + "label": "right_10", + "dx": 70 + }, + { + "label": "left_30", + "dx": -210 + }, + { + "label": "right_30", + "dx": 210 + }, + { + "label": "left_60", + "dx": -420 + }, + { + "label": "right_60", + "dx": 420 + } + ] + }, + { + "name": "attack", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "keys": [ + "J" + ] + }, + { + "label": "fire_fresh", + "note": "J is released in the first sub-step only. The rocket launcher does not fire on a trigger still held from before: use this once after changing to it.", + "subs": [ + [], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "next_weapon", + "tap": [ + "K" + ] + }, + { + "label": "prev_weapon", + "tap": [ + "L" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/doom_remake/draw.js b/environments/games/web/games/doom_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..57af718e5c878995aa0818bd84c97068a1c33dea --- /dev/null +++ b/environments/games/web/games/doom_remake/draw.js @@ -0,0 +1,489 @@ +/* DOOM arena renderer (read-only): software raycast first-person view at 854x410 + 70 px status bar. + Textured walls, floors, ceilings and sky; distance light diminishing in the spirit of DOOM colormaps; + billboard sprites whose frame letters follow the simulation state tables; first-person weapon with bob, + muzzle flash and extralight; status bar with ammo/health/arms/face/armor; damage and pickup palettes. + All art is procedural and original. The renderer never mutates the game or draws from its RNG. */ +(function (root) { + 'use strict'; + const M = root.DoomGame, TAU = Math.PI * 2, W = 854, H = 410, HALF = 205, F = 427, LV = 32; + let R = null; + // ---------- deterministic helpers (no gameplay RNG) ---------- + function h2(x, y, s) { let h = Math.imul(x | 0, 374761393) + Math.imul(y | 0, 668265263) + Math.imul(s | 0, 1442695041) | 0; h = Math.imul(h ^ (h >>> 13), 1274126177); h ^= h >>> 16; return (h >>> 0) / 4294967296; } + function vn(x, y, s, px, py) { // tileable value noise + const xi = Math.floor(x), yi = Math.floor(y), fx = x - xi, fy = y - yi, sx = fx * fx * (3 - 2 * fx), sy = fy * fy * (3 - 2 * fy); + const a = h2(((xi % px) + px) % px, ((yi % py) + py) % py, s), b = h2((((xi + 1) % px) + px) % px, ((yi % py) + py) % py, s); + const c = h2(((xi % px) + px) % px, (((yi + 1) % py) + py) % py, s), d = h2((((xi + 1) % px) + px) % px, (((yi + 1) % py) + py) % py, s); + return a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy; + } + function fbm(x, y, s, p, oct = 4) { let v = 0, amp = 0.5, f = 1; for (let i = 0; i < oct; i++) { v += amp * vn(x * f, y * f, s + i * 17, p * f, p * f); amp *= 0.5; f *= 2; } return v; } + const SHADE = Array.from({ length: LV }, (_, i) => 1 - i / (LV - 1) * 0.9); + const pack = (r, g, b) => (255 << 24 | (Math.max(0, Math.min(255, b)) << 16) | (Math.max(0, Math.min(255, g)) << 8) | Math.max(0, Math.min(255, r))) >>> 0; + // Texture: w*h RGB floats + emissive mask -> LV shaded Uint32 tables. + function texture(w, h, fn) { + const n = w * h, base = new Float32Array(n * 3), emis = new Uint8Array(n); + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const o = fn(x, y), i = y * w + x; base[i * 3] = o[0]; base[i * 3 + 1] = o[1]; base[i * 3 + 2] = o[2]; emis[i] = o[3] ? 1 : 0; } + const tab = new Uint32Array(n * LV); + for (let l = 0; l < LV; l++) { const s = SHADE[l]; for (let i = 0; i < n; i++) { const k = emis[i] ? 1 : s; tab[l * n + i] = pack(base[i * 3] * k | 0, base[i * 3 + 1] * k | 0, base[i * 3 + 2] * k | 0); } } + return { w, h, n, tab }; + } + const mix = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; + const mul = (c, k) => [c[0] * k, c[1] * k, c[2] * k]; + function buildTextures() { + const T = {}; + T.stone = texture(64, 128, (x, y) => { // irregular stone blocks + const row = y >> 4, off = (row & 1) * 16 + (h2(row, 0, 3) * 8 | 0), bx = ((x + off) & 63) >> 5, mort = (y & 15) === 0 || ((x + off) & 31) === 0; + const n = fbm(x / 8, y / 8, 11, 8), k = 0.75 + 0.35 * h2(bx + row * 7, row, 5) + (n - 0.5) * 0.5; + return mort ? [38, 34, 30] : mul([118, 104, 88], k); + }); + T.marble = texture(64, 128, (x, y) => { // green marble pillar with veins and gold bands + if (y < 6 || y > 121) return mul([150, 118, 52], 0.8 + 0.3 * ((y & 3) / 3)); + const v = Math.abs(Math.sin((x * 0.11 + y * 0.05 + fbm(x / 10, y / 10, 21, 7) * 4))), n = fbm(x / 6, y / 6, 23, 11); + const c = mix([52, 82, 64], [118, 150, 122], n); return v < 0.12 ? mul(c, 0.45) : (x % 32 === 0 ? mul(c, 0.6) : c); + }); + T.metal = texture(64, 128, (x, y) => { // riveted panels + const sx = x & 31, sy = y & 63, seam = sx === 0 || sy === 0, rivet = (sx === 4 || sx === 27) && (sy === 5 || sy === 58); + const n = fbm(x / 4, y / 16, 31, 16) - 0.5; let c = mul([92, 98, 108], 1 + n * 0.35 + (sy < 3 ? 0.25 : 0)); + if (seam) c = [34, 36, 42]; if (rivet) c = [170, 176, 186]; return c; + }); + T.lights = texture(64, 128, (x, y) => { // frame with an emissive light strip + if (x > 22 && x < 42 && y > 14 && y < 114) { const e = 1 - Math.abs(x - 32) / 12; return [220 + 35 * e, 210 + 40 * e, 160 + 60 * e, 1]; } + const n = fbm(x / 4, y / 4, 41, 16); const edge = (x === 22 || x === 42) && y > 13 && y < 115; + return edge ? [40, 40, 44] : mul([84, 86, 92], 0.8 + n * 0.4); + }); + T.rock = texture(64, 128, (x, y) => { // red hell rock + const n = fbm(x / 9, y / 9, 51, 7, 5), crack = Math.abs(fbm(x / 14, y / 22, 53, 5) - 0.5) < 0.025; + const c = mix([70, 28, 18], [156, 72, 42], n); return crack ? [30, 10, 6] : c; + }); + T.tech = texture(64, 128, (x, y) => { // tech pillar with blinking panels (emissive dots) + const px = x & 15, py = y & 15, cell = (x >> 4) + (y >> 4) * 4, lit = h2(cell, 7, 61) > 0.62; + if (px > 4 && px < 11 && py > 5 && py < 10 && lit) { const g = h2(cell, 9, 63); return g > 0.5 ? [80, 230, 120, 1] : [230, 90, 60, 1]; } + const n = fbm(x / 8, y / 8, 65, 8); const groove = px === 0 || py === 0; return groove ? [24, 28, 30] : mul([60, 66, 70], 0.8 + 0.5 * n); + }); + T.door = texture(64, 128, (x, y) => { // big door with hazard stripes + if (y > 104) return (((x + y) >> 3) & 1) ? [200, 170, 40] : [30, 30, 30]; + const n = fbm(x / 6, y / 6, 71, 11), seam = x === 31 || x === 32; const c = mul([110, 104, 92], 0.75 + 0.45 * n); + return seam ? [28, 26, 24] : ((y & 31) === 0 ? mul(c, 0.6) : c); + }); + // flats 64x64 + T.floor = texture(64, 64, (x, y) => { const t = (x & 31) === 0 || (y & 31) === 0, n = fbm(x / 5, y / 5, 81, 13); return t ? [40, 38, 36] : mul([98, 92, 84], 0.75 + 0.4 * n + 0.12 * h2(x >> 5, y >> 5, 83)); }); + T.dirt = texture(64, 64, (x, y) => { const n = fbm(x / 7, y / 7, 91, 9, 5), r = h2(x, y, 93) > 0.97; return r ? [40, 30, 24] : mix([64, 44, 32], [130, 96, 66], n); }); + T.blood = texture(64, 64, (x, y) => { const n = fbm(x / 6, y / 6, 101, 11), v = fbm(x / 10, y / 10, 103, 6); return v > 0.58 ? mix([90, 6, 6], [150, 16, 12], n) : mix([58, 48, 46], [96, 84, 80], n); }); + T.ceil = texture(64, 64, (x, y) => { const lit = x > 20 && x < 44 && y > 20 && y < 44; if (lit) return [235, 230, 200, 1]; const n = fbm(x / 6, y / 6, 111, 11); const e = (x & 15) === 0 || (y & 15) === 0; return e ? [36, 36, 40] : mul([84, 84, 90], 0.8 + 0.3 * n); }); + T.nukage = [0, 1, 2, 3].map(f => texture(64, 64, (x, y) => { const n = fbm(x / 8 + f * 0.9, y / 8 + f * 0.4, 121, 8, 3); return [40 + 60 * n, 150 + 100 * n, 30 + 40 * n, 1]; })); + return T; + } + function buildSky(kind) { // 1024 x HALF panorama, not distance lit + const w = 1024, h = HALF, out = new Uint32Array(w * h); + const top = kind === 'dusk' ? [24, 18, 48] : [40, 4, 4], hor = kind === 'dusk' ? [200, 110, 70] : [210, 80, 30]; + for (let x = 0; x < w; x++) { + const ridge = 0.55 + 0.25 * fbm(x / 64, 0.5, kind === 'dusk' ? 131 : 133, 16, 5), ridge2 = 0.72 + 0.18 * fbm(x / 40, 3.5, 137, 25, 4); + for (let y = 0; y < h; y++) { + const t = y / h; let c = mix(top, hor, Math.pow(t, 1.6)); + const cl = fbm(x / 90, y / 30, 139, 11, 4); c = mix(c, kind === 'dusk' ? [120, 80, 110] : [120, 30, 10], Math.max(0, cl - 0.55) * 1.4); + if (t > ridge2) c = kind === 'dusk' ? [36, 26, 40] : [60, 14, 8]; + if (t > ridge) c = mix(kind === 'dusk' ? [20, 16, 26] : [30, 8, 6], [10, 6, 8], (t - ridge) * 2); + out[y * w + x] = pack(c[0] | 0, c[1] | 0, c[2] | 0); + } + } + return out; + } + // ---------- procedural sprites (Canvas 2D at 2 texels per map unit) ---------- + const SPR = { cyberdemon: [150, 124], baron: [80, 78], spider: [270, 116], vile: [70, 82], imp: [56, 60], fatso: [116, 84], undead: [64, 80] }; + function canvas(w, h) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; } + function lin(x, x0, y0, x1, y1, stops) { const g = x.createLinearGradient(x0, y0, x1, y1); for (const [o, c] of stops) g.addColorStop(o, c); return g; } + function rad(x, cx, cy, r, stops) { const g = x.createRadialGradient(cx, cy, 0, cx, cy, r); for (const [o, c] of stops) g.addColorStop(o, c); return g; } + function ell(x, cx, cy, rx, ry, fill, rot = 0, stroke) { x.beginPath(); x.ellipse(cx, cy, Math.max(0.1, rx), Math.max(0.1, ry), rot, 0, TAU); x.fillStyle = fill; x.fill(); if (stroke) { x.strokeStyle = stroke; x.lineWidth = 2; x.stroke(); } } + function poly(x, pts, fill, stroke, lw = 2) { x.beginPath(); x.moveTo(pts[0], pts[1]); for (let i = 2; i < pts.length; i += 2) x.lineTo(pts[i], pts[i + 1]); x.closePath(); x.fillStyle = fill; x.fill(); if (stroke) { x.strokeStyle = stroke; x.lineWidth = lw; x.stroke(); } } + function limb(x, pts, w, col, edge) { x.lineCap = 'round'; x.lineJoin = 'round'; x.beginPath(); x.moveTo(pts[0], pts[1]); for (let i = 2; i < pts.length; i += 2) x.lineTo(pts[i], pts[i + 1]); x.strokeStyle = edge; x.lineWidth = w + 4; x.stroke(); x.strokeStyle = col; x.lineWidth = w; x.stroke(); } + function horn(x, x0, y0, cx, cy, x1, y1, w) { x.lineCap = 'round'; x.beginPath(); x.moveTo(x0, y0); x.quadraticCurveTo(cx, cy, x1, y1); x.strokeStyle = '#3a2a1a'; x.lineWidth = w + 3; x.stroke(); x.strokeStyle = lin(x, x0, y0, x1, y1, [[0, '#d8c8a0'], [0.7, '#b8a070'], [1, '#4a3a2a']]); x.lineWidth = w; x.stroke(); } + function gore(x, cx, cy, w, n, seed) { for (let i = 0; i < n; i++) { const a = h2(i, seed, 7) * TAU, d = h2(i, seed, 9) * w; ell(x, cx + Math.cos(a) * d, cy + Math.sin(a) * d * 0.35, 4 + h2(i, seed, 11) * 10, 3 + h2(i, seed, 13) * 6, h2(i, seed, 15) > 0.5 ? '#7a0e0a' : '#a8402c'); } } + function drawCyber(x, L) { + const W2 = 300, G = 248, walk = 'ABCD'.indexOf(L), atk = L === 'E' || L === 'F', pain = L === 'G', die = 'HIJKLMNOP'.indexOf(L); + if (die >= 4) { // collapsing remains + const t = (die - 4) / 4, hgt = 120 * (1 - t) + 30; + gore(x, W2 / 2, G - 18, 120, 26, 3); ell(x, W2 / 2, G - hgt / 2 + 10, 70 + t * 30, hgt / 2, lin(x, 0, G - hgt, 0, G, [[0, '#8a4a30'], [1, '#3a1810']])); + ell(x, W2 / 2 + 40, G - 22, 30, 16, '#6a6e72'); horn(x, W2 / 2 - 30, G - hgt + 30, W2 / 2 - 70, G - hgt - 10, W2 / 2 - 60, G - hgt - 40 + t * 40, 8); + if (t < 1) gore(x, W2 / 2, G - hgt + 20, 60, 14, 5); + return; + } + const sink = die >= 0 ? die * 10 : 0, bob = walk === 1 || walk === 3 ? 3 : 0, lf = walk === 0 ? -8 : 0, rf = walk === 2 ? -8 : 0; + x.save(); x.translate(0, sink + bob); + // legs: organic left (screen) with hoof, mechanical right + limb(x, [118, 150, 108, 196, 116, G - 20 + lf], 26, '#7a4a2c', '#2a140a'); poly(x, [98, G - 24 + lf, 134, G - 24 + lf, 138, G - 4 + lf, 94, G - 4 + lf], '#1e1612'); + limb(x, [182, 150, 192, 196, 186, G - 22 + rf], 22, '#80868c', '#22262a'); ell(x, 192, 196, 12, 12, '#a8aeb4', 0, '#2a2e32'); + poly(x, [168, G - 22 + rf, 206, G - 22 + rf, 214, G - 4 + rf, 160, G - 4 + rf], '#4a4e54', '#1a1c20'); limb(x, [196, 160, 204, 206], 6, '#c0c4c8', '#30343a'); + poly(x, [104, 136, 196, 136, 206, 160, 94, 160], '#3a2416', '#1a0c06'); + // torso + x.beginPath(); x.moveTo(70, 70); x.quadraticCurveTo(150, 40, 230, 70); x.lineTo(206, 140); x.quadraticCurveTo(150, 156, 94, 140); x.closePath(); + x.fillStyle = rad(x, 140, 92, 110, [[0, pain ? '#c86048' : '#a8603e'], [0.6, pain ? '#8a3424' : '#7a3c24'], [1, '#3a160c']]); x.fill(); x.strokeStyle = '#2a0e06'; x.lineWidth = 3; x.stroke(); + x.strokeStyle = '#4a1e10'; x.lineWidth = 3; for (const [a, b, c, d] of [[150, 64, 150, 140], [104, 96, 146, 104], [196, 96, 154, 104], [112, 120, 188, 120]]) { x.beginPath(); x.moveTo(a, b); x.lineTo(c, d); x.stroke(); } + ell(x, 124, 84, 18, 12, 'rgba(255,190,150,.18)'); ell(x, 176, 84, 18, 12, 'rgba(255,190,150,.18)'); + // left (screen) organic arm with claws + limb(x, [72, 76, 52, 120, 58, 168], 24, '#8a4e30', '#2a120a'); for (let i = 0; i < 4; i++) limb(x, [50 + i * 6, 170, 46 + i * 7, 184], 4, '#e0d0b0', '#3a2a1a'); + // right (screen) rocket-launcher arm + if (atk) { limb(x, [228, 78, 246, 104], 26, '#7a8086', '#202428'); ell(x, 246, 112, 26, 26, '#6a7076', 0, '#1a1c20'); ell(x, 246, 112, 15, 15, '#101214'); ell(x, 246, 112, 8, 8, L === 'F' ? '#fff0a0' : '#2a2c30'); + if (L === 'F') { ell(x, 246, 112, 34, 34, 'rgba(255,170,40,.55)'); ell(x, 246, 112, 18, 18, 'rgba(255,250,200,.9)'); } } + else { limb(x, [228, 76, 250, 120, 250, 168], 26, '#7a8086', '#202428'); ell(x, 250, 172, 14, 10, '#121416'); poly(x, [236, 128, 264, 128, 262, 136, 238, 136], '#a0a6ac'); } + // head and horns + const ht = pain ? 6 : 0; x.save(); x.translate(150, 52); x.rotate(pain ? -0.18 : 0); + horn(x, -20, -8, -64, -20, -54, -64, 12); horn(x, 20, -8, 64, -20, 54, -64, 12); + ell(x, 0, 0, 24, 26, rad(x, 0, -6, 30, [[0, '#b07850'], [1, '#5a2c18']]), 0, '#2a120a'); + ell(x, -10, -6, 6, 4, '#ffd040'); ell(x, 10, -6, 6, 4, '#ffd040'); ell(x, -10, -6, 2, 2, '#ff4010'); ell(x, 10, -6, 2, 2, '#ff4010'); + poly(x, [-14, 10, 14, 10, 10, 20 + ht, -10, 20 + ht], '#2a0c06'); for (let i = -10; i <= 8; i += 6) poly(x, [i, 10, i + 4, 10, i + 2, 15], '#e8dcc0'); + x.restore(); + if (die >= 0) { gore(x, 150, 100, 50, 10 + die * 6, die + 1); ell(x, 150, 96, 30 + die * 10, 24 + die * 6, 'rgba(255,140,30,' + (0.5 - die * 0.1) + ')'); } + x.restore(); + } + function drawBaron(x, L) { + const W2 = 160, G = 154, walk = 'ABCD'.indexOf(L), pain = L === 'H', die = 'IJKLMNO'.indexOf(L); + if (die >= 3) { const t = (die - 3) / 3; gore(x, 80, G - 10, 50, 16, 21); ell(x, 80, G - 16 + t * 4, 46 + t * 10, 18 - t * 6, lin(x, 0, G - 34, 0, G, [[0, '#c88870'], [1, '#5a2a1c']])); horn(x, 60, G - 28, 46, G - 46, 40, G - 50 + t * 20, 5); gore(x, 80, G - 20, 30, 10, 23); return; } + const fall = die >= 0 ? (die + 1) * 12 : 0, bob = walk === 1 || walk === 3 ? 2 : 0, lf = walk === 0 ? -6 : 0, rf = walk === 2 ? -6 : 0; + x.save(); x.translate(80, G); x.rotate(die >= 0 ? -0.15 * (die + 1) : 0); x.translate(-80, -G + fall + bob); + // goat legs (brown fur), hooves + limb(x, [64, 92, 52, 120, 62, G - 8 + lf], 16, '#6a4a30', '#24160c'); limb(x, [96, 92, 108, 120, 98, G - 8 + rf], 16, '#6a4a30', '#24160c'); + poly(x, [52, G - 10 + lf, 72, G - 10 + lf, 74, G + lf, 50, G + lf], '#1a1210'); poly(x, [88, G - 10 + rf, 108, G - 10 + rf, 110, G + rf, 86, G + rf], '#1a1210'); + // torso + x.beginPath(); x.moveTo(44, 46); x.quadraticCurveTo(80, 32, 116, 46); x.lineTo(104, 96); x.quadraticCurveTo(80, 104, 56, 96); x.closePath(); + x.fillStyle = rad(x, 76, 60, 60, [[0, pain ? '#f0a890' : '#e0a890'], [0.65, pain ? '#c06050' : '#b87862'], [1, '#5a2c22']]); x.fill(); x.strokeStyle = '#3a1810'; x.lineWidth = 2; x.stroke(); + x.strokeStyle = '#8a4a3a'; x.lineWidth = 2; for (const [a, b, c, d] of [[80, 46, 80, 98], [58, 64, 78, 68], [102, 64, 82, 68], [64, 82, 96, 82]]) { x.beginPath(); x.moveTo(a, b); x.lineTo(c, d); x.stroke(); } + // arms: attack E (wind up), F (high), G (throw toward the viewer) + const glow = (cx, cy, r) => { ell(x, cx, cy, r * 1.8, r * 1.8, 'rgba(80,255,90,.35)'); ell(x, cx, cy, r, r, '#70ff70'); ell(x, cx, cy, r * 0.5, r * 0.5, '#e8ffe0'); }; + limb(x, [46, 50, 32, 76, 34, 104 + (walk === 0 ? 4 : 0)], 13, '#d09a84', '#3a1810'); + if (L === 'E') { limb(x, [114, 50, 134, 30, 126, 10], 13, '#d09a84', '#3a1810'); glow(124, 8, 7); } + else if (L === 'F') { limb(x, [114, 50, 124, 22, 108, 4], 13, '#d09a84', '#3a1810'); glow(106, 2, 9); } + else if (L === 'G') { limb(x, [114, 50, 112, 66], 15, '#d09a84', '#3a1810'); glow(110, 66, 12); } + else limb(x, [114, 50, 128, 76, 126, 104 + (walk === 2 ? 4 : 0)], 13, '#d09a84', '#3a1810'); + // head with horns + x.save(); x.translate(80, 30); x.rotate(pain ? 0.2 : 0); + horn(x, -10, -6, -26, -20, -22, -40, 6); horn(x, 10, -6, 26, -20, 22, -40, 6); + ell(x, 0, 0, 13, 15, rad(x, 0, -4, 16, [[0, '#e8b098'], [1, '#8a4a3a']]), 0, '#3a1810'); + ell(x, -5, -3, 3.2, 2.2, '#ff5020'); ell(x, 5, -3, 3.2, 2.2, '#ff5020'); poly(x, [-7, 6, 7, 6, 5, pain ? 13 : 10, -5, pain ? 13 : 10], '#3a0a08'); + x.restore(); + if (die >= 0) gore(x, 80, 70, 24, 6 + die * 4, die + 31); + x.restore(); + } + function drawVile(x, L) { // gaunt, pale, tall; attack frames raise the hands with growing flame, heal frames glow + const G = 162, walk = 'ABCDEF'.indexOf(L), atk = 'GHIJKLMNOP'.indexOf(L), heal = 'abc'.indexOf(L), pain = L === 'Q', die = 'RSTUVWXYZ'.indexOf(L); + if (die >= 3) { const t = Math.min(1, (die - 3) / 5); gore(x, 70, G - 8, 40, 12, 41); ell(x, 70, G - 12 + t * 4, 34 + t * 8, 12 - t * 4, lin(x, 0, G - 26, 0, G, [[0, '#d8c8a8'], [1, '#6a5a40']])); gore(x, 70, G - 16, 26, 8, 43); return; } + const fall = die >= 0 ? (die + 1) * 16 : 0, step = walk >= 0 ? (walk % 2 ? 3 : 0) : 0, lf = walk === 0 || walk === 3 ? -8 : 0, rf = walk === 1 || walk === 4 ? -8 : 0; + x.save(); x.translate(70, G); x.rotate(die >= 0 ? 0.18 * (die + 1) : 0); x.translate(-70, -G + fall + step); + limb(x, [62, 96, 54, 128, 58, G - 6 + lf], 9, '#d8cbb0', '#3a3020'); limb(x, [78, 96, 88, 128, 84, G - 6 + rf], 9, '#d8cbb0', '#3a3020'); + // ribbed torso and shoulder spikes + x.beginPath(); x.moveTo(50, 40); x.quadraticCurveTo(70, 30, 90, 40); x.lineTo(84, 100); x.quadraticCurveTo(70, 106, 56, 100); x.closePath(); + x.fillStyle = lin(x, 50, 40, 90, 100, [[0, pain ? '#fff0d8' : '#eadcc0'], [1, '#8a7a5a']]); x.fill(); x.strokeStyle = '#3a3020'; x.lineWidth = 2; x.stroke(); + x.strokeStyle = '#a89070'; x.lineWidth = 1.5; for (let i = 0; i < 5; i++) { x.beginPath(); x.moveTo(56, 52 + i * 9); x.quadraticCurveTo(70, 56 + i * 9, 84, 52 + i * 9); x.stroke(); } + poly(x, [50, 42, 40, 22, 56, 38], '#c8b890', '#3a3020'); poly(x, [90, 42, 100, 22, 84, 38], '#c8b890', '#3a3020'); + const flame = (cx, cy, r) => { ell(x, cx, cy, r * 1.6, r * 2, 'rgba(255,120,20,.35)'); ell(x, cx, cy - r * 0.3, r, r * 1.5, '#ffa020'); ell(x, cx, cy - r * 0.1, r * 0.5, r * 0.8, '#fff2b0'); }; + if (atk >= 0) { const up = Math.min(1, atk / 7), r = 4 + atk * 1.4; limb(x, [52, 46, 36, 30 - up * 14, 44, 10 - up * 10], 8, '#e0d2b8', '#3a3020'); limb(x, [88, 46, 104, 30 - up * 14, 96, 10 - up * 10], 8, '#e0d2b8', '#3a3020'); if (atk >= 1 && atk < 9) { flame(44, 6 - up * 10, r); flame(96, 6 - up * 10, r); } if (atk === 8) flame(70, 0, 16); } + else if (heal >= 0) { limb(x, [52, 46, 34, 60, 30, 84], 8, '#e0d2b8', '#3a3020'); limb(x, [88, 46, 106, 60, 110, 84], 8, '#e0d2b8', '#3a3020'); ell(x, 70, 70, 52, 60, 'rgba(255,240,160,' + (0.25 + heal * 0.12) + ')'); } + else { limb(x, [52, 46, 42, 76, 46, 102 + (walk === 1 ? 4 : 0)], 8, '#e0d2b8', '#3a3020'); limb(x, [88, 46, 98, 76, 94, 102 + (walk === 4 ? 4 : 0)], 8, '#e0d2b8', '#3a3020'); } + // long skull-like head + x.save(); x.translate(70, 24); x.rotate(pain ? -0.25 : 0); + ell(x, 0, 0, 10, 15, rad(x, 0, -6, 16, [[0, '#f4e8d0'], [1, '#9a8a6a']]), 0, '#3a3020'); + const eye = atk >= 0 || heal >= 0 ? '#ffe060' : '#ff4020'; + ell(x, -4, -2, 2.6, 3.4, '#200a04'); ell(x, 4, -2, 2.6, 3.4, '#200a04'); ell(x, -4, -2, 1, 1.2, eye); ell(x, 4, -2, 1, 1.2, eye); + poly(x, [-5, 8, 5, 8, 3, pain ? 15 : 12, -3, pain ? 15 : 12], '#2a1a0a'); + x.restore(); x.restore(); + } + function drawFatso(x, L) { // huge pale-brown belly, tiny head, a flame cannon on each arm; H is the muzzle flash + const W = 232, G = 158, c = W / 2, walk = 'ABCDEF'.indexOf(L), raise = L === 'G', fire = L === 'H', recoil = L === 'I', pain = L === 'J', die = 'KLMNOPQRS'.indexOf(L), dead = L === 'T'; + if (dead || die >= 5) { const t = dead ? 1 : (die - 4) / 5; gore(x, c, G - 8, 66 + t * 18, 16, 71); ell(x, c, G - 16 + t * 6, 62 + t * 12, 26 - t * 12, lin(x, 0, G - 44, 0, G, [[0, '#b89070'], [1, '#5a3a24']]), 0, '#2a1a10'); ell(x, c - 40, G - 12, 12, 7, '#4a4a50', 0, '#1a1a20'); ell(x, c + 40, G - 12, 12, 7, '#4a4a50', 0, '#1a1a20'); return; } + const fall = die >= 0 ? (die + 1) * 12 : 0, bob = walk >= 0 ? (walk % 2 ? 2 : 0) : 0, lf = walk === 0 || walk === 3 ? -6 : 0, rf = walk === 1 || walk === 4 ? -6 : 0; + x.save(); x.translate(c, G); x.rotate(die >= 0 ? 0.07 * (die + 1) : 0); x.translate(-c, -G + fall + bob); + limb(x, [c - 34, 120, c - 42, G - 18, c - 40, G - 4 + lf], 22, '#a07858', '#2a1a10'); limb(x, [c + 34, 120, c + 42, G - 18, c + 40, G - 4 + rf], 22, '#a07858', '#2a1a10'); + ell(x, c, 88, 66, 58, rad(x, c - 12, 74, 72, [[0, pain ? '#f0c8a8' : '#d0a888'], [0.7, '#a07858'], [1, '#5a3a24']]), 0, '#2a1a10'); + x.strokeStyle = '#7a5a40'; x.lineWidth = 2; for (const k of [0, 1, 2]) { x.beginPath(); x.moveTo(c - 44 + k * 4, 104 + k * 10); x.quadraticCurveTo(c, 116 + k * 12, c + 44 - k * 4, 104 + k * 10); x.stroke(); } + x.fillStyle = '#6a5040'; x.fillRect(c - 62, 72, 124, 6); ell(x, c, 75, 8, 7, '#8a8a90', 0, '#2a2a30'); + const up = raise ? -30 : fire ? -22 : recoil ? -12 : 0, arm = (sx) => { + limb(x, [c + sx * 58, 58, c + sx * 78, 76, c + sx * 84, 70 + up], 18, '#b08868', '#2a1a10'); + x.save(); x.translate(c + sx * 88, 62 + up); poly(x, [-11, 16, 11, 16, 8, -14, -8, -14], '#55555c', '#1a1a20'); ell(x, 0, -14, 8, 4, '#1a1a20'); if (fire) { ell(x, 0, -24, 16, 18, 'rgba(255,120,30,.5)'); ell(x, 0, -22, 9, 11, '#ffd070'); } x.restore(); + }; + arm(-1); arm(1); + ell(x, c, 30, 20, 16, rad(x, c - 4, 26, 22, [[0, '#d8b090'], [1, '#7a5a40']]), 0, '#2a1a10'); + ell(x, c - 7, 27, 3.4, 3, '#200a04'); ell(x, c + 7, 27, 3.4, 3, '#200a04'); ell(x, c - 7, 27, 1.2, 1.2, '#ff5020'); ell(x, c + 7, 27, 1.2, 1.2, '#ff5020'); + poly(x, [c - 10, 36, c + 10, 36, c + 7, pain || fire ? 44 : 40, c - 7, pain || fire ? 44 : 40], '#2a0a04'); + x.restore(); + } + function drawUndead(x, L) { // tall bone-white skeleton in a dark breastplate, shoulder launchers; K launches, I punches + const W = 128, G = 158, c = W / 2, walk = 'ABCDEF'.indexOf(L), punch = 'GHI'.indexOf(L), aim = L === 'J', fire = L === 'K', pain = L === 'L', die = 'MNOPQ'.indexOf(L); + if (die >= 3) { const t = (die - 3) / 1; gore(x, c, G - 6, 30, 8, 81); for (let i = 0; i < 6; i++) ell(x, c - 24 + i * 10, G - 8 - (i % 2) * 4, 7, 3, '#e8e2d0', i * 0.6, '#5a5446'); ell(x, c + 26, G - 12, 9 + t, 8, '#e8e2d0', 0, '#5a5446'); return; } + const fall = die >= 0 ? (die + 1) * 16 : 0, lf = walk === 0 || walk === 3 ? -8 : 0, rf = walk === 1 || walk === 4 ? -8 : 0; + x.save(); x.translate(c, G); x.rotate(die >= 0 ? -0.2 * (die + 1) : 0); x.translate(-c, -G + fall); + const bone = '#ece6d4', edge = '#4a4436'; + limb(x, [c - 9, 96, c - 14, 126, c - 12, G - 4 + lf], 6, bone, edge); limb(x, [c + 9, 96, c + 14, 126, c + 12, G - 4 + rf], 6, bone, edge); + poly(x, [c - 20, 46, c + 20, 46, c + 15, 96, c - 15, 96], lin(x, c - 20, 46, c + 20, 96, [[0, pain ? '#6a5a50' : '#4a4038'], [1, '#1a1612']]), '#0a0806'); + x.strokeStyle = '#2a241c'; x.lineWidth = 2; for (let i = 0; i < 4; i++) { x.beginPath(); x.moveTo(c - 14, 56 + i * 9); x.lineTo(c + 14, 56 + i * 9); x.stroke(); } + for (const sx of [-1, 1]) { x.save(); x.translate(c + sx * 22, 40); poly(x, [-7, 10, 7, 10, 6, -16, -6, -16], '#5a5a62', '#1a1a20'); ell(x, 0, -16, 5, 3, '#1a1a20'); if (fire) { ell(x, 0, -24, 9, 11, 'rgba(255,140,40,.55)'); ell(x, 0, -22, 5, 7, '#ffe090'); } x.restore(); } + const reach = punch === 2 ? 34 : punch === 1 ? 18 : 0; + limb(x, [c - 20, 52, c - 30, 76, c - 26 + (aim || fire ? -6 : 0), 98], 6, bone, edge); + limb(x, [c + 20, 52, c + 30 + reach * 0.3, 70 - reach * 0.6, c + 26 + reach, 92 - reach * 1.3], 6, bone, edge); + x.save(); x.translate(c, 30); x.rotate(pain ? 0.25 : 0); + ell(x, 0, 0, 11, 13, rad(x, -3, -4, 14, [[0, '#fbf7ea'], [1, '#a8a08a']]), 0, edge); + ell(x, -4, -1, 3.2, 3.6, '#120a06'); ell(x, 4, -1, 3.2, 3.6, '#120a06'); ell(x, -4, -1, 1, 1, '#ff4020'); ell(x, 4, -1, 1, 1, '#ff4020'); + poly(x, [-6, 8, 6, 8, 4, pain || punch >= 0 ? 15 : 12, -4, pain || punch >= 0 ? 15 : 12], '#2a1a10'); + x.restore(); x.restore(); + } + function drawImp(x, L) { // brown, spiked, fireball in hand on G + const G = 116, walk = 'ABCD'.indexOf(L), pain = L === 'H', die = 'IJKLM'.indexOf(L), gib = 'NOPQRSTU'.indexOf(L); + if (gib >= 0) { gore(x, 56, G - 8, 22 + gib * 4, 8 + gib * 2, 51 + gib); if (gib < 3) ell(x, 56, G - 40 + gib * 10, 16 - gib * 3, 20 - gib * 5, '#8a5a3a'); return; } + if (die >= 3) { gore(x, 56, G - 6, 30, 10, 61); ell(x, 56, G - 10, 30, 9, lin(x, 0, G - 18, 0, G, [[0, '#9a6a44'], [1, '#4a2a14']])); return; } + const fall = die >= 0 ? (die + 1) * 14 : 0, lf = walk === 0 ? -6 : 0, rf = walk === 2 ? -6 : 0; + x.save(); x.translate(56, G); x.rotate(die >= 0 ? -0.2 * (die + 1) : 0); x.translate(-56, -G + fall); + limb(x, [48, 70, 42, 92, 46, G - 4 + lf], 10, '#8a5a3a', '#24140a'); limb(x, [64, 70, 70, 92, 66, G - 4 + rf], 10, '#8a5a3a', '#24140a'); + ell(x, 56, 52, 18, 24, rad(x, 52, 46, 26, [[0, pain ? '#c8906a' : '#a8784e'], [1, '#4a2a14']]), 0, '#24140a'); + for (const [sx, sy] of [[42, 34], [70, 34], [40, 52], [72, 52]]) poly(x, [sx, sy, sx + (sx < 56 ? -8 : 8), sy - 6, sx + (sx < 56 ? -2 : 2), sy + 6], '#e8dcc0', '#3a2a14', 1); + if (L === 'G') { limb(x, [70, 40, 86, 30], 8, '#9a6a44', '#24140a'); ell(x, 88, 28, 10, 10, 'rgba(255,120,30,.5)'); ell(x, 88, 28, 6, 6, '#ffb040'); } + else if (L === 'E' || L === 'F') { limb(x, [70, 40, 80, 18], 8, '#9a6a44', '#24140a'); limb(x, [42, 40, 34, 20], 8, '#9a6a44', '#24140a'); if (L === 'F') ell(x, 80, 14, 6, 6, '#ff9030'); } + else { limb(x, [42, 40, 34, 66], 8, '#9a6a44', '#24140a'); limb(x, [70, 40, 78, 66], 8, '#9a6a44', '#24140a'); } + ell(x, 56, 22, 11, 12, rad(x, 54, 18, 14, [[0, '#b8885e'], [1, '#5a3a1e']]), 0, '#24140a'); + ell(x, 51, 20, 2.4, 2, '#ffa020'); ell(x, 61, 20, 2.4, 2, '#ffa020'); poly(x, [50, 28, 62, 28, 60, pain ? 33 : 31, 52, pain ? 33 : 31], '#2a0a04'); + x.restore(); + } + function drawSpider(x, L) { + const W2 = 540, G = 232, walk = 'ABCDEF'.indexOf(L), atk = L === 'G' || L === 'H', pain = L === 'I', die = 'JKLMNOPQRS'.indexOf(L); + const t = die < 0 ? 0 : die / 9, lower = t * 120; + // legs (4), animated knees/feet + const ph = walk < 0 ? 0 : walk / 6 * TAU; + const legs = [[-1, 0], [-1, 1], [1, 0], [1, 1]]; + for (const [s, k] of legs) { + const base = [270 + s * (60 + k * 30), 150 + lower * 0.6], knee = [270 + s * (150 + k * 70), 40 + lower + Math.sin(ph + k * Math.PI + (s > 0 ? Math.PI / 2 : 0)) * 10 * (walk >= 0 ? 1 : 0)]; + const foot = [270 + s * (190 + k * 60) + (walk >= 0 ? Math.cos(ph + k * Math.PI) * 8 * s : 0), Math.min(G, G - 2 + lower * 0.1)]; + limb(x, [base[0], base[1], knee[0], knee[1] + (die >= 0 ? t * 80 : 0), foot[0] + s * t * 40, foot[1]], 16, '#6a7076', '#1c2024'); + ell(x, knee[0], knee[1] + (die >= 0 ? t * 80 : 0), 11, 11, '#8a9096', 0, '#1c2024'); limb(x, [knee[0], knee[1] + (die >= 0 ? t * 80 : 0), (knee[0] + foot[0]) / 2, (knee[1] + foot[1]) / 2 + 10], 5, '#b0b6bc', '#30343a'); + } + if (die >= 8) { gore(x, 270, G - 26, 140, 24, 41); ell(x, 270, G - 40, 120, 34, lin(x, 0, G - 74, 0, G, [[0, '#d07a80'], [1, '#5a1c22']])); ell(x, 270, G - 20, 150, 18, '#3a3e44'); return; } + // chassis + poly(x, [180, 138 + lower, 360, 138 + lower, 340, 178 + lower, 200, 178 + lower], '#4a5056', '#1a1e22', 3); ell(x, 270, 140 + lower, 96, 16, '#5a6066', 0, '#1a1e22'); + // brain + const bc = pain ? ['#ff9a9a', '#c03a48', '#5a141c'] : ['#f0a0a8', '#c0606c', '#5a1c26'], by = 74 + lower * 0.8, br = 100 * (1 - t * 0.35); + ell(x, 270, by, br, 62 * (1 - t * 0.4), rad(x, 250, by - 24, br * 1.1, [[0, bc[0]], [0.6, bc[1]], [1, bc[2]]]), 0, '#3a0c14'); + x.strokeStyle = 'rgba(90,20,34,.8)'; x.lineWidth = 3; for (let i = 0; i < 9; i++) { x.beginPath(); const yy = by - 46 + i * 11; x.moveTo(190 + h2(i, 1, 3) * 20, yy); x.bezierCurveTo(230, yy - 14, 310, yy + 14, 352 - h2(i, 2, 3) * 20, yy); x.stroke(); } + x.beginPath(); x.moveTo(270, by - 60); x.lineTo(270, by + 50); x.stroke(); + // face and chaingun + ell(x, 270, 126 + lower, 30, 18, '#c08070', 0, '#3a1410'); ell(x, 258, 122 + lower, 6, 4, '#ffd040'); ell(x, 282, 122 + lower, 6, 4, '#ffd040'); poly(x, [258, 134 + lower, 282, 134 + lower, 276, 130 + lower, 264, 130 + lower], '#2a0808'); + ell(x, 270, 168 + lower, 26, 18, '#40464c', 0, '#101214'); for (let i = 0; i < 6; i++) { const a = i / 6 * TAU; ell(x, 270 + Math.cos(a) * 11, 168 + lower + Math.sin(a) * 7, 4, 3.5, '#0c0e10'); } + if (atk || L === 'A*') { const r = L === 'G' ? 34 : 24; ell(x, 270, 172 + lower, r * 1.4, r, 'rgba(255,190,60,.55)'); ell(x, 270, 172 + lower, r * 0.6, r * 0.45, 'rgba(255,250,210,.95)'); } + if (die >= 0) { gore(x, 270, 110, 80, 8 + die * 3, die + 51); ell(x, 270, 100, 40 + die * 8, 30 + die * 4, 'rgba(255,170,60,' + Math.max(0, 0.45 - die * 0.05) + ')'); } + } + function drawPickup(x, kind) { + const c = x.canvas.width / 2, G = x.canvas.height; + if (kind === 'medikit' || kind === 'stimpack') { const s = kind === 'medikit' ? 1 : 0.7; poly(x, [c - 26 * s, G - 30 * s, c + 26 * s, G - 30 * s, c + 26 * s, G, c - 26 * s, G], '#e8e4d8', '#6a665c'); poly(x, [c - 5 * s, G - 26 * s, c + 5 * s, G - 26 * s, c + 5 * s, G - 4 * s, c - 5 * s, G - 4 * s], '#c01818'); poly(x, [c - 16 * s, G - 20 * s, c + 16 * s, G - 20 * s, c + 16 * s, G - 10 * s, c - 16 * s, G - 10 * s], '#c01818'); } + else if (kind === 'rocketbox') { poly(x, [c - 28, G - 26, c + 28, G - 26, c + 28, G, c - 28, G], '#6a5a3a', '#2a2014'); for (let i = 0; i < 4; i++) { poly(x, [c - 24 + i * 13, G - 40, c - 16 + i * 13, G - 40, c - 16 + i * 13, G - 24, c - 24 + i * 13, G - 24], '#8a8e90', '#30343a'); poly(x, [c - 24 + i * 13, G - 40, c - 20 + i * 13, G - 48, c - 16 + i * 13, G - 40], '#c03020'); } } + else if (kind === 'bulletbox') { poly(x, [c - 28, G - 26, c + 28, G - 26, c + 28, G, c - 28, G], '#4a5a3a', '#1a2410'); x.fillStyle = '#d8c060'; x.font = 'bold 12px monospace'; x.textAlign = 'center'; x.fillText('AMMO', c, G - 9); } + else if (kind === 'shellbox') { poly(x, [c - 28, G - 24, c + 28, G - 24, c + 28, G, c - 28, G], '#8a3a20', '#3a1408'); for (let i = 0; i < 5; i++) poly(x, [c - 24 + i * 10, G - 34, c - 18 + i * 10, G - 34, c - 18 + i * 10, G - 22, c - 24 + i * 10, G - 22], '#d0a040', '#6a4a10'); } + else { const col = kind === 'greenarmor' ? ['#40b040', '#1a5a1a'] : ['#4060d0', '#1a2a6a']; x.beginPath(); x.moveTo(c - 24, G - 40); x.lineTo(c - 10, G - 44); x.quadraticCurveTo(c, G - 36, c + 10, G - 44); x.lineTo(c + 24, G - 40); x.lineTo(c + 20, G - 4); x.quadraticCurveTo(c, G + 2, c - 20, G - 4); x.closePath(); x.fillStyle = lin(x, c - 24, G - 44, c + 24, G, [[0, col[0]], [1, col[1]]]); x.fill(); x.strokeStyle = '#101010'; x.lineWidth = 2; x.stroke(); poly(x, [c - 4, G - 34, c + 4, G - 34, c + 4, G - 8, c - 4, G - 8], 'rgba(255,255,255,.25)'); } + } + function drawFx(x, kind, f) { + const w = x.canvas.width, c = w / 2, cy = x.canvas.height / 2; + if (kind === 'rocket') { ell(x, c, cy, 22, 22, 'rgba(255,120,30,.45)'); ell(x, c, cy, 13, 13, '#ff9a30'); ell(x, c, cy, 7, 7, '#fff4c0'); } + else if (kind === 'fireball') { const r = f ? 16 : 13; ell(x, c, cy, r * 1.6, r * 1.6, 'rgba(70,255,80,.35)'); ell(x, c, cy, r, r, '#60f060'); ell(x, c, cy, r * 0.5, r * 0.5, '#efffe8'); } + else if (kind === 'fireballX') { const r = 14 + f * 9; ell(x, c, cy, r * 1.3, r * 1.3, 'rgba(70,255,80,' + (0.45 - f * 0.12) + ')'); ell(x, c, cy, r * 0.8, r * 0.8, 'rgba(160,255,150,' + (0.8 - f * 0.25) + ')'); } + else if (kind === 'blast') { const r = [26, 36, 42][f]; ell(x, c, cy, r * 1.25, r * 1.2, ['rgba(255,140,40,.6)', 'rgba(230,90,20,.55)', 'rgba(120,40,20,.45)'][f]); ell(x, c, cy, r, r * 0.95, ['#ffb040', '#e86a20', '#7a2c18'][f]); ell(x, c - 4, cy - 4, r * 0.55, r * 0.5, ['#fff6c0', '#ffc060', '#a04a28'][f]); for (let i = 0; i < 7; i++) { const a = i / 7 * TAU + f; ell(x, c + Math.cos(a) * r * 0.9, cy + Math.sin(a) * r * 0.85, r * 0.35, r * 0.3, ['#ffd070', '#f08030', '#5a2014'][f]); } } + else if (kind === 'troopshot') { const r = f ? 12 : 10; ell(x, c, cy, r * 1.6, r * 1.6, 'rgba(255,110,30,.35)'); ell(x, c, cy, r, r, '#ff8a20'); ell(x, c, cy, r * 0.5, r * 0.5, '#fff0b0'); } + else if (kind === 'troopshotX') { const r = 12 + f * 8; ell(x, c, cy, r * 1.3, r * 1.3, 'rgba(255,110,30,' + (0.45 - f * 0.12) + ')'); ell(x, c, cy, r * 0.8, r * 0.8, 'rgba(255,200,120,' + (0.8 - f * 0.25) + ')'); } + else if (kind === 'tracer') { const r = f ? 11 : 9; ell(x, c, cy, r * 1.8, r * 1.8, 'rgba(255,160,60,.35)'); ell(x, c, cy, r, r, '#ffa030'); ell(x, c, cy, r * 0.45, r * 0.45, '#fffbe0'); } + else if (kind === 'smoke') { const r = [7, 9, 8, 6][f] || 6; ell(x, c, cy, r, r, ['#bcb8b0', '#a09c96', '#8a8680', '#6a6662'][f] || '#6a6662'); } + else if (kind === 'fatshot') { const r = f ? 13 : 11; ell(x, c, cy, r * 1.7, r * 1.5, 'rgba(255,90,20,.4)'); ell(x, c, cy, r, r * 0.9, '#ff7a18'); ell(x, c + 2, cy - 1, r * 0.45, r * 0.4, '#ffe8a0'); } + else if (kind === 'hellfire') { const S = x.canvas.height, W2 = x.canvas.width, hgt = 0.5 + 0.5 * Math.sin((f + 1) / 9 * Math.PI); const tongue = (cx, w, hh, col) => { x.beginPath(); x.moveTo(cx - w, S); x.quadraticCurveTo(cx - w * 1.1, S - hh * 0.55, cx + w * 0.25, S - hh); x.quadraticCurveTo(cx + w * 0.2, S - hh * 0.5, cx + w, S); x.closePath(); x.fillStyle = col; x.fill(); }; for (let i = 0; i < 7; i++) { const cx = W2 * (0.12 + i * 0.127), hh = S * (0.55 + 0.4 * h2(i, f, 191)) * hgt; tongue(cx, W2 * 0.09, hh, i % 2 ? '#e05010' : '#ff8a18'); } for (let i = 0; i < 5; i++) { const cx = W2 * (0.2 + i * 0.15), hh = S * (0.35 + 0.3 * h2(i, f, 193)) * hgt; tongue(cx, W2 * 0.06, hh, '#ffd050'); } ell(x, W2 / 2, S - 4, W2 * 0.42, 6, '#fff0b0'); } + else if (kind === 'tfog') { const r = 10 + f * 3, al = Math.max(0.1, 0.8 - f * 0.07); ell(x, c, cy, r * 1.4, r * 1.9, 'rgba(60,255,90,' + al * 0.5 + ')'); ell(x, c, cy, r * 0.7, r, 'rgba(200,255,200,' + al + ')'); } + else if (kind === 'puff') { const r = [9, 8, 6, 4][f]; ell(x, c, cy, r, r, ['#fff8e0', '#c8c4bc', '#9a968e', '#6a6660'][f]); } + else if (kind === 'blood') { const r = [8, 6, 4][f]; ell(x, c, cy, r, r * 1.2, '#b01010'); ell(x, c + r, cy + r, r * 0.5, r * 0.6, '#801010'); } + } + function toSprite(cv) { const d = cv.getContext('2d').getImageData(0, 0, cv.width, cv.height).data, n = cv.width * cv.height, px = new Uint32Array(n); for (let i = 0; i < n; i++) { const a = d[i * 4 + 3]; px[i] = a < 110 ? 0 : pack(d[i * 4], d[i * 4 + 1], d[i * 4 + 2]); } return { w: cv.width, h: cv.height, px }; } + function sprite(kind, frame) { + const key = kind + ':' + frame; if (R.spr[key]) return R.spr[key]; + let cv; + if (SPR[kind]) { const [w, h] = SPR[kind]; cv = canvas(w * 2, h * 2); const x = cv.getContext('2d'); if (kind === 'cyberdemon') drawCyber(x, frame); else if (kind === 'baron') drawBaron(x, frame); else if (kind === 'vile') drawVile(x, frame); else if (kind === 'fatso') drawFatso(x, frame); else if (kind === 'undead') drawUndead(x, frame); else if (kind === 'imp') drawImp(x, frame); else drawSpider(x, frame); } + else if (['medikit', 'stimpack', 'rocketbox', 'shellbox', 'bulletbox', 'greenarmor', 'bluearmor'].includes(kind)) { cv = canvas(64, 56); drawPickup(cv.getContext('2d'), kind); } + else { const s = kind === 'blast' ? 120 : kind === 'puff' || kind === 'blood' || kind === 'smoke' ? 24 : kind === 'fireballX' || kind === 'troopshotX' ? 80 : kind === 'tfog' ? 64 : kind === 'hellfire' ? 128 : 56; cv = canvas(s, s); drawFx(cv.getContext('2d'), kind, frame); } + return R.spr[key] = toSprite(cv); + } + // ---------- first-person weapons and status bar (Canvas 2D) ---------- + function weaponCanvas(weapon, frame, flash) { + const key = 'w:' + weapon + frame + (flash || ''); if (R.spr[key]) return R.spr[key]; + const cv = canvas(300, 260), x = cv.getContext('2d'), c = 150; + if (weapon === 'shotgun') { + const dy = { A: 0, B: 18, C: 34, D: 44 }[frame] || 0, pump = frame === 'A' ? 0 : 22; + if (flash) { const r = flash === 'A' ? 30 : 20; ell(x, c, 48 + dy, r * 1.3, r, 'rgba(255,170,40,.55)'); ell(x, c, 52 + dy, r * 0.7, r * 0.55, '#fff2b0'); } + poly(x, [c - 10, 60 + dy, c + 10, 60 + dy, c + 22, 200 + dy, c - 22, 200 + dy], lin(x, c - 22, 0, c + 22, 0, [[0, '#2a2e32'], [0.5, '#6a7076'], [1, '#22262a']]), '#0c0e10'); + ell(x, c, 62 + dy, 10, 5, '#0a0a0a'); poly(x, [c - 26, 140 + dy + pump, c + 26, 140 + dy + pump, c + 30, 184 + dy + pump, c - 30, 184 + dy + pump], lin(x, 0, 140, 0, 184, [[0, '#8a5a2a'], [1, '#4a2a10']]), '#1a0c04'); + poly(x, [c - 52, 210 + dy, c + 52, 210 + dy, c + 64, 260, c - 64, 260], '#3a3e42', '#101214'); poly(x, [c - 40, 196 + dy, c + 40, 196 + dy, c + 52, 214 + dy, c - 52, 214 + dy], '#5a3a1c', '#1a0c04'); + ell(x, c - 34, 168 + dy + pump, 18, 14, '#b88a68', 0, '#3a2414'); ell(x, c + 34, 168 + dy + pump, 18, 14, '#b88a68', 0, '#3a2414'); + } else if (weapon === 'chaingun') { + const spin = frame === 'B' ? 1 : 0; + if (flash) { const r = flash === 'A' ? 15 : 19; ell(x, c, 56, r * 1.5, r, 'rgba(255,180,50,.55)'); ell(x, c, 58, r * 0.7, r * 0.5, '#fff4c0'); for (let i = 0; i < 5; i++) { const a = i / 5 * TAU + (flash === 'B' ? 0.6 : 0); poly(x, [c + Math.cos(a) * r * 0.5, 58 + Math.sin(a) * r * 0.3, c + Math.cos(a + 0.25) * r * 1.9, 58 + Math.sin(a + 0.25) * r * 1.1, c + Math.cos(a + 0.5) * r * 0.5, 58 + Math.sin(a + 0.5) * r * 0.3], 'rgba(255,220,120,.8)'); } } + poly(x, [c - 40, 70, c + 40, 70, c + 58, 220, c - 58, 220], lin(x, c - 58, 0, c + 58, 0, [[0, '#24282c'], [0.5, '#5a6066'], [1, '#1c2024']]), '#0a0c0e'); + for (let i = 0; i < 6; i++) { const a = (i + spin * 0.5) / 6 * TAU, bx = c + Math.cos(a) * 18; ell(x, bx, 66 + Math.sin(a) * 5, 6, 4, Math.sin(a) > 0 ? '#2a2e32' : '#0c0e10'); poly(x, [bx - 4, 66, bx + 4, 66, bx + 6, 120, bx - 6, 120], Math.cos(a) > 0 ? '#7a8086' : '#4a5056', '#101214', 1); } + ell(x, c, 66, 26, 9, 'rgba(0,0,0,0)', 0, '#30343a'); poly(x, [c - 50, 120, c + 50, 120, c + 54, 140, c - 54, 140], '#3a3e44', '#101214'); + ell(x, c - 56, 196, 20, 16, '#b88a68', 0, '#3a2414'); ell(x, c + 56, 196, 20, 16, '#b88a68', 0, '#3a2414'); poly(x, [c - 70, 224, c + 70, 224, c + 80, 260, c - 80, 260], '#2e3236'); + } else { + const dy = frame === 'B' ? 12 : 0; + if (flash) { const k = 'ABCD'.indexOf(flash), r = [20, 27, 24, 16][k]; ell(x, c, 46 + dy, r * 1.5, r, 'rgba(255,150,40,.5)'); ell(x, c, 48 + dy, r * 0.8, r * 0.55, ['#fff6c8', '#ffe090', '#ffb060', '#e07030'][k]); for (let i = 0; i < 6; i++) { const a = i / 6 * TAU + k; poly(x, [c + Math.cos(a) * r * 0.6, 48 + dy + Math.sin(a) * r * 0.35, c + Math.cos(a + 0.22) * r * 1.8, 48 + dy + Math.sin(a + 0.22) * r, c + Math.cos(a + 0.44) * r * 0.6, 48 + dy + Math.sin(a + 0.44) * r * 0.35], 'rgba(255,200,90,.75)'); } } + poly(x, [c - 34, 50 + dy, c + 34, 50 + dy, c + 56, 230 + dy, c - 56, 230 + dy], lin(x, c - 56, 0, c + 56, 0, [[0, '#3a4234'], [0.45, '#7a8a6a'], [1, '#2a3024']]), '#0c100a'); + ell(x, c, 52 + dy, 34, 12, '#1a1e18'); ell(x, c, 52 + dy, 24, 8, '#050605'); poly(x, [c - 60, 120 + dy, c + 60, 120 + dy, c + 62, 134 + dy, c - 62, 134 + dy], '#2a2e26'); + poly(x, [c - 18, 150 + dy, c + 18, 150 + dy, c + 22, 200 + dy, c - 22, 200 + dy], '#4a4e46', '#141612'); + ell(x, c - 62, 200 + dy, 22, 18, '#b88a68', 0, '#3a2414'); ell(x, c + 62, 200 + dy, 22, 18, '#b88a68', 0, '#3a2414'); poly(x, [c - 70, 230, c + 70, 230, c + 80, 260, c - 80, 260], '#3a3e36'); + } + return R.spr[key] = cv; + } + function faceCanvas(level, look, mode) { + const key = 'f:' + level + look + mode; if (R.spr[key]) return R.spr[key]; + const cv = canvas(60, 62), x = cv.getContext('2d'), c = 30; + ell(x, c, 34, 20, 25, rad(x, c - 4, 26, 26, [[0, mode === 'dead' ? '#9a7a6a' : '#e0a888'], [1, '#8a5a40']]), 0, '#2a1a10'); + poly(x, [c - 20, 20, c - 12, 6, c + 12, 6, c + 20, 20, c + 16, 14, c - 16, 14], '#5a3a1a'); + for (let i = 0; i < level; i++) ell(x, c - 12 + (h2(i, level, 3) * 24), 26 + h2(i, level, 5) * 26, 3 + i, 2 + i * 0.6, 'rgba(160,20,16,.75)'); + if (mode === 'dead') { x.strokeStyle = '#3a0a0a'; x.lineWidth = 3; for (const s of [-1, 1]) { x.beginPath(); x.moveTo(c + s * 12 - 4, 26); x.lineTo(c + s * 12 + 4, 32); x.moveTo(c + s * 12 + 4, 26); x.lineTo(c + s * 12 - 4, 32); x.stroke(); } poly(x, [c - 8, 46, c + 8, 46, c + 6, 50, c - 6, 50], '#3a0a0a'); return R.spr[key] = cv; } + const ox = look * 4; ell(x, c - 9, 29, 5, 3.4, '#f4f0e8'); ell(x, c + 9, 29, 5, 3.4, '#f4f0e8'); ell(x, c - 9 + ox, 29, 2.3, 2.3, '#2a4a7a'); ell(x, c + 9 + ox, 29, 2.3, 2.3, '#2a4a7a'); + x.strokeStyle = '#5a3018'; x.lineWidth = 2.5; x.beginPath(); x.moveTo(c - 15, mode === 'ouch' ? 20 : 23); x.lineTo(c - 4, 24); x.moveTo(c + 15, mode === 'ouch' ? 20 : 23); x.lineTo(c + 4, 24); x.stroke(); + if (mode === 'ouch') ell(x, c, 46, 7, 6, '#3a0a0a'); else if (mode === 'grin') { poly(x, [c - 12, 42, c + 12, 42, c + 8, 50, c - 8, 50], '#f0ece0', '#3a0a0a'); } else { x.beginPath(); x.moveTo(c - 9, 46 + level * 0.4); x.quadraticCurveTo(c, 44 - level, c + 9, 46 + level * 0.4); x.stroke(); } + return R.spr[key] = cv; + } + function digits(c, text, x, y, size, color) { // segment-style status bar numerals (original glyphs) + const SEG = { 0: 'abcdef', 1: 'bc', 2: 'abdeg', 3: 'abcdg', 4: 'bcfg', 5: 'acdfg', 6: 'acdefg', 7: 'abc', 8: 'abcdefg', 9: 'abcdfg', '%': '' }; + const w = size * 0.55, t = Math.max(2, size * 0.14); c.fillStyle = color; + for (const ch of String(text)) { + if (ch === '%') { c.fillRect(x, y + size * 0.05, t, t); c.fillRect(x + w - t, y + size - t * 1.2, t, t); c.save(); c.translate(x + w / 2, y + size / 2); c.rotate(0.6); c.fillRect(-t / 3, -size / 2, t * 0.7, size); c.restore(); x += w + t * 1.4; continue; } + const s = SEG[ch] || ''; const r = (a, b, ww, hh) => c.fillRect(x + a, y + b, ww, hh); + if (s.includes('a')) r(t * 0.5, 0, w - t, t); if (s.includes('g')) r(t * 0.5, size / 2 - t / 2, w - t, t); if (s.includes('d')) r(t * 0.5, size - t, w - t, t); + if (s.includes('f')) r(0, t * 0.5, t, size / 2 - t * 0.5); if (s.includes('b')) r(w - t, t * 0.5, t, size / 2 - t * 0.5); if (s.includes('e')) r(0, size / 2, t, size / 2 - t * 0.5); if (s.includes('c')) r(w - t, size / 2, t, size / 2 - t * 0.5); + x += w + t * 1.4; + } + } + function statusBack() { + if (R.bar) return R.bar; const cv = canvas(W, 70), x = cv.getContext('2d'); + const img = x.createImageData(W, 70), d = new Uint32Array(img.data.buffer); + for (let y = 0; y < 70; y++) for (let i = 0; i < W; i++) { const n = fbm(i / 6, y / 6, 151, 64, 3); d[y * W + i] = pack(78 + n * 40 | 0, 74 + n * 36 | 0, 66 + n * 30 | 0); } + x.putImageData(img, 0, 0); + const box = (x0, w, label) => { x.fillStyle = 'rgba(0,0,0,.35)'; x.fillRect(x0 + 3, 5, w - 6, 60); x.strokeStyle = '#2a2622'; x.lineWidth = 2; x.strokeRect(x0 + 3, 5, w - 6, 60); x.strokeStyle = 'rgba(255,255,255,.12)'; x.strokeRect(x0 + 5, 7, w - 10, 56); x.fillStyle = '#d8d0c0'; x.font = 'bold 11px monospace'; x.textAlign = 'center'; x.fillText(label, x0 + w / 2, 62); }; + box(0, 120, 'AMMO'); box(120, 150, 'HEALTH'); box(270, 110, 'ARMS'); box(380, 94, ''); box(474, 150, 'ARMOR'); box(624, 230, ''); + x.strokeStyle = '#1a1612'; x.lineWidth = 3; x.strokeRect(1, 1, W - 2, 68); return R.bar = cv; + } + // ---------- frame ---------- + function build(c) { + const T = buildTextures(), img = c.createImageData(W, H); + R = { T, img, buf: new Uint32Array(img.data.buffer), z: new Float32Array(W), sky: { red: buildSky('red'), dusk: buildSky('dusk') }, spr: {}, maps: {}, pre: {}, fd: new Float32Array(H), cd: new Float32Array(H), fl: Array.from({ length: 5 }, () => new Uint8Array(H)), cl: Array.from({ length: 5 }, () => new Uint8Array(H)) }; + } + const WALLTEX = { '#': 'stone', P: 'marble', M: 'metal', L: 'lights', R: 'rock', T: 'tech', D: 'door' }; + function mapTables(key) { + if (R.maps[key]) return R.maps[key]; + const m = M.maps[key], wall = [], flat = new Uint8Array(m.w * m.h), sky = new Uint8Array(m.w * m.h), wt = []; + for (let y = 0; y < m.h; y++) for (let x = 0; x < m.w; x++) { const ch = m.rows[y][x], i = y * m.w + x; wt[i] = WALLTEX[ch] ? R.T[WALLTEX[ch]] : null; flat[i] = ch === 'n' ? 3 : ch === 'x' ? 2 : ch === ',' ? 1 : 0; sky[i] = ch === ',' || ch === 'n' && key !== 'barons' ? 1 : 0; } + if (key === 'barons') for (let i = 0; i < flat.length; i++) if (m.rows[Math.floor(i / m.w)][i % m.w] === 'n') sky[i] = 1; + const cls = new Uint8Array(m.w * m.h), flick = new Uint8Array(m.w * m.h); + for (let y = 0; y < m.h; y++) for (let x = 0; x < m.w; x++) { + const i = y * m.w + x; if (wt[i]) { cls[i] = 1; continue; } + let lit = 0, walls = 0; for (let yy = -1; yy <= 1; yy++) for (let xx = -1; xx <= 1; xx++) { const ch = (m.rows[y + yy] || '')[x + xx]; if (ch === 'L') lit++; if (WALLTEX[ch]) walls++; } + cls[i] = lit ? 3 : sky[i] ? 2 : walls >= 4 ? 0 : 1; if (lit && h2(x, y, 171) < 0.35) flick[i] = 1; + } + return R.maps[key] = { m, wt, flat, sky, wall, cls, flick }; + } + const lightIndex = (light, dist, extra) => { const b = light / 255 * (0.32 + 0.78 * Math.exp(-dist / 620)) + extra * 0.09; return Math.max(0, Math.min(LV - 1, Math.round((1 - Math.min(1, b)) * (LV - 1)))); }; + M.renderStatus = () => ({ ready: true, error: null, kind: 'perspective', renderer: 'software-raycast' }); + M.draw = function (g, c) { + if (!R) build(c); + // Precache per arena + loadout (the loadout changes with the tier); sprite() memoises, so repeats are cheap. + const preKey = g.key + ':' + g.player.arms.join(','); + if (!R.pre[preKey]) { R.pre[preKey] = 1; for (const kind of new Set(g.bosses.map(b => b.kind))) for (const seq of Object.values(M.seq[kind])) for (const fr of seq.f) sprite(kind, fr[1]); if (g.fires) for (let f = 0; f < 8; f++) sprite('hellfire', f); for (let f = 0; f < 3; f++) { sprite('troopshot', f % 2); sprite('troopshotX', f); } for (const k of ['rocket', 'fireball', 'puff', 'blood']) for (let f = 0; f < 4; f++) if (!(k === 'rocket' && f) && !(k === 'blood' && f > 2) && !(k === 'fireball' && f > 1)) sprite(k, f); for (let f = 0; f < 3; f++) { sprite('blast', f); sprite('fireballX', f); } const combos = { shotgun: ['A', 'B', 'C', 'D', 'AA', 'AB'], rocket: ['A', 'B', 'BA', 'BB', 'BC', 'BD'], chaingun: ['A', 'B', 'AA', 'AB', 'BA', 'BB'] }; + for (const w of g.player.arms || []) for (const cmb of combos[w]) weaponCanvas(w, cmb[0], cmb[1] || null); + for (let l = 0; l < 5; l++) for (const lk of [-1, 0, 1]) for (const md of ['idle', 'ouch', 'grin', 'dead']) faceCanvas(l, lk, md); + for (let f = 0; f < 10; f++) sprite('tfog', f); } + const p = g.player, tb = mapTables(g.key), m = tb.m, mw = m.w, mh = m.h, buf = R.buf, Z = R.z, T = R.T, tic = M.ticOf(g.t); // original-tic clock for cosmetic cycles + const speed2 = p.vx * p.vx + p.vy * p.vy, bob = Math.min(16, speed2 / 4), vz = (p.hp > 0 ? 41 + bob / 2 * Math.sin(TAU * tic / 20) : 10) + (p.z || 0); + const ca = Math.cos(p.a), sa = Math.sin(p.a), px = p.x, py = p.y, extra = p.extralight || 0, light = m.light, sky = R.sky[m.sky]; + const flickOn = h2(tic >> 2, 3, 177) > 0.22, LIGHTS = [light - 40, light, light + 22, light + 44, flickOn ? light + 44 : light - 10]; + for (let y = 0; y < H; y++) { const dy = y + 0.5 - HALF; if (dy > 0) { R.fd[y] = vz * F / dy; for (let k = 0; k < 5; k++) R.fl[k][y] = lightIndex(LIGHTS[k], R.fd[y], extra); } else { R.cd[y] = (128 - vz) * F / -dy; for (let k = 0; k < 5; k++) R.cl[k][y] = lightIndex(LIGHTS[k], R.cd[y], extra); } } + const cellCls = i => tb.flick[i] ? 4 : tb.cls[i]; + const flats = [T.floor, T.dirt, T.blood, T.nukage[(tic >> 3) & 3]], ceil = T.ceil; + for (let x = 0; x < W; x++) { + const cx = (x + 0.5 - W / 2) / F, rdx = ca - sa * cx, rdy = sa + ca * cx; + let mx = Math.floor(px / 64), my = Math.floor(py / 64); + const ddx = Math.abs(64 / (rdx || 1e-9)), ddy = Math.abs(64 / (rdy || 1e-9)), sx = rdx < 0 ? -1 : 1, sy = rdy < 0 ? -1 : 1; + let tx = (rdx < 0 ? px - mx * 64 : (mx + 1) * 64 - px) / Math.abs(rdx || 1e-9), ty = (rdy < 0 ? py - my * 64 : (my + 1) * 64 - py) / Math.abs(rdy || 1e-9), side = 0, perp = 4000, tex = null, front = my * mw + mx; + for (let i = 0; i < 96; i++) { + if (mx >= 0 && my >= 0 && mx < mw && my < mh) front = my * mw + mx; + if (tx < ty) { perp = tx; tx += ddx; mx += sx; side = 0; } else { perp = ty; ty += ddy; my += sy; side = 1; } + if (mx < 0 || my < 0 || mx >= mw || my >= mh) { tex = T.stone; break; } + const w = tb.wt[my * mw + mx]; if (w) { tex = w; break; } + } + if (perp < 1) perp = 1; + Z[x] = perp; + let u = side === 0 ? py + perp * rdy : px + perp * rdx; u = ((u % 64) + 64) % 64 | 0; if ((side === 0 && rdx < 0) || (side === 1 && rdy > 0)) u = 63 - u; + const top = HALF - (128 - vz) * F / perp, bot = HALF + vz * F / perp, y0 = Math.max(0, Math.ceil(top - 0.5)), y1 = Math.min(H, Math.ceil(bot - 0.5)); + const lv = Math.min(LV - 1, lightIndex(LIGHTS[cellCls(front)] === undefined ? light : LIGHTS[cellCls(front)], perp, extra) + (side ? 1 : 0)), tab = tex.tab, base = lv * tex.n, step = perp / F; + let v = (y0 + 0.5 - top) * step; + for (let y = y0; y < y1; y++) { buf[y * W + x] = tab[base + ((v | 0) & 127) * 64 + u]; v += step; } + const scol = ((((p.a + Math.atan(cx)) / TAU) * 1024 % 1024) + 1024) % 1024 | 0; + for (let y = 0; y < y0; y++) { + const d = R.cd[y], wx = px + d * rdx, wy = py + d * rdy, ci = ((wy / 64) | 0) * mw + ((wx / 64) | 0); + buf[y * W + x] = tb.sky[ci] ? sky[y * 1024 + scol] : ceil.tab[R.cl[tb.flick[ci] ? 4 : tb.cls[ci]][y] * 4096 + (((wy | 0) & 63) << 6) + ((wx | 0) & 63)]; + } + for (let y = y1; y < H; y++) { + const d = R.fd[y], wx = px + d * rdx, wy = py + d * rdy, ci = ((wy / 64) | 0) * mw + ((wx / 64) | 0), ft = flats[tb.flat[ci] || 0]; + buf[y * W + x] = ft.tab[R.fl[tb.flick[ci] ? 4 : tb.cls[ci]][y] * 4096 + (((wy | 0) & 63) << 6) + ((wx | 0) & 63)]; + } + } + // sprites (things), far to near, clipped by the wall depth buffer + const list = []; + const add = (o, kind, frame, w, h, z0, bright, flash) => { const dx = o.x - px, dy = o.y - py, fz = dx * ca + dy * sa; if (fz < (h < 40 ? 36 : 6)) return; list.push({ fz, sx: -dx * sa + dy * ca, kind, frame, w, h, z0, bright, flash, cell: Math.max(0, Math.min(mh - 1, (o.y / 64) | 0)) * mw + Math.max(0, Math.min(mw - 1, (o.x / 64) | 0)) }); }; + for (const it of g.pickups) if (!it.taken) add(it, it.type, 'A', 32, 28, 0, false); + for (const b of g.bosses) { const fr = M.frameOf(b), [w, h] = SPR[b.kind]; add(b, b.kind, fr[1], w, h, 0, fr[3] || b.flash > 0 && b.hp > 0, b.flash > 0 && b.hp > 0); } + for (const f of g.fx) { if (f.kind === 'tfog') { add(f, 'tfog', f.frame, 56, 56, 0, true); continue; } if ((f.x - px) * ca + (f.y - py) * sa < 64) continue; add(f, f.kind, f.frame, 12, 12, f.z - 6, f.kind === 'puff' && f.frame === 0); } + for (const fr of g.fires || []) add(fr, 'hellfire', 'ABCDEFGH'.indexOf(M.fire[Math.min(fr.i, M.fire.length - 1)][1]), 40, 60, 0, true); + for (const q of g.projectiles) add(q, q.kind, q.kind === 'fireball' || q.kind === 'troopshot' || q.kind === 'fatshot' || q.kind === 'tracer' ? q.i : 0, q.kind === 'rocket' ? 28 : 28, 28, 22, true); + for (const bl of g.blasts) { if (bl.kind === 'rocket') add(bl, 'blast', Math.min(2, bl.i), 60, 60, 4, true); else add(bl, bl.kind === 'troopshot' || bl.kind === 'fatshot' || bl.kind === 'tracer' ? 'troopshotX' : 'fireballX', Math.min(2, bl.i), 40, 40, 14, true); } + list.sort((a, b) => b.fz - a.fz); + for (const s of list) { + const spr = sprite(s.kind, s.frame), scale = F / s.fz, wpx = s.w * scale, hpx = s.h * scale, cxs = W / 2 + s.sx * scale, left = cxs - wpx / 2, topy = HALF - (s.z0 + s.h - vz) * scale; + const x0 = Math.max(0, Math.ceil(left - 0.5)), x1 = Math.min(W, Math.ceil(left + wpx - 0.5)), y0 = Math.max(0, Math.ceil(topy - 0.5)), y1 = Math.min(H, Math.ceil(topy + hpx - 0.5)); + if (x0 >= x1 || y0 >= y1) continue; + const k = s.bright ? 1 : SHADE[lightIndex(LIGHTS[cellCls(s.cell)] || light, s.fz, extra)], fl = s.flash ? 60 : 0, sw = spr.w, sh = spr.h, pxs = spr.px, ux = sw / wpx, vy = sh / hpx; + for (let x = x0; x < x1; x++) { + if (Z[x] <= s.fz) continue; + const tcol = Math.min(sw - 1, ((x + 0.5 - left) * ux) | 0); let v = (y0 + 0.5 - topy) * vy; + for (let y = y0; y < y1; y++, v += vy) { + const cpx = pxs[Math.min(sh - 1, v | 0) * sw + tcol]; if (!cpx) continue; + buf[y * W + x] = k === 1 && !fl ? cpx : pack(((cpx & 255) * k + fl) | 0, (((cpx >>> 8) & 255) * k + fl) | 0, (((cpx >>> 16) & 255) * k + fl) | 0); + } + } + } + c.putImageData(R.img, 0, 0); + // first-person weapon (psprite): lowered/raised position or ready bob + const st = p.wst ? M.wstates[p.wst] : null; + if (st && p.hp > 0) { + const lowering = /DOWN|UP/.test(p.wst), wy = lowering ? p.wy : (p.sy || 32), wx = lowering ? 0 : ((p.sx || 1) - 1); + const fst = p.fst && p.fst !== 'LIGHTDONE' ? M.wstates[p.fst][1] : null, cv = weaponCanvas(p.weapon, st[1], fst); + c.drawImage(cv, W / 2 - 150 + wx * 2.4, H - 250 + (wy - 32) * 2.6, 300, 260); + } + // palettes: damage red, pickup gold + const red = (p.damagecount + 7) >> 3; if (red) { c.fillStyle = 'rgba(255,0,0,' + Math.min(0.62, red * 0.075) + ')'; c.fillRect(0, 0, W, H); } + if (p.hp <= 0) { c.fillStyle = 'rgba(140,0,0,.45)'; c.fillRect(0, 0, W, H); } + const gold = (p.bonuscount + 7) >> 3; if (gold) { c.fillStyle = 'rgba(255,220,90,' + gold * 0.06 + ')'; c.fillRect(0, 0, W, H); } + // HUD overlay: boss names and health, timer, skill + const name = { cyberdemon: 'Rocket Colossus', baron: 'Green-Flame Horned Fiends', spider: 'Four-Legged Gun Platform', vile: 'Flame-Caller Sorcerer', fatso: 'Twin-Cannon Brute', undead: 'Shoulder-Cannon Skeleton' }; + const hudB = g.bosses.filter(M.isBoss), minions = g.bosses.filter(b => !M.isBoss(b)), hudRows = hudB.length + (minions.length ? 1 : 0); + c.fillStyle = 'rgba(10,6,4,.55)'; c.fillRect(10, 8, 378, 20 + hudRows * 18); c.font = 'bold 13px monospace'; c.textAlign = 'left'; + if (minions.length) { const y = 14 + hudB.length * 18, up = minions.filter(b => b.hp > 0).length; c.fillStyle = '#d8b890'; c.font = 'bold 12px monospace'; c.fillText('Fire Imp ' + up + ' / ' + minions.length + ' alive', 18, y + 11); c.font = 'bold 13px monospace'; } + hudB.forEach((b, i) => { const y = 14 + i * 18; c.fillStyle = '#f0d0a0'; c.fillText(name[b.kind] + (hudB.length > 1 ? ' ' + (i + 1) : ''), 18, y + 11); c.fillStyle = '#2a0a06'; c.fillRect(170, y + 2, 160, 10); c.fillStyle = b.hp > 0 ? (b.mode === 'pain' ? '#ffb040' : '#d02a1a') : '#4a2a20'; c.fillRect(170, y + 2, 160 * b.hp / b.maxHp, 10); c.fillStyle = '#fff'; c.font = '10px monospace'; c.fillText(String(b.hp), 300, y + 11); c.fillStyle = b.mode === 'attack' ? '#ff9060' : b.mode === 'pain' ? '#ffd060' : '#a89880'; c.fillText(b.hp <= 0 ? 'DEAD' : { see: 'CHASE', attack: 'ATTACK', pain: 'PAIN', spawn: 'IDLE', death: 'DYING' }[b.mode], 336, y + 11); c.font = 'bold 13px monospace'; }); + c.fillStyle = '#c8b090'; c.font = '11px monospace'; c.fillText('BOSS ' + hudB.reduce((n, b) => n + Math.max(0, b.hp), 0) + ' / ' + g.maxBoss, 18, 22 + hudRows * 18); // g may be a plain state snapshot: no methods + c.textAlign = 'right'; c.fillStyle = 'rgba(10,6,4,.55)'; c.fillRect(W - 300, 8, 290, 40); c.fillStyle = '#f0e0c0'; c.font = 'bold 16px monospace'; + const secs = g.t / M.hz, left = Math.max(0, M.maxSeconds - secs); c.fillText((Math.floor(secs / 60)) + ':' + String(Math.floor(secs % 60)).padStart(2, '0') + '.' + Math.floor(secs * 10 % 10) + ' / ' + Math.floor(left) + 's', W - 18, 26); + // tier / original skill / native clock (doom-arena@10 simulates at 60 Hz, original timing TICRATE 35) + const tierName = g.tier ? g.tier.toUpperCase() : 'd=' + g.d, hz = M.hz + 'Hz'; + c.font = 'bold 12px monospace'; c.fillStyle = '#ffd070'; c.fillText(hz, W - 18, 42); const hzw = c.measureText(hz).width; + c.font = '11px monospace'; c.fillStyle = '#c8b090'; c.fillText(tierName + ' · ' + M.skills[g.skill] + (g.fast && g.skill < 4 ? ' Fast' : '') + ' · ', W - 18 - hzw, 42); c.textAlign = 'left'; + // Crosshair (BossBench addition, vanilla has none): dark outline, white line, centre dot, readable on any background. + for (const [lw, col] of [[4, 'rgba(0,0,0,.75)'], [2, '#ffffff']]) { c.strokeStyle = col; c.lineWidth = lw; c.beginPath(); c.moveTo(W / 2 - 12, HALF); c.lineTo(W / 2 - 5, HALF); c.moveTo(W / 2 + 5, HALF); c.lineTo(W / 2 + 12, HALF); c.moveTo(W / 2, HALF - 12); c.lineTo(W / 2, HALF - 5); c.moveTo(W / 2, HALF + 5); c.lineTo(W / 2, HALF + 12); c.stroke(); } + c.fillStyle = 'rgba(0,0,0,.75)'; c.fillRect(W / 2 - 2, HALF - 2, 4, 4); c.fillStyle = '#ffffff'; c.fillRect(W / 2 - 1, HALF - 1, 2, 2); + if (g.outcome) { c.fillStyle = 'rgba(0,0,0,.5)'; c.fillRect(0, HALF - 34, W, 60); c.textAlign = 'center'; c.font = 'bold 30px Georgia, serif'; c.fillStyle = g.outcome === 'win' ? '#ffd070' : '#ff6050'; c.fillText({ win: 'BOSS DEFEATED', loss: 'YOU DIED', timeout: 'TIME UP' }[g.outcome] + ' ' + secs.toFixed(1) + 's', W / 2, HALF + 6); c.textAlign = 'left'; } + // status bar + c.drawImage(statusBack(), 0, H); + const ammo = p[M.winfo[p.weapon].ammo], arms = p.arms; digits(c, ammo, 24, H + 12, 36, '#d02a1a'); digits(c, Math.max(0, p.hp) + '%', 140, H + 12, 36, '#d02a1a'); digits(c, p.armor + '%', 492, H + 12, 36, p.armorType === 1 ? '#40c040' : '#d02a1a'); + c.font = 'bold 18px monospace'; [['2', true], ['3', arms.includes('shotgun')], ['4', arms.includes('chaingun')], ['5', arms.includes('rocket')], ['6', false], ['7', false]].forEach(([n, has], i) => { const cur = (n === '3' && p.weapon === 'shotgun') || (n === '4' && p.weapon === 'chaingun') || (n === '5' && p.weapon === 'rocket'); c.fillStyle = cur ? '#ffe060' : has ? '#d8d0c0' : '#6a645a'; c.fillText(n, 290 + (i % 3) * 30, H + 28 + Math.floor(i / 3) * 22); }); + const hl = p.hp <= 0 ? 4 : Math.min(4, Math.floor((100 - Math.max(0, Math.min(100, p.hp))) / 20)), mode = p.hp <= 0 ? 'dead' : p.damagecount > 20 ? 'ouch' : p.bonuscount ? 'grin' : 'idle', look = mode === 'idle' ? [0, -1, 0, 1][Math.floor(M.ticOf(g.t) / 18) % 4] : 0; + c.drawImage(faceCanvas(hl, look, mode), 397, H + 5, 60, 62); + // ammo panel: one row per owned ammo type, current weapon highlighted + const rows = [['bullets', 'BULL'], ['shells', 'SHEL'], ['rockets', 'RCKT']].filter(([a]) => arms.some(w => M.winfo[w].ammo === a)), cur = M.winfo[p.weapon].ammo; + c.font = 'bold 12px monospace'; rows.forEach(([a, n], i) => { const y = H + 18 + i * 14; c.fillStyle = '#e8d8b0'; c.fillText(n, 640, y); c.fillStyle = a === cur ? '#ffe060' : '#e8d8b0'; c.fillText(String(p[a]).padStart(3, ' ') + ' / ' + (p.max ? p.max[a] : 100), 690, y); }); + c.fillStyle = '#b8a888'; c.font = '10px monospace'; c.fillText(M.maps[g.key].title, 640, H + 63); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/doom_remake/game.js b/environments/games/web/games/doom_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..9a9e3f0b771f69f5f83c681e3f2bfb34d0da96fe --- /dev/null +++ b/environments/games/web/games/doom_remake/game.js @@ -0,0 +1,1099 @@ +/* DOOM (1993) / DOOM II boss arena, rules doom-arena@11 (60 Hz simulation, original 35 Hz timing kept in seconds, DOOM map units). + Independent JavaScript re-implementation of DOOM game rules read from id Software's linuxdoom-1.10 source + (GPL-2.0, commit a77dfb96cb91780ca334d0d4cfd86957558007e0): state tables and mobjinfo (info.c), A_Chase / + P_NewChaseDir / P_CheckMissileRange / boss attacks (p_enemy.c), P_DamageMobj (p_inter.c), PIT_CheckThing / + P_RadiusAttack / P_LineAttack (p_map.c), weapon psprites (p_pspr.c), thrust/friction/turning (p_user.c, + p_mobj.c, g_game.c), skill / -fast / -respawn rules (g_game.c G_InitNew, d_main.c). No engine code is copied; + RNDTABLE is the 256-byte P_Random table of m_random.c, kept because the deterministic sequence is a rule. + Arenas are original (not E1M8/E2M8/E3M8/E4M8) and art is procedural. Public tiers (2026-11-02): each tier is an + original skill setting plus a BossBench boss-health table (an extension: vanilla never scales spawnhealth). + */ +(function (root) { + 'use strict'; + const N = root.NativeBench, PI = Math.PI, TAU = PI * 2, Q = PI / 4; + const BAM = TAU / 4294967296; + const RNDTABLE = '00086ddcdef1956b4bf8fe8c10424a15d32f50f29a1bcd80a1594d245f6e5530d48cd3f9164fc8321cbc348cca7844913e46b8be5bc598e0956819b2fcb6cab68dc50451b5f2912a27e39cc6e1c1db5d7aaff900af8f46ef2ef6a335a36da88702eb195c14918a4d45a64eb0add4a6715ea12932ef316fa4463c0225ab4b889c0b382a928ae549924d3d62c4876a3fc5c35660cb7165aaf7b57150fa6c07ffed81e24f6b70a667f118dfef78c63a3c528003b8428fe091e051cea32d3f5aa8723b219f5f1c8b7b627dc40f46c2fd360e6de24711a15dba57f48a14347bfb1a24112e34e7e84c1fdd5425d8a5d46ac5f2622b27affe91be5476debb8878a3ecf9'.match(/../g).map(h => parseInt(h, 16)); + // Clock (doom-arena@10, 2026-11-06 user decision "all four games moved to 60 Hz"): the simulation ticks at HZ = 60 and keeps the original + // behaviour in seconds. Two kinds of original quantities: + // - discrete tic logic (mobj state tables and their actions, psprites, missile / blast / fire / effect frames, the + // palette counters, gametic tests): accumulated in time. Original tic k ends at (k+1)/35 s; it runs in the HZ tick + // whose end is the first at or after that instant, so its result is never shown early and is at most 1/60 s late. + // 7 of every 12 ticks carry one, no drift, and each 2-tick hold window of a packet holds the same number of + // original tics as at 35 Hz (1,1,1,1,1,2). Every P_Random roll of tic logic keeps its original rate: DOOM samples + // nothing per tick, so no 1-(1-p)^k rescaling was needed; + // - continuous motion (player thrust / friction / turning, momentum, knockback, missile flight, z): every HZ tick. + // Velocities stay in map units per original tic (V); a tick moves V*R (R = 35/HZ), friction is FRICTION^R, thrust and + // knockback are scaled by (1-FRICTION^R)/(1-FRICTION) so the run speed per second and the knockback distance are the + // original ones, gravity is R per tick (in V units). + // At HZ = 35 every expression reduces to doom-arena@9 exactly (checked by replaying the @9 regression references). + const HZ = 60, OHZ = 35, GCD = (a, b) => b ? GCD(b, a % b) : a, TIC = HZ / GCD(OHZ, HZ), STEP = OHZ / GCD(OHZ, HZ), R = STEP / TIC; + const TT = n => Math.round(n * TIC / STEP); // original tics -> HZ ticks (rounded; used for counters and look-ahead lengths) + // p_mobj.c / p_local.h / g_game.c constants (fixed point converted to map units, per original tic). + const FRICTION = 0xe800 / 65536, STOPSPEED = 0x1000 / 65536, MAXMOVE = 30, THRUST = 2048 / 65536; + const FORWARD = [25, 50], SIDE = [24, 40], TURN = [640, 1280, 320], SLOWTURNTICS = 6, MOUSE_RAD = 0.0025; + const FRICTION_T = FRICTION ** R, GAIN = (1 - FRICTION_T) / (1 - FRICTION), THRUST_T = THRUST * GAIN, KNOCK_T = GAIN / R; + const SLOWTURN_T = TT(SLOWTURNTICS), MISSILE_TTL = TT(700), PKT = HZ / 5; + if (HZ < OHZ) throw Error('at most one original tic per tick'); + const ticsBefore = t => Math.floor(t * STEP / TIC); // original tics completed when tick t starts (= index of the tic tick t runs) + const FATSPREAD = Math.PI / 16, TRACEANGLE = 0xc000000 * 2 * Math.PI / 4294967296; // 16.875 deg + const MELEERANGE = 64, MISSILERANGE = 2048, BASETHRESHOLD = 100, WEAPONTOP = 32, WEAPONBOTTOM = 128; + const XSPEED = [1, 47000 / 65536, 0, -47000 / 65536, -1, -47000 / 65536, 0, 47000 / 65536]; + const YSPEED = [0, 47000 / 65536, 1, 47000 / 65536, 0, -47000 / 65536, -1, -47000 / 65536]; + const NODIR = 8, OPPOSITE = [4, 5, 6, 7, 0, 1, 2, 3, 8], DIAGS = [3, 1, 5, 7]; + const SK_BABY = 0, SK_EASY = 1, SK_MEDIUM = 2, SK_HARD = 3, SK_NIGHTMARE = 4; + const SKILLS = ['Tier 1 · half damage', 'Tier 2', 'Tier 3 · Standard', 'Tier 4', 'Tier 5 · resurrecting enemies']; // neutral names of the five original skills, in order + // Public tiers = an original skill setting + a BossBench boss-health table; every tier fights + // with the same case arsenal (2026-11-03 user decision: "same fight, paced differently", no pistol-start variant). + // easy = I'm too young to die (half damage to the player, doubled ammo pickups, extra easy-flag supplies) + // normal = Hurt me plenty + // hard = Ultra-Violence with -fast (d_main.c fastparm: A_Chase attack gating off, fast baron fireballs) + // Continuous d keeps the whole original ladder: ITYTD < .25 <= HNTR < .45 <= HMP < .7 <= UV < .8 <= UV -fast + // < .95 <= Nightmare. Boss spawnhealth (vanilla: cyber 4000, spider 3000, baron 1000) is a BossBench extension + // calibrated to the script windows (easy 20-30 s, normal 45-90 s, hard 150-240 s): flat below easy, linear between + // the three tier anchors, flat above hard. Health is continuous in d; the skill switches at .25/.45/.7/.95 and + // -fast at .8 are original-mode steps, so fight length is not continuous there. + const TIERS = { easy: 0.15, normal: 0.5, hard: 0.85 }; + const HEALTH_D = [TIERS.easy, TIERS.normal, TIERS.hard]; + const HEALTH = { cyberdemon: [2600, 6800, 15500], spider: [1500, 4200, 7000], baron: [800, 1900, 4400], vile: [2500, 7000, 22000], fatso: [1650, 4400, 13000], undead: [700, 2700, 7000] }; + // mobjinfo (info.c): spawnhealth, radius, height, speed, mass, painchance, reactiontime. + const KINDS = { + cyberdemon: { hp: 4000, r: 40, height: 110, speed: 16, mass: 1000, pain: 20, reaction: 8, melee: false, name: 'Rocket Colossus' }, + baron: { hp: 1000, r: 24, height: 64, speed: 8, mass: 1000, pain: 50, reaction: 8, melee: true, name: 'Green-Flame Horned Fiends' }, + spider: { hp: 3000, r: 128, height: 100, speed: 12, mass: 1000, pain: 40, reaction: 8, melee: false, name: 'Four-Legged Gun Platform' }, + vile: { hp: 700, r: 20, height: 56, speed: 15, mass: 500, pain: 10, reaction: 8, melee: false, name: 'Flame-Caller Sorcerer' }, + fatso: { hp: 600, r: 48, height: 64, speed: 8, mass: 1000, pain: 80, reaction: 8, melee: false, name: 'Twin-Cannon Brute' }, + undead: { hp: 300, r: 20, height: 56, speed: 10, mass: 500, pain: 100, reaction: 8, melee: true, name: 'Shoulder-Cannon Skeleton' }, + // Minion (not a boss: never counted for the win, the health bar or BossBench health scaling). raise = has S_TROO_RAISE1. + imp: { hp: 60, r: 20, height: 56, speed: 8, mass: 100, pain: 200, reaction: 8, melee: true, raise: true, name: 'Fire Imp' }, + }; + // State sequences: [tics, frame letter, action, fullbright]. A sequence's next is a mode name or [mode, offset]. + const F = (spec) => spec.split(' ').map(s => { const [t, f, a] = s.split(':'); return [Number(t), f.replace('*', ''), a || null, f.includes('*')]; }); + const SEQ = { + cyberdemon: { + spawn: { f: F('10:A:Look 10:B:Look'), next: 'spawn' }, + see: { f: F('3:A:Hoof 3:A:Chase 3:B:Chase 3:B:Chase 3:C:Chase 3:C:Chase 3:D:Metal 3:D:Chase'), next: 'see' }, + attack: { f: F('6:E:FaceTarget 12:F:CyberAttack 12:E:FaceTarget 12:F:CyberAttack 12:E:FaceTarget 12:F:CyberAttack'), next: 'see' }, + pain: { f: F('10:G:Pain'), next: 'see' }, + death: { f: F('10:H 10:I:Scream 10:J 10:K 10:L 10:M:Fall 10:N 10:O 30:P -1:P:BossDeath'), next: null }, + }, + baron: { + spawn: { f: F('10:A:Look 10:B:Look'), next: 'spawn' }, + see: { f: F('3:A:Chase 3:A:Chase 3:B:Chase 3:B:Chase 3:C:Chase 3:C:Chase 3:D:Chase 3:D:Chase'), next: 'see' }, + attack: { f: F('8:E:FaceTarget 8:F:FaceTarget 8:G:BruisAttack'), next: 'see' }, + pain: { f: F('2:H 2:H:Pain'), next: 'see' }, + death: { f: F('8:I 8:J:Scream 8:K 8:L:Fall 8:M 8:N -1:O:BossDeath'), next: null }, + }, + spider: { + spawn: { f: F('10:A:Look 10:B:Look'), next: 'spawn' }, + see: { f: F('3:A:Metal 3:A:Chase 3:B:Chase 3:B:Chase 3:C:Metal 3:C:Chase 3:D:Chase 3:D:Chase 3:E:Metal 3:E:Chase 3:F:Chase 3:F:Chase'), next: 'see' }, + attack: { f: F('20:A*:FaceTarget 4:G*:SPosAttack 4:H*:SPosAttack 1:H*:SpidRefire'), next: ['attack', 20] }, + pain: { f: F('3:I 3:I:Pain'), next: 'see' }, + death: { f: F('20:J:Scream 10:K:Fall 10:L 10:M 10:N 10:O 10:P 10:Q 10:R 30:S -1:S:BossDeath'), next: null }, + }, + // info.c S_VILE_*: the attack is one 94-tic sequence (A_VileTarget at +10, A_VileAttack at +66); ATK1 is a 0-tic state. + // DIE10 has no action in vanilla (MT_VILE ends no level); BossDeath there is the BossBench arena win rule. + vile: { + spawn: { f: F('10:A:Look 10:B:Look'), next: 'spawn' }, + see: { f: F('2:A:VileChase 2:A:VileChase 2:B:VileChase 2:B:VileChase 2:C:VileChase 2:C:VileChase 2:D:VileChase 2:D:VileChase 2:E:VileChase 2:E:VileChase 2:F:VileChase 2:F:VileChase'), next: 'see' }, + attack: { f: F('0:G*:VileStart 10:G*:FaceTarget 8:H*:VileTarget 8:I*:FaceTarget 8:J*:FaceTarget 8:K*:FaceTarget 8:L*:FaceTarget 8:M*:FaceTarget 8:N*:FaceTarget 8:O*:VileAttack 20:P*'), next: 'see' }, + heal: { f: F('10:a* 10:b* 10:c*'), next: 'see' }, // S_VILE_HEAL1-3 (vanilla frames [ \ ], named a / b / c here) + pain: { f: F('5:Q 5:Q:Pain'), next: 'see' }, + death: { f: F('7:Q 7:R:Scream 7:S:Fall 7:T 7:U 7:V 7:W 5:X 5:Y -1:Z:BossDeath'), next: null }, + }, + // info.c 498-533 S_FATT_*: 80-tic attack, three volleys at +20 / +40 / +60. DIE10 calls A_BossDeath in vanilla too (MAP07). + fatso: { + spawn: { f: F('15:A:Look 15:B:Look'), next: 'spawn' }, + see: { f: F('4:A:Chase 4:A:Chase 4:B:Chase 4:B:Chase 4:C:Chase 4:C:Chase 4:D:Chase 4:D:Chase 4:E:Chase 4:E:Chase 4:F:Chase 4:F:Chase'), next: 'see' }, + attack: { f: F('20:G:FatRaise 10:H*:FatAttack1 5:I:FaceTarget 5:G:FaceTarget 10:H*:FatAttack2 5:I:FaceTarget 5:G:FaceTarget 10:H*:FatAttack3 5:I:FaceTarget 5:G:FaceTarget'), next: 'see' }, + pain: { f: F('3:J 3:J:Pain'), next: 'see' }, + death: { f: F('6:K 6:L:Scream 6:M:Fall 6:N 6:O 6:P 6:Q 6:R 6:S -1:T:BossDeath'), next: null }, + }, + // info.c 457-492 S_SKEL_*: melee (FIST, 18 tics) and missile (MISS, 30 tics) are separate states. DIE6 has no action in + // vanilla; BossDeath there is the BossBench arena win rule (as for the Arch-Vile). + undead: { + spawn: { f: F('10:A:Look 10:B:Look'), next: 'spawn' }, + see: { f: F('2:A:Chase 2:A:Chase 2:B:Chase 2:B:Chase 2:C:Chase 2:C:Chase 2:D:Chase 2:D:Chase 2:E:Chase 2:E:Chase 2:F:Chase 2:F:Chase'), next: 'see' }, + melee: { f: F('0:G:FaceTarget 6:G:SkelWhoosh 6:H:FaceTarget 6:I:SkelFist'), next: 'see' }, + attack: { f: F('0:J*:FaceTarget 10:J*:FaceTarget 10:K:SkelMissile 10:K:FaceTarget'), next: 'see' }, + pain: { f: F('5:L 5:L:Pain'), next: 'see' }, + death: { f: F('7:L 7:M 7:N:Scream 7:O:Fall 7:P -1:Q:BossDeath'), next: null }, + }, + imp: { // info.c S_TROO_*: melee and missile share ATK1 (A_TroopAttack picks the claw in melee range) + spawn: { f: F('10:A:Look 10:B:Look'), next: 'spawn' }, + see: { f: F('3:A:Chase 3:A:Chase 3:B:Chase 3:B:Chase 3:C:Chase 3:C:Chase 3:D:Chase 3:D:Chase'), next: 'see' }, + attack: { f: F('8:E:FaceTarget 8:F:FaceTarget 6:G:TroopAttack'), next: 'see' }, + pain: { f: F('2:H 2:H:Pain'), next: 'see' }, + death: { f: F('8:I 8:J:Scream 6:K 6:L:Fall -1:M'), next: null }, + xdeath: { f: F('5:N 5:O:XScream 5:P 5:Q:Fall 5:R 5:S 5:T -1:U'), next: null }, + raise: { f: F('8:M 8:L 6:K 6:J 6:I'), next: 'see' }, + }, + }; + // MT_FIRE (S_FIRE1-30, 2 tics each, all fullbright; A_StartFire / A_FireCrackle only add a sound to A_Fire). + const FIRE = F('2:A* 2:B* 2:A* 2:B* 2:C* 2:B* 2:C* 2:B* 2:C* 2:D* 2:C* 2:D* 2:C* 2:D* 2:E* 2:D* 2:E* 2:D* 2:E* 2:F* 2:E* 2:F* 2:E* 2:F* 2:G* 2:H* 2:G* 2:H* 2:G* 2:H*'); + for (const kind of Object.values(SEQ)) for (const seq of Object.values(kind)) { + let t = 0; seq.starts = seq.f.map(fr => { const s = t; t += fr[0] < 0 ? Infinity : fr[0]; return s; }); seq.length = t; + } + // Missiles (MT_ROCKET, MT_BRUISERSHOT, MT_TROOPSHOT): speed (fast = G_InitNew -fast speed), radius, damage multiplier, flight and death frames. + const MISSILES = { + rocket: { speed: 20, r: 11, damage: 20, fly: F('1:A*'), death: F('8:B*:Explode 6:C* 4:D*') }, + fireball: { speed: 15, fast: 20, r: 6, damage: 8, fly: F('4:A* 4:B*'), death: F('6:C* 6:D* 6:E*') }, + troopshot: { speed: 10, fast: 20, r: 6, damage: 3, fly: F('4:A* 4:B*'), death: F('6:C* 6:D* 6:E*') }, // MT_TROOPSHOT + tracer: { speed: 10, r: 11, damage: 10, fly: F('2:A*:Tracer 2:B*:Tracer'), death: F('8:A* 6:B* 4:C*') }, // MT_TRACER: no A_Explode, -fast leaves it alone + fatshot: { speed: 20, r: 6, damage: 8, fly: F('4:A* 4:B*'), death: F('8:B* 6:C* 4:D*') }, // MT_FATSHOT: no A_Explode, -fast leaves it alone + }; + // Weapon psprite states (info.c S_SGUN*, S_CHAIN*, S_MISSILE*), weaponinfo ready/down/up/attack/flash. + const WSTATES = { + SGUN: [1, 'A', 'WeaponReady', 'SGUN'], SGUNDOWN: [1, 'A', 'Lower', 'SGUNDOWN'], SGUNUP: [1, 'A', 'Raise', 'SGUNUP'], + SGUN1: [3, 'A', null, 'SGUN2'], SGUN2: [7, 'A', 'FireShotgun', 'SGUN3'], SGUN3: [5, 'B', null, 'SGUN4'], SGUN4: [5, 'C', null, 'SGUN5'], + SGUN5: [4, 'D', null, 'SGUN6'], SGUN6: [5, 'C', null, 'SGUN7'], SGUN7: [5, 'B', null, 'SGUN8'], SGUN8: [3, 'A', null, 'SGUN9'], SGUN9: [7, 'A', 'ReFire', 'SGUN'], + SGUNFLASH1: [4, 'A', 'Light1', 'SGUNFLASH2'], SGUNFLASH2: [3, 'B', 'Light2', 'LIGHTDONE'], + MISSILE: [1, 'A', 'WeaponReady', 'MISSILE'], MISSILEDOWN: [1, 'A', 'Lower', 'MISSILEDOWN'], MISSILEUP: [1, 'A', 'Raise', 'MISSILEUP'], + MISSILE1: [8, 'B', 'GunFlash', 'MISSILE2'], MISSILE2: [12, 'B', 'FireMissile', 'MISSILE3'], MISSILE3: [0, 'B', 'ReFire', 'MISSILE'], + MISSILEFLASH1: [3, 'A', 'Light1', 'MISSILEFLASH2'], MISSILEFLASH2: [4, 'B', null, 'MISSILEFLASH3'], MISSILEFLASH3: [4, 'C', 'Light2', 'MISSILEFLASH4'], MISSILEFLASH4: [4, 'D', 'Light2', 'LIGHTDONE'], + CHAIN: [1, 'A', 'WeaponReady', 'CHAIN'], CHAINDOWN: [1, 'A', 'Lower', 'CHAINDOWN'], CHAINUP: [1, 'A', 'Raise', 'CHAINUP'], + CHAIN1: [4, 'A', 'FireCGun', 'CHAIN2'], CHAIN2: [4, 'B', 'FireCGun', 'CHAIN3'], CHAIN3: [0, 'B', 'ReFire', 'CHAIN'], + CHAINFLASH1: [5, 'A', 'Light1', 'LIGHTDONE'], CHAINFLASH2: [5, 'B', 'Light2', 'LIGHTDONE'], + LIGHTDONE: [0, 'A', 'Light0', null], + }; + const WINFO = { + shotgun: { ammo: 'shells', ready: 'SGUN', down: 'SGUNDOWN', up: 'SGUNUP', atk: 'SGUN1', flash: 'SGUNFLASH1', name: 'SHOTGUN' }, + chaingun: { ammo: 'bullets', ready: 'CHAIN', down: 'CHAINDOWN', up: 'CHAINUP', atk: 'CHAIN1', flash: 'CHAINFLASH1', name: 'CHAINGUN' }, + rocket: { ammo: 'rockets', ready: 'MISSILE', down: 'MISSILEDOWN', up: 'MISSILEUP', atk: 'MISSILE1', flash: 'MISSILEFLASH1', name: 'ROCKET L.' }, + }; + // ---------- Original arenas (64-unit cells). Characters: wall textures # (stone) P (marble pillar) M (metal) L (light panel) + // R (red rock) T (tech pillar) D (big door, decorative); floors . (flat ceiling) , (open sky) n (nukage) x (blood stone). + const SOLID = '#PMLRTD'; + function arena(w, h, fill, edge, ops) { + const g = Array.from({ length: h }, (_, y) => Array.from({ length: w }, (_, x) => (x === 0 || y === 0 || x === w - 1 || y === h - 1) ? edge : fill)); + const rect = (x0, y0, x1, y1, ch) => { for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) g[y][x] = ch; }; + ops(rect, g); return g.map(r => r.join('')); + } + const MAPS = { + barons: { + title: 'Four-pillar hall (original layout)', sky: 'red', light: 168, + rows: arena(24, 22, '.', '#', (rect, g) => { + for (const [x, y] of [[6, 7], [17, 7], [6, 13], [17, 13]]) rect(x, y, x, y + 1, 'P'); + for (const [x, y] of [[3, 3], [19, 3], [3, 17], [19, 17]]) rect(x, y, x + 1, y + 1, 'M'); + rect(10, 10, 13, 11, 'n'); rect(8, 8, 15, 13, ','); rect(10, 10, 13, 11, 'n'); + for (let x = 3; x < 21; x += 5) { g[0][x] = 'L'; g[21][x] = 'L'; } + for (let y = 4; y < 20; y += 5) { g[y][0] = 'L'; g[y][23] = 'L'; } + g[0][11] = g[0][12] = 'D'; + }), + player: [768, 1216, -PI / 2], bosses: [[576, 288], [960, 288]], arms: ['shotgun', 'chaingun'], + items: [['medikit', 160, 704, 'all'], ['medikit', 1376, 704, 'all'], ['bulletbox', 160, 1216, 'all'], ['shellbox', 1376, 1216, 'all'], + ['shellbox', 160, 448, 'all'], ['shellbox', 1376, 448, 'all'], ['bulletbox', 768, 1312, 'all'], + ['medikit', 768, 704, 'easy'], ['stimpack', 448, 1216, 'easy'], ['stimpack', 1088, 1216, 'easy'], ['greenarmor', 768, 1088, 'easy'], + ['stimpack', 768, 960, 'normal']], + }, + cyberdemon: { + title: 'Open-sky crater (original layout)', sky: 'red', light: 200, + rows: arena(32, 30, ',', 'R', (rect, g) => { + for (const [x, y] of [[7, 8], [23, 8], [7, 20], [23, 20]]) rect(x, y, x + 1, y + 1, 'T'); + for (const [x, y] of [[15, 9], [15, 20]]) rect(x, y, x + 1, y, 'P'); + for (const [x, y] of [[11, 14], [20, 14]]) rect(x, y, x, y + 1, 'P'); + rect(13, 12, 18, 17, 'x'); rect(15, 14, 16, 15, 'n'); + rect(1, 1, 30, 2, '.'); rect(1, 27, 30, 28, '.'); + for (let x = 4; x < 30; x += 6) { g[0][x] = 'L'; g[29][x] = 'L'; } + for (let y = 5; y < 28; y += 6) { g[y][0] = 'L'; g[y][31] = 'L'; } + }), + player: [1024, 1664, -PI / 2], bosses: [[1024, 320]], arms: ['shotgun', 'chaingun', 'rocket'], + items: [['medikit', 192, 960, 'all'], ['medikit', 1856, 960, 'all'], ['rocketbox', 192, 1664, 'all'], ['rocketbox', 1856, 1664, 'all'], + ['shellbox', 512, 1792, 'all'], ['shellbox', 1536, 1792, 'all'], ['bulletbox', 1024, 1792, 'all'], + ['medikit', 1024, 1152, 'easy'], ['medikit', 640, 1664, 'easy'], ['medikit', 1408, 1664, 'easy'], ['greenarmor', 1024, 1472, 'easy'], + ['stimpack', 640, 1344, 'normal'], ['stimpack', 1408, 1344, 'normal']], + }, + spider: { + title: 'Tech-base pillar hall (original layout)', sky: 'dusk', light: 176, + rows: arena(32, 28, '.', 'M', (rect, g) => { + for (const x of [5, 12, 19, 26]) for (const y of [10, 18]) rect(x, y, x + 1, y + 1, 'T'); + for (const x of [8, 23]) rect(x, 4, x + 1, 4, 'P'); + rect(10, 3, 21, 8, ','); rect(10, 12, 21, 16, 'x'); rect(14, 13, 17, 15, ','); + for (let x = 3; x < 30; x += 5) { g[0][x] = 'L'; g[27][x] = 'L'; } + for (let y = 3; y < 26; y += 5) { g[y][0] = 'L'; g[y][31] = 'L'; } + g[0][15] = g[0][16] = 'D'; + }), + player: [1024, 1600, -PI / 2], bosses: [[1024, 352]], arms: ['shotgun', 'chaingun', 'rocket'], + items: [['medikit', 160, 1600, 'all'], ['medikit', 1888, 1600, 'all'], ['rocketbox', 160, 800, 'all'], ['rocketbox', 1888, 800, 'all'], + ['bulletbox', 512, 1664, 'all'], ['bulletbox', 1536, 1664, 'all'], ['shellbox', 1024, 1664, 'all'], + ['medikit', 1024, 1408, 'easy'], ['medikit', 640, 1600, 'easy'], ['medikit', 1408, 1600, 'easy'], ['greenarmor', 1024, 1216, 'easy'], + ['stimpack', 480, 1216, 'normal'], ['stimpack', 1600, 1216, 'normal']], + }, + revenant: { + // Pillar cloister: a homing tracer turns 16.875 deg every 4th tic, so the answer is to put a pillar between it and you. + // Imps (map thing skill bits) give the scene monsters that can hurt each other: the infighting path in a full fight. + title: 'Pillar cloister (original layout)', sky: 'red', light: 172, + rows: arena(30, 26, '.', '#', (rect, g) => { + for (let x = 5; x < 26; x += 5) for (const y of [6, 12, 18]) rect(x, y, x, y, 'P'); + rect(12, 10, 17, 14, ','); rect(14, 11, 15, 13, 'x'); + for (let x = 3; x < 28; x += 6) { g[0][x] = 'L'; g[25][x] = 'L'; } + for (let y = 4; y < 24; y += 6) { g[y][0] = 'L'; g[y][29] = 'L'; } + g[0][14] = g[0][15] = 'D'; + }), + player: [960, 1472, -PI / 2], bosses: [[960, 288]], arms: ['shotgun', 'chaingun'], + minions: [[448, 608, 'imp', [0, 1, 2, 3, 4]], [1472, 608, 'imp', [0, 1, 2, 3, 4]], [448, 992, 'imp', [2, 3, 4]], [1472, 992, 'imp', [3, 4]]], + items: [['medikit', 160, 1472, 'all'], ['medikit', 1760, 1472, 'all'], ['shellbox', 160, 288, 'all'], ['shellbox', 1760, 288, 'all'], + ['shellbox', 576, 1536, 'all'], ['shellbox', 1344, 1536, 'all'], ['bulletbox', 960, 1568, 'all'], ['shellbox', 160, 864, 'all'], ['shellbox', 1760, 864, 'all'], ['shellbox', 448, 1280, 'all'], ['shellbox', 1472, 1280, 'all'], + ['medikit', 960, 1248, 'easy'], ['medikit', 576, 1280, 'easy'], ['medikit', 1344, 1280, 'easy'], ['greenarmor', 960, 1120, 'easy'], + ['stimpack', 544, 1120, 'normal'], ['stimpack', 1376, 1120, 'normal']], + }, + mancubus: { + // Open atrium: a fan of fireballs is answered by moving sideways, so the floor stays open; four pillars at the corners + // of the fight give cover from a volley, not a place to live. No minions: this scene tests the pattern alone. + title: 'Open atrium (original layout)', sky: 'red', light: 176, + rows: arena(30, 26, '.', '#', (rect, g) => { + for (const [x, y] of [[7, 7], [21, 7], [7, 17], [21, 17]]) rect(x, y, x + 1, y + 1, 'P'); + rect(11, 9, 18, 16, ','); rect(13, 11, 16, 14, 'n'); + for (let x = 3; x < 28; x += 6) { g[0][x] = 'L'; g[25][x] = 'L'; } + for (let y = 4; y < 24; y += 6) { g[y][0] = 'L'; g[y][29] = 'L'; } + g[0][14] = g[0][15] = 'D'; + }), + player: [960, 1472, -PI / 2], bosses: [[960, 288]], arms: ['shotgun', 'chaingun'], + items: [['medikit', 160, 1472, 'all'], ['medikit', 1760, 1472, 'all'], ['shellbox', 160, 288, 'all'], ['shellbox', 1760, 288, 'all'], + ['shellbox', 160, 864, 'all'], ['shellbox', 1760, 864, 'all'], ['bulletbox', 576, 1536, 'all'], ['bulletbox', 1344, 1536, 'all'], ['shellbox', 960, 1568, 'all'], ['shellbox', 448, 1280, 'all'], ['shellbox', 1472, 1280, 'all'], + ['medikit', 960, 1248, 'easy'], ['medikit', 576, 1280, 'easy'], ['medikit', 1344, 1280, 'easy'], ['greenarmor', 960, 1120, 'easy'], + ['stimpack', 544, 1120, 'normal'], ['stimpack', 1376, 1120, 'normal']], + }, + archvile: { + // Pillar courtyard: the only answer to the Arch-Vile's flame is breaking its sight line on the tic of A_VileAttack, + // so the floor is broken by a ring of 2x2 pillars and four short walls; imps (thing skill bits: easy / medium / hard + // as in a map lump) give it bodies to raise. + title: 'Pillar courtyard (original layout)', sky: 'red', light: 184, + rows: arena(30, 28, '.', '#', (rect, g) => { + for (const [x, y] of [[6, 6], [13, 5], [22, 6], [5, 13], [23, 13], [6, 20], [10, 21], [18, 21], [22, 20]]) rect(x, y, x + 1, y + 1, 'P'); + rect(10, 10, 10, 12, 'R'); rect(19, 10, 19, 12, 'R'); rect(10, 16, 10, 17, 'R'); rect(19, 16, 19, 17, 'R'); + rect(12, 12, 17, 15, ','); rect(14, 13, 15, 14, 'x'); + for (let x = 3; x < 28; x += 6) { g[0][x] = 'L'; g[27][x] = 'L'; } + for (let y = 4; y < 26; y += 6) { g[y][0] = 'L'; g[y][29] = 'L'; } + g[0][14] = g[0][15] = 'D'; + }), + player: [960, 1600, -PI / 2], bosses: [[960, 288]], arms: ['shotgun', 'chaingun', 'rocket'], + minions: [[448, 640, 'imp', [0, 1, 2, 3, 4]], [1472, 640, 'imp', [0, 1, 2, 3, 4]], [256, 1088, 'imp', [0, 1, 2, 3, 4]], [1664, 1088, 'imp', [0, 1, 2, 3, 4]], + [704, 384, 'imp', [2, 3, 4]], [1216, 384, 'imp', [2, 3, 4]], [960, 640, 'imp', [3, 4]]], + items: [['medikit', 160, 1600, 'all'], ['medikit', 1760, 1600, 'all'], ['rocketbox', 160, 448, 'all'], ['rocketbox', 1760, 448, 'all'], + ['shellbox', 576, 1664, 'all'], ['shellbox', 1344, 1664, 'all'], ['bulletbox', 960, 1696, 'all'], ['medikit', 960, 1024, 'all'], + ['rocketbox', 288, 160, 'all'], ['rocketbox', 1632, 160, 'all'], ['rocketbox', 288, 1696, 'all'], ['rocketbox', 1632, 1696, 'all'], + ['rocketbox', 640, 160, 'all'], ['rocketbox', 1280, 160, 'all'], ['rocketbox', 160, 1376, 'all'], ['rocketbox', 1760, 1376, 'all'], ['rocketbox', 704, 960, 'all'], ['rocketbox', 1216, 960, 'all'], + ['bulletbox', 160, 960, 'all'], ['bulletbox', 1760, 960, 'all'], ['shellbox', 736, 1056, 'all'], ['shellbox', 1184, 1056, 'all'], + ['medikit', 960, 1248, 'easy'], ['medikit', 576, 1408, 'easy'], ['medikit', 1344, 1408, 'easy'], ['greenarmor', 960, 1120, 'easy'], + ['stimpack', 544, 1216, 'normal'], ['stimpack', 1376, 1216, 'normal']], + }, + }; + for (const m of Object.values(MAPS)) { + m.h = m.rows.length; m.w = m.rows[0].length; + m.solid = m.rows.map(r => [...r].map(ch => SOLID.includes(ch) ? 1 : 0)); + } + const ITEMS = { bulletbox: { r: 20 }, medikit: { r: 20 }, stimpack: { r: 20 }, rocketbox: { r: 20 }, shellbox: { r: 20 }, greenarmor: { r: 20 }, bluearmor: { r: 20 } }; + const caseKey = id => id.endsWith('barons') ? 'barons' : id.endsWith('cyberdemon') ? 'cyberdemon' : id.endsWith('archvile') ? 'archvile' : id.endsWith('mancubus') ? 'mancubus' : id.endsWith('revenant') ? 'revenant' : 'spider'; + const kindOf = key => key === 'barons' ? 'baron' : key === 'archvile' ? 'vile' : key === 'mancubus' ? 'fatso' : key === 'revenant' ? 'undead' : key; + const isBoss = o => o.boss !== false; // minions carry boss:false; the three @5 scenes have no such field (state hash unchanged) + const approx = (dx, dy) => { dx = Math.abs(dx); dy = Math.abs(dy); return dx + dy - (dx < dy ? dx : dy) / 2; }; // P_AproxDistance + const norm = a => Math.atan2(Math.sin(a), Math.cos(a)); + const frameOf = b => { const seq = SEQ[b.kind][b.mode], t = Math.max(0, b.attackTick - 1); let k = 0; while (k + 1 < seq.f.length && seq.starts[k + 1] <= t) k++; return seq.f[k]; }; + const skillOf = d => d < 0.25 ? SK_BABY : d < 0.45 ? SK_EASY : d < 0.7 ? SK_MEDIUM : d < 0.95 ? SK_HARD : SK_NIGHTMARE; + const fastOf = d => d >= 0.8; // -fast (fastparm); Nightmare implies it (G_InitNew) + const hpOf = (kind, d) => HEALTH[kind] ? healthOf(kind, d) : KINDS[kind].hp; // minions keep vanilla spawnhealth + const healthOf = (kind, d) => { // BossBench spawnhealth table, rounded to 10 + const h = HEALTH[kind], [a, b, c] = HEALTH_D; + const v = d <= a ? h[0] : d <= b ? h[0] + (h[1] - h[0]) * (d - a) / (b - a) : d <= c ? h[1] + (h[2] - h[1]) * (d - b) / (c - b) : h[2]; + return Math.round(v / 10) * 10; + }; + const tierOf = d => Object.keys(TIERS).find(t => Math.abs(TIERS[t] - d) < 1e-9) || null; + // Original mode a difficulty falls in (public info difficulty_band): the skill name, plus -fast where it is a flag. + const bandOf = d => SKILLS[skillOf(d)] + (fastOf(d) && skillOf(d) !== SK_NIGHTMARE ? ' Fast' : ''); + // Loadout: the case arsenal with a backpack (maxammo 400/100/100, p_inter.c) in every tier and skill; health 100% + // and 200% blue armor (practice-arena rule; vanilla starts with the pistol and no armor). + const loadoutOf = map => ({ arms: map.arms.slice(), max: { bullets: 400, shells: 100, rockets: 100 } }); + + const M = root.DoomGame = { + id: 'doom_remake', version: 'doom-arena@11', hz: HZ, originalHz: OHZ, maxSeconds: 300, dimension: '3d', renderer: 'software-raycast', + tiers: TIERS, difficultyBand: bandOf, + title: 'DOOM · Hell Arena', + cases: [{ id: 'doom/cyberdemon', name: 'Rocket Colossus' }, { id: 'doom/barons', name: 'Green-Flame Barons ×2' }, { id: 'doom/spider_mastermind', name: 'Four-Legged Gun Platform' }, { id: 'doom/archvile', name: 'Fire Sorcerer (+ Fire Imp minions)' }, { id: 'doom/mancubus', name: 'Twin-Cannon Brute' }, { id: 'doom/revenant', name: 'Shoulder-Cannon Skeleton (+ Fire Imp)' }], + controls: { + 'W / S': 'Forward / backward (thrust and friction; original 35 Hz speed preserved per second)', 'A / D': 'Strafe left / right', 'Shift': 'Run (about twice normal speed)', 'mouse dx / Q E': 'Turn horizontally (no pitch or free look in the original)', + 'J / LMB': 'Fire (hold for repeated shots)', 'K / RMB': 'Next weapon (shotgun → chaingun → rocket launcher where available; otherwise shotgun ↔ chaingun; lowering and raising takes about 30 ticks); mouse dz > 0 has the same effect in the policy interface', 'L': 'Previous weapon; mouse dz < 0 has the same effect in the policy interface', 'Space': 'The original has no jump', + }, + }; + + class Game { + constructor(id, seed, d) { + this.id = id; this.key = caseKey(id); this.d = d; this.skill = skillOf(d); this.fast = fastOf(d); this.tier = tierOf(d); + // M_ClearRandom starts at index 0 each level; the BossBench engine seed selects the start index (SOURCES C-SEED). + // Golden-ratio hash (seed 0 -> 0 as in vanilla): consecutive seeds start >= 23 table steps apart, so they do not + // resynchronise into identical episodes (doom-arena@3's xor fold mapped seeds 1..8 to indices 1..8). + this.prnd = Math.imul(seed >>> 0, 0x9e3779b1) >>> 24; + this.t = 0; this.outcome = null; this.events = []; this.shots = 0; this.damageDealt = 0; this.damageTaken = 0; + const map = MAPS[this.key], [px, py, pa] = map.player, kit = loadoutOf(map); + const arms = kit.arms, first = arms.includes('rocket') ? 'rocket' : arms.includes('chaingun') ? 'chaingun' : arms[0]; + const bullets = arms.includes('chaingun') ? kit.max.bullets : 0; + this.player = { x: px, y: py, a: pa, vx: 0, vy: 0, hp: 100, armor: 200, armorType: 2, r: 16, weapon: first, pending: null, arms, max: kit.max, + shells: arms.includes('shotgun') ? kit.max.shells : 0, rockets: arms.includes('rocket') ? kit.max.rockets : 0, bullets, + wst: WINFO[first].ready, wtics: 1, wy: WEAPONTOP, sx: 1, sy: WEAPONTOP, fst: null, ftics: 0, attackdown: false, refire: 0, extralight: 0, damagecount: 0, bonuscount: 0, + attacker: -1, turnheld: 0, fwd: 0, side: 0, fire: false, kills: 0, shootable: true, solid: true }; + const kind = kindOf(this.key), hp = healthOf(kind, d); + this.bosses = map.bosses.map(([x, y]) => { + const k = KINDS[kind]; + return { kind, x, y, a: norm(Math.atan2(py - y, px - x)), vx: 0, vy: 0, hp, maxHp: hp, r: k.r, height: k.height, mode: 'see', attackTick: 0, + movedir: NODIR, movecount: 0, reactiontime: this.skill === SK_NIGHTMARE ? 0 : k.reaction, threshold: 0, target: 1, justhit: false, justattacked: false, + flash: 0, shootable: true, solid: true, dead: false }; + }); + for (const [x, y, mk, skills] of map.minions || []) { // thing skill flags as in the map lump (easy / medium / hard bits) + if (!skills.includes(this.skill)) continue; + const k = KINDS[mk]; + this.bosses.push({ kind: mk, x, y, a: norm(Math.atan2(py - y, px - x)), vx: 0, vy: 0, hp: k.hp, maxHp: k.hp, r: k.r, height: k.height, mode: 'see', attackTick: 0, + movedir: NODIR, movecount: 0, reactiontime: this.skill === SK_NIGHTMARE ? 0 : k.reaction, threshold: 0, target: 1, justhit: false, justattacked: false, + flash: 0, shootable: true, solid: true, dead: false, boss: false }); + } + if (kind === 'vile') { this.bosses[0].tracer = -1; this.fires = []; this.fireSeq = 0; this.player.z = 0; this.player.vz = 0; } + this.maxBoss = this.bosses.filter(isBoss).reduce((n, b) => n + b.hp, 0); + const flag = { all: [0, 1, 2, 3, 4], easy: [0, 1], normal: [0, 1, 2] }; + this.pickups = map.items.filter(it => flag[it[3]].includes(this.skill)).map(([type, x, y]) => ({ type, x, y, taken: false })); + this.projectiles = []; this.blasts = []; this.fx = []; this.soundtarget = false; + this.spawnpoints = this.bosses.map(({ x, y }) => ({ x, y })); + } + mapdef() { return MAPS[this.key]; } + prandom() { this.prnd = (this.prnd + 1) & 255; return RNDTABLE[this.prnd]; } + randomByte() { return this.prandom(); } + // ---------------- geometry ---------------- + solidAt(cx, cy) { const m = MAPS[this.key]; return cx < 0 || cy < 0 || cx >= m.w || cy >= m.h ? 1 : m.solid[cy][cx]; } + wall(x, y) { return this.solidAt(Math.floor(x / 64), Math.floor(y / 64)); } + boxClear(x, y, r) { + const x0 = Math.floor((x - r) / 64), x1 = Math.ceil((x + r) / 64) - 1, y0 = Math.floor((y - r) / 64), y1 = Math.ceil((y + r) / 64) - 1; + for (let cy = y0; cy <= y1; cy++) for (let cx = x0; cx <= x1; cx++) if (this.solidAt(cx, cy)) return false; + return true; + } + ray(x, y, a, max = MISSILERANGE * 2) { + // Grid DDA: distance to the first solid cell boundary (used for sight, hitscan and the renderer). + const dx = Math.cos(a), dy = Math.sin(a); let cx = Math.floor(x / 64), cy = Math.floor(y / 64); + const sx = dx < 0 ? -1 : 1, sy = dy < 0 ? -1 : 1, ddx = Math.abs(64 / (dx || 1e-12)), ddy = Math.abs(64 / (dy || 1e-12)); + let tx = (dx < 0 ? x - cx * 64 : (cx + 1) * 64 - x) / Math.abs(dx || 1e-12), ty = (dy < 0 ? y - cy * 64 : (cy + 1) * 64 - y) / Math.abs(dy || 1e-12), dist = 0, side = 0; + for (let i = 0; i < 128; i++) { + if (tx < ty) { dist = tx; tx += ddx; cx += sx; side = 0; } else { dist = ty; ty += ddy; cy += sy; side = 1; } + if (dist > max) return { dist: max, side: 0, tile: 0, cx: -1, cy: -1 }; + if (this.solidAt(cx, cy)) return { dist, side, tile: 1, cx, cy }; + } + return { dist: max, side: 0, tile: 0, cx: -1, cy: -1 }; + } + sight(a, b) { // P_CheckSight approximated by a grid ray between centres (things never block sight). + const dist = Math.hypot(b.x - a.x, b.y - a.y); if (dist < 1) return true; + return this.ray(a.x, a.y, Math.atan2(b.y - a.y, b.x - a.x), dist).dist >= dist - 0.01; + } + things() { return [this.player, ...this.bosses]; } + // Monster target: 0 none, 1 the player (all @5 scenes), 'm' = this.bosses[i] (infighting, Arch-Vile scene only). + tgt(b) { return b.target === 1 ? this.player : typeof b.target === 'string' ? this.bosses[+b.target.slice(1)] : null; } + srcObj(source) { return source === 'player' ? this.player : typeof source === 'number' ? this.bosses[source] || null : null; } + lying(b) { const seq = SEQ[b.kind][b.mode]; return (b.mode === 'death' || b.mode === 'xdeath') && b.attackTick > seq.starts[seq.f.length - 1]; } // tics == -1 + fits(o, x, y) { // P_CheckPosition for a walker: walls, then every solid thing (vanilla things are infinitely tall) + if (!this.boxClear(x, y, o.r)) return false; + for (const t of this.things()) { if (t === o || !t.solid) continue; const bd = t.r + o.r; if (Math.abs(t.x - x) < bd && Math.abs(t.y - y) < bd) return false; } + return true; + } + // P_TryMove for walking things: walls and solid things as axis-aligned boxes (PIT_CheckThing blockdist). + tryMove(o, x, y) { + if (!this.boxClear(x, y, o.r)) return false; + for (const t of this.things()) { + if (t === o || !(t.solid || t.shootable) || !t.solid) continue; + const bd = t.r + o.r; if (Math.abs(t.x - x) < bd && Math.abs(t.y - y) < bd) return false; + } + o.x = x; o.y = y; + if (o === this.player) this.touchPickups(); + return true; + } + move(o, dx, dy) { // axis-separated slide (approximation of P_SlideMove on a grid) + if (!this.tryMove(o, o.x + dx, o.y + dy)) { + if (this.tryMove(o, o.x + dx, o.y)) { o.vy = 0; } else if (this.tryMove(o, o.x, o.y + dy)) { o.vx = 0; } else { o.vx = 0; o.vy = 0; } + } + } + // P_XYMovement for players and monsters (missiles have their own loop). + xyMove(o, isPlayer) { + if (!o.vx && !o.vy) return; + o.vx = N.clamp(o.vx, -MAXMOVE, MAXMOVE); o.vy = N.clamp(o.vy, -MAXMOVE, MAXMOVE); + let xm = o.vx * R, ym = o.vy * R; // velocity is per original tic; a tick moves R of it (the 15-unit split is a distance) + do { + let tx, ty; + if (xm > MAXMOVE / 2 || ym > MAXMOVE / 2) { tx = o.x + xm / 2; ty = o.y + ym / 2; xm /= 2; ym /= 2; } else { tx = o.x + xm; ty = o.y + ym; xm = ym = 0; } + if (!this.tryMove(o, tx, ty)) { if (isPlayer) this.move(o, tx - o.x, ty - o.y); else { o.vx = o.vy = 0; } } + } while (xm || ym); + const p = this.player; + if (o.z > 0) return; // no friction when airborne (only the Arch-Vile scene gives the player a z) + if (o.vx > -STOPSPEED && o.vx < STOPSPEED && o.vy > -STOPSPEED && o.vy < STOPSPEED && (!isPlayer || (!p.fwd && !p.side))) { o.vx = 0; o.vy = 0; } + else { o.vx *= FRICTION_T; o.vy *= FRICTION_T; } + } + touchPickups() { + const p = this.player; + for (const it of this.pickups) { + if (it.taken || Math.abs(it.x - p.x) >= 20 + p.r || Math.abs(it.y - p.y) >= 20 + p.r) continue; + const dbl = this.skill === SK_BABY || this.skill === SK_NIGHTMARE ? 2 : 1, max = p.max; + let ok = false; + if (it.type === 'medikit' || it.type === 'stimpack') { if (p.hp < 100) { p.hp = Math.min(100, p.hp + (it.type === 'medikit' ? 25 : 10)); ok = true; } } + else if (it.type === 'rocketbox') { if (p.rockets < max.rockets) { p.rockets = Math.min(max.rockets, p.rockets + 5 * dbl); ok = true; } } + else if (it.type === 'shellbox') { if (p.shells < max.shells) { p.shells = Math.min(max.shells, p.shells + 20 * dbl); ok = true; } } + else if (it.type === 'bulletbox') { if (p.bullets < max.bullets) { p.bullets = Math.min(max.bullets, p.bullets + 50 * dbl); ok = true; } } + else if (it.type === 'greenarmor' || it.type === 'bluearmor') { const type = it.type === 'greenarmor' ? 1 : 2; if (p.armor < type * 100) { p.armor = type * 100; p.armorType = type; ok = true; } } + if (ok) { it.taken = true; p.bonuscount += 6; this.events.push('pickup:' + it.type); } + } + } + // ---------------- damage ---------------- + hurt(target, damage, inflictor, source) { this.damageMobj(target, inflictor, source, damage); } + damageMobj(target, inflictor, source, damage) { + if (!target.shootable || target.hp <= 0) return; + const p = this.player, isPlayer = target === p; + damage = Math.floor(damage); + if (isPlayer && this.skill === SK_BABY) damage >>= 1; + if (inflictor) { // thrust = damage*(FRACUNIT>>3)*100/mass + const ang = Math.atan2(target.y - inflictor.y, target.x - inflictor.x), thrust = damage * 12.5 / (isPlayer ? 100 : KINDS[target.kind].mass) * KNOCK_T; + target.vx += thrust * Math.cos(ang); target.vy += thrust * Math.sin(ang); + } + if (isPlayer) { + if (p.armorType) { + let saved = p.armorType === 1 ? Math.floor(damage / 3) : Math.floor(damage / 2); + if (p.armor <= saved) { saved = p.armor; p.armorType = 0; } + p.armor -= saved; damage -= saved; + } + p.attacker = source === undefined || source === null || source === 'player' ? -1 : source; + p.damagecount = Math.min(100, p.damagecount + damage); + this.damageTaken += damage; + } else this.damageDealt += Math.min(damage, target.hp); + target.hp -= damage; + if (target.hp <= 0) { const raw = target.hp; target.hp = 0; this.killMobj(target, raw); return; } + if (isPlayer) { this.prandom(); this.events.push('player_pain'); return; } // painchance 255: only the sprite changes + if (this.prandom() < KINDS[target.kind].pain) { target.justhit = true; this.enter(target, 'pain'); this.events.push('pain'); } + target.reactiontime = 0; + // Retarget: an Arch-Vile always turns on its attacker; nobody turns on an Arch-Vile (p_inter.c 904-911). + const src = this.srcObj(source); + if ((!target.threshold || target.kind === 'vile') && src && src !== target && src.kind !== 'vile') { target.target = src === p ? 1 : 'm' + source; target.threshold = BASETHRESHOLD; if (target.mode === 'spawn' && target.attackTick <= SEQ[target.kind].spawn.starts[1]) this.enter(target, 'see'); } // state == spawnstate + target.flash = 4; + } + killMobj(target, raw = 0) { + if (target === this.player) { target.shootable = false; target.solid = false; this.events.push('player_dead'); return; } + target.shootable = false; target.dead = true; target.height = Math.floor(target.height / 4); target.vx = target.vy = 0; + this.player.kills++; this.events.push(isBoss(target) ? 'boss_dead' : 'kill:' + target.kind); + const mode = raw < -KINDS[target.kind].hp && SEQ[target.kind].xdeath ? 'xdeath' : 'death'; // gibbed below -spawnhealth + this.enter(target, mode); + const first = SEQ[target.kind][mode].f[0][0], skip = Math.min(this.prandom() & 3, first - 1); + target.attackTick += skip; // tics -= P_Random()&3 (minimum 1) + } + // ---------------- monster state machine ---------------- + enter(b, mode, offset = 0) { // P_SetMobjState: enter and run the entry action this tic. + b.mode = mode; b.attackTick = offset; + this.runFrame(b); + } + runFrame(b) { // "check then advance": the frame starting at attackTick runs its action, then the counter moves on. + const seq = SEQ[b.kind][b.mode], mode = b.mode, t = b.attackTick++; + for (let k = seq.starts.indexOf(t); k >= 0 && k < seq.f.length && seq.starts[k] === t; k++) { // 0-tic frames run in the same call + if (seq.f[k][2]) this['A_' + seq.f[k][2]](b); + if (b.mode !== mode || b.attackTick !== t + 1) break; + } + } + thinkMonster(b) { // tic part of P_MobjThinker (its momentum part runs every tick in update) + if (this.lying(b)) { // tics == -1 + if (this.skill !== SK_NIGHTMARE) return; + if (++b.movecount < 12 * 35 || (this.tic() & 31) || this.prandom() > 4) return; + this.nightmareRespawn(b); return; + } + if (b.flash > 0) b.flash--; + const seq = SEQ[b.kind][b.mode]; + if (b.attackTick >= seq.length) { + const next = seq.next; if (Array.isArray(next)) this.enter(b, next[0], next[1]); else if (next) this.enter(b, next); + } else this.runFrame(b); + } + frameOf(b) { return frameOf(b); } + tic() { return ticsBefore(this.t); } // gametic: index of the original tic that falls in this tick + nightmareRespawn(b) { + const i = this.bosses.indexOf(b), sp = this.spawnpoints[i], k = KINDS[b.kind], hp = hpOf(b.kind, this.d); + if (!this.boxClear(sp.x, sp.y, k.r)) return; + for (const t of this.things()) if (t !== b && t.solid && Math.abs(t.x - sp.x) < t.r + k.r && Math.abs(t.y - sp.y) < t.r + k.r) return; + this.prandom(); this.prandom(); // two teleport fogs (P_SpawnMobj lastlook) + this.fx.push({ kind: 'tfog', x: b.x, y: b.y, z: 0, tics: 6, frame: 0 }, { kind: 'tfog', x: sp.x, y: sp.y, z: 0, tics: 6, frame: 0 }); + this.prandom(); // new monster (P_SpawnMobj lastlook) + const nb = { kind: b.kind, x: sp.x, y: sp.y, a: 0, vx: 0, vy: 0, hp, maxHp: hp, r: k.r, height: k.height, mode: 'spawn', attackTick: 1, movedir: NODIR, movecount: 0, + reactiontime: 18, threshold: 0, target: 0, justhit: false, justattacked: false, flash: 0, shootable: true, solid: true, dead: false }; + if (!isBoss(b)) nb.boss = false; + if (b.kind === 'vile') nb.tracer = -1; + this.bosses[i] = nb; this.events.push('respawn:' + b.kind); + } + A_Look(b) { + const p = this.player; b.threshold = 0; + let seen = this.soundtarget && p.shootable; + if (!seen && p.hp > 0 && this.sight(b, p)) { const an = norm(Math.atan2(p.y - b.y, p.x - b.x) - b.a); seen = Math.abs(an) <= PI / 2 || approx(p.x - b.x, p.y - b.y) <= MELEERANGE; } + if (seen) { b.target = 1; this.events.push('sight:' + b.kind); this.enter(b, 'see'); } + } + A_Hoof(b) { this.events.push('hoof'); this.A_Chase(b); } + A_Metal(b) { this.events.push('metal'); this.A_Chase(b); } + lookAround(b) { // P_LookForPlayers(actor, true) for the single player (lastlook rotation not modelled) + const p = this.player; if (p.hp <= 0 || !this.sight(b, p)) return false; + b.target = 1; return true; + } + A_Chase(b) { + const p = this.tgt(b); + if (b.reactiontime) b.reactiontime--; + if (b.threshold) { if (!p || p.hp <= 0) b.threshold = 0; else b.threshold--; } + if (b.movedir < 8) { // turn 45 degrees per call towards the movement direction + b.a = Math.floor(((b.a % TAU) + TAU) % TAU / Q + 1e-4) * Q; + const delta = norm(b.a - b.movedir * Q); + if (delta > 1e-9 && delta < PI - 1e-9) b.a -= Q; else if (delta < -1e-9 || delta >= PI - 1e-9) b.a += Q; + b.a = norm(b.a); + } + if (!p || !p.shootable) { if (this.lookAround(b)) return; this.enter(b, 'spawn'); return; } + if (b.justattacked) { b.justattacked = false; if (!this.fast) this.newChaseDir(b); return; } + if (KINDS[b.kind].melee && this.checkMeleeRange(b)) { this.enter(b, SEQ[b.kind].melee ? 'melee' : 'attack'); return; } + if (!(!this.fast && b.movecount) && this.checkMissileRange(b)) { this.enter(b, 'attack'); b.justattacked = true; this.events.push('boss_attack'); return; } + if (--b.movecount < 0 || !this.pMove(b)) this.newChaseDir(b); + if (this.prandom() < 3) this.events.push('active:' + b.kind); + } + checkMeleeRange(b) { const p = this.tgt(b); return !!p && approx(p.x - b.x, p.y - b.y) < MELEERANGE - 20 + p.r && this.sight(b, p); } + checkMissileRange(b) { + const p = this.tgt(b); + if (!this.sight(b, p)) return false; + if (b.justhit) { b.justhit = false; return true; } + if (b.reactiontime) return false; + let dist = approx(b.x - p.x, b.y - p.y) - 64; + if (!KINDS[b.kind].melee) dist -= 128; + dist = Math.floor(dist); + if (b.kind === 'vile' && dist > 14 * 64) return false; // too far away + if (b.kind === 'undead') { if (dist < 196) return false; dist >>= 1; } // close for fist attack + if (b.kind === 'cyberdemon' || b.kind === 'spider') dist >>= 1; + if (dist > 200) dist = 200; + if (b.kind === 'cyberdemon' && dist > 160) dist = 160; + return !(this.prandom() < dist); + } + pMove(b) { + if (b.movedir === NODIR) return false; + const sp = KINDS[b.kind].speed; + return this.tryMove(b, b.x + sp * XSPEED[b.movedir], b.y + sp * YSPEED[b.movedir]); + } + tryWalk(b) { if (!this.pMove(b)) return false; b.movecount = this.prandom() & 15; return true; } + newChaseDir(b) { + const p = this.tgt(b), olddir = b.movedir, turnaround = OPPOSITE[olddir], dx = p.x - b.x, dy = p.y - b.y, d = [0, NODIR, NODIR]; + d[1] = dx > 10 ? 0 : dx < -10 ? 4 : NODIR; + d[2] = dy < -10 ? 6 : dy > 10 ? 2 : NODIR; + if (d[1] !== NODIR && d[2] !== NODIR) { b.movedir = DIAGS[((dy < 0) << 1) + (dx > 0)]; if (b.movedir !== turnaround && this.tryWalk(b)) return; } + if (this.prandom() > 200 || Math.abs(dy) > Math.abs(dx)) { const t = d[1]; d[1] = d[2]; d[2] = t; } + if (d[1] === turnaround) d[1] = NODIR; + if (d[2] === turnaround) d[2] = NODIR; + if (d[1] !== NODIR) { b.movedir = d[1]; if (this.tryWalk(b)) return; } + if (d[2] !== NODIR) { b.movedir = d[2]; if (this.tryWalk(b)) return; } + if (olddir !== NODIR) { b.movedir = olddir; if (this.tryWalk(b)) return; } + if (this.prandom() & 1) { for (let t = 0; t <= 7; t++) if (t !== turnaround) { b.movedir = t; if (this.tryWalk(b)) return; } } + else { for (let t = 7; t >= 0; t--) if (t !== turnaround) { b.movedir = t; if (this.tryWalk(b)) return; } } + if (turnaround !== NODIR) { b.movedir = turnaround; if (this.tryWalk(b)) return; } + b.movedir = NODIR; + } + A_FaceTarget(b) { const t = this.tgt(b); if (t) b.a = norm(Math.atan2(t.y - b.y, t.x - b.x)); } // no MF_SHADOW targets here: no P_Random + A_CyberAttack(b) { if (!b.target) return; this.A_FaceTarget(b); this.missile(b, this.tgt(b), 'rocket', this.bosses.indexOf(b)); } + A_BruisAttack(b) { + if (!b.target) return; + if (this.checkMeleeRange(b)) { this.events.push('claw'); this.damageMobj(this.tgt(b), b, this.bosses.indexOf(b), (this.prandom() % 8 + 1) * 10); return; } + this.missile(b, this.tgt(b), 'fireball', this.bosses.indexOf(b)); + } + // p_enemy.c 1351-1410. FATSPREAD = ANG90/8. P_SpawnMissile aims and half-steps along the line to the target (actor->angle + // does not matter to it), then A_FatAttack turns the missile: momentum only, so the half step is not bent. Angles here + // mirror BAM (D strafes to a + 90 deg; the same flip as P_SpawnPlayerMissile's autoaim in missile()), so vanilla's + + // spread is - here: seen from the Mancubus, volley 1 leans to its left, volley 2 to its right, volley 3 brackets the aim. + // p_enemy.c 1002-1110. The tracer spawns like any P_SpawnMissile (half step), then takes one more full step. + A_SkelMissile(b) { + if (!b.target) return; + this.A_FaceTarget(b); + const q = this.missile(b, this.tgt(b), 'tracer', this.bosses.indexOf(b)); + if (q.ttl > 0) { q.x += q.vx; q.y += q.vy; } // mo->x += mo->momx (no collision check, as in vanilla) + q.tracer = b.target; q.a = Math.atan2(q.vy, q.vx); + } + A_SkelWhoosh(b) { if (!b.target) return; this.A_FaceTarget(b); this.events.push('skel_whoosh'); } + A_SkelFist(b) { if (!b.target) return; this.A_FaceTarget(b); if (this.checkMeleeRange(b)) { this.events.push('skel_fist'); this.damageMobj(this.tgt(b), b, this.bosses.indexOf(b), (this.prandom() % 10 + 1) * 6); } } + A_Tracer(q) { // gametic & 3: the level's original tic count tic() (0 at level start) stands for gametic; smoke and puff are drawn only, their rolls are kept + if (this.tic() & 3) return; + const z = 32 + (this.prandom() - this.prandom()) / 64; this.prandom(); // P_SpawnPuff: z jitter, P_SpawnMobj lastlook + this.fx.push({ kind: 'puff', x: q.x, y: q.y, z, tics: Math.max(1, 4 - (this.prandom() & 3)), frame: 0 }); + this.prandom(); // MT_SMOKE: P_SpawnMobj lastlook + this.fx.push({ kind: 'smoke', x: q.x - q.vx, y: q.y - q.vy, z: 32, tics: Math.max(1, 4 - (this.prandom() & 3)), frame: 0 }); + if (this.fx.length > 48) this.fx.splice(0, this.fx.length - 48); + const dest = q.tracer === 1 ? this.player : typeof q.tracer === 'string' ? this.bosses[+q.tracer.slice(1)] : null; + if (!dest || dest.hp <= 0) return; + const exact = Math.atan2(dest.y - q.y, dest.x - q.x), diff = norm(exact - q.a); + if (Math.abs(diff) <= TRACEANGLE) q.a = exact; else q.a = norm(q.a + Math.sign(diff) * TRACEANGLE); + const sp = MISSILES.tracer.speed; q.vx = Math.cos(q.a) * sp; q.vy = Math.sin(q.a) * sp; + } + A_FatRaise(b) { this.A_FaceTarget(b); this.events.push('fat_raise'); } + fatShot(b, turn) { + const q = this.missile(b, this.tgt(b), 'fatshot', this.bosses.indexOf(b)), a = Math.atan2(q.vy, q.vx) + turn, sp = MISSILES.fatshot.speed; + if (turn) { q.vx = Math.cos(a) * sp; q.vy = Math.sin(a) * sp; } + } + A_FatAttack1(b) { if (!b.target) return; this.A_FaceTarget(b); b.a = norm(b.a - FATSPREAD); this.fatShot(b, 0); this.fatShot(b, -FATSPREAD); } + A_FatAttack2(b) { if (!b.target) return; this.A_FaceTarget(b); b.a = norm(b.a + FATSPREAD); this.fatShot(b, 0); this.fatShot(b, 2 * FATSPREAD); } + A_FatAttack3(b) { if (!b.target) return; this.A_FaceTarget(b); this.fatShot(b, FATSPREAD / 2); this.fatShot(b, -FATSPREAD / 2); } + A_TroopAttack(b) { // p_enemy.c 913: claw 3x(1..8) in melee range, else MT_TROOPSHOT + if (!b.target) return; + this.A_FaceTarget(b); + if (this.checkMeleeRange(b)) { this.events.push('claw'); this.damageMobj(this.tgt(b), b, this.bosses.indexOf(b), (this.prandom() % 8 + 1) * 3); return; } + this.missile(b, this.tgt(b), 'troopshot', this.bosses.indexOf(b)); + } + // ---------------- Arch-Vile (p_enemy.c 1121-1335) ---------------- + A_VileChase(b) { + if (b.movedir !== NODIR) { + const sp = KINDS[b.kind].speed, tx = b.x + sp * XSPEED[b.movedir], ty = b.y + sp * YSPEED[b.movedir]; + // PIT_VileCheck over the things near (tx, ty); blockmap order approximated by spawn order. + for (const c of this.bosses) { + if (!c.dead || !this.lying(c) || !KINDS[c.kind].raise) continue; + const maxdist = c.r + KINDS.vile.r; + if (Math.abs(c.x - tx) > maxdist || Math.abs(c.y - ty) > maxdist) continue; + c.vx = c.vy = 0; + if (!this.fits(c, c.x, c.y)) continue; // something solid stands on the body (the vile itself included) + b.a = norm(Math.atan2(c.y - b.y, c.x - b.x)); + this.enter(b, 'heal'); this.events.push('vile_raise'); + c.height = KINDS[c.kind].height; c.shootable = true; c.solid = true; c.dead = false; c.hp = KINDS[c.kind].hp; c.target = 0; c.justhit = c.justattacked = false; // flags = info->flags + this.enter(c, 'raise'); + return; + } + } + this.A_Chase(b); + } + A_VileStart() { this.events.push('vile_start'); } + A_VileTarget(b) { + if (!b.target) return; + this.A_FaceTarget(b); + const t = this.tgt(b); + this.prandom(); // P_SpawnMobj lastlook (spawned at (target.x, target.x): vanilla typo, corrected by the A_Fire below) + const f = { id: ++this.fireSeq, x: t.x, y: t.x, src: this.bosses.indexOf(b), dest: b.target, i: 0, tics: FIRE[0][0] }; + this.fires.push(f); b.tracer = f.id; this.events.push('vile_fire'); + this.fireFollow(f); + } + fireFollow(f) { // A_Fire: keep the fire 24 units in front of its victim unless the vile lost sight + const dest = f.dest === 1 ? this.player : typeof f.dest === 'string' ? this.bosses[+f.dest.slice(1)] : null; + if (!dest || !this.sight(this.bosses[f.src], dest)) return; + f.x = dest.x + 24 * Math.cos(dest.a); f.y = dest.y + 24 * Math.sin(dest.a); + } + A_VileAttack(b) { + if (!b.target) return; + this.A_FaceTarget(b); + const t = this.tgt(b); + if (!this.sight(b, t)) return; + this.events.push('vile_blast'); + this.damageMobj(t, b, this.bosses.indexOf(b), 20); + if (t === this.player) this.player.vz = 1000 / 100; // momz = 1000*FRACUNIT / mass (player mass 100) + const f = this.fires.find(o => o.id === b.tracer); + if (!f) return; + f.x = t.x - 24 * Math.cos(b.a); f.y = t.y - 24 * Math.sin(b.a); // between the vile and its victim + this.radiusAttack(f, this.bosses.indexOf(b), 70); + } + A_SPosAttack(b) { + if (!b.target) return; + this.events.push('hitscan'); this.A_FaceTarget(b); b.flash = 2; + const src = this.bosses.indexOf(b); + for (let i = 0; i < 3; i++) { + const ang = b.a + (this.prandom() - this.prandom()) * (1 << 20) * BAM, dmg = (this.prandom() % 5 + 1) * 3; + this.hitscan(b, ang, dmg, undefined, src); + } + } + A_SpidRefire(b) { + this.A_FaceTarget(b); + if (this.prandom() < 10) return; + const t = this.tgt(b); + if (!t || t.hp <= 0 || !this.sight(b, t)) this.enter(b, 'see'); + } + A_Pain(b) { this.events.push('pain_sound:' + b.kind); } + A_Scream(b) { this.events.push('death_sound:' + b.kind); } + A_XScream(b) { this.events.push('gib_sound:' + b.kind); } + A_Fall(b) { b.solid = false; } + A_BossDeath(b) { + if (this.player.hp <= 0) return; + if (this.bosses.some(o => o !== b && isBoss(o) && o.hp > 0)) return; + this.events.push('level_exit'); this.outcome = 'win'; + } + // ---------------- attacks ---------------- + traceThing(src, dx, dy, o, near) { // distance along the trace to the thing's box diagonal facing it, or -1 + const pos = (dx > 0) === (dy > 0) && dx !== 0 && dy !== 0 ? true : (dy === 0 ? dx > 0 : (dx === 0 ? dy > 0 : false)); + const r = o.r, x1 = o.x - r, x2 = o.x + r, y1 = pos ? o.y + r : o.y - r, y2 = pos ? o.y - r : o.y + r; + const ex = x2 - x1, ey = y2 - y1, den = dx * ey - dy * ex; if (Math.abs(den) < 1e-12) return -1; + const t = ((x1 - src.x) * ey - (y1 - src.y) * ex) / den, u = ((x1 - src.x) * dy - (y1 - src.y) * dx) / den; + return t > 0 && t < near && u >= 0 && u <= 1 ? t : -1; + } + hitscan(src, a, damage, targets, owner) { + // P_LineAttack in 2D: first wall or shootable thing (box diagonal facing the trace, PIT_AddThingIntercepts). + const range = MISSILERANGE, dx = Math.cos(a), dy = Math.sin(a), wall = this.ray(src.x, src.y, a, range).dist; + let near = wall, hit = null; + for (const o of targets || this.things()) { + if (o === src || !o.shootable || o.hp <= 0) continue; + const t = this.traceThing(src, dx, dy, o, near); if (t >= 0) { near = t; hit = o; } + } + let z = 0; + if (hit || wall < range) { z = 32 + (this.prandom() - this.prandom()) / 64; this.prandom(); } // z jitter, then P_SpawnMobj lastlook + if (hit) { + this.fx.push({ kind: 'blood', x: src.x + dx * (near - 10), y: src.y + dy * (near - 10), z, tics: Math.max(1, 8 - (this.prandom() & 3)), frame: damage >= 9 && damage <= 12 ? 1 : damage < 9 ? 2 : 0 }); + this.damageMobj(hit, src, owner === undefined ? (src === this.player ? 'player' : this.bosses.indexOf(src)) : owner, damage); + } else if (wall < range) { + this.fx.push({ kind: 'puff', x: src.x + dx * (wall - 4), y: src.y + dy * (wall - 4), z, tics: Math.max(1, 4 - (this.prandom() & 3)), frame: 0 }); + } + if (this.fx.length > 48) this.fx.splice(0, this.fx.length - 48); + return hit; + } + aimLine(src, a, range) { // P_AimLineAttack in 2D: first shootable thing along the line, else null. + const wall = this.ray(src.x, src.y, a, range).dist, dx = Math.cos(a), dy = Math.sin(a); + let near = Math.min(wall, range), hit = null; + for (const o of this.bosses) { + if (!o.shootable) continue; + const t = this.traceThing(src, dx, dy, o, near); if (t >= 0) { near = t; hit = o; } + } + return hit; + } + missile(src, target, kind, owner) { + // P_SpawnMissile (monsters, aimed at the target's current position) / P_SpawnPlayerMissile (autoaim +-1<<26). + const info = MISSILES[kind], speed = this.fast && info.fast ? info.fast : info.speed; // G_InitNew: BRUISERSHOT / TROOPSHOT 20 when fast + let a; + if (typeof target === 'number') a = target; + else if (target) a = Math.atan2(target.y - src.y, target.x - src.x); + else { + a = src.a; + if (!this.aimLine(src, a, 1024)) { a = src.a - (1 << 26) * BAM; if (!this.aimLine(src, a, 1024)) { a = src.a + (1 << 26) * BAM; if (!this.aimLine(src, a, 1024)) a = src.a; } } + } + this.prandom(); // P_SpawnMobj: lastlook = P_Random() % MAXPLAYERS + const q = { kind, x: src.x, y: src.y, vx: Math.cos(a) * speed, vy: Math.sin(a) * speed, r: info.r, owner, ttl: MISSILE_TTL, tics: info.fly[0][0], i: 0 }; + q.tics = Math.max(1, q.tics - (this.prandom() & 3)); // P_CheckMissileSpawn + this.projectiles.push(q); this.events.push(kind); + q.x += q.vx / 2; q.y += q.vy / 2; + if (!this.missileTry(q, q.x, q.y)) this.explode(q); + return q; + } + missileTry(q, x, y) { // P_TryMove for a missile; returns false when it must explode. + if (!this.boxClear(x, y, q.r)) return false; + const p = this.player, ownerObj = q.owner === 'player' ? p : this.bosses[q.owner]; + for (const t of this.things()) { + if (!t.shootable) continue; // corpses are lower than the 32-unit missile height after height>>=2 + const bd = t.r + q.r; if (Math.abs(t.x - x) >= bd || Math.abs(t.y - y) >= bd) continue; + if (ownerObj && (t === ownerObj)) continue; + if (ownerObj && ownerObj !== p && t !== p && t.kind === ownerObj.kind) return false; // same species: explode, no damage + const dmg = (this.prandom() % 8 + 1) * MISSILES[q.kind].damage; + this.damageMobj(t, q, q.owner, dmg); + return false; + } + q.x = x; q.y = y; return true; + } + explode(q) { + // P_ExplodeMissile + A_Explode (rockets): radius attack 128 from the missile position; the shooter is not immune. + q.ttl = 0; + const info = MISSILES[q.kind] || MISSILES.rocket, death = info.death; + const blast = { kind: q.kind || 'rocket', x: q.x, y: q.y, tics: death[0][0], i: 0 }; + this.blasts.push(blast); this.events.push('explode:' + blast.kind); + if (blast.kind === 'rocket') this.radiusAttack(q, q.owner, 128); + blast.tics = Math.max(1, blast.tics - (this.prandom() & 3)); + } + radiusAttack(spot, source, damage) { + for (const t of this.things()) { + if (!t.shootable || t.kind === 'cyberdemon' || t.kind === 'spider') continue; + let dist = Math.floor(Math.max(Math.abs(t.x - spot.x), Math.abs(t.y - spot.y)) - t.r); if (dist < 0) dist = 0; + if (dist >= damage) continue; + if (this.sight(t, spot)) this.damageMobj(t, spot, source, damage - dist); + } + } + // ---------------- player weapons (psprites) ---------------- + setPsp(p, which, name) { + for (let guard = 0; guard < 8; guard++) { + if (!name) { if (which === 'w') p.wst = null; else p.fst = null; return; } + const st = WSTATES[name]; + if (which === 'w') { p.wst = name; p.wtics = st[0]; } else { p.fst = name; p.ftics = st[0]; } + if (st[2]) { this['W_' + st[2]](p, which); if (which === 'w' ? !p.wst : !p.fst) return; } + if (which === 'w' ? p.wtics : p.ftics) return; + name = WSTATES[which === 'w' ? p.wst : p.fst][3]; + } + } + checkAmmo(p) { + if (p[WINFO[p.weapon].ammo] > 0) return true; + const other = ['chaingun', 'shotgun', 'rocket'].find(w => w !== p.weapon && p.arms.includes(w) && p[WINFO[w].ammo] > 0); + if (other) { p.pending = other; this.setPsp(p, 'w', WINFO[p.weapon].down); } + return false; + } + fireWeapon(p) { if (!this.checkAmmo(p)) return; this.setPsp(p, 'w', WINFO[p.weapon].atk); this.soundtarget = true; } // P_NoiseAlert: one open sector + W_WeaponReady(p) { + if (p.pending || p.hp <= 0) { this.setPsp(p, 'w', WINFO[p.weapon].down); return; } + if (p.fire) { if (!p.attackdown || p.weapon !== 'rocket') { p.attackdown = true; this.fireWeapon(p); return; } } + else p.attackdown = false; + const bob = Math.min(16, (p.vx * p.vx + p.vy * p.vy) / 4), ang = (128 * this.tic()) % 8192; + p.sx = 1 + bob * Math.cos(ang / 8192 * TAU); p.sy = WEAPONTOP + bob * Math.sin((ang % 4096) / 8192 * TAU); + } + W_ReFire(p) { if (p.fire && !p.pending && p.hp > 0) { p.refire++; this.fireWeapon(p); } else { p.refire = 0; this.checkAmmo(p); } } + W_Lower(p) { + p.wy += 6; if (p.wy < WEAPONBOTTOM) return; + if (p.hp <= 0) { p.wy = WEAPONBOTTOM; return; } + p.weapon = p.pending || p.weapon; p.pending = null; p.wy = WEAPONBOTTOM; this.setPsp(p, 'w', WINFO[p.weapon].up); + } + W_Raise(p) { p.wy -= 6; if (p.wy > WEAPONTOP) return; p.wy = WEAPONTOP; this.setPsp(p, 'w', WINFO[p.weapon].ready); } + W_GunFlash(p) { this.setPsp(p, 'f', WINFO[p.weapon].flash); } + W_FireShotgun() { this.firePlayer(); } + W_FireMissile() { this.firePlayer(); } + W_FireCGun() { this.firePlayer(); } + W_Light0(p) { p.extralight = 0; } W_Light1(p) { p.extralight = 1; } W_Light2(p) { p.extralight = 2; } + firePlayer() { + const p = this.player; + if (p.weapon === 'chaingun') { // A_FireCGun + P_GunShot: flash follows the firing frame, first shot of a burst is accurate + if (p.bullets <= 0) return; p.bullets--; this.setPsp(p, 'f', p.wst === 'CHAIN2' ? 'CHAINFLASH2' : 'CHAINFLASH1'); + const dmg = 5 * (this.prandom() % 3 + 1), ang = p.refire ? p.a + (this.prandom() - this.prandom()) * (1 << 18) * BAM : p.a; this.hitscan(p, ang, dmg, undefined, 'player'); + } else if (p.weapon === 'shotgun') { + if (p.shells <= 0) return; p.shells--; this.setPsp(p, 'f', WINFO.shotgun.flash); + for (let i = 0; i < 7; i++) { const dmg = 5 * (this.prandom() % 3 + 1), ang = p.a + (this.prandom() - this.prandom()) * (1 << 18) * BAM; this.hitscan(p, ang, dmg, undefined, 'player'); } + } else { + if (p.rockets <= 0) return; p.rockets--; this.missile(p, null, 'rocket', 'player'); + } + this.shots++; this.events.push('player_fire:' + p.weapon); + } + zMove(o) { // P_ZMovement on a flat floor at z 0 (GRAVITY = 1 unit/tic^2; a resting mobj first gets -2), every tick + o.z += o.vz * R; + if (o.z <= 0) { o.z = 0; if (o.vz < 0) o.vz = 0; } + else o.vz = o.vz === 0 ? -2 * R : o.vz - R; + } + // ---------------- tic ---------------- + update(keys, pressed, mouse) { + const p = this.player, tic = ticsBefore(this.t + 1) > ticsBefore(this.t); // an original tic falls in this tick + if (p.hp > 0) { + // G_BuildTiccmd + P_MovePlayer: turning (slow-turn ramp for keys), thrust from forward/side moves. + const run = keys.has('Shift') ? 1 : 0, left = keys.has('Q'), right = keys.has('E'); + if (left || right) p.turnheld++; else p.turnheld = 0; + const rate = TURN[p.turnheld < SLOWTURN_T ? 2 : run] * 65536 * BAM * R, turn = (right ? rate : 0) - (left ? rate : 0); + p.a = norm(p.a + turn + (mouse[0] || 0) * MOUSE_RAD); + p.fwd = ((keys.has('W') ? 1 : 0) - (keys.has('S') ? 1 : 0)) * FORWARD[run]; + p.side = ((keys.has('D') ? 1 : 0) - (keys.has('A') ? 1 : 0)) * SIDE[run]; + const onground = !(p.z > 0); + if (p.fwd && onground) { p.vx += Math.cos(p.a) * p.fwd * THRUST_T; p.vy += Math.sin(p.a) * p.fwd * THRUST_T; } + if (p.side && onground) { p.vx += Math.cos(p.a + PI / 2) * p.side * THRUST_T; p.vy += Math.sin(p.a + PI / 2) * p.side * THRUST_T; } + p.fire = keys.has('J') || keys.has('LMB'); + // Weapon change: K / RMB / wheel up = next owned weapon, L / wheel down = previous (vanilla selects by number key). + const next = pressed.has('K') || pressed.has('RMB') || mouse[2] > 0, prev = pressed.has('L') || mouse[2] < 0; + if ((next || prev) && !p.pending && p.arms.length > 1) { const i = p.arms.indexOf(p.weapon); p.pending = p.arms[(i + (next ? 1 : p.arms.length - 1)) % p.arms.length]; } + } else { p.fwd = p.side = 0; p.fire = false; } + if (tic) { // P_MovePsprites, palette counters + if (p.wst && p.wtics !== -1 && --p.wtics <= 0) this.setPsp(p, 'w', WSTATES[p.wst][3]); + if (p.fst && p.ftics !== -1 && --p.ftics <= 0) this.setPsp(p, 'f', WSTATES[p.fst][3]); + if (p.damagecount) p.damagecount--; + if (p.bonuscount) p.bonuscount--; + } + // P_RunThinkers in spawn order: player, bosses, missiles, effects. Momentum every tick, states on tic ticks. + this.xyMove(p, true); + if (p.vz || p.z > 0) this.zMove(p); + for (const b of this.bosses) { if (b.vx || b.vy) this.xyMove(b, false); if (tic) this.thinkMonster(b); } + if (this.fires && tic) { // MT_FIRE thinkers (spawned after the monsters, so they also tick on their spawn tic) + for (const f of this.fires) if (--f.tics <= 0) { f.i++; if (f.i < FIRE.length) { f.tics = FIRE[f.i][0]; this.fireFollow(f); } } + this.fires = this.fires.filter(f => f.i < FIRE.length); + } + for (const q of this.projectiles) { + if (q.ttl <= 0) continue; + if (--q.ttl <= 0) continue; + let xm = q.vx * R, ym = q.vy * R; + do { + let tx, ty; + if (xm > MAXMOVE / 2 || ym > MAXMOVE / 2) { tx = q.x + xm / 2; ty = q.y + ym / 2; xm /= 2; ym /= 2; } else { tx = q.x + xm; ty = q.y + ym; xm = ym = 0; } + if (!this.missileTry(q, tx, ty)) { this.explode(q); break; } + } while (xm || ym); + if (tic && q.ttl > 0 && --q.tics <= 0) { const fl = MISSILES[q.kind].fly; q.i = (q.i + 1) % fl.length; q.tics = fl[q.i][0]; if (fl[q.i][2]) this['A_' + fl[q.i][2]](q); } + } + this.projectiles = this.projectiles.filter(q => q.ttl > 0); + if (tic) for (const bl of this.blasts) if (--bl.tics <= 0) { const dth = (MISSILES[bl.kind] || MISSILES.rocket).death; bl.i++; bl.tics = bl.i < dth.length ? dth[bl.i][0] : 0; } + this.blasts = this.blasts.filter(bl => bl.i < (MISSILES[bl.kind] || MISSILES.rocket).death.length); + if (tic) for (const f of this.fx) { f.tics--; if (f.kind === 'tfog') { if (f.tics <= 0 && f.frame < 9) { f.frame++; f.tics = 6; } continue; } f.z += f.kind === 'blood' ? 2 : 1; if (f.tics <= 0 && (f.kind === 'puff' && f.frame < 3 || f.kind === 'smoke' && f.frame < 4)) { f.frame++; f.tics = 4; } else if (f.tics <= 0 && f.kind === 'blood' && f.frame < 2) { f.frame++; f.tics = 8; } } + this.fx = this.fx.filter(f => f.tics > 0); + if (!this.outcome && p.hp <= 0) this.outcome = 'loss'; + } + health() { return [Math.max(0, this.player.hp), 100, this.bosses.reduce((n, b) => n + (isBoss(b) ? Math.max(0, b.hp) : 0), 0), this.maxBoss]; } + } + M.Game = Game; M.types = KINDS; M.kinds = KINDS; M.seq = SEQ; M.missiles = MISSILES; M.wstates = WSTATES; M.winfo = WINFO; M.maps = MAPS; M.skills = SKILLS; + M.consts = { FRICTION, STOPSPEED, MAXMOVE, THRUST, FORWARD, SIDE, TURN, MOUSE_RAD, MELEERANGE, MISSILERANGE, WEAPONTOP, WEAPONBOTTOM, BAM, RNDTABLE, XSPEED, YSPEED }; + M.fire = FIRE; M.ticOf = ticsBefore; M.clock = { HZ, OHZ, R, FRICTION_T, THRUST_T, KNOCK_T, SLOWTURN_T, MISSILE_TTL, PKT, TT }; M.isBoss = isBoss; M.skillOf = skillOf; M.fastOf = fastOf; M.healthOf = healthOf; M.tierOf = tierOf; M.bandOf = bandOf; M.health = HEALTH; M.frameOf = frameOf; + M.copyGame = g => Object.assign(Object.create(Game.prototype), N.copy(g)); + + // ---------------- standard scripted controller (privileged, deterministic, read-only) ---------------- + const MOVES = [[], ['W'], ['S'], ['A'], ['D'], ['W', 'A'], ['W', 'D'], ['S', 'A'], ['S', 'D']]; + // Look-ahead copies must not know dice that are not rolled yet. A copy keeps + // the decided state but restarts P_Random at an index mixed only from the current tic and the sample number + // (murmur3 fmix32: a multiply, not an xor, so nothing of the real index leaks; measured by blind_probe.js). Each + // move is played in LOOK_K such futures and scored half worst, half mean. + const LOOK_K = 3; + const fmix = x => { x = Math.imul(x ^ (x >>> 16), 0x85ebca6b); x = Math.imul(x ^ (x >>> 13), 0xc2b2ae35); return (x ^ (x >>> 16)) >>> 0; }; + const blindCopy = (g, k) => { const c = M.copyGame(g); c.prnd = fmix((Math.imul(g.t, 0x9e3779b1) + Math.imul(k + 1, 0x7feb352d)) >>> 0) >>> 24; return c; }; + M.blindCopy = blindCopy; M.LOOK_K = LOOK_K; + function simulate(g, keys, mouseTick, ticks, after, k = 0) { + const h = blindCopy(g, k), ks = new Set(keys), none = new Set(); + for (let t = 0; t < ticks && !h.outcome; t++) { + h.events = []; h.update(t < PKT ? ks : (after || ks), none, [t < PKT ? mouseTick : 0, 0, 0]); N.quantize(h); h.t++; + } + return h; + } + function pickTarget(g) { + const p = g.player, alive = g.bosses.filter(b => b.hp > 0); + if (!alive.length) return null; + // Arch-Vile scene: a close, visible imp first; otherwise the vile, in sight or not (chasing far imps wastes the fight). + // With rockets up and the vile in sight only imps inside 250 interrupt (each chaingun swap costs 2 x 30 tics); otherwise 400. + // (doom-arena@10: 200 / 320 at 35 Hz; at 60 Hz the wider reach clears imps earlier, easy 17 -> 23 / 32 in window, hz60 round doc.) + const boss = alive.find(isBoss); + if (boss && boss.kind === 'vile') { const reach = p.weapon === 'rocket' && g.sight(p, boss) ? 250 : 400, near = alive.filter(b => !isBoss(b) && N.distance(p, b) < reach && g.sight(p, b)).sort((u, v) => N.distance(p, u) - N.distance(p, v))[0]; return near || boss; } + return alive.map(b => ({ b, s: N.distance(p, b) - (g.sight(p, b) ? 400 : 0) + b.hp * 0.05 })).sort((u, v) => u.s - v.s)[0].b; + } + M.scripted = function (g) { + const p = g.player, noop = { holds: Array.from({ length: 6 }, () => []), mouse: [0, 0, 0] }; + if (g.outcome || p.hp <= 0) return noop; + const b = pickTarget(g); + let aim = p.a, dist = 0, los = false; + if (b) { + dist = N.distance(p, b); los = g.sight(p, b); + let tx = b.x, ty = b.y; + if (p.weapon === 'rocket' && b.mode === 'see' && b.movedir < 8) { const lead = Math.min(40, dist / 20) * KINDS[b.kind].speed / 3; tx += XSPEED[b.movedir] * lead; ty += YSPEED[b.movedir] * lead; } + aim = Math.atan2(ty - p.y, tx - p.x); + } + const delta = norm(aim - p.a); + let dx = N.clamp(Math.round(delta / MOUSE_RAD), -1000, 1000); + // Arch-Vile scene: a rocket is committed 8 tics before A_FireMissile (MISSILE1). Turning onto a new target in that + // window can point it at a pillar or an imp in our face; keep the old heading unless the new one is clear for 200. + if (g.fires && p.weapon === 'rocket' && p.wst === 'MISSILE1') { + const a1 = p.a + dx * MOUSE_RAD, near = a => [-11, 0, 11].some(k => g.ray(p.x - Math.sin(a) * k, p.y + Math.cos(a) * k, a, 200).dist < 200) || !!g.aimLine(p, a, 200); + if (near(a1)) { if (!near(p.a)) dx = 0; else for (const da of [0.06, -0.06, 0.12, -0.12, 0.2, -0.2]) if (!near(a1 + da)) { dx = N.clamp(Math.round((norm(a1 + da - p.a)) / MOUSE_RAD), -1000, 1000); break; } } // clamp: packet mouse limit (60 Hz archvile hard seed 13 asked for 1080) + } + const mouseTick = dx / PKT; + const residual = Math.abs(norm(aim - (p.a + dx * MOUSE_RAD))); + // Weapon choice. Cyberdemon: rockets beyond self-splash range (it is splash-immune, so only direct hits count), else + // chaingun, then shotgun. Spider: hitscan first, chaingun then shotgun, because every bullet or pellet that hits rolls + // its painchance 40/256 (8.75 bullets/s; 7 pellets = 70% per blast on its 256-unit body) and pain cuts the 20-tic + // windup short; rockets last, except when hurt (<= 60): then the shotgun may only fire from cover and rockets do 2.4x + // its damage per exposure. Hysteresis around the rocket band avoids 30-tic switch loops. Mancubus: shotgun first, its + // 37-tic cycle leaves room for the 20-tic windup; the chaingun's 80/256 pain per bullet would stun-lock it. + const arms = p.arms, has = w => arms.includes(w) && p[WINFO[w].ammo] > 0, safe = b ? b.r + 190 : 0; + let want = p.weapon; + if (b) { + const order = (b.kind === 'fatso' || b.kind === 'undead' ? ['shotgun', 'chaingun', 'rocket'] : b.kind === 'imp' ? (dist > 220 && p.weapon === 'rocket' ? ['rocket', 'chaingun', 'shotgun'] : ['chaingun', 'shotgun', 'rocket']) : b.kind === 'spider' ? (p.hp > 60 || dist <= safe ? ['chaingun', 'shotgun', 'rocket'] : ['chaingun', 'rocket', 'shotgun']) : dist > safe ? ['rocket', 'chaingun', 'shotgun'] : ['chaingun', 'shotgun', 'rocket']); + want = order.find(has) || p.weapon; + if (order[0] === 'rocket' && p.weapon === 'rocket' && has('rocket') && dist >= b.r + 150) want = 'rocket'; // hysteresis + if (order[0] === 'rocket' && want === 'rocket' && p.weapon !== 'rocket' && has(p.weapon) && dist <= safe + 60) want = p.weapon; + } + const switching = !!p.pending || (p.wst && /DOWN|UP/.test(p.wst)); + const swap = !switching && !!b && want !== p.weapon; + const swapKey = swap && arms[(arms.indexOf(p.weapon) + 1) % arms.length] !== want ? 'L' : 'K'; + // A rocket needs its whole 11-unit box clear to the target, or it bursts on a pillar (wasted, and splash hurts us). + const clearLane = (w, o, t, a = Math.atan2(t.y - o.y, t.x - o.x), dd = N.distance(o, t)) => [-13, 0, 13].every(k => w.ray(o.x - Math.sin(a) * k, o.y + Math.cos(a) * k, a, dd).dist >= dd - t.r); + const aimA = p.a + dx * MOUSE_RAD, lane = !b || p.weapon !== 'rocket' || clearLane(g, p, b, aimA, dist); + // A minion stepping into the rocket's path at close range would take the rocket in our face (bosses never do: @5 parity). + const blocker = b && p.weapon === 'rocket' ? g.aimLine(p, aimA, Math.min(dist, 220)) : null, inFace = !!blocker && blocker !== b && !isBoss(blocker); + const fire = !!b && los && lane && !inFace && residual < 0.09 && !swap && !(p.weapon === 'rocket' && dist < b.r + 150); + const fireKeys = fire ? ['J'] : []; + // Movement: short look-ahead on disposable copies; score damage taken, distance band, projectile danger. + const band = !b ? [500, 900] : b.kind === 'spider' ? [520, 900] : b.kind === 'cyberdemon' ? [460, 800] : b.kind === 'undead' ? [170, 300] : [260, 560]; // Revenant: 20 wide, shotgun pellets need it close + const hp0 = p.hp + p.armor * 0.5, boss0 = g.health()[2]; + // Ammo run: when the remaining ammo can no longer finish the bosses with margin, walk to the nearest useful box. + const usesBullets = arms.includes('chaingun'); + const potential = (usesBullets ? p.bullets * 8 : 0) + p.shells * 50 + (arms.includes('rocket') ? p.rockets * 80 : 0); + // A box is worth the walk only when its whole content fits (P_GiveAmmo caps at maxammo; doubled on ITYTD/NM). + const AMMO = { bulletbox: ['bullets', 50, usesBullets], shellbox: ['shells', 20, arms.includes('shotgun')], rocketbox: ['rockets', 5, arms.includes('rocket')] }, dbl = g.skill === SK_BABY || g.skill === SK_NIGHTMARE ? 2 : 1; + const useful = (it, o) => !it.taken && AMMO[it.type] && AMMO[it.type][2] && o[AMMO[it.type][0]] + AMMO[it.type][1] * dbl <= p.max[AMMO[it.type][0]]; + // Arch-Vile scene: hitscan barely lands on a vile that keeps ducking behind pillars, so low rockets alone trigger the run. + const vileLow = !!g.fires && p.rockets < 25 && g.pickups.some(it => it.type === 'rocketbox' && useful(it, p)); + const ammoRun = vileLow || potential < boss0 * 1.3 && g.pickups.some(it => useful(it, p)), ammoPull = vileLow ? 0.3 : potential < boss0 * 0.5 ? 0.3 : 0.12; + const usefulNow = g.pickups.filter(it => useful(it, p)).length; + // Arch-Vile: its flame (A_VileAttack, 66 tics into the attack) only lands if it sees us on that tic, and it stands + // still while casting. So while a cast is pending we head for the nearest floor cell it cannot see; outside a cast + // we stay within a short dash of such a cell. Cells are scored from the vile's current spot. + const vile = g.bosses.find(o => o.kind === 'vile' && o.hp > 0), map = MAPS[g.key]; + // A cheap flame is not worth a 66-tic hide: on ITYTD (half damage) behind blue armor it costs ~21 health. Expected + // health cost of one blast (20 direct + ~62 splash, armor absorbs its share); with health to spare we keep shooting. + const blastDmg = (20 + 62) * (g.skill === SK_BABY ? 0.5 : 1), blastCost = blastDmg - Math.min(p.armor, p.armorType === 2 ? blastDmg / 2 : p.armorType === 1 ? blastDmg / 3 : 0); + const casting = !!vile && vile.mode === 'attack' && vile.attackTick <= SEQ.vile.attack.starts[9] && !(blastCost <= 25 && p.hp > 60); + // Tics until the flame lands. Hiding has to start early: the run speed builds up over ~10 tics and a pillar corner is + // a detour, so the hiding pull grows from the start of the cast and seen-at-blast counts from 40 tics out (the 28-tic + // look-ahead then ends ~12 tics before the flame; 34 was too late, 50 wasted ~16 tics of fire per cast). + const blastIn = casting ? SEQ.vile.attack.starts[9] - vile.attackTick : 99; + let hides = []; + if (vile) for (let cy = 1; cy < map.h - 1; cy++) for (let cx = 1; cx < map.w - 1; cx++) { + const x = cx * 64 + 32, y = cy * 64 + 32; + if (Math.abs(x - p.x) > 768 || Math.abs(y - p.y) > 768 || !g.boxClear(x, y, p.r + 4) || g.sight(vile, { x, y })) continue; + hides.push({ x, y }); + } + const hideDist = q => hides.reduce((m, o) => Math.min(m, Math.hypot(o.x - q.x, o.y - q.y)), 1e9); + let best = MOVES[0], bestScore = -Infinity; + for (const mv of MOVES) { + // Hitscan weapons keep firing through the 28-tic look-ahead (their pain-lock is part of the outcome); rockets do not. + const keys = ['Shift', ...mv, ...fireKeys], scores = []; + // Spider scene: 5 futures instead of LOOK_K (doom-arena@10: at 60 Hz hard deaths 8 -> 2 / 32, damage taken -17%; 4 futures did not help). + for (let k = 0; k < (b && b.kind === 'spider' ? 5 : LOOK_K); k++) scores.push(scoreOf(mv, simulate(g, keys, mouseTick, TT(28), new Set(['Shift', ...mv, ...(p.weapon !== 'rocket' ? fireKeys : [])]), k))); + const score = 0.5 * Math.min(...scores) + 0.5 * scores.reduce((n, x) => n + x, 0) / scores.length; + if (score > bestScore) { bestScore = score; best = mv; } + } + function scoreOf(mv, h) { + const q = h.player, hp1 = q.hp + q.armor * 0.5; + let score = -(hp0 - hp1) * 30 + (boss0 - h.health()[2]) * 0.3; + if (h.outcome === 'loss' || q.hp <= 0) score -= 1e6; + if (h.outcome === 'win') score += 1e5; + if (b) { + const nd = N.distance(q, b); + score -= Math.max(0, band[0] - nd) * 0.6 + Math.max(0, nd - band[1]) * 0.25; + if (b.kind === 'spider' && b.mode === 'attack' && !fire) score -= h.sight(q, b) ? 60 : 0; + // Sight is wanted, except in front of an attacking spider when we cannot answer with hitscan: break line of + // sight behind a pillar, which A_SpidRefire answers by stopping (246/256). Readiness, not the current trigger, + // decides: otherwise a lost sight line (no fire this packet) would forbid ever stepping back into view. The slower + // shotgun (37-tic cycle) trades shots in the open only while health is above 60. With rockets in hand a sight + // line counts only when the 11-unit rocket box clears the pillars too. + const hb = h.bosses[g.bosses.indexOf(b)], hosing = p.weapon !== 'rocket' && p[WINFO[p.weapon].ammo] > 0 && !swap && (p.weapon !== 'shotgun' || p.hp > 60); + if (h.sight(q, b)) score += hb.kind === 'spider' && hb.mode === 'attack' && !hosing ? -120 : p.weapon === 'rocket' && !clearLane(h, q, hb) ? 15 : 60; + } + for (const m of h.projectiles) if (m.owner !== 'player') { const end = { x: m.x + m.vx * 10, y: m.y + m.vy * 10 }; score -= Math.max(0, 90 - N.segmentDistance(q, m, end)) * 3; } + if (vile) { + const hv = h.bosses[g.bosses.indexOf(vile)], seen = hv.hp > 0 && h.sight(hv, q), hd = hideDist(q); + // A rocket leaves 8 tics after the press, from wherever the strafe has taken us: judge the launched rocket. + for (const m of h.projectiles) if (m.owner === 'player' && !g.projectiles.some(o => o.x === m.x && o.y === m.y) && hv.hp > 0) { + const along = (hv.x - m.x) * m.vx / 20 + (hv.y - m.y) * m.vy / 20, wall = h.ray(m.x, m.y, Math.atan2(m.vy, m.vx), Math.max(0, along)).dist; + if (along > 0 && wall < along - hv.r) score -= 120; + } + for (const bl of h.blasts) if (bl.kind === 'rocket' && !g.blasts.some(o => o.x === bl.x && o.y === bl.y) && Math.hypot(bl.x - hv.x, bl.y - hv.y) > hv.r + 40) score -= 120; + if (casting) score -= (seen && blastIn <= 40 ? 400 : 0) + Math.max(0, hd - Math.max(0, blastIn - 35) * 10) * 0.8; + else score -= Math.max(0, hd - 160) * 0.15; + // After the flame (ATK11, 20 tics) and in the chase the vile is harmless: come back into a rocket lane. + if (!casting && hv.hp > 0 && !h.sight(q, hv)) score -= 90; + // ...and the recovery starts on the blast tic: once it has passed, the look-ahead may already end in the next cast, + // so the 'casting' pull above would keep us hidden. Inside ATK11 we only want the lane back. + if (vile.mode === 'attack' && vile.attackTick > SEQ.vile.attack.starts[9] && hv.hp > 0 && !h.sight(q, hv)) score -= 120; + // A rocket of ours that bursts near us inside the look-ahead (strafing into its path, a pillar corner) is scored + // as the splash it will cost, even past the look-ahead's health check (it may land on the last tic). + for (const bl of h.blasts) if (bl.kind === 'rocket' && !g.blasts.some(o => o.x === bl.x && o.y === bl.y) && Math.hypot(bl.x - q.x, bl.y - q.y) < 150) score -= 300; + } + // stay away from walls (rocket splash, getting cornered) + let wallNear = 0; for (const [ox, oy] of [[96, 0], [-96, 0], [0, 96], [0, -96]]) if (h.wall(q.x + ox, q.y + oy)) wallNear++; + score -= wallNear * 18; + if (mv.length) score += 4; + if (ammoRun) { const left = h.pickups.filter(it => useful(it, q) && (!vileLow || it.type === 'rocketbox')), box = left.map(it => N.distance(q, it)).sort((u, v) => u - v)[0]; score += ((vileLow ? g.pickups.filter(it => useful(it, p) && it.type === 'rocketbox').length : usefulNow) - left.length) * 150 - (box === undefined ? 0 : box * ammoPull); } + if (q.hp < 70) { const med = h.pickups.filter(it => !it.taken && (it.type === 'medikit' || it.type === 'stimpack')).map(it => N.distance(q, it)).sort((u, v) => u - v)[0]; if (med !== undefined) score -= med * 0.08; } + return score; + } + // Arch-Vile scene, rockets: a held trigger commits a rocket at A_WeaponReady / A_ReFire that leaves 8 tics later from + // wherever we have strafed to. Play this packet on a copy (our own inputs only) and drop the trigger when a rocket it + // commits would meet a wall well before the vile's *current* spot or pass far wide of it (no look at where the vile + // will be; it walks 15 units a tic, so only gross misses are vetoed). + let holdFire = fire; + if (fire && vile && p.weapon === 'rocket') { + const tg = b; // judged against the current target (the vile or a close imp) + // Only rockets launched inside this packet count (count launches on the copy; rockets already in flight have moved, + // so matching them by position would judge old rockets as new). The first launch is skipped when the current + // press has already committed one (MISSILE1). + const h = blindCopy(g, 0), ks = new Set(['Shift', ...best, 'J']), after = new Set(['Shift', ...best]), launched = []; + let n = 0; + for (let t = 0; t < TT(16) && !h.outcome; t++) { + const before = new Set(h.projectiles), b0 = h.blasts.length; + const rel = t < PKT / 6 && p.attackdown && p.wst === 'MISSILE'; // same release rule as the holds below (the whole first hold set: 2 ticks at 60 Hz) + h.events = []; h.update(t < PKT && !rel ? ks : after, new Set(), [t < PKT ? mouseTick : 0, 0, 0]); N.quantize(h); h.t++; + if (h.events.includes('player_fire:rocket') && n++ >= (p.wst === 'MISSILE1' ? 1 : 0)) launched.push({ q: h.projectiles.find(q => !before.has(q) && q.owner === 'player') || null, b: h.blasts.slice(b0) }); + } + for (const { q: m, b } of launched) { + if (!m) { if (b.some(bl => Math.hypot(bl.x - p.x, bl.y - p.y) < 200 || Math.hypot(bl.x - tg.x, bl.y - tg.y) > tg.r + 60)) holdFire = false; continue; } + if (m.ttl <= 0) { if (Math.hypot(m.x - p.x, m.y - p.y) < 200 || Math.hypot(m.x - tg.x, m.y - tg.y) > tg.r + 60) holdFire = false; continue; } // burst inside the look-ahead + const a = Math.atan2(m.vy, m.vx), ux = Math.cos(a), uy = Math.sin(a), along = (tg.x - m.x) * ux + (tg.y - m.y) * uy, wide = Math.abs(-(tg.x - m.x) * uy + (tg.y - m.y) * ux); + const wallAt = Math.min(...[-11, 0, 11].map(k => h.ray(m.x - uy * k, m.y + ux * k, a, Math.max(0, along)).dist)); // the rocket box is 11 wide + if (along <= 0 || wide > 64 || wallAt < along * 0.67 || wallAt < Math.min(along, 170)) holdFire = false; // never a wall inside our own splash + } + } + const holds = Array.from({ length: 6 }, (_, i) => { + const k = ['Shift', ...best]; + const fire = holdFire; + if (swap && i === 0) k.push(swapKey); + // Hitscan fires on the tic J is seen, so it waits for the turn to converge; A_FireMissile comes 8 tics after the + // press, so rockets hold J from the first hold set (a 2-tic release would trip A_WeaponReady's attackdown rule). + // A trigger still held from another weapon leaves attackdown set, and the launcher never refires on a held + // trigger: release J for the first (one-tic) hold set so A_WeaponReady clears it. + else if (fire && i === 0 && p.weapon === 'rocket' && p.attackdown && p.wst === 'MISSILE') { /* release */ } + else if (fire && (i >= 2 || residual < 0.05 || p.weapon === 'rocket')) k.push('J'); + return k.slice(0, 4); + }); + return { holds, mouse: [dx, 0, 0] }; + }; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/doom_remake/index.html b/environments/games/web/games/doom_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..22dab411a9d66b53e7cc259dfee84c8fc1838386 --- /dev/null +++ b/environments/games/web/games/doom_remake/index.html @@ -0,0 +1,7 @@ + +DOOM · Hell Arena (doom-arena@11)
    +

    DOOM · Hell Arena

    Boss practice arena · Local play · Recording and Replay

    Back to Game Lobby
    +
    Select a boss to start

    Replays save inputs and seeds for deterministic playback and final-state verification. Scripted Demo uses internal state for testing and does not run RL training.

    +
    +
    All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
    + diff --git a/environments/games/web/games/doom_remake/manifest.json b/environments/games/web/games/doom_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..3ee6c2e26e39fb1c9a0ba0aee842c5c9490c5cf4 --- /dev/null +++ b/environments/games/web/games/doom_remake/manifest.json @@ -0,0 +1,31 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "doom_remake", + "module": "DoomGame", + "title": "DOOM: Arena", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "software-raycast", + "rules": "doom-arena@11", + "cases": [ + "doom/cyberdemon", + "doom/barons", + "doom/spider_mastermind", + "doom/archvile", + "doom/mancubus", + "doom/revenant" + ], + "scripts": [ + "_native/runtime.js", + "doom_remake/game.js", + "doom_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "doom_remake/game.js" + ], + "play_page": "web/games/doom_remake/index.html", + "scripted_controller": "DoomGame.scripted(game) -> {holds:[6 key arrays], mouse:[dx,0,0]}; deterministic look-ahead on copies (DoomGame.oracle is an alias)" +} diff --git a/environments/games/web/games/genshin_remake/app3d.js b/environments/games/web/games/genshin_remake/app3d.js new file mode 100644 index 0000000000000000000000000000000000000000..36935539278dc0e33698eaf3a1886353d25a3b65 --- /dev/null +++ b/environments/games/web/games/genshin_remake/app3d.js @@ -0,0 +1,82 @@ +/* Human play and exact native-input recording. Game state is owned by each module. */ +(function () { + 'use strict'; + const N=NativeBench, M=window.GAME_MODULE, $=s=>document.querySelector(s), canvas=$('canvas'), context=canvas.getContext('2d'); + let session=new N.Session(M,M.cases[0].id,1,.5),running=false,last=0,accumulator=0; + const held=new Set(),pointerHeld=new Map(),touchHeld=new Map(); let mouse=[0,0,0],replay=null,replayIndex=0,automatic=false,script=null,scriptTick=0; + const keys={KeyW:'W',KeyA:'A',KeyS:'S',KeyD:'D',Space:'Space',ShiftLeft:'Shift',ShiftRight:'Shift',KeyJ:'J',KeyK:'K',KeyL:'L',KeyQ:'Q',KeyE:'E',KeyR:'R',ArrowUp:'W',ArrowDown:'S',ArrowLeft:'A',ArrowRight:'D'}; + document.body.dataset.game=M.id; + // Public difficulty = three tiers (2026-11-02): rebuilt from Module.tiers when the game declares it. + if(M.tiers&&$('#difficulty')){const sel=$('#difficulty'),names={easy:'Easy',normal:'Normal',hard:'Hard'};sel.textContent=''; + for(const t of ['easy','normal','hard']){const op=document.createElement('option');op.value=String(M.tiers[t]);op.textContent=names[t]+' (d='+M.tiers[t]+')';if(t==='normal')op.selected=true;sel.append(op);}} + for(const def of M.cases){const option=document.createElement('option');option.value=def.id;option.textContent=def.name;$('#case').append(option);} + const controls=Array.isArray(M.controls)?M.controls.map(value=>['',value]):Object.entries(M.controls); + for(const [key,value]of controls){const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=key;dd.textContent=value;$('dl').append(dt,dd);} + function status(value){$('#status').textContent=value;} + function clear(){held.clear();pointerHeld.clear();touchHeld.clear();mouse=[0,0,0];accumulator=0;} + function inputKeys(){return [...new Set([...held,...[...pointerHeld.values()].flatMap(keys=>[...keys]),...touchHeld.values()])].filter(key=>N.keys.includes(key)).slice(0,4);} + function draw(){ + M.draw(session.game,context); + $('#pause').textContent=running?'Pause':'Resume'; + $('#overlay').hidden=running&&!session.game.outcome; + $('#overlay strong').textContent=session.game.outcome?{win:'Challenge Complete',loss:'Challenge Failed',timeout:'Time up'}[session.game.outcome]:replay?'Replay · Paused':session.game.t?'Paused':'Are You Ready?'; + $('#overlay span').textContent=session.game.outcome?'Restart the challenge or export the current replay':session.game.t?(replay||automatic?'Click Resume to return to battle':'Click the screen to resume and lock the mouse (this click does not attack), or click Resume'):'Click Start Challenge; in battle, click the screen to lock the mouse and move it to turn the camera'; + } + function reset(id,seed,difficulty){running=false;automatic=false;replay=null;script=null;scriptTick=0;clear();session=new N.Session(M,id,seed,difficulty);draw();return session.snapshot();} + window.nativeAPI={reset,packet(packet){if(running)throw Error('Pause before a scripted packet');const value=session.packet(packet);draw();return value;}, + state(){return session.snapshot();},recording(){return session.export();}, + render(){draw();return canvas.toDataURL('image/png');}, + renderMetrics(){return M.renderMetrics?M.renderMetrics(context):{};}, + module(){return {id:M.id,hz:M.hz,version:M.version,cases:M.cases};}}; + // genshin-bosses@7: mouse-look as on PC. A click on the running canvas asks for pointer lock (the click is the user gesture the + // browser needs, and it still counts as LMB); once locked every mouse move turns the camera and LMB / RMB keep their game meaning. + // Start and Continue do not lock: a locked pointer sends every click to the canvas, so the toolbar could not be clicked until Esc + // Esc, window blur, and the end of the fight + // and an error release the pointer and pause, each leaving a status that says so. A click on the paused canvas resumes and locks + // again without attacking. Dragging with a button held still turns the camera when the browser refuses the lock. + const locked=()=>document.pointerLockElement===canvas; + function lockPointer(){if(locked()||!canvas.requestPointerLock)return;try{const r=canvas.requestPointerLock();if(r&&r.catch)r.catch(()=>status('Pointer lock is unavailable: hold a mouse button and drag to turn the camera'));}catch(error){}} + function playing(){return running&&!replay&&!automatic&&!session.game.outcome;} + document.addEventListener('pointerlockchange',()=>{if(locked()){if(running)status('Mouse locked · Press Esc to unlock');}else if(playing()){running=false;clear();status('Mouse unlocked · Battle paused · Click the screen to resume');draw();}}); + function start(useScript){try{reset($('#case').value,Number($('#seed').value),Number($('#difficulty').value));automatic=useScript;running=true;status(useScript?'Verify Script is running':'Battle started · Recording this match · Click the screen to lock the mouse; move it to turn the camera');canvas.focus();draw();}catch(error){status(error.message);}} + $('#start').onclick=()=>start(false);$('#demo').onclick=()=>start(true); + $('#pause').onclick=()=>{if(session.game.outcome)return;running=!running;clear();if(running){canvas.focus();if(!replay&&!automatic)status('Battle resumed · Click the screen to lock the mouse; move it to turn the camera');}else{if(locked())document.exitPointerLock();status(replay||automatic?'Paused · Click Resume':'Paused · Click the screen to resume');}draw();}; + $('#step').onclick=()=>{running=false;if(replay)replayTick();else session.tick();draw();}; + function openReplay(data){N.Session.import(M,data);reset(data.case,data.seed,data.difficulty);replay=data;replayIndex=0;running=true;$('#case').value=data.case;status('Replay validated · Playing');draw();} + function replayTick(){if(replayIndex{const data=session.export(),url=URL.createObjectURL(new Blob([JSON.stringify(data)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=M.id+'-'+session.seed+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status('Current replay exported');}; + $('#import').onclick=()=>$('#file').click();$('#file').onchange=async event=>{const file=event.target.files[0];if(!file)return;try{if(file.size>12e6)throw Error('Replay file is too large');openReplay(JSON.parse(await file.text()));}catch(error){status('Import failed: '+error.message);}event.target.value='';}; + function release(){clear();if(locked())document.exitPointerLock();if(running){running=false;status('Window lost focus · Battle paused');}draw();} + window.addEventListener('blur',release);document.addEventListener('visibilitychange',()=>{if(document.hidden)release();}); + window.addEventListener('keydown',event=>{if(['INPUT','SELECT','BUTTON'].includes(document.activeElement.tagName))return;if(keys[event.code]){event.preventDefault();held.add(keys[event.code]);}if(event.code==='Escape'){const paused=running&&!session.game.outcome;running=false;clear();if(locked())document.exitPointerLock(); + // The keydown pauses before pointerlockchange fires, so that handler no longer sees a running fight: say so here. + if(paused)status(replay||automatic?'Paused (Esc) · Click Resume':'Paused (Esc) · Click the screen to resume and lock the mouse');draw();}}); + window.addEventListener('keyup',event=>{if(keys[event.code]){event.preventDefault();held.delete(keys[event.code]);}}); + canvas.oncontextmenu=event=>event.preventDefault();canvas.onpointerdown=event=>{if(event.button!==0&&event.button!==2)return;canvas.focus(); + // A click on the paused canvas resumes the fight and locks the pointer again; that click is not an attack. + if(!locked()&&!running&&!automatic&&!replay&&!session.game.outcome&&session.game.t>0){lockPointer();running=true;clear();status('Battle resumed');draw();return;} + if(playing()&&!locked())lockPointer();const keys=pointerHeld.get(event.pointerId)||new Set();keys.add(event.button===2?'RMB':'LMB');pointerHeld.set(event.pointerId,keys);}; + // Pointer Events emits pointerup only after the final mouse button is released. + // pointermove carries changes to the button mask for chorded mouse presses. + function syncMouse(event){if(event.pointerType==='mouse'&&pointerHeld.has(event.pointerId)){const keys=new Set();if(event.buttons&1)keys.add('LMB');if(event.buttons&2)keys.add('RMB');if(keys.size)pointerHeld.set(event.pointerId,keys);else pointerHeld.delete(event.pointerId);}} + window.addEventListener('pointermove',syncMouse); + window.addEventListener('pointerup',event=>{if(event.pointerType==='mouse')syncMouse(event);else pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + window.addEventListener('pointercancel',event=>{pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + canvas.onpointermove=event=>{if(event.buttons||document.pointerLockElement===canvas){mouse[0]+=event.movementX;mouse[1]+=event.movementY;}}; + canvas.onwheel=event=>{event.preventDefault();mouse[2]+=Math.sign(event.deltaY);}; + canvas.ondblclick=()=>{if(playing())lockPointer();}; + // Pointer capture is refused while the mouse pointer is locked (Pointer Events: InvalidStateError), so a touch key must not depend on + // it; without capture the window pointerup / pointercancel listeners above still release the key. + document.querySelectorAll('[data-key]').forEach(button=>{button.onpointerdown=event=>{event.preventDefault();try{button.setPointerCapture(event.pointerId);}catch(error){}touchHeld.set(event.pointerId,button.dataset.key);};button.onpointerup=button.onpointercancel=event=>touchHeld.delete(event.pointerId);}); + function frame(now){const delta=Math.min(.1,(now-last)/1000||0);last=now;const beforeTick=session.game.t,wasRunning=running;try{ + if(running&&!session.game.outcome){accumulator+=delta;while(accumulator>=1/M.hz&&running&&!session.game.outcome){accumulator-=1/M.hz; + if(replay)replayTick();else if(automatic){const count=M.hz/5;if(scriptTick===0)script=(M.scripted||M.oracle).call(M,session.game);const sub=Math.ceil((scriptTick+1)*6/count)-1;session.tick(script.holds[sub],script.mouse.map(value=>value/count));scriptTick=(scriptTick+1)%count;} + else{session.tick(inputKeys(),mouse.map((value,index)=>N.clamp(value,index===2?-5:-1000,index===2?5:1000)));mouse=[0,0,0];}} + if(session.game.outcome){running=false;if(locked())document.exitPointerLock();status({win:'Challenge Complete',loss:'Challenge Failed',timeout:'Challenge Timed Out'}[session.game.outcome]+' · You can export or replay this match');}} + if(session.game.t!==beforeTick||running!==wasRunning)draw(); + }catch(error){running=false;clear();if(locked())document.exitPointerLock();status('Runtime error: '+error.message);$('#overlay').hidden=false;$('#overlay strong').textContent='Cannot resume now';$('#overlay span').textContent=error.message;} + requestAnimationFrame(frame); + } + window.addEventListener('pagehide',()=>M.closeRenderer?.(context)); + draw();requestAnimationFrame(frame); +})(); diff --git a/environments/games/web/games/genshin_remake/art_expansion.js b/environments/games/web/games/genshin_remake/art_expansion.js new file mode 100644 index 0000000000000000000000000000000000000000..8a9e9fbadcdb59c63bfb3f5a7dfb5b67e429245a --- /dev/null +++ b/environments/games/web/games/genshin_remake/art_expansion.js @@ -0,0 +1,264 @@ +/* Original procedural art for the expansion bosses (Maguu Kenki, Andrius, La Signora). Registers arena plugins with the + * shared renderer3d.js; like every renderer code path it only reads game state and never consumes game RNG. */ +(function(root){ + 'use strict'; + const B=root.Boss3D;if(!B||!B.registerArena)return; + const PI=Math.PI,TAU=PI*2,clamp=(x,a,b)=>Math.max(a,Math.min(b,x)),items=a=>Array.isArray(a)?a:[],ease=t=>{t=clamp(t,0,1);return t*t*(3-2*t);}; + const EC={pyro:0xff7a3d,cryo:0x9fe6ff,hydro:0x4fb4ff,electro:0xc28cff,anemo:0x6fe0c0,physical:0xf6ecd6}; + function groundDisc(S,th,T,r,color,y=0,mapTex){const m=S.mesh(S.keep(new T.CircleGeometry(r,72)),S.keep(new T.MeshLambertMaterial({color,map:mapTex||null})),th.group);m.rotation.x=-PI/2;m.position.y=y;m.receiveShadow=true;return m;} + function canvasTex(T,w,h,draw){const c=document.createElement('canvas');c.width=w;c.height=h;draw(c.getContext('2d'),w,h);const t=new T.CanvasTexture(c);t.colorSpace=T.SRGBColorSpace;return t;} + function noise(n){let x=Math.imul((n|0)^0x9e3779b9,0x85ebca6b);x^=x>>>13;x=Math.imul(x,0xc2b2ae35);x^=x>>>16;return (x>>>0)/4294967296;} + // Attack effects of the expansion bosses. Plugins own these pools: drawWorld resets the shared ring and shard pools every frame. + function fxPools(S,T,th){const geo=S.keep(new T.RingGeometry(.74,1,32,1,PI/2-1.15,2.3));geo.rotateX(PI/2); + th.fxArc=S.pool(geo,S.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:.8,side:T.DoubleSide,depthWrite:false,blending:T.AdditiveBlending})),12,th.group); + th.fxRing=S.pool(S.geo.ring,S.mat.addSolid,14,th.group);th.fxShard=S.pool(S.geo.oct,S.mat.addSolid,64,th.group);} + function fxPass(S,g,th){let arc=0,ring=0,sh=0;const AIR=1.15,ICE=0xbfeaff; + const sweep=(x,z,r,a,c,y=AIR)=>{arc=S.place(th.fxArc,arc,[x,y,z],[r,1,r],[0,a,0],c);},burst=(x,z,r,u,c,n,up=1.5)=>{ring=S.place(th.fxRing,ring,[x,.12,z],[r*(.35+.65*u),r*(.35+.65*u),1],[-PI/2,0,0],c); + for(let i=0;iid==='genshin/maguu_kenki',camera:{d:7.8,h:3.8,look:1.2,lim:17.5},light:{hemi:1.4,sun:2.1}, + build(S,th,K){const {T,G,Build}=K; + S.sky(th,['#3b6fa8','#9cc2e0','#f2ddc4'],[0xd8d2c4,34,130],{cloudColor:0xfff6ee,sunColor:0xffe2b8}); + const tex=canvasTex(T,1024,1024,(q,w,h)=>{const cx=w/2;q.fillStyle='#b7ab92';q.fillRect(0,0,w,h); + for(let i=0;i<9000;i++){const x=noise(i*3)*w,y=noise(i*3+1)*h,r=1+noise(i*3+2)*2.4,v=noise(i*7);q.fillStyle=v>.6?'rgba(240,232,214,.55)':v>.3?'rgba(150,140,118,.45)':'rgba(120,112,96,.35)';q.beginPath();q.arc(x,y,r,0,TAU);q.fill();} + // Raked gravel rings around the centre stone and a stepping-stone path (karesansui, original layout). + q.strokeStyle='rgba(246,240,226,.55)';q.lineWidth=3;for(let r=60;r(parts[bone]||(parts[bone]=new Build())).add(geo,c,pos,rot,scale); + const lac=0x2e3a4a,trim=0xc9a45c,cloth=0x6a2c34,metal=0x8c96a4; + add('chest',G.lathe([[.2,0],[.26,.18],[.3,.42],[.26,.6],[.12,.7]],10),lac,[0,0,0]);add('chest',G.box(),trim,[0,.35,.2],[0,0,0],[.36,.08,.06]); + for(const s of [-1,1]){add('chest',G.sphere(8,6),metal,[s*.34,.6,0],[0,0,0],[.2,.16,.2]);add('chest',G.box(),lac,[s*.36,.52,0],[0,0,s*.3],[.3,.06,.28]);} + add('hips',G.lathe([[.22,0],[.34,-.25],[.4,-.55],[.0,-.55]],10),cloth,[0,0,0]);add('hips',G.box(),trim,[0,0,0],[0,0,0],[.5,.06,.36]); + add('head',G.sphere(10,8),0x30302e,[0,.12,0],[0,0,0],[.17,.19,.17]);add('head',G.cone(6),0x262626,[0,.38,-.02],[0,0,0],[.06,.22,.06]); + add('mask',G.sphere(10,8),0xe8e2d4,[0,.12,.1],[0,0,0],[.16,.18,.08]);for(const s of [-1,1]){add('mask',G.cone(5),0xd0c8b4,[s*.1,.32,.08],[0,0,s*-.35],[.035,.16,.035]);add('mask',G.box(),0xb8342a,[s*.06,.15,.18],[0,0,s*.2],[.06,.02,.02]);} + for(const side of ['L','R']){add('arm'+side,G.cap(.06,.26,8),lac,[0,-.18,0]);add('fore'+side,G.cap(.055,.22,8),metal,[0,-.15,0]);add('fore'+side,G.sphere(8,6),0x2a2a2a,[0,-.34,0],[0,0,0],[.07,.08,.07]); + add('leg'+side,G.cap(.08,.34,8),cloth,[0,-.24,0]);add('shin'+side,G.cap(.065,.34,8),lac,[0,-.24,0]);add('shin'+side,G.box(),0x2a2a2a,[0,-.5,.06],[0,0,0],[.15,.08,.3]);} + add('sword',G.box(),0xe6eef4,[0,0,.62],[0,0,0],[.035,.012,1.1]);add('sword',G.box(),trim,[0,0,.06],[0,0,0],[.14,.04,.05]);add('sword',G.cyl(1,1,6),0x3a2a22,[0,0,-.08],[PI/2,0,0],[.022,.2,.022]); + const layout=[['hips',null,[0,1.02,0]],['chest','hips',[0,.04,0]],['head','chest',[0,.74,0]],['mask','head',[0,0,0]], + ['armL','chest',[.34,.58,0]],['foreL','armL',[0,-.38,0]],['armR','chest',[-.34,.58,0]],['foreR','armR',[0,-.38,0]], + ['legL','hips',[.14,-.06,0]],['shinL','legL',[0,-.48,0]],['legR','hips',[-.14,-.06,0]],['shinR','legR',[0,-.48,0]],['sword','foreR',[0,-.34,.04]]]; + th.kenki=S.rig(parts,layout,S.mat.outline,true,th.group);th.kenki.root.scale.setScalar(1.25); + th.shadow=S.rig(parts,layout,null,false,th.group);th.shadow.root.scale.setScalar(1.25); + th.shadowMat={anemo:S.keep(new T.MeshBasicMaterial({color:0x7fe8c8,transparent:true,opacity:.42,depthWrite:false,blending:T.AdditiveBlending})),cryo:S.keep(new T.MeshBasicMaterial({color:0xa8e6ff,transparent:true,opacity:.42,depthWrite:false,blending:T.AdditiveBlending}))}; + th.shadow.root.traverse(o=>{if(o.isMesh)o.material=th.shadowMat.anemo;}); + fxPools(S,T,th); + th.oni=S.mesh(S.keep(new T.SphereGeometry(1,16,10,0,TAU,0,PI*.55)),S.keep(new T.MeshToonMaterial({color:0xd8463a,gradientMap:S.mat.toon.gradientMap,side:T.DoubleSide})),th.group); + th.oniHorn=S.pool(S.geo.cone,S.keep(new T.MeshToonMaterial({color:0xf2e8d4,gradientMap:S.mat.toon.gradientMap})),4,th.group); + th.after=S.pool(S.geo.box,S.keep(new T.MeshBasicMaterial({color:0x8fe8d0,transparent:true,opacity:.28,depthWrite:false})),12,th.group); + }, + draw(S,g,th){ + const b=g.boss||{},r=th.kenki,bn=r.bones,tm=g.t/60,move=b.move,mode=b.mode,t=b.moveTick||0,tell=b.tellTicks||0; + S.resetRig(r);r.root.scale.setScalar(1.25);r.root.position.set(b.x||0,b.y||0,b.z||0);r.root.rotation.y=b.yaw||0; + const walk=mode==='idle'&&b.action==='walk',ph=(b.walk||0)*3; + bn.legL.rotation.x=walk?-Math.sin(ph)*.5:.05;bn.legR.rotation.x=walk?Math.sin(ph)*.5:-.05;bn.shinL.rotation.x=walk?Math.max(0,Math.sin(ph+1))*.6:.1;bn.shinR.rotation.x=walk?Math.max(0,-Math.sin(ph+1))*.6:.1; + // Iai stance by default: sword low at the hip, left hand on the scabbard side. + bn.armR.rotation.set(-.3,0,-.3);bn.foreR.rotation.x=-.9;bn.sword.rotation.set(.5,0,0);bn.armL.rotation.set(-.4,0,.4);bn.foreL.rotation.x=-.8;bn.chest.rotation.y=.3; + const k=tell?clamp(t/tell,0,1):1; + if(mode==='attack'&&(move==='ichimonji'||move==='shadowIchimonji')){const gap=20,s=Math.max(0,t-tell)%gap,u=ease(s/8),side=Math.floor(Math.max(0,t-tell)/gap)%2?1:-1; + if(ttell)bn.hips.position.y-=.4;} + if(mode==='attack'&&(move==='pushMask'||move==='explodeMask')){bn.armL.rotation.set(-1.6,0,.2);bn.foreL.rotation.x=0;} + if(mode==='taunt'){bn.armL.rotation.set(-2.6,0,.4);bn.foreL.rotation.x=-1.2;bn.chest.rotation.x=-.15;bn.head.rotation.x=-.3;} + if(mode==='dead'){const u=ease((b.actionTick||0)/50);bn.hips.position.y-=.5*u;bn.legL.rotation.x=-1.2*u;bn.legR.rotation.x=-1.2*u;bn.shinL.rotation.x=1.6*u;bn.shinR.rotation.x=1.6*u;bn.chest.rotation.x=.9*u;} + // Shadow sword: an afterimage at the remembered spot (Anemo green / Cryo blue). + const sh=th.shadow;sh.root.visible=!!(b.shadow||mode==='attack'&&move==='shadowIchimonji'); + if(sh.root.visible){S.resetRig(sh);sh.root.scale.setScalar(1.25);const at=b.shadow||{x:(b.x||0)-Math.sin(b.yaw||0)*.6,z:(b.z||0)-Math.cos(b.yaw||0)*.6},el=b.shadow?b.shadow.el:b.shadowEl||'anemo'; + sh.root.position.set(at.x,0,at.z);sh.root.rotation.y=b.yaw||0;sh.root.traverse(o=>{if(o.isMesh)o.material=th.shadowMat[el]||th.shadowMat.anemo;}); + sh.bones.armR.rotation.set(-1.5,Math.sin(tm*8),-.2);sh.bones.chest.rotation.y=-Math.sin(tm*8)*.6;} + // Oni mask parry and the oni masks of Pushing / Exploding Mask. + th.oni.visible=(b.mask||0)>0;if(th.oni.visible){const a=angle2(b,g.player),fx=Math.sin(a),fz=Math.cos(a),u=(b.mask||0)/24;th.oni.position.set((b.x||0)+fx*1.1,1.6,(b.z||0)+fz*1.1);th.oni.rotation.set(-PI/2,0,0);th.oni.lookAt((b.x||0)+fx*3,1.6,(b.z||0)+fz*3);th.oni.rotateX(-PI/2);th.oni.scale.setScalar(.6+.25*u);} + let hn=0,af=0;for(const h of items(g.hazards)){ + if(h.mask&&h.age>=(h.delay||0)){const a=Math.atan2(h.vx||0,h.vz||0);S._gi=S.glow(S._gi,h.x,1.3,h.z,2.2,0x7fe8c8);hn=S.place(th.oniHorn,hn,[h.x+Math.cos(a)*.5,1.9,h.z-Math.sin(a)*.5],[.12,.4,.12],[0,0,-.3],null);hn=S.place(th.oniHorn,hn,[h.x-Math.cos(a)*.5,1.9,h.z+Math.sin(a)*.5],[.12,.4,.12],[0,0,.3],null);} + if(h.maskBomb){const u=clamp((h.age||0)/(h.delay||1),0,1);S._gi=S.glow(S._gi,h.x,1+u*.5,h.z,1.4+u*1.6,0x9fe6ff);} + if(h.blade){S._gi=S.glow(S._gi,h.x,1,h.z,1.6,0x7fe8c8);S._gi=S.glow(S._gi,h.x-(h.vx||0)*4,1,h.z-(h.vz||0)*4,1.1,0x5fd0b0);} + if(h.shadow&&h.ageu>.7?0xff5a3a:0xffb070,yaw=b.yaw||0; + if((move==='ichimonji'||move==='shadowIchimonji')&&t.7?0xff5a3a:0xffb070); + fxPass(S,g,th); + }}); + function angle2(a,b){return Math.atan2((b.x||0)-(a.x||0),(b.z||0)-(a.z||0));} + // ------------------------------------------------------------------------------------------- Andrius: snowy wolf arena + B.registerArena('wolvendom',{match:id=>id==='genshin/andrius',camera:{d:8.4,h:4.3,look:1.4,lim:19},light:{hemi:1.5,sun:1.9}, + build(S,th,K){const {T,G,Build}=K; + S.sky(th,['#5a7fa8','#b9cfe0','#eef2f4'],[0xdfe6ec,30,120],{cloudColor:0xf4f8fb,sunColor:0xf6f0e0}); + const tex=canvasTex(T,1024,1024,(q,w,h)=>{const cx=w/2;q.fillStyle='#dfe6ec';q.fillRect(0,0,w,h); + for(let i=0;i<7000;i++){const x=noise(i*5)*w,y=noise(i*5+1)*h,r=1+noise(i*5+2)*3,v=noise(i*11);q.fillStyle=v>.55?'rgba(255,255,255,.7)':'rgba(170,186,200,.35)';q.beginPath();q.arc(x,y,r,0,TAU);q.fill();} + q.strokeStyle='rgba(120,150,176,.4)';q.lineWidth=5;q.beginPath();q.arc(cx,cx,cx*.94,0,TAU);q.stroke(); + q.strokeStyle='rgba(160,190,214,.45)';q.lineWidth=3;for(let i=0;i<6;i++){const a=i*TAU/6;q.beginPath();q.moveTo(cx,cx);q.lineTo(cx+Math.cos(a)*cx*.9,cx+Math.sin(a)*cx*.9);q.stroke();} + const e=q.createRadialGradient(cx,cx,cx*.86,cx,cx,cx);e.addColorStop(0,'rgba(0,0,0,0)');e.addColorStop(1,'rgba(70,90,110,.35)');q.fillStyle=e;q.fillRect(0,0,w,h);}); + S.keep(tex);groundDisc(S,th,T,17.4,0xffffff,.01,tex);groundDisc(S,th,T,80,0xc9d6de,-.05); + const rock=new Build(),pine=new Build(),ruin=new Build(); + // Ring of stone pillars (wolf statues reduced to cairns), snowy pines and grey cliffs (original layout). + for(let i=0;i<12;i++){const a=i*TAU/12,r=19.2,x=Math.sin(a)*r,z=Math.cos(a)*r,h=2.2+noise(i)*2.6;ruin.add(G.bevel(),0x8a96a2,[x,h/2,z],[0,a,(noise(i+5)-.5)*.2],[1.1,h,1.1]);ruin.add(G.bevel(),0xf2f6f8,[x,h+.12,z],[0,a,0],[1.3,.3,1.3]);} + for(let i=0;i<30;i++){const a=i*2.4+.2,r=24+noise(i*3)*24,x=Math.sin(a)*r,z=Math.cos(a)*r,h=4+noise(i*7)*4;pine.add(G.cyl(.7,1,6),0x4a3a30,[x,h*.25,z],[0,0,0],[.3,h*.5,.3]); + for(let k=0;k<3;k++)pine.add(G.cone(7),[0x34584a,0x2e5044,0x3c6252][k],[x,h*.4+k*h*.22,z],[0,k,0],[1.9-k*.45,h*.42,1.9-k*.45]);pine.add(G.cone(7),0xf4f8fa,[x,h*.92,z],[0,0,0],[.7,h*.2,.7]);} + for(let i=0;i<16;i++){const a=i*TAU/16+noise(i)*.2,r=58+noise(i+3)*16;rock.add(G.sphere(9,6),[0x8e9aa6,0x9aa6b0,0x7e8a96][i%3],[Math.sin(a)*r,-2,Math.cos(a)*r],[0,a,0],[14+noise(i)*10,10+noise(i+1)*12,10]);rock.add(G.sphere(9,6),0xf2f6f8,[Math.sin(a)*r,4+noise(i+1)*6,Math.cos(a)*r],[0,a,0],[9,3,7]);} + for(const b of [rock,pine,ruin])S.props(th,b); + // Andrius: an original ice-and-wind wolf (no game model): long muzzle, tall ears, heavy mane, crystals along the spine. + // Bones: body / neck / head / tail / four legs. + const parts={},add=(bone,geo,c,pos,rot,scale)=>(parts[bone]||(parts[bone]=new Build())).add(geo,c,pos,rot,scale); + const fur=0xbcd6e6,pale=0xe8f3fa,deep=0x6f8fa8,dark=0x3e5266,ice=0x9fe8ff; + add('body',G.sphere(12,8),fur,[0,.05,.72],[0,0,0],[.62,.78,.85]);add('body',G.sphere(12,8),fur,[0,.02,-.1],[0,0,0],[.5,.6,1.1]);add('body',G.sphere(12,8),fur,[0,.1,-.85],[0,0,0],[.58,.68,.72]); + add('body',G.sphere(10,6),deep,[0,.5,-.15],[0,0,0],[.26,.18,1.2]);add('body',G.sphere(10,6),pale,[0,-.28,.15],[0,0,0],[.42,.38,1.05]); + for(let i=0;i<12;i++){const a=i*TAU/12,x=Math.sin(a)*.6,y=Math.cos(a)*.66;add('body',G.cone(5),i%2?pale:fur,[x,.1+y,.55],[-PI/2+y*.25,0,-x*.5],[.17,.82,.15]);} + for(let i=0;i<5;i++)add('body',G.oct(),ice,[0,.7-Math.abs(i-1)*.06,.6-i*.42],[0,i,0],[.1,.3-i*.03,.14]); + add('neck',G.cyl(.36,.54,8),fur,[0,.12,.28],[1,0,0],[1,1.15,1]);for(let i=0;i<9;i++){const a=i*TAU/9,x=Math.sin(a)*.42,y=Math.cos(a)*.42;add('neck',G.cone(5),i%2?fur:pale,[x,.2+y,.2],[-PI/2+y*.3,0,-x*.5],[.14,.7,.12]);} + add('head',G.sphere(10,8),fur,[0,0,0],[0,0,0],[.36,.33,.46]);add('head',G.cyl(.56,1,6),pale,[0,-.07,.55],[PI/2,0,0],[.2,.66,.15]);add('head',G.sphere(8,6),dark,[0,-.03,.9],[0,0,0],[.075,.06,.06]); + add('head',G.box(),deep,[0,-.17,.44],[.06,0,0],[.2,.05,.52]);for(const s of [-1,1]){add('head',G.cone(5),0xffffff,[s*.08,-.2,.66],[PI,0,0],[.022,.09,.022]); + add('head',G.cone(4),fur,[s*.23,.4,-.12],[-.18,0,s*-.2],[.12,.46,.09]);add('head',G.cone(4),dark,[s*.23,.37,-.09],[-.18,0,s*-.2],[.06,.3,.04]); + add('head',G.sphere(6,5),0xdffcff,[s*.2,.08,.3],[0,0,0],[.055,.03,.04]);add('head',G.box(),dark,[s*.17,.16,.31],[0,0,s*-.42],[.17,.035,.1]); + add('head',G.cone(5),pale,[s*.34,-.08,-.1],[-PI/2,0,s*-.7],[.11,.42,.09]);} + add('tail',G.sphere(10,7),fur,[0,0,-.75],[0,0,0],[.2,.2,.85]);add('tail',G.cone(7),pale,[0,-.08,-1.75],[-PI/2-.1,0,0],[.21,.82,.2]);add('tail',G.oct(),ice,[0,.16,-.9],[0,0,0],[.07,.18,.1]); + for(const leg of ['legFL','legFR','legBL','legBR']){add(leg,G.cap(.17,.5,8),fur,[0,-.36,0]);add(leg,G.cap(.095,.52,8),pale,[0,-.92,.03]);add(leg,G.sphere(8,6),deep,[0,-1.3,.1],[0,0,0],[.16,.09,.25]);for(let i=-1;i<=1;i++)add(leg,G.cone(4),dark,[i*.08,-1.33,.3],[PI/2,0,0],[.03,.1,.03]);} + const layout=[['body',null,[0,1.75,0]],['neck','body',[0,.4,1.1]],['head','neck',[0,.42,.72]],['tail','body',[0,.3,-1.32]], + ['legFL','body',[.42,-.36,.92]],['legFR','body',[-.42,-.36,.92]],['legBL','body',[.4,-.36,-.98]],['legBR','body',[-.4,-.36,-.98]]]; + th.wolf=S.rig(parts,layout,S.mat.outline,true,th.group);th.wolf.root.scale.setScalar(1.3); + const iceMat=S.keep(new T.MeshStandardMaterial({vertexColors:true,emissive:0x4fa8e0,emissiveIntensity:.42,roughness:.15,metalness:.1,flatShading:true})); + const crystal=new Build();crystal.add(G.cyl(.14,.8,6),0xd6f4ff,[0,1.9,0],[0,.3,0],[1,3.8,1]).add(G.cyl(.1,.5,5),0xbfeaff,[.62,1.1,.2],[0,.8,-.28],[1,2.4,1]).add(G.cyl(.08,.46,5),0xcdefff,[-.5,.95,-.32],[.2,.2,.3],[1,2,1]).add(G.cyl(.06,.36,5),0xa8e2ff,[-.1,.6,.62],[-.34,0,0],[1,1.3,1]); + th.pillars=S.pool(S.keep(crystal.build()),iceMat,6,th.group);th.pillars.castShadow=true;fxPools(S,T,th); + th.wolves=S.pool(S.keep(new Build().add(G.sphere(10,7),0xbfe8ff,[0,.55,0],[0,0,0],[.32,.32,.62]).add(G.sphere(8,6),0xd8f2ff,[0,.75,.55],[0,0,0],[.22,.22,.28]).add(G.cone(6),0xd8f2ff,[0,.4,-.6],[-2.2,0,0],[.12,.5,.12]).build()),S.mat.water,8,th.group); + th.storm=S.pool(S.keep(new T.CylinderGeometry(1,1.4,1,14,1,true)),S.keep(new T.MeshBasicMaterial({color:0xcff2ff,transparent:true,opacity:.07,side:T.DoubleSide,depthWrite:false,blending:T.AdditiveBlending})),2,th.group); + }, + draw(S,g,th){ + const b=g.boss||{},r=th.wolf,bn=r.bones,tm=g.t/60,move=b.move,mode=b.mode,t=b.moveTick||0,tell=b.tellTicks||0,k=tell?clamp(t/tell,0,1):1; + S.resetRig(r);r.root.scale.setScalar(1.3);r.root.position.set(b.x||0,b.y||0,b.z||0);r.root.rotation.y=b.yaw||0; + const run=mode==='interlude'||b.action==='walk'||b.action==='run'||mode==='attack'&&move==='charge'&&t>=tell,ph=tm*(run?11:2); + const A=run?.7:.08;bn.legFL.rotation.x=Math.sin(ph)*A;bn.legBR.rotation.x=Math.sin(ph)*A;bn.legFR.rotation.x=-Math.sin(ph)*A;bn.legBL.rotation.x=-Math.sin(ph)*A; + bn.body.position.y+=Math.abs(Math.sin(ph))*(run?.15:.03);bn.tail.rotation.x=.18+Math.sin(tm*3)*.14;bn.tail.rotation.y=Math.sin(tm*1.7)*.22;bn.neck.rotation.x=run?.35:.1;bn.head.rotation.x=.12+Math.sin(tm*1.5)*.05; + if(mode==='attack'&&move==='slash'){if(t=tell)r.root.rotation.y+=ease((t-tell)/14)*TAU; + if(mode==='attack'&&(move==='leap'||move==='charge')&&t=tell){const u=((t-tell)%40)/40;sn=S.place(th.storm,sn,[b.x,2,b.z],[3+u*12,4,3+u*12],[0,tm*2,0],null);} + S.finish(th.storm,sn); + for(const h of items(g.hazards)){if(h.trail&&h.ageu>.7?0xff5a3a:0xffb070,yaw=b.yaw||0; + if(move==='slash'&&t.7?0xff5a3a:0xffb070; + S.surfaceTriangle([b.x+sx,b.z+sz],[ex+sx,ez+sz],[ex-sx,ez-sz],c);S.surfaceTriangle([b.x+sx,b.z+sz],[ex-sx,ez-sz],[b.x-sx,b.z-sz],c);} + fxPass(S,g,th); + }}); + // ------------------------------------------------------------------------------------------- La Signora: palace hall + B.registerArena('palace',{match:id=>id==='genshin/signora',camera:{d:8.2,h:4.2,look:1.3,lim:18.4},light:{hemi:1.35,sun:1.8}, + build(S,th,K){const {T,G,Build}=K; + S.sky(th,['#2a2440','#6a4a6a','#d89a7a'],[0x6a5466,30,110],{cloudColor:0xe8c0b8,cloudOpacity:.5,sunColor:0xffb890}); + const tex=canvasTex(T,1024,1024,(q,w,h)=>{const cx=w/2;q.fillStyle='#3a3048';q.fillRect(0,0,w,h);const n=16;for(let i=0;i(parts[bone]||(parts[bone]=new Build())).add(geo,c,pos,rot,scale); + const coat=0xe8eef6,dark=0x2c2a3a,gold2=0xd6b46a,skin=0xf4dccc,hair=0xf2e2b8; + add('chest',G.lathe([[.14,0],[.17,.2],[.19,.38],[.15,.5],[.06,.56]],10),coat,[0,0,0]);add('chest',G.torus(.17,.05,5,14),0xd8e2ee,[0,.48,0],[PI/2,0,0]); + add('hips',G.lathe([[.16,0],[.3,-.4],[.42,-.82],[.46,-.96],[.0,-.96]],14),coat,[0,0,0]);add('hips',G.torus(.45,.02,4,18),gold2,[0,-.95,0],[PI/2,0,0]); + add('head',G.sphere(12,10),skin,[0,.13,0],[0,0,0],[.15,.17,.15]);add('head',G.sphere(12,9),hair,[0,.17,-.03],[0,0,0],[.17,.17,.17]);add('head',G.cap(.07,.3,8),hair,[0,-.12,-.12],[.3,0,0]); + add('head',G.box(),dark,[0,.16,.14],[0,0,0],[.2,.06,.04]);add('head',G.cyl(1,1,10),dark,[.06,.38,0],[0,0,.2],[.14,.04,.14]); + for(const side of ['L','R']){add('arm'+side,G.cap(.05,.26,8),coat,[0,-.17,0]);add('fore'+side,G.cap(.045,.22,8),dark,[0,-.15,0]);} + // Phase 2 wings: a fan of flame feathers on each side. + for(const [bone,s] of [['wingL',1],['wingR',-1]])for(let i=0;i<7;i++){const a=-.18+i*.25,L=1.75-.11*Math.abs(i-3),dx=s*Math.cos(a),dy=Math.sin(a);add(bone,G.cone(4),[0xff5a2a,0xff7a3a,0xff9a4a,0xffc060,0xff9a4a,0xff7a3a,0xff5a2a][i],[dx*L/2,dy*L/2,-i*.012],[0,0,-s*(PI/2-a)],[.17,L,.05]);} + const layout=[['hips',null,[0,1.02,0]],['chest','hips',[0,0,0]],['head','chest',[0,.62,0]],['armL','chest',[.22,.46,0]],['foreL','armL',[0,-.34,0]],['armR','chest',[-.22,.46,0]],['foreR','armR',[0,-.34,0]],['wingL','chest',[.06,.42,-.18]],['wingR','chest',[-.06,.42,-.18]]]; + th.lady=S.rig(parts,layout,S.mat.outline,true,th.group);th.lady.root.scale.setScalar(1.25); + fxPools(S,T,th); + th.cocoon=S.mesh(S.keep(new T.IcosahedronGeometry(1.6,1)),S.mat.ice,th.group); + th.beacons=S.pool(S.keep(new T.OctahedronGeometry(.6,0)),S.keep(new T.MeshStandardMaterial({color:0xffffff,emissive:0xffffff,emissiveIntensity:.8,roughness:.3})),4,th.group); + th.moths=S.pool(S.keep(new T.PlaneGeometry(.5,.32)),S.keep(new T.MeshBasicMaterial({color:0xff6a3a,side:T.DoubleSide,transparent:true,opacity:.9,blending:T.AdditiveBlending,depthWrite:false})),8,th.group); + th.tornado=S.pool(S.keep(new T.CylinderGeometry(1.2,.4,3.4,14,1,true)),S.keep(new T.MeshBasicMaterial({color:0xff6a2a,transparent:true,opacity:.45,side:T.DoubleSide,depthWrite:false,blending:T.AdditiveBlending})),6,th.group); + }, + draw(S,g,th){ + const b=g.boss||{},r=th.lady,bn=r.bones,tm=g.t/60,move=b.move,mode=b.mode,t=b.moveTick||0,tell=b.tellTicks||0,k=tell?clamp(t/tell,0,1):1,p2=b.phase===2; + S.resetRig(r);r.root.scale.setScalar(1.25);r.root.position.set(b.x||0,(b.y||0)+(p2?.25+Math.sin(tm*2)*.08:0),b.z||0);r.root.rotation.y=b.yaw||0; + r.root.visible=!b.cocoon&&!b.blaze;bn.wingL.visible=bn.wingR.visible=p2;bn.wingL.rotation.z=Math.sin(tm*3)*.16;bn.wingR.rotation.z=-Math.sin(tm*3)*.16; + if(p2&&r.root.visible){const f=b.yaw||0,bx=(b.x||0)-Math.sin(f)*.4,bz=(b.z||0)-Math.cos(f)*.4,cx=Math.cos(f),cz=-Math.sin(f);for(const s of [-1,1])for(const d of [.9,1.8])S._gi=S.glow(S._gi,bx+cx*s*d,1.9+d*.32,bz+cz*s*d,.8,0xff7a3a);} + bn.armL.rotation.set(-.2,0,.3);bn.armR.rotation.set(-.2,0,-.3);bn.chest.rotation.y=Math.sin(tm)*.08; + if(mode==='attack'){if(tu>.7?0xff5a3a:0xffb070,yaw=b.yaw||0; + if((move==='snowfall')&&t our party: Pyro 2x, others 0 (Fandom template). + pillar:{gauge:12,count:6,radius:13.5,iceR:2.6,iceRatio:.0416,slow:.12,explodeRatio:.666}, + edgeIce:{inner:15.2,ratio:.166}, + moves:{ + slash:{tell:26,radius:4.2,half:1.05,ratio:.583,recovery:30}, + leap:{tell:40,air:36,radius:3.6,ratio:.833,recovery:34}, + charge:{tell:54,ticks:34,speed:17,radius:1.9,ratio:1,trail:.3,recovery:40}, + tail:{tell:30,shards:5,ratio:.25,fuse:150,boom:.583,boomR:1.8,recovery:34}, + tailMelee:{tell:30,radius:4.4,half:1.2,ratio:.583,recovery:34}, + spin:{tell:52,radius:5.6,back:3.6,ratio:.833,recovery:42}, + storm:{tell:66,waves:3,gap:40,count:7,ratio:.25,radius:1.4,fall:42,recovery:30}, + roar:{tell:60,ticks:150,minRatio:.0083,maxRatio:.025,rehit:12,recovery:30}, + blades:{tell:36,count:3,spread:.52,speed:12,ratio:.416,recovery:30}, + iceWave:{tell:48,length:12,width:2.2,ratio:.5,ticks:30,recovery:34,slow:.5}, + wolf:{speed:9,ratio:.25,life:240,rehit:30} + }, + thresholds:[{at:.75,o:1,el:'cryo'},{at:.5,o:1,el:'cryo'},{at:.25,o:1,el:'cryo'}]}; + const NAMES={slash:'Claw Slash',leap:'Leaping Pounce',charge:'Straight Charge',tail:'Tail Ice Spikes',tailMelee:'Close Tail Swing',spin:'Spinning Ice Ring',interlude:'Arena Run', + storm:'Falling Ice',roar:'Arena Roar',blades:'Fan Air Slashes',iceWave:'Straight Ice Wave',wolves:'Summon Wolves'}; + // Phase 1 / phase 2 decks with distance gates (no AI table is published for Andrius; selection is a calibrated stand-in). + const DECK={1:[{m:'slash',max:5},{m:'leap',min:6},{m:'charge',min:7},{m:'tail',min:4},{m:'spin',max:7}], + // Phase 1 abilities stay in the phase 2 deck (Fandom). + 2:[{m:'slash',max:5},{m:'leap',min:6},{m:'charge',min:7},{m:'tail',min:4},{m:'tailMelee',max:5},{m:'spin',max:7},{m:'storm'},{m:'roar'},{m:'blades',min:4},{m:'iceWave'}]}; + class Andrius extends DuelFight{ + constructor(id,seed,d){ + super(id,seed,d,{atk:AW.atk,arena:AW.arena,base:.1,immune:['cryo','anemo'],element:'cryo',interval:1.5}); + const hp=Math.round(byTier(AW.hp,d)); + this.boss={id:0,kind:'wolf',x:0,z:-4,y:0,yaw:0,hp,maxHp:hp,phase:1,mode:'idle',move:null,moveTick:0,timer:70,tellTicks:0,action:'idle',actionTick:0, + r:1.5,cy:1.4,hh:1.6,cds:{},shared:{},interval:0,aura:null,frozen:0,hpFloor:0,thresholds:AW.thresholds.map(t=>({...t})),lifeStart:0, + lap:0,lapAngle:0,interludeStep:0,interludeDone:false,wolfTimer:0,walk:0,deck:[]}; + this.pillars=[];this.wolves=[];this.edgeIce=false;this.player.z=7; + Object.assign(this.stats,{moves:Object.fromEntries(Object.keys(NAMES).map(k=>[k,0])),pillarBreaks:0,pillarExplosions:0,wolvesSpawned:0,wolvesKilled:0}); + } + moveName(m){return NAMES[m]||'';} + aliveTargets(){const b=this.boss;return b.mode==='dead'?[]:[...(b.mode==='interlude'||b.mode==='transform'?[]:[b]),...this.pillars.filter(p=>p.gauge>0),...this.wolves.filter(w=>w.hp>0)];} + fallbackTargets(all){return all.length?all:[];} + lookAnchor(){return this.boss;} + targetable(q){return q.kind!=='pillar'||dist(this.player,q)<9;} + aimPoint(q){return {x:q.x,y:(q.y||0)+(q.kind==='phantom'?.6:1.4),z:q.z};} + entity(id){if(id===0)return this.boss;return this.pillars.find(p=>p.id===id)||this.wolves.find(w=>w.id===id)||null;} + projectileHits(q,old,a){return this.segmentDistance(q,old,a)<(q.r||.7)+.1&&a.y>(q.y||0)-.1&&a.y<(q.y||0)+(q.kind==='pillar'?3.2:2.8);} + hitTarget(q,hit){ + if(q.kind==='pillar'){ + // Frozen Pillar: 12 GU Cryo shield, Pyro 2x (Elemental Shield Data); our Cryo/Hydro/Physical hits do not reduce it. + if(q.gauge<=0||!this.application(hit,q))return false;const amount=hit.element==='pyro'?2*hit.gauge:0;if(!amount)return false; + q.gauge=Math.max(0,q.gauge-amount);this.fx('reaction',{x:q.x,z:q.z,y:2.4,element:'pyro',reaction:'melt',gauge:amount,life:54}); + if(q.gauge<=0){this.stats.pillarBreaks++;this.emit('pillar_broken');this.fx('shatter',{x:q.x,z:q.z,y:1.4,element:'cryo',life:40});} + return true;} + if(q.kind==='phantom'){if(hit.element==='cryo'||hit.element==='anemo'){this.stats.immuneHits++;return false;} + q.hp-=hit.damage*.5*.9;this.fx('impact',{x:q.x,z:q.z,y:.6,element:hit.element});if(q.hp<=0){this.stats.wolvesKilled++;this.particle('neutral',1,q.x,q.z);}return true;} + const b=q;if(b.mode==='dead'||b.mode==='transform'||b.mode==='interlude')return false; + if(!this.bossHit(b,hit))return true; + if(b.phase===1&&!b.interludeDone&&b.hp<=b.maxHp*AW.interlude+1e-6)this.beginInterlude(); + if(b.phase===2&&b.hp<=b.maxHp*AW.wolvesAt&&!b.wolfTimer){b.wolfTimer=1;this.emit('phantom_wolves');this.stats.moves.wolves++;} + if(b.hp<=1e-6){b.hp=0;this.outcome='win';b.mode='dead';b.action='dead';b.actionTick=0;this.hazards=this.hazards.filter(h=>h.src!==0);this.wolves=[];this.emit('boss_defeated');} + return true; + } + // Icy floors: the interlude's frosted edge and phase 2 pillar rings slow movement 12% (Fandom) and deal Cryo DoT. + slow(){const p=this.player,b=this.boss,W=AW.moves.iceWave;let f=this.pillars.some(q=>q.gauge>0&&dist(p,q)0&&along!(h.src===0&&(h.age{b.deck=I.shuffle(this,DECK[b.phase].map(x=>x.m));}, + draw=()=>{for(let k=b.deck.length-1;k>=0;k--){const row=DECK[b.phase].find(x=>x.m===b.deck[k]);if((row.min==null||d>=row.min)&&(row.max==null||d<=row.max))return b.deck.splice(k,1)[0];}return null;}; + if(!b.deck.length)deal();let m=draw(); + // Cards gated out at this range must not stall the deck: a held-out charge or leap would leave one move repeating for the whole fight. + if(!m){deal();m=draw();} + return m||(d>6?'leap':'slash');} + begin(m){const b=this.boss,T=this.aggroTarget(b),mv=AW.moves[m];b.mode='attack';b.move=m;b.moveTick=0;b.action=m;b.actionTick=0;b.tellTicks=Math.round((mv.tell||0)*this.pace()); + b.targetX=T.x;b.targetZ=T.z;b.count=0;this.stats.moves[m]++;this.emit('tell_'+m); + if(m==='leap'){const L=this.clampArena({x:T.x,z:T.z},2);b.landing={x:L.x,z:L.z,fromX:b.x,fromZ:b.z};this.hazard('circle',{x:L.x,z:L.z,radius:mv.radius,delay:b.tellTicks+mv.air,life:b.tellTicks+mv.air+6,height:2.6,damage:this.bossDamage(mv.ratio),element:'cryo',src:0,noIframe:true,landing:true});} + if(m==='iceWave'){b.lane={x:b.x,z:b.z,a:angle(b,T)};} + if(m==='spin')this.hazard('circle',{x:b.x,z:b.z,radius:mv.radius,delay:b.tellTicks,life:b.tellTicks+6,height:2.6,damage:this.bossDamage(mv.ratio),element:'cryo',src:0,noIframe:true,spinFront:true,angle:b.yaw,half:PI*.55}); + if(m==='spin')this.hazard('circle',{x:b.x,z:b.z,radius:mv.back,delay:b.tellTicks,life:b.tellTicks+6,height:2.6,damage:this.bossDamage(mv.ratio),element:'cryo',src:0,noIframe:true});} + finish(){const b=this.boss;b.mode='idle';b.move=null;b.action='idle';b.timer=Math.round(40*this.aggression());b.landing=null;} + wolfMove(){ + const b=this.boss,t=b.moveTick++,T=this.aggroTarget(b),mv=AW.moves[b.move],tell=b.tellTicks,P=this.player,f=forward(b.yaw); + switch(b.move){ + case 'slash':if(t=tell+mv.recovery)this.finish();return; + case 'leap':{if(t=1&&t===tell+mv.air-1){b.y=0;this.fx('ice_burst',{x:b.x,z:b.z,y:0,life:36});this.dropOrb(b.x+1,b.z,'cryo');}if(t>=tell+mv.air+mv.recovery)this.finish();return;} + case 'charge':{if(t=mv.ticks+mv.recovery)this.finish();return;} + case 'tail':{if(t=tell+mv.recovery)this.finish();return;} + case 'tailMelee':{// Sweeps the tail behind him, then repositions to face the player (Fandom Tail Sweep, Repositioning). + if(t=tell+mv.recovery)this.finish();return;} + case 'spin':if(t=tell+mv.recovery)this.finish();return; + case 'storm':{if(t=mv.gap*mv.waves+mv.recovery)this.finish();return;} + case 'roar':{if(t0)this.explodePillar(q); + if(k=mv.ticks+mv.recovery)this.finish();return;} + case 'blades':{if(t=tell+mv.recovery)this.finish();return;} + case 'iceWave':{const L=b.lane;if(t=tell+mv.ticks+mv.recovery)this.finish();return;} + } + } + // A standing pillar struck by Wolf King Roar or Wind Blades explodes (66.6% ATK Cryo) and drops 0-5 Cryo orbs (Fandom). + explodePillar(q){q.gauge=0;this.stats.pillarExplosions++;this.hazard('circle',{x:q.x,z:q.z,radius:3,height:3,life:6,damage:this.bossDamage(AW.pillar.explodeRatio),element:'cryo',src:0});this.fx('shatter',{x:q.x,z:q.z,y:1.4,element:'cryo',life:40}); + const n=Math.floor(N.rand(this)*6);for(let i=0;i=TAU*(b.interludeStep===4?1:.75)){b.interludeStep++;b.moveTick=0;b.tellTicks=Math.round(mv.tell*this.pace()); + if(b.interludeStep===5){const L={x:0,z:0};b.landing={x:0,z:0,fromX:b.x,fromZ:b.z};this.hazard('circle',{x:0,z:0,radius:AW.moves.leap.radius,delay:AW.moves.leap.air,life:AW.moves.leap.air+6,height:2.6,damage:this.bossDamage(AW.moves.leap.ratio),element:'cryo',src:0,noIframe:true,landing:true});}} + return;} + if(b.interludeStep===1||b.interludeStep===3){const k=t;if(k=mv.ticks+20){b.interludeStep++;b.moveTick=0;}return;} + if(b.interludeStep===5){const A=AW.moves.leap,u=Math.min(1,(t+1)/A.air),L=b.landing;b.x=L.fromX+(L.x-L.fromX)*u;b.z=L.fromZ+(L.z-L.fromZ)*u;b.y=4.5*Math.sin(PI*u); + if(u>=1){b.y=0;b.landing=null;b.interludeDone=true;this.fx('ice_burst',{x:0,z:0,y:0,life:36}); + // Phase 2 if HP fell below 55% (or the fight ran long); a transformation in place, invulnerable (BWIKI Wolf Spirit of the North). + b.mode='transform';b.moveTick=0;b.action='transform';this.edgeIce=false;} + return;} + } + enterPhase2(){const b=this.boss,P=AW.pillar;b.phase=2;b.hpFloor=0;b.mode='idle';b.timer=30;b.deck=[];this.emit('phase_2'); + this.cfg.immune=['cryo','anemo']; + // Push nearby players away, then 6 Frozen Pillars with icy floors around the edge (Fandom Phase 2 start). + const p=this.player,d=dist(p,b);if(d<6){const a=angle(b,p),f=forward(a);this.movePlayer(f.x*(6-d),f.z*(6-d));} + this.pillars=[];for(let i=0;iAW.edgeIce.inner&&this.t%60===0)this.hurt(this.bossDamage(AW.edgeIce.ratio),'cryo',{light:true}); + if(this.t%60===0&&this.pillars.some(q=>q.gauge>0&&dist(P,q)0&&dist(h,q)=90){b.hpFloor=0;if(b.hp<=b.maxHp*AW.interlude+1e-6||this.t-b.lifeStart>=AW.stallTicks)this.enterPhase2();else{b.mode='idle';b.timer=30;}}return;} + if(b.mode==='attack'){this.wolfMove();return;} + // Interlude also starts when the fight runs long in phase 1 (Fandom trigger 2); phantom wolves likewise in phase 2. + if(b.phase===1&&!b.interludeDone&&this.t-b.lifeStart>=AW.stallTicks){this.beginInterlude();return;} + if(b.phase===2&&!b.wolfTimer&&this.t-b.lifeStart>=AW.stallTicks*2){b.wolfTimer=1;this.stats.moves.wolves++;} + if(b.timer>0)b.timer--;const T=this.aggroTarget(b); + if(!b.timer){this.begin(this.pickMove());return;} + const off=this.turnToward(T,.08),d=dist(b,T);b.action=d>4?'walk':'idle';if(d>4&&off<1){this.stepBoss(b.yaw,3.4);b.walk+=3.4/HZ;} + } + updateWolves(){ + const b=this.boss,P=this.player,W=AW.moves.wolf; + // Small Phantom Wolf: summoned more and more often as time goes on (Fandom), from 15% HP or a long fight. + if(b.wolfTimer&&b.mode!=='dead'){b.wolfTimer++;const period=Math.max(150,Math.round((540-b.wolfTimer*.12)*this.aggression())); + if(b.wolfTimer%period===0){const a=N.rand(this)*TAU,L={x:Math.sin(a)*(AW.arena-2),z:Math.cos(a)*(AW.arena-2)}; + this.wolves.push({id:this.idNext(),kind:'phantom',x:L.x,z:L.z,y:0,r:.55,hp:this.boss.maxHp*.012,age:0,yaw:0});this.stats.wolvesSpawned++;}} + for(const w of this.wolves){if(w.hp<=0)continue;w.age++;const a=angle(w,P),f=forward(a);w.yaw=a;w.x+=f.x*W.speed/HZ;w.z+=f.z*W.speed/HZ; + if(dist(w,P)<.9&&(!w.last||this.t-w.last>=W.rehit)){w.last=this.t;this.hurt(this.bossDamage(W.ratio),'cryo',{x:w.x,z:w.z});w.hp=0;this.fx('shatter',{x:w.x,z:w.z,y:.6,element:'cryo',life:30});} + if(w.age>=W.life)w.hp=0;} + this.wolves=this.wolves.filter(w=>w.hp>0); + } + } + // ---------------------------------------------------------------- reference controller plan + const {KAEYA,AMBER,XIANGLING,BARBARA}=I; + function awIntent(g){ + const H=I.helpers(g),{p,party,ai,skillReady,burstReady,low,hpFrac}=H,b=g.boss,d=dist(p,b); + const out={want:ai,action:null,anchor:0,desired:3,weight:1.3,holdJ:false,charge:false,bunny:0,mode:'melee'}; + const choose=I.chooser(out,H),heal=[];if(burstReady(BARBARA)&&(low>=1||hpFrac<.55))heal.push([BARBARA,'L',{}]);if(skillReady(BARBARA)&&(hpFrac<.75||low))heal.push([BARBARA,'K',{}]); + if(b.mode==='interlude'||b.mode==='transform'){out.mode='evade';out.home=true;out.anchor=-1;out.weight=.5;if(!choose(heal))choose([[AMBER,'charge',{charge:true,keep:true}]]);return out;} + // Phase 2: a Guoba dropped beside a Frozen Pillar melts it when one stands near the fight. Only Pyro cuts the ward: Xiangling's spear is + // Physical, so this mode must not hold the player there with normal attacks (every fight used to end with pillars 0, boom 6). + const pil=g.pillars.filter(q=>q.gauge>0).sort((a,c)=>dist(p,a)-dist(p,c))[0]; + if(b.phase===2&&pil&&dist(p,pil)<6&&skillReady(XIANGLING)&&!(b.mode==='attack'&&b.move==='roar')){out.anchor=pil.id;out.desired=2.4;out.weight=1.5;out.mode='pillar'; + choose([...heal,[XIANGLING,'K',{desired:2.2}]]);return out;} + const wolf=g.wolves.filter(w=>w.hp>0).sort((a,c)=>dist(p,a)-dist(p,c))[0]; + if(wolf&&dist(p,wolf)<4){out.anchor=wolf.id;out.desired=1.6;out.weight=1.2;choose([...heal,[XIANGLING,'J',{holdJ:true}],[KAEYA,'J',{holdJ:true}]]);return out;} + const tell=b.mode==='attack'?Math.max(0,b.tellTicks-b.moveTick):0; + if(b.mode==='attack'&&(b.move==='spin'||b.move==='charge'||b.move==='leap')&&tell>0){out.mode='evade';out.desired=b.move==='spin'?7.6:6.5;out.weight=1.1;if(!choose(heal))choose([[XIANGLING,null,{}]]);return out;} + const list=[...heal]; + // Andrius is immune to Cryo and Anemo, so Kaeya deals nothing: Xiangling and Amber carry the damage. + if(burstReady(XIANGLING))list.push([XIANGLING,'L',{desired:3}]); + if(skillReady(XIANGLING))list.push([XIANGLING,'K',{desired:2.6}]); + if(burstReady(AMBER))list.push([AMBER,'L',{desired:5}]); + if(skillReady(AMBER)&&d<7)list.push([AMBER,'bunny',{bunny:Math.round((clamp(d*.6,2,8)-2)*20),desired:3}]); + const cur=party[ai].id;if(cur==='xiangling')list.push([ai,'J',{holdJ:true,desired:2.6}]);if(cur==='amber')list.push([ai,'charge',{charge:true,desired:5.5}]); + list.push([XIANGLING,'J',{holdJ:true,desired:2.6}],[AMBER,'charge',{charge:true,desired:5.5}]); + choose(list);if(g.auras.some(a=>a.kind==='pyronado')&&out.action!=='charge')out.desired=3.3; + return out; + } + function awPenalty(g,c){const b=c.boss,p=c.player;if(b.mode==='dead')return 0;let pen=0;const d=dist(p,b),tell=b.mode==='attack'?Math.max(0,b.tellTicks-b.moveTick):0; + if(b.mode==='attack'&&b.move==='spin'&&tell>0&&d<6.4)pen+=170*(6.4-d); + if(b.mode==='attack'&&b.move==='slash'&&tell>0){const a=Math.abs(wrap(angle(b,p)-b.yaw));if(d<4.8&&a<1.2)pen+=200;} + if((b.mode==='attack'&&b.move==='charge'||b.mode==='interlude'&&(b.interludeStep===1||b.interludeStep===3))&&tell>=0){const f=forward(b.yaw),dx=p.x-b.x,dz=p.z-b.z,along=dx*f.x+dz*f.z,lat=Math.abs(dx*f.z-dz*f.x);if(along>-1&&along<12&&lat<2.6)pen+=150*(2.6-lat);} + if(c.edgeIce&&Math.hypot(p.x,p.z)>AW.edgeIce.inner-.5)pen+=200; + for(const q of c.pillars)if(q.gauge>0&&dist(p,q)0&&dist(p,q)<3.6)pen+=260;pen+=8*d;} + return pen;} + M.register({id:'genshin/andrius',name:'Tundra Wolf'},Andrius,{intent:awIntent,penalty:awPenalty,arena:14.8, + gain:(g,c,intent,base)=>(base.hp-c.boss.hp)+600*(base.pil-c.pillars.reduce((s,q)=>s+Math.max(0,q.gauge),0)), + base:c=>({hp:c.boss.hp,pil:c.pillars.reduce((s,q)=>s+Math.max(0,q.gauge),0)})}); + M.andrius=AW;M.andriusMoveNames=NAMES; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/genshin_remake/boss_common.js b/environments/games/web/games/genshin_remake/boss_common.js new file mode 100644 index 0000000000000000000000000000000000000000..de97f3445e0ec738eb7ab49475f25b07faa8f477 --- /dev/null +++ b/environments/games/web/games/genshin_remake/boss_common.js @@ -0,0 +1,74 @@ +/* BossBench · Genshin Impact expansion (2026-11-03): shared base for the bosses added after the first three were accepted. + * The accepted encounters in game.js keep their exact code paths and state shape; everything here is new code that only + * the new cases construct, so recordings of the first three replay to the same hash under the same rule version. */ +(function(root){ + 'use strict'; + const M=root.GenshinGame,N=root.NativeBench,I=M.internals; + const {Fight,HZ,PI,clamp,dist,angle,forward,wrap,resMult,span}=I; + // A case registers its class, its controller plan and its display name; the play page and the policy env read M.cases. + // cloneGame copies the RNG state, so an unblinded lookahead would roll the real future: reading what is not decided yet is the one + // thing a privileged controller may not do (EXPAND 2.4). plan.base runs first on each clone, so reseeding here from the tick alone gives + // every candidate one synthetic future that holds nothing of the real RNG. The accepted scenes keep their controller; see + const blind=c=>{c.rng=(Math.imul(c.t+1,0x9e3779b1)>>>0)||1;}; + M.register=function(def,Klass,plan){if(!M.cases.some(c=>c.id===def.id))M.cases.push(def);I.CLASSES[def.id]=Klass; + if(plan)I.PLANS[def.id]={...plan,base:c=>{blind(c);return plan.base(c);}};}; + class DuelFight extends Fight{ + // cfg: {atk, arena, res (element -> RES), base (default RES), immune (elements dealing no damage), element (hazards)} + constructor(id,seed,d,cfg){ + super(id,seed,d);this.cfg=cfg;this.atk=cfg.atk;this.arenaR=cfg.arena;this.hazardElement=cfg.element||'physical'; + Object.assign(this.stats,{bossHits:0,immuneHits:0,playerFrozen:0}); + } + res(){return this.cfg.res||{};} + resistance(el){const r=this.res();return r[el]!==undefined?r[el]:(this.cfg.base??.1);} + // Generic damage on a boss entity: immunity, ICD/aura reactions (bosses are freeze-immune: Fandom Frozen "Most Bosses"), + // Fandom RES multiplier, an optional cap, an HP floor (phase gates), Barbara's healing, weapon energy and HP-threshold drops. + bossHit(b,hit,opts={}){ + const owner=this.party[hit.owner]; + if((this.cfg.immune||[]).includes(hit.element)){this.stats.immuneHits++;if(hit.damage>0)this.fx('immune',{x:b.x,z:b.z,y:(b.y||0)+(b.cy||1.5)+.8,life:30});return 0;} + const applied=this.application(hit,b);if(applied)this.stats.elementApplications++; + const rx=applied?this.react(b,hit):{mult:1,reaction:null};b.frozen=0; + let damage=hit.damage*.5*resMult(this.resistance(hit.element))*rx.mult*(opts.crit||1); + if(opts.cap!==undefined&&damage>opts.cap)damage=opts.cap; + const floor=b.hpFloor||0,actual=Math.max(0,Math.min(damage,b.hp-floor));b.hp=Math.max(floor,b.hp-damage); + this.stats.damageDealt+=actual;this.stats.bossHits++;const y=(b.y||0)+(b.cy||1.5); + this.fx('impact',{x:b.x,z:b.z,y,element:hit.element}); + if(actual>0)this.fx('dmg',{x:b.x,z:b.z,y:y+.6,amount:Math.round(actual),element:hit.element,reaction:rx.reaction,life:54}); + if(rx.reaction)this.fx('reaction',{x:b.x,z:b.z,y:y+1.2,element:hit.element,reaction:rx.reaction,life:54}); + this.barbaraHeal(owner,hit);this.naEnergy(owner,hit,actual); + while(b.thresholds&&b.thresholds.length&&b.hp<=b.maxHp*b.thresholds[0].at+1e-6){const t=b.thresholds.shift(); + for(let i=0;i<(t.o||0);i++)this.dropOrb(b.x+i*.4,b.z,t.el||'neutral');for(let i=0;i<(t.p||0);i++)this.particle(t.el||'neutral',1,b.x-.4,b.z);} + return actual; + } + // Cryo on a Wet active character freezes it (Fandom Frozen). Struggling free is not modeled: a fixed 1.25 s hold. + hurt(amount,element='physical',source=null){ + const q=this.owner(),wet=q.wet>0&&element==='cryo',ok=super.hurt(amount,element,source); + if(ok&&wet&&q.hp>0){const p=this.player;p.stun=Math.max(p.stun,75);q.wet=0;this.stats.playerFrozen++;this.emit('player_frozen');this.fx('player_frozen',{x:p.x,z:p.z,y:1,life:75});} + return ok; + } + // Movement slows (ice floors) scale walking and sprinting only; dashes keep their distance. + slow(){return 1;} + movePlayer(dx,dz){const f=this.player.dash?1:this.slow();super.movePlayer(dx*f,dz*f);} + // Fandom AI Logic tables: an ability is usable when off cooldown (own and shared), inside its range and angle and, unless it + // ignores it, after the action interval; the lowest priority number wins, ties are random. CDs scale with aggression. + initCds(list){const b=this.boss,k=this.aggression();for(const a of list)b.cds[a.id]=a.init!=null?Math.round(a.init*HZ*k):0;} + tickCds(){const b=this.boss;for(const k of Object.keys(b.cds))if(b.cds[k]>0)b.cds[k]--;for(const k of Object.keys(b.shared))if(b.shared[k]>0)b.shared[k]--;if(b.interval>0)b.interval--;} + pickAbility(list){ + const b=this.boss,T=this.aggroTarget(b),d=dist(b,T),off=Math.abs(wrap(angle(b,T)-b.yaw))*180/PI; + const ok=list.filter(a=>(!a.phase||a.phase===b.phase)&&!(b.cds[a.id]>0)&&!(a.shared&&b.shared[a.shared]>0)&&d>=a.min&&d<=a.max&& + (a.angle==null||off<=a.angle)&&(a.ign||b.interval<=0)&&(!a.when||a.when.call(this,b,d))); + if(!ok.length)return null;const top=Math.min(...ok.map(a=>a.prio)),best=ok.filter(a=>a.prio===top);return best[Math.floor(N.rand(this)*best.length)]; + } + useAbility(a){const b=this.boss,k=this.aggression();if(a.cd)b.cds[a.id]=Math.round(span(this,a.cd)*HZ*k); + if(a.shared)b.shared[a.shared]=Math.round(a.sharedCD*HZ*k);b.triggers=!!a.trig;b.ability=a.id;} + endAbility(){const b=this.boss;if(b.triggers)b.interval=Math.round(this.cfg.interval*HZ*this.aggression());b.triggers=false;} + turnToward(T,rate){const b=this.boss,dy=wrap(angle(b,T)-b.yaw);b.yaw=wrap(b.yaw+clamp(dy,-rate,rate));return Math.abs(wrap(angle(b,T)-b.yaw));} + boundBoss(margin=1.5){const b=this.boss,r=this.arenaR-margin,n=Math.hypot(b.x,b.z);if(n>r){b.x*=r/n;b.z*=r/n;}} + stepBoss(a,speed){const b=this.boss,f=forward(a);b.x+=f.x*speed/HZ;b.z+=f.z*speed/HZ;this.boundBoss();} + pushOut(next){const b=this.boss;if(!b||b.mode==='dead'||(b.y||0)>1.5||b.ghost)return;const r=(b.r||1)+.45,d=Math.hypot(next.x-b.x,next.z-b.z); + if(d1e-6?Math.atan2(next.x-b.x,next.z-b.z):this.player.yaw+PI;next.x=b.x+Math.sin(a)*r;next.z=b.z+Math.cos(a)*r;}} + cone(radius,half,ratio,el,extra={}){const b=this.boss;return this.hazard('circle',{x:b.x,z:b.z,radius,half,angle:b.yaw,height:2.4,life:6,damage:this.bossDamage(ratio),element:el,src:0,...extra});} + // Telegraph helpers shared by the expansion bosses' renderers read these fields; rules never read them back. + tellLeft(){const b=this.boss;return b.mode==='attack'?Math.max(0,(b.tellTicks||0)-(b.moveTick||0)):0;} + } + M.internals.DuelFight=DuelFight; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/genshin_remake/boss_kenki.js b/environments/games/web/games/genshin_remake/boss_kenki.js new file mode 100644 index 0000000000000000000000000000000000000000..cd3255345d13f84809ea665a9b16e24e6a9c3446 --- /dev/null +++ b/environments/games/web/games/genshin_remake/boss_kenki.js @@ -0,0 +1,199 @@ +/* Maguu Kenki Maguu Kenki (genshin/maguu_kenki). Sources: Fandom Maguu Kenki r1682288 (Stats hp_ratio 20 / atk_ratio 8, Energy + * Drops, Abilities by phase, AI Logic table: ranges, angles, priorities, cooldowns, shared CDs, 1.5 s action interval) and BWIKI + * Maguu Kenki (10% all RES, skill list). Ratios, ranges, cooldowns and the 71% phase rule follow the sources; every tick count, + * radius and speed is a BossBench calibration (no frame data is published). HP and ATK are tier calibrations. Not modeled: + * Shadowsword: Blustering Blade 2 (a return-to-spawn teleport; the circular arena bound makes it unreachable). */ +(function(root){ + 'use strict'; + const M=root.GenshinGame,N=root.NativeBench,I=M.internals; + const {DuelFight,HZ,PI,TAU,clamp,dist,angle,forward,wrap,byTier}=I; + const MK={hp:[22000,56000,144000],atk:3800,arena:16,interval:1.5,phaseAt:.71,maskRange:7, + // AI table rows (Fandom): min/max m, angle deg (null = any), priority (lower wins), CD s, initial CD s, shared CD group, triggers interval. + abilities:[ + {id:'sweeper',move:'sweeper',phase:1,min:0,max:5,angle:null,prio:2,cd:[15,20],init:1,trig:1}, + {id:'rush',move:'rush',phase:1,min:5,max:15,angle:90,prio:3,cd:[5,10],init:1,trig:1}, + {id:'ichi1',move:'ichimonji',phase:1,min:0,max:5,angle:null,prio:4,cd:[0,2.5],init:1,shared:'slash',sharedCD:5,trig:1}, + {id:'ichi2',move:'ichimonji',phase:1,min:0,max:5,angle:90,prio:4,cd:[0,2.5],init:1,shared:'slash',sharedCD:5,trig:1}, + {id:'sichi1',move:'shadowIchimonji',phase:2,min:0,max:10,angle:90,prio:4,cd:[0,2.5],init:1,shared:'slash',sharedCD:5,trig:1}, + {id:'sichi2',move:'shadowIchimonji',phase:2,min:0,max:5,angle:90,prio:4,cd:[0,2.5],init:1,shared:'slash',sharedCD:5,trig:1}, + {id:'rush2',move:'rush',phase:2,min:5,max:15,angle:90,prio:3,cd:[10,15],init:1,trig:1}, + {id:'ssweep',move:'shadowSweeper',phase:2,min:0,max:7,angle:null,prio:1,cd:[15,20],init:1,trig:1}, + // Variant 2 "only triggers upon being hit" (Fandom note): read here as a hit in the last 0.5 s. + {id:'ssweep2',move:'shadowSweeper',phase:2,min:5,max:10,angle:null,prio:2,cd:[5,7.5],init:1,ign:1,when(b){return this.t-b.lastHit<30;}}, + {id:'sblade',move:'shadowBlade',phase:2,min:15,max:50,angle:90,prio:2,cd:[0,10],init:1,shared:'blade',sharedCD:15,trig:1}, + {id:'burst',move:'dualBurst',phase:2,min:0,max:10,angle:null,prio:1,cd:[20,30],init:20,ign:1}, + {id:'push',move:'pushMask',min:0,max:10,angle:90,prio:2,cd:[10,15],init:1,trig:1}, + {id:'explode1',move:'explodeMask',min:5,max:50,angle:null,prio:3,cd:[15,20],init:1,trig:1,ign:1}, + // Exploding Mask 2 lists no CD; taken literally it would win every pick at 15 m+ and Blustering Blade 1 could never fire, so 8-12 s is calibrated. + {id:'explode2',move:'explodeMask',min:15,max:50,angle:null,prio:1,cd:[8,12],init:1,trig:1,ign:1}, + {id:'taunt',move:'taunt',min:7,max:20,angle:null,prio:3,cd:[10,15],init:1,ign:1}, + {id:'dash',move:'dash',min:10,max:50,angle:90,prio:4,cd:null,init:null,ign:1} + ], + moves:{ + ichimonji:{tell:22,gap:20,count:3,radius:3.4,half:1.05,ratio:.5,lunge:1.2,recovery:30}, + rush:{tell:34,dash:16,speed:15,radius:1.5,ratio:.6,recovery:26,bladeRatio:.5}, + sweeper:{tell:60,radius:4.6,ratio:1,recovery:36,pull:2.4}, + pushMask:{tell:30,travel:36,speed:11,radius:1.6,ratio:1,recovery:24}, + explodeMask:{tell:24,fuse:84,radius:3,ratio:1,recovery:20}, + taunt:{ticks:120}, + dash:{hops:5,hopTicks:12,hop:2.6}, + transition:{tell:72,radius:7,ratio:.8,recovery:40}, + dualBurst:{tell:60,radius:7,ratio:.8,recovery:40}, + shadowIchimonji:{tell:20,gap:20,count:3,radius:3.4,half:1.05,ratio:.5,shadowRatio:.3,shadowDelay:10,lunge:1.2,recovery:30}, + shadowSweeper:{tell:66,radius:4.6,ratio:1,shadowRadius:8.5,shadowInner:3.6,shadowRatio:1,shadowDelay:18,pull:2.4,recovery:40,teleport:4.5,variant2Ratio:.6}, + shadowBlade:{tell:30,blades:3,gap:14,speed:13,radius:.7,ratio:.5,recovery:30} + }, + // Fandom Energy Drops: one orb at 75/50/25% HP (and at 0, when the fight ends). + thresholds:[{at:.75,o:1},{at:.5,o:1},{at:.25,o:1}]}; + const NAMES={ichimonji:'Triple Slash',rush:'Straight Dash-Slash',sweeper:'Pulling Sweep',pushMask:'Thrown Mask',explodeMask:'Mask Blast',taunt:'Standing Challenge',dash:'Hop Dash', + transition:'Ground-Pound Ice Ring',dualBurst:'Dual-Blade Ice Ring',shadowIchimonji:'Clone Triple Slash',shadowSweeper:'Clone Pulling Sweep',shadowBlade:'Clone Blade Throw'}; + class MaguuKenki extends DuelFight{ + constructor(id,seed,d){ + super(id,seed,d,{atk:MK.atk,arena:MK.arena,base:.1,element:'anemo',interval:MK.interval}); + const hp=Math.round(byTier(MK.hp,d)); + this.boss={id:0,kind:'kenki',x:0,z:-5,y:0,yaw:0,hp,maxHp:hp,phase:1,mode:'idle',move:null,moveTick:0,timer:50,tellTicks:0, + action:'idle',actionTick:0,r:.8,cy:1.3,hh:1.2,cds:{},shared:{},interval:0,triggers:false,mask:0,shadow:null,shadowEl:null, + aura:null,frozen:0,hpFloor:Math.round(hp*.7),thresholds:MK.thresholds.map(t=>({...t})),walk:0,spawnX:0,spawnZ:-5,dashLeft:0,taunting:0,lastHit:-999,variant:1}; + this.initCds(MK.abilities);this.player.z=6; + Object.assign(this.stats,{moves:Object.fromEntries(Object.keys(NAMES).map(k=>[k,0])),maskBlocks:0,phase2:0,tauntHits:0}); + } + moveName(m){return NAMES[m]||'';} + aliveTargets(){return this.boss.mode==='dead'?[]:[this.boss];} + fallbackTargets(all){return all;} + aimPoint(q){return {x:q.x,y:(q.y||0)+1.3,z:q.z};} + projectileHits(q,old,a){return this.segmentDistance(q,old,a)q.y-.1&&a.y=MK.maskRange;} + hitTarget(b,hit){ + if(b.mode==='dead')return false; + if(b.mode==='transition'){this.stats.immuneHits++;if(hit.damage>0)this.fx('immune',{x:b.x,z:b.z,y:2.4,life:30});return false;} + if(this.maskUp()){b.mask=24;this.stats.maskBlocks++;this.emit('mask_block');this.fx('mask_block',{x:b.x,z:b.z,y:1.4,life:24,angle:angle(b,this.player)});return false;} + if(b.mode==='taunt')this.stats.tauntHits++; + b.lastHit=this.t; + this.bossHit(b,hit); + // Phase 2 at 71%: phase 1 cannot go below 70% (hpFloor), and the transition attack is invulnerable (Fandom, BWIKI). + if(b.phase===1&&b.hp<=b.maxHp*MK.phaseAt+1e-6&&b.mode!=='transition')this.beginTransition(); + if(b.hp<=1e-6){b.hp=0;this.outcome='win';b.mode='dead';b.action='dead';b.actionTick=0;this.hazards=this.hazards.filter(h=>h.src!==0);this.emit('boss_defeated');} + return true; + } + beginTransition(){const b=this.boss,T=MK.moves.transition;this.cancel();b.mode='transition';b.move='transition';b.moveTick=0;b.tellTicks=Math.round(T.tell*this.pace());b.action='transition';b.actionTick=0; + this.stats.moves.transition++;this.emit('tell_transition');} + cancel(){const b=this.boss;this.hazards=this.hazards.filter(h=>!(h.src===0&&h.age=MK.maskRange){const el=b.shadowEl;this.finish(); + if(el==='anemo')this.blade(b.x,b.z,angle(b,P),MK.moves.shadowBlade.ratio);else{const a=MK.abilities.find(x=>x.id==='rush2');this.begin({...a,cd:null});}return;} + if(k%mv.gap===0&&b.count=mv.gap*(mv.count-1)+mv.recovery)this.finish();return;} + case 'rush':{ + if(t=7)this.blade(b.x,b.z,angle(b,P),mv.bladeRatio);else{this.finish();const a=MK.abilities.find(x=>x.id==='sichi2');this.begin({...a,cd:null,shared:null,trig:a.trig});b.shadowEl='cryo';b.followMask=true;return;}} + if(k>=mv.dash+mv.recovery)this.finish();return;} + case 'sweeper':case 'shadowSweeper':{ + // Iai stance charge, dragging the player in (Fandom), then a ring slash; the Cryo shadow adds a wider ring after it. + if(ttell*.4&&dist(b,P)=tell+mv.recovery+(b.move==='shadowSweeper'?mv.shadowDelay:0))this.finish();return;} + case 'pushMask':{ + if(t=tell+mv.recovery+12)this.finish();return;} + case 'explodeMask':{ + // A mask appears on the player, swirls, then explodes as Cryo (Fandom Exploding Mask). + if(t===tell){const L=this.clampArena({x:P.x,z:P.z},1);this.hazard('circle',{x:L.x,z:L.z,radius:mv.radius,delay:mv.fuse,life:mv.fuse+6,height:3,damage:this.bossDamage(mv.ratio),element:'cryo',src:0,landing:true,maskBomb:true});} + if(t>=tell+mv.recovery)this.finish();return;} + case 'dash':{ + // Up to 5 short dashes with afterimages toward the player (Fandom Dash). + const H=MK.moves.dash;if(t%H.hopTicks===0){this.turnToward(T,PI);if(b.dashLeft>0&&dist(b,T)>3.2){b.dashLeft--;this.fx('afterimage',{x:b.x,z:b.z,y:0,angle:b.yaw,life:30});}else{this.finish();return;}} + const hopSpeed=H.hop*HZ/H.hopTicks;this.stepBoss(b.yaw,hopSpeed);return;} + case 'shadowBlade':{ + // Teleports away leaving an Anemo shadow that fires once, then 3 quick wind blades from the boss (Fandom Shadowsword: Blustering Blade). + if(t===1){const a=angle(P,b)+(N.rand(this)-.5)*.8,r=7;const L=this.clampArena({x:P.x+Math.sin(a)*r,z:P.z+Math.cos(a)*r},2);b.x=L.x;b.z=L.z;this.fx('afterimage',{x:b.shadow.x,z:b.shadow.z,y:0,angle:b.yaw,life:40});} + if(t===Math.max(2,Math.round(tell*.5))&&b.shadow)this.blade(b.shadow.x,b.shadow.z,angle(b.shadow,P),mv.ratio); + if(t>=tell){this.turnToward(P,.3);const k=t-tell;if(k%mv.gap===0&&k=mv.gap*mv.blades+mv.recovery)this.finish();} + return;} + case 'dualBurst':{ + if(t=tell+mv.recovery)this.finish();return;} + } + } + blade(x,z,a,ratio){const f=forward(a),mv=MK.moves.shadowBlade;this.hazard('bolt',{x:x+f.x*.8,z:z+f.z*.8,y:1,vx:f.x*mv.speed/HZ,vz:f.z*mv.speed/HZ,radius:mv.radius,life:100,height:2.2,damage:this.bossDamage(ratio),element:'anemo',src:0,blade:true,consume:true});} + updateBoss(){ + const b=this.boss;b.actionTick++;this.decayAura(b);this.tickCds();if(b.mask>0)b.mask--; + if(b.mode==='dead')return; + if(b.mode==='transition'){const T=MK.moves.transition,t=b.moveTick++; + if(t=b.tellTicks+T.recovery){b.phase=2;b.hpFloor=0;b.mode='idle';b.timer=20;this.stats.phase2++;this.emit('phase_2'); + for(const a of MK.abilities)if(a.phase===2)b.cds[a.id]=a.init!=null?Math.round(a.init*HZ*this.aggression()):0;} + return;} + if(b.mode==='taunt'){if(--b.timer<=0){this.endAbility();b.mode='idle';b.move=null;b.timer=10;}return;} + if(b.mode==='attack'){this.kenkiMove();if(b.mode==='idle'&&b.followMask){b.followMask=false;const a=MK.abilities.find(x=>x.id==='push');this.begin({...a,cd:null,shared:null});}return;} + if(b.timer>0){b.timer--;} + const T=this.aggroTarget(b); + if(!b.timer){const a=this.pickAbility(MK.abilities);if(a){this.begin(a);return;}} + // Otherwise it walks toward the player (it always re-engages). + const off=this.turnToward(T,.1),d=dist(b,T);b.action=d>3?'walk':'idle';if(d>3&&off<1){this.stepBoss(b.yaw,3.2);b.walk+=3.2/HZ;} + } + // Wind blades and masks pass the shadow; blades and push masks fly straight; rules for hazards come from Fight. + } + // ---------------------------------------------------------------- reference controller plan + const {KAEYA,AMBER,XIANGLING,BARBARA}=I; + function mkIntent(g){ + const H=I.helpers(g),{p,party,ai,skillReady,burstReady,low,hpFrac}=H,b=g.boss,d=dist(p,b); + const out={want:ai,action:null,anchor:0,desired:2.6,weight:1.4,holdJ:false,charge:false,bunny:0,mode:'melee'}; + const choose=I.chooser(out,H),heal=[];if(burstReady(BARBARA)&&(low>=1||hpFrac<.55))heal.push([BARBARA,'L',{}]);if(skillReady(BARBARA)&&(hpFrac<.75||low))heal.push([BARBARA,'K',{}]); + const busy=b.mode==='attack'&&(g.tellLeftAt(b)>0||['ichimonji','shadowIchimonji','sweeper','shadowSweeper','dualBurst'].includes(b.move)); + // The mask parries everything from 7 m or farther while the boss is idle, so the reference fights it in melee. + if(b.mode==='transition'||b.move==='dualBurst'&&b.mode==='attack'){out.mode='evade';out.desired=8.5;out.weight=1.2;if(!choose(heal))choose([[KAEYA,null,{}]]);return out;} + if(busy&&b.move!=='dash'){out.mode='evade';out.desired=b.move==='shadowSweeper'&&b.variant!==2?9.6:b.move==='shadowSweeper'?6.8:b.move==='sweeper'?6.8:5.4;out.weight=1.1;if(!choose(heal))choose([[XIANGLING,null,{}]]);return out;} + const list=[...heal]; + if(burstReady(XIANGLING))list.push([XIANGLING,'L',{desired:3}]); + if(skillReady(XIANGLING))list.push([XIANGLING,'K',{desired:2.4}]); + if(skillReady(KAEYA))list.push([KAEYA,'K',{desired:2.4}]); + if(burstReady(KAEYA))list.push([KAEYA,'L',{desired:2.2}]); + if(skillReady(AMBER)&&d<6)list.push([AMBER,'bunny',{bunny:0,desired:3}]); + if(burstReady(AMBER)&&b.mode==='taunt')list.push([AMBER,'L',{desired:4}]); + const cur=party[ai].id;if(cur==='kaeya'||cur==='xiangling')list.push([ai,'J',{holdJ:true,desired:2.2}]); + list.push([KAEYA,'J',{holdJ:true,desired:2.2}],[XIANGLING,'J',{holdJ:true,desired:2.4}],[BARBARA,'J',{holdJ:true,desired:2.4}]); + choose(list);if(g.auras.some(a=>a.kind==='pyronado')&&out.action!=='charge')out.desired=3.2; + return out; + } + function mkPenalty(g,c){const b=c.boss,p=c.player;if(b.mode==='dead')return 0;let pen=0;const d=dist(p,b),f=forward(b.yaw),dx=p.x-b.x,dz=p.z-b.z,along=dx*f.x+dz*f.z,lat=Math.abs(dx*f.z-dz*f.x); + // Anticipate telegraphed areas before their hazards exist (the shared lookahead only sees created hazards). + const tell=b.mode==='attack'?c.tellLeftAt(b):0; + if(b.mode==='attack'&&b.move==='sweeper'&&tell>0&&d<5.6)pen+=180*(5.6-d); + if(b.mode==='attack'&&b.move==='shadowSweeper'){if(b.variant===2){if(d<5.6)pen+=180*(5.6-d);if(b.shadow){const e=dist(p,b.shadow);if(e<5.4)pen+=150*(5.4-e);}}else if(d<9.1)pen+=150*(9.1-d);} + if(b.mode==='attack'&&(b.move==='ichimonji'||b.move==='shadowIchimonji')&&d<4.3)pen+=110*(4.3-d); + if(b.mode==='attack'&&(b.move==='rush'||b.move==='pushMask')&&tell>0&&along>-1&&along<8&&lat<2.3)pen+=120*(2.3-lat); + if((b.mode==='transition'||b.mode==='attack'&&b.move==='dualBurst')){const d=dist(p,b);if(d<7.6)pen+=160*(7.6-d);} + return pen;} + MaguuKenki.prototype.tellLeftAt=function(b){return b.mode==='attack'?Math.max(0,(b.tellTicks||0)-(b.moveTick||0)):0;}; + M.register({id:'genshin/maguu_kenki',name:'Masked Dual-Blade'},MaguuKenki,{intent:mkIntent,penalty:mkPenalty,arena:13.8, + gain:(g,c,intent,base)=>(base.hp-c.boss.hp)+(c.boss.phase>base.phase?3000:0),base:c=>({hp:c.boss.hp,phase:c.boss.phase})}); + M.kenki=MK;M.kenkiMoveNames=NAMES; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/genshin_remake/boss_signora.js b/environments/games/web/games/genshin_remake/boss_signora.js new file mode 100644 index 0000000000000000000000000000000000000000..3c55ca9815fdc98e87b81b4adb1089675cdd0184 --- /dev/null +++ b/environments/games/web/games/genshin_remake/boss_signora.js @@ -0,0 +1,287 @@ +/* La Signora La Signora (genshin/signora). Sources: Fandom La Signora r2178758 (phase 1 Cryo / phase 2 Pyro, hp_ratio 10 / 20, + * atk_ratio 4.8, Cryo 50% RES in phase 1 and Pyro 70% in phase 2, Sheer Cold / Blazing Heat 3.33%/s with 3% Max HP + 150 HP/s + * loss when full, Hearts of Flame / Eyes of Frost (12.5%/s relief, 7 hits to destroy, respawn when fewer than two remain), + * Pain for Pain cap 30% / 20% of Max HP, every ability's ratio and gauge gain, Carmine Chrysalis at 20% with a 60 GU Cryo + * shield and 8 GU Pyro moths) and BWIKI La Signora (skill list). Ratios, gauge rates and caps follow the sources; tick counts, + * radii, speeds, the respawn delay and the selection deck are BossBench calibrations. HP and ATK are tier calibrations. */ +(function(root){ + 'use strict'; + const M=root.GenshinGame,N=root.NativeBench,I=M.internals; + const {DuelFight,HZ,PI,TAU,clamp,dist,angle,forward,wrap,byTier}=I; + const SG={hp:[11800,38500,135000],atk:3300,arena:16,phase2Share:2/3,cocoonAt:.2, + temp:{rate:3.33,relief:12.5,lossPct:.03,lossFlat:150,weak:2,strong:5,floor:2.5,beacons:4,beaconR:2.6,beaconHits:7,respawn:600, + corners:[[-11,-11],[11,-11],[-11,11],[11,11]]}, + cap:[.3,.2], + // The 60 GU shield and 8 GU moths are documented; the moth spawn period and the Whirling Blaze length are not, so both are + // calibrated per tier (byTier anchors) — the cocoon and the blaze are fixed-time segments that HP scaling cannot shorten. + cocoon:{gauge:60,mothGU:8,mothEvery:[100,360,420],iceTicks:180},blazeTicks:[180,480,600], + moves:{ + wheel:{tell:30,shards:5,spread:.12,speed:13,wheelSpeed:9,ratio:.375,recovery:40}, + hail:{tell:40,radius:2.6,ratio:.75,floor:420,recovery:30}, + flower:{tell:30,count:3,fuse:90,radius:1.8,ratio:.375,floor:360,recovery:24}, + biting:{tell:34,count:5,gap:14,speed:9,turn:.06,ratio:.25,recovery:30}, + snowfall:{tell:44,radius:4.2,ratio:.5,recovery:30}, + benevolence:{tell:80,radius:2.4,ratio:1,recovery:40}, + frozenVoid:{tell:48,ratio:.5,fuse:240,boomR:3.4,boom:.75,recovery:30}, + lash:{tell:24,radius:4.6,half:.8,ratio:.5,recovery:30}, + lashLong:{tell:30,length:9,width:.9,ratio:.5,recovery:30}, + lashTriple:{tell:40,radius:9,half:.55,ratio:.5,boom:.75,boomDelay:24,recovery:36}, + warp:{ticks:34,speed:14,radius:1.4,ratio:.375,recovery:16}, + fireball:{tell:28,speed:7,radius:1.3,ratio:.625,life:200,recovery:24}, + wrath:{tell:50,waves:3,gap:36,count:5,radius:2.2,ratio:1,fall:40,recovery:30}, + onslaught:{tell:30,count:6,radius:1.2,ratio:.25,speed:10,recovery:30}, + moth:{tell:20,speed:6,ratio:.375,life:240,recovery:16}, + blaze:{speed:5,radius:1.6,ratio:.75,miniEvery:180,miniRatio:.375,miniSpeed:6,recovery:40} + }, + counter:{radius:6,ratio:1.25}}; + const NAMES={wheel:'Ice Shard Fan',hail:'Targeted Ice Fall',flower:'Triple Ice Burst',biting:'Homing Ice Spears',snowfall:'Close Ice Burst',benevolence:'Underfoot Ice Array',frozenVoid:'Delayed Giant Spear', + cocoon:'Ice Shell Charge',lash:'Fire Whip Slash',lashLong:'Fire Whip Thrust',lashTriple:'Triple Fire Whip',warp:'Close-Range Dash',fireball:'Slow Fireball',wrath:'Falling Fire Pillars',onslaught:'Floating Flame Volley',moth:'Homing Flame',blaze:'Patrol Fire Whirl',counter:'Retaliation'}; + const DECK={1:['hail','flower','biting','snowfall','frozenVoid','wheel'],2:['lash','lashLong','lashTriple','warp','fireball','wrath','onslaught','moth']}; + class Signora extends DuelFight{ + constructor(id,seed,d){ + super(id,seed,d,{atk:SG.atk,arena:SG.arena,base:.1,res:{cryo:.5},element:'cryo',interval:1.5}); + const total=Math.round(byTier(SG.hp,d)),hp1=Math.round(total*(1-SG.phase2Share)),hp2=total-hp1; + // Pain for Pain caps hits above 30% / 20% of Max HP. The rule is anti-burst and rare at source HP scale; tier HP shrinks easy + // to a few thousand, where ordinary skills would cross it. Deviation (recorded): the threshold uses max(own, normal-tier) HP. + const nTotal=Math.round(byTier(SG.hp,M.tiers.normal)),n1=Math.round(nTotal*(1-SG.phase2Share));this.capBase=[Math.max(hp1,n1),Math.max(hp2,nTotal-n1)]; + this.boss={id:0,kind:'signora',x:0,z:-5,y:0,yaw:0,hp:hp1,maxHp:hp1,phaseHp:[hp1,hp2],phase:1,mode:'intro',move:null,moveTick:0,timer:50,tellTicks:0, + action:'idle',actionTick:0,r:.7,cy:1.3,hh:1.4,cds:{},shared:{},interval:0,aura:null,frozen:0,hpFloor:Math.round(hp1*SG.cocoonAt),thresholds:[],deck:[],lifeStart:0, + cocoon:null,blaze:null,warped:0,walk:0}; + this.temp=0;this.beacons=[];this.floors=[];this.moths=[];this.beaconTimer=0;this.player.z=7;this.placeBeacons(); + Object.assign(this.stats,{moves:Object.fromEntries(Object.keys(NAMES).map(k=>[k,0])),counters:0,beaconBreaks:0,tempLossTicks:0,mothPicks:0,cocoonGauge:0}); + } + moveName(m){return NAMES[m]||'';} + tempName(){return this.boss.phase===1?'Sheer Cold':'Heat';} + placeBeacons(){this.beacons=SG.temp.corners.map(([x,z])=>({id:this.idNext(),kind:'beacon',x,z,y:0,r:.7,hits:SG.temp.beaconHits,lastHit:-100}));} + // Total progress for the public health(): phase 1 HP plus the untouched phase 2 bar. The bar held at 20% drains with the cocoon's + // shield, so progress never steps backward and breaking the shield is worth what it looks like. + health(){const b=this.boss,rest=b.phase===1?b.phaseHp[1]:0,own=b.cocoon?b.hp*b.cocoon.gauge/b.cocoon.maxGauge:b.hp; + return [this.party.reduce((s,p)=>s+p.hp,0),this.party.reduce((s,p)=>s+p.maxHp,0),this.outcome==='win'?0:Math.max(0,own)+rest,b.phaseHp[0]+b.phaseHp[1]];} + aliveTargets(){const b=this.boss;if(b.mode==='dead')return [];const out=[];if(b.cocoon)out.push(b.cocoon);else if(!b.blaze)out.push(b); + for(const q of this.beacons)if(q.hits>0)out.push(q);return out;} + targetable(q){return q.kind!=='beacon'||dist(this.player,q)<5;} + fallbackTargets(all){return all;} + lookAnchor(){return this.boss;} + aimPoint(q){return {x:q.x,y:(q.y||0)+(q.kind==='beacon'?1:1.3),z:q.z};} + entity(id){if(id===0)return this.boss;if(this.boss.cocoon&&this.boss.cocoon.id===id)return this.boss.cocoon;return this.beacons.find(q=>q.id===id)||null;} + projectileHits(q,old,a){return this.segmentDistance(q,old,a)<(q.r||.7)+.1&&a.y>(q.y||0)-.1&&a.y<(q.y||0)+(q.kind==='cocoon'?4:2.6);} + hitTarget(q,hit){ + if(q.kind==='beacon'){ + // Hearts of Flame / Eyes of Frost break after 7 hits (durability is hit-based) and clear the gauge and nearby floors. + if(q.hits<=0||this.t-q.lastHit<6)return false;q.lastHit=this.t;q.hits--;this.fx('impact',{x:q.x,z:q.z,y:1,element:this.boss.phase===1?'pyro':'cryo'}); + if(q.hits<=0){this.stats.beaconBreaks++;this.temp=0;this.floors=this.floors.filter(f=>Math.sign(f.x)!==Math.sign(q.x)||Math.sign(f.z)!==Math.sign(q.z));this.emit('beacon_broken'); + this.fx('beacon_burst',{x:q.x,z:q.z,y:1,element:this.boss.phase===1?'pyro':'cryo',life:40});} + return true;} + if(q.kind==='cocoon'){ + // Carmine Chrysalis: 60 GU Cryo shield (Elemental Shield Data: Pyro 2x); a moth-imbued attack applies 8 GU Pyro. + if(q.gauge<=0||!this.application(hit,q))return false;const amount=hit.element==='pyro'?2*hit.gauge:0;if(!amount)return false; + q.gauge=Math.max(0,q.gauge-amount);this.stats.cocoonGauge+=amount;this.fx('reaction',{x:q.x,z:q.z,y:2.6,element:'pyro',reaction:'melt',gauge:amount,life:54}); + if(q.gauge<=0)this.breakCocoon();return true;} + const b=q;if(b.mode==='dead'||b.mode==='intro'||b.blaze)return false; + // Pain for Pain: a single hit above 30% (phase 1) / 20% (phase 2) of Max HP is capped, she counters and fills the gauge. + const cap=SG.cap[b.phase-1]*this.capBase[b.phase-1],before=b.hp;this.bossHit(b,hit,{cap}); + if(before-b.hp>=cap-1e-6)this.counter(); + if(b.phase===1&&!b.cocoon&&b.mode!=='cocoon'&&b.hp<=b.hpFloor+1e-6)this.beginCocoon(); + if(b.phase===2&&!b.blazeDone&&b.hp<=b.hpFloor+1e-6&&b.mode!=='attack')this.beginBlaze(); + if(b.phase===2&&b.hp<=1e-6){b.hp=0;this.outcome='win';b.mode='dead';b.action='dead';b.actionTick=0;this.hazards=this.hazards.filter(h=>h.src!==0);this.emit('boss_defeated');} + return true; + } + counter(){const b=this.boss,C=SG.counter;this.stats.counters++;this.stats.moves.counter++;this.emit('pain_for_pain'); + this.hazard('circle',{x:b.x,z:b.z,radius:C.radius,height:3,life:6,damage:this.bossDamage(C.ratio),element:b.phase===1?'cryo':'pyro',src:0});this.temp=100; + this.fx('counter',{x:b.x,z:b.z,y:1,element:b.phase===1?'cryo':'pyro',life:36});} + gainTemp(amount){this.temp=Math.min(100,this.temp+amount);} + hurt(amount,element,source){const ok=super.hurt(amount,element,source);if(ok&&source&&source.temp)this.gainTemp(source.temp);if(ok&&source&&source.floorHit)this.floor(this.player.x,this.player.z,1.4,360);return ok;} + beginCocoon(){const b=this.boss,C=SG.cocoon;this.cancel();b.x=0;b.z=0;b.y=0;b.hpFloor=b.hp;b.mode='cocoon';b.move='cocoon';b.moveTick=0;b.action='cocoon'; + b.cocoon={id:this.idNext(),kind:'cocoon',x:0,z:0,y:0,r:1.6,gauge:C.gauge,maxGauge:C.gauge};this.stats.moves.cocoon++;this.emit('carmine_chrysalis');} + breakCocoon(){const b=this.boss;b.cocoon=null;this.moths=[];this.hazards=this.hazards.filter(h=>h.src!==0);this.floors=[];this.temp=0; + // Phase 2: the Crimson Witch of Embers. She waits in the centre until the player approaches or strikes (Fandom). The bar holds + // at 20% until Whirling Blaze has played, so a burst cannot skip it and the fight length does not depend on where the last hit falls. + b.phase=2;b.hp=b.phaseHp[1];b.maxHp=b.phaseHp[1];b.hpFloor=Math.round(b.maxHp*SG.cocoonAt);b.mode='intro2';b.timer=90;b.deck=[];b.lifeStart=this.t;this.cfg.res={pyro:.7};this.hazardElement='pyro'; + // A cutscene repositions her in the middle with the player placed away (Fandom); 11 m is calibrated. + const P=this.player,a=angle(b,P);P.x=b.x+Math.sin(a)*11;P.z=b.z+Math.cos(a)*11; + this.placeBeacons();this.emit('phase_2');this.fx('cocoon_break',{x:0,z:0,y:2,life:50});} + beginBlaze(){const b=this.boss,B=SG.moves.blaze;this.cancel();b.blazeDone=true;b.hpFloor=0;b.blaze={t:0,x:0,z:0};b.mode='blaze';b.move='blaze';b.moveTick=0;b.action='blaze';this.stats.moves.blaze++;this.emit('whirling_blaze');} + cancel(){const b=this.boss;this.hazards=this.hazards.filter(h=>!(h.src===0&&(h.age=2700&&!b.benevolenceAt){b.benevolenceAt=this.t;return 'benevolence';} + if(b.phase===1&&b.benevolenceAt&&this.t-b.benevolenceAt>=1800){b.benevolenceAt=this.t;return 'benevolence';} + return b.deck.pop();} + begin(m){const b=this.boss,T=this.aggroTarget(b),mv=SG.moves[m];b.mode='attack';b.move=m;b.moveTick=0;b.action=m;b.actionTick=0; + b.tellTicks=Math.round((mv.tell||0)*this.pace());b.targetX=T.x;b.targetZ=T.z;b.count=0;this.stats.moves[m]++;this.emit('tell_'+m); + // Snowfall Strike: teleports close first if the player is far (Fandom). + if(m==='snowfall'&&dist(b,T)>6){const a=angle(T,b),f=forward(a);const L=this.clampArena({x:T.x+f.x*2,z:T.z+f.z*2},1.5);b.x=L.x;b.z=L.z;this.fx('afterimage',{x:b.x,z:b.z,y:0,life:24});} + if(m==='frozenVoid'){b.spear={x:T.x,z:T.z};} + if(m==='benevolence'){b.ring={x:T.x,z:T.z};}} + finish(){const b=this.boss;b.mode='idle';b.move=null;b.action='idle';b.timer=Math.round(36*this.aggression());} + floor(x,z,r,life){this.floors.push({x,z,r,age:0,life,el:this.boss.phase===1?'cryo':'pyro'});if(this.floors.length>24)this.floors.shift();} + sigMove(){ + const b=this.boss,t=b.moveTick++,T=this.aggroTarget(b),mv=SG.moves[b.move],tell=b.tellTicks,P=this.player,S=SG.temp; + const strong=S.strong,weak=S.weak,el=b.phase===1?'cryo':'pyro'; + switch(b.move){ + case 'wheel':{if(t=tell+mv.recovery)this.finish();return;} + case 'hail':{if(t===tell){const L=this.clampArena({x:b.targetX,z:b.targetZ},1);this.hazard('circle',{x:L.x,z:L.z,radius:mv.radius,delay:30,life:36,height:6,damage:this.bossDamage(mv.ratio),element:'cryo',src:0,temp:strong,hail:true});b.hailAt=L;} + if(t===tell+30&&b.hailAt)this.floor(b.hailAt.x,b.hailAt.z,mv.radius,mv.floor);if(t>=tell+mv.recovery+30)this.finish();return;} + case 'flower':{if(t===tell)for(let i=0;i=tell+mv.recovery)this.finish();return;} + case 'biting':{if(t=mv.gap*mv.count+mv.recovery)this.finish();return;} + case 'snowfall':if(t===tell){this.hazard('circle',{x:b.x,z:b.z,radius:mv.radius,height:2.6,life:6,damage:this.bossDamage(mv.ratio),element:'cryo',src:0,temp:strong});this.fx('frost_burst',{x:b.x,z:b.z,y:0,life:30});} + if(t>=tell+mv.recovery)this.finish();return; + case 'benevolence':{// Six ice spears surround the player and converge (Fandom). + if(t===tell){const R=b.ring;this.hazard('circle',{x:R.x,z:R.z,radius:mv.radius,height:3,life:6,damage:this.bossDamage(mv.ratio),element:'cryo',src:0,temp:strong});this.floor(R.x,R.z,mv.radius,420);} + if(t>=tell+mv.recovery)this.finish();return;} + case 'frozenVoid':{// A large spear tracks the player, strikes (50%), then explodes 4 s later (75%) and leaves Frosted Floor. + if(t=tell+mv.recovery)this.finish();return;} + case 'lash':{if(t0){b.warped=0;this.cone(mv.radius,mv.half,mv.ratio,'pyro',{temp:strong});this.fx('whip',{x:b.x,z:b.z,y:1.2,angle:b.yaw,life:16});} + if(t>=tell+mv.recovery+14)this.finish();return;} + case 'lashLong':{// A single strike in front of her with a longer range (Fandom Decimating Lash, third variation). + if(t=tell+mv.recovery)this.finish();return;} + case 'lashTriple':{if(t=tell+mv.recovery+mv.boomDelay)this.finish();return;} + case 'warp':{// Cloaked in flame she moves to a new spot, burning what she passes and leaving Embered Earth; a double lash follows. + if(t===0){const a=angle(P,b)+(N.rand(this)<.5?1:-1)*(.9+N.rand(this)*.6),r=2.4;const L=this.clampArena({x:P.x+Math.sin(a)*r,z:P.z+Math.cos(a)*r},1.5);b.warpTo=L;b.warpFrom={x:b.x,z:b.z};} + const u=Math.min(1,(t+1)/mv.ticks),W=b.warpTo,F=b.warpFrom;const old={x:b.x,z:b.z};b.x=F.x+(W.x-F.x)*u;b.z=F.z+(W.z-F.z)*u; + this.hazard('sweep',{x:old.x,z:old.z,toX:b.x,toZ:b.z,radius:mv.radius,height:2,life:1,damage:this.bossDamage(mv.ratio),element:'pyro',src:0,temp:strong});if(t%8===0)this.floor(b.x,b.z,1.3,300); + if(u>=1){b.warped=1;this.finish();this.begin('lash');}return;} + case 'fireball':{if(t=tell+mv.recovery)this.finish();return;} + case 'wrath':{const k=t-tell;if(k>=0&&k%mv.gap===0&&k=mv.gap*mv.waves+mv.recovery){this.finish();if(N.rand(this)<.5)this.begin('fireball');}return;} + case 'onslaught':{if(t=tell+mv.recovery){this.finish();if(N.rand(this)<.5)this.begin('fireball');}return;} + case 'moth':{if(t===tell){const f=forward(angle(b,P));this.hazard('bolt',{x:b.x+f.x,z:b.z+f.z,y:1.2,vx:f.x*mv.speed/HZ,vz:f.z*mv.speed/HZ,radius:.6,life:mv.life,height:2.4,damage:this.bossDamage(mv.ratio),element:'pyro',src:0,consume:true,temp:strong,homing:true,turn:.05,lotus:true});} + if(t>=tell+mv.recovery)this.finish();return;} + } + } + // Homing bolts (Biting Shards, the Frozen Wheel, Crimson Lotus Moths) steer toward the player each tick. + steer(){const P=this.player;for(const h of this.hazards){if(!h.homing||h.spent)continue;const sp=Math.hypot(h.vx,h.vz),want=angle(h,P),cur=Math.atan2(h.vx,h.vz),na=cur+clamp(wrap(want-cur),-h.turn,h.turn); + h.vx=Math.sin(na)*sp;h.vz=Math.cos(na)*sp;if(h.trailFloor&&h.age%10===0)this.floor(h.x,h.z,1.1,300);} + for(const h of this.hazards)if(h.trailFloor&&!h.homing&&h.age%10===0)this.floor(h.x,h.z,1.1,300); + // Delayed explosions that leave a floor create it as they go off. + for(const h of this.hazards)if(h.floorAfter&&h.age===h.delay)this.floor(h.x,h.z,h.radius||1.6,h.floorAfter);} + updateTemp(){ + // Sheer Cold / Blazing Heat (Fandom): +3.33%/s on the field, depleting 12.5%/s near a Heart of Flame / Eye of Frost, floors + // add 2.5% per DoT hit; when full the active character loses 3% Max HP + 150 HP per second. Doubled in the cocoon. + const S=SG.temp,P=this.player,b=this.boss;if(b.mode==='intro'||b.mode==='intro2'&&dist(P,b)>9)return; + const near=this.beacons.some(q=>q.hits>0&&dist(P,q)dist(P,f)=100&&this.t%60===0){const q=this.owner(),loss=q.maxHp*S.lossPct+S.lossFlat;const inv=P.inv;P.inv=0;this.hurt(loss/((TUNING_DEF(q))*.9),'physical',{light:true,pure:true});P.inv=inv;this.stats.tempLossTicks++;} + // Beacons respawn over time when fewer than two remain: the northeast corner first, then the southwest (Fandom); calibrated 10 s. + if(this.beacons.filter(q=>q.hits>0).length<2){if(++this.beaconTimer>=S.respawn){this.beaconTimer=0;const dead=[1,2].map(i=>this.beacons[i]).find(q=>q.hits<=0);if(dead){dead.hits=S.beaconHits;this.emit('beacon_respawn');}}}else this.beaconTimer=0; + for(const f of this.floors)f.age++;this.floors=this.floors.filter(f=>f.age=3600)){this.beginBlaze();return;} + if(b.timer>0)b.timer--;const T=this.aggroTarget(b); + if(!b.timer){this.begin(this.pickMove());return;} + const off=this.turnToward(T,.08),d=dist(b,T);b.action=d>5?'walk':'idle';if(d>5&&off<1){this.stepBoss(b.yaw,2.6);b.walk+=2.6/HZ;} + } + cocoonTick(){ + // Carmine Chrysalis: only Biting Shards (enhanced, 9 spears) and Ice Flower drops; Crimson Lotus Moths spawn to pick up. + const b=this.boss,C=SG.cocoon,t=b.moveTick++,P=this.player; + if(t%Math.round(byTier(C.mothEvery,this.d))===40){const a=N.rand(this)*TAU,r=5+N.rand(this)*6;this.moths.push({id:this.idNext(),x:Math.sin(a)*r,z:Math.cos(a)*r,age:0});} + for(const m of this.moths){m.age++;if(dist(P,m)<1.1){m.taken=true;this.player.mothPyro=1;this.stats.mothPicks++;this.emit('moth_picked');}} + this.moths=this.moths.filter(m=>!m.taken&&m.age<900); + if(t%C.iceTicks===90){const a=N.rand(this)*TAU,L=this.clampArena({x:P.x+Math.sin(a)*1.2,z:P.z+Math.cos(a)*1.2},1); + this.hazard('circle',{x:L.x,z:L.z,radius:1.8,delay:80,life:86,height:2.4,damage:this.bossDamage(.375),element:'cryo',src:2,temp:SG.temp.weak,flower:true,floorAfter:360,landing:true});} + const k=t%300-150;if(k>=0&&k<54&&k%6===0){const a=k/6*TAU/9+angle(b,P),f=forward(a);this.hazard('bolt',{x:f.x*1.8,z:f.z*1.8,y:1.6,vx:f.x*7/HZ,vz:f.z*7/HZ,radius:.35,life:150,height:2.4,damage:this.bossDamage(.25),element:'cryo',src:0,consume:true,temp:SG.temp.weak,homing:true,turn:.07,spear:true,floorHit:true});} + // The Tsaritsa's Benevolence survives into the cocoon (Fandom) and keeps its "too long" meaning here; calibrated at 30 s. + if(t>0&&t%1800===0){const L=this.clampArena({x:P.x,z:P.z},1),mv=SG.moves.benevolence;this.hazard('circle',{x:L.x,z:L.z,radius:mv.radius,delay:mv.tell,life:mv.tell+6,height:3,damage:this.bossDamage(mv.ratio),element:'cryo',src:2,temp:SG.temp.strong,floorAfter:420,landing:true});} + } + blazeTick(){ + // Whirling Blaze: an untargetable tornado roams the arena, spawning 4 mini-tornadoes every ~3 s, then +50% Blazing Heat. + const b=this.boss,B=SG.moves.blaze,t=b.moveTick++,P=this.player,z=b.blaze; + const a=t*.011,R=7;const old={x:b.x,z:b.z};b.x=Math.sin(a)*R*Math.cos(a*.7);b.z=Math.cos(a*1.3)*R*.8; + this.hazard('sweep',{x:old.x,z:old.z,toX:b.x,toZ:b.z,radius:B.radius,height:3,life:1,damage:this.bossDamage(B.ratio),element:'pyro',src:0,temp:SG.temp.strong});if(t%10===0)this.floor(b.x,b.z,1.4,300); + if(t%B.miniEvery===60)this.miniTornadoes(); + // At the end she spreads her wings in the middle: +50% Blazing Heat and another 4 mini-tornadoes (Fandom). + if(t>=Math.round(byTier(SG.blazeTicks,this.d))){b.x=0;b.z=0;this.gainTemp(50);this.miniTornadoes();b.blaze=null;b.mode='idle';b.timer=60;this.emit('blaze_end');} + } + miniTornadoes(){const b=this.boss,B=SG.moves.blaze,P=this.player;for(let i=0;i<4;i++){const aa=i===0?angle(b,P):i*TAU/4+N.rand(this),f=forward(aa);this.hazard('bolt',{x:b.x+f.x,z:b.z+f.z,y:.6,vx:f.x*B.miniSpeed/HZ,vz:f.z*B.miniSpeed/HZ,radius:.9,life:180,height:3,damage:this.bossDamage(B.miniRatio),element:'pyro',src:0,consume:true,temp:SG.temp.weak,mini:true});}} + // Moth-imbued attacks: the next hit after picking a moth applies 8 GU Pyro (Fandom Carmine Chrysalis). + hit(target,hit){if(this.player.mothPyro&&this.boss.cocoon&&target===this.boss.cocoon&&hit.damage>0){this.player.mothPyro=0;hit={...hit,element:'pyro',gauge:SG.cocoon.mothGU,noICD:true};} + if(target===this.boss&&this.boss.mode==='intro2')this.boss.provoked=true;return super.hit(target,hit);} + } + // Temperature HP loss is a percentage of Max HP; hurt() applies DEF and 0.9, so pre-divide to land the exact amount. + function TUNING_DEF(q){const L=M.tuning.bossLevel;return (L+100)/(L+100+q.def/5);} + // ---------------------------------------------------------------- reference controller plan + const {KAEYA,AMBER,XIANGLING,BARBARA}=I; + function sgIntent(g){ + const H=I.helpers(g),{p,party,ai,skillReady,burstReady,low,hpFrac}=H,b=g.boss,d=dist(p,b); + const out={want:ai,action:null,anchor:0,desired:3,weight:1.3,holdJ:false,charge:false,bunny:0,mode:'fight'}; + const choose=I.chooser(out,H),heal=[];if(burstReady(BARBARA)&&(low>=1||hpFrac<.55))heal.push([BARBARA,'L',{}]);if(skillReady(BARBARA)&&(hpFrac<.75||low))heal.push([BARBARA,'K',{}]); + // Relieve the temperature gauge at the nearest beacon; break it only when the gauge is nearly full. + const beacon=g.beacons.filter(q=>q.hits>0).sort((a,c)=>dist(p,a)-dist(p,c))[0]; + // A held moth (8 GU Pyro on the next hit) goes straight to the cocoon before anything else short of a full gauge. + const holdingMoth=b.cocoon&&p.mothPyro&&g.temp<96,mothWork=b.cocoon&&(p.mothPyro||g.moths.length&&b.cocoon.gauge>4)&&g.temp<88; + // After Whirling Blaze the bar is low and she stands in the centre: finishing her beats walking to a beacon unless the gauge is nearly full. + const coolAt=b.blazeDone&&b.mode!=='blaze'?97:72; + if(beacon&&g.temp>=coolAt&&!holdingMoth&&!mothWork){out.anchor=beacon.id;out.desired=g.temp>=92?1.2:1.8;out.weight=1.6;out.mode='cool'; + const list=[...heal];if(g.temp>=92)list.push([KAEYA,'J',{holdJ:true,desired:1.2}],[XIANGLING,'J',{holdJ:true,desired:1.3}]);choose(list);return out;} + if(b.cocoon){out.anchor=b.cocoon.id;out.desired=3.2;out.weight=1.4;out.mode='cocoon'; + // The last few GU fall to any Pyro hit: walking to a moth for them only wastes time. + const moth=b.cocoon.gauge>4&&g.moths.slice().sort((a,c)=>dist(p,a)-dist(p,c))[0];if(moth&&!p.mothPyro){out.anchor=-1;out.home=false;out.mothTarget={x:moth.x,z:moth.z};out.weight=1.6;} + if(p.mothPyro){out.desired=2.4;out.weight=1.8;} + const list=[...heal];if(burstReady(XIANGLING))list.push([XIANGLING,'L',{desired:3}]);if(skillReady(XIANGLING))list.push([XIANGLING,'K',{desired:2.8}]); + if(burstReady(AMBER))list.push([AMBER,'L',{desired:5}]);list.push([XIANGLING,'J',{holdJ:true,desired:2.6}],[AMBER,'charge',{charge:true,desired:5}]);choose(list);return out;} + if(b.mode==='intro2'){out.mode='approach';out.desired=5.5;out.weight=1;choose([...heal,[KAEYA,null,{}]]);return out;} + if(b.mode==='blaze'){out.mode='wait';out.anchor=beacon?beacon.id:-1;out.home=!beacon;out.desired=1.6;out.weight=.8;if(!choose(heal))choose([[AMBER,'charge',{charge:true,keep:true}]]);return out;} + const list=[...heal],phase2=b.phase===2; + // Phase 1 resists Cryo (50%); phase 2 resists Pyro (70%): the damage dealers swap with the phase. + if(!phase2){if(burstReady(XIANGLING))list.push([XIANGLING,'L',{desired:3}]);if(skillReady(XIANGLING))list.push([XIANGLING,'K',{desired:2.6}]);if(burstReady(AMBER))list.push([AMBER,'L',{desired:5}]); + if(skillReady(AMBER)&&d<7)list.push([AMBER,'bunny',{bunny:Math.round((clamp(d*.6,2,8)-2)*20),desired:3.4}]);} + else{if(skillReady(KAEYA))list.push([KAEYA,'K',{desired:2.4}]);if(burstReady(KAEYA))list.push([KAEYA,'L',{desired:2.2}]);} + const cur=party[ai].id;if(!phase2&&(cur==='xiangling'||cur==='amber'))list.push([ai,cur==='amber'?'charge':'J',cur==='amber'?{charge:true,desired:5}:{holdJ:true,desired:2.6}]); + // Phase 2: Kaeya's Cryo and Xiangling's Physical spear do the work (Pyro is resisted 70%); Barbara only heals. + if(phase2&&(cur==='kaeya'||cur==='xiangling'))list.push([ai,'J',{holdJ:true,desired:cur==='kaeya'?2.2:2.6}]); + if(!phase2)list.push([XIANGLING,'J',{holdJ:true,desired:2.6}],[AMBER,'charge',{charge:true,desired:5}]);else list.push([KAEYA,'J',{holdJ:true,desired:2.2}],[XIANGLING,'J',{holdJ:true,desired:2.6}]); + choose(list);if(g.auras.some(a=>a.kind==='pyronado')&&out.action!=='charge')out.desired=3.3; + return out; + } + function sgPenalty(g,c){const b=c.boss,p=c.player;if(b.mode==='dead')return 0;let pen=0; + const chasing=g.boss.cocoon&&!g.player.mothPyro&&g.moths.length;for(const f of c.floors)if(dist(p,f)=100)pen+=240; + if(b.mode==='attack'&&(b.move==='snowfall'||b.move==='lash')&&b.moveTick0&&along<9.4&&lat<1.3)pen+=140*(1.3-lat);} + if(b.mode==='attack'&&b.move==='lashTriple'&&b.moveTick({prog:c.health()[2],temp:c.temp})}); + M.signora=SG;M.signoraMoveNames=NAMES; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/genshin_remake/compact_actions.json b/environments/games/web/games/genshin_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..60e5d2398c93bffad0f8be25607d600cf6a8bb55 --- /dev/null +++ b/environments/games/web/games/genshin_remake/compact_actions.json @@ -0,0 +1,204 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "genshin_remake", + "version": "genshin-compact@2", + "note": "A 200 ms packet combines movement, view or character switching, and one action. Positive mouse dx turns right and positive dy lowers the aim. The unlocked camera applies mouse movement over the packet. Charge and release actions follow the listed sub-step timings.", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W" + ] + }, + { + "label": "back", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "forward_left", + "keys": [ + "W", + "A" + ] + }, + { + "label": "forward_right", + "keys": [ + "W", + "D" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D" + ] + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "attack", + "keys": [ + "J" + ] + }, + { + "label": "charge", + "keys": [ + "LMB" + ] + }, + { + "label": "charge_release", + "subs": [ + [ + "LMB" + ], + [ + "LMB" + ], + [ + "LMB" + ], + [], + [], + [] + ] + }, + { + "label": "shot", + "tap": [ + "LMB" + ] + }, + { + "label": "shot_up", + "tap": [ + "LMB" + ], + "dy": -44 + }, + { + "label": "shot_down", + "tap": [ + "LMB" + ], + "dy": 44 + }, + { + "label": "skill", + "tap": [ + "K" + ] + }, + { + "label": "skill_hold", + "keys": [ + "K" + ] + }, + { + "label": "burst", + "tap": [ + "L" + ] + }, + { + "label": "dash", + "tap": [ + "Shift" + ] + }, + { + "label": "jump", + "tap": [ + "Space" + ] + } + ] + }, + { + "name": "view", + "options": [ + { + "label": "none" + }, + { + "label": "next", + "tap": [ + "E" + ] + }, + { + "label": "prev", + "tap": [ + "Q" + ] + }, + { + "label": "lock", + "tap": [ + "R" + ] + }, + { + "label": "lock_left_18", + "tap": [ + "R" + ], + "dx": -126 + }, + { + "label": "left_5", + "dx": -35 + }, + { + "label": "right_5", + "dx": 35 + }, + { + "label": "left_45", + "dx": -314 + }, + { + "label": "right_45", + "dx": 314 + } + ] + } + ] +} diff --git a/environments/games/web/games/genshin_remake/draw.js b/environments/games/web/games/genshin_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..d1e6e88d0cfd607582fe7bed3eeee6de405cea57 --- /dev/null +++ b/environments/games/web/games/genshin_remake/draw.js @@ -0,0 +1,195 @@ +(function(root){ + 'use strict';const M=root.GenshinGame,B=root.Boss3D; + // Element palette shared with renderer3d.js (hex for Canvas). + const EL={pyro:'#ff9a5c',cryo:'#a8ecff',hydro:'#6fc0ff',electro:'#c9a6ff',anemo:'#7fe0c0',geo:'#f0c860',dendro:'#9fdc6a',physical:'#f2ece0',heal:'#8ef0a0',neutral:'#fff3c8'}; + const RX={overload:['Overloaded','#ff8a7a'],superconduct:['Superconduct','#bcb6ff'],electrocharged:['Electro-Charged','#d79cff'],quicken:['Quicken','#a8e070'],swirl:['Swirl','#7fe0c0'],crystallize:['Crystallize','#f0c860'], + vaporize:['Vaporize','#ffcf8a'],melt:['Melt','#ffb070'],frozen:['Frozen','#bff4ff']}; + const ROLE={kaeya:'Cryo · Sword',amber:'Pyro · Bow',xiangling:'Pyro · Polearm',barbara:'Hydro · Catalyst'}; + // Display names by party id. TEAM[].name stays in the hashed state, so the HUD does not read it. + const PARTY={kaeya:'Swordsman',amber:'Archer',xiangling:'Polearm Fighter',barbara:'Healer'}; + const TIER_NAME={easy:'Easy',normal:'Normal',hard:'Hard'}; + const BOSS={'genshin/electro_hypostasis':['Floating Square Array','#b394ee'],'genshin/ruin_guard':['Back-Cannon Colossus','#e3a86a'],'genshin/oceanid':['Tidepool Summoner','#6fc8ff'], + 'genshin/maguu_kenki':['Masked Dual-Blade','#8fd8c8'],'genshin/andrius':['Tundra Wolf','#bfe6f8'],'genshin/signora':['Frost-Flame Caster','#ffb48a']}; + function panel(c,x,y,w,h,fill='rgba(10,18,28,.62)',edge='rgba(226,214,186,.22)'){c.fillStyle=fill;c.fillRect(x,y,w,h);c.strokeStyle=edge;c.lineWidth=1;c.strokeRect(x+.5,y+.5,w-1,h-1);} + function bar(c,x,y,w,h,v,color,back='rgba(8,14,22,.85)'){c.fillStyle=back;c.fillRect(x,y,w,h);c.fillStyle=color;c.fillRect(x+1,y+1,Math.max(0,(w-2)*Math.max(0,Math.min(1,v))),h-2);} + function ring(c,x,y,r,v,color,width=3){c.lineWidth=width;c.strokeStyle='rgba(8,14,22,.8)';c.beginPath();c.arc(x,y,r,0,Math.PI*2);c.stroke();if(v>0){c.strokeStyle=color;c.beginPath();c.arc(x,y,r,-Math.PI/2,-Math.PI/2+Math.PI*2*Math.min(1,v));c.stroke();}} + function txt(c,s,x,y,size,color,align='left',weight=''){c.font=(weight?weight+' ':'')+size+'px "Segoe UI","Microsoft YaHei",sans-serif';c.textAlign=align;c.lineWidth=3;c.strokeStyle='rgba(6,10,16,.85)';c.strokeText(s,x,y);c.fillStyle=color;c.fillText(s,x,y);} + function diamond(c,x,y,r,color){c.fillStyle=color;c.beginPath();c.moveTo(x,y-r);c.lineTo(x+r,y);c.lineTo(x,y+r);c.lineTo(x-r,y);c.closePath();c.fill();} + // Project a world point with the renderer's camera (pure read; returns null when behind the camera). + function project(c,x,y,z){const s=B.scene&&B.scene(c,'genshin');if(!s)return null;return s.project(x,y,z);} + function floating(c,g){ + for(const fx of Array.isArray(g.effects)?g.effects:[]){ + const kind=fx.kind,age=fx.age||0,life=fx.life||36;if(!['dmg','taken','heal','reaction','immune'].includes(kind))continue; + const rise=age*.035,pt=project(c,fx.x||0,(fx.y||1)+rise,fx.z||0);if(!pt)continue;const alpha=Math.max(0,Math.min(1,(life-age)/14));c.globalAlpha=alpha; + const jitter=(((fx.amount||0)*7)%9-4)*7+((Math.round((fx.x||0)*13)+Math.round((fx.z||0)*7))%5-2)*6; + // Pop-in: numbers start 35% larger and settle within a quarter second. + const pop=1+.35*Math.max(0,1-age/14); + if(kind==='dmg'){const big=(fx.amount||0)>=1500||fx.crit,size=Math.round((fx.crit?24:big?21:16)*pop);txt(c,String(fx.amount),pt.x+jitter,pt.y,size,EL[fx.element]||EL.physical,'center','700'); + if(fx.crit)txt(c,'Critical',pt.x+jitter+size*1.4,pt.y-size*.55,11,'#ffe08a','center','700'); +} + else if(kind==='taken')txt(c,'-'+fx.amount,pt.x,pt.y,Math.round(15*pop),'#ff8f8f','center','700'); + else if(kind==='heal')txt(c,'+'+fx.amount,pt.x,pt.y,Math.round(15*pop),EL.heal,'center','700'); + else if(kind==='reaction'&&fx.reaction&&RX[fx.reaction]){txt(c,RX[fx.reaction][0],pt.x,pt.y,Math.round(15*pop),RX[fx.reaction][1],'center','700');if(fx.gauge)txt(c,'-'+(+fx.gauge.toFixed(1))+'U',pt.x,pt.y+15,11,EL[fx.element]||'#fff','center');} + else if(kind==='immune'&&age<20)txt(c,'Immune',pt.x,pt.y,13,'#cfc6e8','center','600'); + c.globalAlpha=1; + } + } + function bossBar(c,g,value,max,color,ticks=[]){ + const x=232,w=390,[name]=BOSS[g.id]||['Boss']; + txt(c,name,427,26,20,'#f3ecdc','center','600');txt(c,'Lv.'+(M.tuning?.bossLevel||80),x+w+6,52,11,'#cfc7b2','left'); + // Damage lag: the recently lost slice fades from white so hits read at a glance (derived from this tick's effects only). + bar(c,x,38,w,10,value/max,color); + c.fillStyle='rgba(255,255,255,.55)';for(const t of ticks)c.fillRect(x+1+(w-2)*t,38,1,10); + txt(c,Math.ceil(Math.max(0,value)).toLocaleString('en-US')+' / '+Math.round(max).toLocaleString('en-US'),427,47,9,'#f6f1ff','center'); + } + function ehHud(c,g){ + const b=g.boss,MOVE=M.moveNames||{};bossBar(c,g,b.hp,b.maxHp,b.mode==='revival'?'#7a6aa8':'#b394ee',[M.tuning?.reviveThreshold||.05,.25,.5,.75]); + let status='',color='#e9d3a8'; + if(g.outcome==='win'){status='Defeated';color='#f3dc9a';} + else if(b.mode==='revival'){status='Reviving · Destroy three crystal blocks';color='#e5d3ff';} + else if(b.exposed){status='Core exposed · Damage it now';color='#f5dc9c';} + else if(b.mode==='tell'||b.mode==='attack'){status=(MOVE[b.move]||'')+(b.mode==='tell'?' · Incoming':'');color='#d9c9ff';} + else status='Shell closed · Immune to Electro'; + txt(c,status,427,66,13,color,'center','600'); + if(b.mode==='revival'){ + const secs=Math.max(0,(b.timer||0)/M.hz),prisms=Array.isArray(b.prisms)?b.prisms:[]; + ring(c,300,93,12,secs/15,'#cdb6ff',3);txt(c,secs.toFixed(1),300,97,10,'#f1e8ff','center','700'); + let n=0;for(const p of prisms){const px=330+n*84,alive=p.alive!==false&&p.active;panel(c,px-2,82,70,22,'rgba(18,14,34,.65)',alive?'rgba(201,166,255,.6)':'rgba(120,110,140,.3)'); + txt(c,'Crystal Blocks'+(n+1),px+3,96,10,alive?'#e9dcff':'#8c86a0');if(alive)bar(c,px+30,89,34,7,(p.gauge||0)/(p.maxGauge||3),'#c9a6ff');else txt(c,'Destroyed',px+34,96,10,'#8c86a0');n++;} + } + } + function rgHud(c,g){ + const b=g.boss,G=M.guard,MOVE=M.guardMoveNames||{};bossBar(c,g,b.hp,b.maxHp,b.mode==='paralyzed'?'#f0c070':'#e3a86a',[.25,.5,.75]); + let status='',color='#e9d3a8';const s=v=>(v/M.hz).toFixed(1)+'s'; + if(g.outcome==='win'){status='Defeated';color='#f3dc9a';} + else if(b.mode==='paralyzed'){status='Paralyzed · Weak point closed; deal damage now '+s(b.timer||0);color='#ffe09a';} + else if((b.frozen||0)>0){status='Frozen '+s(b.frozen);color='#cff4ff';} + else if(b.mode==='stagger'||b.weak&&b.weak.window>0){status='Weak point hit · One more hit will paralyze '+s(b.weak.window||0);color='#ffd27a';} + else if(b.mode==='attack'){status=(MOVE[b.move]||'')+(b.move==='volley'?' · Back weak point exposed':'');color='#f4c9a0';} + else status=b.action==='walk'?'Approaching':'Alert'; + txt(c,status,427,66,13,color,'center','600'); + // Weak points: the eye and the back socket; protective runes block a new disable for a while. + const rune=b.weak&&b.weak.rune>0,hidden=b.mode==='paralyzed'||b.mode==='dead'; + [['Eye Weak Point',334],['Back Weak Point',454]].forEach(([label,x],i)=>{const back=i===1,exposed=!back||b.mode==='attack'&&b.move==='volley'; + panel(c,x-2,76,108,22,'rgba(28,20,12,.62)',hidden?'rgba(120,110,100,.3)':rune?'rgba(111,246,230,.55)':'rgba(255,190,110,.55)'); + diamond(c,x+9,87,5,hidden?'#5d554c':rune?'#6ff6e6':back?'#5ff0e0':'#ffb050'); + txt(c,label,x+19,91,10,hidden?'#8a8478':'#f3e6cf'); + txt(c,hidden?'Close':rune?'Rune '+(b.weak.rune/M.hz).toFixed(0)+'s':exposed?'Hittable':'Facing Away',x+102,91,10,hidden?'#8a8478':rune?'#9ff6ea':exposed?'#ffd27a':'#a99c88','right');}); + } + function ocHud(c,g){ + const b=g.boss,h=typeof g.health==='function'?g.health():[0,0,b.hp,b.maxHp],O=M.oceanid,MOVE=M.oceanidMoveNames||{}; + const waves=(b.plan||[]).length||5;bossBar(c,g,h[2],h[3],'#6fc8ff'); + let status='',color='#cfeaff';const live=(g.mimics||[]).filter(m=>m.hp>0); + if(g.outcome==='win'){status='Defeated';color='#f3dc9a';} + else if(b.mode==='sink'){status=(MOVE.sink||'Platform Sinks')+' · Two platforms are about to sink';color='#9fe0ff';} + else if(b.mode==='summon'){status=(MOVE.summon||'Summon Water Creatures')+' · Wave '+b.wave+' / '+waves;} + else if(b.mode==='wave'){const left=Math.max(0,Math.round((O.torrentTicks*(1.3-.6*g.d))-b.waveTicks)),warn=left<300; + status='Wave '+b.wave+' / '+waves+' · Defeat Hydro Mimics'+(warn?' · '+(MOVE.torrent||'Chasing Whirlpool')+' '+(left/M.hz).toFixed(0)+'s':'');color=warn?'#ffb8a0':'#cfeaff';} + else status='The summoner cannot be attacked directly'; + txt(c,status,427,66,13,color,'center','600'); + // Mimic roster of the current wave, grouped by type, with the elemental weakness. + const groups={};for(const m of live){(groups[m.type]=groups[m.type]||[]).push(m);} + let n=0;for(const [type,list] of Object.entries(groups)){const T=O.types[type],x=286+n*144,hp=list.reduce((s,m)=>s+m.hp,0),max=list.reduce((s,m)=>s+m.maxHp,0); + panel(c,x-2,76,138,24,'rgba(10,26,40,.66)','rgba(111,200,255,.45)');diamond(c,x+9,88,5,EL[T.weak]||'#fff'); + txt(c,T.name+' ×'+list.length,x+19,87,10,'#e6f6ff');bar(c,x+19,91,110,5,hp/max,'#6fc8ff');n++;if(n>=3)break;} + } + function mkHud(c,g){ + const b=g.boss,K=M.kenki,MOVE=M.kenkiMoveNames||{};bossBar(c,g,b.hp,b.maxHp,b.phase===2?'#7fe0d8':'#8fd8c8',[K.phaseAt-.01,.5,.25]); + let status='',color='#d8efe6';const far=Math.hypot(g.player.x-b.x,g.player.z-b.z)>=K.maskRange,guard=far&&!['attack','taunt','dead'].includes(b.mode); + if(g.outcome==='win'){status='Defeated';color='#f3dc9a';} + else if(b.mode==='transition'){status=MOVE.transition+' · Invulnerable · Entering Phase 2';color='#cff4ff';} + else if(b.mode==='taunt'){status=MOVE.taunt+' · Opening';color='#ffe09a';} + else if(b.mode==='attack')status=MOVE[b.move]||''; + else if(guard){status='Mask guard · Attacks beyond 7 m are blocked';color='#ffd27a';} + else status=b.phase===2?'Phase 2 · Clones':'Phase 1 · Stay Close'; + txt(c,status,427,66,13,color,'center','600'); + // The mask rule is range-based: the tag follows the player's distance so the rule reads at a glance. + panel(c,366,76,122,22,'rgba(12,26,26,.62)',guard?'rgba(255,190,110,.6)':'rgba(143,216,200,.5)');diamond(c,377,87,5,guard?'#ffb050':'#8fd8c8'); + txt(c,guard?'Mask · Guarding':'Mask · Lowered',388,91,10,guard?'#ffd27a':'#d8efe6'); + } + function awHud(c,g){ + const b=g.boss,A=M.andrius,MOVE=M.andriusMoveNames||{};bossBar(c,g,b.hp,b.maxHp,b.phase===2?'#9fe8d8':'#bfe6f8',[A.interlude,A.wolvesAt]); + let status='',color='#dff2fb'; + if(g.outcome==='win'){status='Defeated';color='#f3dc9a';} + else if(b.mode==='interlude'){status=MOVE.interlude+' · Invulnerable · Avoid the ice at the arena edge';color='#cff4ff';} + else if(b.mode==='transform'){status='Transforming · Entering Phase 2';color='#9fe8d8';} + else if(b.mode==='attack')status=MOVE[b.move]||''; + else status=b.phase===2?'Phase 2 · Anemo and Cryo':'Phase 1'; + txt(c,status,427,66,13,color,'center','600'); + if(b.phase===2){const alive=(g.pillars||[]).filter(q=>q.gauge>0),wolves=(g.wolves||[]).filter(w=>w.hp>0).length; + panel(c,300,76,124,22,'rgba(12,24,34,.62)','rgba(159,216,255,.5)');diamond(c,311,87,5,'#a8ecff');txt(c,'Ice Pillars × '+alive.length+' · Explode on Roar',321,91,10,'#dff2fb'); + panel(c,430,76,124,22,'rgba(12,24,34,.62)',wolves?'rgba(255,190,110,.6)':'rgba(159,216,255,.3)');diamond(c,441,87,5,wolves?'#ffb050':'#7a8a96');txt(c,'Wolf Pups × '+wolves,451,91,10,wolves?'#ffd27a':'#b8c8d2');} + } + function sgHud(c,g){ + const b=g.boss,S=M.signora,MOVE=M.signoraMoveNames||{},h=g.health(),hot=b.phase===2,temp=g.temp||0; + bossBar(c,g,h[2],h[3],hot?'#ffb48a':'#bfe0f8',[S.phase2Share]); + let status='',color=hot?'#ffe0c8':'#dff2fb'; + if(g.outcome==='win'){status='Defeated';color='#f3dc9a';} + else if(b.mode==='cocoon'){status=MOVE.cocoon+' · Collect flame moths and bring them to the ice cocoon';color='#ffc8a0';} + else if(b.mode==='intro2'){status='Flame form · Approach or attack to start';} + else if(b.mode==='blaze'){status=MOVE.blaze+' · Invulnerable';color='#ffb080';} + else if(b.mode==='attack')status=MOVE[b.move]||''; + else status=hot?'Phase 2 · Pyro':'Phase 1 · Cryo'; + txt(c,status,427,66,13,color,'center','600'); + // Sheer Cold / Blazing Heat gauge, the fight's central clock; full means percentage HP loss every second. + const full=temp>=100,col=hot?'#ff8a4a':'#8fd8ff'; + panel(c,262,76,190,24,'rgba(12,16,28,.66)',full?'rgba(255,120,100,.8)':'rgba(226,214,186,.25)'); + txt(c,(hot?'Heat':'Sheer Cold')+' '+Math.floor(temp)+'%',270,91,10,full?'#ffb0a0':'#f0ead8');bar(c,330,84,116,8,temp/100,full?'#ff6a5a':col); + const beacons=(g.beacons||[]).filter(q=>q.hits>0).length; + panel(c,458,76,134,24,'rgba(12,16,28,.66)','rgba(226,214,186,.25)');diamond(c,469,88,5,hot?'#a8ecff':'#ff9a5c'); + txt(c,(hot?'Cryo Lamps':'Braziers')+' × '+beacons,479,91,10,'#f0ead8'); + if(b.cocoon){panel(c,262,102,190,20,'rgba(12,16,28,.66)','rgba(255,160,110,.5)');txt(c,'Ice Cocoon '+Math.ceil(b.cocoon.gauge)+'U',270,116,10,'#ffd9c0');bar(c,330,108,116,7,b.cocoon.gauge/b.cocoon.maxGauge,'#bfe6f8'); + panel(c,458,102,134,20,'rgba(12,16,28,.66)',g.player.mothPyro?'rgba(255,160,110,.8)':'rgba(226,214,186,.25)');txt(c,g.player.mothPyro?'Flame Infused · Next hit 8U':'Flame Moths × '+(g.moths||[]).length,466,116,10,g.player.mothPyro?'#ffc8a0':'#f0ead8');} + } + function partyHud(c,g){ + const p=g.player,party=Array.isArray(g.party)?g.party:[]; + for(let i=0;i=q.maxEnergy&&!q.burstCD;ring(c,x+w-20,y+34,9,(q.energy||0)/(q.maxEnergy||1),ready?'#fff1b8':col,3); + if(ready){txt(c,'L',x+w-20,y+38,10,'#fff1b8','center','700');}else if(q.burstCD)txt(c,Math.ceil(q.burstCD/M.hz),x+w-20,y+38,9,'#c9d2d8','center'); + const skill=q.skillCD>0?Math.ceil(q.skillCD/M.hz)+'s':'K';txt(c,skill,x+w-48,y+45,10,q.skillCD>0?'#9fb0b8':'#f6e7b0','center','700'); + if(q.pepper>0){c.fillStyle='#ff7a4a';c.beginPath();c.arc(x+w-62,y+41,3,0,Math.PI*2);c.fill();} + if(q.wet>0){c.fillStyle=EL.hydro;c.beginPath();c.arc(x+w-72,y+41,3,0,Math.PI*2);c.fill();} + } + if(p.swapCD>0)txt(c,'Switch Cooldown '+(p.swapCD/M.hz).toFixed(1)+'s',770,108+party.length*62+8,10,'#9fb0b8','center'); + } + function playerHud(c,g){ + const p=g.player,q=(g.party||[])[p.active||0];if(!q)return;const col=EL[q.element]||'#fff'; + txt(c,PARTY[q.id]||q.id,300,434,13,'#f1ead9','left','600');txt(c,Math.ceil(q.hp)+' / '+q.maxHp,554,434,11,'#cfe9d4','right'); + bar(c,300,439,254,8,(q.hp||0)/(q.maxHp||1),q.hp=1&&!bu; + ring(c,600,440,15,sk?1-sk/(q.skillTicks||1):1,sk?'#7d8a94':col,4);txt(c,sk?(sk/M.hz).toFixed(1):'K',600,445,sk?11:13,sk?'#c9d2d8':'#fff4cf','center','700');txt(c,'Skill',600,470,9,'#b8c4ca','center'); + ring(c,645,440,17,ready?1:er,ready?'#fff1b8':col,4);txt(c,bu?(bu/M.hz).toFixed(1):ready?'L':Math.floor(q.energy)+'',645,445,bu?11:12,ready?'#fff1b8':'#c9d2d8','center','700');txt(c,'Burst',645,470,9,'#b8c4ca','center'); + if(p.chargeTicks>0&&!g.outcome){bar(c,397,262,60,4,p.charge||0,(p.charge||0)>=1?col:'#ead8a3');txt(c,(p.charge||0)>=1?'Fully Charged':'Charge',427,282,11,'#efe5c8','center');} + // Bow aim crosshair: in the aim view the camera sits on the arrow ray, so the screen centre is where arrows go. + if(B.aimWeight&&B.aimWeight(g)>=.8){c.strokeStyle=p.chargeTicks>0?'#fff4cf':'rgba(238,229,203,.8)';c.lineWidth=1.4;c.beginPath();c.arc(427,240,6,0,Math.PI*2);c.moveTo(411,240);c.lineTo(419,240);c.moveTo(435,240);c.lineTo(443,240);c.moveTo(427,224);c.lineTo(427,232);c.moveTo(427,248);c.lineTo(427,256);c.stroke();} + if(p.skillHold>0&&q.id==='amber'){bar(c,397,262,60,4,Math.min(1,p.skillHold/120),'#ff9a5c');txt(c,'Throw Distance',427,282,11,'#efe5c8','center');} + } + function tierOf(d){for(const [k,v] of Object.entries(M.tiers||{}))if(Math.abs(v-d)<1e-9)return k;return null;} + function timer(c,g){const s=g.t/M.hz,limit=M.maxSeconds||300,tier=tierOf(g.d); + panel(c,14,394,86,20);txt(c,(tier?TIER_NAME[tier]:'d='+(+g.d).toFixed(2))+' · '+M.hz+'Hz',20,408,10,'#cfe0ea'); + panel(c,14,420,86,20);txt(c,g.player?.lockon?'R Target Lock':'R Free Look',20,434,10,g.player?.lockon?'#f2dc9c':'#b9c6cc'); + panel(c,14,446,86,22);txt(c,s.toFixed(1)+'s',22,461,12,'#e7ecdf');txt(c,'/ '+limit+'s',94,461,9,'#8f9aa0','right');} + function result(c,g){ + if(!g.outcome)return;const win=g.outcome==='win';c.fillStyle=win?'rgba(30,24,10,.42)':'rgba(30,8,8,.5)';c.fillRect(0,0,854,480); + // Banner sits above the centre of the frame: the play page's own overlay box occupies the middle on terminal states. + const grad=c.createLinearGradient(0,108,0,198);grad.addColorStop(0,'rgba(0,0,0,0)');grad.addColorStop(.5,win?'rgba(60,44,12,.75)':'rgba(60,12,12,.75)');grad.addColorStop(1,'rgba(0,0,0,0)');c.fillStyle=grad;c.fillRect(0,108,854,90); + txt(c,win?'Challenge Complete':g.outcome==='loss'?'Challenge Failed':'Time Up',427,152,34,win?'#f6dc94':'#f2a3a3','center','700'); + const st=g.stats||{},extra=g.id==='genshin/ruin_guard'?'Paralyzes '+(st.paralyzes||0)+' · Weak-Point Hits '+(st.weakHits||0):g.id==='genshin/oceanid'?'Hydro Mimics '+Object.values(st.kills||{}).reduce((a,b)=>a+b,0)+' · Waves '+(st.waves||0)+'/5':g.id==='genshin/maguu_kenki'?'Mask Blocks '+(st.maskBlocks||0):g.id==='genshin/andrius'?'Pillars Melted '+(st.pillarBreaks||0)+' · Wolf Pups '+(st.wolvesSpawned||0):g.id==='genshin/signora'?'Moths Collected '+(st.mothPicks||0)+' · Counters '+(st.counters||0):'Crystal Blocks '+(st.prismBreaks||0)+'/3'; + txt(c,'Time '+(g.t/M.hz).toFixed(1)+' s · '+extra+' · Reactions '+(st.elementReaction||0)+' · Damage Taken '+Math.round(st.playerDamage||0),427,180,13,'#efe6cf','center'); + } + M.draw=function(g,c){B.render('genshin',g,c);floating(c,g); + ({'genshin/ruin_guard':rgHud,'genshin/oceanid':ocHud,'genshin/maguu_kenki':mkHud,'genshin/andrius':awHud,'genshin/signora':sgHud}[g.id]||ehHud)(c,g); + partyHud(c,g);playerHud(c,g);timer(c,g);result(c,g);}; + M.renderStatus=ctx=>B.status('genshin',ctx);M.renderMetrics=ctx=>B.metrics('genshin',ctx);M.closeRenderer=ctx=>B.close('genshin',ctx); +})(window); diff --git a/environments/games/web/games/genshin_remake/game.js b/environments/games/web/games/genshin_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..fc0931a49e3458cdebe721f8713e1145fdaabb61 --- /dev/null +++ b/environments/games/web/games/genshin_remake/game.js @@ -0,0 +1,1293 @@ +/* BossBench · Genshin Impact three-boss: deterministic 60 Hz rules for three boss encounters fought by one four-character C0 party. + * Original procedural geometry. The mechanics follow the reference game. boss HP/ATK and the pressure knob d are BossBench + * calibrations (marked where they appear), not values read from the original game. */ +(function(root){ + 'use strict'; + const N=root.NativeBench,PI=Math.PI,TAU=PI*2,HZ=60; + const clamp=N.clamp,dist=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z),angle=(a,b)=>Math.atan2(b.x-a.x,b.z-a.z); + const forward=a=>({x:Math.sin(a),z:Math.cos(a)}),wrap=N.angle; + // Free-aim arrows leave from the right shoulder along (cameraYaw, aimPitch); the renderer puts the aim camera on this ray. + const aimOrigin=p=>{const f=forward(p.cameraYaw);return {x:p.x-f.z*.65+f.x*.2,y:(p.y||0)+1.45,z:p.z+f.x*.65+f.z*.2};}; + // Fandom Damage (r2192775) RES multiplier: negative RES counts half, 75% and above is 1/(4·RES+1). + const resMult=r=>r<0?1-r/2:r<.75?1-r:1/(4*r+1); + // Public tiers. The continuous d stays underneath: boss HP anchors interpolate geometrically + // between the three tier values (held outside [easy, hard]); damage (0.6+0.8d) and pace (1.15-0.3d) stay linear in d. + const TIERS={easy:.2,normal:.5,hard:.8}; + function byTier(anchors,d){const x=[TIERS.easy,TIERS.normal,TIERS.hard];if(d<=x[0])return anchors[0];if(d>=x[2])return anchors[2]; + const i=drange[0]+(range[1]-range[0])*N.rand(g); + function shuffle(g,list){for(let i=list.length-1;i>0;i--){const j=Math.floor(N.rand(g)*(i+1));[list[i],list[j]]=[list[j],list[i]];}return list;} + const TUNING={ + arenaRadius:18,bossLevel:80, + // Electro Hypostasis (Fandom r1857500 hp_ratio 7 / atk_ratio 6 -> Lv80 HP 129,960 / ATK 9,452). Our C0 panels deal a + // fraction of a built Lv80 party, so HP is a BossBench tier anchor (easy, normal, hard) calibrated against the reference + // controller and the tier time windows; normal keeps the @5 calibration. ATK 4,500: a 100% ATK hit removes ~22% of a C0 HP bar. + ehHP:[14500,60000,190000],bossATK:4500,reviveThreshold:.05, + reviveTicks:900,prismGauge:3,pillarGauge:4.4,revivePerPrism:.15,survivorGaugeResets:true, + // EH-C01 (open): Fandom heals 15/35/50% for 1/2/3 absorbed prisms; the BWIKI archive says 15% each. + // 'table' is the default; 'linear' reproduces the BWIKI reading (revivePerPrism x survivors). + reviveHealMode:'table',reviveHeal:[0,.15,.35,.50], + // Lightning Lockdown is "usually performed only when the player takes too long" (Fandom); 40 s is calibrated. + cageInterval:2400,orbThresholds:[.75,.5,.25], + // Documented attack ratios (% ATK, Fandom Abilities table); hazards scale by (0.6+0.8*difficulty). + moveDamage:{fist:.75,clap:1,rpsPunch:.75,rpsScissors:.75,rpsPalm:1,drill:.5,drillPhysical:.25, + laserRing:1,laserBeam:.4,laserConverge:1,projection:.25,cagePillar:1,cageLightning:.5,tremor:.75}, + guoba:{firstBreath:120,interval:90,life:420},bunnyTicks:480,aimedICD:60,rainICD:60,dropoffTicks:42, + naEnergy:{sword:[.10,.05],bow:[0,.05],polearm:[0,.04],catalyst:[0,.10]}, + resistance:.1,prismWeights:{pyro:1,cryo:1,dendro:1,anemo:.5,geo:.5,hydro:0,electro:0,physical:0}, + walkSpeed:5.2,sprintSpeed:8,dashSpeed:14,dashTicks:18,dashIframes:18,dashCost:18, + sprintCost:18,staminaRegen:25,staminaDelay:60,jumpSpeed:5.2,gravity:15, + // Swimming (Fandom Swimming r1759199: swimming consumes Stamina); speed, drain and the drowning reset are calibrated. + swimSpeed:3,swimCost:12, + bowChargeTicks:90,meleeChargeTicks:30,catalystChargeTicks:45,swapCooldown:60, + normalICD:150,normalHitRule:3,prismRadius:5,diamondInterruptPoise:3, + lunge:{fist:{speed:16,ticks:30,radius:1.8},drill:{speed:18,ticks:40,radius:1.8},rps:{speed:14,ticks:24,radius:1.7}}, + cones:{clap:{radius:4.4,half:1.15,at:18},rpsScissors:{radius:5.2,half:.85,at:60},rpsPalm:{radius:4.7,half:PI/2,at:112}}, + moves:{ + fist:{tell:42,active:42,recovery:180},clap:{tell:54,active:48,recovery:180}, + rps:{tell:48,active:150,recovery:210},drill:{tell:48,active:90,recovery:150}, + lasers:{tell:60,active:270,recovery:150},missiles:{tell:60,active:210,recovery:180}, + cage:{tell:96,active:360,recovery:180},waves:{tell:54,active:300,recovery:180} + } + }; + // Ruin Guard (Ruin Guard): Fandom r1960325 (Abilities, AI Logic table, weak points, 70% Physical RES), BWIKI Ruin Guard. + // Attack ratios, ranges, cooldowns and the 3 s action interval are documented; every tick count, radius, speed and the + // paralysis/rune durations are BossBench calibrations (no frame data is published). HP/ATK are tier calibrations. + const RG={hp:[24800,50000,150000],atk:3600,arena:18,res:{physical:.7},baseRes:.1, + walk:2.3,turn:.05,bodyR:1.25, + eye:{fwd:.8,y:2.82},back:{fwd:.93,y:2.42},weakR:.55, + staggerTicks:30,windowTicks:150,runeTicks:600,paralyzeTicks:600,wakeTicks:30,interval:180, + abilities:[ + {id:'combo',move:'combo',min:0,max:7,angle:45,cd:[12.5,17.5],init:[5,15],interval:true}, + {id:'stomp1',move:'stomp',min:0,max:4,angle:90,cd:[2,4],init:null,interval:false}, + {id:'stomp2',move:'stomp',min:0,max:4,angle:90,cd:[2,4],init:null,interval:false}, + {id:'stomp3',move:'stomp',min:0,max:4,angle:90,cd:[2,4],init:null,interval:false}, + {id:'stomp4',move:'stomp',min:0,max:4,angle:90,cd:[2,4],init:null,interval:false}, + {id:'spin',move:'spin',min:0,max:15,angle:180,cd:[30,60],init:[30,60],interval:true}, + {id:'volley1',move:'volley',min:15,max:50,angle:90,cd:[5,10],init:null,interval:true}, + {id:'volley2',move:'volley',min:7,max:15,angle:90,cd:[20,60],init:[20,60],interval:true}, + {id:'volley3',move:'volley',min:4,max:50,angle:90,cd:[5,10],init:null,interval:true}, + {id:'volley4',move:'volley',min:4,max:50,angle:90,cd:[5,10],init:null,interval:true}, + {id:'volley5',move:'volley',min:4,max:50,angle:90,cd:[5,10],init:null,interval:true} + ], + moves:{ + stomp:{tell:36,recovery:30,radius:2.9,offset:.9,ratio:.625}, + clap:{tell:30,recovery:48,radius:4.4,half:.9,ratio:.875,chance:.6,range:4.5}, + combo:{tell:30,punches:[30,60],ratios:[.5,.75],jump:84,land:138,recovery:60,radius:4.2,half:1.3,landRadius:3.2,landRatio:1}, + spin:{tell:42,active:420,recovery:72,radius:3.4,march:1.4,ratio:.75,rehit:30}, + volley:{swivel:24,fire:114,count:6,spacing:5,track:60,back:36,speed:8,life:240,ratio:.3125,radius:.45} + }, + orbThresholds:[.75,.5,.25]}; + // Oceanid / Rhodeia of Loch (Oceanid · Rhodeia of Loch): Fandom r2076922 + eight Hydro Mimic pages (r2175365-r2176186), BWIKI. + // The boss itself cannot be hit; defeating mimics damages her (BWIKI). Five summons in groups 1/1/2/2/2 covering the eight + // types once and sinking after the 2nd and 4th cleared waves follow community guides (approximation). Mimic HP ratios, ATK + // ratios, elemental weaknesses and self-heals are documented; each kill removing that mimic's max HP, timings, speeds and + // the HP unit per tier are BossBench calibrations. + const OC={hpUnit:[190,2500,9550],atk:4500,mimicATK:650,pond:17,tile:7,selfAura:1, + waves:[1,1,2,2,2],sinkAfter:[2,4],torrentTicks:1800,orbTicks:40,formTicks:30,sinkTell:100, + types:{ + boar:{name:'Hydro Mimic Boar',cat:'duo',count:2,hp:1.6,atk:2,weak:'pyro',heal:.05,r:.85,cy:.6,hh:.7,speed:3.6}, + squirrel:{name:'Hydro Mimic Squirrel',cat:'duo',count:2,hp:1.4,atk:3,weak:'pyro',heal:.0375,r:.65,cy:.5,hh:.6,speed:4}, + crab:{name:'Hydro Mimic Crab',cat:'duo',count:2,hp:1.6,atk:4,weak:'cryo',r:.75,cy:.35,hh:.5,speed:2.2}, + mallard:{name:'Hydro Mimic Mallard',cat:'duo',count:2,hp:1.6,atk:2,weak:'cryo',r:.65,cy:.45,hh:.55,speed:2.6}, + crane:{name:'Hydro Mimic Crane',cat:'trio',count:3,hp:.8,atk:5,weak:'electro',r:.6,cy:1,hh:.95,speed:3.2}, + raptor:{name:'Hydro Mimic Raptor',cat:'trio',count:3,hp:.8,atk:4,weak:'electro',r:.6,cy:.3,hh:.55,speed:6,fly:4.2}, + frog:{name:'Hydro Mimic Frog',cat:'solo',count:1,hp:3,atk:5,weak:'geo',r:.9,cy:.6,hh:.75,speed:2.6,bomb:true}, + finch:{name:'Hydro Mimic Finch',cat:'solo',count:1,hp:3,atk:5,weak:'geo',r:.8,cy:.55,hh:.65,speed:3.4,bomb:true} + }, + tiles:{trio:[0,2,6,8],duo:[4],solo:[1,3,5,7]}}; + const TEAM=[ + {id:'kaeya',name:'Kaeya',element:'cryo',weapon:'sword',maxHp:10500,atk:680,def:650,er:1.267,maxEnergy:60, + skillTicks:360,burstTicks:900,burstDuration:480,normal:[.781,.751,.949,1.03,1.283],charged:[.8,1.063],chargeCost:20,plungePath:.929,plunge:[1.86,2.32]}, + {id:'amber',name:'Amber',element:'pyro',weapon:'bow',maxHp:9800,atk:700,def:600,er:1,maxEnergy:40, + skillTicks:900,burstTicks:720,burstDuration:120,normal:[.525,.525,.675,.688,.863],charged:[1.74],chargeCost:0,plungePath:.826,plunge:[1.65,2.06]}, + {id:'xiangling',name:'Xiangling',element:'pyro',weapon:'polearm',maxHp:11000,atk:660,def:680,er:1.4,maxEnergy:80, + skillTicks:720,burstTicks:1200,burstDuration:600,normal:[.611,.613,[.379,.379],[.205,.205,.205,.205],1.03],charged:[1.77],chargeCost:25,plungePath:.929,plunge:[1.86,2.32]}, + {id:'barbara',name:'Barbara',element:'hydro',weapon:'catalyst',maxHp:14500,atk:480,def:650,er:1.3,maxEnergy:80, + skillTicks:1920,burstTicks:1200,burstDuration:0,normal:[.53,.497,.575,.773],charged:[2.33],chargeCost:50,plungePath:.826,plunge:[1.65,2.06]} + ]; + const MOVE_NAMES={fist:'Block Punch',clap:'Twin-Plate Clap',rps:'Three-Shape Combo',drill:'Spiral Dash',lasers:'Rotating Beams',missiles:'Diamond Barrage',cage:'Eight-Pillar Cage',waves:'Ground Rings'}; + const GUARD_MOVES={stomp:'Stomp Quake',clap:'Arm Slam',combo:'Punch and Leap-Slam',spin:'Spin Crush',volley:'Back-Cannon Volley'}; + const OCEANID_MOVES={summon:'Summon Water Creatures',sink:'Platform Sinks',torrent:'Chasing Whirlpool'}; + // Hitting an Electro ward with these elements shows the reaction (Electro aura + attacker element). + const WARD_REACTION={pyro:'overload',cryo:'superconduct',dendro:'quicken',anemo:'swirl',geo:'crystallize'}; + const CASES=[{id:'genshin/electro_hypostasis',name:'Floating Square Array'},{id:'genshin/ruin_guard',name:'Back-Cannon Colossus'},{id:'genshin/oceanid',name:'Tidepool Summoner'}]; + const M=root.GenshinGame={id:'genshin_remake',version:'genshin-bosses@8',hz:HZ,maxSeconds:300, + dimension:'3d',renderer:'webgl-boss3d',title:'Genshin Impact · Boss Challenge',tiers:TIERS,cases:CASES, + controls:{'W A S D':'Move relative to the camera; falling into water in the Oceanid arena makes you swim and consumes stamina','mouse dx dy':'Turn the camera at any time when unlocked and adjust aiming pitch; while locked on, the camera follows the target','R':'Toggle target lock (off by default for free camera). When locked, the camera and facing follow the target and arrows auto-aim. When unlocked, hold LMB as the archer for over-the-shoulder aiming; fire along the reticle to hit the Ruin Guard’s weak point', + 'J':'Continuous normal attacks; press in the air for a plunging attack','LMB':'Hold to charge and release a heavy attack; as the archer, tap to aim and shoot or fully charge for a Pyro arrow', + 'K / RMB':'Elemental skill; hold as the archer to adjust decoy throw distance','L':'Elemental burst (requires energy and completed cooldown)', + 'Q / E':'Previous / next living party member; switching shares a 1-second cooldown','Shift':'Press to dash with invulnerability frames; hold to run and consume stamina', + 'Space':'Jump; a low hop can clear ground shockwaves'},tuning:TUNING,guard:RG,oceanid:OC,team:TEAM, + moveNames:MOVE_NAMES,guardMoveNames:GUARD_MOVES,oceanidMoveNames:OCEANID_MOVES,byTier,aimOrigin}; + // ---------------------------------------------------------------------------------------------- shared party core + class Fight{ + constructor(id,seed,d){ + this.id=id;this.rng=seed||1;this.d=d;this.t=0;this.outcome=null;this.events=[];this.nextId=1; + this.party=TEAM.map(v=>({...N.copy(v),constellation:0,talentLevel:6,hp:v.maxHp,energy:v.maxEnergy,skillCD:0,burstCD:0,wet:0,electrocharged:0,pepper:0,naChance:TUNING.naEnergy[v.weapon][0]})); + this.player={x:0,z:10,y:0,yaw:PI,cameraYaw:PI,aimPitch:0,active:0,hp:this.party[0].hp,maxHp:this.party[0].maxHp, + stamina:240,maxStamina:240,sinceSpend:120,inv:0,stun:0,vy:0,grounded:true,action:'idle',actionTick:0, + actionLock:0,normalCD:0,combo:0,comboRest:0,chargeTicks:0,charge:0,skillHold:0,swapCD:0, + dash:0,dashX:0,dashZ:0,dashUses:0,dashReset:0,lockon:false,lockBlend:12,swimming:false,moveSpeed:0}; + this.hazards=[];this.projectiles=[];this.summons=[];this.effects=[];this.auras=[];this.particles=[];this.pickups=[];this.pending=[];this.icd={};this.reactionSeq={}; + this.arenaR=TUNING.arenaRadius;this.atk=TUNING.bossATK;this.hazardElement='electro'; + this.stats={elementApplications:0,elementReaction:0,reactions:{overload:0,superconduct:0,electrocharged:0,quicken:0,vaporize:0,melt:0,frozen:0}, + charSkill:Object.fromEntries(TEAM.map(q=>[q.id,0])),charBurst:Object.fromEntries(TEAM.map(q=>[q.id,0])),normals:0,charged:0,dodges:0,dodgedHits:0, + switches:0,jumps:0,plunges:0,particleCollections:0,orbCollections:0,naEnergy:0,damageDealt:0,playerDamage:0,drowns:0}; + } + owner(){return this.party[this.player.active];} + idNext(){return this.nextId++;} + emit(name){this.events.push(name);} + fx(kind,o={}){this.effects.push({kind,age:0,life:36,...o});} + statATK(owner){return owner.atk*(1.25+(owner.pepper ? .1 : 0));} + // Hooks each encounter overrides. + aliveTargets(){return [];} + targetable(){return true;} + solid(){return true;} + fallbackTargets(){return [];} + lookAnchor(){return this.boss;} + aimPoint(q){return {x:q.x,y:q.y||1.3,z:q.z};} + guobaFallback(){return null;} + wallCollision(){return false;} + terrain(){return 'ground';} + pushOut(){} + entity(id){return this.boss&&this.boss.id===id?this.boss:null;} + health(){const b=this.boss;return [this.party.reduce((s,p)=>s+p.hp,0),this.party.reduce((s,p)=>s+p.maxHp,0),this.outcome==='win'?0:Math.max(0,b.hp),b.maxHp];} + target(){ + const p=this.player,all=this.aliveTargets(),valid=all.filter(q=>this.targetable(q)); + const candidates=valid.length?valid:this.fallbackTargets(all); + let best=null,score=Infinity; + for(const q of candidates){const a=Math.abs(wrap(angle(p,q)-p.yaw)),v=dist(p,q)+(p.lockon?0:a*20);if(va.kind==='melody')?.88:1);} + swap(direction,forced=false){ + const p=this.player;if(!forced&&(p.swapCD||p.actionLock||p.stun||!p.grounded||p.swimming))return false; + for(let n=1;n<=4;n++){const next=(p.active+direction*n+8)%4;if(this.party[next].hp>0){ + const previous=p.active;this.pending=this.pending.filter(v=>v.owner!==previous||!['normal','charged','skill','burst','swing'].includes(v.kind)); + p.active=next;p.swapCD=TUNING.swapCooldown;p.chargeTicks=0;p.charge=0;p.skillHold=0;p.combo=0;p.normalCD=0; + if(forced){p.actionLock=0;p.stun=0;p.plunging=false;} + p.action='swap';p.actionTick=0;this.stats.switches++;this.emit('character_switched');return true;}} + return false; + } + syncPlayerHealth(){const p=this.player,q=this.owner();p.hp=q.hp;p.maxHp=q.maxHp;} + replaceDefeated(){ + if(this.outcome||this.owner().hp>0)return; + if(!this.party.some(q=>q.hp>0)){this.outcome='loss';this.emit('party_defeated');} + else this.swap(1,true); + this.syncPlayerHealth(); + } + hurt(amount,element='electro',source=null){ + const p=this.player,q=this.owner();if(this.outcome||q.hp<=0)return false; + // Finch leaps cannot be avoided with dash i-frames (Fandom Hydro Mimic Finch). + if(p.inv&&!(source&&source.noIframe)){this.stats.dodgedHits++;return false;} + // Drill contact carries a separate Physical component (Fandom 50% Electro + 25% Physical). + const defense=(TUNING.bossLevel+100)/(TUNING.bossLevel+100+q.def/5),damage=(amount+(source&&source.physical||0))*defense*.9; + const actual=Math.min(q.hp,damage);q.hp=Math.max(0,q.hp-damage); + // Light DoT (bubble streams, vortices, whirlpools) chips HP without hit-stun or recovery frames, so it never stun-locks. + if(!(source&&source.light)){p.stun=source&&source.knock?40:15;p.normalCD=Math.max(p.normalCD,18);p.actionLock=0;p.inv=25; + p.chargeTicks=0;p.charge=0;p.skillHold=0;this.pending=this.pending.filter(v=>v.owner!==p.active||!['normal','charged','skill'].includes(v.kind));} + this.stats.playerDamage+=actual;this.fx('hurt',{x:p.x,z:p.z,y:1,element});this.fx('taken',{x:p.x,z:p.z,y:p.y+2,amount:Math.round(actual),element,life:54});this.emit('character_hurt'); + if(source&&source.knock&&(source.x!==undefined)){const a=angle(source,p),f=forward(a);this.movePlayer(f.x*1.6,f.z*1.6);} + if(element==='hydro')q.wet=Math.max(q.wet,240); + if(q.wet&&element==='electro'){q.electrocharged=90;this.emit('wet_electrocharged');} + if(q.hp<=0){this.emit('character_down');this.replaceDefeated();} + this.syncPlayerHealth(); + return true; + } + heal(owner,amount,all=false){let total=0;for(const c of this.party)if(c.hp>0&&(all||c===owner)){const before=c.hp;c.hp=Math.min(c.maxHp,c.hp+amount);total+=c.hp-before;} + if(total>=1){const p=this.player;this.fx('heal',{x:p.x,z:p.z,y:p.y+2.2,amount:Math.round(total),element:'heal',life:54});}} + // Elemental particles (skills), orbs (boss drops; three times a particle) and colorless drops ('neutral'). + particle(element,count,x,z,orb=false){for(let n=0;n=span){this.icd[key]={start:this.t,hits:1};return true;} + const apply=rec.hits%TUNING.normalHitRule===0;rec.hits++;return apply; + } + // Generic aura model (Fandom Elemental Gauge Theory r2070927): an applied xU leaves a 0.8x aura decaying over 2.5x+7 s; + // same-element hits keep the larger gauge (Pyro may replace); amplifying reactions consume 2x (strong) or 0.5x (weak) the + // trigger; Hydro+Cryo freezes for 2*sqrt(5*G+4)-4 s with G=2*min(aura, trigger) (Fandom Frozen r2070196). A self aura + // (Hydro mimics) never depletes. Returns the damage multiplier and the reaction name. + react(t,hit){ + const E=hit.element,G=hit.gauge;if(!G||E==='physical')return {mult:1,reaction:null}; + const self=t.selfAura,a=self?{el:self,g:OC.selfAura}:t.aura; + if(!a||a.g<=1e-6){t.aura={el:E,g:.8*G,rate:.8*G/((2.5*G+7)*HZ)};return {mult:1,reaction:null};} + if(a.el===E){if(!self){if(E==='pyro'&&.8*G>a.g)t.aura={el:E,g:.8*G,rate:.8*G/((2.5*G+7)*HZ)};else a.g=Math.max(a.g,.8*G);}return {mult:1,reaction:null};} + const pair=a.el+'>'+E;let mult=1,reaction=null,use=0; + if(pair==='hydro>pyro'){mult=1.5;reaction='vaporize';use=.5*G;} + else if(pair==='pyro>hydro'){mult=2;reaction='vaporize';use=2*G;} + else if(pair==='cryo>pyro'){mult=2;reaction='melt';use=2*G;} + else if(pair==='pyro>cryo'){mult=1.5;reaction='melt';use=.5*G;} + else if(pair==='hydro>cryo'||pair==='cryo>hydro'){reaction='frozen';const fg=2*Math.min(a.g,G),secs=2*Math.sqrt(5*fg+4)-4; + t.frozen=Math.max(t.frozen||0,Math.round(secs*HZ));use=Math.min(a.g,G);} + if(!reaction){if(!self)t.aura={el:E,g:.8*G,rate:.8*G/((2.5*G+7)*HZ)};return {mult:1,reaction:null};} + if(!self){a.g-=use;if(a.g<=1e-6)t.aura=null;} + this.stats.elementReaction++;this.stats.reactions[reaction]=(this.stats.reactions[reaction]||0)+1;this.emit(reaction); + return {mult,reaction}; + } + decayAura(t){if(t.aura&&!t.selfAura){t.aura.g-=t.aura.rate;if(t.aura.g<=1e-6)t.aura=null;}} + bossDamage(ratio){return this.atk*ratio*this.dmgScale();} + dmgScale(){return .6+.8*this.d;} + // BossBench pressure knob (not an original setting): telegraph and core-exposure windows scale by 1.15-0.3d, + // i.e. exactly the calibrated values at the default d=0.5, 9% longer at d=0.2 and 9% shorter at d=0.8. + pace(){return 1.15-.3*this.d;} + // Aggression knob (BossBench): cooldowns and action intervals 1.3-0.6d (identity at d=0.5). + aggression(){return 1.3-.6*this.d;} + dropOrb(x,z,element='electro'){this.particle(element,1,x,z,true);this.emit('energy_orb');} + hit(target,hit){if(!target||this.outcome)return false;return this.hitTarget(target,hit);} + hitTarget(){return false;} + // Normal/charged hits generate 1 Energy with a weapon-specific probability that rises on each miss (Fandom Energy). + naEnergy(owner,hit,actual){ + if(!(actual>0&&['normal','charged'].includes(hit.group)))return;const rule=TUNING.naEnergy[owner.weapon]; + if(N.rand(this)a.kind==='melody')&&['normal','charged'].includes(hit.group))this.heal(owner,(owner.maxHp*.0105+114)*(hit.group==='charged'?4:1),true);} + attackHit(owner,damage,element,gauge,group,extra={}){return {owner,damage:this.statATK(this.party[owner])*damage,element,gauge,group,...extra};} + area(hit,x,z,radius,cone=null,y=1,verticalRange=3){ + let count=0;for(const q of this.aliveTargets()){const r=q.r!==undefined?q.r:(q.kind==='core'?1.1:.65); + if(!this.outcome&&dist({x,z},q)<=radius+r&&(!cone||Math.abs(wrap(angle({x,z},q)-cone.angle))<=cone.half)&&Math.abs((q.y||1)-y){ + const hit=this.attackHit(i,value,q.weapon==='catalyst'?'hydro':'physical',q.weapon==='catalyst'?1:0,'normal',{poise:.6}); + this.pending.push({kind:'normal',delay:8+n*5,owner:i,hit,range:q.weapon==='polearm'?3.8:3.1}); + });this.stats.normals++; + } + charged(ticks){ + const p=this.player,q=this.owner(),i=p.active;if(!p.grounded||q.hp<=0||p.actionLock||p.stun||p.normalCD||p.swimming)return; + if(q.weapon==='bow'){ + // Aimed shot: fully charged is 2U Pyro (Charged Attack ICD 1 s/3 hits); uncharged is Physical. Both count as charged + // attacks for weak points (Fandom Ruin Guard: bow users disable it with Charged Attacks). + const full=ticks>=TUNING.bowChargeTicks;p.action='bow';p.normalCD=18;p.actionTick=0; + this.projectile(this.attackHit(i,full?q.charged[0]:.638,full?'pyro':'physical',full?2:0,'charged',{icd:TUNING.aimedICD,poise:2,aimed:true,full}),this.target(),35); + }else{ + if(!this.spend(q.chargeCost))return;p.action='charged';p.actionTick=0;p.normalCD=42; + if(q.id==='xiangling'){const f=forward(p.yaw);this.movePlayer(f.x*1.6,f.z*1.6);} + const parts=q.id==='kaeya'?q.charged:[q.charged[0]]; + parts.forEach((m,n)=>this.pending.push({kind:'charged',delay:8+n*7,owner:i, + hit:this.attackHit(i,m,q.weapon==='catalyst'?'hydro':'physical',q.weapon==='catalyst'?1:0,'charged',{noICD:q.weapon==='catalyst',poise:2}), + range:q.weapon==='catalyst'?5:4.1})); + } + this.stats.charged++;this.emit('charged_attack'); + } + skill(heldTicks=0){ + const p=this.player,q=this.owner(),i=p.active;if(!p.grounded||q.hp<=0||q.skillCD||p.actionLock||p.stun||p.swimming)return false; + q.skillCD=q.skillTicks;p.action='skill';p.actionTick=0;p.actionLock=24;p.chargeTicks=0; + this.pending.push({kind:'skill',owner:i,delay:16,castDelay:15,throwTicks:heldTicks});this.stats.charSkill[q.id]++;this.emit(q.id+'_skill');return true; + } + skillImpact(item){ + const q=this.party[item.owner],p=this.player,f=forward(p.yaw); + if(q.id==='kaeya'){ + const hit=this.attackHit(item.owner,2.68,'cryo',2,'skill',{noICD:true,poise:3.2}); + const count=this.area(hit,p.x,p.z,5.3,{angle:p.yaw,half:.7}); + // Frostgnaw averages 2.67 particles: 3 with probability 2/3, otherwise 2 (Fandom note). + if(count){this.particle('cryo',2+(N.rand(this)<2/3?1:0),p.x+f.x*3,p.z+f.z*3);this.heal(q,this.statATK(q)*.15);} + this.fx('frost_cone',{x:p.x,z:p.z,y:1,angle:p.yaw,element:'cryo',life:24}); + } + if(q.id==='amber'){ + const range=clamp(2+item.throwTicks/HZ*3,2,8),x=p.x+f.x*range,z=p.z+f.z*range; + this.summons.push({id:this.idNext(),kind:'bunny',owner:item.owner,x,z,y:0,age:0,life:TUNING.bunnyTicks,hp:q.maxHp*.579,hit:this.attackHit(item.owner,1.72,'pyro',2,'bunny',{noICD:true,poise:3})}); + } + if(q.id==='xiangling')this.summons.push({id:this.idNext(),kind:'guoba',owner:item.owner,x:p.x+f.x*1.4,z:p.z+f.z*1.4,y:0,yaw:p.yaw,age:0,life:TUNING.guoba.life-(item.castDelay||0),breaths:0,castDelay:item.castDelay||0,snapATK:this.statATK(q)}); + if(q.id==='barbara'){ + this.auras.push({id:this.idNext(),kind:'melody',owner:item.owner,age:0,life:900,extension:0});q.wet=90; + // The skill deals two droplet instances at the start; both share the Elemental Skill ICD tag. + for(let n=0;n<2;n++)this.area(this.attackHit(item.owner,.818,'hydro',1,'show',{poise:1}),p.x,p.z,2.5); + } + } + burst(){ + const p=this.player,q=this.owner();if(!p.grounded||q.hp<=0||q.burstCD||q.energythis.pending.push({kind:'swing',owner:item.owner,delay:n*8,last:n===2,hit:this.attackHit(item.owner,damage,'pyro',1,'burst',{poise:2})})); + this.auras.push({id:this.idNext(),kind:'pyronado',owner:item.owner,age:0,life:600,angle:0,hitTicks:{},snapATK:null}); + } + if(q.id==='amber')this.auras.push({id:this.idNext(),kind:'rain',owner:item.owner,x:target?target.x:p.x,z:target?target.z:p.z,age:0,life:121}); + if(q.id==='barbara'){this.heal(q,q.maxHp*.246+2683,true);this.fx('miracle',{x:p.x,z:p.z,y:1,element:'hydro',life:50});} + } + segmentsIntersect(a,b,c,d){ + const cross=(p,q,r)=>(q.x-p.x)*(r.z-p.z)-(q.z-p.z)*(r.x-p.x),abC=cross(a,b,c),abD=cross(a,b,d),cdA=cross(c,d,a),cdB=cross(c,d,b); + if(Math.abs(abC)+Math.abs(abD)+Math.abs(cdA)+Math.abs(cdB)<1e-9)return Math.max(Math.min(a.x,b.x),Math.min(c.x,d.x))<=Math.min(Math.max(a.x,b.x),Math.max(c.x,d.x))&& + Math.max(Math.min(a.z,b.z),Math.min(c.z,d.z))<=Math.min(Math.max(a.z,b.z),Math.max(c.z,d.z)); + return abC*abD<=0&&cdA*cdB<=0; + } + segmentDistance(p,a,b){const x=b.x-a.x,z=b.z-a.z,t=clamp(((p.x-a.x)*x+(p.z-a.z)*z)/(x*x+z*z||1),0,1);return Math.hypot(p.x-a.x-t*x,p.z-a.z-t*z);} + clampArena(next,margin=.5){const r=this.arenaR-margin,n=Math.hypot(next.x,next.z);if(n>r){next.x*=r/n;next.z*=r/n;}return next;} + movePlayer(dx,dz){ + const p=this.player,old={x:p.x,z:p.z},next=this.clampArena({x:p.x+dx,z:p.z+dz});this.pushOut(next);this.clampArena(next); + if(p.y>3||!this.wallCollision(old,next)){p.x=next.x;p.z=next.z;} + } + drown(){const p=this.player;this.stats.drowns++;this.emit('drowned');this.fx('drown',{x:p.x,z:p.z,y:.2,life:40}); + p.x=0;p.z=0;p.y=0;p.vy=0;p.grounded=true;p.swimming=false;p.stamina=p.maxStamina*.5;p.stun=60;p.inv=60;p.dash=0;} + updatePlayer(keys,pressed,mouse){ + const p=this.player,startX=p.x,startZ=p.z;p.cameraYaw=wrap(p.cameraYaw-mouse[0]*.0025);p.aimPitch=clamp(p.aimPitch-mouse[1]*.002,-.5,1.1); + // lockBlend counts ticks since the last R toggle (renderer eases the bow aim view in or out on a toggle; no rule reads it). + // genshin-bosses@7: the fight starts unlocked (free camera, as on PC where lock-on is an optional key); R locks the target. + if(pressed.has('R')){p.lockon=!p.lockon;p.lockBlend=0;}else if(p.lockBlend<12)p.lockBlend++; + if(pressed.has('E'))this.swap(1);if(pressed.has('Q'))this.swap(-1); + const q=this.owner(),swim=p.swimming; + const target=this.target(),look=target||this.lookAnchor();if(p.lockon&&look)p.cameraYaw=p.yaw=angle(p,look);else p.yaw=p.cameraYaw; + let dx=(keys.has('D')?1:0)-(keys.has('A')?1:0),dz=(keys.has('W')?1:0)-(keys.has('S')?1:0),length=Math.hypot(dx,dz)||1; + const f=forward(p.cameraYaw),wx=(f.x*dz-f.z*dx)/length,wz=(f.z*dz+f.x*dx)/length; + if(!swim&&pressed.has('Shift')&&p.dashUses<2&&!p.actionLock&&this.spend(TUNING.dashCost*this.staminaFactor())){ + const v=Math.hypot(wx,wz)||1;p.dashX=(wx||(!dx&&!dz?Math.sin(p.yaw):0))/v;p.dashZ=(wz||(!dx&&!dz?Math.cos(p.yaw):0))/v; + p.dash=TUNING.dashTicks;p.inv=Math.max(p.inv,TUNING.dashIframes);p.dashUses++;p.dashReset=72;p.action='dodge';p.actionTick=0;p.stun=0;this.stats.dodges++;this.emit('dash'); + } + if(p.dash&&!swim){this.movePlayer(p.dashX*TUNING.dashSpeed/HZ,p.dashZ*TUNING.dashSpeed/HZ);p.dash--;} + else if(!p.stun){let speed=swim?TUNING.swimSpeed:TUNING.walkSpeed; + if(!swim&&keys.has('Shift')&&Math.hypot(dx,dz)>0&&this.spend(TUNING.sprintCost*this.staminaFactor()/HZ))speed=TUNING.sprintSpeed; + if(p.chargeTicks)speed*=.4;if(p.actionLock)speed*=.25;this.movePlayer(wx*speed/HZ,wz*speed/HZ); + } + if(!swim&&pressed.has('Space')&&p.grounded&&!p.actionLock&&!p.stun){p.vy=TUNING.jumpSpeed;p.grounded=false;p.action='jump';p.actionTick=0;this.stats.jumps++;} + if(!p.grounded){const oldY=p.y;p.vy-=TUNING.gravity/HZ;p.y+=p.vy/HZ; + if(p.plunging)for(const v of this.aliveTargets())if(!this.outcome&&!p.plungeHit.includes(v.id)&&dist(p,v)<1.2&&v.y>=p.y&&v.y<=oldY+1){ + p.plungeHit.push(v.id);this.hit(v,this.attackHit(p.active,q.plungePath,q.weapon==='catalyst'?'hydro':'physical',q.weapon==='catalyst'?1:0,'plunge_path',{noICD:true,poise:1}));} + if(this.outcome)return; + if(p.y<=0){p.y=0;p.vy=0;p.grounded=true; + if(p.plunging){this.area(this.attackHit(p.active,q.plunge[p.plungeHeight>=3?1:0],q.weapon==='catalyst'?'hydro':'physical',q.weapon==='catalyst'?1:0,'plunge',{noICD:true,poise:3}),p.x,p.z,4);p.plunging=false;this.stats.plunges++;p.normalCD=35;}}} + if(this.outcome)return; + // Deep water (sunken platforms, the pond): swim, no attacks, Stamina drains; empty Stamina = drown and reset (calibrated). + p.swimming=p.grounded&&this.terrain(p.x,p.z)==='water'; + if(p.swimming){p.chargeTicks=0;p.charge=0;p.skillHold=0;p.dash=0;p.stamina=Math.max(0,p.stamina-TUNING.swimCost/HZ);p.sinceSpend=0; + if(p.stamina<=0)this.drown();p.moveSpeed=Math.hypot(p.x-startX,p.z-startZ)*HZ;p.action='swim';return;} + if(keys.has('LMB')&&p.grounded&&!p.actionLock&&!p.stun){p.chargeTicks++;p.charge=clamp(p.chargeTicks/(q.weapon==='bow'?90:q.weapon==='catalyst'?45:30),0,1);p.action=q.weapon==='bow'?'aim':'charge';} + else if(p.chargeTicks){const held=p.chargeTicks;p.chargeTicks=0;p.charge=0;if(q.weapon==='bow'||held>=(q.weapon==='catalyst'?45:30))this.charged(held);else this.normal();} + if(p.grounded?keys.has('J'):pressed.has('J'))this.normal(); + if(q.id==='amber'){ + if(keys.has('K')||keys.has('RMB')){if(p.grounded&&!p.actionLock&&!p.stun&&!q.skillCD)p.skillHold++;} + else if(p.skillHold){const held=p.skillHold;p.skillHold=0;this.skill(held);} + }else if(pressed.has('K')||pressed.has('RMB'))this.skill(); + if(pressed.has('L'))this.burst(); + // Horizontal speed (m/s) for the renderer's walk/run cycle; a pure function of this tick's motion. + p.moveSpeed=Math.hypot(p.x-startX,p.z-startZ)*HZ; + } + // Baron Bunny draws aggro within 15 m (BWIKI: taunts nearby enemies). + aggroTarget(from){const bunny=this.summons.find(s=>s.kind==='bunny'&&s.hp>0&&dist(s,from)<15);return bunny||this.player;} + hazard(kind,extra={}){const b=this.boss;const h={id:this.idNext(),kind,x:b.x,z:b.z,y:0,age:0,delay:0,life:8,lastHit:-10000,damage:this.bossDamage(.5),...extra};this.hazards.push(h);return h;} + hazardContains(h,p,future=0){ + if(h.age+future=h.life||h.kind==='pillar'||h.spent)return false; + if((p.y||0)>=(h.height||2))return false; + // Airborne projectiles (Ruin Guard missiles climbing out of the cannons) pass over the player. + if(h.kind==='bolt'&&h.y!==undefined&&h.y>(p.y||0)+2.2)return false; + const x=h.x+(h.vx||0)*future,z=h.z+(h.vz||0)*future,d=Math.hypot(p.x-x,p.z-z); + if(h.kind==='sweep')return this.segmentDistance(p,{x,z},{x:h.toX,z:h.toZ})h.inner-.3&&alongh.gap;} + if(h.kind==='square')return Math.abs(p.x-x)=h.delay&&h.kind!=='pillar'&&!h.spent){ + if(this.hazardContains(h,this.player)&&this.t-h.lastHit>=(h.rehit||30)){if(this.hurt(h.damage,h.element||this.hazardElement,h))h.lastHit=this.t;if(h.consume){h.spent=true;h.life=h.age+1;}} + // Baron Bunny takes hazard damage with the same 0.5 s re-hit interval as the player (was every tick). + for(const s of this.summons)if(s.kind==='bunny'&&s.hp>0&&this.hazardContains(h,{...s,y:0})){const key='bunnyHit'+s.id;if(this.t-(h[key]??-10000)>=30){h[key]=this.t;s.hp-=h.damage;}} + } + h.age++;if(h.vx!==undefined||h.vz!==undefined){h.x+=h.vx||0;h.z+=h.vz||0;}if(h.rotation)h.angle+=h.rotation;if(h.speed)h.radius+=h.speed; + } + this.hazards=this.hazards.filter(h=>h.age0)); + } + projectileHits(q,old,a){const r=q.r!==undefined?q.r:(q.kind==='core'?1.1:.7),cy=q.cy!==undefined?q.cy:q.y,hh=q.hh!==undefined?q.hh:1.4; + return this.segmentDistance(q,old,a)TUNING.dropoffTicks){const f=Math.max(.1,1-.1*Math.floor((a.age-TUNING.dropoffTicks)/3));hit={...hit,damage:hit.damage*f,gauge:hit.gauge*f};} + if(q.kind==='guard')hit={...hit,path:{x0:old.x,y0:old.y,z0:old.z,x1:a.x,y1:a.y,z1:a.z}}; + this.hit(q,hit);a.dead=true;break;} + if(this.wallCollision(old,a))a.dead=true; + } + this.projectiles=this.projectiles.filter(a=>!a.dead&&a.age-.5); + } + updateSummons(){ + for(const s of this.summons){ + if(this.outcome)return; + // Guoba: first breath 2 s after the cast, then every 1.5 s, four breaths, 7 s on field; Flame DMG snapshots ATK. + const g=TUNING.guoba,first=g.firstBreath-(s.castDelay||0); + if(s.kind==='guoba'&&s.age>=first&&s.breaths<4&&((s.age-first)%g.interval===0)){ + // Guoba cannot attack flying targets (BWIKI): the breath only reaches targets near ground height. + const targets=this.aliveTargets().filter(q=>this.targetable(q)&&Math.abs((q.y||1)-1)<1.2);targets.sort((a,c)=>dist(s,a)-dist(s,c));const target=targets[0]||this.guobaFallback(); + const facing=target?angle(s,target):s.yaw; + const hit={owner:s.owner,damage:(s.snapATK||this.statATK(this.party[s.owner]))*1.56,element:'pyro',gauge:1,group:'guoba',noICD:true,poise:1.6}; + // Breath cone after Crossfire: 5 m long, about 1.5 m wide at max range (Fandom Guoba Attack note). + const hits=this.area(hit,s.x,s.z,5,{angle:facing,half:.2},1,1.2);if(hits&&target)this.particle('pyro',1,target.x,target.z); + this.fx('flame',{x:s.x,z:s.z,y:1,angle:facing,element:'pyro'});s.breaths++;s.yaw=facing; + } + if(s.kind==='bunny'&&(s.age>=s.life-1||s.hp<=0)){ + if(this.area(s.hit,s.x,s.z,4))this.particle('pyro',4,s.x,s.z);s.dead=true;this.fx('bunny_explosion',{x:s.x,z:s.z,element:'pyro'}); + } + s.age++; + if(s.kind==='guoba'&&s.age>=s.life){this.pickups.push({kind:'pepper',x:s.x,z:s.z,age:0,life:600});} + } + this.summons=this.summons.filter(s=>!s.dead&&s.age(a.kind==='icicles'?30:36)){ + // Icicles re-hit the same target after 0.5 s, Pyronado after 0.6 s; both snapshot ATK. + const atk=a.snapATK||this.statATK(this.party[a.owner]); + a.hitTicks[q.id+':'+i]=this.t;this.hit(q,{owner:a.owner,damage:atk*(a.kind==='icicles'?1.09:1.57),element:a.kind==='icicles'?'cryo':'pyro',gauge:1,group:a.kind==='icicles'?'burst':'pyronado', + noICD:a.kind==='pyronado',poise:.5});}} + a.angle+=omega; + } + if(a.kind==='rain'){ + // Fiery Rain: 1U Pyro per arrow, Elemental Burst ICD 1 s / 3 hits; arrows fall from above and reach flying targets. + const owner=a.owner,emit=(x,z)=>{this.area(this.attackHit(owner,.393,'pyro',1,'rain',{icd:TUNING.rainICD,poise:.2}),x,z,.55,null,2.5,3.2);this.fx('rain_arrow',{x,z,y:4,element:'pyro'});}; + if(a.age>0&&a.age%12===0&&a.age<=120)emit(a.x,a.z); + if(a.age>0&&a.age%24===0&&a.age<=120){const t=N.rand(this)*TAU,r=Math.sqrt(N.rand(this))*2.6;emit(a.x+Math.sin(t)*r,a.z+Math.cos(t)*r);} + if(a.age>0&&a.age%36===0&&a.age<=108){const t=N.rand(this)*TAU,r=Math.sqrt(N.rand(this))*2.6;emit(a.x+Math.sin(t)*r,a.z+Math.cos(t)*r);} + } + if(a.kind==='melody'){ + if(a.age%300===0){const q=this.party[a.owner];this.heal(this.owner(),q.maxHp*.056+610);this.owner().wet=90;} + if(a.age%60===0)this.area(this.attackHit(a.owner,0,'hydro',1,'melody'),p.x,p.z,1.6); + } + a.age++; + } + this.auras=this.auras.filter(a=>a.age18){v.x+=(p.x-v.x)*.15;v.z+=(p.z-v.z)*.15;} + if(d<1&&v.age>18){for(let i=0;i<4;i++){const q=this.party[i],base=v.element==='neutral'?2:(q.element===v.element?3:1),amount=base*(v.orb?3:1);q.energy=Math.min(q.maxEnergy,q.energy+amount*q.er*(i===p.active?1:.6));} + if(v.orb)this.stats.orbCollections++;else this.stats.particleCollections++;v.dead=true;const melody=this.auras.find(a=>a.kind==='melody');if(melody&&melody.extension<300){melody.life+=60;melody.extension+=60;}} + } + // Particles last about 30 s and orbs about 9 s if not collected (Fandom Energy, marked Verify there). + this.particles=this.particles.filter(v=>!v.dead&&v.age<(v.orb?540:1800)); + for(const v of this.pickups){v.age++;if(dist(p,v)<1){this.owner().pepper=600;v.dead=true;this.emit('pepper_atk_buff');}} + this.pickups=this.pickups.filter(v=>!v.dead&&v.age0)p[name]--; + if(!p.comboRest)p.combo=0;if(!p.dashReset)p.dashUses=0; + p.sinceSpend++;if(p.sinceSpend>=TUNING.staminaDelay)p.stamina=Math.min(p.maxStamina,p.stamina+TUNING.staminaRegen/HZ); + for(const q of this.party){if(q.skillCD>0)q.skillCD--;if(q.burstCD>0)q.burstCD--;if(q.wet>0)q.wet--;if(q.pepper>0)q.pepper--; + if(q.electrocharged>0){q.electrocharged--;if(q.electrocharged%60===0&&q.hp>0){const actual=Math.min(q.hp,350);q.hp-=actual;this.stats.playerDamage+=actual;if(!q.hp)this.emit('character_down');}}} + this.replaceDefeated();if(this.outcome)return; + this.updatePlayer(keys,pressed,mouse); + if(this.outcome){this.syncPlayerHealth();return;} + for(const item of this.pending){item.delay--;if(item.delay<=0){ + if(this.party[item.owner].hp<=0){item.dead=true;continue;} + if(item.kind==='skill')this.skillImpact(item);else if(item.kind==='burst')this.burstImpact(item); + else if(item.kind==='swing'){this.area(item.hit,p.x,p.z,4);this.fx('swing',{x:p.x,z:p.z,y:1,element:'pyro',life:18}); + if(item.last){const tornado=this.auras.find(a=>a.kind==='pyronado'&&a.owner===item.owner&&a.snapATK===null);if(tornado)tornado.snapATK=this.statATK(this.party[item.owner]);}} + else if(this.party[item.owner].weapon==='bow'||this.party[item.owner].weapon==='catalyst'&&item.kind==='normal')this.projectile(item.hit,this.target()); + else this.area(item.hit,p.x,p.z,item.range,{angle:p.yaw,half:1});item.dead=true;if(this.outcome)break;}} + this.pending=this.pending.filter(q=>!q.dead); + if(this.outcome){this.syncPlayerHealth();return;} + for(const stage of ['updateBoss','updateProjectiles','updateSummons','updateAuras','updateHazards','updateParticles']){this[stage]();if(this.outcome){this.syncPlayerHealth();return;}} + for(const v of this.effects)v.age++;this.effects=this.effects.filter(v=>v.age({id:100+i,kind:'prism',x:Math.sin(i*TAU/3)*TUNING.prismRadius, + z:Math.cos(i*TAU/3)*TUNING.prismRadius,y:.8,gauge:3,maxGauge:3,alive:true,active:false}))}; + Object.assign(this.stats,{moves:Object.fromEntries(Object.keys(MOVE_NAMES).map(k=>[k,0])),coreExposures:0,coreHits:0, + blockedCoreHits:0,electroImmune:0,prismIgnoredHits:0,pillarBreaks:0,prismBreaks:0,revivalCycles:0,revivals:0,diamondInterrupts:0,cages:0}); + } + moveName(m){return MOVE_NAMES[m]||'';} + aliveTargets(){return [this.boss,...this.boss.prisms.filter(p=>p.alive&&p.active),...this.hazards.filter(h=>h.kind==='pillar'&&h.gauge>0&&h.age>=h.delay)];} + targetable(q){return q.kind!=='core'||this.boss.exposed;} + fallbackTargets(all){return all.filter(t=>t.kind==='core');} + guobaFallback(){return this.boss;} + entity(id){if(id===0)return this.boss;return this.boss.prisms.find(p=>p.id===id)||null;} + exposed(value){ + if(value&&!this.boss.exposed){this.stats.coreExposures++;this.emit('core_exposed');} + this.boss.exposed=value; + } + hitTarget(target,hit){ + if(target.kind==='prism'||target.kind==='pillar'){ + if(target.gauge<=0||target.alive===false||target.kind==='pillar'&&target.age!p.alive)){this.boss.hp=0;this.outcome='win';this.boss.mode='dead';this.boss.shape='dead';this.emit('boss_defeated');} + return true; + } + const b=this.boss;if(!b.exposed||b.mode==='revival'){this.stats.blockedCoreHits++;if(hit.damage>0)this.fx('immune',{x:b.x,z:b.z,y:b.y+1.2,life:30});return false;} + if(hit.element==='electro'){this.stats.electroImmune++;return false;} + const owner=this.party[hit.owner],baseResistance=hit.element==='physical'&&b.physicalShred?-.3:.1; + let damage=hit.damage*.5*(baseResistance<0?1-baseResistance/2:1-baseResistance),reaction=null; + const applied=this.application(hit,b); + if(applied){this.stats.elementApplications++; + // Damage Sequence (Fandom Overloaded / Superconduct): per attacker and target, at most 1 Overloaded or + // 2 Superconduct instances every 0.5 s. The aura still reacts; only the reaction damage instance is capped. + const seq=kind=>{const key=hit.owner+':'+kind,rec=this.reactionSeq[key],limit=kind==='overload'?1:2; + if(!rec||this.t-rec.start>=30){this.reactionSeq[key]={start:this.t,count:1};return true;}if(rec.count0)this.fx('dmg',{x:b.x,z:b.z,y:b.y+1.1,amount:Math.round(actual),element:hit.element,reaction,life:54}); + this.barbaraHeal(owner,hit);this.naEnergy(owner,hit,actual); + while(b.orbThresholds.length&&b.hp<=b.maxHp*b.orbThresholds[0]+1e-6){b.orbThresholds.shift();this.dropOrb(b.x,b.z);} + if(b.hp<=b.maxHp*TUNING.reviveThreshold+1e-6)this.enterRevival(); + else if(b.move==='missiles'&&b.mode==='attack'){ + b.poise+=hit.poise||0;if(b.poise>=TUNING.diamondInterruptPoise){this.stats.diamondInterrupts++;this.emit('diamond_interrupted');this.finishMove();} + } + return true; + } + wallCollision(a,b){ + const pillars=this.hazards.filter(h=>h.kind==='pillar'&&h.gauge>0&&h.age>=h.delay); + for(const h of pillars){const next=pillars.find(v=>v.cage===h.cage&&v.index===(h.index+1)%8);if(!next)continue; + // Sweep the whole motion segment; an end-point test misses crossing a thin wall. + const from=this.segmentDistance(a,h,next),to=this.segmentDistance(b,h,next); + if(from<=.38&&to>=from)continue; + if(this.segmentDistance(b,h,next)<.38||this.segmentsIntersect(a,b,h,next)|| + this.segmentDistance(h,a,b)<.38||this.segmentDistance(next,a,b)<.38)return true;} + return false; + } + bossTarget(){return this.aggroTarget(this.boss);} + beginMove(name){ + const b=this.boss,c=TUNING.moves[name],target=name==='cage'?this.player:this.bossTarget(); + b.move=name;b.mode='tell';b.action=name;b.actionTick=0;b.moveTick=0;b.timer=Math.round(c.tell*this.pace());b.tellTicks=b.timer;b.poise=0;this.exposed(false); + if(['lasers','waves','cage','missiles'].includes(name)){b.x=0;b.z=0;} + if(name==='clap'){const a=angle(b,target),f=forward(a);b.x=target.x-f.x*2.8;b.z=target.z-f.z*2.8;this.boundBoss();} + b.y=name==='missiles'?3.2:1.5;b.shape=name==='missiles'?'diamond':name; + b.originX=b.x;b.originZ=b.z;b.targetX=target.x;b.targetZ=target.z;b.yaw=angle(b,target); + this.stats.moves[name]++;this.emit('tell_'+name); + if(name==='cage'){ + const cage=this.idNext();b.cageCenter={x:target.x,z:target.z}; + for(let i=0;i<8;i++)this.hazards.push({id:this.idNext(),kind:'pillar',cage,index:i,x:target.x+Math.sin(i*TAU/8)*6, + z:target.z+Math.cos(i*TAU/8)*6,y:0,radius:.45,height:4,gauge:4.4,maxGauge:4.4,alive:true,age:0,delay:(i+1)*12,life:c.tell+c.active}); + for(let i=0;i<8;i++)this.hazard('circle',{x:target.x+Math.sin(i*TAU/8)*6,z:target.z+Math.cos(i*TAU/8)*6,radius:.9,delay:(i+1)*12,life:(i+1)*12+4,height:4,damage:this.bossDamage(TUNING.moveDamage.cagePillar),landing:true}); + } + } + selectMove(){ + const b=this.boss; + // Lockdown only after the current life has run long (Fandom: "usually ... when the player takes too long"). + if(this.t-b.lifeStart>=TUNING.cageInterval&&this.t-b.lastCage>=TUNING.cageInterval){b.lastCage=this.t;this.stats.cages++;this.beginMove('cage');return;} + if(!b.deck.length){b.deck=Object.keys(MOVE_NAMES).filter(k=>k!=='cage'); + for(let i=b.deck.length-1;i>0;i--){const j=Math.floor(N.rand(this)*(i+1));[b.deck[i],b.deck[j]]=[b.deck[j],b.deck[i]];}} + this.beginMove(b.deck.pop()); + } + finishMove(){ + const b=this.boss;if(b.mode==='revival'||b.mode==='dead')return; + // Rotating Lasers and Tremors each leave one Electro Energy Orb when they end (Fandom). + if(b.mode==='attack'&&(b.move==='lasers'||b.move==='waves'))this.dropOrb(b.x+forward(b.yaw).x*2,b.z+forward(b.yaw).z*2); + if(b.move==='drill'&&N.rand(this)<.65){this.beginMove(N.rand(this)<.5?'fist':'clap');return;} + b.mode='open';b.shape='exposed';b.y=1.3;b.timer=Math.round(TUNING.moves[b.move].recovery*this.pace());b.action='exposed';b.actionTick=0;this.exposed(true); + } + meleeBoss(radius,half=null,ratio=1){this.hazard('circle',{radius,angle:this.boss.yaw,half,damage:this.bossDamage(ratio),height:2,life:6});} + boundBoss(){const b=this.boss,r=TUNING.arenaRadius-1,n=Math.hypot(b.x,b.z);if(n>r){b.x*=r/n;b.z*=r/n;}} + bossMove(){ + const b=this.boss,t=b.moveTick++,f=forward(b.yaw),D=TUNING.moveDamage; + if(b.move==='fist'||b.move==='drill'){ + const L=TUNING.lunge[b.move],speed=L.speed,end=L.ticks,drill=b.move==='drill'; + if(t=TUNING.moves[b.move].active)this.finishMove(); + } + enterRevival(){ + const b=this.boss;if(b.mode==='revival')return;b.x=0;b.z=0;b.y=1.2;b.mode='revival';b.phase=2;b.shape='revival';b.action='revival';b.actionTick=0; + b.timer=TUNING.reviveTicks;b.revivalRound++;this.stats.revivalCycles++;this.exposed(false); + this.hazards=this.hazards.filter(h=>h.kind==='pillar');this.hazards.forEach(h=>{h.life=h.age;}); + b.prisms.forEach(p=>{p.active=p.alive;});this.emit('revival_started'); + } + reviveHeal(survivors){return TUNING.reviveHealMode==='linear'?survivors*TUNING.revivePerPrism:TUNING.reviveHeal[Math.min(survivors,3)];} + updateBoss(){ + const b=this.boss;b.actionTick++;if(b.physicalShred>0)b.physicalShred--; + if(b.mode==='revival'){ + if(--b.timer<=0){const survivors=b.prisms.filter(p=>p.alive);if(!survivors.length){b.hp=0;this.outcome='win';return;} + b.hp=Math.min(b.maxHp,b.hp+this.reviveHeal(survivors.length)*b.maxHp);b.lifeStart=this.t; + for(const p of survivors){p.active=false;if(TUNING.survivorGaugeResets)p.gauge=p.maxGauge;} + b.mode='idle';b.phase=1;b.shape='closed';b.timer=90;this.stats.revivals++;this.emit('boss_revived');} + return; + } + if(b.mode==='attack'){this.bossMove();return;} + if(--b.timer>0)return; + if(b.mode==='tell'){b.mode='attack';b.moveTick=0;b.actionTick=0;this.emit('attack_'+b.move);} + else if(b.mode==='open'){this.exposed(false);b.mode='idle';b.shape='closed';b.timer=36;} + else this.selectMove(); + } + // Full HP plus nine prism gauge and the 1.45x maximum are the same number reached by different sums, so at some continuous d + // floating point lands the progress one ULP above its maximum. Clamped: only those overshoots change, and no rule reads health(). + health(){const b=this.boss,prisms=b.prisms.reduce((s,p)=>s+(p.alive?p.gauge:0),0),max=b.maxHp*1.45; + return [this.party.reduce((s,p)=>s+p.hp,0),this.party.reduce((s,p)=>s+p.maxHp,0),this.outcome==='win'?0:Math.min(b.hp+prisms*b.maxHp*.05,max),max];} + } + // ---------------------------------------------------------------------------------------------- Ruin Guard + class RuinGuard extends Fight{ + constructor(id,seed,d){ + super(id,seed,d);this.atk=RG.atk;this.arenaR=RG.arena;this.hazardElement='physical'; + const hp=Math.round(byTier(RG.hp,d)),cds={}; + for(const a of RG.abilities)cds[a.id]=a.init?Math.round(span(this,a.init)*HZ*this.aggression()):0; + this.boss={id:0,kind:'guard',x:0,z:-4,y:0,vy:0,yaw:0,upper:0,hp,maxHp:hp,mode:'idle',move:null,moveTick:0,timer:60,action:'idle',actionTick:0, + r:RG.bodyR,cy:1.9,hh:2.1,interval:0,cds,weak:{window:0,rune:0},aura:null,frozen:0,inv:0,phase:1,crosshair:null,landing:null,walk:0, + orbThresholds:[...RG.orbThresholds]}; + Object.assign(this.stats,{moves:Object.fromEntries(Object.keys(GUARD_MOVES).map(k=>[k,0])),weakHits:0,eyeHits:0,backHits:0,staggers:0,paralyzes:0,volleyBreaks:0,missiles:0,guardHits:0,blockedHits:0}); + } + moveName(m){return GUARD_MOVES[m]||'';} + aliveTargets(){return this.boss.mode==='dead'?[]:[this.boss];} + fallbackTargets(all){return all;} + // Weak points: the glowing eye (front of the head) and the socket on the back (Fandom); hidden while paralyzed. + weakPoints(){const b=this.boss,fy=b.yaw+b.upper,f=forward(fy),k=forward(fy+PI); + return [{id:'eye',x:b.x+f.x*RG.eye.fwd,y:b.y+RG.eye.y,z:b.z+f.z*RG.eye.fwd,nx:f.x,nz:f.z}, + {id:'back',x:b.x+k.x*RG.back.fwd,y:b.y+RG.back.y,z:b.z+k.z*RG.back.fwd,nx:k.x,nz:k.z}];} + weakOpen(){const b=this.boss;return b.mode!=='paralyzed'&&b.mode!=='dead';} + // Lock-on aims arrows at the body. Weak points need free aim (R off, mouse yaw/pitch), as aim mode does in the original. + aimPoint(q){return {x:q.x,y:(q.y||0)+1.9,z:q.z};} + projectileHits(q,old,a){return this.segmentDistance(q,old,a)q.y-.2&&a.y-.15)continue; + const px=w.x-path.x0,py=w.y-path.y0,pz=w.z-path.z0,t=clamp(px*ux+py*uy+pz*uz,0,l+2.5),cx=px-t*ux,cy=py-t*uy,cz=pz-t*uz; + if(Math.hypot(cx,cy,cz)0){this.stats.blockedHits++;if(hit.damage>0)this.fx('immune',{x:b.x,z:b.z,y:b.y+3.2,life:30});return false;} + const weak=hit.path&&hit.aimed?this.weakHit(hit.path):null; + const applied=this.application(hit,b);if(applied)this.stats.elementApplications++; + const rx=applied?this.react(b,hit):{mult:1,reaction:null}; + // Aimed shots that strike a weak point are guaranteed CRIT (Fandom Bow); base CRIT DMG 50%. + const crit=weak?1.5:1,damage=hit.damage*.5*resMult(this.resistance(hit.element))*rx.mult*crit; + const owner=this.party[hit.owner],actual=Math.min(b.hp,damage);b.hp=Math.max(0,b.hp-damage); + this.stats.damageDealt+=actual;this.stats.guardHits++; + const y=weak==='eye'?b.y+RG.eye.y:weak==='back'?b.y+RG.back.y:b.y+2; + this.fx('impact',{x:b.x,z:b.z,y,element:hit.element}); + if(actual>0)this.fx('dmg',{x:b.x,z:b.z,y:y+.6,amount:Math.round(actual),element:hit.element,reaction:rx.reaction,crit:!!weak,life:54}); + if(rx.reaction)this.fx('reaction',{x:b.x,z:b.z,y:y+1.2,element:hit.element,reaction:rx.reaction,life:54}); + this.barbaraHeal(owner,hit);this.naEnergy(owner,hit,actual); + while(b.orbThresholds.length&&b.hp<=b.maxHp*b.orbThresholds[0]+1e-6){b.orbThresholds.shift();this.dropOrb(b.x,b.z,'neutral');this.particle('neutral',1,b.x+.6,b.z);} + if(b.hp<=0){this.outcome='win';b.mode='dead';b.action='dead';b.actionTick=0;this.cancelMove();this.emit('boss_defeated');return true;} + if(rx.reaction==='frozen'){this.cancelMove();b.mode='idle';b.action='frozen';this.emit('guard_frozen');} + if(weak)this.weakPointHit(weak); + return true; + } + weakPointHit(id){ + const b=this.boss,W=b.weak;this.stats.weakHits++;this.stats[id==='eye'?'eyeHits':'backHits']++;this.emit('weak_point_'+id); + const w=this.weakPoints().find(v=>v.id===id);this.fx('weak',{x:w.x,z:w.z,y:w.y,element:'physical',life:24}); + // Protective runes block a new disable but the spot still takes CRIT hits (Fandom strategy section). + if(W.rune>0||b.mode==='paralyzed')return; + // Two quick weak-point hits paralyze; a lone hit only staggers briefly (Fandom: "If a second follow-up attack ..."). + if(W.window>0){this.paralyze();return;} + W.window=RG.windowTicks;this.stats.staggers++; + // Hitting the back socket during the Suppressive Volley aim stops it (BWIKI); a rear hit turns the guard to face you. + if(b.mode==='attack'&&b.move==='volley'&&b.moveTick!(h.src===0&&(h.follow!==undefined||h.age1.5)return;const r=b.r+.45,d=Math.hypot(next.x-b.x,next.z-b.z); + if(d1e-6?Math.atan2(next.x-b.x,next.z-b.z):this.player.yaw+PI;next.x=b.x+Math.sin(a)*r;next.z=b.z+Math.cos(a)*r;}} + boundBoss(){const b=this.boss,r=RG.arena-1.5,n=Math.hypot(b.x,b.z);if(n>r){b.x*=r/n;b.z*=r/n;}} + turnToward(T,rate){const b=this.boss,want=angle(b,T),dy=wrap(want-b.yaw);b.yaw=wrap(b.yaw+clamp(dy,-rate,rate));return Math.abs(wrap(want-b.yaw));} + beginMove(ab){ + const b=this.boss,T=this.aggroTarget(b);b.mode='attack';b.move=ab.move;b.moveTick=0;b.action=ab.move;b.actionTick=0;b.ability=ab.id; + b.cds[ab.id]=Math.round(span(this,ab.cd)*HZ*this.aggression());b.useInterval=ab.interval;b.tellTicks=Math.round(RG.moves[ab.move].tell*this.pace()||0); + b.targetX=T.x;b.targetZ=T.z;this.stats.moves[ab.move]++;this.emit('tell_'+ab.move); + } + finishMove(){const b=this.boss;b.mode='idle';b.action='idle';b.move=null;b.upper=0;b.crosshair=null;b.landing=null; + if(b.useInterval)b.interval=Math.round(RG.interval*this.aggression());b.timer=12;} + guardMove(){ + const b=this.boss,t=b.moveTick++,T=this.aggroTarget(b),f=forward(b.yaw),Mv=RG.moves; + if(b.move==='stomp'){const S=Mv.stomp,tell=b.tellTicks; + if(t=tell+S.recovery){const P=this.player,a=Math.abs(wrap(angle(b,P)-b.yaw)); + // Fandom: "If a player is still within melee range after the stomp, the Ruin Guard may lean down and clap". + if(dist(b,P)=tell+C.recovery)this.finishMove();return;} + if(b.move==='combo'){const C=Mv.combo,tell=b.tellTicks,shift=tell-C.tell; + if(t{if(t===at+shift){const ff=forward(b.yaw);this.hazard('circle',{x:b.x,z:b.z,radius:C.radius,half:C.half,angle:b.yaw,height:2.4,life:6,damage:this.bossDamage(C.ratios[i]),src:0});const o={x:b.x,z:b.z};b.x+=ff.x*.8;b.z+=ff.z*.8;this.boundBoss();if(!Number.isFinite(o.x))b.x=0;}}); + if(t===C.jump+shift){const L=this.clampArena({x:T.x,z:T.z},2);b.landing={x:L.x,z:L.z,fromX:b.x,fromZ:b.z}; + this.hazard('circle',{x:L.x,z:L.z,radius:C.landRadius,delay:C.land-C.jump,life:C.land-C.jump+6,height:2.2,damage:this.bossDamage(C.landRatio),src:0,landing:true});} + if(b.landing&&t>C.jump+shift&&t<=C.land+shift){const u=(t-C.jump-shift)/(C.land-C.jump),L=b.landing;b.x=L.fromX+(L.x-L.fromX)*u;b.z=L.fromZ+(L.z-L.fromZ)*u;b.y=4*Math.sin(Math.PI*u); + if(t===C.land+shift){b.y=0;b.landing=null;this.fx('land',{x:b.x,z:b.z,y:0,life:36});}} + if(t>=C.land+shift+C.recovery)this.finishMove();return;} + if(b.move==='spin'){const S=Mv.spin,tell=b.tellTicks; + if(t1.2){b.x+=ff.x*S.march/HZ;b.z+=ff.z*S.march/HZ;this.boundBoss();}b.upper=wrap(b.upper+.42);return;} + b.upper=0;if(t>=tell+S.active+S.recovery)this.finishMove();return;} + if(b.move==='volley'){const V=Mv.volley; + // Swivel the upper body 180 degrees so the back cannons (and the back weak point) face the target, then stay put. + if(t=V.fire&&tV.fire+V.count*V.spacing+V.track){b.upper=PI*Math.max(0,1-(t-(V.fire+V.count*V.spacing+V.track))/V.back);} + if(t>=V.fire+V.count*V.spacing+V.track+V.back)this.finishMove();return;} + } + updateMissiles(){ + // Seeking Missiles re-aim almost instantly while the crosshair is up, then continue straight (Fandom). + const b=this.boss,P=this.player,V=RG.moves.volley; + for(const h of this.hazards){if(!h.missile)continue; + if(h.age<20){h.y+=h.vy;continue;}h.y=Math.max(.9,h.y-.05); + if(b.crosshair&&!h.spent){const a=angle(h,P),sp=V.speed/HZ;h.vx=Math.sin(a)*sp;h.vz=Math.cos(a)*sp;} + if(Math.hypot(h.x,h.z)>RG.arena+2)h.life=h.age;} + } + updateBoss(){ + const b=this.boss;b.actionTick++;this.decayAura(b); + for(const k of Object.keys(b.cds))if(b.cds[k]>0)b.cds[k]--; + if(b.interval>0)b.interval--;if(b.inv>0)b.inv--;if(b.weak.rune>0)b.weak.rune--; + if(b.weak.window>0&&--b.weak.window===0&&b.mode!=='paralyzed')b.weak.rune=RG.runeTicks; + this.updateMissiles(); + if(b.mode==='dead')return; + if(b.frozen>0){b.frozen--;b.action='frozen';if(!b.frozen){b.action='idle';b.timer=20;}return;} + if(b.mode==='paralyzed'){if(--b.timer<=0){b.mode='idle';b.action='wake';b.actionTick=0;b.weak.rune=RG.runeTicks;b.inv=RG.wakeTicks;b.timer=40;this.emit('guard_recovered');}return;} + if(b.mode==='stagger'){if(--b.timer<=0){b.mode='idle';b.action='idle';b.timer=18;}return;} + if(b.mode==='attack'){this.guardMove();return;} + if(b.timer>0)b.timer--; + const T=this.aggroTarget(b),d=dist(b,T),off=Math.abs(wrap(angle(b,T)-b.yaw))*180/PI; + if(!b.timer&&b.interval<=0){ + // AI table: every ability off cooldown whose range and angle requirements hold is equally likely (same priority). + const ready=RG.abilities.filter(a=>b.cds[a.id]<=0&&d>=a.min&&d<=a.max&&off<=a.angle); + if(ready.length){this.beginMove(ready[Math.floor(N.rand(this)*ready.length)]);return;} + } + // Otherwise march toward the target (the guard always re-engages). + const off2=this.turnToward(T,RG.turn);b.action=d>2.4?'walk':'idle'; + if(d>2.4&&off2<1.1){const f=forward(b.yaw);b.x+=f.x*RG.walk/HZ;b.z+=f.z*RG.walk/HZ;this.boundBoss();b.walk+=RG.walk/HZ;} + } + } + // ---------------------------------------------------------------------------------------------- Oceanid + class Oceanid extends Fight{ + constructor(id,seed,d){ + super(id,seed,d);this.atk=OC.atk;this.arenaR=OC.pond;this.hazardElement='hydro'; + const unit=byTier(OC.hpUnit,d),types=shuffle(this,Object.keys(OC.types));let k=0; + const plan=OC.waves.map(n=>types.slice(k,k+=n)); + const maxHp=plan.flat().reduce((s,t)=>s+OC.types[t].count*Math.round(OC.types[t].hp*unit),0); + this.boss={id:0,kind:'oceanid',x:0,z:-15,y:1.2,yaw:0,hp:maxHp,maxHp,mode:'intro',timer:60,wave:0,waveTicks:0,moveTick:0,unit,plan, + orbs:[],tiles:[false,false,false,false,false,false,false,false,false],warn:[],action:'idle',actionTick:0,phase:1}; + this.mimics=[];this.player.z=2.5; + Object.assign(this.stats,{moves:Object.fromEntries(Object.keys(OCEANID_MOVES).map(k=>[k,0])),kills:Object.fromEntries(Object.keys(OC.types).map(k=>[k,0])), + waves:0,mimicHits:0,hydroImmune:0,bombs:0,mimicAttacks:0}); + } + moveName(m){return OCEANID_MOVES[m]||'';} + aliveTargets(){return this.mimics.filter(m=>m.hp>0);} + targetable(m){return m.mode!=='form';} + solid(m){return m.mode!=='form';} + aimPoint(m){return {x:m.x,y:m.y+OC.types[m.type].cy,z:m.z};} + projectileHits(q,old,a){return this.segmentDistance(q,old,a)m.id===id)||null;} + tileCenter(i){return {x:(i%3-1)*OC.tile,z:(Math.floor(i/3)-1)*OC.tile};} + tileAt(x,z){const h=OC.tile*1.5,ix=Math.floor((x+h)/OC.tile),iz=Math.floor((z+h)/OC.tile);return ix<0||ix>2||iz<0||iz>2?-1:iz*3+ix;} + terrain(x,z){const i=this.tileAt(x,z);return i<0||this.boss.tiles[i]?'water':'ground';} + health(){const b=this.boss,missing=this.mimics.reduce((s,m)=>s+(m.hp>0?m.maxHp-m.hp:0),0); + return [this.party.reduce((s,p)=>s+p.hp,0),this.party.reduce((s,p)=>s+p.maxHp,0),this.outcome==='win'?0:Math.max(0,b.hp-missing),b.maxHp];} + mimicDamage(m,ratio){return OC.mimicATK*OC.types[m.type].atk*ratio*this.dmgScale();} + chooseTile(cat){const list=OC.tiles[cat];return list[Math.floor(N.rand(this)*list.length)];} + beginSummon(){ + const b=this.boss;b.wave++;b.mode='summon';b.moveTick=0;b.action='summon';b.actionTick=0;b.waveTicks=0;this.stats.moves.summon++;this.emit('tell_summon'); + b.orbs=b.plan[b.wave-1].map((type,i)=>{const tile=this.chooseTile(OC.types[type].cat),c=this.tileCenter(tile);return {type,tile,x:c.x,z:c.z,from:{x:b.x+(i?1:-1)*.8,z:b.z},t:-1};}); + } + spawnGroup(o){ + const T=OC.types[o.type],unit=this.boss.unit; + for(let i=0;i1?1.4:0; + this.mimics.push({id:this.idNext(),kind:'mimic',type:o.type,x:o.x+Math.sin(a)*r,z:o.z+Math.cos(a)*r,y:T.fly?T.fly:0,yaw:angle(o,this.player), + hp:Math.round(T.hp*unit),maxHp:Math.round(T.hp*unit),mode:'form',timer:OC.formTicks,move:null,moveTick:0,cd:Math.round(40+N.rand(this)*50), + frozen:0,healBlock:0,healT:0,selfAura:'hydro',r:T.r,cy:T.cy,hh:T.hh,wave:this.boss.wave,action:'form',actionTick:0,orbit:a,rest:0,hz:0,tx:0,tz:0,fromX:0,fromZ:0});} + this.fx('splash',{x:o.x,z:o.z,y:.2,life:40}); + } + hitTarget(m,hit){ + if(m.hp<=0||m.mode==='form')return false; + // Hydro Mimics are completely immune to Hydro (Fandom); Pyro also halts the boar/squirrel self-heal for 3 s. + if(hit.element==='hydro'){this.stats.hydroImmune++;if(hit.damage>0)this.fx('immune',{x:m.x,z:m.z,y:m.y+m.cy+1,life:30});return false;} + if(hit.element==='pyro')m.healBlock=180; + const T=OC.types[m.type],applied=this.application(hit,m);if(applied)this.stats.elementApplications++; + const rx=applied?this.react(m,hit):{mult:1,reaction:null}; + if(rx.reaction==='frozen')this.freezeMimic(m); + const res=hit.element===T.weak?-.4:.15,damage=hit.damage*.5*resMult(res)*rx.mult,actual=Math.min(m.hp,damage),owner=this.party[hit.owner]; + m.hp=Math.max(0,m.hp-damage);this.stats.damageDealt+=actual;this.stats.mimicHits++; + this.fx('impact',{x:m.x,z:m.z,y:m.y+m.cy,element:hit.element}); + if(actual>0)this.fx('dmg',{x:m.x,z:m.z,y:m.y+m.cy+.9,amount:Math.round(actual),element:hit.element,reaction:rx.reaction,life:54}); + if(rx.reaction)this.fx('reaction',{x:m.x,z:m.z,y:m.y+m.cy+1.5,element:hit.element,reaction:rx.reaction,life:54}); + this.barbaraHeal(owner,hit);this.naEnergy(owner,hit,actual); + if(m.hp<=0)this.killMimic(m); + return true; + } + // Mimics stay over the 3×3 platform grid (they can hover on water, so sunken tiles still hold them). + boundMimic(m){const r=OC.tile*1.5-.7;m.x=clamp(m.x,-r,r);m.z=clamp(m.z,-r,r);} + gridPoint(P){const r=OC.tile*1.5-.7;return {x:clamp(P.x,-r,r),z:clamp(P.z,-r,r)};} + dropAttached(m){if(m.hz){this.hazards=this.hazards.filter(h=>h.id!==m.hz);m.hz=0;}} + freezeMimic(m){this.dropAttached(m);m.mode='idle';m.move=null;m.action='frozen';this.emit('mimic_frozen');} + killMimic(m){ + const b=this.boss,T=OC.types[m.type];this.dropAttached(m);m.mode='dead';m.action='dead'; + b.hp=Math.max(0,b.hp-m.maxHp);this.stats.kills[m.type]++;this.emit('mimic_defeated');this.fx('splash',{x:m.x,z:m.z,y:m.y,life:40}); + this.particle('neutral',1,m.x,m.z); + // Frogs and finches turn into a wide water bomb when defeated (Fandom). + if(T.bomb){this.hazard('circle',{x:m.x,z:m.z,radius:4.2,delay:90,life:96,height:3,damage:this.mimicDamage(m,1),bomb:true,src:m.id});this.stats.bombs++;} + if(this.mimics.every(v=>v.hp<=0)&&b.mode==='wave')this.waveCleared(); + } + waveCleared(){ + const b=this.boss;this.stats.waves++;this.emit('wave_cleared'); + if(b.wave>=b.plan.length){b.hp=0;this.outcome='win';b.mode='dead';b.action='dead';this.emit('boss_defeated');return;} + if(OC.sinkAfter.includes(b.wave))this.beginSink();else{b.mode='rest';b.timer=45;} + } + beginSink(){ + const b=this.boss,open=[0,1,2,3,5,6,7,8].filter(i=>!b.tiles[i]);shuffle(this,open); + b.warn=open.slice(0,2);b.mode='sink';b.moveTick=0;b.action='dive';b.actionTick=0;this.stats.moves.sink++;this.emit('tell_sink'); + } + updateBoss(){ + const b=this.boss;b.actionTick++; + for(const m of this.mimics)this.updateMimic(m);if(this.outcome)return; + this.mimics=this.mimics.filter(m=>m.hp>0); + for(const h of this.hazards)if(h.whirl){ + // Tide and Torrent: the whirlpool follows the player, then explodes for 200% ATK (Fandom). + const P=this.player,a=angle(h,P),dd=dist(h,P),sp=Math.min(dd,3.6/HZ);h.x+=Math.sin(a)*sp;h.z+=Math.cos(a)*sp; + if(h.age===h.life-2)this.hazard('circle',{x:h.x,z:h.z,radius:3,life:4,height:3,damage:this.bossDamage(2),burst:true});} + if(b.mode==='intro'){if(--b.timer<=0)this.beginSummon();return;} + if(b.mode==='rest'){if(--b.timer<=0)this.beginSummon();return;} + if(b.mode==='summon'){const t=b.moveTick++,launch=30; + if(t===launch)b.orbs.forEach(o=>{o.t=0;}); + for(const o of b.orbs)if(o.t>=0&&++o.t===OC.orbTicks){this.spawnGroup(o);o.done=true;} + if(b.orbs.every(o=>o.done)){b.orbs=[];b.mode='wave';b.action='idle';b.waveTicks=0;} + return;} + if(b.mode==='wave'){b.waveTicks++; + const limit=Math.round(OC.torrentTicks*this.aggression()); + if(b.waveTicks>=limit){b.waveTicks=0;const P=this.player;this.stats.moves.torrent++;this.emit('tide_and_torrent'); + this.hazard('circle',{x:P.x,z:P.z,radius:2.2,delay:30,life:300,height:2,rehit:60,damage:this.bossDamage(.5),whirl:true,light:true});} + return;} + if(b.mode==='sink'){const t=b.moveTick++,impact=Math.round(OC.sinkTell*this.pace()); + const first=this.tileCenter(b.warn[0]||4);b.x=b.x+(first.x-b.x)*.04;b.z=b.z+(first.z-b.z)*.04;b.y=timpact+20){b.x=b.x+(0-b.x)*.1;b.z=b.z+(-15-b.z)*.1;b.y=Math.min(1.2,b.y+.06);} + if(t>=impact+50){b.warn=[];b.x=0;b.z=-15;b.y=1.2;b.mode='rest';b.timer=20;b.action='idle';} + return;} + } + // Mimic behaviours. Attack kinds and ratios come from the Fandom mimic pages; speeds, ranges and timings are calibrated. + updateMimic(m){ + if(m.hp<=0)return;const T=OC.types[m.type];m.actionTick++; + if(m.healBlock>0)m.healBlock--; + if(T.heal&&++m.healT>=90){m.healT=0;if(!m.healBlock&&m.hp0){m.frozen--;if(T.fly)m.y=Math.max(.3,m.y-.12);if(!m.frozen){m.action='idle';m.cd=Math.max(m.cd,30);}return;} + const P=this.aggroTarget(m),d=dist(m,P),face=()=>{m.yaw=wrap(m.yaw+clamp(wrap(angle(m,P)-m.yaw),-.15,.15));}; + const step=(a,speed)=>{const f=forward(a);m.x+=f.x*speed/HZ;m.z+=f.z*speed/HZ;this.boundMimic(m);}; + const tell=n=>Math.round(n*this.pace());if(m.cd>0)m.cd--; + const begin=(move,ticks)=>{m.mode='tell';m.move=move;m.timer=tell(ticks);m.moveTick=0;m.action=move;m.actionTick=0;this.stats.mimicAttacks++;}; + if(m.mode==='recover'){if(--m.timer<=0){m.mode='idle';m.action='idle';}if(T.fly&&m.timer<30)m.y=Math.min(T.fly,m.y+.13);return;} + if(m.type==='boar'){ + if(m.mode==='tell'){face();if(--m.timer<=0){m.mode='attack';m.moveTick=0;}return;} + if(m.mode==='attack'){const L=m.move==='ram'?{speed:9,ticks:16}:{speed:11,ticks:56},old={x:m.x,z:m.z};step(m.yaw,L.speed); + this.hazard('sweep',{x:old.x,z:old.z,toX:m.x,toZ:m.z,radius:.9,height:1.6,life:1,damage:this.mimicDamage(m,1),src:m.id}); + if(++m.moveTick>=L.ticks){m.mode='recover';m.timer=m.move==='ram'?40:54;m.action='recover';}return;} + face();if(m.cd<=0&&d<3.4){begin('ram',30);m.cd=Math.round(100*this.aggression());return;} + if(m.cd<=0&&d>=6){begin('charge',42);m.cd=Math.round(150*this.aggression());return;} + if(d>2.2){step(m.yaw,T.speed);m.action='move';}else m.action='idle';return;} + if(m.type==='squirrel'){ + if(m.mode==='tell'){if(m.move==='sweep')face();if(--m.timer<=0){m.mode='attack';m.moveTick=0;m.fromX=m.x;m.fromZ=m.z; + if(m.move==='sweep')this.hazard('circle',{x:m.x,z:m.z,radius:2.6,half:1.1,angle:m.yaw,height:1.8,life:6,damage:this.mimicDamage(m,1),src:m.id});}return;} + if(m.mode==='attack'){if(m.move==='slam'){const u=Math.min(1,(m.moveTick+1)/36);m.x=m.fromX+(m.tx-m.fromX)*u;m.z=m.fromZ+(m.tz-m.fromZ)*u;m.y=2.5*Math.sin(Math.PI*u);if(u>=1)m.y=0;} + if(++m.moveTick>=(m.move==='slam'?36:12)){m.mode='recover';m.timer=m.move==='slam'?40:36;m.action='recover';m.y=0;}return;} + face();if(m.cd<=0&&d<2.8){begin('sweep',24);m.cd=Math.round(90*this.aggression());return;} + if(m.cd<=0&&d<7){begin('slam',30);const L=this.gridPoint(P);m.tx=L.x;m.tz=L.z;m.cd=Math.round(130*this.aggression()); + this.hazard('circle',{x:L.x,z:L.z,radius:1.6,delay:m.timer+36,life:m.timer+42,height:1.8,damage:this.mimicDamage(m,1),src:m.id,landing:true});return;} + if(d>2){step(m.yaw,T.speed);m.action='move';}else m.action='idle';return;} + if(m.type==='crab'){ + // Bubble Spray: walks sideways around the player spitting a stream (10% ATK DoT); rests now and then (Fandom). + face();m.rest++;const resting=m.rest%300>=210; + if(resting){this.dropAttached(m);m.action='rest';return;} + const side=m.yaw+PI/2*(m.id%2?1:-1),want=d>4.6?m.yaw:d<3.2?m.yaw+PI:side;step(want,T.speed);m.action='spray'; + let h=m.hz?this.hazards.find(v=>v.id===m.hz):null; + if(!h){h=this.hazard('beam',{x:m.x,z:m.z,angle:m.yaw,length:4.6,width:.4,inner:0,height:1.4,life:100000,rehit:30,damage:this.mimicDamage(m,.1),src:m.id,stream:true,light:true});m.hz=h.id;} + h.x=m.x;h.z=m.z;h.angle=m.yaw;return;} + if(m.type==='mallard'){ + // Vortex: follows the player with a water vortex underneath dealing 50% ATK DoT (Fandom). + face();if(d>.6){step(m.yaw,T.speed);m.action='move';} + if(!m.hz){const h=this.hazard('circle',{x:m.x,z:m.z,radius:1.9,height:1.2,life:100000,rehit:30,damage:this.mimicDamage(m,.5),src:m.id,follow:m.id,vortex:true,light:true});m.hz=h.id;}return;} + if(m.type==='crane'){ + if(m.mode==='tell'){face();if(--m.timer<=0){const a=angle(m,P),f=forward(a);m.mode='recover';m.timer=30;m.action='recover'; + this.hazard('bolt',{x:m.x+f.x*.8,z:m.z+f.z*.8,y:.6,vx:f.x*9/HZ,vz:f.z*9/HZ,radius:.8,life:110,height:1.4,damage:this.mimicDamage(m,1),src:m.id,wave:true});}return;} + face();if(m.cd<=0&&d<14){begin('wave',36);m.cd=Math.round(150*this.aggression());return;} + // Backstep: keeps its distance like a Fatui bracer (Fandom). + if(d<5){step(m.yaw+PI,T.speed);m.action='back';}else if(d>11){step(m.yaw,T.speed);m.action='move';}else{step(m.yaw+PI/2,T.speed*.4);m.action='idle';}return;} + if(m.type==='raptor'){ + if(m.mode==='tell'){face();if(--m.timer<=0){m.mode='attack';m.moveTick=0;m.fromX=m.x;m.fromZ=m.z;}return;} + if(m.mode==='attack'){const u=Math.min(1,(m.moveTick+1)/24);m.x=m.fromX+(m.tx-m.fromX)*u;m.z=m.fromZ+(m.tz-m.fromZ)*u;m.y=T.fly*(1-u)+.3*u; + if(++m.moveTick>=24){m.mode='recover';m.timer=90;m.action='grounded';}return;} + // Dive: swoops onto the player for 100% ATK with severe knockback (Fandom); it rests on the ground before climbing. + m.orbit+=.015;const ox=P.x+Math.sin(m.orbit)*6,oz=P.z+Math.cos(m.orbit)*6;step(angle(m,{x:ox,z:oz}),Math.min(T.speed,dist(m,{x:ox,z:oz})*HZ));m.y=Math.min(T.fly,m.y+.08);face(); + if(m.cd<=0&&m.y>=T.fly-.01){begin('dive',30);const L=this.gridPoint(P);m.tx=L.x;m.tz=L.z;m.cd=Math.round(170*this.aggression()); + this.hazard('circle',{x:L.x,z:L.z,radius:1.5,delay:m.timer+24,life:m.timer+30,height:2.5,damage:this.mimicDamage(m,1),src:m.id,knock:true,landing:true});} + m.action='fly';return;} + // Frog / finch: hopping leapers that explode on death. + if(m.mode==='tell'){face();if(--m.timer<=0){m.mode='attack';m.moveTick=0;m.fromX=m.x;m.fromZ=m.z; + if(m.move==='wave'){const a=angle(m,P),f=forward(a);m.mode='recover';m.timer=36;m.action='recover'; + this.hazard('bolt',{x:m.x+f.x*.9,z:m.z+f.z*.9,y:.5,vx:f.x*8/HZ,vz:f.z*8/HZ,radius:.85,life:110,height:1.4,damage:this.mimicDamage(m,1),src:m.id,wave:true});}}return;} + if(m.mode==='attack'){const air=m.move==='leap'?24:48,u=Math.min(1,(m.moveTick+1)/air);m.x=m.fromX+(m.tx-m.fromX)*u;m.z=m.fromZ+(m.tz-m.fromZ)*u;m.y=(m.move==='leap'?1.6:3.6)*Math.sin(Math.PI*u); + if(++m.moveTick>=air){m.y=0;m.mode='recover';m.timer=40;m.action='recover';}return;} + face(); + if(m.cd<=0){ + if(m.type==='finch'&&d<4){begin('leap',18);const L=this.gridPoint(P);m.tx=L.x;m.tz=L.z;m.cd=Math.round(110*this.aggression()); + // Finch Leap cannot be avoided with dash i-frames (Fandom). + this.hazard('circle',{x:L.x,z:L.z,radius:1.6,delay:m.timer+24,life:m.timer+30,height:1.8,damage:this.mimicDamage(m,1),src:m.id,noIframe:true,landing:true});return;} + if(m.type==='frog'&&d>5){begin('wave',36);m.cd=Math.round(160*this.aggression());return;} + if(d<11){begin('high',20);const L=this.gridPoint(P);m.tx=L.x;m.tz=L.z;m.cd=Math.round((m.type==='frog'?160:120)*this.aggression()); + this.hazard('circle',{x:L.x,z:L.z,radius:m.type==='frog'?2.6:2.4,delay:m.timer+48,life:m.timer+54,height:2,damage:this.mimicDamage(m,1),src:m.id,landing:true});return;} + } + if(d>2.4){const hop=Math.sin(m.actionTick*.25)>0;if(hop)step(m.yaw,T.speed*1.6);m.y=hop?Math.abs(Math.sin(m.actionTick*.25))*.35:0;m.action='hop';} + } + } + const CLASSES={'genshin/electro_hypostasis':ElectroHypostasis,'genshin/ruin_guard':RuinGuard,'genshin/oceanid':Oceanid}; + // NativeBench.Session calls `new Module.Game(id, seed, d)`; a constructor returning an object yields that object. + M.Game=function(id,seed,d){const C=CLASSES[id];if(!C)throw Error('Unknown Genshin case');return new C(id,seed,d);}; + M.classes=CLASSES; + // ---- Standard scripted reference controller (overnight protocol section 3) ---- + // Trusted, deterministic, packet-level. It reads privileged state and plans on deep copies of the + // simulation; it never writes the live game or its RNG and only returns legal packets (<=4 keys/hold). + const SCRIPT_MEMORY=new WeakMap(); + const MOVE_SETS=[[],['W'],['S'],['A'],['D'],['W','A'],['W','D'],['S','A'],['S','D']]; + const KAEYA=0,AMBER=1,XIANGLING=2,BARBARA=3; + function cloneGame(g){const c=Object.create(Object.getPrototypeOf(g));Object.assign(c,N.copy(g));return c;} + // Mirrors NativeBench.Session.tick exactly, including the 1e-6 quantization, so the lookahead follows the same + // arithmetic in every V8 version (Node and Chromium differ by 1 ULP in trigonometry otherwise). + function stepClone(c,held,keys,mouse=[0,0,0]){const k=[...keys].sort(),pressed=k.filter(x=>!held.includes(x));c.events=[];c.update(new Set(k),new Set(pressed),mouse);N.quantize(c);c.t++; + if(!c.outcome&&c.t>=HZ*M.maxSeconds)c.outcome='timeout';return k;} + const partyHP=g=>g.party.reduce((s,q)=>s+q.hp,0); + const wardGauge=g=>g.boss.prisms.reduce((s,p)=>s+(p.alive&&p.active?p.gauge:0),0); + const pillarGauge=g=>g.hazards.reduce((s,h)=>s+(h.kind==='pillar'&&h.gauge>0?h.gauge:0),0); + function helpers(g){ + const p=g.player,party=g.party,ai=p.active,alive=i=>party[i].hp>0; + const skillReady=i=>alive(i)&&!party[i].skillCD,burstReady=i=>alive(i)&&!party[i].burstCD&&party[i].energy>=party[i].maxEnergy; + const canSwap=!p.swapCD&&!p.actionLock&&!p.stun&&p.grounded&&!p.swimming,low=party.filter(q=>q.hp>0&&q.hps+q.hp,0)/party.reduce((s,q)=>s+q.maxHp,0); + return {p,party,ai,alive,skillReady,burstReady,canSwap,low,hpFrac}; + } + function chooser(out,H){return list=>{for(const [i,action,extra] of list){if(!H.alive(i))continue;if(i!==H.ai&&!H.canSwap)continue;out.want=i;out.action=action;Object.assign(out,extra||{});return true;}return false;};} + function ehIntent(g){ + const H=helpers(g),{p,party,ai,alive,skillReady,burstReady,low,hpFrac}=H,b=g.boss,bossFrac=b.hp/b.maxHp; + const revival=b.mode==='revival',prisms=b.prisms.filter(v=>v.alive&&v.active); + const exposedSoon=b.exposed||b.mode==='tell'&&['lasers','missiles','cage'].includes(b.move)&&b.timer<=10|| + b.mode==='attack'&&b.move!=='lasers'&&TUNING.moves[b.move].active-b.moveTick<=10&&!(b.move==='drill'); + const out={want:ai,action:null,anchor:0,desired:8.5,weight:1,holdJ:false,charge:false,bunny:0,mode:revival?'revival':exposedSoon?'exposed':'closed'}; + const choose=chooser(out,H),amberCharge=extra=>({charge:true,desired:5,...extra}); + if(revival&&prisms.length){ + const T=prisms.slice().sort((a,c)=>dist(p,a)-dist(p,c))[0],d=dist(p,T);out.anchor=T.id;out.desired=3;out.weight=2.5; + const list=[]; + if(burstReady(AMBER))list.push([AMBER,'L',{desired:5}]); + if(skillReady(KAEYA))list.push([KAEYA,'K',{desired:2.6}]); + if(burstReady(XIANGLING))list.push([XIANGLING,'L',{desired:3.3}]); + if(skillReady(XIANGLING))list.push([XIANGLING,'K',{desired:2.4}]); + if(skillReady(AMBER)&&b.timer>540)list.push([AMBER,'bunny',{desired:4,bunny:Math.round((clamp(d,2,8)-2)*20)}]); + if(burstReady(KAEYA))list.push([KAEYA,'L',{desired:2.4}]); + list.push([AMBER,'charge',amberCharge({desired:4.5})]); + if(!choose(list)){out.want=ai;out.action=party[ai].id==='amber'?'charge':null;out.charge=party[ai].id==='amber';} + // Pyronado or icicles already spinning: orbit the prism at their radius. + if(g.auras.some(a=>a.kind==='pyronado'))out.desired=3.3;else if(g.auras.some(a=>a.kind==='icicles')&&out.action!=='charge')out.desired=2.4; + return out; + } + const reserve=bossFrac<.17&&b.revivalRound===0; + if(out.mode==='exposed'){ + out.desired=2.4;out.weight=1.6; + const list=[]; + // Showcase: while Melody Loop is up, Barbara's Hydro normals (water projectiles, Electro-Charged) once per fight. + if(g.auras.some(a=>a.kind==='melody'&&a.owner===BARBARA)&&g.stats.reactions.electrocharged<2&&alive(BARBARA))list.push([BARBARA,'J',{desired:4.5,holdJ:true}]); + if(burstReady(XIANGLING)&&!reserve)list.push([XIANGLING,'L',{desired:3.2}]); + if(skillReady(KAEYA))list.push([KAEYA,'K',{desired:2.6}]); + if(burstReady(KAEYA)&&!reserve)list.push([KAEYA,'L',{desired:2.2}]); + if(skillReady(XIANGLING))list.push([XIANGLING,'K',{desired:2.2}]); + if(burstReady(AMBER)&&!reserve)list.push([AMBER,'L',{desired:5}]); + if(g.auras.some(a=>a.kind==='melody'&&a.owner===BARBARA)&&low)list.push([BARBARA,'J',{desired:4.5,holdJ:true}]); + const cur=party[ai].id; + if(cur==='amber'||cur==='kaeya'||cur==='xiangling')list.push([ai,cur==='amber'?'charge':'J',cur==='amber'?amberCharge():{holdJ:true,desired:2.3}]); + list.push([AMBER,'charge',amberCharge()],[KAEYA,'J',{holdJ:true,desired:2.3}],[XIANGLING,'J',{holdJ:true,desired:2.3}],[BARBARA,'J',{holdJ:true,desired:4.5}]); + choose(list); + if(b.move==='lasers'&&b.mode==='attack')out.desired=b.moveTick<205?1.2:6; + if(g.auras.some(a=>a.kind==='pyronado')&&out.action!=='charge')out.desired=3.2; + return out; + } + // Closed shell: heal, set up, keep distance from lunges; pre-charge Amber's aimed shot. + out.desired=b.mode==='tell'&&['lasers','waves','missiles','cage'].includes(b.move)?7:6.5; + const list=[]; + // Showcase (reference demo): Barbara's kit appears at least once per fight even when nobody is hurt. + const show=alive(BARBARA)&&g.t>6*HZ&&b.mode!=='attack'; + if(show&&g.stats.charSkill.barbara===0&&skillReady(BARBARA))list.push([BARBARA,'K',{}]); + if(show&&g.stats.charBurst.barbara===0&&burstReady(BARBARA)&&bossFrac<.5)list.push([BARBARA,'L',{}]); + if(burstReady(BARBARA)&&(low>=1||hpFrac<.62))list.push([BARBARA,'L',{}]); + if(skillReady(BARBARA)&&(hpFrac<.8||low))list.push([BARBARA,'K',{}]); + if(skillReady(AMBER)&&b.mode!=='attack'&&dist(p,b)<11)list.push([AMBER,'bunny',{bunny:Math.round((clamp(dist(p,b)*.5,2,8)-2)*20)}]); + if(burstReady(XIANGLING)&&!reserve&&b.mode==='attack'&&TUNING.moves[b.move].active-b.moveTick<=40)list.push([XIANGLING,null,{}]); + if(skillReady(KAEYA))list.push([KAEYA,null,{}]); + list.push([AMBER,'charge',{charge:true,keep:true}]); + choose(list); + return out; + } + function rgIntent(g){ + const H=helpers(g),{p,party,ai,alive,skillReady,burstReady,low,hpFrac}=H,b=g.boss,d=dist(p,b); + const out={want:ai,action:null,anchor:0,desired:8.5,weight:1,holdJ:false,charge:false,bunny:0,tap:false,mode:'kite'}; + const choose=chooser(out,H); + const facing=Math.abs(wrap(angle(b,p)-(b.yaw+b.upper))),canDisable=b.weak.rune<=0&&b.mode!=='paralyzed'&&b.mode!=='dead'&&b.y<.5; + const heal=[];if(burstReady(BARBARA)&&(low>=1||hpFrac<.55))heal.push([BARBARA,'L',{}]);if(skillReady(BARBARA)&&(hpFrac<.75||low))heal.push([BARBARA,'K',{}]); + if(b.mode==='paralyzed'||b.frozen>0){ + out.mode='burst';out.desired=2.6;out.weight=1.6;const list=[...heal]; + if(burstReady(XIANGLING))list.push([XIANGLING,'L',{desired:3.2}]); + if(skillReady(KAEYA))list.push([KAEYA,'K',{desired:2.6}]); + if(burstReady(KAEYA))list.push([KAEYA,'L',{desired:2.3}]); + if(skillReady(XIANGLING))list.push([XIANGLING,'K',{desired:2.4}]); + if(burstReady(AMBER))list.push([AMBER,'L',{desired:5}]); + if(skillReady(AMBER))list.push([AMBER,'bunny',{desired:3,bunny:0}]); + const cur=party[ai].id;if(cur==='amber')list.push([AMBER,'charge',{charge:true,desired:4.5}]); + list.push([KAEYA,'J',{holdJ:true,desired:2.4}],[AMBER,'charge',{charge:true,desired:4.5}],[XIANGLING,'J',{holdJ:true,desired:2.5}]); + choose(list);if(g.auras.some(a=>a.kind==='pyronado')&&out.action!=='charge')out.desired=3.2;return out; + } + const backOpen=b.mode==='attack'&&b.move==='volley'&&b.upper>2.6,eyeOpen=facing<.75&&b.mode!=='attack'||facing<.75&&b.mode==='attack'&&b.move!=='volley'; + if(canDisable&&(eyeOpen||backOpen||b.weak.window>0)&&alive(AMBER)&&(ai===AMBER||H.canSwap)&&d>4.5){ + out.want=AMBER;out.action=ai===AMBER?'aimshot':null;out.aim=backOpen?'back':'eye';out.mode='disable';out.desired=Math.max(7.5,Math.min(d,10));out.weight=.8;return out;} + if(choose(heal))return out; + out.desired=b.mode==='attack'&&b.move==='spin'?8.5:7.8; + const list=[]; + if(skillReady(XIANGLING)&&d<10&&d>4.5)list.push([XIANGLING,'K',{}]); + if(skillReady(AMBER)&&d<12)list.push([AMBER,'bunny',{bunny:Math.round((clamp(d*.6,2,8)-2)*20)}]); + list.push([AMBER,'charge',{charge:true,keep:true}]); + choose(list);return out; + } + function ocIntent(g){ + const H=helpers(g),{p,party,ai,alive,skillReady,burstReady,low,hpFrac}=H,b=g.boss; + const out={want:ai,action:null,anchor:-1,desired:0,weight:.6,holdJ:false,charge:false,bunny:0,mode:'idle',home:true}; + const choose=chooser(out,H),live=g.mimics.filter(m=>m.hp>0&&m.mode!=='form'); + const heal=[];if(burstReady(BARBARA)&&(low>=1||hpFrac<.55))heal.push([BARBARA,'L',{}]);if(skillReady(BARBARA)&&(hpFrac<.75||low))heal.push([BARBARA,'K',{}]); + if(!live.length){out.mode='wait';if(!choose(heal))choose([[AMBER,'charge',{charge:true,keep:true}]]);return out;} + // Prefer the nearest target, flyers only while they are low enough to hit; finish wounded targets first. + const score=m=>dist(p,m)+(m.y>2.5?6:0)-(1-m.hp/m.maxHp)*4; + const T=live.slice().sort((a,c)=>score(a)-score(c))[0],weak=OC.types[T.type].weak,d=dist(p,T); + out.anchor=T.id;out.home=false;out.mode='fight';out.weight=1.4; + const near=live.filter(m=>dist(p,m)<4.2&&m.y<2.5).length,list=[...heal]; + // Flyers, targets hovering over sunken tiles and cranes (which back away) are shot from the platform with Amber. + if(T.y>2.5||g.terrain(T.x,T.z)==='water'||T.type==='crane'&&!(skillReady(KAEYA)&&d<5)){list.push([AMBER,'tap',{tap:true,desired:6.5}]);choose(list);return out;} + if(weak==='pyro'){if(burstReady(XIANGLING)&&near>=1)list.push([XIANGLING,'L',{desired:2.8}]);if(skillReady(XIANGLING)&&d<6)list.push([XIANGLING,'K',{desired:2.6}]);} + if(weak==='cryo'||T.type==='crane'){if(skillReady(KAEYA)&&d<5.5)list.push([KAEYA,'K',{desired:2.4}]);if(burstReady(KAEYA)&&near>=1)list.push([KAEYA,'L',{desired:2}]);} + if(burstReady(XIANGLING)&&near>=2)list.push([XIANGLING,'L',{desired:2.8}]); + if(skillReady(KAEYA)&&d<5)list.push([KAEYA,'K',{desired:2.4}]); + if(burstReady(AMBER)&&near>=2)list.push([AMBER,'L',{desired:5}]); + if(weak==='pyro')list.push([AMBER,'charge',{charge:true,desired:6}]); + const cur=party[ai].id;if(cur==='kaeya'||cur==='xiangling')list.push([ai,'J',{holdJ:true,desired:2.2}]); + list.push([KAEYA,'J',{holdJ:true,desired:2.2}],[XIANGLING,'J',{holdJ:true,desired:2.4}],[AMBER,'charge',{charge:true,desired:6}]); + choose(list);if(g.auras.some(a=>a.kind==='pyronado')&&out.action!=='charge')out.desired=3.2; + return out; + } + function scriptHolds(g,intent){ + const p=g.player,holds=[[],[],[],[],[],[]],ai=p.active,party=g.party; + // Re-lock the target after a free-aim shot (R is a press edge, so it is only held in the first hold set). + if(!p.lockon&&intent.action!=='aimshot')holds[0].push('R'); + let slot=0,who=ai; + if(intent.want!==ai){ + // E = next living character, Q = previous; choose whichever reaches the wanted slot in fewer swaps. + const nextAlive=(from,dir)=>{for(let n=1;n<=4;n++){const at=(from+dir*n+8)%4;if(party[at].hp>0)return at;}return from;}; + const stepsTo=dir=>{let at=ai;for(let n=1;n<=3;n++){at=nextAlive(at,dir);if(at===intent.want)return n;}return 9;}; + const dir=stepsTo(1)<=stepsTo(-1)?1:-1;holds[0].push(dir>0?'E':'Q');slot=2;who=nextAlive(ai,dir); + if(who!==intent.want)return {holds,who,slot}; + } + const q=party[who],charge=intent.charge&&q.id==='amber',chargeTicks=who===ai?p.chargeTicks:0; + if(intent.action==='K'||intent.action==='L')holds[slot].push(intent.action); + if(intent.action==='bunny'&&q.id==='amber'){ + const need=Math.max(2,intent.bunny-(who===ai?p.skillHold:0)),n=Math.min(6-slot,Math.ceil(need/2)); + for(let i=slot;i0){}else{const at=Math.max(slot,Math.ceil((who===ai?p.normalCD:0)/2));if(at<5)holds[at].push('LMB');}} + if(charge&&!(intent.action==='bunny')){ + const need=TUNING.bowChargeTicks-chargeTicks,m=Math.ceil(Math.max(0,need)/2); + for(let i=slot;i<6;i++)if(intent.keep||i2*(6-slot))holds[i].push('LMB'); + } + if(intent.holdJ)for(let i=slot;i<6;i++)if(!holds[i].includes('K')&&!holds[i].includes('L'))holds[i].push('J'); + return {holds,who,slot}; + } + function ehPenalty(g,c){ + const b=g.boss,p=c.player;let pen=0; + if(b.mode==='tell'||b.mode==='attack'&&b.moveTick<30){ + if(['fist','drill','rps'].includes(b.move)){const f=forward(b.yaw),dx=p.x-b.x,dz=p.z-b.z,along=dx*f.x+dz*f.z,lat=Math.abs(dx*f.z-dz*f.x); + if(along>-1.5&&along<(b.move==='drill'?14:10)&&lat<3.2)pen+=420*(3.2-lat)/3.2;} + if(b.move==='clap'){const d=dist(p,b),a=Math.abs(wrap(angle(b,p)-b.yaw));if(d<5.2&&a<1.3)pen+=380;} + } + if(b.move==='lasers'&&(b.mode==='tell'&&b.timer<14||b.mode==='attack'&&b.moveTick<10)){const d=dist(p,b);if(d>2.2&&d<4.2)pen+=500;} + if(b.move==='lasers'&&b.mode==='attack'&&b.moveTick>=226&&dist(p,b)<4.9)pen+=350; + return pen; + } + // Free-aim weak-point shot (Ruin Guard): unlock, turn the camera with the mouse so the uncharged aimed shot released at + // tick f flies from the shoulder to where the weak point will be on impact, and verify the hit on a clone before using it. + function aimedShot(g,mem,intent){ + const p=g.player;if(!p.grounded||p.swimming||p.stun||p.actionLock||p.chargeTicks)return null; + const at=Math.ceil(p.normalCD/2);if(at>4)return null; + const f=2*(at+1),holds=[[],[],[],[],[],[]];if(p.lockon)holds[0].push('R');holds[at].push('LMB'); + const run=(ticks,mouse)=>{const c=cloneGame(g);let held=mem.held;const hp=partyHP(c),w0=c.stats.weakHits; + for(let t=0;tv/12):[0,0,0]);return {c,hurt:hp-partyHP(c),hit:c.stats.weakHits>w0};}; + let yaw=p.cameraYaw,pitch=p.aimPitch,flight=12,T=null; + for(let k=0;k<3;k++){const c=run(f+1+flight,[0,0,0]).c;if(c.outcome||c.boss.mode==='paralyzed')return null;T=c.weakPoints().find(v=>v.id===intent.aim); + let o=null;for(let j=0;j<3;j++){o=aimOrigin({x:p.x,y:p.y,z:p.z,cameraYaw:yaw});yaw=Math.atan2(T.x-o.x,T.z-o.z);} + const h=Math.hypot(T.x-o.x,T.z-o.z);pitch=Math.atan2(T.y-o.y,h);flight=Math.ceil(Math.hypot(h,T.y-o.y)/(35/HZ));} + const frac=(f+1)/12,dx=Math.round(-wrap(yaw-p.cameraYaw)/(.0025*frac)),dy=Math.round((p.aimPitch-clamp(pitch,-.5,1.1))/(.002*frac)); + if(Math.abs(dx)>1000||Math.abs(dy)>1000)return null; + const check=run(f+flight+10,[dx,dy,0]);if(!check.hit||check.hurt>0)return null; + return {holds,mouse:[dx,dy,0]}; + } + function rgPenalty(g,c){ + // Melee range of an active guard is where stomp/clap/combo land; spinning reach is wider. + const b=c.boss,p=c.player;if(b.mode==='paralyzed'||b.mode==='dead'||b.frozen>0)return 0; + const d=dist(p,b);let pen=0;if(d<4.6)pen+=260*(4.6-d);if(b.mode==='attack'&&b.move==='spin'&&d<5.5)pen+=200*(5.5-d); + return pen; + } + function ocPenalty(g,c){ + const p=c.player,b=c.boss;let pen=0;if(c.terrain(p.x,p.z)==='water'){let best=99;for(let i=0;i<9;i++)if(!b.tiles[i]){const t=c.tileCenter(i);best=Math.min(best,Math.max(Math.abs(p.x-t.x),Math.abs(p.z-t.z))-OC.tile/2);}pen+=900+300*Math.max(0,best);} + for(const i of b.warn||[]){const t=c.tileCenter(i);if(Math.abs(p.x-t.x)0&&m.mode!=='form'&&m.y<2.5&&(m.mode==='tell'||m.mode==='attack')){const d=dist(p,m);if(d<2.2)pen+=120*(2.2-d);} + return pen; + } + const PLANS={ + 'genshin/electro_hypostasis':{intent:ehIntent,penalty:ehPenalty,arena:15.5, + gain:(g,c,intent,base)=>{const b0=base.boss,ward0=base.ward,pil0=base.pillar,prism0=base.prisms;let s=(intent.mode==='hold'?-.5:1)*(b0-c.boss.hp)+2600*(ward0-wardGauge(c))+4000*(prism0-c.boss.prisms.filter(v=>v.alive).length); + const trapped=g.hazards.some(h=>h.kind==='pillar'&&h.age>=h.delay)&&g.boss.cageCenter&&dist(g.player,g.boss.cageCenter)<5.8;if(trapped)s+=500*(pil0-pillarGauge(c));return s;}, + base:c=>({boss:c.boss.hp,ward:wardGauge(c),pillar:pillarGauge(c),prisms:c.boss.prisms.filter(v=>v.alive).length})}, + 'genshin/ruin_guard':{intent:rgIntent,penalty:rgPenalty,arena:15.5, + gain:(g,c,intent,base)=>(base.boss-c.boss.hp)+(c.boss.mode==='paralyzed'&&base.mode!=='paralyzed'?6000:0)+(c.boss.weak.window>0&&!base.window?1500:0), + base:c=>({boss:c.boss.hp,mode:c.boss.mode,window:c.boss.weak.window>0})}, + 'genshin/oceanid':{intent:ocIntent,penalty:ocPenalty,arena:99, + gain:(g,c,intent,base)=>base.prog-c.health()[2],base:c=>({prog:c.health()[2]})} + }; + function scoreCandidate(g,mem,intent,holds,moveKeys,tag,plan){ + const c=cloneGame(g);let held=mem.held; + const hp0=partyHP(c),base=plan.base(c); + for(let t=0;t<12&&!c.outcome;t++)held=stepClone(c,held,holds[Math.ceil((t+1)/2)-1]); + const mid={x:c.player.x,z:c.player.z},midHP=partyHP(c); + const ext=[...moveKeys];if(intent.holdJ)ext.push('J');if(c.player.chargeTicks>0&&holds[5].includes('LMB'))ext.push('LMB');if(c.player.skillHold>0&&holds[5].includes('K'))ext.push('K'); + for(let t=0;t<18&&!c.outcome;t++)held=stepClone(c,held,ext.slice(0,4)); + let s=0; + if(c.outcome==='win')s+=1e7;else if(c.outcome==='loss')s-=1e7; + s-=4*(hp0-midHP)+2.5*(midHP-partyHP(c)); + s+=plan.gain(g,c,intent,base); + if(intent.anchor!==-1&&intent.anchor!==undefined){const target=c.entity(intent.anchor)||g.entity(intent.anchor);if(target)s-=120*intent.weight*Math.abs(dist(mid,target)-intent.desired);} + else if(intent.home)s-=120*intent.weight*Math.hypot(mid.x,mid.z); + s-=plan.penalty(g,c); + const r=Math.hypot(mid.x,mid.z);if(r>plan.arena)s-=80*(r-plan.arena); + for(const h of c.hazards)for(const f of [0,8,16])if(c.hazardContains(h,c.player,f)){s-=260;break;} + if(tag==='dash')s-=45;if(tag==='jump')s-=20;if(tag==='bare')s-=30; + return s; + } + M.scripted=function(g){ + // Memory = keys held at the end of the previous packet (needed to predict press edges in the lookahead). + // Repeated calls at the same tick reuse the same start state, so the output is a pure function of (state, history). + let mem=SCRIPT_MEMORY.get(g);if(!mem||g.t===0&&mem.callT!==0){mem={callT:-1,startHeld:[],endHeld:[]};SCRIPT_MEMORY.set(g,mem);} + if(g.t!==mem.callT){mem.startHeld=g.t===mem.callT+HZ/5?mem.endHeld:[];mem.callT=g.t;} + mem.held=mem.startHeld; + const plan=PLANS[g.id],intent=plan.intent(g); + if(intent.action==='aimshot'){const shot=aimedShot(g,mem,intent);if(shot){mem.endHeld=[...shot.holds[5]].sort();return shot;}intent.action=null;} + const act=scriptHolds(g,intent); + const build=(moveKeys,actionHolds,extra)=>actionHolds.map((h,i)=>{const keys=[...h];for(const k of moveKeys)if(keys.length<4&&!keys.includes(k))keys.push(k); + if(extra&&i===0&&keys.length<4&&!keys.includes(extra))keys.push(extra);return keys.slice(0,4);}); + let best=null,bestScore=-Infinity; + // Scores are rounded so that ULP-level differences cannot reorder candidates; ties keep the first candidate. + const consider=(moveKeys,actionHolds,extra,tag)=>{const holds=build(moveKeys,actionHolds,extra),score=Math.round(scoreCandidate(g,mem,intent,holds,moveKeys,tag,plan)*1000)/1000; + if(score>bestScore){bestScore=score;best=holds;}return score;}; + MOVE_SETS.forEach(m=>consider(m,act.holds,null,'plan')); + const danger=g.hazards.some(h=>h.kind!=='pillar')||g.boss.mode==='tell'||g.boss.mode==='attack'||g.id!=='genshin/electro_hypostasis'; + if(danger&&bestScore<-500){ + // genshin-bosses@7 starts unlocked: the opening packet locks on whichever candidate wins (plan candidates already carry R from + // scriptHolds), so every lookahead plays the locked fight @6 started in. Later packets are unchanged. + const bare=[!g.player.lockon&&g.t===0?['R']:[],[],[],[],[],[]]; + for(const m of MOVE_SETS)consider(m,bare,null,'bare'); + const p=g.player;if(p.dashUses<2&&p.stamina>20&&!p.actionLock&&!p.swimming)for(const m of MOVE_SETS.slice(1))consider(m,bare,'Shift','dash'); + if(p.grounded&&!p.swimming&&g.hazards.some(h=>h.kind==='ring'))for(const m of [[],['A'],['D']])consider(m,bare,'Space','jump'); + } + mem.endHeld=[...best[5]].sort(); + return {holds:best.map(h=>[...h]),mouse:[0,0,0]}; + }; + // Backward-compatible name used by older shared validators. + M.oracle=M.scripted; + // Extension point for the bosses added on 2026-11-03 (boss_*.js). Exporting references changes no rule: the three accepted + // encounters above keep their exact code paths; new files only add classes, cases and controller plans of their own. + M.internals={Fight,TUNING,TEAM,HZ,PI,TAU,clamp,dist,angle,forward,wrap,resMult,byTier,span,shuffle,CLASSES,PLANS, + helpers,chooser,scriptHolds,cloneGame,stepClone,partyHP,MOVE_SETS,KAEYA,AMBER,XIANGLING,BARBARA}; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/genshin_remake/index.html b/environments/games/web/games/genshin_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..15f55077e7e141f4de8ce2ef93516ce9b7d53043 --- /dev/null +++ b/environments/games/web/games/genshin_remake/index.html @@ -0,0 +1,7 @@ +Genshin Impact · Boss Challenge
    +
    Boss Trials · 60 Hz · Original procedural art

    Genshin Impact · Boss Challenge

    A four-character elemental party faces six bosses: a floating cube with an exposed core and revival crystals; a cannon-backed automaton with paralyzable weak points; a water summoner whose mimics must be defeated; a masked swordsman with guards and clones; an icy wolf with pillars and pups; and an ice-and-fire sorceress with temperature and cocoon mechanics.

    Back to Game Lobby ↗
    +
    Are You Ready?Click Start Challenge
    +

    Verify Script reads internal state to test the mechanics. Its win rate does not represent human or vision-model performance. Boss health, attack power, and difficulty tiers are calibrated for BossBench, not taken from the original game.

    +
    +
    All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
    + diff --git a/environments/games/web/games/genshin_remake/manifest.json b/environments/games/web/games/genshin_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..047abd5e95631728e2571890090560ee6123819c --- /dev/null +++ b/environments/games/web/games/genshin_remake/manifest.json @@ -0,0 +1,42 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "genshin_remake", + "module": "GenshinGame", + "title": "Genshin: Boss Challenges", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-boss3d", + "rules": "genshin-bosses@8", + "cases": [ + "genshin/electro_hypostasis", + "genshin/ruin_guard", + "genshin/oceanid", + "genshin/maguu_kenki", + "genshin/andrius", + "genshin/signora" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "genshin_remake/renderer3d.js", + "genshin_remake/game.js", + "genshin_remake/boss_common.js", + "genshin_remake/boss_kenki.js", + "genshin_remake/boss_andrius.js", + "genshin_remake/boss_signora.js", + "genshin_remake/art_expansion.js", + "genshin_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "genshin_remake/game.js", + "genshin_remake/boss_common.js", + "genshin_remake/boss_kenki.js", + "genshin_remake/boss_andrius.js", + "genshin_remake/boss_signora.js" + ], + "play_page": "web/games/genshin_remake/index.html", + "scripted_controller": "GenshinGame.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,dz]} (falls back to .oracle)" +} diff --git a/environments/games/web/games/genshin_remake/renderer3d.js b/environments/games/web/games/genshin_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..1a11983cbf6c9102a6ba165a28361c6522bd949e --- /dev/null +++ b/environments/games/web/games/genshin_remake/renderer3d.js @@ -0,0 +1,753 @@ +/* Original stylised 3D art for BossBench · Genshin Impact (procedural geometry only; Three.js r160 pinned locally, MIT). + * Rules own every action, pose clock and hazard. Rendering is a pure function of the game state: it never writes + * game state and never consumes game RNG, so rendering the same state twice yields the same image. */ +(function(root){ + 'use strict'; + const T=root.THREE,B=root.Boss3D={}; + if(!T)throw Error('Offline Three.js renderer library is missing'); + const byCanvas=new WeakMap(),PI=Math.PI,TAU=PI*2; + // Arena plugins registered by the expansion bosses' art file (art_expansion.js): {match(caseId), build(scene, th), draw(scene, g, th), + // camera:{d,h,look,lim}, light:{hemi,sun}}. The three original arenas stay built in below. + const PLUGINS={}; + const clamp=(x,a,b)=>Math.max(a,Math.min(b,x)),items=a=>Array.isArray(a)?a:[],lerp=(a,b,t)=>a+(b-a)*t,ease=t=>{t=clamp(t,0,1);return t*t*(3-2*t);}; + const EL={pyro:0xff7a3d,cryo:0x9fe6ff,hydro:0x4fb4ff,electro:0xc28cff,anemo:0x6fe0c0,geo:0xf2c95c,dendro:0x9be36a,physical:0xf6ecd6,neutral:0xfff3c8,heal:0x8cf0a0}; + const hash=n=>{let x=Math.imul((n|0)^0x9e3779b9,0x85ebca6b);x^=x>>>13;x=Math.imul(x,0xc2b2ae35);x^=x>>>16;return (x>>>0)/4294967296;}; + const v3=(x,y,z)=>new T.Vector3(x,y,z); + // ------------------------------------------------------------------------------------------------ canvas textures + function canvas(w,h,draw){const c=document.createElement('canvas');c.width=w;c.height=h;draw(c.getContext('2d'),w,h);const t=new T.CanvasTexture(c);t.colorSpace=T.SRGBColorSpace;return t;} + function noiseFill(q,w,h,base,amp,seed){const im=q.createImageData(w,h);for(let y=0;y>3)*31+(y>>3)*977+seed*3)-.5)*amp*.8,i=(y*w+x)*4; + im.data[i]=base[0]+n;im.data[i+1]=base[1]+n;im.data[i+2]=base[2]+n*.8;im.data[i+3]=255;}q.putImageData(im,0,0);} + const TEX={ + grass:()=>{const t=canvas(256,256,(q,w,h)=>{noiseFill(q,w,h,[96,146,78],26,3);for(let i=0;i<900;i++){const x=hash(i*3)*w,y=hash(i*3+1)*h,l=3+hash(i*3+2)*6;q.strokeStyle=hash(i)>.5?'rgba(150,196,104,.55)':'rgba(64,112,58,.5)';q.lineWidth=1;q.beginPath();q.moveTo(x,y);q.lineTo(x+(hash(i+9)-.5)*3,y-l);q.stroke();}});t.wrapS=t.wrapT=T.RepeatWrapping;return t;}, + dirt:()=>{const t=canvas(128,128,(q,w,h)=>noiseFill(q,w,h,[120,104,82],30,11));t.wrapS=t.wrapT=T.RepeatWrapping;return t;}, + arena:theme=>canvas(1024,1024,(q,w,h)=>{ + const cx=w/2,stone=theme==='ruins'?[150,146,128]:[214,206,184];noiseFill(q,w,h,stone,22,theme==='ruins'?5:7); + q.lineCap='round'; + if(theme==='ruins'){ // weathered flagstones with moss, cracks and a faded ring + q.strokeStyle='rgba(70,66,56,.55)';q.lineWidth=3;for(let r=60;r20;r-=cx*.12){q.strokeStyle='rgba(120,112,96,.6)';q.lineWidth=4;q.beginPath();q.arc(cx,cx,r,0,TAU);q.stroke();} + q.strokeStyle='rgba(206,164,86,.85)';q.lineWidth=7;for(const r of [cx*.2,cx*.47,cx*.86]){q.beginPath();q.arc(cx,cx,r,0,TAU);q.stroke();} + for(let i=0;i<16;i++){const a=i*TAU/16;q.strokeStyle='rgba(120,112,96,.55)';q.lineWidth=3;q.beginPath();q.moveTo(cx+Math.cos(a)*cx*.2,cx+Math.sin(a)*cx*.2);q.lineTo(cx+Math.cos(a)*cx*.98,cx+Math.sin(a)*cx*.98);q.stroke();} + q.fillStyle='rgba(206,164,86,.8)';for(let i=0;i<8;i++){const a=i*TAU/8+.2,x=cx+Math.cos(a)*cx*.66,y=cx+Math.sin(a)*cx*.66;q.save();q.translate(x,y);q.rotate(a);q.beginPath();q.moveTo(-18,0);q.quadraticCurveTo(0,-26,18,0);q.quadraticCurveTo(0,-8,-18,0);q.fill();q.restore();} + const gr=q.createRadialGradient(cx,cx,0,cx,cx,cx*.18);gr.addColorStop(0,'rgba(196,160,255,.5)');gr.addColorStop(1,'rgba(196,160,255,0)');q.fillStyle=gr;q.fillRect(0,0,w,h); + } + const edge=q.createRadialGradient(cx,cx,cx*.9,cx,cx,cx);edge.addColorStop(0,'rgba(0,0,0,0)');edge.addColorStop(1,'rgba(40,36,30,.45)');q.fillStyle=edge;q.fillRect(0,0,w,h);}), + slab:()=>{const t=canvas(256,256,(q,w,h)=>{noiseFill(q,w,h,[150,150,140],24,21);q.strokeStyle='rgba(70,72,70,.6)';q.lineWidth=4;q.strokeRect(10,10,w-20,h-20);q.strokeStyle='rgba(205,190,140,.55)';q.lineWidth=3;q.strokeRect(28,28,w-56,h-56); + q.strokeStyle='rgba(90,90,84,.45)';q.lineWidth=2;q.beginPath();q.moveTo(w/2,28);q.lineTo(w/2,h-28);q.moveTo(28,h/2);q.lineTo(w-28,h/2);q.stroke();});return t;}, + rune:()=>canvas(128,128,(q,w,h)=>{q.fillStyle='#231b3d';q.fillRect(0,0,w,h);q.strokeStyle='#5b4a8a';q.lineWidth=5;q.strokeRect(8,8,w-16,h-16); + q.strokeStyle='#d6b8ff';q.lineWidth=6;q.beginPath();q.moveTo(64,22);q.lineTo(94,52);q.lineTo(76,80);q.lineTo(64,68);q.lineTo(50,94);q.lineTo(32,62);q.closePath();q.stroke(); + q.strokeStyle='#f6eaff';q.lineWidth=2.5;q.beginPath();q.moveTo(40,62);q.lineTo(86,62);q.moveTo(64,30);q.lineTo(64,106);q.stroke();}), + runeGlow:()=>canvas(128,128,(q,w,h)=>{q.fillStyle='#000';q.fillRect(0,0,w,h);q.strokeStyle='#5a3ca0';q.lineWidth=5;q.strokeRect(8,8,w-16,h-16); + q.strokeStyle='#c99cff';q.lineWidth=7;q.beginPath();q.moveTo(64,22);q.lineTo(94,52);q.lineTo(76,80);q.lineTo(64,68);q.lineTo(50,94);q.lineTo(32,62);q.closePath();q.stroke(); + q.strokeStyle='#ffffff';q.lineWidth=3;q.beginPath();q.moveTo(40,62);q.lineTo(86,62);q.moveTo(64,30);q.lineTo(64,106);q.stroke();}), + dot:()=>canvas(64,64,(q,w,h)=>{const g=q.createRadialGradient(32,32,0,32,32,32);g.addColorStop(0,'rgba(255,255,255,1)');g.addColorStop(.25,'rgba(255,255,255,.75)');g.addColorStop(.6,'rgba(255,255,255,.18)');g.addColorStop(1,'rgba(255,255,255,0)');q.fillStyle=g;q.fillRect(0,0,w,h);}), + cloud:()=>canvas(256,128,(q,w,h)=>{for(let i=0;i<14;i++){const x=40+hash(i)*176,y=56+(hash(i+20)-.5)*36,r=22+hash(i+40)*30,g=q.createRadialGradient(x,y,0,x,y,r);g.addColorStop(0,'rgba(255,255,255,.9)');g.addColorStop(1,'rgba(255,255,255,0)');q.fillStyle=g;q.fillRect(0,0,w,h);}}), + ripple:()=>{const t=canvas(256,256,(q,w,h)=>{const im=q.createImageData(w,h);for(let y=0;ycanvas(128,128,(q,w,h)=>{q.translate(64,64);for(let k=0;k<4;k++){q.rotate(TAU/4);q.strokeStyle='rgba(220,245,255,.85)';q.lineWidth=5;q.beginPath();for(let i=0;i<40;i++){const a=i*.16,r=6+i*1.4;q.lineTo(Math.cos(a)*r,Math.sin(a)*r);}q.stroke();}}), + reticle:()=>canvas(128,128,(q,w,h)=>{q.strokeStyle='rgba(255,70,50,.95)';q.lineWidth=7;q.beginPath();q.arc(64,64,44,0,TAU);q.stroke();q.lineWidth=5;q.beginPath();q.arc(64,64,18,0,TAU);q.stroke(); + q.beginPath();for(const [a,b,c,d] of [[64,2,64,30],[64,98,64,126],[2,64,30,64],[98,64,126,64]]){q.moveTo(a,b);q.lineTo(c,d);}q.stroke();}), + sky:theme=>canvas(4,256,(q,w,h)=>{const C=Array.isArray(theme)?theme:{cape:['#3f86c8','#8fc4e6','#e9f0e2'],ruins:['#4d88b8','#a8cbdc','#f2e6c8'],lake:['#55708a','#93a9b6','#c9d3d4']}[theme],g=q.createLinearGradient(0,0,0,h); + g.addColorStop(0,C[0]);g.addColorStop(.48,C[1]);g.addColorStop(.62,C[2]);g.addColorStop(1,C[2]);q.fillStyle=g;q.fillRect(0,0,w,h);}), + face:id=>canvas(128,128,(q,w,h)=>{ + // Unlit anime face decal: large eyes with gradient irises and highlights, thin brows, small mouth. + const F={kaeya:{iris:'#4f9fe6',patch:true,brow:'#262a44'},amber:{iris:'#c8692a',brow:'#5a2e1a',blush:true},xiangling:{iris:'#dca23a',brow:'#22253a',blush:true},barbara:{iris:'#4a8be0',brow:'#c9a85a',blush:true}}[id]; + const eye=(x,flip)=>{q.save();q.translate(x,58);q.fillStyle='#fbfaf6';q.beginPath();q.ellipse(0,0,17,20,0,0,TAU);q.fill(); + const g=q.createLinearGradient(0,-18,0,18);g.addColorStop(0,'#1c1830');g.addColorStop(.42,F.iris);g.addColorStop(1,'#fff8e8');q.fillStyle=g;q.beginPath();q.ellipse(flip*1.5,2,13,17,0,0,TAU);q.fill(); + q.fillStyle='#120e1c';q.beginPath();q.ellipse(flip*1.5,3,6,9,0,0,TAU);q.fill();q.fillStyle='#ffffff';q.beginPath();q.arc(-4+flip*1.5,-6,4.2,0,TAU);q.fill();q.beginPath();q.arc(4+flip*1.5,8,2.2,0,TAU);q.fill(); + q.strokeStyle='#17121f';q.lineWidth=5;q.beginPath();q.ellipse(0,1,18,21,0,PI*1.06,PI*1.94);q.stroke();q.lineWidth=3;q.beginPath();q.moveTo(flip*16,-10);q.lineTo(flip*23,-15);q.stroke(); + q.lineWidth=1.6;q.beginPath();q.ellipse(0,0,15,19,0,PI*.2,PI*.8);q.stroke();q.restore();}; + eye(36,-1);eye(92,1); + q.strokeStyle=F.brow;q.lineWidth=3.5;q.beginPath();q.moveTo(20,28);q.quadraticCurveTo(36,21,50,27);q.moveTo(78,27);q.quadraticCurveTo(92,21,108,28);q.stroke(); + if(F.patch){q.fillStyle='#1d1d27';q.beginPath();q.ellipse(36,57,21,23,0,0,TAU);q.fill();q.strokeStyle='#1d1d27';q.lineWidth=4;q.beginPath();q.moveTo(16,46);q.lineTo(0,36);q.moveTo(56,46);q.lineTo(128,30);q.stroke();} + if(F.blush){q.fillStyle='rgba(255,130,130,.35)';q.beginPath();q.ellipse(22,86,11,5,0,0,TAU);q.ellipse(106,86,11,5,0,0,TAU);q.fill();} + q.strokeStyle='#8a4a44';q.lineWidth=3;q.beginPath();q.moveTo(57,102);q.quadraticCurveTo(64,107,71,102);q.stroke();}) + }; + // ------------------------------------------------------------------------------------------------ geometry builder + const _m=new T.Matrix4(),_q=new T.Quaternion(),_e=new T.Euler(),_s=new T.Vector3(),_p=new T.Vector3(),_nm=new T.Matrix3(),_v=new T.Vector3(); + // Merges primitives into one BufferGeometry with per-vertex colours (one draw call per rig bone or prop batch). + class Build{ + constructor(){this.p=[];this.n=[];this.c=[];} + add(geo,color,pos=[0,0,0],rot=[0,0,0],scale=[1,1,1]){ + const g=geo.index?geo.toNonIndexed():geo,P=g.attributes.position,Nr=g.attributes.normal,col=new T.Color(color); + _m.compose(_p.set(pos[0],pos[1],pos[2]),_q.setFromEuler(_e.set(rot[0],rot[1],rot[2])),_s.set(scale[0],scale[1],scale[2]));_nm.getNormalMatrix(_m); + for(let i=0;i1e-9)d.normalize().multiplyScalar(b);p.setXYZ(i,a+d.x,bb+d.y,cc+d.z);}geo.computeVertexNormals();return geo;} + const G={sphere:(w=10,h=7)=>new T.SphereGeometry(1,w,h),box:()=>new T.BoxGeometry(1,1,1),bevel:()=>beveled(2),cyl:(t=1,b=1,s=8)=>new T.CylinderGeometry(t,b,1,s),cone:(s=8)=>new T.ConeGeometry(1,1,s), + cap:(r,l,s=8)=>new T.CapsuleGeometry(r,l,2,s),lathe:(pts,s=10)=>new T.LatheGeometry(pts.map(([x,y])=>new T.Vector2(x,y)),s),torus:(r,t,rs=5,ts=14,arc=TAU)=>new T.TorusGeometry(r,t,rs,ts,arc), + ico:(d=0)=>new T.IcosahedronGeometry(1,d),oct:()=>new T.OctahedronGeometry(1,0),tet:()=>new T.TetrahedronGeometry(1,0)}; + // ------------------------------------------------------------------------------------------------ character design + // Original procedural interpretations of the four C0 characters (no game models, textures or rigs). + const HERO={ + kaeya:{h:1.04,skin:0xc8906d,hair:0x2a3157,top:0x27386a,trim:0xc9a45c,shirt:0xebe5d8,legs:0x232a3c,boot:0x3b2d28,glove:0x2a2a33,weapon:'sword'}, + amber:{h:.97,skin:0xf4cdab,hair:0x713c22,top:0xc8392d,trim:0xf2ece2,shirt:0x6b3a22,legs:0x2a2226,boot:0x6b3a22,glove:0x6b3a22,weapon:'bow'}, + xiangling:{h:.93,skin:0xf3c9a5,hair:0x23283f,top:0x2d2c38,trim:0xc63b2c,shirt:0xd6a64e,legs:0xf3c9a5,boot:0x7a2f24,glove:0xf3c9a5,weapon:'polearm'}, + barbara:{h:.95,skin:0xf9dbc5,hair:0xf2d78a,top:0xf7f4ee,trim:0x3d6fc4,shirt:0xe4c46a,legs:0xf4f1ea,boot:0x2f4f8f,glove:0xf7f4ee,weapon:'catalyst'} + }; + function heroParts(id){ + const P=HERO[id],L={},add=(bone,geo,color,pos,rot,scale)=>(L[bone]||(L[bone]=new Build())).add(geo,color,pos,rot,scale); + const bare=id==='xiangling'||id==='amber'; + // Body shared by everyone: shaped lathe torso, rounded limbs, big anime head (the head bone is scaled up in the rig). + add('chest',G.lathe([[.112,0],[.124,.06],[.138,.16],[.15,.26],[.147,.33],[.118,.39],[.055,.435]],12),P.top,[0,0,0],[0,0,0],[1,1,.76]); + add('chest',G.cyl(1,1,8),P.skin,[0,.45,0],[0,0,0],[.043,.07,.043]); + add('hips',G.sphere(10,7),id==='barbara'?P.top:id==='xiangling'?P.top:P.shirt,[0,-.01,0],[0,0,0],[.152,.115,.11]); + add('head',G.sphere(14,10),P.skin,[0,.13,0],[0,0,0],[.156,.166,.152]); + for(const s of [-1,1])add('head',G.sphere(6,5),P.skin,[s*.152,.115,0],[0,0,0],[.02,.034,.02]); + // Hair: cap, back volume, bangs hanging over the forehead and side locks framing the face. + add('head',G.sphere(12,9),P.hair,[0,.17,-.02],[0,0,0],[.172,.166,.172]); + add('head',G.sphere(10,8),P.hair,[0,.11,-.07],[0,0,0],[.168,.17,.12]); + for(let i=0;i<7;i++){const x=(i-3)*.043,len=.1+(i%2)*.025+(i===3?.015:0);add('head',G.cone(5),P.hair,[x,.255-len/2+.03,.128-Math.abs(x)*.42],[PI-.32-Math.abs(x)*.3,0,x*1.6],[.036,len,.026]);} + for(const s of [-1,1])add('head',G.cone(5),P.hair,[s*.142,.08,.055],[PI+.08,0,-s*.12],[.04,.2,.03]); + for(const side of ['L','R']){ + add('arm'+side,G.sphere(8,6),P.top,[0,-.005,0],[0,0,0],[.062,.06,.06]); + add('arm'+side,G.cap(.046,.16,8),P.top,[0,-.13,0]); + add('fore'+side,G.cap(.041,.14,8),bare?P.skin:P.glove,[0,-.105,0]); + add('fore'+side,G.cyl(1,.9,8),bare?P.trim:P.glove,[0,-.02,0],[0,0,0],[.05,.05,.05]); + add('fore'+side,G.sphere(8,6),bare||id==='barbara'?P.skin:P.glove,[0,-.235,.008],[0,0,0],[.044,.05,.04]); + add('leg'+side,G.cap(.067,.24,8),P.legs,[0,-.185,0]); + add('shin'+side,G.cap(.054,.25,8),P.boot,[0,-.19,0]); + add('shin'+side,G.sphere(8,6),P.boot,[0,-.375,.045],[0,0,0],[.06,.05,.12]);add('shin'+side,G.box(),0x2a2220,[0,-.405,.04],[0,0,0],[.11,.02,.22]); + } + if(id==='kaeya'){ + add('chest',G.box(),P.shirt,[0,.25,.108],[-.12,0,0],[.095,.21,.02]);add('chest',G.box(),P.trim,[0,.3,.115],[-.12,0,0],[.02,.12,.022]); + add('chest',G.cyl(1,1,10),P.trim,[0,.03,0],[0,0,0],[.14,.036,.107]); + add('chest',G.torus(.118,.05,6,16),0xf3f1ec,[0,.405,-.005],[PI/2,0,0],[1,.82,1]);add('chest',G.sphere(8,6),0xf3f1ec,[-.13,.41,.02],[0,0,0],[.085,.065,.075]); + add('cape',G.box(),0x2f4f92,[0,-.3,0],[.04,0,0],[.37,.62,.025]);add('cape',G.box(),0xf3f1ec,[0,-.01,0],[0,0,0],[.39,.075,.05]);add('cape',G.box(),P.trim,[0,-.61,0],[0,0,0],[.37,.022,.03]); + add('hips',G.box(),P.top,[0,-.13,-.085],[.22,0,0],[.31,.27,.03]);for(const s of [-1,1])add('hips',G.box(),P.top,[s*.09,-.1,.08],[-.15,0,s*.08],[.11,.19,.02]); + add('head',G.cone(6),P.hair,[-.15,-.02,.035],[PI+.05,0,.1],[.042,.27,.034]);add('tail',G.cap(.036,.2,6),P.hair,[0,-.12,0]); + for(const s of ['L','R'])add('shin'+s,G.cyl(1,1,8),P.trim,[0,-.05,0],[0,0,0],[.058,.03,.058]); + } + if(id==='amber'){ + add('chest',G.box(),P.trim,[0,.37,.06],[-.3,0,0],[.21,.05,.06]);add('chest',G.box(),P.trim,[0,.22,.11],[-.06,0,0],[.07,.2,.02]); + add('chest',G.cyl(1,1,10),0x5a3420,[0,.02,0],[0,0,0],[.138,.04,.105]);add('chest',G.box(),0x5a3420,[.1,.0,.075],[0,0,0],[.06,.07,.04]); + add('hips',G.box(),P.top,[0,-.12,-.08],[.25,0,0],[.29,.23,.025]); + // Ribbon bow: two rounded loops and a knot on top of the head. + for(const s of [-1,1]){add('head',G.sphere(8,6),P.top,[s*.07,.355,-.03],[0,0,-s*.5],[.05,.135,.022]);add('head',G.sphere(6,5),0x8a2a22,[s*.072,.355,-.024],[0,0,-s*.5],[.028,.1,.012]);} + add('head',G.sphere(8,6),P.top,[0,.29,-.04],[0,0,0],[.045,.04,.035]); + add('head',G.box(),0x3a2a22,[0,.255,.105],[-.32,0,0],[.22,.035,.035]);for(const s of [-1,1])add('head',G.cyl(1,1,10),0xffb04a,[s*.052,.262,.125],[PI/2-.32,0,0],[.034,.02,.034]); + add('tail',G.cap(.075,.32,8),P.hair,[0,-.2,0],[0,0,0],[1,1,.55]); + } + if(id==='xiangling'){ + add('chest',G.box(),P.trim,[0,.2,.072],[0,0,-.7],[.05,.42,.04]);for(const y of [.1,.18,.26])add('chest',G.sphere(6,4),P.shirt,[.035,y,.112],[0,0,0],[.014,.014,.01]); + add('hips',G.box(),P.trim,[0,-.08,.092],[-.08,0,0],[.18,.21,.02]);add('hips',G.sphere(10,7),P.top,[0,-.035,0],[0,0,0],[.155,.1,.112]); + for(const s of [-1,1]){add('head',G.sphere(9,7),P.hair,[s*.11,.29,-.045],[0,0,0],[.07,.07,.07]);add('head',G.torus(.052,.015,4,10),P.shirt,[s*.11,.255,-.045],[PI/2,0,0]);} + } + if(id==='barbara'){ + add('chest',G.box(),P.trim,[0,.25,.104],[-.1,0,0],[.042,.22,.02]);add('chest',G.box(),P.trim,[0,.3,.106],[-.1,0,0],[.15,.036,.02]);add('chest',G.sphere(6,4),P.shirt,[0,.35,.104],[0,0,0],[.026,.026,.015]); + add('hips',G.lathe([[.12,.02],[.2,-.1],[.25,-.22],[.266,-.27],[.0,-.27]],14),P.top,[0,0,0]);add('hips',G.torus(.262,.017,4,18),P.trim,[0,-.26,0],[PI/2,0,0]); + add('head',G.cyl(.86,1,12),0xf8f6f0,[0,.305,-.015],[0,0,0],[.135,.075,.135]);add('head',G.box(),P.trim,[0,.315,.118],[0,0,0],[.15,.032,.02]); + for(const s of [-1,1])add('head',G.box(),P.trim,[s*.05,.19,-.16],[.25,0,s*.15],[.036,.23,.012]); + for(const k of ['tailL','tailR']){add(k,G.cap(.058,.24,8),P.hair,[0,-.15,0]);add(k,G.sphere(8,6),P.hair,[0,-.33,.012],[0,0,0],[.064,.064,.064]);} + } + // Weapons (original shapes): sword, bow, polearm, catalyst book. + if(P.weapon==='sword'){add('weapon',G.box(),0xdde6ee,[0,0,.47],[0,0,0],[.036,.012,.78]);add('weapon',G.box(),0x9ec8ef,[0,.007,.45],[0,0,0],[.012,.006,.62]); + add('weapon',G.box(),P.trim,[0,0,.06],[0,0,0],[.17,.03,.04]);add('weapon',G.cyl(1,1,6),0x262630,[0,0,-.02],[PI/2,0,0],[.018,.12,.018]);add('weapon',G.sphere(6,4),P.trim,[0,0,-.09],[0,0,0],[.026,.026,.026]);} + if(P.weapon==='bow'){add('weapon',G.torus(.4,.02,5,16,PI),0x9a4a2a,[0,0,0],[0,PI/2,PI/2]);for(const s of [-1,1])add('weapon',G.sphere(6,4),0xd6a64e,[0,s*.4,0],[0,0,0],[.03,.03,.03]); + add('weapon',G.cyl(1,1,4),0xf4efe6,[0,0,0],[0,0,0],[.005,.8,.005]);add('weapon',G.box(),0x5a3420,[0,0,0],[0,0,0],[.03,.12,.03]);} + if(P.weapon==='polearm'){add('weapon',G.cyl(1,1,6),0x7a4a2a,[0,0,.46],[PI/2,0,0],[.017,1.72,.017]);add('weapon',G.cone(4),0xd8dfe6,[0,0,1.42],[PI/2,0,0],[.045,.26,.018]); + add('weapon',G.cone(6),P.trim,[0,0,1.2],[-PI/2,0,0],[.04,.14,.04]);add('weapon',G.cyl(1,1,6),P.shirt,[0,0,1.27],[PI/2,0,0],[.026,.03,.026]);} + if(P.weapon==='catalyst'){add('book',G.bevel(),0x2f5fae,[0,0,0],[0,0,0],[.2,.26,.05]);add('book',G.box(),0xf6f1e4,[.012,0,0],[0,0,0],[.17,.23,.055]);add('book',G.ico(0),0xe4c46a,[0,0,.03],[0,0,0],[.04,.05,.012]);} + return L; + } + // ------------------------------------------------------------------------------------------------ Ruin Guard design + function guardParts(){ + const L={},add=(bone,geo,color,pos,rot,scale)=>(L[bone]||(L[bone]=new Build())).add(geo,color,pos,rot,scale); + const stone=0x8b8170,plate=0x9d927d,dark=0x4d4842,iron=0x5d5a55,moss=0x6f8a55; + add('hips',G.bevel(),dark,[0,0,0],[0,0,0],[1.05,.42,.72]);add('hips',G.cyl(1,1,10),iron,[0,.2,0],[0,0,0],[.6,.16,.5]); + add('upper',G.lathe([[.78,0],[.92,.25],[1,.62],[.95,1.02],[.72,1.25],[.3,1.34]],14),stone,[0,.2,0],[0,0,0],[1,1,.86]); + add('upper',G.bevel(),plate,[0,.85,.66],[-.12,0,0],[1.06,.66,.2]);add('upper',G.bevel(),plate,[0,.42,.7],[.15,0,0],[.82,.3,.16]); + add('upper',G.torus(.9,.06,5,20),dark,[0,.45,0],[PI/2,0,0],[1,.86,1]); + for(const s of [-1,1]){add('upper',G.sphere(10,7),plate,[s*.95,1.1,0],[0,0,0],[.5,.42,.52]);add('upper',G.bevel(),dark,[s*.45,1.22,-.86],[0,0,0],[.44,.5,.42]); + for(let k=0;k<3;k++)add('upper',G.cyl(1,1,6),0x2e2b28,[s*.45+(k-1)*.12,1.42,-.86],[0,0,0],[.045,.08,.045]);} + add('upper',G.sphere(8,6),moss,[.55,1.26,.3],[0,0,0],[.28,.08,.22]);add('upper',G.sphere(8,6),moss,[-.6,.3,.55],[0,0,0],[.22,.1,.12]); + add('head',G.sphere(12,8),plate,[0,.05,0],[0,0,0],[.5,.38,.46]);add('head',G.bevel(),stone,[0,.22,.18],[-.2,0,0],[.7,.14,.5]); + add('head',G.cyl(1,1,14),0x262320,[0,0,.4],[PI/2,0,0],[.2,.14,.2]); + for(const side of ['L','R']){const s=side==='L'?1:-1; + add('arm'+side,G.cyl(.85,1,10),stone,[0,-.5,0],[0,0,0],[.25,1,.25]);add('arm'+side,G.sphere(8,6),dark,[0,-1.02,0],[0,0,0],[.27,.27,.27]); + add('fore'+side,G.cyl(1.15,1,10),plate,[0,-.42,0],[0,0,0],[.26,.84,.26]); + add('fore'+side,G.bevel(),stone,[0,-.98,.04],[0,0,0],[.56,.46,.6]);for(let k=0;k<3;k++)add('fore'+side,G.bevel(),dark,[(k-1)*.17,-1.24,.12],[0,0,0],[.13,.22,.16]); + add('thigh'+side,G.cyl(1,1.1,10),dark,[0,-.28,0],[0,0,0],[.31,.56,.31]);add('thigh'+side,G.sphere(8,6),plate,[0,-.58,.05],[0,0,0],[.3,.26,.3]); + add('shin'+side,G.cyl(1,1.2,10),stone,[0,-.3,0],[0,0,0],[.29,.6,.29]);add('shin'+side,G.bevel(),plate,[0,-.62,.15],[0,0,0],[.6,.28,.92]);} + return L; + } + // ------------------------------------------------------------------------------------------------ Oceanid mimics + function mimicGeometry(type){ + const b=new Build(),W=0x9fe3ff,D=0x5fbde8,E=0xffffff,add=(geo,c,pos,rot,scale)=>b.add(geo,c,pos,rot,scale); + if(type==='boar'){add(G.sphere(12,8),W,[0,.62,0],[0,0,0],[.62,.52,.85]);add(G.sphere(10,7),W,[0,.68,.78],[0,0,0],[.36,.34,.38]);add(G.cyl(.8,1,8),D,[0,.62,1.12],[PI/2,0,0],[.15,.12,.13]); + for(const s of [-1,1]){add(G.cone(5),E,[s*.16,.55,1.05],[-.9,0,s*.4],[.04,.22,.04]);add(G.cone(5),W,[s*.2,.98,.7],[-.3,0,s*.3],[.08,.16,.05]);for(const z of [-.45,.45])add(G.cyl(1,.8,6),D,[s*.32,.2,z],[0,0,0],[.12,.42,.12]);}} + if(type==='squirrel'){add(G.sphere(12,8),W,[0,.5,0],[0,0,0],[.36,.42,.46]);add(G.sphere(10,7),W,[0,.86,.25],[0,0,0],[.28,.26,.27]);add(G.torus(.36,.17,6,12,PI*1.4),D,[0,.95,-.45],[0,PI/2,.3],[1,1,1]); + for(const s of [-1,1]){add(G.cone(5),W,[s*.13,1.12,.2],[0,0,s*.25],[.06,.16,.04]);add(G.sphere(6,4),D,[s*.18,.22,.12],[0,0,0],[.09,.14,.12]);}} + if(type==='crab'){add(G.sphere(12,6),W,[0,.36,0],[0,0,0],[.7,.26,.55]);for(const s of [-1,1]){add(G.sphere(8,6),D,[s*.72,.42,.45],[0,0,0],[.26,.2,.3]);add(G.cap(.07,.3,6),W,[s*.5,.36,.28],[0,0,s*.9],[1,1,1]); + for(let k=0;k<3;k++)add(G.cap(.04,.34,5),D,[s*(.55+k*.04),.2,-.2+k*.18],[0,0,s*1.1],[1,1,1]);add(G.cyl(1,1,6),E,[s*.16,.66,.36],[0,0,0],[.04,.18,.04]);}} + if(type==='mallard'){add(G.sphere(12,8),W,[0,.4,0],[0,0,0],[.4,.3,.58]);add(G.sphere(10,7),W,[0,.78,.4],[0,0,0],[.22,.22,.22]);add(G.cone(6),0xffe7a0,[0,.74,.68],[PI/2,0,0],[.08,.18,.05]);add(G.cone(6),D,[0,.48,-.6],[-2.2,0,0],[.12,.2,.08]);} + if(type==='crane'){add(G.sphere(12,8),W,[0,1.25,0],[0,0,0],[.32,.3,.52]);add(G.cap(.06,.6,6),W,[0,1.72,.3],[.45,0,0]);add(G.sphere(8,6),W,[0,2.1,.46],[0,0,0],[.13,.12,.15]);add(G.cone(6),0xffe7a0,[0,2.1,.7],[PI/2,0,0],[.04,.3,.04]); + for(const s of [-1,1])add(G.cyl(1,1,5),D,[s*.12,.55,0],[0,0,0],[.025,1.1,.025]);add(G.cone(6),D,[0,1.2,-.6],[-2,0,0],[.15,.35,.08]);} + if(type==='raptor'){add(G.sphere(12,8),W,[0,0,0],[0,0,0],[.3,.26,.55]);add(G.sphere(8,6),W,[0,.18,.48],[0,0,0],[.16,.15,.18]);add(G.cone(6),0xffe7a0,[0,.15,.68],[PI/2+.4,0,0],[.06,.16,.05]);add(G.cone(6),D,[0,0,-.62],[-PI/2,0,0],[.2,.32,.06]); + for(const s of [-1,1])add(G.cone(4),D,[s*.12,-.28,.12],[0,0,0],[.04,.16,.04]);} + if(type==='frog'){add(G.sphere(12,8),W,[0,.55,0],[0,0,0],[.72,.52,.72]);for(const s of [-1,1]){add(G.sphere(8,6),E,[s*.3,1.0,.42],[0,0,0],[.16,.16,.16]);add(G.sphere(6,5),0x14365a,[s*.32,1.02,.55],[0,0,0],[.07,.07,.05]); + add(G.sphere(8,6),D,[s*.6,.25,-.25],[0,0,0],[.3,.24,.5]);add(G.sphere(6,5),D,[s*.42,.18,.5],[0,0,0],[.14,.12,.2]);}} + if(type==='finch'){add(G.sphere(12,8),W,[0,.62,0],[0,0,0],[.5,.48,.56]);add(G.sphere(10,7),W,[0,1.05,.25],[0,0,0],[.3,.28,.3]);add(G.cone(6),0xffe7a0,[0,1.02,.55],[PI/2,0,0],[.08,.16,.06]); + add(G.cone(6),D,[0,.7,-.6],[-2.1,0,0],[.16,.3,.06]);for(const s of [-1,1])add(G.cyl(1,1,5),D,[s*.15,.12,.05],[0,0,0],[.03,.25,.03]);} + return b.build(); + } + const WINGED={crane:{span:.95,y:1.3,z:-.05},raptor:{span:1.1,y:.05,z:0},finch:{span:.6,y:.75,z:0},mallard:{span:.45,y:.45,z:-.05}}; + // ------------------------------------------------------------------------------------------------ the scene + class Scene{ + constructor(style,canvasEl){ + this.style=style;this.canvas=canvasEl;this.resources=new Set();this.times=[];this.ready=false;this.error=null;this.closed=false;this.themes={};this.theme=null; + this.view=document.createElement('canvas');this.view.width=854;this.view.height=480; + // No MSAA: the multisample resolve is not bit-exact between renders of the same state on this GPU path, which broke render + // purity (same state must give the same RGB). Inverted-hull outlines keep silhouettes readable without it. + this.renderer=new T.WebGLRenderer({canvas:this.view,alpha:false,antialias:false,preserveDrawingBuffer:true,powerPreference:'low-power'}); + this.renderer.setPixelRatio(1);this.renderer.setSize(854,480,false);this.renderer.outputColorSpace=T.SRGBColorSpace;this.renderer.toneMapping=T.NoToneMapping; + this.renderer.shadowMap.enabled=true;this.renderer.shadowMap.type=T.PCFShadowMap;this.renderer.info.autoReset=false; + this.view.addEventListener('webglcontextlost',e=>{e.preventDefault();this.ready=false;this.error='WebGL context lost';}); + this.world=new T.Scene();this.camera=new T.PerspectiveCamera(52,854/480,.1,260); + this.hemi=new T.HemisphereLight(0xd8ecff,0x6b6650,1.45);this.world.add(this.hemi); + this.sun=new T.DirectionalLight(0xfff1d8,2.25);this.sun.castShadow=true;this.sun.shadow.mapSize.set(1024,1024); + Object.assign(this.sun.shadow.camera,{left:-14,right:14,top:14,bottom:-14,near:.5,far:70});this.sun.shadow.bias=-.0008;this.sun.shadow.normalBias=.035;this.world.add(this.sun);this.world.add(this.sun.target); + const grad=this.keep(new T.DataTexture(new Uint8Array([104,104,104,255,178,178,178,255,255,255,255,255]),3,1));grad.minFilter=grad.magFilter=T.NearestFilter;grad.generateMipmaps=false;grad.needsUpdate=true;this.gradient=grad; + const soft=this.keep(new T.DataTexture(new Uint8Array([196,196,196,255,232,232,232,255,255,255,255,255]),3,1));soft.minFilter=soft.magFilter=T.NearestFilter;soft.generateMipmaps=false;soft.needsUpdate=true; + this.mat={toon:this.keep(new T.MeshToonMaterial({vertexColors:true,gradientMap:grad})),toonSoft:this.keep(new T.MeshToonMaterial({vertexColors:true,gradientMap:soft})), + lambert:this.keep(new T.MeshLambertMaterial({vertexColors:true})), + outline:this.outline(.016,0x1c1922),outlineBig:this.outline(.045,0x221d1a), + glow:this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:.9,depthWrite:false})), + add:this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:1,depthWrite:false,blending:T.AdditiveBlending,map:this.keep(TEX.dot())})), + addSolid:this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:.85,depthWrite:false,blending:T.AdditiveBlending})), + warn:this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:.42,side:T.DoubleSide,depthWrite:false})), + water:this.keep(new T.MeshStandardMaterial({vertexColors:true,color:0xffffff,transparent:true,opacity:.82,roughness:.14,metalness:.0,emissive:0x3a9ad0,emissiveIntensity:.55})), + ice:this.keep(new T.MeshStandardMaterial({color:0xcff6ff,transparent:true,opacity:.62,roughness:.08,metalness:.1,emissive:0x5fb8d8,emissiveIntensity:.35,flatShading:true}))}; + this.geo={plane:this.keep(new T.PlaneGeometry(1,1)),ring:this.keep(new T.RingGeometry(.86,1,40)),disc:this.keep(new T.CircleGeometry(1,32)),box:this.keep(new T.BoxGeometry(1,1,1)), + oct:this.keep(new T.OctahedronGeometry(1,0)),ico:this.keep(new T.IcosahedronGeometry(1,0)),cone:this.keep(new T.ConeGeometry(1,1,6)),cyl:this.keep(new T.CylinderGeometry(1,1,1,10,1,true)), + bevel:this.keep(beveled(2)),sphere:this.keep(new T.SphereGeometry(1,12,8))}; + this.dummy=new T.Object3D();this.camQ=new T.Quaternion(); + this.buildCommon(); + for(const id of ['genshin/electro_hypostasis','genshin/ruin_guard','genshin/oceanid'])this.ensureTheme(id,false); + for(const key of Object.keys(PLUGINS))this.ensureTheme('plugin:'+key,false); + // Compile with fog on: every theme uses linear Fog, so programs built here are the ones real frames use. + this.world.fog=this.theme.fogObj;this.warm();this.primeThemes(); + } + // Each theme has its own light set (the Electro Hypostasis core light exists only in the cape theme), so shader programs differ + // per theme. Render every theme once, alone, so its first real frame neither compiles programs nor differs from later frames. + primeThemes(){const all=Object.values(this.themes); + for(const th of all){for(const t of all)t.group.visible=t===th;this.world.fog=th.fogObj;for(const r of Object.values(this.heroes))r.root.visible=true; + for(let k=0;k<2;k++)this.renderer.render(this.world,this.camera);} + for(const r of Object.values(this.heroes))r.root.visible=false;} + keep(x){this.resources.add(x);return x;} + outline(width,color){const m=this.keep(new T.MeshBasicMaterial({color,side:T.BackSide})); + m.onBeforeCompile=s=>{s.vertexShader=s.vertexShader.replace('#include ','#include \n transformed += normal * '+width.toFixed(4)+';');}; + m.customProgramCacheKey=()=>'outline'+width;return m;} + mesh(geo,mat,parent,shadow=false){const m=new T.Mesh(geo,mat);m.castShadow=shadow;m.receiveShadow=shadow;parent.add(m);return m;} + pool(geo,mat,n,parent=this.world){const m=new T.InstancedMesh(geo,mat,n);m.count=0;m.frustumCulled=false;parent.add(m);this.keep(m);return m;} + // Rig = bones (Groups) + one merged toon mesh per bone with an inverted-hull outline. + rig(parts,layout,outline,shadow=true,parent=this.world){ + const root=new T.Group(),bones={}; + for(const [name,parent,pos,scale] of layout){const o=new T.Group();o.position.set(...pos);o.userData.rest=pos.slice();o.userData.scale=scale||1;o.scale.setScalar(o.userData.scale);(parent?bones[parent]:root).add(o);bones[name]=o;} + for(const [name,build] of Object.entries(parts)){if(build.empty||!bones[name])continue;const geo=this.keep(build.build());const m=this.mesh(geo,name==='head'&&this.mat.toonSoft?this.mat.toonSoft:this.mat.toon,bones[name],shadow);m.receiveShadow=false; + if(outline){const o=new T.Mesh(geo,outline);o.castShadow=false;bones[name].add(o);}} + parent.add(root);return {root,bones}; + } + resetRig(r){for(const b of Object.values(r.bones)){b.rotation.set(0,0,0);const p=b.userData.rest;b.position.set(p[0],p[1],p[2]);b.scale.setScalar(b.userData.scale||1);}r.root.rotation.set(0,0,0);r.root.scale.set(1,1,1);} + buildCommon(){ + const HL=[['hips',null,[0,.86,0]],['chest','hips',[0,.08,0]],['head','chest',[0,.44,0],1.13],['tail','head',[0,.1,-.15]],['tailL','head',[.15,.13,-.04]],['tailR','head',[-.15,.13,-.04]],['cape','chest',[-.04,.4,-.12]], + ['armL','chest',[.178,.36,0]],['foreL','armL',[0,-.27,0]],['armR','chest',[-.178,.36,0]],['foreR','armR',[0,-.27,0]], + ['legL','hips',[.09,-.02,0]],['shinL','legL',[0,-.4,0]],['legR','hips',[-.09,-.02,0]],['shinR','legR',[0,-.4,0]], + ['weapon','foreR',[0,-.245,.02]],['bowhand','foreL',[0,-.245,.02]],['book','chest',[-.34,.26,.26]]]; + this.heroes={}; + for(const id of Object.keys(HERO)){const parts=heroParts(id),layout=HL.map(r=>r.slice()); + if(HERO[id].weapon==='bow'){parts.bowhand=parts.weapon;delete parts.weapon;} + const r=this.rig(parts,layout,this.mat.outline);r.root.scale.setScalar(HERO[id].h);r.id=id;r.root.visible=false; + const face=this.keep(new T.MeshBasicMaterial({map:this.keep(TEX.face(id)),transparent:true,alphaTest:.35,color:0xf2ece6})); + const fg=this.keep(new T.SphereGeometry(.1575,20,14,PI/2-.66,1.32,1.1,.84));const f=new T.Mesh(fg,face);f.position.set(0,.13,0);f.scale.set(1,1.06,.995);r.bones.head.add(f); + this.heroes[id]=r;} + // Effects shared by every encounter. + const M=this.mat,Gm=this.geo; + this.glows=this.pool(Gm.plane,M.add,220);this.shards=this.pool(Gm.oct,M.addSolid,80);this.rings=this.pool(Gm.ring,M.addSolid,40); + this.flatRings=this.pool(Gm.ring,M.warn,24);this.beams=this.pool(Gm.box,M.warn,24);this.bolts=this.pool(Gm.ico,M.glow,60);this.arrows=this.pool(Gm.box,this.keep(new T.MeshBasicMaterial({color:0xe9c27a})),30); + const zc=this.keep(new T.ConeGeometry(1,1,6).rotateX(PI/2));this.spikes=this.pool(zc,M.ice,24);this.iceShell=this.pool(Gm.ico,M.ice,24);this.fireCones=this.pool(zc,M.addSolid,40);this.columns=this.pool(Gm.cyl,M.addSolid,12); + this.trailPos=new Float32Array(48*3);this.trailCol=new Float32Array(48*3);this.trailGeo=this.keep(new T.BufferGeometry());this.trailGeo.setAttribute('position',new T.BufferAttribute(this.trailPos,3).setUsage(T.DynamicDrawUsage)); + this.trailGeo.setAttribute('color',new T.BufferAttribute(this.trailCol,3).setUsage(T.DynamicDrawUsage));this.trailGeo.setDrawRange(0,0); + this.trail=new T.Mesh(this.trailGeo,this.keep(new T.MeshBasicMaterial({vertexColors:true,transparent:true,opacity:.5,side:T.DoubleSide,depthWrite:false,blending:T.AdditiveBlending})));this.trail.frustumCulled=false;this.world.add(this.trail); + // Ground telegraph surface: authored sectors/annuli in world units from the same geometry the rules use. + this.surfacePositions=new Float32Array(9000*3);this.surfaceColors=new Float32Array(9000*3);this.surfaceGeo=this.keep(new T.BufferGeometry()); + this.surfaceGeo.setAttribute('position',new T.BufferAttribute(this.surfacePositions,3).setUsage(T.DynamicDrawUsage));this.surfaceGeo.setAttribute('color',new T.BufferAttribute(this.surfaceColors,3).setUsage(T.DynamicDrawUsage)); + this.surfaceGeo.setDrawRange(0,0);this.surfaceMesh=new T.Mesh(this.surfaceGeo,this.keep(new T.MeshBasicMaterial({vertexColors:true,transparent:true,opacity:.42,side:T.DoubleSide,depthWrite:false})));this.surfaceMesh.frustumCulled=false;this.surfaceMesh.renderOrder=2;this.world.add(this.surfaceMesh); + // Summons: Baron Bunny and Guoba (original toy-like shapes). + const bunny=new Build();bunny.add(G.sphere(10,7),0xd2523e,[0,.42,0],[0,0,0],[.36,.42,.32]);bunny.add(G.sphere(10,7),0xf4e2c8,[0,.95,0],[0,0,0],[.3,.28,.28]);for(const s of [-1,1]){bunny.add(G.cap(.07,.36,6),0xd2523e,[s*.12,1.38,0],[0,0,s*.15]);bunny.add(G.sphere(6,4),0x2a2020,[s*.1,.98,.25],[0,0,0],[.04,.04,.02]);} + bunny.add(G.box(),0x3a2a26,[0,.42,.3],[0,0,0],[.2,.05,.03]); + this.bunny=this.mesh(this.keep(bunny.build()),M.toon,this.world,true);this.bunnyO=new T.Mesh(this.bunny.geometry,M.outline);this.bunny.add(this.bunnyO);this.bunny.visible=false; + const guoba=new Build();guoba.add(G.sphere(10,7),0xb8452c,[0,.42,0],[0,0,0],[.4,.42,.36]);guoba.add(G.sphere(10,7),0xc95a35,[0,.95,.05],[0,0,0],[.34,.3,.3]);guoba.add(G.sphere(8,6),0xf2dcc0,[0,.86,.3],[0,0,0],[.16,.1,.08]); + for(const s of [-1,1]){guoba.add(G.sphere(6,5),0x3a2018,[s*.2,1.2,0],[0,0,0],[.1,.1,.08]);guoba.add(G.sphere(6,4),0x1e1414,[s*.1,1.0,.3],[0,0,0],[.04,.05,.02]);guoba.add(G.cap(.07,.16,6),0x5a2a1c,[s*.22,.2,.05]);} + guoba.add(G.ico(0),0xffd27a,[0,1.32,0],[0,0,0],[.07,.07,.07]); + this.guoba=this.mesh(this.keep(guoba.build()),M.toon,this.world,true);this.guobaO=new T.Mesh(this.guoba.geometry,M.outline);this.guoba.add(this.guobaO);this.guoba.visible=false; + } + // ---------------------------------------------------------------------------------------------- themes (lazy) + ensureTheme(id,warm=true){ + const plug=Object.keys(PLUGINS).find(k=>id==='plugin:'+k||PLUGINS[k].match(id)); + const key=plug||(id.includes('ruin')?'ruins':id.includes('oceanid')?'lake':'cape'); + if(!this.themes[key]){const g=new T.Group();this.world.add(g);const th={key,group:g,plugin:plug?PLUGINS[plug]:null};this.themes[key]=th;if(plug)PLUGINS[plug].build(this,th,{T,G,Build,TEX,beveled,hash,v3,EL,HERO});else this['build_'+key](th);if(warm)this.warm();} + for(const [k,th] of Object.entries(this.themes))th.group.visible=k===key;this.theme=this.themes[key];return this.theme; + } + // Compile every material/instance-colour buffer once so a first mid-fight use never stalls a frame. + warm(){const pools=[];this.world.traverse(o=>{if(o.isInstancedMesh&&o.count===0)pools.push(o);}); + // setColorAt allocates instanceColor filled with zeros: fill it with white so instances placed without a colour keep their + // material/vertex colours instead of rendering black. + for(const p of pools){this.place(p,0,[0,-80,0],[.001,.001,.001],[0,0,0],0xffffff);if(p.instanceColor)p.instanceColor.array.fill(1);p.count=1;p.instanceMatrix.needsUpdate=true;if(p.instanceColor)p.instanceColor.needsUpdate=true;} + const hidden=[];this.world.traverse(o=>{if(!o.visible&&(o.isMesh||o.isGroup)){hidden.push(o);o.visible=true;}}); + this.renderer.compile(this.world,this.camera);this.renderer.render(this.world,this.camera);for(const o of hidden)o.visible=false;for(const p of pools)p.count=0;} + // theme: built-in key or [top, mid, horizon] palette; opts.clouds tints/hides clouds for plugin arenas. + sky(th,theme,fog,opts={}){const sky=this.mesh(this.keep(new T.SphereGeometry(200,24,12)),this.keep(new T.MeshBasicMaterial({map:this.keep(TEX.sky(theme)),side:T.BackSide,fog:false,depthWrite:false})),th.group);sky.renderOrder=-10; + th.fog=fog;th.fogObj=new T.Fog(fog[0],fog[1],fog[2]);const cloud=this.keep(new T.MeshBasicMaterial({map:this.keep(TEX.cloud()),transparent:true,depthWrite:false,fog:false,opacity:opts.cloudOpacity??(theme==='lake'?.55:.85),color:opts.cloudColor??(theme==='lake'?0xc9d4da:0xffffff)})); + const b=[];for(let i=0;i<11;i++){const a=i*.57+.3,r=150,y=26+hash(i*17)*30,s=36+hash(i*5)*30;const pl=new T.PlaneGeometry(s*2,s);pl.lookAt(v3(-Math.sin(a),0,-Math.cos(a)));pl.translate(Math.sin(a)*r,y,Math.cos(a)*r);b.push(pl);} + const merged=new T.BufferGeometry(),pos=[],uv=[];for(const g of b){const n=g.index?g.toNonIndexed():g;pos.push(...n.attributes.position.array);uv.push(...n.attributes.uv.array);n.dispose();g.dispose();} + merged.setAttribute('position',new T.Float32BufferAttribute(pos,3));merged.setAttribute('uv',new T.Float32BufferAttribute(uv,2));this.mesh(this.keep(merged),cloud,th.group).renderOrder=-9; + const sun=this.mesh(this.geo.plane,this.keep(new T.MeshBasicMaterial({map:this.mat.add.map,color:opts.sunColor??(theme==='lake'?0x8899a0:0xfff2c8),transparent:true,blending:T.AdditiveBlending,depthWrite:false,fog:false})),th.group); + sun.position.set(-90,95,70);sun.scale.setScalar(60);sun.lookAt(0,0,0);} + props(th,build,mat=this.mat.lambert,shadow=false){if(build.empty)return null;const m=this.mesh(this.keep(build.build()),mat,th.group,false);m.receiveShadow=true;m.castShadow=shadow;return m;} + build_cape(th){ + this.sky(th,'cape',[0xb8d8e6,40,150]); + const ground=this.mesh(this.keep(new T.CircleGeometry(48,56)),this.keep(new T.MeshLambertMaterial({map:(()=>{const t=this.keep(TEX.grass());t.repeat.set(18,18);return t;})()})),th.group);ground.rotation.x=-PI/2;ground.position.y=-.3;ground.receiveShadow=true; + const top=this.mesh(this.keep(new T.CircleGeometry(18.3,72)),this.keep(new T.MeshLambertMaterial({map:this.keep(TEX.arena('cape'))})),th.group);top.rotation.x=-PI/2;top.position.y=.01;top.receiveShadow=true; + const rock=new Build(),ruin=new Build(),tree=new Build(),deco=new Build(); + rock.add(new T.CylinderGeometry(18.3,18.9,.62,72,1,true),0xb7ae96,[0,-.3,0]); + // Cliff ring and sea beyond: the plateau of a seaside cape (original layout). + for(let i=0;i<44;i++){const a=i*TAU/44,r=48+hash(i)*1.6,h=13+hash(i+50)*2.5,top=-.1+hash(i+90)*1.4;rock.add(G.bevel(),[0x8d8a7a,0x9b9584,0x7d7b6e][i%3],[Math.sin(a)*r,top-h/2,Math.cos(a)*r],[0,a,(hash(i+7)-.5)*.2],[7.6,h,5]);} + for(let i=0;i<7;i++){const a=i*.9+2.2,r=110+hash(i*9)*60,h=10+hash(i)*14;rock.add(G.sphere(9,6),[0x7f9a82,0x8aa78c][i%2],[Math.sin(a)*r,-12,Math.cos(a)*r],[0,a,0],[18+hash(i+3)*14,h,14+hash(i+5)*10]);} + for(let i=0;i<10;i++){const a=i*TAU/10+.2,x=Math.sin(a)*21.5,z=Math.cos(a)*21.5,h=i%3===0?1.4:2.6+(i%2)*1.4; + ruin.add(G.bevel(),0xd9d2bd,[x,h/2-.25,z],[0,a,i%3===0?.16:0],[.95,h,.95]);ruin.add(G.bevel(),0xc8c0aa,[x,-.18,z],[0,a,0],[1.5,.35,1.5]);ruin.add(G.bevel(),0xe4ddc9,[x,h-.15,z],[0,a,0],[1.25,.28,1.25]); + if(i%2===0){const b2=a+PI/10,x2=Math.sin(b2)*21.5,z2=Math.cos(b2)*21.5;ruin.add(G.bevel(),0xd2cab4,[(x+x2)/2,h+.05,(z+z2)/2],[0,b2-PI/2+.2,.06],[.55,.4,3.6]);} + else ruin.add(G.bevel(),0xcfc7b0,[x+Math.sin(a+1.4)*1.7,0,z+Math.cos(a+1.4)*1.7],[0,a+.6,.24],[2,.45,.75]);} + for(let i=0;i<14;i++){const a=i*2.39+.4,r=27+hash(i*3)*22,x=Math.sin(a)*r,z=Math.cos(a)*r,h=3+hash(i*7)*2.5; + tree.add(G.cyl(.8,1,6),0x6b4a34,[x,h/2-.3,z],[0,0,(hash(i)-.5)*.1],[.28,h,.28]); + for(let k=0;k<3;k++)tree.add(G.sphere(8,6),[0x5f9a52,0x6eab5a,0x4f8a48][k],[x+(k-1)*.9,h+.4+(k%2)*.7,z+(hash(i+k)-.5)*1.2],[0,0,0],[1.7,1.4,1.7]);} + for(let i=0;i<34;i++){const a=i*2.17,r=19.6+hash(i)*8;deco.add(G.cone(5),[0x7cbf63,0x8ccf6f,0x5fa452][i%3],[Math.sin(a)*r,.1,Math.cos(a)*r],[0,a,0],[.35,.6,.35]); + if(i%3===0)deco.add(G.ico(0),[0xffffff,0xfff0a8][i%2],[Math.sin(a)*r+.4,.4,Math.cos(a)*r],[0,0,0],[.14,.14,.14]);} + this.props(th,rock);this.props(th,ruin);this.props(th,tree);this.props(th,deco); + const sea=this.mesh(this.keep(new T.CircleGeometry(240,40)),this.keep(new T.MeshLambertMaterial({color:0x3a93c0})),th.group);sea.rotation.x=-PI/2;sea.position.y=-12; + // Electro Hypostasis model: eight rune cubes, a crystal core, glow, arcs and the revival prisms. + const cubeMat=this.keep(new T.MeshStandardMaterial({map:this.keep(TEX.rune()),emissiveMap:this.keep(TEX.runeGlow()),emissive:0xd0a8ff,emissiveIntensity:.9,roughness:.38,metalness:.25})); + th.cubes=this.pool(this.geo.bevel,cubeMat,8,th.group);th.cubes.castShadow=true;th.cubesO=this.pool(this.geo.bevel,this.mat.outlineBig,8,th.group); + th.core=this.mesh(this.geo.oct,this.keep(new T.MeshStandardMaterial({color:0xe9d8ff,emissive:0xb07cff,emissiveIntensity:1.6,roughness:.15,metalness:.1})),th.group,true); + th.coreShell=this.mesh(this.geo.oct,this.keep(new T.MeshBasicMaterial({color:0xc6a2ff,transparent:true,opacity:.18,depthWrite:false})),th.group); + th.coreLight=new T.PointLight(0xc8a0ff,0,10,1.6);th.group.add(th.coreLight); + th.prisms=this.pool(this.keep(new T.CylinderGeometry(.42,.6,1.9,3)),this.keep(new T.MeshStandardMaterial({color:0xb79bff,emissive:0x7a4fe0,emissiveIntensity:.9,roughness:.2,metalness:.2,flatShading:true})),3,th.group); + th.pillars=this.pool(this.geo.bevel,this.keep(new T.MeshStandardMaterial({map:cubeMat.map,emissiveMap:cubeMat.emissiveMap,emissive:0xb994ff,emissiveIntensity:.8,roughness:.5})),8,th.group); + th.ghosts=this.pool(this.geo.bevel,this.keep(new T.MeshBasicMaterial({color:0xb79cff,transparent:true,opacity:.15,depthWrite:false})),8,th.group); + th.walls=this.pool(this.geo.plane,this.keep(new T.MeshBasicMaterial({color:0xc39bff,transparent:true,opacity:.42,side:T.DoubleSide,depthWrite:false,blending:T.AdditiveBlending})),8,th.group); + const arcPos=new Float32Array(160*3);th.arcGeo=this.keep(new T.BufferGeometry());th.arcGeo.setAttribute('position',new T.BufferAttribute(arcPos,3).setUsage(T.DynamicDrawUsage));th.arcGeo.setDrawRange(0,0); + th.arcs=new T.LineSegments(th.arcGeo,this.keep(new T.LineBasicMaterial({color:0xe6d0ff,transparent:true,opacity:.95,blending:T.AdditiveBlending,depthWrite:false})));th.arcs.frustumCulled=false;th.group.add(th.arcs); + th.baseRing=this.mesh(this.geo.ring,this.keep(new T.MeshBasicMaterial({color:0xb48cff,transparent:true,opacity:.5,depthWrite:false,blending:T.AdditiveBlending,side:T.DoubleSide})),th.group);th.baseRing.rotation.x=-PI/2; + } + build_ruins(th){ + this.sky(th,'ruins',[0xc9d8d6,36,140]); + const ground=this.mesh(this.keep(new T.CircleGeometry(80,48)),this.keep(new T.MeshLambertMaterial({map:(()=>{const t=this.keep(TEX.grass());t.repeat.set(30,30);return t;})(),color:0xe8f0d0})),th.group);ground.rotation.x=-PI/2;ground.position.y=-.02;ground.receiveShadow=true; + const floor=this.mesh(this.keep(new T.CircleGeometry(18.6,72)),this.keep(new T.MeshLambertMaterial({map:this.keep(TEX.arena('ruins'))})),th.group);floor.rotation.x=-PI/2;floor.position.y=.015;floor.receiveShadow=true; + const wall=new Build(),glyph=new Build(),tree=new Build(),deco=new Build(); + // Broken Khaenri'ah-style enclosure: wall segments with arches, fallen blocks, glyph slabs (original design). + for(let i=0;i<18;i++){const a=i*TAU/18,r=23.5,x=Math.sin(a)*r,z=Math.cos(a)*r,h=i%4===1?1.2:2.6+hash(i)*2.2,broken=i%5===3; + if(broken){wall.add(G.bevel(),0x8f8a7a,[x,.25,z],[0,a+.5,.3],[2.6,.8,1]);continue;} + wall.add(G.bevel(),[0x9a9482,0x8d8877,0xa39d8a][i%3],[x,h/2,z],[0,a+PI/2,0],[6.6,h,1]); + if(i%3===0){wall.add(G.bevel(),0x7c776a,[x,h+.6,z],[0,a+PI/2,0],[2.2,1.2,1.1]);glyph.add(G.box(),0x58e6d6,[x-Math.sin(a)*.52,h*.55,z-Math.cos(a)*.52],[0,a+PI/2,0],[1.4,.12,.05]); + glyph.add(G.box(),0x58e6d6,[x-Math.sin(a)*.52,h*.55+.35,z-Math.cos(a)*.52],[0,a+PI/2,0],[.12,.6,.05]);} + if(i%2===0)deco.add(G.sphere(8,6),0x6f9a52,[x-Math.sin(a)*.6,h-.05,z-Math.cos(a)*.6],[0,a,0],[1.4,.25,.5]);} + for(let i=0;i<8;i++){const a=i*TAU/8+.35,r=17.2;wall.add(G.bevel(),0x938d7c,[Math.sin(a)*r,.2,Math.cos(a)*r],[0,a,hash(i)*.3],[1.4,.5,.9]);} + for(let i=0;i<4;i++){const a=i*TAU/4+.8,r=21.2;wall.add(G.cyl(1,1,10),0xa7a08c,[Math.sin(a)*r,1.8,Math.cos(a)*r],[0,0,0],[.6,3.6,.6]);wall.add(G.bevel(),0x8a8474,[Math.sin(a)*r,3.7,Math.cos(a)*r],[0,a,0],[1.6,.4,1.6]); + glyph.add(G.torus(.62,.05,4,16),0x58e6d6,[Math.sin(a)*r,2.4,Math.cos(a)*r],[PI/2,0,0]);} + for(let i=0;i<16;i++){const a=i*2.41+.2,r=28+hash(i*3)*26,x=Math.sin(a)*r,z=Math.cos(a)*r,h=3.5+hash(i*7)*3; + tree.add(G.cyl(.75,1,6),0x5f4433,[x,h/2,z],[0,0,0],[.3,h,.3]);for(let k=0;k<3;k++)tree.add(G.ico(1),[0x4d8a46,0x5d9c4f,0x437c3e][k],[x+(k-1)*1,h+.5+(k%2)*.8,z+(hash(i+k)-.5)*1.4],[0,k,0],[1.9,1.6,1.9]);} + for(let i=0;i<9;i++){const a=i*TAU/9+.1,r=55+hash(i)*10;tree.add(G.sphere(10,6),[0x7f9a86,0x8aa48f,0x73907c][i%3],[Math.sin(a)*r,-2,Math.cos(a)*r],[0,0,0],[16,9+hash(i)*7,12]);} + for(let i=0;i<40;i++){const a=i*1.91,r=18.8+hash(i)*9;deco.add(G.cone(5),[0x6faa55,0x7fba63,0x5a9447][i%3],[Math.sin(a)*r,.12,Math.cos(a)*r],[0,a,0],[.32,.55,.32]);} + this.props(th,wall);this.props(th,tree);this.props(th,deco); + const gl=this.mesh(this.keep(glyph.build()),this.keep(new T.MeshBasicMaterial({vertexColors:true})),th.group); + // Ruin Guard rig: wide barrel body, single eye, long arms, back cannons and back weak point (original design). + const layout=[['hips',null,[0,1.28,0]],['upper','hips',[0,.12,0]],['head','upper',[0,1.42,.32]],['armL','upper',[1.12,1.12,0]],['foreL','armL',[0,-1.08,0]],['armR','upper',[-1.12,1.12,0]],['foreR','armR',[0,-1.08,0]], + ['thighL','hips',[.5,-.12,0]],['shinL','thighL',[0,-.62,0]],['thighR','hips',[-.5,-.12,0]],['shinR','thighR',[0,-.62,0]]]; + th.guard=this.rig(guardParts(),layout,this.mat.outlineBig,true,th.group); + const lit=this.keep(new T.MeshBasicMaterial({color:0xffb347}));th.eyeMat=lit;th.eye=this.mesh(this.keep(new T.CircleGeometry(.15,20)),lit,th.guard.bones.head);th.eye.position.set(0,0,.475); + th.socketMat=this.keep(new T.MeshBasicMaterial({color:0x5ff0e0}));th.socket=this.mesh(this.keep(new T.CircleGeometry(.24,20)),th.socketMat,th.guard.bones.upper);th.socket.position.set(0,1.02,-.93);th.socket.rotation.y=PI; + th.lineMat=this.keep(new T.MeshBasicMaterial({color:0x5ff0e0}));const lines=new Build(); + for(const [x,y,w,h] of [[0,.85,.06,.5],[-.3,.85,.4,.05],[.3,.85,.4,.05],[0,.45,.6,.05]])lines.add(G.box(),0xffffff,[x,y,.77],[-.12,0,0],[w,h,.03]); + for(const s of [-1,1])lines.add(G.box(),0xffffff,[s*.98,1.1,.4],[0,0,0],[.05,.3,.05]); + this.mesh(this.keep(lines.build()),th.lineMat,th.guard.bones.upper);th.lineMat.vertexColors=true; + th.crosshair=this.mesh(this.geo.plane,this.keep(new T.MeshBasicMaterial({map:this.keep(TEX.reticle()),transparent:true,depthWrite:false,opacity:.95})),th.group);th.crosshair.rotation.x=-PI/2;th.crosshair.visible=false; + th.runeRing=this.pool(this.geo.ring,this.mat.addSolid,2,th.group); + } + build_lake(th){ + this.sky(th,'lake',[0xa9b8bf,34,150]); + const rip=this.keep(TEX.ripple());rip.repeat.set(22,22);th.ripple=rip; + th.water=this.mesh(this.keep(new T.CircleGeometry(140,48)),this.keep(new T.MeshStandardMaterial({color:0x2f7f9f,roughness:.16,metalness:.15,normalMap:rip,normalScale:new T.Vector2(.55,.55),transparent:true,opacity:.92})),th.group); + th.water.rotation.x=-PI/2;th.water.position.y=-.32;th.water.receiveShadow=true; + const slabTex=this.keep(TEX.slab()),slabMat=this.keep(new T.MeshLambertMaterial({map:slabTex})); + th.tiles=[];for(let i=0;i<9;i++){const m=this.mesh(this.keep(beveled(2,.04)),slabMat,th.group);m.scale.set(6.92,.7,6.92);m.receiveShadow=true;th.tiles.push(m);} + th.tileGlow=this.pool(this.geo.box,this.keep(new T.MeshBasicMaterial({color:0x7fe0ff,transparent:true,opacity:.35,depthWrite:false,blending:T.AdditiveBlending})),4,th.group); + const hills=new Build(),deco=new Build(); + // Liyue karst pillars in the mist around the lake (original placement). + for(let i=0;i<18;i++){const a=i*TAU/18+hash(i)*.25,r=78+hash(i*3)*55,h=24+hash(i*5)*30,w=5+hash(i*7)*5,x=Math.sin(a)*r,z=Math.cos(a)*r; + hills.add(G.cyl(.62,1,9),[0x8c9a92,0x7f8f88,0x96a39b][i%3],[x,h/2-3,z],[0,0,(hash(i)-.5)*.06],[w,h,w]);hills.add(G.sphere(9,6),[0x5f8a64,0x6c9870][i%2],[x,h-3.4,z],[0,0,0],[w*.72,w*.5,w*.72]);} + for(let i=0;i<10;i++){const a=i*TAU/10+.4,r=34+hash(i*11)*10;hills.add(G.sphere(9,5),[0x6f8a64,0x7a9670][i%2],[Math.sin(a)*r,-2.2,Math.cos(a)*r],[0,a,0],[9+hash(i)*6,3.2+hash(i+2)*2,6+hash(i+4)*4]);} + for(let i=0;i<22;i++){const a=i*2.2,r=13.5+hash(i)*3;deco.add(G.cyl(.6,1,6),0x6f8f5a,[Math.sin(a)*r,0,Math.cos(a)*r],[0,0,(hash(i)-.5)*.3],[.06,1.4+hash(i)*.8,.06]);} + this.props(th,hills);this.props(th,deco); + // Rain: instanced streaks recycled around the camera; positions are a pure function of the tick. + th.rain=this.pool(this.geo.box,this.keep(new T.MeshBasicMaterial({color:0xd8ecf6,transparent:true,opacity:.35,depthWrite:false})),260,th.group); + // Rhodeia: a translucent water spirit with flowing hair and a water tail (original design). + const body=new Build(),W=0xbfeeff,D=0x7fd0f4; + body.add(G.lathe([[.0,-.2],[.32,0],[.26,.55],[.34,.95],[.2,1.15],[.07,1.25]],12),W,[0,0,0]);body.add(G.sphere(12,9),W,[0,1.42,0],[0,0,0],[.24,.27,.24]); + for(let k=0;k<6;k++){const a=(k-2.5)*.28;body.add(G.cap(.07,.9,6),D,[Math.sin(a)*.2,1.25,-.18-Math.abs(a)*.1],[.9,a*.5,0]);} + body.add(G.cone(10),D,[0,-.9,0],[PI,0,0],[.45,1.6,.45]);for(const s of [-1,1])body.add(G.cap(.06,.55,6),W,[s*.38,.95,0],[0,0,s*.5]); + th.oceanid=this.mesh(this.keep(body.build()),this.mat.water,th.group);th.oceanidGlow=this.mesh(this.geo.plane,this.keep(new T.MeshBasicMaterial({map:this.mat.add.map,color:0x5fd0ff,transparent:true,depthWrite:false,blending:T.AdditiveBlending})),th.group); + th.orbs=this.pool(this.geo.sphere,this.mat.water,4,th.group); + th.mimics={};for(const type of ['boar','squirrel','crab','mallard','crane','raptor','frog','finch']){const m=this.pool(this.keep(mimicGeometry(type)),this.mat.water,3,th.group);m.castShadow=true;th.mimics[type]=m;} + th.wings=this.pool(this.keep(new T.ConeGeometry(.5,1,4).rotateZ(PI/2).translate(.5,0,0).scale(1,.08,.45)),this.mat.water,12,th.group); + th.bombs=this.pool(this.geo.sphere,this.keep(new T.MeshStandardMaterial({color:0x8fe0ff,transparent:true,opacity:.45,roughness:.1,emissive:0x2a8fd0,emissiveIntensity:.6})),4,th.group); + th.swirls=this.pool(this.geo.plane,this.keep(new T.MeshBasicMaterial({map:this.keep(TEX.swirl()),transparent:true,depthWrite:false,blending:T.AdditiveBlending,color:0x8fdcff})),8,th.group); + th.waveCrest=this.pool(this.keep(new T.CylinderGeometry(1,1,1,10,1,true,0,PI)),this.mat.water,8,th.group); + } + // ---------------------------------------------------------------------------------------------- helpers + place(pool,index,pos,scale=[1,1,1],rotation=[0,0,0],color=null){if(index>=pool.instanceMatrix.count)return index;const d=this.dummy;d.position.set(pos[0],pos[1],pos[2]);d.scale.set(scale[0],scale[1],scale[2]); + if(rotation.isQuaternion)d.quaternion.copy(rotation);else d.rotation.set(rotation[0],rotation[1],rotation[2]);d.updateMatrix();pool.setMatrixAt(index,d.matrix);if(color!==null)pool.setColorAt(index,this.tmpColor.set(color));return index+1;} + get tmpColor(){return this._c||(this._c=new T.Color());} + glow(i,x,y,z,s,color){return this.place(this.glows,i,[x,y,z],[s,s,s],this.camQ,color);} + finish(pool,count){pool.count=count;pool.instanceMatrix.needsUpdate=true;if(pool.instanceColor)pool.instanceColor.needsUpdate=true;} + dir(dx,dy,dz){const a=v3(dx,dy,dz);if(a.lengthSq()<1e-10)return new T.Quaternion();return new T.Quaternion().setFromUnitVectors(v3(0,0,1),a.normalize());} + surfaceTriangle(a,b,c,color,y=.05){if(this.surfaceN+3>this.surfacePositions.length/3)return;const rgb=this.tmpColor.set(color); + for(const p of [a,b,c]){const n=this.surfaceN++*3;this.surfacePositions[n]=p[0];this.surfacePositions[n+1]=y;this.surfacePositions[n+2]=p[1];this.surfaceColors[n]=rgb.r;this.surfaceColors[n+1]=rgb.g;this.surfaceColors[n+2]=rgb.b;}} + sector(x,z,inner,outer,start,end,color,y){if(!(outer>0)||!Number.isFinite(start)||!Number.isFinite(end))return;const count=Math.min(96,Math.max(2,Math.ceil(Math.abs(end-start)*10))),pt=(r,a)=>[x+Math.sin(a)*r,z+Math.cos(a)*r]; + for(let i=0;i0)this.surfaceTriangle(p,r,s,color,y);}} + // Filled area plus a brighter rim, so a telegraph reads clearly against stone, grass and water. + area(x,z,r,color,half=PI,a=0,y){this.sector(x,z,0,r,a-half,a+half,color,y);this.sector(x,z,Math.max(0,r-.09),r+.07,a-half,a+half,color,y);} + // ---------------------------------------------------------------------------------------------- party pose + heroPose(r,g,tickOverride){ + const p=g.player||{},q=items(g.party)[p.active||0]||{},id=r.id,W=HERO[id].weapon,b=r.bones,tm=g.t/60; + const act=String(p.action||''),tick=tickOverride!==undefined?tickOverride:Number(p.actionTick||0),spd=Number(p.moveSpeed||0),step=Number(p.comboStep||0); + this.resetRig(r);r.root.scale.setScalar(HERO[id].h); + const swim=!!p.swimming,run=clamp(spd/5.2,0,1.5),sprint=spd>6.6,ph=tm*(sprint?13:spd>.5?10:2); + r.root.position.set(p.x||0,(p.y||0)+(swim?-.95:0),p.z||0);r.root.rotation.y=Number(p.yaw||0); + // Locomotion base: stride, counter-swinging arms, bob and lean. + const A=.62*Math.min(run,1.25); + b.legL.rotation.x=-Math.sin(ph)*A;b.legR.rotation.x=Math.sin(ph)*A;b.shinL.rotation.x=Math.max(0,Math.sin(ph+1.2))*A*1.2;b.shinR.rotation.x=Math.max(0,-Math.sin(ph+1.2))*A*1.2; + b.armL.rotation.set(Math.sin(ph)*A*.75,0,.14);b.armR.rotation.set(-Math.sin(ph)*A*.75,0,-.14);b.foreL.rotation.x=-.25-.2*run;b.foreR.rotation.x=-.25-.2*run; + b.hips.position.y+=Math.abs(Math.sin(ph))*.04*run+Math.sin(tm*2.2)*.006;b.chest.rotation.set(.07*run+(sprint?.14:0)+Math.sin(tm*2.2)*.012,Math.sin(ph)*.12*run,0);b.head.rotation.x=-.05*run; + if(b.cape)b.cape.rotation.x=.18+.35*run+Math.sin(tm*3)*.04;if(b.tail)b.tail.rotation.x=.25+.4*run+Math.sin(tm*2.6)*.06; + for(const k of ['tailL','tailR'])if(b[k])b[k].rotation.set(.15+.3*run+Math.sin(tm*2.4+(k==='tailL'?0:1))*.05,0,(k==='tailL'?.12:-.12)); + // Idle weapon stance. + if(W==='sword'&&run<.2){b.armR.rotation.set(-.25,0,-.25);b.foreR.rotation.x=-.55;} + if(W==='polearm'){b.armR.rotation.x+=-.35;b.foreR.rotation.x=-.9;b.weapon.rotation.set(-.15,0,.2);} + if(W==='bow'){b.bowhand.rotation.set(-1.25,0,0);} + const k=(n)=>ease(tick/n); + if(act==='attack'||act==='charged'){ + if(W==='sword'){const kind=act==='charged'?(tick<7?0:1):[0,1,2,0,3][step%5],u=k(act==='charged'?7:11),m=kind===1?-1:1; + b.chest.rotation.y=m*lerp(.75,-.85,u); + if(kind<2){b.armR.rotation.set(-1.45,m*lerp(.95,-1.05,u),-.15);b.foreR.rotation.set(-.25,0,0);b.weapon.rotation.set(0,0,0);} + else if(kind===2){b.armR.rotation.set(lerp(-2.9,-.55,u),0,-.1);b.foreR.rotation.x=-.2;} + else{b.armR.rotation.set(-1.5,lerp(1.2,-2.4,u),-.2);b.chest.rotation.y=lerp(1,-1.6,u);} + b.armL.rotation.set(-.4,0,.5);b.legL.rotation.x=-.35;b.legR.rotation.x=.25;b.shinR.rotation.x=.35;} + if(W==='polearm'){const u=k(10),thrust=act==='charged'||step%2===0; + if(thrust){b.armR.rotation.set(lerp(-.6,-1.45,u),.25,-.1);b.foreR.rotation.x=lerp(-1.3,-.1,u);b.armL.rotation.set(lerp(-.4,-1.35,u),-.3,.2);b.foreL.rotation.x=-.6;b.weapon.rotation.set(0,0,0);b.chest.rotation.y=lerp(.5,-.2,u);b.legL.rotation.x=-.55;b.shinR.rotation.x=.4;} + else{b.armR.rotation.set(-1.3,lerp(1.2,-1.2,u),-.3);b.foreR.rotation.x=-.4;b.chest.rotation.y=lerp(.9,-.9,u);b.armL.rotation.set(-.6,0,.4);}} + if(W==='catalyst'){const u=k(9);b.armR.rotation.set(lerp(-.4,-1.45,u),-.2,-.15);b.foreR.rotation.x=lerp(-.9,-.1,u);b.armL.rotation.set(-.3,0,.45);b.chest.rotation.y=lerp(.3,-.25,u); + if(act==='charged'){b.armL.rotation.set(lerp(-.4,-1.4,u),.2,.15);b.foreL.rotation.x=-.1;}} + if(W==='bow'){b.armL.rotation.set(-1.5,.12,0);b.foreL.rotation.x=0;b.bowhand.rotation.set(-PI/2,0,0);const u=k(8);b.armR.rotation.set(-1.4,lerp(.1,.55,1-u),0);b.foreR.rotation.x=lerp(-1.8,-.4,u);b.chest.rotation.y=.35;} + } + if(act==='aim'||act==='bow'){b.armL.rotation.set(-1.52,.1,0);b.foreL.rotation.x=0;b.bowhand.rotation.set(-PI/2,0,0);b.armR.rotation.set(-1.45,.5,0);b.foreR.rotation.x=act==='aim'?-2:-.6;b.chest.rotation.y=.42;b.head.rotation.y=-.3; + b.legL.rotation.x=-.3;b.legR.rotation.x=.25;if(act==='aim')b.chest.rotation.x-=Math.min(.3,Math.max(-.3,Number(p.aimPitch||0)*.5));} + if(act==='skill'){const u=k(14); + if(id==='kaeya'){b.armL.rotation.set(lerp(-.3,-1.55,u),-.25,.15);b.foreL.rotation.x=0;b.chest.rotation.y=lerp(-.2,.5,u);b.legR.rotation.x=.4;b.legL.rotation.x=-.45;} + if(id==='amber'){b.armR.rotation.set(lerp(.9,-2.1,u),0,-.1);b.foreR.rotation.x=-.2;b.chest.rotation.x=lerp(.3,-.1,u);} + if(id==='xiangling'){b.armR.rotation.set(-2.2*u,0,-.2);b.foreR.rotation.x=-.4;b.armL.rotation.set(-1.2*u,0,.3);r.root.position.y+=Math.sin(u*PI)*.12;} + if(id==='barbara'){r.root.rotation.y+=u*TAU;b.armL.rotation.set(-2.6*u,0,.4);b.armR.rotation.set(-2.6*u,0,-.4);}} + if(act==='burst'){const u=k(26); + if(id==='kaeya'){b.armR.rotation.set(lerp(-.5,-2.9,u),0,-.1);b.foreR.rotation.x=-.1;b.armL.rotation.set(-.5,0,.6);b.chest.rotation.x=-.12;} + if(id==='amber'){b.armL.rotation.set(-2.7,0,0);b.foreL.rotation.x=0;b.bowhand.rotation.set(-PI/2,0,0);b.armR.rotation.set(-2.5,.35,0);b.foreR.rotation.x=-1.6+u*1.2;b.chest.rotation.x=-.25;} + if(id==='xiangling'){r.root.rotation.y+=u*TAU*1.5;b.armR.rotation.set(-1.5,0,-.6);b.armL.rotation.set(-1.4,0,.6);b.weapon.rotation.set(0,PI/2,0);} + if(id==='barbara'){b.armL.rotation.set(-2.3,0,1.2*u);b.armR.rotation.set(-2.3,0,-1.2*u);b.head.rotation.x=-.35*u;b.chest.rotation.x=-.18*u;}} + if(act==='dodge'){b.chest.rotation.x=.55;b.legL.rotation.x=-.9;b.legR.rotation.x=.7;b.shinL.rotation.x=.9;b.shinR.rotation.x=.4;b.armL.rotation.set(.6,0,.4);b.armR.rotation.set(.6,0,-.4);b.hips.position.y-=.12;} + if(!p.grounded&&act!=='plunge'&&!swim){const up=(p.vy||0)>0;b.legL.rotation.x=up?-.9:-.4;b.shinL.rotation.x=up?1.3:.5;b.legR.rotation.x=up?-.2:.15;b.shinR.rotation.x=up?.6:.3;b.armL.rotation.set(-.5,0,.5);b.armR.rotation.set(-.6,0,-.5);} + if(act==='plunge'){b.armR.rotation.set(-2.9,0,0);b.armL.rotation.set(-2.6,0,.3);b.chest.rotation.x=.35;b.legL.rotation.x=-.6;b.shinL.rotation.x=.9;} + if((p.stun||0)>0&&act!=='dodge'&&!swim){const s=(p.stun||0)/15;b.chest.rotation.x-=.35*Math.min(1,s);b.head.rotation.x-=.25*Math.min(1,s);b.armL.rotation.z+=.4;b.armR.rotation.z-=.4;} + if(swim){r.root.rotation.x=1.2;const sw=Math.sin(tm*5);b.armL.rotation.set(-2.4+sw*1.1,0,.3);b.armR.rotation.set(-2.4-sw*1.1,0,-.3);b.legL.rotation.x=Math.sin(tm*9)*.35;b.legR.rotation.x=-Math.sin(tm*9)*.35;b.head.rotation.x=-.9;} + if(q.hp<=0){r.root.rotation.z=1.45;r.root.position.y=.18;} + if(b.book){b.book.position.y=.26+Math.sin(tm*2.3)*.05;b.book.rotation.set(-.3,Math.sin(tm*1.2)*.4+.5,0);if(act==='attack'||act==='charged'||act==='burst'){b.book.position.z=.36;b.book.rotation.x=-.9;}} + } + weaponTip(r,f=1){const W=HERO[r.id].weapon,b=r.bones;r.root.updateMatrixWorld(true);return v3(0,0,(W==='sword'?.86:1.5)*f+(W==='sword'?0:.0)).applyMatrix4(b.weapon.matrixWorld);} + // Weapon trail from the same pose function evaluated at the previous ticks (pure; no render history). + drawTrail(r,g){const p=g.player||{},act=String(p.action||''),W=HERO[r.id].weapon,tick=Number(p.actionTick||0);let n=0; + if((W==='sword'||W==='polearm')&&(act==='attack'||act==='charged'||act==='burst'&&r.id==='xiangling')&&tick<13){ + const color=new T.Color(r.id==='kaeya'?0x5ab8ff:0xff7a2a),samples=[];for(let k=0;k<7;k++){const t=tick-k*1.3;if(t<0)break;this.heroPose(r,g,t);const tip=this.weaponTip(r,1),base=this.weaponTip(r,.45);samples.push([tip,base]);} + this.heroPose(r,g); + for(let i=0;i+1.55&&!exposed)continue;let a=[x,y,z];const e=P[i];for(let k=1;k<=4;k++){const u=k/4,j=k<4?.22:0,h1=hash(i*97+k*7+Math.floor(g.t/2)),h2=hash(i*31+k*5+Math.floor(g.t/2)+3); + const nb=[lerp(x,e[0],u)+(h1-.5)*j,lerp(y,e[1],u)+(h2-.5)*j,lerp(z,e[2],u)+(h1-h2)*j];arc.set(a,n*3);arc.set(nb,n*3+3);n+=2;a=nb;}} + th.arcGeo.setDrawRange(0,n);th.arcGeo.attributes.position.needsUpdate=true; + let gi=this._gi;gi=this.glow(gi,x,y,z,dead||revival?0:exposed?2.3:1.6,exposed?0xa77ee8:0x6a4ab8);this._gi=gi; + th.baseRing.visible=!dead&&y<2;th.baseRing.position.set(x,.04,z);th.baseRing.scale.setScalar(exposed?2.8+Math.sin(tm*6)*.15:2.2);th.baseRing.material.opacity=exposed?.65:.32; + th.coreLight.position.set(x,y,z);th.coreLight.intensity=dead?0:exposed?3+Math.sin(tm*6)*.6:revival?1.3:.5; + let pn=0,pg=this._gi;for(const v of items(b.prisms)){if(!v.active||v.alive===false)continue;const s=.75+.25*(v.gauge||0)/(v.maxGauge||3);pn=this.place(th.prisms,pn,[v.x,(v.y||.8)+.45+Math.sin(tm*2+v.id)*.08,v.z],[s,s,s],[0,tm*.6+v.id,0]); + pg=this.glow(pg,v.x,(v.y||.8)+.5,v.z,1.6+.6*(v.gauge||0)/(v.maxGauge||3)+Math.sin(tm*5+v.id)*.15,0xa070ff); + for(let k=0;k<3;k++){const a=tm*1.6+k*TAU/3+v.id;pg=this.glow(pg,v.x+Math.sin(a)*.9,(v.y||.8)+.2+k*.35,v.z+Math.cos(a)*.9,.22,0xe0c8ff);}} + this._gi=pg;this.finish(th.prisms,pn); + // Lightning Lockdown pillars and the walls joining them. + const cam=this.camera.position,pp=g.player||{},occludes=(px,pz)=>{const ax=cam.x,az=cam.z,bx=pp.x||0,bz=pp.z||0,dx=bx-ax,dz=bz-az,l=dx*dx+dz*dz||1,t=clamp(((px-ax)*dx+(pz-az)*dz)/l,0,1);return t<.97&&Math.hypot(px-ax-t*dx,pz-az-t*dz)<1.6;}; + let pil=0,gh=0,wl=0;const pillars=items(g.hazards).filter(h=>h.kind==='pillar'&&h.gauge>0&&h.alive!==false); + for(const h of pillars){const up=(h.age||0)>=(h.delay||0),hh=h.height||4,rr=h.radius||.45,yy=up?hh/2:Math.max(.12,hh/2*((h.age||0)/(h.delay||1))-hh/2+.12); + if(occludes(h.x,h.z))gh=this.place(th.ghosts,gh,[h.x,yy,h.z],[rr*2,hh,rr*2]);else pil=this.place(th.pillars,pil,[h.x,yy,h.z],[rr*2,hh,rr*2]); + if(up){this._gi=this.glow(this._gi,h.x,hh+.2,h.z,.9+.2*Math.sin(tm*7+h.index),0xd0a8ff);const next=pillars.find(v=>v.cage===h.cage&&v.index===(h.index+1)%8&&(v.age||0)>=(v.delay||0)); + if(next){const dx=next.x-h.x,dz=next.z-h.z,l=Math.hypot(dx,dz);wl=this.place(th.walls,wl,[(h.x+next.x)/2,1.5,(h.z+next.z)/2],[l,3*(.85+.15*Math.sin(tm*13+h.index)),1],[0,Math.atan2(dx,dz)+PI/2,0]);}}} + this.finish(th.pillars,pil);this.finish(th.ghosts,gh);this.finish(th.walls,wl); + } + drawGuard(g,th){ + const b=g.boss||{},r=th.guard,bn=r.bones,tm=g.t/60,mode=b.mode||'idle',move=b.move,t=Number(b.moveTick||0),RG=root.GenshinGame&&root.GenshinGame.guard; + this.resetRig(r);r.root.position.set(b.x||0,b.y||0,b.z||0);r.root.rotation.y=b.yaw||0; + const walk=mode==='idle'&&b.action==='walk',ph=(b.walk||0)*2.4; + bn.thighL.rotation.x=walk?-Math.sin(ph)*.38:0;bn.thighR.rotation.x=walk?Math.sin(ph)*.38:0;bn.shinL.rotation.x=walk?Math.max(0,Math.sin(ph+1))*.4:0;bn.shinR.rotation.x=walk?Math.max(0,-Math.sin(ph+1))*.4:0; + bn.hips.position.y+=walk?Math.abs(Math.sin(ph))*.08:Math.sin(tm*1.5)*.02;bn.upper.rotation.set(.04,walk?Math.sin(ph)*.06:0,walk?Math.sin(ph)*.04:0); + bn.armL.rotation.set(walk?Math.sin(ph)*.25:.05,0,.12);bn.armR.rotation.set(walk?-Math.sin(ph)*.25:.05,0,-.12);bn.foreL.rotation.x=-.25;bn.foreR.rotation.x=-.25; + bn.upper.rotation.y+=Number(b.upper||0); + const M=RG?RG.moves:null,tell=Number(b.tellTicks||30); + if(mode==='attack'&&M){ + if(move==='stomp'){const raise=t=tell?Math.min(1,(t-tell)/5):0;bn.upper.rotation.x=.55*u;bn.armL.rotation.set(-1.1*u,0,lerp(1.3*u,.15,shut));bn.armR.rotation.set(-1.1*u,0,-lerp(1.3*u,.15,shut));bn.foreL.rotation.x=-.2;bn.foreR.rotation.x=-.2;} + if(move==='combo'){const P=M.combo.punches,sh=tell-M.combo.tell; + if(t.05;bn.thighL.rotation.x=air?-.6:-.9;bn.thighR.rotation.x=air?-.6:-.9;bn.shinL.rotation.x=1;bn.shinR.rotation.x=1;bn.armL.rotation.set(-2.6,0,.3);bn.armR.rotation.set(-2.6,0,-.3);if(!air)bn.hips.position.y-=.35;}} + if(move==='spin'){const u=t0,live=!para&&mode!=='dead'; + th.eyeMat.color.set(live?(rune?0xffd78a:0xffa53a):0x3a2a20);th.socketMat.color.set(live?(move==='volley'&&mode==='attack'?0xa8fff4:0x4fe0d0):0x1e3a38); + th.lineMat.color.set(live?0x5ff0e0:0x24403e); + let rn=0;if(rune&&live){r.root.updateMatrixWorld(true);const e=v3(0,0,.5).applyMatrix4(bn.head.matrixWorld),s=v3(0,1.02,-1).applyMatrix4(bn.upper.matrixWorld); + rn=this.place(th.runeRing,rn,[e.x,e.y,e.z],[.32,.32,.32],this.camQ,0x6ff6e6);rn=this.place(th.runeRing,rn,[s.x,s.y,s.z],[.4,.4,.4],this.camQ,0x6ff6e6);} + this.finish(th.runeRing,rn); + if(live&&!rune){r.root.updateMatrixWorld(true);const e=v3(0,0,.5).applyMatrix4(bn.head.matrixWorld);this._gi=this.glow(this._gi,e.x,e.y,e.z,.75+Math.sin(tm*6)*.08,0xffb050); + if(move==='volley'&&mode==='attack'){const s=v3(0,1.02,-1).applyMatrix4(bn.upper.matrixWorld);this._gi=this.glow(this._gi,s.x,s.y,s.z,.95,0x7ff8ea);}} + const ch=b.crosshair;th.crosshair.visible=!!ch;if(ch){th.crosshair.position.set(ch.x,.07,ch.z);th.crosshair.scale.setScalar(1.6+Math.sin(tm*10)*.1);th.crosshair.rotation.z=tm*1.5;} + if((b.frozen||0)>0){let n=0;for(let i=0;i<9;i++){const a=i*2.3,h=.4+(i%3)*1.1;n=this.place(this.iceShell,n,[(b.x||0)+Math.sin(a)*.9,h,(b.z||0)+Math.cos(a)*.9],[.55,.7,.55],[a,i,0]);}this._ice=n;}else this._ice=0; + } + drawLake(g,th){ + const b=g.boss||{},tm=g.t/60,OC=root.GenshinGame&&root.GenshinGame.oceanid; + th.ripple.offset.set((g.t*.0009)%1,(g.t*.0006)%1); + for(let i=0;i<9;i++){const sunk=!!(b.tiles&&b.tiles[i]),m=th.tiles[i],x=(i%3-1)*7,z=(Math.floor(i/3)-1)*7;m.position.set(x,sunk?-1.45:-.35,z);} + let tg=0;for(const i of items(b.warn)){const x=(i%3-1)*7,z=(Math.floor(i/3)-1)*7,pulse=.5+.5*Math.sin(tm*12);tg=this.place(th.tileGlow,tg,[x,.06,z],[6.9,.08+pulse*.06,6.9]); + this.surfaceTriangle([x-3.45,z-3.45],[x+3.45,z-3.45],[x+3.45,z+3.45],0x3fb8ff,.07);this.surfaceTriangle([x-3.45,z-3.45],[x+3.45,z+3.45],[x-3.45,z+3.45],0x3fb8ff,.07);} + this.finish(th.tileGlow,tg); + const sway=Math.sin(tm*1.3)*.15;th.oceanid.position.set(b.x||0,(b.y||1.2)+.2+Math.sin(tm*1.7)*.12,b.z||-15);th.oceanid.rotation.set(sway*.2,PI*0+Math.atan2(-(b.x||0),-(b.z||-15))*0,sway*.1); + th.oceanid.scale.setScalar(2.3+(b.action==='summon'?.08*Math.sin(Math.min(1,(b.moveTick||0)/30)*PI):0));th.oceanid.visible=b.mode!=='dead'; + th.oceanidGlow.position.set(th.oceanid.position.x,th.oceanid.position.y+1.1,th.oceanid.position.z);th.oceanidGlow.quaternion.copy(this.camQ);th.oceanidGlow.scale.setScalar(b.mode==='dead'?0:4.2+Math.sin(tm*2)*.3); + let on=0;for(const o of items(b.orbs)){if(o.t<0||o.done)continue;const u=o.t/(OC?OC.orbTicks:40),x=lerp(o.from.x,o.x,u),z=lerp(o.from.z,o.z,u),y=lerp(2.6,.6,u)+Math.sin(u*PI)*5;on=this.place(th.orbs,on,[x,y,z],[.55,.55,.55]);this._gi=this.glow(this._gi,x,y,z,1.6,0x6fd8ff);} + this.finish(th.orbs,on); + const count={},wn=[];let wc=0,ice=this._ice||0;for(const k of Object.keys(th.mimics))count[k]=0; + for(const m of items(g.mimics)){if(m.hp<=0)continue;const pool=th.mimics[m.type];if(!pool)continue;const form=m.mode==='form'?clamp(1-(m.timer||0)/30,0,1):1,s=(.35+.65*ease(form))*(m.type==='frog'||m.type==='finch'?1.15:1); + const bob=m.type==='raptor'?Math.sin(tm*5+m.id)*.1:0,tilt=m.mode==='tell'?-.15:m.mode==='attack'?.25:0; + count[m.type]=this.place(pool,count[m.type],[m.x,(m.y||0)+bob,m.z],[s,s,s],[tilt,m.yaw||0,0]); + const W=WINGED[m.type];if(W){const flap=(m.frozen||0)>0?0:Math.sin(tm*(m.type==='raptor'?9:m.type==='crane'?6:12)+m.id)*(m.type==='mallard'?.25:.6);for(const sd of [-1,1]){const a=(m.yaw||0),cx=m.x+Math.cos(a)*sd*.18*s,cz=m.z-Math.sin(a)*sd*.18*s; + wc=this.place(th.wings,wc,[cx,(m.y||0)+bob+W.y*s,cz],[W.span*s*sd,s,s],[0,a+(sd<0?0:0),sd*flap]);}} + if((m.frozen||0)>0)ice=this.place(this.iceShell,ice,[m.x,(m.y||0)+m.cy,m.z],[m.r*1.25,m.hh*1.3,m.r*1.25],[m.id,0,m.id*.7]); + if(m.mode==='form')this._gi=this.glow(this._gi,m.x,.6,m.z,2.4*(1-form)+.4,0x7fe0ff); + if(m.mode==='tell')this.mimicTell(m);} + for(const [k,pool] of Object.entries(th.mimics))this.finish(pool,count[k]);this.finish(th.wings,wc);this._ice=ice; + // Rain streaks: deterministic loop of falling positions around the play area. + let rn=0;const P=g.player||{};for(let i=0;i<260;i++){const fall=((g.t*.55+hash(i)*60)%60)/60,x=(P.x||0)+(hash(i*3+1)-.5)*34,z=(P.z||0)+(hash(i*3+2)-.5)*34;rn=this.place(th.rain,rn,[x,14-fall*15,z],[.02,.9,.02],[.08,0,.04]);} + this.finish(th.rain,rn); + let bn=0,sw=0,wcr=0;for(const h of items(g.hazards)){ + if(h.bomb){const u=clamp((h.age||0)/(h.delay||90),0,1);bn=this.place(th.bombs,bn,[h.x,.6+u*.4,h.z],[.6+u*1.6,.6+u*1.2,.6+u*1.6]);} + if(h.whirl||h.vortex){sw=this.place(th.swirls,sw,[h.x,.09,h.z],[(h.radius||2)*2.1,(h.radius||2)*2.1,1],[-PI/2,0,tm*(h.whirl?3:5)]);} + if(h.wave){const a=Math.atan2(h.vx||0,h.vz||0);wcr=this.place(th.waveCrest,wcr,[h.x,.1,h.z],[.9,1.6,.9],[0,a+PI/2,PI/2]);} + if(h.stream){for(let k=1;k<=6;k++){const d=k*.75,bx=h.x+Math.sin(h.angle)*d,bz=h.z+Math.cos(h.angle)*d;this._gi=this.glow(this._gi,bx,.7+Math.sin(tm*9+k)*.1,bz,.35,0xbff0ff);}}} + this.finish(th.bombs,bn);this.finish(th.swirls,sw);this.finish(th.waveCrest,wcr); + } + mimicTell(m){const a=m.yaw||0,fx=Math.sin(a),fz=Math.cos(a),lane=(len,w,col)=>{const sx=fz*w,sz=-fx*w,ex=m.x+fx*len,ez=m.z+fz*len;this.surfaceTriangle([m.x+sx,m.z+sz],[ex+sx,ez+sz],[ex-sx,ez-sz],col);this.surfaceTriangle([m.x+sx,m.z+sz],[ex-sx,ez-sz],[m.x-sx,m.z-sz],col);}; + // Boar ram 9 m/s x16 ticks, charge 11 m/s x56 ticks (sweep radius .9); squirrel sweep 2.6 m cone; crane/frog wave 9/8 m/s lane. + if(m.type==='boar')lane(m.move==='ram'?2.4:10.3,.9,0x5fb8ff); + if(m.type==='squirrel'&&m.move==='sweep')this.area(m.x,m.z,2.6,0x5fb8ff,1.1,a); + if((m.type==='crane'||m.type==='frog')&&m.move==='wave')lane(m.type==='crane'?16:14,.8,0x5fb8ff);} + // ---------------------------------------------------------------------------------------------- hazards, effects, summons + drawWorld(g){ + let bm=0,bolt=0,arrow=0,spike=this._spikeStart||0,fire=0,ring=0,fr=0,col=0,sh=0; + // Arena plugins tint hazards by element; the built-in arenas keep their fixed palettes. + const plug=Object.values(PLUGINS).some(q=>q.match(String(g.id))),tint=(el,fallback)=>plug&&EL[el]||fallback; + const tm=g.t/60,p=g.player||{},pal=g.id&&g.id.includes('ruin')?{w:0xffb070,a:0xff6a3a}:g.id&&g.id.includes('oceanid')?{w:0x6fd0ff,a:0x2a90ff}:{w:0xf2bd6d,a:0xb070ff}; + for(const h of items(g.hazards)){const k=h.kind,warning=(h.age||0)<(h.delay||0),x=h.x||0,z=h.z||0,a=h.angle||0; + const heat=warning?clamp((h.age||0)/(h.delay||1),0,1):1,color=warning?(heat>.7?0xff5a3a:pal.w):tint(h.element,pal.a); + if(k==='pillar'||h.whirl||h.vortex&&!warning)continue; + if(k==='circle'){const r=h.radius||1;if(h.lightning&&!warning){col=this.place(this.columns,col,[x,(h.height||8)/2,z],[r,h.height||8,r],[0,0,0],0xc8a0ff);} + if(h.spin){this.sector(x,z,Math.max(0,r-.35),r+.05,0,TAU,0xffa060);continue;} + if(h.bomb){this.area(x,z,r,warning?(heat>.6?0x2a7fff:0x5fc8ff):0x2a90ff);continue;} + this.area(x,z,r,color,h.half||PI,a);} + else if(k==='square'){const s=h.half||3.5;this.surfaceTriangle([x-s,z-s],[x+s,z-s],[x+s,z+s],0x2a90ff,.07);this.surfaceTriangle([x-s,z-s],[x+s,z+s],[x-s,z+s],0x2a90ff,.07);} + else if(k==='ring'){const r=h.radius||1,w=h.width||.5,gap=h.gap||0;if(gap){for(let i=0;i<8;i++)this.sector(x,z,Math.max(0,r-w),r+w,a+i*PI/4+gap,a+(i+1)*PI/4-gap,color);}else this.sector(x,z,Math.max(0,r-w),r+w,0,TAU,color); + if(!warning&&!gap)ring=this.place(this.rings,ring,[x,.4,z],[r,r,r],[-PI/2,0,0],tint(h.element,0xc8a0ff));} + else if(k==='sweep'){const tx=h.toX??x,tz=h.toZ??z,r=h.radius||1.7,an=Math.atan2(tx-x,tz-z),sx=Math.cos(an)*r,sz=-Math.sin(an)*r;this.surfaceTriangle([x+sx,z+sz],[tx+sx,tz+sz],[tx-sx,tz-sz],color);this.surfaceTriangle([x+sx,z+sz],[tx-sx,tz-sz],[x-sx,z-sz],color);this.sector(x,z,0,r,an+PI/2,an+PI*1.5,color);this.sector(tx,tz,0,r,an-PI/2,an+PI/2,color);} + else if(k==='beam'){if(h.stream){this.sector(x,z,0,h.length||4,a-.12,a+.12,0x6fd0ff);continue;} + const outer=h.length||8,inner=h.inner||0,len=outer-inner,c=(inner+outer)/2,cx=x+Math.sin(a)*c,cz=z+Math.cos(a)*c; + bm=this.place(this.beams,bm,[cx,warning?.035:.55+(h.height||1.3)/2-.2,cz],[2*(h.width||.7),warning?.04:(h.height||1.3),len],[0,a,0],warning?pal.w:tint(h.element,0xb37dff)); + if(!warning)for(let j=0;j<3;j++)this._gi=this.glow(this._gi,cx+Math.sin(a)*(j-1)*len*.33,1,cz+Math.cos(a)*(j-1)*len*.33,1.4,tint(h.element,0xd0a0ff));} + else if(k==='bolt'){if(h.missile){const q=this.dir(h.vx||0,0,h.vz||0);bolt=this.place(this.bolts,bolt,[x,h.y||1,z],[.16,.16,.42],q,0x4a4440);this._gi=this.glow(this._gi,x-(h.vx||0)*3,(h.y||1),z-(h.vz||0)*3,.8,0xff8a3a);this._gi=this.glow(this._gi,x-(h.vx||0)*7,(h.y||1)+.05,z-(h.vz||0)*7,.5,0x9a948c);} + else if(h.wave){} + else{const s=plug?Math.max(.22,(h.radius||.4)*.62):.32;bolt=this.place(this.bolts,bolt,[x,Math.max(.2,h.y||1),z],[s,s,s],[tm*3,tm*2,0],tint(h.element,0xd4b4ff));this._gi=this.glow(this._gi,x,Math.max(.2,h.y||1),z,plug?.9+s:.9,tint(h.element,0xb88cff));}} + } + // Telegraphs drawn from the same tuning the rules use: lunge lanes and clap / scissors / palm sectors (Electro Hypostasis). + const M=root.GenshinGame,bb=g.boss||{}; + if(g.id==='genshin/electro_hypostasis'&&M&&bb.move&&(bb.mode==='tell'||bb.mode==='attack')){const TU=M.tuning,yaw=bb.yaw||0,bx=bb.originX??bb.x,bz=bb.originZ??bb.z,L=TU.lunge[bb.move],tell=bb.tellTicks||TU.moves[bb.move].tell, + heat=bb.mode==='tell'?1-(bb.timer||0)/tell:1,c2=heat>.7?0xff5a3a:0xf2bd6d; + if(L&&bb.mode==='tell'){const len=L.speed*L.ticks/60,w=L.radius+.4,fx=Math.sin(yaw),fz=Math.cos(yaw),sx=fz*w,sz=-fx*w,ex=bx+fx*len,ez=bz+fz*len;this.surfaceTriangle([bx+sx,bz+sz],[ex+sx,ez+sz],[ex-sx,ez-sz],c2);this.surfaceTriangle([bx+sx,bz+sz],[ex-sx,ez-sz],[bx-sx,bz-sz],c2);} + const cone=(c,start)=>{const t=bb.mode==='attack'?(bb.moveTick||0):-1;if(bb.mode==='attack'&&t=c.at-start)this.area(bb.x||0,bb.z||0,c.radius+.4,t>c.at-10?0xff5a3a:0xf2bd6d,c.half,yaw);}; + if(bb.move==='clap'){if(bb.mode==='tell')this.area(bb.x||0,bb.z||0,TU.cones.clap.radius+.4,c2,TU.cones.clap.half,yaw);cone(TU.cones.clap,18);} + if(bb.move==='rps'){cone(TU.cones.rpsScissors,24);cone(TU.cones.rpsPalm,30);}} + // Ruin Guard telegraphs: stomp foot circle, clap cone and punch arcs during their wind-ups (same tuning as the rules). + if(g.id==='genshin/ruin_guard'&&M&&bb.mode==='attack'){const R=M.guard.moves,t=bb.moveTick||0,tell=bb.tellTicks||30,fx=Math.sin(bb.yaw||0),fz=Math.cos(bb.yaw||0),hot=u=>u>.7?0xff5a3a:0xffb070; + if(bb.move==='stomp'&&t=at+sh-24)this.area(bb.x,bb.z,R.combo.radius,hot(1-(at+sh-t)/24),R.combo.half,bb.yaw);} + if(bb.move==='spin'&&ts.kind==='bunny'&&!(s.hp<=0)),guoba=items(g.summons).find(s=>s.kind==='guoba'); + this.bunny.visible=!!bunny;if(bunny){const yaw=Math.floor((bunny.age||0)/120)*PI+Math.sin((bunny.age||0)*.2)*.25;this.bunny.position.set(bunny.x,0,bunny.z);this.bunny.rotation.y=yaw;this.bunny.scale.setScalar(1+Math.max(0,((bunny.age||0)-430)/50)*.25);} + this.guoba.visible=!!guoba;if(guoba){this.guoba.position.set(guoba.x,Math.abs(Math.sin((guoba.age||0)*.12))*.06,guoba.z);this.guoba.rotation.y=guoba.yaw||0;} + // Auras: icicles, Pyronado, Melody Loop, Fiery Rain. + for(const a of items(g.auras)){const k=a.kind,an=a.angle||0; + if(k==='icicles')for(let i=0;i<3;i++){const yw=an+i*TAU/3,x=(p.x||0)+Math.sin(yw)*2.4,z=(p.z||0)+Math.cos(yw)*2.4;spike=this.place(this.spikes,spike,[x,.9,z],[.16,.16,.95],this.dir(Math.cos(yw),0,-Math.sin(yw)),0xffffff);this._gi=this.glow(this._gi,x,.9,z,.9,0x9fe6ff);} + if(k==='pyronado'){const x=(p.x||0)+Math.sin(an)*3.4,z=(p.z||0)+Math.cos(an)*3.4;for(let j=0;j<5;j++){const aa=j*TAU/5+g.t*.2;fire=this.place(this.fireCones,fire,[x+Math.sin(aa)*.32,.7+Math.sin(g.t*.15+j)*.1,z+Math.cos(aa)*.32],[.22,.22,.95],this.dir(Math.sin(aa)*.3,1,Math.cos(aa)*.3),0xff6a2a);} + this._gi=this.glow(this._gi,x,1,z,2.2,0xff8a3a);this.sector(p.x||0,p.z||0,3.3,3.5,an-.6,an+.6,0xff8a3a);} + if(k==='melody'){fr=this.place(this.flatRings,fr,[p.x||0,.06,p.z||0],[1.65,1.65,1],[-PI/2,0,0],0x6fc8ff);for(let i=0;i<6;i++){const yw=i*PI/3+g.t*.03;this._gi=this.glow(this._gi,(p.x||0)+Math.sin(yw)*1.6,.9+Math.sin(tm*3+i)*.15,(p.z||0)+Math.cos(yw)*1.6,.35,0x9fe0ff);}} + if(k==='rain'){fr=this.place(this.flatRings,fr,[a.x||0,.06,a.z||0],[2.6,2.6,1],[-PI/2,0,0],0xff9a50);} + } + // Elemental particles / orbs / pickups. + for(const q of [...items(g.particles),...items(g.pickups)]){if(q.dead)continue;const c=q.kind==='pepper'?0xff5a3a:EL[q.element]||0xfff0c8,s=q.orb?.5:.32,y=.65+Math.sin((g.t+(q.id||0))*.15)*.08; + this._gi=this.glow(this._gi,q.x,y,q.z,s*2.1,c);sh=this.place(this.shards,sh,[q.x,y,q.z],[s*.35,s*.5,s*.35],[0,g.t*.05,0],c);} + const wet=items(g.party)[p.active||0];if(wet&&wet.wet>0)for(let i=0;i<3;i++)this._gi=this.glow(this._gi,(p.x||0)+Math.sin(tm*3+i*2.1)*.3,(p.y||0)+1.95+i*.05,(p.z||0)+Math.cos(tm*3+i*2.1)*.3,.18,0x63b7ff); + this.finish(this.beams,bm);this.finish(this.bolts,bolt);this.finish(this.arrows,arrow);this.finish(this.spikes,spike);this.finish(this.fireCones,fire);this.finish(this.rings,ring);this.finish(this.flatRings,fr);this.finish(this.columns,col);this.finish(this.shards,sh); + this.finish(this.iceShell,this._ice||0); + } + // ---------------------------------------------------------------------------------------------- frame + render(g,ctx){ + if(this.closed||this.renderer.getContext().isContextLost()){this.ready=false;this.error=this.closed?'3D renderer is closed':'WebGL context lost';throw Error(this.error);}const start=performance.now(); + try{const id=String(g.id||'genshin/electro_hypostasis'),th=this.ensureTheme(id),p=g.player||{},b=g.boss||{}; + const yaw=p.cameraYaw!==undefined?p.cameraYaw:Math.atan2((b.x||0)-(p.x||0),(b.z||0)-(p.z||0)); + const cfg=th.plugin?th.plugin.camera:th.key==='ruins'?{d:8.4,h:4.1,look:1.5}:th.key==='lake'?{d:8.2,h:4.6,look:1.1}:{d:7.6,h:3.7,look:1.05}; + const dx=Math.sin(yaw),dz=Math.cos(yaw),px=p.x||0,pz=p.z||0,py=(p.y||0)*(p.swimming?0:1); + let boom=cfg.d;const lim=th.plugin?th.plugin.camera.lim:th.key==='ruins'?20.4:th.key==='cape'?20.6:1e9; + for(let k=0;k<24&&boom>3.2;k++){if(Math.hypot(px-dx*boom+dz*.7,pz-dz*boom-dx*.7)<=lim)break;boom-=.25;} + const M=root.GenshinGame,lockPos=[px-dx*boom+dz*.7,cfg.h-(cfg.d-boom)*.12+py*.55,pz-dz*boom-dx*.7],lockAt=[px+dx*3,cfg.look+py*.3,pz+dz*3]; + let pos=lockPos,at=lockAt; + if(M&&M.aimOrigin){ + // genshin-bosses@7: the default view is this follow camera, free or locked (the mouse turns it through cameraYaw while + // unlocked). The over-the-shoulder camera on the arrow ray (aimOrigin + yaw/pitch, screen centre = aim point) is the + // bow's aim mode only, as in the original: the bow user, unlocked, charging or just after the shot (aimWeight below). + const w=aimWeight(g); + if(w>0){const o=M.aimOrigin(p),pitch=Number(p.aimPitch||0),fx=Math.sin(yaw)*Math.cos(pitch),fy=Math.sin(pitch),fz=Math.cos(yaw)*Math.cos(pitch),back=3.4; + const aimPos=[o.x-fx*back,o.y-fy*back+.12,o.z-fz*back],aimAt=[o.x+fx*20,o.y+fy*20,o.z+fz*20],u=ease(w); + pos=lockPos.map((v,i)=>lerp(v,aimPos[i],u));at=lockAt.map((v,i)=>lerp(v,aimAt[i],u));}} + this.camera.position.set(pos[0],pos[1],pos[2]);this.camera.lookAt(at[0],at[1],at[2]);this.camera.updateMatrixWorld();this.camQ.copy(this.camera.quaternion); + if(this.world.fog!==th.fogObj)this.world.fog=th.fogObj; + this.sun.position.set(px-9,18,pz+8);this.sun.target.position.set(px,0,pz);this.sun.target.updateMatrixWorld(); + this.hemi.intensity=th.plugin?th.plugin.light.hemi:th.key==='lake'?1.25:1.45;this.sun.intensity=th.plugin?th.plugin.light.sun:th.key==='lake'?1.35:2.25; + this.surfaceN=0;this._gi=0;this._ice=0; + const q=items(g.party)[p.active||0]||{};for(const [k,r] of Object.entries(this.heroes))r.root.visible=k===q.id;const hero=this.heroes[q.id]; + if(hero){this.heroPose(hero,g);this.drawTrail(hero,g);} + if(th.plugin)th.plugin.draw(this,g,th);else if(th.key==='cape')this.drawHypostasis(g,th);else if(th.key==='ruins')this.drawGuard(g,th);else this.drawLake(g,th); + this.drawWorld(g); + this.finish(this.glows,this._gi); + this.surfaceGeo.setDrawRange(0,this.surfaceN);this.surfaceGeo.attributes.position.needsUpdate=true;this.surfaceGeo.attributes.color.needsUpdate=true; + // The first frame after a theme switch (or construction) renders twice: light-set changes settle on the first pass, so the + // returned image is identical to any later render of the same state (render purity). + if(this.lastTheme!==th){this.renderer.render(this.world,this.camera);this.lastTheme=th;} + this.renderer.info.reset();this.renderer.render(this.world,this.camera);ctx.drawImage(this.view,0,0,854,480); + this.times.push(performance.now()-start);if(this.times.length>120)this.times.shift();this.ready=true;this.error=null; + }catch(e){this.ready=false;this.error=String(e);throw e;} + } + project(x,y,z){const p=new T.Vector3(x,y,z).project(this.camera);if(p.z>1||p.z<-1)return null;return {x:(p.x+1)*427,y:(1-p.y)*240};} + metrics(){ + const info=this.renderer.info,sorted=[...this.times].sort((a,b)=>a-b);let geometryBytes=0,textureBytes=0; + for(const r of this.resources){if(r.isBufferGeometry){for(const a of Object.values(r.attributes))geometryBytes+=a.array.byteLength;if(r.index)geometryBytes+=r.index.array.byteLength;}if(r.isTexture&&r.image)textureBytes+=(r.image.width||0)*(r.image.height||0)*4;if(r.isInstancedMesh)geometryBytes+=r.instanceMatrix.array.byteLength;} + return {renderer:'webgl-boss3d',webglVersion:this.renderer.capabilities.isWebGL2?2:1,drawCalls:info.render.calls,triangles:info.render.triangles,geometries:info.memory.geometries,textures:info.memory.textures,geometryBytes,textureBytes,shadowMapBytes:1024*1024*4,canvasBytes:854*480*4,resourceBytesEstimate:geometryBytes+textureBytes+1024*1024*4+854*480*8,staticAssetBytes:669884,renderSamples:sorted.length,cpuRenderMsP50:sorted.length?sorted[Math.floor((sorted.length-1)*.5)]:null,cpuRenderMsP95:sorted.length?sorted[Math.floor((sorted.length-1)*.95)]:null,shadows:'one 1024x1024 directional map; characters and bosses cast',postprocess:false,themes:Object.keys(this.themes)}; + } + close(){if(this.closed)return;this.closed=true;this.ready=false;this.resources.forEach(r=>r.dispose?.());this.renderer.dispose();this.renderer.forceContextLoss();this.resources.clear();} + } + // genshin-bosses@7 camera, a pure read of the state (render purity): weight 0..1 of the bow's over-the-shoulder aim view. + // In the original, holding Normal Attack puts a bow user in Aiming Mode. Here: the bow user, unlocked, while charging (LMB held, + // in over 3 ticks) and after the aimed shot while its 18-tick cooldown runs (normalCD: full through tick 6, out by tick 17). The + // cooldown, not the action tick, drives the fade so pressing LMB again mid-fade (action becomes 'aim') does not bounce the view. + // lockBlend (ticks since the last R toggle) eases a toggle: unlocking ramps the view in; locking eases out of the weight the bow + // user had at the toggle (w evaluated lockBlend ticks earlier). Locked (settled), swimming, other characters: 0. + function aimWeight(g){const p=g&&g.player;if(!p||g.outcome||p.swimming)return 0;const q=items(g.party)[p.active||0];if(!q||q.weapon!=='bow')return 0; + const ct=Number(p.chargeTicks||0),cd=Number(p.normalCD||0),shot=p.action==='bow'||p.action==='aim',lb=clamp(Number(p.lockBlend??12),0,12),u=lb/12; + const w=dt=>Math.max(ct>dt?clamp((ct-dt)/3,0,1):0,shot&&cd>0&&cd+dt<=18?clamp((cd+dt-1)/11,0,1):0); + return p.lockon===false?w(0)*u:w(lb)*(1-u);} + B.aimWeight=aimWeight; + B.registerArena=function(key,plugin){PLUGINS[key]=plugin;}; + B.render=function(style,g,ctx){let m=byCanvas.get(ctx.canvas);if(!m){m=new Map();byCanvas.set(ctx.canvas,m);}let scene=m.get(style);if(!scene||scene.closed){scene=new Scene(style,ctx.canvas);m.set(style,scene);}scene.render(g,ctx);return scene;}; + // Read-only access for HUD overlays: projects a world point with the camera of the last rendered frame. + B.scene=function(ctx,style){const s=ctx&&byCanvas.get(ctx.canvas)?.get(style);return s&&!s.closed?s:null;}; + B.status=function(style,ctx){const s=ctx&&byCanvas.get(ctx.canvas)?.get(style);if(s&&!s.closed&&s.renderer.getContext().isContextLost()){s.ready=false;s.error='WebGL context lost';}return {renderer:'webgl-boss3d',kind:'perspective',ready:!!s?.ready&&!s.closed,error:s?.error||null};}; + B.metrics=function(style,ctx){const s=ctx&&byCanvas.get(ctx.canvas)?.get(style);return s?s.metrics():null;}; + B.close=function(style,ctx){const m=ctx&&byCanvas.get(ctx.canvas),s=m?.get(style);if(s){s.close();m.delete(style);}}; +})(window); diff --git a/environments/games/web/games/genshin_remake/style3d.css b/environments/games/web/games/genshin_remake/style3d.css new file mode 100644 index 0000000000000000000000000000000000000000..df673172470e9188762c19cb2ab95c394082b9f0 --- /dev/null +++ b/environments/games/web/games/genshin_remake/style3d.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#14191a;--panel:#1d2425;--edge:#354141;--text:#ebe7dc;--muted:#a5b2ad;--accent:#dfb676}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top,#29312b,transparent 60%),var(--bg);color:var(--text);font:14px/1.7 'Segoe UI','Microsoft YaHei',sans-serif}body[data-game=genshin_remake]{--bg:#101822;--panel:#1b2530;--edge:#374754;--accent:#baacff;background:radial-gradient(ellipse at top,#2b2942,transparent 60%),var(--bg)}main{max-width:1220px;margin:auto;padding:28px 24px 40px}header{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:20px}.eyebrow{color:var(--accent);font-size:11px;letter-spacing:2.5px;text-transform:uppercase}h1{font:500 32px/1.35 Georgia,'Microsoft YaHei',serif;letter-spacing:1px;margin:6px 0}header p{color:var(--muted);margin:0;font-size:13px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.layout{display:grid;grid-template-columns:minmax(0,854px) 245px;gap:24px;align-items:start}.stage{position:relative;border:1px solid var(--edge);box-shadow:0 22px 55px #0005;background:#111b1c}canvas{display:block;width:100%;aspect-ratio:854/480;touch-action:none;outline:none}canvas:focus-visible{outline:2px solid var(--accent);outline-offset:3px}#overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#10171b30;pointer-events:none}#overlay[hidden]{display:none}#overlay div{background:#111b23de;padding:19px 32px;border:1px solid #9ba6a655;max-width:80%;text-align:center}#overlay strong{font:500 24px Georgia,'Microsoft YaHei',serif;display:block}#overlay span{display:block;color:var(--muted);font-size:12px;margin-top:7px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;padding:12px;background:var(--panel);border-top:1px solid var(--edge)}button,select,input{font:inherit;background:var(--panel);color:var(--text);border:1px solid var(--edge);border-radius:4px;padding:7px 11px}button{cursor:pointer}button:hover{border-color:var(--accent);background:#ffffff09}button.primary{background:var(--accent);color:var(--bg);font-weight:600}button:focus-visible,select:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}aside{padding:19px;border:1px solid var(--edge);background:var(--panel)}h2{font-size:16px;margin:0 0 8px}label{display:block;font-size:12px;color:var(--muted);margin:12px 0 5px}select,input{width:100%}dl{border-top:1px solid var(--edge);padding-top:16px;margin:18px 0 0}dt{color:var(--accent);font:12px/1.8 Consolas,monospace}dd{color:var(--muted);font-size:12px;margin:0 0 10px}.note{color:var(--muted);font-size:12px}#status{min-height:25px;margin:10px 0;color:var(--accent);overflow-wrap:anywhere}.record-toolbar{border:1px solid var(--edge);padding:10px;background:transparent}.record-toolbar button{font-size:12px}#file{display:none}.mobile{display:none}footer{display:flex;flex-wrap:wrap;gap:22px;border-top:1px solid var(--edge);margin-top:28px;padding-top:15px;font-size:12px}@media(max-width:950px){main{padding:14px}.layout{grid-template-columns:1fr}aside{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}aside dl,aside .note{grid-column:1/-1}dl{columns:2}.mobile{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.mobile button{min-width:45px;touch-action:none}header{align-items:start}h1{font-size:26px}}@media(max-width:500px){header{display:block}header a{font-size:12px}aside{padding:14px}#overlay div{padding:14px 20px}#overlay strong{font-size:19px}.toolbar{gap:6px;padding:8px}button{font-size:12px}h1{font-size:25px}} diff --git a/environments/games/web/games/hexen2_remake/art_death.js b/environments/games/web/games/hexen2_remake/art_death.js new file mode 100644 index 0000000000000000000000000000000000000000..023ae2aa057f65eaf905e2656339e84e594c126d --- /dev/null +++ b/environments/games/web/games/hexen2_remake/art_death.js @@ -0,0 +1,34 @@ +/* Hexen II boss arenas - original procedural model of Death (BossBench art, no Hexen II model data): a skeletal black horse running on air, a robed rider with a scythe. Reads the state only. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Hexen2Game, Q = M.Q, R = M.R3, { part, bx, cy, S } = R; + R.MODELS.death = { + build(sc) { + const root = new T.Group(); root.scale.setScalar(S); + const coal = sc.std(0x24222c), bone = sc.std(0xd8d4c0), robe = sc.std(0x14121c), steel = sc.std(0x9aa0b0, { metalness: 0.7, roughness: 0.3 }), ember = sc.glow(0x60ff80, 1); + const h = R.horse(sc, coal, { girth: 0.85, len: 1.1, legLen: 1, mane: sc.glow(0x70ff90, 0.8) }); root.add(h.root); + for (let i = 0; i < 7; i++) part(sc, h.body, bx(3, 24, 31), bone, -24 + i * 8, 4, 0); + part(sc, h.head, bx(30, 8, 13), bone, 11, 0, 0, [0, 0, -0.35]); + part(sc, h.head, new T.SphereGeometry(1.8, 6, 4), ember, 12, 3, 6); part(sc, h.head, new T.SphereGeometry(1.8, 6, 4), ember, 12, 3, -6); + const rider = new T.Group(); rider.position.set(-6, 20, 0); h.body.add(rider); + part(sc, rider, cy(11, 20, 50, 8), robe, 0, 24, 0); + const hood = new T.Group(); hood.position.set(2, 56, 0); rider.add(hood); + part(sc, hood, new T.ConeGeometry(12, 26, 8), robe, -1, 7, 0); part(sc, hood, new T.SphereGeometry(7, 8, 6), bone, 3, 0, 0); + part(sc, hood, new T.SphereGeometry(1.5, 6, 4), ember, 9, 1, 2.8); part(sc, hood, new T.SphereGeometry(1.5, 6, 4), ember, 9, 1, -2.8); + const arm = new T.Group(); arm.position.set(2, 42, 14); rider.add(arm); + part(sc, arm, cy(2.4, 1.8, 26, 5), bone, 8, 0, 0, [0, 0, -1.3]); + part(sc, arm, cy(1.6, 1.6, 110, 6), steel, 20, 10, 0); + part(sc, arm, bx(52, 7, 2), steel, 2, 64, 0, [0, 0, 0.25]); + const halo = part(sc, rider, new T.TorusGeometry(46, 3, 6, 24), sc.glow(0xff7a20, 0.8), 0, 30, 0, [Math.PI / 2, 0, 0]); + return { root, h, arm, halo }; + }, + update(m, b, g, time) { + R.qv(b.o[0], b.o[1], b.o[2], m.root.position); m.root.rotation.y = b.yaw * Q.DEG; + R.gallop(m.h, b.fr / 12, 1, 0); + const swing = b.stage ? Math.sin((b.fr / 12) * Math.PI) : 0; + m.arm.rotation.z = -0.3 + swing * 1.5; m.arm.rotation.x = swing * 0.3; + m.halo.visible = b.stage === 16; + m.halo.scale.setScalar(0.5 + (b.fr / 12) * 0.7); + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/art_eidolon.js b/environments/games/web/games/hexen2_remake/art_eidolon.js new file mode 100644 index 0000000000000000000000000000000000000000..47cb3cad193bf4aee04b0f99cb4049aa2a153341 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/art_eidolon.js @@ -0,0 +1,47 @@ +/* Hexen II boss arenas - original procedural model of Eidolon and the chaos orb (BossBench art, no Hexen II model data): a horned serpent demon that scales with the state. Reads the state only. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Hexen2Game, Q = M.Q, R = M.R3, { part, bx, cy, S } = R; + R.MODELS.eidolon = { + build(sc) { + const root = new T.Group(), scaleTo = new T.Group(); root.add(scaleTo); + const skin = sc.std(0x4a2c5c), belly = sc.std(0x8a6a4a), horn = sc.std(0xe0d4b0), eye = sc.glow(0xffe050, 1); + const hips = new T.Group(); hips.position.y = 60; scaleTo.add(hips); + part(sc, hips, cy(24, 30, 50, 9), skin, 0, 0, 0); + const torso = new T.Group(); torso.position.y = 24; hips.add(torso); + part(sc, torso, cy(34, 24, 62, 9), skin, 0, 30, 0); part(sc, torso, bx(14, 50, 40), belly, 20, 28, 0); + const head = new T.Group(); head.position.set(10, 68, 0); torso.add(head); + part(sc, head, new T.SphereGeometry(19, 9, 7), skin, 6, 4, 0).scale.set(1.3, 0.9, 1); + part(sc, head, new T.ConeGeometry(5, 34, 6), horn, -6, 26, 13, [0.3, 0, 0.3]); part(sc, head, new T.ConeGeometry(5, 34, 6), horn, -6, 26, -13, [-0.3, 0, 0.3]); + part(sc, head, new T.SphereGeometry(2.6, 6, 4), eye, 24, 6, 8); part(sc, head, new T.SphereGeometry(2.6, 6, 4), eye, 24, 6, -8); + const mouth = part(sc, head, new T.SphereGeometry(7, 7, 5), sc.glow(0xff8020, 0.95), 26, -6, 0); + const arms = [1, -1].map(s => { const a = new T.Group(); a.position.set(2, 52, s * 36); torso.add(a); part(sc, a, cy(9, 6, 54, 6), skin, 0, -24, s * 6); part(sc, a, new T.ConeGeometry(9, 22, 6), horn, 4, -58, s * 6, [Math.PI, 0, 0]); return a; }); + const legs = [1, -1].map(s => { const l = new T.Group(); l.position.set(0, 36, s * 20); hips.add(l); part(sc, l, cy(13, 8, 56, 7), skin, 0, -40, 0); part(sc, l, bx(30, 10, 18), horn, 6, -72, 0); return l; }); + const tail = new T.Group(); tail.position.set(-20, 0, 0); hips.add(tail); part(sc, tail, new T.ConeGeometry(16, 90, 7), skin, -36, -20, 0, [0, 0, 1.9]); + const shell = sc.keep(new T.ShaderMaterial({ transparent: true, depthWrite: false, blending: T.AdditiveBlending, uniforms: { color: { value: new T.Color(0xa070ff) }, power: { value: 1 } }, + vertexShader: 'varying vec3 vN; varying vec3 vV; void main(){ vec4 mv = modelViewMatrix * vec4(position,1.0); vN = normalize(normalMatrix*normal); vV = normalize(-mv.xyz); gl_Position = projectionMatrix*mv; }', + fragmentShader: 'uniform vec3 color; uniform float power; varying vec3 vN; varying vec3 vV; void main(){ float f = pow(1.0-abs(dot(vN,vV)),2.6); gl_FragColor = vec4(color*(0.3+1.4*f)*power, 0.05+0.9*f); }' })); + const orbM = new T.Mesh(sc.keep(new T.SphereGeometry(52, 32, 20)), shell); const ped = new T.Mesh(sc.keep(cy(46, 62, 20, 12)), sc.std(0x3a3044)); + const rings = [0, 1, 2].map(i => { const r = new T.Mesh(sc.keep(new T.TorusGeometry(40 - i * 6, 1.2, 6, 48)), sc.glow([0xd0b0ff, 0x9070ff, 0xffffff][i], 0.7)); r.position.copy(R.qv(1200, 1200, 70)); r.scale.setScalar(S); sc.world.add(r); return r; }); + R.qv(1200, 1200, 70, orbM.position); orbM.scale.setScalar(S); R.qv(1200, 1200, 10, ped.position); ped.scale.setScalar(S); sc.world.add(orbM, ped); + const spines = sc.std(0x2a1838); for (let i = 0; i < 6; i++) part(sc, torso, new T.ConeGeometry(4, 16 - i, 5), spines, -26 + i * 2, 8 + i * 10, 0, [0, 0, 1.2]); + part(sc, torso, new T.OctahedronGeometry(7), sc.glow(0xffb040, 0.95), 27, 34, 0); + return { root, scaleTo, hips, torso, head, mouth, arms, legs, orbM, rings }; + }, + update(m, b, g, time, sc) { + R.qv(b.o[0], b.o[1], b.o[2], m.root.position); m.root.rotation.y = b.yaw * Q.DEG; + m.scaleTo.scale.setScalar(S * b.scale * 1.1); + const walking = b.state === 'run', ph = time * (b.scale > 1 ? 2.2 : 3.2), fake = b.state === 'fakedie' ? Math.min(1, b.fr / 30) : b.state === 'darken' || b.state === 'readygrow' ? 1 : 0; + m.legs.forEach((l, i) => { l.rotation.z = walking ? Math.sin(ph * Math.PI * 2 + i * Math.PI) * 0.45 : 0; }); + m.arms.forEach((a, i) => { a.rotation.z = b.state === 'roar' ? -1.9 : b.state === 'power' ? -1.2 : b.state === 'spell' ? -1.4 + Math.sin(time * 14) * 0.2 : walking ? Math.sin(ph * Math.PI * 2 + (i + 1) * Math.PI) * 0.3 : 0; }); + m.torso.rotation.z = (b.state === 'roar' ? 0.35 : b.state === 'flames' || b.state === 'fireballs' ? -0.3 : 0) - fake * 1.15; + m.hips.position.y = 60 - fake * 40; + m.mouth.visible = b.state === 'flames' || b.state === 'fireballs' || b.state === 'roar'; + const alive = b.orb > 0; m.orbM.visible = alive; m.rings.forEach((r, i) => { r.visible = alive; r.rotation.set(time * (0.7 + i * 0.4), time * (1.1 - i * 0.3), i * 1.1); }); + const eye = Q.eye(g.p), near = Math.max(0.2, Math.min(1, (Math.hypot(eye[0] - 1200, eye[1] - 1200, eye[2] - 70) - 70) / 260)); + m.orbM.material.uniforms.power.value = (b.level ? 2.2 : 1 + Math.sin(time * 3) * 0.15) * near; m.rings.forEach(r => { r.material.opacity = 0.7 * near; }); + if (alive) { const c = [1200, 1200, 70]; sc.fx.glow(c, b.level ? 70 : 46, 0xb080ff, 0.75, 1, 0, 0.3); sc.fx.glow(c, 150, 0x8050ff, b.level ? 0.35 : 0.18, 0, 0, 0.7); for (let k = 0; k < 5; k++) { const a = time * 1.3 + k * 1.257; sc.fx.glow([c[0] + Math.cos(a) * 64, c[1] + Math.sin(a) * 64, c[2] + Math.sin(a * 2 + k) * 24], 10, 0xe0d0ff, 0.9, 3, a, 0.1); } sc.light([c[0], c[1], c[2] + 40], 0x9060ff, b.level ? 4 : 1.6, 420); + if (b.level) { const from = [b.o[0], b.o[1], b.o[2] + 300]; sc.fx.chain(R.jagged(c, from, 10, 30, 77, g.t >> 1), 6, 0xc0a0ff, 0.9, 0.8); } } + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/art_famine.js b/environments/games/web/games/hexen2_remake/art_famine.js new file mode 100644 index 0000000000000000000000000000000000000000..d52cce325bd784c09d1f0147ae6f22c50263ec00 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/art_famine.js @@ -0,0 +1,36 @@ +/* Hexen II boss arenas - original procedural model of Famine (BossBench art, no Hexen II model data). Update functions read the state only. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Hexen2Game, Q = M.Q, R = M.R3, { part, bx, cy, S } = R; + const place = (m, b) => { R.qv(b.o[0], b.o[1], b.o[2], m.root.position); m.root.rotation.y = b.yaw * Q.DEG; }; + // Famine: a starved pale horse with bare ribs; a hooded rider in rags, glowing eyes, a raised bony hand that casts the soul beam. + R.MODELS.famine = { + build(sc) { + const root = new T.Group(); root.scale.setScalar(S); + const hide = sc.std(0xb8a888), bone = sc.std(0xe8e0c4), cloak = sc.std(0x4a3a5c), dark = sc.std(0x241c2c), eye = sc.glow(0xff5030, 1); + const h = R.horse(sc, hide, { girth: 0.72, len: 1, legLen: 1.05, mane: sc.std(0xd8d0c0, { emissive: 0x302820 }) }); root.add(h.root); + for (let i = 0; i < 6; i++) { part(sc, h.body, bx(3, 20, 25), bone, -16 + i * 7, 2, 0); } + part(sc, h.head, bx(30, 6, 11), bone, 11, 2, 0, [0, 0, -0.35]); + const rider = new T.Group(); rider.position.set(-4, 19, 0); h.body.add(rider); + part(sc, rider, cy(9, 17, 44, 7), cloak, 0, 21, 0); + for (let i = 0; i < 5; i++) part(sc, rider, bx(3, 22, 7), cloak, -14 + (i % 2) * 2, 4 - i, -14 + i * 7); + const hood = new T.Group(); hood.position.set(1, 48, 0); rider.add(hood); + part(sc, hood, new T.ConeGeometry(11, 24, 7), cloak, -1, 6, 0); part(sc, hood, new T.SphereGeometry(6.5, 8, 6), dark, 3, 0, 0); + part(sc, hood, new T.SphereGeometry(1.4, 6, 4), eye, 8.5, 1, 2.6); part(sc, hood, new T.SphereGeometry(1.4, 6, 4), eye, 8.5, 1, -2.6); + const arm = new T.Group(); arm.position.set(2, 38, 12); rider.add(arm); + part(sc, arm, cy(2.6, 2, 28, 5), bone, 8, 0, 0, [0, 0, -1.3]); const orb = part(sc, arm, new T.SphereGeometry(5, 10, 8), sc.glow(0xff4030, 0.85), 24, 5, 0); + return { root, h, rider, arm, orb }; + }, + update(m, b, g, time) { + place(m, b); + const vis = b.state !== 'hidden'; m.root.visible = vis; + m.root.scale.set(S * b.scale, S, S * b.scale); + const rearing = b.state === 'rear' && (b.stage === 1 || b.stage === 2 || b.stage === 5), rise = rearing ? (b.stage === 1 ? Math.min(1, b.fr / 12) : 1) : (b.state === 'rear' && b.stage === 3 ? Math.max(0, 1 - b.fr / 12) : b.state.startsWith('blink') ? 1 : 0); + R.gallop(m.h, b.state === 'move' ? b.fr / 12 : 0, b.state === 'move' ? 0.8 : 0.1, rise); + const tele = M.telegraph(g), casting = b.stage === 4 || b.stage === 7 || !!tele; + m.arm.rotation.z = casting ? 0.9 : b.stage === 6 ? Math.sin(time * 22) * 0.2 : -0.7; + m.rider.rotation.z = b.stage === 6 ? Math.sin(time * 18) * 0.07 : 0; + m.orb.visible = casting; m.orb.scale.setScalar(casting ? 1 + Math.sin(time * 18) * 0.25 : 1); + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/art_pestilence.js b/environments/games/web/games/hexen2_remake/art_pestilence.js new file mode 100644 index 0000000000000000000000000000000000000000..85e3dac209f2621a4e4db9ba7acbe50bc2cfc634 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/art_pestilence.js @@ -0,0 +1,32 @@ +/* Hexen II boss arenas - original procedural model of Pestilence (BossBench art, no Hexen II model data): a boil-covered boar and a gaunt green archer, with buzzing swarms. Reads the state only. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Hexen2Game, Q = M.Q, R = M.R3, { part, bx, cy, S } = R; + R.MODELS.pestilence = { + build(sc) { + const root = new T.Group(); root.scale.setScalar(S); + const hide = sc.std(0x5a5a2c), bristle = sc.std(0x2c2c16), boil = sc.std(0xb0c040, { emissive: 0x304010 }), tusk = sc.std(0xe0d8b0), skin = sc.std(0x8a9858), cloak = sc.std(0x34401c); + const body = new T.Group(); body.position.y = 56; root.add(body); + part(sc, body, new T.SphereGeometry(52, 12, 9), hide, 0, 0, 0).scale.set(1.5, 0.95, 1.1); + part(sc, body, bx(120, 12, 16), bristle, -6, 50, 0); + for (let i = 0; i < 12; i++) part(sc, body, new T.SphereGeometry(5 + (i % 3) * 2, 6, 4), boil, -56 + (i * 37) % 112, 22 + (i * 13) % 26, i % 2 ? 42 : -42); + const head = new T.Group(); head.position.set(76, -4, 0); body.add(head); + part(sc, head, new T.SphereGeometry(30, 10, 8), hide, 0, 0, 0).scale.set(1.2, 0.9, 0.95); + part(sc, head, cy(14, 18, 24, 8), hide, 38, -8, 0, [0, 0, Math.PI / 2]); + part(sc, head, new T.ConeGeometry(5, 30, 6), tusk, 40, -2, 18, [0, 0, -1]); part(sc, head, new T.ConeGeometry(5, 30, 6), tusk, 40, -2, -18, [0, 0, -1]); + const legs = [[52, 34], [52, -34], [-52, 34], [-52, -34]].map(([x, z], i) => { const hip = new T.Group(); hip.position.set(x, 44, z); root.add(hip); part(sc, hip, cy(14, 9, 44, 7), hide, 0, -22, 0); return { hip, ph: [0, 0.5, 0.5, 0][i] }; }); + const rider = new T.Group(); rider.position.set(-6, 104, 0); root.add(rider); + part(sc, rider, cy(10, 15, 42, 7), cloak, 0, 20, 0); + part(sc, rider, new T.SphereGeometry(8, 8, 6), skin, 2, 50, 0); part(sc, rider, new T.ConeGeometry(11, 20, 7), cloak, -1, 58, 0); + part(sc, rider, new T.TorusGeometry(26, 1.2, 4, 12, Math.PI), sc.std(0x3a2a14), 22, 30, 0, [0, 0, -Math.PI / 2]); + return { root, body, head, legs, rider }; + }, + update(m, b, g, time) { + R.qv(b.o[0], b.o[1], b.o[2], m.root.position); m.root.rotation.y = b.yaw * Q.DEG; + const charge = b.stage === 3, run = b.stage !== 6, ph = time * (charge ? 5 : 1.8); + m.legs.forEach(l => { l.hip.rotation.z = run ? Math.sin((ph + l.ph) * Math.PI * 2) * (charge ? 0.9 : 0.45) : 0; }); + m.body.rotation.z = charge ? -0.14 : 0; m.body.position.y = 56 + Math.abs(Math.sin(ph * Math.PI * 2)) * (charge ? 7 : 3); m.head.rotation.z = charge ? -0.28 : Math.sin(time * 3) * 0.05; + m.rider.rotation.y = (b.ryaw - b.yaw) * Q.DEG; + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/art_praevus.js b/environments/games/web/games/hexen2_remake/art_praevus.js new file mode 100644 index 0000000000000000000000000000000000000000..e03096ed25d904586668337d3dcb96bac81d2af2 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/art_praevus.js @@ -0,0 +1,41 @@ +/* Hexen II boss arenas - original procedural model of the star-volley sorcerer and its six-shard shield (BossBench art, no Hexen II model data): a robed, crowned caster on a floating dais. + Reads the state only: scale for the teleport shrink and grow, god for the recharge glow, shards[] and shardR for the shield. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Hexen2Game, Q = M.Q, R = M.R3, { part, bx, cy, S } = R; + R.MODELS.praevus = { + build(sc) { + const root = new T.Group(), body = new T.Group(); root.add(body); + const robe = sc.std(0x2a1a4a), trim = sc.std(0xc8a050, { metalness: 0.6, roughness: 0.35 }), skin = sc.std(0x9a8aa8), gem = sc.glow(0xff60e0, 1), stone = sc.std(0x3a3448); + part(sc, body, cy(30, 34, 10, 10), stone, 0, 5, 0); + part(sc, body, cy(12, 30, 70, 10), robe, 0, 45, 0); part(sc, body, cy(31, 31, 4, 10), trim, 0, 12, 0); + const torso = new T.Group(); torso.position.y = 80; body.add(torso); + part(sc, torso, cy(14, 12, 24, 9), robe, 0, 6, 0); part(sc, torso, bx(6, 22, 26), trim, 10, 6, 0); + const head = new T.Group(); head.position.y = 26; torso.add(head); + part(sc, head, new T.SphereGeometry(9, 9, 7), skin, 0, 0, 0); + for (let i = 0; i < 5; i++) part(sc, head, new T.ConeGeometry(2, 10, 4), trim, Math.cos(i * 1.257) * 8, 9, Math.sin(i * 1.257) * 8); + part(sc, head, new T.SphereGeometry(1.8, 6, 4), gem, 8, 1, 3); part(sc, head, new T.SphereGeometry(1.8, 6, 4), gem, 8, 1, -3); + const arms = [1, -1].map(s => { const a = new T.Group(); a.position.set(0, 12, s * 16); torso.add(a); part(sc, a, cy(5, 7, 30, 6), robe, 8, -10, s * 2, [0, 0, -0.9]); return a; }); + const orb = part(sc, torso, new T.OctahedronGeometry(6), gem, 26, 0, 0); + const shardMat = sc.std(0x8070c0, { emissive: 0x402080, metalness: 0.3, roughness: 0.25, transparent: true, opacity: 0.85 }); + const shards = [0, 1, 2, 3, 4, 5].map(() => { const m = new T.Mesh(sc.keep(new T.OctahedronGeometry(1)), shardMat); m.scale.set(18 * S, 64 * S, 18 * S); sc.world.add(m); return m; }); + return { root, body, torso, head, arms, orb, shards }; + }, + update(m, b, g, time) { + R.qv(b.o[0], b.o[1], b.o[2], m.root.position); m.root.rotation.y = b.yaw * Q.DEG; + const gone = b.state === 'gone'; m.root.visible = !gone; + m.body.scale.setScalar(S * Math.max(0.05, b.scale || 1)); + const cast = b.state === 'point' || b.state === 'conjure' || b.state === 'storm' || b.state === 'pillar' || b.state === 'firewall'; + m.arms.forEach((a, i) => { a.rotation.z = cast ? -1.4 + Math.sin(time * 12 + i) * 0.15 : Math.sin(time * 1.5 + i) * 0.1; }); + m.body.position.y = Math.sin(time * 2) * 3 * S; + m.orb.scale.setScalar(b.god && b.state !== 'birth' && b.state !== 'wait' ? 1.8 + Math.sin(time * 10) * 0.3 : 1); + m.orb.rotation.set(time * 2, time * 3, 0); + const hide = gone || b.state === 'shrink' || b.state === 'grow'; + m.shards.forEach((s, k) => { + s.visible = !hide && b.shards[k] > 0; if (!s.visible) return; + const a = (60 * (k + 1) + 100 * Q.now(g)) * Q.DEG, r = b.shardR; R.qv(b.o[0] + Math.cos(a) * r, b.o[1] + Math.sin(a) * r, b.o[2] + 64, s.position); + s.rotation.y = -a + time; const hp = b.shards[k] / b.shardMax; s.material.opacity = 0.45 + 0.4 * hp; + }); + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/art_war.js b/environments/games/web/games/hexen2_remake/art_war.js new file mode 100644 index 0000000000000000000000000000000000000000..8f6260e7b62688a6ba582c75cbc0a0c6ea31719f --- /dev/null +++ b/environments/games/web/games/hexen2_remake/art_war.js @@ -0,0 +1,32 @@ +/* Hexen II boss arenas - original procedural model of War (BossBench art, no Hexen II model data): an armored red warhorse and a plate rider with a stack of axes. Reads the state only. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Hexen2Game, Q = M.Q, R = M.R3, { part, bx, cy, S } = R; + R.MODELS.war = { + build(sc) { + const root = new T.Group(); root.scale.setScalar(S); + const hide = sc.std(0x5c1c14), plate = sc.std(0x6c6660, { metalness: 0.65, roughness: 0.4 }), gold = sc.std(0xb88a30, { metalness: 0.6, roughness: 0.4 }), steel = sc.std(0xa8acb4, { metalness: 0.75, roughness: 0.3 }), wood = sc.std(0x3e2a18), fire = sc.glow(0xff6020, 0.95); + const h = R.horse(sc, hide, { girth: 1.15, len: 1.12, legLen: 1.05, mane: sc.std(0x3a0a08, { emissive: 0x200402 }) }); root.add(h.root); + part(sc, h.body, bx(66, 18, 37), plate, 6, 20, 0); part(sc, h.body, bx(30, 34, 37), plate, 38, 8, 0); + part(sc, h.neck, bx(16, 34, 18), plate, 8, 18, 0, [0, 0, -0.5]); part(sc, h.head, bx(26, 12, 15), plate, 8, 2, 0, [0, 0, -0.35]); part(sc, h.head, new T.ConeGeometry(3.5, 20, 5), gold, 2, 16, 0); + const rider = new T.Group(); rider.position.set(-8, 28, 0); h.body.add(rider); + part(sc, rider, cy(14, 18, 46, 8), plate, 0, 23, 0); part(sc, rider, bx(38, 10, 46), gold, 0, 40, 0); + const helm = new T.Group(); helm.position.set(2, 58, 0); rider.add(helm); + part(sc, helm, cy(9, 10, 18, 8), plate, 0, 0, 0); part(sc, helm, bx(3, 12, 20), gold, 0, 13, 0); part(sc, helm, bx(4, 3, 12), fire, 10, 1, 0); + const axeOf = (parent, x, y, z) => { const a = new T.Group(); a.position.set(x, y, z); parent.add(a); part(sc, a, cy(1.6, 1.6, 34, 5), wood, 0, 0, 0); part(sc, a, bx(3, 16, 20), steel, 0, 12, 7); return a; }; + for (let i = 0; i < 4; i++) axeOf(rider, -18, 30 + i * 3, -16 + i * 11).rotation.x = 0.5; + const arm = new T.Group(); arm.position.set(2, 42, 20); rider.add(arm); + part(sc, arm, cy(4, 3, 24, 6), plate, 8, 0, 0, [0, 0, -1.3]); + const held = axeOf(arm, 22, 6, 0), big = part(sc, arm, new T.SphereGeometry(10, 8, 6), fire, 24, 20, 0); + return { root, h, arm, held, big }; + }, + update(m, b, g, time) { + R.qv(b.o[0], b.o[1], b.o[2], m.root.position); m.root.rotation.y = b.yaw * Q.DEG; + const moving = b.state === 'move', rearing = b.state === 'rear' && (b.stage === 1 || b.stage === 2), rise = rearing ? (b.stage === 1 ? Math.min(1, b.fr / 12) : 1) : b.state === 'rear' && b.stage === 3 ? Math.max(0, 1 - b.fr / 9) : 0; + R.gallop(m.h, moving ? b.fr / [12, 16, 20][b.gait] : 0, moving ? [1, 0.75, 0.45][b.gait] : 0.08, rise); + const swing = b.stage === 4 || b.stage === 5 ? Math.sin(time * 16) : b.stage === 2 ? Math.min(1, b.fr / 39) * 1.3 : -0.4; + m.arm.rotation.z = swing; m.big.visible = b.stage === 2 && b.fr < 39; + m.big.scale.setScalar(0.5 + (b.fr / 39) * 0.8); + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/boss_death.js b/environments/games/web/games/hexen2_remake/boss_death.js new file mode 100644 index 0000000000000000000000000000000000000000..c0ef6826a07239cc17151cd26dd70ec6050ee62b --- /dev/null +++ b/environments/games/web/games/hexen2_remake/boss_death.js @@ -0,0 +1,132 @@ +/* Death, rider_death (dthhorse.hc). A flying horse at 12 units per frame on the rider_path graph, ramming whatever it meets. At the end of each 12-frame gallop, if nothing of its own is still + alive (cnt == 0), it attacks with chance .7 + skill/10: 30% the bone missile, 30% the fire circle, 40% three homing shots at frames 7, 9 and 11. It has no pain reaction. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q; + const NORMAL = 0, ATTACK1 = 4, ATTACK2 = 8, ATTACK3 = 16, SPEED = 12; + const now = Q.now; + // death_missile: no velocity at spawn, HomeThink builds it up; 500 speed, veer 50, turn_time 2, 5 s, 10 health, thinks at 10 Hz. On the player it starts the bone rain; it does no damage itself. + Q.MISSILE.bonemis = { + think(g, m) { if (m.life % 2 === 0) { Q.home(g, m); Q.veer(g, m, 50); } }, + touch(g, m, hitPlayer) { + const b = g.boss; + if (hitPlayer) { b.bonesUntil = now(g) + Q.random(g, 4, 6); b.bonesNext = g.t; g.events.push({ type: 'boss_attack', name: 'death_bones', tick: g.t }); } + else if (b.cnt > 0) b.cnt--; + Q.fx(g, 'redcloud', m.o); + }, + expire(g, m) { Q.fx(g, 'redcloud', m.o); }, + }; + // generate_bone: falls under gravity (MOVETYPE_BOUNCE) and hurts 1-3 on its first touch. + Q.MISSILE.boneshard = { + think(g, m) { m.v[2] -= 800 * Q.DT; }, + touch(g, m, hitPlayer) { if (hitPlayer) Q.damagePlayer(g, Q.random(g, 1, 3), m.o, 'death_bone'); }, + }; + function bone(g) { + const p = g.p, ceil = Q.traceWorld(g, p.o, [p.o[0], p.o[1], p.o[2] + 999]).end; + // Ahead of the way the player faces (+-50 degrees, 170-250 away) under the ceiling, thrown at where the player is now. + const a = (p.yaw + Q.random(g, -50, 50)) * Q.DEG, c = Q.random(g, 170, 250), o = [ceil[0] + c * Math.cos(a), ceil[1] + c * Math.sin(a), ceil[2] - 10]; + const h = Q.norm([p.o[0] - o[0], p.o[1] - o[1], 0]), s = Q.random(g, 200, 280); + Q.spawnMissile(g, 'boneshard', o, [h[0] * s, h[1] * s, Q.random(g, -600, -400)], 5, { minor: true, r: 3 }); + } + // drop_fire_circ: 700 speed, turn_time .5, 3 s, thinks at 10 Hz. Its first aim is the source's unset movechain.enemy, the world origin, and homing corrects it; within 40 units or out of time it goes off at the target. + Q.MISSILE.circfire = { + think(g, m) { + if (m.life % 2 !== 0) return; + if (Q.len(Q.sub(g.p.o, m.o)) < 40) { ring(g, m, true); return false; } + Q.home(g, m); + }, + touch(g, m, hitPlayer) { ring(g, m, hitPlayer); }, + expire(g, m) { ring(g, m, true); }, + }; + function ring(g, m, onPlayer) { // fire_circ_hit + const p = g.p, c = onPlayer ? [p.o[0], p.o[1], p.o[2] + 100] : m.o.slice(); + g.boss.rings.push({ c, yaw: onPlayer ? p.yaw : 0, dmg: 0, wait: 0 }); + Q.fx(g, 'blast', [c[0], c[1], Math.max(8, c[2] - 76)], { r: 30 }); + g.events.push({ type: 'boss_attack', name: 'death_fire_circle', tick: g.t }); + } + function ringsThink(g, b) { // circle_of_fire: 15 degrees and one floor flame a frame, radius damage dmg/3 inside 150 as dmg climbs 3.33 a frame to 80; die_out 4.2 s later + b.rings = b.rings.filter(r => { + if (r.wait > 0) { if (--r.wait === 0) { if (b.cnt > 0) b.cnt--; return false; } return true; } + r.yaw += 15; if (r.yaw > 360) r.yaw -= 360; + if (r.dmg >= 80) { r.wait = 84; return true; } + r.dmg += 3.33; + Q.radiusDamage(g, [r.c[0], r.c[1], r.c[2] - 76], r.dmg / 3, 'death_fire_circle', 150); + const a = r.yaw * Q.DEG; Q.spawnFlame(g, r.c[0] + Math.cos(a) * 100, r.c[1] + Math.sin(a) * 100, 3, 5.1); + return true; + }); + } + Q.HP.death = [2750, 4300, 10000]; + Q.CASES.push({ id: 'hexen2/airborne_bone_rider', name: 'Airborne Bone-Rain Rider', arena: 'death' }); + const B = Q.brush, pts = Q.ring(1024, 1024, 800, 10, 0).map((o, i) => [o[0], o[1], i % 2 ? 210 : 70]); + // A bone nave under a night sky. Six tall piers break the homing shots' sight; the path dips low enough to ram at every other point. + Q.ARENAS.death = { + title: 'Bone Corridor (original arena)', size: [2048, 2048, 720], theme: 'death', + brushes: [...Q.shell(2048, 2048, 720, { floor: 'ash', wall: 'bone', roof: 'sky' }), + B(700, 620, 0, 800, 720, 420, 'bone'), B(1248, 620, 0, 1348, 720, 420, 'bone'), B(700, 1328, 0, 800, 1428, 420, 'bone'), B(1248, 1328, 0, 1348, 1428, 420, 'bone'), + B(560, 974, 0, 660, 1074, 300, 'obsidian'), B(1388, 974, 0, 1488, 1074, 300, 'obsidian'), B(944, 944, 0, 1104, 1104, 48, 'obsidian')], + paths: Q.ringPaths(pts, 2), + player: [1024, 420, 0, 90], boss: [1824, 1024, 70, 90], + items: [['health', 200, 1024, 10], ['health', 1848, 1024, 10], ['health', 1024, 200, 10], ['health', 1024, 1848, 10], ['mana', 300, 300, 15], ['mana', 1748, 300, 15], ['mana', 300, 1748, 15], ['mana', 1748, 1748, 15], ['health', 750, 1024, 10], ['health', 1298, 1024, 10]], + }; + Q.BOSS.death = { + title: 'Airborne Bone-Rain Rider', + spawn(g, o, yaw, hp) { + return { kind: 'death', o: o.slice(), yaw, ideal_yaw: yaw, yaw_speed: 4, speed: SPEED, path_distance: 100, mins: [-55, -55, -24], maxs: [55, 55, 100], hp, maxHp: hp, path: 0, fr: 0, stage: NORMAL, fly: true, solid: true, + cnt: 0, attack_finished: 0, rings: [], bonesUntil: 0, bonesNext: 0, y_change: 0, move_adjust: 0 }; + }, + think(g, b) { + const r = Q.advanceFrame(b, 12), p = g.p, t = now(g), pause = g.tierScale.pause; + Q.riderpathMove(g, b, b.speed, true); + if (r === Q.AF_BEGINNING) { + b.stage = NORMAL; + if (Q.random(g) < 0.7 + g.skill / 10 && !b.cnt && p.hp > 0) { + const k = Q.random(g); + b.stage = k < 0.3 ? ATTACK1 : k < 0.6 ? ATTACK3 : ATTACK2; + } + } + if (b.cnt && b.attack_finished < t) b.cnt = 0; + if (b.stage && p.hp > 0) { + if (b.stage === ATTACK1 && b.fr === 8) { + b.cnt++; b.attack_finished = t + 10 * pause; + Q.spawnMissile(g, 'bonemis', b.o, [0, 0, 0], 5, { speed: 500, turn: 2, hp: 10, r: 14 }); + g.events.push({ type: 'boss_attack', name: 'death_bone_missile', tick: g.t }); + } else if (b.stage === ATTACK3 && b.fr === 8) { + b.cnt++; b.attack_finished = t + 10 * pause; + const v = Q.qcVectors([0, b.yaw]), o = Q.ma(Q.ma([b.o[0], b.o[1], b.o[2] + 36], 4, v.f), 10, v.r), aim = Q.norm(Q.sub([0, 0, 30], o)); + Q.spawnMissile(g, 'circfire', o, Q.scale(aim, 700), 3, { speed: 700, turn: 0.5, r: 12 }); + } else if (b.stage === ATTACK2 && (b.fr === 7 || b.fr === 9 || b.fr === 11)) { + // death_missile_2(FALSE): dir 0 on all three, so every shot leaves 25 degrees left of the horse's heading at speed 700; cnt is not given back by these shots, only by the 7 s timer. + b.cnt++; b.attack_finished = t + 7 * pause; + Q.spawnMissile(g, 'famshot', [b.o[0], b.o[1], b.o[2] + 120], Q.qcVectors([0, b.yaw - 25]).f, 3, { speed: 700, turn: 2.25, src: 'death_missile' }); + if (b.fr === 7) g.events.push({ type: 'boss_attack', name: 'death_missiles', tick: g.t }); + } + } + if (r === Q.AF_END) b.stage = NORMAL; + // bones_think at 10 Hz: 1 bone, 80% a second, 50% a third. + if (b.bonesUntil) { + if (t > b.bonesUntil) { b.bonesUntil = 0; if (b.cnt > 0) b.cnt--; } + else if (g.t >= b.bonesNext && p.hp > 0) { b.bonesNext = g.t + 6; bone(g); if (Q.random(g) < 0.8) bone(g); if (Q.random(g) < 0.5) bone(g); } + } + ringsThink(g, b); + }, + targets(g, b) { + const out = [Object.assign({ id: 'horse' }, Q.boxAt(b, b.o))]; + for (const m of g.missiles) if (m.k === 'bonemis') out.push({ id: 'bonemis:' + m.id, mins: m.o.map(v => v - 8), maxs: m.o.map(v => v + 8) }); + return out; + }, + aim(g, b) { return [b.o[0], b.o[1], b.o[2] + 40]; }, + vel(g, b) { const r = b.yaw * Q.DEG, s = b.speed * 20; return [Math.cos(r) * s, Math.sin(r) * s, 0]; }, + hurt(g, b, id, dmg) { + if (id !== 'horse') { // death_missile_die: 10 health, gives cnt back + const m = g.missiles.find(x => 'bonemis:' + x.id === id); if (!m) return; + m.hp -= dmg; if (m.hp <= 0) { g.missiles = g.missiles.filter(x => x !== m); if (b.cnt > 0) b.cnt--; Q.fx(g, 'redcloud', m.o); } + return; + } + b.hp -= dmg; if (b.hp <= 0) { b.hp = 0; g.bossKilled = true; } + }, + progress(g, b) { return b.hp; }, + max(g, b) { return b.maxHp; }, + phase(g, b) { return b.bonesUntil ? 'Bone Rain' : b.rings.length ? 'Fire Ring' : { 4: 'Bone Missile', 8: 'Triple Homing Missiles', 16: 'Fire Ring' }[b.stage] || 'Dashing'; }, + warn(g, b) { return b.bonesUntil ? 'Bone rain: keep moving and take cover' : b.rings.some(r => !r.wait) ? 'The fire ring is closing: move beyond 150 units' : null; }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/boss_eidolon.js b/environments/games/web/games/hexen2_remake/boss_eidolon.js new file mode 100644 index 0000000000000000000000000000000000000000..7b62ced0006c3feb0a2a5f465d98ce54f3c1d5a7 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/boss_eidolon.js @@ -0,0 +1,251 @@ +/* Eidolon, monster_eidolon + obj_chaos_orb (eidolon.hc; the flow is written up in gamecode/devel/eidolon.txt). Small form: cannot die, damage only adds up; at 2000 and past its pain lockout it fakes death, darkens the sky, + and once the player looks at it and the orb, grows to scale 2.55. The orb takes damage from the start (obj_chaos_orb, eidolon.hc:321); only while Eidolon grows does orb_pain hand it back. Big form: still cannot die while the chaos orb lives; 1000 damage sends it back to the orb to recharge, and hitting the orb then interrupts it. Orb broken: real health, + 4000 + skill*2000 in the source. Boss health is reported as one bar over the three parts so it never jumps back: small + orb + big, in the proportion 2000 : 2000 : 6000 of skill 1. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q; + const now = Q.now, SPEED = 10.5, SMALL = 0.75, BIG = 2.55, PART = [0.2, 0.2, 0.6], ORB = [1200, 1200, 0], STORM = [1200, 1200, 560], STORM_R = 1000; + const isBig = b => b.scale > 1; + // For the controller. Breaking the orb sends Eidolon back to the start of a roar (orb_die -> eidolon_ready_roar), one more lightning storm. It costs least in the opening roar, + // which only restarts and where the body cannot be hurt anyway; in the fake-death chain it undoes the chain. So: the orb in the opening roar and in the big form, never in between. + const aimOrb = b => b.orb > 0 && b.state !== 'grow' && (isBig(b) || (b.god && (b.state === 'preroar' || b.state === 'roar'))); + // The last roar ends god mode on its frame 60 (eidolon_roar): with the orb gone, a bolt at 1000 u/s fired now that lands after that counts. + const godEndsBy = (g, b) => b.god && b.orb <= 0 && isBig(b) && b.state === 'roar' && (60 - b.fr) * Q.DT <= Q.len(Q.sub(b.o, g.p.o)) / 1000; + const setBox = b => { if (isBig(b) || b.state === 'grow') { const r = 21.3333 * b.scale; b.mins = [-r, -r, 0]; b.maxs = [r, r, 266.67 * b.scale]; } }; + const proj = b => [b.o[0], b.o[1], b.o[2] + (isBig(b) ? 200 : 100)]; + const set = (b, state) => { b.state = state; b.fr = 0; }; + const sees = (g, b) => Q.clear(g, proj(b), Q.center(g.p)); + const faceEnemy = (g, b) => { b.ideal_yaw = Q.vectoyaw(Q.sub(g.p.o, b.o)); Q.changeYaw(b); }; + const playerLooksAt = (g, at) => { const d = Q.norm(Q.sub(at, g.p.o)), r = g.p.yaw * Q.DEG; return d[0] * Math.cos(r) + d[1] * Math.sin(r) > 0.3; }; // infront_of_ent(thing, player) + // pmissile2_touch: 150-200 on a direct hit, and 120-160 radius to everyone else. Tracks from 0.3 s, every .15 s (pmissile2_puff). + Q.MISSILE.fireball = { + think(g, m) { m.age = (m.age || 0) + 1; if (m.age >= 6 && m.age % 3 === 0) Q.home(g, m); }, + touch(g, m, hitPlayer) { + if (hitPlayer) Q.damagePlayer(g, Q.random(g, 150, 200), m.o, 'eidolon_fireball'); else Q.radiusDamage(g, m.o, Q.random(g, 120, 160), 'eidolon_fireball'); + Q.fx(g, 'blast', m.o, { r: 40 }); + }, + }; + // flame_stream_touch: 30 on the player, radius 60 on the world; fire_anim removes it after 27 frames at .025 s and lifts it a little faster each frame. + Q.MISSILE.flame = { + think(g, m) { m.age = (m.age || 0) + 2; m.v[2] += m.age * 2 * 2; }, + touch(g, m, hitPlayer) { if (hitPlayer) Q.damagePlayer(g, 30, m.o, 'eidolon_flame'); else Q.radiusDamage(g, m.o, 60, 'eidolon_flame'); }, + }; + // Tome-powered magic missile: 30-40 direct, the same again as radius on a miss; turn_time 3, veer 100, homing at 10 Hz, 5 s, 1000 u/s, slows on turns. + Q.MISSILE.magic = { + think(g, m) { m.age = (m.age || 0) + 1; if (m.age >= 4 && m.age % 2 === 0) { Q.home(g, m); Q.veer(g, m, 100); } }, + touch(g, m, hitPlayer) { const d = Q.random(g, 30, 40); if (hitPlayer) Q.damagePlayer(g, d, m.o, 'eidolon_magic'); else Q.radiusDamage(g, m.o, d, 'eidolon_magic'); Q.fx(g, 'hit', m.o, { r: 12 }); }, + }; + function fireball(g, b) { + const v = Q.qcVectors([0, b.yaw]), o = Q.ma(Q.ma(Q.ma(proj(b), 128, v.f), 24, v.r), -12, v.u), aim = Q.norm(Q.sub(Q.center(g.p), o)), dir = [v.f[0], v.f[1], aim[2]]; + b.cnt++; if (b.cnt === 2) { b.attack_finished = now(g) + 7 * g.tierScale.pause; b.cnt = 0; } + Q.spawnMissile(g, 'fireball', o, Q.scale(dir, 1000), 2, { speed: 1000, turn: 2, r: 26 }); + g.events.push({ type: 'boss_attack', name: 'eidolon_fireball', tick: g.t }); + } + // The flame and polymorph aim: down the facing, taking the player's bearing only inside the .85 cone, pitch toward the player * 1.7. + function coneDir(g, b, o) { + const v = Q.qcVectors([0, b.yaw]), w = Q.norm(Q.sub(g.p.o, o)), h = Q.norm([w[0], w[1], 0]), dot = v.f[0] * h[0] + v.f[1] * h[1]; + return dot > 0.85 ? [w[0], w[1], w[2] * 1.7] : [v.f[0], v.f[1], w[2] * 1.7]; + } + function flame(g, b) { + const v = Q.qcVectors([0, b.yaw]), o = Q.ma(Q.ma(Q.ma(proj(b), 128, v.f), 20, v.r), -12, v.u), s = Q.random(g, 300, 350); + Q.spawnMissile(g, 'flame', o, Q.scale(coneDir(g, b, o), s), 0.675, { minor: false, r: 16 }); + } + function magic(g, b) { + const v = Q.qcVectors([0, b.yaw]), o = Q.ma(Q.ma(proj(b), 48, v.f), 20, v.r), d = Q.norm(Q.sub(Q.center(g.p), Q.ma(proj(b), 64, v.f))); + Q.spawnMissile(g, 'magic', o, Q.scale([v.f[0], v.f[1], d[2]], 1000), 5, { speed: 1000, turn: 3, hover: true, r: 8 }); + g.events.push({ type: 'boss_attack', name: 'eidolon_magic', tick: g.t }); + } + // lightning_strike with the map's storm (Q.lightningStrike, h2boss.js): the base game's storm does 10000 a beam, so a hit kills. Eidolon and the orb are immune. + const strike = g => Q.lightningStrike(g, STORM, STORM_R, 10000, 'eidolon_lightning'); + function pathMove(g, b) { // eidolon_riderpath_move: riderpath_findbest, one point change a second, half speed while turning (big form) + const t = now(g), goal = b.toOrb ? ORB : g.p.o, cur = g.paths[b.path], dist = Q.hlen(Q.sub(b.o, cur.o)); + if (dist < b.path_distance) { + let best = -1, bd = Q.len(Q.sub(goal, b.o)); + for (const n of cur.next) { const d = Q.len(Q.sub(goal, g.paths[n].o)); if (d < bd) { bd = d; best = n; } } + if (best < 0 || b.turn_time >= t) return false; + b.path = best; b.turn_time = t + 1; + } + const node = g.paths[b.path].o, off = Math.abs(Q.angdiff(Q.vectoyaw(Q.sub(node, b.o)) - b.yaw)); + b.yaw_speed = off <= 30 || !isBig(b) ? 10 : 15; + const step = SPEED * b.scale / (off <= 30 || !isBig(b) ? 1 : 2); + b.ideal_yaw = Q.vectoyaw(Q.sub(node, b.o)); Q.changeYaw(b); b.yaw_speed = 10; + const res = Q.walkMove(g, b, b.yaw, step); + if (res === 'player') Q.ram(g, b); + else if (res === 'world') { + // Blocked by the world (MOVETYPE_PUSH): setorigin straight on by move_speed, unless a player within size_x + move_speed is in its 90 fov (eidolon.hc:465-481). + // So the demon walks through plinths and walls; walkmove fails again from inside them and it keeps pushing until it is out. + const r = b.yaw * Q.DEG, fwd = [Math.cos(r), Math.sin(r), 0], pc = Q.center(g.p), to = Q.norm(Q.sub(pc, proj(b))); + const near = g.p.hp > 0 && Q.len(Q.sub(pc, b.o)) <= b.maxs[0] - b.mins[0] + step && 180 - Q.dot(to, fwd) * 180 <= 90; + if (!near) b.o = [b.o[0] + fwd[0] * step, b.o[1] + fwd[1] * step, b.o[2]]; + } + return true; + } + function checkAttack(g, b) { // eidolon_check_attack + if (b.toOrb) return false; + const t = now(g), o = proj(b), c = Q.center(g.p); + if (!Q.clear(g, o, c)) return false; + const dist = Q.len(Q.sub(g.p.o, b.o)); + if (dist < 200 && isBig(b)) { set(b, 'flames'); return true; } + if (t < b.attack_finished) return false; + if (Q.random(g) < 0.3 - g.skill / 10 && b.orb > 0) return false; + if (!Q.aggressive(g)) { b.attack_finished = t + Q.random(g, 0, 2); return false; } + fire(g, b, dist); b.attack_finished = t + Q.random(g, 0, 2); + return b.state !== 'run'; + } + function fire(g, b, dist) { // eidolon_fire; the polymorph spell (1%) is not implemented, see the deviation table + if (b.scale === SMALL) { + if (dist < 120) { const d = Q.norm(Q.sub(Q.center(g.p), b.o)); g.p.v = Q.ma(g.p.v, 300, d); g.p.onground = false; } // UseBlast, approximation + set(b, 'spell'); + } else if (dist > 128 && dist < 424) set(b, 'flames'); + else if (Q.random(g) < 0.2) set(b, 'preroar'); + else { + const r = b.yaw * Q.DEG, d = Q.norm(Q.sub(g.p.o, b.o)); + if (d[0] * Math.cos(r) + d[1] * Math.sin(r) > 0.3) set(b, 'fireballs'); else b.cnt = 0; + } + } + const STEP = { + preroar(g, b) { b.attack_finished = now(g) + 1.5; g.events.push({ type: 'boss_attack', name: 'eidolon_roar', tick: g.t }); set(b, 'roar'); }, + roar(g, b) { + b.fr++; + if (b.fr > 13 && Q.random(g) < 0.5) strike(g); + if (b.fr === 60) { b.god = false; b.attack_finished = now(g) + 3; set(b, 'run'); } + }, + run(g, b) { + if (checkAttack(g, b)) return; + const moved = pathMove(g, b); + if (!moved) faceEnemy(g, b); + }, + spell(g, b) { + b.fr++; faceEnemy(g, b); + if ((b.fr >= 8 && b.fr <= 16 && Q.random(g) < 0.2 + g.skill / 10) || b.fr === 10) magic(g, b); + if (b.fr === 20) { b.attack_finished = now(g) + 2; set(b, 'run'); } + }, + flames(g, b) { + b.fr++; faceEnemy(g, b); + const p = g.p, d = Q.sub(p.o, b.o); + if (Q.len(d) < 200) { const n = Q.norm(d); p.v[0] = n[0] * 100; p.v[1] = n[1] * 100; if (p.onground) p.v[2] = 150; p.onground = false; } + // Frames 25-41 run at .025 s each and frame 25-40 twice: two flames per source frame. + if (b.fr >= 25 && b.fr <= 41) { flame(g, b); flame(g, b); if (b.fr === 25) g.events.push({ type: 'boss_attack', name: 'eidolon_flames', tick: g.t }); } + if (b.fr === 50) { b.attack_finished = now(g) + 10 * g.tierScale.pause; set(b, 'run'); } + }, + fireballs(g, b) { + b.fr++; faceEnemy(g, b); + if (b.fr === 36) fireball(g, b); + if (b.fr > 24 && b.fr < 41 && Q.random(g) < 0.1 + g.skill / 10) fireball(g, b); + if (b.fr === 50) { b.attack_finished = now(g) + 3 * g.tierScale.pause; set(b, 'run'); } + }, + fakedie(g, b) { if (++b.fr === 30) set(b, 'darken'); }, + darken(g, b) { // eidolon_darken_sky: the skipped light steps are nine frames; then wait to be watched by the player at under 1500 units + b.fr = b.fr >= 29 ? 1 : b.fr + 1; b.dark++; + // An orb broken before the growth leaves controller = world: the source then reads infront_of_ent(world) here and errors out writing world.think in eidolon_ready_grow. Approximation: Eidolon alone has to be watched. + if (b.fr === 29 && b.dark >= 9 && playerLooksAt(g, Q.center(b)) && (b.orb <= 0 || playerLooksAt(g, [ORB[0], ORB[1], 60])) && Q.len(Q.sub(g.p.o, b.o)) < 1500) { b.solid = false; b.lifetime = now(g) + 2; set(b, 'readygrow'); } + }, + readygrow(g, b) { // 0.1 s a frame + b.sub = !b.sub; if (b.sub) return; + b.fr = b.fr >= 29 ? 1 : b.fr + 1; + if (b.fr === 29 && b.lifetime < now(g)) set(b, 'grow'); + }, + grow(g, b) { // eidolon_grow: frames under 71 at .1 s, then .05 s; shoves and burns whoever stands close + if (b.fr < 71) { b.sub = !b.sub; if (b.sub) return; } + b.fr++; + if (b.scale < 2.52) b.scale = Math.round((b.scale + 0.03) * 1e4) / 1e4; + setBox(b); + const p = g.p, d = Q.sub(p.o, b.o); + if (Q.hlen(d) < 2 * b.maxs[0] + 25) { const n = Q.norm(d); p.v = Q.scale(n, 100); p.v[2] += 100; p.onground = false; Q.damagePlayer(g, 3, null, 'eidolon_grow'); } + if (b.fr >= 100) { b.scale = BIG; setBox(b); b.path_distance = 64; b.weapon = 0; b.solid = true; b.wait = 20; set(b, 'postgrow'); } + }, + postgrow(g, b) { if (--b.wait <= 0) set(b, 'preroar'); }, + pain(g, b) { if (++b.fr === 9) { if (b.weapon >= 1000 && b.orb > 0) { b.weapon = 0; b.toOrb = true; set(b, 'faceorb'); } else set(b, 'run'); } }, + faceorb(g, b) { b.ideal_yaw = Q.vectoyaw(Q.sub(ORB, b.o)); Q.changeYaw(b); if (Math.abs(Q.angdiff(b.yaw - b.ideal_yaw)) < 10) { b.level = true; set(b, 'power'); } }, + power(g, b) { // frame 10 holds 2 s + if (b.fr === 10 && b.hold < 40) { b.hold++; return; } + b.fr++; + if (b.fr === 20) { b.level = false; b.toOrb = false; b.hold = 0; set(b, 'run'); } + }, + orbpain(g, b) { if (++b.fr === 20) { b.weapon = 0; b.level = false; b.toOrb = false; b.hold = 0; set(b, 'run'); } }, + }; + function pain(g, b, dmg) { // eidolon_check_fake + const t = now(g); + let chance; + if (b.orb > 0 || !isBig(b)) { if (isBig(b)) { chance = 0.1; b.weapon += dmg; } else { chance = 0.6; b.weapon = 0; } } + else chance = 0.2; + if (b.pain_finished > t || !['run', 'spell', 'flames', 'fireballs', 'power'].includes(b.state)) return; + b.pain_finished = t + 3 + g.skill; + if (b.small <= 0 && !isBig(b)) { b.god = true; b.solid = true; b.level = false; g.events.push({ type: 'boss_phase', name: 'fake_death', tick: g.t }); set(b, 'fakedie'); } + else if (Q.random(g) < chance / 2 || b.weapon >= 1000) set(b, b.level ? 'orbpain' : 'pain'); + } + Q.HP.eidolon = [100, 2400, 8400]; + Q.CASES.push({ id: 'hexen2/orb_warded_serpent', name: 'Orb-Shielded Serpent', arena: 'eidolon' }); + const B = Q.brush, ringA = Q.ring(1200, 1200, 860, 8, 0), ringB = Q.ring(1200, 1200, 460, 8, 0); + // Two mana crystals sat at r = 820 on the 12 and 6 o'clock axis, one under the boss's spawn and on the outer path ring: the grown demon stood on it flaming, and a dry player + // could neither take it nor get past (hard seed 8 timed out that way). They are now at r = 1020, outside the ring and its chords (>= 795 + box 54). + // A ruined court round the chaos orb. The path graph is two rings joined by spokes, so the demon can always step to the point nearest the player. Eight low plinths stop flames, not fireballs from above. + const graph = [...ringA, ...ringB].map((o, i) => { const k = i % 8, out = i < 8; return { o: o.map(Math.round), next: out ? [(k + 1) % 8, (k + 7) % 8, 8 + k] : [8 + (k + 1) % 8, 8 + (k + 7) % 8, k] }; }); + Q.ARENAS.eidolon = { + title: 'Orb Altar (original arena)', size: [2400, 2400, 1000], theme: 'eidolon', + brushes: [...Q.shell(2400, 2400, 1000, { floor: 'marble', wall: 'obsidian', roof: 'sky' }), + ...Q.ring(1200, 1200, 660, 8, 0).map(p => B(p[0] - 56, p[1] - 56, 0, p[0] + 56, p[1] + 56, 72, 'crystal'))], + paths: graph, orb: ORB, + player: [1200, 200, 0, 90], boss: [1200, 2060, 0, 270], + items: [['health', 180, 1200, 10], ['health', 2220, 1200, 10], ['health', 1200, 150, 10], ['health', 1200, 2250, 10], ['mana', 280, 280, 15], ['mana', 2120, 280, 15], ['mana', 280, 2120, 15], ['mana', 2120, 2120, 15], ['mana', 1000, 200, 15], ['mana', 1400, 2200, 15], ['health', 380, 1200, 10], ['health', 2020, 1200, 10]], + }; + Q.BOSS.eidolon = { + title: 'Orb-Shielded Serpent', + spawn(g, o, yaw, hp) { + return { kind: 'eidolon', o: o.slice(), yaw, ideal_yaw: yaw, yaw_speed: 10, path_distance: 30, mins: [-40, -40, 0], maxs: [40, 40, 150], maxHp: hp, small: Math.round(hp * PART[0]), orb: Math.round(hp * PART[1]), big: hp - Math.round(hp * PART[0]) - Math.round(hp * PART[1]), + orbPain: 0, path: 4, fr: 0, sub: false, state: 'preroar', scale: SMALL, solid: true, god: true, weapon: 0, cnt: 0, level: false, toOrb: false, hold: 0, dark: 0, wait: 0, lifetime: 0, attack_finished: 0, pain_finished: 0, turn_time: 0, y_change: 0, move_adjust: 0 }; + }, + think(g, b) { STEP[b.state](g, b); }, + targets(g, b) { + const out = [Object.assign({ id: 'body' }, Q.boxAt(b, b.o))]; + if (b.orb > 0) out.push({ id: 'orb', mins: [ORB[0] - 48, ORB[1] - 48, 0], maxs: [ORB[0] + 48, ORB[1] + 48, 123] }); + return out; + }, + aim(g, b) { + if (aimOrb(b)) return [ORB[0], ORB[1], 70]; + if (b.state === 'darken' && b.orb > 0) return [(b.o[0] + ORB[0]) / 2, (b.o[1] + ORB[1]) / 2, 70]; + return [b.o[0], b.o[1], b.o[2] + (isBig(b) ? 120 : 80)]; + }, + // For the controller's lead only: walking in run at SPEED * scale along its yaw (half while a big form turns), still otherwise. + // For the controller, out of mana: while the orb lives the big demon's body takes no damage, so a sword run at the body is wasted; walk to the orb instead (stop 70 short, on the player's side). + dryGoal(g, b) { if (!aimOrb(b)) return null; const d = Q.norm(Q.sub(g.p.o, ORB)); return [ORB[0] + d[0] * 70, ORB[1] + d[1] * 70, 0]; }, + vel(g, b) { if (b.state !== 'run' || aimOrb(b)) return [0, 0, 0]; // the orb does not move: leading it by the demon's walk threw every shot 30-40 degrees wide + const r = b.yaw * Q.DEG, s = SPEED * b.scale * 20; return [Math.cos(r) * s, Math.sin(r) * s, 0]; }, + // Darken waits until Eidolon and the orb are both ahead of the player from under 1500 units: stand off to the side of the line between them, where one look takes in both. + goal(g, b) { + // Retreat to the corner of the current quadrant during the storm. + if (b.state === 'preroar' || b.state === 'roar') { const p = g.p.o; return [p[0] < 1200 ? 180 : 2220, p[1] < 1200 ? 180 : 2220, 0]; } + // The small form must take one more hit past its lockout to fake death, and a purifier bolt at 2000 units lands 2 s late on a walking target: close to 800. + // With the orb on the line to it, a shot would break the orb instead (one more roar): step 300 to the side away from the orb. + if (!isBig(b) && !b.god && (b.state === 'run' || b.state === 'spell')) { + const p = g.p.o, d = Q.norm([b.o[0] - p[0], b.o[1] - p[1], 0]), side = [-d[1], d[0], 0], w = [ORB[0] - p[0], ORB[1] - p[1], 0], along = Q.dot(w, d), off = Q.dot(w, side); + if (b.orb > 0 && along > 0 && along < Q.len(Q.sub(b.o, p)) && Math.abs(off) < 110) { const k = off > 0 ? -300 : 300; return [Math.max(170, Math.min(2230, p[0] + side[0] * k)), Math.max(170, Math.min(2230, p[1] + side[1] * k)), 0]; } + return Q.len(Q.sub(p, b.o)) > 800 ? b.o.slice() : null; + } + if (b.state !== 'darken') return null; + if (b.orb <= 0) return Q.len(Q.sub(g.p.o, b.o)) < 1300 ? null : b.o.slice(); // orb gone: only the 1500-unit watch is left to satisfy + const mid = [(b.o[0] + ORB[0]) / 2, (b.o[1] + ORB[1]) / 2, 0], d = Q.norm(Q.sub(ORB, b.o)), side = Q.dot(Q.sub(g.p.o, mid), [-d[1], d[0], 0]) >= 0 ? 1 : -1; + const c = v => Math.max(170, Math.min(2230, v)); + return [c(mid[0] - d[1] * side * 620), c(mid[1] + d[0] * side * 620), 0]; + }, + // For the controller: is a shot that meets this target worth firing now. The body is untouchable in god mode and, once big, while the orb lives; the orb as aimOrb. + shootable(g, b, id) { return id === 'orb' ? aimOrb(b) : (!b.god || godEndsBy(g, b)) && (!isBig(b) || b.orb <= 0); }, + hurt(g, b, id, dmg) { + if (id === 'orb') { // orb_pain answers only once per 1.75 s; breaking the orb gives the real health + if (b.state === 'grow') return; + b.orb -= dmg; + if (b.orb <= 0) { b.orb = 0; b.solid = true; b.level = false; b.toOrb = false; b.hold = 0; b.weapon = 0; g.events.push({ type: 'boss_phase', name: 'orb_broken', tick: g.t }); set(b, 'preroar'); return; } + if (b.orbPain <= now(g)) { b.orbPain = now(g) + 1.75; if (b.level) set(b, 'orbpain'); } + return; + } + if (b.god) return; + if (!isBig(b)) b.small = Math.max(0, b.small - dmg); + else if (b.orb <= 0) { b.big -= dmg; if (b.big <= 0) { b.big = 0; g.bossKilled = true; return; } } + pain(g, b, dmg); + }, + progress(g, b) { return b.small + b.orb + b.big; }, + max(g, b) { return b.maxHp; }, + phase(g, b) { return { preroar: 'Roar', roar: 'Thunder Roar', spell: 'Magic Missile', flames: 'Fire breath', fireballs: 'Fireballs', fakedie: 'Feigned Death', darken: 'Darkening Sky', readygrow: 'Charge', grow: 'Growth', postgrow: 'Growth', power: 'Charging from Orb', faceorb: 'Turning to Orb', orbpain: 'Charge Interrupted', pain: 'Wounded' }[b.state] || (isBig(b) ? (b.orb > 0 ? 'Giant · Orb Intact' : 'Giant · Vulnerable') : 'Small Form'); }, + warn(g, b) { return b.state === 'darken' ? (b.orb > 0 ? 'Face Eidolon and the orb to resume the fight' : 'Face Eidolon to resume the fight') : isBig(b) && b.orb > 0 ? 'Destroy the orb: Eidolon cannot die while it remains' : b.state === 'roar' ? 'Thunder roar: a direct strike is fatal' : null; }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/boss_famine.js b/environments/games/web/games/hexen2_remake/boss_famine.js new file mode 100644 index 0000000000000000000000000000000000000000..96907e0388943f5ee8073105d362f487b16c3fe9 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/boss_famine.js @@ -0,0 +1,142 @@ +/* Famine, rider_famine (famhorse.hc). The horse canters the rider_path graph at 5.5 units per .05 s source frame and never rams. Every 12-frame gallop cycle: rear and blink away + (chance > max(hp fraction, .5)), laugh (< .05), else if looktime has passed and the rider sees the player: 30% the pull, 40% three homing shots. Being hit rolls much the same way. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q; + const NORMAL = 0, BEGIN_REAR = 1, MIDDLE_REAR = 2, END_REAR = 3, ATTACK = 4, STANDING = 5, LAUGHING = 6, ATTACK2 = 7; + const SPEED = 5.5, HEAD = 120, ROOM = { mins: [-55, -55, 0], maxs: [55, 55, 150] }; + const sees = (g, from) => Q.clear(g, from, g.p.o); + function missile(g, b, dir) { + // famine_missile: aimed along (eye - origin + '0 0 120'), a source slip that aims high; makevectors then flips the pitch, so the shot leaves low and HomeThink corrects it. + const p = g.p, diff = [p.o[0] - b.o[0], p.o[1] - b.o[1], p.o[2] + 50 - b.o[2] + HEAD], ang = Q.vectoangles(Q.norm(diff)); + if (dir === 0) ang[1] -= 25; else if (dir === 2) ang[1] += 25; + Q.spawnMissile(g, 'famshot', [b.o[0], b.o[1], b.o[2] + HEAD], Q.qcVectors(ang).f, 2, { speed: dir === 1 ? 800 : 700, turn: 5, src: 'famine_missile' }); + } + function volley(g, b) { + Q.fx(g, 'redflash', [b.o[0], b.o[1], b.o[2] + HEAD]); + missile(g, b, 0); missile(g, b, 1); missile(g, b, 2); + g.events.push({ type: 'boss_attack', name: 'famine_missiles', tick: g.t }); + } + function nearestPoint(g) { // famine_pointcheck: the rider_path point nearest the player with room for the horse + let best = -1, bd = Infinity; + g.paths.forEach((n, i) => { + const d = Q.len(Q.sub(n.o, g.p.o)), at = [n.o[0], n.o[1], 0]; + if (d < bd && !Q.pointSolid(g, at, ROOM.mins, ROOM.maxs) && !Q.touchesPlayer(g, ROOM, at)) { bd = d; best = i; } + }); + return best; + } + function rear(g, b) { // famhorse_rear + if (b.stage === BEGIN_REAR) { + const r = Q.advanceFrame(b, 16); + if (b.fr > 10) b.speed = 1; + Q.riderpathMove(g, b, b.speed, false); + if (r === Q.AF_END) { b.stage = MIDDLE_REAR; b.fr = 0; } + } else if (b.stage === MIDDLE_REAR) { + const r = Q.advanceFrame(b, 50); + if (b.fr === 10) { b.state = 'blinkout'; b.takedamage = false; b.solid = false; b.scale = 1; return; } + if (b.fr === 30 && g.p.hp > 0) volley(g, b); + if (r === Q.AF_END) { b.stage = Q.random(g) < 0.7 ? STANDING : END_REAR; b.fr = 0; } + } else if (b.stage === STANDING) { + if (Q.random(g) < 0.5) { b.stage = END_REAR; b.fr = 0; } + } else if (b.stage === END_REAR) { + const r = Q.advanceFrame(b, 16); + b.speed = b.fr < 11 ? 0 : b.fr < 13 ? SPEED * 0.5 : SPEED; + if (r === Q.AF_END) { b.state = 'move'; b.stage = NORMAL; b.fr = 0; } + Q.riderpathMove(g, b, b.speed, false); + } + } + function pain(g, b) { // famine_pain + if (b.stage !== NORMAL) return; + const rearChance = Math.max(b.hp / b.maxHp, 0.5), c = Q.random(g); + b.fr = 1; + if (c > rearChance) { b.state = 'rear'; b.stage = BEGIN_REAR; b.fr = 0; } + else if (c < 0.20) { b.stage = LAUGHING; b.rf = 1; } + else if (c < 0.60) { b.stage = ATTACK2; b.rf = 1; } + } + function move(g, b) { // famhorse_move + const now = Q.now(g), p = g.p, r = Q.advanceFrame(b, 12); + Q.riderpathMove(g, b, b.speed, false); + if (r === Q.AF_BEGINNING && b.stage === NORMAL && p.hp > 0) { + const rearChance = Math.max(b.hp / b.maxHp, 0.5), c = Q.random(g); + if (c > rearChance) { b.state = 'rear'; b.stage = BEGIN_REAR; b.fr = 0; return; } + if (c < 0.05) { b.stage = LAUGHING; b.rf = 1; } + else if (b.looktime < now && sees(g, [b.o[0], b.o[1], b.o[2] + HEAD])) { + const roll = Q.random(g); + if (Q.aggressive(g)) { + if (roll < 0.30) { b.pulltime = now + Q.random(g, 2, 5); b.stage = ATTACK; b.rf = 1; g.events.push({ type: 'boss_attack', name: 'famine_pull', tick: g.t }); } + else if (roll < 0.70) { b.stage = ATTACK2; b.rf = 1; } + } + } + } + if (b.stage === ATTACK) { + if (b.rf === 10 && p.hp > 0) { + // Both beams, 25 units either side at rider height, must reach the player's origin or the pull ends at once: cover breaks it. + const d = Q.norm([p.o[0] - b.o[0], p.o[1] - b.o[1], p.o[2] - b.o[2] + HEAD]), right = Q.qcVectors(Q.vectoangles(d)).r, from = [b.o[0], b.o[1], b.o[2] + HEAD]; + if (!sees(g, Q.ma(from, 25, right)) || !sees(g, Q.ma(from, -25, right))) b.pulltime = 0; + if (b.pulltime) { + b.beam = true; + p.v = Q.scale(Q.norm(Q.sub(p.o, b.o)), -250); p.onground = false; + } + if (b.hurttime < now) { // one damage tick a second: 300/distance held to 2..8 + Q.damagePlayer(g, Math.max(2, Math.min(8, 300 / Q.len(Q.sub(p.o, b.o)))), null, 'famine_pull'); + b.hurttime = now + 1; + } + if (b.pulltime < now) { b.rf += 50; b.looktime = now + Q.random(g, 5, 10) * g.tierScale.pause; b.beam = false; } + } else b.rf++; + if (b.rf >= 70) { b.stage = NORMAL; b.beam = false; } + } else if (b.stage === ATTACK2) { + if (b.rf === 10) { if (p.hp > 0) volley(g, b); b.rf += 50; } + b.rf++; + if (b.rf >= 70) b.stage = NORMAL; + } else if (b.stage === LAUGHING) { + if (++b.rf >= 16) b.stage = NORMAL; + } + } + Q.HP.famine = [2050, 4100, 10000]; + Q.CASES.push({ id: 'hexen2/blinking_tether_rider', name: 'Blinking Tether Rider', arena: 'famine' }); + const B = Q.brush; + // A dead threshing floor. Four granaries give real cover from the pull, whose beams need a clear line; the horse canters a ring around them. + Q.ARENAS.famine = { + title: 'Withered Threshing Floor (original arena)', size: [1920, 1920, 560], theme: 'famine', + brushes: [...Q.shell(1920, 1920, 560, { floor: 'dust', wall: 'stone', roof: 'sky' }), + B(640, 640, 0, 800, 800, 220, 'granary'), B(1120, 640, 0, 1280, 800, 220, 'granary'), B(640, 1120, 0, 800, 1280, 220, 'granary'), B(1120, 1120, 0, 1280, 1280, 220, 'granary'), + B(900, 900, 0, 1020, 1020, 300, 'well')], + paths: Q.ringPaths(Q.ring(960, 960, 760, 8, 0), 2), + player: [960, 420, 0, 90], boss: [960, 1720, 0, 270], + items: [['health', 180, 960, 10], ['health', 1740, 960, 10], ['health', 960, 180, 10], ['health', 960, 1740, 10], ['mana', 270, 270, 15], ['mana', 1650, 270, 15], ['mana', 270, 1650, 15], ['mana', 1650, 1650, 15], ['health', 860, 960, 10], ['health', 1060, 960, 10]], + }; + Q.BOSS.famine = { + title: 'Blinking Tether Rider', + spawn(g, o, yaw, hp) { + return { kind: 'famine', o: o.slice(), yaw, ideal_yaw: yaw, yaw_speed: 10, speed: SPEED, path_distance: 75, mins: [-40, -40, 0], maxs: [40, 40, 100], hp, maxHp: hp, path: 0, fr: 0, rf: 0, + state: 'move', stage: NORMAL, scale: 1, solid: true, takedamage: true, looktime: 0, pulltime: 0, hurttime: 0, wait: 0, beam: false, y_change: 0, move_adjust: 0 }; + }, + think(g, b) { + if (b.state === 'move') move(g, b); + else if (b.state === 'rear') rear(g, b); + else if (b.state === 'blinkout') { // famine_blinkout: 0.1 scale per half frame, gone below .1, back in 0.5-3 s + b.scale -= 0.2; + if (b.scale < 0.10) { b.state = 'hidden'; b.wait = Math.round(Q.random(g, 0.5, 3) * 20); } + } else if (b.state === 'hidden') { + if (--b.wait <= 0) { + const i = nearestPoint(g); + if (i >= 0) { b.path = i; b.o = [g.paths[i].o[0], g.paths[i].o[1], 0]; } + b.solid = true; b.takedamage = true; b.state = 'blinkin'; b.scale = 0.1; + Q.pathNext(g, b); + b.yaw = b.ideal_yaw = Q.vectoyaw(Q.sub(g.paths[b.path].o, b.o)); + Q.fx(g, 'redcloud', [b.o[0], b.o[1], 40]); + } + } else if (b.state === 'blinkin') { + b.scale += 0.10; + if (b.scale >= 1) { b.scale = 1; b.state = 'rear'; } + } + }, + targets(g, b) { return b.takedamage ? [Object.assign({ id: 'horse' }, Q.boxAt(b, b.o))] : []; }, + aim(g, b) { return [b.o[0], b.o[1], b.o[2] + 60]; }, + vel(g, b) { const r = b.yaw * Q.DEG, s = b.state === 'move' ? b.speed * 20 : 0; return [Math.cos(r) * s, Math.sin(r) * s, 0]; }, + hurt(g, b, id, dmg) { b.hp -= dmg; if (b.hp <= 0) { b.hp = 0; g.bossKilled = true; } else pain(g, b); }, + progress(g, b) { return b.hp; }, + max(g, b) { return b.maxHp; }, + phase(g, b) { return b.beam ? 'Soul Pull' : { blinkout: 'Blink', hidden: 'Blink', blinkin: 'Blink' }[b.state] || { 4: 'Soul Pull', 6: 'Laughter', 7: 'Triple Homing Missiles' }[b.stage] || (b.state === 'rear' ? 'Reeling' : 'Charging'); }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/boss_pestilence.js b/environments/games/web/games/hexen2_remake/boss_pestilence.js new file mode 100644 index 0000000000000000000000000000000000000000..0052339c883061f91aee8a1508b9f4b6cdbc1dce --- /dev/null +++ b/environments/games/web/games/hexen2_remake/boss_pestilence.js @@ -0,0 +1,145 @@ +/* Pestilence, rider_pestilence (pstboar.hc). The only rider that hunts: while it sees the player (or for 5 s after) it walks straight at them on its own yaw, ramming on contact; otherwise it + follows the rider_path graph. Every frame the rider, turning on his own up to 89 degrees from the boar, may act if the player is in front of him: chance = random(100), divided by 3 for + pain_finished: < 3 hive (none of its swarms left), < 5 poison arrow, < 8 charge. T_Damage sets pain_finished to +5 s at skill 3, which is why Nightmare's Pestilence shoots so much more. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q; + const NORMAL = 0, ATTACK = 1, ATTACK2 = 2, CHARGE = 3, CHARGE_ST = 4, CHARGE_END = 5, STAND = 6, BACKUP = 7; + const SPEEDS = [7, 7, 7, 20, 15, 15, 7, 7], FRAMES = [12, 12, 12, 8, 8, 8, 1, 12]; + const now = Q.now; + const eyeLine = (g, b) => Q.clear(g, [b.o[0], b.o[1], b.o[2] + 30], Q.eye(g.p)); + const inFront = (g, b) => { const d = Q.norm(Q.sub(g.p.o, b.o)), r = b.ryaw * Q.DEG; return d[0] * Math.cos(r) + d[1] * Math.sin(r) > 0.3; }; // infront_of_ent(enemy, movechain) + function poison(g) { g.p.poison.push({ next: g.t + 3, until: g.t + Math.round(Q.random(g, 5, 10) * 20) * 3 }); } + Q.MISSILE.poison = { + think(g, m) { Q.home(g, m); }, + touch(g, m, hitPlayer) { if (hitPlayer) { poison(g); Q.damagePlayer(g, Q.random(g, 10, 20), m.o, 'pest_arrow'); } Q.fx(g, 'greenspark', m.o); }, + expire(g, m) { Q.fx(g, 'greenspark', m.o); }, + }; + // throw_hive: MOVETYPE_BOUNCE under gravity; breaks into three swarms on any touch, when shot, or after 2.5 s. + const burst = (g, m) => { const b = g.boss; for (let i = 0; i < 3; i++) b.swarms.push({ o: [m.o[0], m.o[1], m.o[2] + 5], age: 0, life: 10 + 400, id: g.fxSeq++ }); b.cnt += 3; Q.fx(g, 'greenspark', m.o, { r: 30 }); }; + Q.MISSILE.hive = { + think(g, m) { m.v[2] -= 800 * Q.DT; }, + touch(g, m) { burst(g, m); }, + expire(g, m) { burst(g, m); }, + }; + function arrow(g, b) { + const v = Q.qcVectors([0, b.ryaw]); + Q.spawnMissile(g, 'poison', [b.o[0] + v.f[0] * 20, b.o[1] + v.f[1] * 20, b.o[2] + 90], v.f, 2, { speed: 700, turn: 3 }); + g.events.push({ type: 'boss_attack', name: 'pest_arrow', tick: g.t }); + } + function throwHive(g, b) { + const v = Q.qcVectors([0, b.ryaw]), o = [b.o[0] + v.f[0] * 25, b.o[1] + v.f[1] * 25, b.o[2] + 110], d = Q.norm(Q.sub(Q.eye(g.p), o)); + Q.spawnMissile(g, 'hive', o, Q.scale([d[0] + v.u[0] * 0.5, d[1] + v.u[1] * 0.5, d[2] + v.u[2] * 0.5], 500), 2.5, { r: 14, hp: 1 }); + g.events.push({ type: 'boss_attack', name: 'pest_hive', tick: g.t }); + } + // Swarms: 10 frames growing, 20 s alive at velocity 100 toward the player plus movetogoal(10) a frame, 15 frames dying. A touch hurts 3-10 with chance .1 a frame on flesh. + function swarmsThink(g, b) { + const p = g.p, c = Q.center(p); + b.swarms = b.swarms.filter(s => { + if (++s.age > s.life + 15) { b.cnt--; return false; } + if (s.age > 10 && s.age <= s.life && p.hp > 0) { const d = Q.norm(Q.sub(c, s.o)); s.o = Q.ma(s.o, 15, d); } + if (s.age > 10 && p.hp > 0 && Math.abs(c[0] - s.o[0]) < 66 && Math.abs(c[1] - s.o[1]) < 66 && Math.abs(c[2] - s.o[2]) < 78 && Q.random(g) < 0.1) Q.damagePlayer(g, Q.random(g, 3, 10), null, 'pest_swarm'); + return true; + }); + } + function step(g, b) { // psthorse_move's movement half + const p = g.p, t = now(g), o0 = b.o.slice(); let hitPlayer = false; + if ((p.hp > 0 && eyeLine(g, b)) || b.search_time > t) { + const res = Q.walkMove(g, b, b.yaw, b.speed); + if (res !== 'ok') { + if (res === 'player') { hitPlayer = true; if (b.torchtime < t) { b.torchtime = t + 0.5; Q.ram(g, b); } } + const y = Q.vectoyaw(Q.sub(p.o, b.o)); + for (const off of [0, 45, -45, 90, -90]) if (Q.walkMove(g, b, y + off, Math.abs(b.speed)) === 'ok') break; // movetogoal (approximation) + if (b.stage === BACKUP) b.stage = b.mode = NORMAL; + } + } else Q.riderpathMove(g, b, Math.abs(b.speed), true); + // Stuck: 30 frames of little progress back up for 3 s. + if (Q.len(Q.sub(b.o, o0)) < Math.abs(b.speed) * 0.75 && b.turn_time < t && !hitPlayer) b.aflag++; else b.aflag = 0; + b.ideal_yaw = Q.vectoyaw(Q.sub(p.o, b.o)); + if (b.aflag > 30) { b.stage = BACKUP; b.aflag = 0; b.turn_time = t + 3; } + if (b.aflag) { + const r = b.yaw * Q.DEG, f = [Math.cos(r), Math.sin(r), 0], tr = Q.traceWorld(g, b.o, Q.ma(b.o, 200, f), [-48, -48, 0], [48, 48, 100]); + if (tr.normal) b.ideal_yaw = Q.vectoyaw([(tr.normal[0] + f[0]) * 0.5, (tr.normal[1] + f[1]) * 0.5, 0]); + } + Q.changeYaw(b); + } + Q.HP.pestilence = [3000, 4700, 10000]; + Q.CASES.push({ id: 'hexen2/boar_archer_rider', name: 'Boar-Riding Poison Archer', arena: 'pestilence' }); + const B = Q.brush; + // A drowned charnel hall. The boar is wide (168 units), so the low crypt rows make it steer while the player slips between; pillars stop arrows and its line of sight. + Q.ARENAS.pestilence = { + title: 'Rotting Marsh Hall (original arena)', size: [2240, 2048, 620], theme: 'pestilence', + brushes: [...Q.shell(2240, 2048, 620, { floor: 'moss', wall: 'rot', roof: 'sky' }), + B(560, 520, 0, 680, 640, 400, 'rot'), B(1560, 520, 0, 1680, 640, 400, 'rot'), B(560, 1408, 0, 680, 1528, 400, 'rot'), B(1560, 1408, 0, 1680, 1528, 400, 'rot'), + B(1060, 964, 0, 1180, 1084, 400, 'rot'), B(1040, 420, 0, 1200, 500, 60, 'moss'), B(1040, 1548, 0, 1200, 1628, 60, 'moss')], + paths: Q.ringPaths(Q.ring(1120, 1024, 820, 8, 0), 2), + player: [1120, 260, 0, 90], boss: [1120, 1760, 0, 270], + items: [['health', 200, 1024, 10], ['health', 2040, 1024, 10], ['health', 1120, 200, 10], ['health', 1120, 1848, 10], ['mana', 300, 300, 15], ['mana', 1940, 300, 15], ['mana', 300, 1748, 15], ['mana', 1940, 1748, 15], ['health', 860, 1024, 10], ['health', 1380, 1024, 10]], + }; + Q.BOSS.pestilence = { + title: 'Boar-Riding Poison Archer', + spawn(g, o, yaw, hp) { + // monster_awake is set from the start: in the original a trigger wakes it; an arena fight begins with the fight. + return { kind: 'pestilence', o: o.slice(), yaw, ideal_yaw: yaw, yaw_speed: 4, speed: 7, path_distance: 200, mins: [-84, -84, 0], maxs: [84, 84, 100], hp, maxHp: hp, path: 0, fr: 0, rf: 0, stage: STAND, mode: STAND, solid: true, + ryaw: yaw, cnt: 0, level: 0, lifespan: 0, pain_finished: 0, search_time: 0, turn_time: 0, torchtime: 0, aflag: 0, swarms: [], y_change: 0, move_adjust: 0 }; + }, + think(g, b) { + const p = g.p, t = now(g); + if (b.stage !== STAND) { const r = Q.advanceFrame(b, FRAMES[b.stage]); b.lastAF = r; step(g, b); } + const vis = p.hp > 0 && eyeLine(g, b); + if (vis) b.search_time = t + 5; + // The rider turns on his own, at most 89 degrees off the boar's heading (the source's clamp), else he faces forward. + let rel = 0; if (b.mode < CHARGE_ST && vis) rel = Math.max(-89, Math.min(89, Q.angdiff(Q.vectoyaw(Q.sub(p.o, b.o)) - b.yaw))); + const rr = { yaw: b.ryaw, ideal_yaw: b.yaw + rel, yaw_speed: 10 }; Q.changeYaw(rr); b.ryaw = rr.yaw; + if (b.mode === ATTACK || b.mode === ATTACK2) b.rf++; + if (b.mode === ATTACK) { + if (b.rf === 4) arrow(g, b); + if (b.rf >= 6) b.mode = b.stage === BACKUP ? NORMAL : b.stage; + } else if (b.mode === ATTACK2) { + if (b.rf === 33) throwHive(g, b); + if (b.rf >= 38) b.mode = b.stage === BACKUP ? NORMAL : b.stage; + } + if (b.stage >= CHARGE && b.stage < STAND) { + if (b.stage === CHARGE_ST && b.fr === 8) { b.stage = b.mode = CHARGE; b.fr = 0; } + else if (b.stage === CHARGE && b.fr === 8) { + b.level++; // never reset in the source: the first charge runs 8-16 s, later ones end at their first cycle + if (b.level >= Q.random(g, 20, 40)) { b.stage = b.mode = CHARGE_END; b.fr = 0; } + } else if (b.stage === CHARGE_END && b.fr === 8) { b.lifespan = t + 5; b.stage = b.mode = NORMAL; b.yaw_speed = 4; b.fr = 0; } + if (b.mode === CHARGE && Q.random(g, 1000) <= 5 && vis && (inFront(g, b) || Q.random(g) < 0.2)) { + if (Q.random(g) < 0.1 && b.cnt <= 0) { b.mode = ATTACK2; b.rf = 1; } else { b.mode = ATTACK; b.rf = 1; } + } + } + const want = SPEEDS[b.stage]; let sp = Math.abs(b.speed); + sp = Math.abs(want - sp) < 0.2 ? want : want > sp ? sp + 0.2 : sp - 0.2; + b.speed = sp; + if (b.stage === BACKUP) { if (b.turn_time < t) b.stage = b.mode = NORMAL; else b.speed = -sp; } + if (b.mode === NORMAL && vis && inFront(g, b)) { + let c = Q.random(g, 100); if (b.pain_finished > t) c /= 3; + if (c < 8 && Q.aggressive(g)) { + if (c < 3 && b.cnt <= 0) { b.mode = ATTACK2; b.rf = 1; } + else if (c < 5) { b.mode = ATTACK; b.rf = 1; } + else if (c >= 5 && b.stage < CHARGE && b.lifespan < t) { b.mode = b.stage = CHARGE_ST; b.fr = 0; b.yaw_speed = 8; g.events.push({ type: 'boss_attack', name: 'pest_charge', tick: g.t }); } + } + } else if (b.stage === STAND) { + if (b.rf >= 12) { b.fr = 1; b.rf = 0; b.stage = b.mode = NORMAL; } else b.rf++; + } + swarmsThink(g, b); + }, + targets(g, b) { + const out = [Object.assign({ id: 'boar' }, Q.boxAt(b, b.o))]; + for (const m of g.missiles) if (m.k === 'hive') out.push({ id: 'hive:' + m.id, mins: m.o.map(v => v - 8), maxs: m.o.map(v => v + 8) }); + return out; + }, + aim(g, b) { return [b.o[0], b.o[1], b.o[2] + 56]; }, + vel(g, b) { const r = b.yaw * Q.DEG, s = b.speed * 20; return [Math.cos(r) * s, Math.sin(r) * s, 0]; }, + hurt(g, b, id, dmg) { + if (id !== 'boar') { const m = g.missiles.find(x => 'hive:' + x.id === id); if (m) { burst(g, m); g.missiles = g.missiles.filter(x => x !== m); } return; } + b.hp -= dmg; if (b.hp <= 0) { b.hp = 0; g.bossKilled = true; return; } + b.pain_finished = now(g) + (g.skill === 3 ? 5 : 0.5); // pest_hurt +.5; T_Damage overwrites it with +5 at skill 3 + }, + progress(g, b) { return b.hp; }, + max(g, b) { return b.maxHp; }, + phase(g, b) { return b.stage === CHARGE || b.stage === CHARGE_ST ? 'Charge' : b.mode === ATTACK ? 'Poison Arrow' : b.mode === ATTACK2 ? 'Hive Throw' : b.stage === BACKUP ? 'Retreat' : b.stage === STAND ? 'Rise up' : 'Chase'; }, + warn(g, b) { return b.stage === CHARGE_ST ? 'The boar is charging: strafe aside' : g.p.poison.length ? 'Poisoned: 1 damage per stack per second' : null; }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/boss_praevus.js b/environments/games/web/games/hexen2_remake/boss_praevus.js new file mode 100644 index 0000000000000000000000000000000000000000..77eca7a6100a94ff5f728c1161c8daddd92ff1bd --- /dev/null +++ b/environments/games/web/games/hexen2_remake/boss_praevus.js @@ -0,0 +1,182 @@ +/* Praevus (portals/buddha.hc, Portal of Praevus). Built in steps: M1 = birth, run, decide (star volley only), damage and progress. Fire wall, fire pillars, + storm, recharge, teleport and the six-piece shield come in M2/M3; until then their decide branches "return 1 and do nothing" (rolled again next frame). */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q; + // EASY: user 11-11 "Easy can be changed; preferably keep the full fight" (fill the easy window): on skill 0 only, recharge skips the rewait rounds (rechar 20 + recharge_done 11 frames: 1.55 s + // untouchable, not ~6 s) and the teleport stays hidden 0.5 s (not random(2,3)). The moves, their frames and normal / hard are the original's. + const EASY = g => g.skill === 0, EASY_HOLD = 8; + const now = Q.now, CHEST = 50, STORM = [1200, 1200, 560], STORM_R = 1000, SHARD_R = 125; + // The mission pack's storm locked to Praevus: 50 a beam and the cascade goes on (portals/lightning.hc:320-323). + const strike = g => Q.lightningStrike(g, STORM, STORM_R, 50, 'praevus_lightning'); + // Shield: 6 shards at 60k degrees + 100 deg/s round the boss, radius 125 (5 while teleporting), box +-32 from the floor to 128; 500 + 200 * skill each, scaled with the boss's own table; never come back. + const shardAt = (g, b, k) => { const a = (60 * (k + 1) + 100 * now(g)) * Q.DEG, r = b.shardR; return [b.o[0] + Math.cos(a) * r, b.o[1] + Math.sin(a) * r]; }; + const hidden = b => b.state === 'gone' || b.state === 'shrink' || b.state === 'grow'; + const set = (b, state) => { b.state = state; b.fr = 0; }; + const faceEnemy = (g, b) => { b.ideal_yaw = Q.vectoyaw(Q.sub(g.p.o, b.o)); Q.changeYaw(b); }; // ai_face + // praevus_star: 400 u/s, turn_time 0.2, veer 1, hoverz, HomeThink every 0.1 s, 5 s. 10 * random(2,3) on the player (BSpark); nothing on the world. + Q.MISSILE.pstar = { + think(g, m) { m.age = (m.age || 0) + 1; if (m.age % 2 === 0) { Q.home(g, m); Q.veer(g, m, 1); } }, + touch(g, m, hitPlayer) { if (hitPlayer) Q.damagePlayer(g, 10 * Q.random(g, 2, 3), m.o, 'praevus_star'); Q.fx(g, 'spark', m.o, { r: 6 }); }, + }; + // do_point: one star on point2/6/9 with v_right offsets -0.45 / 0 / +0.45 added to the unit aim and not renormalised, x400. + const DFLAG = { 2: -0.45, 6: 0, 9: 0.45 }; + function star(g, b, dflag) { + const v = Q.qcVectors([0, b.yaw]), base = [b.o[0], b.o[1], b.o[2] + CHEST], o = Q.ma(base, 164, v.f); + const dir = Q.norm(Q.sub(Q.eye(g.p), Q.ma(base, 256, v.f))), w = Q.ma(dir, dflag, v.r); + Q.spawnMissile(g, 'pstar', o, Q.scale(w, 400), 5, { speed: 400, turn: 0.2, hover: true, r: 10 }); + if (dflag === -0.45) g.events.push({ type: 'boss_attack', name: 'praevus_star', tick: g.t }); + } + // Fire pillar (do_firepillar): under the player's feet on the ground, active after 0.2 s, every 0.1 s 2 to a player within 64, drifts up 100 u/s, 2.5 s. + function pillar(g, b) { + const tr = Q.traceWorld(g, [g.p.o[0], g.p.o[1], g.p.o[2] + 40], [g.p.o[0], g.p.o[1], -600]); + b.pillars.push({ o: [g.p.o[0], g.p.o[1], tr.end[2]], age: 0 }); + } + // firewalker: box +-100 from the boss's front 64, flies along its yaw at 125 + 25 * skill for random(5,10) s, stops on a brush. + // firewalker_check_damage every QC frame: boxes overlap, the player ahead of the wall's back (o - 64 f), forward < 128 and lateral < 200 -> skill + 1. + function walker(g, b) { + const v = Q.qcVectors([0, b.yaw]); + b.walls.push({ o: Q.ma([b.o[0], b.o[1], b.o[2]], 64, v.f), f: [v.f[0], v.f[1], 0], speed: 125 + 25 * g.skill, life: Math.round(Q.random(g, 5, 10) * 20) }); + g.events.push({ type: 'boss_attack', name: 'praevus_firewall', tick: g.t }); + } + const WALL_MIN = [-100, -100, 1], WALL_MAX = [100, 100, 100]; + function hazards(g, b) { + const p = g.p, pb = Q.playerBox(p); + b.pillars = b.pillars.filter(h => { + h.age++; if (h.age > 50) return false; + h.o[2] += 100 * Q.DT; + if (h.age >= 4 && h.age % 2 === 0 && p.hp > 0 && Q.len(Q.sub(Q.center(p), h.o)) < 64) Q.damagePlayer(g, 2, h.o, 'praevus_pillar'); + return true; + }); + b.walls = b.walls.filter(w => { + if (--w.life <= 0) return false; + const n = Q.ma(w.o, w.speed * Q.DT, w.f); + if (!Q.pointSolid(g, n, WALL_MIN, WALL_MAX)) w.o = n; + if (p.hp <= 0) return true; + const over = p.o[0] + pb.maxs[0] > w.o[0] - 100 && p.o[0] + pb.mins[0] < w.o[0] + 100 && p.o[1] + pb.maxs[1] > w.o[1] - 100 && p.o[1] + pb.mins[1] < w.o[1] + 100 && p.o[2] < w.o[2] + 100; + if (!over) return true; + const d = Q.sub(p.o, Q.ma(w.o, -64, w.f)), fw = d[0] * w.f[0] + d[1] * w.f[1], side = Math.abs(d[0] * -w.f[1] + d[1] * w.f[0]); + if (fw > 0 && fw < 128 && side < 200) Q.damagePlayer(g, g.skill + 1, w.o, 'praevus_firewall'); + return true; + }); + } + function warp(g, b) { // teleport_buddha points, skipping the last one + const W = Q.ARENAS.praevus.warps; let k; do k = Math.floor(Q.random(g, W.length)); while (k === b.warp || k >= W.length); b.warp = k; b.o = W[k].slice(); + } + // decide_attack. 1 = an attack started (or the teleport cooldown, which does nothing); 0 = rest. BossBench easy: Q.aggressive fails -> treated as 0. + function decide(g, b) { + const r = Q.random(g); + if (r <= 0.2) return 0; + if (!Q.aggressive(g)) return 0; + if (r > 0.9) { if (b.teleport_time <= now(g)) { b.teleport_time = now(g) + 10; b.god = true; b.spin = 0; b.count = 0; set(b, 'tele'); g.events.push({ type: 'boss_attack', name: 'praevus_teleport', tick: g.t }); } return 1; } + if (r > 0.7) { set(b, 'point'); return 1; } + if (r > 0.5) { set(b, 'pillar'); return 1; } + if (r > 0.3) { set(b, 'firewall'); return 1; } + set(b, 'conjure'); g.events.push({ type: 'boss_attack', name: 'praevus_conjure', tick: g.t }); return 1; + } + const STEP = { + birth(g, b) { if (++b.fr === 16) { b.wait = now(g) + Q.random(g, 1, 2); set(b, 'wait'); } }, + // EASY (user 11-11): the opening holds at least EASY_HOLD s of fight time before the boss can be hurt (a longer wait between birth and rise), which lifts the quick fights. + wait(g, b) { if (now(g) >= b.wait && (!EASY(g) || now(g) >= EASY_HOLD)) set(b, 'rise'); }, + rise(g, b) { if (++b.fr === 8) set(b, 'spindown'); }, + // spindown: avelocity_y -= count, count -= 2.5 every 0.05 s until <= 150; then turn to the player and only once faced take damage and go to run. + spindown(g, b) { + if (b.spin > 150) { b.yaw = Q.anglemod(b.yaw + b.spin * Q.DT); b.spin -= b.count; b.count = Math.max(0, b.count - 2.5); return; } + faceEnemy(g, b); + if (Math.abs(Q.angdiff(b.yaw - b.ideal_yaw)) < 10) { b.god = false; b.solid = true; set(b, 'run'); } + }, + run(g, b) { // praevus_run (ready1..20): recharge thresholds, ai_face, decide when attack_finished has passed; the ret quirk rerolls the rest every frame + if (b.dmgtime < 4 && b.hp <= b.maxHp * (4 - b.dmgtime) / 5) { b.dmgtime++; b.god = true; set(b, 'recharge'); g.events.push({ type: 'boss_phase', name: 'praevus_recharge', tick: g.t }); return; } + faceEnemy(g, b); + const t = now(g); + if (b.attack_finished < t) { b.ret = decide(g, b); if (b.state !== 'run') return; } + if (!b.ret) b.attack_finished = t + Math.round(Q.random(g, 6 / Math.max(g.skill, 1) + 0.1)) * g.tierScale.pause; + }, + conjure(g, b) { b.fr++; faceEnemy(g, b); if (b.fr === 13) { b.wait = now(g) + Q.random(g, 2, 4); set(b, 'storm'); } }, + storm(g, b) { if (Q.random(g) < 0.7) strike(g); if (now(g) > b.wait) set(b, 'endstorm'); }, + endstorm(g, b) { if (++b.fr === 8) set(b, 'run'); }, + // recharge: no health back, only ~6 s untouchable (rechar 20 frames, rewait 30-frame rounds until lifetime(+4 s) has passed at frame 30, recharge_done 11 frames), then a fire wall. + recharge(g, b) { if (++b.fr === 20) { b.lifetime = 0; set(b, EASY(g) ? 'rechdone' : 'rewait'); } }, + rewait(g, b) { + b.fr++; + if (b.fr === 1 && b.lifetime < now(g)) b.lifetime = now(g) + 4; + if (b.fr === 30) { if (b.lifetime < now(g)) set(b, 'rechdone'); else b.fr = 0; } + }, + rechdone(g, b) { if (++b.fr === 11) { b.god = false; set(b, 'firewall'); } }, + // teleport: 26 frames spinning up (avelocity += count, count += 2.5), shrink 0.1 every 0.1 s, gone random(2,3) s, warp, grow 0.1 a frame, spindown, run. + tele(g, b) { b.fr++; b.yaw = Q.anglemod(b.yaw + b.spin * Q.DT); b.spin += b.count; b.count += 2.5; b.shardR = Math.max(5, SHARD_R - 120 * b.fr / 26); if (b.fr === 26) { b.solid = false; set(b, 'shrink'); } }, + shrink(g, b) { b.sub = !b.sub; if (b.sub) return; b.scale = Math.round((b.scale - 0.1) * 10) / 10; if (b.scale <= 0.1) { b.wait = now(g) + (EASY(g) ? 0.5 : Q.random(g, 2, 3)); warp(g, b); set(b, 'gone'); } }, + gone(g, b) { if (now(g) >= b.wait) set(b, 'grow'); }, + grow(g, b) { b.scale = Math.round((b.scale + 0.1) * 10) / 10; if (b.scale >= 1) { b.scale = 1; b.shardR = SHARD_R; set(b, 'spindown'); } }, + pillar(g, b) { // push1..30 a round; count = random(0,0.3)*10 on the first frame (rerolled while 0), one round per started unit + b.fr++; faceEnemy(g, b); + if (b.fr === 1 && !b.rounds) { do b.pcount = Q.random(g, 0, 0.3) * 10; while (b.pcount === 0); b.rounds = true; g.events.push({ type: 'boss_attack', name: 'praevus_pillar', tick: g.t }); } + if (b.fr === 4) { b.pcount -= 1; let n = Q.random(g, 1, 2); while (n > 0) { pillar(g, b); n -= 1; } } + if (b.fr === 30) { if (b.pcount <= 0) { b.rounds = false; set(b, 'run'); } else b.fr = 0; } + }, + firewall(g, b) { b.fr++; faceEnemy(g, b); if (b.fr === 33) set(b, 'sendwall'); }, // push1..33: charge, facing the player + sendwall(g, b) { b.fr++; if (b.fr === 2) walker(g, b); if (b.fr === 37) set(b, 'run'); }, + point(g, b) { + b.fr++; faceEnemy(g, b); + if (DFLAG[b.fr] !== undefined) star(g, b, DFLAG[b.fr]); + if (b.fr === 12) set(b, 'run'); + }, + }; + // Health scales across difficulty tiers. + Q.HP.praevus = [1000, 2000, 4300]; + Q.CASES.push({ id: 'hexen2/star_volley_sorcerer', name: 'Star Volley Sorcerer', arena: 'praevus' }); + const B = Q.brush; + // A moonlit cloister (original): a square court with four broken columns at the warp points' corners and two low altars that block stars but not the view from above. + const COLS = [[700, 700], [1700, 700], [700, 1700], [1700, 1700]]; + Q.ARENAS.praevus = { + title: 'Starlit Corridor (original arena)', size: [2400, 2400, 1000], theme: 'praevus', + brushes: [...Q.shell(2400, 2400, 1000, { floor: 'marble', wall: 'obsidian', roof: 'sky' }), + ...COLS.map(([x, y]) => B(x - 48, y - 48, 0, x + 48, y + 48, 260, 'crystal')), + B(1100, 1150, 0, 1300, 1250, 56, 'crystal')], + paths: [], warps: [[1200, 2000, 0], [400, 1200, 0], [2000, 1200, 0], [1200, 1700, 0]], + player: [1200, 300, 0, 90], boss: [1200, 2000, 0, 270], + items: [['health', 180, 1200, 10], ['health', 2220, 1200, 10], ['health', 1200, 150, 10], ['health', 1200, 2250, 10], ['mana', 280, 280, 15], ['mana', 2120, 280, 15], ['mana', 280, 2120, 15], ['mana', 2120, 2120, 15], ['mana', 1000, 200, 15], ['mana', 1400, 2200, 15], ['health', 380, 1200, 10], ['health', 2020, 1200, 10]], + }; + Q.BOSS.praevus = { + title: 'Star Volley Sorcerer', + spawn(g, o, yaw, hp) { + const sh = Math.round((500 + 200 * g.skill) * hp / (5000 + 1000 * g.skill)); + return { shards: [sh, sh, sh, sh, sh, sh], shardMax: sh, shardR: SHARD_R, scale: 1, sub: false, warp: 0, teleport_time: 0, lifetime: 0, kind: 'praevus', o: o.slice(), yaw, ideal_yaw: yaw, yaw_speed: 10, mins: [-32, -32, 0], maxs: [32, 32, 120], maxHp: hp, hp, + state: 'birth', fr: 0, wait: 0, spin: 450, count: 40, solid: false, god: true, ret: 0, attack_finished: 0, dmgtime: 0, pcount: 0, rounds: false, pillars: [], walls: [] }; + }, + think(g, b) { STEP[b.state](g, b); hazards(g, b); }, + targets(g, b) { + const out = b.solid ? [Object.assign({ id: 'body' }, Q.boxAt(b, b.o))] : []; + if (!hidden(b)) for (let k = 0; k < 6; k++) if (b.shards[k] > 0) { const c = shardAt(g, b, k); out.push({ id: 'shard' + k, mins: [c[0] - 32, c[1] - 32, b.o[2]], maxs: [c[0] + 32, c[1] + 32, b.o[2] + 128] }); } + return out; + }, + aim(g, b) { return [b.o[0], b.o[1], b.o[2] + 70]; }, + dryGoal() { return null; }, + vel() { return [0, 0, 0]; }, // never walks; teleport (M3) is a jump, not a velocity + // The storm calls lightning round the arena centre (radius 1000), as the serpent's roar: the corners are almost never hit. The banner shows it, so this reads only what is shown. + goal(g, b) { + if (b.state === 'conjure' || b.state === 'storm') { + const p = g.p.o; + // EASY (user 11-11): only step out to the storm's edge (r 1050 on the player's bearing from the centre), not the far corner, so the fight keeps its line of fire. + if (EASY(g)) { const d = Q.norm([p[0] - STORM[0], p[1] - STORM[1], 0]), c = v => Math.max(170, Math.min(2230, v)); return Q.len(Q.sub([p[0], p[1], 0], [STORM[0], STORM[1], 0])) > 1050 ? null : [c(STORM[0] + d[0] * 1050), c(STORM[1] + d[1] * 1050), 0]; } + return [p[0] < 1200 ? 180 : 2220, p[1] < 1200 ? 180 : 2220, 0]; + } + // EASY (user 11-11): top up mana before it runs out (below 50, not the shared 25), at the nearest live crystal, so the fight never falls back to the sword walk-in. + if (false && (g.p.green < 50 || g.p.blue < 50)) { let best = null, bd = Infinity; for (const it of g.items) { if (it.k !== 'mana' || it.respawn > g.t) continue; const d = Q.len(Q.sub(it.o, g.p.o)); if (d < bd) { bd = d; best = it; } } if (best) return [best.o[0], best.o[1], 0]; } + // EASY only (user 11-11, fill the easy window): close to ~600 while the boss is out and mana is not low (the supply run and the dry sword walk-in keep their own goals), so the purifier's flight time and misses stop stretching the fight. Reads position and state only. + if (EASY(g) && b.state !== 'gone' && g.p.green >= 25 && g.p.blue >= 25 && Q.len(Q.sub(g.p.o, b.o)) > 700) { const d = Q.norm([g.p.o[0] - b.o[0], g.p.o[1] - b.o[1], 0]); return [b.o[0] + d[0] * 600, b.o[1] + d[1] * 600, 0]; } + return null; + }, + shootable(g, b, id) { return id !== 'body' || !b.god; }, + hurt(g, b, id, dmg) { + if (id !== 'body') { const k = +id.slice(5); b.shards[k] = Math.max(0, b.shards[k] - dmg); if (!b.shards[k]) g.events.push({ type: 'boss_phase', name: 'praevus_shard_broken', tick: g.t }); return; } + if (b.god) return; + b.hp -= dmg; + if (b.hp <= 0) { b.hp = 0; g.bossKilled = true; } + }, + progress(g, b) { return b.hp; }, + max(g, b) { return b.maxHp; }, + phase(g, b) { return { birth: 'Appearing', wait: 'Appearing', rise: 'Rising', spindown: 'Turning to Face You', point: 'Triple Star Bolt', pillar: 'Fire pillar', firewall: 'Charging Fire Wall', sendwall: 'Launching Fire Wall', conjure: 'Summon Storm', storm: 'Thunderstorm', endstorm: 'Thunderstorm', recharge: 'Charging (invulnerable)', rewait: 'Charging (invulnerable)', rechdone: 'Charging (invulnerable)', tele: 'Teleport', shrink: 'Teleport', gone: 'Teleporting', grow: 'Appearing', }[b.state] || 'Idle'; }, + warn(g, b) { return b.state === 'point' ? 'Star bolts track you: strafe or use a pillar' : b.state === 'firewall' ? 'Fire wall incoming: move sideways beyond its width' : b.state === 'pillar' ? 'A fire pillar is rising beneath you: move away' : b.state === 'conjure' || b.state === 'storm' ? 'Lightning incoming: take cover in a corner' : b.god && b.state !== 'birth' && b.state !== 'wait' ? 'Invulnerable' : null; }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/boss_war.js b/environments/games/web/games/hexen2_remake/boss_war.js new file mode 100644 index 0000000000000000000000000000000000000000..a0fc780b495394740dfd56e6ac81660d082d2f3a --- /dev/null +++ b/environments/games/web/games/hexen2_remake/boss_war.js @@ -0,0 +1,89 @@ +/* War, rider_war (warhorse.hc). Three gaits by how hard the path bends: fast 12 frames at speed 12, middle 16 frames at speed 10, slow 20 frames at speed 6; each cycle's end shifts a gait down if it turned + 15 degrees or more that cycle, else up. Every cycle attacks: the gait sets how many axes are thrown (2, 3, 4). On a straight run (under 1 degree) 10% rear: one big exploding axe, then 70% a standing volley. + Odd source rule kept as written: a horizontal axe is not spawned at chance .3 + skill/10, so higher skill throws fewer small axes. rider_quake_center_use returns at once in the source, so no earthquake. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q; + const NORMAL = 0, BEGIN_REAR = 1, MIDDLE_REAR = 2, END_REAR = 3, ATTACK = 4, STANDING = 5; + const SPEED = [12, 10, 6], LEN = [12, 16, 20]; + // Frames of the throw per gait with the throwing hand's offset (right, forward, up): RaxeA8/A9, RaxeB10/12/13, RaxeC12/13/14/15. + const THROWS = [{ 8: [3, 3, 82], 9: [-3, 3, 70] }, { 10: [3, 3, 82], 12: [-3, 3, 70], 13: [0, 3, 70] }, { 12: [3, 3, 82], 13: [2, 3, 78], 14: [0, 3, 74], 15: [-3, 3, 70] }]; + const hits = (g, m, hitPlayer) => hitPlayer ? Q.damagePlayer(g, m.dmg, m.o, m.big ? 'war_big_axe' : 'war_axe') : 0; + // waraxe_move: homes at 10 Hz while alive; after 5 s it stops steering and falls, velocity_z -20 each think. The big axe explodes on a hit: MultiExplode with dmg unset, so it adds no radius damage. + Q.MISSILE.waraxe = { + think(g, m) { if (m.life % 2 !== 0) return; if (m.life > 100) Q.home(g, m); else m.v[2] -= 20; }, + touch(g, m, hitPlayer) { hits(g, m, hitPlayer); Q.fx(g, m.big ? 'blast' : 'spark', m.o, { r: m.big ? 26 : 6 }); }, + }; + function waraxe(g, b, off, horizontal) { + if (horizontal && Q.random(g) < 0.3 + g.skill / 10) return; + const v = Q.qcVectors([0, b.yaw]), o = [b.o[0] + off[0] * v.r[0] + off[1] * v.f[0], b.o[1] + off[0] * v.r[1] + off[1] * v.f[1], b.o[2] + off[2]]; + // Leaves along the horizontal part of the offset, off to the side or ahead of the horse, and then homes in. + const dir = Q.norm([off[0] * v.r[0] + off[1] * v.f[0], off[0] * v.r[1] + off[1] * v.f[1], 0]), speed = Q.random(g, 500, 600); + // lifetime 5 s, then it falls until something stops it; the 10 s here only ends a miss that never lands. + Q.spawnMissile(g, 'waraxe', o, Q.scale(dir, speed), 10, { speed, turn: horizontal ? 2 : 1, dmg: horizontal ? Q.random(g, 20, 30) : Q.random(g, 60, 80), big: !horizontal, k2: horizontal ? 'small' : 'big', r: horizontal ? 7 : 12 }); + g.events.push({ type: 'boss_attack', name: horizontal ? 'war_axe' : 'war_big_axe', tick: g.t }); + } + function rear(g, b) { // warhorse_rear + if (b.stage === BEGIN_REAR) { + b.speed /= 1.2; Q.riderpathMove(g, b, b.speed, true); + if (Q.advanceFrame(b, 16) === Q.AF_END) { b.stage = MIDDLE_REAR; b.fr = 0; } + } else if (b.stage === MIDDLE_REAR) { + const r = Q.advanceFrame(b, 40); + if (b.fr === 39 && g.p.hp > 0) waraxe(g, b, [1, 2, 70], 0); + if (r === Q.AF_END) { b.stage = Q.random(g) < 0.7 ? STANDING : END_REAR; b.fr = 0; } + } else if (b.stage === STANDING) { + const r = Q.advanceFrame(b, 15); + if (g.p.hp > 0) { if (b.fr === 9) waraxe(g, b, [3, 3, 82], 1); else if (b.fr === 10) waraxe(g, b, [-3, 3, 70], 1); else if (b.fr === 13) waraxe(g, b, [-1, 3, 75], 1); } + if (r === Q.AF_END && Q.random(g) < 0.5) { b.stage = END_REAR; b.fr = 0; } + } else if (b.stage === END_REAR) { + const r = Q.advanceFrame(b, 12); + if (r === Q.AF_END) { b.state = 'move'; b.stage = NORMAL; b.speed = SPEED[b.gait]; b.fr = 0; } + else b.speed *= 1.3; + Q.riderpathMove(g, b, b.speed, true); + } + } + function move(g, b) { // warhorse_move + const r = Q.advanceFrame(b, LEN[b.gait]); + Q.riderpathMove(g, b, b.speed, true); + if (r === Q.AF_BEGINNING) { + const turn = Math.abs(b.y_change); + if (turn >= 15) b.gait = b.gait >= 1 ? 2 : 1; else b.gait = b.gait <= 1 ? 0 : 1; + b.fr = 1; + if (turn < 1 && Q.random(g) < 0.1) { b.state = 'rear'; b.stage = BEGIN_REAR; b.fr = 0; return; } + // The tier's aggression is applied here: every cycle attacks in the source, so an easy cycle may ride by. + if (g.p.hp > 0 && Q.aggressive(g)) b.stage = ATTACK; + } + if (b.stage === ATTACK && g.p.hp > 0) { const off = THROWS[b.gait][b.fr]; if (off) waraxe(g, b, off, 1); } + if (r === Q.AF_END) b.stage = NORMAL; + const want = SPEED[b.gait]; + b.speed = Math.abs(want - b.speed) < 0.2 ? want : want > b.speed ? b.speed + 0.2 : b.speed - 0.2; + } + Q.HP.war = [2800, 4200, 9000]; + Q.CASES.push({ id: 'hexen2/axe_hurling_rider', name: 'Axe-Hurling Armoured Rider', arena: 'war' }); + const B = Q.brush, pts = [[300, 300], [1000, 220], [1800, 300], [1960, 1000], [1800, 1800], [1000, 1880], [300, 1800], [220, 1000]].map(p => [p[0], p[1], 0]); + // A burnt siege yard. The ring's corners bend hard, so the path itself sets the gait: slow and four axes at a corner, fast and two on a long side. Ramparts cut the axes' homing. + Q.ARENAS.war = { + title: 'Scorched Siegeground (original arena)', size: [2200, 2100, 640], theme: 'war', + brushes: [...Q.shell(2200, 2100, 640, { floor: 'blood', wall: 'iron', roof: 'sky' }), + B(620, 620, 0, 880, 700, 180, 'iron'), B(1320, 620, 0, 1580, 700, 180, 'iron'), B(620, 1400, 0, 880, 1480, 180, 'iron'), B(1320, 1400, 0, 1580, 1480, 180, 'iron'), + B(1040, 960, 0, 1160, 1140, 240, 'iron')], + paths: Q.ringPaths(pts, 2), + player: [1100, 480, 0, 90], boss: [300, 300, 0, 0], + items: [['health', 420, 1050, 10], ['health', 1780, 1050, 10], ['health', 1100, 420, 10], ['health', 1100, 1680, 10], ['mana', 560, 860, 15], ['mana', 1640, 860, 15], ['mana', 560, 1240, 15], ['mana', 1640, 1240, 15], ['health', 860, 1050, 10], ['health', 1340, 1050, 10]], + }; + Q.BOSS.war = { + title: 'Axe-Hurling Armoured Rider', + spawn(g, o, yaw, hp) { + return { kind: 'war', o: o.slice(), yaw, ideal_yaw: yaw, yaw_speed: 2, speed: SPEED[2], path_distance: 200, mins: [-50, -50, 0], maxs: [50, 50, 124], hp, maxHp: hp, path: 1, fr: 0, state: 'move', stage: NORMAL, gait: 2, solid: true, pain_finished: 0, y_change: 0, move_adjust: 0 }; + }, + think(g, b) { if (b.state === 'move') move(g, b); else rear(g, b); }, + targets(g, b) { return [Object.assign({ id: 'horse' }, Q.boxAt(b, b.o))]; }, + aim(g, b) { return [b.o[0], b.o[1], b.o[2] + 64]; }, + vel(g, b) { const r = b.yaw * Q.DEG, s = b.speed * 20; return [Math.cos(r) * s, Math.sin(r) * s, 0]; }, + hurt(g, b, id, dmg) { b.hp -= dmg; if (b.hp <= 0) { b.hp = 0; g.bossKilled = true; } }, + progress(g, b) { return b.hp; }, + max(g, b) { return b.maxHp; }, + phase(g, b) { return b.state === 'rear' ? (b.stage === STANDING ? 'Standing Axe Volley' : 'Reeling') : b.stage === ATTACK ? ['Fast Axe Throw', 'Medium Axe Throw', 'Slow Axe Throw'][b.gait] : ['Fast March', 'Medium March', 'Slow March'][b.gait]; }, + warn(g, b) { return b.state === 'rear' && b.stage === MIDDLE_REAR ? 'Reeling charge: giant axe deals 60–80 damage; find cover' : null; }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/compact_actions.json b/environments/games/web/games/hexen2_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..ce03a424d6ba4717179c75c2e3a7875e000ddbd3 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/compact_actions.json @@ -0,0 +1,177 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "hexen2_remake", + "version": "hexen2-compact@1", + "note": "A 200 ms packet combines eight-way running, yaw, pitch, and one weapon action. One mouse count is 0.066 degrees. Positive dx turns right and positive dy looks down.", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W", + "Shift" + ] + }, + { + "label": "back", + "keys": [ + "S", + "Shift" + ] + }, + { + "label": "left", + "keys": [ + "A", + "Shift" + ] + }, + { + "label": "right", + "keys": [ + "D", + "Shift" + ] + }, + { + "label": "forward_left", + "keys": [ + "W", + "A", + "Shift" + ] + }, + { + "label": "forward_right", + "keys": [ + "W", + "D", + "Shift" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A", + "Shift" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D", + "Shift" + ] + } + ] + }, + { + "name": "turn", + "options": [ + { + "label": "none" + }, + { + "label": "left_3", + "dx": -45 + }, + { + "label": "right_3", + "dx": 45 + }, + { + "label": "left_10", + "dx": -152 + }, + { + "label": "right_10", + "dx": 152 + }, + { + "label": "left_30", + "dx": -455 + }, + { + "label": "right_30", + "dx": 455 + }, + { + "label": "left_60", + "dx": -909 + }, + { + "label": "right_60", + "dx": 909 + } + ] + }, + { + "name": "pitch", + "options": [ + { + "label": "none" + }, + { + "label": "up_3", + "dy": -45 + }, + { + "label": "down_3", + "dy": 45 + } + ] + }, + { + "name": "attack", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "keys": [ + "J" + ] + }, + { + "label": "next_weapon", + "subs": [ + [], + [], + [], + [ + "K" + ], + [ + "K" + ], + [] + ], + "note": "pressed in the second half of the packet; the change lands once the weapon is ready (0.3 s select)" + }, + { + "label": "prev_weapon", + "subs": [ + [], + [], + [], + [ + "R" + ], + [ + "R" + ], + [] + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/hexen2_remake/draw.js b/environments/games/web/games/hexen2_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..99bf4c93502bf40b0458defb7403baa5755675cf --- /dev/null +++ b/environments/games/web/games/hexen2_remake/draw.js @@ -0,0 +1,98 @@ +/* Hexen II boss arenas - Module.draw: the WebGL first-person view plus a Canvas 2D HUD (health, armor, green and blue mana, the Paladin's four weapons), with BossBench additions: + boss name, health bar and phase, fight timer, skill / tier and the native tick rate. Read-only on the game state. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q, R = M.R3; + const WEAPON_LABEL = { gauntlet: 'Gauntlets', vorpal: 'Longsword', axe: 'Throwing Axe', purifier: 'Purifier Staff' }; + const SKILL = ['Easy', 'Medium', 'Hard', 'Nightmare']; + const panel = (c, x, y, w, h) => { c.fillStyle = 'rgba(16,12,20,.66)'; c.fillRect(x, y, w, h); c.strokeStyle = 'rgba(190,150,90,.5)'; c.lineWidth = 1; c.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1); }; + const num = (c, v, x, y, col, label) => { c.textAlign = 'right'; c.font = 'bold 32px Consolas, "Courier New", monospace'; c.fillStyle = '#000a'; c.fillText(v, x + 2, y + 2); c.fillStyle = col; c.fillText(v, x, y); c.font = '11px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#c8b88a'; c.fillText(label, x, y + 15); c.textAlign = 'left'; }; +// Crosshair: four ticks and a dot, white over a dark outline so it reads on sky, fire and stone alike; it turns red while the aim line meets a boss target box (geometry only). + function crosshair(c, g) { + const W = 854, H = 480, x = W / 2, y = H / 2, p = g.p, D = Q.BOSS[g.boss.kind], v = Q.viewVectors([p.pitch, p.yaw]), e = Q.eye(p), tr = Q.traceShot(g, e, Q.ma(e, 4000, v.f), 0); + const on = !!tr.target, col = on ? '#ff5a3c' : '#ffffff', gap = on ? 4 : 5, len = on ? 8 : 7; + c.lineCap = 'round'; + for (const [w, s] of [[4, 'rgba(0,0,0,.75)'], [2, col]]) { + c.strokeStyle = s; c.lineWidth = w; c.beginPath(); + c.moveTo(x - gap - len, y); c.lineTo(x - gap, y); c.moveTo(x + gap, y); c.lineTo(x + gap + len, y); c.moveTo(x, y - gap - len); c.lineTo(x, y - gap); c.moveTo(x, y + gap); c.lineTo(x, y + gap + len); c.stroke(); + } + c.fillStyle = 'rgba(0,0,0,.75)'; c.fillRect(x - 2, y - 2, 4, 4); c.fillStyle = col; c.fillRect(x - 1, y - 1, 2, 2); c.lineCap = 'butt'; + } + // Off-screen boss: an arrow on the edge of the open view pointing the shortest way to turn, with the distance; a wind-up tints it. + function pointer(c, g) { + const V = M.VIEW, b = g.boss; if (!V.bossShown(g, b) || g.outcome) return; + const cam = V.camera(g), pts = V.bossPoints(g, b); + if (V.framed(cam, pts)) { + if (V.seen(g, cam, pts)) return; + const s = V.project(cam, pts[0]); if (!s) return; + c.strokeStyle = 'rgba(0,0,0,.6)'; c.lineWidth = 4; c.beginPath(); c.moveTo(s.x, s.y - 11); c.lineTo(s.x + 9, s.y); c.lineTo(s.x, s.y + 11); c.lineTo(s.x - 9, s.y); c.closePath(); c.stroke(); + c.strokeStyle = '#' + (R.RIM[g.key] || 0xc8ff70).toString(16).padStart(6, '0'); c.lineWidth = 2; c.stroke(); return; + } + const v = Q.viewVectors([cam.pitch, cam.yaw]), d = Q.sub(pts[0], cam.eye), x = Q.dot(d, v.r), y = Q.dot(d, v.u), z = Q.dot(d, v.f); + let a = Math.atan2(-y, x); if (z < 0 && Math.abs(x) < 1e-3) a = Math.PI; + const cx = 427, cy = 238, rx = 395, ry = 160, px = cx + Math.cos(a) * rx, py = cy + Math.sin(a) * ry, tele = M.telegraph(g), col = tele ? V.HUE[tele.hue] : '#ffd070'; + c.save(); c.translate(px, py); c.rotate(a); + c.fillStyle = 'rgba(0,0,0,.6)'; c.beginPath(); c.moveTo(20, 0); c.lineTo(-10, -15); c.lineTo(-4, 0); c.lineTo(-10, 15); c.closePath(); c.fill(); + c.fillStyle = col; c.beginPath(); c.moveTo(16, 0); c.lineTo(-7, -11); c.lineTo(-2, 0); c.lineTo(-7, 11); c.closePath(); c.fill(); c.restore(); + c.font = 'bold 12px Consolas, monospace'; c.textAlign = 'center'; c.fillStyle = '#000a'; const tx = cx + Math.cos(a) * (rx - 34), ty = cy + Math.sin(a) * (ry - 26) + 4, dist = Math.round(Q.hlen(Q.sub(b.o, g.p.o)) / 32) + ' m'; + c.fillText(dist, tx + 1, ty + 1); c.fillStyle = col; c.fillText(dist, tx, ty); c.textAlign = 'left'; + } + // Where the last hit came from: a red arc on a ring round the crosshair, fading with the damage tint. + function hurtDir(c, g) { + const p = g.p; if (!(p.dmgAlpha > 0.02) || !p.dmgDir) return; + const yr = p.yaw * Q.DEG, f = [Math.cos(yr), Math.sin(yr)], r = [Math.sin(yr), -Math.cos(yr)], from = [-p.dmgDir[0], -p.dmgDir[1]]; + const a = Math.atan2(-(from[0] * f[0] + from[1] * f[1]), from[0] * r[0] + from[1] * r[1]); + c.strokeStyle = 'rgba(255,40,20,' + Math.min(0.9, p.dmgAlpha * 1.6) + ')'; c.lineWidth = 7; c.beginPath(); c.arc(427, 240, 70, a - 0.45, a + 0.45); c.stroke(); + } + // Wind-up banner under the boss bar: the move, a bar for the time left, in the move's colour. + function windup(c, g) { + const V = M.VIEW, tele = M.telegraph(g); if (!tele || g.outcome || !V.bossShown(g, g.boss)) return false; + const col = V.HUE[tele.hue], x = 297, y = 60, w = 260; + c.fillStyle = 'rgba(10,6,12,.72)'; c.fillRect(x, y, w, 26); c.strokeStyle = col; c.lineWidth = 1.5; c.strokeRect(x + 0.5, y + 0.5, w - 1, 25); + c.fillStyle = col; c.globalAlpha = 0.85; c.fillRect(x + 2, y + 21, (w - 4) * tele.k, 3); c.globalAlpha = 1; + c.font = 'bold 14px "Segoe UI", "Microsoft YaHei", sans-serif'; c.textAlign = 'center'; c.fillStyle = col; c.fillText('⚠ ' + tele.label + ' · ' + tele.lead.toFixed(1) + ' s', x + w / 2, y + 17); c.textAlign = 'left'; + return true; + } + function vignette(c, r, g, b, a) { + const v = c.createRadialGradient(427, 240, 150, 427, 240, 520); v.addColorStop(0, `rgba(${r},${g},${b},0)`); v.addColorStop(0.55, `rgba(${r},${g},${b},${a * 0.45})`); v.addColorStop(1, `rgba(${r},${g},${b},${a})`); + c.fillStyle = v; c.fillRect(0, 0, 854, 480); + } + M.draw = function (g, c) { + R.render(g, c); + const p = g.p, W = 854, H = 480, h = g.health(), D = Q.BOSS[g.boss.kind]; + // Damage and poison tint the edges of the view (a vignette), not the centre, so the boss and the crosshair stay readable while hurt. + if (p.dmgAlpha > 0) vignette(c, 190, 20, 10, Math.min(0.75, p.dmgAlpha * 1.4)); + if (p.poison.length) vignette(c, 80, 170, 20, 0.35); + if (p.hp <= 0) { c.fillStyle = 'rgba(90,0,0,.35)'; c.fillRect(0, 0, W, H); } + if (p.hp > 0) crosshair(c, g); + pointer(c, g); hurtDir(c, g); + panel(c, 8, H - 58, 838, 50); + num(c, Math.max(0, Math.ceil(p.hp)), 100, H - 24, p.hp < 30 ? '#ff5040' : '#f0d070', 'Health'); + const armor = p.armor.amulet + p.armor.bracer + p.armor.breast + p.armor.helm; + num(c, Math.round(armor), 200, H - 24, '#9fd27a', 'Armor'); + num(c, Math.round(p.green), 310, H - 24, '#7ae07a', 'Green Mana'); + num(c, Math.round(p.blue), 420, H - 24, '#7ab8ff', 'Blue Mana'); + c.font = 'bold 15px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#e8dcb8'; c.fillText(WEAPON_LABEL[p.weapon], 450, H - 36); + c.font = '12px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#a99e84'; + c.fillText(Q.WEAPONS.map(w => (w === p.weapon ? '[' + WEAPON_LABEL[w] + ']' : WEAPON_LABEL[w])).join(' '), 450, H - 17); + panel(c, 676, 8, 170, 46); c.textAlign = 'right'; c.font = 'bold 18px Consolas, monospace'; c.fillStyle = '#f0e4c0'; + c.fillText((g.t / M.hz).toFixed(1) + ' s', 838, 30); c.font = 'bold 12px Consolas, monospace'; c.fillStyle = '#9fd0ff'; c.fillText(M.hz + 'Hz · tick ' + g.t, 838, 46); c.textAlign = 'left'; + panel(c, 187, 8, 480, 46); + c.fillStyle = '#2a1410'; c.fillRect(197, 30, 460, 14); c.fillStyle = '#c23a28'; c.fillRect(197, 30, 460 * (h[3] ? h[2] / h[3] : 0), 14); + c.font = 'bold 14px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#f2e6c0'; c.fillText(D.title, 197, 24); + c.textAlign = 'right'; c.font = '12px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#e8b070'; c.fillText(D.phase(g, g.boss) + ' ' + Math.ceil(h[2]) + ' / ' + h[3], 657, 24); c.textAlign = 'left'; + panel(c, 8, 8, 170, 46); + c.font = 'bold 12px Consolas, monospace'; c.fillStyle = '#f0d070'; c.fillText('HEXEN II · ' + SKILL[g.skill].toUpperCase(), 16, 26); + c.font = '11px Consolas, monospace'; c.fillStyle = '#a99e84'; c.fillText('skill ' + g.skill + (g.tier ? ' · tier ' + g.tier : '') + ' · d=' + g.d, 16, 44); + const shown = windup(c, g), note = D.warn && D.warn(g, g.boss); + if (note) { c.font = 'bold 15px "Segoe UI", "Microsoft YaHei", sans-serif'; c.textAlign = 'center'; c.fillStyle = '#000a'; c.fillText(note, W / 2 + 1, shown ? 105 : 79); c.fillStyle = '#ffd070'; c.fillText(note, W / 2, shown ? 104 : 78); c.textAlign = 'left'; } + if (g.outcome) { + c.fillStyle = 'rgba(8,6,10,.55)'; c.fillRect(0, 96, W, 80); c.textAlign = 'center'; c.font = 'bold 30px "Segoe UI", "Microsoft YaHei", sans-serif'; + c.fillStyle = g.outcome === 'win' ? '#f0d070' : '#ff6a50'; + c.fillText(g.outcome === 'win' ? 'Boss Defeated · ' + (g.t / M.hz).toFixed(1) + ' s' : g.outcome === 'loss' ? 'Slain' : 'Time up', W / 2, 147); c.textAlign = 'left'; + } + }; + M.renderStatus = ctx => R.status(ctx); + M.renderMetrics = ctx => R.metrics(ctx); + M.closeRenderer = ctx => R.close(ctx); +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/fx3d.js b/environments/games/web/games/hexen2_remake/fx3d.js new file mode 100644 index 0000000000000000000000000000000000000000..23abff575a7f421d11e31dfc24804aedfaccf76a --- /dev/null +++ b/environments/games/web/games/hexen2_remake/fx3d.js @@ -0,0 +1,116 @@ +/* Hexen II boss arenas - effect batches for the WebGL view: soft glows and hot cores, streaks (trails, sparks, beams, lightning), smoke, and floor marks; five instanced draw calls a frame. + Original procedural effects (no Hexen II sprites). Filled from the game state every frame; nothing here touches the simulation. Colours are display sRGB and not tone mapped. + Sizes are clamped against depth in the shaders, so an effect next to the eye never fills the screen. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Hexen2Game, R = M.R3, S = R.S; + const FOG = 'uniform float fogNear; uniform float fogFar;'; + const VS_SPRITE = `${FOG} + attribute vec3 iPos; attribute vec4 iCol; attribute vec4 iSize; + varying vec2 vUv; varying vec4 vCol; varying float vShape; varying float vFog; + void main() { + vec4 mv = modelViewMatrix * vec4(iPos, 1.0); + float c = cos(iSize.y), s = sin(iSize.y), sz = min(iSize.x, iSize.w * max(-mv.z, 0.05)); + mv.xy += vec2(c * position.x - s * position.y, s * position.x + c * position.y) * sz; + gl_Position = projectionMatrix * mv; + vUv = position.xy * 2.0; vCol = iCol; vShape = iSize.z; vFog = smoothstep(fogNear, fogFar, -mv.z); + }`; + const VS_DECAL = `${FOG} + attribute vec3 iPos; attribute vec4 iCol; attribute vec4 iSize; + varying vec2 vUv; varying vec4 vCol; varying float vShape; varying float vFog; + void main() { + float c = cos(iSize.y), s = sin(iSize.y); + vec3 w = iPos + vec3(c * position.x - s * position.y, 0.0, s * position.x + c * position.y) * iSize.x; + vec4 mv = modelViewMatrix * vec4(w, 1.0); + gl_Position = projectionMatrix * mv; + vUv = position.xy * 2.0; vCol = iCol; vShape = iSize.z; vFog = smoothstep(fogNear, fogFar, -mv.z); + }`; + // shapes: 0 soft glow, 1 hot core (white centre), 2 ring, 3 star flare, 4..5 smoke puff (lumpy edge), 6 rune circle (ring with ticks) + const FS_SPRITE = ` + varying vec2 vUv; varying vec4 vCol; varying float vShape; varying float vFog; + void main() { + float r = length(vUv); if (r > 1.0) discard; + vec3 col = vCol.rgb; float a, ang = atan(vUv.y, vUv.x); + if (vShape < 0.5) a = pow(1.0 - r, 2.2); + else if (vShape < 1.5) { a = pow(1.0 - r, 1.3); col = mix(col, vec3(1.0), smoothstep(0.55, 0.0, r)); } + else if (vShape < 2.5) a = smoothstep(0.14, 0.0, abs(r - 0.8)) + pow(1.0 - r, 3.0) * 0.2; + else if (vShape < 3.5) { a = pow(1.0 - r, 2.0) * (0.3 + 0.7 * pow(abs(cos(ang * 2.0)), 14.0)) + pow(1.0 - r, 6.0); col = mix(col, vec3(1.0), pow(1.0 - r, 5.0)); } + else if (vShape < 5.99) { float e = 0.74 + 0.13 * sin(ang * 5.0 + vShape * 9.0) + 0.07 * sin(ang * 11.0 - vShape * 3.0); a = smoothstep(e, e - 0.5, r); } + else { a = smoothstep(0.08, 0.0, abs(r - 0.86)) + smoothstep(0.05, 0.0, abs(r - 0.62)) + step(0.62, r) * step(r, 0.86) * step(0.93, abs(cos(ang * 6.0))) * 0.8; } + gl_FragColor = vec4(col, a * vCol.a * (1.0 - vFog)); + }`; + const VS_STREAK = `${FOG} + attribute vec3 iA; attribute vec3 iB; attribute vec4 iCol; attribute vec4 iW; + varying vec2 vUv; varying vec4 vCol; varying float vHot; varying float vFog; + void main() { + vec3 a = (modelViewMatrix * vec4(iA, 1.0)).xyz, b = (modelViewMatrix * vec4(iB, 1.0)).xyz, d = b - a; + vec3 mid = mix(a, b, position.x), sd = cross(d, mid); float l = length(sd); + vec3 side = l > 1e-7 ? sd / l : vec3(0.0, 1.0, 0.0); + float w = min(mix(iW.x, iW.y, position.x), 0.035 * max(-mid.z, 0.05)); + gl_Position = projectionMatrix * vec4(mid + side * w * position.y, 1.0); + vUv = position.xy; vCol = vec4(iCol.rgb, iCol.a * mix(iW.z, 1.0, position.x)); vHot = iW.w; vFog = smoothstep(fogNear, fogFar, -mid.z); + }`; + const FS_STREAK = ` + varying vec2 vUv; varying vec4 vCol; varying float vHot; varying float vFog; + void main() { + float v = abs(vUv.y), a = (1.0 - v * v) * vCol.a; + vec3 col = mix(vCol.rgb, vec3(1.0), vHot * smoothstep(0.55, 0.0, v)); + gl_FragColor = vec4(col, a * (1.0 - vFog)); + }`; + const SPRITE_ATTRS = [['iPos', 3], ['iCol', 4], ['iSize', 4]]; + function batch(sc, n, vs, fs, attrs, geo, blending, order) { + const g = new T.InstancedBufferGeometry(); g.index = geo.index; g.setAttribute('position', geo.getAttribute('position')); + const arr = {}; + for (const [name, size] of attrs) { const a = new T.InstancedBufferAttribute(new Float32Array(n * size), size); a.setUsage(T.DynamicDrawUsage); g.setAttribute(name, a); arr[name] = a; } + g.instanceCount = 0; + const mat = new T.ShaderMaterial({ vertexShader: vs, fragmentShader: fs, transparent: true, depthWrite: false, depthTest: true, blending, uniforms: sc.fogUniforms, toneMapped: false }); + const mesh = new T.Mesh(g, mat); mesh.frustumCulled = false; mesh.renderOrder = order; sc.keep(g); sc.keep(mat); sc.keep(geo); + return { mesh, g, arr, n, i: 0 }; + } + const CACHE = {}; + const col = hex => CACHE[hex] || (CACHE[hex] = [((hex >> 16) & 255) / 255, ((hex >> 8) & 255) / 255, (hex & 255) / 255]); + R.col = col; + class FX { + constructor(sc, world) { + const quad = () => new T.PlaneGeometry(1, 1), strip = new T.PlaneGeometry(1, 2); strip.translate(0.5, 0, 0); + this.shade = batch(sc, 192, VS_DECAL, FS_SPRITE, SPRITE_ATTRS, quad(), T.NormalBlending, 10); + this.marks = batch(sc, 256, VS_DECAL, FS_SPRITE, SPRITE_ATTRS, quad(), T.AdditiveBlending, 11); + this.smoke = batch(sc, 384, VS_SPRITE, FS_SPRITE, SPRITE_ATTRS, quad(), T.NormalBlending, 20); + this.glows = batch(sc, 1536, VS_SPRITE, FS_SPRITE, SPRITE_ATTRS, quad(), T.AdditiveBlending, 30); + this.streaks = batch(sc, 1536, VS_STREAK, FS_STREAK, [['iA', 3], ['iB', 3], ['iCol', 4], ['iW', 4]], strip, T.AdditiveBlending, 31); + this.all = [this.shade, this.marks, this.smoke, this.glows, this.streaks]; + for (const b of this.all) world.add(b.mesh); + this.v = new T.Vector3(); + } + begin() { for (const b of this.all) b.i = 0; } + end() { for (const b of this.all) { b.g.instanceCount = b.i; for (const k of Object.keys(b.arr)) b.arr[k].needsUpdate = true; } } + count() { return this.all.reduce((s, b) => s + b.i, 0); } + // Quake-unit positions in; sizes are the sprite's diameter in Quake units. + // clamp: largest diameter as a share of the depth (0.1 keeps a bolt by the eye at about 43 px); decals ignore it. + sprite(b, o, size, hex, a, shape, rot, clamp) { + if (b.i >= b.n || a <= 0.003 || size <= 0) return; const i = b.i++, c = col(hex), v = R.qv(o[0], o[1], o[2], this.v); + b.arr.iPos.setXYZ(i, v.x, v.y, v.z); b.arr.iCol.setXYZW(i, c[0], c[1], c[2], Math.min(1, a)); b.arr.iSize.setXYZW(i, size * S, rot || 0, shape || 0, clamp || 0.6); + } + glow(o, size, hex, a, shape, rot, clamp) { this.sprite(this.glows, o, size, hex, a, shape, rot, clamp); } + puff(o, size, hex, a, seed, rot) { this.sprite(this.smoke, o, size, hex, a, 4 + ((seed || 0) % 9) / 9 * 1.9, rot); } + mark(o, size, hex, a, shape, rot) { this.sprite(this.marks, [o[0], o[1], o[2] + 1.5], size, hex, a, shape, rot); } + shadow(o, size, a) { this.sprite(this.shade, [o[0], o[1], o[2] + 1], size, 0x000000, a, 0, 0); } + // A streak from a to b: widths in Quake units at each end, alpha aFrom at a rising to alpha at b; hot = white core 0..1. + streak(a, b, wa, wb, hex, alpha, aFrom, hot) { + const s = this.streaks; if (s.i >= s.n || alpha <= 0.003) return; const i = s.i++, c = col(hex), v = R.qv(a[0], a[1], a[2], this.v); + s.arr.iA.setXYZ(i, v.x, v.y, v.z); R.qv(b[0], b[1], b[2], v); s.arr.iB.setXYZ(i, v.x, v.y, v.z); + s.arr.iCol.setXYZW(i, c[0], c[1], c[2], Math.min(1, alpha)); s.arr.iW.setXYZW(i, wa * S, wb * S, aFrom === undefined ? 1 : aFrom, hot || 0); + } + chain(pts, w, hex, alpha, hot) { for (let k = 1; k < pts.length; k++) this.streak(pts[k - 1], pts[k], w, w, hex, alpha, 1, hot); } + } + R.FX = FX; + // Deterministic noise for effects: a hash of integers to [0, 1). + R.h1 = (a, b, c) => { let n = Math.imul((a | 0) + 0x9E3779B9, 0x85EBCA6B) ^ Math.imul((b | 0) + 0x632BE5AB, 0xC2B2AE35) ^ Math.imul((c | 0) + 0x27D4EB2F, 0x165667B1); n = Math.imul(n ^ (n >>> 15), 0x2C1B3C6D); n = Math.imul(n ^ (n >>> 13), 0x297A2D39); return ((n ^ (n >>> 16)) >>> 0) / 4294967296; }; + // A unit direction from a hash (for spark sprays); up biases it upward. + R.hdir = (a, b, up) => { const z = Math.max(-1, Math.min(1, (R.h1(a, b, 1) * 2 - 1) * 0.85 + (up || 0))), t = R.h1(a, b, 2) * Math.PI * 2, r = Math.sqrt(1 - z * z); return [Math.cos(t) * r, Math.sin(t) * r, z]; }; + // Jagged lightning between two points: n segments, the middle pushed sideways by up to amp, the same shape for the same seed and t. + R.jagged = (a, b, n, amp, seed, t) => { + const pts = [a]; for (let k = 1; k < n; k++) { const f = k / n, j = Math.sin(f * Math.PI); pts.push([a[0] + (b[0] - a[0]) * f + (R.h1(seed, k, t) - 0.5) * 2 * amp * j, a[1] + (b[1] - a[1]) * f + (R.h1(seed, k, t + 7) - 0.5) * 2 * amp * j, a[2] + (b[2] - a[2]) * f + (R.h1(seed, k, t + 13) - 0.5) * amp * j]); } + pts.push(b); return pts; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/fx_draw.js b/environments/games/web/games/hexen2_remake/fx_draw.js new file mode 100644 index 0000000000000000000000000000000000000000..06f5142fcde5803167fefa6786ff045bf2df696f --- /dev/null +++ b/environments/games/web/games/hexen2_remake/fx_draw.js @@ -0,0 +1,217 @@ +/* Hexen II boss arenas - every effect drawn into the view through the fx3d.js batches: missiles (glow, hot core, trail, smoke), impacts (flash, sparks, smoke, shock ring), + floor flames, fire rings, swarms, the pull beam, lightning, pickups, torches, motes, and the wind-up cue of every damaging move (telegraph.js). + Reads the state only; all noise is hashed from ids and ticks. Player missiles are azure and leave the weapon's mouth; no boss missile is azure. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q, R = M.R3, V = M.VIEW, { h1, hdir, jagged } = R, HZ = M.hz; + const HUE = { crimson: 0xff3a2e, violet: 0xc060ff, bone: 0x7aff6a, ember: 0xff8a1e, toxic: 0x9cff2e, blood: 0xff4a28, storm: 0xa8c8ff, arcane: 0x7aa0ff }; + R.HUE = HUE; + const AZ = { core: 0xeafcff, glow: 0x38c4ff, trail: 0x2894ff }; + const up = (o, z) => [o[0], o[1], o[2] + z]; + const clamp01 = x => Math.max(0, Math.min(1, x)); + // Smoke left behind a moving missile: puffs at a fixed spacing that stay put in the world while the missile flies on. + function smokeTrail(fx, g, m, d, sp, len, spacing, size, hex, a) { + const run = g.t * sp / HZ, ph = run % spacing; + for (let back = ph, k = 0; back < len; back += spacing, k++) { const f = back / len; fx.puff(Q.ma(m.o, -back, d), size * (1 + f * 1.6), hex, a * (1 - f), Math.floor((run - back) / spacing) + m.id, m.id + k); } + } + // A spray of sparks under gravity from o: n streaks, speed u/s, life s. + function sparks(fx, o, id, age, n, speed, grav, life, hex, w, lift) { + const tt = age / HZ; + for (let j = 0; j < n; j++) { + const lf = life * (0.55 + 0.45 * h1(id, j, 4)); if (tt > lf) continue; + const d = hdir(id, j, lift || 0), s = speed * (0.5 + 0.5 * h1(id, j, 3)), at = t => [o[0] + d[0] * s * t, o[1] + d[1] * s * t, o[2] + d[2] * s * t - 0.5 * grav * t * t]; + fx.streak(at(Math.max(0, tt - 0.04)), at(tt), w * 0.4, w, hex, 1 - tt / lf, 0, 0.8); + } + } + function cloud(fx, o, id, age, n, r, hex, a, rise, life) { + const tt = age / HZ, L = life || 1; if (tt > L) return; + for (let j = 0; j < n; j++) { const d = hdir(id, j + 20, 0.2), e = 1 - Math.pow(1 - clamp01(tt / 0.5), 2), k = 0.4 + 0.6 * e; fx.puff([o[0] + d[0] * r * k, o[1] + d[1] * r * k, o[2] + d[2] * r * k * 0.6 + rise * tt], r * (0.7 + tt * 1.2), hex, a * (1 - tt / L), id + j, j); } + } + // clamp: the flash's largest diameter as a share of its depth (0.12 = 51 px on screen at any distance). + function flash(fx, o, size, hex, a, age, dur, rot, clamp) { if (age >= dur) return; const k = age / dur, c = clamp || 0.5; fx.glow(o, size * (0.7 + 0.6 * k), hex, a * (1 - k), 3, rot || 0, c); fx.glow(o, size * 0.45, 0xffffff, a * (1 - k) * 0.9, 1, 0, c * 0.6); } + function shock(fx, o, size, hex, a, age, dur) { if (age >= dur) return; const k = age / dur; fx.glow(o, size * (0.3 + k), hex, a * (1 - k), 2, 0, 0.35); } + // ---------------- missiles ---------------- + function playerBolt(sc, g, m) { + const fx = sc.fx, o = V.boltPos(g, m); if (!o) return; const d = Q.norm(m.v), age = V.boltAge(g, m), len = Math.min(120, Math.max(0, age * 16.7 - 30)); + fx.streak(Q.ma(o, -len, d), o, 1, 6, AZ.trail, 0.8, 0, 0.5); + fx.streak(Q.ma(o, -len * 0.4, d), o, 0.5, 3, AZ.core, 0.9, 0, 1); + fx.glow(o, 26, AZ.glow, 0.5, 0, 0, 0.07); fx.glow(o, 9, 0xffffff, 0.95, 1, 0, 0.025); + sc.light(o, 0x50c8ff, 0.9, 160); + } + function playerAxe(sc, g, m) { + const fx = sc.fx, o = V.boltPos(g, m); if (!o) return; const d = Q.norm(m.v), age = V.boltAge(g, m), h = Math.hypot(d[0], d[1]) || 1, r = [d[1] / h, -d[0] / h, 0], a = age * 0.75; + const e = [r[0] * Math.cos(a), r[1] * Math.cos(a), Math.sin(a)], f = [-r[0] * Math.sin(a), -r[1] * Math.sin(a), Math.cos(a)]; + fx.streak(Q.ma(o, -9, e), Q.ma(o, 9, e), 2.5, 2.5, 0xd8e8ff, 0.85, 1, 0.4); fx.streak(Q.ma(o, -5, f), Q.ma(o, 5, f), 4, 4, 0xa8c8e8, 0.7, 1, 0.2); + fx.glow(o, 22, AZ.glow, 0.3, 0, 0, 0.06); fx.streak(Q.ma(o, -Math.min(60, age * 15), d), o, 1, 5, AZ.trail, 0.35, 0, 0.2); + } + const trailLen = (g, m, L) => Math.max(0, Math.min(L, Q.len(Q.sub(m.o, g.boss.o)) - 50)); + const BOSS_MISSILE = { + pstar(sc, g, m) { + const fx = sc.fx, sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / sp), L = trailLen(g, m, 90), fl = 0.85 + 0.15 * Math.sin(g.t * 0.7 + m.id); + fx.streak(Q.ma(m.o, -L, d), m.o, 1.5, 10, 0xd060ff, 0.75, 0, 0.35); + fx.glow(m.o, 40 * fl, 0xe060ff, 0.6, 3, g.t * 0.15 + m.id, 0.3); fx.glow(m.o, 12, 0xffe8ff, 1, 1, 0, 0.15); + sc.light(m.o, 0xe060ff, 1.6, 220); + }, + famshot(sc, g, m) { + const fx = sc.fx, sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / sp), L = trailLen(g, m, 130), fl = 0.85 + 0.15 * Math.sin(g.t * 0.9 + m.id); + smokeTrail(fx, g, m, d, sp, L, 22, 14, 0x2a0a08, 0.45); + fx.streak(Q.ma(m.o, -L, d), m.o, 2, 13, HUE.crimson, 0.9, 0, 0.35); + fx.glow(m.o, 52 * fl, 0xff2a1a, 0.65, 0, 0, 0.4); fx.glow(m.o, 16, 0xffd8c0, 1, 1, 0, 0.2); fx.glow(m.o, 34, 0xff6040, 0.5, 3, g.t * 0.2 + m.id, 0.3); + sc.light(m.o, 0xff3020, 2.2, 260); + }, + bonemis(sc, g, m) { + const fx = sc.fx, sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / Math.max(1, sp)), L = trailLen(g, m, 110); + smokeTrail(fx, g, m, d, Math.max(sp, 100), L, 18, 16, 0x0c200c, 0.5); + fx.streak(Q.ma(m.o, -L, d), m.o, 2, 16, 0x5aff5a, 0.7, 0, 0.3); + fx.glow(m.o, 60, 0x40ff50, 0.55, 0, 0, 0.4); fx.glow(m.o, 20, 0xf0ffe0, 1, 1, 0, 0.2); + for (let k = 0; k < 3; k++) { const a = g.t * 0.25 + k * 2.09 + m.id; fx.glow([m.o[0] + Math.cos(a) * 20, m.o[1] + Math.sin(a) * 20, m.o[2] + Math.sin(a * 1.3) * 10], 9, 0xe8ffc8, 0.9, 1, 0, 0.1); } + sc.light(m.o, 0x40ff50, 2, 240); + }, + boneshard(sc, g, m) { const sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / sp); sc.fx.streak(Q.ma(m.o, -16, d), m.o, 3, 3, 0xe8e0c8, 0.9, 0.5, 0.6); sc.fx.glow(m.o, 12, 0x7aff6a, 0.45, 0, 0, 0.1); }, + circfire(sc, g, m) { + const fx = sc.fx, sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / sp), L = trailLen(g, m, 150); + smokeTrail(fx, g, m, d, sp, L, 24, 18, 0x2a1408, 0.5); + for (let k = 0; k < 5; k++) fx.glow(Q.ma(m.o, -k * L / 5, d), 44 - k * 6, k ? 0xff6a10 : 0xffa040, 0.6 - k * 0.09, 0, 0, 0.4); + fx.glow(m.o, 80, 0xff7a18, 0.5, 3, g.t * 0.15, 0.5); fx.glow(m.o, 24, 0xfff0c0, 1, 1, 0, 0.2); + sc.light(m.o, 0xff7a20, 3, 320); + }, + poison(sc, g, m) { + const fx = sc.fx, sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / sp), L = trailLen(g, m, 90); + smokeTrail(fx, g, m, d, sp, L, 16, 9, 0x12240a, 0.5); + fx.streak(Q.ma(m.o, -26, d), Q.ma(m.o, 6, d), 2.5, 2.5, 0xd8ffa0, 0.95, 1, 0.7); fx.streak(Q.ma(m.o, -L, d), m.o, 1, 9, HUE.toxic, 0.75, 0, 0.3); + fx.glow(m.o, 34, 0x8cff20, 0.6, 0, 0, 0.3); fx.glow(m.o, 10, 0xf0ffd0, 0.9, 1, 0, 0.1); + sc.light(m.o, 0x8cff30, 1.5, 200); + }, + hive(sc, g, m) { + const fx = sc.fx; fx.puff(m.o, 30, 0x4a3a10, 0.95, m.id, 0); fx.glow(m.o, 40, 0xc0b030, 0.25, 0, 0, 0.4); + for (let k = 0; k < 8; k++) { const a = g.t * 0.5 + k * 0.8, r = 18 + 6 * Math.sin(k + g.t * 0.3); fx.puff([m.o[0] + Math.cos(a) * r, m.o[1] + Math.sin(a) * r, m.o[2] + Math.sin(a * 1.7) * 8], 3.5, 0x14120a, 0.9, k, 0); } + }, + waraxe(sc, g, m) { + const fx = sc.fx, big = m.big, s = big ? 1.8 : 1, sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / sp), h = Math.hypot(d[0], d[1]) || 1, r = [d[1] / h, -d[0] / h, 0], a = g.t * (big ? 0.35 : 0.6) + m.id; + const e = [r[0] * Math.cos(a) + d[0] * Math.sin(a), r[1] * Math.cos(a) + d[1] * Math.sin(a), Math.sin(a) * 0.3]; + fx.streak(Q.ma(m.o, -10 * s, e), Q.ma(m.o, 10 * s, e), 3 * s, 3 * s, 0xd0d4dc, 0.9, 1, 0.3); + fx.streak(Q.ma(m.o, 6 * s, e), Q.ma(Q.ma(m.o, 10 * s, e), 7 * s, [0, 0, 1]), 7 * s, 4 * s, 0xf0f0f0, 0.8, 1, 0.5); + const L = trailLen(g, m, big ? 140 : 90); + fx.streak(Q.ma(m.o, -L, d), m.o, 1, (big ? 16 : 8), big ? 0xff7a18 : 0xff4020, 0.7, 0, 0.3); + fx.glow(m.o, big ? 90 : 36, big ? 0xff7a18 : 0xff4a28, big ? 0.6 : 0.45, 0, 0, 0.4); + if (big) { smokeTrail(fx, g, m, d, sp, L, 22, 16, 0x2a1008, 0.5); sc.light(m.o, 0xff7020, 3, 320); } else sc.light(m.o, 0xff4020, 1, 160); + }, + fireball(sc, g, m) { + const fx = sc.fx, sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / sp), L = trailLen(g, m, 220); + smokeTrail(fx, g, m, d, sp, L, 30, 30, 0x241030, 0.55); + for (let k = 0; k < 6; k++) fx.glow(Q.ma(m.o, -k * L / 6, d), 90 - k * 11, k ? 0xff4a20 : 0xff9a40, 0.6 - k * 0.08, 0, 0, 0.45); + fx.glow(m.o, 130, 0xd040ff, 0.35, 3, g.t * 0.1, 0.6); fx.glow(m.o, 40, 0xfff0d0, 1, 1, 0, 0.25); + sc.light(m.o, 0xff6030, 4, 420); + }, + flame(sc, g, m) { const fx = sc.fx, fl = 0.8 + 0.4 * h1(m.id, g.t, 1); fx.glow(m.o, 46 * fl, 0xff8a20, 0.55, 0, g.t * 0.2, 0.35); fx.glow(m.o, 18, 0xffe080, 0.8, 1, 0, 0.15); fx.puff(up(m.o, 14), 18, 0x2a1408, 0.25, m.id, 0); }, + magic(sc, g, m) { + const fx = sc.fx, sp = Q.len(m.v) || 1, d = Q.scale(m.v, 1 / sp), L = trailLen(g, m, 100); + fx.streak(Q.ma(m.o, -L, d), m.o, 1, 10, 0x8a6aff, 0.8, 0, 0.4); fx.glow(m.o, 40, 0x9070ff, 0.6, 3, g.t * 0.3, 0.3); fx.glow(m.o, 12, 0xf0e8ff, 1, 1, 0, 0.1); + sc.light(m.o, 0x8a6aff, 1.5, 200); + }, + }; + // ---------------- impacts and casts (g.fx) ---------------- + const IMPACT = { + hit(sc, g, f, a) { + const fx = sc.fx; + if (f.r === 5) { flash(fx, f.o, 40, AZ.glow, 0.9, a, 7, f.id, 0.12); if (a < 8) fx.glow(f.o, 20 + a * 5, AZ.glow, 0.5 * (1 - a / 8), 2, 0, 0.12); sparks(fx, f.o, f.id, a, 10, 260, 500, 0.35, 0xb0ecff, 3, 0.3); cloud(fx, f.o, f.id, a, 3, 14, 0x283038, 0.35, 30, 0.8); if (a < 6) sc.light(f.o, 0x60d0ff, 3, 220); return; } + flash(fx, f.o, 70, 0x9070ff, 0.9, a, 10, f.id); sparks(fx, f.o, f.id, a, 12, 240, 400, 0.4, 0xc0a8ff, 3, 0.4); if (a < 8) sc.light(f.o, 0x9070ff, 3, 260); + }, + spark(sc, g, f, a) { + const fx = sc.fx, mine = f.r === 4, hex = mine ? 0xa8e8ff : 0xffb070; + flash(fx, f.o, mine ? 30 : 36, mine ? AZ.glow : 0xff7030, 0.9, a, 7, f.id); sparks(fx, f.o, f.id, a, 9, 220, 600, 0.45, hex, 2.5, 0.35); cloud(fx, f.o, f.id, a, 3, 10, 0x2a2a2a, 0.35, 25, 0.9); + if (a < 5) sc.light(f.o, mine ? 0x60c8ff : 0xff8040, 1.6, 160); + }, + redspark(sc, g, f, a) { const fx = sc.fx; flash(fx, f.o, 60, 0xff2a1a, 0.95, a, 9, f.id); sparks(fx, f.o, f.id, a, 12, 260, 500, 0.45, 0xff7050, 3, 0.4); cloud(fx, f.o, f.id, a, 5, 18, 0x3a0c08, 0.5, 30, 1); if (a < 7) sc.light(f.o, 0xff3020, 2.5, 240); }, + redflash(sc, g, f, a) { const fx = sc.fx; flash(fx, f.o, 110, 0xff2a1a, 1, a, 12, f.id); shock(fx, f.o, 150, 0xff4030, 0.7, a, 14); if (a < 10) sc.light(f.o, 0xff3020, 4, 400); }, + redcloud(sc, g, f, a) { const fx = sc.fx; cloud(fx, f.o, f.id, a, 9, 34, 0x5a0c0a, 0.7, 40, 0.8); flash(fx, f.o, 80, 0xff3020, 0.7, a, 10, f.id); sparks(fx, f.o, f.id, a, 8, 160, 200, 0.5, 0xff6040, 2.5, 0.6); }, + greenspark(sc, g, f, a) { const fx = sc.fx, big = (f.r || 16) >= 30; flash(fx, f.o, big ? 90 : 50, 0x8cff20, 0.9, a, 10, f.id); sparks(fx, f.o, f.id, a, big ? 16 : 10, 220, 500, 0.5, 0xc8ff70, 2.5, 0.3); cloud(fx, f.o, f.id, a, big ? 8 : 4, big ? 36 : 18, 0x1c3008, 0.55, 20, 1); if (a < 7) sc.light(f.o, 0x8cff30, 2, 240); }, + blast(sc, g, f, a) { + const fx = sc.fx, r = f.r || 30, s = r / 30, tt = a / HZ; + flash(fx, f.o, 160 * s, 0xff8a30, 1, a, 16, f.id); shock(fx, f.o, 260 * s, 0xffb060, 0.7, a, 18); + if (tt < 0.5) fx.glow(f.o, 200 * s * (0.6 + tt), 0xff5a10, 0.7 * (1 - tt / 0.5), 0, 0, 0.8); + sparks(fx, f.o, f.id, a, 18, 420 * Math.sqrt(s), 600, 0.7, 0xffc070, 3.5, 0.5); cloud(fx, f.o, f.id, a, 10, 46 * s, 0x2a1810, 0.65, 60, 1.6); + fx.mark([f.o[0], f.o[1], Math.max(0, f.o[2] - 60)], 180 * s, 0xff6010, 0.5 * (1 - a / 48), 0, 0); fx.shadow([f.o[0], f.o[1], Math.max(0, f.o[2] - 60)], 150 * s, 0.5 * (1 - a / 48)); + if (a < 14) sc.light(f.o, 0xff8030, 6 * (1 - a / 14) + 1, 500 * s); + }, + }; + // ---------------- hazards ---------------- + function flames(sc, g) { + const fx = sc.fx; + g.flames.forEach((f, i) => { + const fade = clamp01(f.life / 20), o = f.o, n = Math.floor(o[0] * 7 + o[1] * 13); + for (let k = 0; k < 3; k++) { const fl = h1(n, g.t >> 1, k); fx.glow([o[0] + (fl - 0.5) * 8, o[1] + (h1(n, k, g.t >> 2) - 0.5) * 8, o[2] + 10 + k * 13 + fl * 6], (34 - k * 8) * (0.8 + 0.4 * fl), k ? 0xff7a18 : 0xffb040, 0.5 * fade, 0, fl * 6, 0.5); } + fx.mark(o, 70, 0xff5a10, 0.35 * fade, 0, 0); if (i % 3 === 0) fx.puff(up(o, 50 + (g.t % 30) * 2), 22, 0x201008, 0.3 * fade, n, 0); + if (i % 6 === 0) sc.light(up(o, 30), 0xff7020, 1.4 * fade, 220); + }); + } + function praevusFire(sc, g, b) { + for (const h of b.pillars) { const k = h.age < 4 ? h.age / 4 : clamp01((50 - h.age) / 10), n = Math.floor(h.o[0] * 3 + h.o[1] * 5); + sc.fx.mark([h.o[0], h.o[1], 1], 128, HUE.ember, 0.45 * k, 2, 0); + if (h.age >= 4) for (let j = 0; j < 4; j++) { const fl = h1(n, g.t >> 1, j); sc.fx.glow([h.o[0] + (fl - 0.5) * 20, h.o[1] + (h1(n, j, g.t >> 2) - 0.5) * 20, h.o[2] - 30 + j * 30], 50 * k * (0.8 + 0.4 * fl), j ? 0xff7a18 : 0xffc040, 0.55, 0, fl * 6, 0.5); } + sc.light(up(h.o, 20), 0xff7020, 1.6 * k, 260); } + for (const w of b.walls) { const side = [-w.f[1], w.f[0], 0]; + for (let s = -4; s <= 4; s++) { const at = [w.o[0] + side[0] * s * 25, w.o[1] + side[1] * s * 25, 0], fl = h1(s + 9, g.t >> 1, 5); + sc.fx.glow([at[0], at[1], 30 + fl * 20], 60 + fl * 20, s % 2 ? 0xff7a18 : 0xffb040, 0.55, 0, fl * 6, 0.5); sc.fx.mark(at, 70, HUE.ember, 0.3, 0, 0); } + sc.light(up(w.o, 40), 0xff7020, 2.4, 380); } + } + function deathRings(sc, g, b) { + for (const r of b.rings) { if (r.wait) continue; const fl = [r.c[0], r.c[1], Math.max(0, r.c[2] - 100)], k = r.dmg / 80; sc.fx.mark(fl, 300, HUE.ember, 0.55 - 0.25 * k, 6, r.yaw * Q.DEG); sc.fx.mark(fl, 300 * (1 - k * 0.3), 0xff3010, 0.25, 2, 0); } + } + function swarms(sc, g, b) { + for (const s of b.swarms) { + const k = Math.min(1, s.age / 10) * (s.age > s.life ? clamp01(1 - (s.age - s.life) / 15) : 1); if (k <= 0) continue; + sc.fx.glow(s.o, 110 * k, 0x9ab020, 0.14, 0, 0, 0.8); + for (let j = 0; j < 18; j++) { const a = g.t * (0.12 + 0.1 * h1(s.id, j, 1)) + j * 2.4, r = (14 + 26 * h1(s.id, j, 2)) * k; sc.fx.puff([s.o[0] + Math.cos(a) * r, s.o[1] + Math.sin(a) * r, s.o[2] + Math.sin(a * 1.9 + j) * 18 * k], 4, 0x0e0c06, 0.9, j, 0); } + } + } + function pullBeam(sc, g, b) { + if (!b.beam) return; + const r = b.yaw * Q.DEG, hand = [b.o[0] + Math.cos(r) * 20 - Math.sin(r) * 14, b.o[1] + Math.sin(r) * 20 + Math.cos(r) * 14, b.o[2] + 128], to = up(g.p.o, 30); + for (let k = 0; k < 2; k++) sc.fx.chain(jagged(hand, to, 10, 14 + k * 10, 31 + k, g.t >> 1), 4 - k * 1.5, k ? 0xe0a0ff : 0xb050ff, 0.85, k ? 0.2 : 0.8); + sc.fx.glow(hand, 60, 0xc060ff, 0.7, 3, g.t * 0.2, 0.4); sc.light(hand, 0xb050ff, 3, 300); + } + function lightning(sc, g) { + (g.bolts || []).forEach((w, i) => { + const a = g.t - w.t0, ground = [w.b[0], w.b[1], 2]; + if (a < 9) { const k = 1 - a / 9, pts = jagged(w.a, w.b, 12, 40, w.t0 + i * 17, a >> 1); sc.fx.chain(pts, 18, 0x6080ff, 0.3 * k, 0); sc.fx.chain(pts, 5, 0xd8e4ff, k, 1); sc.fx.glow(ground, 160 * k + 40, 0xa8c8ff, 0.8 * k, 3, i, 0.9); if (a < 4) sc.light(up(ground, 60), 0xc0d8ff, 8, 700); } + if (a < 240) sc.fx.shadow(ground, 70, 0.55 * (1 - a / 240)); + }); + } + // ---------------- the scene's own life ---------------- + function ambient(sc, g, time) { + const fx = sc.fx, st = sc.style; + sc.items.forEach((m, i) => { if (!m.visible) return; const it = g.items[i], hex = it.k === 'health' ? 0xff4030 : 0x40a0ff; fx.glow(it.o.slice(0, 2).concat(26 + Math.sin(time * 2 + i) * 3), 34, hex, 0.45, 0, 0, 0.5); fx.mark([it.o[0], it.o[1], 0], 54, hex, 0.35 + 0.1 * Math.sin(time * 3 + i), 6, time * 0.5 + i); }); + sc.torches.forEach((o, i) => { const fl = h1(i, g.t >> 2, 3); fx.glow([o[0], o[1], o[2] + fl * 4], 26 + fl * 8, st.torch, 0.55, 0, fl * 5, 0.6); fx.glow([o[0], o[1], o[2] + 6], 10, 0xfff0c0, 0.8, 1, 0, 0.3); fx.glow(o, 110, st.torch, 0.08, 0, 0, 0.9); }); + const [w, h] = sc.arena.size; + for (let k = 0; k < 48; k++) { const x = (h1(k, 1, 9) * w + time * 9 * (h1(k, 2, 9) - 0.5)) % w, y = (h1(k, 3, 9) * h + time * 7 * (h1(k, 4, 9) - 0.5)) % h, z = 20 + ((h1(k, 5, 9) * 300 + time * 12) % 300); fx.glow([x < 0 ? x + w : x, y < 0 ? y + h : y, z], 4, st.mote, 0.35, 0, 0, 0.02); } + } + // The wind-up cue: a gathering flare at the move's source, a ring closing on it, sparks drawn in; floor marks for moves that sweep the ground. + function windup(sc, g, tele) { + const fx = sc.fx, k = tele.k, hex = HUE[tele.hue] || 0xffffff, at = tele.at, b = g.boss; + fx.glow(at, 40 + 80 * k, hex, 0.35 + 0.5 * k, 3, g.t * 0.12, 0.6); fx.glow(at, 20 + 20 * k, 0xffffff, 0.4 + 0.5 * k, 1, 0, 0.3); + fx.glow(at, 40 + 220 * (1 - k), hex, 0.25 + 0.5 * k, 2, 0, 0.6); + for (let j = 0; j < 10; j++) { const d = hdir(b.kind.length * 31 + j, 7, 0), f = (k * 2 + j / 10) % 1, r = 140 * (1 - f); fx.streak(Q.ma(at, r + 18, d), Q.ma(at, r, d), 1, 3, hex, 0.8 * f, 0, 0.6); } + sc.light(at, hex, 1.5 + 3 * k, 360); + if (tele.move === 'pest_charge') { const r = b.yaw * Q.DEG; for (let s = 1; s <= 8; s++) fx.mark([b.o[0] + Math.cos(r) * s * 90, b.o[1] + Math.sin(r) * s * 90, 0], 120, HUE.blood, (0.25 + 0.4 * k) * (1 - s / 10), 0, 0); } + if (tele.move === 'eidolon_roar') { fx.mark([1200, 1200, 0], 2000, HUE.storm, 0.18 + 0.2 * k, 6, g.t * 0.004); fx.glow([1200, 1200, 900], 2400, 0x6070c0, 0.08 + 0.12 * k, 0, 0, 2); } + } + function dropMark(sc, m, hex) { const h = Math.max(0, m.o[2]); if (h < 8 || h > 600) return; const k = 1 - h / 600; sc.fx.shadow([m.o[0], m.o[1], 0], 26 + 30 * (1 - k), 0.25 + 0.4 * k); sc.fx.mark([m.o[0], m.o[1], 0], 30 + 50 * (1 - k), hex, 0.15 + 0.35 * k, 2, 0); } + R.drawEffects = (sc, g, time) => { + ambient(sc, g, time); + const b = g.boss; + for (const m of g.missiles) if (!m.player && (m.k === 'boneshard' || m.k === 'hive' || (m.k === 'waraxe' && m.v[2] < -40))) dropMark(sc, m, m.k === 'hive' ? HUE.toxic : m.k === 'boneshard' ? HUE.bone : HUE.blood); + for (const m of g.missiles) { if (m.player) (m.k === 'axe' ? playerAxe : playerBolt)(sc, g, m); else if (BOSS_MISSILE[m.k]) BOSS_MISSILE[m.k](sc, g, m); else sc.fx.glow(m.o, 24, 0xffffff, 0.6, 1, 0, 0.3); } + for (const f of g.fx) { const a = g.t - f.t0; if (IMPACT[f.kind]) IMPACT[f.kind](sc, g, f, a); } + flames(sc, g); + if (b.kind === 'death') deathRings(sc, g, b); + if (b.kind === 'pestilence') swarms(sc, g, b); + if (b.kind === 'famine') pullBeam(sc, g, b); + if (b.kind === 'praevus') { praevusFire(sc, g, b); lightning(sc, g); if (b.state === 'storm') sc.fx.glow([1200, 1200, 900], 2400, 0x8090e0, 0.12 + 0.1 * h1(g.t >> 2, 3, 1), 0, 0, 2); } + if (b.kind === 'eidolon') { lightning(sc, g); if (b.state === 'roar' && b.fr > 13) { sc.fx.glow([1200, 1200, 900], 2400, 0x8090e0, 0.12 + 0.1 * h1(g.t >> 2, 3, 1), 0, 0, 2); } } + const tele = M.telegraph(g); if (tele && V.bossShown(g, b) && !g.outcome) windup(sc, g, tele); + if (g.outcome === 'win') { const c = Q.BOSS[b.kind].aim(g, b); sc.fx.glow(c, 420, 0xffd080, 0.9, 3, 0.3, 0.9); sc.fx.glow(c, 200, 0xffffff, 0.8, 1, 0, 0.6); sc.fx.glow(c, 520, 0xff8030, 0.6, 2, 0, 1.2); sparks(sc.fx, c, 7, 6, 28, 500, 300, 1, 0xffe0a0, 6, 0.4); sc.light(c, 0xffc070, 10, 900); } + // a soft contact shadow under the boss + if (V.bossShown(g, b)) sc.fx.shadow([b.o[0], b.o[1], 0], (b.maxs[0] - b.mins[0]) * 1.7 * (b.kind === 'famine' ? b.scale : 1), 0.45); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/game.js b/environments/games/web/games/hexen2_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..c204743e7c23d282e6e52ebcb126765d8d4b9ae0 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/game.js @@ -0,0 +1,58 @@ +/* Hexen II (1997) boss arenas, rules hexen2-arena@4 - the BossBench module: cases, tiers, original arenas, the 60 Hz tick, the public declaration. + Clock: 60 Hz, a 200 ms packet is twelve ticks, two per hold set. The source think clock HX_FRAME_TIME 0.05 (constant.hc:8) is every third tick (Q.QC). + Independent reimplementation from the GPL-2 uHexen2 source (sezero/uhexen2 3d7ff45). Arenas, loadouts and pickups are original; art is procedural; no pak data is used. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.Hexen2Game, Q = M.Q; + // Tiers on Hexen II's skill cvar: easy = skill 0, normal = skill 1, hard = skill 3 (Nightmare), the original's own modes and the same fight on each. Skill 2 is d in [0.6, 0.8); + // 0.85 keeps hard stable under a +-0.005 step, away from the gate at 0.8. Boss health per tier is a BossBench extension (the riders do not scale with skill), declared in each boss file, + // calibrated to the script windows (easy 20-30 s, normal 45-90 s, hard 150-240 s). Damage, pause and aggression tables are BossBench extensions too; normal is the source value of each. + const TIERS = { easy: 0.2, normal: 0.5, hard: 0.85 }; + const skillOf = d => d < 0.3 ? 0 : d < 0.6 ? 1 : d < 0.8 ? 2 : 3; + const tierOf = d => Object.keys(TIERS).find(t => Math.abs(TIERS[t] - d) < 1e-9) || null; + const tierScale = d => ({ damage: Q.tierValue(d, TIERS, [0.5, 1, 1.5]), pause: Q.tierValue(d, TIERS, [1.5, 1, 0.6]), aggr: Q.tierValue(d, TIERS, [0.6, 1, 1]) }); + const hpOf = (key, d) => Math.round(Q.tierValue(d, TIERS, Q.HP[key])); + const ARENAS = Q.ARENAS, CASES = Q.CASES; + class Game { + constructor(id, seed, d, options) { + const def = CASES.find(c => c.id === id), a = ARENAS[def.arena]; + this.id = id; this.key = def.arena; this.d = d; this.skill = skillOf(d); this.tier = tierOf(d); this.tierScale = tierScale(d); + this.t = 0; this.outcome = null; this.events = []; this.fx = []; this.fxSeq = 0; this.missiles = []; this.flames = []; this.bolts = []; this.tapped = []; this.bossKilled = false; this.bossHits = 0; + this.rng = (Math.imul((seed >>> 0) + 1, 2654435761) ^ 0x9E3779B9) >>> 0 || 1; + this.oneHpFixture = !!(options && options.oneHpFixture); this.fixtureSaves = 0; + this.p = Q.spawnPlayer(a.player.slice(0, 3), a.player[3]); + this.items = a.items.map(([k, x, y, n]) => ({ k, n, o: [x, y, 16], respawn: 0 })); + this.boss = Q.BOSS[this.key].spawn(this, a.boss.slice(0, 3), a.boss[3], hpOf(this.key, d)); + } + get brushes() { return ARENAS[this.key].brushes; } + get paths() { return ARENAS[this.key].paths; } + // SV_Physics order: the client (PlayerPreThink, physics, PlayerPostThink with W_WeaponFrame), then every other edict. Physics and missile flight run every tick; weapons, pickups and + // edict thinks on QC frames. A key pressed between QC frames is held in tapped for the next one, so a short tap is not lost. + update(keys, pressed, mouse) { + this.fx = this.fx.filter(f => this.t - f.t0 < 48); + for (const k of pressed) if (!this.tapped.includes(k)) this.tapped.push(k); + if (this.p.hp > 0) { Q.playerThink(this, keys, mouse); Q.separate(this); } + if (this.t % Q.QC === 0) { + const tap = new Set(this.tapped); this.tapped = []; + if (this.p.hp > 0) { Q.weaponThink(this, new Set([...keys, ...tap]), tap); Q.itemsThink(this); } + Q.BOSS[this.boss.kind].think(this, this.boss); + Q.flamesThink(this); + } + Q.missilesThink(this); + if (this.bossKilled) this.outcome = 'win'; + else if (this.p.hp <= 0) this.outcome = 'loss'; + } + health() { const b = this.boss, D = Q.BOSS[b.kind]; return [Math.max(0, this.p.hp), this.p.maxHp, Math.max(0, D.progress(this, b)), D.max(this, b)]; } + } + Object.assign(M, { + id: 'hexen2_remake', version: 'hexen2-arena@4', hz: 60, maxSeconds: 300, dimension: '3d', renderer: 'webgl-hexen2', + title: 'Hexen II · the Four Horsemen and Eidolon', cases: CASES, tiers: TIERS, pointerLock: true, Game, arenas: ARENAS, skillOf, tierOf, tierScale, hpTable: Q.HP, + controls: { + 'W / S': 'Forward / backward (speed 200; Shift ×2)', 'A / D': 'Strafe left / right (speed 225; Shift ×2)', 'Shift': 'Run (cl_movespeedkey 2.0)', + 'mouse dx / dy': 'Turn / pitch (0.066° per count; 80° down, 70° up)', 'Q / E': 'Turn left / right with keyboard (140°/s)', 'Space': 'Jump (initial velocity 270)', 'L': 'Crouch', + 'J / LMB': 'Attack (hold to repeat)', 'K / RMB': 'Next weapon', 'R': 'Previous weapon', + }, + copyGame: g => Object.assign(Object.create(Game.prototype), N.copy(g)), + validateOptions(o) { for (const k of Object.keys(o)) if (k !== 'oneHpFixture') throw Error('unknown option ' + k); if (typeof o.oneHpFixture !== 'boolean') throw Error('oneHpFixture must be boolean'); }, + }); +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/h2boss.js b/environments/games/web/games/hexen2_remake/h2boss.js new file mode 100644 index 0000000000000000000000000000000000000000..ee3a46ccb688d4392b0f3f57ea8a610d9c0346fc --- /dev/null +++ b/environments/games/web/games/hexen2_remake/h2boss.js @@ -0,0 +1,186 @@ +/* Hexen II boss arenas - what every boss shares: the frame helper (PF_AdvanceFrame), rider paths and riderpath_move (rider.hc), + HomeThink (projbhvr.hc), T_RadiusDamage (damage.hc), the missile table and shot traces. One file per boss registers itself in Q.BOSS. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q; + Q.BOSS = {}; Q.MISSILE = {}; Q.ARENAS = {}; Q.CASES = []; Q.HP = {}; + // Each boss file registers its own case, original arena and tier health, so adding a boss touches no shared file. + Q.ring = (cx, cy, r, n, z) => Array.from({ length: n }, (_, i) => [cx + r * Math.cos(i * 2 * Math.PI / n), cy + r * Math.sin(i * 2 * Math.PI / n), z]); + // A rider_path ring: from each point the next point, the next but one, or back. Chords are NOT guaranteed clear for a wide boss; . + Q.ringPaths = (pts, skip) => pts.map((o, i) => ({ o: o.map(Math.round), next: [(i + 1) % pts.length, (i + skip) % pts.length, (i + pts.length - 1) % pts.length] })); + const AF_BEGINNING = 1, AF_END = 2; + Q.AF_BEGINNING = AF_BEGINNING; Q.AF_END = AF_END; + // PF_AdvanceFrame on frames counted 1..n of the current animation; fr 0 = "not in this range yet". + Q.advanceFrame = (b, n) => { + if (b.fr < 1 || b.fr > n) { b.fr = 1; return 0; } + if (b.fr === n) { b.fr = 1; return AF_BEGINNING; } + b.fr++; + return b.fr === n ? AF_END : 0; + }; + // QuakeC makevectors on entity angles: AngleVectors takes pitch down positive while vectoangles returns pitch up positive, so the z of a forward vector flips. + Q.qcVectors = ang => Q.viewVectors([ang[0], ang[1]]); + // ---------------- rider paths ---------------- + Q.pathNext = (g, b) => { // riderpath_findnext: random among the point's next_path entries + const next = g.paths[b.path].next; + b.path = next[Math.min(next.length - 1, Math.floor(Q.random(g, next.length)))]; + }; + Q.boxAt = (b, o) => ({ mins: [o[0] + b.mins[0], o[1] + b.mins[1], o[2] + b.mins[2]], maxs: [o[0] + b.maxs[0], o[1] + b.maxs[1], o[2] + b.maxs[2]] }); + Q.touchesPlayer = (g, b, o) => { + const p = g.p, pb = Q.playerBox(p), B = Q.boxAt(b, o); + return p.hp > 0 && p.o[0] + pb.maxs[0] > B.mins[0] && p.o[0] + pb.mins[0] < B.maxs[0] && p.o[1] + pb.maxs[1] > B.mins[1] && p.o[1] + pb.mins[1] < B.maxs[1] && p.o[2] + pb.maxs[2] > B.mins[2] && p.o[2] + pb.mins[2] < B.maxs[2]; + }; + // walkmove: one step along yaw, refused by a brush or by the player. Returns 'ok', 'world' or 'player'. + Q.walkMove = (g, b, yaw, dist) => { + const r = yaw * Q.DEG, o = [b.o[0] + Math.cos(r) * dist, b.o[1] + Math.sin(r) * dist, b.o[2]]; + if (Q.pointSolid(g, o, b.mins, b.maxs)) return 'world'; + if (Q.touchesPlayer(g, b, o)) return 'player'; + b.o = o; + return 'ok'; + }; + // The ram in riderpath_move and psthorse_move: in front 1000-1600 and 25-35 damage, otherwise 700-900 and 15-20 (rider.hc:200-226). + Q.ram = (g, b) => { + const p = g.p, d = Q.norm(Q.sub(Q.center(p), Q.center(b))), yr = b.yaw * Q.DEG; + const front = Q.dot(d, [Math.cos(yr), Math.sin(yr), 0]) > 0.3; // infront(): dot > 0.3 (ai.hc) + p.v = Q.ma(p.v, front ? Q.random(g, 1000, 1600) : Q.random(g, 700, 900), d); + if (p.v[2] > 1) p.onground = false; + Q.damagePlayer(g, front ? Q.random(g, 25, 35) : Q.random(g, 15, 20), Q.center(b), 'ram'); + }; + // riderpath_move: head for the current path point, walkmove, movetogoal when blocked. Famine never rams (rider.hc:200). + Q.riderpathMove = (g, b, speed, rams) => { + const node = g.paths[b.path].o; + b.ideal_yaw = Q.vectoyaw(Q.sub(node, b.o)); + b.y_change = Q.changeYaw(b); + if (b.fly) { // MOVETYPE_FLY: glide toward the point's height inside 400 units + const dist = Q.hlen(Q.sub(b.o, node)); let alt = node[2] - b.o[2]; + if (dist < 400) { + const t = (1 - (dist - b.path_distance) / (400 - b.path_distance)) / 6; + if (alt > 30) b.move_adjust -= 0.1; else if (alt < -30) b.move_adjust += 0.15; + if (alt > 60) b.move_adjust -= 0.1; else if (alt < -60) b.move_adjust += 0.15; + alt *= t; + } else { alt = 0; b.move_adjust -= b.move_adjust / 15; } + b.o = [b.o[0], b.o[1], b.o[2] + alt]; + } + const step = speed + (b.move_adjust || 0), res = Q.walkMove(g, b, b.yaw, step); + if (res !== 'ok') { + if (res === 'player' && rams) Q.ram(g, b); + // movetogoal: the direct heading, then either side of it (SV_StepDirection / SV_NewChaseDir simplified; approximation). + const y = Q.vectoyaw(Q.sub(node, b.o)); + for (const off of [0, 45, -45, 90, -90]) if (Q.walkMove(g, b, y + off, step) === 'ok') break; + } + if (Q.hlen(Q.sub(b.o, g.paths[b.path].o)) < b.path_distance) Q.pathNext(g, b); + }; + // The boss is solid to the player (SOLID_SLIDEBOX): resolve an overlap along the shallower horizontal axis. + Q.separate = g => { + const p = g.p, b = g.boss; + if (!b.solid) return; + const pb = Q.playerBox(p), B = Q.boxAt(b, b.o); + if (p.o[2] + pb.maxs[2] <= B.mins[2] || p.o[2] >= B.maxs[2]) return; + const dx0 = B.maxs[0] - (p.o[0] + pb.mins[0]), dx1 = (p.o[0] + pb.maxs[0]) - B.mins[0], dy0 = B.maxs[1] - (p.o[1] + pb.mins[1]), dy1 = (p.o[1] + pb.maxs[1]) - B.mins[1]; + if (dx0 <= 0 || dx1 <= 0 || dy0 <= 0 || dy1 <= 0) return; + const m = Math.min(dx0, dx1, dy0, dy1), o = p.o.slice(); + if (m === dx0) o[0] += dx0; else if (m === dx1) o[0] -= dx1; else if (m === dy0) o[1] += dy0; else o[1] -= dy1; + if (!Q.pointSolid(g, o, pb.mins, pb.maxs)) p.o = o; + }; + // T_RadiusDamage against the player: radius damage+40 (circfire 150), points = damage - 0.5 * distance centre to centre. + Q.radiusDamage = (g, at, damage, source, radius) => { + const p = g.p, c = Q.center(p), dist = Q.len(Q.sub(c, at)); + if (dist > (radius === undefined ? damage + 40 : radius)) return 0; + const pts = damage - 0.5 * dist; + if (pts <= 0 || !Q.clear(g, at, c)) return 0; + // A player's mass is at most 10, so inertia is 1: velocity += direction * points * 10 and off the ground. + const d = Q.norm(Q.sub(c, at)); p.v = Q.ma(p.v, pts * 10, d); p.onground = false; + return Q.damagePlayer(g, pts, at, source); + }; + // ---------------- missiles ---------------- + // HomeThink: newdir = (olddir*turn_time + huntdir)/(turn_time+1); the result is not renormalized, so a hard turn really slows the missile. Turns only while it sees the eye. + Q.home = (g, m) => { + const p = g.p; if (p.hp <= 0) return; + const eye = Q.eye(p); + if (!Q.clear(g, m.o, eye)) return; + const old = Q.norm(m.v), hunt = Q.norm(Q.sub(eye, m.o)), t = m.turn, nd = [(old[0] * t + hunt[0]) / (t + 1), (old[1] * t + hunt[1]) / (t + 1), (old[2] * t + hunt[2]) / (t + 1)]; + const mod = m.hover ? Math.max(0.05, Q.dot(old, nd)) : 1; // hoverz: slow down on turns + m.v = Q.scale(nd, m.speed * mod); + }; + Q.veer = (g, m, amount) => { m.v = [m.v[0] + Q.random(g, -amount, amount), m.v[1] + Q.random(g, -amount, amount), m.v[2] + Q.random(g, -amount, amount)]; }; + // Trace a segment through the brushes and whatever the boss currently exposes to shots. + Q.traceShot = (g, s, e, grow) => { + const tr = Q.traceWorld(g, s, e), G = grow || 0; let best = tr.fraction, target = null; + for (const t of Q.BOSS[g.boss.kind].targets(g, g.boss)) { + const h = Q.slab(s, e, [t.mins[0] - G, t.mins[1] - G, t.mins[2] - G], [t.maxs[0] + G, t.maxs[1] + G, t.maxs[2] + G]); + if (h && h.frac < best) { best = h.frac; target = t.id; } + } + return { fraction: best, target, normal: target ? null : tr.normal, end: Q.ma(s, best, Q.sub(e, s)) }; + }; + Q.hurtTarget = (g, id, dmg, kind) => { + const b = g.boss, D = Q.BOSS[b.kind], before = D.progress(g, b); + D.hurt(g, b, id, dmg, kind); + g.events.push({ type: 'boss_damage', amount: Math.round((before - D.progress(g, b)) * 1000) / 1000, target: id, weapon: kind, tick: g.t }); + g.bossHits++; + }; + Q.missilesThink = g => { + const p = g.p, keep = [], qc = g.t % Q.QC === 0; + for (const m of g.missiles) { + const d = Q.MISSILE[m.k]; + if (qc) { // life and think (homing, gravity) stay on the QC clock; only the flight and its traces are per tick + if (m.life-- <= 0) { if (d && d.expire) d.expire(g, m); continue; } + if (d && d.think && d.think(g, m) === false) continue; + } + const e = Q.ma(m.o, Q.TICK, m.v); + if (m.player) { + const tr = Q.traceShot(g, m.o, e, 15); // SV_Move clips MOVE_MISSILE 15 units larger against monsters (world.c:1054) + if (tr.target) { Q.hurtTarget(g, tr.target, m.k === 'axe' ? Q.random(g, 30, 50) : Q.random(g, 15, 25), m.k); Q.fx(g, 'hit', tr.end, { r: 5 }); continue; } + if (tr.fraction < 1) { + if (m.k === 'axe' && ++m.cnt < 4) { // T_PhaseMissileTouch: bounce three times, losing a quarter of its speed each time + const back = 2 * Q.dot(m.v, tr.normal); + m.v = Q.scale([m.v[0] - tr.normal[0] * back, m.v[1] - tr.normal[1] * back, m.v[2] - tr.normal[2] * back], 0.75); + m.o = Q.ma(tr.end, 1, tr.normal); keep.push(m); continue; + } + Q.fx(g, 'spark', tr.end, { r: 4 }); continue; + } + m.o = e; keep.push(m); continue; + } + const wt = Q.traceWorld(g, m.o, e), ph = p.hp > 0 ? Q.hitPlayerBox(p, m.o, e) : null; + if (ph && ph.frac <= wt.fraction) { m.o = Q.ma(m.o, ph.frac, Q.sub(e, m.o)); if (d.touch(g, m, true) === 'keep') keep.push(m); continue; } + if (wt.fraction < 1) { m.o = wt.end; m.normal = wt.normal; if (d.touch(g, m, false) === 'keep') keep.push(m); continue; } + m.o = e; keep.push(m); + } + g.missiles = keep; + }; + // famine_missile_touch, also used by Death's death_missile_2: 8-16 damage and a red spark. + Q.MISSILE.famshot = { + think(g, m) { Q.home(g, m); }, + touch(g, m, hitPlayer) { if (hitPlayer) Q.damagePlayer(g, Q.random(g, 8, 16), m.o, m.src); Q.fx(g, 'redspark', m.o); }, + expire(g, m) { Q.fx(g, 'redspark', m.o); }, + }; + // Floor flames (mummy.hc mflame_burn, SpawnMummyFlame): a point on the ground that burns whoever stands on it, dmg + random()*dmg at most every .05 s. + Q.spawnFlame = (g, x, y, dmg, life) => { const tr = Q.traceWorld(g, [x, y, 40], [x, y, -600]); g.flames.push({ o: [x, y, tr.end[2]], dmg, life: Math.round(life * 20) }); }; + Q.flamesThink = g => { + if (!g.flames.length) return; + const p = g.p, box = Q.playerBox(p), keep = []; + for (const f of g.flames) { + if (--f.life <= 0) continue; + keep.push(f); + if (p.hp > 0 && f.o[0] > p.o[0] + box.mins[0] && f.o[0] < p.o[0] + box.maxs[0] && f.o[1] > p.o[1] + box.mins[1] && f.o[1] < p.o[1] + box.maxs[1] && f.o[2] + 16 > p.o[2] && f.o[2] < p.o[2] + box.maxs[2]) + Q.damagePlayer(g, f.dmg + Q.random(g) * f.dmg, null, 'flame'); + } + g.flames = keep; + }; + // lightning_strike (lightning.hc) of a light_thunderstorm with the LIGHTNING flag: a random point within its radius, then 3-7 beams down the sky, dmg to whoever a beam crosses. + // The base game's storm does 10000 a beam (Eidolon): a hit kills and the strike ends there. The mission pack's does 50 when the storm is locked to Praevus + // (portals/lightning.hc:320-323) and the cascade goes on. One ray per beam against the player's box: the side rays are not implemented ( deviation table). + Q.lightningStrike = (g, storm, radius, dmg, source) => { + const a = Q.random(g, 360) * Q.DEG, d = Q.random(g, radius); let org = Q.traceWorld(g, storm, [storm[0] + Math.cos(a) * d, storm[1] + Math.sin(a) * d, storm[2]]).end; + let to = [org[0] + Q.random(g, -100, 100), org[1] + Q.random(g, -100, 100), 0], n = Math.round(Q.random(g, 3, 7)); + while (n-- > 0) { + g.bolts.push({ a: org.slice(), b: to.slice(), t0: g.t }); if (g.bolts.length > 24) g.bolts.shift(); + const h = g.p.hp > 0 ? Q.slab(org, to, [g.p.o[0] - 16, g.p.o[1] - 16, g.p.o[2]], [g.p.o[0] + 16, g.p.o[1] + 16, g.p.o[2] + 56]) : null; + if (h) { Q.damagePlayer(g, dmg, null, source); if (dmg >= 10000) return; } + const dir = Q.norm(Q.sub(to, org)), len = Q.len(Q.sub(to, org)); + org = Q.ma(org, Q.random(g, n + len / 10, n + len / 5), dir); + to = [org[0] + (Q.random(g) < 0.5 ? 1 : -1) * Q.random(g, 125, 375), org[1] + (Q.random(g) < 0.5 ? 1 : -1) * Q.random(g, 125, 375), 0]; + } + }; + Q.spawnMissile = (g, k, o, v, life, extra) => { const m = Object.assign({ k, o: o.slice(), v: v.slice(), life: Math.round(life * 20), id: g.fxSeq++ }, extra || {}); g.missiles.push(m); return m; }; + // Tier aggression, a BossBench extension: a voluntary attack roll passes with this chance at easy, always at normal and above. + Q.aggressive = g => g.tierScale.aggr >= 1 || Q.random(g) < g.tierScale.aggr; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/h2core.js b/environments/games/web/games/hexen2_remake/h2core.js new file mode 100644 index 0000000000000000000000000000000000000000..5688f38979633b432b7dc97340c32fb6e84092eb --- /dev/null +++ b/environments/games/web/games/hexen2_remake/h2core.js @@ -0,0 +1,96 @@ +/* Hexen II (1997) boss arenas, rules hexen2-arena@4 - shared core: dice, vectors, QuakeC angle helpers, axis-aligned brush world and traces. + Independent reimplementation from the GPL-2 uHexen2 source (sezero/uhexen2 3d7ff45); no game data (pak, models, sounds, maps) is used. + Units are Quake units, z up. All state is plain JSON (the runtime deep-copies and quantizes it). */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.Hexen2Game = {}, Q = M.Q = {}; + // The simulation runs at 60 Hz. The original's think clock stays as it was: HX_FRAME_TIME 0.05 (constant.hc:8), sys_ticrate 0.05 (host.c:63), so a QC frame is every third tick. + // Everything that ticks on QC frames keeps its source numbers and its seconds exactly; player physics and missile flight integrate over Q.TICK. + Q.DT = 0.05; Q.QC = 3; Q.TICK = 1 / 60; + Q.now = g => Math.floor(g.t / Q.QC) * Q.DT; // QuakeC time: the same float a 20 Hz clock gave + Q.DEG = Math.PI / 180; + // QuakeC random(), random(x), random(a, b) on the game's own dice. + Q.random = (g, a, b) => { const r = N.rand(g); return a === undefined ? r : b === undefined ? r * a : a + r * (b - a); }; + Q.add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; + Q.sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + Q.scale = (a, s) => [a[0] * s, a[1] * s, a[2] * s]; + Q.ma = (a, s, b) => [a[0] + s * b[0], a[1] + s * b[1], a[2] + s * b[2]]; + Q.dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + Q.len = a => Math.hypot(a[0], a[1], a[2]); + Q.hlen = a => Math.hypot(a[0], a[1]); // vhlen + Q.norm = a => { const l = Q.len(a); return l ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0]; }; + Q.anglemod = a => ((a % 360) + 360) % 360; + Q.angdiff = a => ((a % 360) + 540) % 360 - 180; + Q.vectoyaw = v => (v[0] === 0 && v[1] === 0) ? 0 : Q.anglemod(Math.atan2(v[1], v[0]) / Q.DEG); + // vectoangles: [pitch up positive, yaw, 0] as QuakeC stores it on entities. + Q.vectoangles = v => { const f = Q.hlen(v); return [(f === 0 && v[2] === 0) ? 0 : Math.atan2(v[2], f) / Q.DEG, Q.vectoyaw(v), 0]; }; + // makevectors on an entity's angles (pitch up positive); use viewVectors for a player's v_angle (pitch down positive). + Q.makevectors = ang => { + const p = ang[0] * Q.DEG, y = ang[1] * Q.DEG, cp = Math.cos(p), sp = Math.sin(p), cy = Math.cos(y), sy = Math.sin(y); + return { f: [cp * cy, cp * sy, sp], r: [sy, -cy, 0], u: [-sp * cy, -sp * sy, cp] }; + }; + Q.viewVectors = v => Q.makevectors([-v[0], v[1], 0]); + // PF_changeyaw: turn e.yaw toward e.ideal_yaw by at most e.yaw_speed per call; returns the turn still wanted BEFORE the clamp (pr_cmds.c: OFS_RETURN is set first). War's gait reads it. + Q.changeYaw = e => { + const cur = Q.anglemod(e.yaw); let move = Q.anglemod(e.ideal_yaw) - cur; + if (move === 0) return 0; + if (cur < Q.anglemod(e.ideal_yaw)) { if (move >= 180) move -= 360; } else if (move <= -180) move += 360; + const wanted = move; + if (move > 0) move = Math.min(move, e.yaw_speed); else move = Math.max(move, -e.yaw_speed); + e.yaw = Q.anglemod(cur + move); + return wanted; + }; + // ---------------- brushes: axis-aligned solids of the original arenas; static per case (never in the state) ---------------- + // Segment against one box grown by the moving box; returns entry fraction and face normal, or null. + Q.slab = (s, e, mins, maxs) => { + let t0 = 0, t1 = 1, axis = -1, sign = 0; + for (let i = 0; i < 3; i++) { + const d = e[i] - s[i]; + if (d === 0) { if (s[i] <= mins[i] || s[i] >= maxs[i]) return null; continue; } + let a = (mins[i] - s[i]) / d, b = (maxs[i] - s[i]) / d, sg = -1; + if (a > b) { const c = a; a = b; b = c; sg = 1; } + if (a >= t0) { t0 = a; axis = i; sign = sg; } + if (b < t1) t1 = b; + if (t0 >= t1) return null; + } + return { frac: t0, axis, sign }; + }; + Q.boxHit = (o, mins, maxs, grow) => { const g = grow || 0; return { mins: [o[0] + mins[0] - g, o[1] + mins[1] - g, o[2] + mins[2] - g], maxs: [o[0] + maxs[0] + g, o[1] + maxs[1] + g, o[2] + maxs[2] + g] }; }; + const NOBOX = [0, 0, 0]; + // Trace a box through the world brushes. fraction 1 = clear. normal points back at the mover. + Q.traceWorld = (g, s, e, mins, maxs) => { + const m0 = mins || NOBOX, m1 = maxs || NOBOX; + let best = 1, normal = null; + for (const b of g.brushes) { + const hit = Q.slab(s, e, [b.mins[0] - m1[0], b.mins[1] - m1[1], b.mins[2] - m1[2]], [b.maxs[0] - m0[0], b.maxs[1] - m0[1], b.maxs[2] - m0[2]]); + if (hit && hit.axis >= 0 && hit.frac < best) { best = hit.frac; normal = [0, 0, 0]; normal[hit.axis] = hit.sign; } + } + const end = best === 1 ? [e[0], e[1], e[2]] : [s[0] + (e[0] - s[0]) * best, s[1] + (e[1] - s[1]) * best, s[2] + (e[2] - s[2]) * best]; + if (normal) for (let i = 0; i < 3; i++) end[i] += normal[i] * 0.03125; // DIST_EPSILON: never rest exactly on a plane + return { fraction: best, normal, end }; + }; + Q.pointSolid = (g, p, mins, maxs) => { + const m0 = mins || NOBOX, m1 = maxs || NOBOX; + for (const b of g.brushes) if (p[0] + m1[0] > b.mins[0] && p[0] + m0[0] < b.maxs[0] && p[1] + m1[1] > b.mins[1] && p[1] + m0[1] < b.maxs[1] && p[2] + m1[2] > b.mins[2] && p[2] + m0[2] < b.maxs[2]) return true; + return false; + }; + Q.clear = (g, a, b) => Q.traceWorld(g, a, b).fraction === 1; + Q.brush = (x0, y0, z0, x1, y1, z1, mat) => ({ mins: [x0, y0, z0], maxs: [x1, y1, z1], mat }); + // Floor, four walls and a ceiling; walls are thick so a fast missile never tunnels. + Q.shell = (w, h, height, mat) => { + const t = 128, B = Q.brush; + return [B(-t, -t, -t, w + t, h + t, 0, mat.floor), B(-t, -t, 0, 0, h + t, height, mat.wall), B(w, -t, 0, w + t, h + t, height, mat.wall), + B(0, -t, 0, w, 0, height, mat.wall), B(0, h, 0, w, h + t, height, mat.wall), B(-t, -t, height, w + t, h + t, height + t, mat.roof)]; + }; + // Tier anchors, linear between them, held outside: the same table shape for every tier-scaled number. + Q.tierValue = (d, T, v) => { + if (d <= T.easy) return v[0]; + if (d >= T.hard) return v[2]; + if (d <= T.normal) return v[0] + (v[1] - v[0]) * (d - T.easy) / (T.normal - T.easy); + return v[1] + (v[2] - v[1]) * (d - T.normal) / (T.hard - T.normal); + }; + Q.fx = (g, kind, o, extra) => { + g.fx.push(Object.assign({ kind, o: [o[0], o[1], o[2]], t0: g.t, id: g.fxSeq++ }, extra || {})); + if (g.fx.length > 64) g.fx.splice(0, g.fx.length - 64); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/h2player.js b/environments/games/web/games/hexen2_remake/h2player.js new file mode 100644 index 0000000000000000000000000000000000000000..753937c6f5f796c6ad8a2529eebd124d197858ae --- /dev/null +++ b/environments/games/web/games/hexen2_remake/h2player.js @@ -0,0 +1,217 @@ +/* Hexen II boss arenas - the player: a level 5 Paladin. usercmd (cl_input.c), SV_UserFriction / SV_Accelerate / SV_AirAccelerate (sv_user.c), + gravity and jump (sv_phys.c, client.hc), T_Damage and armor (damage.hc), the four Paladin weapons with their weapon frames, items. + Independent reimplementation; see for the facts and file names. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q; + const MINS = [-16, -16, 0], MAXS = [16, 16, 56], MAXS_CROUCH = [16, 16, 28]; // client.hc:878, :1870 + const FORWARD = 200, SIDE = 225, RUN = 2, MAXSPEED = 640; // cl_input.c forward/side move, cl_movespeedkey 2.0; sv_maxspeed 640 + const FRICTION = 4, STOPSPEED = 100, EDGEFRICTION = 2, ACCEL = 10, GRAVITY = 800, JUMP = 270, AIRCAP = 30, STEP = 18; + const YAWSPEED = 140, MOUSE_DEG = 3 * 0.022; // cl_yawspeed 140 deg/s; sensitivity 3 x m_yaw 0.022 + const ARMOR_PROT = { amulet: 0.05, bracer: 0.10, breast: 0.25, helm: 0.15 }; // damage.hc ClassArmorProtection, Paladin row + const STRENGTH_MOD = 1 + (17 - 11) / 30; // T_Damage melee mod for strength 17 (table 15-18) + const WEAPONS = ['gauntlet', 'vorpal', 'axe', 'purifier']; + Q.WEAPONS = WEAPONS; Q.MOUSE_DEG = MOUSE_DEG; + Q.playerBox = p => ({ mins: MINS, maxs: p.crouch ? MAXS_CROUCH : MAXS }); + Q.eye = p => [p.o[0], p.o[1], p.o[2] + (p.crouch ? 24 : 50)]; // view_ofs 50, crouched 24 (client.hc:775, :1338) + Q.spawnPlayer = (origin, yaw) => ({ + o: origin.slice(), v: [0, 0, 0], yaw, pitch: 0, onground: true, crouch: false, jumpHeld: false, + hp: 120, maxHp: 120, level: 5, green: 120, blue: 120, // BossBench practice character: mid-roll level 5 from the stats.hc tables + armor: { amulet: 0, bracer: 0, breast: 20, helm: 20 }, // armor pieces are 20 points each (items.hc:768-780) + weapon: 'purifier', wfr: 0, wth: 'ready', attack_finished: 0, poison: [], dmgAlpha: 0, dmgDir: null, kick: 0, hits: 0, taken: 0, + }); + + // ---------------- movement ---------------- + function friction(g, p, dt) { + const speed = Q.hlen(p.v); if (speed < 1) { p.v[0] = 0; p.v[1] = 0; return; } + // SV_UserFriction: double friction when the ground 16 units ahead along the velocity is missing. + const s = [p.o[0] + p.v[0] / speed * 16, p.o[1] + p.v[1] / speed * 16, p.o[2]]; + const f = Q.traceWorld(g, s, [s[0], s[1], s[2] - 34]).fraction === 1 ? FRICTION * EDGEFRICTION : FRICTION; + const ns = Math.max(0, speed - dt * Math.max(speed, STOPSPEED) * f) / speed; + p.v[0] *= ns; p.v[1] *= ns; + } + function accelerate(p, wishspeed, dir, dt) { + const add = wishspeed - Q.dot(p.v, dir); if (add <= 0) return; + const a = Math.min(add, ACCEL * dt * wishspeed); + for (let i = 0; i < 3; i++) p.v[i] += a * dir[i]; + } + function airAccelerate(p, wishspeed, dir, dt) { + const add = Math.min(wishspeed, AIRCAP) - Q.dot(p.v, dir); if (add <= 0) return; + const a = Math.min(add, ACCEL * wishspeed * dt); + for (let i = 0; i < 3; i++) p.v[i] += a * dir[i]; + } + // SV_FlyMove: slide along up to four planes. + function flyMove(g, p, dt, box) { + let left = dt, blocked = false; + for (let n = 0; n < 4 && left > 0; n++) { + const tr = Q.traceWorld(g, p.o, Q.ma(p.o, left, p.v), box.mins, box.maxs); + if (tr.fraction > 0) p.o = tr.end; + if (tr.fraction === 1) break; + left *= 1 - tr.fraction; blocked = true; + const back = Q.dot(p.v, tr.normal); + for (let i = 0; i < 3; i++) { p.v[i] -= tr.normal[i] * back; p.o[i] += tr.normal[i] * 0.03125; } + } + return blocked; + } + function groundCheck(g, p, box) { + const tr = Q.traceWorld(g, p.o, [p.o[0], p.o[1], p.o[2] - 1], box.mins, box.maxs); + const on = tr.fraction < 1 && tr.normal && tr.normal[2] > 0.7 && p.v[2] <= 1; + if (on) { p.o[2] = tr.end[2]; p.v[2] = 0; } + p.onground = !!on; + } + // SV_WalkMove: on a blocked horizontal move retry 18 units higher, then settle back down. + function walkMove(g, p, dt, box) { + const o0 = p.o.slice(), v0 = p.v.slice(); + if (!flyMove(g, p, dt, box) || !p.onground) return; + const o1 = p.o.slice(), v1 = p.v.slice(); + const up = Q.traceWorld(g, o0, [o0[0], o0[1], o0[2] + STEP], box.mins, box.maxs); + p.o = up.end.slice(); p.v = v0; + flyMove(g, p, dt, box); + const down = Q.traceWorld(g, p.o, [p.o[0], p.o[1], p.o[2] - STEP - 1], box.mins, box.maxs); + if (down.fraction === 1 || !down.normal || down.normal[2] < 0.7) { p.o = o1; p.v = v1; return; } + p.o = down.end.slice(); + if (Q.hlen(Q.sub(p.o, o0)) < Q.hlen(Q.sub(o1, o0))) { p.o = o1; p.v = v1; } + } + Q.playerThink = (g, keys, mouse) => { + const p = g.p, dt = Q.TICK; + // CL_AdjustAngles + mouse look; pitch range 80 down, 70 up (cl_input.c:452-454). + if (keys.has('Q')) p.yaw += YAWSPEED * dt; + if (keys.has('E')) p.yaw -= YAWSPEED * dt; + p.yaw = Q.anglemod(p.yaw - mouse[0] * MOUSE_DEG); + p.pitch = Math.max(-70, Math.min(80, p.pitch + mouse[1] * MOUSE_DEG)); + p.crouch = keys.has('L') || (p.crouch && Q.pointSolid(g, p.o, MINS, MAXS)); // cannot stand up under a brush + const box = Q.playerBox(p); + let fwd = 0, side = 0; + if (keys.has('W')) fwd += FORWARD; + if (keys.has('S')) fwd -= FORWARD; + if (keys.has('D')) side += SIDE; + if (keys.has('A')) side -= SIDE; + if (keys.has('Shift')) { fwd *= RUN; side *= RUN; } + const yr = p.yaw * Q.DEG, f = [Math.cos(yr), Math.sin(yr), 0], r = [Math.sin(yr), -Math.cos(yr), 0]; + let wish = [f[0] * fwd + r[0] * side, f[1] * fwd + r[1] * side, 0], speed = Q.len(wish); + if (speed > MAXSPEED) { wish = Q.scale(wish, MAXSPEED / speed); speed = MAXSPEED; } + const dir = Q.norm(wish); + if (keys.has('Space') && p.onground && !p.jumpHeld) { p.v[2] += JUMP; p.onground = false; p.jumpHeld = true; } + if (!keys.has('Space')) p.jumpHeld = false; + if (p.onground) { friction(g, p, dt); accelerate(p, speed, dir, dt); } + else airAccelerate(p, speed, dir, dt); + if (!p.onground) p.v[2] -= GRAVITY * dt; + for (let i = 0; i < 3; i++) p.v[i] = Math.max(-2000, Math.min(2000, p.v[i])); // sv_maxvelocity + if (p.onground) walkMove(g, p, dt, box); else flyMove(g, p, dt, box); + groundCheck(g, p, box); + p.dmgAlpha = Math.max(0, p.dmgAlpha - dt * 1.6); p.kick = Math.max(0, p.kick - dt * 10); + // poison_think: 1 damage per second for each active dose (pstboar.hc). + p.poison = p.poison.filter(d => { if (g.t < d.next) return true; Q.damagePlayer(g, 1, null, 'poison'); d.next = g.t + 60; return g.t < d.until; }); + }; + + // ---------------- damage ---------------- + // T_Damage + armor_calc for the player. The tier damage scale is a BossBench extension applied here, once, to every boss source. + Q.damagePlayer = (g, dmg, from, source) => { + const p = g.p; if (p.hp <= 0) return 0; + const scaled = dmg * g.tierScale.damage; + const a = p.armor, pieces = ['amulet', 'bracer', 'breast', 'helm'].filter(k => a[k] > 0); + let absorbed = 0; + if (pieces.length) { + let prot = p.level * 0.001; for (const k of pieces) prot += ARMOR_PROT[k]; + absorbed = prot * scaled; + if (absorbed > pieces.reduce((s, k) => s + a[k], 0)) { for (const k of pieces) a[k] = 0; } + else { + const per = absorbed / pieces.length; // a single pass over the pieces: the original's loop was commented out for E3 + for (const k of pieces) { a[k] -= per; if (a[k] < 1) a[k] = 0; } + } + } + const taken = scaled - absorbed; + if (from) { // velocity += dir * damage * 8 for MOVETYPE_WALK + const d = Q.norm(Q.sub(Q.center(p), from)); + p.v = Q.ma(p.v, scaled * 8, d); p.dmgDir = d; + if (p.v[2] > 1) p.onground = false; + } + p.hp -= taken; p.taken += taken; p.hits++; + if (p.hp >= 0 && p.hp < 1) p.hp = -0.1; // "No more Zombie mode" (damage.hc) + p.dmgAlpha = Math.min(0.6, p.dmgAlpha + 0.1 + taken * 0.01); p.kick = Math.min(1, p.kick + 0.4); + g.events.push({ type: 'player_damage', amount: Math.round(taken * 1000) / 1000, source: source || null, tick: g.t }); + if (p.hp <= 0 && g.oneHpFixture) { p.hp = 1; g.fixtureSaves++; } + return taken; + }; + Q.center = e => { const m = e.mins ? e : Q.playerBox(e); return [e.o[0] + (m.mins[0] + m.maxs[0]) / 2, e.o[1] + (m.mins[1] + m.maxs[1]) / 2, e.o[2] + (m.mins[2] + m.maxs[2]) / 2]; }; + Q.heal = (p, n) => { if (p.hp >= p.maxHp) return false; p.hp = Math.min(p.maxHp, p.hp + Math.ceil(n)); return true; }; + Q.hitPlayerBox = (p, s, e) => { const b = Q.playerBox(p), o = p.o; return Q.slab(s, e, [o[0] + b.mins[0], o[1] + b.mins[1], o[2] + b.mins[2]], [o[0] + b.maxs[0], o[1] + b.maxs[1], o[2] + b.maxs[2]]); }; + + // ---------------- weapons: W_WeaponFrame + player_frames th_weapon on QC frames (20 a second); animation frames counted from 1 as in the source ---------------- + function melee(g, p, base, mod, reach, scale) { + // FireMelee / gauntlet_fire / vorpal_melee: straight 64, then reach 30 down, then reach 30 up. + const v = Q.viewVectors([p.pitch, p.yaw]), s = Q.eye(p); + for (const e of [Q.ma(s, 64, v.f), Q.ma(Q.ma(s, reach, v.f), -30, v.u), Q.ma(Q.ma(s, reach, v.f), 30, v.u)]) { + const tr = Q.traceShot(g, s, e, 0); + if (tr.target) { Q.hurtTarget(g, tr.target, (base + Q.random(g, mod)) * scale, 'melee'); return true; } + if (tr.fraction < 1) return false; + } + return false; + } + const advance = (p, a, b) => { // PF_advanceweaponframe, ascending ranges + if (p.wfr > b || p.wfr < a) { p.wfr = a; return 'started'; } + if (p.wfr === b) { p.wfr = a; return 'wrapped'; } + p.wfr++; return p.wfr === b ? 'last' : 'normal'; + }; + function launch(g, p, kind, speed, life) { + const v = Q.viewVectors([p.pitch, p.yaw]), e = Q.eye(p); + g.missiles.push({ k: kind, player: true, o: Q.ma(e, 10, v.f), v: Q.scale(v.f, speed), life, cnt: 0, id: g.fxSeq++ }); + g.events.push({ type: 'player_shot', weapon: kind, tick: g.t }); + } + const ANIM = { + ready(g, p) { p.wfr = 0; }, + gauntlet_a(g, p) { const st = advance(p, 1, 14); if (p.wfr === 4) melee(g, p, 16, 12, 64, STRENGTH_MOD); if (st === 'last') p.wth = 'ready'; }, + vorpal_a(g, p) { + const st = advance(p, 1, 24); + if (p.wfr === 9) { + const mana = p.blue >= 2; + if (melee(g, p, mana ? 30 : 20, mana ? 20 : 10, 88, STRENGTH_MOD) && mana) p.blue -= 2; // "Only monsters make it use mana" + } + if (st === 'last') p.wth = 'ready'; + }, + axe_a(g, p) { + const st = advance(p, 1, 25); + if ((p.wfr >= 2 && p.wfr <= 4) || (p.wfr >= 6 && p.wfr <= 7)) p.wfr++; // axe_a skips these frames + if (p.wfr === 15 && p.green >= 2) { melee(g, p, 12, 12, 64, 1); launch(g, p, 'axe', 900, 40); p.green -= 2; } + if (st === 'last') p.wth = 'ready'; + }, + purifier_a(g, p, firing, now) { // purifier_rapidfire*: 3 frames, a shot when attack_finished has run out with the button down + const st = advance(p, 1, 3); + if (p.attack_finished <= now && firing && p.green >= 1 && p.blue >= 1) { launch(g, p, 'pur', 1000, 50); p.green -= 1; p.blue -= 1; } + if (st === 'wrapped') p.wth = 'ready'; + }, + select(g, p, firing, now) { if (advance(p, 1, 6) === 'last') { p.wth = 'ready'; p.attack_finished = now - 1; } }, + }; + Q.weaponThink = (g, keys, pressed) => { + const p = g.p, now = Q.now(g), firing = keys.has('J') || keys.has('LMB'); + // ImpulseCommands: next / previous weapon, six frames of the select animation. + const step = pressed.has('K') || pressed.has('RMB') ? 1 : pressed.has('R') ? -1 : 0; + if (step && now >= p.attack_finished) { + p.weapon = WEAPONS[(WEAPONS.indexOf(p.weapon) + step + WEAPONS.length) % WEAPONS.length]; + p.wth = 'select'; p.wfr = 0; p.attack_finished = now + 0.3; + } + ANIM[p.wth](g, p, firing, now); + if (now < p.attack_finished || !firing || p.wth === 'select') return; + // W_Attack -> pal_*_fire: one more animation advance, then attack_finished. + if (p.weapon === 'gauntlet') { p.wth = 'gauntlet_a'; ANIM.gauntlet_a(g, p); p.attack_finished = now + 0.5; } + else if (p.weapon === 'vorpal') { p.wth = 'vorpal_a'; ANIM.vorpal_a(g, p); p.attack_finished = now + 0.3; } + else if (p.weapon === 'axe') { p.wth = 'axe_a'; ANIM.axe_a(g, p); p.attack_finished = now + 0.35; } + else if (p.green >= 2 && p.blue >= 2) { p.wth = 'purifier_a'; ANIM.purifier_a(g, p, firing, now); p.attack_finished = now + 0.14; } + }; + + // ---------------- items: instant health 10 and mana. Mana comes back after 20 s, the original's deathmatch 1 rule (items.hc:249), so long fights stay supplied with ammunition; + // health is taken once per fight and never comes back (hexen2-arena@3): a respawning heal let a player stand and trade blows with the boss. ---------------- + const GONE = 1e9; // a tick no fight reaches (maxSeconds 300 = 18000 ticks); finite so it survives the JSON copies of look-ahead and replays + Q.itemsThink = g => { + const p = g.p, box = Q.playerBox(p); + if (p.hp <= 0) return; + for (const it of g.items) { + if (it.respawn > g.t) continue; + if (Math.abs(p.o[0] - it.o[0]) > 24 || Math.abs(p.o[1] - it.o[1]) > 24 || p.o[2] > it.o[2] + 28 || p.o[2] + box.maxs[2] < it.o[2] - 8) continue; + let taken = false; + if (it.k === 'health') taken = Q.heal(p, it.n); + else if (p.green < 120 || p.blue < 120) { p.green = Math.min(120, p.green + it.n); p.blue = Math.min(120, p.blue + it.n); taken = true; } + if (taken) { it.respawn = it.k === 'health' ? GONE : g.t + 1200; g.events.push({ type: 'pickup', item: it.k, tick: g.t }); } + } + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/index.html b/environments/games/web/games/hexen2_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..3cecb8a0f9dca707e19fa2e7a9f6b5d826349056 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/index.html @@ -0,0 +1,7 @@ + +Hexen II · the Four Horsemen and Eidolon (hexen2-arena@3)
    +

    Hexen II · the Four Horsemen and Eidolon

    1997 original rules (independently reimplemented from the uHexen2 GPL source) · native 60 Hz · first-person WebGL · armored swordsman

    Back to Game Lobby
    +
    Select a boss to start

    Replays save inputs and seeds for deterministic playback and final-state verification. Scripted Demo uses internal state for testing and does not run RL training.

    +
    +
    All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
    + diff --git a/environments/games/web/games/hexen2_remake/input-hold.js b/environments/games/web/games/hexen2_remake/input-hold.js new file mode 100644 index 0000000000000000000000000000000000000000..3bb51743f424565cb6bea4f10f63f7f02c0680bb --- /dev/null +++ b/environments/games/web/games/hexen2_remake/input-hold.js @@ -0,0 +1,31 @@ +/* Hexen II keeps the source 50 ms think clock on a 60 Hz tick: a key tapped between two ticks is never sampled. The shared shell + (_native/shell.js) latches a tap only until the next macrotask, which can come before the next tick. + This page therefore holds every key / pointer release until at least one think frame (60 ms) has passed since + the press, by delaying the release event. Page input only: the rules, the policy interface and recordings are + unaffected (a recording stores the keys each tick actually saw). */ +(function () { + 'use strict'; + const HOLD = 60, down = new Map(), pdown = new Map(); + const tracked = e => /^(Key[WASDJKLQER]|Space|ShiftLeft|ShiftRight|Arrow(Up|Down|Left|Right))$/.test(e.code); + const late = new WeakSet(); + window.addEventListener('keydown', e => { if (tracked(e) && !down.has(e.code)) down.set(e.code, performance.now()); }, true); + window.addEventListener('keyup', e => { + if (late.has(e) || !tracked(e)) return; + const t0 = down.get(e.code); down.delete(e.code); + const wait = t0 === undefined ? 0 : HOLD - (performance.now() - t0); + if (wait <= 0) return; + e.stopImmediatePropagation(); e.preventDefault(); + const target = e.target || window; + setTimeout(() => { const ev = new KeyboardEvent('keyup', { code: e.code, key: e.key, bubbles: true, cancelable: true }); late.add(ev); target.dispatchEvent(ev); }, wait); + }, true); + window.addEventListener('pointerdown', e => { pdown.set(e.pointerId, performance.now()); }, true); + window.addEventListener('pointerup', e => { + if (late.has(e)) return; + const t0 = pdown.get(e.pointerId); pdown.delete(e.pointerId); + const wait = t0 === undefined ? 0 : HOLD - (performance.now() - t0); + if (wait <= 0) return; + e.stopImmediatePropagation(); + const target = e.target || window; + setTimeout(() => { const ev = new PointerEvent('pointerup', { bubbles: true, button: e.button, pointerId: e.pointerId }); late.add(ev); target.dispatchEvent(ev); }, wait); + }, true); +})(); diff --git a/environments/games/web/games/hexen2_remake/manifest.json b/environments/games/web/games/hexen2_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ec7c1db5238c7a890b8781f86cf34692b9219545 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/manifest.json @@ -0,0 +1,63 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "hexen2_remake", + "module": "Hexen2Game", + "title": "Hexen II: Four Horsemen and Serpent", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-hexen2", + "rules": "hexen2-arena@4", + "cases": [ + "hexen2/blinking_tether_rider", + "hexen2/airborne_bone_rider", + "hexen2/boar_archer_rider", + "hexen2/axe_hurling_rider", + "hexen2/orb_warded_serpent", + "hexen2/star_volley_sorcerer" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "hexen2_remake/h2core.js", + "hexen2_remake/h2player.js", + "hexen2_remake/h2boss.js", + "hexen2_remake/boss_famine.js", + "hexen2_remake/boss_death.js", + "hexen2_remake/boss_pestilence.js", + "hexen2_remake/boss_war.js", + "hexen2_remake/boss_eidolon.js", + "hexen2_remake/boss_praevus.js", + "hexen2_remake/game.js", + "hexen2_remake/scripted.js", + "hexen2_remake/telegraph.js", + "hexen2_remake/renderer3d.js", + "hexen2_remake/fx3d.js", + "hexen2_remake/fx_draw.js", + "hexen2_remake/art_famine.js", + "hexen2_remake/art_death.js", + "hexen2_remake/art_pestilence.js", + "hexen2_remake/art_war.js", + "hexen2_remake/art_eidolon.js", + "hexen2_remake/art_praevus.js", + "hexen2_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "hexen2_remake/h2core.js", + "hexen2_remake/h2player.js", + "hexen2_remake/h2boss.js", + "hexen2_remake/boss_famine.js", + "hexen2_remake/boss_death.js", + "hexen2_remake/boss_pestilence.js", + "hexen2_remake/boss_war.js", + "hexen2_remake/boss_eidolon.js", + "hexen2_remake/boss_praevus.js", + "hexen2_remake/game.js", + "hexen2_remake/scripted.js" + ], + "play_page": "web/games/hexen2_remake/index.html", + "scripted_controller": "Hexen2Game.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,0]}; privileged state, look-ahead on copies whose RNG is reseeded per tick by a multiply mix", + "source": "https://github.com/sezero/uhexen2/tree/3d7ff45752edb8d1c8e0e02982f42bb54b1160a4 (GPL-2, read only)" +} diff --git a/environments/games/web/games/hexen2_remake/renderer3d.js b/environments/games/web/games/hexen2_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..a3cbacab1ef264b843e017ce23182389f416b70a --- /dev/null +++ b/environments/games/web/games/hexen2_remake/renderer3d.js @@ -0,0 +1,275 @@ +/* Hexen II boss arenas - original procedural 3D art on Three.js r160 (MIT, shared read-only vendor copy in web/games/_boss3d/vendor). + First-person view from the Paladin's eye, 90 degree horizontal field of view (Hexen II default). Rendering is a pure function of the game state: it never writes the + simulation and never draws gameplay RNG; animation time comes from the state's tick counter, effect noise from integer hashes. No Hexen II models, skins or textures are used. + Effects (missiles, impacts, hazards, wind-ups) are drawn by fx_draw.js into the instanced batches of fx3d.js; this file owns the scene, the lights and the view weapon. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Hexen2Game, Q = M && M.Q; + if (!T) throw Error('Three.js is missing (web/games/_boss3d/vendor/three.min.js)'); + const R = M.R3 = { MODELS: {} }; + const S = 1 / 32, DEG = Math.PI / 180, byCanvas = new WeakMap(); + R.S = S; + const qv = (x, y, z, out) => (out || new T.Vector3()).set(x * S, z * S, -y * S); // Quake (x fwd, y left, z up) -> three + R.qv = qv; + function hash(x, y, s) { let n = Math.imul(x + 374761393 * s, 668265263) ^ Math.imul(y + s, 2246822519); n = Math.imul(n ^ (n >>> 13), 1274126177); return ((n ^ (n >>> 16)) >>> 0) / 4294967296; } + function canvasTex(w, h, paint, equirect) { + const c = document.createElement('canvas'); c.width = w; c.height = h; paint(c.getContext('2d'), w, h); + const t = new T.CanvasTexture(c); t.colorSpace = T.SRGBColorSpace; + if (equirect) t.mapping = T.EquirectangularReflectionMapping; else { t.wrapS = t.wrapT = T.RepeatWrapping; t.anisotropy = 4; } + return t; + } + R.canvasTex = canvasTex; + function noise(q, w, h, base, amp, seed, grain) { + const im = q.createImageData(w, h), G = grain || 1; + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { + const n = (hash(Math.floor(x / G), Math.floor(y / G), seed) - 0.5) * amp + (hash(x >> 3, y >> 3, seed + 7) - 0.5) * amp * 0.7 + (hash(x >> 5, y >> 5, seed + 3) - 0.5) * amp * 0.5, i = (y * w + x) * 4; + im.data[i] = base[0] + n; im.data[i + 1] = base[1] + n * 0.95; im.data[i + 2] = base[2] + n * 0.85; im.data[i + 3] = 255; + } + q.putImageData(im, 0, 0); + } + // Mortar lines with a lit top edge and a shaded bottom edge, so blocks read as relief under the hemisphere light. + const blocks = (q, w, h, bw, bh, col) => { + for (let y = 0, r = 0; y < h; y += bh, r++) { + q.fillStyle = col; q.fillRect(0, y, w, 3); q.fillStyle = 'rgba(255,240,220,.10)'; q.fillRect(0, y + 3, w, 2); q.fillStyle = 'rgba(0,0,0,.18)'; q.fillRect(0, y + bh - 5, w, 2); + for (let x = r % 2 ? bw / 2 : 0; x < w; x += bw) { q.fillStyle = col; q.fillRect(x, y, 3, bh); q.fillStyle = 'rgba(255,240,220,.08)'; q.fillRect(x + 3, y, 2, bh); } + } + }; + // Every surface of every arena: a small painter, keyed by the brush's material name. + const PAINT = { + dust(q, w, h) { noise(q, w, h, [116, 96, 66], 34, 3, 2); q.strokeStyle = 'rgba(52,38,22,.5)'; q.lineWidth = 2; for (let k = 0; k < 24; k++) { const x = hash(k, 1, 5) * w, y = hash(k, 2, 5) * h; q.beginPath(); q.moveTo(x, y); q.lineTo(x + (hash(k, 3, 5) - 0.5) * 70, y + (hash(k, 4, 5) - 0.5) * 70); q.stroke(); } q.fillStyle = 'rgba(200,170,110,.25)'; for (let k = 0; k < 60; k++) q.fillRect(hash(k, 6, 5) * w, hash(k, 7, 5) * h, 6, 2); }, + stone(q, w, h) { noise(q, w, h, [88, 82, 74], 30, 11); blocks(q, w, h, 128, 64, '#3b3731'); }, + granary(q, w, h) { noise(q, w, h, [102, 74, 44], 26, 21); q.fillStyle = 'rgba(40,26,14,.7)'; for (let x = 0; x < w; x += 32) q.fillRect(x, 0, 4, h); q.fillStyle = '#5b4a33'; q.fillRect(0, 0, w, 14); q.fillRect(0, h - 14, w, 14); q.fillStyle = '#2c2116'; for (let x = 8; x < w; x += 64) for (let y = 4; y < h; y += 236) q.fillRect(x, y, 5, 5); }, + well(q, w, h) { noise(q, w, h, [78, 80, 84], 28, 31); blocks(q, w, h, 64, 32, '#34363a'); }, + bone(q, w, h) { noise(q, w, h, [150, 142, 120], 22, 41); blocks(q, w, h, 96, 48, '#6e6650'); q.fillStyle = 'rgba(60,50,40,.35)'; for (let k = 0; k < 14; k++) { q.beginPath(); q.arc(hash(k, 1, 4) * w, hash(k, 2, 4) * h, 4 + hash(k, 3, 4) * 6, 0, 7); q.fill(); } }, + ash(q, w, h) { noise(q, w, h, [46, 44, 48], 22, 51, 2); q.fillStyle = 'rgba(180,60,20,.28)'; for (let k = 0; k < 40; k++) q.fillRect(hash(k, 1, 9) * w, hash(k, 2, 9) * h, 3 + hash(k, 3, 9) * 16, 2); }, + obsidian(q, w, h) { noise(q, w, h, [40, 34, 52], 26, 61); blocks(q, w, h, 128, 128, '#191522'); q.strokeStyle = 'rgba(150,120,220,.18)'; q.lineWidth = 1; for (let k = 0; k < 10; k++) { q.beginPath(); q.moveTo(hash(k, 1, 6) * w, hash(k, 2, 6) * h); q.lineTo(hash(k, 3, 6) * w, hash(k, 4, 6) * h); q.stroke(); } }, + moss(q, w, h) { noise(q, w, h, [66, 84, 50], 34, 71, 2); q.fillStyle = 'rgba(30,44,20,.5)'; for (let k = 0; k < 50; k++) { q.beginPath(); q.arc(hash(k, 1, 7) * w, hash(k, 2, 7) * h, 2 + hash(k, 3, 7) * 9, 0, 7); q.fill(); } }, + rot(q, w, h) { noise(q, w, h, [72, 70, 44], 32, 81); blocks(q, w, h, 96, 64, '#30301b'); q.fillStyle = 'rgba(120,150,40,.3)'; for (let k = 0; k < 18; k++) q.fillRect(hash(k, 4, 2) * w, 0, 3, hash(k, 5, 2) * h); }, + iron(q, w, h) { noise(q, w, h, [70, 62, 60], 20, 91); q.fillStyle = '#2e2826'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 6); q.fillStyle = '#a98a70'; for (let x = 16; x < w; x += 48) for (let y = 16; y < h; y += 64) q.fillRect(x, y, 4, 4); q.fillStyle = 'rgba(140,50,20,.22)'; for (let k = 0; k < 20; k++) q.fillRect(hash(k, 8, 3) * w, hash(k, 9, 3) * h, 2, 10 + hash(k, 7, 3) * 40); }, + blood(q, w, h) { noise(q, w, h, [86, 44, 36], 28, 101, 2); blocks(q, w, h, 128, 128, '#3a1a14'); }, + marble(q, w, h) { noise(q, w, h, [168, 160, 170], 16, 111); q.strokeStyle = 'rgba(70,60,90,.35)'; q.lineWidth = 2; for (let k = 0; k < 12; k++) { q.beginPath(); let x = hash(k, 1, 3) * w, y = 0; q.moveTo(x, y); while (y < h) { x += (hash(k, y, 3) - 0.5) * 40; y += 24; q.lineTo(x, y); } q.stroke(); } blocks(q, w, h, 256, 256, '#6f6880'); }, + void(q, w, h) { noise(q, w, h, [30, 26, 56], 22, 121); q.fillStyle = 'rgba(150,120,255,.55)'; for (let k = 0; k < 70; k++) q.fillRect(hash(k, 1, 4) * w, hash(k, 2, 4) * h, 2, 2); }, + crystal(q, w, h) { noise(q, w, h, [96, 70, 150], 30, 131); q.strokeStyle = 'rgba(210,190,255,.6)'; q.lineWidth = 2; for (let k = 0; k < 9; k++) { q.beginPath(); q.moveTo(hash(k, 1, 8) * w, 0); q.lineTo(hash(k, 2, 8) * w, h); q.stroke(); } }, + }; + // Per arena: fog, sky (top, horizon, low), stars, light rig, torch colour and ambient motes. + // Boss rim colour per arena: a hue the arena, its effects and the player's azure bolts do not use, so the silhouette reads against same-coloured walls. + const RIM = { famine: 0xc8ff70, death: 0xff60e0, pestilence: 0xff60e0, war: 0xc8ff70, eidolon: 0xc8ff70, praevus: 0xff60e0 }; + R.RIM = RIM; + // Fresnel rim on a standard material: emissive + colour * (1 - |n.v|)^4 * power, added after the emissive map. + R.addRim = (m, color, power) => { + m.onBeforeCompile = sh => { sh.uniforms.rimColor = { value: color }; sh.uniforms.rimPower = power; + sh.fragmentShader = 'uniform vec3 rimColor; uniform float rimPower;\n' + sh.fragmentShader.replace('#include ', '#include \n totalEmissiveRadiance += rimColor * rimPower * pow(1.0 - clamp(abs(dot(normalize(normal), normalize(vViewPosition))), 0.0, 1.0), 4.0);'); }; + m.customProgramCacheKey = () => 'bb-rim'; + }; + const STYLE = { + famine: { fog: 0x4d4030, near: 900, far: 3600, sky: ['#2a2230', '#7c6242', '#b88e56'], stars: 0, hemi: [0xffe2b0, 0x3a3020, 1.35], sun: [0xffcf8a, 1.7, [1, 0.7, 0.5]], torch: 0xffa040, mote: 0xd8b880 }, + death: { fog: 0x14141c, near: 800, far: 3400, sky: ['#05060c', '#14162a', '#2d2038'], stars: 1, hemi: [0x98a0d8, 0x201c2c, 1.15], sun: [0xb8c4ff, 0.9, [-0.6, 0.8, 0.4]], torch: 0xc8b8ff, mote: 0x9aa8c8 }, + pestilence: { fog: 0x2c3620, near: 700, far: 3000, sky: ['#141c10', '#39482a', '#6e7a3c'], stars: 0, hemi: [0xd8f0a8, 0x262c18, 1.3], sun: [0xc8e088, 1.0, [0.4, 0.8, -0.6]], torch: 0xb8ff50, mote: 0xb8d070 }, + war: { fog: 0x3a1c14, near: 900, far: 4000, sky: ['#1c0c0c', '#5a2014', '#c0562a'], stars: 0, hemi: [0xffc8a0, 0x301810, 1.35], sun: [0xff9a60, 1.5, [-0.5, 0.6, -0.6]], torch: 0xff6a20, mote: 0xff8a40 }, + eidolon: { fog: 0x16102a, near: 1000, far: 4400, sky: ['#06041a', '#1c1040', '#54245e'], stars: 1, hemi: [0xb0a0f0, 0x18142c, 1.2], sun: [0xc8b0ff, 1.1, [0.3, 0.8, 0.5]], torch: 0xb080ff, mote: 0xc0a0ff }, + praevus: { fog: 0x10162c, near: 1000, far: 4200, sky: ['#04081a', '#101c44', '#2c4a78'], stars: 1, hemi: [0xa8c0f8, 0x141a2c, 1.35], sun: [0xa8d0ff, 1.2, [-0.4, 0.8, 0.4]], torch: 0x80c0ff, mote: 0xa0c0ff }, + }; + R.STYLE = STYLE; + // Sky: an equirectangular gradient with stars or cloud bands and the sun or moon, so it turns with the view. + function skyTex(st) { + return canvasTex(1024, 512, (q, w, h) => { + const g = q.createLinearGradient(0, 0, 0, h / 2); g.addColorStop(0, st.sky[0]); g.addColorStop(0.75, st.sky[1]); g.addColorStop(1, st.sky[2]); + q.fillStyle = g; q.fillRect(0, 0, w, h / 2); q.fillStyle = st.sky[2]; q.fillRect(0, h / 2, w, h / 2); + if (st.stars) for (let k = 0; k < 700; k++) { const y = Math.pow(hash(k, 2, 77), 1.6) * h * 0.46, a = 0.25 + hash(k, 3, 77) * 0.7; q.fillStyle = `rgba(230,230,255,${a})`; q.fillRect(hash(k, 1, 77) * w, y, hash(k, 4, 77) < 0.1 ? 2 : 1, hash(k, 4, 77) < 0.1 ? 2 : 1); } + else for (let k = 0; k < 90; k++) { const y = h * (0.14 + hash(k, 2, 55) * 0.3), x = hash(k, 1, 55) * w, l = 60 + hash(k, 3, 55) * 220; q.fillStyle = `rgba(255,235,210,${0.025 + hash(k, 4, 55) * 0.05})`; q.fillRect(x, y, l, 3 + hash(k, 5, 55) * 6); } + const d = new T.Vector3(...st.sun[2]).normalize(), u = (Math.atan2(d.z, d.x) / (2 * Math.PI) + 0.5) * w, v = Math.acos(d.y) / Math.PI * h; + const r = q.createRadialGradient(u, v, 0, u, v, 40); r.addColorStop(0, 'rgba(255,250,235,.95)'); r.addColorStop(0.1, 'rgba(255,240,210,.8)'); r.addColorStop(0.3, 'rgba(255,220,170,.16)'); r.addColorStop(1, 'rgba(255,220,170,0)'); + q.fillStyle = r; q.fillRect(u - 40, v - 40, 80, 80); + }, true); + } + class Scene { + constructor(key, canvas) { + this.key = key; this.canvas = canvas; this.resources = []; this.ready = false; this.error = null; this.closed = false; this.times = []; + this.view = document.createElement('canvas'); this.view.width = 854; this.view.height = 480; + this.renderer = new T.WebGLRenderer({ canvas: this.view, antialias: true, preserveDrawingBuffer: true, powerPreference: 'low-power' }); + this.renderer.setPixelRatio(1); this.renderer.setSize(854, 480, false); this.renderer.outputColorSpace = T.SRGBColorSpace; + this.renderer.toneMapping = T.ACESFilmicToneMapping; this.renderer.toneMappingExposure = 1.12; this.renderer.autoClear = false; this.renderer.info.autoReset = false; + this.view.addEventListener('webglcontextlost', e => { e.preventDefault(); this.ready = false; this.error = 'WebGL context lost'; }); + const st = this.style = STYLE[key], a = this.arena = M.arenas[key], W = this.world = new T.Scene(); + W.fog = new T.Fog(st.fog, st.near * S, st.far * S); + this.fogUniforms = { fogNear: { value: st.near * S }, fogFar: { value: st.far * S } }; + W.background = this.keep(skyTex(st)); + W.add(new T.HemisphereLight(st.hemi[0], st.hemi[1], st.hemi[2])); + const sun = new T.DirectionalLight(st.sun[0], st.sun[1]); sun.position.set(...st.sun[2]); W.add(sun); + // Four point lights for flashes, explosions and glowing missiles; always present so the shaders never recompile, dark when unused. + this.lights = Array.from({ length: 4 }, () => { const l = new T.PointLight(0xffffff, 0, 14, 1.6); W.add(l); return l; }); + this.lightReq = []; + this.camera = new T.PerspectiveCamera(2 * Math.atan(Math.tan(45 * DEG) * 480 / 854) / DEG, 854 / 480, 0.25, 320); + this.mats = {}; this.ball = this.keep(new T.SphereGeometry(1, 12, 9)); + for (const b of a.brushes) if (b.mat !== 'sky') W.add(this.brushMesh(b)); + this.buildItems(a); this.buildTorches(a); + this.fx = new R.FX(this, W); + this.boss = R.MODELS[key].build(this, T); + W.add(this.boss.root); + this.bossMats = new Set(); this.boss.root.traverse(o => { if (o.material && o.material.emissive) this.bossMats.add(o.material); }); + const rim = new T.Color(RIM[key] || 0xffffff); this.rimPower = { value: 0.7 }; + for (const m of this.bossMats) { m.userData.emissive0 = m.emissive.getHex(); R.addRim(m, rim, this.rimPower); } + // view weapon in its own scene so it never clips into walls + this.vscene = new T.Scene(); this.vscene.add(new T.HemisphereLight(0xffffff, 0x444444, 2)); const vl = new T.DirectionalLight(0xffffff, 1.4); vl.position.set(0.4, 1, 0.6); this.vscene.add(vl); + this.vlight = new T.PointLight(0x60c8ff, 0, 3, 1.5); this.vscene.add(this.vlight); + this.vcam = new T.PerspectiveCamera(50, 854 / 480, 0.01, 10); + this.vw = this.buildViewWeapons(); this.vscene.add(this.vw.root); + } + keep(r) { this.resources.push(r); return r; } + mat(name) { + if (this.mats[name]) return this.mats[name]; + return (this.mats[name] = this.keep(new T.MeshStandardMaterial({ map: this.keep(canvasTex(256, 256, PAINT[name] || PAINT.stone)), roughness: 0.9, metalness: 0.02 }))); + } + std(color, o) { return this.keep(new T.MeshStandardMaterial(Object.assign({ color, roughness: 0.75, metalness: 0.08, flatShading: true }, o || {}))); } + glow(color, opacity) { return this.keep(new T.MeshBasicMaterial({ color, transparent: true, opacity: opacity === undefined ? 0.9 : opacity, depthWrite: false, blending: T.AdditiveBlending, fog: false })); } + // A box with world-scale UVs, one tile per 256 units on every face. + brushMesh(b) { + const sx = b.maxs[0] - b.mins[0], sy = b.maxs[1] - b.mins[1], sz = b.maxs[2] - b.mins[2]; + const geo = this.keep(new T.BoxGeometry(sx * S, sz * S, sy * S)), uv = geo.attributes.uv, nor = geo.attributes.normal, pos = geo.attributes.position; + for (let i = 0; i < uv.count; i++) { + const nx = Math.abs(nor.getX(i)), ny = Math.abs(nor.getY(i)); + const x = pos.getX(i) / S + (b.mins[0] + b.maxs[0]) / 2, y = pos.getY(i) / S + (b.mins[2] + b.maxs[2]) / 2, z = pos.getZ(i) / S - (b.mins[1] + b.maxs[1]) / 2; + uv.setXY(i, (nx > 0.5 ? z : x) / 256, (ny > 0.5 ? z : y) / 256); + } + const m = new T.Mesh(geo, this.mat(b.mat)); + qv((b.mins[0] + b.maxs[0]) / 2, (b.mins[1] + b.maxs[1]) / 2, (b.mins[2] + b.maxs[2]) / 2, m.position); + return m; + } + // Pickups: a faceted crystal over a small stone base; the glow and the floor rune come from the effect batches. + buildItems(a) { + const geo = this.keep(new T.OctahedronGeometry(7 * S)), base = this.keep(new T.CylinderGeometry(12 * S, 15 * S, 6 * S, 8)), stone = this.std(0x4a4440); + const red = this.std(0xff3a30, { emissive: 0xa01010, emissiveIntensity: 1.2, roughness: 0.25, metalness: 0.1 }), blue = this.std(0x40a0ff, { emissive: 0x1050b0, emissiveIntensity: 1.2, roughness: 0.25, metalness: 0.1 }); + this.items = a.items.map(([k, x, y]) => { const m = new T.Mesh(geo, k === 'health' ? red : blue), b = new T.Mesh(base, stone); qv(x, y, 24, m.position); qv(x, y, 3, b.position); m.scale.set(1, 1.6, 1); this.world.add(m, b); return m; }); + } + // Wall sconces with a flame, every ~520 units round the arena at head height; scenery only, no collision (they sit in the wall). + buildTorches(a) { + const [w, h] = a.size, iron = this.std(0x2a2624, { metalness: 0.6, roughness: 0.5 }), geo = this.keep(new T.BoxGeometry(10 * S, 14 * S, 10 * S)), arm = this.keep(new T.BoxGeometry(4 * S, 4 * S, 16 * S)); + this.torches = []; + const add = (x, y, nx, ny) => { const m = new T.Mesh(geo, iron), r = new T.Mesh(arm, iron); qv(x + nx * 10, y + ny * 10, 150, m.position); qv(x + nx * 4, y + ny * 4, 146, r.position); r.rotation.y = Math.atan2(nx, -ny); this.world.add(m, r); this.torches.push([x + nx * 10, y + ny * 10, 166]); }; + for (let x = 260; x < w - 100; x += 520) { add(x, 0, 0, 1); add(x, h, 0, -1); } + for (let y = 260; y < h - 100; y += 520) { add(0, y, 1, 0); add(w, y, -1, 0); } + } + buildViewWeapons() { + const root = new T.Group(), metal = this.std(0xc0c4d0, { metalness: 0.7, roughness: 0.3 }), gold = this.std(0xd0a040, { metalness: 0.7, roughness: 0.35 }), leather = this.std(0x4a3020), steel = this.std(0x808890, { metalness: 0.75, roughness: 0.3 }); + const rune = this.std(0x60d0ff, { emissive: 0x2a90ff, emissiveIntensity: 1.6, roughness: 0.2 }); + const box = (p, x, y, z, w, h, d, mat, rx) => { const m = new T.Mesh(this.keep(new T.BoxGeometry(w, h, d)), mat); m.position.set(x, y, z); if (rx) m.rotation.x = rx; p.add(m); return m; }; + const g = { gauntlet: new T.Group(), vorpal: new T.Group(), axe: new T.Group(), purifier: new T.Group() }; + box(g.gauntlet, 0.3, -0.34, -0.55, 0.2, 0.2, 0.34, steel); box(g.gauntlet, 0.3, -0.3, -0.76, 0.17, 0.12, 0.14, gold); box(g.gauntlet, 0.3, -0.25, -0.72, 0.18, 0.03, 0.03, rune); + box(g.vorpal, 0.32, -0.36, -0.42, 0.06, 0.06, 0.28, leather); box(g.vorpal, 0.32, -0.33, -0.57, 0.18, 0.04, 0.04, gold); box(g.vorpal, 0.32, -0.2, -0.95, 0.03, 0.05, 0.8, metal, 0.32); box(g.vorpal, 0.32, -0.19, -0.95, 0.012, 0.02, 0.7, rune, 0.32); + box(g.axe, 0.32, -0.38, -0.5, 0.05, 0.05, 0.5, leather); box(g.axe, 0.32, -0.3, -0.76, 0.03, 0.26, 0.16, metal); box(g.axe, 0.32, -0.16, -0.76, 0.02, 0.06, 0.2, gold); box(g.axe, 0.335, -0.3, -0.84, 0.01, 0.24, 0.02, rune); + // The purifier: two short barrels low on either side, one per hand; the bolts leave them in turn (purifier.hc: +-v_right*10, 6 below the eye). Each barrel runs parallel to the view axis on the + // screen line its bolts fly along (slope 6/10 from the crosshair), so a bolt drawn from 28 units ahead (telegraph.js) appears at its muzzle. + const P = g.purifier; this.muzzles = []; + for (const s of [-1, 1]) { + const X = s * 0.233, Y = -0.14; + box(P, X, Y, -0.65, 0.032, 0.032, 0.3, steel); box(P, X, Y + 0.018, -0.62, 0.012, 0.008, 0.22, rune); box(P, X, Y, -0.79, 0.046, 0.046, 0.03, gold); + box(P, X, Y - 0.006, -0.42, 0.05, 0.05, 0.18, leather); box(P, X, Y - 0.004, -0.51, 0.06, 0.012, 0.02, gold); + const fl = new T.Sprite(this.keep(new T.SpriteMaterial({ map: this.flashTex(), color: 0xffffff, transparent: true, blending: T.AdditiveBlending, depthTest: false, depthWrite: false }))); + fl.position.set(X * 1.04, Y * 1.04, -0.83); fl.visible = false; P.add(fl); this.muzzles.push(fl); + } + // A blade trail for the sword and the gauntlet swing, drawn in the view scene. + this.slash = new T.Mesh(this.keep(new T.RingGeometry(0.5, 0.53, 32, 1, 0, Math.PI * 0.5)), this.keep(new T.MeshBasicMaterial({ color: 0x9fe0ff, transparent: true, opacity: 0, blending: T.AdditiveBlending, depthTest: false, depthWrite: false, side: T.DoubleSide }))); + this.slash.position.set(0.05, -0.1, -0.7); root.add(this.slash); + for (const k of Object.keys(g)) root.add(g[k]); + return { root, g }; + } + flashTex() { + return this._flash || (this._flash = this.keep(canvasTex(64, 64, (q, w, h) => { + const r = q.createRadialGradient(32, 32, 0, 32, 32, 32); r.addColorStop(0, 'rgba(255,255,255,1)'); r.addColorStop(0.2, 'rgba(190,240,255,.9)'); r.addColorStop(0.5, 'rgba(70,170,255,.35)'); r.addColorStop(1, 'rgba(40,120,255,0)'); + q.fillStyle = r; q.fillRect(0, 0, w, h); q.strokeStyle = 'rgba(220,250,255,.7)'; q.lineWidth = 2; for (let k = 0; k < 4; k++) { const a = k * Math.PI / 4; q.beginPath(); q.moveTo(32 - Math.cos(a) * 30, 32 - Math.sin(a) * 30); q.lineTo(32 + Math.cos(a) * 30, 32 + Math.sin(a) * 30); q.stroke(); } + }))); + } + // Light requests from the effects ({o, hex, power, range}); the brightest four light the world this frame. + light(o, hex, power, range) { this.lightReq.push({ o, hex, power, range: range || 320 }); } + applyLights() { + const req = this.lightReq.sort((a, b) => b.power - a.power); + this.lights.forEach((l, i) => { const r = req[i]; if (!r) { l.intensity = 0; return; } qv(r.o[0], r.o[1], r.o[2], l.position); l.color.setHex(r.hex); l.intensity = r.power; l.distance = r.range * S; }); + this.lightReq = []; + } + render(g, ctx) { + const t0 = performance.now(); + try { + const p = g.p, time = g.t / M.hz, eye = Q.eye(p), v = Q.viewVectors([p.pitch + p.kick * 1.5, p.yaw]); + qv(eye[0], eye[1], eye[2], this.camera.position); + this.camera.lookAt(qv(eye[0] + v.f[0], eye[1] + v.f[1], eye[2] + v.f[2])); + g.items.forEach((it, i) => { const m = this.items[i]; m.visible = it.respawn <= g.t; m.rotation.y = time * 2; m.position.y = (26 + Math.sin(time * 2 + i) * 3) * S; }); + this.fx.begin(); R.MODELS[this.key].update(this.boss, g.boss, g, time, this); + const bd = Math.hypot(g.boss.o[0] - eye[0], g.boss.o[1] - eye[1]); this.rimPower.value = 0.7 * Math.max(0.25, Math.min(1, (bd - 150) / 450)); + // Hit flash: the boss model glows white-hot for a few ticks after a player hit (the 'hit' effect of radius 5 is the player's). + const hit = g.fx.reduce((a, f) => (f.kind === 'hit' && f.r === 5 && g.t - f.t0 < 3 ? Math.max(a, 1 - (g.t - f.t0) / 3) : a), 0); + for (const m of this.bossMats) { if (hit > 0) { m.emissive.setHex(0xffc8a0); m.emissiveIntensity = 0.16 * hit; } else { m.emissive.setHex(m.userData.emissive0); m.emissiveIntensity = 1; } } + R.drawEffects(this, g, time); this.fx.end(); this.applyLights(); + this.renderer.info.reset(); this.renderer.clear(); this.renderer.render(this.world, this.camera); + this.renderWeapon(g, time); + ctx.drawImage(this.view, 0, 0, 854, 480); + this.times.push(performance.now() - t0); if (this.times.length > 120) this.times.shift(); + this.ready = true; this.error = null; + } catch (e) { this.ready = false; this.error = String(e && e.stack || e); throw e; } + } + renderWeapon(g, time) { + const p = g.p, firing = p.wth !== 'ready' && p.wth !== 'select'; + for (const k of Object.keys(this.vw.g)) this.vw.g[k].visible = k === p.weapon; + const sw = firing ? Math.sin(Math.min(1, p.wfr / 14) * Math.PI) : 0, moving = Q.hlen(p.v) / 400; + // Muzzle flash: the newest purifier bolt in its first 4 ticks, on the barrel it left from. + let flash = 0, side = 1; + for (const m of g.missiles) if (m.player && m.k === 'pur') { const age = M.VIEW.boltAge(g, m); if (age <= 4 && 1 - age / 5 > flash) { flash = 1 - age / 5; side = M.VIEW.boltSide(m); } } + this.muzzles.forEach((fl, i) => { const on = p.weapon === 'purifier' && flash > 0 && (i ? 1 : -1) === side; fl.visible = on; if (on) { const s = 0.07 + 0.1 * flash; fl.scale.set(s, s, s); fl.material.rotation = (g.t * 1.7) % 6.28; } }); + this.vlight.intensity = p.weapon === 'purifier' ? flash * 3 : 0; this.vlight.position.set(side * 0.233, -0.1, -0.75); + const kickBack = p.weapon === 'purifier' ? flash * 0.035 : 0; + this.vw.root.position.set(Math.sin(time * 7) * 0.012 * moving, Math.abs(Math.cos(time * 7)) * 0.016 * moving - (p.wth === 'select' ? 0.25 : 0), p.weapon === 'purifier' ? sw * 0.02 + kickBack : -sw * 0.14); + this.vw.root.rotation.x = p.weapon === 'purifier' ? flash * 0.05 : -sw * 0.65; + // Blade trail through the hit frames of a sword or gauntlet swing (vorpal frame 9, gauntlet frame 4). + const sl = p.wth === 'vorpal_a' ? (p.wfr >= 6 && p.wfr <= 13 ? 1 - Math.abs(p.wfr - 9) / 4 : 0) : p.wth === 'gauntlet_a' ? (p.wfr >= 2 && p.wfr <= 6 ? 1 - Math.abs(p.wfr - 4) / 3 : 0) : 0; + this.slash.material.opacity = 0.6 * sl; this.slash.visible = sl > 0; this.slash.rotation.z = -0.4 - (p.wfr % 24) * 0.05; + this.renderer.clearDepth(); this.renderer.render(this.vscene, this.vcam); + } + metrics() { const r = this.renderer.info.render, t = this.times.slice().sort((a, b) => a - b); return { calls: r.calls, triangles: r.triangles, ms_p50: t.length ? t[t.length >> 1] : null, ms_max: t.length ? t[t.length - 1] : null, effects: this.fx.count() }; } + close() { if (this.closed) return; this.closed = true; this.ready = false; for (const r of this.resources) r.dispose && r.dispose(); this.renderer.dispose(); this.renderer.forceContextLoss(); } + } + R.render = (g, ctx) => { + let m = byCanvas.get(ctx.canvas); if (!m) { m = new Map(); byCanvas.set(ctx.canvas, m); } + let s = m.get(g.key); if (!s || s.closed) { s = new Scene(g.key, ctx.canvas); m.set(g.key, s); } + s.render(g, ctx); m.last = s; return s; + }; + R.status = ctx => { + const m = ctx && byCanvas.get(ctx.canvas); let ready = false, error = null; + if (m) for (const s of m.values()) { if (!s.closed && s.renderer.getContext().isContextLost()) { s.ready = false; s.error = 'WebGL context lost'; } ready = ready || (s.ready && !s.closed); error = error || s.error; } + return { renderer: 'webgl-hexen2', kind: 'perspective', ready, error }; + }; + R.metrics = ctx => { const m = ctx && byCanvas.get(ctx.canvas); return m && m.last && !m.last.closed ? m.last.metrics() : null; }; + R.close = ctx => { const m = ctx && byCanvas.get(ctx.canvas); if (!m) return; for (const s of m.values()) s.close(); byCanvas.delete(ctx.canvas); }; + // ---------------- shared rider parts: model axes are x forward, y up, z to the rider's right, in Quake units (root scale S) ---------------- + R.part = (sc, parent, geo, mat, x, y, z, rot) => { const m = new T.Mesh(sc.keep(geo), mat); m.position.set(x || 0, y || 0, z || 0); if (rot) m.rotation.set(rot[0] || 0, rot[1] || 0, rot[2] || 0); parent.add(m); return m; }; + R.bx = (w, h, d) => new T.BoxGeometry(w, h, d); + R.cy = (r0, r1, h, n) => new T.CylinderGeometry(r0, r1, h, n || 8); + // A horse: four jointed legs, neck, head, mane, tail. opt scales its build (gaunt, armored). + R.horse = (sc, mat, opt) => { + const o = Object.assign({ girth: 1, len: 1, legLen: 1, mane: null }, opt || {}), root = new T.Group(), G = o.girth, L = o.len, H = 62 * o.legLen, { part, bx, cy } = R; + const body = new T.Group(); body.position.y = H; root.add(body); + part(sc, body, bx(84 * L, 30 * G, 28 * G), mat, 0, 6, 0); + part(sc, body, bx(30 * L, 34 * G, 31 * G), mat, 32 * L, 7, 0); part(sc, body, bx(28 * L, 32 * G, 30 * G), mat, -32 * L, 7, 0); + part(sc, body, new T.SphereGeometry(17 * G, 8, 6), mat, -40 * L, 6, 0).scale.set(1, 1, 0.95); + const neck = new T.Group(); neck.position.set(44 * L, 16, 0); body.add(neck); + part(sc, neck, bx(18, 40, 14 * G), mat, 8, 16, 0, [0, 0, -0.5]); + if (o.mane) for (let i = 0; i < 5; i++) part(sc, neck, bx(6, 9, 3), o.mane, 2 + i * 3.4, 10 + i * 6.5, 0, [0, 0, -0.5]); + const head = new T.Group(); head.position.set(20, 38, 0); neck.add(head); + part(sc, head, bx(30, 14, 12), mat, 10, -3, 0, [0, 0, -0.35]); part(sc, head, bx(4, 8, 3), mat, -3, 8, 4); part(sc, head, bx(4, 8, 3), mat, -3, 8, -4); + const legs = [[34, 11], [34, -11], [-34, 11], [-34, -11]].map(([x, z], i) => { + const hip = new T.Group(); hip.position.set(x * L, H - 6, z * G); root.add(hip); + part(sc, hip, cy(5.5 * G, 3.6, 30 * o.legLen, 6), mat, 0, -14 * o.legLen, 0); + const knee = new T.Group(); knee.position.y = -29 * o.legLen; hip.add(knee); + part(sc, knee, cy(3.4, 2.8, 25 * o.legLen, 6), mat, 0, -12 * o.legLen, 0); part(sc, knee, bx(9, 5, 8), mat, 1, -25 * o.legLen, 0); + return { hip, knee, ph: [0, 0.5, 0.6, 0.1][i] }; + }); + const tail = new T.Group(); tail.position.set(-46 * L, H + 14, 0); root.add(tail); part(sc, tail, cy(2.5, 1, 30, 5), o.mane || mat, -6, -13, 0, [0, 0, -0.4]); + return { root, body, neck, head, legs, tail, height: H }; + }; + // Leg cycle: phase in turns, amount scales the stride; rearing lifts the forehand on the hind legs. + R.gallop = (h, phase, amount, rear) => { + h.legs.forEach((l, i) => { const a = Math.sin((phase + l.ph) * Math.PI * 2) * amount, front = i < 2; l.hip.rotation.z = a * 0.7 + (front ? rear * 0.9 : -rear * 0.35); l.knee.rotation.z = -Math.max(0, -a) * 0.9 + (front ? -rear * 1.2 : 0); }); + h.body.rotation.z = rear * 0.72 + Math.sin(phase * Math.PI * 4) * 0.03 * amount; + h.body.position.y = h.height + Math.abs(Math.sin(phase * Math.PI * 2)) * 3.5 * amount + rear * 22; + h.tail.rotation.z = Math.sin(phase * Math.PI * 4) * 0.18 * amount; + h.neck.rotation.z = Math.sin(phase * Math.PI * 2 + 1) * 0.06 * amount - rear * 0.2; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/scripted.js b/environments/games/web/games/hexen2_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..212539e5682deae317c9f15decaa1aa6ebb4bd40 --- /dev/null +++ b/environments/games/web/games/hexen2_remake/scripted.js @@ -0,0 +1,123 @@ +/* Hexen II boss arenas - the standard scripted controller. Privileged state, legal keys only, look-ahead on copies of the game; it never writes the live game. + Blinding: a copy never carries the live RNG. Before every simulated tick it is reseeded from a multiply mix of (tick, sample), so a look-ahead learns what is already decided + (states, timers, missiles in flight), never a coin flip that has not happened yet. Each plan is scored over three sampled futures: half worst case, half mean. + The score is health lost against damage dealt in the horizon; no distance-to-target reward, so walking to a pickup is never punished for moving away from the boss. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.Hexen2Game, Q = M.Q; + const HORIZON = 72, SAMPLES = 3; // 1.2 s of 60 Hz ticks + const mix = (t, k) => { let h = Math.imul(t + 40503, 0x85EBCA6B) ^ Math.imul(k + 7919, 0xC2B2AE35); h = Math.imul(h ^ (h >>> 15), 0x2C1B3C6D); h = Math.imul(h ^ (h >>> 13), 0xC2B2AE3D); return ((h ^ (h >>> 16)) >>> 0) || 1; }; + M.lookaheadSeed = mix; + const MOVES = [[], ['W'], ['S'], ['A'], ['D'], ['W', 'A'], ['W', 'D'], ['S', 'A'], ['S', 'D']]; + const SPEED = { purifier: 1000, axe: 900 }; + // Where to look: at the boss, led by its velocity over the missile's flight. + function aimAngles(g) { + const p = g.p, b = g.boss, D = Q.BOSS[b.kind], eye = Q.eye(p), a = D.aim(g, b), v = D.vel ? D.vel(g, b) : [0, 0, 0]; + const dist = Q.len(Q.sub(a, eye)), s = SPEED[p.weapon], to = Q.sub(s ? Q.ma(a, dist / s, v) : a, eye); + return { yaw: Q.vectoyaw(to), pitch: -Math.atan2(to[2], Q.hlen(to)) / Q.DEG, dist }; + } + function mouseFor(g) { + const p = g.p, a = aimAngles(g), lim = 1000; + return [Math.max(-lim, Math.min(lim, -Q.angdiff(a.yaw - p.yaw) / Q.MOUSE_DEG)), Math.max(-lim, Math.min(lim, (a.pitch - p.pitch) / Q.MOUSE_DEG)), 0]; + } + function wantWeapon(g) { + const p = g.p, b = g.boss, reach = aimAngles(g).dist - (b.maxs ? b.maxs[0] : 0); + if (reach < 60) return 'vorpal'; + if (p.green >= 2 && p.blue >= 2) return 'purifier'; + if (p.green >= 2) return 'axe'; + return 'vorpal'; + } + function rollout(g0, keys, sample) { + const c = M.copyGame(g0), none = new Set(), set = new Set(keys), D = Q.BOSS[c.boss.kind]; + const p0 = c.p.hp, b0 = D.progress(c, c.boss); + let m = [0, 0, 0]; + for (let t = 0; t < HORIZON && !c.outcome; t++) { + c.rng = mix(c.t, sample); + c.events = []; + if (t % 12 === 0) m = mouseFor(c).map(v => v / 12); + c.update(set, none, m); + c.t++; + } + const threats = c.missiles.reduce((s, mi) => { if (mi.player || mi.minor) return s; const d = Q.len(Q.sub(mi.o, Q.center(c.p))); return s + (d < 200 ? (200 - d) / 200 : 0); }, 0); + return { lost: p0 - Math.max(0, c.p.hp), dealt: b0 - D.progress(c, c.boss), dead: c.p.hp <= 0 || c.outcome === 'loss', threats, hits: c.p.hits - g0.p.hits }; + } + function score(g, keys) { + let worst = Infinity, sum = 0; + for (let s = 0; s < SAMPLES; s++) { + const r = rollout(g, keys, s), v = -r.lost * 6 + r.dealt * 0.08 - r.threats * 2 - r.hits - (r.dead ? 400 : 0); + worst = Math.min(worst, v); sum += v; // copies skip N.quantize for speed; the score is rounded below so one ULP cannot flip a plan + } + return Math.round((0.5 * worst + 0.5 * sum / SAMPLES) * 1e4) / 1e4; + } + // Nearest live pickup of a wanted kind: a goal chosen outright when supplies run low, not scored by distance. + function supplyGoal(g) { + const p = g.p, wantH = p.hp < p.maxHp * 0.55, wantM = p.green < 25 || p.blue < 25; + if (!wantH && !wantM) return null; + let best = null, bd = Infinity; + for (const it of g.items) { + if (it.respawn > g.t || !((wantH && it.k === 'health') || (wantM && it.k === 'mana'))) continue; + const d = Q.len(Q.sub(it.o, p.o)); if (d < bd) { bd = d; best = it; } + } + return best; + } + // No line to the aim point: the nearest spot the player can walk straight to that has one. A goal chosen outright when the line is lost, not a distance reward, so nothing is scored for closing in. + function sightGoal(g) { + const p = g.p, D = Q.BOSS[g.boss.kind], aim = D.aim(g, g.boss), eye = Q.eye(p); + if (Q.clear(g, eye, aim)) return null; + const toAim = Q.vectoyaw(Q.sub(aim, p.o)); + for (const r of [96, 192, 320, 480, 640, 860]) for (let k = 0; k < 16; k++) { + const a = (toAim + (k % 2 ? 1 : -1) * Math.ceil(k / 2) * 22.5) * Q.DEG, o = [p.o[0] + Math.cos(a) * r, p.o[1] + Math.sin(a) * r, p.o[2]]; + if (Q.traceWorld(g, p.o, o, [-16, -16, 0], [16, 16, 56]).fraction < 1) continue; + if (Q.clear(g, [o[0], o[1], eye[2]], aim)) return { o }; + } + return { o: aim }; + } + // Flying boss only: does a shot fired now on the planned aim land? A blinded copy (reseeded per tick like the rollouts) flies one missile with the player's other shots removed. + // Circling flyers otherwise eat the mana on misses and the fight stalls on the long walk to the crystals. + function shotLands(g, a) { + const c = M.copyGame(g), p = c.p, kind = p.weapon === 'axe' ? 'axe' : 'pur', spd = kind === 'axe' ? 900 : 1000, life = kind === 'axe' ? 40 : 50, none = new Set(); + p.yaw = a.yaw; p.pitch = a.pitch; + const v = Q.viewVectors([p.pitch, p.yaw]); c.missiles = c.missiles.filter(m => !m.player); + c.missiles.push({ k: kind, player: true, o: Q.ma(Q.eye(p), 10, v.f), v: Q.scale(v.f, spd), life, cnt: 0, id: -1 }); + for (let t = 0; t < (life + 1) * Q.QC; t++) { + c.rng = mix(c.t, 99); c.events = []; c.update(none, none, [0, 0, 0]); c.t++; + if (!c.missiles.some(m => m.id === -1)) return c.events.some(e => e.type === 'boss_damage' && e.amount > 0) || !!c.outcome; + } + return false; + } + // The target a shot would meet, and whether the boss says a hit there counts (no say: any target counts). + const hits = (g, id) => !!id && (!Q.BOSS[g.boss.kind].shootable || Q.BOSS[g.boss.kind].shootable(g, g.boss, id)); + function moveToward(p, to) { + const rel = Q.angdiff(Q.vectoyaw(Q.sub(to, p.o)) - p.yaw), keys = []; + if (Math.abs(rel) < 67) keys.push('W'); else if (Math.abs(rel) > 113) keys.push('S'); + if (rel > 22 && rel < 158) keys.push('A'); else if (rel < -22 && rel > -158) keys.push('D'); + return keys; + } + M.scripted = function (g) { + const p = g.p, D = Q.BOSS[g.boss.kind], want = wantWeapon(g), forced = D.goal && D.goal(g, g.boss), dry = p.green < 2 || p.blue < 2, supply = supplyGoal(g); + // Dry: walk in for the sword, at the boss unless it says where the sword is any use (the big demon while its orb lives). + const dg = dry && D.dryGoal && D.dryGoal(g, g.boss), goal = forced ? { o: forced } : supply || (dry ? { o: dg || g.boss.o.slice() } : sightGoal(g)); + const cands = MOVES.map(m => (m.length ? m.concat('Shift') : []).concat('J')); + if (goal) cands.push(moveToward(p, goal.o).concat('Shift', 'J')); + let best = cands[0], bestV = -Infinity; + cands.forEach((c, i) => { + const v = score(g, c) + (goal && i === cands.length - 1 ? (dry || forced ? 40 : 6) : 0); // a supply run keeps its chance against a merely safer step + if (v > bestV) { bestV = v; best = c; } + }); + // Mana is the whole sustained damage budget: hold the trigger only when a shot can land, on the aim the packet ends with. + const a = aimAngles(g), aimed = Math.abs(Q.angdiff(a.yaw - p.yaw)) < 34 && Q.BOSS[g.boss.kind].targets(g, g.boss).length > 0 && hits(g, Q.traceShot(g, Q.eye(p), Q.BOSS[g.boss.kind].aim(g, g.boss), 8).target); + // A boss that says which targets are worth a shot: the led line the bolt really flies must not meet one that is not, with the boxes grown by 50 for the player's own step + // within the packet. (It may meet nothing now: it is aimed where a walking target will be.) + if (aimed && D.shootable && SPEED[p.weapon]) { const v = Q.viewVectors([a.pitch, a.yaw]).f, t = Q.traceShot(g, Q.eye(p), Q.ma(Q.eye(p), a.dist + 200, v), 50).target; if (t && !hits(g, t)) best = best.filter(k => k !== 'J'); } + if (!aimed || (g.boss.fly && SPEED[p.weapon] && !shotLands(g, a))) best = best.filter(k => k !== 'J'); + const holds = Array.from({ length: 6 }, () => best.slice()); + // A change of weapon lands only once attack_finished has run out, so the trigger is off for the whole packet and the tap is on its second half. + if (p.weapon !== want) { + const cycle = (Q.WEAPONS.indexOf(want) - Q.WEAPONS.indexOf(p.weapon) + 4) % 4 <= 2 ? 'K' : 'R', move = best.filter(k => k !== 'J'); + for (let i = 0; i < 6; i++) holds[i] = i >= 3 && i < 5 && Q.now(g) + 0.1 >= p.attack_finished ? move.concat(cycle).slice(0, 4) : move.slice(); + } + // Whole mouse counts: the public packet carries integers (keymouse.py parse), so a fractional one here would make Node runs differ from the interface's. + return { holds, mouse: mouseFor(g).map(Math.round) }; + }; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hexen2_remake/telegraph.js b/environments/games/web/games/hexen2_remake/telegraph.js new file mode 100644 index 0000000000000000000000000000000000000000..8e1f2aa72f132520afd9bbdeeef6ff2375f980ec --- /dev/null +++ b/environments/games/web/games/hexen2_remake/telegraph.js @@ -0,0 +1,104 @@ +/* Hexen II boss arenas - what the picture shows: the first-person camera model and, for every damaging move, its wind-up (BossBench render layer; the simulation never loads this file). + M.VIEW.camera / project: the renderer's camera (eye, pitch + kick, yaw; 90 degree horizontal field of view on 854 x 480), shared with the tools that measure the agent's frames. + M.VIEW.boltPos: where a player missile is drawn. The simulation launches it from the eye on the aim line (h2player.js launch); the picture draws it from the weapon's mouth as the source does + (purifier.hc launch_pmissile1: proj_ofs '0 0 44' + v_forward*6 +- v_right*10, alternating; axe.hc: + v_right*1), parallel to the simulated flight and joining it over the last 160 units + before it lands, so the bolt never sits on the crosshair or the boss and its sparks appear where the simulation hit. + M.TELE[kind](g, b) -> null | { move, label, k: 0..1 of the wind-up, lead: seconds to the hit, at: where the cue glows, hue }: a pure function of the state, read by the art and the HUD. + Wind-up lengths are the source's frame counts at 0.05 s; the telegraph table is in Nothing here draws gameplay RNG or writes the state. */ +(function (root) { + 'use strict'; + const M = root.Hexen2Game, Q = M.Q, V = M.VIEW = {}, T = M.TELE = {}; + V.W = 854; V.H = 480; V.TAN_H = 1; V.TAN_V = 480 / 854; V.NEAR = 8; + V.HUD_TOP = 54; V.HUD_BOTTOM = 422; // draw.js panels: boss bar on top, status bar below; the band between is the open view + V.camera = g => ({ eye: Q.eye(g.p), pitch: g.p.pitch + g.p.kick * 1.5, yaw: g.p.yaw }); + // Screen position of a world point, or null behind the near plane. x, y in pixels; z = depth along the view. + V.project = (cam, pt) => { + const v = Q.viewVectors([cam.pitch, cam.yaw]), d = Q.sub(pt, cam.eye), z = Q.dot(d, v.f); + if (z <= V.NEAR) return null; + return { x: V.W / 2 * (1 + Q.dot(d, v.r) / z / V.TAN_H), y: V.H / 2 * (1 - Q.dot(d, v.u) / z / V.TAN_V), z }; + }; + V.inBand = s => !!s && s.x >= 0 && s.x <= V.W && s.y >= V.HUD_TOP && s.y <= V.HUD_BOTTOM; + // The boss model is drawn (Famine is gone while blinked out). + V.bossShown = (g, b) => !(b.kind === 'famine' && b.state === 'hidden') && !(b.kind === 'praevus' && b.state === 'gone'); + V.bossTop = b => [b.o[0], b.o[1], b.o[2] + (b.maxs ? b.maxs[2] : 100)]; + // Sample points of the boss for sight: the declared aim point, the box centre, near the top. + V.bossPoints = (g, b) => { const lo = b.mins ? b.mins[2] : 0, hi = b.maxs ? b.maxs[2] : 100; return [Q.BOSS[b.kind].aim(g, b), [b.o[0], b.o[1], b.o[2] + (lo + hi) / 2], [b.o[0], b.o[1], b.o[2] + hi * 0.85]]; }; + // Seen = some sample point in the open band of the screen with a clear line from the eye (brushes are the only occluders). + V.seen = (g, cam, pts) => pts.some(pt => V.inBand(V.project(cam, pt)) && Q.clear(g, cam.eye, pt)); + V.framed = (cam, pts) => pts.some(pt => V.inBand(V.project(cam, pt))); + // Ticks since a player missile left (h2player.js launch sets life 50 / 40 on a QC frame; missilesThink takes one off the same tick). + const LIFE0 = { pur: 50, axe: 40 }; + V.boltAge = (g, m) => 1 + 3 * ((LIFE0[m.k] || 50) - 1 - m.life) + ((g.t - 1) % 3); + const OFS = { pur: [10, -6], axe: [1, -6] }, SHOWN_FROM = { pur: 28, axe: 40 }; // not drawn closer than this to the eye: inside it the bolt is still in the muzzle + // Distance to where the straight flight next meets a brush or a target (player missiles fly straight between bounces). + V.toImpact = (g, m) => { const sp = Q.len(m.v) || 1, tr = Q.traceShot(g, m.o, Q.ma(m.o, 1.2, m.v), 15); return tr.fraction * sp * 1.2; }; + V.boltSide = m => (m.k === 'pur' ? (m.id % 2 ? 1 : -1) : 1); + V.boltPos = (g, m) => { + const o = OFS[m.k]; if (!o) return m.o; + const ahead = Q.dot(Q.sub(m.o, Q.eye(g.p)), Q.norm(m.v)); if (ahead < SHOWN_FROM[m.k] && V.boltAge(g, m) < 8) return null; + const d = Q.norm(m.v), h = Math.hypot(d[0], d[1]) || 1, right = [d[1] / h, -d[0] / h, 0], side = V.boltSide(m); + const fade = Math.max(0, Math.min(1, (V.toImpact(g, m) - 24) / 140)); + return [m.o[0] + right[0] * o[0] * side * fade, m.o[1] + right[1] * o[0] * side * fade, m.o[2] + o[1] * fade]; + }; + const up = (b, z) => [b.o[0], b.o[1], b.o[2] + z]; + // k: how far into the wind-up (0..1); frames: QC frames still to go before the hit leaves. + const W = (move, label, k, frames, at, hue) => ({ move, label, k: Math.max(0, Math.min(1, k)), lead: Math.max(0, frames) * Q.DT, at, hue }); + // Famine (famhorse_move): ATTACK2 / ATTACK set rf 1 and act on the think that enters with rf 10, so 10 thinks of wind-up; the volley after a blink comes at MIDDLE_REAR frame 30. + T.famine = (g, b) => { + if (b.state === 'move' && b.stage === 7 && b.rf < 10) return W('famine_missiles', 'Triple Homing Missiles', (b.rf - 1) / 9, 11 - b.rf, up(b, 125), 'crimson'); + if (b.state === 'move' && b.stage === 4 && b.rf < 10) return W('famine_pull', 'Soul Pull', (b.rf - 1) / 9, 11 - b.rf, up(b, 125), 'violet'); + if (b.state === 'blinkin') return W('famine_missiles', 'Triple Homing Missiles', 0.2 * b.scale, 20 + Math.round((1 - b.scale) * 10), up(b, 125), 'crimson'); + if (b.state === 'rear' && b.stage === 2 && b.fr >= 10 && b.fr < 30) return W('famine_missiles', 'Triple Homing Missiles', 0.2 + 0.8 * (b.fr - 10) / 19, 30 - b.fr, up(b, 125), 'crimson'); + return null; + }; + // Death (dthhorse.hc): the move is picked on the gallop's first frame and leaves at frame 8 (bone missile, fire circle) or 7, 9 and 11 (three shots). + T.death = (g, b) => { + if (b.stage === 4 && b.fr < 8) return W('death_bone_missile', 'Bone Missile', (b.fr - 1) / 7, 8 - b.fr, up(b, 80), 'bone'); + if (b.stage === 16 && b.fr < 8) return W('death_fire_circle', 'Fire Ring', (b.fr - 1) / 7, 8 - b.fr, up(b, 80), 'ember'); + if (b.stage === 8 && b.fr < 7) return W('death_missiles', 'Triple Homing Missiles', (b.fr - 1) / 6, 7 - b.fr, up(b, 120), 'crimson'); + return null; + }; + // Pestilence (pstboar.hc): the arrow leaves on rf 4, the hive on rf 33; CHARGE_ST runs 8 frames before the boar charges. + T.pestilence = (g, b) => { + if (b.mode === 1 && b.rf < 4) return W('pest_arrow', 'Poison Arrow', (b.rf - 1) / 3, 4 - b.rf, up(b, 110), 'toxic'); + if (b.mode === 2 && b.rf < 33) return W('pest_hive', 'Hive Throw', (b.rf - 1) / 32, 33 - b.rf, up(b, 125), 'toxic'); + if (b.stage === 4) return W('pest_charge', 'Charge', b.fr / 8, 8 - b.fr, up(b, 60), 'blood'); + return null; + }; + // War (warhorse.hc): a cycle's first throw is on frame 8 / 10 / 12 by gait; the rear throws the big axe at MIDDLE_REAR frame 39 after 16 frames of BEGIN_REAR; the standing volley at frame 9. + const FIRST = [8, 10, 12]; + T.war = (g, b) => { + if (b.state === 'move' && b.stage === 4 && b.fr < FIRST[b.gait]) return W('war_axe', 'Axe Throw', (b.fr - 1) / (FIRST[b.gait] - 1), FIRST[b.gait] - b.fr, up(b, 105), 'blood'); + if (b.state === 'rear' && b.stage === 1) return W('war_big_axe', 'Giant Axe', 0.25 * b.fr / 16, 16 - b.fr + 39, up(b, 125), 'ember'); + if (b.state === 'rear' && b.stage === 2 && b.fr < 39) return W('war_big_axe', 'Giant Axe', 0.25 + 0.75 * b.fr / 39, 39 - b.fr, up(b, 125), 'ember'); + if (b.state === 'rear' && b.stage === 5 && b.fr < 9) return W('war_axe', 'Standing Axe Volley', b.fr / 9, 9 - b.fr, up(b, 105), 'blood'); + return null; + }; + // Eidolon (eidolon.hc): the roar may strike from frame 14; a fireball may leave from frame 25 (certain at 36); the flame stream starts at 25; magic may leave from frame 8. + T.eidolon = (g, b) => { + const head = up(b, b.scale > 1 ? 560 : 120); + if (b.state === 'preroar' || (b.state === 'roar' && b.fr <= 13)) return W('eidolon_roar', 'Thunder Roar', b.state === 'roar' ? b.fr / 13 : 0, 14 - (b.state === 'roar' ? b.fr : -1), head, 'storm'); + if (b.state === 'fireballs' && b.fr < 25) return W('eidolon_fireball', 'Fireballs', b.fr / 24, 25 - b.fr, head, 'violet'); + if (b.state === 'flames' && b.fr < 25) return W('eidolon_flames', 'Fire breath', b.fr / 24, 25 - b.fr, head, 'ember'); + if (b.state === 'spell' && b.fr < 8) return W('eidolon_magic', 'Magic Missile', b.fr / 7, 8 - b.fr, head, 'arcane'); + return null; + }; + // Star-volley sorcerer (boss_praevus.js): point fires on its frame 2 (one frame of warning, shown as it is); fire wall charges 33 frames; pillars rise under the player on frame 4 + 0.2 s; + // conjure gathers 13 frames before the storm; the teleport spin-up (26 frames) does no damage but says where it is about to vanish from. + T.praevus = (g, b) => { + const head = up(b, 110 * (b.scale || 1)); + if (b.state === 'point' && b.fr < 2) return W('praevus_star', 'Triple Star Bolt', b.fr / 2, 2 - b.fr, head, 'arcane'); + if (b.state === 'firewall') return W('praevus_firewall', 'Fire Wall', b.fr / 33, 34 - b.fr, up(b, 20), 'ember'); + if (b.state === 'pillar' && b.fr < 4) return W('praevus_pillar', 'Fire pillar', b.fr / 4, 8 - b.fr, [g.p.o[0], g.p.o[1], 4], 'ember'); + if (b.state === 'conjure') return W('praevus_conjure', 'Summon Storm', b.fr / 13, 13 - b.fr, head, 'storm'); + if (b.state === 'tele') return W('praevus_teleport', 'Teleport', b.fr / 26, 26 - b.fr, head, 'violet'); + return null; + }; + M.telegraph = g => { const f = T[g.boss.kind]; return f ? f(g, g.boss) : null; }; + V.HUE = { crimson: '#ff3a2e', violet: '#c060ff', bone: '#7aff6a', ember: '#ff8a1e', toxic: '#9cff2e', blood: '#ff4a28', storm: '#a8c8ff', arcane: '#7aa0ff' }; + // One packet-end frame as the agent gets it: is the boss framed (in the open band), seen (framed with a clear line), is a wind-up on, and is its cue point seen. + V.frameStats = g => { + const b = g.boss, cam = V.camera(g), shown = V.bossShown(g, b), pts = V.bossPoints(g, b), tele = M.telegraph(g); + return { t: g.t, shown, framed: shown && V.framed(cam, pts), seen: shown && V.seen(g, cam, pts), tele: tele ? tele.move : null, teleSeen: !!tele && shown && V.seen(g, cam, [tele.at, ...pts]) }; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/hollowknight_remake/arena.js b/environments/games/web/games/hollowknight_remake/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..877d2a0723198d7d11d9ed743c3b9ebe765fd022 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/arena.js @@ -0,0 +1,14 @@ +// Arena geometry, in game units (u). Origin = left wall surface / floor surface, y up. +// [data] derived from the source boss room: pivot clamps Wall X 15.13 / 37.90, Floor Y 27.55, Roof Y 40.54, +// boss idle box 0.89 x 2.56 at pivot offset (0.12, -0.26) -> floor surface 26.00, wall surfaces ~14.68 / 38.35. +(function (g) { + var BB = g.BB; + var OX = 14.68, OY = 26.0; // source-room coords -> local + BB.ARENA = { + W: 38.35 - OX, // 23.67 u wide + H: 15.3, // roof surface [hand: pivot clamp 40.54 + ~0.76] + OX: OX, OY: OY, + lx: function (srcX) { return srcX - OX; }, + ly: function (srcY) { return srcY - OY; } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/art/scenes.js b/environments/games/web/games/hollowknight_remake/art/scenes.js new file mode 100644 index 0000000000000000000000000000000000000000..7c9e1c5b58d586b8220901b55f1dd032b9872d38 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/art/scenes.js @@ -0,0 +1,413 @@ +// Biome scenes of this game: per-case themes, cached background + foreground framing, ambient motes. +// Contract with engine/renderer.js: ART.scene(doc, caseId) -> {bg, fg} canvases, ART.ambient(x, caseId, t). +(function (g) { + var BB = g.BB, ART = BB.ART, TAU = Math.PI * 2, V = ART.view; + var W = V.W, H = V.H, OX = V.OX, FLOOR = V.FLOOR, ROOF = V.ROOF, CX = W / 2; + + // ---------- biome themes ---------- + var TH = ART.THEMES = { + '2d/needle_warden': { archi: 'thorn', seed: 7, sky: ['#04100f', '#0b2526', '#163a38'], glow: [427, 300, '110,220,190'], + far: '#1b3b3a', fog: '96,170,156', mid: '#0d2425', near: '#030a0b', floorTop: '#5aa98a', floor: '#0a1a1a', wall: '#061012', + wallHi: '#3f7e6c', light: '170,255,225', mote: '170,255,215', moteUp: true, accent: '120,255,200' }, + '2d/iron_bulwark': { archi: 'foundry', seed: 31, sky: ['#0b0907', '#1d1610', '#33271a'], glow: [427, 96, '255,170,90'], + far: '#3a2c1f', fog: '190,140,90', mid: '#1b140e', near: '#060504', floorTop: '#9b7a4c', floor: '#16100a', wall: '#0e0a07', + wallHi: '#6e5432', light: '255,205,140', mote: '255,196,130', moteUp: false, accent: '255,170,80' }, + '2d/hollow_vessel': { archi: 'ember', seed: 53, sky: ['#090404', '#1c0b08', '#36160d'], glow: [427, 470, '255,110,40'], + far: '#3c1a12', fog: '210,100,50', mid: '#1a0a07', near: '#050202', floorTop: '#b65a2c', floor: '#150806', wall: '#0b0504', + wallHi: '#7a3218', light: '255,150,80', mote: '255,140,60', moteUp: true, accent: '255,120,40' }, + '2d/sickle_sisters': { archi: 'court', seed: 77, sky: ['#050c09', '#10221a', '#20392b'], glow: [427, 130, '200,240,160'], + far: '#2b4535', fog: '140,190,140', mid: '#0e1d15', near: '#030806', floorTop: '#86ad74', floor: '#0c1610', wall: '#07100b', + wallHi: '#4c7a58', light: '225,255,200', mote: '190,225,140', moteUp: false, accent: '200,255,160' }, + '2d/pale_vessel': { archi: 'sanctum', seed: 97, sky: ['#040306', '#110f16', '#221e2a'], glow: [427, 230, '225,215,255'], + far: '#2b2733', fog: '160,150,185', mid: '#100e14', near: '#020103', floorTop: '#9a92a8', floor: '#0c0b10', wall: '#07060a', + wallHi: '#5a5268', light: '240,235,255', mote: '225,215,255', moteUp: true, accent: '255,150,70' }, + '2d/lumen_moth': { archi: 'spire', seed: 131, sky: ['#120f07', '#3a2e17', '#6b5a39'], glow: [427, 170, '255,236,180'], + far: '#8a7650', fog: '255,238,200', mid: '#4a3c22', near: '#0d0a05', floorTop: '#f4e6c0', floor: '#2a2214', wall: '#140f08', + wallHi: '#c8b07a', light: '255,246,220', mote: '255,240,200', moteUp: true, accent: '255,230,150' } + }; + + // ---------- scenery primitives ---------- + function rootCurtain(x, r, col, n, len0, len1, w) { + for (var i = 0; i < n; i++) { + var rx = r.uniform(OX - 20, W - OX + 20), len = r.uniform(len0, len1), sw = r.uniform(-30, 30); + x.globalAlpha = r.uniform(0.35, 0.9); x.fillStyle = col; x.beginPath(); + ART.ribbon(x, ART.bez([rx, ROOF - 4], [rx + sw * 0.3, ROOF + len * 0.35], [rx + sw, ROOF + len * 0.7], [rx + sw * 0.6, ROOF + len], 12), r.uniform(w * 0.6, w * 1.4), 0.6); + x.fill(); + } + x.globalAlpha = 1; + } + function stalactites(x, r, col, n, len0, len1, top) { + x.fillStyle = col; + for (var i = 0; i < n; i++) { + var sx0 = r.uniform(0, W), wd = r.uniform(10, 40), len = r.uniform(len0, len1), bend = r.uniform(-8, 8); + x.beginPath(); x.moveTo(sx0 - wd, top); x.quadraticCurveTo(sx0 - wd * 0.3, top + len * 0.6, sx0 + bend, top + len); + x.quadraticCurveTo(sx0 + wd * 0.3, top + len * 0.6, sx0 + wd, top); x.closePath(); x.fill(); + } + } + function hills(x, r, col, y0, amp, step) { + x.fillStyle = col; x.beginPath(); x.moveTo(0, H); x.lineTo(0, y0); + for (var px = 0; px <= W + step; px += step) x.quadraticCurveTo(px - step / 2, y0 - r.uniform(0, amp), px, y0 - r.uniform(0, amp * 0.5)); + x.lineTo(W, H); x.closePath(); x.fill(); + } + function thornVine(x, r, pts, w0, w1, col, thorn) { + x.fillStyle = col; x.beginPath(); ART.ribbon(x, pts, w0, w1); x.fill(); + for (var i = 1; i < pts.length - 1; i++) { + if (!r.chance(thorn)) continue; + var p = pts[i], q = pts[i + 1], a = Math.atan2(q[1] - p[1], q[0] - p[0]) + (r.chance(0.5) ? 1 : -1) * r.uniform(0.9, 1.6); + var wl = (w0 + (w1 - w0) * i / pts.length) * 0.5, tl = r.uniform(5, 11) + wl; + x.beginPath(); x.moveTo(p[0] + Math.cos(a + 1.4) * wl * 0.6, p[1] + Math.sin(a + 1.4) * wl * 0.6); + x.lineTo(p[0] + Math.cos(a) * tl, p[1] + Math.sin(a) * tl); + x.lineTo(p[0] + Math.cos(a - 1.4) * wl * 0.6, p[1] + Math.sin(a - 1.4) * wl * 0.6); x.fill(); + } + } + function leafClump(x, r, cx, cy, n, size, col, hang) { + x.fillStyle = col; + for (var i = 0; i < n; i++) { + var a = hang ? r.uniform(0.3, Math.PI - 0.3) : r.uniform(-Math.PI + 0.2, -0.2), L = r.uniform(size * 0.5, size); + var bx = cx + r.uniform(-size * 0.4, size * 0.4), by = cy + r.uniform(-4, 4); + var tx = bx + Math.cos(a) * L, ty = by + Math.sin(a) * L, nx = -Math.sin(a) * L * 0.22, ny = Math.cos(a) * L * 0.22; + x.beginPath(); x.moveTo(bx, by); x.quadraticCurveTo((bx + tx) / 2 + nx, (by + ty) / 2 + ny, tx, ty); + x.quadraticCurveTo((bx + tx) / 2 - nx, (by + ty) / 2 - ny, bx, by); x.fill(); + } + } + function pillar(x, cx, w, top, bot, col, rings) { + x.fillStyle = col; x.fillRect(cx - w / 2, top, w, bot - top); + x.fillRect(cx - w * 0.7, bot - 14, w * 1.4, 14); x.fillRect(cx - w * 0.65, top, w * 1.3, 12); + if (rings) { x.fillStyle = rings; for (var y = top + 40; y < bot - 30; y += 60) x.fillRect(cx - w * 0.56, y, w * 1.12, 6); } + } + function pointedArch(x, cx, top, w, bot, th, col) { // gothic arch frame (band of thickness th) + x.fillStyle = col; x.beginPath(); + x.moveTo(cx - w / 2 - th, bot); x.lineTo(cx - w / 2 - th, top + w * 0.55); + x.quadraticCurveTo(cx - w / 2 - th, top - th * 0.5, cx, top - th * 1.6); x.quadraticCurveTo(cx + w / 2 + th, top - th * 0.5, cx + w / 2 + th, top + w * 0.55); + x.lineTo(cx + w / 2 + th, bot); x.lineTo(cx + w / 2, bot); x.lineTo(cx + w / 2, top + w * 0.55); + x.quadraticCurveTo(cx + w / 2, top + th * 0.4, cx, top); x.quadraticCurveTo(cx - w / 2, top + th * 0.4, cx - w / 2, top + w * 0.55); + x.lineTo(cx - w / 2, bot); x.closePath(); x.fill(); + } + function chain(x, x0, y0, x1, y1, sag, col, lw) { + x.strokeStyle = col; x.lineWidth = lw; + var n = Math.max(6, Math.round(Math.hypot(x1 - x0, y1 - y0) / (lw * 3))); + for (var i = 0; i < n; i++) { + var k = (i + 0.5) / n, px = x0 + (x1 - x0) * k, py = y0 + (y1 - y0) * k + Math.sin(k * Math.PI) * sag; + var ang = Math.atan2(y1 - y0 + Math.cos(k * Math.PI) * sag * Math.PI, x1 - x0) + (i % 2) * 1.57; + x.beginPath(); x.ellipse(px, py, lw * 1.6, lw * 1.0, ang, 0, TAU); x.stroke(); + } + } + function blisters(x, r, cx, cy, n, size, T) { // glowing infection pustules + for (var i = 0; i < n; i++) { + var bx = cx + r.uniform(-size, size), by = cy + r.uniform(-size * 0.6, size * 0.6), br = r.uniform(size * 0.15, size * 0.42); + ART.glow(x, bx, by, br * 3.2, T.accent, 0.22); + var gr = x.createRadialGradient(bx - br * 0.3, by - br * 0.3, br * 0.1, bx, by, br); + gr.addColorStop(0, '#ffe2a0'); gr.addColorStop(0.45, '#ff9a3a'); gr.addColorStop(1, '#8a2c0c'); + x.fillStyle = gr; x.beginPath(); x.arc(bx, by, br, 0, TAU); x.fill(); + } + } + ART.blisters = blisters; + + // ---------- architecture per biome: far / mid / floor / wall / fg ---------- + var ARCHI = {}; + ARCHI.thorn = { + far: function (x, r, T) { + rootCurtain(x, r, T.far, 34, 60, 260, 6); + ART.glow(x, CX, 300, 230, T.glow[2], 0.16); // ruined round gate, light in its opening + x.fillStyle = T.far; x.beginPath(); x.arc(CX, 330, 190, Math.PI, 0); x.arc(CX, 330, 160, 0, Math.PI, true); x.closePath(); x.fill(); + x.fillRect(CX - 190, 330, 30, FLOOR - 330); x.fillRect(CX + 160, 330, 30, FLOOR - 330); + for (var i = 0; i < 11; i++) { var a = Math.PI + i * Math.PI / 10; x.save(); x.translate(CX + Math.cos(a) * 176, 330 + Math.sin(a) * 176); x.rotate(a + Math.PI / 2); x.fillRect(-9, -20, 18, 24); x.restore(); } + hills(x, r, T.far, 440, 50, 60); + }, + mid: function (x, r, T) { + thornVine(x, r, ART.bez([OX - 30, 150], [200, 40], [300, 70], [380, ROOF - 10], 30), 22, 5, T.mid, 0.55); + thornVine(x, r, ART.bez([W - OX + 30, 220], [640, 90], [560, 30], [500, ROOF - 10], 30), 20, 5, T.mid, 0.55); + thornVine(x, r, ART.bez([OX - 10, 380], [150, 300], [120, 220], [190, 160], 24), 12, 3, T.mid, 0.6); + thornVine(x, r, ART.bez([W - OX + 10, 400], [700, 330], [740, 280], [690, 230], 24), 12, 3, T.mid, 0.6); + for (var i = 0; i < 9; i++) leafClump(x, r, r.uniform(OX, W - OX), ROOF + r.uniform(0, 20), 7, r.uniform(26, 50), T.mid, true); + leafClump(x, r, OX + 40, FLOOR, 16, 70, T.mid, false); leafClump(x, r, W - OX - 50, FLOOR, 16, 76, T.mid, false); + }, + floor: function (x, r, T) { + x.strokeStyle = T.floorTop; + for (var i = 0; i < 140; i++) { var gx = r.uniform(OX, W - OX), gh = r.uniform(3, 10); x.globalAlpha = r.uniform(0.4, 0.9); x.lineWidth = r.uniform(1, 2); x.beginPath(); x.moveTo(gx, FLOOR + 1); x.quadraticCurveTo(gx + 1, FLOOR - gh * 0.6, gx + r.uniform(-4, 4), FLOOR - gh); x.stroke(); } + x.globalAlpha = 1; + }, + wall: function (x, r, T, side, ex) { + var d = side ? 1 : -1; + thornVine(x, r, ART.bez([ex + d * 10, H], [ex - d * 30, 330], [ex + d * 20, 160], [ex - d * 14, ROOF], 30), 14, 6, T.near, 0.7); + }, + fg: function (x, r, T) { + leafClump(x, r, 30, ROOF + 4, 14, 90, T.near, true); leafClump(x, r, W - 30, ROOF + 4, 14, 90, T.near, true); + thornVine(x, r, ART.bez([-10, 60], [80, 30], [160, 10], [240, -10], 20), 16, 5, T.near, 0.6); + thornVine(x, r, ART.bez([W + 10, 80], [W - 90, 40], [W - 170, 12], [W - 260, -10], 20), 16, 5, T.near, 0.6); + leafClump(x, r, 18, H + 8, 10, 44, T.near, false); leafClump(x, r, W - 18, H + 8, 10, 44, T.near, false); + } + }; + ARCHI.foundry = { + far: function (x, r, T) { + ART.glow(x, CX, 96, 220, T.glow[2], 0.24); // high round window pouring warm light + x.fillStyle = 'rgba(255,190,120,0.2)'; x.beginPath(); x.arc(CX, 96, 46, 0, TAU); x.fill(); + x.strokeStyle = T.far; x.lineWidth = 12; x.beginPath(); x.arc(CX, 96, 50, 0, TAU); x.stroke(); + x.lineWidth = 5; for (var i = 0; i < 8; i++) { var a = i * TAU / 8; x.beginPath(); x.moveTo(CX, 96); x.lineTo(CX + Math.cos(a) * 50, 96 + Math.sin(a) * 50); x.stroke(); } + for (i = 0; i < 16; i++) { // stacked crates in the dark + var bx = r.uniform(OX, W - OX), bw = r.uniform(30, 70), bh = r.uniform(30, 120); + if (Math.abs(bx - CX) < 120) continue; + x.fillStyle = T.far; x.fillRect(bx - bw / 2, FLOOR - bh - 20, bw, bh + 20); + x.fillStyle = 'rgba(0,0,0,0.18)'; x.fillRect(bx - bw / 2, FLOOR - bh - 20 + bh * 0.33, bw, 3); + } + x.fillStyle = T.far; x.fillRect(OX, 175, W - 2 * OX, 10); x.fillRect(OX, 168, W - 2 * OX, 4); + for (i = 0; i < 7; i++) x.fillRect(OX + 40 + i * 115, 175, 8, 120); + }, + mid: function (x, r, T) { + pillar(x, 205, 46, ROOF, FLOOR, T.mid, 'rgba(110,80,46,0.45)'); + pillar(x, W - 205, 46, ROOF, FLOOR, T.mid, 'rgba(110,80,46,0.45)'); + chain(x, 290, ROOF, 290, 150, 0, T.mid, 3); chain(x, 560, ROOF, 560, 120, 0, T.mid, 3); + chain(x, 330, ROOF + 10, 520, ROOF + 10, 60, T.mid, 3); + x.fillStyle = T.mid; + [150, W - 150].forEach(function (px) { x.beginPath(); x.ellipse(px, FLOOR - 26, 24, 28, 0, 0, TAU); x.fill(); }); + for (var i = 0; i < 4; i++) { x.save(); x.translate(250 + i * 9, FLOOR); x.rotate(-0.25 + i * 0.05); x.fillRect(-2, -110, 4, 110); x.restore(); } + }, + floor: function (x, r, T) { + x.strokeStyle = 'rgba(0,0,0,0.5)'; x.lineWidth = 1; + for (var px = OX + r.uniform(10, 50); px < W - OX; px += r.uniform(40, 80)) { x.beginPath(); x.moveTo(px, FLOOR + 3); x.lineTo(px + r.uniform(-3, 3), H); x.stroke(); } + x.fillStyle = T.floorTop; + for (var i = 0; i < 30; i++) { x.globalAlpha = r.uniform(0.3, 0.7); x.beginPath(); x.ellipse(r.uniform(OX, W - OX), FLOOR - 1, r.uniform(1.5, 4), r.uniform(1, 2), 0, 0, TAU); x.fill(); } + x.globalAlpha = 1; + }, + wall: function (x, r, T, side, ex) { + var d = side ? 1 : -1, lx = ex - d * 24; + x.fillStyle = '#2a1e12'; x.fillRect(lx - 2, 150, 4, 30); + ART.glow(x, lx, 196, 70, T.accent, 0.35); + x.fillStyle = '#ffd38a'; x.beginPath(); x.ellipse(lx, 196, 6, 9, 0, 0, TAU); x.fill(); + x.strokeStyle = '#2a1e12'; x.lineWidth = 3; x.strokeRect(lx - 9, 182, 18, 28); + }, + fg: function (x, r, T) { + chain(x, 20, -10, 120, 40, 30, T.near, 5); chain(x, W - 20, -10, W - 120, 40, 30, T.near, 5); + x.fillStyle = T.near; + x.beginPath(); x.ellipse(-10, H + 8, 92, 26, 0, 0, TAU); x.fill(); x.beginPath(); x.ellipse(W + 10, H + 8, 92, 26, 0, 0, TAU); x.fill(); + } + }; + ARCHI.ember = { + far: function (x, r, T) { + stalactites(x, r, T.far, 40, 40, 200, ROOF - 2); + hills(x, r, T.far, 430, 90, 70); + for (var i = 0; i < 14; i++) { x.fillStyle = T.far; x.beginPath(); x.arc(r.uniform(OX, W - OX), FLOOR - 60 - r.uniform(0, 140), r.uniform(14, 36), 0, TAU); x.fill(); } + ART.glow(x, CX, FLOOR, 360, T.glow[2], 0.2); + }, + mid: function (x, r, T) { + stalactites(x, r, T.mid, 18, 30, 130, ROOF - 2); + for (var i = 0; i < 12; i++) { // dripping tendrils + var tx = r.uniform(OX, W - OX), L = r.uniform(40, 150); + x.fillStyle = T.mid; x.beginPath(); ART.ribbon(x, ART.bez([tx, ROOF], [tx + 6, ROOF + L * 0.3], [tx - 8, ROOF + L * 0.7], [tx + 2, ROOF + L], 10), 8, 1.5); x.fill(); + x.beginPath(); x.arc(tx + 2, ROOF + L + 3, 2.5, 0, TAU); x.fill(); + } + x.fillStyle = T.mid; x.beginPath(); x.ellipse(OX + 40, FLOOR, 90, 50, 0, Math.PI, 0); x.fill(); x.beginPath(); x.ellipse(W - OX - 40, FLOOR, 100, 46, 0, Math.PI, 0); x.fill(); + blisters(x, r, OX + 50, FLOOR - 30, 6, 30, T); blisters(x, r, W - OX - 60, FLOOR - 28, 6, 30, T); + blisters(x, r, 300, ROOF + 30, 3, 16, T); blisters(x, r, 600, ROOF + 40, 3, 16, T); + }, + floor: function (x, r, T) { + for (var i = 0; i < 22; i++) { var bx = r.uniform(OX + 20, W - OX - 20), br = r.uniform(2, 5); ART.glow(x, bx, FLOOR, br * 3, T.accent, 0.25); x.fillStyle = '#ff9a48'; x.beginPath(); x.arc(bx, FLOOR, br, Math.PI, 0); x.fill(); } + }, + wall: function (x, r, T, side, ex) { var d = side ? 1 : -1; blisters(x, r, ex - d * 22, 120 + r.uniform(0, 60), 5, 26, T); blisters(x, r, ex - d * 18, 330 + r.uniform(0, 50), 4, 20, T); }, + fg: function (x, r, T) { + stalactites(x, r, T.near, 14, 20, 60, -2); + x.fillStyle = T.near; x.beginPath(); x.ellipse(-20, H + 10, 100, 28, 0, 0, TAU); x.fill(); x.beginPath(); x.ellipse(W + 20, H + 10, 100, 28, 0, 0, TAU); x.fill(); + } + }; + ARCHI.court = { + far: function (x, r, T) { + ART.glow(x, CX, 130, 260, T.glow[2], 0.14); + for (var i = 0; i < 5; i++) { // colonnade of tall pointed arches + var cx = CX + (i - 2) * 150, wd = i === 2 ? 120 : 92, top = 70 + (i === 2 ? 0 : 30); + x.fillStyle = 'rgba(200,240,170,' + (i === 2 ? 0.1 : 0.05) + ')'; x.fillRect(cx - wd / 2, top + wd * 0.3, wd, FLOOR - top); + pointedArch(x, cx, top, wd, FLOOR, 16, T.far); + } + for (i = 0; i < 4; i++) { // banners between arches + var bx = CX + (i - 1.5) * 150, bt = 40; + x.fillStyle = T.far; x.beginPath(); x.moveTo(bx - 14, bt); x.lineTo(bx + 14, bt); x.lineTo(bx + 14, bt + 110); x.lineTo(bx, bt + 96); x.lineTo(bx - 14, bt + 110); x.closePath(); x.fill(); + } + hills(x, r, T.far, 452, 20, 40); + }, + mid: function (x, r, T) { + for (var i = 0; i < 9; i++) { // tall sickle fronds on both sides + var side = i % 2, bx = side ? W - OX - r.uniform(0, 110) : OX + r.uniform(0, 110), h = r.uniform(150, 320), lean = (side ? -1 : 1) * r.uniform(30, 90); + x.fillStyle = T.mid; x.beginPath(); + ART.ribbon(x, ART.bez([bx, FLOOR + 4], [bx, FLOOR - h * 0.5], [bx + lean * 0.4, FLOOR - h], [bx + lean, FLOOR - h * 0.85], 16), 12, 1); x.fill(); + } + for (i = 0; i < 7; i++) leafClump(x, r, r.uniform(OX, W - OX), ROOF + 2, 6, r.uniform(30, 60), T.mid, true); + }, + floor: function (x, r, T) { + x.fillStyle = 'rgba(0,0,0,0.35)'; + for (var px = OX; px < W - OX; px += 36) x.fillRect(px, FLOOR + 3, 1, H - FLOOR); + x.strokeStyle = T.floorTop; x.lineWidth = 1; + for (var i = 0; i < 60; i++) { var gx = r.uniform(OX, W - OX); x.globalAlpha = r.uniform(0.3, 0.8); x.beginPath(); x.moveTo(gx, FLOOR + 1); x.lineTo(gx + r.uniform(-3, 3), FLOOR - r.uniform(2, 7)); x.stroke(); } + x.globalAlpha = 1; + }, + wall: function (x, r, T, side, ex) { + var d = side ? 1 : -1; x.fillStyle = T.wallHi; x.globalAlpha = 0.35; + for (var y = 60; y < FLOOR; y += 120) { x.beginPath(); x.moveTo(ex - d * 30, y); x.quadraticCurveTo(ex - d * 50, y + 30, ex - d * 30, y + 70); x.quadraticCurveTo(ex - d * 40, y + 30, ex - d * 30, y); x.fill(); } + x.globalAlpha = 1; + }, + fg: function (x, r, T) { + for (var i = 0; i < 2; i++) { var bx = i ? W + 6 : -6, d = i ? -1 : 1; x.fillStyle = T.near; x.beginPath(); ART.ribbon(x, ART.bez([bx, H + 10], [bx + d * 8, 320], [bx + d * 40, 180], [bx + d * 70, 130], 20), 18, 2); x.fill(); } + leafClump(x, r, 40, ROOF, 12, 80, T.near, true); leafClump(x, r, W - 40, ROOF, 12, 80, T.near, true); + } + }; + ARCHI.sanctum = { + far: function (x, r, T) { + ART.glow(x, CX, 230, 300, T.glow[2], 0.12); + x.strokeStyle = T.far; x.lineWidth = 22; x.beginPath(); x.arc(CX, 230, 150, 0, TAU); x.stroke(); // great sealed ring + x.lineWidth = 6; x.beginPath(); x.arc(CX, 230, 112, 0, TAU); x.stroke(); + x.fillStyle = T.far; + for (var i = 0; i < 12; i++) { var a = i * TAU / 12; x.save(); x.translate(CX + Math.cos(a) * 150, 230 + Math.sin(a) * 150); x.rotate(a); x.fillRect(-16, -12, 32, 24); x.restore(); } + for (i = 0; i < 4; i++) { var b = i * TAU / 4 + 0.4; x.lineWidth = 8; x.beginPath(); x.moveTo(CX + Math.cos(b) * 112, 230 + Math.sin(b) * 112); x.lineTo(CX + Math.cos(b) * 40, 230 + Math.sin(b) * 40); x.stroke(); } + x.fillStyle = 'rgba(255,150,70,0.10)'; x.beginPath(); x.arc(CX, 230, 34, 0, TAU); x.fill(); + chain(x, OX, 40, CX - 150, 200, 40, T.far, 4); chain(x, W - OX, 40, CX + 150, 200, 40, T.far, 4); + chain(x, OX + 60, ROOF, CX - 110, 120, 30, T.far, 3); chain(x, W - OX - 60, ROOF, CX + 110, 120, 30, T.far, 3); + hills(x, r, T.far, 446, 24, 50); + }, + mid: function (x, r, T) { + [[150, 300], [250, 380], [W - 150, 280], [W - 260, 360]].forEach(function (p) { // broken columns + pillar(x, p[0], 34, p[1], FLOOR, T.mid, null); + x.fillStyle = T.mid; x.beginPath(); x.moveTo(p[0] - 22, p[1]); x.lineTo(p[0] - 6, p[1] - 14); x.lineTo(p[0] + 4, p[1] - 4); x.lineTo(p[0] + 22, p[1] - 10); x.lineTo(p[0] + 22, p[1] + 2); x.lineTo(p[0] - 22, p[1] + 2); x.fill(); + }); + chain(x, 200, ROOF, 200, 180, 0, T.mid, 4); chain(x, W - 200, ROOF, W - 200, 210, 0, T.mid, 4); + }, + floor: function (x, r, T) { + x.fillStyle = 'rgba(0,0,0,0.45)'; + for (var px = OX + 20; px < W - OX; px += 56) x.fillRect(px, FLOOR + 3, 2, H - FLOOR); + x.fillStyle = T.floorTop; + for (var i = 0; i < 18; i++) { x.globalAlpha = r.uniform(0.3, 0.6); var bx = r.uniform(OX, W - OX); x.beginPath(); x.moveTo(bx - 4, FLOOR); x.lineTo(bx, FLOOR - r.uniform(2, 5)); x.lineTo(bx + 5, FLOOR); x.fill(); } + x.globalAlpha = 1; + }, + wall: function (x, r, T, side, ex) { + var d = side ? 1 : -1; x.fillStyle = T.wallHi; x.globalAlpha = 0.4; + for (var y = 80; y < FLOOR - 40; y += 90) { x.save(); x.translate(ex - d * 30, y); x.rotate(0.785); x.fillRect(-6, -6, 12, 12); x.restore(); } + x.globalAlpha = 1; + }, + fg: function (x, r, T) { + chain(x, -10, 30, 150, -10, -20, T.near, 6); chain(x, W + 10, 30, W - 150, -10, -20, T.near, 6); + x.fillStyle = T.near; x.beginPath(); x.ellipse(-10, H + 8, 90, 24, 0, 0, TAU); x.fill(); x.beginPath(); x.ellipse(W + 10, H + 8, 90, 24, 0, 0, TAU); x.fill(); + } + }; + + // dream spire (2d/lumen_moth): a sky of pale gold, a halo of light behind her, cloud banks, a floor of pale stone + ARCHI.spire = { + far: function (x, r, T) { + ART.glow(x, CX, 170, 330, T.glow[2], 0.3); + x.save(); x.globalCompositeOperation = 'lighter'; + for (var i = 0; i < 16; i++) { // rays from the halo + var a = i * TAU / 16 + 0.1, gr = x.createLinearGradient(CX, 170, CX + Math.cos(a) * 520, 170 + Math.sin(a) * 520); + gr.addColorStop(0, ART.rgba(T.light, 0.10)); gr.addColorStop(1, ART.rgba(T.light, 0)); + x.fillStyle = gr; x.beginPath(); x.moveTo(CX, 170); x.arc(CX, 170, 520, a - 0.05, a + 0.05); x.closePath(); x.fill(); + } + x.restore(); + x.strokeStyle = ART.rgba(T.light, 0.35); x.lineWidth = 3; x.beginPath(); x.arc(CX, 170, 128, 0, TAU); x.stroke(); + x.lineWidth = 1.2; x.beginPath(); x.arc(CX, 170, 142, 0, TAU); x.stroke(); + for (i = 0; i < 5; i++) { var cx0 = r.uniform(OX, W - OX), cy0 = r.uniform(250, 380); x.fillStyle = ART.rgba(T.fog, r.uniform(0.08, 0.16)); x.beginPath(); x.ellipse(cx0, cy0, r.uniform(90, 180), r.uniform(14, 26), 0, 0, TAU); x.fill(); } + hills(x, r, T.far, 436, 30, 70); + }, + mid: function (x, r, T) { + [[160, 270], [W - 160, 250]].forEach(function (p) { // two slender spires of pale stone + x.fillStyle = T.mid; x.beginPath(); x.moveTo(p[0] - 18, FLOOR); x.lineTo(p[0] - 9, p[1] + 40); x.lineTo(p[0], p[1]); x.lineTo(p[0] + 9, p[1] + 40); x.lineTo(p[0] + 18, FLOOR); x.closePath(); x.fill(); + ART.glow(x, p[0], p[1] + 6, 26, T.glow[2], 0.35); + }); + for (var i = 0; i < 8; i++) { var bx = r.uniform(OX + 40, W - OX - 40); x.fillStyle = ART.rgba(T.fog, 0.12); x.beginPath(); x.ellipse(bx, FLOOR - r.uniform(6, 30), r.uniform(60, 120), r.uniform(10, 18), 0, 0, TAU); x.fill(); } + }, + floor: function (x, r, T) { + x.fillStyle = ART.rgba(T.light, 0.18); + for (var px = OX + 30; px < W - OX; px += 64) x.fillRect(px, FLOOR + 3, 1.5, H - FLOOR); + }, + wall: function (x, r, T, side, ex) { + var d = side ? 1 : -1; x.strokeStyle = ART.rgba(T.light, 0.25); x.lineWidth = 1.5; + for (var y = 70; y < FLOOR - 30; y += 70) { x.beginPath(); x.arc(ex - d * 30, y, 9, 0, TAU); x.stroke(); } + }, + fg: function (x, r, T) { + x.fillStyle = ART.rgba(T.fog, 0.22); x.beginPath(); x.ellipse(-20, H + 4, 140, 30, 0, 0, TAU); x.fill(); x.beginPath(); x.ellipse(W + 20, H + 4, 140, 30, 0, 0, TAU); x.fill(); + } + }; + + // ---------- scene builder ---------- + function shafts(x, r, T, n) { + x.save(); x.globalCompositeOperation = 'lighter'; + for (var i = 0; i < n; i++) { + var top = T.glow[0] + r.uniform(-200, 200), wd = r.uniform(24, 70), sk = r.uniform(40, 110) * (top < CX ? 1 : -1); + var gr = x.createLinearGradient(0, ROOF, 0, FLOOR); + gr.addColorStop(0, ART.rgba(T.light, r.uniform(0.06, 0.12))); gr.addColorStop(0.7, ART.rgba(T.light, 0.025)); gr.addColorStop(1, ART.rgba(T.light, 0)); + x.fillStyle = gr; x.beginPath(); x.moveTo(top - wd / 2, ROOF); x.lineTo(top + wd / 2, ROOF); + x.lineTo(top + sk + wd * 1.4, FLOOR); x.lineTo(top + sk - wd * 1.4, FLOOR); x.closePath(); x.fill(); + } + x.restore(); + } + function fogBand(x, T, y0, y1, a) { + var gr = x.createLinearGradient(0, y0, 0, y1); + gr.addColorStop(0, ART.rgba(T.fog, 0)); gr.addColorStop(0.6, ART.rgba(T.fog, a)); gr.addColorStop(1, ART.rgba(T.fog, a * 0.4)); + x.fillStyle = gr; x.fillRect(0, y0, W, y1 - y0); + } + function walls(x, r, T, A) { + [0, 1].forEach(function (side) { + var x0 = side ? W - OX : 0, ex = side ? W - OX : OX, d = side ? 1 : -1; + var gr = x.createLinearGradient(side ? W : 0, 0, ex, 0); gr.addColorStop(0, T.near); gr.addColorStop(1, T.wall); + x.fillStyle = gr; x.fillRect(x0, 0, OX, H); + for (var y = ROOF; y < H; ) { // irregular stacked stones + var bh = r.uniform(22, 46); + for (var k = 0; k < 2; k++) { + var bx0 = x0 + k * OX / 2 + r.uniform(1, 4), bw = OX / 2 - r.uniform(3, 7); + x.fillStyle = 'rgba(255,255,255,' + r.uniform(0.015, 0.05).toFixed(3) + ')'; x.beginPath(); + ART.blobPath(x, [[bx0, y + 2], [bx0 + bw, y + 1 + r.uniform(0, 3)], [bx0 + bw - 1, y + bh - 2], [bx0 + 1, y + bh - 1]]); x.fill(); + } + y += bh; + } + A.wall(x, r, T, side, ex); + var sg = x.createLinearGradient(ex, 0, ex - d * 26, 0); sg.addColorStop(0, 'rgba(0,0,0,0.45)'); sg.addColorStop(1, 'rgba(0,0,0,0)'); + x.fillStyle = sg; x.fillRect(Math.min(ex, ex - d * 26), ROOF, 26, FLOOR - ROOF); // shadow cast into the room + x.fillStyle = T.wallHi; x.fillRect(ex - (side ? 0 : 2), ROOF, 2, FLOOR - ROOF); // lit lip + }); + } + function floor(x, r, T, A) { + var gr = x.createLinearGradient(0, FLOOR, 0, H); gr.addColorStop(0, T.floor); gr.addColorStop(1, T.near); + x.fillStyle = gr; x.fillRect(0, FLOOR, W, H - FLOOR); + var hg = x.createLinearGradient(0, FLOOR - 40, 0, FLOOR); // ground mist + hg.addColorStop(0, ART.rgba(T.fog, 0)); hg.addColorStop(1, ART.rgba(T.fog, 0.16)); + x.fillStyle = hg; x.fillRect(OX, FLOOR - 40, W - 2 * OX, 40); + x.fillStyle = T.floorTop; x.fillRect(OX, FLOOR, W - 2 * OX, 2); + x.fillStyle = 'rgba(0,0,0,0.55)'; x.fillRect(OX, FLOOR + 2, W - 2 * OX, 2); + A.floor(x, r, T); + } + // returns {bg, fg, T}: bg = sky .. walls (drawn first), fg = framing silhouettes + vignette (drawn over the figures) + ART.scene = function (doc, id) { + var T = TH[id] || TH['2d/needle_warden'], A = ARCHI[T.archi], r = new BB.RNG(T.seed); + var bg = doc.createElement('canvas'); bg.width = W; bg.height = H; + var x = bg.getContext('2d'); + var gr = x.createLinearGradient(0, 0, 0, H); gr.addColorStop(0, T.sky[0]); gr.addColorStop(0.55, T.sky[1]); gr.addColorStop(1, T.sky[2]); + x.fillStyle = gr; x.fillRect(0, 0, W, H); + ART.glow(x, T.glow[0], T.glow[1], 420, T.glow[2], 0.12); + for (var i = 0; i < 90; i++) { x.fillStyle = ART.rgba(T.mote, r.uniform(0.04, 0.18)); x.beginPath(); x.arc(r.uniform(0, W), r.uniform(0, FLOOR), r.uniform(0.5, 1.5), 0, TAU); x.fill(); } + A.far(x, r, T); + fogBand(x, T, 120, FLOOR, 0.22); + shafts(x, r, T, 4); + A.mid(x, r, T); + fogBand(x, T, 300, FLOOR, 0.10); + floor(x, r, T, A); + walls(x, r, T, A); + x.fillStyle = T.near; x.fillRect(0, 0, W, ROOF); + var fg = doc.createElement('canvas'); fg.width = W; fg.height = H; + var y = fg.getContext('2d'); + A.fg(y, new BB.RNG(T.seed + 1), T); + var vg = y.createRadialGradient(CX, H * 0.48, H * 0.42, CX, H * 0.48, W * 0.62); + vg.addColorStop(0, 'rgba(0,0,0,0)'); vg.addColorStop(1, 'rgba(0,0,0,0.55)'); + y.fillStyle = vg; y.fillRect(0, 0, W, H); + return { bg: bg, fg: fg, T: T }; + }; + ART.theme = function (id) { return TH[id] || TH['2d/needle_warden']; }; + + // ---------- ambient motes (function of t only) ---------- + ART.ambient = function (x, id, t) { + var T = ART.theme(id); + x.save(); x.globalCompositeOperation = 'lighter'; + for (var i = 0; i < 46; i++) { + var h1 = ART.hash(i * 3 + 1), h2 = ART.hash(i * 3 + 2), h3 = ART.hash(i * 3 + 3); + var span = FLOOR - ROOF + 40, sp = 8 + 22 * h2, yy = ((h1 * span + (T.moteUp ? -1 : 1) * t * sp) % span + span) % span; + var px = OX + h3 * (W - 2 * OX) + Math.sin(t * (0.4 + h1) + i) * 18, py = ROOF - 20 + yy; + var a = (0.25 + 0.35 * h2) * (0.6 + 0.4 * Math.sin(t * (1.5 + 2 * h3) + i * 1.3)), rr = 0.8 + 1.8 * h1; + x.fillStyle = ART.rgba(T.mote, a * 0.25); x.beginPath(); x.arc(px, py, rr * 3, 0, TAU); x.fill(); + x.fillStyle = ART.rgba(T.mote, a); x.beginPath(); x.arc(px, py, rr, 0, TAU); x.fill(); + } + x.restore(); + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/body_wanderer.js b/environments/games/web/games/hollowknight_remake/body_wanderer.js new file mode 100644 index 0000000000000000000000000000000000000000..f02cbd319af7cd8d274a79af1663222c7f4c2512 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/body_wanderer.js @@ -0,0 +1,205 @@ +// Body "wanderer": small 2D melee body - run, variable jump, dash, 3-way nail slash, pogo, focus-heal. +// Key semantics (proposal 4.3: keys are body-specific): +// A/D move W/S aim slash up/down Space jump (hold = higher) Shift dash J or LMB slash K hold = focus (heal) +(function (g) { + var BB = g.BB; + // [data] HeroController constants of the source game. Its counters count 50 Hz FixedUpdate steps; CLK.steps(n) turns + // n steps into seconds (clock.js), which the 60 Hz engine then samples. Speeds (u/s) and gravity (u/s^2) are unchanged. + var CLK = BB.HK_CLOCK; + var K = BB.WANDERER = { + RUN: 8.3, JUMP_V: 16.65, JUMP_T: CLK.steps(9), JUMP_T_MIN: CLK.steps(4), GRAV: 0.79 * 60, MAX_FALL: 20, + DASH_V: 20, DASH_T: 0.25, DASH_CD: 0.6, + ATK_T: 0.35, ATK_CD: 0.41, BOUNCE_V: 12, BOUNCE_T: 0.25, RECOIL_V: 3.75, RECOIL_T: CLK.steps(8), + HURT_V: 15, HURT_T: 0.2, INVUL: 1.3, HITSTOP: 0.25, + FOCUS_START: 0.25, FOCUS_DRAIN: 0.027, FOCUS_COST: 33, + W: 0.5, H: 1.281, // physics box 0.5 x 1.281, bottom = feet + PIVOT: 1.3905, // hero transform origin above the feet + HURT: { w: 0.455, h: 1.17, ox: 0.006, oy: -0.694 }, // HeroBox trigger, offset from the pivot (sprite faces -x) + ALT_RESET: 0.5, ATK_RECOVERY: 0.1, // Slash/AltSlash alternation reset; no dash in the first 0.1 s of a swing + SLASH_ON: CLK.steps(1), SLASH_OFF: CLK.steps(5), // NailSlash.FixedUpdate: poly on at step 1, off at step 5 + JUMP_Q: CLK.steps(2), ATK_Q: CLK.steps(5), DASH_Q: CLK.steps(10), // input queues: retried only while the key is held + LEDGE: CLK.steps(2), RECOIL_DOWN_V: 0, // ledge buffer (coyote); up-slash contact clamps the rise to 0 + MASKS: 5, NAIL: 5, SOUL_HIT: 11, SOUL_MAX: 99 // PlayerData defaults / HeroController.SoulGain + }; + // [data] nail colliders: PolygonCollider2D points (hit poly + clash "tink" poly) in the child's local space, + // child = Attacks/ at pos, scaled by NailSlash.scale; the hero sprite faces -x at scale +1. + var SLASH = { + side: { pos: [-0.01, -0.41], sc: [1.6011, 1.6452], + poly: [[-1.271, 0.741], [-1.915, 0.34], [-2.042, -0.175], [-1.674, -0.444], [-0.075, -0.642], [0.008, 0.968]], + tink: [[-1.271, 0.741], [-1.915, 0.34], [-2.042, -0.175], [-1.748, -0.487], [-0.156, -0.789], [0.211, 1.016]] }, + alt: { pos: [0.08, -0.436], sc: [1.257, 1.4224], + poly: [[-1.217, 0.981], [-2.39, 0.571], [-2.646, -0.079], [-2.124, -0.538], [-0.367, -0.693], [-0.243, 1.09]], + tink: [[-1.072, 1.028], [-2.306, 0.571], [-2.636, -0.052], [-2.088, -0.591], [-0.392, -0.881], [0.111, 0.999]] }, + up: { pos: [0, 0.69], sc: [1.15, 1.4], + poly: [[-0.471, 1.442], [0.472, 1.463], [1.082, 0.674], [1.148, -0.89], [-1.285, -0.866], [-1.072, 0.619]] }, + down: { pos: [0.16, -1.59], sc: [1.125, 1.28], + poly: [[1.278, 0.607], [1.119, -0.877], [0.588, -1.622], [-0.447, -1.646], [-1.07, -0.731], [-1.382, 0.637]] } + }; + BB.WANDERER_SLASH = SLASH; + + function Wanderer() {} + Wanderer.prototype.id = 'wanderer'; + Wanderer.prototype.NAIL = K.NAIL; // engine contract: damage per nail hit, hit-stop on being hit + Wanderer.prototype.HITSTOP = K.HITSTOP; + Wanderer.prototype.keys = { left: 'A', right: 'D', up: 'W', down: 'S', jump: 'Space', dash: 'Shift', attack: 'J|LMB', focus: 'K' }; + Wanderer.prototype.manual = [ + 'A/D move; Space jump (hold for height, release to cut it short)', + 'Shift dash (once per air time, 0.6 s cooldown, not during the first 0.1 s of a slash)', + 'side slashes alternate between two swings (reset after 0.5 s); early presses queue while held: jump 0.04 s, slash 0.1 s, dash 0.2 s', + 'J or LMB slash; hold W to slash up; in the air hold S to slash down - a downward hit on the boss or a bounceable attack bounces you up (pogo) and refreshes the air dash (not the dash cooldown)', + 'each hit on the boss stores 11 energy; hold K on the ground to spend 33 energy for +1 HP (~1.1 s; moving, leaving the ground or getting hit cancels it)' + ]; + + Wanderer.prototype.reset = function (c) { + this.x = 18.6; this.y = 0; this.vx = 0; this.vy = 0; this.facing = -1; + this.max_hp = K.MASKS; this.hp = K.MASKS; this.soul = 0; + this.grounded = true; this.airDash = true; this.coyote = 0; + this.jumping = false; this.jumpT = 0; this.cut = false; + this.jumpBuf = 0; this.atkBuf = 0; this.dashBuf = 0; this.time = 0; + this.dashT = 0; this.dashCd = 0; this.dashDir = -1; + this.atkT = 0; this.atkCd = 0; this.atkAge = 99; this.slashDir = 'side'; this.slashFacing = -1; this.slashHits = {}; + this.slashShape = 'side'; this.altAttack = false; this.altTime = -99; + this.bounceT = 0; this.recoilT = 0; this.recoilDir = 0; + this.hurtT = 0; this.hurtDir = 0; this.invul = 0; + this.focusT = -1; this.drained = 0; this.drainAcc = 0; + this.prev = {}; + }; + + Wanderer.prototype.box = function () { return { x: this.x, y: this.y + K.H / 2, w: K.W, h: K.H }; }; + Wanderer.prototype.hurtBox = function () { + var h = K.HURT; + return { x: this.x - h.ox * this.facing, y: this.y + K.PIVOT + h.oy, w: h.w, h: h.h }; + }; + Wanderer.prototype.centre = function () { return { x: this.x, y: this.y + K.H / 2 }; }; + // world-space slash polygons for shape `name` with facing `f` + Wanderer.prototype.slashPolys = function (name, f) { + var S = SLASH[name], m = -f, px = this.x, py = this.y + K.PIVOT; + function w(pts) { return pts.map(function (p) { return [px + m * (S.pos[0] + S.sc[0] * p[0]), py + S.pos[1] + S.sc[1] * p[1]]; }); } + var poly = w(S.poly); + return { pts: poly, tink: S.tink ? w(S.tink) : poly }; + }; + Wanderer.prototype.slashLive = function () { // the poly is enabled during [SLASH_ON, SLASH_OFF) of the swing + return this.atkT > 0 && this.atkAge > K.SLASH_ON - 1e-9 && this.atkAge < K.SLASH_OFF - 1e-9; + }; + // active slash: hit polygon, clash polygon and their bounding box {x, y, w, h}; null while the poly is off + Wanderer.prototype.slashBox = function () { + if (!this.slashLive()) return null; + var P = this.slashPolys(this.slashShape, this.slashFacing), l = 1e9, r = -1e9, lo = 1e9, hi = -1e9; + P.pts.forEach(function (p) { l = Math.min(l, p[0]); r = Math.max(r, p[0]); lo = Math.min(lo, p[1]); hi = Math.max(hi, p[1]); }); + return { x: (l + r) / 2, y: (lo + hi) / 2, w: r - l, h: hi - lo, pts: P.pts, tink: P.tink, dir: this.slashDir }; + }; + + Wanderer.prototype.update = function (c, inp) { + var dt = BB.DT, A = BB.ARENA, pv = this.prev, self = this; + function edge(k) { return inp[k] && !pv[k]; } + // queues (HeroController.LookForQueueInput): a press that can't act yet is retried while the key stays held + function queue(k, q, cur) { return edge(k) ? q + 1e-6 : inp[k] ? Math.max(0, cur - dt) : 0; } + this.jumpBuf = queue('jump', K.JUMP_Q, this.jumpBuf); + this.atkBuf = queue('attack', K.ATK_Q, this.atkBuf); + this.dashBuf = queue('dash', K.DASH_Q, this.dashBuf); + this.time += dt; this.atkAge += dt; + this.prev = { left: inp.left, right: inp.right, up: inp.up, down: inp.down, jump: inp.jump, dash: inp.dash, attack: inp.attack, focus: inp.focus }; + ['invul', 'atkCd', 'dashCd', 'atkT', 'coyote', 'recoilT'].forEach(function (k) { self[k] = Math.max(0, self[k] - dt); }); + + var dir = (inp.right ? 1 : 0) - (inp.left ? 1 : 0), gravity = true; + if (this.hurtT > 0) { // knock-back: no control + this.hurtT -= dt; this.vx = this.hurtDir * K.HURT_V; + } else if (this.dashT > 0) { + this.dashT -= dt; this.vx = this.dashDir * K.DASH_V; this.vy = 0; gravity = false; + } else { + if (this.focusT >= 0) { // focus (heal) + if (!inp.focus || !this.grounded || dir !== 0) this.focusT = -1; + else { + this.focusT += dt; + if (this.focusT > K.FOCUS_START) { + this.drainAcc += dt; + while (this.drainAcc >= K.FOCUS_DRAIN && this.soul > 0) { + this.drainAcc -= K.FOCUS_DRAIN; this.soul--; this.drained++; + if (this.drained >= K.FOCUS_COST) { + this.drained = 0; this.hp = Math.min(this.max_hp, this.hp + 1); c.emit('heal'); + if (this.hp >= this.max_hp || this.soul < K.FOCUS_COST) { this.focusT = -1; break; } + this.focusT = K.FOCUS_START; + } + } + } + } + } else if (inp.focus && this.grounded && dir === 0 && this.atkT <= 0 && this.soul >= K.FOCUS_COST && this.hp < this.max_hp) { + this.focusT = 0; this.drained = 0; this.drainAcc = 0; c.emit('focus'); + } + var focusing = this.focusT >= 0; + if (focusing) dir = 0; + this.vx = this.recoilT > 0 ? this.recoilDir * K.RECOIL_V : dir * K.RUN; + if (dir && this.atkT <= 0) this.facing = dir; + var swingLock = this.atkT > 0 && this.atkAge < K.ATK_RECOVERY - 1e-9; // CanDash: attack_time < ATTACK_RECOVERY_TIME + if (this.dashBuf > 0 && this.dashCd <= 0 && !focusing && !swingLock && (this.grounded || this.airDash)) { + this.dashBuf = 0; this.dashT = K.DASH_T; this.dashCd = K.DASH_CD; this.dashDir = dir || this.facing; this.facing = this.dashDir; + if (!this.grounded) this.airDash = false; + this.jumping = false; this.bounceT = 0; this.atkT = 0; + this.vx = this.dashDir * K.DASH_V; this.vy = 0; gravity = false; c.emit('dash'); + } else { + if (this.jumpBuf > 0 && (this.grounded || this.coyote > 0) && !focusing) { + this.jumpBuf = 0; this.coyote = 0; this.jumping = true; this.jumpT = 0; this.cut = true; this.bounceT = 0; c.emit('jump'); + } + if (this.bounceT > 0) { this.bounceT -= dt; this.vy = K.BOUNCE_V; gravity = false; } + else if (this.jumping) { + if ((inp.jump || this.jumpT < K.JUMP_T_MIN) && this.jumpT < K.JUMP_T) { this.vy = K.JUMP_V; this.jumpT += dt; gravity = false; } + else this.jumping = false; + } + if (this.cut && !inp.jump && !this.jumping && this.bounceT <= 0 && this.vy > 0) { this.vy = 0; this.cut = false; } + if (this.atkBuf > 0 && this.atkCd <= 0 && this.atkT <= 0 && !focusing) { + this.atkBuf = 0; this.atkT = K.ATK_T; this.atkCd = K.ATK_CD; this.atkAge = 0; this.slashHits = {}; + this.slashDir = inp.up ? 'up' : (inp.down && !this.grounded ? 'down' : 'side'); this.slashFacing = this.facing; + if (this.time - this.altTime > K.ALT_RESET) this.altAttack = false; // HeroController.Attack + if (this.slashDir === 'side') { this.slashShape = this.altAttack ? 'alt' : 'side'; this.altAttack = !this.altAttack; } + else this.slashShape = this.slashDir; + this.altTime = this.time; + c.emit('slash_' + this.slashDir); + } + } + } + if (gravity) this.vy = Math.max(this.vy - K.GRAV * dt, -K.MAX_FALL); + this.x += this.vx * dt; this.y += this.vy * dt; + var wasGround = this.grounded; + this.x = Math.min(A.W - K.W / 2, Math.max(K.W / 2, this.x)); + if (this.y <= 0) { + this.y = 0; if (this.vy < 0) this.vy = 0; this.grounded = true; this.airDash = true; + if (!wasGround) c.emit('land'); + } else this.grounded = false; + if (wasGround && !this.grounded && !this.jumping && this.bounceT <= 0) this.coyote = K.LEDGE; + if (this.y + K.H > A.H) { this.y = A.H - K.H; if (this.vy > 0) this.vy = 0; this.jumping = false; this.bounceT = 0; } + }; + + // slash connected with something solid: side -> push-back, up -> rise cut, down -> pogo (Bounce keeps the dash cooldown) + Wanderer.prototype.onSlashContact = function (c, kind) { + if (this.slashDir === 'down') { + this.bounceT = K.BOUNCE_T; this.vy = K.BOUNCE_V; this.jumping = false; this.cut = false; this.airDash = true; + c.emit('pogo'); + } else if (this.slashDir === 'side') { + this.recoilT = K.RECOIL_T; this.recoilDir = -this.slashFacing; + } else { + this.jumping = false; if (this.vy > K.RECOIL_DOWN_V) this.vy = K.RECOIL_DOWN_V; + } + if (kind === 'flesh') this.soul = Math.min(K.SOUL_MAX, this.soul + K.SOUL_HIT); + }; + + Wanderer.prototype.hurt = function (c, dmg, fromX) { + if (this.invul > 0 || this.hp <= 0) return false; + this.hp = Math.max(0, this.hp - dmg); this.invul = K.INVUL; + this.hurtT = K.HURT_T; this.hurtDir = this.x >= fromX ? 1 : -1; this.vy = 0; + this.dashT = 0; this.focusT = -1; this.jumping = false; this.bounceT = 0; this.atkT = 0; + c.emit('player_hit'); + return true; + }; + + Wanderer.prototype.state = function () { + var r = BB.r4; + return { + x: r(this.x), y: r(this.y), vx: r(this.vx), vy: r(this.vy), facing: this.facing, + hp: this.hp, max_hp: this.max_hp, soul: this.soul, grounded: this.grounded, + dashing: this.dashT > 0, dash_ready: this.dashCd <= 0 && (this.grounded || this.airDash), + attacking: this.atkT > 0, slash: this.slashLive() ? this.slashDir : null, + focusing: this.focusT >= 0, invul: r(this.invul), hurt: this.hurtT > 0 + }; + }; + BB.Wanderer = Wanderer; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/bosses/hollow_vessel.js b/environments/games/web/games/hollowknight_remake/bosses/hollow_vessel.js new file mode 100644 index 0000000000000000000000000000000000000000..e22b7ebac0f9b9c4ceca0ac7780820538288c099 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/bosses/hollow_vessel.js @@ -0,0 +1,272 @@ +// Boss "hollow_vessel" - hollow nail-bearer (2D). Behaviour follows the source fight's "IK Control" FSM (Idle walk + +// counter, Attack Choice V3, Air Dash?, To Attack?, Damage Response), its "Stun Control" (combo 9 in < 1 s, 12 hits +// max) and the blob cascades / balloons of "Shake Token Control" / "Spawn Balloon". Numbers: specs/hollow_vessel.spec.js. +// Pivot = middle of the feet (y = 0 on the floor); the source room is as wide as our arena, so x maps 1:1. +(function (g) { + var BB = g.BB; + var SPEC = BB.SPECS.hollow_vessel; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.ARENA, GRAV = 60; + var BW = 2.18, BH = 2.28; // [data] collider 1.75 x 1.82, [hand] x1.25 sprite scale + var XMIN = BW / 2 + 0.2, XMAX = A.W - BW / 2 - 0.2; + var GS = MV.jump.params.gravity_scale; // [data] Gravity 2.5 + var SHAKING = { cjump_antic: 1, cjump: 1, shake_antic: 1, shake_start: 1, shake: 1, shake_end: 1 }; + var ROLE = { + intro: 'idle', idle: 'idle', + jump_antic: 'telegraph', jump: 'active', land: 'recovery', + dstab_antic: 'telegraph', dstab_fall: 'active', dstab_land: 'active', dstab_recover: 'recovery', + dash_back: 'telegraph', dash_antic: 'telegraph', dash_antic3: 'telegraph', dash: 'active', dash_recover: 'recovery', fall: 'recovery', + ohead_antic: 'telegraph', ohead: 'active', ohead_recover: 'recovery', + evade_antic: 'telegraph', evade: 'active', evade_recover: 'recovery', + cjump_antic: 'idle', cjump: 'idle', shake_antic: 'telegraph', shake_start: 'active', shake: 'active', shake_end: 'recovery', + stun_air: 'recovery', stunned: 'recovery', stun_recover: 'recovery', dead: 'recovery' + }; + + function Vessel() {} + Vessel.prototype.id = 'hollow_vessel'; + BB.bossKit(Vessel.prototype, SPEC, ROLE); + + Vessel.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.max_hp = this.hp = Math.round(k.hp); + this.dmg = Math.max(1, Math.round(k.dmg)); + this.x = 9.0; this.y = 0; this.vx = 0; this.vy = 0; this.f = 1; this.air = false; this.gs = GS; // [hand] apart from the player spawn (x 18.6) + this.st = 'intro'; this.timer = 1.5; this.stT = 0; this.move = null; + this.track = {}; this.cycle = {}; this.hitFlash = 0; this.stamp = 0; + this.combo = 0; this.comboT = 0; this.total = 0; this.stuns = 0; + this.tokens = 0; this.doShake = false; this.angry = false; + this.intent = null; this.didAirDash = false; this.willEvade = false; this.willOhead = false; this.walk = 0; + this.blobs = []; this.balloons = []; this.balloonOn = false; this.balloonT = 0; this.bid = 0; + this.spawnT = 0; this.prevSpd = [0, 0, 0]; + }; + + // ---------- geometry ---------- + Vessel.prototype.bodyBox = function () { return { x: this.x, y: this.y + BH / 2, w: BW, h: BH }; }; + Vessel.prototype.hitTargets = function () { + var t = [{ id: 'boss', box: this.bodyBox() }]; + this.balloons.forEach(function (b) { if (b.fade <= 0) t.push({ id: 'balloon' + b.id, box: { x: b.x, y: b.y, w: 0.9, h: 0.9 } }); }); + return t; + }; + + // ---------- FSM helpers ---------- + Vessel.prototype.setCounter = function (c) { // [data] Set Counter: Idle Counter U(0.5, 0.75), evade 45 %, overhead 25 % + this.didAirDash = false; this.intent = null; this.move = null; this.gs = GS; + this.willEvade = c.rng.random() < MV.evade.params.chance; + this.willOhead = c.rng.random() < MV.overhead.params.chance; + this.walk = c.rng.uniform(0.5, 1.25) * (c.rng.random() < 0.5 ? -1 : 1); + this.go(c, 'idle', c.rng.uniform(0.5, 0.75) * this.k[SPEC.timing.idle.knob]); + }; + Vessel.prototype.attackChoice = function (c) { // [data] SendRandomEventV3 DOWNSTAB / JUMP / DASH + this.face(c); + var ev = this.pick(c, 'atk', ['DOWNSTAB', 'JUMP', 'DASH'], [1, 0.5, 1], [2, 1, 2], [3, 5, 3]); + if (ev === 'DOWNSTAB') return this.jumpAntic(c, 'dstab'); + if (ev === 'JUMP') return this.jumpAntic(c, 'jump'); + return this.dashChoice(c); + }; + Vessel.prototype.dashChoice = function (c) { // [data] Air Dash?: 30 % jump + air dash, 70 % ground dash + if (c.rng.random() < MV.air_dash.params.chance) return this.jumpAntic(c, 'airdash'); + this.face(c); this.move = 'dash'; + this.vx = -this.f * MV.dash.params.reverse; this.go(c, 'dash_back', MV.dash.params.antic[0]); + }; + Vessel.prototype.jumpAntic = function (c, intent) { + this.intent = intent; this.face(c); this.vx = 0; + this.go(c, 'jump_antic', this.tele(c, MV.jump.telegraph_scale), intent === 'dstab' ? 'downstab' : intent === 'airdash' ? 'air_dash' : 'jump'); + }; + Vessel.prototype.toAttack = function (c) { // [data] To Attack?: only when Angry and no air dash just now + if (this.angry && !this.didAirDash && c.rng.random() < 0.35) return this.dashChoice(c); + this.setCounter(c); + }; + Vessel.prototype.launch = function (vy, vx) { this.vy = vy; this.vx = vx; this.air = true; this.gs = GS; }; + + Vessel.prototype.update = function (c) { + var dt = BB.DT, st, P, b = c.body, dx = b.x - this.x; + this.flash(dt); + this.timer -= dt; this.stT += dt; + if (this.comboT > 0) { this.comboT -= dt; if (this.comboT <= 0) this.combo = 0; } + st = this.st; + if (st === 'dead') { this.vx = 0; } + else if (st === 'intro') { if (this.timer <= 0) { this.balloonOn = true; this.setCounter(c); } } // [data] Roar End sends START SPAWN + else if (st === 'idle') { + if (this.doShake) { this.doShake = false; this.face(c); this.vx = 0; this.go(c, 'cjump_antic', MV.jump.telegraph_scale, 'cascade'); } + else { + this.vx = this.walk * this.spd(); + if (this.willEvade && Math.abs(dx) < MV.evade.params.range) { + this.face(c); this.vx = 0; this.go(c, 'evade_antic', this.tele(c, MV.evade.telegraph_scale), 'evade'); + } else if (this.willOhead && Math.abs(dx) < MV.overhead.params.range[0] && b.y > this.y + BH * 0.6) { + this.face(c); this.vx = 0; this.go(c, 'ohead_antic', this.tele(c, MV.overhead.telegraph_scale), 'overhead'); + } else if (this.timer <= 0) this.attackChoice(c); + } + } + // jumps: plain / down-stab / air dash share the antic [data] + else if (st === 'jump_antic') { + if (this.timer <= 0) { + P = MV.jump.params; + var tx = this.intent === 'dstab' ? (b.x - this.x) * MV.downstab.params.aim_mult : (c.rng.uniform(1.6, 22.07) - this.x) * P.aim_mult; + this.launch(P.vy, tx); this.go(c, 'jump'); + } + } + else if (st === 'jump') { + if (this.intent === 'dstab' && this.y > MV.downstab.params.min_height && Math.abs(dx) < MV.downstab.params.range) { + this.vx = 0; this.vy = 0; this.gs = 0; this.go(c, 'dstab_antic', this.tele(c, MV.downstab.telegraph_scale)); + } else if (this.intent === 'airdash' && this.y > MV.air_dash.params.height && this.vy > 0) { + this.y = MV.air_dash.params.height; this.vx = 0; this.vy = 0; this.gs = 0; this.didAirDash = true; this.face(c); + this.go(c, 'dash_antic', this.tele(c, MV.air_dash.telegraph_scale)); + } + } + else if (st === 'land') { if (this.timer <= 0) this.toAttack(c); } + else if (st === 'dstab_antic') { if (this.timer <= 0) { this.gs = GS; this.vy = MV.downstab.params.fall_vy; this.go(c, 'dstab_fall'); } } + else if (st === 'dstab_land') { if (this.timer <= 0) this.go(c, 'dstab_recover', this.rec(MV.downstab.params.recover)); } + else if (st === 'dstab_recover') { if (this.timer <= 0) this.setCounter(c); } + // dash [data]: back-step 0.1 s at 20, antic 0.65 + 0.067, three attack clips 0.433 s at 32, recover 0.25 + else if (st === 'dash_back') { if (this.timer <= 0) { this.vx = 0; this.go(c, 'dash_antic', this.tele(c, MV.dash.params.antic[1])); } } + else if (st === 'dash_antic') { if (this.timer <= 0) this.go(c, 'dash_antic3', MV.dash.params.antic[2]); } + else if (st === 'dash_antic3') { if (this.timer <= 0) { this.vx = this.f * MV.dash.params.speed * this.spd(); this.go(c, 'dash', MV.dash.active); } } + else if (st === 'dash') { if (this.timer <= 0) { this.vx = 0; this.go(c, 'dash_recover', this.rec(MV.dash.params.recover)); } } + else if (st === 'dash_recover') { + if (this.timer <= 0) { + if (this.y > 0.01) { this.gs = GS; this.air = true; this.go(c, 'fall'); } + else this.setCounter(c); + } + } + else if (st === 'ohead_antic') { if (this.timer <= 0) this.go(c, 'ohead', MV.overhead.active); } + else if (st === 'ohead') { if (this.timer <= 0) this.go(c, 'ohead_recover', this.rec(MV.overhead.params.recover)); } + else if (st === 'ohead_recover') { if (this.timer <= 0) this.setCounter(c); } + else if (st === 'evade_antic') { if (this.timer <= 0) { this.vx = -this.f * MV.evade.params.speed; this.go(c, 'evade', MV.evade.params.time); } } + else if (st === 'evade') { if (this.timer <= 0) { this.vx = 0; this.go(c, 'evade_recover', this.rec(MV.evade.params.recover)); } } + else if (st === 'evade_recover') { if (this.timer <= 0) this.toAttack(c); } + // cascade [data]: jump to the centre (vy 50), Shake Antic 0.417, start 0.5, spawn 4.0, end 1.4 + else if (st === 'cjump_antic') { + if (this.timer <= 0) { P = MV.cascade.params; this.launch(P.jump_vy, (c.rng.uniform(P.centre[0], P.centre[1]) - this.x) * 1.25); this.go(c, 'cjump'); } + } + else if (st === 'shake_antic') { if (this.timer <= 0) this.go(c, 'shake_start', MV.cascade.params.start); } + else if (st === 'shake_start') { if (this.timer <= 0) { this.spawnT = 0; this.go(c, 'shake', MV.cascade.params.spawn); } } + else if (st === 'shake') { + this.spawnT -= dt; + if (this.spawnT <= 0) { this.spawnT += MV.cascade.params.pause / this.k.cascade_rate; this.cascadeWave(c); } + if (this.timer <= 0) this.go(c, 'shake_end', this.rec(MV.cascade.params.end)); + } + else if (st === 'shake_end') { if (this.timer <= 0) { this.balloonOn = true; this.setCounter(c); } } + // stagger [data]: push 10, vy 20, Stunned 3.0 s or until hit, recover 0.333 -> Attack Choice + else if (st === 'stunned') { if (this.timer <= 0) this.go(c, 'stun_recover', 0.333); } + else if (st === 'stun_recover') { if (this.timer <= 0) this.attackChoice(c); } + + // physics + if (this.air) this.vy -= GRAV * this.gs * dt; + this.x += this.vx * dt; this.y += this.vy * dt; + if (this.x < XMIN) { this.x = XMIN; if (this.vx < 0) this.vx = 0; } + if (this.x > XMAX) { this.x = XMAX; if (this.vx > 0) this.vx = 0; } + if (this.y + BH > A.H) { this.y = A.H - BH; if (this.vy > 0) this.vy = 0; } + if (this.y <= 0 && (this.air || this.vy < 0)) { + this.y = 0; this.vy = 0; var was = this.air; this.air = false; + if (was) this.land(c); + } else if (this.y > 0 && !this.air && this.gs > 0) this.air = true; + this.updateShots(c, dt); + }; + Vessel.prototype.updateShots = function (c, dt) { + var P = MV.balloon.params, b = c.body; + this.blobs = this.blobs.filter(function (o) { + if (o.warn > 0) { o.warn -= dt; return true; } + o.vy -= o.g * dt; o.x += o.vx * dt; o.y += o.vy * dt; + if (o.y <= MV.cascade.params.blob_r) { c.emit('boss_land', o.x, 0); return false; } + return o.x > -1 && o.x < A.W + 1; + }); + var maxB = Math.round(this.k.balloons); + if (this.balloonOn && maxB > 0 && this.st !== 'dead') { + this.balloonT -= dt; + if (this.balloonT <= 0) { + this.balloonT = c.rng.uniform(P.every[0], P.every[1]); + if (this.balloons.length < maxB && this.hp <= P.hp_gate * this.max_hp) this.balloons.push({ id: ++this.bid, x: c.rng.uniform(P.x[0], P.x[1]), y: c.rng.uniform(P.y[0], P.y[1]), vx: 0, vy: 0, fade: MV.balloon.telegraph_scale }); + } + } + var cx = b.x, cy = b.y + 0.64; + this.balloons.forEach(function (o) { // [data] ChaseObjectV2 speedMax 5, acceleration 10 + if (o.fade > 0) { o.fade -= dt; return; } + var ax = cx - o.x, ay = cy - o.y, l = Math.sqrt(ax * ax + ay * ay) || 1; + o.vx += ax / l * P.accel * dt; o.vy += ay / l * P.accel * dt; + var s = Math.sqrt(o.vx * o.vx + o.vy * o.vy); if (s > P.speed_max) { o.vx *= P.speed_max / s; o.vy *= P.speed_max / s; } + o.x = BB.clamp(o.x + o.vx * dt, 0.5, A.W - 0.5); o.y = BB.clamp(o.y + o.vy * dt, 0.5, A.H - 0.5); + }); + }; + Vessel.prototype.cascadeWave = function (c) { // [data] spawners L / R / U pick a speed from {5,8,11,14,17}, never the previous one + var P = MV.cascade.params, S = P.speeds, prev = this.prevSpd, out = this.blobs; + for (var i = 0; i < 3; i++) { + var v, guard = 0; do { v = S[c.rng.int(S.length)]; } while (v === prev[i] && ++guard < 16); + prev[i] = v; + if (i === 0) out.push({ x: 0.4, y: P.spawner_y, vx: v, vy: 0, g: P.blob_g, warn: 0 }); + else if (i === 1) out.push({ x: A.W - 0.4, y: P.spawner_y, vx: -v, vy: 0, g: P.blob_g, warn: 0 }); + else out.push({ x: A.W / 2 + (c.rng.random() < 0.5 ? -1 : 1) * v * 0.6, y: A.H - 0.4, vx: 0, vy: 0, g: P.blob_g, warn: 0.25 }); // [hand] roof drop line + } + }; + Vessel.prototype.land = function (c) { + var st = this.st, P = MV.downstab.params, out = this.blobs, x = this.x; + this.vx = 0; c.emit('boss_land', this.x, 0); + if (st === 'jump') this.go(c, 'land', this.rec(MV.jump.params.land)); + else if (st === 'dstab_fall') { + c.shake(0.6); c.emit('boss_land_hard', this.x, 0); + P.blobs.forEach(function (v) { out.push({ x: x, y: 0.5, vx: v, vy: P.blob_vy, g: MV.cascade.params.blob_g, warn: 0 }); }); + this.go(c, 'dstab_land', MV.downstab.active); + } + else if (st === 'fall') this.toAttack(c); + else if (st === 'cjump') { this.face(c); this.go(c, 'shake_antic', this.tele(c, MV.cascade.telegraph_scale)); } + else if (st === 'stun_air') this.go(c, 'stunned', 3.0); + else if (st !== 'dead') this.setCounter(c); + }; + Vessel.prototype.stunStart = function (c) { + this.stuns++; this.combo = 0; this.total = 0; this.intent = null; + this.face(c); this.vx = -this.f * 10; this.vy = 20; this.air = true; this.gs = GS; // [data] Stun Push 10, vy 20 + this.balloonOn = true; + this.go(c, 'stun_air', 0, null); c.emit('boss_stun', this.x, BH / 2); c.shake(0.6); + }; + + // ---------- combat interface ---------- + Vessel.prototype.hazards = function () { + var out = [], st = this.st, P; + if (st === 'dead') return out; + if (st !== 'stunned' && st !== 'stun_air' && st !== 'stun_recover') out.push({ kind: 'body', box: this.bodyBox() }); + if (st === 'dash') { P = MV.dash.params.slash; out.push({ kind: 'nail', box: { x: this.x + this.f * P[2], y: this.y + 1.1, w: P[0], h: P[1] } }); } + if (st === 'ohead') { P = MV.overhead.params.box; out.push({ kind: 'nail', box: { x: this.x + this.f * 0.4, y: this.y + P[2], w: P[0], h: P[1] } }); } + if (st === 'dstab_fall' || (st === 'dstab_land' && this.stT < 0.15)) out.push({ kind: 'nail', box: { x: this.x, y: this.y + 0.3, w: 1.4, h: 1.4 } }); + this.blobs.forEach(function (o) { if (o.warn <= 0) out.push({ kind: 'blob', circle: [o.x, o.y, MV.cascade.params.blob_r], fromX: o.x - (o.vx < 0 ? -1 : 1) }); }); + this.balloons.forEach(function (o) { if (o.fade <= 0) out.push({ kind: 'balloon', circle: [o.x, o.y, MV.balloon.params.radius], fromX: o.x }); }); + return out; + }; + Vessel.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + if (this.st === 'dead') return null; + if (tid !== 'boss') { // [data] balloons have 1 HP + var id = +tid.slice(7); + this.balloons = this.balloons.filter(function (o) { if (o.id === id) { c.emit('boss_hit', o.x, o.y); return false; } return true; }); + return 'flesh'; + } + this.hp -= dmg; this.hitFlash = 0.12; c.emit('boss_hit'); + if (this.hp <= 0) { this.hp = 0; this.st = 'dead'; this.blobs = []; this.balloons = []; this.vx = 0; c.emit('boss_dead', this.x, 1); c.shake(0.8); return 'flesh'; } + // [data] Shake Token Control: HP 370 / 220 / 110 of 525 (scaled with max HP); the first one also makes him Angry + var T = MV.cascade.params.thresholds; + while (this.tokens < T.length && this.hp <= T[this.tokens] * this.max_hp) { this.tokens++; this.angry = true; if (this.k.cascade >= 0.5) this.doShake = true; } + if (this.st === 'stunned') { this.go(c, 'stun_recover', 0.333); return 'flesh'; } + if (!SHAKING[this.st] && this.st !== 'stun_air' && this.st !== 'stun_recover') { + this.total++; this.combo++; this.comboT = 1.0; // [data] Combo Time 1.0 s + if ((this.combo >= Math.round(this.k.stun_combo) || this.total > Math.round(this.k.stun_total)) && this.stuns < 9) { this.stunStart(c); return 'flesh'; } // [data] Hit Max is compared before counting: 13th hit (wiki 13 / 9 / 9) + } + if (this.st === 'idle' && !this.doShake) { // [data] Damage Response: EVADE / JUMP / DASH / FINISHED + var r = c.rng.pick([0.3, 0.2, 0.3, 0.2]); + if (r === 0) { this.face(c); this.vx = 0; this.go(c, 'evade_antic', this.tele(c, MV.evade.telegraph_scale), 'evade'); } + else if (r === 1) this.jumpAntic(c, 'jump'); + else if (r === 2) this.dashChoice(c); + } + return 'flesh'; + }; + Vessel.prototype.state = function () { + var r = BB.r4, role = this.role(); + var hz = this.blobs.map(function (o) { return { kind: 'blob', x: r(o.x), y: r(o.y), vx: r(o.vx), vy: r(o.vy), warn: r(Math.max(0, o.warn)) }; }) + .concat(this.balloons.map(function (o) { return { kind: 'balloon', x: r(o.x), y: r(o.y), warn: r(Math.max(0, o.fade)) }; })); + return { + x: r(this.x), y: r(this.y), vx: r(this.vx), vy: r(this.vy), facing: this.f, + hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: this.move, + telegraph_left: role === 'telegraph' ? r(Math.max(0, this.timer)) : 0, aim_deg: null, + escalated: this.angry, staggers: this.stuns, hazards: hz + }; + }; + BB.HollowVessel = Vessel; + BB.CASES = BB.CASES || {}; + BB.CASES['2d/hollow_vessel'] = { title: 'Orange-Ooze Berserker', Body: BB.Wanderer, Boss: Vessel, arena: 'ash_well' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/bosses/iron_bulwark.js b/environments/games/web/games/hollowknight_remake/bosses/iron_bulwark.js new file mode 100644 index 0000000000000000000000000000000000000000..3955a2882003237183e252257228b6c1c564a706 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/bosses/iron_bulwark.js @@ -0,0 +1,297 @@ +// Boss "iron_bulwark" - armoured mace-bearer (2D). Behaviour follows the source fight's "FalseyControl" FSM and +// "Check_Health" (armour that resets every stage, a soft rider exposed after each break); every move number comes +// from specs/iron_bulwark.spec.js. Pivot = the middle of his feet (y = 0 on the floor). +// Horizontal source distances / speeds are multiplied by SX (source pivot range 27 u -> 19.3 u here) [hand]. +(function (g) { + var BB = g.BB; + var SPEC = BB.SPECS.iron_bulwark; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.ARENA, SX = 0.715, CLK = BB.HK_CLOCK; + var GRAV = 60; // [data] Physics2D gravity + var BW = 4.37, BH = 5.04, HALF = BW / 2; // [data] collider 3.36 x 3.88 at scale 1.3 + var XMIN = HALF, XMAX = A.W - HALF, MIDX = A.W / 2; // [data] rage jumps to the room centre + var HEAD = { w: 1.6, h: 1.71 }; // [data] head collider + var LOW = { stun_land: 1, stun_roll: 1, stun_pause: 1, stun_open: 1, opened: 1, stun_fail: 1, head_recover: 1, final_down: 1 }; + var ROLE = { + intro: 'idle', idle: 'idle', turn: 'idle', + leap_antic: 'telegraph', leap: 'active', leap_land: 'recovery', + ja_antic: 'telegraph', ja_air: 'active', ja_slam: 'active', ja_recoil: 'recovery', + smash_jump: 'idle', smash_antic: 'telegraph', smash: 'active', smash_recover: 'recovery', + run_antic: 'telegraph', run: 'active', + stun_air: 'recovery', stun_land: 'recovery', stun_roll: 'recovery', stun_pause: 'recovery', stun_open: 'recovery', + opened: 'recovery', stun_fail: 'recovery', head_recover: 'recovery', rage_jump: 'idle', + rage_antic: 'telegraph', rage: 'active', rage_recover: 'recovery', final_leap: 'idle', final_down: 'recovery', dead: 'recovery' + }; + + function Bulwark() {} + Bulwark.prototype.id = 'iron_bulwark'; + BB.bossKit(Bulwark.prototype, SPEC, ROLE); + + Bulwark.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.armorMax = Math.round(k.armor); this.headMax = Math.round(k.head); + // [wiki] 3 armour stages + 4 rider stages (the last one after the floor collapse); hp = what is left of all of them. + // stages = armour stages before the collapse: 3 in the source (normal / hard); the easy tier fights one cycle (see spec) + this.stages = Math.round(k.stages); + this.max_hp = this.hp = this.stages * this.armorMax + (this.stages + 1) * this.headMax; + this.armor = this.armorMax; this.headPool = 4 * this.headMax; this.headStage = 0; + this.dmg = Math.max(1, Math.round(k.dmg)); + this.x = 5.5; this.y = 0; this.vx = 0; this.vy = 0; this.f = 1; this.air = false; this.damp = true; + this.st = 'intro'; this.timer = 1.0; this.stT = 0; this.move = null; + // heads = completed maggot stages (= FSM Stunned Amount); staggers = stage of the current armour (1..3) for the HUD; + // redo = the armour was refilled by a failed stun (Stun Fail): breaking it again is not progress, hp does not move + this.staggers = 0; this.heads = 0; this.redo = false; this.final = false; + this.turns = 0; this.firstPause = true; this.jumpCount = 0; this.slamRow = 0; this.jaRow = 0; + this.barrels = []; this.waves = []; this.slamSide = 1; this.slamN = 0; this.rageStage = 0; + this.track = {}; this.cycle = {}; this.hitFlash = 0; this.stamp = 0; + }; + + // ---------- geometry ---------- + Bulwark.prototype.bodyBox = function () { + return LOW[this.st] ? { x: this.x, y: this.y + 1.6, w: BW, h: 3.2 } : { x: this.x + 0.07 * this.f, y: this.y + BH / 2, w: BW, h: BH }; + }; + Bulwark.prototype.headBox = function () { + return { x: this.x + this.f * (HALF + 0.3), y: this.y + HEAD.h / 2, w: HEAD.w, h: HEAD.h }; + }; + Bulwark.prototype.headOpen = function () { return this.st === 'opened'; }; // [data] only Opened moves the Head in + Bulwark.prototype.hitTargets = function () { + var t = []; + if (this.headOpen()) t.push({ id: 'head', box: this.headBox() }); + t.push({ id: 'armor', box: this.bodyBox() }); + return t; + }; + Bulwark.prototype.maceBox = function (side) { // [data] hitter 5.92 x 2.55 at (3.23, -3.02), scale 1.3 + var P = MV.smash.params.mace; + return { x: this.x + side * P[2] * 1.3 * SX, y: this.y + 1.66, w: P[0] * 1.3 * SX, h: P[1] * 1.3 }; + }; + + // ---------- FSM ---------- + Bulwark.prototype.toIdle = function (c) { + this.move = null; this.vx = 0; + this.go(c, 'idle', 1.0 * this.k[SPEC.timing.idle.knob]); // [data] Idle 1.0 s (Idle Min = Max = 1.0) + }; + Bulwark.prototype.choose = function (c) { + var dx = c.body.x - this.x; + this.face(c); + this.turns = 0; // [data] Move Choice: Turns = 0 + if (Math.abs(dx) > MV.charge.params.trigger_dist * SX) return this.go(c, 'run_antic', this.tele(c, MV.charge.telegraph_scale), 'charge'); + // [data] Move Choice: SendRandomEvent SMASH / JUMP ATTACK / JUMP 1:1:1; a choice that is not allowed RETURNs to + // Move Choice and draws again. JUMP needs Jump Count 0 (a slam or jump attack resets it, so never two plain leaps + // in a row) and Stunned Amount != 2 (no plain leaps in the last armour stage); SMASH needs Slam In A Row <= 2; + // JUMP ATTACK needs JA In A Row <= 3. + var ev = null, guard = 0; + while (!ev && guard++ < 16) { + ev = ['SMASH', 'JA', 'JUMP'][c.rng.int(3)]; + if (ev === 'JUMP' && (this.jumpCount > 0 || this.heads === 2)) ev = null; + else if (ev === 'SMASH' && this.slamRow > 2) ev = null; + else if (ev === 'JA' && this.jaRow > 3) ev = null; + } + if (!ev) ev = 'SMASH'; + if (ev === 'SMASH') { this.slamRow++; this.jaRow = 0; this.jumpCount = 0; } + else if (ev === 'JA') { this.jaRow++; this.slamRow = 0; this.jumpCount = 0; } + else this.jumpCount++; + if (ev === 'SMASH') return this.smashJump(c); + if (ev === 'JA') return this.go(c, 'ja_antic', this.tele(c, MV.bludgeon.telegraph_scale), 'bludgeon'); + return this.go(c, 'leap_antic', this.tele(c, MV.leap.telegraph_scale), 'leap'); + }; + Bulwark.prototype.launch = function (vy, vx) { this.vy = vy; this.vx = vx; this.air = true; this.damp = true; }; + Bulwark.prototype.leapVx = function (c, offset, mult, max) { + var hx = BB.clamp(c.body.x, XMIN, XMAX) - this.f * offset; + return BB.clamp((hx - this.x) * mult, -max, max); + }; + Bulwark.prototype.smashJump = function (c) { + var P = MV.smash.params, away = c.body.x > this.x ? -1 : 1, room = away < 0 ? this.x - XMIN : XMAX - this.x; + this.move = 'smash'; + if (room < P.wall_skip * SX) { this.face(c); return this.go(c, 'smash_antic', this.tele(c, MV.smash.telegraph_scale)); } // [data] wall near: no back-jump + var tx = BB.clamp(c.body.x + away * c.rng.uniform(P.back_jump[0], P.back_jump[1]) * SX, XMIN, XMAX); + this.launch(P.back_jump_vy, (tx - this.x) / 1.22); // 1.22 s = air time of a vy 105 jump under the damped gravity + this.go(c, 'smash_jump', 0); + }; + Bulwark.prototype.spawnBarrels = function (c, range) { + var n = Math.round((range[0] + c.rng.int(range[1] - range[0] + 1)) * this.k.barrels); + for (var i = 0; i < n; i++) { + this.barrels.push({ x: c.rng.uniform(1.0, A.W - 1.0), y: A.H - 0.6, vy: 0, warn: this.tele(c, MV.barrel.telegraph_scale) + i * 0.3 }); + } + }; + // [data] after the 3rd rage: JA Antic 2 -> leap toward Final Point X (34.0 in the 13.2..44.3 room) -> Floor Break; the + // floor gives way, he lands below (Death Land 2.0 s), opens (Stun Open 0.333 s) and the maggot stays out until killed + // (Opened 2). [hand] here the arena floor stays: he lands where he leapt and lies open. + Bulwark.prototype.finalLeap = function (c) { + var FX = BB.clamp((34.0 - 13.18) / (44.27 - 13.18) * A.W, XMIN, XMAX); + this.barrels = []; this.waves = []; this.move = null; this.face(c); this.final = true; + this.launch(90, (FX - this.x) * 0.76 / 1.17); this.go(c, 'final_leap'); + }; + // [data] barrel tables are switched by To Phase 2 / To Phase 3, i.e. after each rage + Bulwark.prototype.stage = function () { return Math.min(2, this.rageStage || 0); }; + + Bulwark.prototype.update = function (c) { + var dt = BB.DT, P; + this.flash(dt); + this.timer -= dt; this.stT += dt; + var st = this.st; + if (st === 'dead') { this.vx = 0; } + else if (st === 'intro') { if (this.timer <= 0) this.toIdle(c); } + else if (st === 'idle') { + var side = c.body.x > this.x ? 1 : -1; + if (side !== this.f) { // [data] Idle: TURN L / TURN R + if (this.turns >= 3) this.choose(c); // [data] Turn: Turns == 3 -> Move Choice + else { this.turns++; this.f = side; this.go(c, 'turn', 0.167); } // [data] Turn clip 2 f @ 12 fps + } else if (this.timer <= 0) this.choose(c); + } + else if (st === 'turn') { if (this.timer <= 0) this.toIdle(c); } + // leap + else if (st === 'leap_antic') { + if (this.timer <= 0) { + P = MV.leap.params; var vx; + if (c.rng.random() < 0.5) vx = this.leapVx(c, 0, P.vx_mult, P.vx_max * SX); // [data] TOWARDS + else { var dir = c.rng.random() < 0.5 ? -1 : 1; vx = dir * c.rng.uniform(5, P.vx_max) * SX; } // [data] RANDOM + this.launch(P.vy, vx); this.go(c, 'leap'); + } + } + else if (st === 'ja_antic') { + if (this.timer <= 0) { P = MV.bludgeon.params; this.launch(P.vy, this.leapVx(c, P.aim_offset * SX, P.vx_mult, 12 * SX)); this.go(c, 'ja_air'); } + } + else if (st === 'ja_slam') { if (this.timer <= 0) { this.vx = -this.f * 3 * SX / 0.167; this.go(c, 'ja_recoil', this.rec(MV.bludgeon.params.recoil[0] + MV.bludgeon.params.recoil[1])); } } + else if (st === 'ja_recoil') { if (this.stT > MV.bludgeon.params.recoil[0]) this.vx = 0; if (this.timer <= 0) this.toIdle(c); } + else if (st === 'leap_land') { if (this.timer <= 0) this.toIdle(c); } + // smash + else if (st === 'smash_antic') { + if (this.timer <= 0) { + this.go(c, 'smash', MV.smash.active); + P = MV.smash.params; c.shake(0.7); c.emit('boss_land_hard', this.x + this.f * P.wave_x * SX, 0); + this.waves.push({ x: this.x + this.f * P.wave_x * SX, dir: this.f }); + this.spawnBarrels(c, P.barrels_by_stage[this.stage()]); + } + } + else if (st === 'smash') { if (this.timer <= 0) this.go(c, 'smash_recover', this.rec(MV.smash.params.recover)); } + else if (st === 'smash_recover') { if (this.timer <= 0) this.toIdle(c); } + // run + else if (st === 'run_antic') { if (this.timer <= 0) this.go(c, 'run', 3.0); } + else if (st === 'run') { + this.face(c); this.vx = this.f * MV.charge.params.speed * SX * this.spd(); + if (Math.abs(c.body.x - this.x) < MV.charge.params.stop_dist * SX || this.timer <= 0 || this.x <= XMIN + 0.05 || this.x >= XMAX - 0.05) { + this.vx = 0; this.go(c, 'ja_antic', this.tele(c, MV.bludgeon.telegraph_scale), 'bludgeon'); + } + } + // stagger [data]: land 0.5, roll 0.333, pause 1.2 (2.5 the first time), open 0.333, opened 5.0 + else if (st === 'stun_land') { if (this.timer <= 0) this.go(c, 'stun_roll', 0.333); } + else if (st === 'stun_roll') { if (this.timer <= 0) { this.go(c, 'stun_pause', this.firstPause ? 2.5 : 1.2); this.firstPause = false; } } + else if (st === 'stun_pause') { if (this.timer <= 0) this.go(c, 'stun_open', 0.333); } + else if (st === 'stun_open') { if (this.timer <= 0) this.go(c, 'opened', this.k.head_window); } // [data] Opened: Wait 5.0 -> STUN FAIL + else if (st === 'opened') { if (this.timer <= 0) this.go(c, 'stun_fail', 0.5); } + else if (st === 'stun_fail') { if (this.timer <= 0) { this.armor = this.armorMax; this.redo = true; this.toIdle(c); } } // [data] armour already reset to Recover HP 65 + else if (st === 'head_recover') { + if (this.timer <= 0) { + this.armor = this.armorMax; + this.move = 'rage'; this.face(c); this.launch(90, (MIDX - this.x) / 1.17); this.go(c, 'rage_jump'); + } + } + else if (st === 'rage_antic') { if (this.timer <= 0) { this.slamN = 0; this.slamSide = this.f; this.go(c, 'rage', MV.rage.params.slam_time); } } + else if (st === 'final_down') { this.vx = 0; if (this.timer <= 0) this.go(c, 'opened', 1e9); } // [data] Death Land 2.0 + Death Open 0.333 s + else if (st === 'rage') { + if (this.timer <= 0) { + this.slamN++; c.shake(0.35); c.emit('boss_land_hard', this.x + this.slamSide * 3, 0); + if (this.slamN >= MV.rage.params.slams) { + this.rageStage = Math.min(2, this.rageStage + 1); // [data] To Phase 2 / To Phase 3 + if (this.heads >= this.stages) return this.finalLeap(c); // [data] Rage Check (Stunned Amount 3) BREAK2 -> JA Antic 2 + this.go(c, 'rage_recover', this.rec(MV.rage.params.recover)); + } + else { this.slamSide = -this.slamSide; this.timer = MV.rage.params.slam_time; } + } + } + else if (st === 'rage_recover') { if (this.timer <= 0) this.toIdle(c); } + + // physics: [data] gravity scale 0.125 with the rise damped x0.85 and the fall sped up x1.15 every 0.02 s + if (this.air) { + if (this.damp) { + this.vy -= GRAV * MV.leap.params.gravity_scale * dt; + this.vy *= this.vy > 0 ? CLK.perStep(MV.leap.params.rise_damp) : CLK.perStep(MV.leap.params.fall_damp); + if (this.vy < -90) this.vy = -90; + } else this.vy -= GRAV * dt; + } + this.x += this.vx * dt; this.y += this.vy * dt; + if (this.x < XMIN) { this.x = XMIN; if (this.vx < 0) this.vx = 0; } + if (this.x > XMAX) { this.x = XMAX; if (this.vx > 0) this.vx = 0; } + if (this.y + BH > A.H) { this.y = A.H - BH; if (this.vy > 0) this.vy = 0; } + if (this.y <= 0 && (this.air || this.vy < 0)) { + this.y = 0; this.vy = 0; var was = this.air; this.air = false; + if (was) this.land(c); + } + // hazards + var self = this; + this.waves = this.waves.filter(function (w) { w.x += w.dir * MV.smash.params.wave_speed * SX * self.spd() * dt; return w.x > 0.3 && w.x < A.W - 0.3; }); + this.barrels = this.barrels.filter(function (b) { + if (b.warn > 0) { b.warn -= dt; return true; } + b.vy -= GRAV * MV.barrel.params.gravity_scale * dt; b.y += b.vy * dt; + if (b.y <= MV.barrel.params.radius) { c.emit('boss_land', b.x, 0); return false; } + return true; + }); + }; + Bulwark.prototype.land = function (c) { + var st = this.st; + this.vx = 0; c.emit('boss_land_hard', this.x, 0); c.shake(0.45); + if (st === 'leap') this.go(c, 'leap_land', this.rec(MV.leap.params.land)); + else if (st === 'ja_air') { + this.go(c, 'ja_slam', MV.bludgeon.active); c.shake(0.6); + this.spawnBarrels(c, MV.bludgeon.params.barrels_by_stage[this.stage()]); + } + else if (st === 'smash_jump') { this.face(c); this.go(c, 'smash_antic', this.tele(c, MV.smash.telegraph_scale)); } + else if (st === 'stun_air') this.go(c, 'stun_land', 0.5); + else if (st === 'rage_jump') { this.face(c); this.go(c, 'rage_antic', this.tele(c, MV.rage.telegraph_scale)); this.spawnBarrels(c, [MV.rage.params.barrels, MV.rage.params.barrels]); } + else if (st === 'final_leap') { this.go(c, 'final_down', 2.333); c.shake(0.9); c.emit('boss_stun', this.x, BH / 2); } + else if (st !== 'dead') this.toIdle(c); + }; + Bulwark.prototype.stunStart = function (c) { + this.staggers = Math.min(this.stages, this.heads + 1); this.redo = false; this.move = null; this.barrels = []; this.waves = []; + var away = c.body.x > this.x ? -1 : 1; + this.f = -away; // he falls on his back, the rider toward the player + this.vx = away * 10 * SX; this.vy = 20; this.air = true; this.damp = false; // [data] stun push 10, vy 20 + this.go(c, 'stun_air'); c.emit('boss_stun', this.x, BH / 2); c.shake(0.7); + }; + + // ---------- combat interface ---------- + Bulwark.prototype.hazards = function () { + var out = [], st = this.st; + if (st === 'dead') return out; + if (!LOW[st] && st !== 'stun_air') out.push({ kind: 'body', box: this.bodyBox() }); + if (st === 'ja_air' && this.vy < 0) out.push({ kind: 'mace', box: { x: this.x + this.f * 2.6, y: this.y + 2.5, w: 2.8, h: 3.0 } }); + if (st === 'ja_slam' || st === 'smash') out.push({ kind: 'mace', box: this.maceBox(this.f) }); + if (st === 'rage' && this.timer < 0.12) out.push({ kind: 'mace', box: this.maceBox(this.slamSide) }); + this.waves.forEach(function (w) { out.push({ kind: 'shockwave', box: { x: w.x, y: 0.7, w: 1.0, h: 1.4 }, fromX: w.x - w.dir }); }); + this.barrels.forEach(function (b) { if (b.warn <= 0) out.push({ kind: 'barrel', circle: [b.x, b.y, MV.barrel.params.radius], fromX: b.x }); }); + return out; + }; + Bulwark.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + if (this.st === 'dead') return null; + if (tid === 'head') { + if (!this.headOpen()) return null; + var d = Math.min(dmg, this.headMax - this.headStage); + this.hp -= d; this.headStage += d; this.hitFlash = 0.12; + c.emit('boss_hit', this.headBox().x, this.headBox().y); + if (this.hp <= 0) { this.hp = 0; this.st = 'dead'; this.barrels = []; this.waves = []; c.emit('boss_dead', this.x, 1); c.shake(0.8); return 'flesh'; } + if (this.headStage >= this.headMax) { this.headStage = 0; this.heads++; this.go(c, 'head_recover', 1.0); } // [data] Recover: Stunned Amount + 1; 0.5 + Idle Pause 0.5 + return 'flesh'; + } + // armour: takes damage, gives no soul [wiki]; it is inert while he is down + if (LOW[this.st] || this.st === 'stun_air') { c.emit('tink', this.x, 2); return 'tink'; } + var a = Math.min(dmg, this.armor); + this.armor -= a; if (!this.redo && this.heads < this.stages) this.hp -= a; this.hitFlash = 0.12; // [wiki] 355 = 3 armour + 4 head stages: a refilled (failed-stun) or post-collapse shell is not new progress + c.emit('boss_hit'); + if (this.armor <= 0) this.stunStart(c); + return 'armor'; + }; + Bulwark.prototype.state = function () { + var r = BB.r4, role = this.role(); + var hz = this.barrels.map(function (b) { return { kind: 'barrel', x: r(b.x), y: r(b.y), warn: r(Math.max(0, b.warn)) }; }) + .concat(this.waves.map(function (w) { return { kind: 'shockwave', x: r(w.x), y: 0, dir: w.dir }; })); + return { + x: r(this.x), y: r(this.y), vx: r(this.vx), vy: r(this.vy), facing: this.f, + hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: this.move, + telegraph_left: role === 'telegraph' ? r(Math.max(0, this.timer)) : 0, aim_deg: null, + escalated: this.heads > 0, staggers: this.staggers, heads: this.heads, stages: this.stages, final: this.final, armor: this.armor, head_open: this.headOpen(), hazards: hz + }; + }; + BB.IronBulwark = Bulwark; + BB.CASES = BB.CASES || {}; + BB.CASES['2d/iron_bulwark'] = { title: 'Iron-Bell Mace Soldier', Body: BB.Wanderer, Boss: Bulwark, arena: 'iron_hall' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/bosses/lumen_moth.js b/environments/games/web/games/hollowknight_remake/bosses/lumen_moth.js new file mode 100644 index 0000000000000000000000000000000000000000..16b22f10c20983651a257c64c587b5b468dd34df --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/bosses/lumen_moth.js @@ -0,0 +1,485 @@ +// Boss "lumen_moth" - radiant moth deity (2D). Source fight: The Radiance (Hollow Knight, Dream No More). +// There is no game-data dump of this fight (specs/lumen_moth.spec.js header): the attack list, counts, phase damage +// shares and mask damage follow the wiki / guide descriptions [web]; state names follow the game's own FSM names as +// patched by a Godhome mod (Attack Choices "A1 Choice" / "A2 Choice", Attack Commands "Orb Antic", "Nail Fan", +// "EB 1".., "Beam Sweep L/R", Phase Control) [mod]; every timing, speed and size is [hand] and lives in the spec. +// She floats: (x, y) is the centre of her body, y up. She has no contact damage; every hazard is a projectile, a +// beam, the spike floor or the abyss. She is fought with the Channelled Nail (13 per hit, the k.nail knob): the +// pale_vessel preset, since the Radiance follows the Hollow Knight in the same run; the source's 1700 HP is sized for it. +// Terrain (deviation): the shared body only knows one flat floor, so the source's platform phase becomes four +// floor-level footholds with void between them - the void is a floor hazard whose knock-back throws the player onto +// the nearest foothold - and the final climb is compressed into her descent under the big beam. +(function (g) { + var BB = g.BB; + var SPEC = BB.SPECS.lumen_moth; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.ARENA, W = A.W, H = A.H, TAU = Math.PI * 2; + var BW = 1.7, BH = 2.4; // [hand] her core (the nail's target box) + var SC = MV.scream.params, TP = MV.teleport.params; + var SHARE = SC.shares, SHARE_SUM = SHARE[0] + SHARE[1] + SHARE[2] + SHARE[3]; + var CHOICE = { // [mod] A1 Choice (phases 1-2) / A2 Choice (abyss phase) + 1: ['ORBS', 'SWORD_BURST', 'SWORD_RAIN', 'SWORD_WALL', 'BEAM_BURST', 'BEAM_SWEEP'], + 4: ['ORBS', 'SWORD_BURST', 'SWORD_WALL', 'BEAM_BURST', 'BEAM_SWEEP'] + }; + var ROLE = { + intro: 'idle', idle: 'idle', tele_out: 'idle', tele_in: 'idle', + orbs_antic: 'telegraph', orbs: 'active', orbs_recover: 'recovery', + burst_antic: 'telegraph', burst: 'active', burst_recover: 'recovery', + rain_antic: 'telegraph', rain: 'active', rain_recover: 'recovery', + wall_antic: 'telegraph', wall: 'active', wall_recover: 'recovery', + beam_antic: 'telegraph', beam: 'active', beam_recover: 'recovery', + sweep_antic: 'telegraph', sweep: 'active', sweep_recover: 'recovery', + scream: 'recovery', glide: 'idle', centre: 'active', stagger: 'recovery', abyss_form: 'telegraph', rise: 'idle', + final_glide: 'idle', final_beam: 'active', final_sink: 'recovery', exposed: 'recovery', dead: 'recovery' + }; + var HIDDEN = { tele_out: 1, tele_in: 1 }; + var INVULN = { intro: 1, scream: 1, glide: 1, abyss_form: 1, rise: 1, final_glide: 1, final_beam: 1, final_sink: 1 }; + + function Moth() {} + Moth.prototype.id = 'lumen_moth'; + BB.bossKit(Moth.prototype, SPEC, ROLE); + + Moth.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.fightHP = Math.round(k.hp); this.finalHP = SC.final_hp; + this.max_hp = this.hp = this.fightHP + this.finalHP; + this.dmg = Math.max(1, Math.round(k.dmg)); this.floorDmg = Math.max(1, Math.round(k.floor_dmg)); this.nail = Math.round(k.nail); + var cut = 0; this.cuts = SHARE.map(function (s) { cut += s; return Math.round(cut / SHARE_SUM * this.fightHP); }, this); + this.x = W / 2; this.y = SC.intro_from; this.vx = 0; this.vy = 0; this.f = -1; + this.st = 'intro'; this.timer = SC.intro; this.stT = 0; this.move = null; this.next = null; + this.phase = 1; this.pending = 1; this.track = {}; this.cycle = {}; this.hitFlash = 0; this.stamp = 0; + this.orbs = []; this.swords = []; this.beams = []; this.bigs = []; this.sweep = null; + this.spikes = null; this.spikeT = MV.spikes.params.first; this.abyss = false; + this.count = 0; this.everyT = 0; this.side = 1; this.lastAng = null; this.glideFrom = null; this.oid = 0; this.lastGaps = null; this.lastGapT = 0; + }; + + // ---------- geometry ---------- + Moth.prototype.bodyBox = function () { return { x: this.x, y: this.y, w: BW, h: BH }; }; + Moth.prototype.hitTargets = function () { return [{ id: 'boss', box: HIDDEN[this.st] || this.st === 'dead' ? null : this.bodyBox() }]; }; + function islands() { return MV.abyss.params.islands; } + function nearestIsland(x) { // the foothold nearest to x: [x0, x1] + var I = islands(), best = I[0], bd = 1e9; + for (var i = 0; i < I.length; i++) { var d = x < I[i][0] ? I[i][0] - x : x > I[i][1] ? x - I[i][1] : 0; if (d < bd) { bd = d; best = I[i]; } } + return best; + } + + // ---------- phase control [web] 350 / 400 / 250 / 700 of 1700, scaled to k.hp ---------- + Moth.prototype.dealt = function () { return this.max_hp - this.hp; }; + Moth.prototype.updatePending = function () { + var dl = this.dealt(); + for (var i = 0; i < 4; i++) if (dl >= this.cuts[i]) this.pending = Math.max(this.pending, i + 2); + }; + // called whenever she is free to act: a pending phase change comes before the next attack + Moth.prototype.ready = function (c) { + if (this.pending > this.phase) return this.phaseUp(c); + if (this.phase === 3) return this.go(c, 'centre', 0); + var I = TP.idle; + this.face(c); this.move = null; this.vx = 0; this.vy = 0; + this.go(c, 'idle', c.rng.uniform(I[0], I[1]) * this.k[SPEC.timing.idle.knob]); + }; + Moth.prototype.phaseUp = function (c) { + var to = this.phase + 1; + this.phase = to; this.move = null; this.vx = 0; this.vy = 0; this.next = null; + c.emit('boss_escalate'); c.shake(0.5); + if (to === 2) return this.go(c, 'scream', SC.roar); // the spike floor joins + if (to === 3) { // she takes the centre; spikes hold both edges + this.spikes = { side: 0, warn: this.tele(c, MV.spikes.telegraph_scale), up: 1e9 }; this.glideTo(c, SC.centre[0], SC.centre[1], 'centre'); // the edges glow first, like every spike rise + return this.go(c, 'scream', SC.roar); + } + if (to === 4) { // [web] the stagger: then the floor gives way + this.swords = []; this.spikes = null; this.vy = -3; + c.emit('boss_stun', this.x, this.y); c.shake(0.8); + return this.go(c, 'stagger', SC.stun); + } + // to === 5: the final ascent under the big beam + this.orbs = []; this.swords = []; this.beams = []; this.sweep = null; + this.glideTo(c, W / 2, MV.big_beam.params.top, 'final'); + return this.go(c, 'scream', SC.roar); + }; + Moth.prototype.glideTo = function (c, x, y, then) { this.glideFrom = { x0: this.x, y0: this.y, x1: x, y1: y, then: then }; }; + + // ---------- teleport [web] around the arena, often above the player ---------- + Moth.prototype.teleTo = function (c, next) { + this.next = next; this.vx = 0; this.vy = 0; + this.go(c, 'tele_out', TP.out * this.k[SPEC.timing.telegraph.knob]); + }; + Moth.prototype.telePoint = function (c) { + var P = this.phase >= 4 ? TP.points_p4 : TP.points, b = c.body, hx = b.x, hy = b.y + 0.7, cand = [], near = [], self = this; + if (this.phase >= 4 && (this.next === 'BEAM_BURST' || this.next === 'ORBS')) P = P.filter(function (p) { return p[1] >= 6.0; }); + P.forEach(function (p) { + if (Math.abs(p[0] - self.x) < 0.5 && Math.abs(p[1] - self.y) < 0.5) return; // never the same spot + if (Math.hypot(p[0] - hx, p[1] - hy) < TP.min_dist) return; // never on top of the player + cand.push(p); if (Math.abs(p[0] - hx) < TP.near) near.push(p); + }); + if (!cand.length) cand = P; + var pool = near.length && c.rng.random() < 0.5 ? near : cand; + return pool[c.rng.int(pool.length)]; + }; + + // ---------- attack choice [mod] A1 / A2 Choice: SendRandomEventV3 shape; weights and caps [hand] ---------- + Moth.prototype.choose = function (c) { + var evs = CHOICE[this.phase >= 4 ? 4 : 1], n = evs.length, w = [], rep = [], miss = []; + for (var i = 0; i < n; i++) { w.push(1); rep.push(1); miss.push(n + 1); } + var ev = this.pick(c, 'atk' + (this.phase >= 4 ? 4 : 1), evs, w, rep, miss); + // beam burst and orbs are cast from where she stands (Absolute Radiance does not teleport during them) [web]; + // over the abyss [hand fairness] she first rises to a high point, so the eight beams cross the footholds far apart + if ((ev === 'BEAM_BURST' || ev === 'ORBS') && !(this.phase >= 4 && this.y < 6.0)) return this.startAttack(c, ev); + this.teleTo(c, ev); + }; + Moth.prototype.startAttack = function (c, ev) { + var P; + this.face(c); this.count = 0; this.everyT = 0; + switch (ev) { + case 'ORBS': return this.go(c, 'orbs_antic', this.tele(c, MV.orbs.telegraph_scale), 'orbs'); + case 'SWORD_BURST': { // [web] 12 swords from her face, hanging in a ring first + P = MV.sword_burst.params; var a0 = c.rng.uniform(0, TAU / P.count); + for (var i = 0; i < P.count; i++) { + var a = a0 + i * TAU / P.count; + this.swords.push({ id: ++this.oid, x: this.x + Math.cos(a) * P.ring, y: this.y + Math.sin(a) * P.ring, ang: a, vx: 0, vy: 0, hang: 1e9, kind: 'burst', hl: P.half_len, r: P.r }); + } + return this.go(c, 'burst_antic', this.tele(c, MV.sword_burst.telegraph_scale), 'sword_burst'); + } + case 'SWORD_RAIN': return this.go(c, 'rain_antic', this.tele(c, MV.sword_rain.telegraph_scale), 'sword_rain'); + case 'SWORD_WALL': return this.go(c, 'wall_antic', this.tele(c, MV.sword_wall.telegraph_scale), 'sword_wall'); + case 'BEAM_BURST': return this.go(c, 'beam_antic', this.tele(c, MV.beam_burst.telegraph_scale), 'beam_burst'); + case 'BEAM_SWEEP': { + P = MV.beam_sweep.params; var dir = c.rng.random() < 0.5 ? 1 : -1; // +1: from the left wall to the right + if (this.spikes && this.spikes.side) dir = -this.spikes.side; // [hand fairness] the dark far end is never spiked + this.sweep = { dir: dir, x: dir > 0 ? P.width / 2 : W - P.width / 2, warn: this.tele(c, MV.beam_sweep.telegraph_scale), end: dir > 0 ? W * P.reach : W * (1 - P.reach) }; + return this.go(c, 'sweep_antic', this.sweep.warn, 'beam_sweep'); + } + } + }; + + // ---------- spawners ---------- + // the floor span a gap may use: not under spikes that are up or warning (a safe gap must be standable) [hand fairness] + Moth.prototype.safeSpan = function () { + var s = this.spikes, e = MV.spikes.params.edge; + if (!s) return [0, W]; + if (s.side === 0) return [e, W - e]; + return s.side < 0 ? [W / 2, W] : [0, W / 2]; + }; + Moth.prototype.rainWave = function (c, P, interval) { // [web] swords drop from the ceiling with wide safe gaps + var slots = Math.floor(W / P.slot), sw = W / slots, gaps = [], i, j, hang = P.hang * this.k[SPEC.timing.telegraph.knob]; + var span = this.safeSpan(), lo = Math.ceil(span[0] / sw - 1e-9), hi = Math.floor(span[1] / sw + 1e-9) - P.gap_slots; + // [hand fairness] one gap is always reachable. A wave that follows another closely (< 1.5 s) puts its first gap + // within run speed x (interval - 0.12 s) of the previous wave's gap nearer the player (stand in one, step to the + // next); a fresh wave puts it within run speed x (time until the swords reach head height - 0.15 s) of the player. + var fall = (H - 0.9 - 1.4) / (P.speed * this.spd()), chained = this.lastGaps && c.t - this.lastGapT < 1.5 * BB.FPS; + var reachU = P.reach * BB.WANDERER.RUN * Math.max(0.05, chained ? interval - 0.12 : hang + fall - 0.15); + var me = Math.floor(c.body.x / sw) - Math.floor(P.gap_slots / 2), prev = me; + if (chained) prev = this.lastGaps.reduce(function (a, q) { return Math.abs(q - me) < Math.abs(a - me) ? q : a; }); + var rs = Math.max(1, Math.floor(reachU / sw)); + for (j = 0; j < P.gaps; j++) { + var g0, ok, guard = 0, a = lo, z = hi; + if (j === 0 && prev !== null) { a = Math.max(lo, prev - rs); z = Math.min(hi, prev + rs); if (z < a) { a = lo; z = hi; } } + do { g0 = a + c.rng.int(Math.max(1, z - a + 1)); ok = gaps.every(function (q) { return Math.abs(q - g0) > P.gap_slots + 1; }); } while (!ok && guard++ < 20); + gaps.push(g0); + } + this.lastGaps = gaps; this.lastGapT = c.t; + + for (i = 0; i < slots; i++) { + if (gaps.some(function (q) { return i >= q && i < q + P.gap_slots; })) continue; + this.swords.push({ id: ++this.oid, x: (i + 0.5) * W / slots, y: H - 0.9, ang: -Math.PI / 2, vx: 0, vy: 0, hang: hang, speed: P.speed * this.spd(), kind: 'rain', hl: P.half_len, r: P.r }); + } + c.emit('boss_rain_wave'); + }; + // [web] a wall of swords crosses the arena with one gap. [hand fairness] each wall forms along the wall farther from + // the player: formed beside a player who stands against a wall, a high gap could not be reached in the warning + Moth.prototype.wallWave = function (c) { + var P = MV.sword_wall.params, side = this.side = c.body.x < W / 2 ? 1 : -1, G = P.gaps[c.rng.int(P.gaps.length)], x0 = side < 0 ? 0.9 : W - 0.9; + c.emit('boss_wall_wave'); + for (var i = 0; i < P.rows; i++) { + if (i >= G[0] && i < G[0] + G[1]) continue; + this.swords.push({ id: ++this.oid, x: x0, y: (i + 0.5) * P.row, ang: side < 0 ? 0 : Math.PI, vx: 0, vy: 0, hang: P.hang * this.k[SPEC.timing.telegraph.knob], speed: P.speed * this.spd(), kind: 'wall', hl: P.half_len, r: P.r }); + } + }; + Moth.prototype.beamBurst = function (c) { // [web] 8 evenly spread beams; never the same lines twice + var P = MV.beam_burst.params, step = TAU / P.beams, off; + // circular distance between the new and the previous offset, modulo one beam spacing (0.95 and 0.10 of a step are + // only 0.15 apart); at least 0.3 of a step, so a burst never re-fires on (or next to) the previous lines + function apart(o, p) { var dd = Math.abs(o - p) % step; return Math.min(dd, step - dd); } + do { off = c.rng.uniform(0, step); } while (this.lastAng !== null && apart(off, this.lastAng) < step * 0.3); + this.lastAng = off; + for (var i = 0; i < P.beams; i++) this.beams.push({ x: this.x, y: this.y, ang: off + i * step, warn: P.warn * this.k[SPEC.timing.telegraph.knob], fire: P.fire, w: P.width }); + }; + Moth.prototype.spawnOrb = function (c) { + var P = MV.orbs.params, a = c.rng.uniform(0, TAU); + this.orbs.push({ id: ++this.oid, x: this.x + Math.cos(a) * P.spread, y: this.y + Math.sin(a) * P.spread * 0.6, vx: Math.cos(a) * P.launch, vy: Math.sin(a) * P.launch, life: P.life }); + }; + + // ---------- per-tick update ---------- + Moth.prototype.update = function (c) { + var dt = BB.DT, st, P, tk = this.k[SPEC.timing.telegraph.knob]; + this.flash(dt); + this.timer -= dt; this.stT += dt; + st = this.st; + if (this.glideFrom && (st === 'glide' || st === 'scream' || st === 'final_glide' || st === 'rise')) this.glideStep(dt); + switch (st) { + case 'dead': break; + case 'intro': + this.y = SC.intro_to + (SC.intro_from - SC.intro_to) * Math.max(0, this.timer / SC.intro); + if (this.timer <= 0) { this.y = SC.intro_to; this.ready(c); } + break; + case 'idle': if (this.timer <= 0) { if (this.pending > this.phase) this.phaseUp(c); else this.choose(c); } break; + case 'tele_out': + if (this.timer <= 0) { var p = this.telePoint(c); this.x = p[0]; this.y = p[1]; this.face(c); this.go(c, 'tele_in', TP.in * tk); c.emit('boss_tele', this.x, this.y); } + break; + case 'tele_in': + if (this.timer <= 0) { + var nx = this.next; this.next = null; + if (nx === 'RESUME') { this.st = this.resume; this.timer = this.resumeT; this.stT = 0; } + else if (nx) this.startAttack(c, nx); else this.ready(c); + } + break; + // orbs [web] up to three homing orbs + case 'orbs_antic': if (this.timer <= 0) { this.go(c, 'orbs', MV.orbs.active); this.everyT = 0; } break; + case 'orbs': + P = MV.orbs.params; this.everyT -= dt; + if (this.everyT <= 0 && this.count < P.count) { this.spawnOrb(c); this.count++; this.everyT += P.every; c.emit('boss_orb', this.x, this.y); } + if (this.timer <= 0 && this.count >= P.count) this.go(c, 'orbs_recover', this.rec(P.recover)); + break; + // sword burst [web] 12 swords fly out of the ring + case 'burst_antic': + if (this.timer <= 0) { + P = MV.sword_burst.params; var sp = P.speed * this.spd(); + this.swords.forEach(function (s) { if (s.kind === 'burst' && s.hang > 1e8) { s.hang = 0; s.vx = Math.cos(s.ang) * sp; s.vy = Math.sin(s.ang) * sp; } }); + c.emit('boss_sword_burst', this.x, this.y); c.shake(0.25); + this.go(c, 'burst', MV.sword_burst.active); + } + break; + case 'burst': if (this.timer <= 0) this.go(c, 'burst_recover', this.rec(MV.sword_burst.params.recover)); break; + // sword rain [web] waves from the ceiling; she teleports during it + case 'rain_antic': if (this.timer <= 0) { this.go(c, 'rain', 1e9); this.everyT = 0; this.count = 0; } break; + case 'rain': + P = MV.sword_rain.params; this.everyT -= dt; + if (this.everyT <= 0 && this.count < P.waves) { + this.rainWave(c, P, P.every * tk); this.count++; this.everyT += P.every * tk; + if (this.count === P.tele_after && this.count < P.waves) { this.resume = 'rain'; this.resumeT = 1e9; this.teleTo(c, 'RESUME'); break; } + } + if (this.count >= P.waves && this.everyT <= 0) this.go(c, 'rain_recover', this.rec(P.recover)); + break; + // sword wall [web] walls cross the arena, one gap each; she teleports during it + case 'wall_antic': if (this.timer <= 0) { this.go(c, 'wall', 1e9); this.everyT = 0; this.count = 0; } break; + case 'wall': + P = MV.sword_wall.params; this.everyT -= dt; + if (this.everyT <= 0 && this.count < P.walls) { + this.wallWave(c); this.count++; this.everyT += P.every * tk; + if (this.count === P.tele_after && this.count < P.walls) { this.resume = 'wall'; this.resumeT = 1e9; this.teleTo(c, 'RESUME'); break; } + } + if (this.count >= P.walls && this.everyT <= 0) this.go(c, 'wall_recover', this.rec(P.recover)); + break; + // beam burst [web] three bursts of eight beams + case 'beam_antic': if (this.timer <= 0) { this.go(c, 'beam', 1e9); this.count = 0; this.everyT = 0; } break; + case 'beam': + P = MV.beam_burst.params; this.everyT -= dt; + if (this.everyT <= 0 && this.count < P.bursts && !this.beams.length) { this.beamBurst(c); this.count++; this.everyT = P.warn * tk + P.fire + P.gap; } + if (this.count >= P.bursts && !this.beams.length) this.go(c, 'beam_recover', this.rec(P.recover)); + break; + // beam sweep [web] a wall of light crosses all but the far end of the arena + case 'sweep_antic': if (this.timer <= 0) { this.sweep.warn = 0; c.emit('boss_beam_sweep', this.sweep.x, H / 2); this.go(c, 'sweep', 1e9); } break; + case 'sweep': + P = MV.beam_sweep.params; var sw = this.sweep, v = (W * P.reach - P.width / 2) / P.cross * this.spd(); + sw.x += sw.dir * v * dt; + if ((sw.dir > 0 && sw.x >= sw.end) || (sw.dir < 0 && sw.x <= sw.end)) { this.sweep = null; this.go(c, 'sweep_recover', this.rec(P.recover)); } + break; + case 'orbs_recover': case 'burst_recover': case 'rain_recover': case 'wall_recover': case 'beam_recover': case 'sweep_recover': + if (this.timer <= 0) this.ready(c); + break; + // phase 3 [web] she holds the centre: endless sword rain + case 'centre': + P = MV.sword_rain.params; this.everyT -= dt; + if (this.everyT <= 0) { this.rainWave(c, P, SC.rain_every * tk); this.everyT += SC.rain_every * tk; } + if (this.pending > this.phase) this.phaseUp(c); + break; + case 'scream': if (this.timer <= 0) { if (this.glideFrom) this.go(c, this.phase === 5 ? 'final_glide' : 'glide', SC.glide); else this.ready(c); } break; + case 'glide': if (!this.glideFrom) { this.everyT = 0; this.ready(c); } break; + // phase 3 -> 4: a stagger, then the floor gives way to an abyss between footholds + case 'stagger': + this.vy = Math.min(0, this.vy + 6 * dt); this.y = Math.max(SC.centre[1] - 2.6, this.y + this.vy * dt); + if (this.timer <= 0) { this.vy = 0; this.go(c, 'abyss_form', this.tele(c, MV.abyss.telegraph_scale)); c.emit('boss_abyss_antic'); } + break; + case 'abyss_form': + if (this.timer <= 0) { + this.abyss = true; c.emit('boss_abyss'); c.shake(0.6); + var q = TP.points_p4[c.rng.int(TP.points_p4.length)]; + this.glideTo(c, q[0], q[1], 'rise'); this.go(c, 'rise', SC.rise); + } + break; + case 'rise': if (!this.glideFrom) this.ready(c); break; + // phase 5: big beams from above while she sinks, then one strike ends her + case 'final_glide': if (!this.glideFrom) { this.count = 0; this.everyT = 0; this.go(c, 'final_beam', 1e9); } break; + case 'final_beam': + P = MV.big_beam.params; this.everyT -= dt; + if (this.everyT <= 0 && this.count < P.beams) { + this.bigs.push({ x: BB.clamp(c.body.x, P.width / 2, W - P.width / 2), warn: this.tele(c, MV.big_beam.telegraph_scale), fire: MV.big_beam.active }); + this.count++; this.everyT += P.every * tk; + } + this.y = P.top - (P.top - (P.low + 2.2)) * Math.min(1, this.count / P.beams); + if (this.count >= P.beams && !this.bigs.length) { + var isl = nearestIsland(c.body.x); + this.glideTo(c, (isl[0] + isl[1]) / 2, P.low, 'exposed'); this.go(c, 'final_sink', SC.sink); + } + break; + case 'final_sink': this.glideStep(dt); if (!this.glideFrom) { this.go(c, 'exposed', 1e9); c.emit('boss_exposed', this.x, this.y); } break; + case 'exposed': break; + } + this.updateHazards(c, dt); + }; + Moth.prototype.glideStep = function (dt) { + var G = this.glideFrom; if (!G) return; + G.t = (G.t || 0) + dt; var dur = this.st === 'final_sink' ? SC.sink : this.st === 'rise' ? SC.rise : SC.glide; + var u = Math.min(1, G.t / dur), e = u * u * (3 - 2 * u); + this.x = G.x0 + (G.x1 - G.x0) * e; this.y = G.y0 + (G.y1 - G.y0) * e; + if (u >= 1) this.glideFrom = null; + }; + Moth.prototype.updateHazards = function (c, dt) { + var b = c.body, P; + // orbs home in on the player and burst on any surface [web] + P = MV.orbs.params; + var hx = b.x, hy = b.y + 0.7, sp = this.spd(); + this.orbs = this.orbs.filter(function (o) { + o.life -= dt; + var dx = hx - o.x, dy = hy - o.y, d = Math.hypot(dx, dy) || 1; + o.vx += dx / d * P.accel * sp * dt; o.vy += dy / d * P.accel * sp * dt; + var v = Math.hypot(o.vx, o.vy), vm = P.speed * sp; if (v > vm) { o.vx *= vm / v; o.vy *= vm / v; } // [hand] speed clamp, not a per-step factor + o.x += o.vx * dt; o.y += o.vy * dt; + if (o.y <= P.radius || o.x <= P.radius || o.x >= W - P.radius || o.y >= H - P.radius || o.life <= 0) { c.emit('boss_orb_burst', o.x, Math.max(0, o.y)); return false; } + return true; + }); + // swords: hang, then fly straight; gone once they leave the room + this.swords = this.swords.filter(function (s) { + if (s.hang > 1e8) return true; // still in the ring of an unfinished burst + if (s.hang > 0) { s.hang -= dt; if (s.hang <= 0) { s.vx = Math.cos(s.ang) * s.speed; s.vy = Math.sin(s.ang) * s.speed; } return true; } + s.x += s.vx * dt; s.y += s.vy * dt; + if (s.kind === 'rain' && s.y <= 0) { c.emit('boss_land', s.x, 0); return false; } + return s.x > -2 && s.x < W + 2 && s.y > -2 && s.y < H + 2; + }); + // beams: warning line, then the beam + this.beams = this.beams.filter(function (o) { + if (o.warn > 0) { o.warn -= dt; if (o.warn <= 0) c.emit('boss_beam', o.x, o.y); return true; } + o.fire -= dt; return o.fire > 0; + }); + this.bigs = this.bigs.filter(function (o) { + if (o.warn > 0) { o.warn -= dt; if (o.warn <= 0) { c.emit('boss_big_beam', o.x, 0); c.shake(0.4); } return true; } + o.fire -= dt; return o.fire > 0; + }); + // the spike floor [web] phase 2: half the floor for 5 s after a glow; phase 3: both edges + if (this.phase === 3 && this.spikes && this.spikes.warn > 0 && (this.spikes.warn -= dt) <= 0) { c.emit('boss_spikes'); c.shake(0.3); } + if (this.phase === 2 && this.st !== 'dead') { + P = MV.spikes.params; + if (!this.spikes) { + this.spikeT -= dt; + if (this.spikeT <= 0 && !this.sweep) { this.spikes = { side: c.rng.random() < 0.5 ? -1 : 1, warn: this.tele(c, MV.spikes.telegraph_scale), up: MV.spikes.active }; c.emit('boss_spikes_antic'); } + } else if (this.spikes.warn > 0) { this.spikes.warn -= dt; if (this.spikes.warn <= 0) { c.emit('boss_spikes'); c.shake(0.3); } } + else if ((this.spikes.up -= dt) <= 0) { this.spikes = null; this.spikeT = c.rng.uniform(P.every[0], P.every[1]); } + } + }; + + // ---------- combat interface ---------- + // a long beam as a chain of 2.4 u capsules: the engine tests 9 points per capsule, so samples sit 0.3 u apart + function beamSegs(out, o, kind, dmg) { + var ca = Math.cos(o.ang), sa = Math.sin(o.ang), len = 0, step = 2.4; + var tx = ca > 0 ? (W - o.x) / ca : ca < 0 ? -o.x / ca : 1e9, ty = sa > 0 ? (H - o.y) / sa : sa < 0 ? -o.y / sa : 1e9; + len = Math.min(tx, ty); + for (var s = 0; s < len; s += step) { + var e = Math.min(len, s + step); + out.push({ kind: kind, seg: [o.x + ca * s, o.y + sa * s, o.x + ca * e, o.y + sa * e], r: o.w / 2, dmg: dmg, fromX: o.x }); + } + } + Moth.prototype.hazards = function () { + var out = [], self = this, P; + if (this.st === 'dead') return out; + this.orbs.forEach(function (o) { out.push({ kind: 'orb', circle: [o.x, o.y, MV.orbs.params.radius], dmg: self.dmg, fromX: o.x }); }); + this.swords.forEach(function (s) { + if (s.hang > 0) return; // hanging swords are the warning + var ca = Math.cos(s.ang), sa = Math.sin(s.ang); + out.push({ kind: 'sword', seg: [s.x - ca * s.hl, s.y - sa * s.hl, s.x + ca * s.hl, s.y + sa * s.hl], r: s.r, dmg: self.dmg, fromX: s.x - ca }); + }); + this.beams.forEach(function (o) { if (o.warn <= 0) beamSegs(out, o, 'beam', self.dmg); }); + if (this.sweep && this.sweep.warn <= 0) { + P = MV.beam_sweep.params; out.push({ kind: 'beam_sweep', box: { x: this.sweep.x, y: H / 2, w: P.width, h: H }, dmg: this.dmg, fromX: this.sweep.x - this.sweep.dir }); + } + this.bigs.forEach(function (o) { if (o.warn <= 0) out.push({ kind: 'big_beam', box: { x: o.x, y: H / 2, w: MV.big_beam.params.width, h: H }, dmg: self.dmg, fromX: o.x }); }); + this.spikeBoxes().forEach(function (b) { out.push({ kind: 'spikes', box: b, dmg: self.floorDmg, fromX: b.fromX }); }); + if (this.abyss) this.voidBoxes().forEach(function (b) { out.push({ kind: 'abyss', box: b, dmg: self.floorDmg, fromX: b.fromX }); }); + return out; + }; + Moth.prototype.spikeBoxes = function () { + var s = this.spikes, P = MV.spikes.params, h = P.height, out = []; + if (!s || s.warn > 0) return out; + if (s.side === 0) { // phase 3: both edges (knock-back toward the middle) + out.push({ x: P.edge / 2, y: h / 2, w: P.edge, h: h, fromX: -1 }); + out.push({ x: W - P.edge / 2, y: h / 2, w: P.edge, h: h, fromX: W + 1 }); + } else out.push({ x: s.side < 0 ? W / 4 : W * 3 / 4, y: h / 2, w: W / 2 - 0.3, h: h, fromX: s.side < 0 ? -1 : W + 1 }); + return out; + }; + // the gaps between footholds, shrunk by the hero hurt box half-width (0.455 / 2): you fall once your centre is over + // the gap, not while your toes hang over a foothold's edge + var EDGE = BB.WANDERER.HURT.w / 2 + 0.005; + Moth.prototype.voidBoxes = function () { + var I = islands(), out = [], hgt = MV.abyss.params.height; + for (var i = 0; i + 1 < I.length; i++) { + var x0 = I[i][1] + EDGE, x1 = I[i + 1][0] - EDGE, m = (x0 + x1) / 2; + // fromX at the far side of the player's half sends the knock-back to the nearer foothold + out.push({ x: m, y: hgt / 2, w: x1 - x0, h: hgt, fromX: m, gap: [x0, x1] }); + } + return out; + }; + // read by the reference controller (scripted.js): 1 where the floor at x hurts now or is about to (spikes up or + // glowing, the abyss gaps, the abyss while it forms), else 0. Pure query. + Moth.prototype.floorDanger = function (x) { + var s = this.spikes, e = MV.spikes.params.edge, I, i; + if (s) { + if (s.side === 0 && (x < e + 0.3 || x > W - e - 0.3)) return 1; + if (s.side < 0 && x < W / 2 + 0.3) return 1; + if (s.side > 0 && x > W / 2 - 0.3) return 1; + } + if (this.abyss || this.st === 'abyss_form') { + I = islands(); + for (i = 0; i < I.length; i++) if (x >= I[i][0] + 0.3 && x <= I[i][1] - 0.3) return 0; + return 1; + } + return 0; + }; + Moth.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + var st = this.st; + if (st === 'dead' || HIDDEN[st]) return null; + if (INVULN[st]) { c.emit('tink', this.x, this.y); return 'tink'; } + var d = this.nail; // Channelled Nail preset (see header) + if (st === 'exposed') { this.hp = 0; } + else this.hp = Math.max(this.finalHP, this.hp - d); + this.hitFlash = 0.12; c.emit('boss_hit', this.x, this.y); + if (this.hp <= 0) { + this.st = 'dead'; this.orbs = []; this.swords = []; this.beams = []; this.bigs = []; this.sweep = null; this.spikes = null; + c.emit('boss_dead', this.x, this.y); c.shake(0.9); return 'flesh'; + } + this.updatePending(); + return 'flesh'; + }; + Moth.prototype.state = function () { + var r = BB.r4, role = this.role(); + var hz = this.orbs.map(function (o) { return { kind: 'orb', x: r(o.x), y: r(o.y), vx: r(o.vx), vy: r(o.vy) }; }) + .concat(this.swords.map(function (s) { return { kind: 'sword', x: r(s.x), y: r(s.y), ang: r(s.ang), live: s.hang <= 0 }; })) + .concat(this.beams.map(function (o) { return { kind: 'beam', x: r(o.x), y: r(o.y), ang: r(o.ang), live: o.warn <= 0 }; })) + .concat(this.bigs.map(function (o) { return { kind: 'big_beam', x: r(o.x), live: o.warn <= 0 }; })); + if (this.sweep) hz.push({ kind: 'beam_sweep', x: r(this.sweep.x), dir: this.sweep.dir, live: this.sweep.warn <= 0 }); + if (this.spikes) hz.push({ kind: 'spikes', side: this.spikes.side, live: this.spikes.warn <= 0 }); + return { + x: r(this.x), y: r(this.y), vx: r(this.vx), vy: r(this.vy), facing: this.f, + hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: this.move, + telegraph_left: role === 'telegraph' ? r(Math.max(0, this.timer)) : 0, aim_deg: null, + escalated: this.phase > 1, phase: this.phase, abyss: this.abyss, staggers: this.phase >= 4 ? 1 : 0, hazards: hz + }; + }; + // ticks the reference controller simulates past its packet (default 36). Its look-ahead copies draw a different RNG + // stream, so they invent rain waves that will never fall; while rain is falling (or about to) a horizon shorter than + // a wave's spawn-to-head time (~0.98 s on hard) keeps those invented waves out of reach. Read-only hint, no gameplay. + // A beam burst is fully determined once it starts (its warn lines are visible), so from its antic on she asks for the + // long horizon again: the controller must see where the second and third bursts will reach it. + Object.defineProperty(Moth.prototype, 'lookahead', { get: function () { return /^beam/.test(this.st) ? 66 : /^(rain|centre)/.test(this.st) || (this.phase === 3) ? 36 : 66; } }); + Moth.prototype.planner = 'two_step'; // reference controller: packet + best simple continuation (scripted.js) + BB.LumenMoth = Moth; + BB.CASES = BB.CASES || {}; + BB.CASES['2d/lumen_moth'] = { title: 'Four-Winged Sword Wielder', Body: BB.Wanderer, Boss: Moth, arena: 'dream_spire' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/bosses/needle_warden.js b/environments/games/web/games/hollowknight_remake/bosses/needle_warden.js new file mode 100644 index 0000000000000000000000000000000000000000..a43952a3789519b8667cf9ab7b45ea622a92a625 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/bosses/needle_warden.js @@ -0,0 +1,478 @@ +// Boss "needle_warden" - agile needle duelist (2D). Behaviour = the source fight's PlayMaker "Control" FSM, +// re-implemented state by state; every move timing / speed comes from specs/needle_warden.spec.js (the Boss Spec), +// every other number is marked [data] (read from the game files) or [hand]. +// Positions are the boss pivot in arena-local units; the pivot sits 1.55 u above her feet. +(function (g) { + var BB = g.BB; + var SPEC = BB.SPECS.needle_warden; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.ARENA; + // [data] FSM float variables, converted to arena-local coordinates + var GROUND = A.ly(27.55), ROOF = A.ly(40.54), WALL_L = A.lx(15.13), WALL_R = A.lx(37.90); + var JUMP_L = A.lx(16.06), JUMP_R = A.lx(36.53), SPHERE_Y = A.ly(33.8); + var THROW_L = A.lx(22.51), THROW_R = A.lx(30.16); + // [data] Decelerate* actions multiply the velocity once per 50 Hz FixedUpdate; CLK.perStep turns "x f every 0.02 s" + // into the matching 60 Hz per-tick factor (clock.js), so slide distances keep their source length. + var CLK = BB.HK_CLOCK; + var GRAV = 60; // [data] Physics2D gravity magnitude; boss gravity scale 1.5 (2.0 after a wall/roof hit) + var HERO_PIVOT = 1.39; // [data] hero collider 0.5 x 1.28 at offset y -0.75 -> pivot 1.39 u above the feet + // [data] collider boxes per pose: size, offset (offset x is in sprite space: +x = behind her) + var BOX = { + idle: [0.895, 2.565, 0.120, -0.265], antic: [1.229, 1.381, 1.081, -0.857], + gdash: [1.563, 1.506, 0.050, -0.794], adash: [1.460, 1.025, 0.102, 0.0], + throw: [0.982, 2.565, 0.997, -0.265], throwing: [1.394, 1.156, 0.148, -0.969] + }; + // [data] A Dash Range trigger polygon (sprite space; it is left/right symmetric) + var ADASH_RANGE = [[0.03, 0.24], [25.44, 18.41], [26.45, -21.55], [7.36, -21.34], [0.01, -0.19], [-6.96, -21.22], [-25.19, -21.34], [-24.87, 19.83]]; + var ROLE = { + intro: 'idle', idle: 'idle', run_antic: 'idle', run: 'idle', dmg_idle: 'idle', air: 'idle', land: 'recovery', + evade_antic: 'idle', evade: 'idle', evade_land: 'idle', + gdash_antic: 'telegraph', gdash: 'active', gdash_rec1: 'recovery', gdash_rec2: 'recovery', + jump_antic: 'telegraph', adash_antic: 'telegraph', adash: 'active', hard_land: 'recovery', wall_impact: 'recovery', + a_sphere_antic: 'telegraph', a_sphere: 'active', a_sphere_recover: 'recovery', + g_sphere_antic: 'telegraph', g_sphere: 'active', g_sphere_recover: 'recovery', + throw_antic: 'telegraph', thrown: 'active', throw_recover: 'recovery', + stun_air: 'recovery', stun_land: 'recovery', stun_recover: 'recovery', dead: 'recovery' + }; + + function Warden() {} + Warden.prototype.id = 'needle_warden'; + Warden.prototype.spec = SPEC; + + Warden.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.max_hp = this.hp = Math.round(k.hp); + this.dmg = Math.max(1, Math.round(k.dmg)); + this.x = A.lx(19.62); this.y = GROUND; this.vx = 0; this.vy = 0; this.gs = 1.5; this.f = 1; + this.st = 'intro'; this.timer = 1.167; // [data] "Flourish" clip before the first Idle + this.move = null; this.box = 'idle'; + this.idleMin = 0.5; this.idleMax = 0.75; this.runMin = 0.5; this.runMax = 1.0; // [data] + this.escalated = false; + this.track = {}; // SendRandomEventV2/V3 repeat & miss counters + this.cycle = {}; // deterministic cycles (entropy knob) + this.airPause = 999; this.airT = 0; this.willSphere = false; + this.angle = 0; this.recoilOn = true; this.recoilT = 0; this.recoilDir = 0; + this.evadeOn = false; this.evadeT = c.rng.uniform(2, 3); // [data] "Evade Range" toggler starts in Off + this.stun = { combo: 0, total: 0, stuns: 0, comboT: 0, stopped: false }; + this.needle = null; this.sphere = null; + this.hitFlash = 0; + }; + + // ---------- helpers ---------- + Warden.prototype.role = function () { return ROLE[this.st] || 'idle'; }; + Warden.prototype.s = function () { return -this.f; }; // sprite x-scale (the sprite faces -x at scale 1) + Warden.prototype.bodyBox = function () { + var b = BOX[this.box] || BOX.idle; + return { x: this.x + b[2] * this.s(), y: this.y + b[3], w: b[0], h: b[1] }; + }; + Warden.prototype.face = function (c) { + var hx = c.body.x; + if (hx > this.x + 1e-6) this.f = 1; else if (hx < this.x - 1e-6) this.f = -1; + }; + Warden.prototype.heroIn = function (c, w, h, ox, oy) { + return BB.overlap(c.body.box(), { x: this.x + ox * this.s(), y: this.y + oy, w: w, h: h }); + }; + Warden.prototype.tele = function (c, base) { // spec timing.telegraph: knob x scale + jitter, floored + var tm = SPEC.timing.telegraph, t = base * this.k[tm.knob]; + if (tm.jitter && this.k[tm.jitter] > 0) t += c.rng.uniform(-this.k[tm.jitter], this.k[tm.jitter]); + return Math.max(tm.min || 0, t); + }; + Warden.prototype.rec = function (base) { return base * this.k[SPEC.timing.recovery.knob]; }; + Warden.prototype.spd = function () { return this.k[SPEC.locomotion.knob]; }; + Warden.prototype.go = function (c, st, timer) { + this.st = st; this.timer = timer == null ? 0 : timer; this.stT = 0; + if (ROLE[st] === 'telegraph' && SPEC.announce) + c.emit(SPEC.announce.telegraph.replace('{move}', st === 'jump_antic' ? 'jump' : this.move)); + }; + + // SendRandomEventV3 semantics [data]: events past their repeat cap are re-rolled; an event missed + // missMax times in a row is forced. With prob (1 - entropy) the pick is a fixed cycle instead (spec select.policy). + Warden.prototype.pick = function (c, key, evs, w, maxRep, missMax) { + var tr = this.track, i, n = evs.length, ev = null; + evs.forEach(function (e) { if (!tr[e]) tr[e] = { ct: 0, ms: 0 }; }); + if (c.rng.random() < this.k[SPEC.select.knob]) { + if (missMax) for (i = 0; i < n && ev === null; i++) if (tr[evs[i]].ms >= missMax[i]) ev = evs[i]; + for (var guard = 0; ev === null && guard < 64; guard++) { + var j = c.rng.pick(w); + if (!maxRep || tr[evs[j]].ct < maxRep[j]) ev = evs[j]; + } + if (ev === null) ev = evs[0]; + } else { + var cy = this.cycle[key] = (this.cycle[key] || 0) + 1; + ev = evs[(cy - 1) % n]; + } + evs.forEach(function (e) { + if (e === ev) { tr[e].ct++; tr[e].ms = 0; } else { tr[e].ct = 0; tr[e].ms++; } + }); + return ev; + }; + + // ---------- FSM transitions (names follow the source states) ---------- + Warden.prototype.toIdle = function (c) { + this.move = null; this.box = 'idle'; this.vx = 0; this.face(c); + this.airPause = 999; + if (this.evadeOn && this.heroIn(c, 7.62, 6.23, 0, 1.82)) return this.evadeAntic(c); + // [data] SendRandomEvent(''/RUN 0.5/0.5) followed by SendRandomEventV2(IDLE/RUN 0.5/0.5, max 2 repeats) + var run = c.rng.random() < this.k[SPEC.select.knob] ? c.rng.random() < 0.5 : false; + if (!run) run = this.pick(c, 'idle', ['IDLE', 'RUN'], [0.5, 0.5], [2, 2]) === 'RUN'; + if (run) return this.flipQ(c); + this.go(c, 'idle', c.rng.uniform(this.idleMin, this.idleMax) * this.k[SPEC.timing.idle.knob]); + }; + Warden.prototype.flipQ = function (c) { + if (c.rng.random() < 0.5) this.f = -this.f; // [data] "Flip?" 50 % + if (this.heroIn(c, 9.49, 4.455, 0, 0.928)) { this.face(c); this.f = -this.f; } // [data] "Run Away?" + this.go(c, 'run_antic', 0.25); + }; + Warden.prototype.escalation = function (c) { + if (!this.escalated && this.hp <= this.max_hp * SPEC.phases[0].at.hp_below) { + this.escalated = true; this.idleMin = 0.1; this.idleMax = 0.4; this.runMin = 0.35; this.runMax = 0.75; // [data] + c.emit('boss_escalate'); + } + this.toIdle(c); + }; + Warden.prototype.gSphereQ = function (c) { + this.face(c); + var hb = c.body.box(); + if (BB.circleBox(this.x - 0.0625 * this.s(), this.y - 0.281, 3.43, hb) && + this.pick(c, 'gsphere', ['SPHERE', 'FINISHED'], [0.2, 0.8], [1, 5]) === 'SPHERE') { + this.move = 'g_sphere'; this.vx = 0; return this.go(c, 'g_sphere_antic', this.tele(c, MV.g_sphere.telegraph_scale)); + } + // [data] "Can Throw?": only from near a wall, facing into the room + var heroRight = c.body.x > this.x; + var can = (this.x > THROW_R && !heroRight) || (this.x < THROW_L && heroRight); + var evs = ['AIRDASH', 'SPHERE_A', 'G_DASH'], w = [0.33, 0.33, 0.34], rep = [2, 1, 2], miss = [5, 7, 5]; + if (can) { evs.push('THROW'); w = [0.25, 0.25, 0.25, 0.25]; rep.push(1); miss.push(3); } + var ev = this.pick(c, 'move', evs, w, rep, miss); + if (ev === 'G_DASH') { + this.move = 'g_dash'; this.box = 'antic'; this.vx = 0; + return this.go(c, 'gdash_antic', this.tele(c, MV.g_dash.telegraph_scale)); + } + if (ev === 'THROW') { + this.move = 'throw'; this.box = 'throw'; this.vx = 0; + this.angle = c.body.x >= this.x ? 0 : 180; // [data] aim, then locked to horizontal + this.recoilOn = false; this.stun.stopped = true; // [data] STUN CONTROL STOP, recoil 0 + return this.go(c, 'throw_antic', this.tele(c, MV.throw.telegraph_scale)); + } + if (ev === 'AIRDASH') { this.move = 'a_dash'; this.airPause = c.rng.uniform(0.15, 0.4); this.willSphere = false; } + else { this.move = 'a_sphere'; this.airPause = 999; this.willSphere = true; } + this.jumpAntic(c); + }; + Warden.prototype.jumpAntic = function (c) { + this.box = 'idle'; this.vx = 0; this.vy = 0; this.face(c); + this.go(c, 'jump_antic', this.tele(c, 0.333)); // [data] "Jump Antic" 0.333 s (Q: 0.25) + }; + Warden.prototype.jump = function (c) { + var jx; + do { jx = c.rng.uniform(JUMP_L, JUMP_R) - this.x; } while (Math.abs(jx) < 2.5); // [data] "Re Aim" + if (this.willSphere) jx *= MV.a_sphere.params.jump_vx_mult; + this.vx = jx; this.vy = MV.a_dash.params.jump_vy; this.gs = MV.a_dash.params.gravity_scale; + c.emit('boss_jump'); + this.inAir(c); + }; + Warden.prototype.inAir = function (c) { this.go(c, 'air', 0); this.airT = 0; }; + Warden.prototype.evadeAntic = function (c) { + this.box = 'idle'; + // [data] "Evade Check": a 3.5 x 1 box behind her touching the wall cancels the evade + var back = this.x + this.s() * 1.256, half = 3.51 / 2; + if (back - half < 0 || back + half > A.W) return this.gSphereQ(c); + this.evadeOn = false; this.evadeT = c.rng.uniform(2, 3); + this.vx = 0; this.vy = 0; this.face(c); this.move = 'evade'; + this.go(c, 'evade_antic', MV.evade.telegraph_scale); + }; + Warden.prototype.tookDamage = function (c) { // "TOOK DAMAGE" is only wired from Idle and Run [data] + if (this.st === 'stun_land') return this.go(c, 'stun_recover', 0.167); + if (this.st !== 'idle' && this.st !== 'run') return; + var ev = this.pick(c, 'dmg', ['EVADE', 'JUMP', 'ATTACK', 'IDLE'], [0.3, 0.15, 0.15, 0.4]); + if (ev === 'EVADE') return this.evadeAntic(c); + if (ev === 'JUMP') { this.move = 'jump'; this.airPause = 999; this.willSphere = false; return this.jumpAntic(c); } + if (ev === 'ATTACK') return this.gSphereQ(c); + this.vx = 0; this.go(c, 'dmg_idle', c.rng.uniform(0.25, 0.4)); + }; + Warden.prototype.stunStart = function (c) { + this.needle = null; this.sphere = null; this.recoilOn = true; this.stun.stopped = false; + this.box = 'idle'; this.gs = 1.5; this.face(c); this.move = null; + this.vx = 10 * this.s(); this.vy = 20; // [data] knocked away from the hero + c.emit('boss_stun'); + this.go(c, 'stun_air', 0); + }; + + // ---------- per-tick update ---------- + Warden.prototype.update = function (c) { + var dt = BB.DT, P, tr; + this.timer -= dt; this.stT = (this.stT || 0) + dt; + this.hitFlash = Math.max(0, this.hitFlash - dt); + // evade-range toggler (separate FSM) [data] + this.evadeT -= dt; + if (this.evadeT <= 0) { this.evadeOn = !this.evadeOn; this.evadeT = this.evadeOn ? c.rng.uniform(1, 2) : c.rng.uniform(2, 3); } + // stun combo window [data] + if (this.stun.combo > 0) { this.stun.comboT -= dt; if (this.stun.comboT <= 0) this.stun.combo = 0; } + + var gravity = false, wallStop = false; + switch (this.st) { + case 'dead': this.vx *= 0.9; gravity = true; break; // [hand] presentation slide, per 60 Hz tick (not a source number) + case 'intro': if (this.timer <= 0) this.toIdle(c); gravity = true; break; + case 'idle': gravity = true; if (this.timer <= 0) this.gSphereQ(c); break; + case 'dmg_idle': gravity = true; if (this.timer <= 0) this.gSphereQ(c); break; + case 'run_antic': + gravity = true; + if (this.timer <= 0) { + this.go(c, 'run', c.rng.uniform(this.runMin, this.runMax)); + if (this.evadeOn && this.heroIn(c, 7.62, 6.23, 0, 1.82)) this.evadeAntic(c); + } + break; + case 'run': + gravity = true; wallStop = true; this.vx = 8 * this.f * this.spd(); + if (this.timer <= 0) this.gSphereQ(c); + break; + // ground dash + case 'gdash_antic': + gravity = true; + if (this.timer <= 0) { + this.box = 'gdash'; this.vx = MV.g_dash.params.speed * this.f * this.spd(); c.emit('boss_g_dash'); c.shake(0.35); + this.go(c, 'gdash', MV.g_dash.active); + } + break; + case 'gdash': + gravity = true; wallStop = true; + if (this.timer <= 0) { this.box = 'antic'; this.go(c, 'gdash_rec1', this.rec(MV.g_dash.params.recover[0])); } + break; + case 'gdash_rec1': + gravity = true; this.vx *= CLK.perStep(MV.g_dash.params.decel[0]); + if (this.timer <= 0) { this.box = 'idle'; this.go(c, 'gdash_rec2', this.rec(MV.g_dash.params.recover[1])); } + break; + case 'gdash_rec2': + gravity = true; this.vx *= CLK.perStep(MV.g_dash.params.decel[1]); + if (this.timer <= 0) this.escalation(c); + break; + // jump / air dash / air sphere + case 'jump_antic': gravity = true; if (this.timer <= 0) this.jump(c); break; + case 'air': + gravity = true; this.airT += dt; + if (this.airT >= this.airPause) { this.adashAnticQ(c); break; } + if (this.willSphere && this.vy < 0 && this.y < SPHERE_Y) { + if (this.heroIn(c, 13.05, 35.9, 0, 0.722)) { // [data] "A Sphere Range" + this.willSphere = false; this.face(c); this.gs = 0; + this.go(c, 'a_sphere_antic', this.tele(c, MV.a_sphere.telegraph_scale)); + } else this.willSphere = false; + } + break; + case 'adash_antic': + this.vx = 0; this.vy = 0; + if (this.timer <= 0) { + var sp = MV.a_dash.params.speed * this.spd(), a = this.angle; + this.vx = Math.cos(a) * sp; this.vy = Math.sin(a) * sp; this.box = 'adash'; this.airPause = 999; + c.emit('boss_a_dash'); c.shake(0.35); + this.go(c, 'adash', 0); + } + break; + case 'adash': + P = MV.a_dash.params; + if (this.y <= GROUND) { + this.y = GROUND; this.box = 'idle'; this.gs = 1.5; this.vy = 0; c.emit('boss_land_hard'); c.shake(0.25); + this.go(c, 'hard_land', this.rec(P.hard_land)); + } else if (this.y >= ROOF) { + this.y = ROOF; this.vx = 0; this.vy = 0; this.gs = 2; this.box = 'idle'; this.inAir(c); + } else if (this.x <= WALL_L || this.x >= WALL_R) { + var left = this.x <= WALL_L; + this.x = left ? WALL_L : WALL_R; this.vx = 0; this.vy = 0; this.box = 'idle'; this.f = left ? 1 : -1; + c.emit('boss_wall'); c.shake(0.2); + this.go(c, 'wall_impact', this.rec(P.wall_impact)); + } + break; + case 'wall_impact': + if (this.timer <= 0) { + P = MV.a_dash.params; this.vx = P.wall_bounce[0] * this.f; this.vy = P.wall_bounce[1]; this.gs = 2; this.inAir(c); + } + break; + case 'hard_land': gravity = true; this.vx *= CLK.perStep(0.8); // [data] Hard Land DecelerateXY 0.8 + if (this.timer <= 0) this.escalation(c); break; + case 'land': gravity = true; this.vx = 0; if (this.timer <= 0) this.escalation(c); break; + case 'a_sphere_antic': + this.vx *= CLK.perStep(0.78); this.vy *= CLK.perStep(0.78); // [data] DecelerateV2 0.78 + if (this.timer <= 0) { this.sphere = { t: 0 }; c.emit('boss_a_sphere'); c.shake(0.3); this.go(c, 'a_sphere', MV.a_sphere.active); } + break; + case 'a_sphere': + this.vx *= CLK.perStep(0.78); this.vy *= CLK.perStep(0.78); + if (this.timer <= 0) { this.sphere = null; this.go(c, 'a_sphere_recover', this.rec(MV.a_sphere.params.recover)); } + break; + case 'a_sphere_recover': if (this.timer <= 0) { this.gs = 1.5; this.inAir(c); } break; + // ground sphere + case 'g_sphere_antic': + gravity = true; this.vx = 0; + if (this.timer <= 0) { this.sphere = { t: 0 }; c.emit('boss_g_sphere'); c.shake(0.3); this.go(c, 'g_sphere', MV.g_sphere.active); } + break; + case 'g_sphere': + gravity = true; + if (this.timer <= 0) { this.sphere = null; this.go(c, 'g_sphere_recover', this.rec(MV.g_sphere.params.recover)); } + break; + case 'g_sphere_recover': gravity = true; if (this.timer <= 0) this.escalation(c); break; + // needle throw + case 'throw_antic': + gravity = true; + if (this.timer <= 0) { + P = MV.throw.params; this.box = 'throwing'; + var dir = this.angle === 0 ? 1 : -1; + this.needle = { x: this.x, y: this.y - 0.5, x0: this.x, y0: this.y - 0.5, vx: dir * P.speed * this.spd(), ph: 'out', t: 0, dir: dir }; + c.emit('boss_throw'); + this.go(c, 'thrown', 0); + } + break; + case 'thrown': + gravity = true; + if (this.needle && this.needle.ph === 'done') { + this.needle = null; this.recoilOn = true; this.stun.stopped = false; this.stun.combo = 0; // [data] STUN CONTROL START + this.go(c, 'throw_recover', this.rec(MV.throw.params.recover)); + } + break; + case 'throw_recover': gravity = true; if (this.timer <= 0) this.escalation(c); break; + // evade + case 'evade_antic': + gravity = true; + if (this.timer <= 0) { this.vx = MV.evade.params.speed * this.s() * this.spd(); c.emit('boss_evade'); this.go(c, 'evade', MV.evade.active); } + break; + case 'evade': + gravity = true; wallStop = true; + if (this.timer <= 0) { this.vx = 0; this.go(c, 'evade_land', MV.evade.params.land); } + break; + case 'evade_land': + gravity = true; this.vx = 0; + if (this.timer <= 0) { if (c.rng.random() < 0.5) this.gSphereQ(c); else this.escalation(c); } + break; + // stun + case 'stun_air': gravity = true; break; + case 'stun_land': gravity = true; this.vx = 0; if (this.timer <= 0) this.go(c, 'stun_recover', 0.167); break; + case 'stun_recover': + gravity = true; + if (this.timer <= 0) { this.move = 'jump'; this.airPause = 999; this.willSphere = false; this.jumpAntic(c); } + break; + } + + // integrate + if (gravity) this.vy -= GRAV * this.gs * dt; + var rx = 0; + if (this.recoilT > 0) { this.recoilT -= dt; rx = this.recoilDir * 15; } // [data] recoil 15 u/s + this.x += (this.vx + rx) * dt; this.y += this.vy * dt; + if (this.st === 'adash') { // the dash resolves contact next tick; never render past a wall + this.x = Math.min(WALL_R, Math.max(WALL_L, this.x)); this.y = Math.min(ROOF, Math.max(GROUND, this.y)); + } else { + if (this.x < WALL_L) { this.x = WALL_L; if (wallStop) this.wallHit(c); else if (this.vx < 0) this.vx = 0; } + if (this.x > WALL_R) { this.x = WALL_R; if (wallStop) this.wallHit(c); else if (this.vx > 0) this.vx = 0; } + if (this.y > ROOF) { this.y = ROOF; if (this.vy > 0) this.vy = 0; } + if (this.y <= GROUND && this.vy <= 0) { + var wasAir = this.y < GROUND - 1e-9 || this.vy < -1e-6; + this.y = GROUND; this.vy = 0; + if (wasAir && this.st === 'air') { this.vx = 0; this.box = 'idle'; this.gs = 1.5; c.emit('boss_land'); this.go(c, 'land', this.rec(0.25)); } + else if (wasAir && this.st === 'stun_air') this.go(c, 'stun_land', this.rec(3.0)); // [data] 3 s, any hit ends it + } + } + + // hazards + if (this.needle) this.updateNeedle(c); + if (this.sphere) this.sphere.t += dt; + }; + Warden.prototype.wallHit = function (c) { + this.vx = 0; + if (this.st === 'run') this.gSphereQ(c); + else if (this.st === 'gdash') { this.box = 'antic'; this.go(c, 'gdash_rec1', this.rec(MV.g_dash.params.recover[0])); } + else if (this.st === 'evade') this.go(c, 'evade_land', MV.evade.params.land); + }; + Warden.prototype.adashAnticQ = function (c) { + var h = c.body, dx = (h.x - this.x) * this.s(), dy = (h.y + HERO_PIVOT) - this.y; + if (!BB.inPoly(dx, dy, ADASH_RANGE)) { this.inAir(c); return; } // CANCEL -> In Air (the wait restarts) + this.angle = Math.atan2(h.y + HERO_PIVOT + MV.a_dash.params.aim_offset_y - this.y, h.x - this.x); + this.face(c); this.vx = 0; this.vy = 0; this.gs = 0; + this.go(c, 'adash_antic', this.tele(c, MV.a_dash.telegraph_scale)); + }; + Warden.prototype.updateNeedle = function (c) { + var n = this.needle, P = MV.throw.params, dt = BB.DT; + n.t += dt; + if (n.ph === 'out') { + n.x += n.vx * dt; + if (n.t >= P.out_time || n.x < 0.3 || n.x > A.W - 0.3) { n.ph = 'decel'; n.t = 0; } + } else if (n.ph === 'decel') { + n.vx *= CLK.perStep(P.decel); n.x += n.vx * dt; + if (Math.abs(n.vx) < 0.5) { + n.ph = 'return'; n.t = 0; n.rx = n.x; n.ry = n.y; + n.dur = Math.max(0.05, Math.hypot(n.x - n.x0, n.y - n.y0) / (P.return_speed * this.spd())); + c.emit('boss_needle_return'); + } + } else if (n.ph === 'return') { + var u = Math.min(1, n.t / n.dur), e = 1 - Math.cos(u * Math.PI / 2); // [data] iTween easeInSine + n.x = n.rx + (n.x0 - n.rx) * e; n.y = n.ry + (n.y0 - n.ry) * e; + if (u >= 1) n.ph = 'done'; + } + }; + + // ---------- combat interface used by the sim ---------- + Warden.prototype.sphereRadius = function () { + if (!this.sphere) return 0; + var u = Math.min(1, this.sphere.t / MV.g_sphere.params.grow_time); + var P = MV.g_sphere.params; + return P.radius * (P.grow_from + (P.grow_to - P.grow_from) * Math.sin(u * Math.PI / 2)); // [data] easeOutSine + }; + // every shape that hurts the hero this tick + Warden.prototype.hazards = function () { + var out = [], s = this.s(), f = this.f; + if (this.st === 'dead') return out; + if (this.role() !== 'recovery' || this.st === 'hard_land' || this.st === 'land') { + if (this.st !== 'stun_air' && this.st !== 'stun_land' && this.st !== 'stun_recover') out.push({ kind: 'body', box: this.bodyBox() }); // [hand] no contact damage while staggered + } + if (this.st === 'gdash') out.push({ kind: 'needle_lunge', box: { x: this.x + f * 1.24, y: this.y - 0.78, w: 1.9, h: 0.42 } }); + if (this.st === 'adash') { + var ca = Math.cos(this.angle), sa = Math.sin(this.angle); + out.push({ kind: 'needle_lunge', seg: [this.x + ca * 0.3, this.y + sa * 0.3, this.x + ca * 2.15, this.y + sa * 2.15], r: 0.2 }); + } + if (this.needle) { + var n = this.needle; + out.push({ kind: 'needle', seg: [n.x - n.dir * 1.25, n.y, n.x + n.dir * 1.25, n.y], r: 0.12 }); + } + if (this.sphere) out.push({ kind: 'sphere', circle: [this.x - 0.0625 * s, this.y - 0.281, this.sphereRadius()] }); + return out; + }; + Warden.prototype.tinkBox = function () { + var n = this.needle; + return n ? { x: n.x, y: n.y, w: 3.25, h: 0.25 } : null; // [data] "Needle Tink" + }; + // a nail hit lands on the boss; returns 'flesh' | 'tink' | null + Warden.prototype.onNailHit = function (c, dmg, slashDir, slashFacing) { + if (this.st === 'dead') return null; + this.hp = Math.max(0, this.hp - dmg); this.hitFlash = 0.12; + c.emit('boss_hit'); + if (this.recoilOn && slashDir === 'side' && this.st !== 'gdash' && this.st !== 'adash') { + this.recoilT = 0.15; this.recoilDir = slashFacing; // [data] 15 u/s, 0.15 s; never upward + } + if (this.hp <= 0) { + this.st = 'dead'; this.needle = null; this.sphere = null; this.gs = 1.5; this.box = 'idle'; + c.emit('boss_dead'); c.shake(0.8); + return 'flesh'; + } + // stun control [data] (Stun Control FSM: Hit Max 10 is compared before the hit is counted, Combo 6, Combo Time 2 s, + // Stuns Max 5) = the wiki stagger table 11 / 6 (<2 s per hit) / 5: the 11th hit, or the 6th quick hit, staggers + var S = this.stun; + S.total++; + if (!S.stopped && !/^stun/.test(this.st)) { + S.combo++; S.comboT = 2.0; + if ((S.combo >= 6 || S.total > 10) && S.stuns < 5) { S.stuns++; S.combo = 0; S.total = 0; this.stunStart(c); return 'flesh'; } + } + this.tookDamage(c); + return 'flesh'; + }; + + Warden.prototype.state = function () { + var r = BB.r4, role = this.role(); + var hz = []; + if (this.needle) hz.push({ kind: 'needle', x: r(this.needle.x), y: r(this.needle.y - GROUND + 1.55), phase: this.needle.ph, dir: this.needle.dir }); + if (this.sphere) hz.push({ kind: 'sphere', x: r(this.x - 0.0625 * this.s()), y: r(this.y - 0.281), r: r(this.sphereRadius()) }); + return { + x: r(this.x), y: r(this.y - GROUND), vx: r(this.vx), vy: r(this.vy), facing: this.f, + hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: this.move, + telegraph_left: role === 'telegraph' ? r(Math.max(0, this.timer)) : 0, + aim_deg: this.st === 'adash_antic' || this.st === 'adash' ? r(this.angle * 180 / Math.PI) : null, + escalated: this.escalated, staggers: this.stun.stuns, hazards: hz + }; + }; + Warden.GROUND = GROUND; + BB.NeedleWarden = Warden; + BB.CASES = BB.CASES || {}; + BB.CASES['2d/needle_warden'] = { title: 'Green-Robed Lancer', Body: BB.Wanderer, Boss: Warden, arena: 'thorn_hollow' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/bosses/pale_vessel.js b/environments/games/web/games/hollowknight_remake/bosses/pale_vessel.js new file mode 100644 index 0000000000000000000000000000000000000000..a901a2e583b93053583664375329a65de1de2a3f --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/bosses/pale_vessel.js @@ -0,0 +1,494 @@ +// Boss "pale_vessel" - four-phase nail-bearer (2D). Behaviour follows the source fight's "Control" FSM (Idle Stance, +// Choice P1-P4 SendRandomEventV3 tables, Try Slash / Walk, Tele, Counter, DStab + plumes, SmallShot, ChestShot, Puppet, +// SelfStab, Roars), its "Phase Control" (HP 750 / 400 / 0 of 1000 -> heals 250) and "Stun Control" (combo 10 in < 1 s, +// 12 hits, 5 stuns, off from phase 3). Numbers: specs/pale_vessel.spec.js. +// Geometry: source room x 24.66..65.66 -> 0..W (SX on x positions, x speeds and x sizes); y unscaled, body bottom = y. +// HP model: max_hp = phases 1-3 (k.hp) + phase 4 (k.p4) and hp only ever goes down, so the verifier's 1 - hp/max_hp stays +// monotone; the source "heal to 250" is the p4 block becoming damageable after the phase-4 roar. +(function (g) { + var BB = g.BB; + var SPEC = BB.SPECS.pale_vessel; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.ARENA, SX = A.W / 41, SRC0 = 24.66, FLOOR_SRC = 6.53, GRAV = 60, GS = 3; + var BW = 2.19 * SX, BH = 2.86; // [data] collider 2.19 x 2.86 + var XMIN = BW / 2 + 0.15, XMAX = A.W - BW / 2 - 0.15; + function X(sx) { return (sx - SRC0) * SX; } + function heroSrcX(c) { return c.body.x / SX + SRC0; } + var IDLE_T = [[0.75, 1.0], [0.15, 0.3], [0.0, 0.25], [1.0, 1.0]]; // [data] Idle Time per phase + var EVADE_P = [0.0, 0.6, 0.15, -1]; // [data] Evade Chance per phase + var CHOICE = [ // [data] Choice P1..P4 (V3: weight, max, missMax) + [['SLASH', 'DASH', 'JUMP', 'TELE'], [0.3, 0.3, 0.2, 0.2], [3, 2, 1, 2], [4, 4, 6, 4]], + [['SLASH', 'DASH', 'JUMP', 'DSTAB', 'SMALLSHOT', 'TELE'], [0.2, 0.2, 0.05, 0.2, 0.175, 0.175], [3, 2, 1, 2, 2, 2], [6, 6, 9, 6, 6, 6]], + [['SELFSTAB', 'PUPPET', 'CHEST', 'DSTAB', 'SMALLSHOT', 'TELE'], [0.2, 0.2, 0.1, 0.2, 0.2, 0.1], [1, 2, 1, 3, 2, 2], [6, 6, 8, 6, 6, 6]], + [['WEAKSLASH', 'PUPPET', 'SELFSTAB'], [0.4, 0.4, 0.2], [1, 2, 1], [3, 2, 5]] + ]; + var HIDDEN = { tele_out: 1, tele_in: 1 }; + var STUN = { stun_air: 1, stun_fall: 1, stunned: 1, stun_up: 1, stun_idle: 1, pup_fall: 1 }; + var NOSTUN = { roar_antic: 1, roar: 1, roar_end: 1, p4_roar: 1, ss_antic: 1, ss_thrust: 1, ss_reantic: 1, ss_mini: 1, ss_rep: 1 }; + var ROLE = { + intro: 'idle', idle: 'idle', walk: 'idle', + slash_antic: 'telegraph', slash1: 'active', slash2: 'active', slash3: 'active', slash_recover: 'recovery', + dash_antic: 'telegraph', dash: 'active', dash_recover: 'recovery', + counter_antic: 'telegraph', counter: 'active', cs_block: 'telegraph', cslash: 'active', cs_recover: 'recovery', counter_end: 'recovery', + evade_antic: 'telegraph', evade: 'active', evade_recover: 'recovery', + jump_antic: 'telegraph', jump: 'active', land: 'recovery', + tele_out: 'telegraph', tele_in: 'telegraph', + dstab_antic: 'telegraph', dstab_jump: 'active', stomp_antic: 'telegraph', stomp: 'active', dstab_land: 'active', plume_gen: 'active', plume_up: 'recovery', + shot_antic: 'telegraph', shot: 'active', shot_recover: 'recovery', + chest_antic: 'telegraph', chest_rise: 'telegraph', chest: 'active', chest_pause: 'recovery', chest_fall: 'recovery', + pup_antic: 'telegraph', pup_up: 'active', pup_down: 'active', pup_slam: 'active', pup_end: 'recovery', pup_fall: 'recovery', pup_stand: 'recovery', + ss_antic: 'telegraph', ss_thrust: 'active', ss_reantic: 'telegraph', ss_mini: 'active', ss_rep: 'active', + weak_walk: 'idle', weak_antic: 'telegraph', weak_slash: 'active', + roar_antic: 'telegraph', roar: 'active', roar_end: 'recovery', p4_roar: 'active', + stun_air: 'recovery', stun_fall: 'recovery', stunned: 'recovery', stun_up: 'recovery', stun_idle: 'recovery', dead: 'recovery' + }; + + function Pale() {} + Pale.prototype.id = 'pale_vessel'; + BB.bossKit(Pale.prototype, SPEC, ROLE); + + Pale.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.h1 = Math.round(k.hp); this.p4 = Math.round(k.p4); + this.max_hp = this.hp = this.h1 + this.p4; + this.dmg = Math.max(1, Math.round(k.dmg)); this.plumeDmg = Math.max(1, Math.round(k.plume_dmg)); + this.x = X(52); this.y = 0; this.vx = 0; this.vy = 0; this.f = -1; this.air = false; this.gs = GS; + this.st = 'intro'; this.timer = 1.5; this.stT = 0; this.move = null; + this.track = {}; this.cycle = {}; this.hitFlash = 0; this.stamp = 0; + this.combo = 0; this.comboT = 0; this.total = 0; this.stuns = 0; + this.phase = 1; this.pending = 0; this.locked = false; this.willEvade = false; this.idleInit = true; + this.next = null; this.intent = null; this.loops = 0; this.shotT = 0; this.sweep = null; + this.blobs = []; this.plumes = []; this.plumeL = 0; this.plumeR = 0; this.rounds = 0; + }; + + // ---------- geometry ---------- + Pale.prototype.bodyBox = function () { return { x: this.x, y: this.y + BH / 2, w: BW, h: BH }; }; + Pale.prototype.hitTargets = function () { return [{ id: 'boss', box: HIDDEN[this.st] || this.st === 'dead' ? null : this.bodyBox() }]; }; + Pale.prototype.ahead = function (c) { return (c.body.x - this.x) / SX * this.f; }; // source units, + = in front + Pale.prototype.heroHigh = function (c) { return c.body.y + BB.WANDERER.PIVOT + FLOOR_SRC > MV.tele.params.hero_high; }; + + // ---------- FSM helpers ---------- + Pale.prototype.setIdle = function (c) { // [data] Set Idle Time / Will Evade per phase + this.vx = 0; this.gs = GS; this.next = null; this.intent = null; this.move = null; + if (this.pending > this.phase) return this.phaseUp(c); + var T = IDLE_T[this.phase - 1], t = this.idleInit ? 0.5 : c.rng.uniform(T[0], T[1]); + this.idleInit = false; + this.willEvade = c.rng.random() < EVADE_P[this.phase - 1]; + this.face(c); this.go(c, 'idle', t * this.k[SPEC.timing.idle.knob]); + }; + Pale.prototype.choice = function (c) { // [data] Choice P1..P4 (SendRandomEventV3) + var T = CHOICE[this.phase - 1]; + this.face(c); + this.attack(c, this.pick(c, 'p' + this.phase, T[0], T[1], T[2], T[3])); + }; + Pale.prototype.attack = function (c, ev) { + this.face(c); this.vx = 0; + switch (ev) { + case 'SLASH': return this.trySlash(c); + case 'DASH': return this.go(c, 'dash_antic', this.tele(c, MV.dash.telegraph_scale), 'dash'); + case 'JUMP': return this.startJump(c, false); + case 'TELE': return this.teleTo(c, null); + case 'COUNTER': return this.go(c, 'counter_antic', this.tele(c, MV.counter.telegraph_scale), 'counter'); + case 'EVADE': return this.go(c, 'evade_antic', this.tele(c, MV.evade.telegraph_scale), 'evade'); + case 'DSTAB': return this.go(c, 'dstab_antic', this.tele(c, MV.dstab.telegraph_scale), 'dstab'); + case 'SMALLSHOT': return this.go(c, 'shot_antic', this.tele(c, MV.barrage.telegraph_scale), 'barrage'); + case 'CHEST': { + var P = MV.outbreak.params, sx = this.x / SX + SRC0; + if (sx < P.centre[0] || sx > P.centre[1]) return this.teleTo(c, 'chest'); + return this.go(c, 'chest_antic', this.tele(c, MV.outbreak.telegraph_scale), 'outbreak'); + } + case 'PUPPET': return this.go(c, 'pup_antic', this.tele(c, MV.puppet.telegraph_scale), 'puppet'); + case 'SELFSTAB': return this.selfStab(c, false); + case 'WEAKSLASH': return this.go(c, 'weak_walk', c.rng.uniform(MV.weak_slash.params.walk_time[0], MV.weak_slash.params.walk_time[1]), 'weak_slash'); + } + this.setIdle(c); + }; + Pale.prototype.inSlashRange = function (c) { // [data] Slash range: -0.64..8 ahead, player not far above + var R = MV.slash.params.range, a = this.ahead(c); + return a >= R[0] && a <= R[1] && c.body.y - this.y < R[2]; + }; + Pale.prototype.trySlash = function (c) { // [data] Try Slash: in range -> slash; else jump at the player 30 % / walk 70 % + if (this.inSlashRange(c)) return this.go(c, 'slash_antic', this.tele(c, MV.slash.telegraph_scale), 'slash'); + if (c.rng.random() < 0.3) return this.startJump(c, true); + this.go(c, 'walk', c.rng.uniform(1.0, 2.0), null); + }; + Pale.prototype.startJump = function (c, atHero) { + this.intent = atHero ? 'hero' : 'random'; + this.go(c, 'jump_antic', this.tele(c, MV.jump.telegraph_scale), 'jump'); + }; + Pale.prototype.followUp = function (c) { // [data] after evade / jump: straight into an attack + var ev = this.phase === 1 ? ['SLASH', 'DASH'][c.rng.int(2)] : ['SLASH', 'DASH', 'SMALLSHOT', 'DSTAB'][c.rng.int(4)]; + this.attack(c, ev); + }; + Pale.prototype.teleTo = function (c, kind) { // [data] Tele Out 0.3 -> position -> Tele In 0.3 -> attack + this.next = kind; this.vx = 0; this.vy = 0; this.gs = 0; + this.go(c, 'tele_out', MV.tele.params.out, 'tele'); + }; + Pale.prototype.teleChoice = function (c) { // [data] Tele Choice P1 / P2 3 + if (this.phase === 1) return ['counter', 'slash', 'dash'][c.rng.pick([0.2, 0.4, 0.4])]; + var k = ['counter', 'slash', 'dash', 'dstab', 'shot'][c.rng.pick([0.1, 0.2, 0.2, 0.25, 0.25])]; + if (k === 'dstab' && this.heroHigh(c)) k = 'shot'; // [data] player above Hero High -> small shot instead + return k; + }; + Pale.prototype.telePos = function (c, kind) { // returns arena [x, y] + var P = MV.tele.params, hx = c.body.x / SX + SRC0, s0 = this.x / SX + SRC0, x, i; + if (kind === 'dstab') return [X(BB.clamp(hx, P.dstab_x[0], P.dstab_x[1])), P.dstab_y - 9.0]; + if (kind === 'chest') { var C = MV.outbreak.params.centre; return [X(c.rng.uniform(C[0], C[1])), 0]; } + if (kind === 'p4') return [X(45.16), 0]; + var r = P[kind] || P.slash; + for (i = 0; i < 24; i++) { + x = hx + (c.rng.random() < 0.5 ? -1 : 1) * c.rng.uniform(r[0], r[1]); + if (x >= P.range[0] && x <= P.range[1] && Math.abs(x - s0) >= P.self) break; + } + return [X(BB.clamp(x, P.range[0], P.range[1])), 0]; + }; + Pale.prototype.selfStab = function (c, long) { // [data] SelfStab: 2-3 loops (3 after the phase-3 roar) + var P = MV.self_stab.params; + this.loops = long ? P.loops_l : P.loops_s[0] + c.rng.int(P.loops_s[1] - P.loops_s[0] + 1); + this.go(c, 'ss_antic', this.tele(c, long ? P.antic_l : MV.self_stab.telegraph_scale), 'self_stab'); + }; + Pale.prototype.phaseUp = function (c) { // [data] P2 Roar / P3 Roar -> long self stab + this.phase++; this.vx = 0; + this.go(c, 'roar_antic', MV.roar.telegraph_scale, 'roar'); + c.emit('boss_phase', this.x, BH); + }; + Pale.prototype.p4Start = function (c) { // [data] HP 0 -> centre, Long Roar 3.0, collapse (heal = p4 block) + this.phase = 4; this.pending = 4; this.locked = true; + this.blobs = []; this.plumes = []; this.combo = 0; this.total = 0; + this.teleTo(c, 'p4'); c.emit('boss_phase', this.x, BH); c.shake(0.8); + }; + Pale.prototype.quickStun = function (c) { + this.vx = 0; this.move = null; + if (this.y > 0.01) { this.gs = GS; this.air = true; this.go(c, 'stun_air', 0); } + else this.go(c, 'stun_fall', 0.5); + }; + Pale.prototype.stunStart = function (c) { // [data] Stun Control: combo / hit max reached + this.stuns++; this.combo = 0; this.total = 0; this.next = null; this.intent = null; + this.blobs = this.blobs.filter(function (o) { return !o.chest; }); + this.vx = 0; this.vy = Math.max(this.vy, 8); this.air = true; this.gs = GS; + this.go(c, 'stun_air', 0, null); c.emit('boss_stun', this.x, BH / 2); c.shake(0.6); + }; + + Pale.prototype.update = function (c) { + var dt = BB.DT, st, P, b = c.body, dx = b.x - this.x, sp = this.spd(); + this.flash(dt); + this.timer -= dt; this.stT += dt; + if (this.comboT > 0) { this.comboT -= dt; if (this.comboT <= 0) this.combo = 0; } + st = this.st; + switch (st) { + case 'dead': this.vx = 0; break; + case 'intro': if (this.timer <= 0) this.setIdle(c); break; + case 'idle': // [data] Idle Stance: face, EVADE when close, MOVE after Idle Time + this.face(c); + if (this.willEvade && Math.abs(dx) < MV.evade.params.range * SX) this.attack(c, c.rng.random() < 0.5 ? 'EVADE' : 'COUNTER'); + else if (this.timer <= 0) this.choice(c); + break; + case 'walk': // [data] Walk 4 for U(1, 2) s, then tele; in range: SLASH / COUNTER / EVADE + this.face(c); this.vx = this.f * 4 * SX * sp; + if (this.inSlashRange(c)) this.attack(c, ['SLASH', 'COUNTER', 'EVADE'][c.rng.pick([0.6, 0.2, 0.2])]); + else if (this.timer <= 0) this.teleTo(c, null); + break; + // triple slash [data]: Slash1 at 44 for 0.1 s, 0.167, Slash2 29.3 / 0.05, 0.167, Slash3 29.3 / 0.05, Recover 0.333 + case 'slash_antic': if (this.timer <= 0) this.slashN(c, 0); break; + case 'slash1': case 'slash2': case 'slash3': + P = MV.slash.params; var n = +st.charAt(5) - 1; + if (this.stT >= P.time[n]) this.vx = 0; + if (this.timer <= 0) { if (n < 2) this.slashN(c, n + 1); else this.go(c, 'slash_recover', this.rec(P.recover)); } + break; + case 'slash_recover': if (this.timer <= 0) this.setIdle(c); break; + // lunge [data]: Dash Antic 0.583, 45 for 0.3 s, then x0.8 per frame for 0.45 s + case 'dash_antic': if (this.timer <= 0) { this.vx = this.f * MV.dash.params.speed * SX * sp; this.go(c, 'dash', MV.dash.active); } break; + case 'dash': if (this.timer <= 0) this.go(c, 'dash_recover', this.rec(MV.dash.params.recover)); break; + case 'dash_recover': this.vx *= BB.perTick(MV.dash.params.decel, 0.02); if (this.timer <= 0) this.setIdle(c); break; // [data] DecelerateXY 0.8 per 50 Hz FixedUpdate + // parry [data]: Counter Antic 0.25, stance 0.75; a blocked hit -> block 0.357 -> riposte at 88 for 0.05 -> 0.167 + 0.333 + case 'counter_antic': if (this.timer <= 0) this.go(c, 'counter', MV.counter.active); break; + case 'counter': if (this.timer <= 0) this.go(c, 'counter_end', MV.counter.params.end); break; + case 'counter_end': if (this.timer <= 0) this.setIdle(c); break; + case 'cs_block': if (this.timer <= 0) { this.face(c); this.vx = this.f * MV.counter.params.speed * SX * sp; this.go(c, 'cslash', MV.counter.params.slash); } break; + case 'cslash': if (this.timer <= 0) { this.vx = 0; P = MV.counter.params.recover; this.go(c, 'cs_recover', this.rec(P[0] + P[1])); } break; + case 'cs_recover': if (this.timer <= 0) this.setIdle(c); break; + // evade [data]: Antic 0.333, 40 backwards for 0.18 s, Recover 0.333, then straight into an attack + case 'evade_antic': if (this.timer <= 0) { this.vx = -this.f * MV.evade.params.speed * SX; this.go(c, 'evade', MV.evade.params.time); } break; + case 'evade': if (this.timer <= 0) { this.vx = 0; this.go(c, 'evade_recover', this.rec(MV.evade.params.recover)); } break; + case 'evade_recover': if (this.timer <= 0) this.followUp(c); break; + // jump [data]: Antic 0.333, vy U(55, 60), vx = 1.4 x dx (player or random point, |dx| >= 2.5), |vx| <= 40 + case 'jump_antic': + if (this.timer <= 0) { + P = MV.jump.params; var tx, s0 = this.x / SX + SRC0; + if (this.intent === 'hero') tx = heroSrcX(c); + else { var guard = 0; do { tx = c.rng.uniform(P.x[0], P.x[1]); } while (Math.abs(tx - s0) < P.min_dx && ++guard < 16); } + this.vx = BB.clamp((tx - s0) * P.aim_mult, -P.max_vx, P.max_vx) * SX; + this.vy = c.rng.uniform(P.vy[0], P.vy[1]); this.air = true; this.gs = GS; this.face(c); + this.go(c, 'jump'); + } + break; + case 'land': if (this.timer <= 0) { if (this.intent === 'hero' && this.inSlashRange(c)) this.attack(c, 'SLASH'); else this.setIdle(c); } break; + // teleport [data]: Tele Out 0.3 (gone) -> new position by the next attack -> Tele In 0.3 -> attack + case 'tele_out': + if (this.timer <= 0) { + var kind = this.next || this.teleChoice(c), pos = this.telePos(c, kind); + this.next = kind; this.x = BB.clamp(pos[0], XMIN, XMAX); this.y = pos[1]; this.vx = 0; this.vy = 0; + this.air = this.y > 0.01; this.gs = this.air ? 0 : GS; this.face(c); + this.go(c, 'tele_in', MV.tele.params['in']); + } + break; + case 'tele_in': + if (this.timer <= 0) { + var k2 = this.next; this.next = null; this.face(c); + if (k2 === 'dstab') { this.move = 'dstab'; this.go(c, 'stomp_antic', this.tele(c, MV.dstab.telegraph_scale)); } + else if (k2 === 'p4') { this.move = 'roar'; this.go(c, 'p4_roar', MV.roar.params['long']); } + else this.attack(c, { counter: 'COUNTER', slash: 'SLASH', dash: 'DASH', shot: 'SMALLSHOT', chest: 'CHEST' }[k2] || 'SLASH'); + } + break; + // dive + pillars [data]: Antic 0.333, jump (vx 3 x dx, vy 60), hang 0.333 over the player, stomp at -70 (vx 5), + // land 0.15, 10 plume rounds x 0.05 s spreading L / R by U(4.5, 5), Burst Pause 0.1, PLUMES UP (0.55 s), Recover 0.333 + case 'dstab_antic': + if (this.timer <= 0) { + P = MV.dstab.params; this.vx = BB.clamp(dx / SX * P.aim_mult, -40, 40) * SX; this.vy = P.jump_vy; + this.air = true; this.gs = GS; this.go(c, 'dstab_jump'); + } + break; + case 'dstab_jump': + if ((Math.abs(dx) < MV.dstab.params.range_w * SX && this.vy < 30) || this.vy <= 0) { + this.vx = 0; this.vy = 0; this.gs = 0; this.face(c); this.go(c, 'stomp_antic', this.tele(c, MV.dstab.telegraph_scale)); + } + break; + case 'stomp_antic': this.vx = 0; this.vy = 0; this.gs = 0; if (this.timer <= 0) { P = MV.dstab.params; this.vy = P.fall_vy; this.vx = this.f * P.fall_vx * SX; this.go(c, 'stomp'); } break; + case 'stomp': this.vy = MV.dstab.params.fall_vy; this.gs = 0; this.air = true; break; + case 'dstab_land': + if (this.timer <= 0) { + P = MV.plume.params; this.plumeL = this.x; this.plumeR = this.x + (c.rng.uniform(2.5, 5) - c.rng.uniform(2.5, 5)) * SX; + this.rounds = P.rounds; this.go(c, 'plume_gen', 0, 'plume'); + } + break; + case 'plume_gen': + if (this.timer <= 0) { + P = MV.plume.params; + if (this.rounds <= 0) { this.go(c, 'plume_burst', P.pause); break; } + this.rounds--; this.timer += P.every * this.k[SPEC.timing.telegraph.knob]; + var self = this; + [this.plumeL, this.plumeR].forEach(function (px) { if (px > 0.2 && px < A.W - 0.2) self.plumes.push({ x: px, warn: 99, life: MV.plume.active }); }); + this.plumeL -= c.rng.uniform(P.step[0], P.step[1]) * SX; this.plumeR += c.rng.uniform(P.step[0], P.step[1]) * SX; + } + break; + case 'plume_burst': + if (this.timer <= 0) { + this.plumes.forEach(function (o) { if (o.warn > 50) o.warn = 0; }); + c.emit('boss_plume', this.x, 0); c.shake(0.4); this.go(c, 'plume_up', this.rec(MV.plume.params.recover)); + } + break; + case 'plume_up': if (this.timer <= 0) this.setIdle(c); break; + // barrage [data]: SmallShot Antic 0.357; LowHigh (from 250 deg sweeping -90 deg/s, one / 0.15 s at 28) or + // HighLow (from 120 deg, +90 deg/s, one / 0.25 s at 30 slowing 15 / s) for 1.5 s; gravity 27; Recover 0.357 + case 'shot_antic': + if (this.timer <= 0) { + P = MV.barrage.params; var L = c.rng.random() < 0.5 ? P.low : P.high; + this.sweep = { a: L[0] + c.rng.uniform(-L[1], L[1]), da: L[2], every: L[3], v: L[4], dv: L[5] }; + this.shotT = 0; this.go(c, 'shot', P.time); + } + break; + case 'shot': + P = MV.barrage.params; var S = this.sweep; + S.a += S.da * dt; S.v += S.dv * dt; this.shotT -= dt; + if (this.shotT <= 0) { this.shotT += S.every / this.k.shot_rate; this.shoot(S.a, S.v, P.gravity, false); } + if (this.timer <= 0) this.go(c, 'shot_recover', this.rec(P.recover)); + break; + case 'shot_recover': if (this.timer <= 0) this.setIdle(c); break; + // outbreak [data]: ChestShot Antic 0.214, rise 4 at 15 (wait 0.85), U(5, 6) s of blobs every 0.15 s + // (one up-left, one up-right, 1-2 downward), Pause 0.75, fall + case 'chest_antic': if (this.timer <= 0) { this.gs = 0; this.air = true; this.vy = MV.outbreak.params.rise_v; this.baseY = this.y; this.go(c, 'chest_rise', MV.outbreak.params.rise_wait); } break; + case 'chest_rise': + P = MV.outbreak.params; this.gs = 0; + if (this.y >= this.baseY + P.rise) { this.y = this.baseY + P.rise; this.vy = 0; } + if (this.timer <= 0) { this.vy = 0; this.shotT = 0; this.go(c, 'chest', c.rng.uniform(P.time[0], P.time[1])); } + break; + case 'chest': + P = MV.outbreak.params; this.gs = 0; this.vy = 0; this.shotT -= dt; + if (this.shotT <= 0) { this.shotT += P.every / this.k.shot_rate; this.outbreakTick(c); } + if (this.timer <= 0) this.go(c, 'chest_pause', this.rec(P.pause)); + break; + case 'chest_pause': this.gs = 0; this.vy = 0; if (this.timer <= 0) { this.gs = GS; this.go(c, 'chest_fall'); } break; + // puppet slams [data]: Up vy 25 (x0.95 / frame) chasing (max 20, accel 1) 1 s -> Down -50 -> Slam 0.083 -> + // ReUp vy 75 (x0.88) accel 1.5 for 0.65 s ... 2-5 slams -> End 0.167 -> Fall Down 1.0 -> Stand 0.417 + case 'pup_antic': + if (this.timer <= 0) { + P = MV.puppet.params; this.loops = P.loops[0] + c.rng.int(P.loops[1] - P.loops[0] + 1); + this.air = true; this.gs = 0; this.vy = P.up[0]; this.pupDecay = P.up[1]; this.pupAcc = P.chase[1]; this.go(c, 'pup_up', P.up[2]); + } + break; + case 'pup_up': + P = MV.puppet.params; this.gs = 0; this.vy *= BB.perTick(this.pupDecay, 0.02); /* [data] Puppet Up/ReUp DecelerateXY y 0.95 / 0.88 per 50 Hz step */ this.chase(c, P.chase[0], this.pupAcc, dt); + if (this.timer <= 0) { this.vy = P.down; this.go(c, 'pup_down', 2.0); } + break; + case 'pup_down': + this.gs = 0; this.vy = MV.puppet.params.down; this.chase(c, MV.puppet.params.chase[0], MV.puppet.params.chase[1], dt); + if (this.timer <= 0) this.pupSlam(c); + break; + case 'pup_slam': + if (this.timer <= 0) { + P = MV.puppet.params; + if (--this.loops > 0) { this.air = true; this.gs = 0; this.vy = P.reup[0]; this.pupDecay = P.reup[1]; this.pupAcc = P.chase[2]; this.go(c, 'pup_up', P.reup[2]); } + else this.go(c, 'pup_end', P.end); + } + break; + case 'pup_end': this.vx = 0; if (this.timer <= 0) this.go(c, 'pup_fall', this.rec(MV.puppet.params.fall)); break; + case 'pup_fall': this.vx = 0; if (this.timer <= 0) this.go(c, 'pup_stand', this.rec(MV.puppet.params.stand)); break; + case 'pup_stand': if (this.timer <= 0) this.setIdle(c); break; + // self stab [data]: Antic 0.5 (1.2) -> Thrust 1.75 -> per extra loop Reantic 0.5 + Mini Thrust 0.25 + 0.25 -> collapse + case 'ss_antic': if (this.timer <= 0) this.go(c, 'ss_thrust', MV.self_stab.active); break; + case 'ss_thrust': case 'ss_rep': + if (this.timer <= 0) { if (--this.loops > 0) this.go(c, 'ss_reantic', MV.self_stab.params.reantic); else this.quickStun(c); } + break; + case 'ss_reantic': if (this.timer <= 0) this.go(c, 'ss_mini', MV.self_stab.params.mini); break; + case 'ss_mini': if (this.timer <= 0) this.go(c, 'ss_rep', MV.self_stab.params.rep); break; + // phase 4 swing [data]: walk 3 toward the player, Slash1 Antic 0.583, one slash in place, then collapse + case 'weak_walk': + this.face(c); this.vx = this.f * MV.weak_slash.params.walk * SX; + if (this.timer <= 0 || this.inSlashRange(c)) { this.vx = 0; this.go(c, 'weak_antic', this.tele(c, MV.weak_slash.telegraph_scale)); } + break; + case 'weak_antic': if (this.timer <= 0) this.go(c, 'weak_slash', MV.weak_slash.active); break; + case 'weak_slash': if (this.timer <= 0) this.quickStun(c); break; + // roars [data]: Roar Antic 0.583, Roar 1.25, RoarToIdle 0.25; phase 3 continues into the long self stab + case 'roar_antic': if (this.timer <= 0) { c.shake(0.5); this.go(c, 'roar', MV.roar.active); } break; + case 'roar': if (this.timer <= 0) this.go(c, 'roar_end', MV.roar.params.end); break; + case 'roar_end': if (this.timer <= 0) { if (this.phase === 3) this.selfStab(c, true); else this.setIdle(c); } break; + case 'p4_roar': if (this.timer <= 0) { this.locked = false; this.quickStun(c); } break; + // stagger [data]: Stun Air -> land -> Stun Fall 0.5 -> Stun 2.25 (hit -> StunHitUp 0.417) -> StunToIdle 0.417 -> 50 % tele + case 'stun_fall': this.vx = 0; if (this.timer <= 0) this.go(c, 'stunned', 2.25); break; + case 'stunned': this.vx = 0; if (this.timer <= 0) this.go(c, 'stun_idle', 0.417); break; + case 'stun_up': if (this.timer <= 0) this.setIdle(c); break; + case 'stun_idle': + if (this.timer <= 0) { if ((this.phase === 2 || this.phase === 3) && this.pending <= this.phase && c.rng.random() < 0.5) this.teleTo(c, null); else this.setIdle(c); } + break; + } + + // physics + if (this.air) this.vy -= GRAV * this.gs * dt; + this.x += this.vx * dt; this.y += this.vy * dt; + if (this.x < XMIN) { this.x = XMIN; if (this.vx < 0) this.vx = 0; } + if (this.x > XMAX) { this.x = XMAX; if (this.vx > 0) this.vx = 0; } + if (this.y + BH > A.H) { this.y = A.H - BH; if (this.vy > 0) this.vy = 0; } + if (this.y <= 0 && (this.air || this.vy < 0)) { + this.y = 0; this.vy = 0; var was = this.air; this.air = false; + if (was) this.land(c); + } else if (this.y > 0 && !this.air && this.gs > 0) this.air = true; + this.updateShots(c, dt); + }; + Pale.prototype.slashN = function (c, n) { + var P = MV.slash.params; + this.vx = this.f * P.speed[n] * SX * this.spd(); + this.go(c, 'slash' + (n + 1), P.time[n] + (n < 2 ? P.gap : 0)); + }; + Pale.prototype.chase = function (c, max, acc, dt) { // [data] ChaseObjectGround: accel per frame, capped speed + var want = c.body.x > this.x ? 1 : -1; + this.vx = BB.clamp(this.vx + want * acc * 60 * SX * dt, -max * SX, max * SX); + }; + Pale.prototype.pupSlam = function (c) { + this.vx = 0; this.vy = 0; c.emit('boss_land_hard', this.x, 0); c.shake(0.5); + this.go(c, 'pup_slam', MV.puppet.params.slam); + }; + Pale.prototype.shoot = function (deg, v, grav, chest) { // source angles are for a boss facing left; mirrored when facing right + var a = (this.f < 0 ? deg : 180 - deg) * Math.PI / 180; + this.blobs.push({ x: this.x + this.f * 0.4, y: this.y + 1.9, vx: Math.cos(a) * v * SX, vy: Math.sin(a) * v, g: grav, chest: chest }); + }; + Pale.prototype.outbreakTick = function (c) { // [data] Chest Shot: up-left, up-right and 1-2 downward each tick + var P = MV.outbreak.params, r = c.rng, n = 1 + r.int(2), i, a, v; + this.blobs.push({ x: this.x, y: this.y + 1.9, vx: r.uniform(P.left[0], P.left[1]) * SX, vy: r.uniform(P.left[2], P.left[3]), g: P.gravity, chest: true }); + this.blobs.push({ x: this.x, y: this.y + 1.9, vx: r.uniform(P.right[0], P.right[1]) * SX, vy: r.uniform(P.right[2], P.right[3]), g: P.gravity, chest: true }); + for (i = 0; i < n; i++) { + a = r.uniform(P.down[0], P.down[1]) * Math.PI / 180; v = r.uniform(P.down[2], P.down[3]); + this.blobs.push({ x: this.x, y: this.y + 1.2, vx: Math.cos(a) * v * SX, vy: Math.sin(a) * v, g: P.gravity, chest: true }); + } + }; + Pale.prototype.updateShots = function (c, dt) { + var R = MV.barrage.params.r; + this.blobs = this.blobs.filter(function (o) { + o.vy -= o.g * dt; o.x += o.vx * dt; o.y += o.vy * dt; + if (o.y <= R) { c.emit('boss_land', o.x, 0); return false; } + return o.x > -1 && o.x < A.W + 1 && o.y < A.H + 4; + }); + this.plumes = this.plumes.filter(function (o) { + if (o.warn > 50) return true; // charging until PLUMES UP + if (o.warn > 0) { o.warn -= dt; return true; } + o.life -= dt; return o.life > 0; + }); + }; + Pale.prototype.land = function (c) { + var st = this.st; + this.vx = 0; c.emit('boss_land', this.x, 0); + if (st === 'jump') this.go(c, 'land', this.rec(MV.jump.params.recover)); + else if (st === 'stomp') { c.shake(0.6); c.emit('boss_land_hard', this.x, 0); this.go(c, 'dstab_land', MV.dstab.params.land); } + else if (st === 'pup_down') this.pupSlam(c); + else if (st === 'stun_air') this.go(c, 'stun_fall', 0.5); + else if (st === 'chest_fall' || st === 'dstab_jump') this.setIdle(c); + else if (st !== 'dead' && this.role() !== 'idle' && !STUN[st]) this.setIdle(c); + }; + + // ---------- combat interface ---------- + Pale.prototype.slashBox = function (n) { // [data] slash colliders: x from..to ahead (source units), y 0..3.5 + var P = MV.slash.params, a = P.ahead[n], x0 = this.x + this.f * a[0] * SX, x1 = this.x + this.f * a[1] * SX; + return { x: (x0 + x1) / 2, y: this.y + (P.y[0] + P.y[1]) / 2, w: Math.abs(x1 - x0), h: P.y[1] - P.y[0] }; + }; + Pale.prototype.hazards = function () { + var out = [], st = this.st, P, self = this, n; + if (st === 'dead') return out; + if (!STUN[st] && !HIDDEN[st] && st !== 'pup_end') out.push({ kind: 'body', box: this.bodyBox() }); + if (st === 'slash1' || st === 'slash2' || st === 'slash3') { + n = +st.charAt(5) - 1; + if (this.stT < MV.slash.params.time[n] + 0.1) out.push({ kind: 'nail', box: this.slashBox(n) }); // [hand] 0.1 s swing tail + } + if (st === 'weak_slash') out.push({ kind: 'nail', box: this.slashBox(0) }); + if (st === 'cslash' || (st === 'cs_recover' && this.stT < 0.1)) out.push({ kind: 'nail', box: this.slashBox(1) }); + if (st === 'dash' || (st === 'dash_recover' && Math.abs(this.vx) > 3)) { + P = MV.dash.params.box; out.push({ kind: 'nail', box: { x: this.x + this.f * P[0] * SX * 0.35, y: this.y + P[1] / 2, w: P[0] * SX, h: P[1] } }); + } + if (st === 'stomp' || st === 'dstab_land') out.push({ kind: 'nail', box: { x: this.x, y: this.y + 0.2, w: 1.0, h: 1.4 } }); + P = MV.plume.params; + this.plumes.forEach(function (o) { if (o.warn <= 0) out.push({ kind: 'plume', box: { x: o.x, y: P.h / 2, w: Math.max(0.5, P.w * SX * 1.4), h: P.h }, dmg: self.plumeDmg, fromX: o.x }); }); + this.blobs.forEach(function (o) { out.push({ kind: 'blob', circle: [o.x, o.y, MV.barrage.params.r], fromX: o.x - (o.vx < 0 ? -1 : 1) }); }); + return out; + }; + Pale.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + var st = this.st; + if (st === 'dead' || HIDDEN[st]) return null; + if (st === 'counter' && (c.body.x - this.x) * this.f > -0.2) { // [data] Counter Stance: BLOCKED HIT -> riposte + this.vx = 0; this.go(c, 'cs_block', this.tele(c, MV.counter.params.block)); c.emit('tink'); return 'tink'; + } + if (this.locked) { c.emit('tink'); return 'tink'; } // invulnerable through the phase-4 roar + var d = /^ss_/.test(st) ? MV.self_stab.params.hit_dmg : Math.round(this.k.nail); + this.hp -= d; this.hitFlash = 0.12; c.emit('boss_hit'); + if (this.hp <= 0) { this.hp = 0; this.st = 'dead'; this.blobs = []; this.plumes = []; this.vx = 0; c.emit('boss_dead', this.x, 1); c.shake(0.8); return 'flesh'; } + if (this.phase < 4) { // [data] Phase Control: 750 / 400 / 0 of 1000 (scaled with k.hp) + var rem = this.hp - this.p4; + if (rem <= 0) { this.hp = this.p4; this.p4Start(c); return 'flesh'; } + if (rem <= 0.4 * this.h1) this.pending = Math.max(this.pending, 3); + else if (rem <= 0.75 * this.h1) this.pending = Math.max(this.pending, 2); + } + if (st === 'stunned') { this.go(c, 'stun_up', 0.417); return 'flesh'; } + if (this.phase < 3 && this.pending < 3 && !STUN[st] && !NOSTUN[st]) { // [data] Stun Control, off from phase 3 + this.total++; this.combo++; this.comboT = 1.0; + if ((this.combo >= Math.round(this.k.stun_combo) || this.total > Math.round(this.k.stun_total)) && this.stuns < 5) { this.stunStart(c); return 'flesh'; } + } + if (st === 'idle' && this.phase < 4) { // [data] TOOK DAMAGE: EVADE / SLASH / TELE / DASH / stay + if (this.pending > this.phase) { this.phaseUp(c); return 'flesh'; } + var r = c.rng.pick([0.185, 0.185, 0.24, 0.19, 0.2]); + if (r < 4) this.attack(c, ['EVADE', 'SLASH', 'TELE', 'DASH'][r]); + } + return 'flesh'; + }; + Pale.prototype.state = function () { + var r = BB.r4, role = this.role(), self = this, P = MV.plume.params; + var charge = this.st === 'plume_gen' ? this.rounds * P.every + P.pause : this.st === 'plume_burst' ? Math.max(0, this.timer) : 0; + var hz = this.blobs.map(function (o) { return { kind: 'blob', x: r(o.x), y: r(o.y), vx: r(o.vx), vy: r(o.vy), warn: 0 }; }) + .concat(this.plumes.map(function (o) { return { kind: 'plume', x: r(o.x), y: 0, vx: 0, vy: 0, warn: r(o.warn > 50 ? charge : Math.max(0, o.warn)) }; })); + return { + x: r(this.x), y: r(this.y), vx: r(this.vx), vy: r(this.vy), facing: this.f, + hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: this.move, + telegraph_left: role === 'telegraph' ? r(Math.max(0, this.timer)) : 0, aim_deg: null, + escalated: this.phase > 1, phase: this.phase, staggers: this.stuns, hazards: hz + }; + }; + BB.PaleVessel = Pale; + BB.CASES = BB.CASES || {}; + BB.CASES['2d/pale_vessel'] = { title: 'Split-Chest Swordsman', Body: BB.Wanderer, Boss: Pale, arena: 'black_egg' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/bosses/sickle_sisters.js b/environments/games/web/games/hollowknight_remake/bosses/sickle_sisters.js new file mode 100644 index 0000000000000000000000000000000000000000..90b859ba499d763e9ec5ec4f8f41e0ec76f479b7 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/bosses/sickle_sisters.js @@ -0,0 +1,304 @@ +// Boss "sickle_sisters" - three lance duelists (2D). Behaviour follows the source fight's per-lord "Mantis Lord" FSM +// (Attack Choice V3: Dash / Dstab / Throw, High Throw when the player hugs a wall or flies high), the "Battle Sub" +// controller that drives the last two together (7 choreographies, V3) and the boomerang blade's "Control" FSM. +// Numbers: specs/sickle_sisters.spec.js. Geometry: source cage x 17..43 -> 0..W (SX on x positions / x speeds / x +// offsets), floor y 6.08 -> 0; a lord's source pivot y maps to body-bottom y = pivot - 8.99 (Land Y puts her feet on it). +(function (g) { + var BB = g.BB; + var SPEC = BB.SPECS.sickle_sisters; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.ARENA, SX = A.W / 26, LIFT = 8.99; + var BW = 1.344 * SX, BH = 2.391; // [data] collider 1.344 x 2.391 + function X(sx) { return (sx - 17) * SX; } + function Y(sy) { return Math.max(0, sy - LIFT); } + function heroSrc(c) { return { x: c.body.x / SX + 17, y: c.body.y + BB.WANDERER.PIVOT + 6.08 }; } + var ROLE = { + gone: 'idle', start: 'idle', idle: 'idle', sub_idle: 'idle', after_throw: 'idle', dying: 'recovery', + dash_arrive: 'telegraph', dash_antic: 'telegraph', dash: 'active', dash_recover: 'recovery', dash_leave: 'recovery', + dstab_arrive: 'telegraph', dstab_fall: 'active', dstab_land: 'recovery', dstab_leave: 'recovery', + wall_arrive: 'telegraph', throw_antic: 'telegraph', throw: 'active', throw_cd: 'recovery', leave_pause: 'recovery', wall_leave: 'recovery', + gap: 'idle', duo_wait: 'idle', dead: 'recovery' + }; + var READY = { start: 1, idle: 1, sub_idle: 1 }; // states that take a command from the duo controller + + // ---------------- one lord ---------------- + function Sister(id, hp, k) { + this.id = id; this.hp = hp; this.k = k; + this.x = A.W / 2; this.y = 0; this.vx = 0; this.vy = 0; this.f = -1; + this.st = 'gone'; this.timer = 0; this.stT = 0; this.move = null; this.on = false; this.sub = false; + this.track = {}; this.cycle = {}; this.hitFlash = 0; this.stamp = 0; this.dir = 1; this.shot = null; + } + BB.bossKit(Sister.prototype, SPEC, ROLE); + Sister.prototype.to = function (st, timer) { this.st = st; this.timer = timer; this.stT = 0; }; // no announce + Sister.prototype.enter = function () { this.to('start', 0.5); this.on = false; }; // [data] Start Pause 0.5 + Sister.prototype.away = function (c) { // [data] Away -> Idle 0.4 s (Sub: then Sub Idle) + this.on = false; this.vx = 0; this.vy = 0; this.move = null; + this.go(c, 'idle', 0.4 * this.k[SPEC.timing.idle.knob]); + }; + Sister.prototype.box = function () { + var h = this.st.indexOf('dash') === 0 ? MV.dash.params.body_h : BH; // [hand] crouched lance pose on the floor + return { x: this.x, y: this.y + h / 2, w: BW, h: h }; + }; + Sister.prototype.attackChoice = function (c) { // [data] Attack Choice: high / wall check, then V3 + var h = heroSrc(c), P = MV.high_throw.params; + if (h.y > P.hero_y || h.x < P.hero_x[0] || h.x > P.hero_x[1]) return this.highThrow(c); + var ev = this.pick(c, 'atk', ['DASH', 'DSTAB', 'THROW'], [1, 1, 1], [2, 3, 2], [5, 5, 5]); + if (ev === 'DASH') this.dashDir(c); + else if (ev === 'DSTAB') this.dstab(c); + else this.wallThrow(c); + }; + Sister.prototype.dashDir = function (c) { // [data] Dash Dir: start on the far side from the player + var hx = heroSrc(c).x, P = MV.dash.params; + this.dash(c, hx < P.hero_split[0] ? -1 : hx > P.hero_split[1] ? 1 : (c.rng.random() < 0.5 ? -1 : 1)); + }; + Sister.prototype.dash = function (c, dir) { // dir +1 = "Dash R": appear at Dash X L, run right + var P = MV.dash.params; + this.dir = dir; this.f = dir; this.x = X(dir > 0 ? P.x[0] : P.x[1]); this.y = 0; this.vx = 0; this.vy = 0; this.on = true; + this.go(c, 'dash_arrive', this.tele(c, P.arrive), 'dash'); + }; + Sister.prototype.dstab = function (c) { // [data] Dstab Pos / Shift? / Shift Y? + var P = MV.dstab.params, h = heroSrc(c), sx = BB.clamp(h.x, P.x[0], P.x[1]); + if (c.rng.random() < 0.5) sx = BB.clamp(sx + c.rng.uniform(-P.shift, P.shift), P.x[0], P.x[1]); + this.x = X(sx); this.y = Y(h.y > P.hero_high ? P.y_high : P.y); this.vx = 0; this.vy = 0; this.on = true; + if (c.rng.random() < 0.5) this.f = -this.f; + this.go(c, 'dstab_arrive', this.tele(c, MV.dstab.telegraph_scale), 'dstab'); + }; + Sister.prototype.wall = function (c, right, sy, kind) { // Throw L / Throw R: cling to a side wall, face inward + var P = MV.throw.params; + this.x = X(right ? P.wall_x[1] : P.wall_x[0]); this.y = Y(sy); + this.f = right ? -1 : 1; this.vx = 0; this.vy = 0; this.on = true; this.shot = kind; + this.go(c, 'wall_arrive', this.tele(c, 0.45), kind.move); // [data] Wall Arrive clip 0.45 s + }; + Sister.prototype.wallSide = function (c) { // [data] Throw Pos: wall away from the player, else random + var hx = heroSrc(c).x, P = MV.throw.params; + return hx < P.hero_wall[0] ? true : hx > P.hero_wall[1] ? false : c.rng.random() < 0.5; + }; + Sister.prototype.wallThrow = function (c) { // [data] Throw UD?: high wall + sinking blade, or low + rising + var P = MV.throw.params, ud = c.rng.random() < 0.5; + var sy = ud ? c.rng.uniform(P.y_ud[0], P.y_ud[1]) : c.rng.uniform(P.y_du[0], P.y_du[1]); + this.wall(c, this.wallSide(c), sy, { move: 'throw', ud: ud }); + }; + Sister.prototype.highThrow = function (c) { // [data] High Check LR: wall at the player's height - 1 + var P = MV.high_throw.params, sy = BB.clamp(heroSrc(c).y - 1, P.y_clamp[0], P.y_clamp[1]); + this.wall(c, this.wallSide(c), sy, { move: 'high_throw', ud: true }); + }; + Sister.prototype.duoThrow = function (c, right, wide) { // [data] Wide / Narrow Throw L|R: y U(14.5, 15.5) + var W = MV.duo.params.wall_y; + this.wall(c, right, c.rng.uniform(W[0], W[1]), { move: 'duo', wide: wide }); + }; + Sister.prototype.spawnBlade = function (c, boss) { // [data] Shot Mantis Lord "Control" + var B = MV.blade.params, s = this.shot, P = MV.throw.params, dir = this.f, vx, fx, vy; + var x = this.x + dir * Math.abs(P.point[0]) * SX, y = this.y + LIFT - 6.08 + P.point[1]; + if (s.wide != null) { var T = s.wide ? B.wide : B.narrow; vx = T[0]; fx = T[1]; vy = T[2]; } + else { + vx = B.vx; fx = B.force; vy = s.ud ? -B.vy : B.vy; + if (!s.ud) { y -= B.du_drop; if (y + 6.08 > B.corner_y) vy = B.corner_vy; } + } + var sp = this.k[SPEC.locomotion.knob]; + boss.blades.push({ id: boss.bid++, x: x, y: Math.max(0.5, y), vx: vx * dir * SX * sp, fx: fx * dir * SX * sp * sp, vy: vy, life: B.life / sp }); + }; + // command from the duo controller (Battle Sub "SendEventByName" targets) + Sister.prototype.order = function (c, ev, arg) { + if (ev === 'DASH') this.dashDir(c); + else if (ev === 'DASH L') this.dash(c, -1); + else if (ev === 'DASH R') this.dash(c, 1); + else if (ev === 'DSTAB') this.dstab(c); + else if (ev === 'HIGH THROW') this.highThrow(c); + else if (ev === 'THROW') this.duoThrow(c, arg.right, arg.wide); + }; + Sister.prototype.update = function (c, boss) { + var dt = BB.DT, P, sp = this.k[SPEC.locomotion.knob]; + this.stT += dt; this.timer -= dt; this.flash(dt); + switch (this.st) { + case 'gone': case 'gap': break; + case 'start': if (this.timer <= 0) this.to(this.sub ? 'sub_idle' : 'idle', 0.4 * this.k[SPEC.timing.idle.knob]); break; + case 'idle': + if (this.sub) { this.st = 'sub_idle'; break; } + if (this.timer <= 0) this.attackChoice(c); + break; + case 'sub_idle': if (!this.sub) this.to('idle', 0.4 * this.k[SPEC.timing.idle.knob]); break; + case 'dash_arrive': if (this.timer <= 0) this.go(c, 'dash_antic', this.tele(c, MV.dash.params.antic)); break; + case 'dash_antic': if (this.timer <= 0) { this.vx = this.dir * MV.dash.params.speed * SX * sp; this.go(c, 'dash', 0); } break; + case 'dash': + P = MV.dash.params; this.x += this.vx * dt; + var end = X(this.dir > 0 ? P.x[1] : P.x[0]); + if ((this.dir > 0 && this.x >= end) || (this.dir < 0 && this.x <= end)) { + this.x = end; this.vx = 0; this.go(c, 'dash_recover', this.rec(P.recover)); + } + break; + case 'dash_recover': if (this.timer <= 0) { this.on = false; this.to('dash_leave', MV.dash.params.leave); } break; + case 'dash_leave': case 'dstab_leave': if (this.timer <= 0) this.away(c); break; + case 'wall_leave': if (this.timer <= 0) { this.on = false; this.to('after_throw', MV.throw.params.after); } break; // [data] After Throw Pause 0.65 (off stage) + case 'dstab_arrive': if (this.timer <= 0) { this.vy = MV.dstab.params.speed * sp; this.go(c, 'dstab_fall', 0); } break; + case 'dstab_fall': + P = MV.dstab.params; // [data] ChaseObjectGround speedMax 7, accel 7 + var dx = c.body.x - this.x, want = BB.clamp(dx * 8, -P.chase[0], P.chase[0]) * SX; + this.vx += BB.clamp(want - this.vx, -P.chase[1] * SX * dt, P.chase[1] * SX * dt); + this.x = BB.clamp(this.x + this.vx * dt, BW / 2, A.W - BW / 2); this.y += this.vy * dt; + if (this.y <= 0) { + this.y = 0; this.vy = 0; this.vx = 0; c.emit('boss_land_hard', this.x, 0); c.shake(0.4); + this.go(c, 'dstab_land', this.rec(P.land)); + } + break; + case 'dstab_land': if (this.timer <= 0) { this.to('dstab_leave', MV.dstab.params.leave); } break; + case 'wall_arrive': if (this.timer <= 0) this.go(c, 'throw_antic', this.tele(c, 0.417)); break; + case 'throw_antic': if (this.timer <= 0) { this.spawnBlade(c, boss); this.go(c, 'throw', MV.throw.active); } break; + case 'throw': if (this.timer <= 0) this.to('throw_cd', this.rec(MV.throw.params.cd)); break; + case 'throw_cd': if (this.timer <= 0) this.to('leave_pause', this.rec(MV.throw.params.leave[0])); break; + case 'leave_pause': if (this.timer <= 0) this.to('wall_leave', MV.throw.params.leave[1] + MV.throw.params.leave[2]); break; + case 'after_throw': if (this.timer <= 0) this.away(c); break; + case 'dying': + this.vy -= 40 * dt; this.y = Math.max(0, this.y + this.vy * dt); + if (this.timer <= 0) { this.on = false; this.st = 'dead'; } + break; + } + }; + + // ---------------- the fight: one lord, then the other two together (Battle Sub) ---------------- + function Sisters() {} + Sisters.prototype.id = 'sickle_sisters'; + Sisters.prototype.spec = SPEC; + Sisters.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.max_hp = this.hp = Math.round(k.hp); + this.dmg = Math.max(1, Math.round(k.dmg)); + var h0 = Math.round(this.max_hp * 210 / 530), h1 = Math.round(this.max_hp * 160 / 530); // [wiki] 210 / 160 / 160 + this.sis = [new Sister(0, h0, k), new Sister(1, h1, k), new Sister(2, this.max_hp - h0 - h1, k)]; + this.sis[0].enter(); this.sis[0].f = -1; + this.phase = 1; this.ctl = null; this.ctlT = 0; this.queue = []; this.gapT = 0; + this.track = {}; this.cycle = {}; this.blades = []; this.bid = 0; this.stamp = 0; + this.x = A.W / 2; this.y = 0; this.vx = 0; this.vy = 0; this.f = -1; this.hitFlash = 0; + this.st = 'start'; this.timer = 0; this.stT = 0; this.move = null; this.offstage = true; + this.sub1 = 1; this.sub2 = 2; + }; + Sisters.prototype.alive = function () { return this.sis.filter(function (s) { return s.st !== 'gone' && s.st !== 'dead' && s.st !== 'dying' && s.hp > 0; }); }; + Sisters.prototype.primary = function () { + for (var i = 0; i < 3; i++) { var s = this.sis[i]; if (s.on && s.st !== 'dead') return s; } + return null; + }; + Sisters.prototype.pick = Sister.prototype.pick; + // Battle Sub "Choose Move": hero high / at a wall -> High Throw, else V3 over the 7 choreographies + Sisters.prototype.choose = function (c) { + var D = MV.duo.params, h = heroSrc(c), H = MV.high_throw.params, s1 = this.sis[this.sub1], s2 = this.sis[this.sub2]; + var wait = this.k[SPEC.timing.idle.knob], self = this; + function send(s, ev, delay, arg) { self.queue.push({ t: delay * wait, s: s, ev: ev, arg: arg || {} }); } + if (c.rng.random() < 0.5) { var t = this.sub1; this.sub1 = this.sub2; this.sub2 = t; s1 = this.sis[this.sub1]; s2 = this.sis[this.sub2]; } // [data] Set Subs + if (h.y > H.hero_y || h.x < H.hero_x[0] || h.x > H.hero_x[1]) { send(s1, 'HIGH THROW', 0.5); this.ctlT = D.high_wait + 0.5; this.move = 'high_throw'; return; } + for (var guard = 0; guard < 8; guard++) { + var ev = this.pick(c, 'duo', D.choices, D.weights, D.max, D.miss_max); + if (ev === 'pincer' && (h.x < D.pincer_x[0] || h.x > D.pincer_x[1])) continue; // [data] Pincer Check fails -> choose again + this.move = 'duo'; + if (ev === 'stab_dash') { send(s1, 'DSTAB', 0); send(s2, 'DASH', D.stab_dash[0]); this.ctlT = D.stab_dash[1]; } + else if (ev === 'dash_stab') { send(s1, 'DASH', 0); send(s2, 'DSTAB', D.dash_stab[0]); this.ctlT = D.dash_stab[1]; } + else if (ev === 'double_stab') { send(s1, 'DSTAB', 0); send(s2, 'DSTAB', D.double_stab[0]); this.ctlT = D.double_stab[1]; } + else if (ev === 'pincer') { send(s1, 'DASH R', 0); send(s2, 'DASH L', 0); this.ctlT = D.pincer[1]; } + else if (ev === 'double_dash') { + // [data] D Dash Dir compares the player with "Centre X", which the FSM never sets (0): the first dash always runs right. + // D Dash R 2: if the player is now left of Pincer Min X the second one runs left instead. + send(s1, 'DASH R', 0); send(s2, 'DDASH2', D.double_dash[0]); this.ctlT = D.double_dash[0] + D.double_dash[1]; + } + else { var wide = ev === 'throw_wide'; send(s1, 'THROW', D.dthrow[0], { right: false, wide: wide }); send(s2, 'THROW', D.dthrow[0], { right: true, wide: wide }); this.ctlT = D.dthrow[1]; } + this.ctlT *= wait; return; + } + this.ctlT = 0.5 * wait; + }; + Sisters.prototype.dispatch = function (c, q) { + var s = q.s; + if (s.st !== 'sub_idle' || !s.sub) return; // an event a lord cannot take in her current state is dropped + if (q.ev === 'DDASH2') return s.order(c, heroSrc(c).x < MV.duo.params.pincer_x[0] ? 'DASH L' : 'DASH R'); + s.order(c, q.ev, q.arg); + }; + Sisters.prototype.update = function (c) { + var dt = BB.DT, self = this, i, s; + this.stT += dt; + for (i = 0; i < 3; i++) if (this.sis[i].st !== 'gone' && this.sis[i].st !== 'dead') this.sis[i].update(c, this); + if (this.st !== 'dead') { + if (this.phase === 1 && this.sis[0].st === 'dead') { this.phase = 2; this.gapT = MV.duo.params.gap; } + if (this.phase === 2 && this.gapT > 0 && (this.gapT -= dt) <= 0) { + this.phase = 3; + this.sis[1].sub = this.sis[2].sub = true; this.sis[1].enter(); this.sis[2].enter(); this.ctlT = MV.duo.telegraph_scale; + } + if (this.phase === 3) { + var live = this.alive(); + if (live.length === 2) { + this.queue = this.queue.filter(function (q) { if ((q.t -= dt) <= 0) { self.dispatch(c, q); return false; } return true; }); + if ((this.ctlT -= dt) <= 0) this.choose(c); + } else if (live.length === 1 && live[0].sub) { // [data] Killed: the survivor goes back to her own FSM + live[0].sub = false; this.queue = []; + } + } + } + this.blades = this.blades.filter(function (b) { + b.vx += b.fx * dt; b.x += b.vx * dt; b.y += b.vy * dt; b.life -= dt; + return b.life > 0 && b.x > -6 && b.x < A.W + 6 && b.y < A.H + 3; + }); + var p = this.primary(); + this.offstage = !p; + if (p) { this.x = p.x; this.y = p.y; this.vx = p.vx; this.vy = p.vy; this.f = p.f; this.move = p.move; this.timer = p.timer; } + else { this.x = A.W / 2; this.y = 0; this.vx = 0; this.vy = 0; } + var st = this.st === 'dead' ? 'dead' : p ? p.st : this.phase === 2 ? 'gap' : 'away'; + if (st !== this.st) { this.st = st; this.stT = 0; } + this.hitFlash = 0; for (i = 0; i < 3; i++) this.hitFlash = Math.max(this.hitFlash, this.sis[i].hitFlash); + }; + Sisters.prototype.role = function () { var p = this.primary(); return p ? p.role() : 'idle'; }; + + // ---------------- combat interface ---------------- + function lance(s) { // [hand] lance in front of the body while dashing + var L = MV.dash.params.lance, x0 = s.x + s.f * L[0] * SX, x1 = s.x + s.f * L[1] * SX; + return { x: (x0 + x1) / 2, y: s.y + L[2], w: Math.abs(x1 - x0), h: L[3] }; + } + Sisters.prototype.bodyBox = function () { var p = this.primary(); return p ? p.box() : null; }; + Sisters.prototype.hitTargets = function () { + return this.sis.map(function (s) { return { id: 's' + s.id, box: s.on && s.st !== 'dying' && s.st !== 'dead' ? s.box() : null }; }); + }; + Sisters.prototype.hazards = function () { + var out = [], B = MV.blade.params, bw = B.box[0] * B.scale * SX, bh = B.box[1] * B.scale; + if (this.st === 'dead') return out; + this.sis.forEach(function (s) { + if (!s.on || s.st === 'dying' || s.st === 'dead') return; + out.push({ kind: 'body', box: s.box(), fromX: s.x }); + if (s.st === 'dash') out.push({ kind: 'lance', box: lance(s), fromX: s.x }); + }); + this.blades.forEach(function (b) { out.push({ kind: 'blade', box: { x: b.x, y: b.y, w: bw, h: bh }, fromX: b.x - (b.vx > 0 ? 1 : -1) }); }); + return out; + }; + Sisters.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + var s = this.sis[+tid.slice(1)]; + if (!s || this.st === 'dead' || s.hp <= 0) return null; + var d = Math.min(dmg, s.hp); + s.hp -= d; this.hp -= d; s.hitFlash = 0.12; c.emit('boss_hit', s.x, s.y + BH / 2); + if (this.hp <= 0) { + this.hp = 0; this.st = 'dead'; this.blades = []; this.queue = []; + s.st = 'dead'; s.on = false; c.emit('boss_dead', s.x, 1); c.shake(0.8); return 'flesh'; + } + if (s.hp <= 0) { // [data] Death Air 0.167 + Death Land 0.25 + Death Leave 0.1 + s.vx = 0; s.vy = s.y > 0 ? 0 : 6; s.move = null; s.to('dying', 0.517); + c.emit('boss_stun', s.x, s.y + BH / 2); c.shake(0.6); + } + return 'flesh'; + }; + Sisters.prototype.state = function () { + var r = BB.r4, p = this.primary(), role = this.role(), tl = 0; + if (p && role === 'telegraph') { + tl = Math.max(0, p.timer); + if (p.st === 'dash_arrive') tl += 0.417 * this.k.telegraph; + else if (p.st === 'wall_arrive') tl += 0.417 * this.k.telegraph; + } + var B = MV.blade.params; + var hz = this.blades.map(function (b) { return { kind: 'blade', x: r(b.x), y: r(b.y), vx: r(b.vx), vy: r(b.vy), w: r(B.box[0] * B.scale * SX), h: r(B.box[1] * B.scale) }; }); + this.sis.forEach(function (s, i) { + if (s !== p && s.on && s.st !== 'dead') hz.push({ kind: 'sister', x: r(s.x), y: r(s.y), fsm: s.st, hp: s.hp, role: s.role() }); + }); + return { + x: r(this.x), y: r(this.y), vx: r(this.vx), vy: r(this.vy), facing: this.f, + hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: p ? p.move : null, + telegraph_left: r(tl), aim_deg: null, + escalated: this.phase >= 3, staggers: this.sis.filter(function (s) { return s.st === 'dead' || s.st === 'dying'; }).length, + sisters: this.sis.map(function (s) { return { hp: s.hp, on: s.on, fsm: s.st }; }), + hazards: hz + }; + }; + BB.SickleSisters = Sisters; + BB.CASES = BB.CASES || {}; + BB.CASES['2d/sickle_sisters'] = { title: 'Triple Lancers', Body: BB.Wanderer, Boss: Sisters, arena: 'mantis_court' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/clock.js b/environments/games/web/games/hollowknight_remake/clock.js new file mode 100644 index 0000000000000000000000000000000000000000..1e94ab43c05ca41a0e7036c449f91037011da241 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/clock.js @@ -0,0 +1,19 @@ +// Clock of this game. The source game steps its physics in Unity FixedUpdate at 50 Hz (0.02 s); every BossBench case +// runs at the engine's native 60 Hz (BB.FPS, shown on the HUD). A source number enters the 60 Hz engine in exactly one +// of four ways, and every conversion in body_wanderer.js / bosses/*.js goes through BB.HK_CLOCK to preserve source timings: +// 1. seconds (FSM Wait actions, clip lengths, cooldowns) ......... unchanged: 0.35 s is 0.35 s at any tick rate +// 2. velocities u/s, accelerations u/s^2 ......................... unchanged (integrated with dt = 1/60) +// 3. physics-step counts ("on at step 1, off at step 5") ........ CLK.steps(n) = n x 0.02 s, then sampled at 60 Hz +// 4. per-step factors ("Decelerate: x f every FixedUpdate") ...... CLK.perStep(f) = f^(0.02 -> 1/60) = f^(5/6) per tick, +// so one second still multiplies by f^50 as in the source. Multiplying by f every 60 Hz tick instead would be +// f^60 per second. +(function (g) { + var BB = g.BB; + var SOURCE_HZ = 50, STEP = 1 / SOURCE_HZ; + BB.HK_CLOCK = { + SOURCE_HZ: SOURCE_HZ, SOURCE_STEP: STEP, ENGINE_HZ: BB.FPS, + steps: function (n) { return n * STEP; }, // n source physics steps -> seconds + perStep: function (f) { return Math.pow(f, BB.DT / STEP); }, // "x f every 0.02 s" -> factor per 60 Hz tick + ticks: function (sec) { return sec * BB.FPS; } // seconds -> engine ticks + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/compact_actions.json b/environments/games/web/games/hollowknight_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..91b231d38e498a0766fb7c03261afff187e84d3a --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/compact_actions.json @@ -0,0 +1,528 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "hollowknight_remake", + "version": "hollowknight-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "left_tap", + "subs": [ + [ + "A" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "right_tap", + "subs": [ + [ + "D" + ], + [], + [], + [], + [], + [] + ] + } + ] + }, + { + "name": "jump", + "options": [ + { + "label": "none" + }, + { + "label": "hold", + "keys": [ + "Space" + ] + }, + { + "label": "press2_hold", + "subs": [ + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "tap1", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "tap2", + "subs": [ + [], + [ + "Space" + ], + [], + [], + [], + [] + ] + }, + { + "label": "tap3", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "tap4", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "tap5", + "subs": [ + [], + [], + [], + [], + [ + "Space" + ], + [] + ] + }, + { + "label": "tap6", + "subs": [ + [], + [], + [], + [], + [], + [ + "Space" + ] + ] + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "down_1", + "subs": [ + [ + "J", + "S" + ], + [ + "S" + ], + [ + "J", + "S" + ], + [ + "S" + ], + [ + "J", + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "down_2", + "subs": [ + [], + [ + "J", + "S" + ], + [ + "S" + ], + [ + "J", + "S" + ], + [ + "S" + ], + [ + "J", + "S" + ] + ] + }, + { + "label": "down_3", + "subs": [ + [], + [], + [ + "J", + "S" + ], + [ + "S" + ], + [ + "J", + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "down_4", + "subs": [ + [], + [], + [], + [ + "J", + "S" + ], + [ + "S" + ], + [ + "J", + "S" + ] + ] + }, + { + "label": "down_5", + "subs": [ + [], + [], + [], + [], + [ + "J", + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "down_6", + "subs": [ + [], + [], + [], + [], + [], + [ + "J", + "S" + ] + ] + }, + { + "label": "slash_101010", + "subs": [ + [ + "J" + ], + [], + [ + "J" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "slash_010101", + "subs": [ + [], + [ + "J" + ], + [], + [ + "J" + ], + [], + [ + "J" + ] + ] + }, + { + "label": "slash_100000", + "subs": [ + [ + "J" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "slash_010000", + "subs": [ + [], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "slash_001010", + "subs": [ + [], + [], + [ + "J" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "slash_000101", + "subs": [ + [], + [], + [], + [ + "J" + ], + [], + [ + "J" + ] + ] + }, + { + "label": "slash_000010", + "subs": [ + [], + [], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "slash_000001", + "subs": [ + [], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "up_1", + "subs": [ + [ + "J", + "W" + ], + [ + "W" + ], + [ + "J", + "W" + ], + [ + "W" + ], + [ + "J", + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "up_2", + "subs": [ + [ + "W" + ], + [ + "J", + "W" + ], + [ + "W" + ], + [ + "J", + "W" + ], + [ + "W" + ], + [ + "J", + "W" + ] + ] + }, + { + "label": "up_3", + "subs": [ + [ + "J", + "W" + ], + [ + "W" + ], + [], + [], + [], + [] + ] + }, + { + "label": "up_5", + "subs": [ + [], + [], + [], + [], + [ + "J", + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "dash", + "subs": [ + [ + "Shift" + ], + [ + "Shift" + ], + [], + [], + [], + [] + ] + }, + { + "label": "dash_mid", + "subs": [ + [], + [], + [], + [ + "Shift" + ], + [], + [] + ] + }, + { + "label": "heal", + "keys": [ + "K" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/hollowknight_remake/draw/hollow_vessel.js b/environments/games/web/games/hollowknight_remake/draw/hollow_vessel.js new file mode 100644 index 0000000000000000000000000000000000000000..564fd56878e06ad85af96a5a98d3cd7a9ced39ff --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/hollow_vessel.js @@ -0,0 +1,120 @@ +// Drawing for 2d/hollow_vessel: BB.BOSS_DRAW[caseId] = {bar, hazards, body}. Pure presentation, original design. +(function (g) { + var BB = g.BB, ART = BB.ART, D = BB.BOSS_DRAW = BB.BOSS_DRAW || {}, K = BB.DRAWKIT; + var TAU = Math.PI * 2, INK = K.INK, TELE = K.TELE; + var teleK = K.teleK, aura = K.aura, stars = K.stars, blob = K.blob, nailArc = K.nailArc, blade = K.blade; + + // ---------- Hollow Vessel: a hunched husk knight, cracked round shell with one snapped horn, a heavy ragged + // cape, a long chipped nail, and orange infection seeping through every crack ---------- + function vesselPose(w, t) { + var st = w.st, p = { crouch: 0, lean: 0, nail: 0.15, reach: 0, shake: 0, slump: 0, cape: 0 }; + if (/dash_back|dash_antic|evade_antic/.test(st)) { p.crouch = 0.35; p.lean = -0.18; p.nail = Math.PI - 0.35; } + else if (st === 'dash') { p.lean = 0.32; p.nail = 0.05; p.reach = 1; p.cape = 1; } + else if (st === 'dash_recover' || st === 'evade_recover') { p.lean = 0.1; p.nail = 0.4; } + else if (st === 'jump_antic' || st === 'cjump_antic') { p.crouch = 0.45; p.nail = 0.6; } + else if (st === 'jump' || st === 'cjump' || st === 'fall') { p.crouch = -0.1; p.nail = -0.5; p.cape = 0.6; } + else if (st === 'land') { p.crouch = 0.4; p.nail = 0.6; } + else if (st === 'dstab_antic') { p.crouch = 0.2; p.nail = Math.PI / 2; p.lean = 0.05; } + else if (/dstab_fall|dstab_land/.test(st)) { p.nail = Math.PI / 2; p.crouch = st === 'dstab_land' ? 0.45 : -0.1; p.cape = st === 'dstab_fall' ? 1 : 0; } + else if (st === 'dstab_recover') { p.crouch = 0.3; p.nail = 1.2; } + else if (st === 'ohead_antic') { p.nail = -1.9; p.lean = -0.08; } + else if (st === 'ohead') { p.nail = -1.57 + Math.sin(t * 22) * 1.2; p.lean = 0.05 * Math.sin(t * 22); } + else if (st === 'evade') { p.lean = -0.25; p.cape = 0.8; } + else if (/shake/.test(st)) { p.shake = st === 'shake_antic' ? 0.5 : 1; p.crouch = 0.15; p.nail = 0.9; } + else if (/stun|stunned/.test(st)) { p.slump = 1; p.nail = 1.35; p.crouch = 0.3; } + else if (st === 'dead') { p.slump = 1; p.nail = 1.5; p.crouch = 0.4; } + return p; + } + function vesselHead(x, hr, fl, t, angry) { // origin = head centre, facing +x + x.beginPath(); x.moveTo(-hr * 0.15, -hr * 0.85); x.quadraticCurveTo(-hr * 0.35, -hr * 1.7, -hr * 0.05, -hr * 2.05); // the long horn, snapped + x.lineTo(hr * 0.12, -hr * 1.7); x.lineTo(hr * 0.05, -hr * 1.55); x.quadraticCurveTo(hr * 0.1, -hr * 1.2, hr * 0.25, -hr * 0.85); x.closePath(); + ART.ink(x, ART.lit(fl, '#d8d0c2'), 1.5, INK); + x.beginPath(); x.moveTo(hr * 0.45, -hr * 0.75); x.quadraticCurveTo(hr * 0.75, -hr * 1.15, hr * 0.55, -hr * 1.35); x.quadraticCurveTo(hr * 0.68, -hr * 1.0, hr * 0.7, -hr * 0.65); x.closePath(); + ART.ink(x, ART.lit(fl, '#d8d0c2'), 1.5, INK); // the stub horn + x.beginPath(); x.ellipse(0, 0, hr, hr * 0.92, 0, 0, TAU); + var gr = x.createRadialGradient(-hr * 0.35, -hr * 0.4, hr * 0.1, 0, 0, hr * 1.05); + gr.addColorStop(0, '#fffdf6'); gr.addColorStop(0.75, '#e2dccf'); gr.addColorStop(1, '#9f978a'); + ART.ink(x, ART.lit(fl, gr), 2, INK); + x.fillStyle = '#0b0807'; + x.beginPath(); x.ellipse(hr * 0.12, hr * 0.02, hr * 0.2, hr * 0.38, 0.08, 0, TAU); x.fill(); + x.beginPath(); x.ellipse(hr * 0.6, hr * 0.0, hr * 0.17, hr * 0.33, 0.05, 0, TAU); x.fill(); + // the crack: dark split with orange light seeping out + x.strokeStyle = '#120806'; x.lineWidth = 2.2; + x.beginPath(); x.moveTo(-hr * 0.55, -hr * 0.72); x.lineTo(-hr * 0.3, -hr * 0.42); x.lineTo(-hr * 0.42, -hr * 0.12); x.lineTo(-hr * 0.12, hr * 0.12); x.stroke(); + x.strokeStyle = ART.rgba('255,150,60', angry ? 0.95 : 0.7); x.lineWidth = 1; + x.stroke(); + ART.glow(x, -hr * 0.35, -hr * 0.3, hr * (angry ? 1.1 : 0.7), '255,130,40', angry ? 0.45 + 0.15 * Math.sin(t * 9) : 0.25); + } + D['2d/hollow_vessel'] = { + bar: function (w) { return w.angry ? '#ff8a3a' : '#d9a070'; }, + hazards: function (x, c, t, V) { + var w = c.boss; + w.blobs.forEach(function (o) { + if (o.warn > 0) { // a blister swelling on the wall / roof where a blob will emerge + var X = V.sx(o.x), Y = V.sy(o.y), k = 1 - Math.min(1, o.warn / 0.5); + ART.glow(x, X, Y, 12 + 10 * k, '255,140,50', 0.35 + 0.3 * k); + x.fillStyle = '#ff9a3c'; x.beginPath(); x.arc(X, Y, 3 + 4 * k, 0, TAU); x.fill(); return; + } + blob(x, V, o, 0.35, t); + }); + w.balloons.forEach(function (o) { // drifting infected sacs with a dark, staring core + var a = o.fade > 0 ? 0.35 : 1, X = V.sx(o.x), Y = V.sy(o.y), R = 0.45 * V.S * (1 + 0.06 * Math.sin(t * 6 + o.id)); + x.save(); x.globalAlpha = a; + ART.glow(x, X, Y, R * 2.4, '255,140,50', 0.4); + x.beginPath(); + for (var i = 0; i < 12; i++) { var an = i / 12 * TAU, rr = R * (1 + 0.07 * Math.sin(t * 5 + i * 2.3 + o.id)); i ? x.lineTo(X + Math.cos(an) * rr, Y + Math.sin(an) * rr) : x.moveTo(X + Math.cos(an) * rr, Y + Math.sin(an) * rr); } + x.closePath(); + var gr = x.createRadialGradient(X - R * 0.3, Y - R * 0.3, R * 0.1, X, Y, R * 1.05); + gr.addColorStop(0, '#ffe4a8'); gr.addColorStop(0.5, '#f08a36'); gr.addColorStop(1, '#8a2e0c'); + ART.ink(x, gr, 1.5, '#3a1206'); + x.fillStyle = '#2a0e06'; x.beginPath(); x.arc(X + R * 0.15, Y + R * 0.08, R * 0.28, 0, TAU); x.fill(); + x.fillStyle = '#ffd890'; x.beginPath(); x.arc(X + R * 0.2, Y + R * 0.02, R * 0.08, 0, TAU); x.fill(); + x.restore(); + }); + }, + body: function (x, c, t, V) { + var w = c.boss, st = w.st, f = w.f, fl = w.hitFlash > 0, bb = w.bodyBox(); + var X = V.sx(w.x), Yf = V.sy(w.y), hw = bb.w / 2 * V.S, hh = bb.h * V.S; + var p = ART.smooth('vessel', vesselPose(w, t), 18), body = ART.lit(fl, '#1d1a1c'); + ART.shade(x, X, V.sy(0) - 1, hw * 1.3 * (1 - Math.min(0.6, w.y / 10)), 6, 0.5); + aura(x, X, Yf - hh * 0.55, hw * 1.5, hh * 0.72, teleK(w), t); + w.hazards().forEach(function (h) { if (h.kind === 'nail') nailArc(x, V, h.box, f, '255,190,130', w.x); }); + if (st === 'dash') for (var gI = 1; gI <= 3; gI++) { // dash afterimages + x.save(); x.globalAlpha = 0.18 / gI; x.fillStyle = '#ffb070'; + x.beginPath(); x.ellipse(X - f * gI * 18, Yf - hh * 0.45, hw * 0.8, hh * 0.45, 0, 0, TAU); x.fill(); x.restore(); + } + x.save(); x.translate(X + (p.shake ? Math.sin(t * 70) * 2.5 * p.shake : 0), Yf); x.scale(f, 1); + if (st === 'dead') x.globalAlpha = 0.75; + var H = hh * (1 - 0.22 * p.crouch), lean = p.lean + 0.25 * p.slump; + x.rotate(lean); + // legs + x.fillStyle = body; + [[-0.32, 1], [0.28, -1]].forEach(function (L) { + var lx = hw * L[0], kx = lx + L[1] * 3 + p.crouch * 6; + x.beginPath(); ART.ribbon(x, [[lx, -H * 0.32], [kx, -H * 0.16], [lx + 3, 0]], 9, 7); ART.ink(x, body, 1.5, INK); + }); + // heavy cape, swept back by motion, with a torn hem + var sw = -p.cape * hw * 0.6, ph = t * 3; + x.beginPath(); x.moveTo(-hw * 0.45, -H * 0.82); + x.quadraticCurveTo(-hw * 1.15 + sw, -H * 0.5, -hw * 1.05 + sw * 1.6, -H * 0.05); + ART.hem(x, -hw * 1.05 + sw * 1.6, hw * 0.6, -H * 0.04, 7, 10, 2.5, ph, 53); + x.quadraticCurveTo(hw * 0.75, -H * 0.5, hw * 0.4, -H * 0.85); x.closePath(); + var cg = x.createLinearGradient(-hw, -H, hw, 0); cg.addColorStop(0, '#2e2626'); cg.addColorStop(1, '#4a3a34'); + ART.ink(x, ART.lit(fl, cg), 2, INK); + if (!fl && w.angry) { var rr = new BB.RNG(53); ART.blisters(x, rr, -hw * 0.2, -H * 0.45, 4, hw * 0.45, { accent: '255,140,50' }); } + // shoulders + head + x.beginPath(); x.ellipse(hw * 0.05, -H * 0.8, hw * 0.62, H * 0.12, 0, 0, TAU); ART.ink(x, ART.lit(fl, '#3a302c'), 1.5, INK); + x.save(); x.translate(hw * 0.12, -H * 0.93 + p.slump * 8); x.rotate(0.35 * p.slump); + vesselHead(x, hh * 0.19, fl, t, w.angry); + x.restore(); + // arm + nail + var ax = hw * 0.45, ay = -H * 0.6; + x.save(); x.translate(ax, ay); x.rotate(p.nail); + x.beginPath(); ART.ribbon(x, [[-8, 0], [6, 1]], 9, 7); ART.ink(x, body, 1.5, INK); + blade(x, 2.0 * V.S * (1 + 0.15 * p.reach), 6, ART.lit(fl, '#cfc8bc'), 'rgba(255,170,100,0.55)'); + x.restore(); + x.restore(); + if (/stun/.test(st)) stars(x, X, Yf - hh - 14, t); + } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/draw/iron_bulwark.js b/environments/games/web/games/hollowknight_remake/draw/iron_bulwark.js new file mode 100644 index 0000000000000000000000000000000000000000..9f2ddde3f763063e9b5214476ebcb66ffc90559e --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/iron_bulwark.js @@ -0,0 +1,164 @@ +// Drawing for 2d/iron_bulwark: BB.BOSS_DRAW[caseId] = {bar, hazards, body}. Pure presentation, original design. +(function (g) { + var BB = g.BB, ART = BB.ART, D = BB.BOSS_DRAW = BB.BOSS_DRAW || {}, K = BB.DRAWKIT; + var TAU = Math.PI * 2, INK = K.INK, TELE = K.TELE; + var teleK = K.teleK, aura = K.aura, stars = K.stars, blob = K.blob, nailArc = K.nailArc, blade = K.blade; + + // ---------- Iron Bulwark: a walking furnace-bell of riveted iron, a slab mace on a chain-wrapped haft, + // and inside, a soft pale grub that tends the fire (exposed when the shell is knocked over) ---------- + function bulwarkPose(w, t) { + var st = w.st, side = st === 'rage' ? w.slamSide * w.f : 1, p = { mace: 1.25, sq: 1, lean: 0, tip: 0, glow: 0.35 }; + if (/leap_antic|ja_antic|smash_antic|run_antic/.test(st)) { p.mace = -2.2; p.sq = 0.9; p.lean = -0.08; } + else if (st === 'rage_antic') { p.mace = -1.6; p.sq = 0.92; p.glow = 0.9; } + else if (st === 'ja_air') p.mace = w.vy < 0 ? 0.6 : -2.0; + else if (/^(ja_slam|smash|smash_recover|ja_recoil)$/.test(st)) { p.mace = 1.03; p.sq = 0.94; p.lean = 0.1; } + else if (st === 'rage') { p.mace = w.timer < 0.12 ? (side > 0 ? 1.03 : Math.PI - 1.03) : -1.57; p.glow = 1; p.lean = 0.06 * side; } + else if (st === 'run') { p.mace = 2.5; p.lean = 0.12; } + else if (/leap|smash_jump|rage_jump/.test(st)) { p.mace = -0.6; p.sq = 1.05; } + else if (/land|leap_land/.test(st)) { p.sq = 0.88; } + if (/stun_land|stun_roll|stun_pause|stun_open|opened|stun_fail|head_recover|final_down/.test(st)) p.tip = 1; + if (st === 'stun_air') { p.tip = 0.5; p.mace = 2.6; } + if (w.escalated) p.glow = Math.max(p.glow, 0.6); + return p; + } + function bulwarkShell(x, hw, hh, fl, glowK, t, esc) { + // bell-shaped dome, origin = feet centre, facing +x + var base = -hh * 0.2, top = -hh; + x.beginPath(); x.moveTo(-hw * 1.02, base + 6); + x.bezierCurveTo(-hw * 1.1, top * 0.62, -hw * 0.62, top * 1.02, hw * 0.08, top); + x.bezierCurveTo(hw * 0.78, top * 0.99, hw * 1.12, top * 0.6, hw * 1.02, base + 6); + x.quadraticCurveTo(0, base + 16, -hw * 1.02, base + 6); x.closePath(); + var gr = x.createLinearGradient(-hw, top, hw, base); + gr.addColorStop(0, '#2a241e'); gr.addColorStop(0.5, '#5d4f3e'); gr.addColorStop(0.82, '#8c7658'); gr.addColorStop(1, '#3a3026'); + ART.ink(x, ART.lit(fl, gr), 3, INK); + if (fl) return; + x.save(); x.clip(); + for (var i = 1; i < 4; i++) { // riveted plate bands + var py = base + (top - base) * i / 4.2; + x.strokeStyle = 'rgba(15,10,6,0.75)'; x.lineWidth = 3; x.beginPath(); x.moveTo(-hw * 1.1, py + 8); x.quadraticCurveTo(0, py - 12, hw * 1.1, py + 8); x.stroke(); + x.strokeStyle = 'rgba(255,220,170,0.18)'; x.lineWidth = 1; x.beginPath(); x.moveTo(-hw * 1.1, py + 10); x.quadraticCurveTo(0, py - 10, hw * 1.1, py + 10); x.stroke(); + for (var j = 0; j < 7; j++) { + var rx = -hw * 0.85 + j * hw * 0.28, ry = py + 8 - 20 * (1 - Math.pow(rx / hw, 2)) * 0.5 + 6; + x.fillStyle = '#b89a6a'; x.beginPath(); x.arc(rx, ry, 2.4, 0, TAU); x.fill(); + x.fillStyle = 'rgba(0,0,0,0.5)'; x.beginPath(); x.arc(rx + 0.8, ry + 0.8, 1.2, 0, TAU); x.fill(); + } + } + var rim = x.createLinearGradient(hw * 0.4, 0, hw * 1.05, 0); rim.addColorStop(0, 'rgba(255,190,110,0)'); rim.addColorStop(1, 'rgba(255,190,110,0.35)'); + x.fillStyle = rim; x.fillRect(hw * 0.4, top, hw, hh); // forge light from the front + if (esc) { // heat cracks after the first stagger + x.strokeStyle = ART.rgba('255,130,40', 0.55 + 0.3 * Math.sin(t * 6)); x.lineWidth = 2; + x.beginPath(); x.moveTo(-hw * 0.5, top * 0.85); x.lineTo(-hw * 0.3, top * 0.7); x.lineTo(-hw * 0.42, top * 0.55); x.lineTo(-hw * 0.2, top * 0.42); + x.moveTo(hw * 0.1, top * 0.95); x.lineTo(hw * 0.2, top * 0.8); x.lineTo(hw * 0.05, top * 0.7); x.stroke(); + } + x.restore(); + // furnace grille + ember eyes on the front face + var gx = hw * 0.42, gy = top * 0.66; + x.beginPath(); x.ellipse(gx, gy, hw * 0.34, hh * 0.1, -0.12, 0, TAU); ART.ink(x, '#140d08', 2, INK); + ART.glow(x, gx, gy, hw * 0.5, '255,150,60', 0.25 + 0.35 * glowK); + x.fillStyle = esc ? '#ff6a2a' : '#ffb347'; + x.beginPath(); x.ellipse(gx - hw * 0.12, gy, 4, 3, 0, 0, TAU); x.ellipse(gx + hw * 0.14, gy - 1, 4.5, 3.2, 0, 0, TAU); x.fill(); + x.strokeStyle = '#2a2016'; x.lineWidth = 2.5; + for (i = -2; i <= 2; i++) { x.beginPath(); x.moveTo(gx + i * hw * 0.11, gy - hh * 0.09); x.lineTo(gx + i * hw * 0.11 - 2, gy + hh * 0.09); x.stroke(); } + } + function bulwarkGrub(x, HX, HY, R, f, fl, t) { // the soft rider: pale segmented grub with a lantern glow + ART.glow(x, HX, HY, R * 2.6, '190,255,170', 0.3 + 0.12 * Math.sin(t * 8)); + x.save(); x.translate(HX, HY); x.scale(f, 1); + var sq = 1 + 0.06 * Math.sin(t * 9); + x.beginPath(); x.ellipse(0, 0, R * 0.95 * sq, R * 0.78 / sq, 0, 0, TAU); + var gr = x.createRadialGradient(-R * 0.3, -R * 0.35, R * 0.1, 0, 0, R); + gr.addColorStop(0, '#fffbe8'); gr.addColorStop(0.7, '#e3d9b6'); gr.addColorStop(1, '#a89a74'); + ART.ink(x, ART.lit(fl, gr), 2, INK); + x.strokeStyle = 'rgba(120,100,70,0.55)'; x.lineWidth = 1.2; + for (var i = -1; i <= 1; i++) { x.beginPath(); x.arc(-R * 0.9 + i * 6, 0, R * 0.8, -0.6, 0.6); x.stroke(); } + x.fillStyle = '#1b140c'; x.beginPath(); x.ellipse(R * 0.25, -R * 0.2, 3, 4, 0, 0, TAU); x.ellipse(R * 0.6, -R * 0.22, 2.6, 3.6, 0, 0, TAU); x.fill(); + x.fillStyle = 'rgba(255,255,255,0.8)'; x.fillRect(R * 0.22, -R * 0.32, 1.4, 1.4); x.fillRect(R * 0.57, -R * 0.34, 1.2, 1.2); + x.restore(); + } + D['2d/iron_bulwark'] = { + bar: function (w) { return w.escalated ? '#e07a3a' : '#c9a86a'; }, + hazards: function (x, c, t, V) { + var w = c.boss; + w.waves.forEach(function (o, i) { // a rolling wave of embers and cracked stone + var X = V.sx(o.x), Y = V.sy(0), d = o.dir; + ART.glow(x, X, Y - 16, 40, '255,140,50', 0.55); + x.beginPath(); x.moveTo(X - d * 22, Y); x.quadraticCurveTo(X - d * 8, Y - 50, X + d * 16, Y); x.closePath(); + var gr = x.createLinearGradient(0, Y - 46, 0, Y); gr.addColorStop(0, 'rgba(255,120,40,0)'); gr.addColorStop(0.5, 'rgba(255,140,50,0.8)'); gr.addColorStop(1, '#ffe2a0'); + x.fillStyle = gr; x.fill(); + x.beginPath(); x.moveTo(X - d * 10, Y); x.quadraticCurveTo(X - d * 2, Y - 28, X + d * 9, Y); x.closePath(); x.fillStyle = 'rgba(255,248,220,0.95)'; x.fill(); + for (var k = 0; k < 4; k++) { // flung chips + var ph = (t * 3 + k * 0.27 + i * 0.5) % 1, cx = X - d * (6 + ph * 30), cy = Y - 40 * ph * (1 - ph) * 3; + x.fillStyle = '#2a1e14'; x.fillRect(cx - 2, cy - 2, 4, 3); + } + }); + w.barrels.forEach(function (o) { + var X = V.sx(o.x), R = 0.55 * V.S; + if (o.warn > 0) { // dust trickling from the roof + a growing shadow on the floor + var top = ART.view.ROOF + 4; + for (var k = 0; k < 6; k++) { var ph = (t * 1.6 + k / 6) % 1; x.fillStyle = 'rgba(210,180,130,' + (0.7 * (1 - ph)).toFixed(3) + ')'; x.fillRect(X - 3 + ART.hash(k) * 6, top + ph * 70, 2, 3); } + ART.glow(x, X, top + 4, 14, TELE, 0.35 + 0.25 * Math.sin(t * 20)); + ART.shade(x, X, V.sy(0) - 1, R * (1.4 - Math.min(1, o.warn)), 4, 0.5); return; + } + var Y = V.sy(o.y); + ART.shade(x, X, V.sy(0) - 1, R * 1.2, 4, 0.45); + x.save(); x.translate(X, Y); x.rotate(t * 3 + o.x); + x.beginPath(); x.ellipse(0, 0, R, R * 0.82, 0, 0, TAU); + var gr = x.createLinearGradient(-R, -R, R, R); gr.addColorStop(0, '#8a6c46'); gr.addColorStop(1, '#3e2c1a'); + ART.ink(x, gr, 2, INK); + x.strokeStyle = '#1e1610'; x.lineWidth = 3; x.beginPath(); x.moveTo(-R * 0.45, -R * 0.72); x.lineTo(-R * 0.45, R * 0.72); x.moveTo(R * 0.45, -R * 0.72); x.lineTo(R * 0.45, R * 0.72); x.stroke(); + x.strokeStyle = 'rgba(255,220,170,0.3)'; x.lineWidth = 1; x.beginPath(); x.ellipse(0, 0, R * 0.8, R * 0.6, 0, -2.6, -1.2); x.stroke(); + x.restore(); + }); + }, + body: function (x, c, t, V) { + var w = c.boss, st = w.st, f = w.f, fl = w.hitFlash > 0, hw = 4.37 / 2 * V.S, hh = 5.04 * V.S; + var X = V.sx(w.x), Yf = V.sy(w.y), tgt = bulwarkPose(w, t); + if (st === 'dead') tgt.tip = 1; + var p = ART.smooth('bulwark', tgt, 14), air = w.y > 0.05; + ART.shade(x, X, V.sy(0) - 1, hw * 1.25 * (1 - Math.min(0.6, w.y / 12)), 7, 0.55); + aura(x, X, Yf - hh * 0.5 * (1 - 0.4 * p.tip), hw * 1.25, hh * 0.62 * (1 - 0.4 * p.tip), teleK(w), t); + w.hazards().forEach(function (h) { if (h.kind === 'mace') nailArc(x, V, h.box, h.box.x > w.x ? 1 : -1, '255,200,140', w.x, 0.8); }); + x.save(); x.translate(X, Yf); x.scale(f, 1); + if (st === 'dead') x.globalAlpha = 0.8; + x.rotate(-0.42 * p.tip); x.translate(-hw * 0.3 * p.tip, -hh * 0.06 * p.tip); + x.scale(1 / Math.sqrt(p.sq), p.sq); x.rotate(p.lean); + // stubby legs: iron greaves, stepping while running + var stp = st === 'run' ? Math.sin(t * 14) : 0, lift = air ? 6 : 0; + [[-0.5, stp], [0.18, -stp]].forEach(function (L) { + var lx = hw * L[0] + L[1] * 8, ly = -Math.max(0, -L[1]) * 6 - lift; + x.beginPath(); x.moveTo(lx, -hh * 0.24); x.lineTo(lx + hw * 0.34, -hh * 0.24); x.lineTo(lx + hw * 0.38, ly); x.lineTo(lx - hw * 0.06, ly); x.closePath(); + ART.ink(x, ART.lit(fl, '#2e261d'), 2, INK); + x.beginPath(); x.ellipse(lx + hw * 0.16, ly, hw * 0.28, 5, 0, Math.PI, TAU); ART.ink(x, ART.lit(fl, '#4a3c2c'), 2, INK); + }); + var mac = p.mace, side = Math.cos(mac) >= 0 ? 1 : -1, hx = side * hw * 0.8, hy = -hh * 0.55; + var drawMace = function () { + if (st === 'dead') return; + var L = 2.75 * V.S, ex = hx + Math.cos(mac) * L, ey = hy + Math.sin(mac) * L; + x.save(); x.translate(hx, hy); x.rotate(mac); + x.beginPath(); x.rect(-6, -4, L + 6, 8); ART.ink(x, ART.lit(fl, '#3a2e22'), 2, INK); + x.strokeStyle = '#6a5a44'; x.lineWidth = 1.5; + for (var i = 0; i < 6; i++) { x.beginPath(); x.moveTo(8 + i * 11, -4); x.lineTo(14 + i * 11, 4); x.stroke(); } // chain wrap + x.restore(); + x.save(); x.translate(ex, ey); x.rotate(mac + Math.PI / 2); + x.beginPath(); x.moveTo(-28, -22); x.lineTo(28, -22); x.lineTo(32, 18); x.lineTo(0, 30); x.lineTo(-32, 18); x.closePath(); + var gr = x.createLinearGradient(-30, -20, 30, 28); gr.addColorStop(0, '#6a5d50'); gr.addColorStop(1, '#2a241e'); + ART.ink(x, ART.lit(fl, gr), 3, INK); + x.fillStyle = '#9a8a70'; [[-16, -10], [16, -10], [-18, 10], [18, 10], [0, 18]].forEach(function (q) { x.beginPath(); x.arc(q[0], q[1], 3.5, 0, TAU); x.fill(); }); + if (p.glow > 0.5) ART.glow(x, 0, 6, 34, '255,140,50', 0.3 * p.glow); + x.restore(); + }; + if (side < 0) drawMace(); // swinging behind: the mace passes behind the shell + if (p.tip < 0.5 || !w.headOpen()) bulwarkShell(x, hw, hh, fl, p.glow, t, w.escalated); + else { // knocked over: the open shell mouth faces the player + bulwarkShell(x, hw, hh, fl, 0, t, w.escalated); + x.beginPath(); x.ellipse(hw * 0.95, -hh * 0.5, hw * 0.2, hh * 0.35, 0, 0, TAU); ART.ink(x, '#120b06', 2, INK); + } + // arm: a thick iron gauntlet from the shoulder to the haft + x.beginPath(); ART.ribbon(x, [[hw * 0.25 * side, -hh * 0.6], [(hw * 0.25 + hx * 0.75) / 2 * side * side, hy - 8], [hx, hy]], 16, 12); + ART.ink(x, ART.lit(fl, '#4a3c2c'), 2, INK); + if (side > 0) drawMace(); + x.restore(); + if (w.headOpen()) { var hb = w.headBox(); bulwarkGrub(x, V.sx(hb.x), V.sy(hb.y), hb.h / 2 * V.S * 0.95, f, fl, t); } + if (/stun_air|stun_land|stun_roll|stun_pause|final_down/.test(st)) stars(x, X, Yf - hh * 0.7 - 10, t); + } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/draw/kit.js b/environments/games/web/games/hollowknight_remake/draw/kit.js new file mode 100644 index 0000000000000000000000000000000000000000..11de3360b9a32b9d724ef3e6bf4f15328bf317c0 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/kit.js @@ -0,0 +1,55 @@ +// Shared drawing bits of this game's bosses (telegraph aura, dazed stars, blobs, nail arcs, blades): BB.DRAWKIT. +(function (g) { + var BB = g.BB, ART = BB.ART; + var TAU = Math.PI * 2, INK = '#05080a', TELE = '255,200,90'; + + // ---------- shared bits ---------- + function teleK(w) { // 0 = none, 0.5 = winding up, 1 = about to strike + return w.role() === 'telegraph' ? (Math.max(0, w.timer) < 0.18 ? 1 : 0.5) : 0; + } + function aura(x, cx, cy, rx, ry, k, t) { // amber telegraph halo + a thin pulsing ring + if (!k) return; + ART.glow(x, cx, cy, Math.max(rx, ry) * 1.2, TELE, 0.22 + 0.25 * k); + x.save(); x.strokeStyle = ART.rgba(TELE, 0.35 + 0.45 * k * (0.75 + 0.25 * Math.sin(t * 30))); + x.lineWidth = 1.5 + k; x.beginPath(); x.ellipse(cx, cy, rx, ry, 0, 0, TAU); x.stroke(); x.restore(); + } + function stars(x, cx, cy, t) { // dazed: orbiting sparks + for (var i = 0; i < 3; i++) { + var a = t * 5 + i * 2.1, px = cx + Math.cos(a) * 16, py = cy + Math.sin(a) * 4; + ART.glow(x, px, py, 8, '255,233,160', 0.5); ART.spark(x, px, py, 4, '#fff3c4'); + } + } + function blob(x, V, o, r, t, hot) { // glowing infection globule, stretched along its motion + var X = V.sx(o.x), Y = V.sy(o.y), R = r * V.S, vx = o.vx || 0, vy = o.vy || 0, sp = Math.sqrt(vx * vx + vy * vy); + ART.glow(x, X, Y, R * 3, hot || '255,140,50', 0.45); + x.save(); x.translate(X, Y); x.rotate(Math.atan2(-vy, vx)); x.scale(1 + Math.min(0.35, sp * 0.02), 1 - Math.min(0.2, sp * 0.012)); + var gr = x.createRadialGradient(-R * 0.3, -R * 0.3, R * 0.1, 0, 0, R); + gr.addColorStop(0, '#fff0c0'); gr.addColorStop(0.4, '#ffa040'); gr.addColorStop(1, '#a8360c'); + x.beginPath(); x.arc(0, 0, R, 0, TAU); ART.ink(x, gr, 1.2, '#3a1206'); + x.restore(); + } + // swing drawn over its hit box: a crescent from the hilt side, brightest at the cutting edge + function nailArc(x, V, box, f, rgb, bx, k) { + var X0 = V.sx(box.x - box.w / 2), X1 = V.sx(box.x + box.w / 2), Y0 = V.sy(box.y + box.h / 2), Y1 = V.sy(box.y - box.h / 2); + var cy = (Y0 + Y1) / 2, ry = (Y1 - Y0) / 2, mid = bx != null && Math.abs(box.x - bx) < box.w * 0.25; + var cx = mid ? (X0 + X1) / 2 : f > 0 ? X0 : X1, rx = mid ? (X1 - X0) / 2 : X1 - X0; + var a0 = mid ? 0 : f > 0 ? -Math.PI / 2 : Math.PI / 2, a1 = mid ? TAU : a0 + Math.PI; + k = k == null ? 1 : k; rgb = rgb || '235,242,255'; + x.save(); x.globalCompositeOperation = 'lighter'; + x.translate(cx, cy); x.scale(1, ry / rx); + var gr = x.createRadialGradient(0, 0, rx * 0.35, 0, 0, rx); + gr.addColorStop(0, ART.rgba(rgb, 0)); gr.addColorStop(0.75, ART.rgba(rgb, 0.22 * k)); gr.addColorStop(1, ART.rgba(rgb, 0.6 * k)); + x.fillStyle = gr; x.beginPath(); x.moveTo(0, 0); x.arc(0, 0, rx, a0, a1); x.closePath(); x.fill(); + x.strokeStyle = 'rgba(255,255,255,' + (0.9 * k).toFixed(3) + ')'; x.lineWidth = 3 * rx / Math.max(ry, 1) > 6 ? 2 : 3; + x.beginPath(); x.arc(0, 0, rx - 1.5, a0, a1); x.stroke(); + x.restore(); + } + function blade(x, len, w, col, edge) { // straight nail blade from the origin along +x + x.beginPath(); x.moveTo(-6, -w * 0.45); x.lineTo(len - w * 2.5, -w / 2); x.lineTo(len, 0); x.lineTo(len - w * 2.5, w / 2); x.lineTo(-6, w * 0.45); x.closePath(); + ART.ink(x, col, 1.2, INK); + x.strokeStyle = edge || 'rgba(255,255,255,0.7)'; x.lineWidth = 1; x.beginPath(); x.moveTo(0, -w * 0.18); x.lineTo(len - w * 2.6, -w * 0.22); x.stroke(); + x.beginPath(); x.rect(-12, -w * 0.4, 7, w * 0.8); ART.ink(x, '#3a3028', 1, INK); // grip + x.beginPath(); x.rect(-6, -w * 1.1, 3, w * 2.2); ART.ink(x, '#8a7a62', 1, INK); // guard + } + BB.DRAWKIT = { INK: INK, TELE: TELE, teleK: teleK, aura: aura, stars: stars, blob: blob, nailArc: nailArc, blade: blade }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/draw/lumen_moth.js b/environments/games/web/games/hollowknight_remake/draw/lumen_moth.js new file mode 100644 index 0000000000000000000000000000000000000000..c2fd75a16342c89e14c68fd29c6398c22970ca5a --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/lumen_moth.js @@ -0,0 +1,124 @@ +// Drawing for 2d/lumen_moth: BB.BOSS_DRAW[caseId] = {bar, hazards, body}. Pure presentation, original design: +// a pale moth-like deity with four wide translucent wings, a cowled head with a single eye and a glowing core. +// Every hazard is drawn from the simulation's own geometry (sword capsules, beam lines, orb circles, the sweep box, +// spike / void boxes), so what you see is what hits. +(function (g) { + var BB = g.BB, ART = BB.ART, D = BB.BOSS_DRAW = BB.BOSS_DRAW || {}, K = BB.DRAWKIT; + var TAU = Math.PI * 2, INK = K.INK, teleK = K.teleK, aura = K.aura, stars = K.stars; + var GOLD = '255,236,170', WHITE = '255,252,240'; + + function sword(x, V, s, live, t) { // a thin radiant blade along its angle + var X = V.sx(s.x), Y = V.sy(s.y), L = s.hl * V.S; + x.save(); x.translate(X, Y); x.rotate(-s.ang); + if (!live) { x.globalAlpha = 0.55 + 0.35 * Math.sin(t * 22 + s.id); } + ART.glow(x, 0, 0, L * 0.9, GOLD, live ? 0.35 : 0.18); + x.beginPath(); x.moveTo(L, 0); x.lineTo(L * 0.55, -3.2); x.lineTo(-L, -1.6); x.lineTo(-L * 1.05, 0); x.lineTo(-L, 1.6); x.lineTo(L * 0.55, 3.2); x.closePath(); + ART.ink(x, live ? '#fffbe8' : 'rgba(255,248,220,0.75)', 1, 'rgba(120,96,40,0.9)'); + x.restore(); + } + function beamLine(x, V, o, t, w, lit) { // warning line, then the beam, to the room edge + var A = BB.ARENA, ca = Math.cos(o.ang), sa = Math.sin(o.ang); + var tx = ca > 0 ? (A.W - o.x) / ca : ca < 0 ? -o.x / ca : 1e9, ty = sa > 0 ? (A.H - o.y) / sa : sa < 0 ? -o.y / sa : 1e9, L = Math.min(tx, ty); + var X0 = V.sx(o.x), Y0 = V.sy(o.y), X1 = V.sx(o.x + ca * L), Y1 = V.sy(o.y + sa * L); + x.save(); x.globalCompositeOperation = 'lighter'; x.lineCap = 'round'; + if (!lit) { + x.strokeStyle = ART.rgba(GOLD, 0.35 + 0.25 * Math.sin(t * 30)); x.lineWidth = 1.5; + x.beginPath(); x.moveTo(X0, Y0); x.lineTo(X1, Y1); x.stroke(); + } else { + x.strokeStyle = ART.rgba(GOLD, 0.35); x.lineWidth = w * V.S * 1.9; x.beginPath(); x.moveTo(X0, Y0); x.lineTo(X1, Y1); x.stroke(); + x.strokeStyle = ART.rgba(WHITE, 0.95); x.lineWidth = w * V.S; x.beginPath(); x.moveTo(X0, Y0); x.lineTo(X1, Y1); x.stroke(); + } + x.restore(); + } + function column(x, V, cx, w, warn, t, rgb) { // a full-height column of light (sweep / big beam) or its warning + var A = BB.ARENA, X0 = V.sx(cx - w / 2), X1 = V.sx(cx + w / 2), Y0 = V.sy(A.H), Y1 = V.sy(0); + x.save(); x.globalCompositeOperation = 'lighter'; + if (warn) { + x.fillStyle = ART.rgba(rgb, 0.10 + 0.08 * Math.sin(t * 24)); x.fillRect(X0, Y0, X1 - X0, Y1 - Y0); + x.strokeStyle = ART.rgba(rgb, 0.6); x.lineWidth = 1.5; x.beginPath(); x.moveTo((X0 + X1) / 2, Y0); x.lineTo((X0 + X1) / 2, Y1); x.stroke(); + } else { + var gr = x.createLinearGradient(X0, 0, X1, 0); + gr.addColorStop(0, ART.rgba(rgb, 0)); gr.addColorStop(0.3, ART.rgba(rgb, 0.7)); gr.addColorStop(0.5, ART.rgba(WHITE, 0.95)); gr.addColorStop(0.7, ART.rgba(rgb, 0.7)); gr.addColorStop(1, ART.rgba(rgb, 0)); + x.fillStyle = gr; x.fillRect(X0 - (X1 - X0) * 0.25, Y0, (X1 - X0) * 1.5, Y1 - Y0); + } + x.restore(); + } + + D['2d/lumen_moth'] = { + bar: function (w) { return ['#fff1c8', '#ffe39a', '#ffd06a', '#ffb84a', '#ffffff'][Math.max(0, Math.min(4, w.phase - 1))]; }, + hazards: function (x, c, t, V) { + var w = c.boss, A = BB.ARENA, i; + // abyss: the void between footholds; the footholds stay pale stone + if (w.abyss) w.voidBoxes().forEach(function (b) { + var X0 = V.sx(b.gap[0]), X1 = V.sx(b.gap[1]), Yf = V.sy(0); + var gr = x.createLinearGradient(0, Yf - 26, 0, Yf + 16); gr.addColorStop(0, 'rgba(10,8,20,0)'); gr.addColorStop(0.5, 'rgba(10,8,20,0.85)'); gr.addColorStop(1, 'rgba(4,3,8,1)'); + x.fillStyle = gr; x.fillRect(X0, Yf - 26, X1 - X0, 44); + x.fillStyle = 'rgba(120,100,200,0.35)'; for (i = 0; i < 4; i++) { var px = X0 + ((t * 18 + i * 37) % Math.max(1, X1 - X0)); x.fillRect(px, Yf - 4 - (i % 2) * 6, 2, 2); } + }); + // spike floor: a glow while warning, then a row of pale spikes (the box is exactly the hazard) + var s = w.spikes; + if (s) { + var P = BB.SPECS.lumen_moth.moves.filter(function (m) { return m.name === 'spikes'; })[0].params, spans = []; + if (s.side === 0) spans = [[0, P.edge], [A.W - P.edge, A.W]]; + else spans = [s.side < 0 ? [0.15, A.W / 2 - 0.15] : [A.W / 2 + 0.15, A.W - 0.15]]; + spans.forEach(function (sp) { + var X0 = V.sx(sp[0]), X1 = V.sx(sp[1]), Yf = V.sy(0); + if (s.warn > 0) { x.save(); x.globalCompositeOperation = 'lighter'; x.fillStyle = ART.rgba(GOLD, 0.18 + 0.12 * Math.sin(t * 20)); x.fillRect(X0, Yf - 8, X1 - X0, 8); x.restore(); } + else { + var hgt = P.height * V.S; x.fillStyle = '#f7ecc8'; x.strokeStyle = 'rgba(110,86,40,0.9)'; x.lineWidth = 1; + for (var px = X0; px < X1 - 1; px += 12) { x.beginPath(); x.moveTo(px, Yf); x.lineTo(px + 6, Yf - hgt); x.lineTo(px + 12, Yf); x.closePath(); x.fill(); x.stroke(); } + } + }); + } + w.beams.forEach(function (o) { beamLine(x, V, o, t, o.w, o.warn <= 0); }); + if (w.sweep) column(x, V, w.sweep.x, BB.SPECS.lumen_moth.moves.filter(function (m) { return m.name === 'beam_sweep'; })[0].params.width, w.sweep.warn > 0, t, GOLD); + w.bigs.forEach(function (o) { column(x, V, o.x, BB.SPECS.lumen_moth.moves.filter(function (m) { return m.name === 'big_beam'; })[0].params.width, o.warn > 0, t, '255,250,230'); }); + w.swords.forEach(function (sw) { sword(x, V, sw, sw.hang <= 0, t); }); + w.orbs.forEach(function (o) { + var X = V.sx(o.x), Y = V.sy(o.y), R = 0.42 * V.S; + ART.glow(x, X, Y, R * 3.2, GOLD, 0.55); + var gr = x.createRadialGradient(X - R * 0.3, Y - R * 0.3, R * 0.1, X, Y, R); + gr.addColorStop(0, '#ffffff'); gr.addColorStop(0.5, '#fff1b8'); gr.addColorStop(1, 'rgba(255,214,110,0.9)'); + x.fillStyle = gr; x.beginPath(); x.arc(X, Y, R, 0, TAU); x.fill(); + }); + }, + body: function (x, c, t, V) { + var w = c.boss, st = w.st, fl = w.hitFlash > 0, X = V.sx(w.x), Y = V.sy(w.y), S = V.S; + var fade = st === 'tele_out' ? 1 - Math.min(1, w.stT / 0.25) : st === 'tele_in' ? Math.min(1, w.stT / 0.25) : 1; + if (st === 'dead') fade = Math.max(0, 1 - w.stT * 0.8); + if (fade <= 0.01) return; + x.save(); x.globalAlpha = fade; + var flap = Math.sin(t * 2.2) * 0.12, spread = /stagger|exposed|final_sink/.test(st) ? 0.55 : 1; + ART.glow(x, X, Y, 4.2 * S, GOLD, 0.22 + 0.1 * Math.sin(t * 3)); + aura(x, X, Y, 1.4 * S, 1.6 * S, teleK(w), t); + // four wings (drawn as pale membranes with gold veins); they are not hit boxes and deal no damage [web] + [[-1, 0], [1, 0], [-1, 1], [1, 1]].forEach(function (wg) { + var sd = wg[0], low = wg[1], span = (low ? 2.6 : 3.6) * S * spread, lift = (low ? 0.9 : -1.6) * S; + x.save(); x.translate(X + sd * 0.5 * S, Y + (low ? 0.4 : -0.3) * S); x.scale(sd, 1); x.rotate((low ? 0.25 : -0.2) + flap * (low ? -1 : 1)); + x.beginPath(); x.moveTo(0, 0); x.bezierCurveTo(span * 0.4, lift * 1.3, span * 0.95, lift * 0.9, span, lift * 0.2); + x.bezierCurveTo(span * 0.8, lift * -0.2 + 10, span * 0.3, 14, 0, 6); x.closePath(); + var gw = x.createLinearGradient(0, 0, span, lift); gw.addColorStop(0, 'rgba(255,250,232,0.85)'); gw.addColorStop(1, 'rgba(255,236,190,0.25)'); + x.fillStyle = fl ? 'rgba(255,255,255,0.95)' : gw; x.fill(); + x.strokeStyle = 'rgba(200,160,80,0.7)'; x.lineWidth = 1; + for (var v = 1; v <= 3; v++) { x.beginPath(); x.moveTo(2, 2); x.quadraticCurveTo(span * 0.3 * v / 3, lift * 0.6, span * (0.4 + 0.2 * v), lift * (0.9 - v * 0.25)); x.stroke(); } + x.restore(); + }); + // body: a tall cowled figure of pale silk, the core at its chest + x.beginPath(); x.moveTo(X, Y - 1.35 * S); x.bezierCurveTo(X + 0.75 * S, Y - 1.1 * S, X + 0.7 * S, Y + 0.6 * S, X + 0.25 * S, Y + 1.25 * S); + x.lineTo(X - 0.25 * S, Y + 1.25 * S); x.bezierCurveTo(X - 0.7 * S, Y + 0.6 * S, X - 0.75 * S, Y - 1.1 * S, X, Y - 1.35 * S); x.closePath(); + var gb = x.createLinearGradient(X, Y - 1.4 * S, X, Y + 1.3 * S); gb.addColorStop(0, '#fffdf3'); gb.addColorStop(1, '#d9c79a'); + ART.ink(x, ART.lit(fl, gb), 1.6, '#6a5428'); + // cowl and one wide eye + x.beginPath(); x.ellipse(X, Y - 1.0 * S, 0.42 * S, 0.36 * S, 0, 0, TAU); ART.ink(x, ART.lit(fl, '#fff8e2'), 1.4, '#6a5428'); + var eyeOpen = /antic|beam|burst|exposed/.test(st) ? 1 : 0.6; + x.fillStyle = '#ffb33a'; x.beginPath(); x.ellipse(X, Y - 1.0 * S, 0.17 * S, 0.11 * S * eyeOpen, 0, 0, TAU); x.fill(); + ART.glow(x, X, Y - 1.0 * S, 0.5 * S, '255,190,90', 0.5); + // the core (her vulnerable body) pulses brighter while she is exposed + var core = st === 'exposed' ? 1 : 0.55; + ART.glow(x, X, Y - 0.1 * S, (0.6 + 0.4 * core) * S, WHITE, 0.4 + 0.4 * core * (0.8 + 0.2 * Math.sin(t * 12))); + x.fillStyle = '#fffaf0'; x.beginPath(); x.arc(X, Y - 0.1 * S, 0.18 * S, 0, TAU); x.fill(); + x.restore(); + if (st === 'stagger') stars(x, X, Y - 1.6 * S, t); + } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/draw/needle_warden.js b/environments/games/web/games/hollowknight_remake/draw/needle_warden.js new file mode 100644 index 0000000000000000000000000000000000000000..bcbc7e46d6060cf0847c730bdce5861c2b4c2c2b --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/needle_warden.js @@ -0,0 +1,208 @@ +// Needle Warden drawing: BB.BOSS_DRAW['2d/needle_warden'] = {hazards, body}; no bar() -> the engine's default bar colours. +(function (g) { + var BB = g.BB, ART = BB.ART, V = BB.VIEW, TAU = Math.PI * 2; + var S = V.S, OX = V.OX, FLOOR = V.FLOOR, PAL = V.PAL, sx = V.sx, sy = V.sy; + + // pose table per FSM state (targets; ART.smooth blends between them) + function bossPose(w, t) { + var st = w.st, p = { crouch: 0, lean: 0, needle: -2.4, needleLen: 1, arms: 0, cloak: 0, rot: 0, glow: 0, stretch: 1, kneel: 0, guard: 0, dizzy: 0, dead: 0 }; + var tl = Math.max(0, w.timer), role = w.role(); + switch (st) { + case 'run': case 'run_antic': p.lean = 0.35; p.cloak = 0.6; p.needle = -2.7; break; + case 'gdash_antic': p.crouch = 0.75; p.lean = 0.25; p.needle = 0; p.needleLen = 1.1; p.glow = tl < 0.18 ? 1 : 0.3; break; + case 'gdash': p.crouch = 0.6; p.lean = 0.9; p.stretch = 1.35; p.needle = 0; p.needleLen = 1.3; p.cloak = 1; break; + case 'gdash_rec1': case 'gdash_rec2': p.crouch = 0.4; p.lean = -0.1; p.needle = -0.3; break; + case 'jump_antic': p.crouch = 0.6; p.needle = -2.2; break; + case 'air': p.crouch = 0.3; p.cloak = 0.8; p.needle = -2.6; break; + case 'adash_antic': p.crouch = 0.5; p.rot = 0; p.needle = null; p.glow = tl < 0.18 ? 1 : 0.35; p.cloak = 0.4; break; + case 'adash': p.stretch = 1.4; p.needle = null; p.cloak = 1; break; + case 'hard_land': p.crouch = 0.8; p.kneel = 1; p.needle = 0.3; break; + case 'wall_impact': p.crouch = 0.5; p.needle = -1.4; break; + case 'land': case 'evade_land': p.crouch = 0.45; break; + case 'g_sphere_antic': case 'a_sphere_antic': p.arms = 1; p.crouch = 0.2; p.glow = 0.6; p.needle = -1.6; break; + case 'g_sphere': case 'a_sphere': p.arms = 1.4; p.cloak = 1; p.needle = -1.6; break; + case 'g_sphere_recover': case 'a_sphere_recover': p.arms = 0.4; break; + case 'throw_antic': p.lean = -0.35; p.needle = -0.15; p.needleLen = 1.2; p.arms = 0.3; p.glow = tl < 0.18 ? 1 : 0.3; break; + case 'thrown': case 'throw_recover': p.lean = 0.2; p.needle = null; p.arms = 0.6; break; + case 'evade_antic': p.crouch = 0.4; break; + case 'evade': p.lean = -0.5; p.cloak = 1; break; + case 'stun_air': p.crouch = 0.3; p.dizzy = 1; p.needle = -3; break; + case 'stun_land': case 'stun_recover': p.kneel = 1; p.crouch = 0.9; p.dizzy = 1; p.needle = 0.8; break; + case 'dead': p.kneel = 1; p.crouch = 1; p.dead = 1; p.needle = 0.9; break; + } + p.role = role; + return p; + } + + // ---------- the needle warden ---------- + // Tall, slender guardian: bone mask with two swept horns, layered teal cloak with a tattered hem, + // red-thread sash, needle held in a thin dark arm. All poses blend through ART.smooth. + function warden(x, c, t) { + var w = c.boss, X = sx(w.x), Yf = sy(w.y - 1.55), f = w.f, tgt = bossPose(w, t); + var p = ART.smooth('warden', tgt, 22); + if (tgt.needle === null || p.needle === null) p.needle = tgt.needle; + var hgt = 2.45 * S * (1 - 0.33 * p.crouch), flash = w.hitFlash > 0; + var tele = w.role() === 'telegraph'; + ART.shade(x, X, FLOOR + 1, 30, 5, 0.55 * (1 - ART.c01((w.y - 1.55) / 8) * 0.7)); + x.save(); x.translate(X, Yf); + if (w.st === 'adash' || w.st === 'adash_antic') { + x.translate(0, -1.2 * S); x.rotate(-w.angle + (f < 0 ? Math.PI : 0)); x.translate(0, 1.2 * S); + } + x.scale(f, 1); + if (p.dead > 0.5) x.globalAlpha = 0.85; + x.rotate(p.lean * 0.32); + x.scale(p.stretch, 1 / Math.sqrt(p.stretch)); + // telegraph aura (readable cue for humans and pixel agents) + if (p.glow > 0.02) { + ART.glow(x, 0, -hgt * 0.55, 46 + 22 * p.glow, PAL.teleRGB, 0.22 + 0.4 * p.glow); + x.beginPath(); x.ellipse(0, -hgt * 0.52, 22 + 8 * p.glow, hgt * 0.56, 0, 0, TAU); + x.lineWidth = 1.5 + 1.5 * p.glow; x.strokeStyle = ART.rgba(PAL.teleRGB, 0.25 + 0.5 * p.glow); x.stroke(); + } + var INK = PAL.ink, cw = 20 + 12 * p.cloak + 8 * p.arms, ph = t * 5 + w.x; + var fl = Math.sin(t * 6) * 1.5 * (0.3 + p.cloak); + // back cloak layer (long, dark) + x.beginPath(); x.moveTo(-5, -hgt * 0.84); + x.bezierCurveTo(-cw * 0.7, -hgt * 0.62, -cw - fl - 6 * p.cloak, -hgt * 0.25, -cw - 10 * p.cloak - fl, -2); + ART.hem(x, -cw - 10 * p.cloak - fl, cw * 0.55, -2, 7, 6, 1.2 + p.cloak, ph, 11); + x.bezierCurveTo(cw * 0.5, -hgt * 0.3, cw * 0.35, -hgt * 0.62, 6, -hgt * 0.84); x.closePath(); + ART.ink(x, ART.lit(flash, PAL.bossCloak2), 2, INK); + // legs (thin, long) + x.lineCap = 'round'; x.strokeStyle = ART.lit(flash, PAL.boss); + var stp = w.st === 'run' ? Math.sin(t * 18) * 7 : 0; + x.lineWidth = 4.5; x.beginPath(); + if (p.kneel > 0.5) { x.moveTo(-4, -hgt * 0.14); x.lineTo(-13, -2); x.moveTo(5, -hgt * 0.14); x.lineTo(15, -7); x.lineTo(15, 0); } + else { x.moveTo(-3, -hgt * 0.15); x.quadraticCurveTo(-8 + stp, -hgt * 0.07, -5 + stp, 0); x.moveTo(4, -hgt * 0.15); x.quadraticCurveTo(9 - stp, -hgt * 0.07, 6 - stp, 0); } + x.stroke(); + // front cloak / mantle with a pale lining edge + x.beginPath(); x.moveTo(-4, -hgt * 0.82); + x.bezierCurveTo(-cw * 0.45, -hgt * 0.55, -cw * 0.7 - fl, -hgt * 0.32, -cw * 0.62 - fl, -hgt * 0.16); + ART.hem(x, -cw * 0.62 - fl, cw * 0.38, -hgt * 0.16, 5, 5, 0.8 + p.cloak, ph + 1, 23); + x.bezierCurveTo(cw * 0.34, -hgt * 0.42, 7, -hgt * 0.66, 5, -hgt * 0.82); x.closePath(); + ART.ink(x, ART.lit(flash, PAL.bossCloak), 1.6, INK); + if (!flash) { + x.beginPath(); x.moveTo(-3, -hgt * 0.8); x.bezierCurveTo(-cw * 0.4, -hgt * 0.55, -cw * 0.62 - fl, -hgt * 0.33, -cw * 0.58 - fl, -hgt * 0.18); + x.lineWidth = 1.2; x.strokeStyle = 'rgba(160,240,215,0.55)'; x.stroke(); + x.beginPath(); x.moveTo(-cw * 0.32, -hgt * 0.5); x.quadraticCurveTo(0, -hgt * 0.42, cw * 0.3, -hgt * 0.6); // red thread sash + x.lineWidth = 2.4; x.strokeStyle = '#b8443c'; x.stroke(); + x.beginPath(); x.moveTo(-cw * 0.3, -hgt * 0.5); + x.quadraticCurveTo(-cw * 0.45 - fl, -hgt * 0.35, -cw * 0.55 - fl * 2, -hgt * 0.22 + Math.sin(t * 4) * 2); + x.lineWidth = 1.6; x.stroke(); + } + if (p.arms > 0.05) { // arms spread for silk gathering + x.strokeStyle = ART.lit(flash, PAL.boss); x.lineWidth = 3; + x.beginPath(); x.moveTo(-2, -hgt * 0.66); x.quadraticCurveTo(-12 * p.arms, -hgt * 0.6, -20 * p.arms, -hgt * (0.68 + 0.14 * p.arms)); + x.moveTo(3, -hgt * 0.66); x.quadraticCurveTo(12 * p.arms, -hgt * 0.6, 20 * p.arms, -hgt * (0.68 + 0.14 * p.arms)); x.stroke(); + ART.glow(x, -20 * p.arms, -hgt * (0.68 + 0.14 * p.arms), 12, '255,245,220', 0.4 * p.arms); + ART.glow(x, 20 * p.arms, -hgt * (0.68 + 0.14 * p.arms), 12, '255,245,220', 0.4 * p.arms); + } + // head: bone mask with two swept horns, eye slits that burn amber + var hy = -hgt * 0.9; + x.beginPath(); x.moveTo(-2, hy - 6); x.bezierCurveTo(-10, hy - 16, -20, hy - 17, -27, hy - 12); x.bezierCurveTo(-18, hy - 12, -10, hy - 8, -3, hy - 1); x.closePath(); + ART.ink(x, ART.lit(flash, '#d9cfb8'), 1.4, INK); + x.beginPath(); x.moveTo(3, hy - 9); x.bezierCurveTo(-2, hy - 22, -10, hy - 27, -17, hy - 28); x.bezierCurveTo(-8, hy - 21, -2, hy - 14, 7, hy - 5); x.closePath(); + ART.ink(x, ART.lit(flash, PAL.bossMask), 1.4, INK); + x.beginPath(); x.moveTo(-5, hy - 7); x.bezierCurveTo(-4, hy - 13, 9, hy - 13, 10, hy - 4); + x.bezierCurveTo(11, hy + 4, 7, hy + 12, 3, hy + 13); x.bezierCurveTo(-1, hy + 12, -6, hy + 5, -5, hy - 7); x.closePath(); + var mg = x.createLinearGradient(0, hy - 12, 0, hy + 12); mg.addColorStop(0, '#fbf5e6'); mg.addColorStop(1, '#b9ae96'); + ART.ink(x, ART.lit(flash, mg), 1.5, INK); + x.fillStyle = '#0b0a08'; // two deep, slanted sockets and a thin mouth seam + x.beginPath(); x.ellipse(0.5, hy - 1.5, 2.3, 3.6, -0.35, 0, TAU); x.fill(); + x.beginPath(); x.ellipse(6.6, hy - 2.2, 2.6, 4, 0.35, 0, TAU); x.fill(); + x.strokeStyle = 'rgba(60,50,40,0.6)'; x.lineWidth = 0.8; x.beginPath(); x.moveTo(1.5, hy + 7); x.lineTo(6.5, hy + 6.2); x.stroke(); + var ec = p.dizzy > 0.5 ? '#7a7a7a' : PAL.bossEye; + x.fillStyle = ec; x.beginPath(); x.arc(0.9, hy - 1.2, 0.9, 0, TAU); x.arc(6.9, hy - 1.8, 1.05, 0, TAU); x.fill(); + if (p.dizzy < 0.5) ART.glow(x, 5, hy - 1.8, 6 + (tele ? 8 : 0), '255,179,71', 0.3 + (tele ? 0.35 : 0)); + if (p.needle !== null) { // needle in hand + var nl = 1.75 * S * p.needleLen, hx = 6, hyy = -hgt * 0.6, ca = Math.cos(p.needle), sa = -Math.sin(p.needle); + x.strokeStyle = ART.lit(flash, PAL.boss); x.lineWidth = 3; x.beginPath(); x.moveTo(2, -hgt * 0.7); x.lineTo(hx, hyy); x.stroke(); + x.save(); x.translate(hx, hyy); x.rotate(Math.atan2(sa, ca)); + x.beginPath(); x.moveTo(-6, -1.2); x.lineTo(nl - 5, -1.4); x.lineTo(nl + 2, 0); x.lineTo(nl - 5, 1.4); x.lineTo(-6, 1.2); x.closePath(); + ART.ink(x, PAL.needle, 1, INK); + x.beginPath(); x.arc(-7, 0, 2.6, 0, TAU); x.lineWidth = 1.4; x.strokeStyle = '#d6c79a'; x.stroke(); + x.restore(); + if (p.glow >= 0.95) { + var gx = hx + ca * nl, gy = hyy + sa * nl; + ART.glow(x, gx, gy, 18, '255,240,190', 0.8); ART.spark(x, gx, gy, 6 + 3 * Math.sin(t * 40), '#fff6c8'); + } + } else if (w.st === 'adash' || w.st === 'adash_antic') { + x.save(); x.translate(8, -1.2 * S); + x.beginPath(); x.moveTo(0, -1.4); x.lineTo(2.0 * S - 6, -1.6); x.lineTo(2.0 * S + 2, 0); x.lineTo(2.0 * S - 6, 1.6); x.lineTo(0, 1.4); x.closePath(); + ART.ink(x, PAL.needle, 1, INK); x.restore(); + if (p.glow >= 0.95) { ART.glow(x, 8 + 2.0 * S, -1.2 * S, 18, '255,240,190', 0.8); ART.spark(x, 8 + 2.0 * S, -1.2 * S, 7, '#fff6c8'); } + if (w.st === 'adash') { + for (var s = 1; s <= 4; s++) { x.globalAlpha = 0.18 * (5 - s) / 4; x.fillStyle = PAL.bossCloak; x.beginPath(); x.ellipse(-s * 14, -hgt * 0.5, 14, hgt * 0.4, 0, 0, TAU); x.fill(); } + x.globalAlpha = 1; + } + } + if (p.guard > 0.05) { + x.strokeStyle = ART.rgba('255,240,180', (0.45 + 0.3 * Math.sin(t * 30)) * p.guard); x.lineWidth = 3; + x.beginPath(); x.arc(10, -hgt * 0.55, 24, -1.2, 1.2); x.stroke(); + ART.glow(x, 22, -hgt * 0.55, 26, '255,240,180', 0.3 * p.guard); + } + x.restore(); + if (p.dizzy > 0.5 && p.dead < 0.5) for (var i = 0; i < 3; i++) { var a = t * 5 + i * 2.1; ART.spark(x, X + Math.cos(a) * 15, Yf - hgt - 10 + Math.sin(a) * 4, 4, '#ffe9a0'); } + if (w.st === 'adash_antic') { // aim line (aim locks when the freeze starts) [hand readability aid] + var cx0 = X, cy0 = sy(w.y), L = 900; + x.save(); x.setLineDash([6, 8]); x.strokeStyle = ART.rgba('255,207,90', 0.25 + 0.35 * (w.timer < 0.18 ? 1 : 0)); x.lineWidth = 1.5; + x.beginPath(); x.moveTo(cx0, cy0); x.lineTo(cx0 + Math.cos(w.angle) * L, cy0 - Math.sin(w.angle) * L); x.stroke(); x.restore(); + } + } + + function needleShape(x, X, Y, dir, len0, len1) { + x.beginPath(); x.moveTo(X - dir * len0, Y - 1.6); x.lineTo(X + dir * (len1 - 8), Y - 2); x.lineTo(X + dir * (len1 + 4), Y); + x.lineTo(X + dir * (len1 - 8), Y + 2); x.lineTo(X - dir * len0, Y + 1.6); x.closePath(); + ART.ink(x, PAL.needle, 1.2, PAL.ink); + x.beginPath(); x.arc(X - dir * (len0 + 3), Y, 3, 0, TAU); x.lineWidth = 1.5; x.strokeStyle = '#d6c79a'; x.stroke(); + } + function hazards(x, c, t) { + var w = c.boss; + if (w.needle) { + var n = w.needle, X = sx(n.x), Y = sy(n.y); + x.save(); + if (n.ph !== 'out') { // thread back to her hand (slight sag) + var hx0 = sx(w.x), hy0 = sy(w.y - 0.3); + x.strokeStyle = PAL.thread; x.lineWidth = 1.5; + x.beginPath(); x.moveTo(hx0, hy0); x.quadraticCurveTo((hx0 + X) / 2, (hy0 + Y) / 2 + 10, X, Y); x.stroke(); + ART.glow(x, X, Y, 10, '255,214,140', 0.3); + } + x.save(); x.globalCompositeOperation = 'lighter'; // motion streak behind the flying needle + var sg = x.createLinearGradient(X - n.dir * 110, Y, X, Y); sg.addColorStop(0, 'rgba(230,240,255,0)'); sg.addColorStop(1, 'rgba(230,240,255,0.45)'); + x.fillStyle = sg; x.beginPath(); x.moveTo(X - n.dir * 110, Y); x.lineTo(X, Y - 5); x.lineTo(X, Y + 5); x.closePath(); x.fill(); + x.restore(); + needleShape(x, X, Y, n.dir, 1.25 * S, 0.8 * S + 12); + x.restore(); + } + if (w.sphere) { // silk sphere: woven threads around a bright core + var r = w.sphereRadius() * S, cx = sx(w.x + 0.0625 * w.f), cy = sy(w.y - 0.281); + x.save(); + ART.glow(x, cx, cy, r * 1.35, '255,248,230', 0.35); + var fg = x.createRadialGradient(cx, cy, 0, cx, cy, r); fg.addColorStop(0, 'rgba(255,250,240,0.22)'); fg.addColorStop(0.85, 'rgba(255,248,230,0.1)'); fg.addColorStop(1, 'rgba(255,255,255,0.3)'); + x.fillStyle = fg; x.beginPath(); x.arc(cx, cy, r, 0, TAU); x.fill(); + x.strokeStyle = PAL.silk; + var rr = new BB.RNG(Math.floor(t * 30)); + for (var i = 0; i < 30; i++) { + var a0 = rr.uniform(0, TAU), a1 = a0 + rr.uniform(1.2, 2.8); + x.lineWidth = rr.uniform(0.8, 2); x.globalAlpha = rr.uniform(0.5, 1); + x.beginPath(); x.moveTo(cx + Math.cos(a0) * r, cy + Math.sin(a0) * r); + x.quadraticCurveTo(cx + Math.cos((a0 + a1) / 2) * r * 0.2, cy + Math.sin((a0 + a1) / 2) * r * 0.2, cx + Math.cos(a1) * r, cy + Math.sin(a1) * r); + x.stroke(); + } + x.globalAlpha = 1; x.lineWidth = 2.5; x.strokeStyle = 'rgba(255,255,255,0.85)'; x.beginPath(); x.arc(cx, cy, r, 0, TAU); x.stroke(); + x.restore(); + } + if (w.st === 'g_sphere_antic' || w.st === 'a_sphere_antic') { // silk drawn inward + var k = 1 - Math.max(0, w.timer) / 0.9, cx2 = sx(w.x), cy2 = sy(w.y - 0.28), r2 = (1 - k) * 90 + 10; + x.save(); x.globalCompositeOperation = 'lighter'; + for (var j = 0; j < 14; j++) { + var a = j * 0.449 + t * 2, rj = r2 + 8 * Math.sin(j * 2.3); + x.strokeStyle = ART.rgba('255,245,220', 0.35 + 0.4 * k); x.lineWidth = 1.2; + x.beginPath(); x.moveTo(cx2 + Math.cos(a) * rj, cy2 + Math.sin(a) * rj); x.lineTo(cx2 + Math.cos(a + 0.15) * (rj + 22), cy2 + Math.sin(a + 0.15) * (rj + 22)); x.stroke(); + } + ART.glow(x, cx2, cy2, 20 + 30 * k, '255,245,220', 0.3 + 0.4 * k); + x.restore(); + } + } + + BB.BOSS_DRAW = BB.BOSS_DRAW || {}; + BB.BOSS_DRAW['2d/needle_warden'] = { hazards: hazards, body: warden }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/draw/pale_vessel.js b/environments/games/web/games/hollowknight_remake/draw/pale_vessel.js new file mode 100644 index 0000000000000000000000000000000000000000..6fb13d4c2b3bb9f04610aff381160f7fb0844dcc --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/pale_vessel.js @@ -0,0 +1,159 @@ +// Drawing for 2d/pale_vessel: BB.BOSS_DRAW[caseId] = {bar, hazards, body}. Pure presentation, original design. +(function (g) { + var BB = g.BB, ART = BB.ART, D = BB.BOSS_DRAW = BB.BOSS_DRAW || {}, K = BB.DRAWKIT; + var TAU = Math.PI * 2, INK = K.INK, TELE = K.TELE; + var teleK = K.teleK, aura = K.aura, stars = K.stars, blob = K.blob, nailArc = K.nailArc, blade = K.blade; + + // ---------- Pale Vessel: a tall pale knight, horned shell mask, long grey cloak bound with chains, + // a broad nail, and a chest crack that leaks more orange light every phase ---------- + function palePose(w, t) { + var st = w.st, p = { nail: 0.25, lean: 0, crouch: 0, kneel: 0, chest: 0, rise: 0, arm2: 0 }; + if (st === 'slash_antic' || st === 'weak_antic') { p.nail = -2.5; p.lean = -0.1; p.crouch = 0.1; } + else if (/slash[123]|weak_slash|cslash/.test(st)) { var n = +st.charAt(5) || 1; p.nail = n === 2 ? -0.9 : 0.55; p.lean = 0.18; } + else if (st === 'slash_recover' || st === 'cs_recover') { p.nail = 0.9; } + else if (st === 'dash_antic') { p.nail = Math.PI - 0.25; p.crouch = 0.35; p.lean = -0.2; } + else if (st === 'dash') { p.nail = 0.02; p.lean = 0.35; p.crouch = 0.15; } + else if (/counter_antic|counter$|cs_block/.test(st)) { p.nail = -1.15; p.lean = -0.05; p.arm2 = 1; } + else if (/jump_antic|dstab_antic|stomp_antic|pup_antic/.test(st)) { p.crouch = 0.4; p.nail = 1.0; } + else if (/dstab_jump|stomp|dstab_land|pup_down|pup_slam/.test(st)) { p.nail = Math.PI / 2; p.crouch = /land|slam/.test(st) ? 0.4 : 0; } + else if (/plume_gen|plume_up/.test(st)) { p.nail = Math.PI / 2; p.kneel = 0.8; p.crouch = 0.3; } + else if (/shot/.test(st)) { p.nail = -0.4; p.arm2 = 1; p.chest = 0.4; } + else if (/chest/.test(st)) { p.chest = 1; p.nail = 1.4; p.lean = -0.22; p.rise = st === 'chest' || st === 'chest_rise' ? 1 : 0.5; } + else if (/^ss_/.test(st)) { p.nail = -2.0; p.kneel = 0.5; p.crouch = 0.25; p.chest = 0.7; } + else if (/roar/.test(st)) { p.lean = -0.25; p.nail = 1.2; p.chest = 0.8; } + else if (STUN_RE.test(st)) { p.kneel = 1; p.crouch = 0.45; p.nail = 1.5; } + else if (st === 'dead') { p.kneel = 1; p.crouch = 0.6; p.nail = 1.6; } + else if (st === 'walk' || st === 'weak_walk') p.lean = 0.05; + return p; + } + var STUN_RE = /stun|pup_fall|pup_end|pup_stand/; + D['2d/pale_vessel'] = { + bar: function (w) { return ['#e8e4dc', '#e8d4b8', '#f0b880', '#ff8a4a'][Math.max(0, Math.min(3, w.phase - 1))]; }, + hazards: function (x, c, t, V) { + var w = c.boss; + w.plumes.forEach(function (o) { + var X = V.sx(o.x), Yf = V.sy(0); + if (o.warn > 0) { // charging: a glowing fissure and rising embers + var a = 0.5 + 0.3 * Math.sin(t * 18 + o.x); + ART.glow(x, X, Yf - 4, 26, '255,140,60', a * 0.6); + x.fillStyle = ART.rgba('255,190,110', a); x.beginPath(); x.ellipse(X, Yf - 1, 15, 2.5, 0, 0, TAU); x.fill(); + for (var i = 0; i < 5; i++) { var yy = (t * 50 + i * 9 + o.x * 7) % 40; x.fillStyle = ART.rgba('255,200,130', 1 - yy / 40); x.fillRect(X - 10 + i * 5 + Math.sin(yy * 0.3 + i) * 2, Yf - yy, 2, 3); } + } + }); + w.hazards().forEach(function (h) { + if (h.kind === 'plume') { // a column of infection: hot core, flickering tongues + var b = h.box, X0 = V.sx(b.x - b.w / 2), Y0 = V.sy(b.y + b.h / 2), Wd = b.w * V.S, Hd = b.h * V.S, cx = X0 + Wd / 2; + x.save(); x.globalCompositeOperation = 'lighter'; + var gr = x.createLinearGradient(0, Y0 + Hd, 0, Y0); + gr.addColorStop(0, 'rgba(255,170,80,0.95)'); gr.addColorStop(0.65, 'rgba(255,110,40,0.55)'); gr.addColorStop(1, 'rgba(255,110,40,0)'); + x.fillStyle = gr; x.beginPath(); x.moveTo(X0, Y0 + Hd); + for (var k = 0; k <= 8; k++) { var yy = Y0 + Hd * (1 - k / 8); x.lineTo(X0 + Math.sin(t * 14 + k * 1.3) * 3 * k / 8, yy); } + x.lineTo(cx, Y0 - 6); + for (k = 8; k >= 0; k--) { var y2 = Y0 + Hd * (1 - k / 8); x.lineTo(X0 + Wd + Math.sin(t * 13 + k * 1.7) * 3 * k / 8, y2); } + x.closePath(); x.fill(); + var cg = x.createLinearGradient(0, Y0 + Hd, 0, Y0 + Hd * 0.1); cg.addColorStop(0, 'rgba(255,250,220,0.95)'); cg.addColorStop(1, 'rgba(255,240,200,0)'); + x.fillStyle = cg; x.fillRect(cx - Wd * 0.14, Y0 + Hd * 0.1, Wd * 0.28, Hd * 0.9); + x.restore(); + ART.glow(x, cx, Y0 + Hd, Wd * 1.6, '255,140,60', 0.5); + } else if (h.kind === 'blob') { + blob(x, V, { x: h.circle[0], y: h.circle[1], vx: 0, vy: 0 }, h.circle[2], t); + } + }); + }, + body: function (x, c, t, V) { + var w = c.boss, st = w.st, f = w.f, fl = w.hitFlash > 0, bb = w.bodyBox(); + var X = V.sx(w.x), Yf = V.sy(w.y), hw = bb.w / 2 * V.S, H = bb.h * V.S; + var p = ART.smooth('pale', palePose(w, t), 18); + if (st === 'tele_out' || st === 'tele_in') { // dissolving / reforming into pale dust + var k = st === 'tele_out' ? Math.min(1, w.stT / 0.3) : 1 - Math.min(1, w.stT / 0.3); + ART.glow(x, X, Yf - H * 0.5, H * 0.7, '230,226,215', 0.4 * (1 - k)); + for (var d = 0; d < 18; d++) { + var hx = ART.hash(d), hy = ART.hash(d + 40), rise = k * (30 + 50 * hy); + x.fillStyle = 'rgba(235,230,220,' + (0.85 * (1 - k)).toFixed(3) + ')'; + x.fillRect(X + (hx - 0.5) * hw * 2 * (1 + k), Yf - hy * H - rise, 2.5, 2.5); + } + return; + } + ART.shade(x, X, V.sy(0) - 1, hw * 1.35 * (1 - Math.min(0.6, w.y / 10)), 6, 0.5); + aura(x, X, Yf - H * 0.5, hw * 1.7, H * 0.7, teleK(w), t); + if (st === 'counter' || st === 'cs_block') { // parry stance: a cold, shimmering guard + ART.glow(x, X + f * hw * 0.7, Yf - H * 0.6, H * 0.55, '200,225,255', 0.3 + 0.12 * Math.sin(t * 20)); + x.save(); x.strokeStyle = 'rgba(220,235,255,0.7)'; x.lineWidth = 2; x.beginPath(); x.arc(X + f * hw * 0.2, Yf - H * 0.6, H * 0.45, f > 0 ? -1.1 : Math.PI - 1.1 + 0, f > 0 ? 1.1 : Math.PI + 1.1); x.stroke(); x.restore(); + } + w.hazards().forEach(function (h) { if (h.kind === 'nail') nailArc(x, V, h.box, f, null, w.x); }); + if (st === 'dash') for (var gI = 1; gI <= 4; gI++) { // afterimages: the figure's own silhouette, fading back + var gx = X - f * gI * 17, gh = H * 0.9; + x.save(); x.globalAlpha = 0.22 / gI; x.fillStyle = '#d8d4ea'; x.translate(gx, Yf); x.scale(f, 1); x.rotate(0.35); + x.beginPath(); x.moveTo(-hw * 0.4, -gh * 0.84); x.quadraticCurveTo(-hw * 1.3, -gh * 0.4, -hw * 1.2, 0); x.lineTo(hw * 0.5, 0); + x.quadraticCurveTo(hw * 0.7, -gh * 0.45, hw * 0.4, -gh * 0.84); x.closePath(); x.fill(); + x.beginPath(); x.ellipse(hw * 0.06, -gh * 0.95, H * 0.12, H * 0.14, 0, 0, TAU); x.fill(); + x.restore(); + } + if (/^pup_/.test(st)) { // the puppet pull: glowing threads from the dark above + x.save(); x.strokeStyle = 'rgba(255,170,90,0.45)'; x.lineWidth = 1.2; + [-0.4, 0.4].forEach(function (o) { x.beginPath(); x.moveTo(X + o * hw, Yf - H * 0.75); x.quadraticCurveTo(X + o * hw * 2, Yf - H * 2, X + o * hw * 1.5, ART.view.ROOF); x.stroke(); }); + x.restore(); + } + x.save(); x.translate(X, Yf); x.scale(f, 1); + if (st === 'dead') x.globalAlpha = 0.75; + var h = H * (1 - 0.25 * p.crouch - 0.12 * p.kneel); + x.rotate(p.lean); + var body = ART.lit(fl, '#18161c'); + // legs: one knee down when kneeling + [[-0.25, 1], [0.25, 0]].forEach(function (L, li) { + var lx = hw * L[0], kn = li === 0 ? p.kneel : 0, kx = lx + 4 + p.crouch * 6, ky = -h * 0.18 + kn * h * 0.12; + x.beginPath(); ART.ribbon(x, [[lx, -h * 0.36], [kx, ky], [lx + (kn ? -10 : 2), kn ? -2 : 0]], 10, 7); ART.ink(x, body, 1.5, INK); + }); + // long cloak, chain-bound at the waist, hem tattered + var ph = t * 2.4, sw = -Math.max(0, p.lean) * hw * 0.8; + x.beginPath(); x.moveTo(-hw * 0.42, -h * 0.84); + x.quadraticCurveTo(-hw * 1.05 + sw, -h * 0.45, -hw * 0.95 + sw * 1.5, -h * 0.03); + ART.hem(x, -hw * 0.95 + sw * 1.5, hw * 0.55, -h * 0.02, 8, 9, 2, ph, 97); + x.quadraticCurveTo(hw * 0.7, -h * 0.45, hw * 0.4, -h * 0.84); x.closePath(); + var cg = x.createLinearGradient(-hw, -h, hw, 0); cg.addColorStop(0, '#2a2730'); cg.addColorStop(0.7, '#4c4754'); cg.addColorStop(1, '#5e5866'); + ART.ink(x, ART.lit(fl, cg), 2, INK); + if (!fl) { + x.strokeStyle = 'rgba(255,255,255,0.12)'; x.lineWidth = 1.5; // fold lines + for (var fi = 0; fi < 3; fi++) { x.beginPath(); x.moveTo(-hw * 0.3 + fi * hw * 0.25, -h * 0.6); x.quadraticCurveTo(-hw * 0.45 + fi * hw * 0.3, -h * 0.3, -hw * 0.55 + fi * hw * 0.35 + Math.sin(ph + fi) * 2, -h * 0.06); x.stroke(); } + x.strokeStyle = '#8a8290'; x.lineWidth = 2.5; x.setLineDash([4, 3]); + x.beginPath(); x.moveTo(-hw * 0.6, -h * 0.48); x.quadraticCurveTo(0, -h * 0.42, hw * 0.55, -h * 0.5); x.stroke(); x.setLineDash([]); + } + // pale torso plate with the chest crack + x.beginPath(); x.moveTo(-hw * 0.32, -h * 0.82); x.quadraticCurveTo(hw * 0.02, -h * 0.88, hw * 0.36, -h * 0.82); + x.quadraticCurveTo(hw * 0.32, -h * 0.6, hw * 0.12, -h * 0.5); x.lineTo(-hw * 0.14, -h * 0.5); x.quadraticCurveTo(-hw * 0.34, -h * 0.6, -hw * 0.32, -h * 0.82); x.closePath(); + var tg = x.createLinearGradient(0, -h * 0.88, 0, -h * 0.5); tg.addColorStop(0, '#f4f1ea'); tg.addColorStop(1, '#b8b2a8'); + ART.ink(x, ART.lit(fl, tg), 1.5, INK); + var heat = Math.min(1, Math.max(p.chest, 0.2 + 0.2 * (w.phase - 1))); + x.strokeStyle = '#1a0a04'; x.lineWidth = 2.5 + 2 * heat; + x.beginPath(); x.moveTo(-hw * 0.12, -h * 0.8); x.lineTo(hw * 0.06, -h * 0.7); x.lineTo(-hw * 0.04, -h * 0.62); x.lineTo(hw * 0.08, -h * 0.53); x.stroke(); + x.strokeStyle = ART.rgba('255,170,80', 0.6 + 0.4 * heat); x.lineWidth = 1 + 1.5 * heat; x.stroke(); + ART.glow(x, 0, -h * 0.67, hw * (0.6 + 1.2 * heat), '255,140,60', 0.2 + 0.4 * heat * (0.85 + 0.15 * Math.sin(t * 14))); + // head: tall pale shell, two long backswept horns, dark hollow eyes + var hx = hw * 0.06, hy = -h * 0.95, hr = H * 0.125; + // two horns rising from the crown, sweeping back in a long tapering curve (far one darker, shorter) + [[-0.35, 0.8], [0.2, 1]].forEach(function (hn) { + var bx0 = hx + hn[0] * hr, s2 = hn[1]; + x.beginPath(); + ART.ribbon(x, ART.bez([bx0, hy - hr * 0.55], [bx0 - hr * 0.1, hy - hr * 1.9 * s2], [bx0 - hr * 0.8 * s2, hy - hr * 2.9 * s2], [bx0 - hr * 2.0 * s2, hy - hr * 3.2 * s2], 14), hr * 0.62, 1.2); + ART.ink(x, ART.lit(fl, hn[1] < 1 ? '#bfb9b0' : '#ebe7df'), 1.4, INK); + }); + x.beginPath(); x.ellipse(hx, hy, hr * 0.92, hr * 1.12, 0, 0, TAU); + var mg = x.createRadialGradient(hx - hr * 0.3, hy - hr * 0.4, hr * 0.1, hx, hy, hr * 1.2); mg.addColorStop(0, '#ffffff'); mg.addColorStop(1, '#bdb7ad'); + ART.ink(x, ART.lit(fl, mg), 1.8, INK); + x.fillStyle = '#08070a'; + x.beginPath(); x.ellipse(hx + hr * 0.02, hy + hr * 0.05, hr * 0.2, hr * 0.42, 0.06, 0, TAU); x.fill(); + x.beginPath(); x.ellipse(hx + hr * 0.55, hy + hr * 0.02, hr * 0.17, hr * 0.38, 0.04, 0, TAU); x.fill(); + if (heat > 0.75) ART.glow(x, hx + hr * 0.3, hy, hr * 1.2, '255,140,60', 0.25); + // off-hand raised for the parry / shot + if (p.arm2 > 0.05) { x.beginPath(); ART.ribbon(x, [[-hw * 0.1, -h * 0.74], [hw * 0.3, -h * 0.72 - 6 * p.arm2], [hw * 0.55 * p.arm2, -h * 0.78]], 8, 6); ART.ink(x, body, 1.4, INK); } + // broad nail + x.save(); x.translate(hw * 0.38, -h * 0.64); x.rotate(p.nail); + x.beginPath(); ART.ribbon(x, [[-10, 0], [8, 0]], 10, 8); ART.ink(x, body, 1.4, INK); + blade(x, 2.3 * V.S, 8, ART.lit(fl, '#dcd8d0')); + x.restore(); + x.restore(); + if (w.locked) ART.glow(x, X, Yf - H * 0.5, H * 0.9, '255,255,255', 0.18); + if (/stun/.test(st)) stars(x, X, Yf - H - 10, t); + } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/draw/palette.js b/environments/games/web/games/hollowknight_remake/draw/palette.js new file mode 100644 index 0000000000000000000000000000000000000000..7f71171fa0b44a550ec92b01579950faa465b983 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/palette.js @@ -0,0 +1,12 @@ +// Palette of this game (BB.VIEW.PAL), shared by the body, warden and HUD drawing. +(function (g) { + var BB = g.BB; + BB.VIEW.PAL = { + sky0: '#0b1a24', sky1: '#16313a', fog: 'rgba(120,190,180,0.06)', wall: '#0a1418', wallEdge: '#24453f', + floor: '#13262a', moss: '#2f6a58', thorn: '#0f2a26', + hero: '#161c2e', heroCloak: '#1c2540', heroRim: 'rgba(170,225,235,0.55)', heroHead: '#ece6d6', heroEye: '#7ff3ff', scarf: '#6fc9d2', nail: '#dfe6ec', + boss: '#102522', bossCloak: '#2c7d6c', bossCloak2: '#163f38', bossMask: '#efe6d2', bossEye: '#ffb347', + needle: '#e4ebf0', thread: 'rgba(255,214,140,0.9)', silk: 'rgba(250,240,220,0.95)', + ink: '#05080a', tele: '#ffcf5a', teleRGB: '255,200,90', danger: '#ff5a4a', soul: '#bfefff', hud: '#e9f1f2' + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/draw/sickle_sisters.js b/environments/games/web/games/hollowknight_remake/draw/sickle_sisters.js new file mode 100644 index 0000000000000000000000000000000000000000..9e2f953f6b56c36e19a635f09f8a300ec3af7c7f --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/sickle_sisters.js @@ -0,0 +1,133 @@ +// Drawing for 2d/sickle_sisters: BB.BOSS_DRAW[caseId] = {bar, hazards, body}. Pure presentation, original design. +(function (g) { + var BB = g.BB, ART = BB.ART, D = BB.BOSS_DRAW = BB.BOSS_DRAW || {}, K = BB.DRAWKIT; + var TAU = Math.PI * 2, INK = K.INK, TELE = K.TELE; + var teleK = K.teleK, aura = K.aura, stars = K.stars, blob = K.blob, nailArc = K.nailArc, blade = K.blade; + + // ---------- Sickle Sisters: three slender chitin duelists (one tint each), narrow-waisted, with wing-case + // mantles, crested helm-masks and long lances; boomerang crescents ---------- + var SIS_COL = ['#7f9c6a', '#6f8aa0', '#9a7fa8'], SIS_RGB = ['150,200,130', '140,180,220', '200,160,220']; + function SIS_LANCE(w) { return w.spec.moves.filter(function (m) { return m.name === 'dash'; })[0].params.lance; } + function sisPose(s) { + var st = s.st, p = { crouch: 0, lance: -1.25, lean: 0, arm: 0, wing: 0 }; + if (/^dash_(arrive|antic)$/.test(st)) { p.crouch = 0.55; p.lance = 0; p.lean = 0.2; p.wing = 0.4; } + else if (st === 'dash') { p.crouch = 0.55; p.lance = 0; p.lean = 0.35; p.wing = 1; } + else if (/dash_(recover|leave)/.test(st)) { p.crouch = 0.3; p.lance = 0.2; p.lean = 0.1; } + else if (/^dstab/.test(st)) { p.lance = Math.PI / 2; p.crouch = st === 'dstab_land' ? 0.4 : 0; p.wing = st === 'dstab_fall' ? 1 : 0.5; } + else if (st === 'throw_antic' || st === 'wall_arrive') { p.lance = -2.4; p.arm = 1; p.lean = -0.1; p.wing = 0.5; } + else if (st === 'throw') { p.lance = -0.3; p.arm = -0.5; p.lean = 0.15; } + else if (/throw_cd|leave_pause|wall_leave/.test(st)) { p.lance = -1.0; } + else if (st === 'dying') { p.crouch = 0.5; p.lance = 1.2; p.lean = -0.3; } + return p; + } + function sister(x, s, i, V, t, w) { + var b = s.box(), X = V.sx(s.x), Yf = V.sy(s.y), f = s.f, fl = s.hitFlash > 0; + var H = 2.391 * V.S, hw = b.w / 2 * V.S, p = ART.smooth('sis' + i, sisPose(s), 20); + var col = ART.lit(fl, SIS_COL[i]), dark = ART.lit(fl, '#141a16'); + ART.shade(x, X, V.sy(0) - 1, hw * 1.4 * (1 - Math.min(0.6, s.y / 10)), 5, 0.45); + var tk = s.role() === 'telegraph' ? (Math.max(0, s.timer) < 0.18 ? 1 : 0.5) : 0; + aura(x, X, Yf - H * 0.5 * (1 - 0.4 * p.crouch), hw * 1.7, H * 0.62 * (1 - 0.3 * p.crouch), tk, t); + x.save(); x.translate(X, Yf); x.scale(f, 1); + if (s.st === 'dying') x.globalAlpha = 0.55; + var h = H * (1 - 0.42 * p.crouch); + x.rotate(p.lean); + // long jointed legs (knees forward when crouched) + x.strokeStyle = dark; x.lineCap = 'round'; + [[-0.25, -1], [0.25, 1]].forEach(function (L) { + var hx0 = hw * L[0] * 0.5, kx = hw * L[0] + hw * 0.5 * p.crouch, ky = -h * 0.2, fx = hw * L[0] * 1.2 - L[1] * p.crouch * hw * 0.5; + x.lineWidth = 4.5; x.beginPath(); x.moveTo(hx0, -h * 0.42); x.lineTo(kx, ky); x.lineTo(fx, 0); x.stroke(); + x.lineWidth = 2; x.beginPath(); x.moveTo(fx, 0); x.lineTo(fx + 6, 0); x.stroke(); + }); + // wing-case mantle: two long chitin plates flaring back + var fly = p.wing; + x.beginPath(); x.moveTo(-hw * 0.1, -h * 0.82); + x.quadraticCurveTo(-hw * (1.4 + fly), -h * (0.7 - 0.1 * fly), -hw * (1.1 + 1.2 * fly), -h * (0.18 + 0.1 * fly)); + x.quadraticCurveTo(-hw * 0.5, -h * 0.35, hw * 0.1, -h * 0.5); x.closePath(); + var wg = x.createLinearGradient(-hw * 2, 0, hw * 0.2, 0); wg.addColorStop(0, '#1a221c'); wg.addColorStop(1, col); + ART.ink(x, ART.lit(fl, wg), 1.5, INK); + x.strokeStyle = 'rgba(255,255,255,0.25)'; x.lineWidth = 1; x.beginPath(); x.moveTo(-hw * 0.05, -h * 0.78); x.quadraticCurveTo(-hw * (1.0 + fly), -h * 0.6, -hw * (0.95 + fly), -h * 0.28); x.stroke(); + // torso: narrow waist, plated chest + x.beginPath(); x.moveTo(-hw * 0.32, -h * 0.84); x.quadraticCurveTo(hw * 0.05, -h * 0.9, hw * 0.4, -h * 0.82); + x.quadraticCurveTo(hw * 0.25, -h * 0.6, hw * 0.06, -h * 0.5); x.lineTo(hw * 0.2, -h * 0.4); x.lineTo(-hw * 0.2, -h * 0.4); x.lineTo(-hw * 0.08, -h * 0.5); + x.quadraticCurveTo(-hw * 0.38, -h * 0.65, -hw * 0.32, -h * 0.84); x.closePath(); + var tg = x.createLinearGradient(0, -h * 0.9, 0, -h * 0.4); tg.addColorStop(0, col); tg.addColorStop(1, '#1a221c'); + ART.ink(x, ART.lit(fl, tg), 1.5, INK); + // short skirt of plates + x.beginPath(); x.moveTo(-hw * 0.25, -h * 0.42); x.lineTo(hw * 0.28, -h * 0.42); x.lineTo(hw * 0.4, -h * 0.28); x.lineTo(hw * 0.05, -h * 0.32); x.lineTo(-hw * 0.4, -h * 0.26); x.closePath(); + ART.ink(x, ART.lit(fl, '#26302a'), 1.2, INK); + // crested helm-mask: pointed visor, swept crest, two thin eye slits + var hx = hw * 0.12, hy = -h * 0.93; + x.beginPath(); x.moveTo(hx - hw * 0.15, hy - 4); x.quadraticCurveTo(hx - hw * 0.7, hy - h * 0.12, hx - hw * 0.95, hy - h * 0.2); + x.quadraticCurveTo(hx - hw * 0.45, hy - h * 0.07, hx - hw * 0.05, hy - 1); x.closePath(); + ART.ink(x, ART.lit(fl, '#cfd6c6'), 1.2, INK); + x.beginPath(); x.moveTo(hx - hw * 0.28, hy - 2); x.quadraticCurveTo(hx - hw * 0.22, hy - h * 0.085, hx + hw * 0.18, hy - h * 0.075); + x.quadraticCurveTo(hx + hw * 0.5, hy - h * 0.03, hx + hw * 0.62, hy + h * 0.03); x.quadraticCurveTo(hx + hw * 0.3, hy + h * 0.06, hx - hw * 0.1, hy + h * 0.055); + x.quadraticCurveTo(hx - hw * 0.32, hy + h * 0.03, hx - hw * 0.28, hy - 2); x.closePath(); + var mg = x.createLinearGradient(0, hy - h * 0.08, 0, hy + h * 0.06); mg.addColorStop(0, '#f7f9f0'); mg.addColorStop(1, '#a9b2a0'); + ART.ink(x, ART.lit(fl, mg), 1.4, INK); + x.fillStyle = '#0c120e'; + x.beginPath(); x.moveTo(hx + hw * 0.02, hy - 1); x.lineTo(hx + hw * 0.22, hy - 2.5); x.lineTo(hx + hw * 0.2, hy + 0.5); x.closePath(); x.fill(); + x.beginPath(); x.moveTo(hx + hw * 0.3, hy - 2.6); x.lineTo(hx + hw * 0.46, hy - 2.5); x.lineTo(hx + hw * 0.42, hy + 0.2); x.closePath(); x.fill(); + if (!fl) ART.glow(x, hx + hw * 0.3, hy - 1, 7 + 6 * tk, SIS_RGB[i], 0.35 + 0.3 * tk); + // arm + lance (while dashing, the lance is drawn along its hit box below instead) + var sh = [hw * 0.15, -h * 0.78]; + if (s.st !== 'dash' && !/^dash_(arrive|antic)$/.test(s.st)) { + x.save(); x.translate(sh[0], sh[1]); x.rotate(p.lance); + x.strokeStyle = dark; x.lineWidth = 3.5; x.beginPath(); x.moveTo(0, 0); x.lineTo(14, 0); x.stroke(); + x.translate(10, 0); x.rotate(0); + x.beginPath(); x.moveTo(-1.6 * V.S, -1.6); x.lineTo(1.6 * V.S, -1.8); x.lineTo(1.6 * V.S + 12, 0); x.lineTo(1.6 * V.S, 1.8); x.lineTo(-1.6 * V.S, 1.6); x.closePath(); + ART.ink(x, ART.lit(fl, '#e8eadf'), 1.1, INK); + x.restore(); + } + x.restore(); + if (/^dash/.test(s.st) && s.st !== 'dash_leave' && s.st !== 'dash_recover') { // lance along its hit box: thin while aiming, bright while it hurts + var L = SIS_LANCE(w), SXs = BB.ARENA.W / 26, ly = V.sy(s.y + L[2]), hot = s.st === 'dash'; + var x0 = V.sx(s.x - f * 0.2), x1 = V.sx(s.x + f * L[1] * SXs), th = hot ? Math.max(4, L[3] * V.S * 0.5) : 3; + if (hot) { + x.save(); x.globalCompositeOperation = 'lighter'; + var lg = x.createLinearGradient(x0 - f * 60, 0, x1, 0); lg.addColorStop(0, ART.rgba(SIS_RGB[i], 0)); lg.addColorStop(1, ART.rgba(SIS_RGB[i], 0.5)); + x.fillStyle = lg; x.fillRect(Math.min(x0 - f * 60, x1), ly - L[3] * V.S / 2, Math.abs(x1 - x0 + f * 60), L[3] * V.S); + x.restore(); + } + x.beginPath(); x.moveTo(x0, ly - th / 2); x.lineTo(x1 - f * 12, ly - th / 2); x.lineTo(x1, ly); x.lineTo(x1 - f * 12, ly + th / 2); x.lineTo(x0, ly + th / 2); x.closePath(); + ART.ink(x, hot ? '#ffffff' : 'rgba(232,234,223,0.85)', 1.2, INK); + if (hot) ART.glow(x, x1, ly, 16, '255,255,255', 0.6); + else { x.save(); x.setLineDash([4, 6]); x.strokeStyle = ART.rgba(TELE, 0.5); x.lineWidth = 1; x.beginPath(); x.moveTo(x1, ly); x.lineTo(x1 + f * 120, ly); x.stroke(); x.restore(); } + } + } + D['2d/sickle_sisters'] = { + bar: function (w) { return w.phase >= 3 ? '#c8a0e0' : '#a8d0a0'; }, + hazards: function (x, c, t, V) { + var w = c.boss; + w.hazards().forEach(function (h) { + if (h.kind !== 'blade') return; + var b = h.box, X = V.sx(b.x), Y = V.sy(b.y), R = b.w / 2 * V.S; + ART.glow(x, X, Y, R * 1.8, '220,240,220', 0.35); + var sp = t * 16 + b.x; + x.save(); x.translate(X, Y); x.scale(1, Math.max(0.6, b.h / b.w)); + x.save(); x.globalCompositeOperation = 'lighter'; // spin blur: faint trailing arcs behind each tip + for (var k = 0; k < 2; k++) { + var a = sp + k * Math.PI; + x.strokeStyle = 'rgba(220,245,215,0.28)'; x.lineWidth = R * 0.22; x.beginPath(); x.arc(0, 0, R * 0.86, a - 1.5, a); x.stroke(); + x.strokeStyle = 'rgba(255,255,250,0.5)'; x.lineWidth = 1.5; x.beginPath(); x.arc(0, 0, R * 0.97, a - 0.9, a); x.stroke(); + } + x.restore(); + x.rotate(sp); + // twin-bladed sickle: two thin crescents around a small hub + for (k = 0; k < 2; k++) { + x.save(); x.rotate(k * Math.PI); + x.beginPath(); x.arc(0, 0, R, -0.3, 1.8); x.quadraticCurveTo(R * 0.85 * Math.cos(0.75), R * 0.85 * Math.sin(0.75), R * Math.cos(-0.3), R * Math.sin(-0.3)); x.closePath(); + var gr = x.createLinearGradient(0, 0, R, R * 0.6); gr.addColorStop(0, '#8ea889'); gr.addColorStop(1, '#f6fbf0'); + ART.ink(x, gr, 1.4, INK); + x.restore(); + } + x.beginPath(); x.arc(0, 0, R * 0.16, 0, TAU); ART.ink(x, '#3a4436', 1.2, INK); + x.restore(); + }); + }, + body: function (x, c, t, V) { + var w = c.boss; + w.sis.forEach(function (s, i) { if (s.on || s.st === 'dying') sister(x, s, i, V, t, w); }); + } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/draw/wanderer.js b/environments/games/web/games/hollowknight_remake/draw/wanderer.js new file mode 100644 index 0000000000000000000000000000000000000000..61de1da8ff09eb81dc1e38525ffc34cc36b89fe5 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/draw/wanderer.js @@ -0,0 +1,295 @@ +// Body drawing for the Wanderer: BB.BODY_DRAW.wanderer = {draw(x, c, t, V, juice), hud(x, c, V)} (see engine/renderer.js). +(function (g) { + var BB = g.BB, ART = BB.ART, V = BB.VIEW, TAU = Math.PI * 2; + var S = V.S, OX = V.OX, FLOOR = V.FLOOR, PAL = V.PAL, sx = V.sx, sy = V.sy; + + // ---------- the wanderer ---------- + // Small hooded traveller: dark cloak, pale beaked mask with one lit eye, trailing scarf, slim nail. + // Animation is derived from body state only: run phase from the distance walked, squash/stretch from vy, + // swing from atkAge, dash ghosts from the dash's elapsed time. + var K = BB.WANDERER; + function heroFigure(x, b, t, o) { + // o: {run, air, vy, sq, lean, swing, ghost, flash}; origin = feet centre, facing +x + var ink = o.ghost ? null : PAL.ink, ph = o.run, air = o.air; + var bob = air ? 0 : Math.abs(Math.sin(ph)) * -1.6 * o.runAmt; + x.save(); x.translate(0, bob); x.rotate(o.lean); x.scale(1 / o.sq, o.sq); + // scarf (behind body): two strands trailing against motion + if (!o.ghost) { + var trail = ART.c01(Math.abs(b.vx) / K.RUN), lift = ART.c01(-b.vy / 14) - ART.c01(b.vy / 16) * 0.5; + for (var s = 0; s < 2; s++) { + var pts = [], L = 13 + 5 * trail + s * 4; + for (var i = 0; i <= 6; i++) { + var k = i / 6, wv = Math.sin(t * 9 + i * 1.1 + s * 1.7) * (1.2 + 2.4 * trail) * k; + pts.push([-3 - k * L * (0.45 + 0.55 * trail), -24 + s * 2 + k * (6 - 9 * trail - 8 * lift) + wv]); + } + x.beginPath(); ART.ribbon(x, pts, 4.2 - s, 1.2); + x.fillStyle = s ? '#3f8f99' : PAL.scarf; x.fill(); + } + } + // legs + var lg = function (side) { + var a = air ? (side ? 0.5 : -0.2) + (o.vy < 0 ? 0.25 : -0.15) : Math.sin(ph + side * Math.PI) * 0.75 * o.runAmt; + var hx = side ? 2.2 : -2.2, kx = hx + Math.sin(a) * 4, ky = -6 + (air ? -1.5 : 0) + Math.cos(a) * 1; + var fx = kx + Math.sin(a * 0.6) * 3, fy = air ? -1.5 : Math.min(0, -Math.max(0, Math.sin(ph + side * Math.PI)) * 2.5 * o.runAmt); + x.beginPath(); x.moveTo(hx, -9); x.quadraticCurveTo(kx, ky, fx, fy); + x.lineWidth = 3.2; x.lineCap = 'round'; x.strokeStyle = o.ghost || '#0c1020'; x.stroke(); + x.beginPath(); x.ellipse(fx + 1.2, fy - 0.6, 2.4, 1.3, 0, 0, TAU); x.fillStyle = o.ghost || '#0c1020'; x.fill(); + }; + lg(1); + // cloak: bell from shoulders to a tattered hem that trails behind with speed + var sw = Math.sin(t * 3.1) * 0.8 + (air ? (o.vy > 0 ? 3 : -3) : 0), back = -9.5 - 3.5 * o.runAmt - (air ? 1.5 : 0), front = 7.5; + x.beginPath(); x.moveTo(-3.5, -25); + x.bezierCurveTo(-8, -20, back + sw * 0.4, -12, back + sw, -6); + ART.hem(x, back + sw, front + sw * 0.3, -6 + (air && o.vy < 0 ? -1 : 0), 5, 3.2, 0.7, t * 6 + b.x, 3); + x.bezierCurveTo(front, -12, 6, -21, 3.5, -25); x.closePath(); + x.fillStyle = o.ghost || PAL.heroCloak; x.fill(); + if (ink) { x.lineWidth = 1.4; x.strokeStyle = ink; x.stroke(); } + if (!o.ghost) { // rim light along the back and a fold + x.beginPath(); x.moveTo(-4, -24); x.bezierCurveTo(-8.5, -19, back + sw * 0.4 + 1, -12, back + sw + 1, -7); + x.lineWidth = 1; x.strokeStyle = PAL.heroRim; x.stroke(); + x.beginPath(); x.moveTo(1, -21); x.quadraticCurveTo(0, -13, 1.5 + sw * 0.3, -6); x.strokeStyle = 'rgba(0,0,0,0.45)'; x.stroke(); + } + lg(0); + // hood + mask + x.save(); x.translate(1.5, -30); x.rotate(o.head || 0); + x.beginPath(); // hood with a long drooping tip + x.moveTo(7, -3); x.bezierCurveTo(8, -12, -4, -15, -8, -9); + var tip = Math.sin(t * 2.3) * 1.5 + (air ? (o.vy > 0 ? 4 : -3) : 0) + 2 * o.runAmt; + x.quadraticCurveTo(-14, -9 + tip * 0.3, -18 - o.runAmt * 2, -2 + tip); + x.quadraticCurveTo(-11, -3, -8, 2); x.bezierCurveTo(-7, 8, 4, 9, 7, 4); x.closePath(); + x.fillStyle = o.ghost || PAL.hero; x.fill(); + if (ink) { x.lineWidth = 1.4; x.strokeStyle = ink; x.stroke(); x.beginPath(); x.moveTo(-8, -9); x.quadraticCurveTo(-14, -9 + tip * 0.3, -18 - o.runAmt * 2, -2 + tip); x.lineWidth = 1; x.strokeStyle = PAL.heroRim; x.stroke(); } + if (!o.ghost) { + x.beginPath(); // pale beaked mask in the hood opening + x.moveTo(-1.5, -6); x.bezierCurveTo(4, -8, 7, -5, 7.5, -2); x.lineTo(12.5, 1.2); x.lineTo(7, 2.6); + x.bezierCurveTo(5.5, 6, 0, 6.5, -1.5, 3.5); x.quadraticCurveTo(-3, -1, -1.5, -6); x.closePath(); + var mg = x.createLinearGradient(0, -7, 0, 6); mg.addColorStop(0, '#fbf6ea'); mg.addColorStop(1, '#bdb4a0'); + x.fillStyle = ART.lit(o.flash, mg); x.fill(); x.lineWidth = 1.1; x.strokeStyle = ink; x.stroke(); + x.beginPath(); x.moveTo(1, -4.5); x.quadraticCurveTo(0.2, -1, 1.2, 2.5); x.strokeStyle = 'rgba(90,80,64,0.55)'; x.lineWidth = 0.8; x.stroke(); + x.beginPath(); x.ellipse(4.2, -1.6, 1.7, 2.4, 0.15, 0, TAU); x.fillStyle = '#0a0d14'; x.fill(); + ART.glow(x, 4.4, -1.6, 7, '127,243,255', 0.5); + x.beginPath(); x.arc(4.6, -1.8, 0.9, 0, TAU); x.fillStyle = PAL.heroEye; x.fill(); + } + x.restore(); + x.restore(); + } + // nail drawn in local (facing +x) space: grip at (gx, gy), angle a (0 = forward, -pi/2 = up) + function nailAt(x, gx, gy, a, len) { + x.save(); x.translate(gx, gy); x.rotate(a); + x.beginPath(); x.moveTo(-3, -1); x.lineTo(2, -1); x.lineTo(2, 1); x.lineTo(-3, 1); x.closePath(); x.fillStyle = '#3a3226'; x.fill(); + x.fillStyle = '#8e8676'; x.fillRect(2, -3, 1.8, 6); + x.beginPath(); x.moveTo(3.8, -1.4); x.lineTo(len - 3, -1.1); x.lineTo(len, 0); x.lineTo(len - 3, 1.1); x.lineTo(3.8, 1.4); x.closePath(); + x.fillStyle = PAL.nail; x.fill(); x.lineWidth = 0.8; x.strokeStyle = PAL.ink; x.stroke(); + x.fillStyle = 'rgba(255,255,255,0.8)'; x.fillRect(5, -1.1, len - 9, 0.7); + x.restore(); + } + + var SWING = { side: [-1.35, 1.0], alt: [1.0, -1.35], up: [0.2, -2.7], down: [-0.2, 2.9] }; + function slashFx(x, b, k) { + // the swing is drawn inside the hit polygon itself (what you see is what hits): crescent edge along the far + // boundary, revealed by an angular wipe that follows the nail + var P = b.slashPolys(b.slashShape || 'side', b.slashFacing).pts, px = sx(b.x), py = sy(b.y + K.PIVOT); + var n = P.length, cx = 0, cy = 0, R = 0, i; + for (i = 0; i < n; i++) { cx += sx(P[i][0]) / n; cy += sy(P[i][1]) / n; } + var a0 = Math.atan2(cy - py, cx - px), lo = 0, hi = 0; + for (i = 0; i < n; i++) { + var dx = sx(P[i][0]) - px, dy = sy(P[i][1]) - py, d = Math.atan2(dy, dx) - a0; + while (d > Math.PI) d -= TAU; while (d < -Math.PI) d += TAU; + lo = Math.min(lo, d); hi = Math.max(hi, d); R = Math.max(R, Math.sqrt(dx * dx + dy * dy)); + } + // wipe direction follows the nail: side = top->bottom, alt = bottom->top, up / down = front->back + var shp = b.slashShape || 'side', rev = (shp === 'side' || shp === 'down') ? b.slashFacing < 0 : b.slashFacing > 0; + var wipe = ART.easeOut(k / 0.55), fade = 1 - ART.easeIn((k - 0.45) / 0.55); + var s0 = rev ? hi + 0.3 : lo - 0.3, s1 = rev ? hi + 0.3 - (hi - lo + 0.6) * wipe : lo - 0.3 + (hi - lo + 0.6) * wipe; + x.save(); + x.beginPath(); x.moveTo(px, py); x.arc(px, py, R + 30, a0 + Math.min(s0, s1), a0 + Math.max(s0, s1)); x.closePath(); x.clip(); + var m = function (j) { var p = P[j % n], q = P[(j + 1) % n]; return [sx((p[0] + q[0]) / 2), sy((p[1] + q[1]) / 2)]; }; + x.beginPath(); var m0 = m(0); x.moveTo(m0[0], m0[1]); + for (i = 1; i <= n; i++) { var v = P[i % n], mm = m(i); x.quadraticCurveTo(sx(v[0]), sy(v[1]), mm[0], mm[1]); } + x.closePath(); + var gr = x.createRadialGradient(px, py, R * 0.15, px, py, R); + gr.addColorStop(0, 'rgba(220,250,255,0)'); gr.addColorStop(0.5, 'rgba(220,250,255,' + (0.06 * fade).toFixed(3) + ')'); + gr.addColorStop(0.8, 'rgba(235,252,255,' + (0.42 * fade).toFixed(3) + ')'); gr.addColorStop(1, 'rgba(255,255,255,' + (0.95 * fade).toFixed(3) + ')'); + x.fillStyle = gr; x.fill(); + // cutting edge: only the far boundary, as a tapered bright stroke (no outline on the near side) + var far = []; + for (i = 0; i <= n * 4; i++) { + var j0 = Math.floor(i / 4) % n, j1 = (j0 + 1) % n, u = (i % 4) / 4; + var ex = sx(ART.mix(P[j0][0], P[j1][0], u)), ey = sy(ART.mix(P[j0][1], P[j1][1], u)); + var dd = Math.sqrt((ex - px) * (ex - px) + (ey - py) * (ey - py)); + far.push(dd > R * 0.78 ? [ex, ey, (dd - R * 0.78) / (R * 0.22)] : null); + } + x.globalCompositeOperation = 'lighter'; x.lineCap = 'round'; + for (i = 0; i + 1 < far.length; i++) { + var e0 = far[i], e1 = far[i + 1]; if (!e0 || !e1) continue; + var kk = Math.min(e0[2], e1[2]); + x.strokeStyle = 'rgba(200,240,255,' + (0.35 * fade * kk).toFixed(3) + ')'; x.lineWidth = 7 * kk + 1; + x.beginPath(); x.moveTo(e0[0], e0[1]); x.lineTo(e1[0], e1[1]); x.stroke(); + x.strokeStyle = 'rgba(255,255,255,' + (0.95 * fade * kk).toFixed(3) + ')'; x.lineWidth = 2.6 * kk + 0.4; + x.beginPath(); x.moveTo(e0[0], e0[1]); x.lineTo(e1[0], e1[1]); x.stroke(); + } + x.restore(); + // leading-edge glint at the nail tip + if (wipe < 1) { + var ae = a0 + s1, gx = px + Math.cos(ae) * R * 0.9, gy = py + Math.sin(ae) * R * 0.9; + ART.glow(x, gx, gy, 16, '220,250,255', 0.6 * fade); + } + } + + function wanderer(x, c, t, juice) { + var b = c.body, X = sx(b.x), Y = sy(b.y), f = b.facing, st = ART.store; + // presentation memory (landing squash, run phase), reset by ART.begin on a new case / rewind + var mem = st.p.hero || (st.p.hero = { ground: b.grounded, landT: -9, ph: 0 }); + if (b.grounded && !mem.ground) mem.landT = t; + mem.ground = b.grounded; + var dashing = b.dashT > 0, running = b.grounded && Math.abs(b.vx) > 0.5 && !dashing && b.hurtT <= 0; + mem.ph += ART.dt() * (running ? 2.6 * Math.abs(b.vx) : 0); + var sm = ART.smooth('heroPose', { + run: running ? 1 : 0, + lean: dashing ? 0.32 : b.hurtT > 0 ? -0.35 : running ? 0.12 : b.grounded ? 0 : ART.c01(-b.vy / 20) * 0.1, + sq: dashing ? 0.8 : !b.grounded ? (b.vy > 0 ? 1 + 0.12 * ART.c01(b.vy / 14) : 1 + 0.07 * ART.c01(-b.vy / 18)) : 1, + head: b.grounded ? 0 : -ART.c01(b.vy / 16) * 0.12 + ART.c01(-b.vy / 18) * 0.12 + }, 26); + var land = t - mem.landT, sq = sm.sq * (land < 0.14 ? 1 - 0.2 * Math.sin(land / 0.14 * Math.PI) : 1); + ART.shade(x, X, FLOOR + 1, 13 * (1 - ART.c01(b.y / 8) * 0.5), 3, 0.5 * (1 - ART.c01(b.y / 10) * 0.7)); + // dash afterimages + speed streaks + if (dashing) { + var el = K.DASH_T - b.dashT; + for (var gI = 3; gI >= 1; gI--) { + var back = Math.min(el, 0.03 * gI) * K.DASH_V * S; + x.save(); x.translate(X - b.dashDir * back, Y); x.scale(b.dashDir, 1); x.globalAlpha = 0.16 * (4 - gI); + heroFigure(x, b, t, { run: 0, runAmt: 0, air: true, vy: 0, sq: 0.8, lean: 0.32, ghost: 'rgb(120,190,240)' }); + x.restore(); + } + x.save(); x.globalCompositeOperation = 'lighter'; + for (var l = 0; l < 5; l++) { + var ly = Y - 6 - l * 7 - 4 * ART.hash(l + Math.floor(t * 30)), ll = 30 + 40 * ART.hash(l * 7 + Math.floor(t * 30)); + x.strokeStyle = 'rgba(170,220,255,' + (0.35 * b.dashT / K.DASH_T).toFixed(3) + ')'; x.lineWidth = 1.2; + x.beginPath(); x.moveTo(X - b.dashDir * 10, ly); x.lineTo(X - b.dashDir * (10 + ll), ly); x.stroke(); + } + x.restore(); + } + // focus: soul drawn inward + if (b.focusT >= 0) { + var fk = ART.c01(b.focusT / 0.25) * 0.5 + 0.5 * ART.c01((t * 3) % 1); + ART.glow(x, X, Y - 20, 46, '170,235,255', 0.35 + 0.15 * Math.sin(t * 14)); + x.save(); x.globalCompositeOperation = 'lighter'; + for (var q = 0; q < 10; q++) { + var qa = q * 0.628 + t * 1.3, qr = 42 * (1 - ((t * 1.6 + q * 0.37) % 1)); + x.fillStyle = 'rgba(200,245,255,' + (0.7 * (1 - qr / 42)).toFixed(3) + ')'; + x.beginPath(); x.arc(X + Math.cos(qa) * qr, Y - 20 + Math.sin(qa) * qr * 0.8, 1.6, 0, TAU); x.fill(); + } + x.restore(); void fk; + } + var blink = b.invul > 0 && b.hurtT <= 0 && Math.floor(t * 20) % 2 === 0; + x.save(); x.translate(X, Y); x.scale(f, 1); + if (blink) x.globalAlpha = 0.4; + var o = { run: mem.ph, runAmt: sm.run, air: !b.grounded && !dashing, vy: b.vy, sq: sq, lean: sm.lean, head: sm.head, flash: b.hurtT > 0 }; + // nail: hangs at the back at rest; follows the swing during an attack + var swingK = b.atkT > 0 ? ART.c01(b.atkAge / 0.1) : -1, shp = b.slashShape || 'side', na, ng; + if (swingK >= 0) { + var sw = SWING[shp], e = ART.easeOut(swingK); + na = sw[0] + (sw[1] - sw[0]) * e; ng = shp === 'down' ? [2, -16] : shp === 'up' ? [2, -24] : [4, -18]; + if (swingK >= 1) na = sw[1] + Math.sin(ART.c01((b.atkAge - 0.1) / 0.2) * Math.PI) * 0.15; + } + if (swingK < 0) nailAt(x, -4, -16, 2.05 + Math.sin(t * 2) * 0.04 + sm.run * 0.25, 19); + heroFigure(x, b, t, o); + if (swingK >= 0) { + nailAt(x, ng[0], ng[1], na, 20); + x.beginPath(); x.arc(ng[0], ng[1], 2.6, 0, TAU); x.fillStyle = PAL.hero; x.fill(); // hand + } + x.restore(); + if (b.atkT > 0 && b.atkAge < 0.16 && b.slashPolys) slashFx(x, b, b.atkAge / 0.16); + void juice; + } + + // ---------- HUD: bone masks, soul vessel, framed boss bar ---------- + function maskPath(x, mx, my, s) { + x.beginPath(); x.moveTo(mx - 8 * s, my - 6 * s); + x.bezierCurveTo(mx - 9 * s, my - 15 * s, mx - 3 * s, my - 13 * s, mx - 2 * s, my - 18 * s); // left horn + x.quadraticCurveTo(mx, my - 12 * s, mx + 2 * s, my - 18 * s); + x.bezierCurveTo(mx + 3 * s, my - 13 * s, mx + 9 * s, my - 15 * s, mx + 8 * s, my - 6 * s); + x.bezierCurveTo(mx + 8 * s, my + 4 * s, mx + 4 * s, my + 10 * s, mx, my + 11 * s); + x.bezierCurveTo(mx - 4 * s, my + 10 * s, mx - 8 * s, my + 4 * s, mx - 8 * s, my - 6 * s); x.closePath(); + } + function hud(x, c) { + var b = c.body, i, t = c.t / BB.FPS; + var vx = OX + 30, vy = 34, fr = b.soul / K.SOUL_MAX, full = b.soul >= K.FOCUS_COST; + // soul vessel: dark orb with liquid soul, a meniscus wave and a rim + var rg = x.createRadialGradient(vx - 4, vy - 5, 2, vx, vy, 20); rg.addColorStop(0, '#22303c'); rg.addColorStop(1, '#070b10'); + x.fillStyle = rg; x.beginPath(); x.arc(vx, vy, 19, 0, TAU); x.fill(); + x.save(); x.beginPath(); x.arc(vx, vy, 16.5, 0, TAU); x.clip(); + var lv = vy + 16.5 - 33 * fr; + var lg = x.createLinearGradient(0, lv, 0, vy + 17); lg.addColorStop(0, full ? '#f4fdff' : '#9fc6d4'); lg.addColorStop(1, full ? '#6fc4dc' : '#3d6474'); + x.fillStyle = lg; x.beginPath(); x.moveTo(vx - 18, vy + 18); + for (i = 0; i <= 12; i++) x.lineTo(vx - 18 + i * 3, lv + Math.sin(t * 3 + i * 0.9) * 1.4 * (fr > 0.02 && fr < 0.98 ? 1 : 0)); + x.lineTo(vx + 18, vy + 18); x.closePath(); x.fill(); + x.restore(); + if (full) ART.glow(x, vx, vy, 30, '190,240,255', 0.25 + 0.08 * Math.sin(t * 4)); + x.lineWidth = 3; x.strokeStyle = '#d9dfe2'; x.beginPath(); x.arc(vx, vy, 18, 0, TAU); x.stroke(); + x.lineWidth = 1; x.strokeStyle = PAL.ink; x.beginPath(); x.arc(vx, vy, 20, 0, TAU); x.stroke(); + x.fillStyle = 'rgba(255,255,255,0.35)'; x.beginPath(); x.ellipse(vx - 6, vy - 8, 5, 2.5, -0.6, 0, TAU); x.fill(); + // health masks, with a crack on lost ones and a glint on the newest full one + for (i = 0; i < b.max_hp; i++) { + var mx = vx + 36 + i * 22, my = 32, on = i < b.hp; + maskPath(x, mx, my, 0.85); + if (on) { + var mg = x.createLinearGradient(mx, my - 15, mx, my + 10); mg.addColorStop(0, '#ffffff'); mg.addColorStop(1, '#c9d2d6'); + x.fillStyle = mg; x.fill(); x.lineWidth = 1.5; x.strokeStyle = PAL.ink; x.stroke(); + x.fillStyle = PAL.ink; + x.beginPath(); x.ellipse(mx - 3.2, my - 1, 1.9, 3.2, 0.2, 0, TAU); x.fill(); + x.beginPath(); x.ellipse(mx + 3.2, my - 1, 1.9, 3.2, -0.2, 0, TAU); x.fill(); + } else { + x.fillStyle = 'rgba(20,28,34,0.7)'; x.fill(); x.lineWidth = 1.2; x.strokeStyle = 'rgba(200,215,220,0.35)'; x.stroke(); + x.beginPath(); x.moveTo(mx - 1, my - 12); x.lineTo(mx + 1.5, my - 4); x.lineTo(mx - 1.5, my + 1); x.lineTo(mx + 1, my + 7); x.stroke(); + } + } + // soul count inside the vessel, boss phase / stage line under the engine's boss bar (read-only) + x.font = '700 10px Georgia, "Times New Roman", serif'; x.textAlign = 'center'; + x.lineWidth = 2.5; x.strokeStyle = 'rgba(6,10,14,0.75)'; x.strokeText(String(b.soul), vx, vy + 4); + x.fillStyle = full ? '#ffffff' : 'rgba(205,224,232,0.9)'; x.fillText(String(b.soul), vx, vy + 4); + var ph = phaseLine(c); + if (ph) { + x.font = '600 10px Georgia, "Times New Roman", serif'; x.textAlign = 'right'; + var rx = BB.VIEW.W - OX - 14, ry = 64; + x.fillStyle = 'rgba(0,0,0,0.6)'; x.fillText(ph.text, rx + 1, ry + 1); + x.fillStyle = ph.hot ? '#ffcf8a' : 'rgba(225,232,236,0.82)'; x.fillText(ph.text, rx, ry); + } + // native tick rate + public tier under the engine's "d=.. mm:ss" line + x.font = '600 11px "Segoe UI", sans-serif'; x.textAlign = 'left'; + var tl = BB.FPS + ' Hz · ' + tierName(c.d); + x.fillStyle = 'rgba(0,0,0,0.55)'; x.fillText(tl, OX + 13, 89); + x.fillStyle = 'rgba(214,233,238,0.78)'; x.fillText(tl, OX + 12, 88); + x.textAlign = 'left'; + } + // the public tier this difficulty came from (BB.GAME.tiers), or the raw d for a custom continuous value + function tierName(d) { + var T = BB.GAME && BB.GAME.tiers; + if (T) for (var k in T) if (Math.abs(T[k] - d) < 1e-9) return k.toUpperCase(); + return 'CUSTOM d ' + d.toFixed(2); + } + // "PHASE n / N" plus a stagger / exposure marker, per source fight structure + function phaseLine(c) { + var w = c.boss, st = String(w.st || ''), stun = /^stun|^stunned/.test(st), hs = String.fromCharCode(8202); + function sp(s) { return s.split('').join(hs); } + if (w.st === 'dead') return null; + if (c.id === '2d/needle_warden') return { text: sp('PHASE ' + (w.escalated ? 2 : 1) + ' / 2' + (stun ? ' · STAGGERED' : '')), hot: stun }; + if (c.id === '2d/iron_bulwark') { + var open = w.headOpen && w.headOpen(), down = stun || /final_down/.test(st); + if (w.final) return { text: sp('FINAL STAGE' + (open ? ' · CORE EXPOSED' : '')), hot: open || down }; + var N = w.stages || 3; + return { text: sp('ARMOUR ' + Math.min(N, (w.heads || 0) + 1) + ' / ' + N + (open ? ' · CORE EXPOSED' : down ? ' · STAGGERED' : '')), hot: open || down }; + } + if (c.id === '2d/hollow_vessel') return { text: sp('PHASE ' + Math.min(4, (w.tokens || 0) + 1) + ' / 4' + (stun ? ' · STAGGERED' : '')), hot: stun }; + if (c.id === '2d/sickle_sisters') { + var s0 = w.sis && w.sis[0], left = w.sis ? w.sis.filter(function (s, i) { return i > 0 && s.hp > 0; }).length : 0; + return { text: sp(s0 && s0.hp > 0 ? 'PHASE 1 / 2' : 'PHASE 2 / 2 · ' + (left > 1 ? 'TWO LEFT' : 'LAST ONE')), hot: false }; + } + if (c.id === '2d/pale_vessel') return { text: sp('PHASE ' + w.phase + ' / 4' + (stun ? ' · STAGGERED' : '')), hot: stun }; + if (c.id === '2d/lumen_moth') return { text: sp('PHASE ' + w.phase + ' / 5' + (st === 'stagger' ? ' · STAGGERED' : st === 'exposed' ? ' · STRIKE NOW' : w.abyss ? ' · ABYSS' : '')), hot: st === 'stagger' || st === 'exposed' }; + return null; + } + + BB.BODY_DRAW = BB.BODY_DRAW || {}; + BB.BODY_DRAW.wanderer = { draw: function (x, c, t, V, J) { wanderer(x, c, t, J); }, hud: hud }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/game.js b/environments/games/web/games/hollowknight_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..f2dd13e2208ae258a4de9292d10eeb814a6e61c5 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/game.js @@ -0,0 +1,90 @@ +// Manifest of this game for the engine shell (engine/app.js): select-screen roster and default case. +// A roster entry is playable once some script registered its id in BB.CASES; the rest show as LOCKED placeholders. +(function (g) { + var BB = g.BB; + BB.GAME = { + id: 'hollowknight_remake', + title: 'Hollow Knight Remake', + // Recordings use this rule version. + rules: 'hk-arena-20261103-r5', + // Boss values interpolate between their easy, normal, and hard configuration anchors. + tiers: { easy: 0, normal: 0.5, hard: 1 }, + // clock: the source runs physics at 50 Hz, the engine at 60 Hz; every conversion goes through clock.js + clock: { engine_hz: 60, source_hz: 50, rule: 'seconds unchanged; n source steps = n x 0.02 s; x f per source step = f^(5/6) per tick' }, + defaultCase: '2d/needle_warden', + roster: [ + { id: '2d/needle_warden', name: 'Green-Robed Lancer', arch: 'Agile spear duelist: ground thrust, aimed aerial thrust, spear throw and recall, spinning area attack, and backward dodge' }, + { id: '2d/iron_bulwark', name: 'Iron-Bell Mace Soldier', arch: 'Armored mace fighter: leap slam, shockwave strike, exposed body when knocked down, and a barrage of falling barrels' }, + { id: '2d/sickle_sisters', name: 'Triple Lancers', arch: 'Three alternating lancers: wall dashes, plunging stabs, and spinning blades; two attack together in phase two' }, + { id: '2d/hollow_vessel', name: 'Orange-Ooze Berserker', arch: 'Frenzied swordsman: long dash, jumping slash, splashing ground stab, reactions to hits, and orange projectile rain' }, + { id: '2d/pale_vessel', name: 'Split-Chest Swordsman', arch: 'Four-phase swordsman: triple slash, parry and counter, ground stab with fire pillars, chest barrage, and self-stab' }, + { id: '2d/lumen_moth', name: 'Four-Winged Sword Wielder', arch: 'Four-winged hovering foe: teleportation, homing orbs, sword rings, sword rain, sword walls, beams, spikes, abyss platforms, and a final beam' } + ] + }; + // localized skill-table rows for the select screen (engine/app.js reads GAME.skillText[case][move]) + BB.GAME.skillText = { + "2d/needle_warden": { + "g_dash": "g_dash Ground thrust: crouches and draws back her needle for 0.56 s, then dashes horizontally at 25 u/s. Jump over her and strike downward during the roughly 0.33 s recovery.", + "a_dash": "a_dash Aerial thrust: leaps, pauses in midair, locks onto your feet, then dives diagonally at 30 u/s. She recovers for 0.5 s on landing; at a wall, she clings briefly before jumping away.", + "throw": "throw Spear throw: from a wall, facing inward, she charges for 0.78 s and throws her needle horizontally. The returning needle also hurts. You can pogo off it; stagger buildup pauses during the throw.", + "g_sphere": "g_sphere Ground spin: stands still and charges for 0.83 s at close range, then spins for 1 s within roughly 2.5 u. Leave the area.", + "a_sphere": "a_sphere Aerial spin: stops while descending and charges for 0.58 s, then spins in midair for 1 s.", + "evade": "evade Evade: when you get close, she crouches briefly and hops backward without dealing damage." + }, + "2d/iron_bulwark": { + "leap": "leap Leap: crouches with the mace, then jumps toward you, with half the landings randomized. Never leaps twice in a row; recovers for 0.5 s on landing.", + "bludgeon": "bludgeon Leaping slam: locks onto your position on takeoff and strikes in front on landing. Recovers for 0.25 s; later phases also drop barrels.", + "smash": "smash Smash: hops back, then slams the mace into the floor, sending a shockwave across the arena. Jump over it. Barrels also fall from phase two onward.", + "charge": "charge Charge: rushes toward you when you are far away, then follows with a leaping slam at close range.", + "rage": "rage Rage: after the exposed body takes a full layer of damage, it retreats and jumps around the center, repeatedly slamming left and right for about 3 s. Each slam drops a barrel.", + "barrel": "barrel Falling barrel: a warning appears overhead before it lands. Later phases drop more barrels." + }, + "2d/hollow_vessel": { + "dash": "dash Ground dash: steps back and charges the blade for 0.82 s, then crosses most of the room at 32 u/s. Recovers for 0.25 s.", + "air_dash": "air_dash Air dash: leaps, hovers, draws back the blade, then dashes horizontally at head height and falls.", + "jump": "jump Jump: crouches, then leaps toward a random spot in the room.", + "downstab": "downstab Downward stab: hovers above your head for 0.5 s, dives straight down, and splashes four orange blobs on landing. You can counter after about 0.9 s.", + "overhead": "overhead Overhead flurry: when you are above it, it has a 25% chance to swing its blade overhead for 1.3 s.", + "evade": "evade Evade: when you get close, it has a 45% chance to hop back, often followed by another attack.", + "cascade": "cascade Cascade: at HP 370, 220, and 110, it jumps to the center and shakes its head while orange blobs spray from both walls and the ceiling for 4 s.", + "balloon": "balloon Orange balloon: below 420 HP, one appears every 4–5 s, up to three at once. It follows you and breaks with one hit." + }, + "2d/sickle_sisters": { + "dash": "dash Spear dash: appears at one end of the floor, pulls back her spear, and dashes across the arena. Jump over her; she recovers for 0.63 s at the other end.", + "dstab": "dstab Plunging stab: appears above your head with spear pointed down, then drops straight down. Dodge and punish her 0.67 s landing recovery.", + "throw": "throw Spinning blade throw: clings high to a wall for a sinking blade, or low for a rising blade, then charges and throws it. She stays on the wall for about 1.2 s.", + "blade": "blade Spinning blade: flies across the room, slows, and returns to the thrower.", + "high_throw": "high_throw Wall punishment: if you cling to a wall, she appears at your height on the opposite wall and throws a blade.", + "duo": "duo Duo phase: after the first sister falls, the other two attack together with a dash and plunge, dashes from both ends, or blades thrown from opposite walls." + }, + "2d/pale_vessel": { + "slash": "slash Triple slash: shoulders the blade and advances with three wide swings. The second and third also hit behind. She recovers for 0.33 s after the third.", + "dash": "dash Dash: crouches with the blade, thrusts along the floor, then skids to a stop for 0.45 s.", + "counter": "counter Parry and counter: when her raised blade glows, a frontal slash is blocked and answered with an immediate sliding counter. She lowers her guard after 0.75 s.", + "evade": "evade Evade: hops backward when you get close, often followed by an attack.", + "jump": "jump Jump: crouches and leaps across the room, recovering for 0.33 s on landing.", + "tele": "tele Teleport: disappears, reappears far away or above you, and attacks.", + "dstab": "dstab Downward stab (phase 2+): jumps or teleports above you, hovers, then slams the floor. Fire pillars rise afterward; she stands for 1.1 s after landing.", + "plume": "plume Fire pillars: orange marks spread from the landing point. All marks then erupt together; stand between them.", + "barrage": "barrage Barrage (phase 2+): opens her cloak and fans out 9–10 orange blobs across roughly 75% of the room.", + "outbreak": "outbreak Chest burst (phase 3+): rises to the center and sprays orange blobs to both sides and downward. You can keep attacking from below.", + "puppet": "puppet Puppet slam (phase 3+): rises as if pulled by strings and follows you with 2–5 ground slams, then collapses for about 1.6 s.", + "self_stab": "self_stab Self-stab (phase 3+): stabs her own chest. Your hits deal only 1 damage during this move; afterward she collapses for 2.25 s.", + "weak_slash": "weak_slash Weak slash (phase 4): staggers closer, swings once, then kneels for 2.25 s.", + "roar": "roar Roar: stops and roars at each phase change." + }, + "2d/lumen_moth": { + "orbs": "orbs Orbs: her core flashes and up to three orbs emerge to follow you. They shatter on walls or the floor; lead them into a wall.", + "sword_burst": "sword_burst Sword ring: 12 outward-pointing swords form a ring around her and fire together. Stand between their paths; distance gives more room.", + "sword_rain": "sword_rain Sword rain: rows of swords hang from the ceiling with two wide gaps before falling. Stand under a gap. She may teleport during the attack.", + "sword_wall": "sword_wall Sword wall: a column of swords forms at one wall, leaving a gap at floor or jump height, then sweeps across. Three walls come in succession; move into each gap.", + "beam_burst": "beam_burst Beam burst: eight warning rays spread from her body before becoming beams. Three staggered waves follow; stand between the rays.", + "beam_sweep": "beam_sweep Beam sweep: light gathers at one wall, then sweeps across, fading about one-ninth of the room from the far wall. Run to the far end.", + "spikes": "spikes Spikes (phase 2+): half the floor glows before spikes rise for 5 s, dealing 1 health. In phase three, spikes move to the side edges.", + "abyss": "abyss Abyss (phase 4): after a stagger, the floor collapses into an abyss, leaving four platforms. Falling costs 1 health and returns you to the nearest platform. Sword rain stops.", + "big_beam": "big_beam Final beam (phase 5): she rises high and drops three giant beams at your feet, then descends exhausted. One hit finishes the fight.", + "teleport": "teleport Teleport: vanishes in light and reappears elsewhere, often near your head. She deals no contact damage; only her core can be hit.", + "scream": "scream Phase change: her roar changes the arena, bringing spikes, central sword rain, the abyss, or the final ascent." + } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/index.html b/environments/games/web/games/hollowknight_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..74b6a62190b43dd970190e2e5ba8c808b5711230 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/index.html @@ -0,0 +1,144 @@ + + + + + +BossBench · Hollow Knight Remake + + + + +
    +

    BOSSBENCH · HOLLOW KNIGHT REMAKE

    +

    2D scene prototype: play as the Cloaked Swordsman with melee strikes, pogo jumps, dashes, and focused healing against bosses. Fixed physics at 60 Hz (converted from the original 50 Hz in clock.js), 200 ms action packets, 480p, and Easy / Normal / Hard difficulty tiers.

    + +
    + + +
    +

    Select BOSS

    +
    +
    + Difficulty + + + + + 0.50 + seed +
    +
    +
    + + + +
    + + +
    +
    +

    Controls (Cloaked Swordsman)

    +
      +
    • A/D Move; Space Jump (hold for height, release to shorten)
    • +
    • J or left mouse button: slash. Hold W to slash upward, or hold S in midair to strike downward. Hitting a boss or a pogoable attack bounces you up and restores your air dash without resetting its cooldown.
    • +
    • Shift Dash (once per jump, 0.6 s cooldown; unavailable for 0.1 s after a slash)
    • +
    • Normal slashes alternate between two forms and reset after 0.5 s without an attack. Early button presses are buffered: jump 0.04 s, slash 0.1 s, dash 0.2 s.
    • +
    • Each hit grants 11 energy. Hold K on the ground to spend 33 energy and heal 1 health (about 1.1 s); moving, leaving the ground, or taking damage interrupts it.
    • +
    • Arrow keys and ZXCV also work.
    • +
    +
    +
    +

    Move List

    +
      +
      +
      +

      All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.

      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/environments/games/web/games/hollowknight_remake/scripted.js b/environments/games/web/games/hollowknight_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..12d04ba196ca232f5daa2b1b6e3e313de9aea9c4 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/scripted.js @@ -0,0 +1,217 @@ +// Standard scripted reference controller of this game (PROTOCOL section 3): BB.GAME.scripted(c) -> one 200 ms packet. +// Trusted harness/demo controller, never shown to a policy. It reads the live BB.Case but never writes it: every +// look-ahead runs on a deep copy whose RNG is a *different* stream (seeded from seed, tick and a salt), so the boss's +// future random choices are not foreseen - only what the current state already determines. +// Decision = model-predictive control at packet granularity: each candidate macro is turned into a fixed packet +// (6 hold sets x 2 ticks, closed loop on a sampled copy), then scored on SAMPLES sampled futures in which the same +// macro keeps running for the rest of the horizon; the worst sample counts. Deterministic: no Math.random, no clock. +// Memory across calls (WeakMap keyed by the case) only keeps the last macro name for hysteresis; reset at tick 0. +(function (g) { + var BB = g.BB; + var KEYCAP = 4, SUB = BB.SUBSTEPS, TPS = BB.TICKS_PER_SUB; // 6 hold sets, 2 ticks each (60 Hz) + var MEM = new WeakMap(); + + function clone(o) { + if (o === null || typeof o !== 'object') return o; + if (Array.isArray(o)) { var a = new Array(o.length); for (var i = 0; i < o.length; i++) a[i] = clone(o[i]); return a; } + var n = Object.create(Object.getPrototypeOf(o)), ks = Object.keys(o); + for (var j = 0; j < ks.length; j++) n[ks[j]] = clone(o[ks[j]]); + return n; + } + function fork(c, salt) { + var n = Object.create(BB.Case.prototype); + n.id = c.id; n.def = c.def; n.arena = c.arena; n.options = c.options; n.seed = c.seed; n.d = c.d; n.t = c.t; + n.trauma = 0; n.result = c.result; n.events = []; + n.body = clone(c.body); n.boss = clone(c.boss); + n.rng = new BB.RNG((Math.imul(c.seed, 2654435761) + Math.imul(c.t, 40503) + salt * 7919 + 12345) >>> 0); + return n; + } + // nearest thing the nail can damage on a copy: an exposed weak point first, then the closest part / balloon + function target(cc) { + var b = cc.body, w = cc.boss, tg = w.hitTargets ? w.hitTargets() : [{ id: 'boss', box: w.bodyBox() }], best = null; + for (var i = 0; i < tg.length; i++) { + if (!tg[i].box) continue; + if (tg[i].id === 'head') return tg[i].box; + if (!best || Math.abs(tg[i].box.x - b.x) < Math.abs(best.x - b.x)) best = tg[i].box; + } + return best; + } + function towards(dx) { return dx > 0 ? 'D' : 'A'; } + function exposed(cc) { + var w = cc.boss, tg = w.hitTargets ? w.hitTargets() : []; + for (var i = 0; i < tg.length; i++) if (tg[i].id === 'head' && tg[i].box) return true; + return false; + } + + // ---------- macros: (i = hold-set index since the decision, cc = sampled copy) -> keys held for that set ---------- + function hold(keys) { return function () { return keys; }; } + function jumpM(dir, n, dashAt) { // Space for n sets (6 = full height); edge-triggered: release first + return function (i, cc) { + var k = {}; if (dir) k[dir] = 1; + var held = cc.body.prev.jump && i === 0; + if (i < n + (held ? 1 : 0) && !held) k.Space = 1; + if (dashAt != null && i === dashAt) k.Shift = 1; + return k; + }; + } + function dashM(dir) { + return function (i, cc) { var k = {}; k[dir] = 1; if ((i === 0 && !cc.body.prev.dash) || i === 1) k.Shift = 1; return k; }; + } + function meleeM(i, cc) { // walk into reach, face the target, slash (up-slash if it is overhead) + var b = cc.body, T = target(cc), k = {}; + if (!T) return k; + var dx = T.x - b.x, gap = Math.abs(dx) - T.w / 2, to = towards(dx), away = dx > 0 ? 'A' : 'D'; + var lo = T.y - T.h / 2, hi = T.y + T.h / 2, edge = !cc.body.prev.attack; + if (gap > 2.4) k[to] = 1; else if (gap < 0.9) k[away] = 1; + if (lo > b.y + 2.3 && gap < 0.6) { k.W = 1; if (edge) k.J = 1; } + else if (gap < 2.9 && lo < b.y + 2.2 && hi > b.y - 0.3) { + if (b.facing !== Math.sign(dx)) { k[to] = 1; delete k[away]; } + if (edge) k.J = 1; + } + return k; + } + function pokeM(i, cc) { // stand still facing the target and slash on every edge + var b = cc.body, T = target(cc), k = {}; + if (!T) return k; + var dx = T.x - b.x; + if (b.facing !== Math.sign(dx) && b.atkT <= 0) k[towards(dx)] = 1; + if (!cc.body.prev.attack) k.J = 1; + if (T.y - T.h / 2 > b.y + 2.3) k.W = 1; + return k; + } + function pogoM(i, cc) { // jump over the target and down-slash it + var b = cc.body, T = target(cc), k = {}; + if (!T) return k; + var dx = T.x - b.x, top = T.y + T.h / 2; + if (Math.abs(dx) > 0.3) k[towards(dx)] = 1; + if (b.grounded) { if (!b.prev.jump) k.Space = 1; } + else if (b.y < top + 1.2 && b.vy > 0) k.Space = 1; + if (!b.grounded && Math.abs(dx) < T.w / 2 + 0.9 && b.y > top - 0.6) { k.S = 1; if (!b.prev.attack) k.J = 1; } + return k; + } + function jslashM(i, cc) { // jump to a raised target (a lord on the wall) and side-slash it mid-air + var b = cc.body, T = target(cc), k = {}; + if (!T) return k; + var dx = T.x - b.x, gap = Math.abs(dx) - T.w / 2, to = towards(dx), away = dx > 0 ? 'A' : 'D'; + var lo = T.y - T.h / 2, hi = T.y + T.h / 2; + if (gap > 1.8) k[to] = 1; else if (gap < 0.7) k[away] = 1; + if (b.grounded) { if (!b.prev.jump) k.Space = 1; } + else if (b.vy > 0 && b.y + 0.6 < lo) k.Space = 1; // keep rising until the slash band (feet .. feet + 2.5) meets the target + if (!b.grounded && gap < 2.6 && b.y + 2.2 > lo && b.y - 0.3 < hi) { + if (b.facing !== Math.sign(dx)) { k[to] = 1; delete k[away]; } + if (!b.prev.attack) k.J = 1; + } + return k; + } + function awayM(i, cc) { // back off from the boss, jumping a wall-pin + var b = cc.body, w = cc.boss, dx = w.x - b.x, k = {}; + var nearWall = b.x < 1.2 || b.x > cc.arena.W - 1.2; + k[nearWall ? towards(dx) : (dx > 0 ? 'A' : 'D')] = 1; + if (nearWall && !b.prev.jump && b.grounded) k.Space = 1; else if (nearWall && !b.grounded && b.vy > 0) k.Space = 1; + return k; + } + var MACROS = [ + ['wait', hold({})], ['L', hold({ A: 1 })], ['R', hold({ D: 1 })], ['away', awayM], + ['jump', jumpM(null, 6)], ['jumpL', jumpM('A', 6)], ['jumpR', jumpM('D', 6)], ['hopL', jumpM('A', 2)], ['hopR', jumpM('D', 2)], + ['dashL', dashM('A')], ['dashR', dashM('D')], ['jdashL', jumpM('A', 6, 3)], ['jdashR', jumpM('D', 6, 3)], + ['melee', meleeM], ['poke', pokeM], ['pogo', pogoM], ['jslash', jslashM], ['heal', hold({ K: 1 })] + ]; + + // ---------- evaluation ---------- + var H = 36, H_HEAL = 66, SAMPLES = 2; // continuation ticks after the 12-tick packet + function cap(k) { // a hold set carries at most 4 keys + var out = {}, n = 0, order = ['Space', 'Shift', 'J', 'K', 'S', 'W', 'A', 'D']; + for (var i = 0; i < order.length && n < KEYCAP; i++) if (k[order[i]]) { out[order[i]] = true; n++; } + return out; + } + function score(c, cc, hp0, bh0, lostAt) { + var b = cc.body, w = cc.boss; + if (lostAt >= 0) return -1000 * (hp0 - b.hp) + lostAt * 4 + (bh0 - w.hp); // got hit: later is better + if (cc.result === 'win') return 5000; + var s = (bh0 - w.hp) * 2.4 + (b.hp - hp0) * 300, T = target(cc); + if (b.hp < b.max_hp) s += Math.min(b.soul, 66) * 0.25; // soul is the next heal + if (T) s -= 0.35 * Math.abs(Math.abs(T.x - b.x) - T.w / 2 - 1.6); // stay near striking range + else s -= 0.05 * Math.abs(b.x - cc.arena.W / 2); + if (b.x < 1.5 || b.x > cc.arena.W - 1.5) s -= 1.5; // do not get cornered + if (w.floorDanger && w.floorDanger(b.x)) s -= 60; // a floor that hurts (spikes, abyss) past the horizon + return s; + } + // build the packet of macro m on sample 0, then score it on every sample (packet keys replayed open loop) + function evaluate(c, m, heal) { + if (c.boss.planner === 'two_step') return evaluate2(c, m, heal); + // a boss may ask for a longer look-ahead (lumen_moth: hazards announce ~1 s ahead); every other case keeps H + var hp0 = c.body.hp, bh0 = c.boss.hp, horizon = heal ? Math.max(H_HEAL, c.boss.lookahead || 0) : (c.boss.lookahead || H), worst = 1e18, packet = []; + for (var smp = 0; smp < SAMPLES; smp++) { + var cc = fork(c, smp), lostAt = -1, tick = 0, i, s, k; + for (s = 0; s < SUB + Math.ceil(horizon / TPS) && !cc.result && lostAt < 0; s++) { + if (s < SUB) { if (smp === 0) packet.push(cap(m(s, cc))); k = packet[s]; } + else k = cap(m(s, cc)); + for (i = 0; i < TPS && !cc.result; i++) { cc.tick(k); tick++; if (cc.body.hp < hp0) { lostAt = tick; break; } } + } + while (smp === 0 && packet.length < SUB) packet.push({}); + var v = score(c, cc, hp0, bh0, lostAt); + if (v < worst) worst = v; + if (worst <= -500) break; // already a hit: no need for a second future + } + return { v: worst, packet: packet }; + } + // two-step look-ahead, only for a boss that asks for it (planner = 'two_step': lumen_moth): the packet of m, then the + // best of a few simple continuations (keep m, stand, walk left / right, jump) instead of m held for the whole horizon, + // so "dash out, then stop short of the spikes" is a plan it can see. Each continuation of a sample replays the same + // RNG stream; the worst sample still counts. Every other case keeps the one-step evaluate above, unchanged. + var CONT = [hold({}), hold({ A: 1 }), hold({ D: 1 }), jumpM(null, 6), dashM('A'), dashM('D')]; + function evaluate2(c, m, heal) { + var hp0 = c.body.hp, bh0 = c.boss.hp, horizon = heal ? Math.max(H_HEAL, c.boss.lookahead || 0) : (c.boss.lookahead || H), worst = 1e18, packet = []; + var steps = Math.ceil(horizon / TPS); + for (var smp = 0; smp < SAMPLES; smp++) { + var cc = fork(c, smp), lostAt = -1, tick = 0, i, s, k; + for (s = 0; s < SUB && !cc.result && lostAt < 0; s++) { + if (smp === 0) packet.push(cap(m(s, cc))); + k = packet[s]; + for (i = 0; i < TPS && !cc.result; i++) { cc.tick(k); tick++; if (cc.body.hp < hp0) { lostAt = tick; break; } } + } + while (smp === 0 && packet.length < SUB) packet.push({}); + var best; + if (lostAt >= 0 || cc.result) best = score(c, cc, hp0, bh0, lostAt); + else { + best = -1e18; + var conts = heal ? [[m, 0]] : [[m, 0]].concat(CONT.map(function (f) { return [f, SUB]; })); + for (var q = 0; q < conts.length; q++) { + var dd = fork(cc, 100 + smp), lost2 = -1, t2 = tick, fn = conts[q][0], off = conts[q][1]; + for (s = SUB; s < SUB + steps && !dd.result && lost2 < 0; s++) { + k = cap(fn(s - off, dd)); + for (i = 0; i < TPS && !dd.result; i++) { dd.tick(k); t2++; if (dd.body.hp < hp0) { lost2 = t2; break; } } + } + var v2 = score(c, dd, hp0, bh0, lost2); + if (v2 > best) best = v2; + } + } + if (best < worst) worst = best; + if (worst <= -500) break; + } + return { v: worst, packet: packet }; + } + function decide(c) { + var mem = MEM.get(c); + if (!mem || c.t === 0) { mem = { name: 'wait' }; MEM.set(c, mem); } + var b = c.body, best = null, bestName = 'wait'; + for (var j = 0; j < MACROS.length; j++) { + var name = MACROS[j][0], heal = name === 'heal'; + if (heal && !(b.hp < b.max_hp && b.soul >= 33 && b.grounded) && !(b.focusT >= 0)) continue; + // an exposed weak point (the maggot) is a timed window: spend it on damage unless one more hit would kill + if (heal && exposed(c) && b.hp > c.boss.dmg && !(b.focusT >= 0)) continue; + var r = evaluate(c, MACROS[j][1], heal); + if (name === mem.name) r.v += 0.6; // hysteresis + if (!best || r.v > best.v) { best = r; bestName = name; } + } + mem.name = bestName; + return { holds: best.packet, mouse: [0, 0, 0], macro: bestName }; + } + + BB.HK_SCRIPTED = { decide: decide, fork: fork, macros: MACROS.map(function (m) { return m[0]; }) }; + BB.GAME.scripted = function (c) { + if (c.result) return BB.NOOP; + var d = decide(c); + return { holds: d.holds, mouse: d.mouse }; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/specs/hollow_vessel.spec.js b/environments/games/web/games/hollowknight_remake/specs/hollow_vessel.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b675f0ff29856ff3300ef5e416fb26c00e71feb6 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/specs/hollow_vessel.spec.js @@ -0,0 +1,333 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["hollow_vessel"] = { + "schema": "bossbench/boss-spec@1", + "id": "hollow_vessel", + "dims": "2d", + "family": "pogo2d", + "archetype": "Frenzied blade-bearer (2D side view): long ground dash, high air dash, leaping down-stab with blob splash, overhead flail, back-step evade, blob cascades at HP thresholds and chasing balloons; staggers after a hit combo", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "jitter": "jitter", + "min": 0.08 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "phases": [ + { + "at": { + "hp_below": 0.7048 + }, + "gate": { + "knob": "cascade", + "min": 0.5 + }, + "add_moves": [ + "cascade" + ] + } + ], + "moves": [ + { + "name": "dash", + "atoms": [ + "charge", + "melee_area" + ], + "telegraph_scale": 0.817, + "active": 0.433, + "params": { + "speed": 32.0, + "reverse": 20.0, + "reverse_time": 0.1, + "antic": [ + 0.1, + 0.65, + 0.067 + ], + "recover": 0.25, + "slash": [ + 3.0, + 1.6, + 1.5 + ] + }, + "damage": 1, + "cue": "steps back, crouches with the blade drawn back, then crosses most of the room in one dash", + "punish": "0.25 s recover at the end of the dash" + }, + { + "name": "air_dash", + "atoms": [ + "leap", + "charge" + ], + "telegraph_scale": 0.65, + "active": 0.433, + "params": { + "chance": 0.3, + "height": 3.32 + }, + "damage": 1, + "cue": "jumps and hangs in the air with the blade drawn, then dashes at head height", + "punish": "falls after the dash; 0.25 s recover" + }, + { + "name": "jump", + "atoms": [ + "leap" + ], + "telegraph_scale": 0.4, + "params": { + "vy": 55.0, + "gravity_scale": 2.5, + "aim_mult": 1.25, + "land": 0.167 + }, + "damage": 1, + "cue": "crouches and jumps to a random point of the room", + "punish": "0.17 s landing" + }, + { + "name": "downstab", + "atoms": [ + "leap", + "melee_area", + "projectile" + ], + "telegraph_scale": 0.5, + "active": 0.583, + "params": { + "aim_mult": 2.5, + "fall_vy": -40.0, + "min_height": 5.13, + "range": 0.8, + "blobs": [ + 10.0, + 19.0, + -10.0, + -19.0 + ], + "blob_vy": 6.0, + "recover": 0.35 + }, + "damage": 1, + "cue": "jumps over the player, hangs with the blade pointing down, then plunges and splashes four blobs along the floor", + "punish": "0.58 s land + 0.35 s recover" + }, + { + "name": "overhead", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.65, + "active": 1.333, + "params": { + "chance": 0.25, + "range": [ + 2.6, + 1.0 + ], + "box": [ + 3.6, + 2.0, + 2.6 + ], + "recover": 0.167 + }, + "damage": 1, + "cue": "raises the blade and flails it over his head while the player is above him", + "punish": "0.17 s recover" + }, + { + "name": "evade", + "atoms": [ + "dodge" + ], + "telegraph_scale": 0.1, + "params": { + "chance": 0.45, + "speed": 25.0, + "time": 0.19, + "range": 3.0, + "recover": 0.083 + }, + "damage": 1, + "cue": "hops backwards away from a close player" + }, + { + "name": "cascade", + "atoms": [ + "leap", + "projectile" + ], + "telegraph_scale": 0.417, + "active": 5.9, + "params": { + "thresholds": [ + 0.7048, + 0.4191, + 0.2096 + ], + "jump_vy": 50.0, + "centre": [ + 11.04, + 13.04 + ], + "start": 0.5, + "spawn": 4.0, + "end": 1.4, + "speeds": [ + 5.0, + 8.0, + 11.0, + 14.0, + 17.0 + ], + "pause": 0.4, + "blob_r": 0.35, + "blob_g": 30.0, + "spawner_y": 6.0 + }, + "damage": 1, + "cue": "jumps to the middle and shakes; orange blobs pour from both walls and the roof for four seconds" + }, + { + "name": "balloon", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.5, + "params": { + "every": [ + 4.0, + 5.0 + ], + "x": [ + 2.9, + 22.0 + ], + "y": [ + 3.98, + 9.24 + ], + "max": 3, + "speed_max": 5.0, + "accel": 10.0, + "hp": 1, + "radius": 0.45, + "hp_gate": 0.8 + }, + "damage": 1, + "cue": "once he is down to 80 % HP, floating balloons drift in every 4-5 s and chase the player; one hit pops them" + } + ], + "difficulty": { + "hp": [ + 210, + 525, + 1050 + ], + "telegraph": [ + 1.2, + 1.0, + 0.69 + ], + "recovery": [ + 1.5, + 1.0, + 0.7 + ], + "idle_gap": [ + 1.4, + 1.0, + 0.6 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 1, + 1, + 2 + ], + "jitter": [ + 0, + 0, + 0 + ], + "entropy": [ + 1, + 1, + 1 + ], + "stun_combo": [ + 9, + 9, + 9 + ], + "stun_total": [ + 12, + 12, + 12 + ], + "balloons": [ + 3, + 3, + 3 + ], + "cascade_rate": [ + 0.6, + 1.0, + 1.3 + ], + "cascade": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "cascade": "unlock", + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/specs/iron_bulwark.spec.js b/environments/games/web/games/hollowknight_remake/specs/iron_bulwark.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..24bde1e07129f292f50dba392aa32fe7273f5ab5 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/specs/iron_bulwark.spec.js @@ -0,0 +1,272 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["iron_bulwark"] = { + "schema": "bossbench/boss-spec@1", + "id": "iron_bulwark", + "dims": "2d", + "family": "pogo2d", + "archetype": "Armoured mace-bearer (2D side view): leaps, leaping mace slam, ground smash with a floor shockwave, falling barrels; the armour gives no energy and, when broken, exposes a soft rider for a short window; a rage of 8 slams follows each exposed stage", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.12 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "phases": [ + { + "at": { + "hp_below": 0.817 + }, + "add_moves": [ + "rage" + ] + } + ], + "moves": [ + { + "name": "leap", + "atoms": [ + "leap" + ], + "telegraph_scale": 0.3, + "params": { + "vy": 90.0, + "gravity_scale": 0.125, + "rise_damp": 0.85, + "fall_damp": 1.15, + "damp_step": 0.02, + "vx_mult": 0.9, + "vx_max": 12.0, + "land": 0.5 + }, + "damage": 1, + "cue": "crouches with the mace on his shoulder, then leaps toward the player (half of the leaps go to a random spot)", + "punish": "0.5 s landing" + }, + { + "name": "bludgeon", + "atoms": [ + "leap", + "melee_area" + ], + "telegraph_scale": 0.3, + "active": 0.083, + "params": { + "vy": 90.0, + "vx_mult": 0.58, + "aim_offset": 3.0, + "recoil": [ + 0.167, + 0.084 + ], + "barrels_by_stage": [ + [ + 0, + 0 + ], + [ + 0, + 0 + ], + [ + 2, + 2 + ] + ] + }, + "damage": 1, + "cue": "leaps with the mace raised and brings it down in front of him as he lands", + "punish": "0.25 s recoil after the slam" + }, + { + "name": "smash", + "atoms": [ + "leap", + "melee_area", + "projectile" + ], + "telegraph_scale": 1.2, + "active": 0.12, + "params": { + "back_jump": [ + 12.0, + 18.0 + ], + "back_jump_vy": 105.0, + "wall_skip": 8.0, + "mace": [ + 5.92, + 2.55, + 3.23 + ], + "wave_speed": 22.0, + "wave_x": 5.5, + "recover": 0.417, + "barrels_by_stage": [ + [ + 0, + 0 + ], + [ + 2, + 3 + ], + [ + 3, + 4 + ] + ] + }, + "damage": 1, + "cue": "jumps back, then winds the mace far behind his head for over a second", + "punish": "the smash sends a shockwave along the floor - jump it; 0.42 s recover" + }, + { + "name": "charge", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.167, + "params": { + "speed": 18.2, + "trigger_dist": 21.0, + "stop_dist": 14.0 + }, + "damage": 1, + "cue": "when the player is far away he runs at them and follows up with the leaping slam" + }, + { + "name": "rage", + "atoms": [ + "melee_area", + "projectile" + ], + "telegraph_scale": 0.7, + "active": 1.99, + "params": { + "slams": 8, + "slam_time": 0.249, + "recover": 0.75, + "barrels": 8 + }, + "damage": 1, + "cue": "after the exposed rider is beaten back into the armour he jumps to the middle and slams left and right" + }, + { + "name": "barrel", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.6, + "params": { + "gravity_scale": 0.5, + "radius": 0.55 + }, + "damage": 1, + "cue": "dust trickles from the roof where a barrel is about to drop" + } + ], + "difficulty": { + "stages": [ + 1, + 3, + 3 + ], + "armor": [ + 65, + 65, + 260 + ], + "head": [ + 30, + 40, + 40 + ], + "hp": [ + 125, + 355, + 940 + ], + "telegraph": [ + 1.2, + 1.0, + 0.69 + ], + "recovery": [ + 1.5, + 1.0, + 0.7 + ], + "idle_gap": [ + 1.4, + 1.0, + 0.6 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 1, + 1, + 2 + ], + "entropy": [ + 1, + 1, + 1 + ], + "barrels": [ + 0.5, + 1.0, + 1.5 + ], + "head_window": [ + 6.5, + 5.0, + 5.0 + ] + }, + "kinds": { + "stages": "unlock", + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/specs/lumen_moth.spec.js b/environments/games/web/games/hollowknight_remake/specs/lumen_moth.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5b09552e6f02e09a5008c9e38483973629d06d15 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/specs/lumen_moth.spec.js @@ -0,0 +1,459 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["lumen_moth"] = { + "schema": "bossbench/boss-spec@1", + "id": "lumen_moth", + "dims": "2d", + "family": "pogo2d", + "archetype": "Four-winged floating figure (2D side view) floating over the arena and teleporting between attacks: homing light orbs, a ring of twelve swords, falling sword rain, sword walls with one gap, three bursts of eight light beams, a sweeping wall of light; spikes cover half the floor from phase 2; in phase 3 she holds the centre under endless sword rain; after a stagger the floor gives way to an abyss between footholds; at last she descends under the big beam and falls to one strike", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.12 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "phases": [ + { + "at": { + "hp_below": 0.7941 + }, + "add_moves": [ + "spikes" + ] + }, + { + "at": { + "hp_below": 0.5588 + } + }, + { + "at": { + "hp_below": 0.4118 + }, + "add_moves": [ + "abyss" + ] + }, + { + "at": { + "hp_below": 0.01 + }, + "add_moves": [ + "big_beam" + ] + } + ], + "moves": [ + { + "name": "orbs", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.75, + "active": 0.9, + "params": { + "count": 3, + "every": 0.45, + "radius": 0.42, + "speed": 6.5, + "accel": 9.0, + "launch": 3.0, + "life": 4.5, + "spread": 1.6, + "recover": 1.0 + }, + "damage": 2, + "cue": "her core flares and up to three orbs of light peel away from her, then home in", + "punish": "they burst on the floor or a wall: lead them into it" + }, + { + "name": "sword_burst", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.6, + "active": 0.25, + "params": { + "count": 12, + "ring": 1.15, + "speed": 16.0, + "half_len": 0.8, + "r": 0.12, + "recover": 0.6 + }, + "damage": 2, + "cue": "twelve swords stand in a ring around her, points outward", + "punish": "stand where two swords' lines spread apart; farther away is safer" + }, + { + "name": "sword_rain", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.45, + "active": 2.4, + "params": { + "waves": 4, + "every": 0.55, + "slot": 0.62, + "gaps": 2, + "gap_slots": 4, + "reach": 0.9, + "hang": 0.6, + "speed": 20.0, + "half_len": 0.8, + "r": 0.12, + "tele_after": 2, + "recover": 0.4 + }, + "damage": 2, + "cue": "rows of swords hang along the ceiling, points down, with two wide gaps", + "punish": "stand under a gap; she teleports half-way through" + }, + { + "name": "sword_wall", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.5, + "active": 4.0, + "params": { + "walls": 3, + "every": 1.6, + "row": 1.1, + "rows": 14, + "gaps": [ + [ + 0, + 3 + ], + [ + 3, + 4 + ] + ], + "hang": 0.5, + "speed": 13.0, + "half_len": 0.8, + "r": 0.12, + "tele_after": 2, + "recover": 0.6 + }, + "damage": 2, + "cue": "a column of swords forms along one side wall, with one gap open at the floor or at full-jump height", + "punish": "stand in a floor gap; for a high gap, jump as it arrives" + }, + { + "name": "beam_burst", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.5, + "active": 3.2, + "params": { + "bursts": 3, + "beams": 8, + "warn": 0.55, + "fire": 0.3, + "gap": 0.2, + "width": 0.35, + "recover": 0.6 + }, + "damage": 2, + "cue": "thin lines of light spread from her in eight directions", + "punish": "stand between two lines; the next burst turns half a step" + }, + { + "name": "beam_sweep", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.9, + "active": 2.6, + "params": { + "width": 1.0, + "reach": 0.89, + "cross": 2.6, + "recover": 0.6 + }, + "damage": 2, + "cue": "light gathers along one side wall", + "punish": "reach the far end before it arrives: it fades just short of the far wall" + }, + { + "name": "spikes", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 1.8, + "active": 5.0, + "params": { + "every": [ + 6.0, + 8.0 + ], + "height": 0.7, + "edge": 4.2, + "first": 0.8 + }, + "damage": 1, + "cue": "one half of the floor glows, then spikes rise there", + "punish": "stand on the other half" + }, + { + "name": "abyss", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 1.2, + "params": { + "islands": [ + [ + 0.0, + 3.0 + ], + [ + 6.89, + 9.89 + ], + [ + 13.78, + 16.78 + ], + [ + 20.67, + 23.67 + ] + ], + "height": 0.3 + }, + "damage": 1, + "cue": "after the stagger the floor darkens into an abyss between four pale footholds", + "punish": "stay on the footholds; jump the gaps" + }, + { + "name": "big_beam", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.6, + "active": 0.35, + "params": { + "width": 1.6, + "every": 1.2, + "beams": 3, + "top": 11.6, + "low": 4.4 + }, + "damage": 2, + "cue": "a thin line of light drops where you stand", + "punish": "step aside; after the third beam she sinks within reach and one strike ends her" + }, + { + "name": "teleport", + "atoms": [ + "dodge" + ], + "telegraph_scale": 0.25, + "active": 0.25, + "params": { + "out": 0.25, + "in": 0.25, + "idle": [ + 0.4, + 0.8 + ], + "min_dist": 2.8, + "near": 6.0, + "points": [ + [ + 3.2, + 6.2 + ], + [ + 6.6, + 4.2 + ], + [ + 6.6, + 8.2 + ], + [ + 9.9, + 6.2 + ], + [ + 11.8, + 4.2 + ], + [ + 13.8, + 6.2 + ], + [ + 13.8, + 8.2 + ], + [ + 17.1, + 4.2 + ], + [ + 17.1, + 8.2 + ], + [ + 20.5, + 6.2 + ] + ], + "points_p4": [ + [ + 1.5, + 5.2 + ], + [ + 8.39, + 4.4 + ], + [ + 8.39, + 6.6 + ], + [ + 15.28, + 4.4 + ], + [ + 15.28, + 6.6 + ], + [ + 22.17, + 5.2 + ] + ] + }, + "damage": 0, + "cue": "she dissolves into light and re-forms elsewhere" + }, + { + "name": "scream", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 1.2, + "params": { + "shares": [ + 350, + 400, + 250, + 700 + ], + "final_hp": 5, + "intro": 1.5, + "intro_from": 12.5, + "intro_to": 8.2, + "centre": [ + 11.835, + 6.8 + ], + "rain_every": 0.9, + "roar": 0.9, + "stun": 1.2, + "sink": 1.0, + "rise": 0.8, + "glide": 1.0 + }, + "damage": 0, + "cue": "she screams and the arena changes" + } + ], + "difficulty": { + "hp": [ + 110, + 500, + 1300 + ], + "telegraph": [ + 1.2, + 1.0, + 0.69 + ], + "recovery": [ + 1.5, + 1.0, + 0.7 + ], + "idle_gap": [ + 1.4, + 1.0, + 0.6 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 1, + 2, + 4 + ], + "floor_dmg": [ + 1, + 1, + 2 + ], + "nail": [ + 13, + 13, + 13 + ], + "entropy": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/specs/needle_warden.spec.js b/environments/games/web/games/hollowknight_remake/specs/needle_warden.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..f5bf7c9842ddaa214b8774e5631488632b075d4f --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/specs/needle_warden.spec.js @@ -0,0 +1,235 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["needle_warden"] = { + "schema": "bossbench/boss-spec@1", + "id": "needle_warden", + "dims": "2d", + "family": "pogo2d", + "archetype": "Agile spear duelist (2D side view): ground lunge, aimed air lunge, tethered spear throw, whirlwind AoE on the ground and mid-air, back-step evade; staggers after a hit combo; escalates below 40 % HP", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.12 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "phases": [ + { + "at": { + "hp_below": 0.4 + }, + "shift": { + "idle_gap": 0.4 + } + } + ], + "moves": [ + { + "name": "g_dash", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.556, + "active": 0.35, + "params": { + "speed": 25.0, + "recover": [ + 0.222, + 0.111 + ], + "decel": [ + 0.77, + 0.75 + ], + "spike_reach": 2.15 + }, + "damage": 1, + "cue": "crouches low facing the player with the spear drawn back", + "punish": "slides to a stop (~0.33 s); jump over her and pogo" + }, + { + "name": "a_dash", + "atoms": [ + "leap", + "charge" + ], + "telegraph_scale": 0.45, + "params": { + "jump_antic": 0.333, + "jump_vy": 41.0, + "gravity_scale": 1.5, + "air_pause": [ + 0.15, + 0.4 + ], + "speed": 30.0, + "aim_offset_y": -0.5, + "hard_land": 0.5, + "wall_impact": 0.333, + "wall_bounce": [ + 10.0, + 20.0 + ] + }, + "damage": 1, + "cue": "jumps, then freezes mid-air and aims at the player's feet; the aim is locked when the freeze starts", + "punish": "0.5 s hard landing" + }, + { + "name": "throw", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.778, + "params": { + "speed": 38.0, + "out_time": 0.3, + "decel": 0.8, + "return_speed": 30.0, + "recover": 0.333, + "only_when": "near a wall, facing into the room" + }, + "damage": 1, + "cue": "rears back with the spear; always thrown horizontally", + "punish": "stands still until the spear returns (~1 s); stagger counting is frozen meanwhile" + }, + { + "name": "g_sphere", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.833, + "active": 1.0, + "params": { + "radius": 2.53, + "grow_from": 0.8, + "grow_to": 1.5, + "grow_time": 0.25, + "trigger_range": 3.43, + "chance": 0.2, + "recover": 0.167 + }, + "damage": 1, + "cue": "plants her feet while a whirlwind gathers around her", + "punish": "0.17 s recover" + }, + { + "name": "a_sphere", + "atoms": [ + "leap", + "melee_area" + ], + "telegraph_scale": 0.583, + "active": 1.0, + "params": { + "jump_vx_mult": 1.25, + "trigger_height": 6.25, + "trigger_dx": 6.525, + "recover": 0.25 + }, + "damage": 1, + "cue": "stalls on the way down while a whirlwind gathers" + }, + { + "name": "evade", + "atoms": [ + "dodge" + ], + "telegraph_scale": 0.25, + "active": 0.25, + "params": { + "speed": 22.0, + "land": 0.25, + "range_w": 7.62, + "range_h": 6.23, + "true": [ + 1.0, + 2.0 + ], + "false": [ + 2.0, + 3.0 + ], + "wall_check": 3.0 + }, + "damage": 0, + "cue": "short crouch, then a fast back-step when the player is close" + } + ], + "difficulty": { + "hp": [ + 175, + 380, + 900 + ], + "telegraph": [ + 1.2, + 1.0, + 0.69 + ], + "recovery": [ + 1.5, + 1.0, + 0.7 + ], + "idle_gap": [ + 1.4, + 1.0, + 0.6 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 1, + 1, + 2 + ], + "entropy": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/specs/pale_vessel.spec.js b/environments/games/web/games/hollowknight_remake/specs/pale_vessel.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..dcf5fd60ffc9380a81d491e3497eacce6e8414ce --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/specs/pale_vessel.spec.js @@ -0,0 +1,548 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["pale_vessel"] = { + "schema": "bossbench/boss-spec@1", + "id": "pale_vessel", + "dims": "2d", + "family": "pogo2d", + "archetype": "Cracked-chest swordsman in four phases (2D side view): triple slash, lunge, parry-riposte, teleports; then diving flame pillars and blob barrages; then hovering outbreak, bouncing balloon slams and self-stabs; finally a dying swing that collapses into a stagger", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "jitter": "jitter", + "min": 0.08 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "phases": [ + { + "at": { + "hp_below": 0.8 + }, + "add_moves": [ + "dstab", + "barrage" + ] + }, + { + "at": { + "hp_below": 0.52 + }, + "add_moves": [ + "outbreak", + "puppet", + "self_stab" + ] + }, + { + "at": { + "hp_below": 0.2 + }, + "add_moves": [ + "weak_slash" + ] + } + ], + "moves": [ + { + "name": "slash", + "atoms": [ + "melee_area", + "charge" + ], + "telegraph_scale": 0.583, + "active": 0.533, + "params": { + "speed": [ + 44.0, + 29.33, + 29.33 + ], + "time": [ + 0.1, + 0.05, + 0.05 + ], + "gap": 0.167, + "recover": 0.333, + "ahead": [ + [ + 1.68, + 6.17 + ], + [ + -5.54, + 5.92 + ], + [ + -3.75, + 5.74 + ] + ], + "y": [ + 0.0, + 3.5 + ], + "range": [ + -0.64, + 8.0, + 2.5 + ] + }, + "damage": 1, + "cue": "plants the blade behind its shoulder, then three wide swings stepping forward; the 2nd and 3rd also reach behind it", + "punish": "0.33 s recover after the third swing" + }, + { + "name": "dash", + "atoms": [ + "charge", + "melee_area" + ], + "telegraph_scale": 0.583, + "active": 0.3, + "params": { + "speed": 45.0, + "decel": 0.8, + "recover": 0.45, + "box": [ + 3.55, + 2.93 + ] + }, + "damage": 1, + "cue": "crouches with the blade pointed forward, then lunges along the ground", + "punish": "slides to a stop over 0.45 s" + }, + { + "name": "counter", + "atoms": [ + "parry" + ], + "telegraph_scale": 0.25, + "active": 0.75, + "params": { + "block": 0.357, + "speed": 88.0, + "slash": 0.05, + "recover": [ + 0.167, + 0.333 + ], + "end": 0.25 + }, + "damage": 1, + "cue": "raises the blade; when it shines, a frontal hit is blocked and answered by a fast sliding riposte", + "punish": "do not hit the front while the blade shines; it lowers the guard after 0.75 s (0.25 s end)" + }, + { + "name": "evade", + "atoms": [ + "dodge" + ], + "telegraph_scale": 0.333, + "params": { + "speed": 40.0, + "time": 0.18, + "recover": 0.333, + "range": 5.0 + }, + "damage": 1, + "cue": "hops backwards away from a close player, often straight into another attack" + }, + { + "name": "jump", + "atoms": [ + "leap" + ], + "telegraph_scale": 0.333, + "params": { + "vy": [ + 55.0, + 60.0 + ], + "aim_mult": 1.4, + "max_vx": 40.0, + "x": [ + 25.84, + 64.47 + ], + "min_dx": 2.5, + "recover": 0.333 + }, + "damage": 1, + "cue": "crouches and leaps across the room", + "punish": "0.33 s landing recover" + }, + { + "name": "tele", + "atoms": [ + "teleport" + ], + "telegraph_scale": 0.3, + "params": { + "out": 0.3, + "in": 0.3, + "range": [ + 29.5, + 63.5 + ], + "self": 4.0, + "counter": [ + 7.5, + 8.0 + ], + "slash": [ + 7.5, + 9.0 + ], + "dash": [ + 8.0, + 14.0 + ], + "shot": [ + 8.0, + 14.0 + ], + "dstab_y": 15.38, + "dstab_x": [ + 31.36, + 59.08 + ], + "hero_high": 9.31 + }, + "damage": 1, + "cue": "fades out and reappears at a distance (or high above the player) ready to attack" + }, + { + "name": "dstab", + "atoms": [ + "leap", + "melee_area", + "projectile" + ], + "telegraph_scale": 0.333, + "active": 0.15, + "params": { + "jump_vy": 60.0, + "aim_mult": 3.0, + "range_w": 2.145, + "fall_vy": -70.0, + "fall_vx": 5.0, + "land": 0.15 + }, + "damage": 1, + "cue": "leaps (or teleports) above the player, hangs with the blade pointing down, then slams into the floor", + "punish": "it stands 1.1 s after landing while the pillars burst" + }, + { + "name": "plume", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.6, + "active": 0.55, + "params": { + "rounds": 10, + "every": 0.05, + "first": 2.5, + "step": [ + 4.5, + 5.0 + ], + "pause": 0.1, + "recover": 0.333, + "w": 0.624, + "h": 3.24 + }, + "damage": 2, + "cue": "orange glows spread across the floor from where it landed; columns of fire shoot up from every glow at once" + }, + { + "name": "barrage", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.357, + "active": 1.5, + "params": { + "time": 1.5, + "low": [ + 250.0, + 5.0, + -90.0, + 0.15, + 28.0, + 0.0 + ], + "high": [ + 120.0, + 5.0, + 90.0, + 0.25, + 30.0, + -15.0 + ], + "gravity": 27.0, + "jitter": [ + 0.25, + 0.5 + ], + "recover": 0.357, + "r": 0.3 + }, + "damage": 1, + "cue": "opens its cloak and sprays 9-10 blobs in a sweeping arc over ~75 % of the room", + "punish": "0.36 s recover" + }, + { + "name": "outbreak", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.214, + "active": 5.5, + "params": { + "time": [ + 5.0, + 6.0 + ], + "rise": 4.0, + "rise_v": 15.0, + "rise_wait": 0.85, + "every": 0.15, + "left": [ + -25.0, + -3.0, + 17.0, + 22.0 + ], + "right": [ + 3.0, + 25.0, + 15.0, + 20.0 + ], + "down": [ + 235.0, + 325.0, + 15.0, + 20.0 + ], + "gravity": 36.0, + "pause": 0.75, + "centre": [ + 34.11, + 59.2 + ] + }, + "damage": 1, + "cue": "rises to the middle of the room and blobs burst out of its chest in arcs to both sides and downward", + "punish": "falls and lands; hittable from below the whole time" + }, + { + "name": "puppet", + "atoms": [ + "leap", + "charge" + ], + "telegraph_scale": 0.214, + "active": 1.0, + "params": { + "loops": [ + 2, + 5 + ], + "up": [ + 25.0, + 0.95, + 1.0 + ], + "reup": [ + 75.0, + 0.88, + 0.65 + ], + "down": -50.0, + "chase": [ + 20.0, + 1.0, + 1.5 + ], + "slam": 0.083, + "end": 0.167, + "fall": 1.0, + "stand": 0.417 + }, + "damage": 1, + "cue": "jerked up like a puppet, it floats after the player and slams down 2-5 times", + "punish": "after the last slam it collapses for ~1.6 s" + }, + { + "name": "self_stab", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.5, + "active": 1.75, + "params": { + "loops_s": [ + 2, + 3 + ], + "loops_l": 3, + "antic_l": 1.2, + "reantic": 0.5, + "mini": 0.25, + "rep": 0.25, + "hit_dmg": 1 + }, + "damage": 1, + "cue": "turns the blade on itself and stabs its own chest; hits only deal 1 meanwhile, then it collapses", + "punish": "the collapse after the stabs is a full stagger (2.25 s)" + }, + { + "name": "weak_slash", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.583, + "active": 0.1, + "params": { + "walk": 3.0, + "walk_time": [ + 1.0, + 2.0 + ] + }, + "damage": 1, + "cue": "staggers toward the player, raises the blade for one swing and falls to its knees", + "punish": "the collapse is a full stagger (2.25 s)" + }, + { + "name": "roar", + "atoms": [ + "buff" + ], + "telegraph_scale": 0.583, + "active": 1.25, + "params": { + "end": 0.25, + "long": 3.0 + }, + "damage": 1, + "cue": "screams at each phase change" + } + ], + "difficulty": { + "hp": [ + 344, + 1000, + 2400 + ], + "p4": [ + 86, + 250, + 600 + ], + "telegraph": [ + 1.2, + 1.0, + 0.69 + ], + "recovery": [ + 1.5, + 1.0, + 0.7 + ], + "idle_gap": [ + 1.4, + 1.0, + 0.6 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 1, + 1, + 2 + ], + "plume_dmg": [ + 1, + 2, + 4 + ], + "jitter": [ + 0, + 0, + 0 + ], + "entropy": [ + 1, + 1, + 1 + ], + "stun_combo": [ + 10, + 10, + 10 + ], + "stun_total": [ + 12, + 12, + 12 + ], + "shot_rate": [ + 0.6, + 1.0, + 1.3 + ], + "nail": [ + 13, + 13, + 13 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/hollowknight_remake/specs/sickle_sisters.spec.js b/environments/games/web/games/hollowknight_remake/specs/sickle_sisters.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9ded818c87540eff9c8bc3e5e4302c616887c362 --- /dev/null +++ b/environments/games/web/games/hollowknight_remake/specs/sickle_sisters.spec.js @@ -0,0 +1,343 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["sickle_sisters"] = { + "schema": "bossbench/boss-spec@1", + "id": "sickle_sisters", + "dims": "2d", + "family": "pogo2d", + "archetype": "Lance duelists (2D side view): appear out of nowhere, ground-length lance dash, plunge from above, wall-thrown boomerang blade; after the first falls, two duelists attack together in fixed choreographies", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.08 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "phases": [ + { + "at": { + "hp_below": 0.604 + }, + "add_moves": [ + "duo" + ] + } + ], + "moves": [ + { + "name": "dash", + "atoms": [ + "charge", + "melee_area" + ], + "telegraph_scale": 0.717, + "active": 0.28, + "params": { + "speed": 55.0, + "x": [ + 22.25, + 37.65 + ], + "hero_split": [ + 29.98, + 30.18 + ], + "arrive": 0.3, + "antic": 0.417, + "recover": 0.625, + "leave": 0.2, + "lance": [ + 1.67, + 4.61, + 0.32, + 0.43 + ], + "body_h": 1.3 + }, + "damage": 1, + "cue": "appears crouched at one end of the floor with the lance drawn back, then crosses the whole floor", + "punish": "0.63 s recover standing at the far end" + }, + { + "name": "dstab", + "atoms": [ + "leap", + "melee_area" + ], + "telegraph_scale": 0.6, + "active": 0.12, + "params": { + "speed": -65.0, + "y": 16.96, + "y_high": 19.2, + "hero_high": 12.0, + "x": [ + 21.5, + 38.5 + ], + "shift": 4.0, + "chase": [ + 7.0, + 7.0 + ], + "land": 0.667, + "leave": 0.15 + }, + "damage": 1, + "cue": "appears high above the player pointing the lance down, then drops straight onto the floor", + "punish": "0.67 s landing pose" + }, + { + "name": "throw", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.867, + "active": 0.333, + "params": { + "wall_x": [ + 18.2, + 41.77 + ], + "hero_wall": [ + 22.0, + 37.0 + ], + "y_ud": [ + 11.5, + 12.5 + ], + "y_du": [ + 9.5, + 10.0 + ], + "point": [ + -2.01, + -1.97 + ], + "cd": 0.5, + "leave": [ + 0.5, + 0.167, + 0.15 + ], + "after": 0.65 + }, + "damage": 1, + "cue": "clings to a side wall high (blade will sink) or low (blade will rise) and winds up a throw", + "punish": "she hangs on the wall ~1.2 s after the throw" + }, + { + "name": "blade", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.1, + "params": { + "vx": 33.0, + "force": -24.0, + "vy": 1.1, + "du_drop": 0.5, + "corner_y": 19.0, + "corner_vy": 2.0, + "life": 6.0, + "box": [ + 3.221, + 0.894 + ], + "scale": 1.5, + "wide": [ + 33.0, + -24.0, + -2.2 + ], + "narrow": [ + 16.5, + -12.0, + -2.2 + ] + }, + "damage": 1, + "cue": "a spinning blade crosses the room, slows, and flies back to the thrower" + }, + { + "name": "high_throw", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.867, + "active": 0.333, + "params": { + "hero_y": 19.0, + "hero_x": [ + 20.16, + 39.87 + ], + "y_clamp": [ + 9.0, + 21.93 + ] + }, + "damage": 1, + "cue": "the player hugs a wall: a duelist appears on the far wall at the player's height and throws" + }, + { + "name": "duo", + "atoms": [ + "charge", + "projectile" + ], + "telegraph_scale": 0.5, + "params": { + "choices": [ + "stab_dash", + "dash_stab", + "double_dash", + "pincer", + "double_stab", + "throw_narrow", + "throw_wide" + ], + "weights": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ], + "max": [ + 2, + 2, + 2, + 2, + 2, + 1, + 1 + ], + "miss_max": [ + 10, + 10, + 10, + 10, + 10, + 12, + 12 + ], + "pincer_x": [ + 27.24, + 33.35 + ], + "stab_dash": [ + 0.8, + 2.75 + ], + "dash_stab": [ + 1.5, + 2.75 + ], + "double_stab": [ + 0.75, + 2.2 + ], + "double_dash": [ + 1.5, + 2.25 + ], + "pincer": [ + 0.0, + 2.0 + ], + "dthrow": [ + 0.5, + 4.0 + ], + "wall_y": [ + 14.5, + 15.5 + ], + "high_wait": 0.5, + "gap": 2.0 + }, + "damage": 1, + "cue": "two duelists at once: dash + plunge combos, a pincer dash from both ends, or blades from both walls" + } + ], + "difficulty": { + "hp": [ + 101, + 240, + 760 + ], + "telegraph": [ + 1.2, + 1.0, + 0.69 + ], + "recovery": [ + 1.5, + 1.0, + 0.7 + ], + "idle_gap": [ + 1.4, + 1.0, + 0.6 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 1, + 1, + 2 + ], + "entropy": [ + 1, + 1, + 1 + ] + }, + "kinds": { + "entropy": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/isaac_remake/compact_actions.json b/environments/games/web/games/isaac_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..0ffe2d845b2eae53c75cf53fab58753e5d0eba35 --- /dev/null +++ b/environments/games/web/games/isaac_remake/compact_actions.json @@ -0,0 +1,113 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "isaac_remake", + "version": "isaac-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "up", + "keys": [ + "W" + ] + }, + { + "label": "up_right", + "keys": [ + "W", + "D" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "down_right", + "keys": [ + "S", + "D" + ] + }, + { + "label": "down", + "keys": [ + "S" + ] + }, + { + "label": "down_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "up_left", + "keys": [ + "W", + "A" + ] + } + ] + }, + { + "name": "fire", + "options": [ + { + "label": "none" + }, + { + "label": "up", + "keys": [ + "Shift" + ] + }, + { + "label": "down", + "keys": [ + "K" + ] + }, + { + "label": "left", + "keys": [ + "J" + ] + }, + { + "label": "right", + "keys": [ + "L" + ] + } + ] + }, + { + "name": "bomb", + "options": [ + { + "label": "none" + }, + { + "label": "place", + "tap": [ + "E" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/isaac_remake/draw.js b/environments/games/web/games/isaac_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..2ca58aad9eaa9585ad819ad02ac3a48d35463095 --- /dev/null +++ b/environments/games/web/games/isaac_remake/draw.js @@ -0,0 +1,629 @@ +/* Isaac basement renderer (read-only). Original procedural vector art with dark hand-drawn outlines, a + * restrained palette (no gore). Never mutates the game object or consumes game RNG: wobble, wing flaps and + * debris use hashes of the tick / ids, so a frame is a pure function of the state. + */ +(function (root) { + 'use strict'; + const M = root.IsaacGame, TAU = Math.PI * 2, R = M.room, TILE = M.tile; + const FONT = "'Microsoft YaHei','PingFang SC','Noto Sans CJK SC','Noto Sans SC',sans-serif"; + const INK = '#22170f'; + const cache = new Map(); + const hash = (a, b) => { let h = (Math.imul(a | 0, 73856093) ^ Math.imul(b | 0, 19349663) ^ 0x5bd1e995) >>> 0; h = Math.imul(h ^ (h >>> 15), 2246822519) >>> 0; h = Math.imul(h ^ (h >>> 13), 3266489917) >>> 0; return ((h ^ (h >>> 16)) >>> 0) / 4294967296; }; + const mk = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }; + function cached(key, w, h, paint) { + let c = cache.get(key); + // Keep sprite caches CPU-backed for frame readback. + if (!c) { c = mk(w, h); paint(c.getContext('2d', { willReadFrequently: true }), w, h); cache.set(key, c); } + return c; + } + const ell = (c, x, y, rx, ry, fill, stroke, lw) => { c.beginPath(); c.ellipse(x, y, Math.max(0.1, rx), Math.max(0.1, ry), 0, 0, TAU); if (fill) { c.fillStyle = fill; c.fill(); } if (stroke) { c.strokeStyle = stroke; c.lineWidth = lw || 2; c.stroke(); } }; + const txt = (c, s, x, y, size, col, align, weight) => { c.font = (weight || 'bold') + ' ' + size + 'px ' + FONT; c.textAlign = align || 'left'; c.textBaseline = 'alphabetic'; c.lineWidth = 3; c.strokeStyle = 'rgba(10,6,4,0.85)'; c.strokeText(s, x, y); c.fillStyle = col; c.fillText(s, x, y); }; + const heartPath = (c, x, y, s) => { c.beginPath(); c.moveTo(x, y + s * 0.95); c.bezierCurveTo(x - s * 1.25, y + s * 0.15, x - s * 0.95, y - s * 0.85, x, y - s * 0.3); c.bezierCurveTo(x + s * 0.95, y - s * 0.85, x + s * 1.25, y + s * 0.15, x, y + s * 0.95); c.closePath(); }; + + // ---------------- room background (cached) ---------------- + function background() { + return cached('bg', 854, 480, (c) => { + c.fillStyle = '#120c0a'; c.fillRect(0, 0, 854, 480); + // walls: top face, sides, bottom lip (stone courses) + const W = { x0: R.x0 - 36, y0: R.y0 - 44, x1: R.x1 + 36, y1: R.y1 + 24 }; + const g = c.createLinearGradient(0, W.y0, 0, R.y0); g.addColorStop(0, '#2c221d'); g.addColorStop(1, '#46372f'); + c.fillStyle = g; c.fillRect(W.x0, W.y0, W.x1 - W.x0, R.y0 - W.y0); + c.fillStyle = '#3a2d27'; c.fillRect(W.x0, R.y0, R.x0 - W.x0, R.y1 - R.y0); c.fillRect(R.x1, R.y0, W.x1 - R.x1, R.y1 - R.y0); + c.fillStyle = '#2e241f'; c.fillRect(W.x0, R.y1, W.x1 - W.x0, W.y1 - R.y1); + c.strokeStyle = 'rgba(15,10,8,0.55)'; c.lineWidth = 1; + for (let row = 0; row < 3; row++) { // brick courses on the top wall + const y = W.y0 + 6 + row * 13; + c.beginPath(); c.moveTo(W.x0, y + 13); c.lineTo(W.x1, y + 13); c.stroke(); + for (let x = W.x0 + (row % 2) * 22; x < W.x1; x += 44) { c.beginPath(); c.moveTo(x, y); c.lineTo(x, y + 13); c.stroke(); } + } + for (let y = R.y0; y < R.y1; y += 26) for (const [x0, x1] of [[W.x0, R.x0], [R.x1, W.x1]]) { c.beginPath(); c.moveTo(x0, y); c.lineTo(x1, y); c.stroke(); } + // floor tiles with soft variation and cracks + for (let r = 0; r < R.rows; r++) for (let q = 0; q < R.cols; q++) { + const x = R.x0 + q * TILE, y = R.y0 + r * TILE, h = hash(q * 7 + 3, r * 13 + 5); + const base = 82 + Math.round(h * 9); + c.fillStyle = `rgb(${base},${Math.round(base * 0.78)},${Math.round(base * 0.6)})`; c.fillRect(x, y, TILE, TILE); + c.fillStyle = 'rgba(255,230,200,0.035)'; c.fillRect(x + 2, y + 2, TILE - 4, 3); + c.strokeStyle = 'rgba(30,20,14,0.45)'; c.strokeRect(x + 0.5, y + 0.5, TILE - 1, TILE - 1); + if (h > 0.72) { c.strokeStyle = 'rgba(30,20,14,0.5)'; c.beginPath(); const cx = x + 10 + hash(q, r) * 28, cy = y + 10 + hash(r, q) * 28; c.moveTo(cx, cy); c.lineTo(cx + 7, cy + 4); c.lineTo(cx + 10, cy + 11); c.stroke(); } + if (h < 0.05) { ell(c, x + 24, y + 30, 7, 3, 'rgba(40,26,18,0.16)'); } + } + // inner wall shadow + vignette + const sh = c.createLinearGradient(0, R.y0, 0, R.y0 + 26); sh.addColorStop(0, 'rgba(10,6,4,0.55)'); sh.addColorStop(1, 'rgba(10,6,4,0)'); + c.fillStyle = sh; c.fillRect(R.x0, R.y0, R.x1 - R.x0, 26); + for (const [x, w, dir] of [[R.x0, 20, 1], [R.x1 - 20, 20, -1]]) { const s2 = c.createLinearGradient(x + (dir < 0 ? 20 : 0), 0, x + (dir < 0 ? 0 : 20), 0); s2.addColorStop(0, 'rgba(10,6,4,0.4)'); s2.addColorStop(1, 'rgba(10,6,4,0)'); c.fillStyle = s2; c.fillRect(x, R.y0, w, R.y1 - R.y0); } + const v = c.createRadialGradient(427, 256, 140, 427, 256, 420); v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(0,0,0,0.42)'); + c.fillStyle = v; c.fillRect(R.x0, R.y0, R.x1 - R.x0, R.y1 - R.y0); + c.strokeStyle = '#1a120e'; c.lineWidth = 3; c.strokeRect(R.x0 - 1.5, R.y0 - 1.5, R.x1 - R.x0 + 3, R.y1 - R.y0 + 3); + c.strokeStyle = '#0c0806'; c.lineWidth = 2; c.strokeRect(W.x0, W.y0, W.x1 - W.x0, W.y1 - W.y0); + // side panels + c.fillStyle = '#0f0a08'; c.fillRect(0, 0, W.x0, 480); c.fillRect(W.x1, 0, 854 - W.x1, 480); + }); + } + const DOORS = [ // [cx, cy, w, h, side] + [427, R.y0 - 22, 62, 44, 'top'], [427, R.y1 + 12, 62, 24, 'bottom'], [R.x0 - 18, 256, 36, 62, 'left'], [R.x1 + 18, 256, 36, 62, 'right'] + ]; + function drawDoors(c, g) { + const open = g.doors === 'open', k = open ? Math.min(1, (g.t - g.clearT) / 20) : 0; + for (const [cx, cy, w, h, side] of DOORS) { + c.fillStyle = '#5a1c1a'; c.fillRect(cx - w / 2 - 6, cy - h / 2 - (side === 'top' ? 4 : 0), w + 12, h + (side === 'top' ? 4 : 0)); + c.fillStyle = '#7a2a24'; c.fillRect(cx - w / 2 - 3, cy - h / 2 - (side === 'top' ? 2 : -2), w + 6, 4); + c.fillStyle = '#0c0706'; c.fillRect(cx - w / 2 + 2, cy - h / 2 + 2, w - 4, h - 4); + if (k < 1) { // bars slide away when the room is cleared + c.save(); c.beginPath(); c.rect(cx - w / 2 + 2, cy - h / 2 + 2, w - 4, h - 4); c.clip(); + c.fillStyle = '#4b3c33'; c.strokeStyle = INK; c.lineWidth = 1.5; + const vertical = side === 'top' || side === 'bottom'; + for (let i = 0; i < 4; i++) { + if (vertical) { const x = cx - w / 2 + 8 + i * (w - 16) / 3, y = cy - h / 2 - k * h; c.fillRect(x - 3, y, 6, h); c.strokeRect(x - 3, y, 6, h); } + else { const y = cy - h / 2 + 8 + i * (h - 16) / 3, x = cx - w / 2 - k * w * (side === 'left' ? 1 : -1); c.fillRect(x, y - 3, w, 6); c.strokeRect(x, y - 3, w, 6); } + } + c.restore(); + } + // horn ornaments of the boss door (original stylisation) + c.fillStyle = '#2a1512'; + if (side === 'top') { for (const s of [-1, 1]) { c.beginPath(); c.moveTo(cx + s * (w / 2 + 2), cy - h / 2 + 2); c.quadraticCurveTo(cx + s * (w / 2 + 16), cy - h / 2 - 6, cx + s * (w / 2 + 10), cy - h / 2 - 18); c.quadraticCurveTo(cx + s * (w / 2 + 8), cy - h / 2 - 4, cx + s * (w / 2 - 4), cy - h / 2 + 2); c.fill(); } } + } + } + + // ---------------- entities ---------------- + function shadow(c, x, y, rx, ry, a) { ell(c, x, y, rx, ry, 'rgba(12,6,4,' + (a === undefined ? 0.38 : a) + ')'); } + + function drawIsaac(c, g) { + const p = g.player, t = g.t; + if (p.inv > 0 && p.dead === 0 && Math.floor(t / 4) % 2 === 0) return shadow(c, p.x, p.y + 2, 11, 4, 0.25); + const dead = p.dead > 0, hd = p.head, bob = p.moving ? Math.abs(Math.sin(p.step * 0.32)) * 2 : 0; + shadow(c, p.x, p.y + 2, 12, 4.5); + c.save(); c.translate(Math.round(p.x), Math.round(p.y)); + if (dead) { c.rotate(Math.PI / 2 * Math.min(1, (M.isaac.deadTicks - p.dead) / 12)); c.globalAlpha = Math.max(0.35, p.dead / M.isaac.deadTicks); } + const hurt = t - p.hurtT < 10; + const skin = hurt ? '#f2a49a' : '#f1d9c6', shade = hurt ? '#d97a72' : '#d7b5a0'; + // legs + body + const leg = p.moving ? Math.sin(p.step * 0.32) * 3 : 0; + c.fillStyle = skin; c.strokeStyle = INK; c.lineWidth = 2; + for (const s of [-1, 1]) { c.beginPath(); c.ellipse(s * 4 + (s > 0 ? leg : -leg) * 0.3, -2, 3, 4, 0, 0, TAU); c.fill(); c.stroke(); } + c.beginPath(); c.ellipse(0, -9 - bob * 0.3, 8, 8, 0, 0, TAU); c.fill(); c.stroke(); + c.fillStyle = shade; c.beginPath(); c.ellipse(1.5, -7 - bob * 0.3, 5, 5, 0, 0, Math.PI); c.fill(); + // head (squashes slightly on each shot) + const shotAge = t - p.fireT, sq = p.cd > g.stats.interval - 5 && shotAge < 2 ? 0.07 : 0; + const hy = -28 - bob; + c.save(); c.translate(0, hy); c.scale(1 + sq, 1 - sq); + c.fillStyle = skin; c.beginPath(); c.ellipse(0, 0, 15, 14, 0, 0, TAU); c.fill(); c.stroke(); + c.fillStyle = shade; c.beginPath(); c.ellipse(4, 5, 10, 7, 0.4, 0, Math.PI); c.fill(); + if (hd[1] < 0) { // facing away: crown of the head + c.strokeStyle = 'rgba(60,40,30,0.5)'; c.lineWidth = 1.5; c.beginPath(); c.arc(0, -4, 6, Math.PI * 1.1, Math.PI * 1.9); c.stroke(); + } else { + const ex = hd[0] * 6, eyes = hd[0] ? [[ex - 3.5 * hd[0], 0], [ex + 4.5 * hd[0], 0.5]] : [[-5.5, 0], [5.5, 0]]; + for (const [x, y] of eyes) { + ell(c, x, y, 3.4, 3.8, '#1c1210'); + ell(c, x - 1, y - 1.3, 1.1, 1.2, '#f8f2ea'); + c.strokeStyle = 'rgba(120,190,240,0.75)'; c.lineWidth = 1.6; // the eternal tear streaks + c.beginPath(); c.moveTo(x, y + 3.5); c.quadraticCurveTo(x + 0.5, y + 7, x - 0.5, y + 10); c.stroke(); + } + c.strokeStyle = INK; c.lineWidth = 1.5; c.beginPath(); c.arc(ex * 0.6, 8, 3, Math.PI * 1.15, Math.PI * 1.85); c.stroke(); + } + c.restore(); + c.restore(); + } + + function drawMonstro(c, g) { + const b = g.boss, t = g.t; + if (b.dead) return; + const p = g.player; + if (b.st === 'track' || b.st === 'lock' || b.st === 'fall') { // landing telegraph: the exact slam circle for Isaac's feet + const lock = b.st !== 'track', pulse = 0.5 + 0.5 * Math.sin(t * 0.6), R2 = M.slamRadius(b), cy = b.sy - M.bosses.monstro.lift; + shadow(c, b.sx, b.sy - 4, b.r * (lock ? 1.05 : 0.8), b.r * 0.42, lock ? 0.55 : 0.32); + if (lock) { // exactly the slam area: Isaac is hit when his body (radius 11) touches this circle + c.fillStyle = `rgba(200,40,40,${0.1 + 0.08 * pulse})`; c.beginPath(); c.arc(b.sx, cy, R2, 0, TAU); c.fill(); + c.strokeStyle = `rgba(230,70,60,${0.55 + 0.4 * pulse})`; c.lineWidth = 2.5; c.setLineDash([7, 5]); + c.beginPath(); c.arc(b.sx, cy, R2, 0, TAU); c.stroke(); c.setLineDash([]); + } + } + if (b.hidden && b.st !== 'fall') return; + if (b.z < 200) shadow(c, b.x, b.y + 4, b.r * (1 - Math.min(0.5, b.z / 300)), b.r * 0.36); + let sx = 1, sy = 1; + if (b.st === 'crouch' || b.st === 'jcrouch' || b.st === 'land') { sx = 1.12; sy = 0.86; } + else if (b.st === 'hop' || b.st === 'rise' || b.st === 'fall') { sx = 0.92; sy = 1.1; } + const coughing = b.st === 'cough', spit = b.st === 'crecover' && b.timer > 18; + if (coughing) { const k = 1 - b.timer / 28; sx += 0.08 * k; sy += 0.06 * k; } + const flash = t - b.flash < 3; + c.save(); c.translate(Math.round(b.x), Math.round(b.y - b.z)); c.scale(b.face * sx, sy); + const body = flash ? '#e2aaa0' : '#c48a80', shade = flash ? '#c88a82' : '#a26a62', belly = flash ? '#f0cfc4' : '#ddb0a4'; + c.lineWidth = 2.5; c.strokeStyle = INK; + c.fillStyle = body; c.beginPath(); c.ellipse(0, -32, 47, 38, 0, 0, TAU); c.fill(); c.stroke(); + c.fillStyle = shade; c.beginPath(); c.ellipse(8, -22, 38, 26, 0.2, 0, Math.PI); c.fill(); + c.fillStyle = belly; c.beginPath(); c.ellipse(-4, -18, 26, 14, 0, Math.PI, TAU); c.fill(); + // stubby feet + c.fillStyle = shade; for (const s of [-1, 1]) { c.beginPath(); c.ellipse(s * 24, -2, 11, 6, 0, 0, TAU); c.fill(); c.stroke(); } + // eyes + for (const [x, y, rr] of [[-14, -54, 7], [12, -56, 8]]) { ell(c, x, y, rr, rr, '#f6efe4', INK, 2); ell(c, x + 2.5, y + 1, rr * 0.45, rr * 0.5, '#1c1210'); } + // mouth: closed line, or open with teeth (one missing) + const open = spit ? 1 : coughing ? Math.max(0, 1 - b.timer / 10) : b.st === 'land' ? 0.35 : 0.15; + c.fillStyle = '#4a1518'; c.beginPath(); c.ellipse(2, -26, 26, 4 + 15 * open, 0, 0, TAU); c.fill(); c.stroke(); + if (open > 0.3) { + c.fillStyle = '#efe7d6'; + for (let i = 0; i < 6; i++) { if (i === 2) continue; const x = -18 + i * 7.5; c.beginPath(); c.moveTo(x, -26 - 4 - 13 * open); c.lineTo(x + 3, -26 - 4 - 13 * open + 6); c.lineTo(x + 6, -26 - 4 - 13 * open); c.fill(); } + } + c.restore(); + } + + function segmentArt(head, flash, dirx) { + return cached('seg' + head + flash + dirx, 50, 50, (c) => { + c.translate(25, 25); + ell(c, 0, 0, 20, 19, flash ? '#f0d6b4' : '#d8b48c', INK, 2.5); + ell(c, 3, 5, 14, 10, flash ? '#d8b490' : '#b98f68'); + c.strokeStyle = 'rgba(70,45,25,0.55)'; c.lineWidth = 2; + c.beginPath(); c.ellipse(0, 0, 13, 18, 0, -1.2, 1.2); c.stroke(); + ell(c, -6, -8, 6, 4, 'rgba(255,240,215,0.45)'); + if (head) { + const ex = dirx * 4; + for (const x of [-6, 6]) { ell(c, x + ex, -3, 4, 4.5, '#f6efe4', INK, 1.5); ell(c, x + ex + dirx, -2, 2, 2.2, '#1c1210'); } + c.strokeStyle = INK; c.lineWidth = 1.6; c.beginPath(); c.arc(ex, 8, 4, Math.PI * 1.15, Math.PI * 1.85); c.stroke(); + } + }); + } + function drawLarry(c, g, items) { + const b = g.boss, t = g.t; + for (const body of b.bodies) { + for (let k = body.segs.length - 1; k >= 0; k--) { + const s = body.segs[k], head = k === 0, wob = Math.sin(t * 0.25 + k * 0.9) * 1.4; + const art = segmentArt(head, t - s.flash < 3, head ? body.dir[0] : 0); + items.push([s.y + (head ? 0.5 : 0), () => { shadow(c, s.x, s.y + 6, 17, 6); c.drawImage(art, Math.round(s.x - 25), Math.round(s.y - 33 + wob)); }]); + } + } + } + + function dukeArt(flash, puff) { + return cached('duke' + flash + puff, 110, 110, (c) => { + c.translate(55, 58); const s = 1 + puff * 0.05; c.scale(s, s); + const body = flash ? '#a8a674' : '#7b7a50', shade = flash ? '#858456' : '#5b5a38', hi = flash ? '#c8c69a' : '#9d9b6c'; + c.fillStyle = shade; c.strokeStyle = INK; c.lineWidth = 2.5; + for (const [x, y, rx, ry] of [[-34, 14, 9, 7], [34, 14, 9, 7], [-16, 34, 8, 9], [16, 34, 8, 9]]) { c.beginPath(); c.ellipse(x, y, rx, ry, 0, 0, TAU); c.fill(); c.stroke(); } + ell(c, 0, 0, 40, 38, body, INK, 2.5); + ell(c, 8, 10, 30, 22, shade); + ell(c, -14, -16, 12, 8, hi); + for (const x of [-14, 12]) { ell(c, x, -12, 6, 5, '#2a2416', INK, 1.5); ell(c, x + 1, -11, 2, 2, '#c9c4a0'); } + ell(c, 0, 12, 20, 11 + puff * 3, '#2b2214', INK, 2); + for (let i = 0; i < 4; i++) ell(c, -10 + i * 7, 12 + (i % 2) * 3, 2.6, 2, '#100c08'); + c.strokeStyle = 'rgba(40,36,20,0.6)'; c.lineWidth = 1.5; + c.beginPath(); c.moveTo(-6, 26); c.lineTo(0, 32); c.lineTo(6, 26); c.moveTo(0, 32); c.lineTo(0, 38); c.stroke(); + }); + } + function drawDuke(c, g, items) { + const b = g.boss, t = g.t; + if (b.dead) return; + const puff = b.wind > 0 ? 1 : 0, art = dukeArt(t - b.flash < 3, puff), bob = Math.sin(t * 0.08) * 3; + items.push([b.y, () => { shadow(c, b.x, b.y + 30, 30, 8, 0.32); c.drawImage(art, Math.round(b.x - 55), Math.round(b.y - 64 + bob)); }]); + } + // ---- Gemini: Contusion (big twin) and Suture (small twin) joined by a dotted umbilical cord + function twinArt(role, flash, mood) { + const big = role === 'contusion', w = big ? 70 : 44; + return cached('twin' + role + flash + mood, w, w, (c) => { + c.translate(w / 2, w / 2 + 2); + const skin = flash ? '#f3c9c0' : big ? '#d9a69c' : '#e6bcb2', shade = flash ? '#e2b0a6' : big ? '#b9837a' : '#c99a90'; + const R = big ? 26 : 15; + ell(c, 0, 0, R, R * 0.96, skin, INK, 2.5); + ell(c, R * 0.25, R * 0.3, R * 0.7, R * 0.5, shade); + if (big) { c.strokeStyle = 'rgba(90,50,45,0.55)'; c.lineWidth = 2; c.beginPath(); c.arc(-6, -R * 0.62, 7, 0.2, Math.PI - 0.2); c.stroke(); } // the dent on his head + const ex = big ? 9 : 5, ey = big ? -5 : -3, er = big ? 5 : 3; + for (const sx of [-1, 1]) { + ell(c, sx * ex, ey, er, er * 1.1, '#f6efe4', INK, 1.5); ell(c, sx * ex + 1, ey + 1, er * 0.5, er * 0.55, '#1c1210'); + if (mood) { c.strokeStyle = INK; c.lineWidth = 2; c.beginPath(); c.moveTo(sx * (ex + er + 1), ey - er - 3); c.lineTo(sx * (ex - er), ey - er + 1); c.stroke(); } // angry brows + } + c.fillStyle = '#5a2224'; c.beginPath(); c.ellipse(0, big ? 11 : 6, big ? 9 : 5, mood ? (big ? 6 : 4) : 2.5, 0, 0, TAU); c.fill(); c.strokeStyle = INK; c.lineWidth = 1.5; c.stroke(); + if (!big) { c.strokeStyle = 'rgba(70,40,40,0.6)'; c.lineWidth = 1.2; for (let i = -1; i <= 1; i++) { c.beginPath(); c.moveTo(i * 4 - 2, -R + 3); c.lineTo(i * 4 + 2, -R + 6); c.stroke(); } } // stitches + }); + } + function drawGemini(c, g, items) { + const b = g.boss, t = g.t, [C, S] = b.twins; + if (b.attached && !C.dead && !S.dead) { // the cord (drawn on the floor layer under both) + items.push([Math.min(C.y, S.y) - 1, () => { + const mx = (C.x + S.x) / 2, my = (C.y + S.y) / 2 + 10 + Math.sin(t * 0.1) * 4; + c.strokeStyle = '#8c4e4a'; c.lineWidth = 4; c.beginPath(); c.moveTo(C.x, C.y - 6); c.quadraticCurveTo(mx, my, S.x, S.y - 6); c.stroke(); + c.strokeStyle = '#d99a90'; c.lineWidth = 2; c.setLineDash([3, 4]); c.beginPath(); c.moveTo(C.x, C.y - 6); c.quadraticCurveTo(mx, my, S.x, S.y - 6); c.stroke(); c.setLineDash([]); + }]); + } + for (const tw of b.twins) { + if (tw.dead) continue; + const big = tw.role === 'contusion', mood = big ? tw.st === 'charge' : tw.st === 'frenzy'; + const art = twinArt(tw.role, t - tw.flash < 3, mood ? 1 : 0), w = art.width; + const bob = big ? Math.abs(Math.sin(t * (tw.st === 'charge' ? 0.5 : 0.22))) * 3 : Math.sin(t * 0.3) * 2; + items.push([tw.y, () => { + shadow(c, tw.x, tw.y + 4, tw.r * 0.95, tw.r * 0.35); + if (big && tw.st === 'rest') { c.fillStyle = 'rgba(235,235,240,0.55)'; for (let i = 0; i < 2; i++) { const a = (t * 0.08 + i * 2) % 1; ell(c, tw.x + 14 + i * 6, tw.y - tw.r * 1.6 - a * 14, 3 + a * 3, 2 + a * 2, `rgba(235,235,240,${0.6 - a * 0.5})`); } } // catching his breath + if (!big && tw.st === 'tethered' && tw.wind > 0) ell(c, tw.x, tw.y - tw.r - 6, 5 + tw.wind * 0.2, 5 + tw.wind * 0.2, 'rgba(200,50,50,0.35)'); + if (mood && !big) { c.strokeStyle = 'rgba(255,255,255,0.35)'; c.lineWidth = 2; const sp = Math.hypot(tw.vx, tw.vy) || 1; c.beginPath(); c.moveTo(tw.x - tw.vx / sp * 26, tw.y - tw.r - tw.vy / sp * 26); c.lineTo(tw.x - tw.vx / sp * 12, tw.y - tw.r - tw.vy / sp * 12); c.stroke(); } + c.save(); c.translate(Math.round(tw.x), Math.round(tw.y - tw.r * 0.9 + bob)); if (big && tw.face < 0) c.scale(-1, 1); c.drawImage(art, -w / 2, -w / 2 - 2); c.restore(); + }]); + } + } + // ---- Famine: a gaunt rider on a hobby-horse-like steed; phase 2 only the hooded head floats + function famineArt(flash, step, rear) { + return cached('famine' + flash + step + rear, 120, 110, (c) => { + c.translate(60, 92); + const hide = flash ? '#a7a69a' : '#6f6e62', dark = flash ? '#7d7b70' : '#4a4940', cloak = flash ? '#8a9a86' : '#53614f'; + c.strokeStyle = INK; c.lineWidth = 3; + const legs = step ? [[-18, 0, -24], [-8, 0, -4], [12, 0, 6], [22, 0, 26]] : [[-18, 0, -12], [-8, 0, -14], [12, 0, 16], [22, 0, 16]]; + for (const [x, , fx] of legs) { c.beginPath(); c.moveTo(x, -26); c.lineTo(fx, rear && x > 0 ? -8 : 0); c.stroke(); } + c.save(); if (rear) c.rotate(-0.18); + ell(c, 0, -32, 30, 13, hide, INK, 2.5); // ribby horse body + c.strokeStyle = 'rgba(30,25,20,0.55)'; c.lineWidth = 1.5; for (let i = -2; i <= 2; i++) { c.beginPath(); c.moveTo(i * 8, -40); c.lineTo(i * 8 + 2, -24); c.stroke(); } + c.fillStyle = hide; c.strokeStyle = INK; c.lineWidth = 2.5; // neck and long skull + c.beginPath(); c.moveTo(22, -38); c.lineTo(36, -58); c.lineTo(52, -56); c.lineTo(54, -48); c.lineTo(38, -44); c.lineTo(28, -30); c.closePath(); c.fill(); c.stroke(); + ell(c, 44, -54, 2.2, 2.2, '#e8d070'); + c.fillStyle = cloak; c.beginPath(); c.moveTo(-14, -40); c.lineTo(-6, -78); c.lineTo(10, -80); c.lineTo(14, -40); c.closePath(); c.fill(); c.stroke(); // rider + ell(c, 3, -84, 10, 11, dark, INK, 2.5); + ell(c, 7, -84, 5, 6, '#1a1712'); + for (const x of [4, 9]) ell(c, x, -85, 1.4, 1.4, '#f0e090'); + c.restore(); + }); + } + function famineHeadArt(flash, open) { + return cached('famhead' + flash + open, 56, 56, (c) => { + c.translate(28, 28); + ell(c, 0, 0, 19, 20, flash ? '#cfcbbd' : '#a9a595', INK, 2.5); + c.fillStyle = flash ? '#7f8c7b' : '#53614f'; c.beginPath(); c.arc(0, -2, 21, Math.PI * 1.05, Math.PI * 1.95); c.lineTo(15, -2); c.lineTo(-15, -2); c.closePath(); c.fill(); c.strokeStyle = INK; c.lineWidth = 2; c.stroke(); + for (const x of [-7, 7]) { ell(c, x, 2, 4, 5, '#1a1712'); ell(c, x, 2, 1.4, 1.4, '#f0e090'); } + ell(c, 0, 12, 6, open ? 5 : 2, '#3a1416', INK, 1.5); + }); + } + function drawFamine(c, g, items) { + const b = g.boss, t = g.t, p = g.player; + if (b.dead) return; + if (b.phase === 1 && (b.st === 'rear' || b.st === 'charge' || b.st === 'brake')) { // the charge lane = his hit band + const band = M.famineBand(b), a = b.st === 'rear' ? 0.12 + 0.1 * Math.sin(t * 0.8) : 0.14; // exactly the hit band for Isaac's feet + c.fillStyle = `rgba(210,60,50,${a})`; c.fillRect(R.x0, b.y - band, R.x1 - R.x0, band * 2); + c.strokeStyle = 'rgba(230,80,60,0.55)'; c.lineWidth = 1.5; c.setLineDash([8, 6]); + c.beginPath(); c.moveTo(R.x0, b.y - band); c.lineTo(R.x1, b.y - band); c.moveTo(R.x0, b.y + band); c.lineTo(R.x1, b.y + band); c.stroke(); c.setLineDash([]); + } + if (b.off) return; + const flash = t - b.flash < 3; + if (b.phase === 1) { + const step = Math.floor(t / (b.st === 'charge' ? 4 : 10)) % 2, art = famineArt(flash, step, b.st === 'rear' ? 1 : 0); + items.push([b.y, () => { + shadow(c, b.x, b.y + 4, 34, 8); + if (b.st === 'charge') { c.strokeStyle = 'rgba(220,210,190,0.35)'; c.lineWidth = 2; for (let i = 0; i < 4; i++) { const y = b.y - 40 + i * 12; c.beginPath(); c.moveTo(b.x - b.dir * (40 + i * 6), y); c.lineTo(b.x - b.dir * (80 + i * 10), y); c.stroke(); } } + if (b.st === 'summon') ell(c, b.x + b.face * 34, b.y - 10, 8 + (26 - b.timer) * 0.3, 8 + (26 - b.timer) * 0.3, 'rgba(120,80,60,0.3)'); + c.save(); c.translate(Math.round(b.x), Math.round(b.y + 4)); if (b.face < 0) c.scale(-1, 1); c.drawImage(art, -60, -92); c.restore(); + }]); + } else { + const art = famineHeadArt(flash, b.st === 'hstop' ? 1 : 0), bob = Math.sin(t * 0.09) * 3; + items.push([b.y, () => { shadow(c, b.x, b.y + 16, 15, 5, 0.3); c.drawImage(art, Math.round(b.x - 28), Math.round(b.y - 30 + bob)); }]); + } + } + function drawPooter(c, g, q) { + const t = g.t, flap = (t + q.id * 3) % 6 < 3, y = q.y - 16 + Math.sin((t + q.id * 7) * 0.12) * 2, flash = t - q.flash < 3; + shadow(c, q.x, q.y + 2, 7, 2.5, 0.25); + c.save(); c.translate(Math.round(q.x), Math.round(y)); + c.fillStyle = 'rgba(235,235,245,0.6)'; + for (const sd of [-1, 1]) { c.beginPath(); c.ellipse(sd * 8, flap ? -6 : -3, 7, flap ? 4 : 6, sd * 0.5, 0, TAU); c.fill(); } + ell(c, 0, 0, 9, 8, flash ? '#c9a090' : '#7a4a3a', INK, 1.8); + ell(c, -3, -2, 2.4, 2.4, '#f6efe4'); ell(c, 3, -2, 2.4, 2.4, '#f6efe4'); ell(c, -2.6, -1.6, 1.1, 1.1, '#1c1210'); ell(c, 3.4, -1.6, 1.1, 1.1, '#1c1210'); + ell(c, 0, 4, 2.5, q.wind > 0 ? 2.6 : 1.2, '#3a1416'); + c.restore(); + } + // ---- Envy: a green scowling head, smaller and faster each split + function envyArt(gen, flash) { + const R = M.bosses.envy.r[gen], w = R * 2 + 8; + return cached('envy' + gen + flash, w, w, (c) => { + c.translate(w / 2, w / 2); + ell(c, 0, 0, R, R * 0.95, flash ? '#9fd08a' : '#6c9a55', INK, gen > 2 ? 1.8 : 2.5); + ell(c, R * 0.25, R * 0.3, R * 0.7, R * 0.45, flash ? '#86b672' : '#557d44'); + c.strokeStyle = 'rgba(40,70,30,0.6)'; c.lineWidth = 1.2; c.beginPath(); c.moveTo(-R * 0.6, -R * 0.4); c.lineTo(-R * 0.3, -R * 0.15); c.lineTo(-R * 0.45, R * 0.1); c.stroke(); // vein + const ex = R * 0.38, er = Math.max(1.6, R * 0.17); + for (const sx of [-1, 1]) { + ell(c, sx * ex, -R * 0.12, er, er, '#f4e8c0', INK, 1.2); ell(c, sx * ex, -R * 0.08, er * 0.5, er * 0.5, '#1c1210'); + c.strokeStyle = INK; c.lineWidth = Math.max(1.2, R * 0.08); c.beginPath(); c.moveTo(sx * (ex + er + 1), -R * 0.12 - er - 2); c.lineTo(sx * (ex - er), -R * 0.12 - er * 0.3); c.stroke(); + } + c.fillStyle = '#2a3a1e'; c.beginPath(); c.ellipse(0, R * 0.45, R * 0.42, R * 0.16, 0, 0, TAU); c.fill(); + c.fillStyle = '#e8e4d0'; for (let i = -2; i <= 2; i++) c.fillRect(i * R * 0.14 - R * 0.05, R * 0.37, R * 0.1, R * 0.08); + }); + } + function drawEnvy(c, g, items) { + const b = g.boss, t = g.t; + for (const h of b.heads) { + const art = envyArt(h.g, t - h.flash < 3), w = art.width, bob = Math.sin((t + h.id * 13) * 0.14) * 2, born = t - h.born < 8 ? 0.6 + 0.05 * (t - h.born) : 1; + items.push([h.y, () => { shadow(c, h.x, h.y + 6, h.r * 0.85, h.r * 0.3, 0.32); c.save(); c.translate(Math.round(h.x), Math.round(h.y - h.r * 0.6 + bob)); c.scale(born, born); c.drawImage(art, -w / 2, -w / 2); c.restore(); }]); + } + } + function drawFly(c, g, f) { + const t = g.t, flap = (t + f.id * 3) % 4 < 2, red = f.big || Math.floor((t + f.id * 5) / 8) % 2 === 0; + const s = f.big ? 1.45 : 1, y = f.y - 14 + Math.sin((t + f.id * 11) * 0.3) * 2; + shadow(c, f.x, f.y + 2, 5 * s, 2 * s, 0.25); + c.save(); c.translate(Math.round(f.x), Math.round(y)); c.scale(s, s); + c.fillStyle = 'rgba(235,235,245,0.6)'; + for (const sd of [-1, 1]) { c.beginPath(); c.ellipse(sd * 5, flap ? -4 : -2, 5, flap ? 3 : 4.5, sd * (flap ? 0.6 : 0.2), 0, TAU); c.fill(); } + const flash = t - f.flash < 4; + ell(c, 0, 0, 5.5, 4.6, flash ? '#ffffff' : red ? '#8e2626' : '#2a2222', INK, 1.5); + ell(c, -1.5, -1.2, 1.4, 1.2, red ? '#f0a0a0' : '#8a8a8a'); + c.restore(); + } + function drawPoop(c, x, y, stage) { // stage 4 = intact .. 1 = almost gone + const k = 0.45 + 0.55 * stage / 4; + shadow(c, x, y + 14, 16 * k, 5 * k, 0.3); + c.save(); c.translate(x, y + 16); c.scale(k, k); + c.strokeStyle = INK; c.lineWidth = 2; + for (const [yy, w, col] of [[-6, 19, '#6e4729'], [-16, 14, '#7f5532'], [-25, 9, '#8c6038']]) { c.fillStyle = col; c.beginPath(); c.ellipse(0, yy, w, 7, 0, 0, TAU); c.fill(); c.stroke(); } + c.beginPath(); c.moveTo(-2, -31); c.quadraticCurveTo(4, -38, 1, -42); c.quadraticCurveTo(6, -36, 3, -30); c.fillStyle = '#8c6038'; c.fill(); c.stroke(); + ell(c, -6, -18, 4, 2, 'rgba(255,220,180,0.25)'); + c.restore(); + } + function drawRock(c, x, y) { + shadow(c, x, y + 14, 18, 6, 0.35); + c.fillStyle = '#7d6f66'; c.strokeStyle = INK; c.lineWidth = 2; + c.beginPath(); c.moveTo(x - 18, y + 12); c.lineTo(x - 15, y - 8); c.lineTo(x - 2, y - 16); c.lineTo(x + 14, y - 10); c.lineTo(x + 18, y + 10); c.closePath(); c.fill(); c.stroke(); + c.fillStyle = '#9a8c82'; c.beginPath(); c.moveTo(x - 12, y - 6); c.lineTo(x - 2, y - 13); c.lineTo(x + 8, y - 8); c.lineTo(x - 4, y - 3); c.closePath(); c.fill(); + } + function drawBomb(c, g, bm) { + const t = g.t, blink = bm.fuse < 30 ? (Math.floor(t / 3) % 2) : (Math.floor(t / 8) % 2), s = 1 + (bm.fuse < 30 ? 0.08 * Math.sin(t * 1.2) : 0); + shadow(c, bm.x, bm.y + 6, 10, 4); + c.save(); c.translate(bm.x, bm.y - 6); c.scale(s, s); + ell(c, 0, 0, 10, 10, blink && bm.fuse < 30 ? '#8a5048' : '#3b3e46', INK, 2); + ell(c, -3, -4, 3.5, 2.5, '#7a808c'); + c.strokeStyle = '#6b5a40'; c.lineWidth = 2; c.beginPath(); c.moveTo(2, -9); c.quadraticCurveTo(6, -15, 3, -18); c.stroke(); + ell(c, 3, -19, 2.6 + blink, 2.6 + blink, '#ffd25a'); + c.restore(); + } + function drawReward(c, g) { + if (!g.reward) return; + const k = Math.min(1, (g.t - g.reward.t) / 18), x = g.reward.x, y = g.reward.y; + // trapdoor below the pedestal, pedestal with a glowing item (cosmetic) + c.globalAlpha = k; + c.fillStyle = '#0a0605'; c.strokeStyle = '#4a3020'; c.lineWidth = 3; + c.beginPath(); c.ellipse(x, y + 66, 22, 12, 0, 0, TAU); c.fill(); c.stroke(); + shadow(c, x, y + 14, 16, 5); + c.fillStyle = '#8a7d74'; c.strokeStyle = INK; c.lineWidth = 2; + c.fillRect(x - 13, y - 6, 26, 18); c.strokeRect(x - 13, y - 6, 26, 18); + c.fillStyle = '#a49890'; c.fillRect(x - 16, y - 10, 32, 6); c.strokeRect(x - 16, y - 10, 32, 6); + const fy = y - 26 + Math.sin(g.t * 0.12) * 3; + const glow = c.createRadialGradient(x, fy, 2, x, fy, 22); glow.addColorStop(0, 'rgba(255,240,190,0.7)'); glow.addColorStop(1, 'rgba(255,240,190,0)'); + c.fillStyle = glow; c.fillRect(x - 24, fy - 24, 48, 48); + txt(c, '?', x, fy + 6, 18, '#fff4cc', 'center'); + c.globalAlpha = 1; + } + + // ---------------- projectiles & fx ---------------- + function tearZ(q) { const k = q.age / q.life; return k < 0.72 ? 15 : 15 * Math.max(0, 1 - Math.pow((k - 0.72) / 0.28, 2)); } + function drawTears(c, g) { + const yellow = g.stats.yellow, homing = g.stats.homing, pierce = g.stats.pierce; + const fill = yellow ? '#f1dc6a' : homing ? '#c9a8ff' : '#a8dcff', rim = yellow ? '#7a6a1a' : homing ? '#4b2f8a' : '#2d5d80'; + for (const q of g.tears) shadow(c, q.x, q.y + 2, q.r * 0.8, q.r * 0.32, 0.25); + for (const q of g.tears) { + const z = tearZ(q), x = q.x, y = q.y - z; + if (pierce) { // triangular piercing tear + const a = Math.atan2(q.vy, q.vx); + c.save(); c.translate(x, y); c.rotate(a); + c.fillStyle = '#ffc2c8'; c.strokeStyle = '#7a2a35'; c.lineWidth = 1.5; + c.beginPath(); c.moveTo(q.r + 3, 0); c.lineTo(-q.r, -q.r * 0.75); c.lineTo(-q.r * 0.5, 0); c.lineTo(-q.r, q.r * 0.75); c.closePath(); c.fill(); c.stroke(); + c.restore(); + continue; + } + ell(c, x, y, q.r, q.r, fill, rim, 1.5); + ell(c, x - q.r * 0.35, y - q.r * 0.35, q.r * 0.32, q.r * 0.28, 'rgba(255,255,255,0.85)'); + if (g.stats.shield) { c.strokeStyle = 'rgba(200,240,255,0.7)'; c.lineWidth = 1; c.beginPath(); c.arc(x, y, q.r + 2.5, 0, TAU); c.stroke(); } + } + } + function drawShots(c, g) { + for (const s of g.shots) shadow(c, s.x, s.y + 2, s.r * 0.8, s.r * 0.3, 0.25); + for (const s of g.shots) { + const y = s.y - 12 - Math.sin(Math.min(1, s.age / s.life) * Math.PI) * 6; + ell(c, s.x, y, s.r, s.r, s.big ? '#9e2329' : '#b3363a', '#3a0b10', 1.5); + ell(c, s.x - s.r * 0.35, y - s.r * 0.35, s.r * 0.35, s.r * 0.28, 'rgba(255,190,180,0.8)'); + } + } + function drawFx(c, g) { + const t = g.t; + for (const f of g.fx) { + const age = t - f.t; + if (age < 0) continue; + if (f.k === 'splash') { + if (age > 10) continue; + const k = age / 10, col = f.c === 2 ? '220,245,255' : f.c === 1 ? '190,225,255' : '160,205,240'; + c.strokeStyle = `rgba(${col},${1 - k})`; c.lineWidth = 2; c.beginPath(); c.ellipse(f.x, f.y - 6, 4 + k * 9, 2 + k * 5, 0, 0, TAU); c.stroke(); + for (let i = 0; i < 4; i++) { const a = i * TAU / 4 + hash(f.t, i) * 1.2; ell(c, f.x + Math.cos(a) * k * 12, f.y - 8 + Math.sin(a) * k * 7 - k * 4, 1.6, 1.6, `rgba(${col},${1 - k})`); } + } else if (f.k === 'drop') { + if (age > 10) continue; + const k = age / 10; c.strokeStyle = `rgba(170,40,45,${0.8 - 0.8 * k})`; c.lineWidth = 2; c.beginPath(); c.ellipse(f.x, f.y, 3 + 7 * k, 1.5 + 3 * k, 0, 0, TAU); c.stroke(); + } else if (f.k === 'hit') { + if (age > 5) continue; + ell(c, f.x, f.y - 18, 9 - age, 9 - age, `rgba(255,255,255,${0.55 - age * 0.1})`); + } else if (f.k === 'pop') { + if (age > 18) continue; + const k = age / 18, n = f.big ? 8 : 5; + for (let i = 0; i < n; i++) { const a = hash(f.t + i, f.x | 0) * TAU, d = (f.big ? 26 : 14) * k; ell(c, f.x + Math.cos(a) * d, f.y - 12 + Math.sin(a) * d * 0.7, (f.big ? 4 : 2.5) * (1 - k), (f.big ? 4 : 2.5) * (1 - k), f.big ? '#c49a70' : '#5a3030'); } + } else if (f.k === 'boom') { + if (age > 24) continue; + const k = age / 24, r = f.r * (0.4 + 0.8 * k); + const gr = c.createRadialGradient(f.x, f.y - 10, 2, f.x, f.y - 10, r); + gr.addColorStop(0, `rgba(255,240,180,${0.9 * (1 - k)})`); gr.addColorStop(0.5, `rgba(255,150,60,${0.65 * (1 - k)})`); gr.addColorStop(1, 'rgba(120,40,20,0)'); + c.fillStyle = gr; c.beginPath(); c.ellipse(f.x, f.y - 10, r, r * 0.8, 0, 0, TAU); c.fill(); + for (let i = 0; i < 10; i++) { const a = hash(f.t, i * 7) * TAU, d = f.r * 1.1 * k; ell(c, f.x + Math.cos(a) * d, f.y - 10 + Math.sin(a) * d * 0.7, 3 * (1 - k), 3 * (1 - k), '#3a2a20'); } + } else if (f.k === 'quake') { + if (age > 20) continue; + const k = age / 20; c.strokeStyle = `rgba(200,170,140,${0.6 * (1 - k)})`; c.lineWidth = 3; c.beginPath(); c.ellipse(f.x, f.y, 30 + 50 * k, 12 + 20 * k, 0, 0, TAU); c.stroke(); + } else if (f.k === 'chip' || f.k === 'poopgone') { + if (age > 14) continue; + const k = age / 14, n = f.k === 'chip' ? 3 : 7; + for (let i = 0; i < n; i++) { const a = hash(f.t + i * 3, f.y | 0) * TAU; ell(c, f.x + Math.cos(a) * 16 * k, f.y + 6 + Math.sin(a) * 8 * k - 10 * k * (1 - k), 3 * (1 - k), 3 * (1 - k), '#6e4729'); } + } else if (f.k === 'ouch') { + if (age > 32) continue; + c.globalAlpha = 1 - age / 32; heartPath(c, f.x, f.y - age * 0.5, 6); c.fillStyle = '#d8263a'; c.fill(); c.globalAlpha = 1; + txt(c, '−' + (f.v === 1 ? '½' : f.v / 2), f.x + 9, f.y - age * 0.5 + 4, 12, '#ffd8d0'); + } + } + } + + // ---------------- HUD ---------------- + function heartIcon(c, x, y, fill) { // fill: 0 empty, 1 half, 2 full + heartPath(c, x, y, 9); c.fillStyle = '#3a1418'; c.fill(); + if (fill) { + c.save(); heartPath(c, x, y, 9); c.clip(); c.fillStyle = '#d8263a'; c.fillRect(x - 12, y - 12, fill === 2 ? 24 : 12, 24); + c.fillStyle = 'rgba(255,200,200,0.55)'; c.beginPath(); c.ellipse(x - 4, y - 2, 2.6, 2, -0.5, 0, TAU); c.fill(); c.restore(); + } + heartPath(c, x, y, 9); c.strokeStyle = '#120808'; c.lineWidth = 2; c.stroke(); + } + const ICON = { + pentagram(c) { c.strokeStyle = '#c8303a'; c.lineWidth = 2; c.beginPath(); c.arc(0, 0, 10, 0, TAU); c.stroke(); c.beginPath(); for (let i = 0; i < 5; i++) { const a = -Math.PI / 2 + i * TAU * 2 / 5; c.lineTo(Math.cos(a) * 9, Math.sin(a) * 9); } c.closePath(); c.stroke(); }, + twenty_twenty(c) { for (const s of [-1, 1]) { ell(c, s * 5.5, 0, 5, 5, '#f4f0e8', INK, 1.5); ell(c, s * 5.5, 0.5, 2, 2, '#1c1210'); } c.strokeStyle = '#d6b34a'; c.lineWidth = 1.5; c.beginPath(); c.moveTo(-1, 0); c.lineTo(1, 0); c.stroke(); }, + cupids_arrow(c) { c.strokeStyle = '#d9c7a0'; c.lineWidth = 2; c.beginPath(); c.moveTo(-10, 8); c.lineTo(7, -7); c.stroke(); heartPath(c, 7, -7, 4.5); c.fillStyle = '#e05a78'; c.fill(); c.fillStyle = '#e8e2d0'; c.fillRect(-11, 6, 4, 4); }, + speed_ball(c) { c.save(); c.rotate(-0.7); c.fillStyle = '#d8e4ec'; c.fillRect(-9, -3.5, 14, 7); c.fillStyle = '#4fa0e8'; c.fillRect(-7, -2.5, 9, 5); c.strokeStyle = INK; c.lineWidth = 1.3; c.strokeRect(-9, -3.5, 14, 7); c.fillStyle = '#9aa'; c.fillRect(5, -1, 6, 2); c.fillRect(-12, -4, 3, 8); c.restore(); }, + inner_eye(c) { ell(c, 0, 0, 10, 7, '#f4f0e8', INK, 1.5); for (const x of [-4, 0, 4]) ell(c, x, 0, 1.8, 1.8, '#1c1210'); }, + spoon_bender(c) { c.strokeStyle = '#b694f0'; c.lineWidth = 2.5; c.beginPath(); c.moveTo(-8, 8); c.quadraticCurveTo(-2, 2, 2, -2); c.quadraticCurveTo(6, -4, 6, -8); c.stroke(); ell(c, 6, -8, 3.5, 4.5, '#cfc4e8', INK, 1.2); }, + sad_onion(c) { ell(c, 0, 2, 9, 8, '#e8d6a8', INK, 1.5); c.fillStyle = '#7aa04a'; c.beginPath(); c.moveTo(-2, -6); c.lineTo(0, -12); c.lineTo(2, -6); c.fill(); for (const x of [-3.5, 3.5]) ell(c, x, 1, 1.4, 1.6, '#1c1210'); c.strokeStyle = INK; c.lineWidth = 1.2; c.beginPath(); c.arc(0, 7, 2.5, Math.PI * 1.15, Math.PI * 1.85); c.stroke(); }, + growth_hormones(c) { ICON.speed_ball(c); c.fillStyle = 'rgba(120,200,90,0.8)'; c.save(); c.rotate(-0.7); c.fillRect(-7, -2.5, 9, 5); c.restore(); }, + number_one(c) { c.fillStyle = '#ecd250'; c.beginPath(); c.moveTo(0, -10); c.quadraticCurveTo(8, 2, 0, 9); c.quadraticCurveTo(-8, 2, 0, -10); c.fill(); c.strokeStyle = INK; c.lineWidth = 1.3; c.stroke(); }, + moms_lipstick(c) { c.fillStyle = '#c42a4a'; c.fillRect(-3, -10, 6, 8); c.fillStyle = '#d0b060'; c.fillRect(-4, -2, 8, 10); c.strokeStyle = INK; c.lineWidth = 1.2; c.strokeRect(-4, -2, 8, 10); }, + polyphemus(c) { ell(c, 0, 0, 10, 10, '#f4f0e8', INK, 1.5); ell(c, 0, 0, 5, 5, '#3d6db0'); ell(c, 0, 0, 2.4, 2.4, '#100c0a'); }, + mutant_spider(c) { c.strokeStyle = INK; c.lineWidth = 1.5; for (let i = 0; i < 4; i++) { c.beginPath(); c.moveTo(-3, -2 + i * 2); c.lineTo(-10, -6 + i * 4); c.moveTo(3, -2 + i * 2); c.lineTo(10, -6 + i * 4); c.stroke(); } ell(c, 0, 1, 5, 6, '#3a2e2a', INK, 1.2); for (const x of [-2, 2]) ell(c, x, -1, 1.2, 1.2, '#d84040'); }, + lost_contact(c) { ell(c, 0, 0, 9, 9, 'rgba(180,220,255,0.35)', '#9ac8f0', 1.5); ell(c, -3, -3, 2.5, 2, 'rgba(255,255,255,0.8)'); }, + rubber_cement(c) { c.fillStyle = '#c9a060'; c.fillRect(-6, -4, 12, 13); c.fillStyle = '#7a5a30'; c.fillRect(-3, -10, 6, 6); c.strokeStyle = INK; c.lineWidth = 1.2; c.strokeRect(-6, -4, 12, 13); }, + my_reflection(c) { ell(c, 0, 0, 8, 10, '#bcd8e8', '#7a6040', 2.5); ell(c, -2, -3, 2, 3, 'rgba(255,255,255,0.7)'); }, + breakfast(c) { ell(c, 0, 2, 10, 6, '#e8e8e0', INK, 1.3); ell(c, 0, 1, 5, 3.5, '#f8f6ee'); ell(c, 0, 1, 2.4, 2, '#f0c030'); }, + the_wafer(c) { ell(c, 0, 0, 9, 9, '#f0e8d0', INK, 1.3); c.strokeStyle = '#c8b890'; c.lineWidth = 1.5; c.beginPath(); c.moveTo(0, -5); c.lineTo(0, 5); c.moveTo(-4, -1); c.lineTo(4, -1); c.stroke(); } + }; + function fit(c, s, w, font) { c.font = font; let out = s; while (out.length > 1 && c.measureText(out).width > w) out = out.slice(0, -1); return out; } + function itemIcon(id) { return cached('item' + id, 28, 28, (c) => { c.translate(14, 14); (ICON[id] || ICON.lost_contact)(c); }); } + function statIcon(k) { + return cached('stat' + k, 16, 16, (c) => { + c.translate(8, 8); c.strokeStyle = '#e8dcc4'; c.fillStyle = '#e8dcc4'; c.lineWidth = 1.6; + if (k === 0) { c.beginPath(); c.moveTo(-6, 4); c.lineTo(-2, -4); c.lineTo(2, -4); c.lineTo(1, 1); c.lineTo(6, 2); c.lineTo(6, 5); c.lineTo(-6, 5); c.closePath(); c.fill(); } + else if (k === 1) { for (const [x, y] of [[-4, -2], [1, -5], [3, 2]]) { c.beginPath(); c.moveTo(x, y - 3); c.quadraticCurveTo(x + 3, y + 1, x, y + 3); c.quadraticCurveTo(x - 3, y + 1, x, y - 3); c.fill(); } } + else if (k === 2) { c.beginPath(); c.moveTo(-5, 5); c.lineTo(5, -5); c.stroke(); c.beginPath(); c.moveTo(-6, 1); c.lineTo(-1, 6); c.stroke(); } + else if (k === 3) { c.beginPath(); c.arc(-1, 0, 6, -1.3, 1.3); c.stroke(); c.beginPath(); c.moveTo(1, -6); c.lineTo(1, 6); c.stroke(); c.beginPath(); c.moveTo(-6, 0); c.lineTo(6, 0); c.stroke(); } + else { c.beginPath(); c.arc(2, 0, 4, 0, TAU); c.fill(); c.beginPath(); c.moveTo(-7, -2); c.lineTo(-3, -2); c.moveTo(-7, 2); c.lineTo(-3, 2); c.stroke(); } + }); + } + const TIER_NAME = d => { const T = M.tiers; return Math.abs(d - T.easy) < 1e-9 ? 'Easy' : Math.abs(d - T.normal) < 1e-9 ? 'Normal' : Math.abs(d - T.hard) < 1e-9 ? 'Hard' : 'Custom'; }; + function drawHud(c, g) { + const p = g.player, st = g.stats, t = g.t, def = M.cases.find(q => q.id === g.id); + // hearts + bombs (top-left) + for (let i = 0; i < p.maxHp / 2; i++) heartIcon(c, 22 + i * 22, 18, Math.max(0, Math.min(2, p.hp - i * 2))); + const bx = 18, by = 37; + ell(c, bx, by, 6, 6, '#3b3e46', INK, 1.5); c.strokeStyle = '#ffd25a'; c.lineWidth = 1.5; c.beginPath(); c.moveTo(bx + 2, by - 5); c.lineTo(bx + 4, by - 8); c.stroke(); + txt(c, '×' + p.bombs, bx + 10, by + 5, 12, '#e8dcc4'); + // stats (left panel, Found-HUD style) + const rows = [['Speed', st.speed.toFixed(2)], ['Fire rate', st.fireRate.toFixed(2)], ['Damage', st.damage.toFixed(2)], ['Range', st.range.toFixed(2)], ['Shot speed', st.shotSpeed.toFixed(2)]]; + txt(c, 'Stats', 8, 74, 11, '#bfae90'); + rows.forEach(([name, v], i) => { const y = 96 + i * 30; c.drawImage(statIcon(i), 6, y - 12); txt(c, v, 25, y, 12, '#f0e6d2'); txt(c, name, 25, y + 12, 9, '#8f826e', 'left', 'normal'); }); + const flags = [st.multi > 1 ? st.multi + ' shots' : '', st.pierce ? 'Piercing' : '', st.homing ? 'Homing' : '', st.bounce ? 'Bouncing' : '', st.boomerang ? 'Boomerang' : '', st.shield ? 'Shielding' : ''].filter(Boolean); + flags.forEach((s, i) => txt(c, s, 8, 262 + i * 15, 11, '#a8d4ff')); + // items (right panel) + txt(c, 'Items', 783, 74, 11, '#bfae90'); + g.items.forEach((id, i) => { + const y = 84 + i * 44; + c.fillStyle = 'rgba(255,240,210,0.06)'; c.fillRect(780, y, 70, 40); + c.drawImage(itemIcon(id), 781, y + 2); + const it = M.items[id]; + txt(c, fit(c, it.name, 46, 'bold 9px ' + FONT), 808, y + 18, 9, '#f0e6d2'); txt(c, fit(c, 'Item #' + it.no, 68, 'normal 8px ' + FONT), 781, y + 36, 8, '#8f826e', 'left', 'normal'); + }); + // timer, Hz, tier (top-right) + const sec = t / 60, mm = Math.floor(sec / 60), ss = (sec % 60).toFixed(1).padStart(4, '0'); + txt(c, mm + ':' + ss, 846, 20, 15, '#f2f2f2', 'right'); + txt(c, M.hz + 'Hz · ' + TIER_NAME(g.d) + ' d=' + g.d.toFixed(2), 846, 37, 10, '#bfb4a0', 'right', 'normal'); + // boss bar (bottom centre) + const bw = 340, x0 = 427 - bw / 2, y0 = 456, frac = g.bossMax ? g.bossHp() / g.bossMax : 0; + c.fillStyle = '#0c0606'; c.fillRect(x0 - 3, y0 - 3, bw + 6, 18); + c.fillStyle = '#2a0e10'; c.fillRect(x0, y0, bw, 12); + c.fillStyle = Math.floor(t / 6) % 2 && t - (g.boss.flash || -99) < 6 ? '#ff6a6a' : '#c0202a'; c.fillRect(x0, y0, bw * frac, 12); + c.fillStyle = 'rgba(255,200,200,0.25)'; c.fillRect(x0, y0, bw * frac, 3); + txt(c, def.name, x0 - 10, y0 + 11, 12, '#f0e2c8', 'right'); + txt(c, Math.ceil(g.bossHp()) + ' / ' + g.bossMax, x0 + bw / 2, y0 + 10.5, 10, '#ffe8e0', 'center'); + let extra = ''; + if (g.kind === 'larry_jr') extra = g.boss.bodies.length + ' bodies · ' + g.boss.bodies.reduce((a, b) => a + b.segs.length, 0) + ' segments'; + else if (g.kind === 'duke_of_flies') extra = 'Flies ' + g.flies.length + ' / 12'; + else if (g.kind === 'monstro') extra = ({ track: 'Jumping · shadow tracks you', lock: 'About to land!', fall: 'Landing!', cough: 'Charging spit' })[g.boss.st] || ''; + else if (g.kind === 'gemini') { const [C, S] = g.boss.twins; extra = (C.dead ? 'Big one ✕' : 'Big one ' + Math.ceil(C.hp)) + ' · ' + (S.dead ? 'Little one ✕' : 'Little one ' + Math.ceil(S.hp)) + (g.boss.attached ? ' · Tethered' : S.dead ? '' : ' · Little one enraged!'); } + else if (g.kind === 'famine') extra = g.boss.phase === 1 ? (g.boss.st === 'rear' || g.boss.st === 'charge' ? 'Charging!' : 'Phase 1 · Mounted') + ' · Pooters ' + g.flies.length + '/2' : 'Phase 2 · Head'; + else if (g.kind === 'envy') { const gmin = g.boss.heads.reduce((m, h) => Math.min(m, h.g), 9); extra = 'Heads ' + g.boss.heads.length + (gmin < 4 ? ' · ' + ['Large', 'Medium', 'Small', 'Tiny'][gmin] : ''); } + if (extra) txt(c, extra, x0 + bw + 10, y0 + 11, 11, '#f0c8a0'); + txt(c, 'WASD Move · Arrows / IJKL Shoot · E Bomb', 427, 16, 10, '#8f826e', 'center', 'normal'); + // intro banner (Isaac VS boss); every boss waits until it has faded (first action at tick 80) + if (t < 75) { + const a = t < 55 ? 1 : 1 - (t - 55) / 20; + c.globalAlpha = a; + c.fillStyle = 'rgba(10,6,4,0.72)'; c.fillRect(R.x0, 214, R.x1 - R.x0, 64); + c.fillStyle = '#7a2a24'; c.fillRect(R.x0, 214, R.x1 - R.x0, 2); c.fillRect(R.x0, 276, R.x1 - R.x0, 2); + txt(c, 'Isaac VS ' + def.name, 427, 248, 26, '#f6e8cc', 'center'); + txt(c, 'Starting items: ' + g.items.map(id => M.items[id].name).join(' + '), 427, 268, 11, '#d8c8a8', 'center', 'normal'); + c.globalAlpha = 1; + } + if (g.clearT >= 0 && !g.outcome) txt(c, 'Room cleared · Door open', 427, R.y0 + 24, 16, '#ffe6a0', 'center'); + } + function drawResult(c, g) { + if (!g.outcome) return; + const map = { win: ['Victory · Boss defeated', 'BOSS DEFEATED · ROOM CLEARED', '#ffd86a'], loss: ['Defeat · Isaac down', 'PLAYER DOWN', '#ff6a5a'], timeout: ['Time up', 'TIME UP', '#d8dde4'] }[g.outcome]; + c.fillStyle = 'rgba(8,5,4,0.66)'; c.fillRect(0, 200, 854, 84); + c.fillStyle = map[2]; c.fillRect(0, 200, 854, 2); c.fillRect(0, 282, 854, 2); + txt(c, map[0], 427, 240, 30, map[2], 'center'); + txt(c, map[1] + ' · ' + (g.t / 60).toFixed(2) + ' s · Hearts left: ' + (g.player.hp / 2) + ' · Hits taken: ' + g.stat.hitsTaken, 427, 268, 13, '#ece6dc', 'center', 'normal'); + } + + // Paint every cached sprite once, and blit it once (invisible) into the target canvas: the first blit of a new + // canvas uploads its texture, which otherwise cost a few ms the first time a sprite variant appears mid-fight. + const warmed = new WeakSet(); + function warm(c) { + warmed.add(c); + const all = [background()]; + for (const h of [true, false]) for (const f of [true, false]) for (const d of [-1, 0, 1]) all.push(segmentArt(h, f, d)); + for (const f of [true, false]) for (const p of [0, 1]) all.push(dukeArt(f, p)); + for (const f of [true, false]) { for (const r of ['contusion', 'suture']) for (const m of [0, 1]) all.push(twinArt(r, f, m)); for (const st of [0, 1]) for (const rr of [0, 1]) all.push(famineArt(f, st, rr)); for (const o of [0, 1]) all.push(famineHeadArt(f, o)); for (let gg = 0; gg < 4; gg++) all.push(envyArt(gg, f)); } + for (const id of M.itemIds) all.push(itemIcon(id)); + for (let i = 0; i < 5; i++) all.push(statIcon(i)); + c.save(); c.globalAlpha = 0.004; for (const img of all) c.drawImage(img, 0, 0, 1, 1); c.restore(); + } + + M.draw = function (g, c) { + if (!warmed.has(c)) warm(c); + c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = 'source-over'; c.imageSmoothingEnabled = true; + c.drawImage(background(), 0, 0); + const age = g.t - g.shake.t, sh = age >= 0 && age < 8 ? g.shake.a * (1 - age / 8) : 0; + const ox = Math.round(Math.sin(g.t * 12.9898) * sh), oy = Math.round(Math.cos(g.t * 78.233) * sh); + c.save(); c.translate(ox, oy); + drawDoors(c, g); + c.save(); c.beginPath(); c.rect(R.x0 - 2, R.y0 - 40, R.x1 - R.x0 + 4, R.y1 - R.y0 + 42); c.clip(); + drawReward(c, g); + const items = []; + for (let i = 0; i < g.cells.length; i++) { + const v = g.cells[i]; if (!v) continue; + const x = M.cellX(i % R.cols), y = M.cellY(Math.floor(i / R.cols)); + items.push([y + 10, () => (v === 1 ? drawRock(c, x, y) : drawPoop(c, x, y, v - 1))]); + } + for (const bm of g.bombs) items.push([bm.y, () => drawBomb(c, g, bm)]); + items.push([g.player.y, () => drawIsaac(c, g)]); + if (g.kind === 'monstro') items.push([g.boss.y + (g.boss.hidden ? -999 : 0), () => drawMonstro(c, g)]); + else if (g.kind === 'larry_jr') drawLarry(c, g, items); + else if (g.kind === 'gemini') drawGemini(c, g, items); + else if (g.kind === 'famine') drawFamine(c, g, items); + else if (g.kind === 'envy') drawEnvy(c, g, items); + else drawDuke(c, g, items); + for (const f of g.flies) items.push([f.y, () => (f.mode === 'pooter' ? drawPooter(c, g, f) : drawFly(c, g, f))]); + items.sort((a, b) => a[0] - b[0]); + for (const it of items) it[1](); + drawShots(c, g); + drawTears(c, g); + drawFx(c, g); + c.restore(); + c.restore(); + drawHud(c, g); + drawResult(c, g); + c.restore(); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/isaac_remake/game.js b/environments/games/web/games/isaac_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..59f154c91abfa89e76678e52f7264af327755e0d --- /dev/null +++ b/environments/games/web/games/isaac_remake/game.js @@ -0,0 +1,1247 @@ +/* The Binding of Isaac: Rebirth basement boss rooms. + * Pure simulation (Node + browser). + * 60 Hz ticks (Isaac's own logic runs at 30 updates/s: one Rebirth tick = 2 ticks here). + * 1 tile = 48 px (= 40 Isaac units); the 13 x 7 tile room is fully visible. + * Values marked "doc" come from the game wiki; + * everything else is a labelled approximation. + */ +(function (root) { + 'use strict'; + // bind builtins once: under Node's vm sandbox every global lookup goes through an interceptor (~30x slower); same values + const Math = root.Math, JSON = root.JSON, Object = root.Object, Array = root.Array, Set = root.Set, Error = root.Error; + const N = root.NativeBench, TAU = Math.PI * 2, DEG = Math.PI / 180; + const HZ = 60, TILE = 48; + const ROOM = { x0: 115, y0: 88, x1: 739, y1: 424, cols: 13, rows: 7 }; + const CX = (ROOM.x0 + ROOM.x1) / 2, CY = (ROOM.y0 + ROOM.y1) / 2; + const clamp = (v, a, b) => (v < a ? a : v > b ? b : v); + const hyp = Math.hypot; + + const M = root.IsaacGame = { + id: 'isaac_remake', version: 'isaac-basement@3', hz: HZ, maxSeconds: 300, dimension: '2d', + renderer: 'canvas-native', title: 'The Binding of Isaac · Basement Bosses', + // Public difficulty tiers: boss HP, aggression and damage all rise from easy to hard. + // hard = 0.8 is the same fight at a faster pace, not another source mode: the one rule gate at d >= 0.65 (M.chapter4) + // is the original's own Chapter 4+ damage rule (half-heart hits become full hearts); Larry Jr. uses the original's + // documented 13-segment arena there. Envy deliberately keeps the regular split at every tier (Super Envy is a separate + // mini-boss). Not scaled by tier on purpose: Duke flies (10 HP) and Famine's Pooters (8 HP) keep their source HP. + tiers: { easy: 0.2, normal: 0.5, hard: 0.8 }, + cases: [ + { id: 'isaac/monstro', name: 'Hopping Blob', en: 'Hopping Blob', items: ['pentagram', 'twenty_twenty'] }, + { id: 'isaac/larry_jr', name: 'Segment Worm', en: 'Segment Worm', items: ['polyphemus', 'speed_ball'] }, + { id: 'isaac/duke_of_flies', name: 'Swarm Host', en: 'Swarm Host', items: ['inner_eye', 'spoon_bender', 'growth_hormones', 'sad_onion'] }, + { id: 'isaac/gemini', name: 'Tethered Pair', en: 'Tethered Pair', items: ['mutant_spider', 'lost_contact', 'pentagram'] }, + { id: 'isaac/famine', name: 'Charging Rider', en: 'Charging Rider', items: ['cupids_arrow', 'inner_eye', 'pentagram', 'sad_onion'] }, + { id: 'isaac/envy', name: 'Splitting Head', en: 'Splitting Head', items: ['spoon_bender', 'twenty_twenty'] } + ], + controls: { + 'W A S D': 'Move in eight directions with momentum; aim independently', + 'J / K / L / Shift': 'Hold to fire tears left / down / right / up. If holding multiple directions, the most recently pressed wins. On the play page, arrow keys or I J K L also work', + 'E': 'Place a bomb (start with 1; explosion deals 60 damage and costs you 1 full heart if caught)', + 'Space': 'Use an active item (none in the default builds for this set)', + 'Q R Shift+… LMB RMB mouse': 'No effect (mouse aiming is unavailable)' + }, + // play-page key map, merged by _native/shell.js over its defaults: the arrow keys and I fire (as the controls text says); + // J / K / L / Shift already map to themselves. The simulation only ever sees the public 14-key names. + codeMap: { ArrowUp: 'Shift', ArrowLeft: 'J', ArrowDown: 'K', ArrowRight: 'L', KeyI: 'Shift' }, + room: ROOM, tile: TILE + }; + + // ---------------- Isaac (doc: 3 red heart containers, 1 bomb, 3.5 damage, 0 tears -> 10 tear delay, 23.75 range, 1.0 speed/shot speed) + const ISAAC = M.isaac = { + hearts: 6, bombs: 1, r: 11, + walk: 4.8 * TILE / HZ, // approx: 4.8 tiles/s at speed 1.0 (not documented; ~2.7 s to cross the 13-tile room) + accel: 0.26, friction: 0.72, // approx: short momentum, Isaac slides a little + inherit: 0.5, // approx: share of Isaac's velocity added to a new tear (doc: tear speed/direction depend on movement) + tearSpeed: 7.5 * TILE / HZ, // doc: shot speed 1.0 = 7.5 tiles/s (one tile per 4 Rebirth ticks) + baseLife: 52, // approx: 23.75 range ~ 6.5 tiles at shot speed 1.0 (Repentance equivalence) = 0.867 s + invPerHalf: 60, // doc: 1 s of invincibility per half heart taken (2 s for a full heart) + deadTicks: 50, bombFuse: 90, bombRadius: 84, bombDamage: 60 // doc: Rebirth bomb 60 damage, 1 full heart to Isaac; fuse/radius approx + }; + + // ---------------- items (doc values are the Rebirth ("nr") lines of each wiki page) + const ITEMS = M.items = { + sad_onion: { name: 'Quick Tears', en: 'Quick Tears', no: 1, desc: 'Tears +0.7 (faster fire rate)', apply(s) { s.tears += 0.7; } }, + number_one: { name: 'Yellow Rapid', en: 'Yellow Rapid', no: 6, desc: 'Tears +1.5, range −17.62 (yellow tears)', apply(s) { s.tears += 1.5; s.range -= 17.62; s.fall += 0.76; s.yellow = true; } }, + pentagram: { name: 'Damage Sigil', en: 'Damage Sigil', no: 51, desc: 'damage +1', apply(s) { s.dmgUps += 1; } }, + growth_hormones: { name: 'Strength Serum', en: 'Strength Serum', no: 70, desc: 'Damage +1, movement speed +0.4', apply(s) { s.dmgUps += 1; s.speed += 0.4; } }, + speed_ball: { name: 'Swift Pill', en: 'Swift Pill', no: 143, desc: 'Movement speed +0.3, shot speed +0.2', apply(s) { s.speed += 0.3; s.shotSpeed += 0.2; } }, + moms_lipstick: { name: 'Long Range', en: 'Long Range', no: 31, desc: 'Range +5.25', apply(s) { s.range += 5.25; s.fall += 0.5; } }, + polyphemus: { name: 'Giant Tear', en: 'Giant Tear', no: 169, desc: 'Giant tears: damage (D+4)×2, much slower fire rate; excess damage carries the tear through a kill', apply(s) { s.flat += 4; s.mult *= 2; s.slow = true; s.poly = true; } }, + inner_eye: { name: 'Triple Shot', en: 'Triple Shot', no: 2, desc: 'Fire 3 tears at once with a slower fire rate', apply(s) { s.inner = true; s.slow = true; } }, + mutant_spider: { name: 'Quad Shot', en: 'Quad Shot', no: 153, desc: 'Fire 4 tears at once with a slower fire rate', apply(s) { s.spider = true; s.slow = true; } }, + twenty_twenty: { name: 'Twin Shot', en: 'Twin Shot', no: 245, desc: 'Fire two tears at once without reducing fire rate', apply(s) { s.twin = true; } }, + cupids_arrow: { name: 'Pierce Tear', en: 'Pierce Tear', no: 48, desc: 'Piercing tears pass through enemies and poop without knockback', apply(s) { s.pierce = true; } }, + spoon_bender: { name: 'Homing Tear', en: 'Homing Tear', no: 3, desc: 'Homing tears', apply(s) { s.homing = true; } }, + lost_contact: { name: 'Shield Tear', en: 'Shield Tear', no: 213, desc: 'Tears cancel enemy projectiles; shot speed −0.15', apply(s) { s.shield = true; s.shotSpeed -= 0.15; } }, + rubber_cement: { name: 'Bounce Tear', en: 'Bounce Tear', no: 221, desc: 'Tears bounce off walls, obstacles, and enemies', apply(s) { s.bounce = true; } }, + my_reflection: { name: 'Boomerang Tear', en: 'Boomerang Tear', no: 5, desc: 'Boomerang tears: range +1.5, shot speed ×1.6', apply(s) { s.boomerang = true; s.range += 1.5; s.fall += 1; s.shotMul *= 1.6; } }, + breakfast: { name: 'Extra Heart', en: 'Extra Heart', no: 25, desc: 'One full red heart container', apply(s) { s.hearts += 2; } }, + the_wafer: { name: 'Damage Cap', en: 'Damage Cap', no: 108, desc: 'Incoming damage capped at half a heart', apply(s) { s.wafer = true; } } + }; + M.itemIds = Object.keys(ITEMS); + + // Rebirth stat formulas (wiki Damage / Tears / Range / Shot Speed / Speed pages) + function computeStats(items) { + const s = { dmgUps: 0, flat: 0, mult: 1, tears: 0, range: 23.75, fall: 0, shotSpeed: 1, shotMul: 1, speed: 1, hearts: ISAAC.hearts, + slow: false, inner: false, spider: false, twin: false, pierce: false, homing: false, bounce: false, boomerang: false, + shield: false, poly: false, wafer: false, yellow: false }; + for (const id of items) ITEMS[id].apply(s); + const damage = (3.5 * Math.sqrt(s.dmgUps * 1.2 + 1) + s.flat) * s.mult; // doc: Effective damage formula + const T = s.tears; + let delay; // doc: Tear Delay (Rebirth: floored, cap 5) + if (T >= 0) delay = Math.max(5, 16 - 6 * Math.sqrt(T * 1.3 + 1)); + else if (T > -0.77) delay = 16 - 6 * Math.sqrt(T * 1.3 + 1) - 6 * T; + else delay = 16 - 6 * T; + delay = Math.floor(delay); + if (s.slow) delay = Math.floor(delay * 2.1 + 3); // doc (nr): Inner Eye / Polyphemus / Mutant Spider (applied once: approx) + delay = Math.max(1, delay); + const range = Math.max(5, s.range), shotSpeed = Math.max(0.6, s.shotSpeed) * s.shotMul; + const multi = (s.spider ? 4 : s.inner ? 3 : 1) + (s.twin ? 1 : 0); + return { + damage: Math.round(damage * 1e4) / 1e4, tearDelay: delay, fireRate: Math.round(30 / (delay + 1) * 1e4) / 1e4, + interval: 2 * (delay + 1), range, fall: s.fall, shotSpeed: Math.round(shotSpeed * 1e4) / 1e4, + speed: clamp(s.speed, 0.1, 2), hearts: s.hearts, multi, + life: Math.max(8, Math.round(ISAAC.baseLife * (range + 4 * s.fall) / 23.75 * (s.boomerang ? 1.6 : 1))), + tearR: clamp(6.5 * Math.sqrt(damage / 3.5), 4.5, 15), + pierce: s.pierce, homing: s.homing, bounce: s.bounce, boomerang: s.boomerang, shield: s.shield, poly: s.poly, + wafer: s.wafer, yellow: s.yellow, twin: s.twin && multi === 2, spider: s.spider, inner: s.inner + }; + } + M.computeStats = computeStats; + + // ---------------- bosses + // hp = original Basement HP (doc). tierHp = HP at the three public tiers easy / normal / hard (d 0.2 / 0.5 / 0.8): easy is the + // roughly 500 HP target, each anchor calibrated so the reference controller with the case's standard loadout lands in + // 20-30 / 45-90 / 150-240 s; any other d interpolates log-quadratically through the anchors (M.tierValue). + const BOSS = M.bosses = { + monstro: { hp: 250, tierHp: [500, 1250, 3745], r: 38, lift: 14, first: 80 }, // lift: body collision centre above the feet (drawn body) + // doc: 22 HP per segment; arenas "1 body with 9 segments" (easy/normal) and "1 body with 13 segments" (hard, d >= 0.65); tierHp per segment + larry_jr: { hpSeg: 22, tierHp: [46, 115, 237], r: 20, spacing: 30, bodies: [[3, 1, [-1, 0]]], segs: 9, segsHard: 13, first: 80 }, + duke_of_flies: { hp: 110, tierHp: [470, 1175, 3520], r: 34, first: 80, flyHp: 10, orbitR: 62 }, // doc: 110 HP; his Attack Flies have 10 base HP (not tier-scaled) + // doc: 280 HP = two twins of 140 (Contusion, Suture); rocks always appear (4 layouts; one symmetric layout here); tierHp per twin + gemini: { hp: 280, twinHp: 140, tierHp: [205, 550, 1650], rC: 26, rS: 15, liftC: 8, cord: 84, first: 80, rocks: [[3, 2], [9, 2], [3, 4], [9, 4]] }, + // doc: 240 HP (one pool over both phases), Pooters 8 HP (max 2); approx: phase 2 below 40% HP + // lift: tears hit a circle raised onto the drawn horse and rider (contact and the charge stay on the ground footprint) + famine: { hp: 240, tierHp: [515, 1220, 3350], r: 28, headR: 18, lift: 20, phase2: 0.4, pooterHp: 8, first: 80 }, + // doc: Envy 60 HP (Rebirth); approx: each split generation has half the HP of its parent; tierHp = the first head + envy: { hp: 60, tierHp: [105, 280, 880], r: [30, 22, 15, 10], speed: [1.6, 2.1, 2.7, 3.3], hpShare: [1, 0.5, 0.25, 0.125], first: 80 } + }; + M.tierValue = (anchors, d) => { + const L = anchors.map(Math.log), x = (d - 0.5) / 0.3, b = (L[2] - L[0]) / 2, c = (L[2] + L[0]) / 2 - L[1]; + return Math.exp(L[1] + b * x + c * x * x); + }; + // other tier knobs: attack gaps x(1.3 - 0.7d) = x1.16 / x0.95 / x0.74, enemy speed x(0.88 + 0.3d) = x0.94 / x1.03 / x1.12; + // from d >= 0.65 every half-heart hit deals a full heart (doc: Chapter 4+ rule) + M.chapter4 = d => d >= 0.65; + + const OPTION_KEYS = ['items']; + M.validateOptions = function (opts) { + if (opts === undefined || opts === null) return; + if (typeof opts !== 'object' || Array.isArray(opts)) throw Error('isaac options must be an object'); + for (const k of Object.keys(opts)) if (!OPTION_KEYS.includes(k)) throw Error('unknown isaac option ' + k); + if (opts.items !== undefined) { + if (!Array.isArray(opts.items) || opts.items.length > 8) throw Error('items must be an array of at most 8 item ids'); + const seen = new Set(); + for (const id of opts.items) { + if (typeof id !== 'string' || !ITEMS[id]) throw Error('unknown item ' + id); + if (seen.has(id)) throw Error('duplicate item ' + id); + seen.add(id); + } + } + }; + + const cellX = c => ROOM.x0 + (c + 0.5) * TILE, cellY = r => ROOM.y0 + (r + 0.5) * TILE; + const cellOf = (x, y) => [clamp(Math.floor((x - ROOM.x0) / TILE), 0, ROOM.cols - 1), clamp(Math.floor((y - ROOM.y0) / TILE), 0, ROOM.rows - 1)]; + const FIRE = { J: [-1, 0], K: [0, 1], L: [1, 0], Shift: [0, -1] }; + M.fireKeys = FIRE; + + class Game { + constructor(id, seed, d, opts) { + const kind = id.split('/')[1], def = M.cases.find(c => c.id === id); + if (!def || !BOSS[kind]) throw Error('Unknown case ' + id); + M.validateOptions(opts); + this.id = id; this.kind = kind; this.rng = Game.mixSeed(seed); this.d = d; this.t = 0; + this.outcome = null; this.events = []; + this.items = (opts && opts.items) ? [...opts.items] : [...def.items]; + this.stats = computeStats(this.items); + this.ch4 = M.chapter4(d); + this.gapMul = 1.3 - 0.7 * d; // attack interval multiplier + this.spd = 0.88 + 0.3 * d; // enemy projectile / movement speed multiplier + const st = this.stats; + this.player = { + x: CX, y: ROOM.y1 - 30, vx: 0, vy: 0, r: ISAAC.r, hp: st.hearts, maxHp: st.hearts, bombs: ISAAC.bombs, + inv: 0, hurtT: -99, dead: 0, cd: 0, eye: 0, head: [0, 1], fireT: -99, fireDir: [0, 1], moving: 0, step: 0, bombCd: 0 + }; + this.fireStack = []; + this.held = []; + this.cells = new Array(ROOM.cols * ROOM.rows).fill(0); // 0 empty, 1 rock, 2..5 poop (hit points left + 1) + this.tears = []; this.shots = []; this.bombs = []; this.flies = []; this.fx = []; this.ids = 0; + this.doors = 'closed'; this.clearT = -1; this.reward = null; + this.shake = { t: -99, a: 0 }; + this.stat = { tears: 0, hits: 0, dealt: 0, taken: 0, hitsTaken: 0, bombHits: 0, blocked: 0, kills: 0 }; + this.initBoss(kind); + } + + ev(name) { this.events.push(name); } + rand() { return N.rand(this); } + nid() { return ++this.ids; } + shakeIt(a) { if (this.t - this.shake.t > 6 || a > this.shake.a) this.shake = { t: this.t, a }; } + health() { return [this.player.hp, this.player.maxHp, this.bossHp(), this.bossMax]; } + bossHp() { + const b = this.boss; + if (this.kind === 'larry_jr') { let s = 0; for (const body of b.bodies) for (const g of body.segs) s += Math.max(0, g.hp); return s; } + if (this.kind === 'gemini') return b.twins.reduce((a, t) => a + Math.max(0, t.hp), 0); + if (this.kind === 'envy') return Math.max(0, this.bossMax - b.lost); + return Math.max(0, b.hp); + } + + initBoss(kind) { + const B = BOSS[kind]; + if (kind === 'monstro') { + const hp = Math.round(M.tierValue(B.tierHp, this.d)); + this.boss = { kind, x: CX, y: CY - 24, r: B.r, hp, maxHp: hp, z: 0, st: 'idle', at: 0, timer: B.first, hops: 0, + vx: 0, vy: 0, face: 1, sx: CX, sy: CY, hidden: false, flash: -99, last: '', deadT: 0, dead: false, seq: 0, tx: 0, ty: 0, bag: [] }; + this.bossMax = hp; + } else if (kind === 'larry_jr') { + const hpSeg = Math.round(M.tierValue(B.tierHp, this.d)), speed = (2.4 + 0.9 * this.d) * TILE / HZ; + const n = this.ch4 ? B.segsHard : B.segs, start = this.ch4 ? [[4, 1, [-1, 0]]] : B.bodies; + const bodies = start.map(([c, r, dir]) => this.newLarry(c, r, dir, speed, n, hpSeg)); + this.boss = { kind, bodies, dead: false, deadT: 0, flash: -99, hpSeg, speed, wake: B.first }; + this.bossMax = hpSeg * n * start.length; + } else if (kind === 'gemini') { + const hp = Math.round(M.tierValue(B.tierHp, this.d)), y = ROOM.y0 + 1.5 * TILE; + for (const [c, r] of B.rocks) this.setCell(c, r, 1); + const C = { id: 'c', role: 'contusion', x: CX, y, r: B.rC, hp, max: hp, vx: 0, vy: 0, st: 'walk', timer: 100, ramp: 0, ca: 0, side: 0, sideDir: 1, flash: -99, dead: false, face: 1 }; + const S = { id: 's', role: 'suture', x: CX + 44, y, r: B.rS, hp, max: hp, vx: 0, vy: 0, st: 'tethered', timer: 90, wind: 0, boost: 0, flash: -99, dead: false }; + this.boss = { kind, twins: [C, S], attached: true, dead: false, flash: -99, still: B.first }; + this.bossMax = 2 * hp; + } else if (kind === 'famine') { + const hp = Math.round(M.tierValue(B.tierHp, this.d)); + this.boss = { kind, x: CX, y: CY - 60, r: B.r, hp, maxHp: hp, phase: 1, st: 'drift', timer: 40, chargeCd: 0, vx: 0, vy: 0, dir: 1, face: 1, + flash: -99, dead: false, off: false, wrapped: 0, tx: CX, ty: CY - 60, still: B.first }; + this.bossMax = hp; + } else if (kind === 'envy') { + // every tier is the regular Envy split (1 -> 2 -> 4 -> 8); Super Envy is a different mini-boss, not a harder Envy + const hp0 = Math.round(M.tierValue(B.tierHp, this.d)); + this.boss = { kind, heads: [], dead: false, flash: -99, hp0, lost: 0, still: B.first }; + const hpg = B.hpShare.map(k => Math.max(1, Math.round(hp0 * k))); + this.bossMax = hpg[0] + 2 * hpg[1] + 4 * hpg[2] + 8 * hpg[3]; + this.boss.heads.push(this.envyHead(0, CX, CY - 40, this.rand() < 0.5 ? 1 : -1, this.rand() < 0.5 ? 1 : -1)); + } else { + const hp = Math.round(M.tierValue(B.tierHp, this.d)), sx = this.rand() < 0.5 ? 1 : -1, sy = this.rand() < 0.5 ? 1 : -1; + const sp = (1.5 + 0.5 * this.d) * TILE / HZ; + this.boss = { kind, x: CX, y: CY - 36, r: B.r, hp, maxHp: hp, vx: sx * sp / Math.SQRT2, vy: sy * sp / Math.SQRT2, speed: sp, still: B.first, + timer: B.first, wind: 0, pending: '', orbitA: 0, flash: -99, dead: false, deadT: 0, last: '', bag: [] }; + this.bossMax = hp; + } + } + newLarry(c, r, dir, speed, n, hpSeg) { + const gap = Math.max(4, Math.round(BOSS.larry_jr.spacing / speed)); + const hx = cellX(c), hy = cellY(r), trail = []; + for (let i = 0; i <= (n - 1) * gap; i++) trail.push([hx - dir[0] * speed * i, hy - dir[1] * speed * i]); + const segs = []; + for (let k = 0; k < n; k++) { const tp = trail[k * gap]; segs.push({ id: this.nid(), hp: hpSeg, max: hpSeg, x: tp[0], y: tp[1], flash: -99 }); } + return { id: this.nid(), c, r, dir: [...dir], p: 0, speed, gap, trail, segs, turnT: 0 }; + } + + // ---------------- room geometry ---------------- + cell(c, r) { return c < 0 || r < 0 || c >= ROOM.cols || r >= ROOM.rows ? 1 : this.cells[r * ROOM.cols + c]; } + setCell(c, r, v) { this.cells[r * ROOM.cols + c] = v; } + solidAt(x, y, r) { + if (x - r < ROOM.x0 || x + r > ROOM.x1 || y - r < ROOM.y0 || y + r > ROOM.y1) return true; + const c0 = Math.floor((x - r - ROOM.x0) / TILE), c1 = Math.floor((x + r - ROOM.x0) / TILE); + const r0 = Math.floor((y - r - ROOM.y0) / TILE), r1 = Math.floor((y + r - ROOM.y0) / TILE); + for (let rr = r0; rr <= r1; rr++) for (let cc = c0; cc <= c1; cc++) { + if (!this.cell(cc, rr)) continue; + const bx = ROOM.x0 + cc * TILE + 3, by = ROOM.y0 + rr * TILE + 3, bw = TILE - 6; + const nx = clamp(x, bx, bx + bw), ny = clamp(y, by, by + bw); + if ((x - nx) * (x - nx) + (y - ny) * (y - ny) < r * r) return true; + } + return false; + } + damagePoop(c, r, n) { + const v = this.cell(c, r); + if (v < 2) return; + const left = v - 1 - n; + this.setCell(c, r, left > 0 ? left + 1 : 0); + this.fx.push({ k: left > 0 ? 'chip' : 'poopgone', x: cellX(c), y: cellY(r), t: this.t }); + if (left <= 0) this.ev('poop_break'); + } + + // ---------------- update ---------------- + update(keys, pressed, mouse) { + this.held = [...keys].sort(); + for (let i = this.fireStack.length - 1; i >= 0; i--) if (!keys.has(this.fireStack[i])) this.fireStack.splice(i, 1); + for (const k of [...pressed].sort()) if (FIRE[k] && !this.fireStack.includes(k)) this.fireStack.push(k); + this.updatePlayer(keys, pressed); + if (this.kind === 'monstro') this.updateMonstro(); + else if (this.kind === 'larry_jr') this.updateLarry(); + else if (this.kind === 'gemini') this.updateGemini(); + else if (this.kind === 'famine') this.updateFamine(); + else if (this.kind === 'envy') this.updateEnvy(); + else this.updateDuke(); + this.updateFlies(); + this.updateTears(); + this.updateShots(); + this.updateBombs(); + this.contact(); + this.checkClear(); + const keep = this.t - 50; + if (this.fx.length && this.fx[0].t < keep) this.fx = this.fx.filter(f => f.t >= keep); + if (this.fx.length > 90) this.fx = this.fx.slice(-90); + } + + updatePlayer(keys, pressed) { + const p = this.player, st = this.stats; + if (p.inv > 0) p.inv--; + if (p.cd > 0) p.cd--; + if (p.bombCd > 0) p.bombCd--; + if (p.dead > 0) { + p.vx = 0; p.vy = 0; p.dead--; + if (p.dead === 0 && !this.outcome) this.outcome = 'loss'; + return; + } + const mx = (keys.has('D') ? 1 : 0) - (keys.has('A') ? 1 : 0), my = (keys.has('S') ? 1 : 0) - (keys.has('W') ? 1 : 0); + if (mx || my) { + const n = hyp(mx, my), v = ISAAC.walk * st.speed; + p.vx += (mx / n * v - p.vx) * ISAAC.accel; p.vy += (my / n * v - p.vy) * ISAAC.accel; + p.moving = 1; p.step++; + } else { p.vx *= ISAAC.friction; p.vy *= ISAAC.friction; p.moving = 0; if (Math.abs(p.vx) < 0.02) p.vx = 0; if (Math.abs(p.vy) < 0.02) p.vy = 0; } + if (p.vx && !this.solidAt(p.x + p.vx, p.y, p.r)) p.x += p.vx; else p.vx = 0; + if (p.vy && !this.solidAt(p.x, p.y + p.vy, p.r)) p.y += p.vy; else p.vy = 0; + // fire: hold a direction key, the most recently pressed held one wins + const fk = this.fireStack.length ? this.fireStack[this.fireStack.length - 1] : null; + if (fk) { + p.head = FIRE[fk]; p.fireT = this.t; + if (p.cd <= 0) this.fire(FIRE[fk]); + } else if (mx || my) p.head = Math.abs(mx) >= Math.abs(my) && mx ? [mx, 0] : [0, my || 1]; + if (pressed.has('E') && p.bombs > 0 && p.bombCd <= 0) { + p.bombs--; p.bombCd = 20; + this.bombs.push({ id: this.nid(), x: p.x, y: p.y + 4, fuse: ISAAC.bombFuse }); + this.ev('bomb_place'); + } + } + + fire(dir) { + const p = this.player, st = this.stats, sp = ISAAC.tearSpeed * st.shotSpeed; + p.cd = st.interval; p.fireDir = dir; + const px = -dir[1], py = dir[0]; + const angles = []; + let offsets = [0]; + if (st.multi === 1) { offsets = [p.eye ? 4 : -4]; angles.push(0); p.eye ^= 1; } + else if (st.twin) { offsets = [-7, 7]; angles.push(0, 0); } + else { const n = st.multi, step = st.spider ? 7 : 6; for (let i = 0; i < n; i++) angles.push((i - (n - 1) / 2) * step * DEG); offsets = angles.map(() => 0); } + const base = Math.atan2(dir[1], dir[0]); + for (let i = 0; i < angles.length; i++) { + const a = base + angles[i], c = Math.cos(a), s = Math.sin(a), off = offsets[i] || 0; + this.tears.push({ id: this.nid(), x: p.x + dir[0] * 9 + px * off, y: p.y + dir[1] * 7 + py * off, vx: c * sp + p.vx * ISAAC.inherit, vy: s * sp + p.vy * ISAAC.inherit, + v0: sp, age: 0, life: st.life, dmg: st.damage, r: st.tearR, hits: [], ret: 0 }); + } + this.stat.tears += angles.length; + this.ev('tear'); + } + + // every hittable enemy part this tick: {id, x, y, r, kind, ref} + targets() { + const out = [], b = this.boss; + if (this.kind === 'monstro') { if (!b.dead && !b.hidden && b.z < 40) out.push({ id: 'm', x: b.x, y: b.y - BOSS.monstro.lift, r: b.r, kind: 'monstro', ref: b }); } + else if (this.kind === 'larry_jr') { for (const body of b.bodies) for (const g of body.segs) out.push({ id: 's' + g.id, x: g.x, y: g.y, r: BOSS.larry_jr.r, kind: 'seg', ref: g, body }); } + else if (this.kind === 'gemini') { for (const t of b.twins) if (!t.dead) out.push({ id: 'g' + t.id, x: t.x, y: t.y - (t.role === 'contusion' ? BOSS.gemini.liftC : 0), r: t.r, kind: 'twin', ref: t }); } + else if (this.kind === 'famine') { if (!b.dead && !b.off) out.push({ id: 'fm', x: b.x, y: b.y - (b.phase === 1 ? BOSS.famine.lift : 0), r: b.r, kind: 'famine', ref: b }); } + else if (this.kind === 'envy') { for (const h of b.heads) out.push({ id: 'h' + h.id, x: h.x, y: h.y, r: h.r, kind: 'head', ref: h }); } + else if (!b.dead) out.push({ id: 'd', x: b.x, y: b.y, r: b.r, kind: 'duke', ref: b }); + for (const f of this.flies) out.push({ id: 'f' + f.id, x: f.x, y: f.y, r: f.r, kind: 'fly', ref: f }); + return out; + } + // apply damage to one target; returns leftover damage when it killed the target (Polyphemus) + damage(tg, dmg, src) { + if (dmg <= 0) return 0; + let before = 0; + if (tg.kind === 'monstro' || tg.kind === 'duke' || tg.kind === 'famine') { + const b = tg.ref; if (b.dead) return 0; + before = b.hp; b.hp -= dmg; b.flash = this.t; + this.stat.dealt += Math.min(dmg, before); + if (b.hp <= 0) { b.hp = 0; this.bossDeath(); } + } else if (tg.kind === 'seg') { + const g = tg.ref; if (g.hp <= 0) return 0; + before = g.hp; g.hp -= dmg; g.flash = this.t; this.boss.flash = this.t; + this.stat.dealt += Math.min(dmg, before); + if (g.hp <= 0) this.killSegment(this.boss.bodies.find(bd => bd.segs.includes(g)), g); + } else if (tg.kind === 'twin') { + const t = tg.ref; if (t.dead) return 0; + before = t.hp; t.hp -= dmg; t.flash = this.t; this.boss.flash = this.t; + this.stat.dealt += Math.min(dmg, before); + if (t.hp <= 0) { // doc: Contusion first -> Suture detaches and charges (next tick); Suture first -> no change + t.hp = 0; t.dead = true; this.fx.push({ k: 'pop', x: t.x, y: t.y, t: this.t, big: 1 }); this.ev(t.role + '_dies'); this.shakeIt(4); + if (this.boss.twins.every(q => q.dead)) this.bossDeath(t.x, t.y); + } + } else if (tg.kind === 'head') { + const h = tg.ref; if (h.dead) return 0; + before = h.hp; h.hp -= dmg; h.flash = this.t; this.boss.flash = this.t; + const lost = Math.min(dmg, before); this.stat.dealt += lost; this.boss.lost += lost; + if (h.hp <= 0) this.splitEnvy(h); + } else { + const f = tg.ref; if (f.dead) return 0; + before = f.hp; f.hp -= dmg; f.flash = this.t; + if (f.hp <= 0) { f.dead = 1; this.stat.kills++; this.fx.push({ k: 'pop', x: f.x, y: f.y, t: this.t }); this.ev('fly_die'); } + } + this.stat.hits++; + this.fx.push({ k: 'hit', x: tg.x, y: tg.y, t: this.t, s: src }); + this.ev(src === 'bomb' ? 'bomb_hit' : 'boss_hit'); + return dmg > before ? dmg - before : 0; + } + + updateTears() { + const p = this.player, st = this.stats; + const tgs = this.targets(); + for (const q of this.tears) { + if (st.homing && tgs.length) { + // approx: a homing tear seeks the enemy part within 4 tiles that lies closest to its heading (60 deg cone, + // angle + distance/8 tiles), turning up to 0.075 rad/tick; parts outside the cone are ignored + const a = Math.atan2(q.vy, q.vx); + let best = null, bs = 1e9; + for (const tg of tgs) { + if (q.hits.includes(tg.id)) continue; + const dd = hyp(tg.x - q.x, tg.y - q.y); if (dd > 4 * TILE) continue; + const off = Math.abs(Math.atan2(Math.sin(Math.atan2(tg.y - q.y, tg.x - q.x) - a), Math.cos(Math.atan2(tg.y - q.y, tg.x - q.x) - a))); + if (off > Math.PI / 3 && dd > tg.r + q.r + 6) continue; + const sc = off + dd / (8 * TILE); + if (sc < bs) { bs = sc; best = tg; } + } + if (best) { + const want = Math.atan2(best.y - q.y, best.x - q.x), sp = hyp(q.vx, q.vy); + const da = clamp(Math.atan2(Math.sin(want - a), Math.cos(want - a)), -0.075, 0.075); + q.vx = Math.cos(a + da) * sp; q.vy = Math.sin(a + da) * sp; + } + } + if (st.boomerang) { // approx: constant pull toward Isaac, reverses at ~45% of the life + const dx = p.x - q.x, dy = p.y - q.y, dd = hyp(dx, dy) || 1, acc = q.v0 * 2.2 / q.life; + q.vx += dx / dd * acc; q.vy += dy / dd * acc; + if (q.age > q.life * 0.3 && dd < p.r + 6) { q.dead = 1; continue; } + } + const ox = q.x, oy = q.y; + q.x += q.vx; q.y += q.vy; q.age++; + // walls and obstacles + let wall = false; + if (q.x < ROOM.x0 + 2 || q.x > ROOM.x1 - 2) { wall = true; if (st.bounce) { q.vx = -q.vx; q.x = clamp(q.x, ROOM.x0 + 2, ROOM.x1 - 2); q.hits = []; } } + if (q.y < ROOM.y0 + 2 || q.y > ROOM.y1 - 2) { wall = true; if (st.bounce) { q.vy = -q.vy; q.y = clamp(q.y, ROOM.y0 + 2, ROOM.y1 - 2); q.hits = []; } } + if (wall && !st.bounce) { this.splash(q); continue; } + const [c, r] = cellOf(q.x, q.y), v = this.cell(c, r); + if (v && !wall) { + if (v >= 2 && st.pierce) { // doc (nr): Cupid's Arrow pierces poop; approx: damages it once + if (!q.hits.includes('p' + c + '_' + r)) { q.hits.push('p' + c + '_' + r); this.damagePoop(c, r, 1); } + } else { + if (v >= 2) this.damagePoop(c, r, 1); + if (st.bounce) { + const [oc, or] = cellOf(ox, oy); + if (oc !== c) q.vx = -q.vx; if (or !== r) q.vy = -q.vy; if (oc === c && or === r) { q.vx = -q.vx; q.vy = -q.vy; } + q.x = ox; q.y = oy; q.hits = []; + } else { this.splash(q); continue; } + } + } + // enemy parts + for (const tg of tgs) { + if (q.dead || q.hits.includes(tg.id) || (tg.ref.dead) || (tg.kind === 'seg' && tg.ref.hp <= 0)) continue; + if (N.segmentDistance(tg, { x: ox, y: oy }, q) >= tg.r + q.r) continue; + const left = this.damage(tg, q.dmg, 'tear'); + this.knock(tg, q); + if (st.pierce) { q.hits.push(tg.id); continue; } + if (st.poly && left > 0) { q.dmg = left; q.hits.push(tg.id); continue; } + if (st.bounce) { const a = this.rand() * TAU, sp = hyp(q.vx, q.vy); q.vx = Math.cos(a) * sp; q.vy = Math.sin(a) * sp; q.hits = [tg.id]; continue; } + q.dead = 1; this.fx.push({ k: 'splash', x: q.x, y: q.y, t: this.t, c: 1 }); + } + if (q.dead) continue; + if (st.shield) for (const s of this.shots) { // doc: Lost Contact tears destroy enemy shots and break + if (!s.dead && hyp(s.x - q.x, s.y - q.y) < s.r + q.r) { s.dead = 1; q.dead = 1; this.stat.blocked++; this.fx.push({ k: 'splash', x: q.x, y: q.y, t: this.t, c: 2 }); this.ev('block'); break; } + } + if (!q.dead && q.age >= q.life) this.splash(q); + } + this.tears = this.tears.filter(q => !q.dead); + if (this.flies.some(f => f.dead)) this.flies = this.flies.filter(f => !f.dead); + } + splash(q) { q.dead = 1; this.fx.push({ k: 'splash', x: clamp(q.x, ROOM.x0, ROOM.x1), y: clamp(q.y, ROOM.y0, ROOM.y1), t: this.t, c: 0 }); } + knock(tg, q) { // tear knockback (doc: from tear velocity; nr piercing tears have none) + if (this.stats.pierce) return; + const sp = hyp(q.vx, q.vy) || 1, ux = q.vx / sp, uy = q.vy / sp; + if (tg.kind === 'fly') { tg.ref.kx += ux * 2.6; tg.ref.ky += uy * 2.6; } + else if (tg.kind === 'duke') { // doc: knockback can change his travel direction; he keeps floating diagonally + // approx: the tear's dominant axis pushes that component of his diagonal along the tear + const b = tg.ref, k = b.speed / Math.SQRT2; + if (Math.abs(ux) > 0.5) b.vx = Math.sign(ux) * k; + if (Math.abs(uy) > 0.5) b.vy = Math.sign(uy) * k; + } + else if (tg.kind === 'twin' && tg.ref.role === 'suture') { // doc: a free Suture takes extra knockback, which can speed him up + const t = tg.ref; + if (t.st === 'frenzy') { t.vx += ux * 1.5; t.vy += uy * 1.5; t.boost = 24; } else { t.vx += ux * 0.8; t.vy += uy * 0.8; } + } + else if (tg.kind === 'monstro' && tg.ref.st === 'idle') { const b = tg.ref; b.x = clamp(b.x + ux * 0.6, ROOM.x0 + b.r, ROOM.x1 - b.r); b.y = clamp(b.y + uy * 0.6, ROOM.y0 + b.r * 0.7, ROOM.y1 - b.r * 0.5); } + } + + // enemy projectiles + shot(x, y, a, speed, big, life) { + const s = speed * this.spd; + this.shots.push({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, r: big ? 7.5 : 5, big: big ? 1 : 0, dmg: big ? 2 : 1, age: 0, life: life || 90, z: 14 }); + } + updateShots() { + const p = this.player, alive = p.dead === 0; + for (const s of this.shots) { + const ox = s.x, oy = s.y; + s.x += s.vx; s.y += s.vy; s.age++; + if (s.age >= s.life || s.x < ROOM.x0 || s.x > ROOM.x1 || s.y < ROOM.y0 || s.y > ROOM.y1) { s.dead = 1; this.fx.push({ k: 'drop', x: clamp(s.x, ROOM.x0, ROOM.x1), y: clamp(s.y, ROOM.y0, ROOM.y1), t: this.t }); continue; } + const [c, r] = cellOf(s.x, s.y); + if (this.cell(c, r)) { s.dead = 1; this.fx.push({ k: 'drop', x: s.x, y: s.y, t: this.t }); continue; } + if (alive && N.segmentDistance(p, { x: ox, y: oy }, s) < p.r + s.r * 0.85) { + if (this.hurt(s.dmg, 'shot', s.x, s.y)) s.dead = 1; + } + } + if (this.shots.length) this.shots = this.shots.filter(s => !s.dead); + } + + updateBombs() { + const p = this.player; + for (const bm of this.bombs) { + if (--bm.fuse > 0) continue; + bm.dead = 1; + const R = ISAAC.bombRadius; + this.fx.push({ k: 'boom', x: bm.x, y: bm.y, r: R, t: this.t }); + this.shakeIt(6); this.ev('explosion'); + for (const tg of this.targets()) if (hyp(tg.x - bm.x, tg.y - bm.y) < R + tg.r) { this.damage(tg, ISAAC.bombDamage, 'bomb'); this.stat.bombHits++; } + if (p.dead === 0 && hyp(p.x - bm.x, p.y - bm.y) < R + p.r) this.hurt(2, 'bomb', bm.x, bm.y, true); + const [c0, r0] = cellOf(bm.x - R, bm.y - R), [c1, r1] = cellOf(bm.x + R, bm.y + R); + for (let rr = r0; rr <= r1; rr++) for (let cc = c0; cc <= c1; cc++) if (this.cell(cc, rr) && hyp(cellX(cc) - bm.x, cellY(rr) - bm.y) < R + TILE * 0.4) { this.setCell(cc, rr, 0); this.fx.push({ k: 'poopgone', x: cellX(cc), y: cellY(rr), t: this.t }); } + } + if (this.bombs.length) this.bombs = this.bombs.filter(b => !b.dead); + } + + hurt(n, src, sx, sy, fixed) { + const p = this.player; + if (p.inv > 0 || p.dead > 0 || p.hp <= 0 || this.clearT >= 0) return false; + if (!fixed && this.ch4 && n === 1) n = 2; // doc: from Chapter 4 on, half-heart hits deal a full heart + if (this.stats.wafer) n = Math.min(n, 1); // doc: The Wafer + p.hp = Math.max(0, p.hp - n); p.inv = ISAAC.invPerHalf * n; p.hurtT = this.t; + this.stat.taken += n; this.stat.hitsTaken++; + if (sx !== undefined) { const dx = p.x - sx, dy = p.y - sy, dd = hyp(dx, dy) || 1; p.vx += dx / dd * 5; p.vy += dy / dd * 5; } + this.shakeIt(3); this.ev('hurt'); + this.fx.push({ k: 'ouch', x: p.x, y: p.y - 30, t: this.t, v: n }); + if (p.hp <= 0) { p.dead = ISAAC.deadTicks; this.ev('isaac_dies'); } + return true; + } + + // contact damage from bodies + contact() { + const p = this.player; + if (p.dead > 0 || this.clearT >= 0) return; + const b = this.boss; + if (this.kind === 'monstro') { + if (!b.dead && !b.hidden && b.z < 8 && hyp(p.x - b.x, p.y - b.y + BOSS.monstro.lift) < b.r + p.r - 4) this.hurt(1, 'contact', b.x, b.y); + } else if (this.kind === 'larry_jr') { + for (const body of b.bodies) for (const g of body.segs) if (hyp(p.x - g.x, p.y - g.y) < BOSS.larry_jr.r + p.r - 3) { this.hurt(1, 'contact', g.x, g.y); return; } + } else if (this.kind === 'gemini') { + for (const t of b.twins) if (!t.dead && hyp(p.x - t.x, p.y - t.y) < t.r + p.r - 3) { this.hurt(1, 'contact', t.x, t.y); break; } + } else if (this.kind === 'famine') { // doc: a whole heart of contact damage in both phases and during the charge + if (!b.dead && !b.off && hyp(p.x - b.x, p.y - b.y) < M.famineBand(b)) this.hurt(2, 'contact', b.x, b.y); + } else if (this.kind === 'envy') { + for (const h of b.heads) if (hyp(p.x - h.x, p.y - h.y) < h.r + p.r - 3) { this.hurt(1, 'contact', h.x, h.y); break; } + } else if (!b.dead && hyp(p.x - b.x, p.y - b.y) < b.r + p.r - 4) this.hurt(1, 'contact', b.x, b.y); + for (const f of this.flies) { + if (f.mode === 'pooter') continue; // doc: Pooters deal no contact damage + if (f.dead || hyp(p.x - f.x, p.y - f.y) >= f.r + p.r - 2) continue; + this.hurt(1, 'fly', f.x, f.y); + f.dead = 1; this.fx.push({ k: 'pop', x: f.x, y: f.y, t: this.t }); // doc: Duke's flies die when Isaac touches them, dealing contact damage first + } + if (this.flies.some(f => f.dead)) this.flies = this.flies.filter(f => !f.dead); + } + + bossDeath(x, y) { + const b = this.boss; + b.dead = true; b.deadT = this.t; b.hidden = false; + this.shots = []; + this.ev('boss_defeated'); this.shakeIt(7); + this.fx.push({ k: 'boom', x: x !== undefined ? x : b.x !== undefined ? b.x : CX, y: y !== undefined ? y : b.y !== undefined ? b.y : CY, r: 70, t: this.t, gore: 1 }); + if (this.kind === 'duke_of_flies') for (const f of this.flies) if (f.mode === 'orbit') { f.mode = 'chase'; f.vx = (f.x - b.x) * 0.05; f.vy = (f.y - b.y) * 0.05; } // doc: orbiting flies are freed + } + checkClear() { + if (this.clearT >= 0) { + if (this.t - this.clearT >= 30 && !this.outcome) this.outcome = 'win'; + return; + } + if (this.boss.dead && !this.flies.length && this.player.dead === 0) { + this.clearT = this.t; this.doors = 'open'; this.shots = []; + this.reward = { x: CX, y: CY - 10, t: this.t }; // doc: boss item pedestal + trapdoor after victory (cosmetic here) + this.ev('room_clear'); + } + } + + // ---------------- Monstro ---------------- + // approx timings; doc behaviour: hops toward Isaac, coughs a spray of projectiles toward him, jumps off-screen and + // lands on him with a burst in all directions; large tears deal a full heart, small ones half a heart + updateMonstro() { + const b = this.boss, p = this.player; + if (b.dead) return; + b.vx = 0; b.vy = 0; + const gap = () => Math.max(14, Math.round((30 + this.rand() * 22) * this.gapMul)); + const R = { x0: ROOM.x0 + b.r + 10, x1: ROOM.x1 - b.r - 10, y0: ROOM.y0 + b.r + 30, y1: ROOM.y1 - b.r * 0.4 }; // keeps the drawn body inside the walls + b.at++; + if (b.st === 'idle') { + b.face = p.x >= b.x ? 1 : -1; + if (--b.timer > 0) return; + // approx: the three documented attacks come from a shuffled bag (2 hop runs, 1 cough, 1 jump), no jump twice in a row; + // far from Isaac a hop is pulled forward so Monstro keeps closing in + if (!b.bag || !b.bag.length) { + const bag = ['hop', 'hop', 'cough', 'jump']; + for (let i = bag.length - 1; i > 0; i--) { const j = Math.floor(this.rand() * (i + 1)); const tmp = bag[i]; bag[i] = bag[j]; bag[j] = tmp; } + if (bag[bag.length - 1] === 'jump' && b.last === 'jump') { bag[bag.length - 1] = bag[0]; bag[0] = 'jump'; } + b.bag = bag; + } + const dist = hyp(p.x - b.x, p.y - b.y); + let k = b.bag.length - 1; + if (dist > 5 * TILE && b.bag.includes('hop')) k = b.bag.lastIndexOf('hop'); + const next = b.bag.splice(k, 1)[0]; + b.last = next; b.seq++; b.at = 0; + if (next === 'hop') { b.st = 'crouch'; b.hops = 1 + Math.floor(this.rand() * (2 + this.d * 2)); b.timer = 8; } + else if (next === 'cough') { b.st = 'cough'; b.timer = 28; this.ev('cough_wind'); } + else { b.st = 'jcrouch'; b.timer = 16; this.ev('jump_wind'); } + return; + } + if (b.st === 'crouch') { + if (--b.timer > 0) return; + let dx = p.x - b.x, dy = p.y - b.y; const dd = hyp(dx, dy), lim = 2.3 * TILE; + if (dd > lim) { dx *= lim / dd; dy *= lim / dd; } + b.tx = clamp(b.x + dx, R.x0, R.x1); b.ty = clamp(b.y + dy, R.y0, R.y1); + b.st = 'hop'; b.timer = 26; b.hx = b.x; b.hy = b.y; b.face = dx >= 0 ? 1 : -1; + this.ev('hop'); + return; + } + if (b.st === 'hop') { + const k = 1 - (b.timer - 1) / 26, ox = b.x, oy = b.y; + b.x = b.hx + (b.tx - b.hx) * k; b.y = b.hy + (b.ty - b.hy) * k; b.z = Math.sin(Math.PI * k) * 34; + b.vx = b.x - ox; b.vy = b.y - oy; + if (--b.timer > 0) return; + b.z = 0; b.st = 'land'; b.timer = 9; this.shakeIt(2); this.ev('land'); + return; + } + if (b.st === 'land') { + if (--b.timer > 0) return; + if (--b.hops > 0) { b.st = 'crouch'; b.timer = 6; } else { b.st = 'idle'; b.timer = gap(); } + return; + } + if (b.st === 'cough') { + b.face = p.x >= b.x ? 1 : -1; + if (--b.timer === 0) { + const n = 9 + Math.floor(this.rand() * 4) + Math.round(5 * this.d), base = Math.atan2(p.y - b.y, p.x - b.x); + for (let i = 0; i < n; i++) { + const a = base + (this.rand() * 2 - 1) * 24 * DEG; + this.shot(b.x + Math.cos(base) * b.r * 0.6, b.y - 10 + Math.sin(base) * b.r * 0.4, a, 3.0 + this.rand() * 2.6, this.rand() < 0.3, 70 + Math.floor(this.rand() * 40)); + } + this.ev('cough'); this.shakeIt(2); + b.st = 'crecover'; b.timer = 30; + } + return; + } + if (b.st === 'crecover') { if (--b.timer <= 0) { b.st = 'idle'; b.timer = gap(); } return; } + if (b.st === 'jcrouch') { if (--b.timer <= 0) { b.st = 'rise'; b.timer = 22; this.ev('jump'); } return; } + if (b.st === 'rise') { + b.z += 15; if (b.z > 60) b.hidden = true; + if (--b.timer <= 0) { b.st = 'track'; b.timer = Math.round(64 - 18 * this.d); b.sx = b.x; b.sy = b.y; } + return; + } + if (b.st === 'track' || b.st === 'lock') { + if (b.st === 'track') { // the landing shadow follows Isaac, then locks (telegraph) + const dx = p.x - b.sx, dy = p.y - b.sy, dd = hyp(dx, dy), v = (2.6 + 1.6 * this.d) * this.spd; + if (dd > v) { b.sx += dx / dd * v; b.sy += dy / dd * v; } else { b.sx = p.x; b.sy = p.y; } + b.sx = clamp(b.sx, R.x0, R.x1); b.sy = clamp(b.sy, R.y0, R.y1); + if (--b.timer <= 0) { b.st = 'lock'; b.timer = Math.round(30 - 10 * this.d); this.ev('jump_lock'); } + } else if (--b.timer <= 0) { b.st = 'fall'; b.timer = 12; b.x = b.sx; b.y = b.sy; b.z = 330; } + b.x = b.sx; b.y = b.sy; + return; + } + if (b.st === 'fall') { + b.z = Math.max(0, b.z - 27.5); + if (b.z < 40) b.hidden = false; + if (--b.timer > 0) return; + b.z = 0; b.hidden = false; + // the slam area is the drawn telegraph circle (around the body centre); Isaac is hit when his body touches it + if (p.dead === 0 && hyp(p.x - b.x, p.y - b.y + BOSS.monstro.lift) < M.slamRadius(b) + p.r) this.hurt(1, 'slam', b.x, b.y); + const n = 10 + Math.floor(this.rand() * 3) + Math.round(5 * this.d), a0 = this.rand() * TAU; + for (let i = 0; i < n; i++) this.shot(b.x, b.y, a0 + i * TAU / n + (this.rand() * 2 - 1) * 0.18, 2.4 + this.rand() * 2.2, this.rand() < 0.25, 60 + Math.floor(this.rand() * 40)); + this.ev('slam'); this.shakeIt(6); + this.fx.push({ k: 'quake', x: b.x, y: b.y, t: this.t }); + b.st = 'jrecover'; b.timer = 34; + return; + } + if (b.st === 'jrecover') { if (--b.timer <= 0) { b.st = 'idle'; b.timer = gap(); } } + } + + // ---------------- Larry Jr. ---------------- + // doc: segments move in cardinal directions, turn at walls/obstacles, drop poop, break poop they run into and turn, + // split into smaller copies when the pieces are longer than 2; approx: speed, turn and poop rates, turn bias toward Isaac + updateLarry() { + const b = this.boss; + if (b.dead) return; + if (b.wake > 0) { b.wake--; this.layLarry(); return; } + for (const body of b.bodies) this.moveLarry(body); + this.layLarry(); + } + layLarry() { + for (const body of this.boss.bodies) { + body.segs.forEach((g, k) => { + const tp = body.trail[Math.min(body.trail.length - 1, k * body.gap)]; + g.x += (tp[0] - g.x) * 0.35; g.y += (tp[1] - g.y) * 0.35; // eases a segment into its slot after a split/join + if (hyp(tp[0] - g.x, tp[1] - g.y) < 0.05) { g.x = tp[0]; g.y = tp[1]; } + }); + } + } + moveLarry(body) { + body.p += body.speed; + if (body.p >= TILE) { body.p -= TILE; body.c += body.dir[0]; body.r += body.dir[1]; this.larryArrive(body); } + const hx = cellX(body.c) + body.dir[0] * body.p, hy = cellY(body.r) + body.dir[1] * body.p; + body.trail.unshift([hx, hy]); + const need = (body.segs.length - 1) * body.gap + 1; + if (body.trail.length > need) body.trail.length = need; + } + larryFree(c, r) { return c >= 0 && r >= 0 && c < ROOM.cols && r < ROOM.rows && this.cell(c, r) !== 1; } + larryArrive(body) { + const p = this.player, ci = body.c, ri = body.r; + // poop just behind the tail end (approx 7% + 3%·d per tile, at most 9 in the room) + if (body.segs.length >= 2 && this.rand() < 0.07 + 0.03 * this.d && this.cells.filter(v => v >= 2).length < 9) { + const n = body.trail.length, tail = body.trail[n - 1], prev = body.trail[Math.max(0, n - 2)]; + const tx = Math.sign(prev[0] - tail[0]), ty = Math.sign(prev[1] - tail[1]); + const [tc, tr] = cellOf(tail[0] - tx * TILE * 0.75, tail[1] - ty * TILE * 0.75); + if (!this.cell(tc, tr) && hyp(cellX(tc) - p.x, cellY(tr) - p.y) > TILE && !this.larryOccupied(tc, tr)) { this.setCell(tc, tr, 5); this.ev('poop'); } + } + const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + const ahead = [ci + body.dir[0], ri + body.dir[1]]; + let must = !this.larryFree(ahead[0], ahead[1]); + if (body.must) { body.must = 0; if (this.rand() < 0.5) must = true; } // doc: may change direction when a segment is destroyed + if (!must && this.cell(ahead[0], ahead[1]) >= 2) { this.setCell(ahead[0], ahead[1], 0); this.fx.push({ k: 'poopgone', x: cellX(ahead[0]), y: cellY(ahead[1]), t: this.t }); this.ev('poop_break'); must = true; } + if (body.turnT > 0) body.turnT--; + // approx: wander turns plus a chase turn toward Isaac's row/column (aggression rises with the tier) + const [pc, pr] = cellOf(p.x, p.y); + let chase = null; + if (!must && body.turnT === 0) { + const offX = pc - ci, offY = pr - ri; + const want = body.dir[0] ? (offY ? [0, Math.sign(offY)] : null) : (offX ? [Math.sign(offX), 0] : null); + if (want && this.larryFree(ci + want[0], ri + want[1]) && this.rand() < 0.12 + 0.22 * this.d) chase = want; + } + if (chase) { body.dir = chase; body.turnT = 1; return; } + if (!must && !(body.turnT === 0 && this.rand() < 0.18 + 0.1 * this.d)) return; + const side = dirs.filter(d => d[0] !== body.dir[0] && d[1] !== body.dir[1] && !(d[0] === -body.dir[0] && d[1] === -body.dir[1]) && this.larryFree(ci + d[0], ri + d[1])); + const perp = dirs.filter(d => (d[0] === 0) !== (body.dir[0] === 0) && this.larryFree(ci + d[0], ri + d[1])); + const opts = perp.length ? perp : side; + if (!opts.length) { const back = [-body.dir[0], -body.dir[1]]; if (this.larryFree(ci + back[0], ri + back[1])) body.dir = back; return; } + let pick; + if (opts.length > 1 && this.rand() < 0.3 + 0.5 * this.d) { // aggression: prefer the turn toward Isaac + pick = opts.reduce((m, d) => (d[0] * (pc - ci) + d[1] * (pr - ri) > m[0] * (pc - ci) + m[1] * (pr - ri) ? d : m)); + } else pick = opts[Math.floor(this.rand() * opts.length)]; + body.dir = [...pick]; body.turnT = 1; + } + larryOccupied(c, r) { // a segment is in that tile, or a head is about to enter it + for (const body of this.boss.bodies) { + if (body.c + body.dir[0] === c && body.r + body.dir[1] === r) return true; + for (const g of body.segs) { const [gc, gr] = cellOf(g.x, g.y); if (gc === c && gr === r) return true; } + } + return false; + } + killSegment(body, g) { + const b = this.boss, k = body.segs.indexOf(g); + this.fx.push({ k: 'pop', x: g.x, y: g.y, t: this.t, big: 1 }); this.ev('segment_die'); this.shakeIt(3); + const front = body.segs.slice(0, k), rear = body.segs.slice(k + 1); + const i = b.bodies.indexOf(body); + const pieceFrom = (segs, start) => { // a piece whose new head sits at trail[start] + const tr = body.trail.slice(start), h = tr[0], nx = tr[1] || [h[0] - body.dir[0], h[1] - body.dir[1]]; + const ddx = h[0] - nx[0], ddy = h[1] - nx[1]; + let dir = Math.abs(ddx) >= Math.abs(ddy) ? [Math.sign(ddx), 0] : [0, Math.sign(ddy)]; + if (!dir[0] && !dir[1]) dir = [...body.dir]; + let c, r, pp; + if (dir[0]) { r = Math.round((h[1] - ROOM.y0 - TILE / 2) / TILE); c = dir[0] > 0 ? Math.floor((h[0] - ROOM.x0 - TILE / 2) / TILE) : Math.ceil((h[0] - ROOM.x0 - TILE / 2) / TILE); pp = Math.abs(h[0] - cellX(c)); } + else { c = Math.round((h[0] - ROOM.x0 - TILE / 2) / TILE); r = dir[1] > 0 ? Math.floor((h[1] - ROOM.y0 - TILE / 2) / TILE) : Math.ceil((h[1] - ROOM.y0 - TILE / 2) / TILE); pp = Math.abs(h[1] - cellY(r)); } + c = clamp(c, 0, ROOM.cols - 1); r = clamp(r, 0, ROOM.rows - 1); pp = clamp(pp, 0, TILE - 0.001); + return { id: this.nid(), c, r, dir, p: pp, speed: body.speed, gap: body.gap, trail: tr, segs, turnT: 0 }; + }; + if (k === 0) { // head destroyed: the next segment leads + if (rear.length) { const nb = pieceFrom(rear, body.gap); nb.turnT = 0; b.bodies.splice(i, 1, nb); this.larryTurnSoon(nb); } + else b.bodies.splice(i, 1); + } else if (front.length >= 3 && rear.length >= 3) { // doc: split into two smaller copies + body.segs = front; + const nb = pieceFrom(rear, (k + 1) * body.gap); + b.bodies.splice(i + 1, 0, nb); this.larryTurnSoon(nb); + this.ev('split'); + } else { // pieces too short to split: the chain closes up + body.segs = front.concat(rear); + this.larryTurnSoon(body); + } + if (!b.bodies.length) this.bossDeath(); + } + larryTurnSoon(body) { body.turnT = 0; body.must = 1; } + + // ---------------- The Duke of Flies ---------------- + // doc: floats diagonally, knockback can change direction; spawns 3 orbiting Attack Flies (max 6 orbit), a larger + // chasing Attack Fly, or sends 5-6 orbiting flies at Isaac; never more than 12 flies; approx: speeds, timings + updateDuke() { + const b = this.boss, p = this.player; + if (b.dead) return; + if (b.still > 0) { b.still--; return; } // waits for the VS banner like every boss + b.x += b.vx; b.y += b.vy; + const lx0 = ROOM.x0 + b.r, lx1 = ROOM.x1 - b.r, ly0 = ROOM.y0 + b.r, ly1 = ROOM.y1 - b.r; + if (b.x < lx0) { b.x = lx0; b.vx = Math.abs(b.vx); } else if (b.x > lx1) { b.x = lx1; b.vx = -Math.abs(b.vx); } + if (b.y < ly0) { b.y = ly0; b.vy = Math.abs(b.vy); } else if (b.y > ly1) { b.y = ly1; b.vy = -Math.abs(b.vy); } + b.orbitA += 0.04 + 0.015 * this.d; + if (b.wind > 0) { + if (--b.wind === 0) this.dukeAct(b.pending); + return; + } + if (--b.timer > 0) return; + // doc: release needs 5-6 orbiting flies; at 4 orbiting he can neither release nor spawn 3 more (max 6 orbit), so he + // spawns a large chaser; never more than 12 flies. approx: the weights below + const orbit = this.flies.filter(f => f.mode === 'orbit').length, total = this.flies.length; + let act = ''; + if (orbit >= 5) act = this.rand() < 0.85 || total >= 12 ? 'release' : 'big'; + else if (orbit !== 4 && orbit + 3 <= 6 && total + 3 <= 12) { + if (!b.bag || !b.bag.length) { // approx: spawn / large fly come from a shuffled bag (2 spawns : 1 large fly) + const bag = ['spawn', 'spawn', 'big']; + for (let i = bag.length - 1; i > 0; i--) { const j = Math.floor(this.rand() * (i + 1)); const tmp = bag[i]; bag[i] = bag[j]; bag[j] = tmp; } + b.bag = bag; + } + act = b.bag.pop(); + } else if (total < 12) act = 'big'; + if (!act) { b.timer = 30; return; } + b.pending = act; b.wind = 24; b.last = act; + this.ev('duke_wind'); + } + dukeAct(act) { + const b = this.boss, p = this.player, F = BOSS.duke_of_flies; + // approx: one action every ~2.5-3.5 s; the Duke's pace scales gently with the tier because every summon also adds + // fly HP that has to be shot through (a steep curve turned hard into a pure attrition fight) + // approx: right after a spawn that fills the orbit to 5-6 he follows up quickly (the documented release window) + const full = act === 'spawn' && this.flies.filter(f => f.mode === 'orbit').length + 3 >= 5; + b.timer = Math.max(40, Math.round((150 + this.rand() * 60) * (1.15 - 0.35 * this.d) * (full ? 0.4 : 1))); + if (act === 'spawn') { + const fhp = F.flyHp; + for (let i = 0; i < 3; i++) this.flies.push({ id: this.nid(), mode: 'orbit', x: b.x, y: b.y + 16, vx: 0, vy: 0, kx: 0, ky: 0, r: 9, hp: fhp, max: fhp, big: 0, flash: -99, a: 0, born: this.t }); + this.ev('flies'); + } else if (act === 'big') { + const a = Math.atan2(p.y - b.y, p.x - b.x); + this.flies.push({ id: this.nid(), mode: 'chase', x: b.x + Math.cos(a) * 30, y: b.y + Math.sin(a) * 30, vx: Math.cos(a) * 2, vy: Math.sin(a) * 2, kx: 0, ky: 0, r: 13, hp: F.flyHp, max: F.flyHp, big: 1, flash: -99, a: 0, born: this.t }); + this.ev('big_fly'); + } else if (act === 'release') { + for (const f of this.flies) if (f.mode === 'orbit') { f.mode = 'chase'; const a = Math.atan2(f.y - b.y, f.x - b.x); f.vx = Math.cos(a) * 3; f.vy = Math.sin(a) * 3; } + this.ev('release'); this.shakeIt(2); + } + } + updateFlies() { + if (this.kind === 'famine') { this.updatePooters(); return; } + if (this.kind !== 'duke_of_flies') return; + const b = this.boss, p = this.player, orbit = this.flies.filter(f => f.mode === 'orbit'); + orbit.forEach((f, i) => { // orbit slots spread evenly; a fly eases into its slot + const a = b.orbitA + i * TAU / orbit.length, R = BOSS.duke_of_flies.orbitR; + const tx = b.x + Math.cos(a) * R, ty = b.y + Math.sin(a) * R; + f.x += (tx - f.x) * 0.2 + f.kx; f.y += (ty - f.y) * 0.2 + f.ky; f.a = a; + f.kx *= 0.7; f.ky *= 0.7; + }); + const fs = (2.0 + 0.8 * this.d) * TILE / HZ; + for (const f of this.flies) { + if (f.mode !== 'chase') continue; + const dx = p.x - f.x, dy = p.y - f.y, dd = hyp(dx, dy) || 1, sp = fs * (f.big ? 0.85 : 1); + const wob = Math.sin((this.t + f.id * 17) * 0.21) * 0.9; + f.vx += (dx / dd * sp - f.vx) * 0.07 - dy / dd * wob * 0.08; f.vy += (dy / dd * sp - f.vy) * 0.07 + dx / dd * wob * 0.08; + f.x += f.vx + f.kx; f.y += f.vy + f.ky; f.kx *= 0.75; f.ky *= 0.75; + f.x = clamp(f.x, ROOM.x0 + f.r, ROOM.x1 - f.r); f.y = clamp(f.y, ROOM.y0 + f.r, ROOM.y1 - f.r); + } + } + + // ---------------- shared helpers for ground walkers ---------------- + moveSolid(o, rr) { // axis-separated move against walls and obstacle cells; true when blocked on an axis + const r = rr || o.r * 0.8; + let blocked = false; + if (o.vx) { if (!this.solidAt(o.x + o.vx, o.y, r)) o.x += o.vx; else { blocked = true; o.vx = 0; } } + if (o.vy) { if (!this.solidAt(o.x, o.y + o.vy, r)) o.y += o.vy; else { blocked = true; o.vy = 0; } } + return blocked; + } + clearLine(a, b) { // no rock / poop cell between two points (sampled every 12 px) + const d = hyp(b.x - a.x, b.y - a.y), n = Math.max(1, Math.ceil(d / 12)); + for (let i = 1; i < n; i++) { const [c, r] = cellOf(a.x + (b.x - a.x) * i / n, a.y + (b.y - a.y) * i / n); if (this.cell(c, r)) return false; } + return true; + } + + // ---------------- Gemini ---------------- + // doc: two bosses joined by an umbilical cord; Contusion chases Isaac and periodically charges with rising speed, then + // stops to catch his breath; Suture, while attached, shoots at Isaac unless an obstacle is in the way; if Contusion dies + // first Suture detaches and charges furiously (high momentum, extra knockback that can speed him up); if Suture dies + // first nothing changes; rocks always appear. approx: speeds, timings, cord length + updateGemini() { + const b = this.boss, p = this.player, C = b.twins[0], S = b.twins[1]; + if (b.dead) return; + const wait = b.still > 0; + if (wait) b.still--; + if (!C.dead && !wait) { + const base = (1.7 + 0.6 * this.d) * TILE / HZ, dx = p.x - C.x, dy = p.y - C.y, dd = hyp(dx, dy) || 1; + C.face = dx >= 0 ? 1 : -1; + if (C.st === 'walk') { + let ux = dx / dd, uy = dy / dd; + if (C.side > 0) { C.side--; const tx = -uy * C.sideDir, ty = ux * C.sideDir; ux = tx; uy = ty; } // sidestep around a rock + C.vx = ux * base; C.vy = uy * base; + if (--C.timer <= 0) { C.st = 'charge'; C.timer = 80; C.ramp = 0; C.ca = Math.atan2(dy, dx); this.ev('gemini_charge'); } + } else if (C.st === 'charge') { // speed ramps up while he steers toward Isaac + C.ramp = Math.min(1, C.ramp + 1 / 40); + const sp = base * (1 + (1.4 + 0.6 * this.d) * C.ramp), want = Math.atan2(dy, dx); + C.ca += clamp(Math.atan2(Math.sin(want - C.ca), Math.cos(want - C.ca)), -0.045, 0.045); + C.vx = Math.cos(C.ca) * sp; C.vy = Math.sin(C.ca) * sp; + if (--C.timer <= 0) { C.st = 'rest'; C.timer = Math.round(75 - 20 * this.d); this.ev('gemini_rest'); } + } else { // rest: catches his breath + C.vx *= 0.8; C.vy *= 0.8; + if (--C.timer <= 0) { C.st = 'walk'; C.timer = Math.round((110 + this.rand() * 60) * this.gapMul); } + } + const ox = C.x, oy = C.y, blocked = this.moveSolid(C); + if (blocked && C.st === 'charge') { C.st = 'rest'; C.timer = Math.round(75 - 20 * this.d); this.shakeIt(3); this.ev('gemini_rest'); } // ran into a rock + else if (blocked && C.st === 'walk' && hyp(C.x - ox, C.y - oy) < base * 0.3 && C.side <= 0) { C.side = 30; C.sideDir = this.rand() < 0.5 ? 1 : -1; } + } + if (!S.dead) { if (b.attached && !C.dead) this.tetherSuture(wait); else if (!wait) this.frenzySuture(); } + } + tetherSuture(wait) { + const b = this.boss, C = b.twins[0], S = b.twins[1], p = this.player, B = BOSS.gemini; + const ax = C.x - p.x, ay = C.y - p.y, ad = hyp(ax, ay) || 1, sway = Math.sin(this.t * 0.06 + 1.3) * 0.8; + const tx = C.x + ax / ad * 40 - ay / ad * sway * 36, ty = C.y + ay / ad * 40 + ax / ad * sway * 36; // bobs behind Contusion + S.vx = S.vx * 0.84 + (tx - S.x) * 0.03; S.vy = S.vy * 0.84 + (ty - S.y) * 0.03; + this.moveSolid(S); + const dx = S.x - C.x, dy = S.y - C.y, d = hyp(dx, dy); + if (d > B.cord) { const nx = C.x + dx / d * B.cord, ny = C.y + dy / d * B.cord; if (!this.solidAt(nx, ny, S.r * 0.8)) { S.x = nx; S.y = ny; } } + if (wait) return; + if (S.wind > 0) { + if (--S.wind === 0 && p.dead === 0 && this.clearLine(S, p)) { this.shot(S.x, S.y - 6, Math.atan2(p.y - S.y, p.x - S.x), 4.0, false, 120); this.ev('suture_shot'); } + } else if (--S.timer <= 0) { + S.timer = Math.round((95 + this.rand() * 45) * this.gapMul); + if (this.clearLine(S, p)) { S.wind = 16; this.ev('suture_wind'); } // doc: no shot while Isaac is behind an obstacle + } + } + frenzySuture() { + const b = this.boss, S = b.twins[1], p = this.player; + if (S.st !== 'frenzy') { S.st = 'frenzy'; S.wind = 0; b.attached = false; this.ev('suture_frenzy'); this.shakeIt(3); } + const dx = p.x - S.x, dy = p.y - S.y, dd = hyp(dx, dy) || 1, acc = 0.14 + 0.06 * this.d, max = (4.4 + 1.2 * this.d) * TILE / HZ; + let ux = dx / dd, uy = dy / dd; + if (S.side > 0) { S.side--; const tx = -uy * S.sideDir, ty = ux * S.sideDir; ux = tx; uy = ty; } // goes around a rock + S.vx = (S.vx + ux * acc) * 0.994; S.vy = (S.vy + uy * acc) * 0.994; // high momentum: overshoots Isaac + const cap = max * (S.boost > 0 ? 1.5 : 1), sp = hyp(S.vx, S.vy); + if (sp > cap) { S.vx *= cap / sp; S.vy *= cap / sp; } + if (S.boost > 0) S.boost--; + const ovx = S.vx, ovy = S.vy, ox = S.x, oy = S.y; + if (this.moveSolid(S)) { // bounces off walls / rocks; fast hits rebound, slow pushes slide + if (!S.vx && Math.abs(ovx) > 1) S.vx = -ovx * 0.6; if (!S.vy && Math.abs(ovy) > 1) S.vy = -ovy * 0.6; + } + S.stuck = hyp(S.x - ox, S.y - oy) < 0.4 ? (S.stuck || 0) + 1 : 0; + if (S.stuck > 8 && !(S.side > 0)) { S.side = 36; S.sideDir = this.rand() < 0.5 ? 1 : -1; S.stuck = 0; } + } + + // ---------------- Famine ---------------- + // doc: phase 1 - charges horizontally across the screen when Isaac is to his left or right, continues off-screen and + // reappears from the opposite end; spawns Pooters (limit 2); at the limit he moves to line up with Isaac; Pooters in the + // charge die. Phase 2 (after enough damage) - body and horse explode, the head moves slowly toward Isaac like a Maw and + // stops to fire three projectiles in a spread. A whole heart of contact damage in both phases. + // approx: speeds, timings, phase-2 threshold (40% HP) + updateFamine() { + const b = this.boss, p = this.player, B = BOSS.famine; + if (b.dead) return; + if (b.still > 0) { b.still--; return; } + const R = { x0: ROOM.x0 + b.r, x1: ROOM.x1 - b.r, y0: ROOM.y0 + b.r, y1: ROOM.y1 - b.r * 0.6 }; + const gap = () => Math.max(30, Math.round((80 + this.rand() * 50) * this.gapMul)); + if (b.phase === 1) { + if (b.chargeCd > 0) b.chargeCd--; + const lane = p.dead === 0 && Math.abs(p.y - b.y) < M.famineBand(b) - 2; // Isaac to his left or right (inside the charge band) + if ((b.st === 'drift' || b.st === 'align') && lane && b.chargeCd === 0 && !b.off) { + b.st = 'rear'; b.timer = Math.round(28 - 8 * this.d); b.dir = p.x >= b.x ? 1 : -1; b.face = b.dir; this.ev('famine_rear'); + } + if (b.st === 'drift') { + if (hyp(b.tx - b.x, b.ty - b.y) < 6) { b.tx = R.x0 + this.rand() * (R.x1 - R.x0); b.ty = R.y0 + this.rand() * (R.y1 - R.y0); } + const a = Math.atan2(b.ty - b.y, b.tx - b.x), sp = 1.0 * TILE / HZ; + b.x += Math.cos(a) * sp; b.y += Math.sin(a) * sp; b.face = p.x >= b.x ? 1 : -1; + if (--b.timer <= 0) { + if (this.flies.filter(q => q.mode === 'pooter').length < 2) { b.st = 'summon'; b.timer = 26; this.ev('famine_wind'); } + else { b.st = 'align'; b.timer = 160; } + } + } else if (b.st === 'align') { // doc: at the Pooter limit he lines up horizontally with Isaac + const sp = (2.0 + 0.8 * this.d) * TILE / HZ, fx = p.x < CX ? R.x1 - TILE : R.x0 + TILE; + b.y = clamp(b.y + clamp(p.y - b.y, -sp, sp), R.y0, R.y1); + b.x += clamp(fx - b.x, -sp * 0.5, sp * 0.5); // approx: backs off for a long run-up + b.face = p.x >= b.x ? 1 : -1; + if (--b.timer <= 0) { b.st = 'drift'; b.timer = gap(); } + } else if (b.st === 'summon') { + if (--b.timer <= 0) { this.spawnPooter(b.x + b.face * 34, b.y + 6); b.st = 'drift'; b.timer = gap(); } + } else if (b.st === 'rear') { // telegraph: the horse rears, the lane is shown + if (--b.timer <= 0) { b.st = 'charge'; b.vx = b.dir * (8 + 3 * this.d) * TILE / HZ; b.wrapped = 0; this.ev('famine_charge'); this.shakeIt(2); } + } else if (b.st === 'charge') { + b.x += b.vx; + for (const q of this.flies) if (q.mode === 'pooter' && !q.dead && Math.abs(q.y - b.y) < b.r + q.r && Math.abs(q.x - b.x) < b.r + q.r) { + q.dead = 1; this.fx.push({ k: 'pop', x: q.x, y: q.y, t: this.t }); this.ev('pooter_trampled'); // doc: Pooters in the charge die + } + const out = 2.4 * b.r; + if (!b.wrapped && (b.x > ROOM.x1 + out || b.x < ROOM.x0 - out)) { b.x = b.dir > 0 ? ROOM.x0 - out : ROOM.x1 + out; b.wrapped = 1; this.ev('famine_wrap'); } + if (b.wrapped && (b.dir > 0 ? b.x > ROOM.x0 + 2.5 * TILE : b.x < ROOM.x1 - 2.5 * TILE)) { b.st = 'brake'; b.timer = 16; } + } else if (b.st === 'brake') { + b.vx *= 0.82; b.x += b.vx; + if (--b.timer <= 0) { b.vx = 0; b.st = 'drift'; b.timer = gap(); b.chargeCd = Math.round(70 - 25 * this.d); b.tx = b.x; b.ty = b.y; } + } + if (this.flies.some(q => q.dead)) this.flies = this.flies.filter(q => !q.dead); + b.off = b.x < ROOM.x0 - b.r * 0.5 || b.x > ROOM.x1 + b.r * 0.5; + if (b.hp <= b.maxHp * B.phase2 && !b.off && b.st !== 'charge') { // doc: body and horse explode, only the head remains + b.phase = 2; b.st = 'hmove'; b.timer = 50; b.r = B.headR; b.vx = 0; + b.x = clamp(b.x, ROOM.x0 + b.r, ROOM.x1 - b.r); b.y = clamp(b.y, ROOM.y0 + b.r, ROOM.y1 - b.r); + this.fx.push({ k: 'boom', x: b.x, y: b.y, r: 70, t: this.t, gore: 1 }); this.shakeIt(6); this.ev('famine_phase2'); + } + } else if (b.st === 'hmove') { // Maw-like: drifts toward Isaac + const dx = p.x - b.x, dy = p.y - b.y, dd = hyp(dx, dy) || 1, sp = (1.1 + 0.5 * this.d) * TILE / HZ; + if (dd > b.r + p.r + 6) { b.x += dx / dd * sp; b.y += dy / dd * sp; } + b.face = dx >= 0 ? 1 : -1; + if (--b.timer <= 0) { b.st = 'hstop'; b.timer = 22; this.ev('famine_spit_wind'); } + } else if (--b.timer <= 0) { // stops and fires three projectiles in a spread at Isaac + const a = Math.atan2(p.y - b.y, p.x - b.x); + for (const k of [-1, 0, 1]) this.shot(b.x, b.y - 4, a + k * 15 * DEG, 3.8, false, 110); + this.ev('famine_spit'); b.st = 'hmove'; b.timer = gap(); + } + } + spawnPooter(x, y) { + const hp = BOSS.famine.pooterHp; + this.flies.push({ id: this.nid(), mode: 'pooter', x: clamp(x, ROOM.x0 + 12, ROOM.x1 - 12), y: clamp(y, ROOM.y0 + 12, ROOM.y1 - 12), vx: 0, vy: 0, kx: 0, ky: 0, r: 10, hp, max: hp, + big: 0, flash: -99, a: 0, born: this.t, shootT: 70 + Math.floor(this.rand() * 50), wind: 0 }); + this.ev('pooter'); + } + updatePooters() { // doc: drift slowly toward Isaac, occasionally fire one blood shot; no contact damage. approx: rates + const p = this.player; + for (const q of this.flies) { + if (q.mode !== 'pooter') continue; + const dx = p.x - q.x, dy = p.y - q.y, dd = hyp(dx, dy) || 1, sp = 0.55 * TILE / HZ, wob = Math.sin((this.t + q.id * 23) * 0.05); + q.x += dx / dd * sp - dy / dd * wob * 0.4 + q.kx; q.y += dy / dd * sp + dx / dd * wob * 0.4 + q.ky; q.kx *= 0.75; q.ky *= 0.75; + q.x = clamp(q.x, ROOM.x0 + q.r, ROOM.x1 - q.r); q.y = clamp(q.y, ROOM.y0 + q.r, ROOM.y1 - q.r); + if (q.wind > 0) { if (--q.wind === 0 && p.dead === 0) { this.shot(q.x, q.y - 4, Math.atan2(p.y - q.y, p.x - q.x), 3.2, false, 110); this.ev('pooter_shot'); } } + else if (--q.shootT <= 0) { q.shootT = Math.round((130 + this.rand() * 60) * this.gapMul); if (dd < 6 * TILE) q.wind = 14; } + } + } + + // ---------------- Envy ---------------- + // doc (mini-boss): floats diagonally, bouncing off the walls; on death splits into 2 medium heads, each into 2 small ones, + // each into 2 even smaller ones; the heads speed up as they split (Super Envy's 3-way split is a different mini-boss: not used). + // approx: HP halves per generation, speeds, tier-scaled turns toward Isaac after a wall bounce and on a re-aim timer (engagement) + updateEnvy() { + const b = this.boss, p = this.player, bias = 0.35 + 0.4 * this.d; + if (b.dead) return; + if (b.still > 0) { b.still--; return; } + for (const h of b.heads) { + h.x += h.vx; h.y += h.vy; + let hit = 0; + if (h.x < ROOM.x0 + h.r) { h.x = ROOM.x0 + h.r; h.vx = Math.abs(h.vx); hit = 1; } else if (h.x > ROOM.x1 - h.r) { h.x = ROOM.x1 - h.r; h.vx = -Math.abs(h.vx); hit = 1; } + if (h.y < ROOM.y0 + h.r) { h.y = ROOM.y0 + h.r; h.vy = Math.abs(h.vy); hit = 2; } else if (h.y > ROOM.y1 - h.r) { h.y = ROOM.y1 - h.r; h.vy = -Math.abs(h.vy); hit = 2; } + if (hit && this.rand() < bias) { if (hit === 1) h.vy = Math.abs(h.vy) * (p.y >= h.y ? 1 : -1); else h.vx = Math.abs(h.vx) * (p.x >= h.x ? 1 : -1); } + // approx (engagement rule): a pure bounce can settle into an orbit that never crosses a standing Isaac, so every + // (60-100) x gap ticks a head turns its diagonal toward him with probability 0.75 + 0.25 d (still diagonal, same speed) + if (--h.aim <= 0) { + h.aim = Math.round((60 + this.rand() * 40) * this.gapMul); + if (this.rand() < 0.75 + 0.25 * this.d) { const v = Math.abs(h.vx); h.vx = (p.x >= h.x ? 1 : -1) * v; h.vy = (p.y >= h.y ? 1 : -1) * v; } + } + } + } + envyHead(g, x, y, sx, sy) { + const b = this.boss, B = BOSS.envy, v = B.speed[g] * this.spd * TILE / HZ / Math.SQRT2, hp = Math.max(1, Math.round(b.hp0 * B.hpShare[g])); + const kids = g >= 3 ? 0 : 2; + return { id: this.nid(), g, x, y, vx: sx * v, vy: sy * v, r: B.r[g], hp, max: hp, kids, flash: -99, born: this.t, dead: 0, aim: 40 + Math.floor(this.rand() * 40) }; + } + splitEnvy(h) { + const b = this.boss, dirs = [[1, 1], [-1, -1], [1, -1], [-1, 1]], k0 = this.rand() < 0.5 ? 0 : 2; + h.dead = 1; b.heads = b.heads.filter(q => q !== h); + this.fx.push({ k: 'pop', x: h.x, y: h.y, t: this.t, big: h.g < 2 ? 1 : 0 }); this.ev('envy_split'); this.shakeIt(h.g < 2 ? 4 : 2); + for (let i = 0; i < h.kids; i++) { + const [sx, sy] = dirs[(k0 + i) % 4], r = BOSS.envy.r[h.g + 1]; + b.heads.push(this.envyHead(h.g + 1, clamp(h.x + sx * h.r * 0.5, ROOM.x0 + r, ROOM.x1 - r), clamp(h.y + sy * h.r * 0.5, ROOM.y0 + r, ROOM.y1 - r), sx, sy)); + } + if (!b.heads.length) this.bossDeath(h.x, h.y); + } + } + + // xorshift32 from small seeds yields tiny first outputs; scramble with a murmur3 finaliser (same as other native games) + Game.mixSeed = function (seed) { + let x = ((seed >>> 0) ^ 0x9e3779b9) >>> 0; + x = Math.imul(x ^ (x >>> 16), 0x85ebca6b) >>> 0; + x = Math.imul(x ^ (x >>> 13), 0xc2b2ae35) >>> 0; + x = (x ^ (x >>> 16)) >>> 0; + return x || 0x6d2b79f5; + }; + M.Game = Game; + M.famineBand = b => b.r + ISAAC.r - 4; // Isaac's centre within this distance of Famine's footprint is hit (contact and charge) + M.slamRadius = b => b.r + 6; // landing attack area around Monstro's body centre (6 px wider than his contact body) + M.newGame = (id, seed, d, opts) => new Game(id, seed, d, opts); + M.cellX = cellX; M.cellY = cellY; M.cellOf = cellOf; + + // ======================= standard scripted controller ======================= + // Reads privileged state and never mutates it: candidates are simulated on JSON deep copies. + // The copy gets a synthetic RNG (seeded from the tick only): the live generator's next values are rolls that have not + // happened yet (a boss's next hop count, cough spread, summon choice ...), and reading them would be reading the future. + const MOVES = [[0, 0], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; + const memory = new WeakMap(); + M.clone = function (g) { const c = N.copy(g); Object.setPrototypeOf(c, Game.prototype); c.rng = Game.mixSeed((g.t * 2654435761 + 0x51ed27) >>> 0); return c; }; + function moveKeys(m) { + const k = []; + if (m[0] > 0) k.push('D'); else if (m[0] < 0) k.push('A'); + if (m[1] > 0) k.push('S'); else if (m[1] < 0) k.push('W'); + return k; + } + function simTick(sim, keys) { + const held = [...keys].sort(), pressed = held.filter(k => !sim.held.includes(k)); + sim.events = []; + sim.update(new Set(held), new Set(pressed), [0, 0, 0]); + sim.t++; + if (!sim.outcome && sim.t >= HZ * M.maxSeconds) sim.outcome = 'timeout'; + } + const holdIndex = (n, count) => Math.ceil(n * 6 / count) - 1; + // the part to shoot at: Monstro / its landing shadow, the best-aligned Larry segment, the Duke or a close chasing fly + function pickTarget(g) { + const p = g.player, b = g.boss; + if (g.kind === 'monstro') { if (b.dead) return null; return b.hidden ? { x: b.sx, y: b.sy, r: b.r, vx: 0, vy: 0 } : { x: b.x, y: b.y, r: b.r, vx: b.vx, vy: b.vy }; } + if (g.kind === 'larry_jr') { + let best = null, bs = 1e9; + for (const body of b.bodies) for (const s of body.segs) { // end segments first: killing a middle one splits Larry in two + const end = s === body.segs[0] || s === body.segs[body.segs.length - 1]; + const dx = s.x - p.x, dy = s.y - p.y, sc = Math.min(Math.abs(dx), Math.abs(dy)) + 0.25 * hyp(dx, dy) + (end ? 0 : 45); + if (sc < bs) { bs = sc; best = { x: s.x, y: s.y, r: BOSS.larry_jr.r, vx: body.dir[0] * body.speed, vy: body.dir[1] * body.speed }; } + } + return best; + } + if (g.kind === 'gemini') { // the twin that is easiest to line up; Suture first while he is tied (killing Contusion frees him) + let best = null, bs = 1e9; + for (const t of b.twins) if (!t.dead) { + const dx = t.x - p.x, dy = t.y - p.y, sc = Math.min(Math.abs(dx), Math.abs(dy)) + 0.25 * hyp(dx, dy) - (t.role === 'suture' && b.attached ? 30 : 0); + if (sc < bs) { bs = sc; best = { x: t.x, y: t.y, r: t.r, vx: t.vx, vy: t.vy }; } + } + return best; + } + if (g.kind === 'envy') { + let best = null, bs = 1e9; + for (const h of b.heads) { const dx = h.x - p.x, dy = h.y - p.y, sc = Math.min(Math.abs(dx), Math.abs(dy)) + 0.3 * hyp(dx, dy); if (sc < bs) { bs = sc; best = { x: h.x, y: h.y, r: h.r, vx: h.vx, vy: h.vy }; } } + return best; + } + if (g.kind === 'famine') { // Famine himself whenever he is on screen; Pooters only while he is off-screen + if (!b.dead && !b.off) return { x: b.x, y: b.y - (b.phase === 1 ? BOSS.famine.lift : 0), r: b.r, vx: b.st === 'charge' ? 0 : b.vx || 0, vy: 0 }; + let near = null, nd = 1e9; + for (const f of g.flies) { const dd = hyp(f.x - p.x, f.y - p.y); if (dd < nd) { nd = dd; near = { x: f.x, y: f.y, r: f.r, vx: 0, vy: 0 }; } } + return near; + } + let near = null, nd = 3.2 * TILE; + for (const f of g.flies) if (f.mode === 'chase') { const dd = hyp(f.x - p.x, f.y - p.y); if (dd < nd) { nd = dd; near = { x: f.x, y: f.y, r: f.r, vx: f.vx, vy: f.vy }; } } + if (near) return near; + if (!b.dead) return { x: b.x, y: b.y, r: b.r, vx: b.vx, vy: b.vy }; + for (const f of g.flies) { const dd = hyp(f.x - p.x, f.y - p.y); if (!near || dd < nd) { nd = dd; near = { x: f.x, y: f.y, r: f.r, vx: f.vx, vy: f.vy }; } } + return near; + } + const FOUR_WAY = new Set(['gemini', 'famine', 'envy']); // scenes 4-6 evaluate all four fire directions + const PREF = { monstro: [150, 270], larry_jr: [120, 260], duke_of_flies: [140, 280], gemini: [130, 260], famine: [100, 240], envy: [120, 250] }; + // Larry segments a tear fired from (x, y) along dir would cross (a piercing tear damages each of them once) + function laneHits(g, x, y, dir) { + const st = g.stats, lane = BOSS.larry_jr.r + st.tearR - 2, reach = ISAAC.tearSpeed * st.shotSpeed * st.life; + let n = 0; + for (const body of g.boss.bodies) for (const sg of body.segs) { + const dx = sg.x - x, dy = sg.y - y, along = dx * dir[0] + dy * dir[1], off = Math.abs(dx * dir[1] - dy * dir[0]); + if (along > 0 && along < reach && off < lane) n++; + } + return n; + } + function evaluate(g, holds, follow, horizon, axis, fireDir) { + const sim = M.clone(g), p0 = sim.player, hp0 = p0.hp, dealt0 = sim.stat.dealt, kills0 = sim.stat.kills; + const count = HZ / 5; + for (let n = 1; n <= count && !sim.outcome; n++) simTick(sim, holds[holdIndex(n, count)]); + const lost1 = hp0 - sim.player.hp; + for (let n = 0; n < horizon && !sim.outcome; n++) simTick(sim, follow); + const p = sim.player, lost2 = hp0 - p.hp - lost1; + let score = -1100 * lost1 - 700 * lost2; + if (sim.outcome === 'loss' || p.dead > 0) score -= 1e6; + if (sim.outcome === 'win' || sim.clearT >= 0) score += 6000; + score += 4 * (sim.stat.dealt - dealt0) + 25 * (sim.stat.kills - kills0); + const tg = pickTarget(sim), b = sim.boss; + if (tg) { + const dx = tg.x - p.x, dy = tg.y - p.y, d = hyp(dx, dy), [lo, hi] = PREF[g.kind]; + const off = axis === 'v' ? Math.abs(dx) : Math.abs(dy); + const lane = axis === 'v' ? { x: p.x, y: tg.y } : { x: tg.x, y: p.y }; // where a straight tear meets the target + const open = !sim.cells.some(v => v === 1) || sim.clearLine(p, lane); + const facing = !FOUR_WAY.has(g.kind) || !fireDir || dx * fireDir[0] + dy * fireDir[1] > 0; + score += (open && facing ? 55 : 0) * Math.max(0, 1 - off / (tg.r + 8)) - 0.25 * off; + if (d < lo) score -= (lo - d) * 1.4; else if (d > hi) score -= (d - hi) * 0.5; + } + const margin = Math.min(p.x - ROOM.x0, ROOM.x1 - p.x, p.y - ROOM.y0, ROOM.y1 - p.y); + if (margin < 44) score -= (44 - margin) * 1.8; + for (const s of sim.shots) { const dd = hyp(s.x - p.x, s.y - p.y); if (dd < 58) score -= (58 - dd) * 0.7 * s.dmg; } + for (const f of sim.flies) { if (f.mode === 'pooter') continue; const dd = hyp(f.x - p.x, f.y - p.y); if (dd < f.r + 46) score -= (f.r + 46 - dd) * 2.2; } + if (g.kind === 'monstro' && !b.dead) { + if (b.hidden || b.st === 'fall') { const dd = hyp(b.sx - p.x, b.sy - p.y), lim = b.r + 60 + (b.st === 'lock' || b.st === 'fall' ? 30 : 0); if (dd < lim) score -= (lim - dd) * (b.st === 'track' ? 1.5 : 6); } + else { const dd = hyp(b.x - p.x, b.y - p.y); if (dd < b.r + 60) score -= (b.r + 60 - dd) * 3; } + } else if (g.kind === 'larry_jr') { + if (fireDir && g.stats.pierce) score += 16 * Math.min(5, laneHits(sim, p.x, p.y, fireDir)); // lines up several segments + for (const body of b.bodies) { + for (const s of body.segs) { const dd = hyp(s.x - p.x, s.y - p.y); if (dd < 70) score -= (70 - dd) * 2.4; } + if (body.segs.length) { // keep out of the head's lane + const h = body.segs[0], ax = h.x + body.dir[0] * 80, ay = h.y + body.dir[1] * 80; + const dd = N.segmentDistance(p, h, { x: ax, y: ay }); if (dd < 40) score -= (40 - dd) * 2; + } + } + for (let i = 0; i < sim.cells.length; i++) if (sim.cells[i]) { const dd = hyp(cellX(i % ROOM.cols) - p.x, cellY(Math.floor(i / ROOM.cols)) - p.y); if (dd < 40) score -= (40 - dd) * 0.6; } + } else if (g.kind === 'gemini') { + for (const t of b.twins) if (!t.dead) { + const lim = t.r + (t.role === 'contusion' ? (t.st === 'charge' ? 95 : 60) : (t.st === 'frenzy' ? 95 : 40)), dd = hyp(t.x - p.x, t.y - p.y); + if (dd < lim) score -= (lim - dd) * 2.6; + } + for (let i = 0; i < sim.cells.length; i++) if (sim.cells[i]) { const dd = hyp(cellX(i % ROOM.cols) - p.x, cellY(Math.floor(i / ROOM.cols)) - p.y); if (dd < 40) score -= (40 - dd) * 0.6; } + } else if (g.kind === 'famine') { + if (!b.dead) { + const dy = Math.abs(p.y - b.y), lane = b.r + p.r + 12; + if (b.phase === 1) { + if ((b.st === 'rear' || b.st === 'charge' || b.st === 'brake') && dy < lane) score -= (lane - dy) * 9; + else if (b.chargeCd === 0 && dy < lane - 8) score -= (lane - 8 - dy) * 1.2; // do not loiter in his lane + } + if (!b.off) { const dd = hyp(b.x - p.x, b.y - p.y), lim = b.r + (b.phase === 1 ? 70 : 60); if (dd < lim) score -= (lim - dd) * 3; } + } + } else if (g.kind === 'envy') { + for (const h of b.heads) { const dd = hyp(h.x - p.x, h.y - p.y), lim = h.r + 50 + 10 * h.g; if (dd < lim) score -= (lim - dd) * 2.4; } + } else if (!b.dead) { const dd = hyp(b.x - p.x, b.y - p.y); if (dd < b.r + 64) score -= (b.r + 64 - dd) * 2.6; } + return score; + } + M.scripted = function (g) { + const p = g.player; + let mem = memory.get(g); + if (!mem || g.t === 0) { mem = { last: 0, axis: 'h' }; memory.set(g, mem); } + const idle = { holds: [[], [], [], [], [], []], mouse: [0, 0, 0] }; + if (p.dead > 0 || g.outcome) return idle; + const tg = pickTarget(g); + let best = null; + if (FOUR_WAY.has(g.kind)) { + // look further ahead while Contusion charges or is about to (he outruns Isaac; the dodge must start early) + const C0 = g.kind === 'gemini' ? g.boss.twins[0] : null; + // also further ahead while several of Envy's fast small heads are near (they close 3-4 px per tick) + const swarm = g.kind === 'envy' && g.boss.heads.filter(h => h.g >= 2 && hyp(h.x - g.player.x, h.y - g.player.y) < 160).length >= 3; + const horizon = (C0 && !C0.dead && (C0.st === 'charge' || (C0.st === 'walk' && C0.timer < 24))) || swarm ? 30 : 18; + for (const [axis, fire] of [['h', 'J'], ['h', 'L'], ['v', 'Shift'], ['v', 'K']]) for (let i = 0; i < MOVES.length; i++) { + const keys = [...moveKeys(MOVES[i]), fire], holds = [keys, keys, keys, keys, keys, keys]; + let sc = evaluate(g, holds, keys, horizon, axis, FIRE[fire]); + if (i === mem.last && fire === mem.fire) sc += 10; + if (!best || sc > best.s) best = { s: sc, holds, i, axis, fire }; + } + mem.last = best.i; mem.axis = best.axis; mem.fire = best.fire; + return { holds: best.holds.map(h => h.slice(0, 4)), mouse: [0, 0, 0] }; + } + for (const axis of ['h', 'v']) { + let fire = null; + if (tg) { + const lead = hyp(tg.x - p.x, tg.y - p.y) / (ISAAC.tearSpeed * g.stats.shotSpeed); + const tx = tg.x + tg.vx * lead * 0.6, ty = tg.y + tg.vy * lead * 0.6; + fire = axis === 'v' ? (ty < p.y ? 'Shift' : 'K') : (tx < p.x ? 'J' : 'L'); + if (g.kind === 'larry_jr' && g.stats.pierce) { // on this axis, shoot the side whose lane holds more segments + const [k1, k2] = axis === 'v' ? ['Shift', 'K'] : ['J', 'L'], n1 = laneHits(g, p.x, p.y, FIRE[k1]), n2 = laneHits(g, p.x, p.y, FIRE[k2]); + if (n1 !== n2) fire = n1 > n2 ? k1 : k2; + } + } + for (let i = 0; i < MOVES.length; i++) { + const mk = moveKeys(MOVES[i]), keys = fire ? [...mk, fire] : mk; + const holds = [keys, keys, keys, keys, keys, keys]; + let s = evaluate(g, holds, keys, 18, axis, fire ? FIRE[fire] : null); + if (i === mem.last && axis === mem.axis) s += 10; + if (!best || s > best.s) best = { s, holds, i, axis }; + } + } + mem.last = best.i; mem.axis = best.axis; + return { holds: best.holds.map(h => h.slice(0, 4)), mouse: [0, 0, 0] }; + }; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/isaac_remake/index.html b/environments/games/web/games/isaac_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..6f46ac24b4a7153ee63899da5792ccaebd456784 --- /dev/null +++ b/environments/games/web/games/isaac_remake/index.html @@ -0,0 +1,9 @@ + +The Binding of Isaac · Basement Bosses +
      +

      The Binding of Isaac · Basement Bosses

      Basement boss rooms · Isaac · Rules isaac-basement@3 · 6 bosses · Local play · Recording and replay

      Back to Game Lobby
      +
      Select a boss to start

      Isaac starts with three red hearts (tracked in half hearts) and one bomb. Move and fire tears independently in four directions; tears inherit some of your movement speed. The boss room stays sealed during combat. Clear the boss and remaining flies or other small enemies to open the door, reveal an item pedestal, and unlock the trapdoor. Six bosses await: Monstro, Larry Jr., Duke of Flies, Gemini, Famine, and Envy. Each has a fixed starting item build shown on the right for reproducible evaluation. Items change fire rate, damage, range, and tear behavior. Easy, Normal, and Hard increase boss health, attack frequency, and damage; on Hard, half-heart hits become full-heart hits. Replays save inputs and the seed so the fight and final state can be reproduced. The scripted demo reads internal state and issues legal key presses for verification.

      +
      +
      All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
      + diff --git a/environments/games/web/games/isaac_remake/manifest.json b/environments/games/web/games/isaac_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..264e83acd45870c22f1830d1bd85e4827b655002 --- /dev/null +++ b/environments/games/web/games/isaac_remake/manifest.json @@ -0,0 +1,31 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "isaac_remake", + "module": "IsaacGame", + "title": "The Binding of Isaac: Basement Bosses", + "dimension": "2d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "canvas-native", + "rules": "isaac-basement@3", + "cases": [ + "isaac/monstro", + "isaac/larry_jr", + "isaac/duke_of_flies", + "isaac/gemini", + "isaac/famine", + "isaac/envy" + ], + "scripts": [ + "_native/runtime.js", + "isaac_remake/game.js", + "isaac_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "isaac_remake/game.js" + ], + "play_page": "web/games/isaac_remake/index.html", + "scripted_controller": "IsaacGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]} (alias .oracle)" +} diff --git a/environments/games/web/games/kirby_remake/arena.js b/environments/games/web/games/kirby_remake/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..cf74b16e073683e1c7a39d9b9b9059acb10e4291 --- /dev/null +++ b/environments/games/web/games/kirby_remake/arena.js @@ -0,0 +1,13 @@ +// Arena geometry, in game units (u). Origin = left wall / floor surface, y up. +// [data] Kirby's Dream Land (GB) units: 8 px = 1 u, so the 160 px wide screen is 20 u; one frame = one 60 Hz tick +// (1 px/frame = 7.5 u/s, 1 px/frame^2 = 450 u/s^2). The viewport is one screen wide: the floor surface is put +// 112 px below the top of the play field [hand: the 128 px field minus one floor tile], so H = 14 u. +(function (g) { + var BB = g.BB; + BB.ARENA = { W: 20, H: 14, + gx: function (px) { return (px - 8) / 8; }, // source coordinates include OAM x+8 / y+16 + gy: function (py) { return (128 - py) / 8; } }; + // [data] MT_DEDEDE_5: 288 px world, ScriptFunc_LockScrolling: fixed viewport. + // [hand] viewport centred on the source rope thresholds 72/232 (OAM x+8); exact entry scroll is not emulated. + BB.KIRBY_RING = { W: 36, H: 14, LEFT: 8, RIGHT: 28, cameraX: 8 }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/art/scenes.js b/environments/games/web/games/kirby_remake/art/scenes.js new file mode 100644 index 0000000000000000000000000000000000000000..587b76ba7a3a2f1ab8228b3e0dddc41e47c07f22 --- /dev/null +++ b/environments/games/web/games/kirby_remake/art/scenes.js @@ -0,0 +1,298 @@ +// The rooms, after the original's stages: Green Greens (tall pale trunks under a scalloped, fruit-dotted canopy), +// Bubbly Clouds (sunlit sky streaks, scalloped cloud platforms), the ring on Mt. Dedede (a diagonal-brick castle +// hall) and the open Green Greens meadow of the Poppy Bros. Sr. fight (puffy clouds, round hedges, a domed door hut). Built once per case from fixed art seeds into cached canvases; never touches the simulation or its RNG. +// Original procedural art: shapes and colours are this project's own, nothing is traced from the game. +(function (g) { + var BB = g.BB, D = BB.KIRBY_DRAW, P = BB.VIEW.PAL, V = BB.VIEW, TAU = Math.PI * 2; + var rooms = { 'kirby/whispy_woods': 'forest', 'kirby/kracko': 'clouds', 'kirby/king_dedede': 'ring', 'kirby/poppy_bros_sr': 'meadow', 'kirby/lololo_lalala': 'castle', 'kirby/kaboola': 'sky' }; + function vgrad(x, y0, y1, stops) { var gr = x.createLinearGradient(0, y0, 0, y1); stops.forEach(function (s) { gr.addColorStop(s[0], s[1]); }); return gr; } + // a scalloped band edge: bumps of radius r along y from x0 to x1 (bumps hang downward when down = true) + function scallop(x, x0, x1, y, r, down, jitter, rng) { + for (var X = x0; X <= x1 + r; X += r * 1.6) { + var rr = r * (1 + (jitter ? rng.uniform(-jitter, jitter) : 0)); + x.moveTo(X + rr, y); x.arc(X, y, rr, 0, TAU); + } + } + + // ---------------- Green Greens ---------------- + function forest(x, f, W, rng) { + var FL = V.FLOOR; + x.fillStyle = vgrad(x, 0, FL, [[0, '#a9dcf2'], [0.55, '#dff4ef'], [1, '#f6f1d8']]); x.fillRect(0, 0, W, V.H); + // far hills + [['#cde9c5', 330, 70], ['#b3dcae', 372, 55]].forEach(function (h, k) { + x.fillStyle = h[0]; x.beginPath(); x.moveTo(0, FL); + for (var X = -40; X <= W + 80; X += 120) x.quadraticCurveTo(X + 60, h[1] - rng.uniform(0, h[2]), X + 120, h[1] + 10); + x.lineTo(W, FL); x.closePath(); x.fill(); + }); + // back row of tall Green Greens trunks (pale, vertical grain), low contrast so they never read as hazards + for (var X = 30; X < W; X += 128 + rng.uniform(-14, 14)) { + var tw = rng.uniform(40, 54), x0 = X - tw / 2; + x.fillStyle = vgrad(x, 120, FL, [[0, '#efe3c6'], [1, '#e2cfa6']]); x.fillRect(x0, 110, tw, FL - 110); + x.fillStyle = 'rgba(160,120,80,0.18)'; x.fillRect(x0 + tw - 9, 110, 9, FL - 110); + x.strokeStyle = 'rgba(150,110,70,0.25)'; x.lineWidth = 2; + for (var k = 0; k < 3; k++) { var lx = x0 + 9 + k * (tw - 18) / 2; x.beginPath(); x.moveTo(lx, 130 + rng.uniform(0, 30)); x.lineTo(lx + rng.uniform(-2, 2), FL - rng.uniform(10, 60)); x.stroke(); } + } + // tall grass tufts behind the play line + for (X = 0; X < W; X += 26) { + var h = rng.uniform(22, 44), sx = X + rng.uniform(-6, 6); + x.fillStyle = rng.chance(0.5) ? '#8fcf7b' : '#7cc56b'; x.beginPath(); x.moveTo(sx - 12, FL); + x.quadraticCurveTo(sx - 6, FL - h * 0.6, sx - 9, FL - h); x.quadraticCurveTo(sx - 1, FL - h * 0.55, sx + 2, FL - h * 0.9); + x.quadraticCurveTo(sx + 5, FL - h * 0.5, sx + 12, FL - h * 0.75); x.quadraticCurveTo(sx + 9, FL - h * 0.3, sx + 13, FL); x.closePath(); x.fill(); + } + // the canopy band across the top, scalloped underside, dotted with fruit and light + var CB = 112; + x.fillStyle = P.leafDark; x.fillRect(0, 0, W, CB); + x.beginPath(); scallop(x, -10, W + 10, CB, 26, true, 0.25, rng); x.fill(); + x.fillStyle = P.leaf; x.fillRect(0, 0, W, CB - 14); + x.beginPath(); scallop(x, 6, W + 10, CB - 14, 22, true, 0.25, rng); x.fill(); + x.fillStyle = '#3f9c5a'; + for (var i = 0; i < 70; i++) D.ellipse(x, rng.uniform(0, W), rng.uniform(4, CB - 30), rng.uniform(10, 22), rng.uniform(7, 14), i % 3 ? '#3f9c5a' : '#4aa864'); + for (i = 0; i < 46; i++) { + var bx = rng.uniform(4, W - 4), by = rng.uniform(8, CB - 10), br = rng.uniform(2.5, 5.5); + D.ellipse(x, bx, by, br, br, rng.chance(0.3) ? '#ffd6a8' : '#e9f7d9'); + if (br > 4.5) D.sparkle(x, bx + br + 2, by - br, 3, '#ffffff'); + } + // floor: grass lip, dotted soil (the GB floor tile's dots) + x.fillStyle = '#6fb85d'; x.fillRect(0, FL - 4, W, 6); + x.fillStyle = '#c99b5c'; x.fillRect(0, FL + 2, W, V.H - FL); + x.fillStyle = 'rgba(255,240,200,0.55)'; + for (X = 3; X < W; X += 9) for (var Y = FL + 5; Y < V.H; Y += 6) x.fillRect(X + ((Y / 6) % 2) * 4, Y, 2, 2); + f.fillStyle = '#5aa84d'; + for (X = 0; X < W; X += 14) { f.beginPath(); f.moveTo(X, FL + 1); f.lineTo(X + 4, FL - 5 - (X * 7 % 5)); f.lineTo(X + 8, FL + 1); f.closePath(); f.fill(); } + } + // ---------------- Green Greens meadow (the Poppy Bros. Sr. screen) ---------------- + function meadow(x, f, W, rng) { + var FL = V.FLOOR; + x.fillStyle = vgrad(x, 0, FL, [[0, '#9fd6f4'], [0.6, '#dff3f7'], [1, '#f7f2dc']]); x.fillRect(0, 0, W, V.H); + // big puffy clouds with a flat underside, as on the GB stage + [[150, 110, 92, 40], [520, 80, 70, 30], [760, 170, 96, 42], [330, 220, 60, 24]].forEach(function (cl) { + x.save(); x.globalAlpha = 0.95; + D.cloudBlob(x, cl[0], cl[1], cl[2], cl[3], 9, '#ffffff', 'rgba(150,170,214,0.55)', 2.5, rng.uniform(0, 1)); + x.fillStyle = 'rgba(205,220,245,0.9)'; D.round(x, cl[0] - cl[2] * 0.8, cl[1] + cl[3] * 0.45, cl[2] * 1.6, 7, 3.5); x.fill(); + x.restore(); + }); + // far hills + [['#cdebc7', 360, 60], ['#b5dfae', 392, 46]].forEach(function (h) { + x.fillStyle = h[0]; x.beginPath(); x.moveTo(0, FL); + for (var X = -40; X <= W + 80; X += 140) x.quadraticCurveTo(X + 70, h[1] - rng.uniform(0, h[2]), X + 140, h[1] + 8); + x.lineTo(W, FL); x.closePath(); x.fill(); + }); + // the domed door hut on the left (a stage door, not a platform: faded so it reads as scenery) + var hx = 190, hw = 150, top = FL - 214; + x.save(); x.globalAlpha = 0.55; + x.beginPath(); x.moveTo(hx - hw / 2, FL); x.lineTo(hx - hw / 2, top + hw / 2); x.arc(hx, top + hw / 2, hw / 2, Math.PI, 0); x.lineTo(hx + hw / 2, FL); x.closePath(); + x.fillStyle = '#fbf7ee'; x.fill(); x.lineWidth = 4; x.strokeStyle = '#8f86b0'; x.stroke(); + x.fillStyle = 'rgba(160,150,200,0.35)'; x.fillRect(hx + hw / 2 - 16, top + hw / 2, 12, FL - top - hw / 2); + x.beginPath(); x.moveTo(hx - 24, FL); x.lineTo(hx - 24, FL - 70); x.arc(hx, FL - 70, 24, Math.PI, 0); x.lineTo(hx + 24, FL); x.closePath(); + x.fillStyle = '#3b3358'; x.fill(); + D.star(x, hx, top + 50, 16, P.gold, 0, 1.6); + x.restore(); + // round-topped hedges along the back (rounded arches, after the GB tiles) + for (var X = 20; X < W; X += 74 + rng.uniform(-10, 14)) { + if (Math.abs(X - hx) < hw * 0.75) continue; + var hh = rng.uniform(46, 78), hw2 = rng.uniform(34, 50); + x.beginPath(); x.moveTo(X - hw2 / 2, FL); x.lineTo(X - hw2 / 2, FL - hh + hw2 / 2); x.arc(X, FL - hh + hw2 / 2, hw2 / 2, Math.PI, 0); x.lineTo(X + hw2 / 2, FL); x.closePath(); + x.fillStyle = rng.chance(0.5) ? '#8fd08a' : '#7cc77a'; x.fill(); x.lineWidth = 3; x.strokeStyle = 'rgba(40,110,60,0.55)'; x.stroke(); + x.strokeStyle = 'rgba(255,255,255,0.45)'; x.lineWidth = 3; x.beginPath(); x.arc(X, FL - hh + hw2 / 2, hw2 / 2 - 7, Math.PI * 1.1, Math.PI * 1.6); x.stroke(); + } + // floor: grass lip and a soil band with tufts and dots (the GB ground tiles) + x.fillStyle = '#6fb85d'; x.fillRect(0, FL - 4, W, 6); + x.fillStyle = '#d6b07a'; x.fillRect(0, FL + 2, W, V.H - FL); + x.fillStyle = 'rgba(255,244,214,0.6)'; + for (X = 4; X < W; X += 10) for (var Y = FL + 6; Y < V.H; Y += 6) x.fillRect(X + ((Y / 6) % 2) * 5, Y, 2, 2); + f.fillStyle = '#5aa84d'; + for (X = 0; X < W; X += 16) { f.beginPath(); f.moveTo(X, FL + 1); f.lineTo(X + 5, FL - 6 - (X * 7 % 5)); f.lineTo(X + 10, FL + 1); f.closePath(); f.fill(); } + } + // ---------------- Castle Lololo (the Lololo & Lalala room) ---------------- + // Four corridors over three brick ledges; every ledge block is drawn exactly at its collision box from + // BB.KIRBY_CASTLE (body_kirby_castle.js): solid bricks as framed stone panels, the one-way bridges as thin slats. + // The doors at both ends of every corridor are where the brothers appear. Diagonal checks on the walls follow the + // GB room's wallpaper; colours are this project's own. + function castle(x, f, W, rng) { + var FL = V.FLOOR, R = BB.KIRBY_CASTLE, S = V.S, OX = V.OX; + function sx(u) { return OX + u * S; } function sy(u) { return FL - u * S; } + x.fillStyle = vgrad(x, 0, FL, [[0, '#f6e3b8'], [1, '#f2d9a6']]); x.fillRect(0, 0, W, V.H); + x.save(); x.beginPath(); x.rect(OX, sy(R.H), R.W * S, R.H * S); x.clip(); // wallpaper: pale diagonal checks + for (var X = -V.H; X < W + V.H; X += 44) { + x.fillStyle = 'rgba(160,185,215,0.42)'; + x.beginPath(); x.moveTo(X, 0); x.lineTo(X + 22, 0); x.lineTo(X + 22 + V.H, V.H); x.lineTo(X + V.H, V.H); x.closePath(); x.fill(); + } + x.restore(); + // doors at both ends of each corridor (row centres 1 / 5 / 9 / 13 u) + [1, 5, 9, 13].forEach(function (cy) { + [0.95, R.W - 0.95].forEach(function (cx) { + var X0 = sx(cx), Y0 = sy(cy); + x.beginPath(); x.moveTo(X0 - 22, Y0 + 30); x.lineTo(X0 - 22, Y0 - 12); x.arc(X0, Y0 - 12, 22, Math.PI, 0); x.lineTo(X0 + 22, Y0 + 30); x.closePath(); + x.fillStyle = '#4a3b5e'; x.fill(); x.lineWidth = 3; x.strokeStyle = '#2d2340'; x.stroke(); + x.fillStyle = 'rgba(255,220,150,0.18)'; x.fillRect(X0 - 16, Y0 - 10, 32, 38); + }); + }); + function brick(X, Y, w, h) { // framed stone panel with a woven centre + D.round(x, X + 1, Y + 1, w - 2, h - 2, 4); x.fillStyle = '#b9c7a4'; x.fill(); x.lineWidth = 3; x.strokeStyle = '#2f3b2a'; x.stroke(); + D.round(x, X + 7, Y + 9, w - 14, h - 18, 6); x.fillStyle = '#6f8f5c'; x.fill(); x.lineWidth = 2; x.stroke(); + x.fillStyle = 'rgba(220,235,190,0.65)'; + for (var i = X + 12; i < X + w - 12; i += 10) for (var j = Y + 14; j < Y + h - 12; j += 10) x.fillRect(i + ((j / 10) % 2) * 5, j, 3, 3); + x.fillStyle = 'rgba(255,255,255,0.35)'; x.fillRect(X + 4, Y + 4, w - 8, 3); + } + R.solid.forEach(function (b) { // solid blocks in 2 u (16 px) tiles, as on the GB tile grid + for (var u = b.x0; u < b.x1 - 1e-9; u += 2) brick(sx(u), sy(b.y1), Math.min(2, b.x1 - u) * S, (b.y1 - b.y0) * S); + }); + R.bridge.forEach(function (b) { // one-way bridges: a thin slat on top, open below + var X0 = sx(b.x0), X1 = sx(b.x1), Y0 = sy(b.y1); + for (var u = b.x0; u < b.x1 - 1e-9; u += 2) { + D.round(x, sx(u) + 2, Y0, 2 * S - 4, 16, 4); x.fillStyle = '#d8e2ef'; x.fill(); x.lineWidth = 2.5; x.strokeStyle = '#2f3b2a'; x.stroke(); + x.fillStyle = 'rgba(255,255,255,0.6)'; x.fillRect(sx(u) + 6, Y0 + 3, 2 * S - 12, 3); + } + x.strokeStyle = 'rgba(47,59,42,0.35)'; x.setLineDash([4, 6]); x.lineWidth = 1.5; + x.beginPath(); x.moveTo(X0, sy(b.y0)); x.lineTo(X1, sy(b.y0)); x.stroke(); x.setLineDash([]); + }); + for (X = 0; X < R.W; X += 2) brick(sx(X), FL, 2 * S, V.H - FL + 4); // the floor row + x.fillStyle = '#2d2340'; x.fillRect(0, 0, W, sy(R.H)); // ceiling band above the top corridor + } + // ---------------- Bubbly Clouds ---------------- + function platform(x, X, Y, w, h, rng) { // a GB-style cloud ledge: scalloped rim, shaded underside + x.save(); + x.beginPath(); D.round(x, X, Y, w, h, h / 2); + scallop(x, X + h * 0.4, X + w - h * 0.4, Y + 2, h * 0.32, false, 0.12, rng); + x.lineWidth = 5; x.strokeStyle = P.cloudRim; x.stroke(); x.fillStyle = '#ffffff'; x.fill(); + x.fillStyle = 'rgba(176,192,236,0.75)'; D.round(x, X + 6, Y + h * 0.58, w - 12, h * 0.34, h * 0.17); x.fill(); + x.restore(); + } + function clouds(x, f, W, rng) { + var FL = V.FLOOR; + x.fillStyle = vgrad(x, 0, FL, [[0, '#6f9fe8'], [0.5, '#a9c6f5'], [1, '#e6dcf7']]); x.fillRect(0, 0, W, V.H); + // diagonal light streaks (the Bubbly Clouds sky) + x.save(); x.globalAlpha = 0.22; x.fillStyle = '#ffffff'; + for (var k = 0; k < 6; k++) { + var s0 = -200 + k * 190 + rng.uniform(-30, 30), wd = rng.uniform(40, 90); + x.beginPath(); x.moveTo(s0, 0); x.lineTo(s0 + wd, 0); x.lineTo(s0 + wd + 380, FL); x.lineTo(s0 + 380, FL); x.closePath(); x.fill(); + } + x.restore(); + for (var i = 0; i < 26; i++) D.sparkle(x, rng.uniform(10, W - 10), rng.uniform(60, 330), rng.uniform(2, 4.5), 'rgba(255,255,255,0.85)'); + // big soft cloud banks, far to near + [[150, 160, 120, 64, '#eef1fd'], [700, 120, 140, 70, '#eef1fd'], [420, 300, 170, 62, '#f6f2ff'], [40, 360, 120, 50, '#f6f2ff'], [820, 350, 130, 56, '#f6f2ff']].forEach(function (c) { + x.save(); x.globalAlpha = 0.6; D.cloudBlob(x, c[0], c[1], c[2], c[3], 11, c[4], 'rgba(160,176,226,0.45)', 0.01, rng.uniform(0, 1)); x.restore(); + }); + // far cloud ledges: faded, so they never read as platforms (the arena has only its floor) + x.save(); x.globalAlpha = 0.3; platform(x, 24, 196, 120, 26, rng); platform(x, 690, 250, 130, 28, rng); x.restore(); + // the floor: one long cloud ledge, bumps along its top + x.fillStyle = '#ffffff'; x.fillRect(0, FL - 4, W, V.H - FL + 4); + x.fillStyle = 'rgba(176,192,236,0.6)'; x.fillRect(0, FL + 6, W, V.H - FL); + x.beginPath(); scallop(x, -4, W + 4, FL - 4, 13, false, 0.15, rng); x.fillStyle = '#ffffff'; x.fill(); + x.strokeStyle = P.cloudRim; x.lineWidth = 2; x.beginPath(); x.moveTo(0, FL + 1); x.lineTo(W, FL + 1); x.stroke(); + } + // ---------------- the ring on Mt. Dedede ---------------- + function ring(x, f, W, rng, wx) { // wx(u) = canvas x of world x + var FL = V.FLOOR, L = wx(BB.KIRBY_RING.LEFT), R = wx(BB.KIRBY_RING.RIGHT); + x.fillStyle = vgrad(x, 0, FL, [[0, '#2b2650'], [1, '#433d74']]); x.fillRect(0, 0, W, V.H); + // diagonal brick wall (Mt. Dedede's hall) + x.save(); x.beginPath(); x.rect(0, 0, W, 300); x.clip(); + x.translate(0, 0); x.rotate(-0.42); + for (var r = -40; r < 60; r++) for (var c2 = -10; c2 < 50; c2++) { + var bx = c2 * 54 + (r % 2 ? 27 : 0), by = r * 22; + x.fillStyle = (r * 7 + c2 * 3) % 5 ? 'rgba(122,116,186,0.30)' : 'rgba(150,140,210,0.36)'; + x.fillRect(bx, by, 50, 18); + } + x.restore(); + // arched windows with the night sky + for (var X = wx(-2); X < W; X += 270) { + x.save(); x.beginPath(); x.moveTo(X - 34, 200); x.lineTo(X - 34, 120); x.arc(X, 120, 34, Math.PI, 0); x.lineTo(X + 34, 200); x.closePath(); + x.fillStyle = vgrad(x, 80, 200, [[0, '#1a1840'], [1, '#3a3a7a']]); x.fill(); x.lineWidth = 6; x.strokeStyle = '#8e86c8'; x.stroke(); x.clip(); + for (var s = 0; s < 5; s++) D.sparkle(x, X + rng.uniform(-28, 28), rng.uniform(95, 190), rng.uniform(2, 3.5), '#fff6c8'); + x.restore(); + x.strokeStyle = '#8e86c8'; x.lineWidth = 3; x.beginPath(); x.moveTo(X, 86); x.lineTo(X, 200); x.moveTo(X - 34, 150); x.lineTo(X + 34, 150); x.stroke(); + } + // the King's banners + for (X = wx(2); X < W; X += 270) { + var bxx = X + 135; + x.fillStyle = '#c8364c'; x.beginPath(); x.moveTo(bxx - 26, 70); x.lineTo(bxx + 26, 70); x.lineTo(bxx + 26, 190); x.lineTo(bxx, 172); x.lineTo(bxx - 26, 190); x.closePath(); x.fill(); + x.lineWidth = 3; x.strokeStyle = '#7d1f33'; x.stroke(); + x.fillStyle = '#e9b949'; x.fillRect(bxx - 30, 64, 60, 8); + D.star(x, bxx, 118, 15, P.gold, 0, 1.6); + } + // stands: rows of small spectators in shadow (only eyes catch the light) + x.fillStyle = '#211d40'; x.fillRect(0, 262, W, 110); + for (var row = 0; row < 3; row++) for (X = (row % 2) * 16; X < W; X += 32) { + var Y = 282 + row * 30, col = ['#4a4482', '#3f3a73', '#564f92'][(X / 32 + row) % 3 | 0]; + D.ellipse(x, X, Y, 13, 12, col); D.ellipse(x, X - 4, Y - 2, 2, 3, 'rgba(255,246,220,0.75)'); D.ellipse(x, X + 4, Y - 2, 2, 3, 'rgba(255,246,220,0.75)'); + } + // spotlights + x.save(); x.globalCompositeOperation = 'lighter'; + [L + 120, (L + R) / 2, R - 120].forEach(function (cx) { + var gr = x.createLinearGradient(0, 0, 0, FL); gr.addColorStop(0, 'rgba(255,240,200,0.20)'); gr.addColorStop(1, 'rgba(255,240,200,0.03)'); + x.fillStyle = gr; x.beginPath(); x.moveTo(cx - 24, 0); x.lineTo(cx + 24, 0); x.lineTo(cx + 150, FL); x.lineTo(cx - 150, FL); x.closePath(); x.fill(); + }); + x.restore(); + // ring floor (canvas), the back ropes and the apron + x.fillStyle = vgrad(x, 372, FL, [[0, '#8f8acb'], [1, '#c9c4ec']]); x.fillRect(0, 372, W, FL - 372); + x.fillStyle = '#efe9f7'; x.fillRect(L, FL - 34, R - L, 36); + x.fillStyle = 'rgba(120,110,170,0.25)'; x.fillRect(L, FL - 34, R - L, 5); + [[150, '#e8475f'], [110, '#fff4f6'], [70, '#4a7fd6']].forEach(function (rp) { + x.strokeStyle = P.ink; x.lineWidth = 7; x.beginPath(); x.moveTo(L, FL - rp[0]); x.lineTo(R, FL - rp[0]); x.stroke(); + x.strokeStyle = rp[1]; x.lineWidth = 4; x.stroke(); + }); + x.fillStyle = '#3d4fa3'; x.fillRect(0, FL + 2, W, V.H - FL); + x.fillStyle = '#ffd23f'; for (X = wx(9); X < W; X += 150) { D.star(x, X, FL + 8, 6, P.gold, 0, 1); } + x.fillStyle = '#f2ecff'; x.fillRect(0, FL - 1, W, 4); + // posts and turnbuckles at the ropes, in front of everything (fg) + [L, R].forEach(function (X) { + var gr = f.createLinearGradient(X - 10, 0, X + 10, 0); gr.addColorStop(0, '#c98f22'); gr.addColorStop(0.45, '#ffe08a'); gr.addColorStop(1, '#b77a17'); + f.fillStyle = gr; f.fillRect(X - 10, FL - 170, 20, 172); f.lineWidth = 2.5; f.strokeStyle = P.ink; f.strokeRect(X - 10, FL - 170, 20, 172); + D.ellipse(f, X, FL - 172, 14, 8, P.gold, P.ink, 2.5); + [150, 110, 70].forEach(function (h, k) { D.round(f, X - 13, FL - h - 9, 26, 18, 6); f.fillStyle = ['#e8475f', '#fff4f6', '#4a7fd6'][k]; f.fill(); f.lineWidth = 2; f.strokeStyle = P.ink; f.stroke(); }); + }); + } + + // ---------------- the sky over Mt. Dedede (the Kaboola fight): the scroll itself is in ambient() ---------------- + function sky(x, f, W, rng) { + x.fillStyle = vgrad(x, 0, V.H, [[0, '#3c3f8f'], [0.55, '#8a6fc0'], [1, '#f2b8c6']]); x.fillRect(0, 0, W, V.H); + for (var i = 0; i < 60; i++) D.ellipse(x, rng.uniform(0, W), rng.uniform(40, 260), 1.3, 1.3, 'rgba(255,255,255,0.75)'); + x.fillStyle = 'rgba(60,50,110,0.55)'; x.beginPath(); x.moveTo(0, V.H); + for (var X = -60; X <= W + 120; X += 120) x.lineTo(X + 60, 400 - rng.uniform(0, 70)), x.lineTo(X + 120, 440); + x.lineTo(W, V.H); x.closePath(); x.fill(); + } + BB.ART.scene = function (doc, id) { + var bg = doc.createElement('canvas'), fg = doc.createElement('canvas'); + var room = rooms[id], wide = room === 'ring', roomW = wide ? BB.KIRBY_RING.W * V.S : V.W - 2 * V.OX; + bg.width = fg.width = wide ? V.W + roomW - (V.W - 2 * V.OX) : V.W; bg.height = fg.height = V.H; + var x = bg.getContext('2d'), f = fg.getContext('2d'), rng = new BB.RNG(room === 'forest' ? 17 : room === 'clouds' ? 23 : room === 'meadow' ? 37 : room === 'castle' ? 41 : room === 'sky' ? 43 : 31); + if (room === 'forest') forest(x, f, bg.width, rng); + else if (room === 'meadow') meadow(x, f, bg.width, rng); + else if (room === 'castle') castle(x, f, bg.width, rng); + else if (room === 'sky') sky(x, f, bg.width, rng); + else if (room === 'clouds') clouds(x, f, bg.width, rng); + else ring(x, f, bg.width, rng, function (u) { return V.OX + u * V.S; }); + // outside the playable room: a soft veil so the fighting area reads at a glance (the room edges are walls) + if (!wide) { + [[0, V.OX], [V.W - V.OX, V.W]].forEach(function (s, k) { + var gr = f.createLinearGradient(s[0], 0, s[1], 0), a = 'rgba(40,30,70,0.30)', z = 'rgba(40,30,70,0)'; + gr.addColorStop(0, k ? z : a); gr.addColorStop(1, k ? a : z); f.fillStyle = gr; f.fillRect(s[0], 46, s[1] - s[0], V.H - 46); + }); + } + return { bg: bg, fg: fg, world: wide }; + }; + // light animated details: drifting pollen in the forest, passing wisps in the sky, flash bulbs in the stands + BB.ART.ambient = function (x, id, t) { + var room = rooms[id], i; + x.save(); + if (room === 'sky') { // [data] the background scrolls 1 px/f (home1.asm Func_11de) = 225 screen px/s here + x.globalAlpha = 0.5; + for (i = 0; i < 7; i++) { + var sw = 90 + (i * 37) % 80, sp = 225 * (0.45 + (i % 3) * 0.275), cx = V.W + sw - ((t * sp + i * 173) % (V.W + 2 * sw)), cy = 90 + (i * 61) % 330; + D.ellipse(x, cx, cy, sw, 11 + (i % 3) * 5, '#ffffff'); + } + } else if (room === 'forest' || room === 'meadow') { + for (i = 0; i < 9; i++) { + var px = (i * 97 + t * (10 + i % 3 * 4)) % V.W, py = 150 + (i * 53) % 260 + Math.sin(t * 1.3 + i) * 10; + x.globalAlpha = 0.55; D.ellipse(x, px, py, 2.4, 3.2, i % 2 ? '#fff4b8' : '#ffffff'); + } + } else if (room === 'clouds') { + x.globalAlpha = 0.5; + for (i = 0; i < 3; i++) { var cx = ((i * 330 + t * (14 + i * 6)) % (V.W + 240)) - 120; D.ellipse(x, cx, 92 + i * 120, 46, 12, '#ffffff'); D.ellipse(x, cx + 30, 86 + i * 120, 28, 10, '#ffffff'); } + for (i = 0; i < 5; i++) { var k = (Math.sin(t * 2 + i * 1.9) + 1) / 2; x.globalAlpha = k; D.sparkle(x, 90 + i * 170, 70 + (i * 71) % 220, 2 + 3 * k, '#ffffff'); } + } else if (room === 'ring') { + for (i = 0; i < 4; i++) { var q = (t * 0.7 + i * 0.37) % 1; if (q < 0.08) { x.globalAlpha = 1 - q / 0.08; D.sparkle(x, 60 + ((i * 211 + Math.floor(t * 0.7 + i * 0.37) * 137) % 740), 280 + (i * 23) % 60, 9, '#ffffff'); } } + } + x.restore(); + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/body_kirby.js b/environments/games/web/games/kirby_remake/body_kirby.js new file mode 100644 index 0000000000000000000000000000000000000000..ca9978293d45014c24c158cb7a4969f240ea6750 --- /dev/null +++ b/environments/games/web/games/kirby_remake/body_kirby.js @@ -0,0 +1,278 @@ +// Body "kirby": Kirby of Kirby's Dream Land (GB), stepped one GB frame per 60 Hz tick. Speeds are kept in the +// source's px/frame (y up) and converted to game units on integration (8 px = 1 u), so every constant below can be +// checked against the disassembly. Tags: [data] = KDL GB disassembly, [cited] = WiKirby, [hand] = our choice. +// Kirby cannot hurt a boss by touching it [cited Inhale/Star Bullet]: the only attack is a Star Bullet, and a star +// needs a mouthful - something the boss throws (apple, Waddle Doo, bomb, Dedede's stars) inhaled first. +// Keys: A/D move Space jump (in the air: float) W float J/LMB inhale (hold) / spit S swallow / duck +(function (g) { + var BB = g.BB; + var K = { + HP: 6, // [data] 6 health bars + WALK_ACC: 32/256, WALK_DEC: 14/256, WALK_MAX: 307/256, // [data] encoded 8.8 values, not decimal approximations + GRAV: 21/256, FALL_MAX: 2.0, // [data] normal and mouthful use the same gravity + FULL_GRAV: 21/256, FULL_FALL: 2.0, + HOV_GRAV: 20/256, HOV_FALL: 204/256, HOV_RISE_ACC: 80/256, HOV_RISE_MAX: 333/256, + HOV_ACC: 22/256, HOV_DEC: 9/256, HOV_MAX: 0.75, + INHALE_FWD: 42, INHALE_DY: 20, INHALE_PULL: 30/256, INHALE_CATCH: 10, INHALE_MIN: 31, + STAR_V: 3, STAR_SIZE: 20, SPIT_CD: 15, // [data] SPIT_COOLDOWN_DURAITON + INVUL: 90, // [data] blink frames after a hit + SWALLOW: 11, SPIT_ANIM: 16, MOUTH_READY: 20, INFLATE: 32, EXHALE: 30, // [data] anim_kirby.asm control gates + W: 2, H: 2, // [data] 16x16 px sprite + NAIL: 1, HITSTOP: 0.1 // one Star Bullet = 1 boss HP [data]; hit-stop [hand] + }; + // [data] jump: vertical speed while the button is held, frame by frame (22 frames), then gravity + var JUMP = [], KB = [4, 3, 3, 2, 2, 2, 1, 1, 1, 1]; + // [data] KirbyControl increments wd065 before checking $16: the final table entry is never integrated. + [[6, 4], [6, 3], [5, 2], [4, 0.5]].forEach(function (s) { for (var i = 0; i < s[0]; i++) JUMP.push(s[1]); }); + var PUFF = [[16, 3, 0], [8, 0.75, 0], [8, 0.125, 0]]; // [data] air bullet when the float ends (px/f) + + function Kirby() {} + Kirby.prototype.id = 'kirby'; + Kirby.prototype.NAIL = K.NAIL; + Kirby.prototype.HITSTOP = K.HITSTOP; + Kirby.prototype.K = K; + Kirby.prototype.keys = { left: 'A', right: 'D', jump: 'Space', up: 'W', attack: 'J|LMB', down: 'S' }; + Kirby.prototype.manual = [ + 'A/D walk; Space jump (hold for height, up to ~6.8 u)', + 'Space again in the air, or W, puffs up and floats; holding it keeps flapping upward; J while floating blows an air puff (harmless to bosses) and ends the float', + 'Hold J or LMB: inhale in front (reach 5.25 u, +-2.5 u vertical); objects a boss throws can be caught - you cannot walk while inhaling; W stops an inhale that is not pulling anything', + 'J or LMB with a full mouth: spit a star straight ahead - the only way to damage a boss (1 HP per star); S swallows the mouthful instead', + 'S on the ground with an empty mouth: duck (smaller hurtbox)', + 'Normal and Extra start with 6 health bars; damage gives 90 frames of blinking and horizontal knockback, preserving your mouthful and float' + ]; + + Kirby.prototype.reset = function (c) { + this.x = 3; this.y = 0; this.vx = 0; this.vy = 0; this.facing = 1; this.grounded = true; + this.max_hp = K.HP; this.hp = K.HP; this.invul = 0; this.kb = KB.length; this.kbDir = 1; + this.jumpT = -1; this.hover = false; this.hoverT = 0; this.flapT = 0; this.flapping = false; this.exhaleT = 0; + this.inhaleT = 0; this.mouth = null; this.mouthT = 0; this.spitCd = 0; this.spitT = 0; this.swallowT = 0; this.duck = false; + this.captured = false; this.stars = []; this.puffs = []; this.nstar = 0; this.curStar = null; + this.slashHits = {}; this.slashFacing = 1; this.prev = {}; + }; + Kirby.prototype.big = function () { return this.hover || this.exhaleT > 0 || this.inhaleT > 0 || !!this.mouth; }; + Kirby.prototype.box = function () { return { x: this.x, y: this.y + K.H / 2, w: K.W, h: K.H }; }; + // [data] hurtbox (half sizes): 3x3 px at the centre; 5x5 px 4 px higher when puffed / inhaling / full; 2x1 px 6 px + // lower when ducking. Small on purpose - that is how the GB game feels. + Kirby.prototype.hurtBox = function () { + if (this.captured) return { x: -99, y: -99, w: 0, h: 0 }; + if (this.duck) return { x: this.x, y: this.y + 1 - 6 / 8, w: 4 / 8, h: 2 / 8 }; + if (this.big()) return { x: this.x, y: this.y + 1 + 4 / 8, w: 10 / 8, h: 10 / 8 }; + return { x: this.x, y: this.y + 1, w: 6 / 8, h: 6 / 8 }; + }; + Kirby.prototype.centre = function () { return { x: this.x, y: this.y + 1 }; }; + // the oldest live Star Bullet is the "slash": a 20x20 px square [data]; its own hit set keeps one hit per target + Kirby.prototype.slashBox = function () { + for (var i = 0; i < this.stars.length; i++) { + var s = this.stars[i]; if (s.dead) continue; + var h = K.STAR_SIZE / 16; + this.slashHits = s.hits; this.slashFacing = s.dir; this.curStar = s; + var pts = [[s.x - h, s.y - h], [s.x + h, s.y - h], [s.x + h, s.y + h], [s.x - h, s.y + h]]; + return { pts: pts, tink: pts, dir: 'side', x: s.x, y: s.y }; + } + this.curStar = null; return null; + }; + Kirby.prototype.inhaleZone = function () { // [data] reach in front of the mouth, for drawing and agents + var f = this.facing; + return { x: this.x + f * K.INHALE_FWD / 16, y: this.y + 1, w: K.INHALE_FWD / 8, h: 2 * K.INHALE_DY / 8 }; + }; + + Kirby.prototype.update = function (c, inp) { + var A = c.arena || BB.ARENA, pv = this.prev; + var jumpP = inp.jump && !pv.jump, upP = inp.up && !pv.up, atkP = inp.attack && !pv.attack, downP = inp.down && !pv.down; + this.prev = { left: inp.left, right: inp.right, jump: inp.jump, up: inp.up, attack: inp.attack, down: inp.down }; + if (this.invul > 0) this.invul--; + if (this.spitCd > 0) this.spitCd--; + if (this.spitT > 0) this.spitT--; + if (this.swallowT > 0) this.swallowT--; + if (this.mouthT > 0) this.mouthT--; + if (this.hoverT > 0) this.hoverT--; + if (this.exhaleT > 0) this.exhaleT--; + this.stepShots(c); + if (this.captured) return; // held in King Dedede's mouth: the boss moves us + + var dir = (inp.right ? 1 : 0) - (inp.left ? 1 : 0), upCancel = false; + // ---- mouth / inhale / spit ---- + if (this.mouth) { + var pending = c.boss.inhalables && c.boss.inhalables().some(function (o) { return o.sucking; }); + if (!pending) this.inhaleT = 0; + if (!pending && atkP && this.mouthT === 0 && this.spitCd <= 0) this.spit(c); + else if (!pending && inp.down && this.grounded && this.mouthT === 0) { this.mouth = null; this.swallowT = K.SWALLOW; c.emit('swallow', this.x, this.y + 1); } + } else if (this.hover) { + if (atkP && this.hoverT === 0 && this.spitCd <= 0) this.exhale(c); + } else if (this.inhaleT > 0) { + var pulling = c.boss.inhalables && c.boss.inhalables().some(function (o) { return o.sucking; }); + // [data] KirbyControl .check_d_up -> .asm_451a: Up held while inhaling and not pulling an object stops the + // inhale at once (sets the end-of-inhale flag, skipping Func_4783's 31-frame minimum). No float this frame. + if (inp.up && !pulling) { this.inhaleT = 0; upCancel = true; } + else if (inp.attack || this.inhaleT < K.INHALE_MIN || pulling) this.inhaleT++; else this.inhaleT = 0; + } else if (atkP && !inp.up && !inp.down && this.spitCd <= 0 && !this.spitT && !this.swallowT && !this.exhaleT) { this.inhaleT = 1; c.emit('inhale', this.x, this.y + 1); } + this.duck = this.grounded && inp.down && !this.mouth && this.inhaleT === 0 && !this.hover && !this.exhaleT && !this.spitT; + if (this.inhaleT > 0) this.suck(c); + + // ---- horizontal ---- + var locked = this.inhaleT > 0 || this.duck || this.swallowT > 0; + var knockback = this.kb < KB.length; + if (this.kb < KB.length) { this.vx = KB[this.kb] * this.kbDir; this.kb++; } + else { + var acc = this.hover ? K.HOV_ACC : K.WALK_ACC, dec = this.hover ? K.HOV_DEC : K.WALK_DEC, mx = this.hover ? K.HOV_MAX : K.WALK_MAX; + if (dir && !locked) { + if (!this.spitT && !this.hoverT) this.facing = dir; + // [data] Func_917: reversal brakes the old direction, first reducing >=1 px/f to 0.5. + if (this.vx * dir < 0) { this.vx = Math.sign(this.vx) * Math.max(0, Math.min(Math.abs(this.vx), 0.5) - dec); } + else this.vx = dir * Math.min(mx, Math.abs(this.vx) + acc); + } else if (this.vx) { var s = Math.abs(this.vx) - dec; this.vx = s > 0 ? s * (this.vx > 0 ? 1 : -1) : 0; } + } + + // ---- jump / float ---- + if (this.grounded && jumpP && this.inhaleT === 0 && !this.duck && !this.hover) { + this.jumpT = 0; this.grounded = false; c.emit('jump', this.x, this.y); + } else if (!this.hover && !this.mouth && this.inhaleT === 0 && !upCancel && ((!this.grounded && jumpP) || upP)) { + this.hover = true; this.hoverT = K.INFLATE; this.jumpT = -1; this.flapping = false; this.grounded = false; c.emit('float', this.x, this.y + 1); + } + if (this.hover) { + if (inp.jump || inp.up) { + this.flapping = true; this.vy = Math.min(this.vy + K.HOV_RISE_ACC, K.HOV_RISE_MAX); + } else { this.flapping = false; this.vy = Math.max(this.vy - K.HOV_GRAV, -K.HOV_FALL); } + } else if (this.jumpT >= 0) { + if (!inp.jump && this.jumpT < 17) this.jumpT = 17; // [data] early release advances to the four 0.5 px/f tail frames + if (this.jumpT < JUMP.length) { this.vy = JUMP[this.jumpT++]; } + else { this.vy = 40/256; this.jumpT = -1; } // [data] Func_38f -0.156 screen-y, then gravity + } + if (!this.hover && this.jumpT < 0) { + var gr = this.mouth ? K.FULL_GRAV : K.GRAV, fm = this.mouth ? K.FULL_FALL : K.FALL_MAX; + this.vy = Math.max(this.vy - gr, -fm); + } + + this.integrate(c, A, knockback); + }; + // ---- integrate (px/f -> u) and the arena bounds; KirbyCastle (body_kirby_castle.js) overrides it with ledges ---- + Kirby.prototype.integrate = function (c, A, knockback) { + this.x += this.vx / 8; this.y += this.vy / 8; + if (knockback && this.kb === KB.length) this.vx = 0; + var left = A.LEFT || 0, right = A.RIGHT == null ? A.W : A.RIGHT; + if (this.x < left + K.W / 2) { this.x = left + K.W / 2; if (this.vx < 0) this.vx = 0; } + if (this.x > right - K.W / 2) { this.x = right - K.W / 2; if (this.vx > 0) this.vx = 0; } + if (this.y > A.H - K.H) { this.y = A.H - K.H; if (this.vy > 0) this.vy = 0; } + if (this.y <= 0) { + var was = this.grounded; + this.y = 0; this.vy = 0; this.grounded = true; this.jumpT = -1; + if (!was) c.emit('land'); + } else this.grounded = false; + }; + + Kirby.prototype.exhale = function (c) { // the float ends with an air puff [data] + this.hover = false; this.flapping = false; + this.exhaleT = K.EXHALE; this.spitCd = K.SPIT_CD; this.vy = Math.trunc(this.vy); + this.puffs.push({ x: this.x + this.facing * 10/8, y: this.y + 1 + 5/8, dir: this.facing, seg: 0, t: 0, age: 0 }); + c.emit('exhale', this.x + this.facing * 10/8, this.y + 1 + 5/8); + }; + Kirby.prototype.spit = function (c) { // Star Bullet straight ahead [data] + this.stars.push({ id: ++this.nstar, x: this.x + this.facing * 10/8, y: this.y + 1 + 5/8, dir: this.facing, age: 0, hits: {}, of: this.mouth }); + this.mouth = null; this.spitCd = K.SPIT_CD; this.spitT = K.SPIT_ANIM; + c.emit('spit', this.x + this.facing, this.y + 1); + }; + // [data] inhale: objects in front of the mouth (up to 42 px ahead, +-20 px vertical) are pulled toward Kirby with an + // accelerating speed and swallowed into the mouth once within 10 px; the boss skips a pulled object's own motion. + Kirby.prototype.suck = function (c) { + var boss = c.boss; if (!boss.inhalables) return; + var mx = this.x, my = this.y + 1, list = boss.inhalables(); + for (var i = 0; i < list.length; i++) { + var o = list[i], dx = (o.x - mx) * this.facing * 8, dy = (o.y - my) * 8; + if (!o.sucking && (dx < 0 || dx >= K.INHALE_FWD || Math.abs(dy) >= K.INHALE_DY)) continue; + o.sucking = true; o.pulled = c.t; + // [data] InhaleObject: horizontal acceleration, vertical gap /8; capture tests X only before moving. + if (Math.abs(o.x - mx) * 8 < K.INHALE_CATCH) { + var kind = boss.capture(c, o); + if (kind) { this.mouth = kind; this.mouthT = K.MOUTH_READY; } + } else { + o.pv = (o.pv || 0) + Math.sign(mx - o.x) * K.INHALE_PULL; + o.x += o.pv / 8; o.y += (my + 1/8 - o.y) / 8; + } + } + if (this.mouth && !boss.inhalables().some(function (o) { return o.sucking; })) this.inhaleT = 0; + }; + Kirby.prototype.stepShots = function (c) { + var A = c && c.arena || BB.ARENA; + for (var i = this.stars.length - 1; i >= 0; i--) { + var s = this.stars[i]; s.age++; + if (!s.dead) s.x += s.dir * K.STAR_V / 8; + if (s.dead ? s.age > 1e9 : (s.x < -1.5 || s.x > A.W + 1.5)) s.dead = true; + if (s.dead) this.stars.splice(i, 1); + } + for (i = this.puffs.length - 1; i >= 0; i--) { + var p = this.puffs[i], sg = PUFF[p.seg]; p.age++; + if(p.dead){this.puffs.splice(i,1);continue;} + p.x += p.dir * sg[1] / 8; + if (++p.t >= sg[0]) { p.seg++; p.t = 0; } + if (p.seg >= PUFF.length) this.puffs.splice(i, 1); + } + }; + Kirby.prototype.onSlashContact = function (c, kind) { + var s = this.curStar; if (!s) return; + s.dead = true; + if (kind === 'block' || kind === 'tink') c.emit('tink', s.x, s.y); + else c.emit('star_burst', s.x, s.y); + }; + Kirby.prototype.hurt = function (c, dmg, fromX) { + if (this.invul > 0 || this.hp <= 0 || this.captured) return false; + this.hp = Math.max(0, this.hp - dmg); this.invul = K.INVUL; + this.kb = 0; this.kbDir = this.x < fromX ? -1 : 1; + // [data] bank05 .CollideWithKirby changes HP, blink and X knockback only; mouth/hover/jump remain. + c.emit('player_hit'); + return true; + }; + // [data] bank05 checks Kirby before the attack objects. Stars / puffs also interact with enemies, + // not just the boss; the source object properties determine whether a hit destroys, blocks, or passes. + Kirby.prototype.resolveInteractions = function (c) { + var w=c.boss, self=this; + if(w.st==='dead')return; + var hz=w.hazards(), hb=this.hurtBox(); + for(var i=0;i 0, duck: this.duck, captured: this.captured, + spit_cd: r(this.spitCd / 60), + stars: this.stars.filter(function (s) { return !s.dead; }).map(function (s) { return { x: r(s.x), y: r(s.y), dir: s.dir }; }) + }; + }; + var KB_V = 7.5; // px/f -> u/s + BB.Kirby = Kirby; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/body_kirby_castle.js b/environments/games/web/games/kirby_remake/body_kirby_castle.js new file mode 100644 index 0000000000000000000000000000000000000000..f0cec50f2d59e205646bf0954fa718ccb82933f6 --- /dev/null +++ b/environments/games/web/games/kirby_remake/body_kirby_castle.js @@ -0,0 +1,88 @@ +// Body "kirby" in the Castle Lololo room (only kirby/lololo_lalala uses it): BB.Kirby plus the room's ledges. +// Four 16 px corridors, one above the other, separated by 16 px brick ledges; a few ledge blocks are thin one-way +// bridges. The rules are the source's (home/home1.asm): a bridge block (BLOCK_1) is a floor from above (Func_caf) and +// does not stop Kirby from below (Func_9de) or from the side (KirbyControl .continue_walk); holding Down while standing +// only on bridge (or empty) blocks drops him through it, before the swallow / duck checks (Func_caf .asm_dd1, so a +// full mouth drops too); a solid block over his head ends a jump: y speed 0 and the rise table is skipped to gravity +// (wd065 = $16). The ledge layout is rebuilt from the GB screenshot (the level's block map is LZ-compressed and not +// in the pinned disassembly copy) [hand, approximation]. Tags: [data] = KDL GB disassembly, [hand] = our choice. +(function (g) { + var BB = g.BB, Kirby = BB.Kirby, K = Kirby.prototype.K; + var HW = 4.5 / 8, EPS = 1e-6; // [data] the two foot points at +3 / +12 px of the 16 px sprite + // [hand] ledges as [bottom, top] in u (y up, floor 0) with their bridge spans [x0, x1] in u; screenshot S11 + var LEDGES = [ + { y0: 2, y1: 4, bridges: [[8, 12]] }, + { y0: 6, y1: 8, bridges: [[2, 6], [14, 18]] }, + { y0: 10, y1: 12, bridges: [[8, 12]] } + ]; + var W = 20, SOLID = [], BRIDGE = []; + LEDGES.forEach(function (l) { + var x = 0; + l.bridges.forEach(function (b) { if (b[0] > x) SOLID.push({ x0: x, x1: b[0], y0: l.y0, y1: l.y1 }); BRIDGE.push({ x0: b[0], x1: b[1], y0: l.y0, y1: l.y1 }); x = b[1]; }); + if (x < W) SOLID.push({ x0: x, x1: W, y0: l.y0, y1: l.y1 }); + }); + BB.KIRBY_CASTLE = { W: W, H: 14, gx: BB.ARENA.gx, gy: BB.ARENA.gy, ledges: LEDGES, solid: SOLID, bridge: BRIDGE }; + + function KirbyCastle() {} + KirbyCastle.prototype = Object.create(Kirby.prototype); + KirbyCastle.prototype.constructor = KirbyCastle; + function xs(self, s) { return self.x + HW > s.x0 + EPS && self.x - HW < s.x1 - EPS; } + // what Kirby is standing on: 'solid' if any solid block is under a foot, else 'bridge', else 'floor' / null + KirbyCastle.prototype.footing = function () { + if (!this.grounded) return null; + if (this.y <= EPS) return 'floor'; + var self = this, y = this.y, on = null; + SOLID.forEach(function (s) { if (Math.abs(s.y1 - y) < EPS && xs(self, s)) on = 'solid'; }); + if (!on) BRIDGE.forEach(function (s) { if (Math.abs(s.y1 - y) < EPS && xs(self, s)) on = 'bridge'; }); + return on; + }; + KirbyCastle.prototype.update = function (c, inp) { + if (inp.down && !this.captured && this.footing() === 'bridge') { + // [data] Func_caf .asm_dd1: off the bridge, 1 px down, airborne; this tick's Down is spent on the drop + this.y -= 1 / 8; this.grounded = false; this.vy = 0; this.jumpT = -1; + c.emit('drop', this.x, this.y); + var o = {}; for (var k in inp) o[k] = inp[k]; o.down = false; inp = o; + } + Kirby.prototype.update.call(this, c, inp); + }; + KirbyCastle.prototype.integrate = function (c, A, knockback) { + var self = this, x0 = this.x, y0 = this.y; + // ---- x ---- + this.x += this.vx / 8; + if (knockback && this.kb === 10) this.vx = 0; // KB.length in body_kirby.js + var left = A.LEFT || 0, right = A.RIGHT == null ? A.W : A.RIGHT; + if (this.x < left + K.W / 2) { this.x = left + K.W / 2; if (this.vx < 0) this.vx = 0; } + if (this.x > right - K.W / 2) { this.x = right - K.W / 2; if (this.vx > 0) this.vx = 0; } + SOLID.forEach(function (s) { // only while inside a ledge's height (rising through a gap) + if (!(y0 < s.y1 - EPS && y0 + K.H > s.y0 + EPS) || !xs(self, s)) return; + self.x = self.x >= x0 ? s.x0 - HW : s.x1 + HW; self.vx = 0; + }); + // ---- y ---- + this.y += this.vy / 8; + if (this.y > A.H - K.H) { this.y = A.H - K.H; if (this.vy > 0) this.vy = 0; } + if (this.vy > 0) SOLID.forEach(function (s) { // [data] head against a solid block: stop, end the jump's rise + if (xs(self, s) && y0 + K.H <= s.y0 + EPS && self.y + K.H > s.y0) { + self.y = s.y0 - K.H; self.vy = 0; self.jumpT = -1; c.emit('bump', self.x, s.y0); + } + }); + var top = this.y <= 0 ? 0 : null; + if (this.vy <= 0) SOLID.concat(BRIDGE).forEach(function (s) { // landing: crossed a top surface going down + if (xs(self, s) && y0 >= s.y1 - EPS && self.y <= s.y1 + EPS && (top === null || s.y1 > top)) top = s.y1; + }); + if (top !== null) { + var was = this.grounded; + this.y = top; this.vy = 0; this.grounded = true; this.jumpT = -1; + if (!was) c.emit('land'); + } else this.grounded = false; + }; + // [hand] a Star Bullet bursts on a brick ledge (the room's corridors are straight, so this only matters for a star + // spat while rising through a gap) + KirbyCastle.prototype.stepShots = function (c) { + Kirby.prototype.stepShots.call(this, c); + this.stars.forEach(function (s) { + if (s.dead) return; + SOLID.forEach(function (b) { if (!s.dead && s.x > b.x0 && s.x < b.x1 && s.y > b.y0 && s.y < b.y1) { s.dead = true; if (c && c.emit) c.emit('star_burst', s.x, s.y); } }); + }); + }; + BB.KirbyCastle = KirbyCastle; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/body_kirby_mint.js b/environments/games/web/games/kirby_remake/body_kirby_mint.js new file mode 100644 index 0000000000000000000000000000000000000000..9d122f16b62a41a1536ece3349cacf8e085b01b4 --- /dev/null +++ b/environments/games/web/games/kirby_remake/body_kirby_mint.js @@ -0,0 +1,84 @@ +// Body "kirby" on the mint leaf (only kirby/kaboola uses it): the shooter controls of the Kaboola fight. BB.Kirby's +// inhale / spit / jump are all off; the source's KirbyControl KABOOLA_BATTLE branch is what runs instead. +// [data] engine/bank01.asm .asm_4692: left / right 1.2 px/f at once and a stop on release (acceleration and deceleration +// 0.996, speed rewritten to 1.0 every frame, capped at wKirbyMaxXVel 1.2); Up -2 px/f on screen, else Down +1, else 0: he +// hangs in the air. [data] the same routine's left branch skips .set_face_left while HURT_PAL_EFFECT is set, so he never +// turns round. [data] B spits on the press (KIRBY4F_NONSTICKY_B), cooldown 15 frames; PuffSpit takes a Group 2 slot and +// there are two (constants/object_constants.asm), so at most two air bullets fly at once. [data] MotionScript_KirbyPuff +// .script_1026a: 4 px/f for as long as it lives, in level coordinates (Data_35b3 PROPERTY_REL_POS) under a background +// scrolling 1 px/f (home1.asm Func_11de), so 3 px/f on the screen, which is what a fixed screen plays. [data] bank05 +// .no_knock_back: a hit costs bars and 90 blink frames, no knockback; .asm_144c5: an air bullet takes 1 HP off Kaboola and +// bursts; OBJINT_UNK4 returns at once, so air bullets pass through its bullets. +// [hand] lower bound y 0: the source allows y -2 (wKirbyScreenY 128, the 16 px under the floor line), which the +// 14 u view has no room for. Tags as in body_kirby.js. +(function (g) { + var BB = g.BB, Kirby = BB.Kirby, K = Kirby.prototype.K; + var M = { X: 1.2, UP: 2, DOWN: 1, PUFF_V: 3, PUFF: 12, SLOTS: 2 }; + function KirbyMint() {} + KirbyMint.prototype = Object.create(Kirby.prototype); + KirbyMint.prototype.constructor = KirbyMint; + KirbyMint.prototype.M = M; + KirbyMint.prototype.manual = [ + 'You fly for the whole fight. A/D move 1.2 px/f and stop at once; W rises 2 px/f, S sinks 1 px/f; with neither you hang in the air', + 'J or LMB (press, not hold): blow an air bullet straight right, 1 HP on the airship; one every 15 frames, at most two in the air', + "You always face right, so stay on the left of the airship to hit it; air bullets pass through its bullets", + 'A hit costs bars and gives 90 frames of blinking, with no knockback' + ]; + KirbyMint.prototype.reset = function (c) { + Kirby.prototype.reset.call(this, c); + this.x = 4; this.y = 5; this.hover = true; this.grounded = false; this.mint = true; + }; + KirbyMint.prototype.update = function (c, inp) { + var A = c.arena || BB.ARENA, atkP = inp.attack && !this.prev.attack; + this.prev = { left: inp.left, right: inp.right, jump: inp.jump, up: inp.up, attack: inp.attack, down: inp.down }; + if (this.invul > 0) this.invul--; + if (this.spitCd > 0) this.spitCd--; + this.stepShots(c); + this.vx = ((inp.right ? 1 : 0) - (inp.left ? 1 : 0)) * M.X; + this.vy = inp.up ? M.UP : inp.down ? -M.DOWN : 0; + this.flapping = !!inp.up; + if (atkP && this.spitCd <= 0) { + this.spitCd = K.SPIT_CD; // [data] set before PuffSpit: a press with no free slot still costs the cooldown + if (this.puffs.length < M.SLOTS) { + this.puffs.push({ x: this.x + 10 / 8, y: this.y + 1 + 5 / 8, dir: 1, age: 0 }); + c.emit('exhale', this.x + 10 / 8, this.y + 1 + 5 / 8); + } + } + this.x = BB.clamp(this.x + this.vx / 8, K.W / 2, A.W - K.W / 2); + this.y = BB.clamp(this.y + this.vy / 8, 0, A.H - K.H); + }; + KirbyMint.prototype.stepShots = function (c) { + var A = c && c.arena || BB.ARENA; + for (var i = this.puffs.length - 1; i >= 0; i--) { + var p = this.puffs[i]; p.age++; p.x += M.PUFF_V / 8; + if (p.dead || p.x > A.W + 1.5) this.puffs.splice(i, 1); + } + }; + KirbyMint.prototype.hurt = function (c, dmg) { + if (this.invul > 0 || this.hp <= 0) return false; + this.hp = Math.max(0, this.hp - dmg); this.invul = K.INVUL; + c.emit('player_hit'); + return true; + }; + KirbyMint.prototype.resolveInteractions = function (c) { + var w = c.boss, self = this; + if (w.st === 'dead') return; + var hb = this.hurtBox(); + w.hazards().forEach(function (h) { + if (h.box && BB.overlap(h.box, hb) && self.hurt(c, h.dmg || w.dmg)) { c.emit('hurt_by'); c.events[c.events.length - 1].by = h.kind; c.shake(0.6); } + }); + if (this.hp <= 0) return; + var bx = w.bodyBox(); + this.puffs.forEach(function (p) { + if (p.dead || w.st === 'dead' || !BB.overlap({ x: p.x, y: p.y, w: M.PUFF / 8, h: M.PUFF / 8 }, bx)) return; + p.dead = true; w.onNailHit(c, 1, 'side', 1, 'boss'); c.emit('air_burst', p.x, p.y); + }); + }; + KirbyMint.prototype.state = function () { + var s = Kirby.prototype.state.call(this), r = BB.r4; + s.mint = true; + s.puffs = this.puffs.filter(function (p) { return !p.dead; }).map(function (p) { return { x: r(p.x), y: r(p.y) }; }); + return s; + }; + BB.KirbyMint = KirbyMint; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/bosses/kaboola.js b/environments/games/web/games/kirby_remake/bosses/kaboola.js new file mode 100644 index 0000000000000000000000000000000000000000..aae60e8fc6b0ce53c8a67bda73e44dc0c4ff0a41 --- /dev/null +++ b/environments/games/web/games/kirby_remake/bosses/kaboola.js @@ -0,0 +1,154 @@ +// Boss "kaboola": Kaboola, the shooter duel of Kirby's Dream Land. A 36 x 32 px blimp on the right of the screen: two +// passes of a figure of eight (firing all the while), then a ram chosen by where Kirby is, then again. Only air bullets +// hurt it (body_kirby_mint.js). The firing script runs alongside the motion script as in the source, where the anim and +// motion scripts are separate; a ram replaces the anim script, so it does not fire during one. The reset option +// mode: 'extra' runs the Extra Game script (fast weave, shorter rams, bullets that aim once after leaving the cannon). +// x, y = centre of its box in u. Tags: [data] = KDL disassembly, [hand] = our choice. +(function (g) { + var BB = g.BB, KB = BB.KIRBY, A = BB.ARENA; + var SPEC = BB.SPECS.kaboola, SP = SPEC.moves[0].params, RP = SPEC.moves[1].params, DMG = SPEC.moves[1].damage; + var BW = RP.size[0] / 8, BH = RP.size[1] / 8, OW = SP.bullet_size[0] / 8, OH = SP.bullet_size[1] / 8; + var ROLE = { intro: 'idle', fly_a: 'active', fly_b: 'active', ram_antic: 'telegraph', ram: 'active', ram_back: 'recovery', dead: 'recovery' }; + function Kaboola() {} + Kaboola.prototype.id = 'kaboola'; + BB.bossKit(Kaboola.prototype, SPEC, ROLE); + KB.objects(Kaboola.prototype); + + // [data] Func_3410: the 8-bit fraction a / d of two screen distances, with the routine's own wrap-around + function frac8(a, d) { + var c = 0; + for (var i = 0; i < 8; i++) { + a = (a << 1) & 255; + if (a < d) c = (c << 1) & 255; else { a -= d; c = ((c << 1) | 1) & 255; } + } + return c; + } + // [data] Func_48f5: direction 0..15 (0 = up, clockwise) from (ox, oy) to the player, in whole pixels; not Func_495c (KB.octant) + var DIR = [0, 4, 4, 8, 8, 12, 12, 0, 1, 3, 5, 7, 9, 11, 13, 15, 2, 2, 6, 6, 10, 10, 14, 14]; + KB.dir16 = function (ox, oy, kx, ky) { + var dy = Math.round((oy - ky) * 8), dx = Math.round((kx - ox) * 8), e = dy < 0 ? 0 : 3, d = Math.abs(dy), b = Math.abs(dx), a; + if (dx < 0) e ^= 7; + if (b >= d) { e ^= 1; a = d; d = b; } else a = b; + var r = frac8(a & 255, d & 255); + return DIR[(r < 0x33 ? 0 : r < 0xad ? 1 : 2) * 8 | e]; + }; + Kaboola.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.configKirby(c); + this.max_hp = this.hp = Math.max(1, Math.round(k.hp)); this.dmg = DMG; this.extra = KB.extraMode(c); + this.objs = []; this.nid = 0; this.hitFlash = 0; this.now = 0; this.f = -1; this.stamp = 0; this.lastActive = null; this.track = {}; this.cycle = {}; + this.x = A.gx(RP.intro_start[0]); this.y = A.gy(RP.intro_start[1]); + this.tr = KB.track(this.extra ? RP.extra_intro : RP.intro); + this.st = 'intro'; this.stT = 0; this.timer = 0; this.move = 'shoot'; this.offstage = true; this.inverted = false; + this.sq = []; this.sw = 0; this.ramKind = null; + }; + // ---- the firing script: a queue of waits (frames) and steps ---- + Kaboola.prototype.volley = function (c) { // [data] .regular_shot / .inverted_shot + var T = SP.thresholds, q = this.sq; + if (c.rng.int(256) < T.one) { if (this.inverted) q.push(12, 'S'); else q.push('S', 12); } // [data] upright fires first, inverted last + else if (c.rng.int(256) < T.three) q.push(6, 'S', 10, 6, 'S', 10, 6, 'S', 10); + else q.push(6, 'F'); + q.push('N'); + }; + Kaboola.prototype.shootStep = function (c) { + var guard = 0; + while (this.sw <= 1e-9 && guard++ < 32) { + if (!this.sq.length) this.volley(c); + var op = this.sq.shift(); + if (typeof op === 'number') this.sw += op; + else if (op === 'S') this.fire(c, 0, this.extra); + else if (op === 'F') { this.fire(c, 1, false); this.fire(c, 0, false); this.fire(c, -1, false); } + else if (op === 'N') this.sq.push(15 * this.k.recovery, 'R'); // [data] .maybe_invert_shot / .maybe_regular_shot: 15 frames, then the roll + else if (op === 'R') { + if (c.rng.int(256) < SP.thresholds.invert) { // [data] 18 frames rolling over; 15 more only when going inverted + this.sq.push('I', 18); if (!this.inverted) this.sq.push(15 * this.k.recovery); + } else this.sq.push(15 * this.k.recovery); + } else if (op === 'I') this.inverted = !this.inverted; + } + this.sw -= this.spd(); + }; + // up = +1 / -1: a slanted bullet of the fan; aimed: the Extra Game's straight-out bullet (script_delay 2, then Func_48f5) + Kaboola.prototype.fire = function (c, up, aimed) { + var o = this.spawn({ kind: 'bullet', x: this.x + SP.offset[0] / 8, y: this.y + (this.inverted ? 1 : -1) * SP.offset[1] / 8, w: OW, h: OH, inh: false, dmg: 1, tr: null, aim: 0 }); + if (aimed) o.aim = 2; + else o.tr = KB.track([[1e6, up ? SP.fan[0] : SP.bullet[0], up ? up * SP.fan[1] : SP.bullet[1]]]); + c.emit('kaboola_shot', o.x, o.y); + }; + Kaboola.prototype.stepObjs = function (c, dt) { + var s = this.spd(), b = c.body; + this.objs = this.objs.filter(function (o) { + if (o.dead) return false; + o.age += dt; + if (o.aim > 0) { + o.aim -= s; + if (o.aim <= 1e-9) { + var p = SP.extra_aim[SP.extra_aim_table[KB.dir16(o.x, o.y, b.x, b.y + 1)]]; + o.tr = KB.track(p.segs, p.loop ? 0 : null); o.aim = 0; + } + return true; + } + o.tr.step(o, dt, s); + return o.x > -1 && o.x < A.W + 1 && o.y > -2 && o.y < A.H + 2; + }); + }; + // ---- the motion script ---- + Kaboola.prototype.fly = function (c, st) { + if (st === 'fly_a') { + if (this.extra) { this.x = A.gx(RP.home[0]); this.y = A.gy(RP.home[1]); } // [data] set_position 132, 80 + this.sq = [10]; this.sw = 0; this.inverted = false; // [data] the anim script restarts upright + } + this.tr = KB.track(this.extra ? RP.extra_weave : RP.weave); + this.go(c, st, 0, 'shoot'); + }; + Kaboola.prototype.startRam = function (c) { + var b = c.body, kind = RP.table[KB.dir16(this.x, this.y, b.x, b.y + 1)], r = (this.extra ? RP.extra_rams : RP.rams)[kind]; + this.ramKind = kind; this.sq = []; this.sw = 0; + this.tr = KB.track(r.antic); + this.go(c, 'ram_antic', 0, 'ram'); + }; + Kaboola.prototype.update = function (c) { + var dt = BB.DT, s = this.spd(), k = this.k; this.flash(dt); this.now = c.t; + this.stepObjs(c, dt); + if (this.st === 'dead') return; + this.stT += dt; + var r = this.ramKind && (this.extra ? RP.extra_rams : RP.rams)[this.ramKind]; + if (this.st === 'intro') { + var more = this.tr.step(this, dt, s / k.idle_gap); + if (this.x <= A.W) this.offstage = false; // only the bounds checks read this: it starts past the right edge + if (!more) this.fly(c, 'fly_a'); + } else if (this.st === 'fly_a' || this.st === 'fly_b') { + var goes = this.tr.step(this, dt, s); + this.shootStep(c); + if (!goes) { if (this.st === 'fly_a') this.fly(c, 'fly_b'); else this.startRam(c); } + } else if (this.st === 'ram_antic') { + if (!this.tr.step(this, dt, s / k.telegraph)) { this.tr = KB.track(r.go); this.go(c, 'ram', 0, 'ram'); c.shake(0.3); } + } else if (this.st === 'ram') { + if (!this.tr.step(this, dt, s)) { this.tr = KB.track(r.back); this.go(c, 'ram_back', 0, 'ram'); } + } else if (this.st === 'ram_back') { + if (!this.tr.step(this, dt, s / k.recovery)) this.fly(c, 'fly_a'); + } + }; + Kaboola.prototype.bodyBox = function () { return { x: this.x, y: this.y, w: BW, h: BH }; }; + Kaboola.prototype.hazards = function () { + var out = []; + if (this.st !== 'dead') out.push({ kind: 'kaboola', box: this.bodyBox(), dmg: this.hd(DMG), fromX: this.x }); + return this.objHazards(this.now, out); + }; + // [data] engine/bank05.asm .asm_144c5: an air bullet takes 1 HP; no invulnerability + Kaboola.prototype.onNailHit = function (c, dmg) { + if (this.st === 'dead') return null; + this.hp = Math.max(0, this.hp - dmg); this.hitFlash = 0.05; + c.emit('boss_hit', this.x - BW / 2, this.y); + if (this.hp <= 0) { this.go(c, 'dead', 0); this.objs = []; c.emit('boss_dead', this.x, this.y); c.shake(0.8); } + return 'flesh'; + }; + Kaboola.prototype.state = function () { + var r = BB.r4, role = this.role(), tr = this.tr, left = 0; + if (role === 'telegraph') { for (var i = tr.i; i < tr.segs.length; i++) left += tr.segs[i][0]; left = (left - tr.t) / 60 * this.k.telegraph / this.spd(); } + return { x: r(this.x), y: r(this.y), w: BW, h: BH, hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: this.move, + ram: this.st === 'ram_antic' || this.st === 'ram' || this.st === 'ram_back' ? this.ramKind : null, + telegraph_left: r(Math.max(0, left)), inverted: this.inverted, extra: this.extra, hazards: this.objState() }; + }; + BB.CASES = BB.CASES || {}; + BB.CASES['kirby/kaboola'] = { title: 'Armed Airship', Body: BB.KirbyMint, Boss: Kaboola }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/bosses/king_dedede.js b/environments/games/web/games/kirby_remake/bosses/king_dedede.js new file mode 100644 index 0000000000000000000000000000000000000000..4fa3504d2621a5ff0e1f8b2ed0785cedcfbe3a55 --- /dev/null +++ b/environments/games/web/games/kirby_remake/bosses/king_dedede.js @@ -0,0 +1,336 @@ +// Boss "king_dedede": King Dedede of Kirby's Dream Land, in his ring. Four moves picked from the script's random +// jumptables (walk-and-slide, jump, inhale, hammer; see specs/king_dedede.spec.js). He has 10 HP and is hurt only by +// a Star Bullet - the ammunition is the stars his jump and his ground swing knock loose. A hit outside the slide and +// the hammer swing freezes him for 30 frames (each hit restarts it); during those two he has super armour (still +// takes the damage, keeps going). His inhale holds Kirby (body.grab) and spits him into the ropes for 1 damage. +// x = centre, y = feet; every path is a GB velocity track (BB.KIRBY.Track) played at the speed knob. The extra knob +// runs the Extra Game script. +(function (g) { + var BB = g.BB, KB = BB.KIRBY, F = KB.f; + var SPEC = BB.SPECS.king_dedede; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.KIRBY_RING; + var BW = 22 / 8, BH = 26 / 8, CY = BH / 2; // [data] Properties_3616: 22 x 26 px, touch damage 1 + var XMIN = 1.375, XMAX = A.W - 1.375; // [hand] the ropes stop him at his half width + var ROPE_LEFT = (72-8)/8, ROPE_RIGHT = (232-8)/8; // [data] Func_49d5, source coordinates include x+8 + var ROLE = { intro: 'idle', wait: 'recovery', walk_antic: 'telegraph', walk: 'active', slide: 'active', + jump_antic: 'telegraph', jump: 'active', land: 'recovery', inhale_antic: 'telegraph', inhale: 'active', + gulp: 'active', inhale_end: 'recovery', hammer_antic: 'telegraph', hammer: 'active', dead: 'recovery' }; + var WP = MV.walk.params, JP = MV.jump.params, IP = MV.inhale.params, HP = MV.hammer.params; + var EVS = ['walk', 'jump', 'inhale', 'hammer']; + // [hand] practice cycle (entropy < 1, the easy tier): one fixed order shared by every node - walk in, jump (two stars), + // hammer (one star on the ground swing), inhale - so the ammunition comes at a steady, readable rhythm. + var CYCLE = ['walk', 'jump', 'hammer', 'inhale']; + // [data] byte &7 indexes these source tables; null slots at entry reroll the same table. + var TABLE = { + start:['walk','jump','inhale','hammer','hammer',null,null,null], + slide:['walk','jump','inhale','hammer','jump','inhale','hammer','hammer'], + jump:['jump','walk','inhale','hammer','walk','inhale','hammer','hammer'], + inhale:['inhale','walk','jump','hammer','walk','jump','hammer','hammer'], + hammer:['hammer','walk','jump','inhale','walk','jump','inhale','hammer'] + }; + var XTABLE = { + start:TABLE.start, + slide:['walk','jump','inhale','hammer','jump','inhale','hammer','walk'], + jump:['jump','walk','inhale','hammer','walk','inhale','hammer','inhale'], + inhale:['inhale','walk','jump','hammer','walk','jump','hammer','walk'], + hammer:['hammer','walk','jump','inhale','walk','jump','inhale','inhale'] + }; + // [data] the hammer arc: [frame, x px, y px (down), life frames] for him facing left; out at 0..24, back at 50..60 + var ARC = HP.arc.map(function (p, i) { return [HP.arc_at[i], p[0], p[1], HP.arc_life[i]]; }); + var BACK = HP.arc.slice().reverse().map(function (p, i) { return [HP.arc_back_at[i], p[0], p[1], i === 5 ? 8 : 2]; }); + var GROUND_REST = HP.ground_motion.slice(); GROUND_REST[0] = [GROUND_REST[0][0] - 16, 0, 0]; // the first 16 frames are the wind-up + function sgn(v) { return v < 0 ? -1 : 1; } + + function Dedede() {} + Dedede.prototype.id = 'king_dedede'; + BB.bossKit(Dedede.prototype, SPEC, ROLE); + KB.objects(Dedede.prototype); + + Dedede.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.configKirby(c); + this.max_hp = this.hp = Math.round(k.hp); this.dmg = MV.walk.damage; this.extra = KB.extraMode(c); + this.x = 27; this.y = 0; this.f = -1; this.objs = []; this.nid = 0; this.hitFlash = 0; this.stun = 0; + c.body.x = 11; // [hand] start 24 px inside the fixed viewport + this.tr = null; this.fx = 0; this.ph = null; this.aim = 0; this.side = 0; this.sw = null; this.cap = null; this.hf = -1; + this.track = {}; this.cycle = {}; this.cyc = 0; this.stamp = 0; this.offstage = false; this.now = 0; this.next = 'start'; + this.move = null; this.st = 'intro'; this.stT = 0; + var n = this.extra ? 3 : 1, t = 0; // [data] one wait before the first move (Extra three) + for (var i = 0; i < n; i++) t += this.waitLen(c); + this.timer = t * k.idle_gap; + }; + Dedede.prototype.waitLen = function (c) { // [data] MotionScript_130ed: 60 or 80 frames (Extra 18 / 30) + var a = c.rng.int(256) < 128; // jump_random 50 percent +1 branches to the longer wait + return F(this.extra ? (a ? 30 : 18) : (a ? 80 : 60)); + }; + Dedede.prototype.cy = function () { return this.y + CY; }; + Dedede.prototype.bodyBox = function () { return { x: this.x, y: this.y + CY, w: BW, h: BH }; }; + Dedede.prototype.armour = function () { // [data] wd3cd = 0: no flinch + return this.st === 'slide' || this.st === 'hammer' || (this.st === 'hammer_antic' && (this.ph === 'windup' || this.ph === 'crouch')); + }; + Dedede.prototype.p = function (key) { return this.extra && WP['extra_' + key] ? WP['extra_' + key] : WP[key]; }; + Dedede.prototype.jp = function (key) { return this.extra && JP['extra_' + key] != null ? JP['extra_' + key] : JP[key]; }; + // the Func_49ac side for a jump / hammer: 0, 1 = left, 2 = up / by side, 3, 4 = right + Dedede.prototype.sideOf = function (c) { + var b = c.body, s = JP.side_table[KB.octant(this.x, this.cy(), b.x, b.y + 1)]; + return s < 0 ? (b.x >= this.x ? 4 : 0) : s; + }; + Dedede.prototype.move1 = function (c, dt, s) { // advance the current track; true when it is over + var going = this.tr.step(this, dt, s, this.fx); + this.clampX(); + return !going; + }; + Dedede.prototype.clampX = function () { this.x = BB.clamp(this.x, XMIN, XMAX); }; + Dedede.prototype.atWall = function (dir) { return (dir < 0 && this.x <= XMIN + 1e-6) || (dir > 0 && this.x >= XMAX - 1e-6); }; + + // ---- selection ---- + Dedede.prototype.choose = function (c, node) { + var ev; + do { + var src = this.k.entropy >= 1 || (this.k.entropy > 0 && c.rng.random() < this.k.entropy); + if (src) { + ev = (this.extra ? XTABLE : TABLE)[node][c.rng.int(256)&7]; + if(!ev)continue; + } else ev = CYCLE[this.cyc++ % CYCLE.length]; + if (this.hp === IP.skip_at_hp && ev === 'inhale') node = 'inhale'; // source jumps to post-inhale table + else break; + } while (true); + this.start(c, ev); + }; + Dedede.prototype.wallCheck = function (c, node) { // [data] Func_49d5: near a rope he jumps away from it + if (this.x < ROPE_LEFT) this.startJump(c, 4); + else if (this.x >= ROPE_RIGHT) this.startJump(c, 0); + else this.choose(c, node); + }; + Dedede.prototype.wait = function (c, node) { this.next = node; this.go(c, 'wait', this.rec(this.waitLen(c))); }; + Dedede.prototype.start = function (c, ev) { + var b = c.body; + if (ev === 'jump') return this.startJump(c, this.sideOf(c)); + if (ev === 'hammer') { + this.aim = b.x; this.side = this.sideOf(c); + this.hf = this.side < 2 ? -1 : this.side > 2 ? 1 : (b.x >= this.x ? 1 : -1); this.f = this.hf; + this.ph = 'hop'; this.fx = 0; + this.tr = KB.track(this.extra ? HP.extra_hop : HP.hop); + return this.go(c, 'hammer_antic', 0, 'hammer'); + } + // walk / inhale: [data] branch_kirby_pos, back off away from the player, then walk in + this.aim = b.x; this.f = b.x >= this.x ? 1 : -1; this.fx = -this.f; this.ph = 'back'; + this.tr = KB.track(this.p('back_off')); + if (this.f > 0) { // [data] .script_13363 / MotionScript_33a15 skip the unreferenced right back-off + this.ph = 'walk'; this.approach(1); return this.go(c, ev === 'walk' ? 'walk' : 'inhale_antic', 0, ev); + } + this.go(c, ev + '_antic', 0, ev); + }; + Dedede.prototype.startJump = function (c, side) { + this.fx = side < 2 ? -1 : side > 2 ? 1 : 0; + if (this.fx) this.f = this.fx; + this.go(c, 'jump_antic', this.tele(c, F(this.extra ? 16 : 32)), 'jump'); // [data] crouch + }; + Dedede.prototype.approach = function (dir) { this.fx = dir; this.f = dir; this.tr = KB.track(this.p('approach'), 0); }; + Dedede.prototype.near = function (x) { return Math.abs(this.x - x) * 8 < WP.trigger; }; + + // ---- per tick ---- + Dedede.prototype.update = function (c) { + var dt = BB.DT; this.flash(dt); this.now = c.t; + this.stepObjs(c, dt); + this.stepCap(c); + if (this.st === 'dead') return; + if (this.stun > 1e-9) { this.stun -= dt; if(this.stun<1e-9)this.stun=0; return; } + this.stT += dt; + var s = this.spd(), st = this.st, b = c.body, ts = s / this.k.telegraph; + if (st === 'intro' || st === 'wait') { + this.face(c); this.timer -= dt; + if (this.timer > 1e-9) return; + if (st === 'intro') this.choose(c, 'start'); + else if (this.next === 'slide') this.wallCheck(c, 'slide'); + else this.choose(c, this.next); + } else if (st === 'walk_antic' || st === 'walk') { + var dir = this.f; + if (this.near(b.x) || (st === 'walk' && this.atWall(dir))) { // [data] Func_14276 (live); [hand] at a rope too + this.fx = dir; this.y = 0; this.tr = KB.track(this.p('slide')); + c.emit('dedede_slide', this.x, this.y); return this.go(c, 'slide', 0, 'walk'); + } + if (this.move1(c, dt, st === 'walk_antic' ? ts : s)) { this.approach(dir); this.go(c, 'walk', 0); } + } else if (st === 'slide') { + if (this.move1(c, dt, s)) this.wait(c, 'slide'); + } else if (st === 'jump_antic') { + this.timer -= dt; + if (this.timer > 1e-9) return; + this.ph = 'rise'; this.tr = KB.track(this.jp('rise')); + c.emit('boss_jump', this.x, this.y); this.go(c, 'jump', 0); + } else if (st === 'jump') { + if (!this.move1(c, dt, s)) return; + if (this.ph === 'rise') { // [data] drift on only if the player is still on that side + this.ph = 'fall'; this.tr = KB.track(this.jp('fall')); + if (this.fx && sgn(b.x - this.x) !== this.fx) this.fx = 0; + return; + } + this.y = 0; this.land(c); + var sv = this.jp('star_track'); + for (var i = 0; i < 2; i++) this.star(c, JP.stars[i][0], JP.stars[i][1], JP.stars[i][0] < 0 ? -1 : 1, sv); + this.go(c, 'land', this.rec(F(this.jp('land')))); + } else if (st === 'land') { + this.timer -= dt; + if (this.timer <= 1e-9) this.wallCheck(c, 'jump'); + } else if (st === 'inhale_antic') this.inhaleAntic(c, dt, s, ts); + else if (st === 'inhale') { + this.timer -= dt; + if (this.canCatch(c)) { + b.grab(c); this.cap = { ph: 'pull', vx: 0, t: 0 }; c.emit('dedede_catch', b.x, b.y + 1); + return this.go(c, 'gulp', 0); + } + if (this.timer <= 1e-9) this.go(c, 'inhale_end', this.rec(F(IP.miss_after))); + } else if (st === 'gulp') { + if (!this.cap || this.cap.ph === 'fly' || this.cap.ph === 'bounce') this.go(c, 'inhale_end', this.rec(F(IP.after))); + } else if (st === 'inhale_end') { + this.timer -= dt; + if (this.timer <= 1e-9) this.wait(c, 'inhale'); + } else if (st === 'hammer_antic') this.hammerAntic(c, dt, s, ts); + else if (st === 'hammer') this.swing(c, dt, s); + }; + Dedede.prototype.land = function (c) { c.emit('boss_land', this.x); c.emit('boss_land_hard', this.x, 0); c.shake(0.5); }; + + Dedede.prototype.inhaleAntic = function (c, dt, s, ts) { + if (this.ph === 'antic') { + this.timer -= dt; + if (this.timer <= 1e-9) { + c.emit('dedede_inhale', this.x + this.f * BW / 2, this.cy()); + this.go(c, 'inhale', (this.extra ? IP.extra_active : MV.inhale.active) / s); + } + return; + } + if (this.near(this.aim) || (this.ph === 'walk' && this.atWall(this.f))) { // [data] Func_141bb; [hand] rope stop + this.ph = 'antic'; this.y = 0; this.timer = this.tele(c, MV.inhale.telegraph_scale); + return; + } + if (this.move1(c, dt, this.ph === 'back' ? ts : s)) { this.ph = 'walk'; this.approach(this.f); } + }; + Dedede.prototype.canCatch = function (c) { // [data] Func_4b19 + var b = c.body; if (b.captured || b.invul > 0 || b.hp <= 0) return false; + var dx = (b.x - this.x) * this.f * 8, dy = (b.y + 1 - this.cy()) * 8; + return dx > 0 && dx < IP.reach[0] && Math.abs(dy) < IP.reach[1]; + }; + // Kirby in his mouth: pulled in, held, spat into the ropes. Runs every tick, also while he is frozen. + Dedede.prototype.stepCap = function (c) { + var cp = this.cap; if (!cp) return; + var b = c.body, K = b.K, mx = this.x, my = this.cy(); + if (cp.ph === 'pull') { // [data] +30/256 px/f^2 toward him, y closes 1/8 per frame + var d = sgn(mx - b.x); cp.vx += IP.pull[0]; + b.x += d * cp.vx / 8; b.y += (my - (b.y + 1)) / 8; + if (Math.abs(mx - b.x) * 8 < IP.pull[1] || sgn(mx - b.x) !== d) { cp.ph = 'hold'; cp.t = IP.hold; c.emit('dedede_gulp', mx, my); } + } else if (cp.ph === 'hold') { + b.x = mx; b.y = my - 1; + if (--cp.t <= 0) { + cp.ph = 'fly'; cp.dir = this.f; b.x = BB.clamp(mx + this.f * 1.5, K.W / 2, A.W - K.W / 2); b.y = my - 1; + c.emit('dedede_spit', b.x, my); + } + } else if (cp.ph === 'fly') { // [data] Func_49d5 rope zone, then a 24-frame scripted bounce + b.x += cp.dir * IP.spit_speed / 8; + if (cp.dir < 0 ? b.x < ROPE_LEFT : b.x >= ROPE_RIGHT) { + b.x -= cp.dir; cp.ph = 'bounce'; cp.t = 0; b.invul = 90; + c.emit('dedede_rope', b.x, b.y + 1); + } + } else { + b.x -= cp.dir * .125/8; b.y += (cp.t < 8 ? 2 : cp.t < 16 ? .75 : .125)/8; + if (++cp.t >= 24) { this.cap = null; b.release(c, this.hd(MV.inhale.damage), -cp.dir); c.emit('hurt_by_inhale', b.x, b.y+1); } + } + }; + + Dedede.prototype.hammerAntic = function (c, dt, s, ts) { + var ph = this.ph; + if (ph === 'windup' || ph === 'crouch') { + this.timer -= dt; + if (this.y > 0) this.y = Math.max(0, this.y - 2 * dt * s * 60 / 8); // [hand] a hop cut short lands first + if (this.timer > 1e-9) return; + if (ph === 'windup') { this.sw = { sf: 16, i: 1, j: 0, jump: false }; this.tr = KB.track(GROUND_REST); } + else { this.sw = { sf: 0, i: 0, j: 0, jump: true }; this.tr = KB.track(this.jp('rise').map(function (g2) { return [g2[0], 0, g2[2]]; })); this.ph = 'rise'; c.emit('boss_jump', this.x, this.y); } + this.fx = 0; return this.go(c, 'hammer', 0); + } + if (this.near(this.aim)) { // [data] Func_141bb, may cut the hop short + this.fx = 0; this.f = this.hf; + if (this.side === 0 || this.side === 4) { // ground swing: the hammer goes up behind him + this.ph = 'windup'; this.timer = this.tele(c, MV.hammer.telegraph_scale); + this.hbox(c, ARC[0], F(ARC[0][3]) * this.timer / F(16)); + } else { this.ph = 'crouch'; this.timer = this.tele(c, F(HP.crouch)); } + return; + } + if (this.move1(c, dt, ph === 'hop' ? ts : s) && ph === 'hop') { this.y = 0; this.ph = 'walk'; this.approach(sgn(this.aim - this.x)); } + if (this.ph === 'walk' && this.atWall(this.fx)) this.aim = this.x; // [hand] at a rope: swing from here + }; + Dedede.prototype.hbox = function (c, ev, life) { // one hammer hit box, fixed where it appears + var big = ev === 'impact', ox = big ? HP.impact[0] : ev[1], oy = big ? HP.impact[1] : ev[2]; + this.spawn({ kind: big ? 'hammer_impact' : 'hammer', x: this.x - this.f * ox / 8, y: this.cy() - oy / 8, + w: (big ? HP.impact[2] : HP.arc_size[0]) / 8, h: (big ? HP.impact[3] : HP.arc_size[1]) / 8, + inh: false, dmg: MV.hammer.damage, life: life, f: this.f }); + }; + Dedede.prototype.star = function (c, ox, oy, dir, segs) { + var o = this.spawn({ kind: 'star', x: this.x - this.f * ox / 8, y: this.cy() - oy / 8, w: JP.star_size[0] / 8, h: JP.star_size[1] / 8, + inh: true, dmg: MV.jump.damage, tr: KB.track(segs), dir: dir }); + o.x = BB.clamp(o.x, o.w / 2, A.W - o.w / 2); + c.emit('dedede_star', o.x, o.y); + }; + Dedede.prototype.swing = function (c, dt, s) { + var sw = this.sw, fr = dt * s * 60, end = sw.jump ? HP.jump_swing : HP.swing, life; + sw.sf += fr; + while (sw.i < ARC.length && sw.sf >= ARC[sw.i][0]) { life = ARC[sw.i][3]; this.hbox(c, ARC[sw.i++], F(life) / s); } + if (sw.sf >= HP.impact[4] && !sw.hit) { + sw.hit = true; this.hbox(c, 'impact', F(HP.impact[5]) / s); + if (!sw.jump) { this.star(c, HP.star[0], HP.star[1], this.f, this.jp('star_track')); this.land(c); } + else c.emit('boss_land', this.x); + } + while (sw.j < BACK.length && sw.sf >= BACK[sw.j][0]) { life = BACK[sw.j][3]; this.hbox(c, BACK[sw.j++], F(life) / s); } + if (this.tr && this.move1(c, dt, s)) { + if (sw.jump && this.ph === 'rise') { this.ph = 'fall'; this.tr = KB.track(this.jp('fall').map(function (g2) { return [g2[0], 0, g2[2]]; })); } + else { if (sw.jump) this.land(c); this.tr = null; this.y = 0; } + } + if (this.y < 0) this.y = 0; + if (sw.sf >= end) { this.sw = null; this.y = 0; this.tr = null; this.wait(c, 'hammer'); } + }; + + Dedede.prototype.stepObjs = function (c, dt) { + var s = this.spd(), self = this; + this.objs = this.objs.filter(function (o) { + if (o.dead) return false; + o.age += dt; + if (o.life != null) { o.life -= dt; return o.life > 1e-9; } + if (!self.free(c, o)) return true; // Kirby is pulling it this tick + var going = o.tr.step(o, dt, s, o.dir); + o.x = BB.clamp(o.x, o.w / 2, A.W - o.w / 2); // [hand] the ropes stop a star + return going; // [data] a star vanishes at the end of its track + }); + }; + + Dedede.prototype.hazards = function () { + if (this.st === 'dead') return []; + return this.objHazards(this.now, [{ kind: 'dedede', box: this.bodyBox(), dmg: this.hd(this.dmg), fromX: this.x }]); + }; + Dedede.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + if (this.st === 'dead') return null; + var s = c.body.curStar; + this.hp = Math.max(0, this.hp - dmg); this.hitFlash = 0.15; + c.emit('boss_hit', this.x - (s ? s.dir : 1) * BW / 2, s ? s.y : this.cy()); c.shake(0.3); + if (this.hp <= 0) { + this.st = 'dead'; this.objs = []; this.stun = 0; + if (this.cap) { var b = c.body; b.captured = false; b.vx = 0; b.vy = 0; b.grounded = false; this.cap = null; } // [hand] let him go unhurt + c.emit('boss_dead', this.x, this.cy()); c.shake(0.8); + } else if (!this.armour()) { this.stun = F(30); c.emit('boss_stun', this.x, this.cy()); } // [data] the flinch + return 'flesh'; + }; + Dedede.prototype.teleLeft = function () { + var st = this.st; + if (st === 'jump_antic') return this.timer; + if ((st === 'inhale_antic' && this.ph === 'antic') || (st === 'hammer_antic' && (this.ph === 'windup' || this.ph === 'crouch'))) return this.timer; + return 0; + }; + Dedede.prototype.state = function () { + var r = BB.r4, role = this.stun > 0 && this.st !== 'dead' ? 'recovery' : this.role(); + return { x: r(this.x), y: r(this.cy()), w: BW, h: BH, facing: this.f, hp: this.hp, max_hp: this.max_hp, fsm: this.st, + phase: this.ph, role: role, move: this.move, telegraph_left: role === 'telegraph' ? r(Math.max(0, this.teleLeft())) : 0, + stunned: this.stun > 0, super_armour: this.armour(), holding: this.cap ? this.cap.ph : null, extra: this.extra, + hazards: this.objState() }; + }; + + BB.CASES = BB.CASES || {}; + BB.CASES['kirby/king_dedede'] = { title: 'Arena Hammer Brute', Body: BB.Kirby, Boss: Dedede, arena: 'dedede_ring', bounds: A }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/bosses/kit.js b/environments/games/web/games/kirby_remake/bosses/kit.js new file mode 100644 index 0000000000000000000000000000000000000000..be279db25f55ac118597e113f6045f7d8767bd7c --- /dev/null +++ b/environments/games/web/games/kirby_remake/bosses/kit.js @@ -0,0 +1,98 @@ +// Shared pieces of the Dream Land bosses (load after engine/boss_kit.js, before bosses/*.js): +// * Track: a GB "set_velocities" list played back in game units. A segment is [frames, vx px/f, vy px/f (+ = up)]; +// vx is written as in the source script (negative = toward the left) and mirrored with fx. Speed s plays the +// same path s times faster (durations / s, velocities * s), so a difficulty knob never changes where things go. +// * The inhalable-object protocol the body uses: boss.inhalables() -> live objects {id, kind, x, y, w, h, ...}, +// the body moves an object it is pulling and stamps o.pulled = c.t (the boss skips that object's own motion and +// its hazard on that tick), then boss.capture(c, o) removes it and returns its kind. hazards() gets no case, so a +// boss keeps this.now = c.t from its update and passes it to objHazards(this.now, out). +(function (g) { + var BB = g.BB; + var KB = BB.KIRBY = BB.KIRBY || {}; + KB.V = 7.5; // 1 px/frame in u/s + KB.f = function (n) { return n / 60; }; // frames -> s + function Track(segs, loopFrom) { this.segs = segs; this.i = 0; this.t = 0; this.loop = loopFrom == null ? -1 : loopFrom; } + // advance by dt (s) at speed s, moving o.x / o.y; returns false once a non-looping track has finished + Track.prototype.step = function (o, dt, s, fx) { + var left = dt * (s == null ? 1 : s) * 60, guard = 0; + while (left > 1e-9 && guard++ < 64) { + if (this.i >= this.segs.length) { if (this.loop < 0) return false; this.i = this.loop; this.t = 0; } + var sg = this.segs[this.i], k = Math.min(sg[0] - this.t, left); + o.x += (fx == null ? 1 : fx) * sg[1] * k / 8; o.y += sg[2] * k / 8; + this.t += k; left -= k; + if (this.t >= sg[0] - 1e-9) { this.i++; this.t = 0; } + } + return this.loop >= 0 || this.i < this.segs.length; + }; + Track.prototype.done = function () { return this.loop < 0 && this.i >= this.segs.length; }; + Track.prototype.frames = function () { var n = 0; this.segs.forEach(function (s) { n += s[0]; }); return n; }; + KB.Track = Track; + KB.track = function (segs, loopFrom) { return new Track(segs, loopFrom); }; + // [data] wExtraGameEnabled selects the Extra motion / animation script banks (home2.asm); the property tables + // (HP, damage) are shared. So the script bank is its own axis: reset option mode: 'normal' (default) | 'extra', + // independent of the difficulty tier, which only scales boss HP, cadence and damage (specs/*.spec.js). + KB.MODES = ['normal', 'extra']; + KB.extraMode = function (c) { + var m = c.options && c.options.mode; + if (m == null) return false; + if (KB.MODES.indexOf(m) < 0) throw new Error("reset option mode must be 'normal' or 'extra', got " + JSON.stringify(m)); + return m === 'extra'; + }; + KB.MAX_HIT = 3; // [data] Properties_34c0: the Gordo's 3 bars, the original's heaviest hit + KB.dur = function (segs) { var n = 0; segs.forEach(function (s) { n += s[0]; }); return n; }; + // [data] Func_495c: octant of the player seen from a boss (0 = up, clockwise on screen), in the game's integer + // steps: bit 3 player right, bit 2 player above, bit 1 mostly horizontal, bit 0 diagonal (smaller > larger / 2) + var OCT = [4, 5, 6, 5, 0, 7, 6, 7, 4, 3, 2, 3, 0, 1, 2, 1]; + KB.octant = function (ox, oy, kx, ky) { + var e = 0, dx = Math.round((kx - ox) * 8), dy = Math.round((oy - ky) * 8); // dy in screen y (+ = player below) + if (dx > 0) e |= 8; + if (dy < 0) e |= 4; + var xd = Math.abs(dx), yd = Math.abs(dy), big = yd, small = xd; + if (yd < xd) { e |= 2; big = xd; small = yd; } + if ((big >> 1) < small) e |= 1; + return OCT[e]; + }; + // common boss methods for the inhalable protocol (boss keeps its objects in this.objs) + KB.objects = function (P) { + P.spawn = function (o) { + o.id = ++this.nid; o.pulled = -9; o.age = 0; + var hp = {apple:1,doo:1,bomb:1,puff:60,gordo:100}[o.kind]; + o.vulnerable = hp != null; if (hp != null) o.hp=hp; + this.objs.push(o); return o; + }; + P.hitObject = function (c,o) { + if(!o||o.dead||!o.vulnerable)return; + if(--o.hp>0)return; + o.dead=true;c.emit('object_hit',o.x,o.y); + if(o.kind==='bomb')this.spawn({kind:'blast',x:o.x,y:o.y,w:5,h:5,inh:false,dmg:1,fr:0}); + }; + P.inhalables = function () { return this.objs.filter(function (o) { return o.inh && !o.dead; }); }; + P.capture = function (c, o) { + if (!o || o.dead || !o.inh || this.objs.indexOf(o) < 0) return null; + o.dead = true; c.emit('inhale_catch', o.x, o.y); return o.kind; + }; + P.free = function (c, o) { return o.pulled < (typeof c === 'number' ? c : c.t); }; // not being inhaled now (c = case or tick) + // [data] Configuration Mode (B + Down + Select on the title screen): Kirby's max HP is wConfigMaxHP, 1..6 + // (DEFAULT_MAX_HP 6). The kirby_hp knob picks it; the body has already been reset with 6. + P.configKirby = function (c) { + if (this.k.kirby_hp == null) return; + c.body.max_hp = c.body.hp = Math.max(1, Math.min(6, Math.round(this.k.kirby_hp))); + }; + // damage dealt to Kirby: the game's value times the tier's dmg knob (absent = 1), rounded, at least 1 bar and never + // above the heaviest hit in the original (3 bars, the Extra Game's Gordo) [hand] + P.hd = function (n) { var m = this.k && this.k.dmg != null ? this.k.dmg : 1; return Math.min(Math.max(1, Math.round(n * m)), Math.max(n, KB.MAX_HIT)); }; + P.objHazards = function (c, out) { + var self = this; + this.objs.forEach(function (o) { + if (!o.dead && o.dmg && self.free(c, o)) out.push({ kind: o.kind, box: { x: o.x, y: o.y, w: o.w, h: o.h }, dmg: self.hd(o.dmg), fromX: o.x, object:o }); + }); + return out; + }; + P.objState = function () { + var r = BB.r4; + return this.objs.filter(function (o) { return !o.dead; }).map(function (o) { + return { kind: o.kind, x: r(o.x), y: r(o.y), w: o.w, h: o.h, inhalable: !!o.inh, dmg: o.dmg || 0 }; + }); + }; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/bosses/kracko.js b/environments/games/web/games/kirby_remake/bosses/kracko.js new file mode 100644 index 0000000000000000000000000000000000000000..b131a91e210dbc1c31c48a26bd5ba5bb314d3f2b --- /dev/null +++ b/environments/games/web/games/kirby_remake/bosses/kracko.js @@ -0,0 +1,233 @@ +// Boss "kracko": Kracko of Kirby's Dream Land. A one-eyed thundercloud that never lands: it drifts across the sky +// in a wave (or swoops low when the player is under its path), spins a ring of sparks and drops Waddle Doos. The +// Doos are the ammunition - inhaled and spat back up at the cloud as Star Bullets. The move order is the game's own +// script (jump_random 31 percent chains, see specs/kracko.spec.js); every path is a GB velocity track (BB.KIRBY.Track) +// played at the speed knob. The extra knob runs the Extra Game script: bomb passes and a charge from a fixed home. +// Coordinates: GB px / 8 = u, y up. Tags: [data] = KDL disassembly, [cited] = WiKirby, [hand] = our choice. +(function (g) { + var BB = g.BB, KB = BB.KIRBY, F = KB.f; + var SPEC = BB.SPECS.kracko; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.ARENA; + var BW = 32 / 8, BH = 26 / 8, BDMG = 1; // [data] Properties_35e9: 32 x 26 px, 1 damage + var HOME_Y = 9; // [hand] the sky line (the GB screen is taller than our arena) + var XHOME = [A.gx(88), A.gy(80)]; // [data] Extra set_abs_pos 88,80 -> (10,6), including OAM offsets + var ROLE = { intro: 'idle', drift: 'recovery', move_antic: 'telegraph', beam_antic: 'telegraph', doo_antic: 'telegraph', + bombs_antic: 'telegraph', charge_antic: 'telegraph', move: 'active', beam: 'active', doo: 'active', + bombs: 'active', charge: 'active', dead: 'recovery' }; + // [data] entrance, MotionScript_12b2d / _331aa: [frames, px/f (- = left), px/f up] + var INTRO = [[8, -1.25, -0.5], [8, -1.25, -1], [8, -1.25, -2], [8, -1, -3], [8, -0.125, 3], [8, -0.0625, 1], [8, 0, -0.125], + [16, 0, -1], [1, 0, -0.125], [10, 0, 0.125], [127, 0, 0.25], [24, 0, 0.75], [8, 0, 0.25], [8, 0, 0]]; + var INTRO_X = [[8, -2, -0.5], [8, -2, -0.5], [8, -1.25, -0.25], [8, -0.5, 0], [8, -0.25, 0]]; + function sum(tr, k) { return tr.reduce(function (a, s) { return a + s[0] * s[k]; }, 0) / 8; } + var IX0 = 16 - sum(INTRO, 1), IY0 = HOME_Y - sum(INTRO, 2); // the entrance ends at (16, HOME_Y) [hand] + // [data] bobs (vertical, px/f up): 12d57 / 12dcf normal (9-frame steps), 333f1 / 33469 Extra (6- / 3-frame steps) + function bob(n, steps) { return steps.map(function (v) { return [n, 0, v]; }); } + var BOB_LONG = [0.125, 0.25, 0.125, -0.125, -0.25, -0.125], BOB_SHORT = [0.125, 0.25, -0.25, -0.125]; + var P = MV.beam.params, DP = MV.doo.params, BP = MV.bombs.params; + function W8(v) { return v / 8; } + + var octant = KB.octant; + + function Kracko() {} + Kracko.prototype.id = 'kracko'; + BB.bossKit(Kracko.prototype, SPEC, ROLE); + KB.objects(Kracko.prototype); + + Kracko.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.configKirby(c); + this.max_hp = this.hp = Math.round(k.hp); this.dmg = BDMG; this.extra = KB.extraMode(c); + this.x = IX0; this.y = IY0; this.f = -1; this.vx = 0; this.objs = []; this.nid = 0; this.hitFlash = 0; + this.st = 'intro'; this.timer = 0; this.stT = 0; this.move = null; this.next = 'start'; this.now = 0; + this.track = {}; this.cycle = {}; this.stamp = 0; this.offstage = true; this.entered = false; + this.path = KB.track(this.extra ? INTRO.concat(INTRO_X) : INTRO); this.pathFx = 1; + this.side = 0; // [data] wKirbySideOfScreen: 0 -> the next move goes left + this.baseY = HOME_Y; this.af = 0; this.emits = []; this.drops = []; this.swoop = false; + }; + Kracko.prototype.bodyBox = function () { // no hitbox until the entrance ends [data] + if (this.st === 'intro' || this.st === 'dead') return null; + return { x: this.x, y: this.y, w: BW, h: BH }; + }; + + // the script's branches after each action (jump_random 31 percent - 1 = 30.5 %) + var J = 78/256*100; // [data] 31 percent -1 = floor(255*31/100)-1 = 78 + Kracko.prototype.choose = function (c, node) { + var ev; + if (this.extra) { this.x = XHOME[0]; this.y = XHOME[1]; } + if (this.k.entropy >= 1) { // one source byte comparison; do not also consume a weighted-pick draw + var low = c.rng.int(256) < 78; + ev = this.extra ? (node === 'beam' ? (low ? 'charge' : 'bombs') : node === 'charge' ? (low ? 'bombs' : 'beam') : (low ? 'beam' : 'charge')) : + node === 'beam' ? (low ? 'move' : 'doo') : node === 'move' ? (low ? 'doo' : 'beam') : (low ? 'beam' : 'move'); + } else if (!this.extra) { + if (node === 'beam') ev = this.pick(c, 'beam', ['move', 'doo'], [J, 100 - J]); + else if (node === 'move') ev = this.pick(c, 'move', ['doo', 'beam'], [J, 100 - J]); + else ev = this.pick(c, 'start', ['beam', 'move'], [J, 100 - J]); // start and after a Doo + } else { + if (node === 'beam') ev = this.pick(c, 'xbeam', ['charge', 'bombs'], [J, 100 - J]); + else if (node === 'charge') ev = this.pick(c, 'xcharge', ['bombs', 'beam'], [J, 100 - J]); + else ev = this.pick(c, 'xstart', ['beam', 'charge'], [J, 100 - J]); // start and after bombs + } + // [data] every action starts with a bob: normal 108 or 36 frames, Extra 36 or 12; the last 36 / 12 are the tell + var long = c.rng.chance(0.5), n = this.extra ? 3 : 9; + var steps = long ? BOB_LONG.concat(BOB_LONG) : BOB_SHORT, frames = n * steps.length, tail = this.extra ? 12 : 36; + this.path = KB.track(bob(n, steps), 0); this.pathFx = 1; this.baseY = this.y; this.next = ev; + this.go(c, 'drift', this.rec(F(frames - tail))); + if (this.timer <= 1e-9) this.antic(c); + }; + Kracko.prototype.antic = function (c) { + var ev = this.next; // the tell = the bob's last 36 frames (Extra 12) [data] + this.go(c, ev + '_antic', this.tele(c, this.extra ? F(12) : MV[ev].telegraph_scale), ev); + }; + Kracko.prototype.act = function (c) { + var ev = this.move, b = c.body, kl = b.x < this.x, s = this.spd(); + this.y = this.baseY; this.af = 0; this.emits = []; this.drops = []; this.swoop = false; + if (ev === 'move') { + var left = this.side === 0; this.side = left ? 1 : 0; // [data] alternates sides, the first goes left + var o = octant(this.x, this.y, b.x, b.y + 1); + var swoop = left ? (o === 4 || o === 5) : (o === 3 || o === 4); // [data] the two jumptables + var mp = MV.move.params, tr = swoop ? mp.swoop : mp.wave.concat(mp.wave, mp.wave); + this.path = KB.track(tr); this.pathFx = left ? -1 : 1; this.swoop = swoop; // written toward the travel side + this.go(c, 'move', F(this.path.frames()) / s); + } else if (ev === 'beam') { + var st = this.extra ? P.extra_steps : P.steps, per = this.extra ? 1 : 2; + for (var i = 0; i < st.length; i++) for (var j = 0; j < per; j++) this.emits.push([(i * per + j) * 4, st[i]]); + this.path = null; + this.go(c, 'beam', (this.extra ? P.extra_active : MV.beam.active) / s); + while (this.emits.length && this.emits[0][0] === 0) this.beamPair(c, this.emits.shift()[1]); + } else if (ev === 'doo') { + this.spawnDoo(c, kl ? -1 : 1); // [data] branch_kirby_pos: walk toward the player's side + this.path = null; + this.go(c, 'doo', MV.doo.active / s); + } else { // Extra bombs / charge: track written for the player on the left + this.path = KB.track(MV[ev].params.track); this.pathFx = kl ? 1 : -1; + if (ev === 'bombs') this.drops = (kl ? BP.drops_after : BP.drops_after_right).slice(); + this.go(c, ev, F(this.path.frames()) / s); + } + }; + Kracko.prototype.spawnDoo = function (c, dir) { + var h = DP.habits, r = c.rng.random(), acc = 0, hab = h[0][0]; + for (var i = 0; i < h.length; i++) { acc += h[i][1]; if (r < acc) { hab = h[i][0]; break; } } + this.spawn({ kind: 'doo', x: this.x, y: this.y, w: W8(DP.size[0]), h: W8(DP.size[1]), inh: true, dmg: MV.doo.damage, + dir: dir, vy: 0, fr: 0, walkFor: hab, ph: 'walk', pt: 0, k: 0 }); + c.emit('kracko_doo', this.x, this.y); + }; + Kracko.prototype.spark = function (x, y, vx, vy) { // ProjectileProperties: 6 x 6 px, 1 damage, 7 frames [data] + return this.spawn({ kind: 'spark', x: x, y: y, w: W8(P.size[0]), h: W8(P.size[1]), inh: false, dmg: MV.beam.damage, + vx: vx, vy: vy, life: P.life }); + }; + Kracko.prototype.beamPair = function (c, i) { + var of = P.offsets[i], v = P.vel[i]; // the source is y down -> flip + this.spark(this.x + W8(of[0]), this.y - W8(of[1]), v[0], -v[1]); + this.spark(this.x - W8(of[0]), this.y + W8(of[1]), -v[0], v[1]); + c.emit('kracko_spark', this.x, this.y); + }; + + Kracko.prototype.update = function (c) { + var dt = BB.DT, s = this.spd(); this.flash(dt); this.now = c.t; + this.stepObjs(c, dt); + if (this.st === 'dead') return; + this.face(c); + this.timer -= dt; this.stT += dt; + var st = this.st; + if (st === 'intro') { + this.path.step(this, dt, s); + if (this.path.done()) { + this.offstage = false; this.x = this.extra ? XHOME[0] : 16; this.y = HOME_Y; this.baseY = HOME_Y; + var n = this.extra ? 6 : 9; // [data] 12d57 / 333f1 entrance bob, 54 / 36 frames + this.path = KB.track(bob(n, BOB_LONG), 0); this.pathFx = 1; this.entered = true; + this.go(c, 'drift', F(n * 6) * this.k.idle_gap); + } + return; + } + if (this.path) this.path.step(this, dt, ROLE[st] === 'active' ? s : 1, this.pathFx); + if (st === 'beam') { + this.af += dt * 60 * s; + while (this.emits.length && this.emits[0][0] <= this.af + 1e-6) this.beamPair(c, this.emits.shift()[1]); + } else if (st === 'bombs') { + while (this.drops.length && this.path.i >= this.drops[0]) { + this.drops.shift(); + this.spawn({ kind: 'bomb', x: this.x, y: this.y, w: W8(12), h: W8(12), inh: true, dmg: MV.bombs.damage, fr: 0 }); + c.emit('kracko_bomb', this.x, this.y); + } + } + // Source charge may cross a screen edge / floor. Do not reshape the trajectory by clamping it. + if (this.timer > 1e-9) return; + if (st === 'drift') { + this.y = this.baseY; + if (this.entered) { this.entered = false; this.choose(c, 'start'); } else this.antic(c); + } else if (ROLE[st] === 'telegraph') this.act(c); + else if (ROLE[st] === 'active') { + if (this.move === 'move') { this.x = this.side === 1 ? 4 : 16; this.y = this.baseY; } // [data] 96 px each way + this.path = null; this.choose(c, this.move); + } + }; + Kracko.prototype.stepObjs = function (c, dt) { + var fr = dt * 60 * this.spd(), self = this, g0 = DP.gravity[0], gmax = DP.gravity[1], add = []; + this.objs = this.objs.filter(function (o) { + if (o.dead) return false; + o.age += dt; + if (!self.free(c, o)) return true; // Kirby is pulling it this tick + if (o.kind === 'spark') { + o.x += o.vx * fr / 8; o.y += o.vy * fr / 8; o.life -= fr; + if (o.life <= 1e-6) return false; + } else if (o.kind === 'doo') { + o.fr += fr; + o.vy = Math.max(o.vy - g0 * fr, -gmax); o.y += o.vy * fr / 8; + if (o.y <= o.h / 2) { o.y = o.h / 2; o.vy = 0; } + if (o.ph === 'walk') { + o.x += o.dir * DP.walk * fr / 8; + if (o.walkFor > 0 && o.fr >= o.walkFor) { o.ph = 'flash'; o.pt = 0; } + } else if (o.ph === 'flash') { // stands and flashes 48 frames [data] + o.pt += fr; + if (o.pt >= DP.flash) { o.ph = 'beam'; o.pt = 0; o.k = 0; c.emit('doo_beam', o.x, o.y); } + } else if (o.ph === 'beam') { // 8 directions x 3 sparks, 4 frames apart [data] + o.pt += fr; + var each = DP.beam_each[0], gap = DP.beam_each[1], n = DP.beam_dirs.length * each; + while (o.k < n && o.k * gap <= o.pt + 1e-6) { + var v = DP.beam_dirs[Math.floor(o.k / each)]; + add.push({ x: o.x, y: o.y, vx: -o.dir * v[0], vy: -v[1] }); // written walking left, y down + o.k++; + } + if (o.k >= n && o.pt >= n * gap) { o.ph = 'walk'; o.walkFor = 0; } // then walks on + } + if (o.x < -1 || o.x > A.W + 1) return false; + } else if (o.kind === 'bomb') { + o.fr += fr; o.y -= BP.fall[1] * fr / 8; + if (o.fr >= BP.fall[0]) { add.push({ blast: true, x: o.x, y: o.y }); return false; } // [data] then explodes + } else if (o.kind === 'blast') { + o.fr += fr; if (o.fr >= BP.blast[2]) return false; + } + return o.x > -2 && o.x < A.W + 2 && o.y > -2 && o.y < A.H + 3; + }); + add.forEach(function (a) { + if (a.blast) { + self.spawn({ kind: 'blast', x: a.x, y: a.y, w: W8(BP.blast[0]), h: W8(BP.blast[1]), inh: false, dmg: MV.bombs.damage, fr: 0 }); + c.emit('kracko_blast', a.x, a.y); c.shake(0.25); + } else self.spark(a.x, a.y, a.vx, a.vy); + }); + }; + + Kracko.prototype.hazards = function () { + var bx = this.bodyBox(), out = []; + if (bx) out.push({ kind: 'cloud', box: bx, dmg: this.hd(BDMG), fromX: this.x }); + return this.objHazards(this.now, out); + }; + Kracko.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + if (!this.bodyBox()) return null; + var s = c.body.curStar; + this.hp = Math.max(0, this.hp - dmg); this.hitFlash = 0.15; + c.emit('boss_hit', s ? s.x : this.x, s ? s.y : this.y); c.shake(0.3); + if (this.hp <= 0) { this.st = 'dead'; this.path = null; this.objs = []; c.emit('boss_dead', this.x, this.y); c.shake(0.8); } + return 'flesh'; + }; + Kracko.prototype.state = function () { + var r = BB.r4, role = this.role(); + return { x: r(this.x), y: r(this.y), w: BW, h: BH, facing: this.f, hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, + move: this.move, telegraph_left: role === 'telegraph' ? r(Math.max(0, this.timer)) : 0, extra: this.extra, + swoop: this.swoop, vulnerable: !!this.bodyBox(), hazards: this.objState() }; + }; + + BB.CASES = BB.CASES || {}; + BB.CASES['kirby/kracko'] = { title: 'One-Eyed Thundercloud', Body: BB.Kirby, Boss: Kracko, arena: 'bubbly_clouds' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/bosses/lololo_lalala.js b/environments/games/web/games/kirby_remake/bosses/lololo_lalala.js new file mode 100644 index 0000000000000000000000000000000000000000..22f97350ef3b5f8a12975ee8252698b4ec32f17a --- /dev/null +++ b/environments/games/web/games/kirby_remake/bosses/lololo_lalala.js @@ -0,0 +1,155 @@ +// Boss "lololo_lalala": Lololo & Lalala, the boss of Castle Lololo in Kirby's Dream Land. Two brothers in a room of +// four corridors with a door at each end (the room and its one-way bridges are body_kirby_castle.js). Each brother +// in turn appears at a random free door on one side, stands there 35 frames with a box in front of him, pushes it all +// the way across, slows down, hides for 32 frames and then takes a free row on the other side; the two share four row +// flags, so they never use the same corridor at once. The boxes are the only ammunition: inhale one, spit it back at +// the brother behind it. A brother is hurt only by Star Bullets; when one falls the other carries on alone (the +// original's AnimScript_OnLololoLalalaDestroyed clears all four row flags) and the fight ends at 0 HP in all. +// The reset option mode: 'extra' runs the Extra Game script (faster pushes, the box outruns him). +// x = centre, y = centre of the 12 x 12 px brother (his row's corridor centre), in u (8 px); the push tracks are written +// toward the push direction and played with fx = +1 (from the left door) or -1 (from the right door). +// Tags: [data] = KDL disassembly, [cited] = WiKirby, [hand] = our choice. +(function (g) { + var BB = g.BB, KB = BB.KIRBY, F = KB.f, A = BB.ARENA; + var SPEC = BB.SPECS.lololo_lalala; + var PP = SPEC.moves[0].params, DMG = SPEC.moves[0].damage; + var BW = PP.brother_size[0] / 8, BH = PP.brother_size[1] / 8, OW = PP.box_size[0] / 8, OH = PP.box_size[1] / 8; + var DOOR = { right: A.gx(PP.doors.right_x), left: A.gx(PP.doors.left_x) }; // [data] OAM x -> u: 19.125 / 1 + var ROWS = PP.doors.rows_y.map(function (y) { return A.gy(y); }); // [data] 13 / 9 / 5 / 1 u, the corridor centres + var NAMES = ['lololo', 'lalala']; + var ROLE = { intro: 'idle', fight: 'active', dead: 'recovery' }; + // the first 35 frames of the box (it slides out 16.25 px and waits) run alongside his 35 frames in the door + function split(segs) { var n = 0, i = 0; while (n < 35) n += segs[i++][0]; return [segs.slice(0, i), segs.slice(i)]; } + + function Brothers() {} + Brothers.prototype.id = 'lololo_lalala'; + BB.bossKit(Brothers.prototype, SPEC, ROLE); + KB.objects(Brothers.prototype); + + Brothers.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.configKirby(c); + this.max_hp = this.hp = Math.max(1, Math.round(k.hp)); this.dmg = DMG; this.extra = KB.extraMode(c); + this.pusher = this.extra ? PP.extra_pusher : PP.pusher; this.boxSegs = split(this.extra ? PP.extra_box : PP.box); + this.objs = []; this.nid = 0; this.hitFlash = 0; this.now = 0; this.x = A.W / 2; this.f = -1; + this.st = 'intro'; this.timer = F(PP.hide) * k.idle_gap; this.stT = 0; this.move = 'push'; this.stamp = 0; + this.track = {}; this.cycle = {}; this.rows = [false, false, false, false]; + var half = [Math.ceil(this.hp / 2), Math.floor(this.hp / 2)], self = this; // [hand] Lololo takes the odd star + this.bro = NAMES.map(function (n, i) { + return { name: n, hp: half[i], max_hp: half[i], side: PP.first_side[n], row: -1, ph: half[i] > 0 ? 'wait' : 'gone', + x: DOOR[PP.first_side[n]], y: ROWS[3], dir: 0, tr: null, timer: 0, coll: false, box: null, flash: 0, deadT: 0, pushes: 0 }; + }); + this.alive = this.bro.filter(function (b) { return b.hp > 0; }).length; + }; + // ---- one brother's script ---- + Brothers.prototype.door = function (c, b) { // [data] jumptable_random %11, rerolled while the row is taken + var r; do r = c.rng.int(256) & 3; while (this.rows[r]); + this.rows[r] = true; b.row = r; b.dir = b.side === 'right' ? -1 : 1; + b.x = DOOR[b.side]; b.y = ROWS[r]; b.coll = true; b.ph = 'appear'; b.pushes++; + b.timer = F(this.pusher[0][0]) * this.k.telegraph / this.spd(); + // [data] AnimScript_22a36 create_object at his position: the box slides out ahead of him while he stands in the door + var o = this.spawn({ kind: 'box', x: b.x, y: b.y, w: OW, h: OH, inh: true, dmg: DMG, tr: KB.track(this.boxSegs[0]), dir: b.dir, ph: 'out', by: b.name }); + o.vulnerable = true; o.hp = 1; // [data] StandardEnemyProperties: 1 HP + b.box = o.id; + c.emit('boss_push_antic', b.x, b.y); c.emit('lololo_door', b.x, b.y); + }; + Brothers.prototype.stepBrother = function (c, b, dt) { + var s = this.spd(); + if (b.flash > 0) b.flash = Math.max(0, b.flash - dt); + if (b.ph === 'dead') { b.deadT += dt; return; } + if (b.ph === 'gone') return; + b.timer -= dt; + var done = b.timer <= 1e-9; + if (b.ph === 'wait') { if (this.st !== 'intro') this.door(c, b); } + else if (b.ph === 'appear') { + if (done) { // [data] the push: 168 frames at 0.75 px/f, then 2 / 1 / 0.25 px/f + b.ph = 'push'; b.tr = KB.track(this.pusher.slice(1)); b.timer = F(b.tr.frames()) / s; + c.emit('boss_push', b.x, b.y); + } + } else if (b.ph === 'push') { + if (b.tr && !b.tr.step(b, dt, s, b.dir)) b.tr = null; + if (done) { // [data] Func_4bad: not collidable, hidden for 32 frames + b.tr = null; b.coll = false; b.ph = 'hide'; b.timer = F(PP.hide) * this.k.recovery / s; + } + } else if (b.ph === 'hide') { + if (done) { // [data] the row flag is cleared and the other side's door taken at once + if (b.row >= 0) this.rows[b.row] = false; + b.row = -1; b.side = b.side === 'right' ? 'left' : 'right'; + this.door(c, b); + } + } + }; + Brothers.prototype.stepObjs = function (c, dt) { + var s = this.spd(), self = this; + this.objs = this.objs.filter(function (o) { + if (o.dead) return false; + o.age += dt; + if (!self.free(c, o)) return true; // Kirby is pulling it this tick + var rate = o.ph === 'out' ? s / self.k.telegraph : s; + if (!o.tr.step(o, dt, rate, o.dir)) { + if (o.ph === 'out') { o.ph = 'roll'; o.tr = KB.track(self.boxSegs[1]); return true; } + return false; // [data] script_end: the box is gone + } + return o.x > -2 && o.x < A.W + 2; + }); + }; + + Brothers.prototype.update = function (c) { + var dt = BB.DT, self = this; this.flash(dt); this.now = c.t; + this.stepObjs(c, dt); + if (this.st === 'dead') { this.bro.forEach(function (b) { if (b.flash > 0) b.flash = Math.max(0, b.flash - dt); b.deadT += dt; }); return; } + this.stT += dt; + if (this.st === 'intro') { this.timer -= dt; if (this.timer <= 1e-9) this.st = 'fight'; } + this.bro.forEach(function (b) { self.stepBrother(c, b, dt); }); + }; + + Brothers.prototype.hitTargets = function () { + var out = []; + this.bro.forEach(function (b) { if (b.coll && b.ph !== 'dead' && b.ph !== 'gone') out.push({ id: b.name, box: { x: b.x, y: b.y, w: BW, h: BH } }); }); + return out; + }; + Brothers.prototype.hazards = function () { + var out = [], self = this; + this.bro.forEach(function (b) { + if (b.coll && b.ph !== 'dead' && b.ph !== 'gone') out.push({ kind: b.name, box: { x: b.x, y: b.y, w: BW, h: BH }, dmg: self.hd(DMG), fromX: b.x }); + }); + return this.objHazards(this.now, out); + }; + // [data] LololoProperties OBJINT_VULNERABLE | OBJINT_UNK3: a star costs the brother it hits 1 HP; at 0 he is destroyed and + // AnimScript_OnLololoLalalaDestroyed clears every row flag while wBossHP is not yet 0. + Brothers.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + if (this.st === 'dead') return null; + var b = null; this.bro.forEach(function (q) { if (q.name === tid) b = q; }); + if (!b || b.ph === 'dead' || b.ph === 'gone' || !b.coll) return null; + var s = c.body.curStar, n = Math.min(dmg, b.hp); + b.hp -= n; this.hp = Math.max(0, this.hp - n); b.flash = this.hitFlash = 0.15; + c.emit('boss_hit', s ? s.x : b.x, s ? s.y : b.y); c.shake(0.3); + if (b.hp <= 0) { + b.ph = 'dead'; b.coll = false; b.tr = null; b.deadT = 0; this.alive--; + this.rows = [false, false, false, false]; + c.emit('lololo_down', b.x, b.y); + } + if (this.hp <= 0) { this.st = 'dead'; this.objs = []; c.emit('boss_dead', b.x, b.y); c.shake(0.8); } + return 'flesh'; + }; + Brothers.prototype.role = function () { + if (this.st !== 'fight') return ROLE[this.st] || 'idle'; + var r = 'recovery'; + this.bro.forEach(function (b) { if (b.ph === 'push') r = 'active'; else if (b.ph === 'appear' && r !== 'active') r = 'telegraph'; }); + return r; + }; + Brothers.prototype.state = function () { + var r = BB.r4, role = this.role(), tl = 0; + this.bro.forEach(function (b) { if (b.ph === 'appear') tl = tl ? Math.min(tl, b.timer) : Math.max(0, b.timer); }); + return { hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: this.move, + telegraph_left: role === 'telegraph' ? r(Math.max(0, tl)) : 0, extra: this.extra, + brothers: this.bro.map(function (b) { + return { name: b.name, x: r(b.x), y: r(b.y), w: BW, h: BH, hp: b.hp, max_hp: b.max_hp, phase: b.ph, row: b.row, + side: b.side, dir: b.dir, hittable: b.coll && b.ph !== 'dead' && b.ph !== 'gone', timer: r(Math.max(0, b.timer)) }; + }), + rows_taken: this.rows.slice(), hazards: this.objState() }; + }; + + BB.CASES = BB.CASES || {}; + BB.CASES['kirby/lololo_lalala'] = { title: 'Box-Pushing Twins', Body: BB.KirbyCastle, Boss: Brothers, bounds: BB.KIRBY_CASTLE }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/bosses/poppy_bros_sr.js b/environments/games/web/games/kirby_remake/bosses/poppy_bros_sr.js new file mode 100644 index 0000000000000000000000000000000000000000..0c61bb3b0c69ab39db20ce4c6bf13d86856a10fd --- /dev/null +++ b/environments/games/web/games/kirby_remake/bosses/poppy_bros_sr.js @@ -0,0 +1,164 @@ +// Boss "poppy_bros_sr": Poppy Bros. Sr., the mid-boss of Green Greens in Kirby's Dream Land. A bomb-throwing jester +// who stays on the right of a fixed screen (the source scripts only ever throw left): small hops on the spot, a high +// jump that lobs a bomb from the top or - after hanging there - lands and rolls one along the floor, and a leap across +// the room and back. The bombs are the only ammunition: inhale one before it bursts and spit it back. The move order +// is the anim script's loop (JumpShort, bomb with delay, JumpShort, bomb, JumpShort, then calltable_random %11 over +// {bomb with delay, bomb, leap, leap}); every path is a GB velocity track (BB.KIRBY.Track) played at the speed knob. +// The reset option mode: 'extra' runs the Extra Game script (shorter hops, a dash in the random slot). +// x = centre, y = feet, in u (8 px); the YAML tracks are written toward his throw side (left), so they play with fx -1. +// Tags: [data] = KDL disassembly, [cited] = WiKirby, [hand] = our choice. +(function (g) { + var BB = g.BB, KB = BB.KIRBY, F = KB.f; + var SPEC = BB.SPECS.poppy_bros_sr; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var BW = 16 / 8, BH = 22 / 8, CY = 20 / 8, BDMG = 1; // [data] Data_356b: 16 x 22 px, 1 damage; box centre 20 px above his feet + var HOME_X = 16; // [hand] his spot: the long leap (120 px left) then just reaches the left + // wall and the hops (16 px right) stay clear of the right one + var DROP = 45 * 2 / 8; // [data] MotionScript_PoppyBrosSr: 45 frames falling 2 px/f before the loop + var L = -1; // the throw side + var ROLE = { intro: 'idle', hop: 'recovery', throw_antic: 'telegraph', throw: 'active', leap_antic: 'telegraph', leap: 'active', + dash_antic: 'telegraph', dash: 'active', dead: 'recovery' }; + var HOP = MV.hop.params, TP = MV.throw.params, LP = MV.leap.params, DP = MV.dash.params; + // the anim script's loop [data]; 'throw' = .ThrowBombNoDelay, 'drop' = .ThrowBombWithDelay + var LOOP = ['hop', 'drop', 'hop', 'throw', 'hop', 'random']; + var XLOOP = ['hop', 'drop', 'hop', 'throw', 'random']; // [data] AnimScript_24fba: no third hop + var SLOT = ['drop', 'throw', 'leap', 'leap'], XSLOT = ['dash', 'dash', 'drop', 'throw']; // [data] the calltable_random tables + // [hand] the easy tier's random slot (the share 1 - entropy of the picks) rerolls the leap - the one move that brings no + // bomb - so every pass of the loop brings ammunition; the roll itself stays the source's, so the seed still matters. + // The Extra table has no leap: there the easy pick is the source table as it is. + var BLAST = TP.blast; + + function Poppy() {} + Poppy.prototype.id = 'poppy_bros_sr'; + BB.bossKit(Poppy.prototype, SPEC, ROLE); + KB.objects(Poppy.prototype); + + Poppy.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.configKirby(c); + this.max_hp = this.hp = Math.round(k.hp); this.dmg = BDMG; this.extra = KB.extraMode(c); + this.x = HOME_X; this.y = DROP; this.f = L; this.objs = []; this.nid = 0; this.hitFlash = 0; + this.st = 'intro'; this.timer = F(45) * k.idle_gap; this.stT = 0; this.move = null; this.now = 0; + this.track = {}; this.cycle = {}; this.stamp = 0; this.offstage = false; + this.step = 0; this.tr = null; this.kind = null; + }; + Poppy.prototype.bodyBox = function () { + if (this.st === 'dead') return null; + return { x: this.x, y: this.y + CY, w: BW, h: BH }; + }; + Poppy.prototype.p = function (key) { return this.extra && TP['extra_' + key] != null ? TP['extra_' + key] : TP[key]; }; + function times(segs, n) { var out = []; for (var i = 0; i < n; i++) out = out.concat(segs); return out; } + Poppy.prototype.hopTrack = function () { return KB.track(this.extra ? times(HOP.extra_track, HOP.extra_repeat) : times(HOP.track, HOP.repeat)); }; + + // ---- the anim script loop ---- + Poppy.prototype.next = function (c) { + var loop = this.extra ? XLOOP : LOOP, ev = loop[this.step++ % loop.length]; + if (ev === 'random') { + var src = this.k.entropy >= 1 || (this.k.entropy > 0 && c.rng.random() < this.k.entropy), table = this.extra ? XSLOT : SLOT; + do ev = table[c.rng.int(256) & 3]; while (!src && ev === 'leap'); + } + this.start(c, ev); + }; + Poppy.prototype.start = function (c, ev) { + var s = this.spd(); + this.x = HOME_X; this.y = 0; // every track is closed: start each move from the spot itself + if (ev === 'hop') { // [data] .JumpShort, repeated; it is the wait between attacks + this.tr = this.hopTrack(); + this.go(c, 'hop', this.rec(F(this.tr.frames())) / s, 'hop'); + } else if (ev === 'throw' || ev === 'drop') { // [data] the high jump; the bomb leaves at the release frame + this.kind = ev === 'throw' ? 'nodelay' : 'delay'; this.tr = KB.track(this.p('jump')); + this.go(c, 'throw_antic', this.tele(c, F(this.p('release')[this.kind])) / s, 'throw'); + } else if (ev === 'leap') { // [data] .JumpLong: the mid hop out and back, then the long leap + this.tr = KB.track(LP.mid); + this.go(c, 'leap_antic', this.tele(c, F(this.tr.frames())) / s, 'leap'); + } else { // [data] Extra: MotionScript_31124, 18 frames backing up first + this.tr = KB.track(DP.track); + this.go(c, 'dash_antic', this.tele(c, F(18)) / s, 'dash'); + } + }; + // Advance the current track. A knob that stretches a state (recovery for the hops, telegraph for a wind-up) plays + // the motion at the matching rate, so the path and its timing marks stay the game's own: the bomb still leaves at + // the top of the jump, the mid hop still ends on his spot [hand]. + Poppy.prototype.move1 = function (dt, rate) { + if (this.tr && !this.tr.step(this, dt, rate, L)) this.tr = null; + if (this.y < 0) this.y = 0; + }; + + Poppy.prototype.update = function (c) { + var dt = BB.DT, s = this.spd(); this.flash(dt); this.now = c.t; + this.stepObjs(c, dt); + if (this.st === 'dead') return; + this.timer -= dt; this.stT += dt; + var st = this.st, done = this.timer <= 1e-9; + if (st === 'intro') { // [data] dropped in from above: 45 frames at 2 px/f + this.y = Math.max(0, DROP * this.timer / (F(45) * this.k.idle_gap)); + if (done) { this.y = 0; this.next(c); } + } else if (st === 'hop') { + this.move1(dt, s / this.k.recovery); + if (done) this.next(c); + } else if (st === 'throw_antic') { + this.move1(dt, s / this.k.telegraph); + if (done) { this.bomb(c); this.go(c, 'throw', F(this.p('total')[this.kind] - this.p('release')[this.kind]) / s); } + } else if (st === 'throw') { + this.move1(dt, s); + if (done) { this.tr = null; this.next(c); } + } else if (st === 'leap_antic') { + this.move1(dt, s / this.k.telegraph); + if (done) { this.x = HOME_X; this.y = 0; this.tr = KB.track(LP.long); c.emit('boss_jump', this.x, this.y); this.go(c, 'leap', F(this.tr.frames()) / s); } + } else if (st === 'leap') { + this.move1(dt, s); + if (done) { this.tr = null; c.emit('boss_land', this.x); this.next(c); } + } else if (st === 'dash_antic') { + this.move1(dt, s / this.k.telegraph); + if (done) { c.emit('poppy_dash', this.x, this.y); this.go(c, 'dash', F(DP.anim - 18) / s); } + } else if (st === 'dash') { + this.move1(dt, s); + if (done) { this.tr = null; this.next(c); } + } + }; + Poppy.prototype.bomb = function (c) { // [data] AnimScript_PoppyBrosSrBomb: position_offset -16, 8 (left, down) + var sp = TP.spawn, w = TP.bomb_size[0] / 8, h = TP.bomb_size[1] / 8; + var o = this.spawn({ kind: 'bomb', x: this.x - L * sp[0] / 8, y: this.y + CY - sp[1] / 8, w: w, h: h, inh: true, dmg: MV.throw.damage, + tr: KB.track(this.p(this.kind === 'nodelay' ? 'bounce' : 'fall')), dir: L, ph: this.kind }); + c.emit('poppy_bomb', o.x, o.y); + }; + Poppy.prototype.stepObjs = function (c, dt) { + var s = this.spd(), self = this, burst = []; + this.objs = this.objs.filter(function (o) { + if (o.dead) return false; + o.age += dt; + if (o.kind === 'blast') { o.fr += dt * 60 * s; return o.fr < BLAST[2]; } // [data] 32 frames, the whole box hurts + if (!self.free(c, o)) return true; // Kirby is pulling it this tick + if (!o.tr.step(o, dt, s, o.dir)) { burst.push(o); return false; } // [data] the path ends: it explodes where it is + return o.x > -2; + }); + burst.forEach(function (o) { // [data] create_object AnimScript_Explosion, ExplosionProperties + self.spawn({ kind: 'blast', x: o.x, y: o.y, w: BLAST[0] / 8, h: BLAST[1] / 8, inh: false, dmg: MV.throw.damage, fr: 0 }); + c.emit('poppy_blast', o.x, o.y); c.shake(0.25); + }); + }; + + Poppy.prototype.hazards = function () { + var bx = this.bodyBox(), out = []; + if (bx) out.push({ kind: 'poppy', box: bx, dmg: this.hd(BDMG), fromX: this.x }); + return this.objHazards(this.now, out); + }; + // [data] his interaction flags are OBJINT_VULNERABLE | OBJINT_UNK3 and his script sets no hurt function: a star costs + // him 1 HP and he carries on (the 30-frame hurt shake is presentation only, here the hit flash). + Poppy.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + if (this.st === 'dead') return null; + var s = c.body.curStar; + this.hp = Math.max(0, this.hp - dmg); this.hitFlash = 0.15; + c.emit('boss_hit', s ? s.x : this.x, s ? s.y : this.y + CY); c.shake(0.3); + if (this.hp <= 0) { this.st = 'dead'; this.tr = null; this.objs = []; c.emit('boss_dead', this.x, this.y + CY); c.shake(0.8); } + return 'flesh'; + }; + Poppy.prototype.state = function () { + var r = BB.r4, role = this.role(); + return { x: r(this.x), y: r(this.y + CY), w: BW, h: BH, facing: this.f, hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, + move: this.move, telegraph_left: role === 'telegraph' ? r(Math.max(0, this.timer)) : 0, extra: this.extra, hazards: this.objState() }; + }; + + BB.CASES = BB.CASES || {}; + BB.CASES['kirby/poppy_bros_sr'] = { title: 'Bomb-Throwing Jester', Body: BB.Kirby, Boss: Poppy, arena: 'green_greens_mid' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/bosses/whispy_woods.js b/environments/games/web/games/kirby_remake/bosses/whispy_woods.js new file mode 100644 index 0000000000000000000000000000000000000000..201477e3bb0d48cc7d1ec3e6c05df850ae8ce330 --- /dev/null +++ b/environments/games/web/games/kirby_remake/bosses/whispy_woods.js @@ -0,0 +1,152 @@ +// Boss "whispy_woods": Whispy Woods of Kirby's Dream Land. A rooted tree on the right: it blows air puffs and drops +// apples. The move order is the game's own script (jump_random chains, see specs/whispy_woods.spec.js); the only way +// to hurt it is an apple inhaled and spat back as a Star Bullet. Timers are in seconds (frames / 60), every object +// path is a GB velocity track (BB.KIRBY.Track) played at the speed knob. The extra knob runs the Extra Game script. +(function (g) { + var BB = g.BB, KB = BB.KIRBY, F = KB.f; + var SPEC = BB.SPECS.whispy_woods; + var MV = {}; SPEC.moves.forEach(function (m) { MV[m.name] = m; }); + var A = BB.ARENA; + var TX = 17, TY = 4, TW = 26 / 8, TH = 64 / 8, TDMG = 2; // [data] Data_3586: 26 x 64 px, touch damage 2 + var ROLE = { intro: 'idle', blink: 'recovery', puffs_antic: 'telegraph', puffs: 'active', puff_burst_antic: 'telegraph', + puff_burst: 'active', apples: 'active', drop: 'active', dead: 'recovery' }; + // a source track [frames, px/f left, px/f up] (0 frames = forever) -> Track segments (vx < 0 = left) + function segs(tr, sy) { return tr.map(function (s) { return [s[0] || 600, -s[1], s[2] * (sy || 1)]; }); } + var P0 = MV.puffs.params, AP = MV.apples.params; + var FALL = AP.fall.slice(1).map(function (s) { return [s[0], 0, s[2]]; }); // initial 25 frames are the hang, once + var ROLL = AP.roll.concat(AP.roll_loop).map(function (s) { return [s[0], -s[1], s[2]]; }); + + function Whispy() {} + Whispy.prototype.id = 'whispy_woods'; + BB.bossKit(Whispy.prototype, SPEC, ROLE); + KB.objects(Whispy.prototype); + + Whispy.prototype.reset = function (c) { + var k = this.k = BB.knobs(SPEC.difficulty, c.d); + this.configKirby(c); + this.max_hp = this.hp = Math.round(k.hp); this.dmg = TDMG; this.extra = KB.extraMode(c); + this.x = TX; this.y = TY; this.f = -1; this.vx = 0; this.objs = []; this.nid = 0; this.hitFlash = 0; + this.st = 'intro'; this.timer = F(60) * k.idle_gap; this.stT = 0; this.move = null; this.n = 0; this.next = 'start'; + this.track = {}; this.cycle = {}; this.stamp = 0; this.offstage = false; this.now = 0; + }; + Whispy.prototype.bodyBox = function () { return { x: TX, y: TY, w: TW, h: TH }; }; + + // the script's branches after each attack (jump_random N percent); Extra branches flattened into one roll + Whispy.prototype.choose = function (c, node) { + var ev; + if (this.k.entropy >= 1) { + // [data] SCRIPT_JUMP_RANDOM compares a random byte with an integer threshold. + var branch = function (n) { return c.rng.int(256) < n; }; + var puffChoice = function () { return branch(96) ? 'puff_burst' : 'puffs'; }; + if (!this.extra) { + ev = node === 'start' ? (branch(128) ? 'apples' : 'puffs') : node === 'puffs' ? (branch(32) ? 'puff_burst' : 'apples') : + node === 'puff_burst' ? (branch(64) ? 'puffs' : 'apples') : (branch(64) ? 'apples' : 'puffs'); + } else { + ev = node === 'start' ? (branch(128) ? 'drop' : puffChoice()) : node === 'puffs' ? 'drop' : + node === 'puff_burst' ? (branch(64) ? puffChoice() : 'drop') : (branch(112) ? 'drop' : puffChoice()); + } + this.n = 0; this.start(c, ev); return; + } + if (!this.extra) { + if (node === 'start') ev = this.pick(c, 'start', ['apples', 'puffs'], [50, 50]); + else if (node === 'puffs') ev = this.pick(c, 'puffs', ['puff_burst', 'apples'], [13, 87]); + else if (node === 'puff_burst') ev = this.pick(c, 'burst', ['puffs', 'apples'], [25, 75]); + else ev = this.pick(c, 'apples', ['apples', 'puffs'], [25, 75]); + } else { + if (node === 'start') ev = this.pick(c, 'xstart', ['drop', 'puffs', 'puff_burst'], [50, 31, 19]); + else if (node === 'puffs') ev = 'drop'; + else if (node === 'puff_burst') ev = this.pick(c, 'xburst', ['drop', 'puffs', 'puff_burst'], [75, 15.5, 9.5]); + else ev = this.pick(c, 'xdrop', ['drop', 'puffs', 'puff_burst'], [44, 34.7, 21.3]); + } + this.n = 0; this.start(c, ev); + }; + Whispy.prototype.start = function (c, ev) { + if (ev === 'puffs' || ev === 'puff_burst') this.go(c, ev + '_antic', this.tele(c, MV[ev].telegraph_scale), ev); + else this.dropOne(c, ev); + }; + Whispy.prototype.blink = function (c, after) { // [data] BlinkTwice: 80 frames (Extra 60) + this.next = after; this.go(c, 'blink', this.rec(F(this.extra ? 60 : 80))); + }; + Whispy.prototype.dropOne = function (c, ev) { + var kind = 'apple'; + if (ev === 'drop') kind = this.n === 0 ? 'gordo' : this.n === 1 ? 'apple' : c.rng.chance(0.5) ? 'gordo' : 'apple'; // [data] + var px = AP.x_px[c.rng.int(8)]; + var o = { kind: kind, x: A.gx(px), y: A.gy(32), w: 1.5, h: 1.5, inh: kind === 'apple', dmg: kind === 'gordo' ? MV.drop.params.gordo_damage : 1, + ph: 'hang', hang: F(25) * this.k.telegraph, tr: KB.track(FALL), dir: 0 }; + this.spawn(o); c.emit('whispy_drop', o.x, o.y); + var gap = ev === 'drop' ? (this.n === 2 ? F(50) : F(60)) : MV.apples.active; // [data] 90 frames per apple, Extra 60 / 60 / 50 + this.go(c, ev, gap / this.spd(), ev); + }; + Whispy.prototype.puff = function (c) { + var sy = c.rng.chance(0.5) ? 1 : -1; // [data] jump_random 50 percent: drift up or down + var tr = this.extra ? KB.track(segs(P0.extra_track, sy), 0) : KB.track(segs(P0.track, sy), 4); + this.spawn({ kind: 'puff', x: TX + P0.spawn[0] / 8, y: TY - P0.spawn[1] / 8, w: 1.5, h: 1.5, inh: false, dmg: MV.puffs.damage, tr: tr }); + c.emit('whispy_puff', TX - 2, TY - 3); + }; + + Whispy.prototype.update = function (c) { + var dt = BB.DT; this.flash(dt); this.now = c.t; + this.stepObjs(c, dt); + if (this.st === 'dead') return; + this.timer -= dt; this.stT += dt; + if (this.timer > 1e-9) return; + var st = this.st, m = this.move; + if (st === 'intro') this.blink(c, 'start'); + else if (st === 'blink') this.choose(c, this.next); + else if (st === 'puffs_antic' || st === 'puff_burst_antic') { + this.puff(c); + var act = m === 'puff_burst' && this.extra ? MV.puff_burst.params.extra_active : MV[m].active; + this.go(c, m, act / this.spd()); + } else if (st === 'puffs' || st === 'puff_burst') { + if (++this.n < MV[m].params.count) this.go(c, m + '_antic', this.tele(c, MV[m].telegraph_scale)); + else if (m === 'puffs') this.blink(c, 'puffs'); + else { this.move = null; this.choose(c, 'puff_burst'); } // [data] no blink after the fast burst + } else if (st === 'apples' || st === 'drop') { + if (++this.n < 3) this.dropOne(c, m); + else this.blink(c, 'apples'); + } + }; + Whispy.prototype.stepObjs = function (c, dt) { + var s = this.spd(), self = this, b = c.body; + this.objs = this.objs.filter(function (o) { + if (o.dead) return false; + o.age += dt; + if (!self.free(c, o)) return true; // Kirby is pulling it this tick + if (o.kind === 'puff') o.tr.step(o, dt, s); + else if (o.ph === 'hang') { o.hang -= dt; if (o.hang <= 1e-9) o.ph = 'fall'; } + else if (o.ph === 'fall') { + o.tr.step(o, dt, s); + if (o.y <= o.h / 2 || o.tr.done()) { // reaches the floor: roll toward Kirby's side [data] branch_kirby_pos + o.y = o.h / 2; o.ph = 'roll'; o.dir = b.x < o.x ? 1 : -1; o.tr = KB.track(ROLL, 8); + c.emit('apple_land', o.x, 0); + } + } else { + o.tr.step(o, dt, s, o.dir); + if (o.y < o.h / 2) o.y = o.h / 2; + } + return o.x > -1.5 && o.x < A.W + 1.5 && o.y > -2 && o.y < A.H + 2; + }); + }; + + Whispy.prototype.hazards = function () { + if (this.st === 'dead') return []; + return this.objHazards(this.now, [{ kind: 'trunk', box: this.bodyBox(), dmg: this.hd(TDMG), fromX: TX }]); + }; + Whispy.prototype.onNailHit = function (c, dmg, slashDir, slashFacing, tid) { + if (this.st === 'dead') return null; + var s = c.body.curStar; + this.hp = Math.max(0, this.hp - dmg); this.hitFlash = 0.15; + c.emit('boss_hit', TX - TW / 2, s ? s.y : TY); c.shake(0.3); + if (this.hp <= 0) { this.st = 'dead'; this.objs = []; c.emit('boss_dead', TX, TY + 1); c.shake(0.8); } + return 'flesh'; + }; + Whispy.prototype.state = function () { + var r = BB.r4, role = this.role(); + return { x: TX, y: TY, w: TW, h: TH, facing: -1, hp: this.hp, max_hp: this.max_hp, fsm: this.st, role: role, move: this.move, + telegraph_left: role === 'telegraph' ? r(Math.max(0, this.timer)) : 0, extra: this.extra, + hazards: this.objState() }; + }; + + BB.CASES = BB.CASES || {}; + BB.CASES['kirby/whispy_woods'] = { title: 'Ancient Apple Tree', Body: BB.Kirby, Boss: Whispy, arena: 'green_greens' }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/compact_actions.json b/environments/games/web/games/kirby_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..45bc08ba3648ea07b78f1c3cc92be8ddd52f3fe1 --- /dev/null +++ b/environments/games/web/games/kirby_remake/compact_actions.json @@ -0,0 +1,340 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "kirby_remake", + "version": "kirby-compact@2", + "heads": [ + { + "name": "mouth", + "options": [ + { + "label": "none" + }, + { + "label": "hold", + "keys": [ + "J" + ] + }, + { + "label": "press_1", + "tap": [ + "J" + ] + }, + { + "label": "press_2", + "subs": [ + [], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "press_3", + "subs": [ + [], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "press_4", + "subs": [ + [], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "press_5", + "subs": [ + [], + [], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "press_6", + "subs": [ + [], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "triple_odd", + "subs": [ + [ + "J" + ], + [], + [ + "J" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "hold_from_2", + "subs": [ + [], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + } + ] + }, + { + "name": "walk", + "options": [ + { + "label": "none" + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "left_tap", + "tap": [ + "A" + ] + }, + { + "label": "right_tap", + "tap": [ + "D" + ] + }, + { + "label": "left_half", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [], + [] + ] + }, + { + "label": "right_half", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [], + [] + ] + }, + { + "label": "left_2", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [], + [], + [], + [] + ] + }, + { + "label": "right_2", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [], + [], + [], + [] + ] + } + ] + }, + { + "name": "vertical", + "options": [ + { + "label": "none" + }, + { + "label": "jump", + "keys": [ + "Space" + ] + }, + { + "label": "jump_tap", + "tap": [ + "Space" + ] + }, + { + "label": "jump_late", + "subs": [ + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "float", + "keys": [ + "W" + ] + }, + { + "label": "float_tap", + "tap": [ + "W" + ] + }, + { + "label": "float_flap", + "subs": [ + [], + [ + "W" + ], + [], + [], + [ + "W" + ], + [] + ] + }, + { + "label": "down", + "keys": [ + "S" + ] + }, + { + "label": "down_tap", + "tap": [ + "S" + ] + }, + { + "label": "down_alt", + "subs": [ + [ + "S" + ], + [], + [ + "S" + ], + [], + [ + "S" + ], + [] + ] + }, + { + "label": "jump_half", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [] + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/kirby_remake/draw/kaboola.js b/environments/games/web/games/kirby_remake/draw/kaboola.js new file mode 100644 index 0000000000000000000000000000000000000000..0718347986c200ced37bb10cbff0e8ac39cf1f39 --- /dev/null +++ b/environments/games/web/games/kirby_remake/draw/kaboola.js @@ -0,0 +1,51 @@ +// Kaboola: a blimp with a cannon that flips from under the hull to over it, firing small black cannonballs, and no face, as +// WiKirby describes the original (S15). The shape is this project's own (a rounded hull, tail fins, portholes); the colours +// too, since the GB original is monochrome. Exactly its 36 x 32 px box is the hull's reach. +// A mint leaf is drawn on Kirby so the fight's rule reads at a glance. Original procedural art; nothing traced from the game. +(function (g) { + var BB = g.BB, D = BB.KIRBY_DRAW, P = BB.VIEW.PAL; + function hull(x, w, st, V, t, hit) { + var X = V.sx(st.x), Y = V.sy(st.y), rx = st.w * V.S / 2, ry = st.h * V.S / 2, ram = st.fsm === 'ram'; + var tip = st.ram === 'up' ? 0.14 : st.ram === 'down' ? -0.14 : 0; + x.save(); x.translate(X, Y); if (st.fsm === 'ram_antic' || ram) x.rotate(tip); + x.fillStyle = '#6b5a8f'; x.strokeStyle = P.ink; x.lineWidth = 2.6; // tail fins + [[-1], [1]].forEach(function (s) { x.beginPath(); x.moveTo(rx * 0.55, s[0] * ry * 0.25); x.lineTo(rx + 4, s[0] * (ry + 2)); x.lineTo(rx + 8, s[0] * ry * 0.2); x.closePath(); x.fill(); x.stroke(); }); + var gr = x.createLinearGradient(0, -ry, 0, ry); + gr.addColorStop(0, hit ? '#ffffff' : '#ff9f9f'); gr.addColorStop(0.5, hit ? '#ffd4d4' : '#e0475b'); gr.addColorStop(1, '#9c2a43'); + D.ellipse(x, 0, 0, rx, ry * 0.86, gr, P.ink, 3); + x.strokeStyle = 'rgba(255,255,255,0.35)'; x.lineWidth = 2; // hull bands + [-0.45, 0, 0.45].forEach(function (k) { x.beginPath(); x.ellipse(k * rx, 0, 7, ry * 0.8 * (1 - Math.abs(k) * 0.45), 0, 0, Math.PI * 2); x.stroke(); }); + [-0.6, -0.2, 0.2].forEach(function (k) { D.ellipse(x, k * rx, -3, 6, 6, '#d8f2ff', P.ink, 2); }); // portholes: not a face + var s = st.inverted ? -1 : 1, open = w.sq && w.sq.length && typeof w.sq[0] !== 'number'; + x.fillStyle = '#3a3550'; x.strokeStyle = P.ink; x.lineWidth = 2.2; // the cannon, 16 px under or over its centre + D.round(x, -rx * 0.5, s * ry * 0.78 - 9, rx * 0.8, 18, 6); x.fill(); x.stroke(); + D.round(x, -rx * 0.5 - (open ? 15 : 10), s * ry * 0.78 - 5, 18, 10, 3); x.fill(); x.stroke(); + x.restore(); + } + function bullet(x, o, V) { + var X = V.sx(o.x), Y = V.sy(o.y), rx = o.w * V.S / 2, ry = o.h * V.S / 2; + x.fillStyle = 'rgba(255,140,60,0.35)'; x.fillRect(X, Y - ry * 0.6, rx * 3, ry * 1.2); + D.ellipse(x, X, Y, rx, ry, '#2a2438', '#fff4b8', 1.6); // black, with a pale rim to read on the dark sky + } + function leaf(x, c, V, t) { + var b = c.body, X = V.sx(b.x), Y = V.sy(b.y + 2.6) + Math.sin(t * 8) * 2; + x.save(); x.translate(X, Y); x.rotate(-0.4); + x.fillStyle = '#5fcf8a'; x.strokeStyle = P.ink; x.lineWidth = 1.8; + x.beginPath(); x.moveTo(-11, 0); x.quadraticCurveTo(0, -11, 11, 0); x.quadraticCurveTo(0, 11, -11, 0); x.closePath(); x.fill(); x.stroke(); + x.beginPath(); x.moveTo(-9, 0); x.lineTo(9, 0); x.stroke(); + x.restore(); + } + function draw(x, c, t, V) { + var w = c.boss, st = w.state(), flash = !c.result && w.hitFlash > 0; + (w.objs || []).forEach(function (o) { if (!o.dead && o.kind === 'bullet') bullet(x, o, V); }); + if (w.st !== 'dead') hull(x, w, st, V, t, flash); + leaf(x, c, V, t); + if (st.role === 'telegraph') { + var X = V.sx(st.x), Y = Math.max(60, V.sy(st.y + st.h / 2) - 14); + x.save(); x.font = 'bold 12px "Microsoft YaHei","Segoe UI",sans-serif'; x.textAlign = 'center'; + D.round(x, X - 24, Y - 18, 48, 18, 9); x.fillStyle = P.cream; x.fill(); x.lineWidth = 1.6; x.strokeStyle = P.ink; x.stroke(); + x.fillStyle = P.ink; x.fillText('Charge', X, Y - 5); x.restore(); + } + } + BB.BOSS_DRAW['kirby/kaboola'] = { hazards: function () {}, bar: function () { return '#e0475b'; }, body: draw }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/draw/king_dedede.js b/environments/games/web/games/kirby_remake/draw/king_dedede.js new file mode 100644 index 0000000000000000000000000000000000000000..9e14a672ee8f37a4646d502b5b842088314c86b5 --- /dev/null +++ b/environments/games/web/games/kirby_remake/draw/king_dedede.js @@ -0,0 +1,103 @@ +// King Dedede: a round blue penguin-like king (the general series look: red tuque with a gold ridge, red coat with white +// fur trim, patterned obi, yellow mouth, gloves and feet) with his wooden mallet. The body is drawn over the 22 x 26 px +// hit box; while the hammer box is live the mallet head is drawn on it (palette.js), otherwise it rests on his shoulder. +// The inhale cone is the exact Func_4b19 catch box; the stars and the King get edge arrows when they leave the fixed +// 160 px view (the ring room is 288 px, ScriptFunc_LockScrolling locks the camera). +(function (g) { + var BB = g.BB, D = BB.KIRBY_DRAW, P = BB.VIEW.PAL, ART = BB.ART; + function suction(x, c, t, V) { + var b = c.boss, IP = b.spec.moves[2].params, on = b.st === 'inhale', tell = b.st === 'inhale_antic' && b.ph === 'antic'; + if (!on && !tell) return; + // The zone is exactly where Kirby's centre gets caught: 0 < dx < reach[0] px ahead of him, |dy| < reach[1] px. + var x0 = V.sx(b.x), x1 = V.sx(b.x + b.f * IP.reach[0] / 8), yc = V.sy(b.cy()), h = IP.reach[1] / 8 * V.S, L = Math.min(x0, x1), W = Math.abs(x1 - x0); + x.save(); + if (on) { + var gr = x.createLinearGradient(x0, 0, x1, 0); gr.addColorStop(0, 'rgba(255,214,91,0.45)'); gr.addColorStop(1, 'rgba(255,214,91,0.05)'); + x.fillStyle = gr; x.fillRect(L, yc - h, W, 2 * h); + x.strokeStyle = 'rgba(255,250,230,0.9)'; x.lineWidth = 2.2; x.lineCap = 'round'; + for (var i = 0; i < 5; i++) { var q = 1 - ((t * 2.4 + i / 5) % 1), ax = x0 + (x1 - x0) * q; x.beginPath(); x.moveTo(ax, yc - h * 0.8 * q - 4); x.quadraticCurveTo(ax - b.f * 16, yc, ax, yc + h * 0.8 * q + 4); x.stroke(); } + } + x.setLineDash([7, 5]); x.strokeStyle = on ? 'rgba(232,64,79,0.95)' : 'rgba(255,176,46,0.95)'; x.lineWidth = 2.5; x.strokeRect(L, yc - h, W, 2 * h); + x.restore(); + } + function edgeMarks(x, c, t, V) { + var lo = V.cameraX, hi = V.cameraX + BB.ARENA.W, b = c.boss, items = []; + if (b.st !== 'dead' && (b.x < lo + 0.3 || b.x > hi - 0.3)) items.push({ x: b.x, y: b.cy(), col: P.red, r: 12, boss: true }); + (b.objs || []).forEach(function (o) { if (!o.dead && o.kind === 'star' && (o.x < lo || o.x > hi)) items.push({ x: o.x, y: o.y, col: P.gold, r: 9 }); }); + items.forEach(function (it) { + var left = it.x < (lo + hi) / 2, X = left ? V.OX + 24 : V.OX + BB.ARENA.W * V.S - 24, Y = Math.max(76, Math.min(V.FLOOR - 14, V.sy(it.y))), dir = left ? -1 : 1; + x.save(); x.globalAlpha = 0.65 + 0.35 * Math.abs(Math.sin(t * 6)); x.fillStyle = it.col; x.strokeStyle = P.ink; x.lineWidth = 2.5; x.lineJoin = 'round'; + x.beginPath(); x.moveTo(X + dir * it.r, Y); x.lineTo(X - dir * it.r * 0.6, Y - it.r); x.lineTo(X - dir * it.r * 0.6, Y + it.r); x.closePath(); x.fill(); x.stroke(); + if (it.boss) { x.font = 'bold 11px "Microsoft YaHei",sans-serif'; x.textAlign = 'center'; x.fillStyle = P.cream; x.strokeStyle = P.ink; x.lineWidth = 3; x.strokeText('Hammer Brute', X - dir * 4, Y - it.r - 5); x.fillText('Hammer Brute', X - dir * 4, Y - it.r - 5); } + x.restore(); + }); + } + function mallet(x, ang, flash) { // resting mallet, local to the shoulder + x.save(); x.rotate(ang); + D.round(x, -4.5, -4, 9, 62, 4); x.fillStyle = '#d9a066'; x.fill(); x.lineWidth = 2.2; x.strokeStyle = P.ink; x.stroke(); + var gr = x.createLinearGradient(-24, 0, 24, 0); gr.addColorStop(0, '#f0bf7e'); gr.addColorStop(0.5, '#d48f4c'); gr.addColorStop(1, '#a8682f'); + D.round(x, -24, 48, 48, 34, 9); x.fillStyle = flash ? '#fff1d6' : gr; x.fill(); x.lineWidth = 2.5; x.stroke(); + x.fillStyle = '#8a5326'; x.fillRect(-18, 50, 7, 30); x.fillRect(11, 50, 7, 30); + x.restore(); + } + function body(x, c, t, V) { + var b = c.boss, X = V.sx(b.x), Y = V.sy(b.y), flash = b.hitFlash > 0 && !c.result, st = b.st, dead = st === 'dead'; + var walking = st === 'walk' || (st === 'walk_antic' && b.ph === 'walk') || (st === 'inhale_antic' && b.ph === 'walk') || (st === 'hammer_antic' && b.ph === 'walk'); + var step = walking ? Math.sin(t * 13) : 0, slide = st === 'slide', crouch = st === 'jump_antic' || (st === 'hammer_antic' && b.ph === 'crouch'); + var holding = b.cap && b.cap.ph === 'hold', inhaling = (st === 'inhale' || st === 'gulp') && !holding, open = inhaling || (st === 'inhale_antic' && b.ph === 'antic'); + var blue = flash ? '#cfe0ff' : '#4f7fe0', blueDark = flash ? '#a9c2f2' : '#2f56b0', red = flash ? '#ffd0d4' : '#e23b4e'; + BB.ART.shade(x, X, V.FLOOR + 2, 46, 6, 0.22 * Math.max(0, 1 - b.y / 12)); + x.save(); x.translate(X, Y); x.scale(b.f, 1); + if (dead) { x.translate(0, -6); x.rotate(-0.28); } + if (slide) { x.translate(10, -44); x.rotate(0.8); x.translate(0, 44); } // the belly slide: a forward dive about his middle + var sq = crouch ? 0.86 : b.stun > 0 ? 0.94 : 1; x.scale(1 / Math.sqrt(sq), sq); + // feet + D.ellipse(x, -18, -6 + step * 3, 21, 9, '#f6b93b', P.ink, 2.5); D.ellipse(x, 20, -6 - step * 3, 21, 9, '#f6b93b', P.ink, 2.5); + // coat behind (red, white fur hem), body, belly + x.beginPath(); x.moveTo(-46, -14); x.quadraticCurveTo(-58, -60, -34, -92); x.lineTo(-6, -96); x.lineTo(-12, -14); x.closePath(); + x.fillStyle = red; x.fill(); x.lineWidth = 2.5; x.strokeStyle = P.ink; x.stroke(); + D.ellipse(x, -30, -14, 20, 8, '#fffaf2', P.ink, 2); + D.ellipse(x, 2, -46, 40, 42, blue, P.ink, 3); + D.ellipse(x, 10, -38, 28, 27, flash ? '#fff6ea' : '#f4ead8', P.ink, 2); + // obi: red and gold teeth pattern + x.save(); D.ellipse(x, 2, -46, 39, 41); x.clip(); + x.fillStyle = '#c8303f'; x.fillRect(-40, -38, 82, 14); + x.fillStyle = '#ffcf3d'; x.beginPath(); for (var k = -40; k < 42; k += 10) { x.moveTo(k, -38); x.lineTo(k + 5, -27); x.lineTo(k + 10, -38); } x.fill(); + x.restore(); + x.strokeStyle = P.ink; x.lineWidth = 2; x.beginPath(); x.moveTo(-36, -38); x.lineTo(40, -38); x.moveTo(-37, -24); x.lineTo(40, -24); x.stroke(); + // head: blue, a pale face patch, the yellow mouth (opens wide for the inhale), blue eyes + D.ellipse(x, 8, -86, holding ? 36 : 30, holding ? 30 : 25, blue, P.ink, 3); // cheeks full while Kirby is held + D.ellipse(x, 17, -88, 21, 16, flash ? '#fff6ea' : '#f4ead8'); + var mo = holding ? 0 : open ? (inhaling ? 1 : 0.6) : st === 'jump' ? 0.25 : 0; + D.ellipse(x, 30, -78, 19, 8 + mo * 12, '#ffcf3d', P.ink, 2.2); + if (mo > 0.2) D.ellipse(x, 34, -76 + mo * 2, 11, 3 + mo * 9, '#7a2433'); + else { x.strokeStyle = P.ink; x.lineWidth = 2; x.beginPath(); x.moveTo(14, -78); x.quadraticCurveTo(30, -73, 46, -79); x.stroke(); } + if (dead) { x.strokeStyle = P.ink; x.lineWidth = 3; x.lineCap = 'round'; [12, 26].forEach(function (ex) { x.beginPath(); x.moveTo(ex - 5, -99); x.lineTo(ex + 5, -89); x.moveTo(ex + 5, -99); x.lineTo(ex - 5, -89); x.stroke(); }); } + else { D.eye(x, 12, -94, 7.5, 2); D.eye(x, 26, -94, 7.5, 2); x.strokeStyle = P.ink; x.lineWidth = 2.5; x.beginPath(); x.moveTo(5, -106); x.lineTo(17, -103); x.moveTo(21, -103); x.lineTo(33, -106); x.stroke(); } + // hat: red tuque, white fur band, gold ridge, pom-pom hanging back + x.beginPath(); x.moveTo(-26, -100); x.quadraticCurveTo(-20, -136, 18, -132); x.quadraticCurveTo(44, -128, 38, -104); x.closePath(); + x.fillStyle = red; x.fill(); x.lineWidth = 2.5; x.strokeStyle = P.ink; x.stroke(); + x.fillStyle = '#ffcf3d'; x.beginPath(); x.moveTo(-14, -124); x.lineTo(-6, -138); x.lineTo(2, -126); x.lineTo(10, -140); x.lineTo(18, -127); x.lineTo(26, -136); x.lineTo(30, -120); x.closePath(); x.fill(); x.stroke(); + D.round(x, -30, -108, 72, 13, 6.5); x.fillStyle = '#fffaf2'; x.fill(); x.stroke(); + D.ellipse(x, -30, -128, 10, 10, '#fffaf2', P.ink, 2.2); + // the mallet on his shoulder (hidden while the swing's hit box is live: palette.js draws the head there) + var active = (b.objs || []).some(function (o) { return o.kind === 'hammer' && !o.dead; }); + if (!active) { + x.save(); x.translate(-20, -64); + // swing frames 26..50 (Properties_362f impact, then the recoil pose): the head lies on the floor ahead of him + var slam = st === 'hammer' && b.sw && b.sw.sf >= 24 && b.sw.sf < 50; + mallet(x, slam ? -0.75 : /hammer/.test(st) ? (b.ph === 'windup' ? 2.6 : -2.3) : walking ? -1.3 + step * 0.08 : -1.35, flash); x.restore(); + } + // gloved hand over the coat + D.ellipse(x, -22, -54, 12, 12, '#f6b93b', P.ink, 2.2); + if (b.stun > 0 && !dead) { D.star(x, -26, -150, 8, P.gold, t * 5); D.star(x, 24, -158, 7, P.gold, -t * 5); D.star(x, 0, -166, 6, P.gold, t * 3); } + x.restore(); + if (st === 'hammer_antic' && b.ph === 'windup') ART.glow(x, X - b.f * 20, Y - 120, 60, '255,210,120', 0.35); + D.tell(x, c, V, t, [X, Y - 150]); + } + BB.BOSS_DRAW['kirby/king_dedede'] = { + hazards: function (x, c, t, V) { suction(x, c, t, V); }, + bar: function () { return P.red; }, + body: function (x, c, t, V) { body(x, c, t, V); D.objects(x, c, t, V); edgeMarks(x, c, t, V); } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/draw/kirby.js b/environments/games/web/games/kirby_remake/draw/kirby.js new file mode 100644 index 0000000000000000000000000000000000000000..14225ad4f0e4957e44fd3717c19096d73521096a --- /dev/null +++ b/environments/games/web/games/kirby_remake/draw/kirby.js @@ -0,0 +1,149 @@ +// Kirby and the HUD. Kirby is drawn around his 16 x 16 px body (one GB sprite tile pair); every state the body has +// (walk, jump, puffed float, inhale, mouthful, spit, swallow, duck, caught, hurt, beaten) has its own pose. The +// inhale range drawn while inhaling is the exact source box. The HUD follows the original's bottom bar - KIRBY with +// six health pills, and a boss vitality meter in place of the score - plus tier, script bank, native Hz and timer. +(function (g) { + var BB = g.BB, D = BB.KIRBY_DRAW, P = BB.VIEW.PAL, ART = BB.ART, TAU = Math.PI * 2; + function draw(x, c, t, V) { + var b = c.body, X = V.sx(b.x), base = V.sy(b.y), dead = b.hp <= 0; + var walking = b.grounded && Math.abs(b.vx) > 0.1 && !b.duck, ph = t * 15, step = walking ? Math.sin(ph) : 0; + var rx = 29, ry = 29, cyOff = 0; + if (b.hover) { rx = 37; ry = 34; } + else if (b.mouth) { rx = 35; ry = 30; } + else if (b.duck) { rx = 33; ry = 18; } + else if (b.inhaleT > 0) { rx = 31; ry = 28; } + else if (!b.grounded && b.vy > 1) { rx = 26; ry = 31; } // stretched on the way up + if (b.swallowT > 0) { ry *= 0.9 + 0.1 * Math.cos(b.swallowT * 0.6); } + if (walking) cyOff = Math.abs(step) * 2.5; + var Y = base - ry - cyOff; + // inhale range: Kirby's source box (42 px ahead, +-20 px), and the wind pulled into the mouth + if (b.inhaleT > 0) { + var z = b.inhaleZone(); + x.save(); x.setLineDash([5, 5]); x.strokeStyle = 'rgba(74,127,214,0.55)'; x.lineWidth = 1.6; + x.strokeRect(V.sx(z.x - z.w / 2), V.sy(z.y + z.h / 2), z.w * V.S, z.h * V.S); x.restore(); + x.save(); x.strokeStyle = 'rgba(255,255,255,0.9)'; x.lineWidth = 2.4; x.lineCap = 'round'; + for (var i = 0; i < 6; i++) { + var q = 1 - ((t * 2.6 + i / 6) % 1), ax = V.sx(b.x + b.facing * (0.9 + 4.2 * q)), ay = V.sy(b.y + 1) + Math.sin(i * 2.1) * 26 * q; + x.beginPath(); x.moveTo(ax, ay); x.lineTo(ax + b.facing * 14 * q + b.facing * 4, ay - Math.sin(i * 2.1) * 6); x.stroke(); + } + x.restore(); + } + // King Dedede's inhale: Kirby shows while pulled in, vanishes into his mouth (hold), then spins out to the ropes + var cap = b.captured && c.boss.cap ? c.boss.cap.ph : null, spin = cap === 'fly' ? t * 24 : 0; + if (!b.captured || (cap && cap !== 'hold')) { + x.save(); + if (b.invul > 0 && b.invul < 80 && Math.floor(b.invul / 4) % 2) x.globalAlpha = 0.35; + ART.shade(x, X, V.FLOOR + 3, 26, 5, 0.2 * Math.max(0, 1 - b.y / 10)); + x.translate(X, Y); x.scale(b.facing, 1); + if (dead) x.rotate(-t * 6); + if (spin) x.rotate(spin); + if (cap === 'pull') x.scale(0.82, 1.12); + // feet (tucked in the air, alternating on the ground) + var fy = ry - 4, tuck = !b.grounded && !b.hover ? -3 : 0; + D.ellipse(x, -13 - step * 3, fy + tuck, 14, 8, P.foot, P.ink, 2.2); + // back arm + var flap = b.hover ? Math.sin(t * (b.flapping ? 26 : 10)) * 6 : 0; + D.ellipse(x, -rx + 3, 4 - flap, 9, 11, P.pinkDark, P.ink, 2); + // body + var gr = x.createRadialGradient(-rx * 0.35, -ry * 0.4, rx * 0.12, 0, 0, rx * 1.15); + gr.addColorStop(0, '#ffe3ee'); gr.addColorStop(0.45, P.pink); gr.addColorStop(1, P.pinkDark); + D.ellipse(x, 0, 0, rx, ry, gr, P.ink, 2.6); + D.ellipse(x, 13 + step * 3, fy + tuck + 1, 14, 8, P.foot, P.ink, 2.2); + // front arm (raised when inhaling, flapping when afloat) + D.ellipse(x, rx - 5, b.inhaleT > 0 ? -8 : 6 + flap, 9, 11, P.pink, P.ink, 2); + // face + var ex = b.mouth || b.hover ? 4 : 6; + if (dead || cap === 'fly' || cap === 'bounce') { + x.strokeStyle = P.ink; x.lineWidth = 3; x.lineCap = 'round'; + [ex - 1, ex + 13].forEach(function (a) { x.beginPath(); x.moveTo(a - 4, -12); x.lineTo(a + 4, -4); x.moveTo(a + 4, -12); x.lineTo(a - 4, -4); x.stroke(); }); + } else if (b.inhaleT > 0 || (b.invul > 80)) { // squeezed eyes: straining to inhale, or just hit + x.strokeStyle = P.navy; x.lineWidth = 3; x.lineCap = 'round'; x.lineJoin = 'round'; + [ex - 1, ex + 13].forEach(function (a, k) { x.beginPath(); x.moveTo(a - 4, -13); x.lineTo(a + (k ? -3 : 3), -9); x.lineTo(a - 4, -5); x.stroke(); }); + } else { + D.eye(x, ex, -9, 9.5, 1.5); D.eye(x, ex + 14, -9, 9.5, 1.5); + } + D.ellipse(x, ex - 7, 5, 6, 3.2, 'rgba(255,90,140,0.75)'); D.ellipse(x, ex + 20, 4, 5.5, 3, 'rgba(255,90,140,0.75)'); + if (b.inhaleT > 0) { D.ellipse(x, rx - 9, 5, 12, 13, P.ink); D.ellipse(x, rx - 8, 10, 7, 4, '#d4466e'); } + else if (b.spitT > 0 || b.exhaleT > 15) { D.ellipse(x, rx - 10, 6, 7, 7, P.ink); } + else if (b.mouth) { x.strokeStyle = P.ink; x.lineWidth = 2.2; x.lineCap = 'round'; x.beginPath(); x.moveTo(ex + 1, 10); x.quadraticCurveTo(ex + 7, 14, ex + 12, 10); x.quadraticCurveTo(ex + 16, 7, ex + 19, 11); x.stroke(); } + else if (b.hover) { D.ellipse(x, ex + 8, 9, 5, 3, P.ink); D.ellipse(x, ex + 8, 8, 3, 1.2, '#ffd9e8'); } + else D.ellipse(x, ex + 7, 7, 3.2, dead ? 2 : 4.2, P.ink); + x.restore(); + } + // Star Bullets (the 20 x 20 px source box) with a sparkle trail; air puffs + b.stars.forEach(function (s) { + if (s.dead) return; + var SX = V.sx(s.x), SY = V.sy(s.y); + for (var k = 1; k <= 4; k++) { x.globalAlpha = 0.5 - k * 0.1; D.sparkle(x, SX - s.dir * k * 13, SY + Math.sin(s.age * 0.5 + k) * 4, 7 - k, '#fff3a6'); } + x.globalAlpha = 1; + ART.glow(x, SX, SY, 46, '255,230,120', 0.35); + D.star(x, SX, SY, V.S * 1.15, P.gold, s.age * 0.35 * s.dir); + }); + b.puffs.forEach(function (p) { D.puff(x, V.sx(p.x), V.sy(p.y), 17, '#ffffff', p.age / 60); }); + } + + // ---------------- HUD ---------------- + var AMMO = { apple: 'apple', doo: 'one-eyed minion', bomb: 'bomb', star: 'star' }; + function chip(x, X, Y, text, bg, fg, w) { + x.font = 'bold 11px "Segoe UI","Microsoft YaHei",sans-serif'; + var tw = w || x.measureText(text).width + 14; + D.round(x, X, Y, tw, 17, 8.5); x.fillStyle = bg; x.fill(); x.lineWidth = 1.6; x.strokeStyle = P.ink; x.stroke(); + x.fillStyle = fg; x.textAlign = 'center'; x.fillText(text, X + tw / 2, Y + 12.5); + return tw; + } + function fullHud(x, c, V, extra) { + var b = c.body, w = c.boss, G = BB.GAME || {}, W = V.W; + x.save(); + var gr = x.createLinearGradient(0, 0, 0, 44); gr.addColorStop(0, '#fffaf0'); gr.addColorStop(1, '#f6ead6'); + x.fillStyle = gr; x.fillRect(0, 0, W, 44); + x.fillStyle = P.ink; x.fillRect(0, 43, W, 3); + x.fillStyle = 'rgba(51,40,74,0.08)'; for (var i = 0; i < W; i += 6) x.fillRect(i, 40, 3, 2); + // KIRBY + six health pills + x.textAlign = 'left'; x.font = '900 15px "Arial Black","Segoe UI",sans-serif'; x.fillStyle = P.ink; x.fillText('Orb', 14, 21); + for (i = 0; i < b.max_hp; i++) { + var px = 78 + i * 21; D.round(x, px, 9, 17, 13, 6.5); + x.fillStyle = i < b.hp ? P.pink : '#ece3f1'; x.fill(); x.lineWidth = 2; x.strokeStyle = P.ink; x.stroke(); + if (i < b.hp) { x.fillStyle = 'rgba(255,255,255,0.7)'; x.fillRect(px + 3, 11.5, 9, 3); } + } + x.font = '12px "Microsoft YaHei","Segoe UI",sans-serif'; x.fillStyle = P.ink; + x.fillText(b.mint ? 'Flying → press J to fire puffs' : b.captured ? 'Caught by the Hammer Brute!' : b.mouth ? 'Mouth: ' + (AMMO[b.mouth] || b.mouth) + ' → press J to spit a star' : b.hover ? 'Floating' : b.inhaleT > 0 ? 'Inhaling…' : b.duck ? 'crouch' : 'Mouth: empty', 14, 37); + // boss vitality meter (one segment per HP up to 40, otherwise a ruled bar) + var bx = 262, bw = 300, by = 23, fr = Math.max(0, w.hp / w.max_hp), title = String(c.def.title).toUpperCase(); + x.font = '900 12px "Arial Black","Segoe UI",sans-serif'; x.fillStyle = P.ink; x.textAlign = 'left'; x.fillText(title, bx, 17); + x.textAlign = 'right'; x.font = 'bold 12px "Segoe UI",sans-serif'; x.fillText(w.hp + ' / ' + w.max_hp, bx + bw, 17); + D.round(x, bx - 2, by - 2, bw + 4, 15, 4); x.fillStyle = '#ece3f1'; x.fill(); x.lineWidth = 2; x.strokeStyle = P.ink; x.stroke(); + var bg2 = x.createLinearGradient(0, by, 0, by + 11); bg2.addColorStop(0, '#fff2b0'); bg2.addColorStop(0.45, w.hitFlash > 0 ? '#ffffff' : P.gold); bg2.addColorStop(1, P.goldDark); + x.fillStyle = bg2; x.fillRect(bx, by, bw * fr, 11); + x.fillStyle = 'rgba(51,40,74,0.55)'; + var step = w.max_hp <= 40 ? 1 : 10; + for (i = step; i < w.max_hp; i += step) x.fillRect(bx + bw * i / w.max_hp - 0.75, by, 1.5, 11); + var stt = w.state(), status = stt.super_armour ? 'Armored: still takes damage' : stt.role === 'telegraph' ? 'Attack tell' : stt.role === 'active' ? 'Attacking' : stt.role === 'recovery' ? 'Counterattack window' : 'Ready'; + x.textAlign = 'center'; x.font = 'bold 11px "Microsoft YaHei","Segoe UI",sans-serif'; x.fillStyle = stt.role === 'telegraph' ? '#c2500a' : P.ink; x.fillText(status, bx + bw * 0.55, 17); + // tier, script bank, native Hz, timer + var tier = G.tierOf ? G.tierOf(c.d) : null, tx = 584; + var tierText = tier ? (G.tierNames[tier] + ' ' + tier.toUpperCase()) : 'd ' + c.d.toFixed(2); + tx += chip(x, tx, 6, tierText, tier ? P[tier] : '#8a7fa0', '#ffffff') + 5; + tx += chip(x, tx, 6, w.extra ? 'EXTRA GAME' : 'NORMAL GAME', w.extra ? P.red : '#efe6ff', w.extra ? '#ffffff' : P.ink) + 5; + chip(x, tx, 6, (G.hz || BB.FPS) + 'Hz', P.navy, '#ffffff'); + var sec = Math.floor(c.t / BB.FPS); + x.textAlign = 'right'; x.font = '900 17px "Arial Black","Segoe UI",sans-serif'; x.fillStyle = P.ink; + x.fillText(Math.floor(sec / 60) + ':' + String(sec % 60).padStart(2, '0'), W - 12, 39); + if (extra) { x.font = 'bold 11px "Microsoft YaHei","Segoe UI",sans-serif'; x.textAlign = 'left'; x.fillStyle = P.red; x.fillText(extra, 584, 39); } + x.restore(); + if (c.result && !D.noCanvasBanner) banner(x, c, V); // the play page shows its own DOM result card instead + } + function banner(x, c, V) { // end-of-fight card, drawn from the verifier only + var v = c.verifier(), G = BB.GAME || {}, msg = (G.results || {})[v.outcome] || v.outcome, win = v.outcome === 'win'; + var cx = V.W / 2, cy = 214, tier = G.tierOf ? G.tierOf(c.d) : null; + x.save(); + D.round(x, cx - 250, cy - 56, 500, 112, 22); x.fillStyle = 'rgba(51,40,74,0.78)'; x.fill(); x.lineWidth = 3; x.strokeStyle = '#ffffff'; x.stroke(); + x.fillStyle = win ? P.gold : P.pinkLight; x.strokeStyle = P.ink; x.lineWidth = 7; x.lineJoin = 'round'; + x.font = '900 40px "Arial Rounded MT Bold","Microsoft YaHei",sans-serif'; x.textAlign = 'center'; + x.strokeText(msg, cx, cy + 4); x.fillText(msg, cx, cy + 4); + if (win) { D.star(x, cx - 175, cy - 10, 17, P.gold, 0.2); D.star(x, cx + 175, cy - 10, 17, P.gold, -0.2); } + x.font = 'bold 14px "Segoe UI","Microsoft YaHei",sans-serif'; x.fillStyle = P.cream; + x.fillText(c.def.title + (tier ? ' · ' + G.tierNames[tier] : '') + ' · Boss damage ' + Math.round(v.boss_damage * 100) + '% · ' + v.seconds.toFixed(1) + ' s · Health remaining ' + v.player_hp, cx, cy + 38); + x.restore(); + } + BB.BODY_DRAW.kirby = { draw: draw, fullHud: fullHud, hud: function () {} }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/draw/kracko.js b/environments/games/web/games/kirby_remake/draw/kracko.js new file mode 100644 index 0000000000000000000000000000000000000000..d404a6930a7dca9ffcf0610c5ad1d882ac44bd5a --- /dev/null +++ b/environments/games/web/games/kirby_remake/draw/kracko.js @@ -0,0 +1,56 @@ +// Kracko: a white thundercloud with one big eye that follows Kirby and a ring of short yellow thorns. The cloud body +// is drawn over its 32 x 26 px hit box (the thorns overhang it a little, as on the GB sprite). Before each move it +// darkens to a storm grey and the thorns flare (the bob's last 36 frames, Extra 12, are the tell); while the sparks +// spin it crackles; in the entrance it has no hit box, so it is drawn faded. +(function (g) { + var BB = g.BB, D = BB.KIRBY_DRAW, P = BB.VIEW.PAL, ART = BB.ART, TAU = Math.PI * 2; + function thorn(x, a, r0, len, w) { // one spike from radius r0 outward + var ca = Math.cos(a), sa = Math.sin(a); + x.beginPath(); x.moveTo(ca * r0 - sa * w, sa * r0 * 0.8 + ca * w); x.lineTo(ca * (r0 + len), sa * (r0 + len) * 0.8); x.lineTo(ca * r0 + sa * w, sa * r0 * 0.8 - ca * w); x.closePath(); + x.fillStyle = P.gold; x.fill(); x.lineWidth = 2; x.lineJoin = 'round'; x.strokeStyle = P.ink; x.stroke(); + } + function bolt(x, X0, Y0, X1, Y1, seed, col) { + x.beginPath(); x.moveTo(X0, Y0); + for (var i = 1; i < 6; i++) { var k = i / 6, j = Math.sin(seed * 13.7 + i * 7.3) * 9; x.lineTo(X0 + (X1 - X0) * k + j, Y0 + (Y1 - Y0) * k - j * 0.4); } + x.lineTo(X1, Y1); x.strokeStyle = col; x.stroke(); + } + function draw(x, c, t, V) { + var b = c.boss, st = b.state(), X = V.sx(b.x), Y = V.sy(b.y), flash = b.hitFlash > 0 && !c.result, dead = b.st === 'dead'; + var tell = st.role === 'telegraph', active = st.role === 'active', beam = b.st === 'beam'; + var rx = 32 / 8 * V.S / 2, ry = 26 / 8 * V.S / 2; // Properties_35e9 box, 60 x 49 px half sizes + x.save(); + if (b.st === 'intro') x.globalAlpha = 0.6; + if (dead) x.globalAlpha = Math.max(0.2, 0.75 - b.stT * 0.25); + x.translate(X, Y + Math.sin(t * 3.1) * 1.5); + var spin = t * (beam ? 2.4 : 0.25) + (b.st === 'charge' ? t * 3 : 0), flare = tell ? 1 + 0.25 * Math.sin(t * 30) : 1; + // shadowy under-cloud, then thorns behind the puff, then the puff itself + for (var i = 0; i < 12; i++) thorn(x, i / 12 * TAU + spin, rx * 1.0, (i % 2 ? 20 : 26) * flare, 9); // [cited] 12 yellow spikes + var fill = flash ? '#fffbe9' : tell ? '#c9cde2' : dead ? '#e8ebf6' : '#ffffff'; + D.cloudBlob(x, 0, 1, rx * 0.8, ry * 0.76, 10, fill, tell ? 'rgba(90,96,140,0.7)' : 'rgba(141,160,214,0.65)', 2.5, 0.2); + // eye: white of the eye with an ink ring, the iris looks toward Kirby + var dx = BB.clamp((c.body.x - b.x) * 2.2, -9, 9), dy = BB.clamp((b.y - c.body.y - 1) * 1.4, -6, 8); + D.ellipse(x, 0, 0, rx * 0.42, ry * 0.62, '#ffffff', P.ink, 3); + if (dead) { x.strokeStyle = P.ink; x.lineWidth = 4; x.lineCap = 'round'; x.beginPath(); x.moveTo(-12, -8); x.lineTo(12, 8); x.moveTo(12, -8); x.lineTo(-12, 8); x.stroke(); } + else { + var lid = tell ? 0.35 : 0; // the tell narrows the eye into a glare + D.ellipse(x, dx * 0.8, dy * 0.8, rx * 0.22, ry * 0.38, flash ? '#d44a5a' : P.navy); + D.ellipse(x, dx * 0.8 - 4, dy * 0.8 - 7, 4.5, 6, '#ffffff'); D.ellipse(x, dx * 0.8 + 4, dy * 0.8 + 5, 2, 2.5, 'rgba(255,255,255,0.7)'); + if (lid) { + x.save(); D.ellipse(x, 0, 0, rx * 0.42 - 1.5, ry * 0.62 - 1.5); x.clip(); + x.fillStyle = '#b9bdd6'; x.fillRect(-rx, -ry, 2 * rx, ry * 0.38 + ry * 1.24 * lid); x.strokeStyle = P.ink; x.lineWidth = 3; + x.beginPath(); x.moveTo(-rx, -ry * 0.62 + ry * 1.24 * lid); x.lineTo(rx, -ry * 0.62 + ry * 1.24 * lid - 6); x.stroke(); x.restore(); + } + } + // crackle while it spins the sparks or charges + if (beam || b.st === 'charge' || (tell && Math.floor(t * 12) % 2)) { + x.save(); x.lineWidth = 2.5; x.lineCap = 'round'; x.globalCompositeOperation = 'lighter'; + for (i = 0; i < 3; i++) { var a = spin * 2 + i * 2.1; bolt(x, Math.cos(a) * rx * 0.4, Math.sin(a) * ry * 0.4, Math.cos(a) * rx * 1.25, Math.sin(a) * ry * 1.25, Math.floor(t * 20) + i, 'rgba(255,240,150,0.9)'); } + x.restore(); + } + x.restore(); + if (beam || tell) ART.glow(x, X, Y, rx * 2.2, '255,236,150', beam ? 0.25 : 0.12); + D.objects(x, c, t, V); + D.tell(x, c, V, t); + } + BB.BOSS_DRAW['kirby/kracko'] = { hazards: function () {}, bar: function () { return P.blue; }, body: draw }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/draw/lololo_lalala.js b/environments/games/web/games/kirby_remake/draw/lololo_lalala.js new file mode 100644 index 0000000000000000000000000000000000000000..4c9600c1ab2c88e89beddf412b4b94056a63b0dd --- /dev/null +++ b/environments/games/web/games/kirby_remake/draw/lololo_lalala.js @@ -0,0 +1,63 @@ +// Lololo & Lalala: the two round guards of Castle Lololo. WiKirby (S13) gives the series look: round bodies, big eyes, no +// mouth, white gloves and feet; Lololo blue, Lalala pink with a yellow bow; the box they push is a green chest (the +// Emerald Framer). Colours are the series' (the GB original is monochrome); the shapes are this project's own. Each +// brother is drawn around his 12 x 12 px box (state brothers[i]), only while the script shows him: in the door before +// the push, pushing, and the short dimming before he hides. Original procedural art; nothing traced from the game. +(function (g) { + var BB = g.BB, D = BB.KIRBY_DRAW, P = BB.VIEW.PAL, ART = BB.ART; + var COL = { lololo: ['#5f8fe0', '#3a62b0', '#c9dcff'], lalala: ['#f58bb7', '#cf5f8f', '#ffe1ee'] }; + function brother(x, b, st, V, t, hit) { + var X = V.sx(b.x), Y = V.sy(b.y), r = b.w * V.S / 2 + 3, c = COL[b.name], dir = b.dir || (b.side === 'right' ? -1 : 1); + var push = b.phase === 'push', walk = push ? Math.sin(t * 16) : 0; + x.save(); + if (b.phase === 'dead') { x.globalAlpha = Math.max(0, 0.9 - (st.deadT || 0) * 0.8); } + x.translate(X, Y); x.scale(dir, 1); + if (b.phase === 'dead') x.rotate(t * 8); + D.ellipse(x, -6 - walk * 3, r - 3, 9, 5.5, '#ffffff', P.ink, 2); // feet + D.ellipse(x, 8 + walk * 3, r - 3, 9, 5.5, '#ffffff', P.ink, 2); + var gr = x.createRadialGradient(-r * 0.35, -r * 0.4, 2, 0, 0, r * 1.2); + gr.addColorStop(0, hit ? '#ffffff' : c[2]); gr.addColorStop(0.5, hit ? c[2] : c[0]); gr.addColorStop(1, c[1]); + D.ellipse(x, 0, -2, r, r, gr, P.ink, 2.4); + D.ellipse(x, r - 2, push ? -4 : 2, 7, 7, '#ffffff', P.ink, 2); // gloves, forward one on the box when pushing + D.ellipse(x, -r + 3, 3, 6, 6, '#ffffff', P.ink, 2); + if (b.phase === 'dead') { + x.strokeStyle = P.ink; x.lineWidth = 2.4; + [[2, -6], [11, -6]].forEach(function (e) { x.beginPath(); x.moveTo(e[0] - 3, e[1] - 3); x.lineTo(e[0] + 3, e[1] + 3); x.moveTo(e[0] + 3, e[1] - 3); x.lineTo(e[0] - 3, e[1] + 3); x.stroke(); }); + } else { D.eye(x, 3, -6, 4.2, 0.5); D.eye(x, 12, -6, 4.2, 0.5); } + if (b.name === 'lalala') { // the yellow bow on her head + x.fillStyle = P.gold; x.strokeStyle = P.ink; x.lineWidth = 1.8; + [[-1, 1], [1, 1]].forEach(function (s) { x.beginPath(); x.moveTo(-2, -r - 1); x.lineTo(-2 + s[0] * 12, -r - 9); x.lineTo(-2 + s[0] * 11, -r + 5); x.closePath(); x.fill(); x.stroke(); }); + D.ellipse(x, -2, -r - 1, 4, 4, P.goldDark, P.ink, 1.6); + } + x.restore(); + } + function box(x, o, V, t) { // the green chest, exactly its 12 x 12 px box + var X = V.sx(o.x), Y = V.sy(o.y), rx = o.w * V.S / 2, ry = o.h * V.S / 2; + x.save(); + if (o.sucking) { x.translate(X, Y); x.rotate(Math.sin(t * 30) * 0.15); x.translate(-X, -Y); } + var gr = x.createLinearGradient(X, Y - ry, X, Y + ry); gr.addColorStop(0, '#7fd88a'); gr.addColorStop(1, '#2f9a55'); + D.round(x, X - rx, Y - ry, rx * 2, ry * 2, 6); x.fillStyle = gr; x.fill(); x.lineWidth = 2.6; x.strokeStyle = P.ink; x.stroke(); + x.fillStyle = '#1f6a3c'; x.fillRect(X - rx + 4, Y - 4, rx * 2 - 8, 6); + D.round(x, X - 6, Y - 9, 12, 14, 3); x.fillStyle = P.gold; x.fill(); x.lineWidth = 1.6; x.stroke(); + D.ellipse(x, X, Y - 2, 2, 2.4, P.ink); + x.fillStyle = 'rgba(255,255,255,0.4)'; x.fillRect(X - rx + 5, Y - ry + 4, rx * 2 - 10, 3); + x.restore(); + } + function draw(x, c, t, V) { + var w = c.boss, st = w.state(), flash = !c.result; + (w.objs || []).forEach(function (o) { if (!o.dead && o.kind === 'box') box(x, o, V, t); }); + st.brothers.forEach(function (b, i) { + var q = w.bro[i], shown = b.phase === 'appear' || b.phase === 'push' || (b.phase === 'dead' && q.deadT < 1.2); + if (!shown) return; + b.deadT = q.deadT; + brother(x, b, b, V, t, flash && q.flash > 0); + if (b.phase === 'appear') { // the telegraph tag over the brother standing in his door + var lbl = { x: V.sx(b.x), y: V.sy(b.y + 1.2) }; + x.save(); x.font = 'bold 12px "Microsoft YaHei","Segoe UI",sans-serif'; x.textAlign = 'center'; + D.round(x, lbl.x - 24, lbl.y - 30, 48, 18, 9); x.fillStyle = P.cream; x.fill(); x.lineWidth = 1.6; x.strokeStyle = P.ink; x.stroke(); + x.fillStyle = P.ink; x.fillText('Box Push', lbl.x, lbl.y - 17); x.restore(); + } + }); + } + BB.BOSS_DRAW['kirby/lololo_lalala'] = { hazards: function () {}, bar: function () { return P.blue; }, body: draw }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/draw/palette.js b/environments/games/web/games/kirby_remake/draw/palette.js new file mode 100644 index 0000000000000000000000000000000000000000..ca316677e2f3cb82ce10b4055c54284f30db6581 --- /dev/null +++ b/environments/games/web/games/kirby_remake/draw/palette.js @@ -0,0 +1,223 @@ +// Shared Dream Land colours, drawing primitives and the boss objects (apples, puffs, Gordos, Waddle Doos, bombs, blasts, +// sparks, King Dedede's stars and hammer). Presentation only: everything reads the case and presentation time t, +// never the game RNG, and every hazard is drawn at its own collision box. Original procedural art (no ROM graphics). +(function (g) { + var BB = g.BB, TAU = Math.PI * 2; + var P = BB.VIEW.PAL = { + ink: '#33284a', inkSoft: 'rgba(51,40,74,0.55)', + pink: '#ff9cc4', pinkLight: '#ffd9e8', pinkDark: '#ee6f9f', blush: '#ff6b9a', foot: '#df2f5a', footDark: '#a81d43', + cream: '#fff7e6', paper: '#fffaf0', gold: '#ffd23f', goldDark: '#e09b17', tele: '#ffb02e', + red: '#e8404f', redDark: '#a92436', blue: '#4a7fd6', blueDark: '#2c4f9e', navy: '#2a2a62', + leaf: '#2f8a4e', leafDark: '#1f6a3c', leafLight: '#5cb86a', bark: '#e6c79c', barkShade: '#c39a69', barkLine: '#9a6d44', + cloud: '#ffffff', cloudShade: '#d6def5', cloudRim: '#9dafdc', storm: '#8f95b8', + green: '#62bb6d', easy: '#4fb06a', normal: '#4a86d8', hard: '#e0475b' + }; + var D = BB.KIRBY_DRAW = {}; + D.TAU = TAU; + D.ellipse = function (x, X, Y, rx, ry, fill, line, lw) { + x.beginPath(); x.ellipse(X, Y, Math.max(0.1, rx), Math.max(0.1, ry), 0, 0, TAU); + if (fill) { x.fillStyle = fill; x.fill(); } + if (line) { x.lineWidth = lw || 2; x.strokeStyle = line; x.stroke(); } + }; + D.round = function (x, X, Y, w, h, r) { // rounded-rect path + r = Math.min(r, w / 2, h / 2); x.beginPath(); + x.moveTo(X + r, Y); x.lineTo(X + w - r, Y); x.quadraticCurveTo(X + w, Y, X + w, Y + r); x.lineTo(X + w, Y + h - r); + x.quadraticCurveTo(X + w, Y + h, X + w - r, Y + h); x.lineTo(X + r, Y + h); x.quadraticCurveTo(X, Y + h, X, Y + h - r); + x.lineTo(X, Y + r); x.quadraticCurveTo(X, Y, X + r, Y); x.closePath(); + }; + D.starPath = function (x, X, Y, r, rot, inner) { + x.beginPath(); + for (var i = 0; i < 10; i++) { + var a = -Math.PI / 2 + (rot || 0) + i * Math.PI / 5, d = r * (i % 2 ? (inner || 0.47) : 1); + if (i) x.lineTo(X + Math.cos(a) * d, Y + Math.sin(a) * d); else x.moveTo(X + Math.cos(a) * d, Y + Math.sin(a) * d); + } + x.closePath(); + }; + D.star = function (x, X, Y, r, fill, rot, lw) { // the Dream Land star: gold, ink edge, a soft highlight + D.starPath(x, X, Y, r, rot); + x.fillStyle = fill || P.gold; x.fill(); + x.lineJoin = 'round'; x.lineWidth = lw == null ? Math.max(1.2, r * 0.13) : lw; x.strokeStyle = P.ink; x.stroke(); + if (r > 6) { D.starPath(x, X - r * 0.12, Y - r * 0.14, r * 0.42, rot); x.fillStyle = 'rgba(255,255,255,0.55)'; x.fill(); } + }; + D.sparkle = function (x, X, Y, s, col) { // four-point twinkle + x.beginPath(); x.moveTo(X - s, Y); x.quadraticCurveTo(X, Y, X, Y - s); x.quadraticCurveTo(X, Y, X + s, Y); + x.quadraticCurveTo(X, Y, X, Y + s); x.quadraticCurveTo(X, Y, X - s, Y); x.fillStyle = col || '#fff'; x.fill(); + }; + D.eye = function (x, X, Y, r, look, shine) { // tall Dream Land eye: navy oval, white glint above, blue below + D.ellipse(x, X, Y, r * 0.62, r, P.navy); + D.ellipse(x, X + (look || 0) * 0.5, Y + r * 0.42, r * 0.36, r * 0.32, '#4a6fd8'); + D.ellipse(x, X + (look || 0) * 0.5, Y - r * 0.42, r * 0.3, r * 0.4, '#ffffff'); + if (shine !== false) D.ellipse(x, X + (look || 0) * 0.5 + r * 0.16, Y + r * 0.12, r * 0.1, r * 0.12, 'rgba(255,255,255,0.8)'); + }; + // puffy cloud blob: a ring of overlapping lobes around (X, Y), radius r, n lobes, filled + inked + D.cloudBlob = function (x, X, Y, rx, ry, n, fill, shade, lw, ph) { + var i, a, pts = []; + for (i = 0; i < n; i++) { a = i / n * TAU + (ph || 0); pts.push([X + Math.cos(a) * rx, Y + Math.sin(a) * ry]); } + var lr = Math.max(rx, ry) * 2.6 / n + Math.min(rx, ry) * 0.18; + x.beginPath(); + for (i = 0; i < n; i++) { x.moveTo(pts[i][0] + lr, pts[i][1]); x.arc(pts[i][0], pts[i][1], lr, 0, TAU); } + x.ellipse(X, Y, rx, ry, 0, 0, TAU); + x.save(); x.lineWidth = (lw || 2.5) * 2; x.strokeStyle = P.ink; x.stroke(); x.restore(); + x.fillStyle = fill; x.fill(); + if (shade) { + x.save(); x.clip(); + var gr = x.createLinearGradient(0, Y - ry, 0, Y + ry + lr); + gr.addColorStop(0, 'rgba(255,255,255,0)'); gr.addColorStop(0.55, 'rgba(255,255,255,0)'); gr.addColorStop(1, shade); + x.fillStyle = gr; x.fillRect(X - rx - lr, Y - ry - lr, 2 * (rx + lr), 2 * (ry + lr)); x.restore(); + } + }; + D.puff = function (x, X, Y, r, colour, t) { // air puff (Whispy's breath, Kirby's air bullet) + var w = Math.sin((t || 0) * 18) * 0.06; + D.cloudBlob(x, X, Y, r * (0.7 + w), r * (0.62 - w), 5, colour || '#ffffff', 'rgba(157,175,220,0.55)', 1.4, (t || 0) * 3); + x.save(); x.strokeStyle = 'rgba(255,255,255,0.9)'; x.lineWidth = 2; x.lineCap = 'round'; + x.beginPath(); x.arc(X - r * 0.15, Y - r * 0.12, r * 0.32, Math.PI * 1.05, Math.PI * 1.6); x.stroke(); x.restore(); + }; + function apple(x, X, Y, r, t, wob) { + x.save(); x.translate(X, Y); x.rotate(wob || 0); + x.beginPath(); x.moveTo(0, -r * 0.62); + x.bezierCurveTo(r * 0.55, -r * 1.05, r * 1.12, -r * 0.45, r * 0.95, r * 0.25); + x.bezierCurveTo(r * 0.8, r * 0.95, r * 0.28, r * 1.05, 0, r * 0.82); + x.bezierCurveTo(-r * 0.28, r * 1.05, -r * 0.8, r * 0.95, -r * 0.95, r * 0.25); + x.bezierCurveTo(-r * 1.12, -r * 0.45, -r * 0.55, -r * 1.05, 0, -r * 0.62); x.closePath(); + var gr = x.createRadialGradient(-r * 0.35, -r * 0.3, r * 0.1, 0, 0, r * 1.1); + gr.addColorStop(0, '#ff8a86'); gr.addColorStop(0.55, P.red); gr.addColorStop(1, '#b8283a'); + x.fillStyle = gr; x.fill(); x.lineWidth = 2.2; x.strokeStyle = P.ink; x.stroke(); + D.ellipse(x, -r * 0.42, -r * 0.18, r * 0.16, r * 0.3, 'rgba(255,240,235,0.85)'); + x.strokeStyle = '#6b4526'; x.lineWidth = 3; x.lineCap = 'round'; + x.beginPath(); x.moveTo(0, -r * 0.55); x.quadraticCurveTo(r * 0.08, -r * 0.9, r * 0.22, -r * 1.1); x.stroke(); + x.beginPath(); x.moveTo(r * 0.16, -r * 0.95); x.quadraticCurveTo(r * 0.7, -r * 1.35, r * 0.95, -r * 0.92); + x.quadraticCurveTo(r * 0.55, -r * 0.7, r * 0.16, -r * 0.95); x.fillStyle = P.leafLight; x.fill(); x.lineWidth = 1.5; x.strokeStyle = P.ink; x.stroke(); + x.restore(); + } + function gordo(x, X, Y, r, t) { // spiked ball: cannot be inhaled, hurts more than an apple + x.save(); x.translate(X, Y); + x.beginPath(); + for (var i = 0; i < 16; i++) { + var a = i / 16 * TAU + t * 0.6, d = i % 2 ? r * 0.72 : r * 1.12; + if (i) x.lineTo(Math.cos(a) * d, Math.sin(a) * d); else x.moveTo(Math.cos(a) * d, Math.sin(a) * d); + } + x.closePath(); x.fillStyle = '#f2ecff'; x.fill(); x.lineWidth = 2; x.strokeStyle = P.ink; x.lineJoin = 'round'; x.stroke(); + var gr = x.createRadialGradient(-r * 0.25, -r * 0.3, 1, 0, 0, r * 0.8); + gr.addColorStop(0, '#5d5a7a'); gr.addColorStop(1, '#1f1b30'); + D.ellipse(x, 0, 0, r * 0.74, r * 0.74, gr, P.ink, 2); + D.ellipse(x, -r * 0.26, -r * 0.05, r * 0.17, r * 0.27, '#ffffff'); D.ellipse(x, r * 0.26, -r * 0.05, r * 0.17, r * 0.27, '#ffffff'); + D.ellipse(x, -r * 0.22, r * 0.02, r * 0.08, r * 0.14, P.ink); D.ellipse(x, r * 0.3, r * 0.02, r * 0.08, r * 0.14, P.ink); + x.restore(); + } + function doo(x, X, Y, rx, ry, o, c, t) { // Waddle Doo: one big eye, orange body, little feet + var walk = o.ph === 'walk', step = walk ? Math.sin(o.fr * 0.35) * 3 : 0, look = c.body.x > o.x ? 1 : -1, dir = o.dir || look; + x.save(); x.translate(X, Y); + D.ellipse(x, -rx * 0.55, ry * 0.85 + step * 0.4, rx * 0.5, ry * 0.26, '#f2a24a', P.ink, 2); + D.ellipse(x, rx * 0.55, ry * 0.85 - step * 0.4, rx * 0.5, ry * 0.26, '#f2a24a', P.ink, 2); + var gr = x.createRadialGradient(-rx * 0.3, -ry * 0.35, 2, 0, 0, rx * 1.15); + gr.addColorStop(0, '#ffc98a'); gr.addColorStop(0.6, '#f28c3a'); gr.addColorStop(1, '#c9622a'); + D.ellipse(x, 0, step * 0.15, rx, ry * 0.95, gr, P.ink, 2.4); + var flash = o.ph === 'flash' && Math.floor(o.pt / 6) % 2; + D.ellipse(x, dir * rx * 0.12, -ry * 0.12, rx * 0.55, ry * 0.55, flash ? '#ffe36a' : '#ffffff', P.ink, 2); + D.ellipse(x, dir * rx * 0.12 + look * rx * 0.16, -ry * 0.1, rx * 0.22, ry * 0.3, P.navy); + D.ellipse(x, dir * rx * 0.12 + look * rx * 0.1, -ry * 0.24, rx * 0.08, ry * 0.1, '#ffffff'); + x.restore(); + } + function bomb(x, X, Y, r, o, t) { + x.save(); x.translate(X, Y); + var gr = x.createRadialGradient(-r * 0.35, -r * 0.35, 2, 0, 0, r); + gr.addColorStop(0, '#6f76a8'); gr.addColorStop(1, '#22233f'); + D.ellipse(x, 0, 0, r, r, gr, P.ink, 2.2); + x.fillStyle = '#8a8fb5'; x.fillRect(-r * 0.3, -r - 5, r * 0.6, 7); x.strokeStyle = P.ink; x.lineWidth = 1.5; x.strokeRect(-r * 0.3, -r - 5, r * 0.6, 7); + x.strokeStyle = '#7a5a33'; x.lineWidth = 2.5; x.beginPath(); x.moveTo(0, -r - 5); x.quadraticCurveTo(r * 0.5, -r - 16, r * 0.7, -r - 10); x.stroke(); + var fl = 0.7 + 0.3 * Math.sin(t * 40); + D.sparkle(x, r * 0.72, -r - 11, 8 * fl, '#fff3a6'); D.sparkle(x, r * 0.72, -r - 11, 4.5 * fl, P.tele); + D.ellipse(x, -r * 0.38, -r * 0.38, r * 0.2, r * 0.13, 'rgba(255,255,255,0.55)'); + x.restore(); + } + function spark(x, X, Y, r, t, i) { // electric spark: hot core + flickering zig-zag rays + var ph = t * 30 + i * 1.7; + x.save(); x.translate(X, Y); + BB.ART.glow(x, 0, 0, r * 2.4, '255,236,140', 0.55); + x.strokeStyle = '#fff7c2'; x.lineWidth = 2; x.lineCap = 'round'; x.lineJoin = 'round'; + for (var k = 0; k < 4; k++) { + var a = k * Math.PI / 2 + ph * 0.3, L = r * (1.5 + 0.4 * Math.sin(ph + k)); + x.beginPath(); x.moveTo(0, 0); + x.lineTo(Math.cos(a + 0.35) * L * 0.5, Math.sin(a + 0.35) * L * 0.5); x.lineTo(Math.cos(a) * L, Math.sin(a) * L); x.stroke(); + } + D.starPath(x, 0, 0, r * 1.05, ph * 0.2, 0.42); x.fillStyle = P.gold; x.fill(); x.lineWidth = 1.2; x.strokeStyle = P.goldDark; x.stroke(); + D.ellipse(x, 0, 0, r * 0.38, r * 0.38, '#ffffff'); + x.restore(); + } + function blast(x, X, Y, rx, ry, o, t) { + // ExplosionProperties 40 x 40 px: the whole square hurts for its 32 frames, so the burst fills exactly that box + var k = Math.max(0, 1 - (o.fr || 0) / 32); + x.save(); + var gr = x.createRadialGradient(X, Y, 2, X, Y, Math.max(rx, ry) * 1.3); + gr.addColorStop(0, 'rgba(255,252,230,' + (0.95 * k + 0.05) + ')'); gr.addColorStop(0.5, 'rgba(255,170,80,' + (0.85 * k + 0.1) + ')'); + gr.addColorStop(1, 'rgba(232,64,79,' + (0.6 * k + 0.1) + ')'); + D.round(x, X - rx, Y - ry, rx * 2, ry * 2, 14); x.fillStyle = gr; x.fill(); + x.lineWidth = 2.5; x.strokeStyle = 'rgba(51,40,74,' + (0.3 + 0.55 * k) + ')'; x.setLineDash([10, 6]); x.stroke(); x.setLineDash([]); + for (var i = 0; i < 6; i++) { var a = i * TAU / 6 + t * 3; D.star(x, X + Math.cos(a) * rx * 0.55, Y + Math.sin(a) * ry * 0.55, 6 + 6 * k, P.gold, a); } + x.restore(); + } + function hammerHead(x, c, X, Y, rx, ry, V) { // the active hammer box: the head sits exactly on it + var w = c.boss, hx = V.sx(w.x - w.f * 0.63), hy = V.sy(w.y + 1.55); // the glove (king_dedede.js) + x.save(); x.lineCap = 'round'; + x.strokeStyle = P.ink; x.lineWidth = 11; x.beginPath(); x.moveTo(hx, hy); x.lineTo(X, Y); x.stroke(); + x.strokeStyle = '#d9a066'; x.lineWidth = 6.5; x.stroke(); + var gr = x.createLinearGradient(X, Y - ry, X, Y + ry); + gr.addColorStop(0, '#f0bf7e'); gr.addColorStop(0.5, '#d48f4c'); gr.addColorStop(1, '#a8682f'); + D.round(x, X - rx, Y - ry, rx * 2, ry * 2, 8); x.fillStyle = gr; x.fill(); x.lineWidth = 2.5; x.strokeStyle = P.ink; x.stroke(); + x.fillStyle = '#8a5326'; x.fillRect(X - rx + 9, Y - ry + 2, 7, ry * 2 - 4); x.fillRect(X + rx - 16, Y - ry + 2, 7, ry * 2 - 4); + x.fillStyle = 'rgba(255,255,255,0.35)'; x.fillRect(X - rx + 4, Y - ry + 5, rx * 2 - 8, 4); + x.restore(); + } + function impact(x, X, Y, rx, ry, o, t) { // Properties_362f 52 x 16 px shock: dust and a ground crack, same box + var k = Math.max(0, Math.min(1, (o.life || 0) * 10)); + x.save(); x.globalAlpha = 0.45 + 0.5 * k; + x.fillStyle = 'rgba(255,214,120,0.55)'; x.beginPath(); + x.moveTo(X - rx, Y + ry); x.lineTo(X - rx, Y + ry * 0.2); + for (var i = 1; i <= 8; i++) x.lineTo(X - rx + i * rx / 4, Y - ry * (i % 2 ? 1 : 0.15)); + x.lineTo(X + rx, Y + ry); x.closePath(); x.fill(); x.strokeStyle = P.tele; x.lineWidth = 2; x.stroke(); + for (i = 0; i < 5; i++) D.ellipse(x, X - rx + (i + 0.5) * rx * 0.4, Y + ry * 0.55, 12, 7, 'rgba(255,248,230,0.75)'); + x.restore(); + } + // Every object is drawn at its collision box: x, y = centre, w, h in u. + D.objects = function (x, c, t, V) { + (c.boss.objs || []).forEach(function (o, i) { + if (o.dead) return; + var X = V.sx(o.x), Y = V.sy(o.y), rx = o.w * V.S / 2, ry = o.h * V.S / 2, r = Math.max(rx, ry); + if (o.kind === 'apple' || o.kind === 'gordo') { + var hang = o.ph === 'hang', wob = hang ? Math.sin(t * 22) * 0.14 : o.ph === 'roll' ? (o.x * 1.4) % TAU : 0; + if (hang && Math.floor(o.age * 8) % 2) { x.save(); BB.ART.glow(x, X, Y, r * 1.8, o.kind === 'gordo' ? '200,190,255' : '255,240,160', 0.7); x.restore(); } + if (o.kind === 'apple') apple(x, X, Y, r * 0.95, t, wob); else gordo(x, X, Y, r * 0.95, t); + } else if (o.kind === 'star') { + D.star(x, X, Y, r * 1.15, P.gold, t * 4 + i); + } else if (o.kind === 'puff') { + x.save(); x.strokeStyle = 'rgba(255,255,255,0.7)'; x.lineWidth = 2; x.lineCap = 'round'; + for (var q = 0; q < 3; q++) { var ly = Y - ry * 0.5 + q * ry * 0.5; x.beginPath(); x.moveTo(X + rx * 1.1, ly); x.lineTo(X + rx * (1.6 + q * 0.25), ly); x.stroke(); } + x.restore(); + D.puff(x, X, Y, r, '#ffffff', t + i); + } else if (o.kind === 'doo') doo(x, X, Y, rx, ry, o, c, t); + else if (o.kind === 'bomb') bomb(x, X, Y, r * 0.95, o, t); + else if (o.kind === 'blast') blast(x, X, Y, rx, ry, o, t); + else if (o.kind === 'spark') spark(x, X, Y, r, t, i); + else if (o.kind === 'hammer') hammerHead(x, c, X, Y, rx, ry, V); + else if (o.kind === 'hammer_impact') impact(x, X, Y, rx, ry, o, t); + }); + }; + // telegraph tag above the boss: what is coming, as long as the boss is in a telegraph state + var NAMES = { move: 'Dive', beam: 'Rotating lightning', doo: 'Summon one-eyed minion', bombs: 'Falling bombs', charge: 'Charge', jump: 'High leap', inhale: 'Inhale', + hammer: 'Hammer swing', walk: 'Slide', puffs: 'Air Puff', puff_burst: 'Puff burst', throw: 'Bomb Throw', leap: 'Leap', dash: 'Dash' }; + D.tell = function (x, c, V, t, at) { + var st = c.boss.state(); + if (st.role !== 'telegraph') return; + var X = at ? at[0] : V.sx(st.x), Y = at ? at[1] : V.sy(st.y + st.h / 2) - 14; + var label = NAMES[st.move] || 'Watch out'; + x.save(); x.font = 'bold 13px "Microsoft YaHei","Segoe UI",sans-serif'; x.textAlign = 'center'; + var w = x.measureText(label).width + 30, bob = Math.sin((t || 0) * 10) * 2; + Y = Math.max(64, Y) + bob; + D.round(x, X - w / 2, Y - 34, w, 22, 11); x.fillStyle = P.cream; x.fill(); x.lineWidth = 2; x.strokeStyle = P.ink; x.stroke(); + x.beginPath(); x.moveTo(X - 6, Y - 13); x.lineTo(X, Y - 5); x.lineTo(X + 6, Y - 13); x.closePath(); x.fillStyle = P.cream; x.fill(); x.stroke(); + x.fillRect(X - 5, Y - 15, 10, 4); + D.star(x, X - w / 2 + 13, Y - 23, 7, P.tele, (t || 0) * 3, 1.2); + x.fillStyle = P.ink; x.fillText(label, X + 7, Y - 18.5); + x.restore(); + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/draw/poppy_bros_sr.js b/environments/games/web/games/kirby_remake/draw/poppy_bros_sr.js new file mode 100644 index 0000000000000000000000000000000000000000..d83bf00cb03dc295138bf6ae5c68b8dc756e12ae --- /dev/null +++ b/environments/games/web/games/kirby_remake/draw/poppy_bros_sr.js @@ -0,0 +1,81 @@ +// Poppy Bros. Sr.: the jester of Green Greens. WiKirby (S13) gives the series look: a pale-blue clown suit, a floppy cap +// like Sword Kirby's, a flat white collar and long hooked shoes; the gold pompom, buttons and colours of the cap and +// shoes are this project's own touches (the GB original is monochrome). The figure fills the GB +// sprite's extent, his feet to 27 px up (OAM_2c088); his 16 x 22 px hit box covers 9..31 px above the feet, so the +// shoes are outside it (a ducking Kirby passes under him, as in the game). In the throw wind-up he holds the bomb up +// behind his head (OAM_2c160) until the frame it leaves his hands; then the bomb object takes over at its own box. +// Original procedural art; nothing is traced from the game. +(function (g) { + var BB = g.BB, D = BB.KIRBY_DRAW, P = BB.VIEW.PAL, ART = BB.ART; + var BLUE = '#3f6fd1', BLUE_D = '#264a9a', FACE = '#ffe8cf', SHOE = '#d9435a'; + function shoe(x, X, Y) { // curled-toe shoe, toe to the left (his facing in local space) + x.beginPath(); x.moveTo(X + 10, Y); x.quadraticCurveTo(X + 11, Y - 12, X, Y - 11); + x.quadraticCurveTo(X - 13, Y - 10, X - 16, Y - 18); x.quadraticCurveTo(X - 22, Y - 6, X - 9, Y); x.closePath(); + x.fillStyle = SHOE; x.fill(); x.lineWidth = 2; x.strokeStyle = P.ink; x.stroke(); + D.ellipse(x, X - 16, Y - 19, 3.2, 3.2, P.gold, P.ink, 1.5); + } + function heldBomb(x, X, Y, t) { + var bg = x.createRadialGradient(X - 6, Y - 6, 2, X, Y, 20); bg.addColorStop(0, '#6f76a8'); bg.addColorStop(1, '#22233f'); + D.ellipse(x, X, Y, 19, 19, bg, P.ink, 2.2); + x.fillStyle = '#8a8fb5'; x.fillRect(X - 5, Y - 25, 10, 7); + var fl = 0.7 + 0.3 * Math.sin(t * 40); D.sparkle(x, X + 10, Y - 29, 8 * fl, '#fff3a6'); D.sparkle(x, X + 10, Y - 29, 4.5 * fl, P.tele); + D.ellipse(x, X - 7, Y - 7, 4, 2.6, 'rgba(255,255,255,0.55)'); + } + function draw(x, c, t, V) { + var b = c.boss, st = b.state(), dead = b.st === 'dead', flash = b.hitFlash > 0 && !c.result; + var X = V.sx(b.x), feet = V.sy(b.y), tell = st.role === 'telegraph', holding = b.st === 'throw_antic' && !dead; + var air = b.y > 0.05, sq = !air && b.st === 'hop' ? 1 + 0.05 * Math.sin(t * 22) : 1; + x.save(); + if (dead) x.globalAlpha = Math.max(0.15, 0.85 - b.stT * 0.3); + ART.shade(x, X, V.FLOOR + 3, 26, 5, 0.22 * Math.max(0, 1 - b.y / 8)); + x.translate(X, feet); + if (dead) x.rotate(Math.sin(t * 9) * 0.35); + x.scale(b.f < 0 ? 1 : -1, 1); // drawn facing left, his throw side + x.scale(1 / sq, sq); + // legs and shoes + var run = b.st === 'dash' ? Math.sin(t * 40) * 5 : 0; + x.lineCap = 'round'; x.strokeStyle = P.ink; x.lineWidth = 6.5; + x.beginPath(); x.moveTo(-7, -22); x.lineTo(-9 - run, -8); x.moveTo(7, -22); x.lineTo(8 + run, -8); x.stroke(); + x.strokeStyle = '#f4ecff'; x.lineWidth = 3.5; x.stroke(); + shoe(x, -9 - run, 0); shoe(x, 10 + run, 0); + // tunic with two gold buttons + var gr = x.createLinearGradient(-20, -58, 20, -20); gr.addColorStop(0, flash ? '#e6f0ff' : '#a9c8f5'); gr.addColorStop(1, flash ? '#b9d0f5' : '#6e96d8'); + x.beginPath(); x.moveTo(-17, -20); x.quadraticCurveTo(-24, -40, -13, -56); x.lineTo(13, -56); x.quadraticCurveTo(24, -40, 17, -20); x.closePath(); + x.fillStyle = gr; x.fill(); x.lineWidth = 2.5; x.strokeStyle = P.ink; x.stroke(); + [-42, -31].forEach(function (yy) { D.ellipse(x, -2, yy, 3.2, 3.2, P.gold, P.ink, 1.3); }); + // arms: raised back to the bomb in the wind-up, else at his sides + var hands = holding ? [[14, -104], [40, -100]] : [[-20, -36], [20, -36]]; + x.strokeStyle = P.ink; x.lineWidth = 7; x.beginPath(); x.moveTo(-12, -50); x.lineTo(hands[0][0], hands[0][1]); x.moveTo(12, -50); x.lineTo(hands[1][0], hands[1][1]); x.stroke(); + x.strokeStyle = BLUE; x.lineWidth = 4.2; x.stroke(); + // ruff collar + for (var i = -3; i <= 3; i++) D.ellipse(x, i * 6.5, -56 + Math.abs(i) * 0.7, 6.5, 5, '#ffffff', P.ink, 1.6); + // head: big and round, as on the sprite + D.ellipse(x, 0, -76, 20, 19, flash ? '#fff7ee' : FACE, P.ink, 2.6); + if (dead) { + x.strokeStyle = P.ink; x.lineWidth = 2.8; + [[-9, -78], [5, -78]].forEach(function (e) { x.beginPath(); x.moveTo(e[0] - 4, e[1] - 4); x.lineTo(e[0] + 4, e[1] + 4); x.moveTo(e[0] + 4, e[1] - 4); x.lineTo(e[0] - 4, e[1] + 4); x.stroke(); }); + } else { + D.ellipse(x, -9, -78, 3.4, tell ? 2.2 : 5, P.navy); D.ellipse(x, 5, -78, 3.4, tell ? 2.2 : 5, P.navy); + D.ellipse(x, -10, -80, 1.2, 1.6, '#ffffff'); D.ellipse(x, 4, -80, 1.2, 1.6, '#ffffff'); + x.strokeStyle = P.ink; x.lineWidth = 2.2; x.beginPath(); + if (tell) { x.moveTo(-9, -66); x.lineTo(1, -67); } else x.arc(-3, -69, 5, 0.15 * Math.PI, 0.85 * Math.PI); + x.stroke(); + } + D.ellipse(x, -15, -70, 4, 2.5, 'rgba(255,110,140,0.55)'); + // cap: a white band, the crown flopping back to a gold pompom + var flop = Math.sin(t * 5) * 2 + (air ? 4 : 0); + x.beginPath(); x.moveTo(-21, -86); x.quadraticCurveTo(-16, -108, 3, -106); x.quadraticCurveTo(24, -104, 31 + flop, -90 - flop * 0.4); + x.quadraticCurveTo(17, -95, 18, -86); x.closePath(); + x.fillStyle = flash ? '#cfe0ff' : BLUE; x.fill(); x.lineWidth = 2.5; x.strokeStyle = P.ink; x.stroke(); + D.round(x, -22, -90, 42, 7, 3.5); x.fillStyle = '#ffffff'; x.fill(); x.lineWidth = 1.8; x.stroke(); + D.ellipse(x, 32 + flop, -90 - flop * 0.4, 6, 6, P.gold, P.ink, 1.8); + if (holding) { + heldBomb(x, 28, -122, t); + D.ellipse(x, hands[0][0], hands[0][1], 6, 6, '#ffffff', P.ink, 2); D.ellipse(x, hands[1][0], hands[1][1], 6, 6, '#ffffff', P.ink, 2); + } else { D.ellipse(x, hands[0][0], hands[0][1], 6, 6, '#ffffff', P.ink, 2); D.ellipse(x, hands[1][0], hands[1][1], 6, 6, '#ffffff', P.ink, 2); } + x.restore(); + D.objects(x, c, t, V); + D.tell(x, c, V, t, [X, feet - 150]); + } + BB.BOSS_DRAW['kirby/poppy_bros_sr'] = { hazards: function () {}, bar: function () { return P.blue; }, body: draw }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/draw/whispy_woods.js b/environments/games/web/games/kirby_remake/draw/whispy_woods.js new file mode 100644 index 0000000000000000000000000000000000000000..691ce660805c532f3d92681a12299e4d64718c4c --- /dev/null +++ b/environments/games/web/games/kirby_remake/draw/whispy_woods.js @@ -0,0 +1,129 @@ +// Whispy Woods: a tall pale trunk with two hollow eyes, a stick nose pointing at Kirby and an O mouth, under a big +// leafy crown. The trunk is drawn exactly over its 26 x 64 px hit box; above that box there are only leaves (Kirby +// can float through them unhurt, so the art does not pretend otherwise). The face follows the game's own animation +// scripts frame by frame: BlinkTwice (20 open / 3 half / 6 shut / 3 half / 4 / 20 / 3 / 8 / 3 / 10), the blink in each +// 90-frame apple drop (30 / 4 / 6 / 4 / 6 / 40) and the puff mouth (1 half-open, open, then 1 half, 1 closing). +(function (g) { + var BB = g.BB, D = BB.KIRBY_DRAW, P = BB.VIEW.PAL, ART = BB.ART; + var BLINK = [[20, 0], [3, 1], [6, 2], [3, 1], [4, 0], [20, 0], [3, 1], [8, 2], [3, 1], [10, 0]]; // [frames, 0 open / 1 half / 2 shut] + var DROP = [[30, 0], [4, 1], [6, 2], [4, 1], [6, 0], [40, 0]]; + function seq(list, k) { // k in [0,1) through a script -> its frame value + var n = 0, i; for (i = 0; i < list.length; i++) n += list[i][0]; + var f = k * n; + for (i = 0; i < list.length; i++) { if (f < list[i][0]) return list[i][1]; f -= list[i][0]; } + return list[list.length - 1][1]; + } + function face(b) { // eyes 0/1/2, mouth 0 shut / 1 half / 2 open + var st = b.st, k = b.stT / Math.max(1e-6, b.stT + Math.max(0, b.timer)), eyes = 0, mouth = 0; + if (st === 'blink') eyes = seq(BLINK, k); + else if (st === 'apples' || st === 'drop') eyes = seq(DROP, k); + if (st === 'puffs_antic' || st === 'puff_burst_antic') mouth = b.stT < 1 / 60 ? 1 : 2; + else if (st === 'puffs' || st === 'puff_burst') mouth = k < 0.85 ? 2 : 1; + return { eyes: eyes, mouth: mouth }; + } + // the crown: clustered leaf masses [dx, dy, r] around (X0, Y0), darker underneath + var CROWN = [[-90, -40, 52], [-20, -55, 60], [55, -45, 58], [120, -25, 48], [-135, 15, 44], [-60, 10, 58], [20, 5, 62], [95, 15, 56], + [150, 30, 40], [-100, 55, 40], [-30, 60, 46], [45, 60, 46], [115, 58, 38]]; + var FRONT = [[-34, 0, 34], [22, -6, 38], [62, 6, 26]]; + // The crown only changes with the hit flash, so each lobe set is painted once per look into a cached canvas and + // drawn with a gentle sway (presentation time) - one drawImage per frame instead of 16 gradients. + var cache = {}; + function leaves(x, X0, Y0, lobes, t, flash, sway) { + var key = (lobes === CROWN ? 'c' : 'f') + (flash ? 1 : 0), pad = 8, im = cache[key]; + if (!im) { + var x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9; + lobes.forEach(function (l) { x0 = Math.min(x0, l[0] - l[2]); x1 = Math.max(x1, l[0] + l[2]); y0 = Math.min(y0, l[1] - l[2]); y1 = Math.max(y1, l[1] + l[2]); }); + var cv = (x.canvas.ownerDocument || document).createElement('canvas'); + cv.width = Math.ceil(x1 - x0 + 2 * pad); cv.height = Math.ceil(y1 - y0 + 2 * pad); + var cx = cv.getContext('2d'); cx.translate(pad - x0, pad - y0); paint(cx, lobes, flash); + im = cache[key] = { cv: cv, ox: x0 - pad, oy: y0 - pad }; + } + x.save(); x.translate(X0 + im.ox, Y0 + im.oy); + x.transform(1, 0, sway * 0.004, 1, -sway * 0.004 * im.cv.height * 0.5, 0); // sway: a slight shear about the middle + x.drawImage(im.cv, 0, 0); x.restore(); + } + function paint(x, lobes, flash) { + var sway = 0; x.save(); + lobes.forEach(function (l, i) { // ink rim first, so the masses read as one crown + D.ellipse(x, l[0] + sway * (i % 3 - 1), l[1], l[2] + 3, l[2] * 0.82 + 3, P.ink); + }); + lobes.forEach(function (l, i) { + var gr = x.createRadialGradient(l[0] - l[2] * 0.3, l[1] - l[2] * 0.4, 4, l[0], l[1], l[2] * 1.1); + gr.addColorStop(0, flash ? '#c9f2c4' : '#6fc777'); gr.addColorStop(0.6, flash ? '#9fe0a0' : P.leaf); gr.addColorStop(1, flash ? '#7ccf86' : P.leafDark); + D.ellipse(x, l[0] + sway * (i % 3 - 1), l[1], l[2], l[2] * 0.82, gr); + }); + x.strokeStyle = 'rgba(25,80,45,0.45)'; x.lineWidth = 2; x.lineCap = 'round'; + var n = lobes.length * 2; + for (var i = 0; i < n; i++) { // leaf strokes and light dots inside the lobes + var l = lobes[i % lobes.length], a = i * 2.39, lx = l[0] + Math.cos(a) * l[2] * 0.5, ly = l[1] + Math.sin(a) * l[2] * 0.4; + x.beginPath(); x.arc(lx, ly, 9, Math.PI * 0.15, Math.PI * 0.85); x.stroke(); + if (i % 3 === 0) D.ellipse(x, lx + 6, ly - 8, 3, 3, 'rgba(235,250,220,0.85)'); + } + x.restore(); + } + function trunk(x, X, top, base, w, flash, dead) { + var L = X - w / 2, R = X + w / 2; + x.save(); + x.beginPath(); + x.moveTo(L - 14, base); x.quadraticCurveTo(L - 2, base - 6, L + 1, base - 40); + x.lineTo(L + 5, top); x.lineTo(R - 5, top); x.lineTo(R - 1, base - 40); x.quadraticCurveTo(R + 2, base - 6, R + 16, base); + x.closePath(); + var gr = x.createLinearGradient(L, 0, R, 0); + gr.addColorStop(0, flash ? '#fff6e2' : '#f4e2bd'); gr.addColorStop(0.5, flash ? '#fff1d6' : P.bark); gr.addColorStop(1, flash ? '#f0dcb8' : P.barkShade); + x.fillStyle = gr; x.fill(); x.lineWidth = 3; x.lineJoin = 'round'; x.strokeStyle = P.ink; x.stroke(); + x.clip(); + x.strokeStyle = 'rgba(154,109,68,0.55)'; x.lineWidth = 2.5; x.lineCap = 'round'; + [-0.36, -0.12, 0.14, 0.34].forEach(function (k, i) { + var gx = X + k * w; x.beginPath(); x.moveTo(gx, top + 10 + i * 13); x.quadraticCurveTo(gx + (i % 2 ? 4 : -4), (top + base) / 2, gx + (i % 2 ? -2 : 3), base - 18 - i * 9); x.stroke(); + }); + D.ellipse(x, X + w * 0.28, top + 70, 7, 4, 'rgba(154,109,68,0.6)'); D.ellipse(x, X - w * 0.3, base - 60, 6, 3.5, 'rgba(154,109,68,0.6)'); + x.restore(); + } + function eye(x, X, Y, state, flash, dead) { + var hole = '#2b1c13'; + if (flash || dead) { // squeezed shut: > < (hit) or a gentle closed curve (beaten) + x.save(); x.strokeStyle = hole; x.lineWidth = 4; x.lineCap = 'round'; + x.beginPath(); if (dead) { x.arc(X, Y - 2, 9, Math.PI * 0.15, Math.PI * 0.85); } else { x.moveTo(X - 8, Y - 9); x.lineTo(X + 5, Y); x.lineTo(X - 8, Y + 9); } + x.stroke(); x.restore(); return; + } + if (state === 2) { x.save(); x.strokeStyle = hole; x.lineWidth = 4; x.lineCap = 'round'; x.beginPath(); x.moveTo(X - 9, Y + 2); x.quadraticCurveTo(X, Y + 7, X + 9, Y + 2); x.stroke(); x.restore(); return; } + var h = state === 1 ? 11 : 21; + D.ellipse(x, X, Y + (21 - h) * 0.6, 9, h, hole); + D.ellipse(x, X - 2, Y + (21 - h) * 0.6 - h * 0.45, 2.5, Math.min(5, h * 0.25), 'rgba(255,240,215,0.55)'); + if (state === 1) { x.fillStyle = P.barkShade; x.fillRect(X - 11, Y - 22, 22, 15); x.strokeStyle = P.barkLine; x.lineWidth = 2; x.beginPath(); x.moveTo(X - 10, Y - 7); x.lineTo(X + 10, Y - 7); x.stroke(); } + } + function draw(x, c, t, V) { + var b = c.boss, X = V.sx(b.x), base = V.sy(0), top = V.sy(b.y + b.bodyBox().h / 2), w = b.bodyBox().w * V.S; + var flash = b.hitFlash > 0 && !c.result, dead = b.st === 'dead', fc = face(b), sway = Math.sin(t * 1.6) * 3; + leaves(x, X + 12, top - 146 + 46, CROWN, t, flash, sway); + trunk(x, X, top - 30, base, w, flash, dead); + leaves(x, X + 4, top - 30, FRONT, t, flash, sway * 0.6); // the front of the crown hides where the trunk goes in + // face: eyes high, the stick nose pointing at the player, the O mouth below (on the trunk's player side) + var fx = X - w * 0.12, eyeY = V.sy(6.25), noseY = V.sy(5.35), mouthY = V.sy(3.6); + eye(x, fx - 15, eyeY, fc.eyes, flash, dead); eye(x, fx + 15, eyeY, fc.eyes, flash, dead); + x.save(); x.lineCap = 'round'; + x.strokeStyle = P.ink; x.lineWidth = 15; x.beginPath(); x.moveTo(fx + 6, noseY); x.lineTo(fx - 58, noseY + 2); x.stroke(); + x.strokeStyle = '#efd9b2'; x.lineWidth = 9.5; x.stroke(); + x.strokeStyle = P.ink; x.lineWidth = 2; x.beginPath(); x.moveTo(fx - 34, noseY - 3); x.lineTo(fx - 42, noseY - 16); x.stroke(); + D.ellipse(x, fx - 44, noseY - 18, 6, 3.5, P.leafLight, P.ink, 1.5); + x.restore(); + var mr = fc.mouth === 2 ? [17, 24] : fc.mouth === 1 ? [11, 15] : [7, 9]; + if (dead) mr = [9, 5]; + D.ellipse(x, fx - 2, mouthY, mr[0], mr[1], '#2b1c13'); + if (fc.mouth === 2) { // breath: the puff is created low by the roots (spawn offset [data]) + D.ellipse(x, fx - 2, mouthY + mr[1] * 0.45, mr[0] * 0.55, mr[1] * 0.3, '#9c3a4a'); + x.save(); x.strokeStyle = 'rgba(255,255,255,0.85)'; x.lineWidth = 3; x.lineCap = 'round'; + var py = V.sy(1), q = (t * 5) % 1; + for (var s = 0; s < 3; s++) { var k2 = (q + s / 3) % 1; x.beginPath(); x.moveTo(fx - 14 - k2 * 30, mouthY + 6 + k2 * (py - mouthY - 6)); x.quadraticCurveTo(fx - 30 - k2 * 30, mouthY + 20 + k2 * (py - mouthY), fx - 40 - k2 * 34, py - 4 + s * 4); x.stroke(); } + x.restore(); + } + if (dead) { // beaten: tears run down the bark + var k = (t * 1.4) % 1; + [fx - 15, fx + 15].forEach(function (ex, i) { D.ellipse(x, ex + 2, eyeY + 14 + ((k + i * 0.5) % 1) * 70, 4.5, 7, 'rgba(110,190,240,0.9)', P.ink, 1.2); }); + } + D.objects(x, c, t, V); // apples, Gordos and puffs, in front of the tree + D.tell(x, c, V, t, [fx - 10, eyeY - 34]); + } + D.whispyFace = face; + BB.BOSS_DRAW['kirby/whispy_woods'] = { hazards: function () {}, bar: function () { return P.green; }, body: draw }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/game.js b/environments/games/web/games/kirby_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..a221f2f7c149343b26892e698dac15a7e6f07911 --- /dev/null +++ b/environments/games/web/games/kirby_remake/game.js @@ -0,0 +1,40 @@ +// Manifest of this game for the engine shell (engine/app.js): select-screen roster and default case. +(function (g) { + var BB = g.BB; + BB.GAME = { + id: 'kirby_remake', + rules: 'kdl-bosses-2026-11-05-r8', + // The three public difficulty tiers ( = the three columns of every specs/*.spec.js + // difficulty table, so each tier is listed in the boss configurations rather than interpolated. A tier scales boss HP, + // cadence (telegraphs, waits, speed, move order) and damage. Which of the original's scripts runs - the Normal + // game or the Extra Game - is the separate reset option mode: 'normal' (default) | 'extra'; any tier x any mode. + tiers: { easy: 0, normal: 0.5, hard: 1 }, + tierNames: { easy: 'Easy', normal: 'Normal', hard: 'Hard' }, + hz: 60, // native tick shown on the HUD (the reference game runs at about 59.73 Hz) + title: 'Kirby Remake', + defaultCase: 'kirby/whispy_woods', + results: {win:'Victory by Star!', loss:'Try again next time', timeout:'Time is up'}, + skillText: { + 'kirby/whispy_woods': {puffs:'Air puff: the tree opens its mouth and blows a low puff. Jump over it; puffs cannot be inhaled.', puff_burst:'Puff burst: four puffs arrive in sequence. Float above them to dodge.', apples:'Falling apples: flashing apples drop from the crown. Hold J toward one to inhale it, then spit it back at the trunk. Avoid staying high in the crown where apples spawn.', drop:'Extra falling objects: apples alternate with spiked balls. Spiked balls cannot be inhaled and deal triple apple damage.'}, + 'kirby/kracko': {move:'Dive: the thundercloud sweeps across the arena in an arc. Watch its direction and jump or float clear.', beam:'Rotating lightning: bolts circle the thundercloud. Keep your distance and wait for an opening.', doo:'Summon one-eyed minion: inhale the minion on the ground, jump, and spit a star at the thundercloud.', bombs:'Extra falling bombs: bombs explode after landing. Inhale one before it detonates and spit a star back.', charge:'Extra charge: the thundercloud rushes across the arena. Jump in time to dodge.'}, + 'kirby/king_dedede': {walk:'Slide: the hammer brute closes in and slides along the ground. Jump over him and keep your distance.', jump:'High jump: landing releases two stars. Avoid the brute, inhale a star, and counterattack.', inhale:'Inhale: the brute stops, opens his mouth, and pulls in the orb ahead of him. Jump above or retreat beyond his range.', hammer:'Hammer swing: the brute raises his hammer and strikes the ground, creating inhalable stars. If the orb is above him, he jumps and swings without dropping stars. Avoid the hammer; he can take damage during the swing but cannot be interrupted.'}, + 'kirby/poppy_bros_sr': {hop:'Hops in place: two sets of short hops mark a gap between attacks. Keep some distance and wait for a bomb.', throw:'Bomb throw: he leaps with a bomb, then either throws it from the air or pauses, lands, and rolls it along the ground. It explodes at the end of its route in a 5×5 area. Inhale it before the blast and spit a star back.', leap:'Leap: he makes a medium hop toward you, then a long leap across the arena and returns. Avoid the landing point or crouch beneath him.', dash:'Extra dash: he steps back, sprints across the ground, then runs back. Jump or float over him.'}, + 'kirby/lololo_lalala': {push:'Box push: the siblings take turns entering a corridor, pause, push a box across it, and move through the opposite door to another empty corridor. Reach that corridor first, inhale the box, turn around, and spit a star at the sibling behind it. You can jump onto narrow bridges from below; press S on a bridge to drop to the next level, even while carrying something.'}, + 'kirby/kaboola': {shoot:'Shooting: the airship flies in a figure eight and fires from a gun above or below its body. When aligned with its centerline, straight shots pass above and below; only two angled spread shots can reach you.', ram:'Ram: the airship retreats to charge, then rushes across the screen at your upper, middle, or lower lane. Move off its path and keep attacking on its return.'} + }, + roster: [ + { id: 'kirby/whispy_woods', name: 'Ancient Apple Tree', arch: 'A tree in a grassy arena. Inhale apples, dodge puffs, and spit stars at the trunk.' }, + { id: 'kirby/kracko', name: 'One-Eyed Thundercloud', arch: 'A thundercloud above the arena. Inhale a one-eyed minion and jump to the right height to counterattack.' }, + { id: 'kirby/king_dedede', name: 'Arena Hammer Brute', arch: 'A hammer-wielding arena foe. Dodge slides and hammer blows, then inhale and return stars.' }, + { id: 'kirby/poppy_bros_sr', name: 'Bomb-Throwing Jester', arch: 'A jester miniboss in a grassy arena. Inhale his bombs and spit them back before they explode.' }, + { id: 'kirby/lololo_lalala', name: 'Box-Pushing Twins', arch: 'Four corridors in a castle. The siblings push boxes across them; inhale a box and spit it at its pusher.' }, + { id: 'kirby/kaboola', name: 'Armed Airship', arch: 'An airship duel in the sky. The orb flies throughout; hold J to fire puffs while dodging shells and rams.' } + ] + }; + // Tier name of a difficulty value (exact tier points only; anything else is a custom continuous d). + BB.GAME.tierOf = function (d) { + var t = BB.GAME.tiers; + for (var k in t) if (Math.abs(t[k] - d) < 1e-9) return k; + return null; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/index.html b/environments/games/web/games/kirby_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..5e7145ca1f3e674e64f8738356e6422d1ccc24f6 --- /dev/null +++ b/environments/games/web/games/kirby_remake/index.html @@ -0,0 +1,174 @@ + + + + + +Kirby · Dream Land Boss Challenge | BossBench + + + + +
      +

      BOSSBENCH / DREAM LAND

      Kirby · Boss Challenge

      Inhale what the boss throws at you, then spit it back as a star. That is your only attack.

      ← Game List
      + +
      + + + +
      + +
      +

      Choose Your Opponent

      +
      Difficulty0.50
      +
      Original Game Mode
      +

      Difficulty changes boss health, attack timing, and damage. Easy uses a fixed attack order, longer warnings, and half damage. Normal uses the original timing and move set. Hard is faster, stronger, and tougher. Choose Main Game or Extra Game separately; mode and difficulty do not affect each other. Kirby always has the original six health points, and arena fights use the original fixed camera.

      +
      +
      +
      +
      +

      Kirby’s Abilities

      +
        +
      • A/D Move, Space Jump (hold for a higher jump)
      • +
      • Press Space again in midair or press W to float; hold to rise. Press J to exhale and stop floating
      • +
      • Hold J or the left mouse button to inhale forward. You can inhale apples, one-eyed enemies, bombs, and stars; dodge air puffs and spiked balls
      • +
      • After inhaling an object, wait briefly, release J, then press it again to spit a star. Press S on the ground to swallow. You can jump with a full mouth, but cannot float
      • +
      • Hold S on the ground with an empty mouth to crouch and reduce your hitbox
      • +
      • During the airship fight, fly with A/D/W/S. Each press of J fires an air pellet to the right.
      • +
      +
      +
      +

      Move List

      +
        +
        +
        +
        Import a Replay · All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
        +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/environments/games/web/games/kirby_remake/replay.html b/environments/games/web/games/kirby_remake/replay.html new file mode 100644 index 0000000000000000000000000000000000000000..6d96641219349716404e05296d77a593371ff04e --- /dev/null +++ b/environments/games/web/games/kirby_remake/replay.html @@ -0,0 +1,23 @@ + + +Kirby · Match Replay + +
        +← Back to Challenge

        Match Replay

        Import a replay downloaded from the results screen. Pause, step forward, or drag the timeline.

        +
        +
        +
        +
        +
        Match Data
        +

        All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.

        +
        + + + + + + + + diff --git a/environments/games/web/games/kirby_remake/replay.js b/environments/games/web/games/kirby_remake/replay.js new file mode 100644 index 0000000000000000000000000000000000000000..4dc79f02b29be52b6c7de52f3b3b22024cdb89e0 --- /dev/null +++ b/environments/games/web/games/kirby_remake/replay.js @@ -0,0 +1,35 @@ +(function(){ + var $=function(id){return document.getElementById(id);},R=new BB.Renderer($('view')); + var run,c,packets=[],frame=0,playing=false,acc=0,last=performance.now(); + function reset(){c=new BB.Case(run.case);c.reset(run.seed,run.d,run.options||{});frame=0;acc=0;R.juice.reset();} + function validate(v){ + if(v&&v.rules&&v.rules!==BB.GAME.rules)throw new Error('This replay belongs to a different rule version; use the matching game version.'); + if(!v||typeof v.case!=='string'||!Object.prototype.hasOwnProperty.call(BB.CASES,v.case)||!Number.isInteger(v.seed)||v.seed<0||v.seed>4294967295||!Number.isFinite(v.d)||v.d<0||v.d>1||!Array.isArray(v.packets)||!v.packets.length||v.packets.length>1500)throw new Error('The replay lacks a valid boss, seed, difficulty, or action packet.'); + var parsed=v.packets.map(BB.parsePacket);if(parsed.some(function(p){return !p;}))throw new Error('The replay contains a malformed action packet.');return parsed; + } + function load(v){ + try{var parsed=validate(v);run=v;packets=parsed;playing=false;reset();$('progress').max=packets.length;$('error').textContent=''; + ['play','step','restart','progress'].forEach(function(id){$(id).disabled=false;});update();} + catch(e){$('error').textContent=e.message;} + } + function tick(){ + if(c.result||frame>=packets.length*12){playing=false;return;} + var p=packets[Math.floor(frame/12)],sub=Math.floor((frame%12)/2);c.tick(p.subs[sub],p.mouse.map(function(v){return v/12;}));frame++; + } + function update(){ + $('play').textContent=playing?'Pause':'Play';$('progress').value=Math.floor(frame/12); + var ended=c.result||frame>=packets.length*12,v=c.verifier(),title=BB.CASES[run.case].title; + var expected=run.verifier,match=ended&&expected&&JSON.stringify(v)===JSON.stringify(expected)&&(!run.final_hash||BB.hashState(c)===run.final_hash); + $('status').textContent=title+' · '+v.seconds.toFixed(1)+' / '+(expected?expected.seconds.toFixed(1):(packets.length*.2).toFixed(1))+' seconds'+(ended?' · '+(v.outcome==='win'?'Victory':v.outcome==='loss'?'Defeat':v.outcome==='timeout'?'Timeout':'Replay ended')+(expected?(match?' · Replay matches':' · Replay differs from this version'):''):''); + $('info').textContent=JSON.stringify({case:run.case,seed:run.seed,d:run.d,packets:packets.length,verifier:v,hash:BB.hashState(c)},null,2); + R.draw(c,c.t/60,'Replay'); + } + $('play').onclick=function(){if(c.result||frame>=packets.length*12)reset();playing=!playing;acc=0;update();}; + $('step').onclick=function(){playing=false;var until=Math.min(packets.length*12,(Math.floor(frame/12)+1)*12);while(frame2*1024*1024){$('error').textContent='Replay file exceeds 2 MB.';return;}try{load(JSON.parse(await f.text()));}catch(e){$('error').textContent='Cannot read the JSON replay.';}this.value='';}; + window.addEventListener('blur',function(){if(c){playing=false;acc=0;update();}}); + function loop(now){var dt=Math.min(.1,(now-last)/1000);last=now;if(playing){acc+=dt*+$('speed').value;while(acc>=BB.DT&&playing){tick();acc-=BB.DT;}update();}requestAnimationFrame(loop);} + requestAnimationFrame(loop); +})(); diff --git a/environments/games/web/games/kirby_remake/scripted.js b/environments/games/web/games/kirby_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..977d0f87a83392f83edfc7547d29ccc31430ddef --- /dev/null +++ b/environments/games/web/games/kirby_remake/scripted.js @@ -0,0 +1,289 @@ +// Standard scripted controller ( §3): BB.GAME.scripted(c) is called once per +// 200 ms action packet with the live BB.Case and returns that packet's six 33 ms key sets. +// Trusted and privileged: it reads the simulation (Kirby, the boss and its objects), never the pixels, and it never +// writes the live case. It plans on deep copies that get their own RNG stream, so a random boss decision taken +// inside the planning window is only seen once it actually shows (no knowledge of the live RNG). +// Packet-level planner: each reactive macro is rolled out for H ticks +// on SAMPLES forked futures with keys that change only at sub-step boundaries, exactly as a packet allows; the worst +// future scores the macro and the best macro's first six sub-steps become the packet. Deterministic: no +// Math.random, no clock; memory (hysteresis only) lives in a WeakMap keyed by the case and resets at tick 0. +(function (g) { + var BB = g.BB, SUB = BB.SUBSTEPS, TPS = BB.TICKS_PER_SUB; + var CFG = { H: 60, SAMPLES: 2, STICK: 0.6, HOVER: 0.5, READY: 3, // horizon (ticks), futures per macro, keep-macro bonus, + CANOPY: 8, OFFSIDE: 6, HARVEST: 5.5, DOOR: 2.6, DOORW: 10, LANE: 4, EXIT: 0.4, PUFF: 6, TRAP: 12, REACH: 1.1, MARGIN: 0.4, MARGIN2: 0.6, RANGE: 7, KALIGN: 3, KSIDE: 4, KEDGE: 0.5 }; // end-state penalty for being puffed up, bonus for being able + // to inhale now; Whispy's canopy line (u, see caution()); + // penalty for being diagonally above Dedede as he chooses; + // where to wait for his next star (u ahead of him) + + function clone(o) { + if (o === null || typeof o !== 'object') return o; + if (o === BB.Kirby.prototype.K) return o; // immutable body constants + if (o instanceof BB.KIRBY.Track) { var tr = new BB.KIRBY.Track(o.segs, o.loop); tr.i = o.i; tr.t = o.t; return tr; } + if (Array.isArray(o)) { var a = new Array(o.length); for (var i = 0; i < o.length; i++) a[i] = clone(o[i]); return a; } + var n = Object.create(Object.getPrototypeOf(o)), ks = Object.keys(o); + for (var j = 0; j < ks.length; j++) n[ks[j]] = clone(o[ks[j]]); + return n; + } + // A private future of c: copied body and boss, empty event log, and an RNG stream that is not the live one. + function fork(c, salt) { + var n = Object.create(BB.Case.prototype); + n.id = c.id; n.def = c.def; n.seed = c.seed; n.d = c.d; n.t = c.t; n.trauma = 0; n.result = c.result; n.events = []; + n.arena = c.arena; n.options = c.options; + n.body = clone(c.body); n.boss = clone(c.boss); + n.rng = new BB.RNG((Math.imul(c.seed ^ 0x5bd1e995, 0x9e3779b1) ^ Math.imul(c.t + 1, 40503) ^ Math.imul(salt + 7, 0x27d4eb2d)) >>> 0); + return n; + } + function target(c) { // the boss box; with several parts (hitTargets) the nearest one + if (!c.boss.hitTargets) return c.boss.bodyBox ? c.boss.bodyBox() : null; + var b = c.body, best = null, bd = 1e9; + c.boss.hitTargets().forEach(function (t) { var d = Math.abs(t.box.x - b.x) + 2 * Math.abs(t.box.y - b.y - 1); if (t.box && d < bd) { bd = d; best = t.box; } }); + return best; + } + function ammo(c) { // nearest live inhalable object + var b = c.body, list = c.boss.inhalables ? c.boss.inhalables() : [], best = null, bd = 1e9; + for (var i = 0; i < list.length; i++) { + var o = list[i], d = Math.abs(o.x - b.x) + 0.6 * Math.abs(o.y - b.y - 1); + if (d < bd) { bd = d; best = o; } + } + return best; + } + + // ---- macros: (sub-step index j, future cc) -> keys held for that whole sub-step ---- + function hold(keys) { return function () { return keys; }; } + function jumpM(dir, n) { // hold Space n sub-steps (release first if it is still held) + return function (j, cc) { + var k = {}; if (dir) k[dir] = 1; + if (j < n && !(j === 0 && cc.body.grounded && cc.body.prev.jump)) k.Space = 1; + return k; + }; + } + function floatM(dir) { // puff up (fresh W press) and keep flapping + return function (j, cc) { var k = { W: (j % 2 === 0 || cc.body.hover) ? 1 : 0 }; if (dir) k[dir] = 1; return k; }; + } + function exhaleM(j, cc) { return cc.body.hover && !cc.body.prev.attack ? { J: 1 } : {}; } + // King Dedede's stars live 36 frames: wait where the next one will pop out and open the mouth just in time. The + // ground swing creates its star at swing frame 26, 20 px ahead of him (it then flies forward), and the impact box + // reaches 34 px ahead, so stand HARVEST u in front of his swing; a jump drops one star on each side as he lands. + function harvestM(j, cc) { + var b = cc.body, w = cc.boss, k = {}; + if (w.id !== 'king_dedede' || b.mouth || b.hover || b.captured) return k; + if (b.inhaleT > 0) return { J: 1 }; + var swing = w.st === 'hammer' && w.sw && !w.sw.jump, ground = swing || (w.st === 'hammer_antic' && (w.side === 0 || w.side === 4)); + var side = ground ? w.hf : (b.x >= w.x ? 1 : -1), A = BB.KIRBY_RING; + var tx = BB.clamp(w.x + side * CFG.HARVEST, A.LEFT + 1.2, A.RIGHT - 1.2), dx = tx - b.x, face = w.x > b.x ? 1 : -1; + var soon = (swing && !w.sw.hit && w.sw.sf >= 16) || (w.st === 'jump' && w.ph === 'fall' && w.y < 3.5); + if (!soon && Math.abs(dx) > 0.5) { k[dx > 0 ? 'D' : 'A'] = 1; return k; } + if (b.facing !== face) { k[face > 0 ? 'D' : 'A'] = 1; return k; } + if (soon && b.grounded && !b.prev.attack) k.J = 1; + return k; + } + function ammoM(j, cc) { // walk to the nearest ammunition, face it, hold J + var b = cc.body, o = ammo(cc), k = {}; + if (b.mouth || !o) return k; + var dx = o.x - b.x, to = dx > 0 ? 'D' : 'A', ad = Math.abs(dx), dy = o.y - b.y - 1, face = dx > 0 ? 1 : -1; + if (b.hover) return { J: b.prev.attack ? 0 : 1 }; + if (b.inhaleT > 0) { if (b.facing === face || ad < 0.6) k.J = 1; return k; } + if (ad > 4.2 || b.facing !== face) { k[to] = 1; if (ad > 1.2 || b.facing !== face) return k; } + if (dy > 2.4 && b.grounded && !b.prev.jump) k.Space = 1; + if (!b.prev.attack) k.J = 1; + return k; + } + function shootM(j, cc) { // line the star up with the boss, face it, spit + var b = cc.body, T = target(cc), k = {}; + if (!b.mouth || !T) return k; + var dx = T.x - b.x, to = dx > 0 ? 'D' : 'A', away = dx > 0 ? 'A' : 'D', dy = T.y - (b.y + 1), reach = T.h / 2 - 0.15, face = dx > 0 ? 1 : -1; + if (Math.abs(dx) < T.w / 2 + 1.2) k[away] = 1; + else if (b.facing !== face) k[to] = 1; + if (dy > reach && b.grounded && !b.prev.jump) k.Space = 1; + else if (dy > reach && !b.grounded && b.vy > 0) k.Space = 1; + if (Math.abs(dy) <= reach && b.facing === face && !b.prev.attack) k.J = 1; + return k; + } + // Lololo & Lalala: the corridor (0 = floor .. 3 = top) of a height, and the corridor the fight wants Kirby in - the + // one a box is coming along when the mouth is empty, the one a hittable brother is in when it is full. Only what is + // already on screen is read (boxes, a brother in his door); the next door is a future roll and is not. + function lane(y) { return Math.max(0, Math.min(3, Math.round(y / 4))); } + function wantLane(cc) { + var b = cc.body, w = cc.boss, best = null, bd = 1e9; + // full: a brother still out when Kirby gets to his corridor (~1 s a corridor; his push timer is decided state) + if (b.mouth) w.bro.forEach(function (q) { + if (!q.coll) return; + var dl = Math.abs(lane(q.y - 1) - lane(b.y)), left = q.ph === 'push' ? q.timer : q.ph === 'appear' ? q.timer + 3 : 0; + if (left < CFG.REACH * dl + 0.4) return; + var d = dl * 6 + Math.abs(q.x - b.x) * 0.1; if (d < bd) { bd = d; best = lane(q.y - 1); } + }); + else w.inhalables().forEach(function (o) { + var ahead = (b.x - o.x) * o.dir, d = Math.abs(lane(o.y - 1) - lane(b.y)) * 6 + (ahead > 0 ? ahead * 0.1 : 8); + if (d < bd) { bd = d; best = lane(o.y - 1); } + }); + return best; + } + // the bridges out of corridor n: [x0, x1, up?] (a corridor is only 16 px high, so a brother walking down it cannot be + // jumped over - the way out is a bridge) + function exits(n) { + var L = BB.KIRBY_CASTLE.ledges, out = []; + if (n > 0) L[n - 1].bridges.forEach(function (s) { out.push([s[0], s[1], false]); }); + if (n < 3) L[n].bridges.forEach(function (s) { out.push([s[0], s[1], true]); }); + return out; + } + // A pushing brother cannot be jumped over in a 16 px corridor and does not stop when hit: ahead of him Kirby has to be + // out through a bridge before he gets there. Returns how many seconds short the best way out is (0 = fine). Reads only + // the brother's decided state (row, direction, place, what is left of his wait in the door). + function trapped(cc) { + // a hit that costs two bars (the hard tier) is worth a wider margin [the damage is the boss's decided table] + var margin = CFG.MARGIN + (cc.boss.hd(1) > 1 ? CFG.MARGIN2 : 0); + var b = cc.body, kn = lane(b.y), worst = 0, vb = 0.75 * BB.KIRBY.V * cc.boss.spd(), vk = 9; // his push 0.75 px/f in u/s; Kirby walks ~9 u/s + if (!b.grounded && !b.hover) return 0; + cc.boss.bro.forEach(function (q) { + if ((q.ph !== 'push' && q.ph !== 'appear') || lane(q.y - 1) !== kn) return; + var ahead = (b.x - q.x) * q.dir; if (ahead < -1.2) return; // he is walking away from Kirby + var wait = q.ph === 'appear' ? Math.max(0, q.timer) : 0, best = -1e9; + exits(kn).forEach(function (e) { + var pt = q.dir > 0 ? Math.max(e[0] + 0.6, Math.min(b.x, e[1] - 0.6)) : Math.min(e[1] - 0.6, Math.max(b.x, e[0] + 0.6)); + var tb = wait + ((pt - q.x) * q.dir - 1.3) / vb; // when his box edge reaches that point + var tk = Math.abs(pt - b.x) / vk + 0.35; // walk there, then jump / drop + if ((pt - q.x) * q.dir > 0) best = Math.max(best, tb - tk); + }); + worst = Math.max(worst, Math.min(3, Math.max(0, margin - best))); + }); + return worst; + } + function exitGap(b) { var g = 1e9; exits(lane(b.y)).forEach(function (e) { g = Math.min(g, Math.max(0, e[0] + 0.6 - b.x, b.x - e[1] + 0.6)); }); return g; } + function crossM(up) { // through the nearest bridge up or down, whatever the target + return function (j, cc) { + var b = cc.body, k = {}; if (cc.boss.id !== 'lololo_lalala' || b.inhaleT > 0 || (!b.grounded && !b.hover)) return k; + var kn = lane(b.y); if (up ? kn >= 3 : kn <= 0) return k; + return go(b, up, BB.KIRBY_CASTLE.ledges[up ? kn : kn - 1]); + }; + } + function go(b, up, L) { + var k = {}, bx = null, bd = 1e9; + L.bridges.forEach(function (s) { var m = (s[0] + s[1]) / 2, d = Math.abs(m - b.x); if (d < bd) { bd = d; bx = m; } }); + if (Math.abs(bx - b.x) > 1.1) { k[bx > b.x ? 'D' : 'A'] = 1; return k; } + if (up) { if ((b.grounded && !b.prev.jump) || (!b.grounded && b.jumpT >= 0)) k.Space = 1; } // hold Space through the rise + else k.S = 1; + return k; + } + // walk to the nearest bridge of the ledge to cross, then jump up through it or press S on it to drop + function navM(j, cc) { + var b = cc.body, k = {}, kt; if (cc.boss.id !== 'lololo_lalala' || b.inhaleT > 0) return k; + kt = wantLane(cc); var kn = lane(b.y); + if (kt === null || kt === kn || (!b.grounded && !b.hover)) return k; + return go(b, kt > kn, BB.KIRBY_CASTLE.ledges[kt > kn ? kn : kn - 1]); + } + // the box comes with its pusher 16 px behind it: inhale it and spit straight back down the corridor (one macro, so a + // rollout sees the catch and the shot together); while the mouth gets ready, back off at walking speed (he pushes at 0.75) + function returnM(j, cc) { + var b = cc.body; if (cc.boss.id !== 'lololo_lalala') return {}; + if (!b.mouth) return ammoM(j, cc); + var T = target(cc); if (!T) return {}; + var face = T.x > b.x ? 1 : -1, k = shootM(j, cc); + if (b.mouthT > 0 && Math.abs(T.y - b.y - 1) < 1 && Math.abs(T.x - b.x) < 3.2) { k = {}; k[face > 0 ? 'A' : 'D'] = 1; } + return k; + } + // Kaboola: the mint-leaf shooter. A press blows an air bullet, and a press with two already out wastes the 15 frame + // cooldown (body_kirby_mint.js), so only press when one will come out. Fire keeps going whatever the movement. + function shot(cc) { var b = cc.body; return b.spitCd <= 1 && !b.prev.attack && b.puffs.length < b.M.SLOTS ? 1 : 0; } + function flyM(h, v) { return function (j, cc) { var k = {}; if (h) k[h] = 1; if (v) k[v] = 1; if (cc.body.mint && shot(cc)) k.J = 1; return k; }; } + function aimM(j, cc) { // the bullet's height on Kaboola's centre, and the range the rollout scores + var b = cc.body, T = target(cc), k = {}; if (!b.mint || !T) return k; + var dy = T.y - (b.y + 1 + 5 / 8), dx = T.x - CFG.RANGE - b.x; + if (dy > 0.2) k.W = 1; else if (dy < -0.2) k.S = 1; + if (dx > 0.2) k.D = 1; else if (dx < -0.2) k.A = 1; + if (shot(cc)) k.J = 1; + return k; + } + var MACROS = [ + ['wait', hold({})], ['L', hold({ A: 1 })], ['R', hold({ D: 1 })], ['duck', hold({ S: 1 })], + ['jump', jumpM(null, 11)], ['jumpL', jumpM('A', 11)], ['jumpR', jumpM('D', 11)], ['hopL', jumpM('A', 3)], ['hopR', jumpM('D', 3)], + ['float', floatM(null)], ['floatL', floatM('A')], ['floatR', floatM('D')], ['exhale', exhaleM], + ['ammo', ammoM], ['shoot', shootM], ['harvest', harvestM, 'king_dedede'], ['nav', navM, 'lololo_lalala'], ['up', crossM(true), 'lololo_lalala'], ['down', crossM(false), 'lololo_lalala'], ['return', returnM, 'lololo_lalala'], // [name, macro, only for this boss] + ['aim', aimM, 'kaboola'], ['fire', flyM(), 'kaboola'], ['fU', flyM(null, 'W'), 'kaboola'], ['fD', flyM(null, 'S'), 'kaboola'], ['fL', flyM('A'), 'kaboola'], ['fR', flyM('D'), 'kaboola'], + ['fUL', flyM('A', 'W'), 'kaboola'], ['fDL', flyM('A', 'S'), 'kaboola'], ['fUR', flyM('D', 'W'), 'kaboola'], ['fDR', flyM('D', 'S'), 'kaboola'] + ]; + + // Roll macro m out on one future; rec (optional) receives the first SUB sub-steps' keys. + function rollout(c, m, salt, rec) { + var cc = fork(c, salt), b = cc.body, w = cc.boss, hp0 = b.hp, bh0 = w.hp, keys = {}, i, offside = 0; + for (i = 0; i < CFG.H && !cc.result; i++) { + if (i % TPS === 0) { keys = m(i / TPS, cc); if (rec && i / TPS < SUB) rec.push(keys); } + var st0 = w.st; + cc.tick(keys); + if (b.hp < hp0 || b.captured) { finish(rec, cc, m, i); return -1000 * Math.max(1, hp0 - b.hp) + i * 4 + 30 * (bh0 - w.hp); } + if (w.id === 'king_dedede' && (st0 === 'wait' || st0 === 'land') && w.st !== st0 && !groundSide(cc)) offside = 1; + } + finish(rec, cc, m, i); + if (cc.result === 'win') return 5000; + var s = (bh0 - w.hp) * 40 - CFG.OFFSIDE * offside, T = target(cc), o = ammo(cc); + var live = b.stars.some(function (st) { return !st.dead; }); + if (b.mouth) s += 12; + else if (live) s += 10; // a star on its way + else if (o) s -= 0.5 * Math.abs(o.x - b.x) + 0.3 * Math.abs(o.y - b.y - 1); + if (b.mouth && T) s -= 0.6 * Math.abs(T.y - b.y - 1) + 0.05 * Math.abs(T.x - b.x); + if (!b.mouth && !o && T) s -= 0.3 * Math.abs(Math.abs(T.x - b.x) - 6); // nothing to eat: keep a safe distance + if (b.hover) s -= CFG.HOVER; + else if (!b.mouth && !b.exhaleT && b.spitCd <= 0 && T) s += CFG.READY * (b.facing === (T.x > b.x ? 1 : -1) ? 1 : 0.5); + return s + caution(cc); + } + function finish(rec, cc, m, i) { // a rollout cut short still fills the packet's sub-steps + if (!rec) return; + while (rec.length < SUB) rec.push(cc.result ? {} : m(rec.length, cc)); + } + // What a rollout cannot see coming, because its place or its moment is random: an expert simply stays clear. + function caution(cc) { + var w = cc.boss, b = cc.body, s = 0; + // Whispy drops each apple from a random canopy column (y 12 u): do not loiter up among the leaves. + if (w.id === 'whispy_woods' && b.y > CFG.CANOPY) s -= 2 * (b.y - CFG.CANOPY); + // Lololo & Lalala: a brother's next door is on the side he is pushing toward (decided), its row is a future roll + // (not read): keep out of every doorway on that side. + if (w.id === 'lololo_lalala') { + w.bro.forEach(function (q) { + if (q.ph !== 'push' && q.ph !== 'hide') return; + var ed = q.dir > 0 ? cc.arena.W - b.x : b.x; if (ed < CFG.DOOR) s -= CFG.DOORW * (CFG.DOOR - ed); + }); var kt = wantLane(cc); if (kt !== null) s -= CFG.LANE * Math.abs(kt - lane(b.y)); + s -= CFG.EXIT * Math.min(exitGap(b), 6); + // puffed up, Kirby cannot inhale until the float ends and the air puff is out (~1 s, past the horizon); the jumps + // between corridors never need a float, so an empty-mouthed float here is only ever a delay + if ((b.hover || b.exhaleT > 0) && !b.mouth) s -= CFG.PUFF; + s -= CFG.TRAP * trapped(cc); + } + // Kaboola: stay level with it and to its left (Kirby cannot turn round), and keep some room above and below for a ram. + if (w.id === 'kaboola') { + var T = target(cc), H = cc.arena.H - 2; + if (T) { + s -= CFG.KALIGN * Math.max(0, Math.abs(T.y - b.y - 1 - 5 / 8) - T.h / 2 + 0.6); + s -= CFG.KSIDE * Math.max(0, b.x - (T.x - T.w / 2 - 1.5)); + } + s -= CFG.KEDGE * (Math.max(0, 2 - b.y) + Math.max(0, b.y - (H - 2))); + } + return s; + } + // King Dedede reads Kirby's octant when a wait ends (Func_49ac side table): beside or below him a hammer is the + // ground swing that knocks a star loose; diagonally above him it is the jumping swing, which drops none. + function groundSide(cc) { var s = cc.boss.sideOf(cc); return s === 0 || s === 4; } + + var MEM = new WeakMap(); + function plan(c) { + var st = MEM.get(c); + if (!st || c.t === 0 || st.t > c.t) { st = { name: 'wait', t: c.t }; MEM.set(c, st); } + st.t = c.t; + var best = -1e18, pick = 0, keys = null; + for (var j = 0; j < MACROS.length; j++) { + if (MACROS[j][2] && MACROS[j][2] !== c.boss.id) continue; + if (!MACROS[j][2] && c.boss.id === 'kaboola') continue; // the mint leaf has its own controls: none of the walk / jump / inhale macros + var sc = 1e18, rec = []; + for (var k = 0; k < CFG.SAMPLES && sc > -500; k++) sc = Math.min(sc, rollout(c, MACROS[j][1], k, k === 0 ? rec : null)); + if (MACROS[j][0] === st.name) sc += CFG.STICK; + if (sc > best) { best = sc; pick = j; keys = rec; } + } + st.name = MACROS[pick][0]; + return { name: st.name, score: best, subs: keys }; + } + function scripted(c) { + if (c.result) return { subs: [{}, {}, {}, {}, {}, {}], mouse: [0, 0, 0] }; + var p = plan(c); + return { subs: p.subs.map(function (h) { var o = {}; Object.keys(h).forEach(function (key) { if (h[key]) o[key] = true; }); return o; }), mouse: [0, 0, 0] }; + } + BB.GAME.scripted = scripted; + BB.KIRBY_SCRIPTED = { cfg: CFG, clone: clone, fork: fork, plan: plan, macros: MACROS, target: target, ammo: ammo }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/specs/kaboola.spec.js b/environments/games/web/games/kirby_remake/specs/kaboola.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..37c65088bb1227abd3a946f4c46993ae78fce900 --- /dev/null +++ b/environments/games/web/games/kirby_remake/specs/kaboola.spec.js @@ -0,0 +1,1116 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["kaboola"] = { + "schema": "bossbench/boss-spec@1", + "id": "kaboola", + "dims": "2d", + "family": "pogo2d", + "archetype": "Side-scrolling shooter duel (2D side view, one screen): Kirby flies on the mint leaf and blows an endless stream of air bullets to the right; a 36 x 32 px blimp weaves a figure of eight on the right of the screen, firing from a cannon under or over its hull, and every 8 s winds up and rams across the screen toward the side Kirby is on", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "intro", + "telegraph": "ram_antic", + "active": "ram", + "recovery": "ram_back" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.05 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 1.0, + "active": 1.0, + "recovery": 1.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "shoot", + "atoms": [ + "projectile" + ], + "active": 8.0, + "params": { + "offset": [ + -10, + 16 + ], + "bullet": [ + -3, + 0 + ], + "fan": [ + -2, + 1 + ], + "bullet_size": [ + 6, + 4 + ], + "thresholds": { + "one": 85, + "three": 128, + "invert": 178 + }, + "extra_aim": { + "up": { + "segs": [ + [ + 2, + -4, + 3 + ], + [ + 2, + -2, + 3 + ], + [ + 2, + -1, + 2 + ], + [ + 2, + -0.125, + 2 + ], + [ + 2, + 0.125, + 2 + ], + [ + 2, + 1, + 2 + ], + [ + 100000, + 2, + 2 + ] + ], + "loop": false + }, + "hi": { + "segs": [ + [ + 2, + -3, + 2 + ], + [ + 2, + -2, + 6 + ], + [ + 2, + -3, + 2 + ], + [ + 2, + -3, + -2 + ], + [ + 2, + -4, + -2 + ], + [ + 2, + -3, + 0 + ] + ], + "loop": true + }, + "mid": { + "segs": [ + [ + 2, + -4, + 2 + ], + [ + 2, + -4, + 6 + ], + [ + 2, + -4, + 2 + ], + [ + 2, + -4, + -2 + ], + [ + 2, + -4, + -6 + ], + [ + 2, + -4, + -2 + ] + ], + "loop": true + }, + "lo": { + "segs": [ + [ + 2, + -3, + -2 + ], + [ + 2, + -2, + -6 + ], + [ + 2, + -3, + -2 + ], + [ + 2, + -3, + 2 + ], + [ + 2, + -4, + 2 + ], + [ + 2, + -3, + 0 + ] + ], + "loop": true + }, + "down": { + "segs": [ + [ + 2, + -4, + -3 + ], + [ + 2, + -2, + -3 + ], + [ + 2, + -1, + -2 + ], + [ + 2, + -0.125, + -2 + ], + [ + 2, + 0.125, + -2 + ], + [ + 2, + 1, + -2 + ], + [ + 100000, + 2, + -2 + ] + ], + "loop": false + } + }, + "extra_aim_table": [ + "up", + "up", + "hi", + "hi", + "mid", + "lo", + "lo", + "down", + "down", + "down", + "lo", + "lo", + "mid", + "hi", + "hi", + "up" + ] + }, + "damage": 1, + "cue": "the cannon opens under the hull (or over it, after the blimp rolls over) and fires one bullet, three in a row, or a fan of three", + "punish": "the straight shots leave 16 px above or below its centre: level with its middle, only the fan's slanted bullets come at you" + }, + { + "name": "ram", + "atoms": [ + "charge" + ], + "telegraph_scale": 1.0666666666666667, + "active": 1.2, + "params": { + "table": [ + "up", + "up", + "up", + "up", + "straight", + "down", + "down", + "down", + "down", + "down", + "down", + "down", + "straight", + "up", + "up", + "up" + ], + "home": [ + 132, + 80 + ], + "intro_start": [ + 201, + 34 + ], + "intro": [ + [ + 32, + -1, + 0 + ], + [ + 8, + -1.125, + -2 + ], + [ + 40, + -0.75, + -1.25 + ], + [ + 16, + -0.75, + -1 + ], + [ + 16, + -0.5, + -0.5 + ], + [ + 16, + -0.25, + 0 + ], + [ + 16, + 0, + 0.75 + ], + [ + 16, + 0.25, + 1 + ], + [ + 16, + 0.75, + 0.75 + ], + [ + 16, + 0.5, + 0.25 + ], + [ + 16, + 0.125, + 0 + ], + [ + 16, + 0, + 0 + ] + ], + "weave": [ + [ + 10, + 0.75, + -0.75 + ], + [ + 10, + 0.5, + -0.75 + ], + [ + 10, + 0.25, + -0.5 + ], + [ + 10, + 0, + -0.5 + ], + [ + 10, + -0.25, + -0.25 + ], + [ + 10, + -0.5, + -0.25 + ], + [ + 10, + -0.75, + 0 + ], + [ + 10, + -0.5, + 0.25 + ], + [ + 10, + -0.25, + 0.25 + ], + [ + 10, + 0, + 0.5 + ], + [ + 10, + 0.25, + 0.5 + ], + [ + 10, + 0.5, + 0.75 + ], + [ + 10, + 0.75, + 0.75 + ], + [ + 10, + 0.5, + 0.75 + ], + [ + 10, + 0.25, + 0.5 + ], + [ + 10, + 0, + 0.5 + ], + [ + 10, + -0.25, + 0.25 + ], + [ + 10, + -0.5, + 0.25 + ], + [ + 10, + -0.75, + 0 + ], + [ + 10, + -0.5, + -0.25 + ], + [ + 10, + -0.25, + -0.25 + ], + [ + 10, + 0, + -0.5 + ], + [ + 10, + 0.25, + -0.5 + ], + [ + 10, + 0.5, + -0.75 + ] + ], + "rams": { + "straight": { + "antic": [ + [ + 16, + 1, + 0 + ], + [ + 16, + 0.5, + 0 + ], + [ + 16, + -0.5, + 0 + ], + [ + 16, + -1, + 0 + ] + ], + "go": [ + [ + 24, + -4, + 0 + ], + [ + 48, + -0.5, + 0 + ] + ], + "back": [ + [ + 48, + 2, + 0 + ], + [ + 48, + 0.5, + 0 + ], + [ + 16, + 0, + 0 + ] + ] + }, + "up": { + "antic": [ + [ + 16, + 1, + -0.5 + ], + [ + 16, + 0.5, + -0.25 + ], + [ + 16, + -0.5, + 0.25 + ], + [ + 16, + -1, + 0.5 + ] + ], + "go": [ + [ + 24, + -4, + 2 + ], + [ + 48, + -0.5, + 0.25 + ] + ], + "back": [ + [ + 48, + 2, + -1 + ], + [ + 48, + 0.5, + -0.25 + ], + [ + 16, + 0, + 0 + ] + ] + }, + "down": { + "antic": [ + [ + 16, + 1, + 0.5 + ], + [ + 16, + 0.5, + 0.25 + ], + [ + 16, + -0.5, + -0.25 + ], + [ + 16, + -1, + -0.5 + ] + ], + "go": [ + [ + 24, + -4, + -2 + ], + [ + 48, + -0.5, + -0.25 + ] + ], + "back": [ + [ + 48, + 2, + 1 + ], + [ + 48, + 0.5, + 0.25 + ], + [ + 16, + 0, + 0 + ] + ] + } + }, + "extra_intro": [ + [ + 32, + -1, + 0 + ], + [ + 8, + -1.125, + -2 + ], + [ + 40, + -0.75, + -1.25 + ], + [ + 16, + -0.75, + -1 + ], + [ + 16, + -0.5, + -0.5 + ], + [ + 16, + -0.25, + 0 + ], + [ + 16, + 0, + 0.75 + ], + [ + 16, + 0.25, + 1 + ], + [ + 16, + 0.75, + 0.75 + ], + [ + 16, + 0.5, + 0.25 + ], + [ + 16, + 0.125, + 0 + ] + ], + "extra_weave": [ + [ + 8, + -2, + 3 + ], + [ + 8, + -1, + 2 + ], + [ + 8, + 0, + 1 + ], + [ + 8, + 1, + 0.5 + ], + [ + 8, + 2, + -0.5 + ], + [ + 8, + 1, + -1 + ], + [ + 8, + 0, + -2 + ], + [ + 8, + -1, + -3 + ], + [ + 8, + -2, + -3 + ], + [ + 8, + -1, + -2 + ], + [ + 8, + 0, + -1 + ], + [ + 8, + 1, + -0.5 + ], + [ + 8, + 2, + 0.5 + ], + [ + 8, + 1, + 1 + ], + [ + 8, + 0, + 2 + ], + [ + 8, + -1, + 3 + ] + ], + "extra_rams": { + "straight": { + "antic": [ + [ + 4, + 2, + 0 + ], + [ + 4, + 1, + 0 + ], + [ + 4, + 0.5, + 0 + ], + [ + 4, + 0.125, + 0 + ], + [ + 8, + 0, + 0 + ] + ], + "go": [ + [ + 12, + -6, + 0 + ], + [ + 8, + -4, + 0 + ], + [ + 8, + -2, + 0 + ], + [ + 8, + -1, + 0 + ] + ], + "back": [ + [ + 8, + 1, + 0 + ], + [ + 8, + 2, + 0 + ], + [ + 8, + 4, + 0 + ], + [ + 12, + 6, + 0 + ], + [ + 4, + -0.125, + 0 + ], + [ + 4, + -0.5, + 0 + ], + [ + 4, + -1, + 0 + ], + [ + 4, + -2, + 0 + ] + ] + }, + "up": { + "antic": [ + [ + 6, + 2, + 1 + ], + [ + 6, + 1, + 1 + ], + [ + 6, + 0, + 1 + ], + [ + 6, + -1, + 1 + ] + ], + "go": [ + [ + 6, + -2, + 1 + ], + [ + 13, + -6, + 0.75 + ], + [ + 8, + -3, + -0.5 + ], + [ + 8, + -1, + -1 + ] + ], + "back": [ + [ + 8, + 0.5, + -2 + ], + [ + 8, + 1, + -1 + ], + [ + 8, + 6, + -0.5 + ], + [ + 8, + 4, + -0.03125 + ], + [ + 8, + 2, + 0 + ], + [ + 8, + 0.25, + 0 + ] + ] + }, + "down": { + "antic": [ + [ + 6, + 2, + -1 + ], + [ + 6, + 1, + -1 + ], + [ + 6, + 0, + -1 + ], + [ + 6, + -1, + -1 + ] + ], + "go": [ + [ + 6, + -2, + -1 + ], + [ + 13, + -6, + -0.75 + ], + [ + 8, + -3, + 0.5 + ], + [ + 8, + -1, + 1 + ] + ], + "back": [ + [ + 8, + 0.5, + 2 + ], + [ + 8, + 1, + 1 + ], + [ + 8, + 6, + 0.5 + ], + [ + 8, + 4, + 0.03125 + ], + [ + 8, + 2, + 0 + ], + [ + 8, + 0.25, + 0 + ] + ] + } + }, + "size": [ + 36, + 32 + ] + }, + "damage": 1, + "cue": "the blimp backs away and tips toward your side (up, level or down), then dashes across the screen and floats back", + "punish": "a dash cannot be outrun sideways: get out of its line up or down (up is twice as fast as down) and keep firing as it comes back" + } + ], + "difficulty": { + "hp": [ + 85, + 240, + 680 + ], + "telegraph": [ + 1.2, + 1.0, + 0.8 + ], + "recovery": [ + 1.2, + 1.0, + 0.75 + ], + "idle_gap": [ + 1.0, + 1.0, + 0.8 + ], + "entropy": [ + 1.0, + 1.0, + 1.0 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 0.5, + 1.0, + 1.6 + ], + "kirby_hp": [ + 6, + 6, + 6 + ] + }, + "kinds": { + "entropy": "continuous", + "dmg": "multiplier" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/specs/king_dedede.spec.js b/environments/games/web/games/kirby_remake/specs/king_dedede.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..ba882a76cc1b3e96583ce8545604da5a5bb599a0 --- /dev/null +++ b/environments/games/web/games/kirby_remake/specs/king_dedede.spec.js @@ -0,0 +1,601 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["king_dedede"] = { + "schema": "bossbench/boss-spec@1", + "id": "king_dedede", + "dims": "2d", + "family": "pogo2d", + "archetype": "Hammer king in a wrestling ring (2D side view, grounded): backs off and waddles in to belly-slide, takes huge jumps that shed two stars on landing, walks up to inhale the player and spit them into the ropes, or hops and swings his hammer over his head into the floor (one star). The stars are the only ammunition - inhale one and spit it back (10 hits); the slide and the hammer swing have super armour", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.05 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 1.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "walk", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.4, + "active": 1.6, + "params": { + "back_off": [ + [ + 8, + 1, + 0 + ], + [ + 8, + 0.5, + 0 + ], + [ + 8, + 0.125, + 0 + ] + ], + "approach": [ + [ + 4, + 1.25, + 0.5 + ], + [ + 4, + 1, + 0 + ], + [ + 4, + 0.75, + 0 + ], + [ + 4, + 0.75, + -0.5 + ], + [ + 10, + 0.75, + 0 + ] + ], + "trigger": 24, + "slide": [ + [ + 16, + 1, + 0 + ], + [ + 16, + 0.5, + 0 + ], + [ + 16, + 0.125, + 0 + ], + [ + 48, + 0, + 0 + ] + ], + "extra_back_off": [ + [ + 8, + 1, + 0 + ] + ], + "extra_approach": [ + [ + 4, + 2, + 0.5 + ], + [ + 4, + 2, + 0 + ], + [ + 4, + 1.25, + 0 + ], + [ + 4, + 1.25, + -0.5 + ], + [ + 10, + 1, + 0 + ] + ], + "extra_slide": [ + [ + 16, + 1.25, + 0 + ], + [ + 16, + 0.75, + 0 + ], + [ + 16, + 0.125, + 0 + ], + [ + 32, + 0, + 0 + ] + ] + }, + "damage": 1, + "cue": "steps back a little, then waddles toward the player; within 3 u he throws himself into a belly slide", + "punish": "jump or float over him as the slide starts - the slide (and the time he lies there) has super armour, but a star still costs him HP" + }, + { + "name": "jump", + "atoms": [ + "leap", + "slam" + ], + "telegraph_scale": 0.5333333333333333, + "active": 1.3333333333333333, + "params": { + "side_table": [ + 2, + 3, + 4, + 4, + -1, + 0, + 0, + 1 + ], + "rise": [ + [ + 10, + 0.75, + 4 + ], + [ + 10, + 0.75, + 3 + ], + [ + 10, + 0.75, + 1 + ], + [ + 10, + 0.75, + 0.5 + ] + ], + "fall": [ + [ + 10, + 0.75, + -0.5 + ], + [ + 10, + 0.75, + -1 + ], + [ + 10, + 0.75, + -3 + ], + [ + 10, + 0.75, + -4 + ] + ], + "land": 32, + "extra_rise": [ + [ + 8, + 2, + 4 + ], + [ + 8, + 2, + 3 + ], + [ + 8, + 2, + 1.25 + ], + [ + 8, + 2, + 0.75 + ] + ], + "extra_fall": [ + [ + 8, + 2, + -0.75 + ], + [ + 8, + 2, + -1.25 + ], + [ + 8, + 2, + -3 + ], + [ + 8, + 2, + -4 + ] + ], + "extra_land": 24, + "stars": [ + [ + -8, + 8 + ], + [ + 8, + 8 + ] + ], + "star_track": [ + [ + 6, + 2, + 1.25 + ], + [ + 10, + 0.5, + 0.5 + ], + [ + 20, + 0, + 0 + ] + ], + "extra_star_track": [ + [ + 6, + 2, + 1.25 + ], + [ + 8, + 1, + 0.75 + ], + [ + 14, + 0, + 0 + ] + ], + "star_size": [ + 12, + 12 + ] + }, + "damage": 1, + "cue": "crouches, then leaps 10 u high toward the player (or straight up when the player is overhead) and crashes down", + "punish": "the two stars that pop out beside him on landing live only 0.6 s - be inhaling next to the landing spot, then spit" + }, + { + "name": "inhale", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.25, + "active": 1.6666666666666667, + "params": { + "trigger": 24, + "reach": [ + 46, + 20 + ], + "pull": [ + 0.1171875, + 10 + ], + "hold": 52, + "spit_speed": 2, + "after": 76, + "miss_after": 20, + "skip_at_hp": 1, + "extra_active": 0.8333333333333334 + }, + "damage": 1, + "cue": "backs off, walks to where the player was, opens his mouth and sucks for up to 1.7 s", + "punish": "stay out of the 5.75 u cone in front of his mouth (above or behind him is safe); a caught player is spat into the ropes for 1 damage" + }, + { + "name": "hammer", + "atoms": [ + "melee_area", + "slam" + ], + "telegraph_scale": 0.26666666666666666, + "active": 1.0, + "params": { + "hop": [ + [ + 8, + 0, + 2 + ], + [ + 8, + 0, + 0.5 + ], + [ + 8, + 0, + -0.5 + ], + [ + 8, + 0, + -2 + ], + [ + 2, + 0, + 0 + ] + ], + "extra_hop": [ + [ + 4, + 0, + 2 + ], + [ + 4, + 0, + 0.5 + ], + [ + 4, + 0, + -0.5 + ], + [ + 4, + 0, + -2 + ], + [ + 2, + 0, + 0 + ] + ], + "trigger": 24, + "side_table": [ + 2, + 3, + 4, + 4, + -1, + 0, + 0, + 1 + ], + "arc": [ + [ + 16, + -18 + ], + [ + 8, + -25 + ], + [ + -8, + -25 + ], + [ + -16, + -18 + ], + [ + -23, + -6 + ], + [ + -23, + 6 + ] + ], + "arc_at": [ + 0, + 16, + 18, + 20, + 22, + 24 + ], + "arc_back_at": [ + 50, + 52, + 54, + 56, + 58, + 60 + ], + "arc_life": [ + 8, + 2, + 2, + 2, + 2, + 2 + ], + "arc_size": [ + 20, + 16 + ], + "impact": [ + -8, + 10, + 52, + 16, + 26, + 6 + ], + "swing": 76, + "jump_swing": 92, + "crouch": 32, + "ground_motion": [ + [ + 26, + 0, + 0 + ], + [ + 8, + 0, + 2 + ], + [ + 8, + 0, + 0 + ], + [ + 8, + 0, + -2 + ], + [ + 26, + 0, + 0 + ] + ], + "star": [ + -20, + 8 + ] + }, + "damage": 1, + "cue": "hops in place, walks up to where the player was, raises the hammer behind him and swings it over his head into the floor in front", + "punish": "the swing covers his back, his head and 4 u of floor in front - stand off; the ground swing drops one star in front of him" + } + ], + "difficulty": { + "hp": [ + 3, + 10, + 25 + ], + "telegraph": [ + 1.3, + 1.0, + 0.8 + ], + "recovery": [ + 1.4, + 1.0, + 0.75 + ], + "idle_gap": [ + 1.4, + 1.0, + 0.8 + ], + "entropy": [ + 0.0, + 1.0, + 1.0 + ], + "speed": [ + 0.85, + 1.0, + 1.15 + ], + "dmg": [ + 0.5, + 1.0, + 1.5 + ], + "kirby_hp": [ + 6, + 6, + 6 + ] + }, + "kinds": { + "entropy": "continuous", + "dmg": "multiplier" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/specs/kracko.spec.js b/environments/games/web/games/kirby_remake/specs/kracko.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e74cff859a86d2132702df219ebf7ed436cc94ad --- /dev/null +++ b/environments/games/web/games/kirby_remake/specs/kracko.spec.js @@ -0,0 +1,595 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["kracko"] = { + "schema": "bossbench/boss-spec@1", + "id": "kracko", + "dims": "2d", + "family": "pogo2d", + "archetype": "One-eyed thundercloud (2D side view, airborne): drifts across the sky in a wave or swoops low toward the player, spins a ring of sparks around itself and drops Waddle Doos that walk the floor (some fire their own sweeping beam); the Doos are the only ammunition - inhale one and spit it up at the cloud (6 hits)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.05 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "move", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.6, + "active": 1.6, + "params": { + "wave": [ + [ + 8, + 1, + 0.25 + ], + [ + 8, + 1, + 1.25 + ], + [ + 8, + 1, + -0.25 + ], + [ + 8, + 1, + -1.25 + ] + ], + "swoop": [ + [ + 8, + 0, + 2 + ], + [ + 8, + 0, + -2 + ], + [ + 8, + 0.75, + -3 + ], + [ + 8, + 1, + -2 + ], + [ + 8, + 2, + -1 + ], + [ + 6, + 3, + -0.25 + ], + [ + 6, + 3, + 0.25 + ], + [ + 8, + 2, + 1 + ], + [ + 8, + 1, + 2 + ], + [ + 8, + 0.75, + 3 + ] + ], + "swoop_octants": [ + 4, + 5 + ] + }, + "damage": 1, + "cue": "drifts 12 u to the other side; when the player is below on that side it rises, then swoops down to floor height and back up", + "punish": "a swoop passes 1.1 u above the floor - duck (S) under it or get out of the way; the cloud is lowest (easiest to hit) mid-swoop" + }, + { + "name": "beam", + "atoms": [ + "projectile", + "melee_area" + ], + "telegraph_scale": 0.6, + "active": 1.3333333333333333, + "params": { + "offsets": [ + [ + 0, + -28 + ], + [ + 8, + -24 + ], + [ + 16, + -16 + ], + [ + 24, + -8 + ], + [ + 28, + 0 + ], + [ + 24, + 8 + ], + [ + 16, + 16 + ], + [ + 8, + 24 + ] + ], + "vel": [ + [ + 0, + -6 + ], + [ + 2.25, + -5.375 + ], + [ + 4, + -4 + ], + [ + 5.375, + -2.25 + ], + [ + 6, + 0 + ], + [ + 5.375, + 2.25 + ], + [ + 4, + 4 + ], + [ + 2.25, + 5.375 + ] + ], + "life": 7, + "size": [ + 6, + 6 + ], + "steps": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 0, + 1 + ], + "extra_steps": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "extra_active": 1.0666666666666667 + }, + "damage": 1, + "cue": "the cloud crackles; sparks shoot out from two opposite points that turn half a circle around it", + "punish": "the sparks reach 8.75 u from the centre - keep a long horizontal distance and stand off the diagonals" + }, + { + "name": "doo", + "atoms": [ + "summon" + ], + "telegraph_scale": 0.6, + "active": 0.016666666666666666, + "params": { + "size": [ + 12, + 12 + ], + "walk": 0.75, + "gravity": [ + 0.140625, + 2.5 + ], + "habits": [ + [ + 0, + 0.5 + ], + [ + 32, + 0.25 + ], + [ + 96, + 0.25 + ] + ], + "flash": 48, + "beam_dirs": [ + [ + 0, + -6 + ], + [ + -2.25, + -5.375 + ], + [ + -4, + -4 + ], + [ + -5.375, + -2.25 + ], + [ + -6, + 0 + ], + [ + -5.375, + 2.25 + ], + [ + -4, + 4 + ], + [ + -2.25, + 5.375 + ] + ], + "beam_each": [ + 3, + 4 + ] + }, + "damage": 1, + "cue": "a one-eyed walker pops out of the cloud and walks toward the player's side; one in two stops, flashes and sweeps a beam from overhead to the floor in front", + "punish": "this is the ammunition: inhale the walker (hold J facing it) and spit it straight up at the cloud from a jump" + }, + { + "name": "bombs", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.2, + "active": 2.133, + "params": { + "track": [ + [ + 8, + -3, + 2 + ], + [ + 8, + -2, + 1 + ], + [ + 8, + -1, + 0.5 + ], + [ + 8, + -0.5, + 0 + ], + [ + 8, + 0.5, + -1 + ], + [ + 8, + 1, + 0 + ], + [ + 8, + 2, + 1 + ], + [ + 8, + 3, + 0 + ], + [ + 8, + 3, + -1 + ], + [ + 8, + 2, + 0 + ], + [ + 8, + 1, + 1 + ], + [ + 8, + 0.5, + 0 + ], + [ + 8, + -0.5, + 0 + ], + [ + 8, + -1, + -0.5 + ], + [ + 8, + -2, + -1 + ], + [ + 8, + -3, + -2 + ] + ], + "drops_after": [ + 5, + 8, + 11 + ], + "drops_after_right": [ + 4, + 8, + 12 + ], + "fall": [ + 32, + 2 + ], + "blast": [ + 40, + 40, + 32 + ], + "extra_only": true + }, + "damage": 1, + "cue": "Extra Game: the cloud loops out and back across the arena dropping three bombs that fall and burst above the floor", + "punish": "inhale a falling bomb before it bursts - in the Extra Game the bombs are the only ammunition; the far corner is out of reach" + }, + { + "name": "charge", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.2, + "active": 2.433, + "params": { + "track": [ + [ + 6, + 2, + 2 + ], + [ + 6, + 1, + 1 + ], + [ + 8, + 0, + 0 + ], + [ + 16, + -4, + -3 + ], + [ + 10, + -1.25, + -0.5 + ], + [ + 10, + -1, + -0.75 + ], + [ + 10, + -0.5, + -0.75 + ], + [ + 16, + 4, + 0 + ], + [ + 8, + 3, + 0 + ], + [ + 8, + 3, + 0.5 + ], + [ + 8, + 2, + 2 + ], + [ + 8, + 1, + 4 + ], + [ + 8, + -1, + 2 + ], + [ + 8, + -2, + -0.5 + ], + [ + 8, + -4, + -1.25 + ], + [ + 8, + -0.75, + -0.75 + ] + ], + "extra_only": true + }, + "damage": 1, + "cue": "Extra Game: rears back away from the player, then dives at 4 px/f down to the floor on the player's side and loops back", + "punish": "the only Extra attack that reaches the corner - duck under it" + } + ], + "difficulty": { + "hp": [ + 3, + 9, + 32 + ], + "telegraph": [ + 1.3, + 1.0, + 0.8 + ], + "recovery": [ + 1.0, + 1.0, + 0.75 + ], + "idle_gap": [ + 1.0, + 1.0, + 0.8 + ], + "entropy": [ + 0.0, + 1.0, + 1.0 + ], + "speed": [ + 1.0, + 1.0, + 1.15 + ], + "dmg": [ + 0.5, + 1.0, + 1.5 + ], + "kirby_hp": [ + 6, + 6, + 6 + ] + }, + "kinds": { + "entropy": "continuous", + "dmg": "multiplier" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/specs/lololo_lalala.spec.js b/environments/games/web/games/kirby_remake/specs/lololo_lalala.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9ebebef5ccf68fd97ed875158769635c2c80023c --- /dev/null +++ b/environments/games/web/games/kirby_remake/specs/lololo_lalala.spec.js @@ -0,0 +1,265 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["lololo_lalala"] = { + "schema": "bossbench/boss-spec@1", + "id": "lololo_lalala", + "dims": "2d", + "family": "pogo2d", + "archetype": "Two brothers in a four-corridor castle room (2D side view, fixed screen): each in turn appears at a random free door on one side, pushes a box across the corridor and vanishes into the door opposite, then picks a free row on the other side; the pushed boxes are the only ammunition - inhale one and spit it back at the brother behind it (3 hits each in the original, 6 in all)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "appear", + "active": "push", + "recovery": "hide" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.05 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "push", + "atoms": [ + "charge", + "projectile" + ], + "telegraph_scale": 0.5833333333333334, + "active": 3.6833333333333336, + "params": { + "doors": { + "right_x": 161, + "left_x": 16, + "rows_y": [ + 24, + 56, + 88, + 120 + ] + }, + "first_side": { + "lololo": "right", + "lalala": "left" + }, + "pusher": [ + [ + 35, + 0, + 0 + ], + [ + 168, + 0.75, + 0 + ], + [ + 6, + 2, + 0 + ], + [ + 6, + 1, + 0 + ], + [ + 6, + 0.25, + 0 + ] + ], + "hide": 32, + "box": [ + [ + 4, + 2, + 0 + ], + [ + 4, + 1, + 0 + ], + [ + 4, + 0.75, + 0 + ], + [ + 4, + 0.25, + 0 + ], + [ + 4, + 0.0625, + 0 + ], + [ + 15, + 0, + 0 + ], + [ + 176, + 0.75, + 0 + ] + ], + "extra_pusher": [ + [ + 35, + 0, + 0 + ], + [ + 100, + 1.25, + 0 + ], + [ + 6, + 2, + 0 + ], + [ + 6, + 1, + 0 + ], + [ + 6, + 0.25, + 0 + ] + ], + "extra_box": [ + [ + 4, + 2, + 0 + ], + [ + 4, + 1, + 0 + ], + [ + 4, + 0.75, + 0 + ], + [ + 4, + 0.25, + 0 + ], + [ + 4, + 0.0625, + 0 + ], + [ + 15, + 0, + 0 + ], + [ + 176, + 1.25, + 0 + ] + ], + "brother_size": [ + 12, + 12 + ], + "box_size": [ + 12, + 12 + ] + }, + "damage": 1, + "cue": "a brother pops out of a door at one end of a corridor with a box in front of him, stands a moment, then starts pushing", + "punish": "get into that corridor ahead of the box, inhale it, and spit the star straight back down the corridor - the brother is right behind it" + } + ], + "difficulty": { + "hp": [ + 5, + 12, + 32 + ], + "telegraph": [ + 1.1, + 1.0, + 0.8 + ], + "recovery": [ + 1.0, + 1.0, + 0.75 + ], + "idle_gap": [ + 1.0, + 1.0, + 0.8 + ], + "entropy": [ + 1.0, + 1.0, + 1.0 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 0.5, + 1.0, + 1.6 + ], + "kirby_hp": [ + 6, + 6, + 6 + ] + }, + "kinds": { + "entropy": "continuous", + "dmg": "multiplier" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/specs/poppy_bros_sr.spec.js b/environments/games/web/games/kirby_remake/specs/poppy_bros_sr.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a0b93e5cd0676b76fb7e0633199923af4d662554 --- /dev/null +++ b/environments/games/web/games/kirby_remake/specs/poppy_bros_sr.spec.js @@ -0,0 +1,857 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["poppy_bros_sr"] = { + "schema": "bossbench/boss-spec@1", + "id": "poppy_bros_sr", + "dims": "2d", + "family": "pogo2d", + "archetype": "Bomb-throwing jester (2D side view, grounded, fixed screen): hops in place, jumps straight up to lob a bomb at the player (from the top of the jump, or after landing so it rolls along the floor), sometimes leaps across the room and back; the bombs are the only ammunition - inhale one before it bursts and spit it back (3 hits in the original)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.05 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 1.0, + "active": 1.0, + "recovery": 1.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "hop", + "atoms": [ + "leap" + ], + "active": 2.1333333333333333, + "params": { + "track": [ + [ + 8, + -0.5, + 1 + ], + [ + 8, + -0.5, + 0.5 + ], + [ + 8, + -0.5, + -0.5 + ], + [ + 8, + -0.5, + -1 + ], + [ + 8, + 0.5, + 1.25 + ], + [ + 8, + 0.5, + 0.75 + ], + [ + 8, + 0.5, + -0.75 + ], + [ + 8, + 0.5, + -1.25 + ] + ], + "repeat": 2, + "extra_track": [ + [ + 6, + -0.5, + 2 + ], + [ + 6, + -0.5, + 1 + ], + [ + 6, + -0.5, + -1 + ], + [ + 6, + -0.5, + -2 + ], + [ + 6, + 0.5, + 1.25 + ], + [ + 6, + 0.5, + 0.75 + ], + [ + 6, + 0.5, + -0.75 + ], + [ + 6, + 0.5, + -1.25 + ] + ], + "extra_repeat": 1 + }, + "damage": 1, + "cue": "small hops on the spot, back and forth (two pairs)", + "punish": "his body hurts on contact, but he only hops in place - stay a few units away and wait for the bomb" + }, + { + "name": "throw", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.7333333333333333, + "active": 0.5333333333333333, + "params": { + "jump": [ + [ + 6, + 0, + 3 + ], + [ + 6, + 0, + 2 + ], + [ + 6, + 0, + 1.25 + ], + [ + 6, + 0, + 0.75 + ], + [ + 6, + 0, + 0.125 + ], + [ + 16, + 0, + 0 + ], + [ + 6, + 0, + -0.125 + ], + [ + 6, + 0, + -0.75 + ], + [ + 6, + 0, + -1.25 + ], + [ + 6, + 0, + -2 + ], + [ + 6, + 0, + -3 + ] + ], + "extra_jump": [ + [ + 5, + 0, + 3 + ], + [ + 5, + 0, + 2 + ], + [ + 5, + 0, + 1.25 + ], + [ + 5, + 0, + 0.75 + ], + [ + 5, + 0, + 0.125 + ], + [ + 16, + 0, + 0 + ], + [ + 5, + 0, + -0.125 + ], + [ + 5, + 0, + -0.75 + ], + [ + 5, + 0, + -1.25 + ], + [ + 5, + 0, + -2 + ], + [ + 5, + 0, + -3 + ] + ], + "release": { + "nodelay": 44, + "delay": 76 + }, + "total": { + "nodelay": 76, + "delay": 87 + }, + "extra_release": { + "nodelay": 39, + "delay": 71 + }, + "extra_total": { + "nodelay": 68, + "delay": 82 + }, + "spawn": [ + -16, + 8 + ], + "bounce": [ + [ + 8, + 2, + -1 + ], + [ + 8, + 2, + -2 + ], + [ + 8, + 2, + -3 + ], + [ + 8, + 1.25, + 2 + ], + [ + 8, + 1.25, + 0.5 + ], + [ + 8, + 1.25, + -0.5 + ], + [ + 8, + 1.25, + -2 + ] + ], + "fall": [ + [ + 8, + 2, + 0 + ], + [ + 8, + 2, + -0.25 + ], + [ + 8, + 2, + -0.75 + ], + [ + 8, + 1.25, + 1.25 + ], + [ + 8, + 1.25, + 0.125 + ], + [ + 8, + 1.25, + -0.125 + ], + [ + 8, + 1.25, + -1 + ] + ], + "extra_bounce": [ + [ + 5, + 3, + -2 + ], + [ + 5, + 3, + -2 + ], + [ + 8, + 3, + -3 + ], + [ + 6, + 2, + 2 + ], + [ + 6, + 2, + 0.5 + ], + [ + 6, + 2, + -0.5 + ], + [ + 6, + 2, + -2 + ] + ], + "extra_fall": [ + [ + 6, + 3, + 0 + ], + [ + 6, + 3, + -0.25 + ], + [ + 6, + 3, + -0.75 + ], + [ + 6, + 2, + 1.25 + ], + [ + 6, + 2, + 0.125 + ], + [ + 6, + 2, + -0.125 + ], + [ + 6, + 2, + -1 + ] + ], + "bomb_size": [ + 12, + 12 + ], + "blast": [ + 40, + 40, + 32 + ] + }, + "damage": 1, + "cue": "jumps straight up with a bomb overhead; either lobs it from the top of the jump, or hangs there, lands and rolls it along the floor", + "punish": "the bomb comes toward you and bursts in a 5 x 5 u blast where its path ends - inhale it first, then spit it back" + }, + { + "name": "leap", + "atoms": [ + "leap", + "charge" + ], + "telegraph_scale": 1.6, + "active": 2.0, + "params": { + "mid": [ + [ + 4, + 0.75, + 2 + ], + [ + 4, + 0.75, + 2 + ], + [ + 4, + 0.75, + 1 + ], + [ + 4, + 0.75, + 0.75 + ], + [ + 4, + 0.75, + 0.5 + ], + [ + 4, + 0.75, + 0.25 + ], + [ + 4, + 0.75, + -0.25 + ], + [ + 4, + 0.75, + -0.5 + ], + [ + 4, + 0.75, + -0.75 + ], + [ + 4, + 0.75, + -1 + ], + [ + 4, + 0.75, + -2 + ], + [ + 4, + 0.75, + -2 + ], + [ + 4, + -0.75, + 2 + ], + [ + 4, + -0.75, + 2 + ], + [ + 4, + -0.75, + 1 + ], + [ + 4, + -0.75, + 0.75 + ], + [ + 4, + -0.75, + 0.5 + ], + [ + 4, + -0.75, + 0.25 + ], + [ + 4, + -0.75, + -0.25 + ], + [ + 4, + -0.75, + -0.5 + ], + [ + 4, + -0.75, + -0.75 + ], + [ + 4, + -0.75, + -1 + ], + [ + 4, + -0.75, + -2 + ], + [ + 4, + -0.75, + -2 + ] + ], + "long": [ + [ + 5, + 2, + 2 + ], + [ + 5, + 2, + 2 + ], + [ + 5, + 2, + 1 + ], + [ + 5, + 2, + 0.75 + ], + [ + 5, + 2, + 0.5 + ], + [ + 5, + 2, + 0.25 + ], + [ + 5, + 2, + -0.25 + ], + [ + 5, + 2, + -0.5 + ], + [ + 5, + 2, + -0.75 + ], + [ + 5, + 2, + -1 + ], + [ + 5, + 2, + -2 + ], + [ + 5, + 2, + -2 + ], + [ + 5, + -2, + 2 + ], + [ + 5, + -2, + 2 + ], + [ + 5, + -2, + 1 + ], + [ + 5, + -2, + 0.75 + ], + [ + 5, + -2, + 0.5 + ], + [ + 5, + -2, + 0.25 + ], + [ + 5, + -2, + -0.25 + ], + [ + 5, + -2, + -0.5 + ], + [ + 5, + -2, + -0.75 + ], + [ + 5, + -2, + -1 + ], + [ + 5, + -2, + -2 + ], + [ + 5, + -2, + -2 + ] + ] + }, + "damage": 1, + "cue": "a medium hop toward the player and back, then a huge leap across the room - he always returns to his spot", + "punish": "get clear of where he lands (or duck: his box stops 9 px above his feet); he drops no bomb during the leap" + }, + { + "name": "dash", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.3, + "active": 1.55, + "params": { + "track": [ + [ + 6, + -2, + 0 + ], + [ + 6, + -1, + 0 + ], + [ + 6, + -0.5, + 0 + ], + [ + 13, + 6, + 0 + ], + [ + 6, + 4, + 0 + ], + [ + 6, + 3, + 0 + ], + [ + 6, + 2, + 0 + ], + [ + 6, + 1, + 0 + ], + [ + 6, + -1, + 0 + ], + [ + 6, + -2, + 0 + ], + [ + 6, + -3, + 0 + ], + [ + 6, + -4, + 0 + ], + [ + 13, + -6, + 0 + ], + [ + 6, + 0.5, + 0 + ], + [ + 6, + 1, + 0 + ], + [ + 6, + 2, + 0 + ] + ], + "anim": 111, + "extra_only": true + }, + "damage": 1, + "cue": "Extra Game: he backs up a step and dashes across the floor at full speed, then runs back", + "punish": "jump or float over the dash, or duck under his box" + } + ], + "difficulty": { + "hp": [ + 5, + 16, + 60 + ], + "telegraph": [ + 1.3, + 1.0, + 0.8 + ], + "recovery": [ + 1.2, + 1.0, + 0.75 + ], + "idle_gap": [ + 1.0, + 1.0, + 0.8 + ], + "entropy": [ + 0.0, + 1.0, + 1.0 + ], + "speed": [ + 0.9, + 1.0, + 1.15 + ], + "dmg": [ + 0.5, + 1.0, + 1.6 + ], + "kirby_hp": [ + 6, + 6, + 6 + ] + }, + "kinds": { + "entropy": "continuous", + "dmg": "multiplier" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/specs/whispy_woods.spec.js b/environments/games/web/games/kirby_remake/specs/whispy_woods.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..15bd8f99d6b4960fae2bff3a5481af94bf07680d --- /dev/null +++ b/environments/games/web/games/kirby_remake/specs/whispy_woods.spec.js @@ -0,0 +1,349 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["whispy_woods"] = { + "schema": "bossbench/boss-spec@1", + "id": "whispy_woods", + "dims": "2d", + "family": "pogo2d", + "archetype": "Rooted tree (2D side view, never moves): blows air puffs along the floor and drops apples from its canopy that roll toward the player; it can only be hurt by inhaling an apple and spitting it back as a Star Bullet (6 hits in the original; 8 / 22 / 80 by tier)", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "idle", + "telegraph": "antic", + "active": "attack", + "recovery": "recover" + }, + "timing": { + "idle": { + "knob": "idle_gap" + }, + "telegraph": { + "knob": "telegraph", + "min": 0.05 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 0.0, + "telegraph": 0.0, + "active": 1.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "idle_timer", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": false + }, + "announce": { + "telegraph": "boss_{move}_antic", + "active": "boss_{move}" + }, + "moves": [ + { + "name": "puffs", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.18333333333333332, + "active": 0.26666666666666666, + "params": { + "count": 2, + "size": [ + 12, + 12 + ], + "spawn": [ + -16, + 24 + ], + "track": [ + [ + 8, + 1, + 0.25 + ], + [ + 8, + 2, + 0 + ], + [ + 8, + 3, + 0.25 + ], + [ + 8, + 3, + 0.5 + ], + [ + 0, + 3, + 0.75 + ] + ], + "extra_track": [ + [ + 2, + 6, + 0 + ], + [ + 2, + 6, + 1 + ], + [ + 2, + 3, + 2 + ], + [ + 1, + 1, + 1 + ], + [ + 1, + 0, + 0 + ], + [ + 1, + 1, + 0 + ], + [ + 2, + 3, + 0 + ], + [ + 2, + 6, + 0 + ] + ] + }, + "damage": 1, + "cue": "the mouth opens into an O, then an air puff shoots out low along the floor, drifting up or down", + "punish": "a puff cannot be inhaled; hop or float over it (or duck under one drifting up)" + }, + { + "name": "puff_burst", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.1, + "active": 0.2833333333333333, + "params": { + "count": 4, + "extra_active": 0.13333333333333333 + }, + "damage": 1, + "cue": "four puffs in quick succession, mouth snapping open each time", + "punish": "float above the floor until the burst passes" + }, + { + "name": "apples", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.4, + "active": 1.5, + "params": { + "count": 3, + "size": [ + 12, + 12 + ], + "x_px": [ + 48, + 24, + 40, + 56, + 72, + 88, + 19, + 77 + ], + "fall": [ + [ + 25, + 0, + 0 + ], + [ + 8, + 0, + -1 + ], + [ + 8, + 0, + -1.25 + ], + [ + 8, + 0, + -2 + ], + [ + 8, + 0, + -3 + ], + [ + 8, + 0, + -4 + ] + ], + "roll": [ + [ + 10, + 0.5, + 2 + ], + [ + 10, + 0.5, + 0.5 + ], + [ + 10, + 0.5, + -0.5 + ], + [ + 10, + 0.5, + -2 + ], + [ + 10, + 0.75, + 1.25 + ], + [ + 10, + 0.75, + 0.25 + ], + [ + 10, + 0.75, + -0.25 + ], + [ + 10, + 0.75, + -1.25 + ] + ], + "roll_loop": [ + [ + 10, + 0.75, + 0.5 + ], + [ + 10, + 0.75, + 0 + ], + [ + 10, + 0.75, + 0 + ], + [ + 10, + 0.75, + -0.5 + ] + ] + }, + "damage": 1, + "cue": "an apple blinks among the leaves, drops, then bounces along the floor toward the player", + "punish": "inhale the apple (hold J facing it) and spit it at the trunk - the only way to hurt the tree" + }, + { + "name": "drop", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.4, + "active": 0.8333333333333334, + "params": { + "gordo_size": [ + 12, + 12 + ], + "gordo_damage": 3, + "extra_only": true + }, + "damage": 3, + "cue": "Extra Game: a spiky ball, an apple, then either one, dropped in turn", + "punish": "the spiky ball cannot be inhaled and hurts 3 - only the apples are ammunition" + } + ], + "difficulty": { + "hp": [ + 8, + 22, + 80 + ], + "telegraph": [ + 1.3, + 1.0, + 0.8 + ], + "recovery": [ + 1.15, + 1.0, + 0.75 + ], + "idle_gap": [ + 1.0, + 1.0, + 0.8 + ], + "entropy": [ + 0.0, + 1.0, + 1.0 + ], + "speed": [ + 1.0, + 1.0, + 1.15 + ], + "dmg": [ + 0.5, + 1.0, + 1.5 + ], + "kirby_hp": [ + 6, + 6, + 6 + ] + }, + "kinds": { + "entropy": "continuous", + "dmg": "multiplier" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kirby_remake/touch.js b/environments/games/web/games/kirby_remake/touch.js new file mode 100644 index 0000000000000000000000000000000000000000..ae462da8dd41c28644eaf8f4e45e1784a1abc998 --- /dev/null +++ b/environments/games/web/games/kirby_remake/touch.js @@ -0,0 +1,48 @@ +// Touch pad for the play page (phones / tablets). Page-only presentation: it turns on-screen button presses into the +// same keydown / keyup events the keyboard sends (engine/input.js samples them per 33 ms sub-step), so live play, +// recordings and replays use exactly the same input path. Inert in Node and on pages without the game stage. +(function (g) { + if (typeof document === 'undefined' || !document.getElementById('stage') || !document.getElementById('play-actions')) return; + var doc = document; + var PADS = [ + ['tp-left', 'KeyA', '◀', 'Move left A'], ['tp-down', 'KeyS', '▼', 'Crouch / swallow S'], ['tp-right', 'KeyD', '▶', 'Move right D'], + ['tp-float', 'KeyW', 'Float', 'Float / close mouth W'], ['tp-jump', 'Space', 'Jump', 'Jump Space'], ['tp-suck', 'KeyJ', 'Inhale', 'Inhale / spit star J'] + ]; + var bar = doc.createElement('div'); bar.id = 'touchpad'; bar.setAttribute('aria-label', 'Touch controls'); + var left = doc.createElement('div'), right = doc.createElement('div'); + left.className = right.className = 'tp-group'; + var held = {}; // button id -> pointerId holding it + function send(type, code) { g.dispatchEvent(new KeyboardEvent(type, { code: code, bubbles: true, cancelable: true })); } + PADS.forEach(function (p, i) { + var b = doc.createElement('button'); + b.type = 'button'; b.id = p[0]; b.className = 'tp-btn'; b.textContent = p[2]; b.title = p[3]; b.setAttribute('aria-label', p[3]); + function down(e) { + e.preventDefault(); + if (held[p[0]] != null) return; + held[p[0]] = e.pointerId == null ? 0 : e.pointerId; + if (b.setPointerCapture && e.pointerId != null) { try { b.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointer */ } } + b.classList.add('on'); send('keydown', p[1]); + } + function up(e) { + if (held[p[0]] == null) return; + if (e && e.pointerId != null && held[p[0]] !== e.pointerId) return; + held[p[0]] = null; b.classList.remove('on'); send('keyup', p[1]); + } + b.addEventListener('pointerdown', down); + b.addEventListener('pointerup', up); + b.addEventListener('pointercancel', up); + b.addEventListener('lostpointercapture', up); + b.addEventListener('contextmenu', function (e) { e.preventDefault(); }); + (i < 3 ? left : right).appendChild(b); + }); + bar.appendChild(left); bar.appendChild(right); + var actions = doc.getElementById('play-actions'); + actions.parentNode.insertBefore(bar, actions); + g.addEventListener('blur', function () { + PADS.forEach(function (p) { if (held[p[0]] != null) { held[p[0]] = null; doc.getElementById(p[0]).classList.remove('on'); send('keyup', p[1]); } }); + }); + // show only while a fight is on screen (the shared shell toggles #play-actions) + function sync() { bar.classList.toggle('live', !actions.classList.contains('hidden')); } + new MutationObserver(sync).observe(actions, { attributes: true, attributeFilter: ['class'] }); + sync(); +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kof_remake/arena.js b/environments/games/web/games/kof_remake/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..c8fdec0088d9f3b2ff523b0bebec2376fd86a7c2 --- /dev/null +++ b/environments/games/web/games/kof_remake/arena.js @@ -0,0 +1 @@ +(function(g){g.BB.ARENA={W:27,H:15};})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/art/scenes.js b/environments/games/web/games/kof_remake/art/scenes.js new file mode 100644 index 0000000000000000000000000000000000000000..bd08929ba54355162fdb8d0d17f3653381eb7cc3 --- /dev/null +++ b/environments/games/web/games/kof_remake/art/scenes.js @@ -0,0 +1,89 @@ +// Original procedural stages (cached; deterministic; never consume the simulation RNG). +// kof97/iori: night rooftop over a neon city; kof97/orochi_iori: red-moon shrine courtyard; kof97/orochi: the seal +// altar under a pale sky (the final-boss stage). Floor line is the engine's FLOOR (y = 466 px). +(function(g){ + var BB=g.BB,A=BB.ART,TAU=Math.PI*2; + function rnd(i){var s=Math.sin(i*127.1+311.7)*43758.5453;return s-Math.floor(s);} + function sky(x,stops){var gr=x.createLinearGradient(0,0,0,466);stops.forEach(function(s){gr.addColorStop(s[0],s[1]);});x.fillStyle=gr;x.fillRect(0,0,854,480);} + function stars(x,n,col){x.fillStyle=col;for(var i=0;i.92?1.6:.9;x.globalAlpha=.4+rnd(i+3)*.6;x.fillRect(px,py,r,r);}x.globalAlpha=1;} + function moon(x,cx,cy,r,col,glow){var gr=x.createRadialGradient(cx,cy,r*.6,cx,cy,r*3);gr.addColorStop(0,glow);gr.addColorStop(1,'rgba(0,0,0,0)');x.fillStyle=gr;x.fillRect(cx-r*3,cy-r*3,r*6,r*6);x.fillStyle=col;x.beginPath();x.arc(cx,cy,r,0,TAU);x.fill();} + function floorBand(x,top,c0,c1,line){var fl=x.createLinearGradient(0,top,0,480);fl.addColorStop(0,c0);fl.addColorStop(1,c1);x.fillStyle=fl;x.fillRect(0,top,854,480-top); + x.strokeStyle=line;x.lineWidth=1;for(var i=-12;i<=24;i++){x.beginPath();x.moveTo(427+i*36,top);x.lineTo(427+i*36*1.9,480);x.stroke();} + for(var j=0;j<4;j++){var y=top+(480-top)*Math.pow(j/4,1.6);x.beginPath();x.moveTo(0,y);x.lineTo(854,y);x.stroke();}} + A.scene=function(doc,id){ + var bg=doc.createElement('canvas'),fg=doc.createElement('canvas');bg.width=fg.width=854;bg.height=fg.height=480; + var x=bg.getContext('2d'),i,j; + if(id==='kof97/orochi'){ + sky(x,[[0,'#0c1427'],[.55,'#25423f'],[1,'#5d8a7b']]);stars(x,90,'#e6fff4'); + moon(x,427,170,58,'#e8fff2','rgba(200,255,230,.35)'); + x.strokeStyle='rgba(206,245,226,.22)';x.lineWidth=2;for(j=0;j<4;j++){x.beginPath();x.arc(427,212,98+j*36,0,TAU);x.stroke();} + for(i=0;i<12;i++){var an=i*TAU/12;x.beginPath();x.moveTo(427+Math.cos(an)*96,212+Math.sin(an)*96);x.lineTo(427+Math.cos(an)*206,212+Math.sin(an)*206);x.stroke();} + // broken stone pillars of the seal altar + for(i=0;i<9;i++){var px=18+i*104+(i%2)*14,ph=110+rnd(i)*80,py=430-ph;x.fillStyle='#12262a';x.fillRect(px,py,34,ph);x.fillStyle='#2f5551';x.fillRect(px-4,py,42,8);x.fillStyle='rgba(180,255,220,.08)';x.fillRect(px+4,py+8,6,ph-8); + if(i%3===1){x.fillStyle='#12262a';x.beginPath();x.moveTo(px,py);x.lineTo(px+12,py-14);x.lineTo(px+22,py);x.fill();}} + // shimenawa rope across the back + x.strokeStyle='#cbb98a';x.lineWidth=5;x.beginPath();x.moveTo(0,300);x.quadraticCurveTo(427,350,854,300);x.stroke(); + for(i=0;i<7;i++){var sx2=80+i*115,sy2=300+Math.sin(i/6*Math.PI)*36;x.fillStyle='#f2efe4';x.beginPath();x.moveTo(sx2,sy2);x.lineTo(sx2+8,sy2+14);x.lineTo(sx2,sy2+22);x.lineTo(sx2+8,sy2+34);x.lineTo(sx2-2,sy2+34);x.lineTo(sx2-8,sy2+20);x.fill();} + floorBand(x,430,'#3d6158','#0d1a1c','rgba(200,240,220,.13)'); + x.strokeStyle='rgba(210,255,235,.35)';x.lineWidth=2;x.beginPath();x.ellipse(427,452,300,22,0,0,TAU);x.stroke(); + }else if(id==='kof97/orochi_yashiro'){ + // "Dry Earth": a cracked wasteland under a dust-orange sky, broken stage scaffolding of Yashiro's band + sky(x,[[0,'#1d0e08'],[.55,'#5a2a12'],[1,'#b8682c']]);stars(x,30,'#ffe2c0'); + moon(x,210,150,62,'#f1a35a','rgba(255,170,90,.32)'); + for(i=0;i<11;i++){var mx2=i*86-30,mh=50+rnd(i+21)*80;x.fillStyle=i%2?'#2a1309':'#331a0c';x.beginPath();x.moveTo(mx2,430);x.lineTo(mx2+20,430-mh);x.lineTo(mx2+70,430-mh*.7);x.lineTo(mx2+110,430);x.fill();} + x.strokeStyle='#4a2a16';x.lineWidth=5;for(i=0;i<3;i++){var sx3=520+i*96;x.beginPath();x.moveTo(sx3,430);x.lineTo(sx3+30,250);x.lineTo(sx3+60,430);x.stroke();} + x.beginPath();x.moveTo(500,262);x.lineTo(800,262);x.stroke();x.fillStyle='#1a0c06';x.fillRect(610,230,42,34);x.fillStyle='rgba(255,150,70,.5)';x.fillRect(616,236,30,6); + floorBand(x,430,'#6b3a1c','#1b0c05','rgba(255,190,140,.12)'); + x.strokeStyle='rgba(30,12,4,.7)';x.lineWidth=2;for(i=0;i<16;i++){var cx3=rnd(i+60)*854,cy3=440+rnd(i+70)*34;x.beginPath();x.moveTo(cx3,cy3);x.lineTo(cx3+12+rnd(i)*20,cy3+6);x.lineTo(cx3+20+rnd(i+1)*26,cy3+2);x.stroke();} + }else if(id==='kof97/orochi_shermie'){ + // "Raging Lightning": a storm over a ruined plaza, a lightning fork frozen in the sky + sky(x,[[0,'#070b1c'],[.6,'#1c2350'],[1,'#3a3f7a']]);stars(x,40,'#d6dcff'); + x.strokeStyle='rgba(190,200,255,.55)';x.lineWidth=3;x.beginPath();x.moveTo(600,0);x.lineTo(575,60);x.lineTo(610,95);x.lineTo(560,170);x.lineTo(585,190);x.lineTo(540,260);x.stroke(); + x.lineWidth=1.5;x.beginPath();x.moveTo(610,95);x.lineTo(650,140);x.lineTo(640,175);x.stroke(); + for(i=0;i<6;i++){var cx4=i*170-40;x.fillStyle='rgba(40,46,92,.9)';x.beginPath();x.ellipse(cx4,70+rnd(i+5)*40,160,40,0,0,TAU);x.fill();} + for(i=0;i<7;i++){var px4=40+i*124,ph4=90+rnd(i+31)*90;x.fillStyle='#161a36';x.fillRect(px4,430-ph4,26,ph4);x.fillStyle='#262c58';x.fillRect(px4-6,430-ph4,38,8);if(i%2){x.fillStyle='#161a36';x.fillRect(px4-10,430-ph4-14,46,6);}} + floorBand(x,430,'#30366a','#0b0d1f','rgba(190,200,255,.13)'); + }else if(id==='kof97/orochi_chris'){ + // "Flames of Destiny": a burning shrine courtyard at night, blue-violet flames on stone braziers + sky(x,[[0,'#080614'],[.5,'#1c1033'],[1,'#3f1d4c']]);stars(x,60,'#e6dcff'); + moon(x,427,120,40,'#d5c8ff','rgba(180,150,255,.3)'); + x.fillStyle='#120a1d';x.fillRect(250,250,354,180);x.beginPath();x.moveTo(220,256);x.lineTo(427,190);x.lineTo(634,256);x.fill();x.fillStyle='#1d1230';x.fillRect(300,300,254,130); + for(i=0;i<4;i++){var bx4=100+i*218;x.fillStyle='#231735';x.fillRect(bx4-14,360,28,70);x.fillRect(bx4-22,352,44,10); + x.fillStyle='rgba(120,140,255,.35)';x.beginPath();x.ellipse(bx4,340,20,26,0,0,TAU);x.fill();x.fillStyle='#9fb2ff';x.beginPath();x.moveTo(bx4-9,352);x.quadraticCurveTo(bx4-4,326,bx4,318);x.quadraticCurveTo(bx4+6,330,bx4+9,352);x.fill();} + floorBand(x,430,'#3a2a52','#0d0716','rgba(200,190,255,.12)'); + }else if(id==='kof97/orochi_iori'){ + sky(x,[[0,'#12060f'],[.5,'#3a0d1d'],[1,'#7a2335']]);stars(x,50,'#ffd9e0'); + moon(x,640,140,54,'#e2465f','rgba(255,70,100,.35)'); + // torii gate + shrine silhouettes + x.fillStyle='#14070d';x.fillRect(150,250,22,180);x.fillRect(330,250,22,180);x.fillRect(120,236,262,16);x.fillRect(140,266,222,10); + for(i=0;i<14;i++){var tx=i*66-20,th=60+rnd(i+5)*70;x.fillStyle=i%2?'#1c0a12':'#220c16';x.beginPath();x.moveTo(tx,430);x.lineTo(tx+33,430-th);x.lineTo(tx+66,430);x.fill();} + // lanterns + for(i=0;i<6;i++){var lx=470+i*64,ly=330+(i%2)*10;x.fillStyle='rgba(255,90,90,.25)';x.beginPath();x.arc(lx,ly,16,0,TAU);x.fill();x.fillStyle='#ff6f6f';x.fillRect(lx-5,ly-8,10,16);} + floorBand(x,430,'#4a1f2b','#120509','rgba(255,170,190,.12)'); + // blood-red petals + x.fillStyle='rgba(255,90,120,.5)';for(i=0;i<40;i++){x.beginPath();x.ellipse(rnd(i+40)*854,436+rnd(i+80)*40,3,1.4,rnd(i)*3,0,TAU);x.fill();} + }else{ + sky(x,[[0,'#0b0f22'],[.6,'#1d2b47'],[1,'#3d5674']]);stars(x,70,'#dfe8ff'); + moon(x,650,128,46,'#f4e3cf','rgba(255,230,200,.25)'); + for(var layer=0;layer<3;layer++)for(i=0;i<22;i++){ + var bx=i*44+layer*17-10,bh=50+rnd(i*3+layer)*130,by=430-bh+layer*8;x.fillStyle=['#121a2b','#172238','#1d2b44'][layer];x.fillRect(bx,by,36,bh); + for(j=0;j<10;j++)if(rnd(i*13+j+layer*7)>.55){x.fillStyle=rnd(j+i)>.5?'rgba(120,220,215,.55)':'rgba(255,200,120,.45)';x.fillRect(bx+5+(j%3)*10,by+10+Math.floor(j/3)*16,5,7);} + } + // neon sign + rooftop railing + x.fillStyle='#3a1640';x.fillRect(58,236,128,44);x.strokeStyle='#ff5fa2';x.lineWidth=2;x.strokeRect(62,240,120,36);x.fillStyle='#ffd1ea';x.font='bold 20px monospace';x.fillText("KOF '97",76,265); + x.strokeStyle='#4b6474';x.lineWidth=3;x.beginPath();x.moveTo(0,392);x.lineTo(854,392);x.stroke();for(i=0;i<29;i++){x.fillStyle='#3a5060';x.fillRect(i*31,394,3,36);} + floorBand(x,430,'#46586a','#121826','rgba(200,220,230,.14)'); + } + // foreground: thin vignette only (fighters stay readable) + var y=fg.getContext('2d'),vg=y.createRadialGradient(427,260,280,427,260,560);vg.addColorStop(0,'rgba(0,0,0,0)');vg.addColorStop(1,'rgba(0,0,0,.35)');y.fillStyle=vg;y.fillRect(0,0,854,480); + return {bg:bg,fg:fg}; + }; + A.ambient=function(x,id,t){x.save(); + if(id==='kof97/orochi'){x.fillStyle='rgba(228,255,236,.5)';for(var i=0;i<22;i++){var px=(i*139+Math.sin(t*.3+i)*20)%854,py=440-((i*53+t*22)%330);x.globalAlpha=.25+.5*Math.abs(Math.sin(t+i));x.fillRect(px,py,2,2);}} + else if(id==='kof97/orochi_yashiro'){x.fillStyle='rgba(255,190,130,.4)';for(var i3=0;i3<18;i3++){var px3=(i3*157+t*18)%854,py3=300+(i3*37+Math.sin(t+i3)*30)%150;x.globalAlpha=.3+.3*Math.abs(Math.sin(t*.7+i3));x.fillRect(px3,py3,3,2);}x.globalAlpha=1;} + else if(id==='kof97/orochi_shermie'){var fl=Math.floor(t*1.7)%9===0?(1-((t*1.7)%1))*.18:0;if(fl>0){x.fillStyle='rgba(210,220,255,'+fl+')';x.fillRect(0,0,854,480);}x.fillStyle='rgba(170,180,255,.45)';for(var i4=0;i4<30;i4++){var px5=(i4*97+t*60)%854,py5=(i4*53+t*300)%430;x.fillRect(px5,py5,1,9);}} + else if(id==='kof97/orochi_chris'){x.fillStyle='rgba(160,170,255,.6)';for(var i5=0;i5<14;i5++){var px6=(i5*129+Math.sin(t+i5)*14)%854,py6=430-((i5*41+t*40)%260);x.globalAlpha=.25+.35*Math.abs(Math.sin(t*2+i5));x.fillRect(px6,py6,2,3);}x.globalAlpha=1;} + else if(id==='kof97/orochi_iori'){x.fillStyle='rgba(255,120,150,.6)';for(i=0;i<16;i++){px=(i*173+t*30+Math.sin(t+i)*30)%854;py=(i*61+t*25)%430;x.globalAlpha=.5;x.beginPath();x.ellipse(px,py,3,1.5,t+i,0,TAU);x.fill();}} + else{x.fillStyle='rgba(143,226,229,.25)';for(i=0;i<14;i++){px=(i*139+Math.sin(t*.18+i)*16)%854;py=120+(i*59+t*9)%280;x.fillRect(px,py,2,2);}} + x.restore();}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/bosses/fighter_ai.js b/environments/games/web/games/kof_remake/bosses/fighter_ai.js new file mode 100644 index 0000000000000000000000000000000000000000..263bdbd4084ce40dba4f270d1bb68760941d305b --- /dev/null +++ b/environments/games/web/games/kof_remake/bosses/fighter_ai.js @@ -0,0 +1,97 @@ +// Opponents share the player's collision, guard, meter and move rules. Decisions use delayed observations. +(function(g){ + var BB=g.BB,KF=BB.KOF; + // Furthest centre distance at which a move can still connect (hitbox front + the target's half width + travel). + // Rules v7: v6 drew normals uniformly from a pool at any distance <= 4.0 u, so ~half of them (a 2.9 u jab at 3.8 u) + // could not reach and were whiff-punished for free. + KF.reachOf=function(id,w){var a=KF.MOVES[id];if(!a)return 0;if(a.remote||a.fullscreen||a.projectile)return 99;return .15+a.reach+(w||1.386)/2+(a.travel?a.travel*a.active/60:0);}; + // Throw reach for the Orochi Team's command throws: the grab box reaches a.reach from the centre (KF.attackBoxes). + KF.grabReach=function(id,w){var a=KF.MOVES[id];return a.reach+(w||1.386)/2+(a.travel?a.travel*a.active/60:0);}; // travel only during active frames + function observe(p,t){return {t:t,x:p.x,y:p.y,vx:p.vx,grounded:p.grounded,move:p.move,age:p.age,st:p.st,crouching:p.crouching,shots:p.shots.map(function(s){return {x:s.x,vx:s.vx};})};} + KF.makeOpponent=function(kind,SPEC){ + function Opponent(){} + var P=Opponent.prototype;P.id=kind; + BB.bossKit(P,SPEC,{idle:'idle',crouch:'idle',air:'idle',startup:'telegraph',active:'active',recovery:'recovery',stun:'recovery',dead:'recovery'}); + // Tier knobs (rules v7): members (1-3, rounded) x member life `hp`, and the opponent's damage multiplier `dmg`. + // Orochi Team opponents (2026-11-03) plug in their own decide / act through KF.TEAM_AI[kind]; others: generic code. + function team(){return KF.TEAM_AI&&KF.TEAM_AI[kind]||null;} + P.reset=function(c){KF.reset(this,c,kind,false);this.k=BB.knobs(SPEC.difficulty,c.d);KF.setupTeam(this,Math.round(this.k.members||1),Math.round(this.k.hp));this.dmgScale=this.k.dmg||1;this.choiceCount=0;this.onRound(c);this.nextDecision=12;if(team())team().reset(this,c);}; + P.onRound=function(c){this.seen=[];this.perceived=null;this.nextDecision=c.t+12;this.intent={};this.aiFollow=null;this.planMove=null;this.gcTried=false;this.techAt=-1;this.lastMove=null;this.lastAge=0;this.stunPrev=0;this.pressureAt=-999;if(team())team().forget(this,c);}; + P.update=function(c){ + var f=this,p=c.body;if(f.roundPause>0){KF.update(f,c,{},p);return;} // round break + f.seen.push(observe(p,c.t)); + var delay=Math.round(f.k.reaction);while(f.seen.length>1&&f.seen[1].t<=c.t-delay)f.seen.shift(); + f.perceived=f.seen[0];var o=f.perceived; + // ADVANCED guard cancel (S02): once per blockstun, spend a stock on a C+D blowback or an A+B roll. + if(f.stun>0&&f.stunType==='block'&&f.stocks>0&&!f.gcTried){f.gcTried=true;var g=c.rng.random(); + if(gf.x?'right':'left']=true;f.nextDecision=c.t+6;}} + if(!f.stun)f.gcTried=false; + // Re-decide at once when a newly observed attack starts (still behind the reaction delay) and on wake-up + // from hit/block stun (the opponent knows its own state); otherwise decisions keep their cadence. + if(o.move&&(o.move!==f.lastMove||(o.age||0)0&&f.stun===0)f.nextDecision=Math.min(f.nextDecision,c.t); + f.stunPrev=f.stun; + // Pressure memory (rules v6): when the observed opponent attacked nearby recently, the CPU respects it and + // guards (crouching unless the attacker is airborne) instead of walking into button presses. + if(o.move&&o.st!=='recovery'&&Math.abs(o.x-f.x)<3.6)f.pressureAt=c.t; + var T=team();if(T&&T.observe)T.observe(f,c,o,p); + if(c.t>=f.nextDecision&&T){f.nextDecision=c.t+Math.round(f.k.decision);f.choiceCount++;f.intent={};f.planMove=null;T.decide(f,c,o,p);} + else if(c.t>=f.nextDecision){ + f.nextDecision=c.t+Math.round(f.k.decision);f.choiceCount++;f.intent={};f.planMove=null; + var dist=Math.abs(o.x-f.x),toward=o.x>f.x?'right':'left',back=o.x>f.x?'left':'right',r=c.rng.random(),r2=c.rng.random(); + var wild=kind==='orochi_iori',oro=kind==='orochi',pressured=c.t-f.pressureAt<50&&dist<3.4,safeWalk=c.t-f.pressureAt>=40||dist>5.4; + // No reads of human keys or future action. Startup is recognized only after the reaction delay. + // v8: the CPU's own Yasakazuki has bound the player (it knows its own shot hit): close in and hit before it wears off. + if(p.stun>0&&p.stunType==='bind'){if(dist>KF.reachOf('heavy_punch',p.w))f.intent[toward]=true;else f.planMove=r<.5&&f.stocks>0?'yaotome':'heavy_punch';}else + // v8: Orochi sometimes answers an attack seen in its startup with a barrier (counter) instead of guarding + if(oro&&o.move&&o.st==='startup'&&dist<3.2&&r0&&r2<.4?'soul_grab':'oro_throw'):'heavy_punch'):(r2<.5?'aoihana':'heavy_punch'); // punish observed recovery (v8: the soul grab costs a stock) + else if(pressured&&!oro&&o.move&&o.st!=='recovery'&&dist<3.2&&r0;})){ + if(oro&&r<.65)f.planMove='mirror';else if(r<.35)f.intent.roll=true;else {f.intent[back]=true;f.intent.down=true;} + }else if(!o.grounded&&dist<3.3&&r=2&&!f.maxMode&&dist<4.6&&r4.0){ + if(oro){f.planMove=r<.42?'pillar':r<.78?'harae':null;if(!f.planMove)f.intent[toward]=true;} + // Riot of the Blood: rush in; Yami Barai is back in v8 (S19 lists it; v7 removed it per the 10-31 task brief) but used + // less than by Iori, mostly when walking in is not safe. + else if(wild){if(safeWalk&&r>=.12){f.intent[toward]=true;f.intent.run=true;if(r>.78)f.intent.jump=true;}else if(r<.4)f.planMove='yami_barai';else if(r2<.45){f.intent[toward]=true;f.intent.jump=true;}else f.intent[back]=true;} + else if(r<.28||!safeWalk&&r<.55)f.planMove='yami_barai';else if(safeWalk){f.intent[toward]=true;if(r>.82)f.intent.jump=true;}else if(r2<.35){f.intent[toward]=true;f.intent.jump=true;}else f.intent[back]=true; + }else if(dist<1.55&&r<.12)f.planMove=oro?'oro_throw':'scum_gale'; // v8: Orochi's close grab = his untechable normal throw + else if(oro&&f.stocks>0&&o.grounded&&dist<4.2&&!(o.move&&o.st!=='recovery')&&r<.1)f.planMove='soul_grab'; // v8: pull-in super, S28 + else if(r=dist;}); + f.planMove=pool.length?pool[Math.floor(c.rng.random()*pool.length)]:null;if(!pool.length)f.intent[toward]=true; // nothing reaches: close in + if(f.stocks>0&&r<(f.maxMode?.42:.2))f.planMove=oro?'marokare':dist>2.6&&r2<.3?'yasakazuki':'yaotome'; + }else if(dist<2.8){f.intent[back]=true;f.intent.down=o.grounded&&r>.4;} + else if(safeWalk){f.intent[toward]=true;if(wild&&r>.9)f.intent.run=true;} + else if(r2<.35){f.intent[toward]=true;f.intent.jump=true;}else {f.intent[back]=true;f.intent.down=o.grounded&&r2<.75;} // approach discipline: no walking into button presses + } + // Normal-throw escape: a fresh heavy press 3 ticks into the window, with probability k.tech (S02: throw escape exists). + if(f.throwPending&&!f.throwPending.seen){f.throwPending.seen=true;f.techAt=c.rng.random()0||f.stun>0||f.landLag>0||KF.life(f)<=0)return; + if(T){T.act(f,c,o,p);return;} + if(f.action&&f.action.connected&&f.action.cancel){ + var chain={aoihana:'aoihana2',aoihana2:'aoihana3'},next=chain[f.action.id]; + if(next&&f.age>f.action.start+f.action.active+1&&c.rng.random()0?'loss':'timeout';if(pd)return 'loss';if(bd&&b.floor<=0)return 'win'; + return b.verdict||null; + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/bosses/iori.js b/environments/games/web/games/kof_remake/bosses/iori.js new file mode 100644 index 0000000000000000000000000000000000000000..a78d8189fa98edcf6e5d2164e9edc1ce8a78d06b --- /dev/null +++ b/environments/games/web/games/kof_remake/bosses/iori.js @@ -0,0 +1 @@ +(function(g){var BB=g.BB,Boss=BB.KOF.makeOpponent('iori',BB.SPECS.iori);BB.CASES=BB.CASES||{};BB.CASES['kof97/iori']={title:'Violet Claw',Body:BB.KOFPlayer,Boss:Boss,arena:'neon_rooftop',outcome:BB.KOF.outcome};})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/bosses/orochi.js b/environments/games/web/games/kof_remake/bosses/orochi.js new file mode 100644 index 0000000000000000000000000000000000000000..c56d8012f99f9d5bdd039d018212ae32d7151fce --- /dev/null +++ b/environments/games/web/games/kof_remake/bosses/orochi.js @@ -0,0 +1 @@ +(function(g){var BB=g.BB,Boss=BB.KOF.makeOpponent('orochi',BB.SPECS.orochi);BB.CASES['kof97/orochi']={title:'Radiant Deity',Body:BB.KOFPlayer,Boss:Boss,arena:'celestial_seal',outcome:BB.KOF.outcome};})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/bosses/orochi_chris.js b/environments/games/web/games/kof_remake/bosses/orochi_chris.js new file mode 100644 index 0000000000000000000000000000000000000000..b63bf96f52f5304adcd5b975397efa8599667fbd --- /dev/null +++ b/environments/games/web/games/kof_remake/bosses/orochi_chris.js @@ -0,0 +1 @@ +(function(g){var BB=g.BB,Boss=BB.KOF.makeOpponent('orochi_chris',BB.SPECS.orochi_chris);BB.CASES['kof97/orochi_chris']={title:'Blaze Youth',Body:BB.KOFPlayer,Boss:Boss,arena:'flames_of_destiny',outcome:BB.KOF.outcome};})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/bosses/orochi_iori.js b/environments/games/web/games/kof_remake/bosses/orochi_iori.js new file mode 100644 index 0000000000000000000000000000000000000000..5ae03f79ac3a800ef89f4f61f295878ce05d94af --- /dev/null +++ b/environments/games/web/games/kof_remake/bosses/orochi_iori.js @@ -0,0 +1 @@ +(function(g){var BB=g.BB,Boss=BB.KOF.makeOpponent('orochi_iori',BB.SPECS.orochi_iori);BB.CASES['kof97/orochi_iori']={title:'Frenzied Claw',Body:BB.KOFPlayer,Boss:Boss,arena:'red_moon',outcome:BB.KOF.outcome};})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/bosses/orochi_shermie.js b/environments/games/web/games/kof_remake/bosses/orochi_shermie.js new file mode 100644 index 0000000000000000000000000000000000000000..95f9fd83b605e88eeaee5c4cac9bf3278af9ff09 --- /dev/null +++ b/environments/games/web/games/kof_remake/bosses/orochi_shermie.js @@ -0,0 +1 @@ +(function(g){var BB=g.BB,Boss=BB.KOF.makeOpponent('orochi_shermie',BB.SPECS.orochi_shermie);BB.CASES['kof97/orochi_shermie']={title:'Storm Dancer',Body:BB.KOFPlayer,Boss:Boss,arena:'raging_lightning',outcome:BB.KOF.outcome};})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/bosses/orochi_team_ai.js b/environments/games/web/games/kof_remake/bosses/orochi_team_ai.js new file mode 100644 index 0000000000000000000000000000000000000000..65eeaa105d55fec7d4bd3299c46a89c2cdbaef0f --- /dev/null +++ b/environments/games/web/games/kof_remake/bosses/orochi_team_ai.js @@ -0,0 +1,146 @@ +// Orochi Team opponents (kof97/orochi_yashiro, orochi_shermie, orochi_chris; scenes added 2026-11-03). +// Plugged into KF.makeOpponent through KF.TEAM_AI[kind]: decide() replaces the generic decision block, act() the generic +// post-update block, reset() / forget() handle the extra AI state. Same delayed observation, reaction delay, guard-cancel +// and throw-escape code as the other opponents (bosses/fighter_ai.js); no reads of the player's keys or future actions. +// Behaviour sources: S23 (the CPU in '97: Yashiro guards very solidly and walks in for reactive command throws; Shermie +// spams Mugetsu no Raiun at varying positions and answers jumps with Ankoku Raikouken when she has a stock; Chris has no +// notable rhythm, sometimes Shishi o Kamu Honoo on wake-up, Taiyo-then-Kagami, presses forward when you over-guard), +// S20-S22 (move functions). Probabilities are the configured probabilities (specs/orochi_*.spec.js); all of them are approximations. +(function(g){ + var BB=g.BB,KF=BB.KOF,T=KF.TEAM_AI=KF.TEAM_AI||{}; + function side(f,o){return {dist:Math.abs(o.x-f.x),toward:o.x>f.x?'right':'left',back:o.x>f.x?'left':'right'};} + function guard(f,o,s,low){f.intent[s.back]=true;f.intent.down=!!low&&o.grounded;} + function reach(f,id,p){return KF.MOVES[id].throw?KF.grabReach(id,p.w):KF.reachOf(id,p.w);} + function plan(f,id,extra){f.planMove=id;f.planExtra=extra||null;} + function pool(f,p,dist,ids){return ids.filter(function(id){return reach(f,id,p)>=dist;});} + function pick(c,list){return list[Math.floor(c.rng.random()*list.length)];} + function pressured(f,c,dist){return c.t-f.pressureAt<50&&dist<3.8;} + // Close in when the opponent has not been applying recent pressure. + function approach(f,c,o,s,r2){if(c.t-f.pressureAt>=40||s.dist>5.4){f.intent[s.toward]=true;return;}if(r2<.3){f.intent[s.toward]=true;f.intent.jump=true;}else guard(f,o,s,o.grounded&&r2<.75);} + // Shared post-update: start the planned move when free; a connected normal may be canceled into the follow-up + // (S02 combos: normal -> special, including command throws); an airborne CPU uses its air attack near the opponent. + function act(f,c,o,p,follow,air){ + var a=f.action; + if(a&&a.connected&&a.cancel&&a.gnormal&&!f.followTried){f.followTried=true;var nx=follow(f,c,o,p,p.stun>0&&p.stunType==='hit');if(nx&&c.rng.random()KF.grabReach(f.planMove,p.w)){f.planMove=null;f.planExtra=null;f.nextDecision=Math.min(f.nextDecision,c.t+1);return;} + if(!a&&f.planMove&&f.grounded){var id=f.planMove,ex=f.planExtra;f.planMove=null;f.planExtra=null;KF.start(f,c,id,{x:o.x},ex||undefined);return;} + if(!f.grounded&&!a&&f.vy<4&&Math.abs(o.x-f.x)<2.9)KF.start(f,c,air,p); + } + function resetState(f){f.planExtra=null;f.followTried=false;} + function forgetState(f){f.planExtra=null;} + + // ---- Yashiro, "the Dry Earth": all specials are throws in '97 (S20/S21); very solid guard, reactive walking throws (S23) + function fastView(f,o){var d=Math.round(f.k.grab_react||0),n=f.seen.length;return d>0&&n>1?f.seen[Math.max(0,n-1-d)]:o;} + T.orochi_yashiro={ + // lastKujiku must be cleared here too: an env reused for a second episode kept the last one's value (U4, 2026-11-03) + reset:function(f){resetState(f);f.walkGrab=null;f.lastKujiku=0;},forget:function(f){forgetState(f);f.walkGrab=null;f.lastKujiku=0;}, + observe:function(f){if(f.stun>0)f.walkGrab=null;}, // a walk-in that gets hit is abandoned + decide:function(f,c,o,p){ + var s=side(f,o),dist=s.dist,r=c.rng.random(),r2=c.rng.random(); + if(f.walkGrab){f.intent[s.toward]=true;return;} // still walking in for a committed throw (act() resolves it) + var q=fastView(f,o),qd=Math.abs(q.x-f.x); // the super-reaction view used for throw decisions only + // walking command throw: a grounded opponent within ~3 u that is not in an active attack -> walk in, throw on arrival + if(qd=reach(f,'museru_daichi',p)-.1&&q.grounded&&(!q.move||q.st==='recovery')&&r0&&r2<.35?(r2<.2?'ankoku_jigoku':'araburu_daichi'):r2<.68?'museru_daichi':'niragu_daichi';f.walkGrab={id:id,until:c.t+14};f.intent[s.toward]=true;return;} + // A quick walk-in throw can catch a grounded opponent during move startup. + if(qd0&&r2<.35)plan(f,r2<.2?'ankoku_jigoku':'araburu_daichi');else plan(f,r2<.68?'museru_daichi':'niragu_daichi');return;} + // an observed attack nearby: his guard is extremely solid (S23 "guard is unusually strong") + if(o.move&&o.st!=='recovery'&&dist<4.4&&r mostly guard (standing / air), sometimes a heavy normal + if(!o.grounded&&dist<4.6){if(r=dist)plan(f,'heavy_punch');else guard(f,o,s,false);return;} + if(pressured(f,c,dist)&&r4.6){ + if(f.stocks>0&&r9&&r28&&r2<.3)f.intent.run=true;return;} + // mid range against an opponent that is not attacking: rushing German suplex or the leaping grab (S20/S21) + if(dist>2.4&&o.grounded&&!(o.move&&o.st!=='recovery')&&r throw; airborne / too slow -> give up + if(!q.grounded||c.t>w.until||f.action){f.walkGrab=null;f.intent={};f.nextDecision=Math.min(f.nextDecision,c.t+1);} + else if(d<=reach(f,w.id,p)-.05&&f.grounded){f.walkGrab=null;f.intent={};KF.start(f,c,w.id,{x:q.x});return;}} + act(f,c,o,p,function(f2,c2,o2,p2,hit){return hit&&Math.abs(o.x-f2.x)0&&p.stunType==='hit'&&!f.planMove){f.lastKujiku=0;plan(f,'museru_daichi');} + if(f.action&&f.action.id==='kujiku_daichi'&&f.action.connected&&!f.lastKujiku)f.lastKujiku=c.t; + if(!f.action||f.action.id!=='kujiku_daichi'){if(f.lastKujiku&&c.t-f.lastKujiku>=30)f.lastKujiku=0;}} + }; + + // ---- Shermie, "the Raging Lightning": keep-away with the placed lightning orb, short shot, fast anti-air super; + // weak at close range and against jumps without a stock (S22/S23) + // Mugetsu no Raiun placement by button (S21/S22 "placement varies by button"): near/far x low/high (approximation). + var ORB=[{placeDist:3.2,orbY:1.0},{placeDist:5.2,orbY:1.0},{placeDist:2.8,orbY:3.11},{placeDist:4.8,orbY:3.11}]; + T.orochi_shermie={ + reset:resetState,forget:forgetState, + decide:function(f,c,o,p){ + var s=side(f,o),dist=s.dist,r=c.rng.random(),r2=c.rng.random(); + // a jump near her: Ankoku Raikouken with a stock (S23 "uses it with superhuman reactions"), otherwise a weak normal or guard + if(!o.grounded&&dist<3.9){if(f.stocks>0&&r=dist)plan(f,'heavy_punch');else guard(f,o,s,false);return;} + if(o.move&&o.st!=='recovery'&&dist<3.9&&r6.2){f.intent[s.toward]=true;if(dist>9&&r2<.3)f.intent.jump=true;return;} + if(r0&&dist<6&&r27){f.intent[s.toward]=true;return;} + if(pressured(f,c,dist)&&r0)f.wasDown=true;}, + decide:function(f,c,o,p){ + var s=side(f,o),dist=s.dist,r=c.rng.random(),r2=c.rng.random(); + // a pattern queued after Taiyo o Iru Honoo: rush in with Kagami o Hofuru Honoo once it is out (S23) + if(f.followUp==='kagami'){f.followUp=null;if(dist<4.2&&dist>1.2){plan(f,'kagami');return;}} + if(!o.grounded&&dist<3.4&&r=3; + if(dist<1.7&&o.grounded&&!(o.move&&o.st!=='recovery')&&r0&&dist<5&&r3.6&&dist<7.5&&r<.32){plan(f,'taiyo');f.followUp='kagami';f.nextDecision=c.t+30;return;} + if(dist>4.2){f.intent[s.toward]=true;if(r2<.35)f.intent.run=true;else if(r2>.85)f.intent.jump=true;return;} + if(pressured(f,c,dist)&&!press&&r1.2&&dist<4.2&&r2<.4){plan(f,'kagami');return;} + approach(f,c,o,s,r2);return;} + if(dist<2.6){guard(f,o,s,r2<.6);return;} + approach(f,c,o,s,r2); + }, + act:function(f,c,o,p){ + // wake-up Shishi o Kamu Honoo: on the first free tick after getting up, sometimes, when the opponent is close (S23) + if(f.wasDown){f.wasDown=false;if(!f.action&&f.grounded&&Math.abs(o.x-f.x)<1.8&&c.rng.random()0){q.body=-Math.PI/2*Math.min(1,(f.y>0.2?.6:1));q.hip=[0,-14];return q;} + if(f.crouching&&!a){q.hip=[0,-24];q.fr=[18,-1];q.fk=[20,-16];q.br=[-16,-1];q.bk=[-6,-14];arms([18,-44],[12,-36],[-2,-42],[-8,-34]);q.crouch=true;} + if(!grounded&&!a){q.hip=[0,-40];q.fk=[14,-34];q.fr=[6,-22];q.bk=[-6,-30];q.br=[-16,-18];arms([18,-64],[12,-54],[-12,-62],[-16,-52]);if(f.jumpType&&/super|hyper/.test(f.jumpType)){q.tilt=Math.sin(Math.min(1,f.jumpHeld/40)*Math.PI)*.35;}} + if(f.running&&grounded&&!a){var s=Math.sin(t*20);q.lean=.28;q.fr=[14+s*14,-2+Math.max(0,-s)*-6];q.fk=[16+s*6,-24];q.br=[-14-s*14,-2+Math.max(0,s)*-6];q.bk=[-2-s*6,-22];arms([16-s*8,-52],[8,-44],[-4+s*8,-54],[-12,-46]);} + else if(Math.abs(f.vx)>.5&&grounded&&!a&&!f.crouching){var w=Math.sin(t*12);q.fr=[12+w*7,-2];q.br=[-12-w*7,-2];q.fk=[12+w*3,-22];q.bk=[-6-w*3,-22];} + if(f.stun>0&&f.stunType==='block'){q.lean=-.12;arms([10,-66],[16,-54],[6,-58],[12,-48]);if(f.crouching){q.hip=[0,-24];q.fr=[18,-1];q.fk=[20,-16];q.br=[-16,-1];q.bk=[-6,-14];arms([12,-48],[16,-38],[6,-44],[12,-34]);}} + else if(f.stun>0&&f.stunType==='hit'){q.lean=-.32;q.head=-20;arms([-6,-50],[2,-44],[-16,-52],[-12,-44]);} + else if(f.stun>0&&f.stunType==='bind'){q.lean=-.08;arms([4,-62],[8,-50],[-8,-60],[-4,-48]);} // v8: held by Yasakazuki (no breathing sway) + else if(f.stun>0&&(f.stunType==='guard_break'||f.stunType==='throw')){q.lean=-.4+Math.sin(t*16)*.06;arms([-14,-70],[-4,-58],[-20,-66],[-12,-56]);} + if(!a)return q; + var reach=Math.min(66,(a.reach||2)/KF.GEOMETRY_SCALE*24); + if(id==='roll'){q.hip=[0,-22];q.body=(f.age/23)*TAU*(a.back?-1:1)*(f.facing>0?1:1);q.crouch=true;return q;} + if(id==='backstep'){q.lean=-.2;q.fr=[10,-12];q.br=[-14,-6];return q;} + if(id==='max'){q.lean=-.05;arms([30,-80],[20,-66],[-30,-80],[-20,-66]);return q;} + var punchy=/jab|heavy_punch|aragami|dokugami|kono_kizu|tsumi_yomi|batsu_yomi|yano_sabi|aoihana|air_punch|naraku|overhead|blowaway|throw|soul_grab|scum_gale|yami_barai|yasakazuki|harae|mirror|pillar|marokare|orochi_nagi|mu_shiki|yaotome/.test(id); + var kicky=/kick|sweep|kai75|nanase|kototsuki|red_kick/.test(id)&&!/air_punch/.test(id); + var ext=st?-.25+k*.25:act?1:1-k*.85; // startup winds back, active extends, recovery returns + // Orochi Team moves reuse the pose families: grabs, rising anti-airs, kicks, punches / projectiles + if(KF.TEAM_GRAB[id]){var gx2=18+ext*14;arms([gx2,-58],[gx2-12,-50],[gx2-6,-46],[gx2-16,-42]);q.lean=.12*ext;if(!grounded){q.fk=[14,-34];q.fr=[6,-22];}return q;} + if(id==='tsuki'||id==='ankoku_raiko'){q.hip=[0,-42];arms(st?[16,-40]:[14+4*(1-ext),-92],[14,-62],[-10,-52],[-14,-44]);q.fk=[12,-36];q.fr=[6,-26];return q;} + if(/shajitsu|shukumei|raijin|gouka/.test(id)){q.lean=act?.2:0;q.fk=[24,-46];q.fr=[18+ext*34,-30];arms([18,-58],[10,-48],[-16,-58],[-14,-48]);return q;} + if(/yatanagi|mugetsu|taiyo|kagami|hoeru_daichi|ankoku_orochinagi/.test(id)){var hx3=14+ext*Math.max(10,reach-4),hy3=id==='kagami'?-66+ext*18:-58;q.lean=.14*ext; + if(id==='mugetsu'){arms([20,-70],[14,-60],[-6,-60],[-12,-50]);q.lean=-.05;return q;} + if((id==='hoeru_daichi'||id==='ankoku_orochinagi')&&a.chargeable&&!a.chargeEnd){arms([-18,-40],[-8,-46],[-26,-42],[-16,-46]);q.lean=-.16;return q;} + arms([hx3,hy3],[Math.max(4,hx3-14),hy3+8],[-8,-58],[-12,-48]);return q;} + if(id==='oni_yaki'){q.hip=[0,-42];q.lean=-.1;arms(st?[16,-40]:[14+4*(1-ext),-92],[14,-62],[-10,-52],[-14,-44]);q.fk=[12,-36];q.fr=[6,-26];return q;} + if(id==='kototsuki_in'){q.lean=act?.2:.05;var ex2=14+ext*Math.max(10,reach-4);arms([ex2,-56],[Math.max(4,ex2-16),-52],[-10,-58],[-14,-48]);return q;} // v8: rushing elbow + if(id==='kototsuki'||id==='red_kick'){q.lean=act?.15:0;q.fk=[24,-46];q.fr=[18+ext*34,-34+ (id==='red_kick'?-12:4)];arms([18,-58],[10,-48],[-16,-58],[-14,-48]);return q;} + if(kicky){ + var low=/sweep|low_kick/.test(id);if(low){q.hip=[0,-24];q.crouch=true;q.bk=[-6,-14];q.br=[-16,-1];q.fk=[16,-10];q.fr=[14+ext*(reach-8),-3];arms([10,-44],[6,-36],[-6,-42],[-10,-34]);if(id==='sweep')q.tilt=.08;return q;} + var hi=/heavy_kick|kai75|nanase|air_kick/.test(id);q.lean=-.1*ext;q.fk=[14+ext*8,hi?-50:-36];q.fr=[16+ext*(reach-6),hi?-62+ext*-6:-30];arms([16,-62],[10,-52],[-16,-56],[-18,-46]); + if(!grounded){q.fk=[18,-30];q.fr=[18+ext*(reach-10),-16];}return q; + } + if(punchy){ + var lowp=/low_jab/.test(id);if(lowp){q.hip=[0,-24];q.crouch=true;q.fr=[18,-1];q.fk=[20,-16];q.br=[-16,-1];q.bk=[-6,-14];} + var up=/oni_yaki|aragami/.test(id)&&id==='aragami'?-4:0,heavy=/heavy|dokugami|batsu|blowaway|overhead|naraku|yami|harae|marokare|orochi_nagi/.test(id); + q.lean=(heavy?.14:.08)*ext;var hx=14+ext*Math.max(10,reach-4),hy=(lowp?-40:-60)+up; + if(id==='naraku'){hx=10+ext*10;hy=-24;q.fk=[12,-30];q.fr=[8,-18];} + if(id==='overhead'){hy=-76+ext*20;} + if(/throw|soul_grab|scum_gale/.test(id)){hx=18+ext*14;hy=-58;arms([hx,hy],[hx-12,hy+8],[hx-6,hy+12],[hx-16,hy+16]);return q;} + if(/yami_barai|harae|yasakazuki/.test(id)){hy=-26;q.lean=.12*ext;hx=16+ext*20;} + if(/marokare|mirror/.test(id)){arms([24+ext*10,-70],[16,-58],[-24-ext*10,-70],[-16,-58]);q.lean=-.06;return q;} + if(/pillar/.test(id)){arms([10,-96],[10,-74],[-8,-60],[-14,-50]);return q;} + if(a.multi){var ph2=(f.age-a.start)*.7;hx=24+Math.sin(ph2)*22;hy=-58+Math.cos(ph2*1.3)*10;arms([hx,hy],[hx-12,hy+8],[22-Math.sin(ph2)*20,-56],[8,-50]);q.lean=.18;return q;} + if(id==='orochi_nagi'){var ch=a.charge&&!a.chargeEnd;hx=ch?-20:14+ext*36;hy=ch?-40:-58;q.lean=ch?-.18:.2*ext;arms([hx,hy],[ch?-8:hx-12,hy+8],[ch?-30:-12,-52],[-14,-44]);return q;} + arms([hx,hy],[Math.max(4,hx-14),hy+8],[-8+ (act?-6:0),-58],[-12,-48]); + if(!grounded&&!lowp){q.fk=[14,-34];q.fr=[6,-22];q.bk=[-6,-30];q.br=[-16,-18];} + return q; + } + return q; + } + // ---------------- figure ---------------- + function figure(x,c,f,t,V){ + var P=pal(f),flash=f.hitFlash>0,kyo=f.kind==='kyo',oro=f.kind==='orochi',ioriLike=f.kind==='iori'||f.kind==='orochi_iori'; + var q=pose(f,t),key=(f.player?'p':'b'); + var sm=ART.smooth('kofpose_'+key,{hx:q.hip[0],hy:q.hip[1],lean:q.lean,tilt:q.tilt, + fhx:q.fh[0],fhy:q.fh[1],fex:q.fe[0],fey:q.fe[1],bhx:q.bh[0],bhy:q.bh[1],bex:q.be[0],bey:q.be[1], + frx:q.fr[0],fry:q.fr[1],fkx:q.fk[0],fky:q.fk[1],brx:q.br[0],bry:q.br[1],bkx:q.bk[0],bky:q.bk[1]},f.action&&phase(f).ph==='active'?60:28); + var sx=V.sx(f.x),sy=V.sy(f.y),S=KF.GEOMETRY_SCALE; + ART.shade(x,sx,V.sy(0)+2,26*(1-Math.min(.6,f.y*.12)),6,.45); + x.save();x.translate(sx,sy);x.scale(f.facing*S,S); + if(q.body){x.translate(0,-14);x.rotate(q.body);x.translate(0,14);} + var lit=function(col){return ART.lit(flash,col);}; + var hip=[sm.hx,sm.hy],lean=sm.lean,neck=[hip[0]+Math.sin(lean)*30,hip[1]-Math.cos(lean)*30],headC=[neck[0]+Math.sin(lean)*12,neck[1]-12]; + x.rotate(sm.tilt||0); + // aura for MAX / Orochi / Riot of the Blood + if(f.maxMode>0){ART.glow(x,0,-40,62+Math.sin(t*14)*4,'255,214,110',.35);} + if(oro)ART.glow(x,0,-44,58,'190,255,225',.18); + if(f.kind==='orochi_iori')ART.glow(x,0,-40,52,'230,40,90',.16+Math.sin(t*9)*.05); + if(f.kind==='orochi_yashiro'||f.kind==='orochi_shermie'||f.kind==='orochi_chris')ART.glow(x,0,-40,50,P.fire,.13+Math.sin(t*7)*.04); + // back leg + back arm (darker, behind the body) + var dark=function(c2){return lit(c2);}; + limb(x,[hip[0]-6,hip[1]],[sm.bkx,sm.bky],[sm.brx,sm.bry],dark(P.pants),11); + poly(x,[[sm.brx-7,sm.bry-3],[sm.brx+8,sm.bry-3],[sm.brx+9,sm.bry+1],[sm.brx-7,sm.bry+1]],'#0d1219'); + limb(x,[neck[0]-6,neck[1]+6],[sm.bex,sm.bey],[sm.bhx,sm.bhy],dark(oro?P.skin:P.coat2),8); + x.fillStyle=lit(P.glove);x.beginPath();x.arc(sm.bhx,sm.bhy,5,0,TAU);x.fill(); + // torso (jacket / bare chest for Orochi) + var sh=[neck[0],neck[1]+4],w1=13,w2=11; + poly(x,[[sh[0]-w1,sh[1]],[sh[0]+w1,sh[1]+1],[hip[0]+w2,hip[1]+4],[hip[0]-w2,hip[1]+4]],lit(oro?P.skin:P.coat),'#070b12'); + if(kyo){poly(x,[[sh[0]-3,sh[1]+1],[sh[0]+6,sh[1]+1],[hip[0]+5,hip[1]],[hip[0]-3,hip[1]]],lit(P.shirt));x.fillStyle='#b9945c';x.fillRect(hip[0]-11,hip[1]-2,22,3); + x.fillStyle=lit('#c8a35a');x.fillRect(sh[0]+6,sh[1]+8,3,10);} + if(ioriLike){x.fillStyle=lit(P.shirt);poly(x,[[sh[0]-2,sh[1]+1],[sh[0]+7,sh[1]+2],[hip[0]+4,hip[1]-6],[hip[0]-4,hip[1]-8]],lit(P.shirt)); + x.strokeStyle=lit('#c1a0d0');x.lineWidth=1.5;x.beginPath();x.moveTo(sh[0]-w1+2,sh[1]+16);x.lineTo(hip[0]-w2,hip[1]-2);x.stroke(); + x.fillStyle=lit('#c9c1b8');x.fillRect(hip[0]-11,hip[1]+1,22,3); + x.strokeStyle='#d9d3cc';x.lineWidth=1.2;x.beginPath();x.moveTo(hip[0]-9,hip[1]+4);x.lineTo(hip[0]+9,hip[1]+16);x.stroke();} + if(oro){x.strokeStyle='rgba(60,90,96,.7)';x.lineWidth=1.6;x.beginPath();x.arc(sh[0]+1,sh[1]+14,7,0,TAU);x.stroke();x.beginPath();x.moveTo(sh[0]-8,sh[1]+26);x.quadraticCurveTo(sh[0]+4,sh[1]+18,sh[0]+8,sh[1]+30);x.stroke(); + poly(x,[[hip[0]-13,hip[1]-2],[hip[0]+13,hip[1]-2],[hip[0]+16,hip[1]+10],[hip[0]-16,hip[1]+10]],lit(P.coat2));} + // front leg + limb(x,[hip[0]+5,hip[1]],[sm.fkx,sm.fky],[sm.frx,sm.fry],lit(P.pants),12); + poly(x,[[sm.frx-6,sm.fry-3],[sm.frx+10,sm.fry-3],[sm.frx+11,sm.fry+1],[sm.frx-6,sm.fry+1]],'#0d1219'); + // head + hair + x.fillStyle=lit(P.skin);x.beginPath();x.ellipse(headC[0],headC[1],9.5,12,lean*.6,0,TAU);x.fill();x.strokeStyle='#070b12';x.lineWidth=1.6;x.stroke(); + x.fillStyle='#16202a';x.fillRect(headC[0]+4,headC[1]-2,4,2); + if(kyo){poly(x,[[headC[0]-11,headC[1]-2],[headC[0]-12,headC[1]-15],[headC[0]-2,headC[1]-19],[headC[0]+9,headC[1]-15],[headC[0]+10,headC[1]-6],[headC[0]+3,headC[1]-9],[headC[0]-4,headC[1]-4]],lit(P.hair)); + x.fillStyle=lit(P.band);x.fillRect(headC[0]-10,headC[1]-8,20,3);var tail=Math.sin(t*9)*3;poly(x,[[headC[0]-10,headC[1]-7],[headC[0]-26,headC[1]-3+tail],[headC[0]-24,headC[1]+1+tail],[headC[0]-10,headC[1]-4]],lit(P.band));} + if(ioriLike){poly(x,[[headC[0]-12,headC[1]+2],[headC[0]-13,headC[1]-15],[headC[0]-2,headC[1]-20],[headC[0]+10,headC[1]-14],[headC[0]+12,headC[1]+6],[headC[0]+5,headC[1]-6],[headC[0]-2,headC[1]-2]],lit(P.hair)); + if(f.kind==='orochi_iori'){x.fillStyle='#ff4d6d';x.fillRect(headC[0]+4,headC[1]-2,4,2);}} + if(f.kind==='orochi_yashiro'){poly(x,[[headC[0]-12,headC[1]],[headC[0]-14,headC[1]-14],[headC[0]-4,headC[1]-20],[headC[0]+8,headC[1]-18],[headC[0]+12,headC[1]-8],[headC[0]+2,headC[1]-11],[headC[0]-6,headC[1]-6]],lit(P.hair));} + if(f.kind==='orochi_shermie'){poly(x,[[headC[0]-10,headC[1]-14],[headC[0]-22,neck[1]+26],[headC[0]-14,neck[1]+30],[headC[0]-6,headC[1]-4]],lit(P.hair));poly(x,[[headC[0]-10,headC[1]-14],[headC[0]+2,headC[1]-20],[headC[0]+12,headC[1]-10],[headC[0]+12,headC[1]-2],[headC[0]+4,headC[1]-12],[headC[0]-6,headC[1]-8]],lit(P.hair));} + if(f.kind==='orochi_chris'){poly(x,[[headC[0]-11,headC[1]-4],[headC[0]-12,headC[1]-16],[headC[0]-2,headC[1]-21],[headC[0]+10,headC[1]-15],[headC[0]+12,headC[1]-4],[headC[0]+6,headC[1]-12],[headC[0]-4,headC[1]-9]],lit(P.hair));} + if(oro){poly(x,[[headC[0]-12,headC[1]-12],[headC[0]-20,neck[1]+30],[headC[0]-10,neck[1]+20],[headC[0]-4,headC[1]-8]],lit(P.hair));poly(x,[[headC[0]-10,headC[1]-14],[headC[0]+2,headC[1]-20],[headC[0]+12,headC[1]-12],[headC[0]+14,neck[1]+18],[headC[0]+6,headC[1]-2]],lit(P.hair));} + // front arm (on top) + limb(x,[neck[0]+6,neck[1]+6],[sm.fex,sm.fey],[sm.fhx,sm.fhy],lit(oro?P.skin:P.coat),9); + x.fillStyle=lit(P.glove);x.beginPath();x.arc(sm.fhx,sm.fhy,6,0,TAU);x.fill();x.strokeStyle='#070b12';x.lineWidth=1.4;x.stroke(); + // fire in the hand while a flame move is out (Kyo orange, Iori purple; Orochi white-green light) + var a=f.action; + if(a&&/oni_yaki|aragami|dokugami|kono_kizu|yano_sabi|tsumi_yomi|batsu_yomi|aoihana|orochi_nagi|mu_shiki|yaotome|yami_barai|yasakazuki|kototsuki_in|harae|marokare/.test(a.id)||a&&KF.TEAM_FLAME[a.id]){ + var ph=phase(f),pw=ph.ph==='active'?1:ph.ph==='startup'?.35+ph.k*.4:.4*(1-ph.k);if(a.chargeable&&!a.chargeEnd)pw=.5+Math.min(1,(a.charge||0)/90)*.6; + ART.glow(x,sm.fhx,sm.fhy,18+pw*20,P.fire,.75*pw);x.fillStyle=P.fireCore;x.globalAlpha=pw;x.beginPath();x.arc(sm.fhx,sm.fhy,4+pw*3,0,TAU);x.fill();x.globalAlpha=1; + } + x.restore(); + } + // ---------------- attack effects (world space) ---------------- + function slashArc(x,cx,cy,r,a0,a1,col,wid,alpha){x.save();x.globalCompositeOperation='lighter';x.globalAlpha=alpha;x.strokeStyle=col;x.lineCap='round'; + for(var i=0;i<3;i++){x.lineWidth=wid*(1-i*.3);x.beginPath();x.arc(cx,cy,r-i*5,a0,a1);x.stroke();}x.restore();} + function effects(x,c,f,t,V){ + var P=pal(f),a=f.action,S=V.S;x.save(); + f.shots.forEach(function(p){ + var px=V.sx(p.x),py=V.sy(p.y),dir=p.vx>0?1:-1,w=p.w*S,h=p.h*S; + if(p.kind==='orochi_shermie'){x.globalCompositeOperation='lighter'; + if(p.vx===0){var rr=Math.max(w,h)*.55*(1+Math.sin(t*30)*.06);ART.glow(x,px,py,rr*1.9,P.fire,.55);x.strokeStyle='#e8ecff';x.lineWidth=2; + for(var b2=0;b2<6;b2++){var an2=b2*1.047+t*9;x.beginPath();x.moveTo(px,py);x.lineTo(px+Math.cos(an2)*rr*.6,py+Math.sin(an2)*rr*.6);x.lineTo(px+Math.cos(an2+.4)*rr,py+Math.sin(an2+.4)*rr);x.stroke();} + x.fillStyle='#f4f6ff';x.beginPath();x.arc(px,py,rr*.35,0,TAU);x.fill();} + else{ART.glow(x,px,py,h*.9,P.fire,.6);x.strokeStyle='#eef1ff';x.lineWidth=3;x.beginPath();x.moveTo(px-dir*w*.6,py);for(var z=1;z<=4;z++)x.lineTo(px-dir*w*.6+dir*w*.3*z,py+(z%2?-1:1)*h*.3);x.stroke();} + x.globalAlpha=1; + }else if(p.kind==='orochi_chris'){x.globalCompositeOperation='lighter';for(var k2=0;k2<3;k2++){x.globalAlpha=.7-k2*.18;x.fillStyle=k2?'rgb('+P.fire+')':P.fireCore;x.beginPath();x.ellipse(px-dir*k2*9,py,w*.5*(1-k2*.15),h*.45*(1-k2*.12),0,0,TAU);x.fill();}ART.glow(x,px,py,h,P.fire,.45);x.globalAlpha=1; + }else if(p.kind==='orochi_yashiro'){x.globalCompositeOperation='lighter';var front=px+dir*w*.5,tail=px-dir*w*1.6,x0=Math.min(front,tail),g4=x.createLinearGradient(tail,0,front,0);g4.addColorStop(0,'rgba(255,150,70,0)');g4.addColorStop(.55,'rgba(255,170,90,.7)');g4.addColorStop(1,'rgba(255,240,200,.95)');x.fillStyle=g4; + x.fillRect(x0,py-h*.5,Math.abs(front-tail),h);if(p.unblockable){x.strokeStyle='rgba(255,90,60,.9)';x.lineWidth=3;x.strokeRect(Math.min(front,px-dir*w*.5),py-h*.5,w,h);}ART.glow(x,px,py,h*.8,P.fire,.5);x.globalAlpha=1; + }else if(p.kind==='orochi'){ + x.globalCompositeOperation='lighter'; + for(var i=0;i<3;i++){var ww=w*(.55+i*.25),hh=h*(.5+i*.22);x.globalAlpha=.55-i*.15;x.strokeStyle=i?'#bfffe5':'#f4fff8';x.lineWidth=4-i;x.beginPath();x.ellipse(px-dir*i*8,py,ww*.35,hh*.5,0,-Math.PI/2,Math.PI/2,dir<0);x.stroke();} + ART.glow(x,px,py,h*.7,P.fire,.45);x.globalAlpha=1; + }else if(p.bind){x.globalCompositeOperation='lighter'; // v8 Yasakazuki: a creeping low flame, drawn to its hitbox + var by2=V.sy(0);for(var j2=0;j2<4;j2++){var fx2=px-dir*j2*w*.22,fh2=h*(.9-j2*.15)+Math.sin(t*24+j2)*2;x.globalAlpha=.8-j2*.15;x.fillStyle=j2<1?P.fireCore:'rgb('+P.fire+')'; + x.beginPath();x.moveTo(fx2-w*.25,by2);x.quadraticCurveTo(fx2,by2-fh2*1.1,fx2+w*.25,by2);x.closePath();x.fill();} + ART.glow(x,px,by2-h*.4,h*1.2,P.fire,.4);x.globalAlpha=1; + }else{ + x.globalCompositeOperation='lighter'; + // Yami Barai: a ground-hugging purple flame wave + var by=V.sy(0);for(var j=0;j<5;j++){var fx=px-dir*j*7,fh=h*(1.1-j*.16)+Math.sin(t*30+j)*3;x.globalAlpha=.75-j*.12;x.fillStyle=j<2?P.fireCore:'rgb('+P.fire+')';x.beginPath();x.moveTo(fx-7,by);x.quadraticCurveTo(fx-2,by-fh*.6,fx+dir*2,by-fh);x.quadraticCurveTo(fx+dir*8,by-fh*.4,fx+7,by);x.closePath();x.fill();} + ART.glow(x,px,by-h*.4,30,P.fire,.35);x.globalAlpha=1; + } + x.globalCompositeOperation='source-over'; + }); + if(f.stun>0&&f.stunType==='bind'){var bx=V.sx(f.x),bt=V.sy(f.y+2.7*KF.GEOMETRY_SCALE),bb=V.sy(f.y);x.globalCompositeOperation='lighter'; + var g6=x.createLinearGradient(0,bb,0,bt);g6.addColorStop(0,'rgba(150,120,255,.75)');g6.addColorStop(1,'rgba(150,120,255,0)');x.fillStyle=g6;x.fillRect(bx-22,bt,44,bb-bt); + ART.glow(x,bx,V.sy(f.y+1.3),46,'150,120,255',.35+Math.sin(t*20)*.08);x.globalCompositeOperation='source-over';} + if(a&&a.pull&&!a.connected&&phase(f).ph==='active'){var ox6=V.sx(f.x+a.facing*a.pull.range),oy6=V.sy(f.y+1.2*KF.GEOMETRY_SCALE),ix6=V.sx(f.x+a.facing*.8);x.globalCompositeOperation='lighter'; + var g7=x.createLinearGradient(ox6,0,ix6,0);g7.addColorStop(0,'rgba(190,255,225,0)');g7.addColorStop(1,'rgba(220,255,240,.6)');x.fillStyle=g7;x.fillRect(Math.min(ox6,ix6),oy6-26,Math.abs(ox6-ix6),52);x.globalCompositeOperation='source-over';} + if(a&&a.chargeable&&a.charge>0&&!a.chargeEnd){var k=Math.min(1,a.charge/90);ART.glow(x,V.sx(f.x+f.facing*1.0),V.sy(f.y+1.7),22+k*30,P.fire,.5+k*.4); + x.strokeStyle='rgba(255,220,140,'+(.5+k*.5)+')';x.lineWidth=2;x.beginPath();x.arc(V.sx(f.x+f.facing*1.0),V.sy(f.y+1.7),14+k*14+Math.sin(t*30)*2,0,TAU);x.stroke();} + if(a){ + var ph=phase(f),boxes=KF.attackBoxes(f); + // startup tell for heavy specials and Orochi's moves (telegraph matches the move that follows) + if(ph.ph==='startup'&&(a.remote)){var tx=V.sx(a.targetX);x.globalCompositeOperation='lighter';x.fillStyle='rgba(190,255,225,'+(.15+.35*ph.k)+')';x.fillRect(tx-20*KF.GEOMETRY_SCALE*.65,V.sy(0)-4,40*KF.GEOMETRY_SCALE*.65,6); + x.strokeStyle='rgba(220,255,240,'+(.3+.5*ph.k)+')';x.lineWidth=2;x.beginPath();x.ellipse(tx,V.sy(0)+1,22*(1.3-ph.k*.3),5,0,0,TAU);x.stroke();x.globalCompositeOperation='source-over';} + if(ph.ph==='startup'&&a.fullscreen){x.fillStyle='rgba(225,255,240,'+(.08+.25*ph.k)+')';x.fillRect(0,0,V.W,V.H);} + // Yashiro's beam charge: the ring grows with the charge and turns red at full (unblockable) + if(a.id==='hoeru_daichi'&&!a.spawned){var kc=Math.min(1,(a.charge||0)/90),cx5=V.sx(f.x+f.facing*.9),cy5=V.sy(f.y+1.3);x.globalCompositeOperation='lighter';ART.glow(x,cx5,cy5,20+kc*34,P.fire,.4+kc*.5); + x.strokeStyle=kc>=1?'rgba(255,90,60,.95)':'rgba(255,200,140,.7)';x.lineWidth=2+kc*2;x.beginPath();x.arc(cx5,cy5,12+kc*18,0,TAU);x.stroke();x.globalCompositeOperation='source-over';} + // Mugetsu no Raiun startup: a faint spark where the orb will appear + if(a.id==='mugetsu'&&ph.ph==='startup'){var ox=V.sx(f.x+f.facing*(a.placeDist||4)),oy=V.sy((a.orbY||1.25)*KF.GEOMETRY_SCALE);x.globalCompositeOperation='lighter';ART.glow(x,ox,oy,10+ph.k*22,P.fire,.15+ph.k*.35);x.globalCompositeOperation='source-over';} + if(ph.ph==='active'||ph.ph==='startup'&&a.reflect){ + if(a.reflect){var mx=V.sx(f.x+f.facing*.95*KF.GEOMETRY_SCALE),my=V.sy(1.15*KF.GEOMETRY_SCALE);x.globalCompositeOperation='lighter'; + var gr=x.createLinearGradient(mx-12,0,mx+12,0);gr.addColorStop(0,'rgba(190,255,225,0)');gr.addColorStop(.5,'rgba(230,255,245,.85)');gr.addColorStop(1,'rgba(190,255,225,0)');x.fillStyle=gr; + x.beginPath();x.ellipse(mx,my,9,40,0,0,TAU);x.fill();x.strokeStyle='rgba(240,255,250,.9)';x.lineWidth=2;x.beginPath();x.ellipse(mx,my,13+Math.sin(t*40)*1.5,44,0,0,TAU);x.stroke();x.globalCompositeOperation='source-over';} + else if(a.remote&&ph.ph==='active'){var px2=V.sx(a.targetX),top=V.sy(Math.min(a.height,14));x.globalCompositeOperation='lighter'; + var g2=x.createLinearGradient(0,V.sy(0),0,top);g2.addColorStop(0,'rgba(255,255,250,.95)');g2.addColorStop(.25,'rgba(200,255,230,.8)');g2.addColorStop(1,'rgba(160,255,220,0)');x.fillStyle=g2; + var wd=0.65*KF.GEOMETRY_SCALE*S;x.beginPath();x.moveTo(px2-wd,V.sy(0));for(var yy=0;yy<=10;yy++){var yv=V.sy(0)+(top-V.sy(0))*yy/10;x.lineTo(px2-wd*(1-yy*.05)+Math.sin(t*40+yy)*4,yv);} + for(yy=10;yy>=0;yy--){yv=V.sy(0)+(top-V.sy(0))*yy/10;x.lineTo(px2+wd*(1-yy*.05)+Math.cos(t*37+yy)*4,yv);}x.closePath();x.fill();x.globalCompositeOperation='source-over';} + else if(a.fullscreen&&ph.ph==='active'){x.fillStyle='rgba(235,255,245,.55)';x.fillRect(0,0,V.W,V.H);x.globalCompositeOperation='lighter';x.strokeStyle='rgba(255,255,255,.8)';x.lineWidth=3; + for(var i2=0;i2<16;i2++){var an=i2/16*TAU+t*2;x.beginPath();x.moveTo(V.sx(f.x),V.sy(1.8));x.lineTo(V.sx(f.x)+Math.cos(an)*900,V.sy(1.8)+Math.sin(an)*900);x.stroke();}x.globalCompositeOperation='source-over';} + else if(boxes.length&&!a.throw){ + var b=boxes[0].box,hx=V.sx(b.x),hy=V.sy(b.y),R=Math.max(16,b.w*S*.5),col='rgb('+P.fire+')',dir=f.facing; + if(a.id==='oni_yaki'){x.globalCompositeOperation='lighter';var gx=V.sx(f.x+f.facing*.5),gy=V.sy(f.y+1.4);ART.glow(x,gx,gy,70,P.fire,.7); + for(var fl=0;fl<6;fl++){var fy=gy+30-fl*16,fw=24-fl*2.5;x.globalAlpha=.75-fl*.08;x.fillStyle=fl<2?P.fireCore:col;x.beginPath();x.ellipse(gx+Math.sin(t*25+fl)*5,fy,fw,14,0,0,TAU);x.fill();}x.globalAlpha=1;x.globalCompositeOperation='source-over';} + else if(a.super||/aragami|dokugami|kono_kizu|yano_sabi|tsumi_yomi|batsu_yomi|aoihana|kototsuki|red_kick|kai75|nanase/.test(a.id)){ + var a0=dir>0?-1.2:Math.PI-1.0,a1=dir>0?1.0:Math.PI+1.2;slashArc(x,hx-dir*R*.4,hy,R*.9,a0,a1,col,8,.85);ART.glow(x,hx,hy,R*1.3,P.fire,.45); + if(a.id==='orochi_nagi'){x.globalCompositeOperation='lighter';var L=b.w*S,gy2=V.sy(f.y+.9);var g3=x.createLinearGradient(V.sx(f.x),0,V.sx(f.x)+dir*L,0);g3.addColorStop(0,'rgba(255,240,200,.95)');g3.addColorStop(.4,'rgba('+P.fire+',.8)');g3.addColorStop(1,'rgba('+P.fire+',0)');x.fillStyle=g3; + x.beginPath();x.moveTo(V.sx(f.x),gy2+4);for(var s2=0;s2<=12;s2++){var xx=V.sx(f.x)+dir*L*s2/12;x.lineTo(xx,gy2-30*Math.sin(s2/12*Math.PI)-10-Math.sin(t*50+s2)*6);}x.lineTo(V.sx(f.x)+dir*L,gy2+4);x.closePath();x.fill();x.globalCompositeOperation='source-over';} + }else{x.globalCompositeOperation='lighter';x.globalAlpha=.55;x.strokeStyle='#f6f2e4';x.lineWidth=3;x.beginPath();x.arc(hx-dir*8,hy,R*.55,dir>0?-.9:Math.PI-.7,dir>0?.7:Math.PI+.9);x.stroke();x.globalAlpha=1;x.globalCompositeOperation='source-over';} + } + } + } + x.restore(); + } + // ---------------- event sparks (from the case event log; deterministic per tick) ---------------- + var SPARK_LIFE=14; + function sparks(x,c,V){ + var ev=c.events,n=ev.length,lo=Math.max(0,n-60);x.save(); + for(var i=n-1;i>=lo;i--){var e=ev[i],age=c.t-e.t;if(age<0||age>SPARK_LIFE+6)continue;if(e.x==null)continue; + var k=age/SPARK_LIFE,px=V.sx(e.x),py=V.sy(e.y!=null?e.y:1),seed=(e.t*31+i*7)%97; + if(e.name==='boss_hit'||e.name==='player_hit'){if(k>1)continue;var big=e.name==='player_hit'?1:1.15;x.globalCompositeOperation='lighter'; + ART.glow(x,px,py,(46+20*(1-k))*big,'255,236,190',.9*(1-k));x.fillStyle='rgba(255,252,240,'+(1-k)+')'; + for(var r=0;r<7;r++){var an=(seed+r*53)%360/57.3,L=(16+((seed*r)%9)*3)*(0.4+k)*big;x.save();x.translate(px,py);x.rotate(an);x.beginPath();x.moveTo(0,-2.5*(1-k));x.lineTo(L,0);x.lineTo(0,2.5*(1-k));x.closePath();x.fill();x.restore();} + x.globalCompositeOperation='source-over';} + else if(e.name==='fighter_block'){if(k>.8)continue;x.globalCompositeOperation='lighter';x.strokeStyle='rgba(150,225,255,'+(1-k/.8)+')';x.lineWidth=3; + x.beginPath();x.arc(px,py,10+k*26,0,TAU);x.stroke();ART.glow(x,px,py,30,'140,210,255',.6*(1-k)); + for(r=0;r<6;r++){an=r*1.047+seed*.1;x.beginPath();x.moveTo(px+Math.cos(an)*(8+k*14),py+Math.sin(an)*(8+k*14));x.lineTo(px+Math.cos(an)*(16+k*28),py+Math.sin(an)*(16+k*28));x.stroke();}x.globalCompositeOperation='source-over';} + else if(e.name==='guard_break'||e.name==='throw_escape'||e.name==='projectile_reflect'||e.name==='projectile_clash'){if(k>1.2)continue;x.globalCompositeOperation='lighter'; + var colr=e.name==='guard_break'?'255,120,120':e.name==='throw_escape'?'255,255,255':'200,255,235';ART.glow(x,px,py,60*(1-k/1.2),colr,.9);x.strokeStyle='rgba('+colr+','+(1-k/1.2)+')';x.lineWidth=4;x.beginPath();x.arc(px,py,8+k*40,0,TAU);x.stroke();x.globalCompositeOperation='source-over'; + if(e.name==='guard_break'||e.name==='throw_escape'){x.fillStyle='rgba(255,240,200,'+(1-k/1.2)+')';x.font='bold 15px monospace';x.textAlign='center';x.fillText(e.name==='guard_break'?'GUARD CRUSH':'ESCAPE',px,py-34-k*10);}} + else if(e.name==='guard_cancel_roll'||e.name==='guard_cancel_blowaway'||e.name==='max_mode'){if(k>1.4)continue;x.fillStyle='rgba(255,225,130,'+(1-k/1.4)+')';x.font='bold 14px monospace';x.textAlign='center'; + x.fillText(e.name==='max_mode'?'MAX!':'GUARD CANCEL',px,py-60-k*12);if(e.name==='max_mode'){x.globalCompositeOperation='lighter';ART.glow(x,px,py,90*(1-k/1.4),'255,214,110',.8);x.globalCompositeOperation='source-over';}} + } + x.restore(); + } + // ---------------- super flash: the stage darkens behind the fighters, then a glow + cut-in name on top ---------------- + function superDark(x,c,V){var f=c.body.flash>0?c.body:c.boss.flash>0?c.boss:null;if(!f)return;var k=f.flash/KF.SUPER_FREEZE;x.save();x.fillStyle='rgba(4,6,14,'+(.62*Math.min(1,k*1.6))+')';x.fillRect(0,0,V.W,V.H);x.restore();} + function superFlash(x,c,V){ + var f=c.body.flash>0?c.body:c.boss.flash>0?c.boss:null;if(!f)return; + var k=f.flash/KF.SUPER_FREEZE,P=pal(f);x.save(); + var y=V.sy(f.y+1.6);x.globalCompositeOperation='lighter';ART.glow(x,V.sx(f.x),y,90+60*(1-k),P.fire,.9); + x.fillStyle='rgba('+P.fire+','+(.22*k)+')';x.fillRect(0,y-28,V.W,56);x.globalCompositeOperation='source-over'; + var names={orochi_nagi:'Charged Flame Sweep',mu_shiki:'Multi-hit Rush',yaotome:'Rush Frenzy',yasakazuki:'Binding Flame',marokare:'— Full-screen White Light —',soul_grab:'— Soul Grab —',araburu_daichi:'Chain Throws',hoeru_daichi:'Charged Beam',ankoku_jigoku:'Super Slam',shukumei:'Multi-hit Flying Kicks',ankoku_raiko:'Anti-air Spark Punch',gouka:'Fireball Rush',ankoku_orochinagi:'Dark Flame Sweep'},a=f.action; + if(a&&names[a.id]){x.font='bold 22px "Microsoft YaHei",sans-serif';x.textAlign=f.player?'left':'right';x.fillStyle='rgba(255,246,220,'+Math.min(1,k*2)+')'; + x.fillText(names[a.id]+(a.powered?' MAX':''),f.player?40:V.W-40,y-38);} + x.restore(); + } + // ---------------- HUD ---------------- + function hud(x,c,V,extra){ + x.save();var W=V.W,w=330; + var top=x.createLinearGradient(0,0,0,92);top.addColorStop(0,'rgba(5,8,16,.92)');top.addColorStop(1,'rgba(5,8,16,.55)');x.fillStyle=top;x.fillRect(0,0,W,92); + function bar(f,bx,flipped,label,sub){ + var hp=Math.max(0,KF.life(f)/KF.lifeMax(f)),trail=ART.smooth('kofhp_'+(flipped?'b':'p')+(f.member||1),{v:hp},2.2).v; + x.fillStyle='#1b2533';x.fillRect(bx,30,w,20); + x.fillStyle='rgba(255,90,90,.85)';var tw=w*Math.max(hp,trail);x.fillRect(flipped?bx+w-tw:bx,30,tw,20); + var g1=x.createLinearGradient(0,30,0,50);g1.addColorStop(0,hp<.25?'#ff8aa0':'#fff4b8');g1.addColorStop(.3,hp<.25?'#e2405e':'#f2c13f');g1.addColorStop(1,hp<.25?'#a01834':'#c47f12'); + x.fillStyle=g1;x.fillRect(flipped?bx+w-w*hp:bx,30,w*hp,20); + x.strokeStyle='#d8dde4';x.lineWidth=1.5;x.strokeRect(bx-.5,29.5,w+1,21); + x.fillStyle='#f3f6f8';x.font='700 15px "Microsoft YaHei",sans-serif';x.textAlign=flipped?'right':'left';x.fillText(label,flipped?bx+w:bx,22); + x.font='600 10px monospace';x.fillStyle='#a9b8c4';x.fillText(sub+' '+Math.max(0,KF.life(f))+' / '+KF.lifeMax(f),flipped?bx+w:bx,64); + // team members (KOF elimination): one marker per member, the fallen ones dark + if((f.members||1)>1)for(var m=0;m=(f.member||1)-1;x.beginPath();x.arc(mx,77,4.5,0,TAU);x.fillStyle=alive?(m===(f.member||1)-1?'#ffd36a':'#c8d4dc'):'#3a2730';x.fill();x.strokeStyle='#e8eef2';x.lineWidth=1;x.stroke();} + // guard gauge (thin, under the life bar) + x.fillStyle='#24303d';x.fillRect(bx,53,w*.42,3);x.fillStyle=f.guardBroken>0?'#ff6b6b':'#7fd3f0';var gw=w*.42*Math.max(0,f.guardGauge)/100;x.fillRect(flipped?bx+w*.42-gw:bx,53,gw,3); + if(f.combo>1){x.fillStyle='#ffe08a';x.font='bold 20px monospace';x.fillText(f.combo+' HITS',flipped?bx+w:bx,118);} + if(f.lastHit==='counter'&&f.stun>0){x.fillStyle='#ff9fae';x.font='bold 12px monospace';x.fillText('COUNTER',flipped?bx+w:bx,134);} + } + var pp=c.body,bb=c.boss; + bar(pp,30,false,'Flame Fist','ADVANCED');bar(bb,W-30-w,true,c.def.title,c.boss.kind==='orochi'?'BOSS':c.boss.kind==='orochi_iori'?'FRENZY':/^orochi_/.test(c.boss.kind)?'AWAKENED TRIO':'ADVANCED'); + // timer + var held=c.boss.roundPause>0?(c.boss.koTick||c.t)-(c.boss.roundStart||0):KF.roundClock(c); // the clock stops at K.O. + var secs=Math.max(0,Math.ceil(Math.min(KF.ROUND_TICKS-held,BB.MAX_SECONDS*BB.FPS-c.t)/60));x.textAlign='center';x.fillStyle='rgba(0,0,0,.5)';x.fillRect(W/2-34,14,68,46);x.strokeStyle='#d8dde4';x.lineWidth=1;x.strokeRect(W/2-34.5,13.5,69,47); + x.fillStyle=secs<=10?'#ff8a8a':'#fff2c2';x.font='bold 36px monospace';x.fillText(String(secs).padStart(2,'0'),W/2,51);x.fillStyle='#9fb2bf';x.font='9px monospace';x.fillText('TIME',W/2,72); + // power gauges (bottom): 3 stock orbs + the filling bar; MAX countdown replaces the bar while active + function power(f,left){ + var bx=left?24:W-24-196,by=468;x.fillStyle='rgba(5,8,16,.72)';x.fillRect(bx-8,by-14,212,26); + x.textAlign=left?'left':'right';x.font='bold 11px monospace';x.fillStyle=f.maxMode?'#ffe28a':'#c7d5de';x.fillText(f.maxMode?'MAX '+(f.maxMode/60).toFixed(1)+'s':'POWER',left?bx:bx+196,by-3); + for(var i=0;i<(f.stockCap||3);i++){var ox=left?bx+92+i*18:bx+88-i*18,on=i=(f.stockCap||3)?1:f.meter/100,g2=x.createLinearGradient(bx,0,bx+196,0);g2.addColorStop(0,f.maxMode?'#ff9a3c':'#2fa7d8');g2.addColorStop(1,f.maxMode?'#ffe48a':'#9ff0ff'); + x.fillStyle=g2;x.fillRect(left?bx:bx+196-196*fill,by+2,196*fill,7);x.strokeStyle='#8ea2b0';x.lineWidth=1;x.strokeRect(bx-.5,by+1.5,197,8); + x.fillStyle='#ffe7a0';x.font='bold 11px monospace';var cap=f.stockCap||3;x.fillText(f.stocks+'/'+cap,left?bx+96+cap*18:bx+86-(cap-1)*18,by-3); // after the last orb (cap grows to 5) + } + power(pp,true);power(bb,false); + x.textAlign='center';x.fillStyle='rgba(160,180,195,.8)';x.font='9px monospace';var T=BB.GAME&&BB.GAME.tiers,tier=T&&Object.keys(T).filter(function(n){return Math.abs(T[n]-c.d)<1e-9;})[0]; + x.fillText((tier?tier.toUpperCase():'d '+c.d.toFixed(2))+' · 60Hz · '+(extra||'ROUND '+(c.boss.round||1)+'/'+(c.boss.members||1)+' · 99 SEC · ADVANCED'),W/2,86); + if(c.result){x.fillStyle='rgba(6,8,16,.62)';x.fillRect(0,196,W,78);x.fillStyle='#fff0b0';x.font='bold 44px monospace'; + var dko=KF.life(c.body)<=0&&KF.life(c.boss)<=0,word=c.result==='timeout'?(c.body.roundTimedOut?'TIME OVER · DRAW':'DOUBLE K.O.'):dko?'DOUBLE K.O.':c.body.roundTimedOut?'TIME OVER':'K.O.';x.fillText(word,W/2,250); + x.font='bold 14px "Microsoft YaHei",sans-serif';x.fillStyle=c.result==='win'?'#ffd36a':c.result==='loss'?'#ff8a9a':'#c8d4dc';x.fillText(c.result==='win'?'Flame Fist WINS':c.result==='loss'?c.def.title+' WINS':'DRAW',W/2,268);} + else if(c.boss.roundPause>0){x.fillStyle='rgba(6,8,16,.5)';x.fillRect(0,206,W,62);x.fillStyle='#fff0b0';x.font='bold 40px monospace';x.fillText(c.boss.roundTimedOut?'TIME OVER':'K.O.',W/2,250); + x.font='bold 13px "Microsoft YaHei",sans-serif';x.fillStyle='#c8d4dc';x.fillText('NEXT · '+c.def.title+' '+((c.boss.member||1)+1)+' / '+c.boss.members,W/2,266);} + else if(KF.roundClock(c)<70){var rc=KF.roundClock(c),k=rc/70;x.globalAlpha=Math.min(1,(1-k)*3);x.fillStyle='#fff3c6';x.font='bold 40px monospace';x.fillText(rc<40?'ROUND '+(c.boss.round||1):'FIGHT!',W/2,240);x.globalAlpha=1;} + x.restore(); + } + BB.BODY_DRAW.kof_kyo={draw:function(x,c,t,V){effects(x,c,c.body,t,V);figure(x,c,c.body,t,V);sparks(x,c,V);superFlash(x,c,V);},fullHud:hud}; + ['kof97/iori','kof97/orochi_iori','kof97/orochi','kof97/orochi_yashiro','kof97/orochi_shermie','kof97/orochi_chris'].forEach(function(id){BB.BOSS_DRAW[id]={hazards:function(x,c,t,V){superDark(x,c,V);effects(x,c,c.boss,t,V);},body:function(x,c,t,V){figure(x,c,c.boss,t,V);}};}); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/fight.js b/environments/games/web/games/kof_remake/fight.js new file mode 100644 index 0000000000000000000000000000000000000000..23d6d7f34ba1e1b673338f9a71cf9055613662e6 --- /dev/null +++ b/environments/games/web/games/kof_remake/fight.js @@ -0,0 +1,558 @@ +// Independent KOF97 ADVANCED-style combat. Timing/hitboxes/damage are normalized for the arena. +(function(g){ + var BB=g.BB,KF=BB.KOF={}; + KF.ROUND_TICKS=99*60;KF.MAX_STOCKS=3;KF.METER_PER_STOCK=100;KF.HP=4500;KF.METER_GAIN=1;KF.ROUND_PAUSE=120;KF.MAX_TICKS=600; + // Gauge gain per event (rules v7; v6 was hit 8 / block 3 / guard 2 / hurt 6% of damage). Specials add their own + // `meter` on start (whiffs too). Approximations: no '97 gauge table is readable. + KF.GAIN={hit:10,block:4,guard:2,hurt:.06}; + KF.GEOMETRY_SCALE=1.32; // 101px standing fighter at 480p; the same scale applies to all combat geometry. + function move(id,start,active,recovery,damage,reach,level,extra){ + return Object.assign({id:id,start:start,active:active,recovery:recovery,damage:damage,reach:reach,level:level||'mid',height:1.2,hitstun:18,blockstun:12,knock:1.7,chip:0,meter:0,cancel:false},extra||{}); + } + var M=KF.MOVES={ + jab:move('jab',3,3,9,30,1.55,'mid',{cancel:true,hitstun:14,blockstun:9}), + low_jab:move('low_jab',3,3,8,25,1.4,'mid',{height:.65,cancel:true,hitstun:13,blockstun:9}), + light_kick:move('light_kick',5,4,11,40,1.9,'mid',{cancel:true}), + low_kick:move('low_kick',4,4,11,30,1.65,'low',{height:.4,cancel:true,hitstun:15}), + heavy_punch:move('heavy_punch',7,5,17,75,1.9,'mid',{cancel:true,hitstun:23,blockstun:16}), + sweep:move('sweep',8,5,23,85,2.3,'low',{height:.3,hitstun:37,knockdown:true,blockstun:19,knock:2.7}), + heavy_kick:move('heavy_kick',9,5,20,80,2.5,'mid',{hitstun:24,blockstun:17,knock:2.1}), + air_punch:move('air_punch',5,8,14,65,1.65,'high',{height:1.25,air:true,hitstun:20,cancel:false}), + air_kick:move('air_kick',6,10,15,75,2.1,'high',{height:.6,air:true,hitstun:22}), + naraku:move('naraku',7,9,17,90,1.4,'high',{height:.65,air:true,crossup:true,hitstun:25}), + overhead:move('overhead',18,4,23,70,1.95,'high',{height:1.4,hitstun:20}), + blowaway:move('blowaway',11,5,26,95,2.5,'mid',{hitstun:40,blockstun:21,knock:3.4,knockdown:true}), + throw:move('throw',1,1,25,100,1.2,'throw',{hitstun:40,knock:2.6,knockdown:true,throw:true}), + aragami:move('aragami',11,5,23,100,2.45,'mid',{chip:8,meter:12,cancel:true,hitstun:23,armor:0}), + kono_kizu:move('kono_kizu',8,4,23,85,2.6,'mid',{chip:7,meter:0,cancel:true,hitstun:24}), + yano_sabi:move('yano_sabi',10,5,23,90,2.65,'high',{chip:7,meter:0,hitstun:27}), + nanase:move('nanase',8,5,22,100,2.9,'mid',{chip:8,meter:0,hitstun:37,knockdown:true}), + dokugami:move('dokugami',18,5,25,130,2.7,'mid',{chip:10,meter:12,cancel:true,hitstun:28}), + tsumi_yomi:move('tsumi_yomi',10,4,23,90,2.8,'mid',{chip:7,meter:0,cancel:true,hitstun:26}), + batsu_yomi:move('batsu_yomi',8,5,28,125,3.0,'mid',{chip:10,meter:0,knockdown:true,hitstun:42}), + oni_yaki:move('oni_yaki',5,13,30,155,1.7,'mid',{height:2.2,chip:12,meter:14,invul:[0,7],launch:17,knockdown:true,hitstun:40}), + kai75:move('kai75',10,6,19,70,2.6,'mid',{height:1.0,chip:6,meter:10,cancel:true,launch:7,hitstun:26}), + kai75_follow:move('kai75_follow',8,6,25,100,2.8,'mid',{height:1.4,chip:8,meter:0,launch:10,knockdown:true,hitstun:40}), + red_kick:move('red_kick',14,15,25,135,2.5,'high',{height:.8,chip:10,meter:12,launch:13,travel:10,knockdown:true,hitstun:39}), + kototsuki:move('kototsuki',14,14,26,155,2.0,'mid',{chip:12,meter:12,travel:12,knockdown:true,hitstun:40}), + orochi_nagi:move('orochi_nagi',20,16,30,260,5.1,'mid',{height:1.5,chip:40,stock:1,super:true,chargeable:true,meter:0,knock:3.5,knockdown:true,hitstun:50}), + mu_shiki:move('mu_shiki',11,65,35,280,2.55,'mid',{height:1.4,chip:30,stock:1,super:true,travel:11,invul:[0,5],knockdown:true,hitstun:55,multi:[0,10,20,30,40,50],capture:true}), + yami_barai:move('yami_barai',14,1,24,90,0,'mid',{chip:10,meter:12,projectile:true}), + // Rules v8 (2026-11-03): moves SNK's official '97 lists give Iori and Riot Iori (S19 hidden page, S25 regular page) that + // v7 lacked. Kototsuki In = rushing elbow (S29: rush), modelled like Kyo's Kototsuki Yo. Yasakazuki = slow ground flame that binds the + // opponent until the next hit or `bind` ticks, with little damage of its own (S30; series-level, no '97 numbers). + kototsuki_in:move('kototsuki_in',14,14,26,150,2.0,'mid',{chip:12,meter:12,travel:12,knockdown:true,hitstun:40}), + yasakazuki:move('yasakazuki',22,1,40,40,0,'mid',{chip:4,stock:1,super:true,projectile:true,bind:90,shotW:.9,shotH:.7,shotSpeed:5.2,shotLife:80}), + aoihana:move('aoihana',10,6,24,95,2.5,'mid',{chip:8,meter:12,cancel:true,travel:6,hitstun:24}), + aoihana2:move('aoihana2',8,6,24,85,2.55,'mid',{chip:8,meter:0,cancel:true,travel:6,hitstun:24}), + aoihana3:move('aoihana3',10,7,30,130,2.7,'mid',{chip:10,meter:0,travel:7,knockdown:true,hitstun:42}), + scum_gale:move('scum_gale',4,1,15,0,1.5,'throw',{throw:true,commandThrow:true,comboGrab:true,hitstun:30,knock:0}), + yaotome:move('yaotome',12,72,34,290,1.7,'mid',{chip:30,stock:1,super:true,travel:14,invul:[0,6],knockdown:true,hitstun:55,multi:[0,9,18,27,36,45,54,63],capture:true}), + // Orochi (S07): multi-hit shockwave with a huge box, almost motionless reflector, near-instant screen-tall pillar. + harae:move('harae',17,1,26,120,0,'mid',{chip:15,projectile:true,meter:12,hits:3,shotW:1.05,shotH:1.9,shotSpeed:8.5}), + mirror:move('mirror',4,26,18,80,1.7,'mid',{height:1.5,chip:10,reflect:true,hitstun:28}), + pillar:move('pillar',14,12,27,140,1.1,'mid',{height:11,chip:20,remote:true,knockdown:true,hitstun:45}), + // v8: "draws the opponent in and extracts their soul" is a SUPER in '97 (236236+B/D, S26/S27/S28): it draws a grounded opponent in from mid + // range and grabs; out of range it whiffs (S28). v7 had it as a free close-range command throw. Numbers are approximations. + soul_grab:move('soul_grab',14,24,34,280,1.4,'throw',{throw:true,commandThrow:true,stock:1,super:true,pull:{range:4.6,speed:7},comboGrab:true,hitstun:50,knockdown:true,knock:2.8}), + // v8: Orochi's two barriers ('97 lists S26/S27: "creates a barrier in front" 236+B, "creates a diagonal upward barrier" 236+C; '98UM calls both + // Kensai, a counter technique = counter, S31): a strike that reaches him in the active frames is caught and answered - the front + // barrier catches grounded attackers, the diagonal one airborne attackers. '97 behaviour inferred from '98UM: approximation. + barrier:move('barrier',3,20,22,90,1.6,'mid',{counter:'ground',chip:0,meter:10,hitstun:30,knockdown:true,knock:2.4}), + barrier_up:move('barrier_up',3,20,22,90,1.6,'mid',{counter:'air',chip:0,meter:10,hitstun:30,knockdown:true,knock:2.4}), + // v8: Orochi's close throw is a normal throw that cannot be escaped (S32 "the throw cannot be escaped"); it replaces v7's close + // "soul grab" command throw (the soul move is the super above). Numbers as the shared normal throw. + oro_throw:move('oro_throw',1,1,25,100,1.2,'throw',{hitstun:40,knock:2.6,knockdown:true,throw:true,commandThrow:true}), + marokare:move('marokare',42,8,42,260,27,'mid',{height:8,chip:50,stock:1,super:true,fullscreen:true,knockdown:true,hitstun:55}), + // ---- Orochi Team ('97 mid-bosses; rules v7, scenes added 2026-11-03). Move sets, commands and roles from S18 (decoded + // command table) / S19 (SNK official '97 hidden-character page); move functions from S20-S23. All frame counts, + // reach and damage are normalized approximations (frame-data sites S10/S12/SuperCombo-Yashiro still blocked). + // Yashiro of the Dry Earth: every special is a throw ('97: "one-frame throw", S20/S21); Hoeru Daichi = projectile + // beam, chargeable, unblockable at full charge (S20, version not stated). + // comboGrab: a command throw that also grabs an opponent still in hit stun (S02 combo rules: "throw specials can be canceled from normals into combos"). Since rules v8 every command throw carries it (Iori's Kuzukaze and + // Orochi's soul super too; v7 kept them out to leave the accepted scenes unchanged). + museru_daichi:move('museru_daichi',1,2,30,170,1.25,'throw',{throw:true,commandThrow:true,comboGrab:true,hitstun:45,knockdown:true,knock:2.6,meter:12}), + niragu_daichi:move('niragu_daichi',1,2,32,150,1.25,'throw',{throw:true,commandThrow:true,comboGrab:true,hitstun:45,knockdown:true,knock:2.4,meter:12}), + odoru_daichi:move('odoru_daichi',8,10,30,140,1.15,'throw',{throw:true,commandThrow:true,travel:9,hitstun:45,knockdown:true,knock:2.8,meter:12}), + // kujiku: leaping grab that ends behind the opponent and leaves it defenceless for a follow-up (no damage of its own, S21) + kujiku_daichi:move('kujiku_daichi',4,8,10,0,1.4,'throw',{throw:true,commandThrow:true,swap:true,launch:6,travel:14,hitstun:34,knock:0,meter:10}), + araburu_daichi:move('araburu_daichi',1,2,40,300,1.25,'throw',{throw:true,commandThrow:true,comboGrab:true,stock:1,super:true,hitstun:55,knockdown:true,knock:2.8}), + hoeru_daichi:move('hoeru_daichi',24,1,34,240,0,'mid',{chip:30,stock:1,super:true,projectile:true,chargeable:true,unblockableAtFull:true,shotW:1.2,shotH:1.6,shotSpeed:10}), + ankoku_jigoku:move('ankoku_jigoku',1,2,44,340,1.25,'throw',{throw:true,commandThrow:true,comboGrab:true,stock:1,super:true,hitstun:60,knockdown:true,knock:3}), + // Shermie, 'of the Raging Lightning' (Shermie of the Raging Lightning): almost no throws; keep-away with a placed lightning orb + // (Mugetsu no Raiun: slow, long-lasting, placed by button, S22/S23), short electric projectile, fast anti-air super. + yatanagi:move('yatanagi',10,1,22,90,0,'mid',{chip:10,meter:12,projectile:true,shotW:.8,shotH:.9,shotSpeed:9,shotLife:14,hitstun:24}), + shajitsu:move('shajitsu',12,7,24,100,2.4,'mid',{chip:8,meter:12,travel:5,hitstun:26,knockdown:true}), + // mugetsu: slow to appear, little recovery once out, the orb stays long (S22); position by button (placeDist / orbY) + mugetsu:move('mugetsu',22,1,14,110,0,'mid',{chip:12,meter:12,projectile:true,placed:true,hits:2,orbW:1.1,orbH:1.1,orbLife:80,placeDist:4}), + raijin:move('raijin',5,10,14,90,1.6,'high',{height:.7,chip:8,meter:10,air:true,launch:4,hitstun:24}), + // shukumei: '97 version hits several times but never knocks down (S23); ankoku_raiko: fast, usable as anti-air, no + // invincibility (S22/S23) + shukumei:move('shukumei',12,40,30,270,1.8,'mid',{height:1.0,chip:30,stock:1,super:true,travel:12,multi:[0,8,16,24,32],knockdown:false,hitstun:30}), + ankoku_raiko:move('ankoku_raiko',4,14,36,250,1.8,'mid',{height:1.25,boxH:2.3,chip:30,stock:1,super:true,knockdown:true,hitstun:50,multi:[0,4,8,12]}), + // Chris, 'of the Flames of Destiny' (Chris of the Flames of Destiny): rushdown; slow multi-hit fireball, hop-in rush, rising anti-air, + // unguardable strike-throw combo starter, Ankoku Orochinagi (chargeable) and the Daichi wo Harau Gouka fireball rush. + // taiyo: very slow multi-hit fireball, short range, short recovery (S21/S22); tsuki: rising anti-air (S21); kagami: + // hop-in rush that misses a crouching opponent (S22: does not hit a crouching opponent) - its box sits above crouch height; + // shishi: strike-throw, five flaming punches then a kick-up, effectively unguardable, a combo part (S21) + taiyo:move('taiyo',24,1,18,100,0,'mid',{chip:12,meter:12,projectile:true,hits:3,shotW:.9,shotH:1.0,shotSpeed:5.5,shotLife:50}), + tsuki:move('tsuki',4,12,28,130,1.7,'mid',{height:2.2,rising:true,chip:10,meter:12,launch:15,knockdown:true,hitstun:40}), + kagami:move('kagami',12,8,22,120,2.0,'mid',{height:1.95,boxH:.5,chip:10,meter:12,travel:11,hitstun:30,knockdown:true}), + shishi:move('shishi',3,30,28,200,1.5,'mid',{unblockable:true,groundOnly:true,multi:[0,5,10,15,20,25],capture:true,chip:0,meter:12,hitstun:45,knockdown:true,knock:2.6}), + gouka:move('gouka',10,40,30,270,1.9,'mid',{height:1.6,chip:30,stock:1,super:true,travel:12,invul:[0,10],multi:[0,10,20,30],knockdown:true,hitstun:50}), + ankoku_orochinagi:move('ankoku_orochinagi',16,16,30,260,5.1,'mid',{height:1.5,chip:40,stock:1,super:true,chargeable:true,knock:3.5,knockdown:true,hitstun:50}) + }; + Object.keys(M).forEach(function(id){M[id].reach*=KF.GEOMETRY_SCALE;M[id].height*=KF.GEOMETRY_SCALE;}); + // Grounded normals and throws cannot be air-guarded; air attacks, specials, supers and projectiles can (rules v4). + ['jab','low_jab','light_kick','low_kick','heavy_punch','sweep','heavy_kick','overhead','blowaway','throw'].forEach(function(id){M[id].gnormal=true;}); + KF.SUPER_FREEZE=16;// Riot of the Blood form (S03: jumps/dashes abnormally fast; S05: faster, stronger, wilder). Multipliers are approximations. + KF.FORM={orochi_iori:{walk:1.18,run:1.3,jump:1.25,lift:1.12,grav:1.25,back:1.2,dmg:1.1}};KF.SPEED=KF.FORM; + KF.airGuardable=function(a){return !!a&&!a.gnormal&&!a.throw;}; + KF.copy=function(v){return JSON.parse(JSON.stringify(v));}; + KF.isAir=function(f){return !f.grounded;}; + KF.reset=function(f,c,kind,player){ + f.kind=kind;f.player=player;f.x=player?7:20;f.y=0;f.vx=0;f.vy=0;f.facing=player?1:-1;f.w=1.05*KF.GEOMETRY_SCALE;f.h=2.55*KF.GEOMETRY_SCALE; + f.hp=f.max_hp=KF.HP;f.memberLife=KF.HP;f.members=f.member=1;f.floor=0;f.stockCap=KF.MAX_STOCKS;f.st='idle';f.stun=0;f.stunType='';f.stop=0;f.action=null;f.age=0;f.move=null; + f.grounded=true;f.crouching=false;f.running=false;f.invul=0;f.throwInvul=0;f.hitFlash=0;f.knockdown=false; + f.stocks=0;f.meter=0;f.maxMode=0;f.guardGauge=100;f.guardRecovery=0;f.guardBroken=0; + f.history=[];f.input={};f.prev={};f.pressAt={};f.queue=null;f.lastPress=null;f.queueAge=0;f.tapForward=-100;f.tapBack=-100; + f.clock=0;f.combo=0;f.comboTimer=0;f.lastDamage=0;f.lastHit='';f.atkHits={};f.shots=[];f.nextShot=0;f.heavyEdge=-100; + f.decision=0;f.intent={};f.jumpHeld=0;f.jumpType='';f.landLag=0;f.throwPending=null;f.aiFollow=null;f.cdEdge=-100;f.abEdge=-100;f.flash=0; + f.dmg=40;f.timer=0;f.stT=0;f.roundTimedOut=false;f.spd=KF.SPEED[kind]||null;f.airHit=false;f.dmgScale=1;f.roundStart=0;f.roundPause=0;f.round=1;f.verdict='';f.koTick=0; + }; + KF.box=function(f){var h=f.crouching?1.5*KF.GEOMETRY_SCALE:f.h;return {x:f.x,y:f.y+h/2,w:f.w,h:h};}; + // Extended limbs are hurtable (rules v7): from the first active frame through the first 40% of recovery a strike adds + // a limb box reaching to KF.LIMB_GAP short of its hitbox front. v6 hitboxes were fully disjoint (a heavy kick hit + // 2.76 u in front of a hurtbox that never moved), so a longer poke could never be whiff-punished or traded with. + KF.LIMB_GAP=.35; + KF.hurtBoxes=function(f){ + var body=KF.box(f),a=f.action; + if(!a||!a.reach||a.projectile||a.remote||a.fullscreen||a.throw||a.crossup||a.super||a.id==='oni_yaki'||a.rising||f.age<=a.start||f.age>a.start+a.active+Math.round(a.recovery*.4))return [body]; + var s=KF.GEOMETRY_SCALE,from=f.w/2,to=.15+a.reach-KF.LIMB_GAP;if(to<=from)return [body]; + return [body,{x:f.x+a.facing*(from+to)/2,y:f.y+(a.height||1.2),w:to-from,h:1.05*s,limb:true}]; + }; + KF.pushBox=function(f){var s=KF.GEOMETRY_SCALE;return {x:f.x,y:f.y+(f.grounded?1.1:1.6)*s,w:f.w,h:(f.grounded?2.2:1.4)*s};}; + KF.addMeter=function(f,amount){ + var cap=f.stockCap||KF.MAX_STOCKS;if(f.maxMode>0)return;f.meter+=Math.max(0,amount)*KF.METER_GAIN; + while(f.meter>=100&&f.stocks=cap)f.meter=Math.min(f.meter,99.99); + }; + // Team life pool (rules v7). A side fields `members` fighters of `memberLife` each; hp is the remaining pool and the + // current member is KO'd when hp reaches `floor` (the life of the members still waiting). The player is one member. + KF.life=function(f){return f.hp-(f.floor||0);}; + KF.lifeMax=function(f){return f.memberLife||f.max_hp;}; + KF.setupTeam=function(f,members,life){f.members=Math.max(1,members);f.member=1;f.memberLife=life;f.max_hp=f.members*life;f.hp=f.max_hp;f.floor=(f.members-1)*life;}; + KF.inputDirection=function(f,i){ + var dx=(i.right?1:0)-(i.left?1:0),dy=(i.jump?1:0)-(i.down?1:0),x=dx*f.facing; + return dy>0?(x<0?7:x>0?9:8):dy<0?(x<0?1:x>0?3:2):(x<0?4:x>0?6:5); + }; + KF.recordInput=function(f,i){ + var d=KF.inputDirection(f,i);if(!f.history.length||f.history[f.history.length-1].d!==d)f.history.push({d:d,t:f.clock}); + f.history=f.history.filter(function(h){return h.t>=f.clock-30;}); + var button=i.lp&&!f.prev.lp?'lp':i.lk&&!f.prev.lk?'lk':i.hp&&!f.prev.hp?'hp':i.hk&&!f.prev.hk?'hk':null; + if(i.hp&&!f.prev.hp||i.hk&&!f.prev.hk)f.heavyEdge=f.clock; + if(button){f.queue={button:button,t:f.clock};f.queueAge=0;f.lastPress={button:button,t:f.clock};} + var pa=f.pressAt||(f.pressAt={});['lp','lk','hp','hk'].forEach(function(b){if(i[b]&&!f.prev[b])pa[b]=f.clock;}); + f.input=Object.assign({},i);return {button:button,d:d}; + }; + // KOF97 accepts commands leniently / simplified (S02 '97 game system). Engineering rule (rules v4): the required + // directions must appear in order and finish within KF.MOTION_FINISH ticks of the button; an interior diagonal + // that lies between its two neighbours may be skipped (2-6 = 2-3-6, 6-2-4 = 6-3-2-1-4, 2-4-2-6 = 2-1-4-1-2-3-6); + // up to two stray entries next (on the stick ring) to the expected or the just-matched direction are tolerated, + // which is what rolling a stick or pressing keys in sequence produces (4-1-2-1 still reads as 4-2-1). Opposite or + // unrelated directions break the motion. + var RING=[6,3,2,1,4,7,8,9]; + function ringDist(a,b){var i=RING.indexOf(a),j=RING.indexOf(b);if(i<0||j<0)return 9;var d=Math.abs(i-j);return Math.min(d,8-d);} + KF.MOTION_FINISH=10;KF.ringDist=ringDist;KF.KARA=3;KF.AIR_LAND=6;KF.CHORD=3; + // Button chords (A+B roll, A+B+C MAX, C+D blowaway) must be pressed together (rules v7): every button held now, one of + // them pressed this tick, all pressed within KF.CHORD ticks. v6 fired when one button joined others already held, so + // holding A+B and later pressing C spent a stock on MAX. + KF.chord=function(f,i,bs){var pa=f.pressAt||{},lo=Infinity,hi=-Infinity,fresh=false; + for(var k=0;k=f.clock-(window||22)&&q.d!==5;}),at=sequence.length-1,stray=0,dur1=99; + // The first direction may be omitted when the next one is the diagonal beside it and that diagonal was only + // passed through (<= 8 ticks) with nothing else before it in the window: rolling 2+6 inside one 33 ms sample gives + // 3-6, which still reads as 2-3-6; holding down-forward, or arriving at it from another direction, does not. + var lead=sequence.length>2&&sequence[1]%2===1&&ringDist(sequence[0],sequence[1])===1,k; + if(!h.length||f.clock-h[h.length-1].t>KF.MOTION_FINISH)return false; + for(k=h.length-1;k>=0&&at>=0;k--){ + var d=h[k].d,need=sequence[at]; + if(d===need){if(at===1)dur1=(k+10&&at0||f.action&&f.action.id!=='guard'||f.stun>0&&f.stunType!=='block')return false; + var back=attacker.x>f.x?f.input.left:f.input.right; + if(!back)return false; + if(!f.grounded)return KF.airGuardable(attack); // ADVANCED air guard ('96 system, S02) + return level==='low'?!!f.input.down:level==='high'?!f.input.down:true; + }; + KF.vulnerable=function(f,throwing){ + if(KF.life(f)<=0)return false; + if(throwing)return f.grounded&&!f.knockdown&&f.throwInvul<=0&&f.stun<=0; + // A knocked-down / blown-away fighter cannot be hit until it is back up (rules v7). S02 dates the first moves that + // can hit "airborne or downed states that cannot normally be followed up" to '99, so '97 has no down attacks; v6 allowed a sweep loop on a + // downed opponent (13 of 14 hits landed on the floor). + if(f.knockdown&&f.stun>0||f.airHit&&!f.grounded)return false; + if(f.invul>0)return false; + var a=f.action;if(a&&a.invul&&f.age>=a.invul[0]&&f.age=2&&f.age<23)return false; + return true; + }; + // A combo grab also takes an opponent standing in hit stun (not block stun, knockdown or air): command throws (v8: all). + KF.grabbable=function(f){return KF.vulnerable(f,true)||KF.life(f)>0&&f.grounded&&!f.knockdown&&f.stun>0&&f.stunType==='hit'&&!f.throwPending;}; + KF.start=function(f,c,id,opponent,extra){ + var a=M[id];if(!a)return false; + if(a.stock&&f.stocks0){a.damage=Math.round(a.damage*1.45);a.chip=Math.round(a.chip*1.4);a.powered=true;} + var trigger=f.input.super?'super':f.queue?f.queue.button:null; + f.action=Object.assign(a,extra||{});f.age=0;f.move=id;f.st='startup';f.atkHits={};f.queue=null;f.running=false; + if(a.chargeable){f.action.charge=0;f.action.chargeEnd=false;f.action.heldButton=trigger;} + f.action.facing=f.facing;f.action.targetX=opponent?opponent.x:f.x+f.facing*4;f.action.connected=false;f.action.spawned=false;f.action.startClock=f.clock; + if(a.launch){f.vy=a.launch;f.grounded=false;} + if(a.super){ + // Super flash: the screen darkens and both fighters pause (S02); the freeze is part of the deterministic clock. + var other=c.body===f?c.boss:c.body;f.stop=Math.max(f.stop,KF.SUPER_FREEZE);other.stop=Math.max(other.stop,KF.SUPER_FREEZE);f.flash=KF.SUPER_FREEZE; + } + KF.addMeter(f,a.meter);c.emit(a.super?'super_start':'fighter_attack',f.x,f.y+1.3);return true; + }; + // Rules v8: a super motion is read only when a stock is available; otherwise it reads as the special it ends with. + // Mu Shiki's official command (236236, S25) ends with Aragami / Dokugami's 236: without this rule two quick 236+P with no stock + // read as an unaffordable Mu Shiki and the second special was lost. Engineering rule (no '97 source on input priority). + KF.special=function(f,button){ + var punch=button==='lp'||button==='hp',heavy=button==='hp'||button==='hk'; + if(f.kind==='kyo'){ + // v8: Mu Shiki is 236236+A/C on SNK's official '97 page (S25); v7 read 2363214. + if(punch&&f.stocks>0&&KF.motion(f,[2,3,6,2,3,6],30))return 'mu_shiki'; + if(punch&&f.stocks>0&&KF.motion(f,[2,1,4,1,2,3,6],30))return 'orochi_nagi'; + if(punch&&KF.motion(f,[6,2,3],20))return 'oni_yaki'; + if(punch&&KF.motion(f,[2,3,6]))return heavy?'dokugami':'aragami'; + if(!punch&&KF.motion(f,[4,2,1],20))return 'red_kick'; + if(!punch&&KF.motion(f,[6,3,2,1,4],26))return 'kototsuki'; + if(!punch&&KF.motion(f,[2,3,6]))return 'kai75'; + }else if(f.kind==='iori'||f.kind==='orochi_iori'){ + // v8: the 7 moves of SNK's official list, the same for both forms (S19 / S25; S03 "the move properties do not change"). + // v7 removed Yami Barai from Riot Iori (10-31 task brief, OI-PROJ), lacked Kototsuki In / Yasakazuki and read Kuzukaze as 632146 + // (official: close 41236+A/C). + if(punch&&f.stocks>0&&KF.motion(f,[2,3,6,3,2,1,4],30))return 'yaotome'; + if(punch&&f.stocks>0&&KF.motion(f,[2,1,4,1,2,3,6],30))return 'yasakazuki'; + if(punch&&KF.motion(f,[4,1,2,3,6],26))return 'scum_gale'; + if(punch&&KF.motion(f,[6,2,3],20))return 'oni_yaki'; + if(!punch&&KF.motion(f,[6,3,2,1,4],26))return 'kototsuki_in'; + if(punch&&KF.motion(f,[2,1,4]))return 'aoihana'; + if(punch&&KF.motion(f,[2,3,6]))return 'yami_barai'; + }else if(f.kind==='orochi_yashiro'){ // S18/S19 ('97): 63214x2 / 41236x2 / 63214-6 / 41236 / 214, 236236 beam + if(punch&&f.stocks>0&&KF.motion(f,[6,3,2,1,4,6,3,2,1,4],36))return 'ankoku_jigoku'; + if(punch&&f.stocks>0&&KF.motion(f,[4,1,2,3,6,4,1,2,3,6],36))return 'araburu_daichi'; + if(punch&&f.stocks>0&&KF.motion(f,[2,3,6,2,3,6],30))return 'hoeru_daichi'; + if(punch&&KF.motion(f,[6,3,2,1,4,6],30))return 'museru_daichi'; + if(punch&&KF.motion(f,[4,1,2,3,6],26))return 'niragu_daichi'; + if(!punch&&KF.motion(f,[4,1,2,3,6],26))return 'odoru_daichi'; + if(punch&&KF.motion(f,[2,1,4]))return 'kujiku_daichi'; + }else if(f.kind==='orochi_shermie'){ // S18/S19: 214+P / 214+K / 41236+any / air 236+K, 2141236+K (v8; v7 read 2363214), 236236+P + if(!punch&&f.stocks>0&&KF.motion(f,[2,1,4,1,2,3,6],30))return 'shukumei'; + if(punch&&f.stocks>0&&KF.motion(f,[2,3,6,2,3,6],30))return 'ankoku_raiko'; + if(KF.motion(f,[4,1,2,3,6],26))return 'mugetsu'; + if(punch&&KF.motion(f,[2,1,4]))return 'yatanagi'; + if(!punch&&KF.motion(f,[2,1,4]))return 'shajitsu'; + }else if(f.kind==='orochi_chris'){ // S19: 214 / 623 / close 41236 +P, 236+K (v8: S19 shows B/D, S18 A/C), 236236 / 2141236 +P + if(punch&&f.stocks>0&&KF.motion(f,[2,1,4,1,2,3,6],30))return 'ankoku_orochinagi'; + if(punch&&f.stocks>0&&KF.motion(f,[2,3,6,2,3,6],30))return 'gouka'; + if(punch&&KF.motion(f,[4,1,2,3,6],26))return 'shishi'; + if(punch&&KF.motion(f,[6,2,3],20))return 'tsuki'; + if(punch&&KF.motion(f,[2,1,4]))return 'kagami'; + if(!punch&&KF.motion(f,[2,3,6]))return 'taiyo'; + } + return null; + }; + KF.SPECIALS={aragami:1,dokugami:1,oni_yaki:1,kai75:1,red_kick:1,kototsuki:1,kototsuki_in:1,yami_barai:1,aoihana:1,scum_gale:1,harae:1,mirror:1,pillar:1,barrier:1,barrier_up:1, + museru_daichi:1,niragu_daichi:1,odoru_daichi:1,kujiku_daichi:1,yatanagi:1,shajitsu:1,mugetsu:1,taiyo:1,tsuki:1,kagami:1,shishi:1}; + KF.CHAINS={aragami:['kono_kizu','yano_sabi','nanase'],kono_kizu:['yano_sabi','nanase'],dokugami:['tsumi_yomi'],tsumi_yomi:['batsu_yomi'],kai75:['kai75_follow'],aoihana:['aoihana2'],aoihana2:['aoihana3']}; + // KOF97 cancels (S02 combos, rules v7): a cancelable normal -> special, super or command normal; a special -> only its + // own follow-up. No normal -> normal chains (v6 let J/K/C cancel into each other: a 49-hit corner infinite) and no + // special -> super cancel (the series added super cancels in '99 / 2001). A canceled command normal loses its overhead + // property (S02: command normals change properties when canceled into, e.g. becomes crouch-guardable). + KF.cancel=function(f,c,id,o){ + if(!f.action||!f.action.connected||!f.action.cancel||f.agef.action.start+f.action.active+13||!M[id])return false; + var from=f.action.id,normal=!!M[from]&&!!M[from].gnormal; + if((KF.CHAINS[from]||[]).indexOf(id)>=0)return KF.start(f,c,id,o); + if(!normal)return false; + if(id==='overhead')return KF.start(f,c,id,o,{level:'mid',canceled:true}); + return (KF.SPECIALS[id]||M[id].super)?KF.start(f,c,id,o):false; + }; + KF.roll=function(f,c,back,cancel){ + if(!f.grounded||f.stocks< (cancel?1:0))return false; + if(cancel)f.stocks--; + f.stun=0;f.stunType='';f.action={id:'roll',start:0,active:23,recovery:9,facing:f.facing,back:!!back};f.age=0;f.move='roll';f.st='active';f.running=false; + c.emit(cancel?'guard_cancel_roll':'roll',f.x,f.y);return true; + }; + KF.activateMax=function(f,c){ + if(!f.grounded||f.stocks<1||f.maxMode>0||f.stun>0||f.action)return false; + f.stocks--;f.maxMode=KF.MAX_TICKS;f.action={id:'max',start:0,active:0,recovery:16};f.age=0;f.move='max';f.st='recovery';c.emit('max_mode',f.x,f.y+1);return true; + }; + KF.commandFromInput=function(f,c,o,i,press){ + var b=press.button; + if(i.special&&!f.prev.special)return f.kind==='kyo'?'aragami':'yami_barai'; + if(i.super&&!f.prev.super)return f.kind==='kyo'?'orochi_nagi':'yaotome'; + if(!b&&f.queue&&f.clock-f.queue.t<=10)b=f.queue.button; + if(!b)return null; + var punch=b==='lp'||b==='hp',heavy=b==='hp'||b==='hk'; + if(f.action&&f.action.connected){ + if(f.action.id==='aragami'&&punch&&KF.motion(f,[2,3,6]))return 'kono_kizu'; + if(f.action.id==='aragami'&&punch&&KF.motion(f,[6,3,2,1,4],26))return 'yano_sabi'; + if(f.action.id==='kono_kizu')return punch?'yano_sabi':'nanase'; + if(f.action.id==='dokugami'&&punch&&KF.motion(f,[6,3,2,1,4],26))return 'tsumi_yomi'; + if(f.action.id==='tsumi_yomi'&&punch&&press.d===6)return 'batsu_yomi'; // v8: Batsu Yomi = during Tsumi Yomi: →+A/C (S18, S27); v7 required 63214 + if(f.action.id==='kai75'&&!punch)return 'kai75_follow'; + } + if(!f.grounded&&f.kind==='orochi_shermie'&&!punch&&KF.motion(f,[2,3,6]))return 'raijin'; + if(!f.grounded)return f.kind==='kyo'&&i.down&&b==='hp'?'naraku':punch?'air_punch':'air_kick'; + var special=KF.special(f,b);if(special)return special; + if(heavy&&(press.d===4||press.d===6)&&Math.abs(f.x-o.x)<1.3*KF.GEOMETRY_SCALE&&KF.vulnerable(o,true))return 'throw'; + if(b==='lk'&&press.d===6&&!i.down)return 'overhead'; + return punch?(heavy?'heavy_punch':i.down?'low_jab':'jab'):(heavy?i.down?'sweep':'heavy_kick':i.down?'low_kick':'light_kick'); + }; + KF.update=function(f,c,i,o){ + f.clock++;f.hitFlash=Math.max(0,f.hitFlash-1/60);f.prev=f.prev||{};f.flash=Math.max(0,(f.flash||0)-1); + if(!f.action&&f.grounded&&!f.stun&&Math.abs(o.x-f.x)>.08)f.facing=o.x>f.x?1:-1; + var press=KF.recordInput(f,i),d=press.d,oldY=f.y; + // Guard-cancel inputs are buffered for 10 ticks so a press made during the block hit-stop still counts (rules v4). + // ...and only presses made while already in block stun count (v7): v6 also spent a stock on a roll / C+D pressed + // up to 10 ticks BEFORE the block, i.e. an attack or roll attempt silently became a paid guard cancel. + var inBlock=f.stun>0&&f.stunType==='block'; + if(inBlock&&KF.chord(f,i,['hp','hk']))f.cdEdge=f.clock; + if(inBlock&&(i.roll&&!f.prev.roll||!i.hp&&KF.chord(f,i,['lp','lk'])))f.abEdge=f.clock; + if(f.stop>0){f.stop--;f.prev=Object.assign({},i);return;} + f.invul=Math.max(0,f.invul-1);f.throwInvul=Math.max(0,f.throwInvul-1);f.landLag=Math.max(0,f.landLag-1); + f.maxMode=Math.max(0,f.maxMode-1);f.comboTimer=Math.max(0,f.comboTimer-1);if(!f.comboTimer)f.combo=0; + f.guardBroken=Math.max(0,f.guardBroken-1);f.guardRecovery++; + if(f.guardRecovery>90)f.guardGauge=Math.min(100,f.guardGauge+.16); + if(f.stun>0){ + if(f.stunType==='block'&&f.grounded&&f.clock-f.cdEdge<=10&&f.stocks>0){ + f.cdEdge=-100;f.stocks--;f.stun=0;f.stunType='';KF.start(f,c,'blowaway',o,{invul:[0,17],guardCancel:true});c.emit('guard_cancel_blowaway',f.x,f.y+1); + }else if(f.stunType==='block'&&f.grounded&&f.clock-f.abEdge<=10&&f.stocks>0){f.abEdge=-100;KF.roll(f,c,d===4,true);} + else {f.stun=f.airHit&&!f.grounded?Math.max(1,f.stun-1):f.stun-1;f.vx*=.87;if(f.stun<=0){f.stunType='';f.knockdown=false;f.throwInvul=8;}f.st='stun';} + } + if(KF.life(f)<=0){ // KO'd: no control, but keep falling / sliding to the floor (visible during the round break) + f.st='dead';f.action=null;f.vx*=.9;if(f.y>0||!f.grounded){f.vy=Math.max(-22,f.vy-40/60);f.y=Math.max(0,f.y+f.vy/60);if(f.y<=0){f.grounded=true;f.vy=0;}} + f.x=BB.clamp(f.x+f.vx/60,.65,26.35);f.prev=Object.assign({},i);return;} + if(!f.stun&&!f.landLag){ + var max=i.max&&!f.prev.max||KF.chord(f,i,['lp','lk','hp']),roll=!max&&(i.roll&&!f.prev.roll||!i.hp&&KF.chord(f,i,['lp','lk'])),cd=KF.chord(f,i,['hp','hk']); + var id=KF.commandFromInput(f,c,o,i,press); + if(f.action){ + if(id&&id!==f.action.id)KF.cancel(f,c,id,o); + else if(!id&&f.action.gnormal&&!f.action.connected&&f.lastPress&&f.lastPress.t===f.action.startClock&&f.clock-f.lastPress.t<=KF.KARA){ + // Button buffer: when the motion completes up to KF.KARA ticks after the button (keys pressed in sequence), + // the normal that the press started is upgraded to the special during its startup (rules v5). + var up=KF.special(f,f.lastPress.button),keep={a:f.action,age:f.age,move:f.move,st:f.st}; + if(up&&up!==f.action.id){f.action=null;if(!KF.start(f,c,up,o)){f.action=keep.a;f.age=keep.age;f.move=keep.move;f.st=keep.st;}} + } + } + else if(max&&f.grounded)KF.activateMax(f,c); + else if(roll&&f.grounded)KF.roll(f,c,d===4,false); + else if(cd)KF.start(f,c,'blowaway',o); + else if(id){KF.start(f,c,id,o);} + else{ + var dir=(i.right?1:0)-(i.left?1:0),forward=dir*f.facing,sp=f.spd||{}; + f.crouching=!!i.down&&f.grounded;f.st=f.crouching?'crouch':'idle'; + if(forward===1&&!((f.prev.right?1:0)-(f.prev.left?1:0))){if(f.clock-f.tapForward<=14)f.running=true;f.tapForward=f.clock;} + if(forward===1&&i.run)f.running=true; // opponent intent: run without re-tapping (same speed rules) + if(forward===-1&&!((f.prev.right?1:0)-(f.prev.left?1:0))&&f.clock-f.tapBack<=14){ + f.action={id:'backstep',start:0,active:16,recovery:12,facing:f.facing};f.age=0;f.move='backstep';f.vy=5*(sp.lift||1);f.grounded=false;f.running=false;f.st='active'; + } + if(forward===-1&&!((f.prev.right?1:0)-(f.prev.left?1:0)))f.tapBack=f.clock; + if(!dir||forward<0)f.running=false; + if(!f.action){ + if(f.grounded)f.vx=f.crouching?0:dir*(f.running?8.6*(sp.run||1):(forward<0?4.0:5.1)*(sp.walk||1)); + if(i.jump&&!f.prev.jump&&f.grounded){ + var hyper=f.running||f.prev.down;f.jumpType=hyper?'super_jump':'jump';f.vy=(hyper?16.5:14)*(sp.lift||1);f.vx=dir*(hyper?7.8:5.8)*(sp.jump||1);f.grounded=false;f.jumpHeld=0;f.crouching=false;f.st='air';c.emit('jump',f.x,f.y); + } + } + } + } + if(f.action){ + var a=f.action,total=a.start+a.active+a.recovery;f.st=f.age=a.start&&f.age=90)f.shots[f.shots.length-1].unblockable=true; + if(a.bind)f.shots[f.shots.length-1].bind=a.bind; // v8: Yasakazuki + c.emit('fighter_projectile',f.x,f.y+.4); + } + if(a.captured&&KF.life(o)>0){o.x=BB.clamp(f.x+a.facing*1.4*KF.GEOMETRY_SCALE,.65,26.35);o.y=0;o.vx=o.vy=0;o.grounded=true;o.airHit=false;} + // Pull-in super (v8, Orochi): during the active frames a grounded opponent in front within pull.range is drawn in; the + // grab box then takes it. Jumping, or staying out of range, makes it whiff (S28). + if(a.pull&&!a.connected&&f.age>a.start&&f.age<=a.start+a.active&&KF.life(o)>0&&o.grounded&&(o.x-f.x)*a.facing>0&&Math.abs(o.x-f.x)=total){f.action=null;f.move=null;f.st=f.grounded?'idle':'air';f.atkHits={};} + } + if(!f.grounded){ + if(!f.action&&f.jumpType&&f.jumpHeld<5&&!i.jump){f.vy=Math.min(f.vy,8.8);f.jumpType=f.jumpType==='super_jump'?'hyper_hop':'hop';} + f.jumpHeld++;f.vy=Math.max(-22,f.vy-40/60*(f.spd&&f.spd.grav||1)); + } + f.x=BB.clamp(f.x+f.vx/60,.65,26.35);f.y=Math.max(0,f.y+f.vy/60); + if(f.y<=0&&(!f.grounded||oldY>0)){f.grounded=true;f.vy=0;f.jumpType='';f.landLag=3;f.crouching=!!i.down; + if(f.airHit){f.airHit=false;if(!f.knockdown)f.stun=Math.min(f.stun,KF.AIR_LAND);} + if(f.action&&f.action.air){f.action=null;f.move=null;f.age=0;}c.emit('land',f.x,0);} + f.shots=f.shots.filter(function(p){p.oldX=p.x;p.x+=p.vx/60;p.life--;if(p.gap>0)p.gap--;return p.life>0&&p.x>0&&p.x<27;}); + f.prev=Object.assign({},i); + }; + KF.attackBoxes=function(f){ + var a=f.action;if(!a||f.age<=a.start||f.age>a.start+a.active||a.damage<=0&&!a.throw||a.projectile||a.counter||a.id==='roll'||a.id==='backstep')return []; + var key='attack';if(a.multi){ + var at=-1,elapsed=f.age-a.start-1;for(var i=0;i=a.multi[i]&&elapsed=a.x?1:-1,penetration=half-Math.abs(a.x-b.x);if(penetration<=0)return; + a.x=BB.clamp(a.x-sign*penetration/2,.65,26.35);b.x=BB.clamp(b.x+sign*penetration/2,.65,26.35); + var left=half-Math.abs(a.x-b.x);if(left>0){if(a.x<=.65||a.x>=26.35)b.x=BB.clamp(b.x+sign*left,.65,26.35);else a.x=BB.clamp(a.x-sign*left,.65,26.35);} + }; + KF.hit=function(attacker,victim,c,a,projectile,snapshot){ + if(snapshot?!snapshot.allowed:!KF.vulnerable(victim,!!a.throw))return false; + if(a.throw){ + if(!a.commandThrow){victim.throwPending={from:attacker.player?'player':'boss',frames:7,started:victim.clock,damage:a.damage,dir:a.facing,hitstun:a.hitstun};victim.stun=9;victim.stunType='throw';victim.action=null;victim.move=null;c.emit('throw_start',victim.x,victim.y+1);return true;} + } + var blocked=snapshot?snapshot.blocked:!a.throw&&KF.guard(victim,attacker,a.level,a),counter=snapshot?snapshot.counter:!blocked&&victim.action&&victim.st==='startup'; + // A combo is a hit that lands while the victim is still in hit stun. v6 counted (and damage-scaled) any hit within + // 50 ticks, so 40% of fresh hits were scaled and shown as "HITS" although the victim had recovered (rules v7). + if(!blocked&&!(victim.stun>0&&victim.stunType==='hit'))attacker.combo=0; + var base=blocked?a.chip||0:a.damage,scale=(attacker.maxMode>0?1.2:1)*(attacker.spd&&attacker.spd.dmg||1)*(attacker.dmgScale||1); + if(!blocked&&attacker.combo>0)scale*=Math.max(.55,1-attacker.combo*.08); + if(victim.maxMode>0)scale*=.85; + var damage=Math.max(0,Math.round(base*scale*(counter?1.15:1))); + victim.hp=Math.max(victim.floor||0,victim.hp-damage);victim.lastDamage=damage;victim.lastHit=blocked?'block':counter?'counter':'hit'; + victim.stun=blocked?a.blockstun:a.hitstun+(counter?5:0);victim.stunType=blocked?'block':'hit';victim.running=false; + // Gauge (S01/S02): strikes and specials fill it; guarding or being hit adds only a little ("slightly"). KF.GAIN (v7). + // Bind (v8, Yasakazuki): no push, the victim stands still until the next hit replaces the stun or a.bind ticks pass. + if(a.bind&&!blocked){victim.stun=a.bind;victim.stunType='bind';} + if(!blocked){victim.action=null;victim.move=null;victim.knockdown=!!a.knockdown;victim.vx=a.bind?0:a.facing*(a.knock||1.7)*3;victim.hitFlash=.14;victim.combo=0;victim.comboTimer=0;attacker.combo++;attacker.comboTimer=50;KF.addMeter(attacker,KF.GAIN.hit);KF.addMeter(victim,damage*KF.GAIN.hurt);} + else{victim.guardGauge-=Math.max(4,(a.damage||20)*.1);victim.guardRecovery=0;victim.vx=a.facing*2.5;KF.addMeter(attacker,KF.GAIN.block);KF.addMeter(victim,KF.GAIN.guard); + if(victim.guardGauge<=0){victim.guardGauge=100;victim.guardBroken=55;victim.stun=55;victim.stunType='guard_break';victim.action=null;c.emit('guard_break',victim.x,victim.y+1);}} + a.connected=true;if(attacker.action){attacker.action.connected=true;if(a.capture&&!blocked){var last=a.multi&&a.part===a.multi.length-1;attacker.action.captured=!last;if(last)attacker.action.captureComplete=true;}} + attacker.stop=victim.stop=a.super?12:blocked?7:counter?11:9; + // An airborne victim falls out of the hit and cannot be hit again before landing (rules v7: no unlimited juggles). + if(!blocked&&!victim.grounded&&!a.capture){victim.airHit=true;victim.vy=Math.min(victim.vy,a.knockdown?-4:4);} + c.emit(blocked?'fighter_block':'boss_hit',victim.x,victim.y+1.3);if(victim.player&&!blocked)c.emit('player_hit',victim.x,victim.y+1.3); + if(a.swap&&!blocked&&KF.life(victim)>0){var dx=victim.x-attacker.x,nx=BB.clamp(victim.x+dx,.65,26.35),sep=(attacker.w+victim.w)/2; + if(Math.abs(nx-victim.x)0?1:-1)*sep,.65,26.35);attacker.x=nx;victim.vx=0;} + if(KF.life(victim)<=0){victim.st='dead';victim.action=null;victim.koTick=c.t;victim.shots=[];c.emit('fighter_ko',victim.x,victim.y);} + return true; + }; + // Counter barrier (v8, Orochi): in its active frames a strike that touches him is caught (front barrier: grounded attacker; + // diagonal-up barrier: airborne attacker) and answered once with the barrier's own hit. Throws and projectiles are not + // caught (the reflector handles projectiles), nor an attacker that cannot be hit at that moment. + KF.counterHit=function(v,f,c,h){var b=v.action; + if(!b||!b.counter||b.connected||v.age<=b.start||v.age>b.start+b.active||h.attack.throw||KF.life(v)<=0||(b.counter==='air')!==!f.grounded||!KF.vulnerable(f,false))return false; + KF.hit(v,f,c,Object.assign({},b,{facing:v.facing}),false,{allowed:true,blocked:false,counter:false});c.emit('barrier_counter',v.x,v.y+1.3);return true;}; + // ---- rounds (rules v7): KOF '97 is a 3-on-3 elimination (S02 basic rules): a KO'd member is replaced next round and the + // round winner keeps its life plus a recovery that depends on the time left. Here the opponent side fields 1-3 + // members (by tier) against Kyo alone; each round has its own 99-count timer, decided on life ratio at time over. + KF.roundClock=function(c){return c.t-(c.boss.roundStart||0);}; + KF.rounds=function(c){ + var p=c.body,b=c.boss; + if(b.roundPause>0){if(--b.roundPause===0)KF.nextRound(c);return;} + if(KF.life(p)<=0||b.verdict||KF.life(b)<=0&&b.floor<=0)return; // match decided: KF.outcome reports it + var ko=KF.life(b)<=0; + // Time over on the round's last tick (the clock advances after resolve), or on the engine's episode cap (5 min). + if(!ko&&(KF.roundClock(c)>=KF.ROUND_TICKS-1||c.t>=BB.MAX_SECONDS*BB.FPS-1)){ + var pr=KF.life(p)/KF.lifeMax(p),br=KF.life(b)/KF.lifeMax(b);p.roundTimedOut=b.roundTimedOut=true; + if(pr0)return KF.rounds(c); // round break: nobody can be hit + KF.pushboxes(a,b); + [a,b].forEach(function(v){if(v.throwPending){ + var p=v.throwPending,attacker=p.from==='player'?a:b; + if(v.heavyEdge>=p.started&&p.frames>0){v.throwPending=null;v.stun=14;attacker.stun=14;v.stunType=attacker.stunType='throw_escape';v.x=BB.clamp(v.x+p.dir*1,.65,26.35);attacker.x=BB.clamp(attacker.x-p.dir*1,.65,26.35);c.emit('throw_escape',v.x,v.y);} + else if(--p.frames<=0){v.throwPending=null;KF.hit(attacker,v,c,{throw:true,commandThrow:true,damage:p.damage,hitstun:p.hitstun,knock:2.7,facing:p.dir,knockdown:true},false,{allowed:KF.life(v)>0,blocked:false,counter:false});} + }}); + // Collect both active hitboxes before applying hitstun, preserving genuine same-frame trades. + var attacks=[{f:a,v:b,boxes:KF.attackBoxes(a)},{f:b,v:a,boxes:KF.attackBoxes(b)}],contacts=[]; + attacks.forEach(function(e){var hurt=KF.hurtBoxes(e.v);e.boxes.forEach(function(h){if(!e.f.atkHits[h.key]&&(h.attack.throw?BB.overlap(h.box,hurt[0]):hurt.some(function(q){return BB.overlap(h.box,q);}))){var blocked=!h.attack.throw&&KF.guard(e.v,e.f,h.attack.level,h.attack);contacts.push({f:e.f,v:e.v,h:h,s:{allowed:(h.attack.comboGrab?KF.grabbable(e.v):KF.vulnerable(e.v,!!h.attack.throw))&&!(h.attack.groundOnly&&!e.v.grounded),blocked:blocked,counter:!blocked&&!!e.v.action&&e.v.st==='startup'}});}});}); + contacts.forEach(function(e){if(KF.counterHit(e.v,e.f,c,e.h)){e.f.atkHits[e.h.key]=true;return;}if(KF.hit(e.f,e.v,c,e.h.attack,false,e.s))e.f.atkHits[e.h.key]=true;}); + a.shots=a.shots.filter(function(p){return !b.shots.some(function(q){if(q.dead)return false;if(BB.overlap({x:p.x,y:p.y,w:p.w,h:p.h},{x:q.x,y:q.y,w:q.w,h:q.h})){q.dead=true;c.emit('projectile_clash',p.x,p.y);return true;}return false;});}); + b.shots=b.shots.filter(function(p){return !p.dead;}); + var reflected=[]; + [{f:a,v:b},{f:b,v:a}].forEach(function(e){e.f.shots=e.f.shots.filter(function(p){ + var hurt=KF.hurtBoxes(e.v),swept={x:(p.oldX+p.x)/2,y:p.y,w:Math.abs(p.x-p.oldX)+p.w,h:p.h}; + if(e.v.action&&e.v.action.reflect&&e.v.age>e.v.action.start&&e.v.age<=e.v.action.start+e.v.action.active&&BB.overlap(swept,{x:e.v.x+e.v.facing*.9*KF.GEOMETRY_SCALE,y:1.1*KF.GEOMETRY_SCALE,w:1.8*KF.GEOMETRY_SCALE,h:2.2*KF.GEOMETRY_SCALE})){ + reflected.push({f:e.v,p:Object.assign({},p,{id:++e.v.nextShot,vx:-p.vx,owner:e.v.player?'player':'boss',x:e.v.x+e.v.facing,oldX:e.v.x+e.v.facing})});c.emit('projectile_reflect',e.v.x,1);return false; + } + // Multi-hit shots (Orochi's shockwave) stay alive for their remaining hits, one contact per 8 ticks. + if(hurt.some(function(q){return BB.overlap(swept,q);})&&!(p.gap>0)){var n=p.hits||1; + var pa={damage:Math.round(p.damage/n),chip:Math.max(1,Math.round(p.chip/n)),level:p.level,facing:p.vx>0?1:-1,hitstun:24,blockstun:16,knock:n>1?.6:1.6,projectile:true};if(p.unblockable)pa.unblockable=true;if(p.bind)pa.bind=p.bind; + if(KF.hit(e.f,e.v,c,pa,true)){ + p.hits=n-1;p.gap=8;if(p.hits<=0)return false;}} + return true; + });});reflected.forEach(function(q){q.f.shots.push(q.p);}); + KF.rounds(c); + }; + KF.state=function(f){var out={};Object.keys(f).forEach(function(k){if(typeof f[k]!=='function')out[k]=f[k];});return KF.copy(out);}; + function Fighter(){} + var P=Fighter.prototype;P.id='kof_kyo';P.NAIL=0;P.HITSTOP=0;P.keys={left:'A',right:'D',down:'S',jump:'W|Space',lp:'J|LMB',lk:'K',hp:'L',hk:'Q',roll:'Shift',max:'E',super:'R'}; + P.manual=['A/D move; S crouch; W/Space jump. Tap for a hop; crouch first or run for a high jump. Double-tap forward to run or backward to backstep.', + 'J light punch (A), K light kick (B), L heavy punch (C), Q heavy kick (D). Hold back to guard; down-back blocks low, standing back blocks jumps and mids. Air back guards air attacks, specials, supers, and projectiles.', + 'J+K or Shift rolls; J+K+L or E enters MAX (one stock); L+Q knocks back, and guard-cancel knockback costs one stock. Press combination keys within 3 ticks. Use forward/back plus a heavy attack for a close throw; heavy attacks escape a normal throw.', + 'Flame Fist: ↓↘→+light punch rushes, heavy punch makes a stronger rush; →↓↘+punch is a rising flame punch; ↓↘→+kick is a rising kick; ←↓↙+kick is a leaping axe kick; →↘↓↙←+kick is a dashing knee.', + 'Supers require one stock; without it, the final motion becomes a special: ↓↘→↓↘→+punch is a multi-hit rush; ↓↙←↙↓↘→+punch is a charged flame sweep. R is a one-stock shortcut for the sweep. ADVANCED has no free low-health supers.', + 'Lenient inputs omit intermediate diagonals (↓→ = ↓↘→), and attack can precede the direction by 3 ticks. Super activation darkens the screen and freezes both fighters for 16 ticks. A super started in MAX becomes a MAX super without ending MAX.', + 'Normals cancel only into specials and supers; specials only into their own follow-ups. Downed or airborne opponents cannot be hit again before landing. Meter: hit +10, blocked strike +4, special +10–14, guarding +2, taking a hit +6% of damage; it carries between rounds.', + 'KOF elimination: difficulty sets 1, 2, or 3 opponents, each in a 99-second round. Timeouts use remaining health ratio. The next opponent enters 2 seconds after a KO; the winner recovers 10–40% health based on time left. Simulated at 60 Hz with 200 ms action packets.']; + P.reset=function(c){KF.reset(this,c,'kyo',true);};P.box=function(){return KF.box(this);};P.hurtBox=P.box; + P.centre=function(){return {x:this.x,y:this.y+1.3};};P.slashBox=function(){return null;};P.onSlashContact=function(){}; + P.update=function(c,i){KF.update(this,c,c.boss.roundPause>0?{}:i,c.boss);};P.resolveInteractions=KF.resolve; + P.hurt=function(c,dmg,fromX){if(!KF.vulnerable(this,false))return false;this.hp=Math.max(this.floor||0,this.hp-dmg);return true;}; + P.state=function(){return KF.state(this);};BB.KOFPlayer=Fighter; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/game.js b/environments/games/web/games/kof_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..4d863c96202b7df920774c4653bb2015b86a08a8 --- /dev/null +++ b/environments/games/web/games/kof_remake/game.js @@ -0,0 +1,15 @@ +(function(g){ + var BB=g.BB;BB.GAME={id:'kof_remake',title:'KOF97 · ADVANCED',rules:'kof97-advanced-v8',defaultCase:'kof97/iori',results:{win:'YOU WIN',loss:'YOU LOSE',timeout:'DRAW'},roster:[ + {id:'kof97/iori',name:'Violet Claw',arch:'Low purple fireball, triple claw slash, rising flame anti-air, dashing elbow, close throw, rushing claw super, and binding flame super'}, + {id:'kof97/orochi_iori',name:'Frenzied Claw',arch:'Frenzied close-range pressure: faster running and jumping, the same moves as Violet Claw (including the purple fireball), and more aggressive claw combos, jump attacks, and anti-air'}, + {id:'kof97/orochi',name:'Radiant Deity',arch:'Triple shockwave, reflecting mirror, counter barrier, position-locked light pillar, soul-grab super, and full-screen white-light super'}, + {id:'kof97/orochi_yashiro',name:'Grappler',arch:'Awakened trio, earth: all specials are command throws that can follow normals, very strong guard, and a long-range charged beam'}, + {id:'kof97/orochi_shermie',name:'Storm Dancer',arch:'Awakened trio, lightning: placed thunder orbs for zoning, a short-range electric projectile, and a meter-powered anti-air super; weaker up close'}, + {id:'kof97/orochi_chris',name:'Blaze Youth',arch:'Awakened trio, fire: slow multi-hit fireball followed by a rush, unblockable strike throw, wake-up throw, and dark flame sweep'}]}; + // Public tiers (2026-11-02, rules v7): easy / normal / hard = 1 / 2 / 3 opponents (KOF elimination), each with more + // life, aggression and damage (specs/*.spec.js `members`, `hp`, `dmg`, `aggression` ...). The continuous difficulty stays. + BB.GAME.tiers={easy:0,normal:0.5,hard:1}; + // Combat already freezes both actors on the deterministic clock. Avoid a second human-only pause. + var consume=BB.Juice.prototype.consume;BB.Juice.prototype.consume=function(c,R){consume.call(this,c,R);if(c.body.id==='kof_kyo')this.hitstop=0;}; + // Request a readback-friendly canvas to keep Chromium on a consistent rasterizer when capturing RGB observations. +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/index.html b/environments/games/web/games/kof_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a130a386d4a2342925bb48d12e6efe936bbb8f9e --- /dev/null +++ b/environments/games/web/games/kof_remake/index.html @@ -0,0 +1,33 @@ + +BossBench · KOF ’97 ADVANCED +
        +

        BOSSBENCH · KOF ’97 ADVANCED / Flame Fist Solo Challenge

        +

        Read attacks, control spacing, jump in, block low, and cancel combos. Face Violet Claw, the faster Frenzied Claw, Radiant Deity, and the awakened trio: Grappler, Storm Dancer, and Blaze Youth. In six KOF elimination challenges, difficulty sets a team of 1, 2, or 3 opponents, each with a 99-second round; your fighter carries one health bar through the match. Build meter for MAX mode and supers. Scripted Demo plays a Standard reference controller.

        +
        +

        SELECT YOUR OPPONENT

        +
        Difficulty Tier0.50
        +

        Three difficulty tiers: Easy has 1 opponent, Standard 2, and Hard 3. Opponent health rises from 2700 to 7900 per fighter, along with aggression and damage (×0.85 / ×1 / ×1.15). Your fighter carries one 4500-point health bar. Move timing and player health stay the same.

        +
        + +

        Flame Fist / Controls and Moves

          +
        • A/D move, S crouch, W/Space jump. Release quickly for a hop; crouch first or jump while running for a high jump. Double-tap forward to run, or backward to backstep.
        • +
        • J light punch (A), K light kick (B), L heavy punch (C), Q heavy kick (D). Left mouse button also throws a light punch.
        • +
        • Hold back to guard; down-back blocks low, standing back blocks jump and mid attacks. Hold back in the air to guard air attacks, specials, supers, and projectiles. Ground normals and throws cannot be air-guarded. Use forward/back plus a heavy attack for a close throw. Press a heavy attack within 7 ticks of being grabbed to escape a normal throw. Downed or airborne opponents cannot be hit again before landing.
        • +
        • Shift or A+B rolls through strikes but not throws; a guard-cancel roll costs one stock. J+K+L or E activates MAX for 10 seconds at the cost of one stock. L+Q knocks back; a guard-cancel knockback also costs one stock. Press combination keys within 3 ticks. Guard cancels require a fresh press during block stun, including hit stop.
        • +
        • ↓↘→+punch: rushing punch (light) or heavy rushing punch; →↓↘+punch: rising flame punch; ↓↘→+kick: rising kick; ←↓↙+kick: leaping axe kick; →↘↓↙←+kick: dashing knee.
        • +
        • ↓↙←↙↓↘→+punch: charged flame sweep (hold to charge); ↓↘→↓↘→+punch: multi-hit rushing super. Without meter, the final motion becomes a special. R is a shortcut for the charged sweep and costs one stock; up to three stocks can be held. Starting a super in MAX makes it stronger without ending MAX. Super activation darkens the screen and freezes both fighters for 16 ticks.
        • Inputs are lenient: intermediate diagonals may be omitted (↓→ counts as ↓↘→), and the attack button may be pressed up to 3 ticks before the direction.
        • +
        • After a rushing punch, ↓↘→+punch adds a straight punch, then punch adds a downward chop or kick adds a kick. After a heavy rushing punch, →↘↓↙←+punch adds a rush punch, then →+punch adds an elbow. Press kick after a rising kick for a second hit. A combo requires a hit or block: normals cancel only into specials or supers; specials only into their own follow-ups.
        • Meter: hit +10, blocked strike +4, special +10–14, guarding +2, taking a hit +6% of damage. Up to three stocks carry between rounds; each defeated opponent increases the cap by one, to five. Winners recover 10–40% health based on time left.
        • +

        Opponent Moves

          +

          Recording and Replay

          Save a replay after a match, or watch a recorded automated example.

          +

          Independent implementation with original visuals. Play Flame Fist against six opponents in an elimination benchmark. Move frames, hitboxes, and damage are approximations.

          +

          All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.

          +
          + + + + + + diff --git a/environments/games/web/games/kof_remake/scripted.js b/environments/games/web/games/kof_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..8576f59b5611a6a7941a86732633b4bc9e64e9ed --- /dev/null +++ b/environments/games/web/games/kof_remake/scripted.js @@ -0,0 +1,148 @@ +// Standard scripted reference controller (BB.GAME.scripted) for the trusted harness and the "Scripted Demo" button. +// It may read privileged state but never writes it: every candidate packet is tried on a deep copy of the case +// (fighters copied; the live case and RNG are untouched), continued with a defensive base policy for HORIZON +// packets, and scored by HP difference, knockdowns and gauge. The copy does NOT inherit the live RNG: each candidate +// is scored as the mean over VARIANTS synthetic RNG streams seeded from (case seed, tick), so the controller plays +// against the opponent's randomness instead of reading its future rolls. Deterministic: no Math.random, no wall clock. +// The packets it returns are ordinary legal key sets (<= 4 keys per hold set), identical to what a human could press. +(function(g){ + var BB=g.BB,KF=BB.KOF,HORIZON=5,VARIANTS=3; + function rep(n,h){var s=[];for(var i=0;i0?'D':'A',Bk=p.facing>0?'A':'D',to=b.x>p.x?'D':'A',away=b.x>p.x?'A':'D'; + return {p:p,b:b,F:F,Bk:Bk,to:to,away:away,dist:Math.abs(p.x-b.x)}; + } + // ---- base policy: used for the rollout continuation (and as the fallback when no candidate is better) ---- + function guard(r){return rep(6,K(r.away,r.b.grounded&&!(r.b.action&&r.b.action.id==='overhead')?'S':null));} + function base(c){ + var r=rel(c),p=r.p,b=r.b,a=p.action; + if(p.stun>0||p.throwPending)return guard(r); + // In MAX with a stock left and the opponent grounded in range: MAX super (rules v7 controller v3), so the lookahead + // sees what activating MAX is worth instead of only its stock cost. + if(!a&&p.grounded&&p.maxMode>30&&p.stocks>0&&r.dist<4.6&&b.grounded&&!(b.stun>0&&b.knockdown)&&!(b.action&&b.action.id==='roll'))return pad([K('R')]); + if(a){ + if(a.connected){ + if(a.id==='aragami')return pad([K('S'),K('S',r.F),K(r.F,'J')]); + if(a.id==='kono_kizu')return pad([K('K')]); + if(a.id==='dokugami')return pad([K(r.F),K('S',r.F),K('S'),K('S',r.Bk),K(r.Bk,'L')]); + if(a.id==='tsumi_yomi')return pad([K(r.F,'L')]); // rules v8: Batsu Yomi = forward + punch during Tsumi Yomi (S18 / S27) + if(a.id==='kai75')return pad([K('K')]); + // In MAX with a stock left, a connected normal is canceled into the MAX super (R); otherwise into Dokugami. + if(/jab|low_kick|light_kick|heavy_punch/.test(a.id))return p.maxMode>0&&p.stocks>0?pad([K('R')]):pad([K('S'),K('S',r.F),K(r.F,'L')]); + } + return guard(r); + } + if(!p.grounded)return r.dist<2.7?pad([K('K',r.to),K(r.to),K('K',r.to),K(r.to),K('K',r.to),K(r.to)]):rep(6,K(r.to)); + // Guard a single-hit projectile only when it is coming at Kyo and close (v3 rule); v2 froze in guard whenever any shot + // was on screen, so Iori's Yami Barai zoning stalled it at range for 30-40% of a fight. Orochi's multi-hit wave is + // still guarded on sight (walking into it doubled the spread of his fight lengths). + var threat=b.shots.some(function(s){var dx=p.x-s.x;return dx*s.vx>0&&((s.hits||1)>1||Math.abs(dx)<4.5);}); + // A stationary orb between Kyo and the opponent (only Shermie's Mugetsu no Raiun is placed with vx 0, so the rule is inert + // in every other scene): roll through it rather than stand guarding in front of it. + if(!threat&&b.shots.some(function(s){return s.vx===0&&(s.x-p.x)*(b.x-p.x)>0&&Math.abs(s.x-p.x)<3.2&&s.y<2.4*KF.GEOMETRY_SCALE;}))return pad([K('Shift',r.to)]); + if(b.action&&b.st!=='recovery'&&r.dist<5.2||threat)return guard(r); + if(r.dist>3.4)return rep(6,K(r.to)); + return guard(r); + } + // ---- candidate packets (facing-relative motions, position-relative guard/walk) ---- + var CANDS=[ + ['guard',function(r){return guard(r);}], + ['stand_guard',function(r){return rep(6,K(r.away));}], + ['walk',function(r){return rep(6,K(r.to));}], + ['run',function(r){return pad([K(r.F),{},K(r.F),K(r.F),K(r.F),K(r.F)]);}], + ['backstep',function(r){return pad([K(r.Bk),{},K(r.Bk)]);}], + ['jump',function(r){return pad([K('W',r.to),K('W',r.to),K('W',r.to),K(r.to),K(r.to),K(r.to)]);}], + ['hop',function(r){return pad([K('W',r.to),K(r.to),K(r.to),K(r.to),K(r.to),K(r.to)]);}], + ['super_jump',function(r){return pad([K('S'),K('W',r.to),K('W',r.to),K('W',r.to),K(r.to),K(r.to)]);}], + ['jab',function(){return pad([K('J'),{},K('J'),{},K('J'),{}]);}], + ['cr_jab',function(){return pad([K('S','J'),K('S'),K('S','J'),K('S'),K('S','J'),K('S')]);}], + ['lk',function(){return pad([K('K')]);}], + ['cr_lk',function(){return pad([K('S','K'),K('S'),K('S','K'),K('S'),K('S','K'),K('S')]);}], + ['hp',function(){return pad([K('L')]);}], + ['hk',function(){return pad([K('Q')]);}], + ['sweep',function(){return pad([K('S','Q'),K('S')]);}], + ['overhead',function(r){return pad([K(r.F,'K')]);}], + ['blowaway',function(){return pad([K('L','Q')]);}], + ['throw',function(r){return pad([K(r.F,'L')]);}], + ['aragami',function(r){return pad([K('S'),K('S',r.F),K(r.F,'J')]);}], + ['dokugami',function(r){return pad([K('S'),K('S',r.F),K(r.F,'L')]);}], + ['oniyaki',function(r){return pad([K(r.F),K('S'),K('S',r.F,'L')]);}], + ['kai75',function(r){return pad([K('S'),K('S',r.F),K(r.F,'K')]);}], + ['red_kick',function(r){return pad([K(r.Bk),K('S'),K('S',r.Bk,'K')]);}], + ['kototsuki',function(r){return pad([K(r.F),K('S',r.F),K('S'),K('S',r.Bk),K(r.Bk,'K')]);}], + ['roll_f',function(r){return pad([K('Shift',r.to)]);}], + ['roll_b',function(r){return pad([K('Shift',r.away)]);}], + ['gc_blowaway',function(){return pad([K('L','Q')]);},function(p){return p.stun>0&&p.stunType==='block'&&p.stocks>0;}], + ['max',function(){return pad([K('J','K','L')]);},function(p){return p.stocks>0&&!p.maxMode;}], + ['orochinagi',function(){return pad([K('R')]);},function(p){return p.stocks>0;}], + ['mu_shiki',function(r){return pad([K('S'),K(r.F),K('S'),K(r.F,'J')]);},function(p){return p.stocks>0;}], // v8: 236236 (S25) + ['idle',function(){return pad([]);}] + ]; + // ---- deep copy and scoring ---- + function copyFighter(f){return Object.assign(Object.create(Object.getPrototypeOf(f)),JSON.parse(JSON.stringify(f)));} + function copyCase(c,variant){ + var k=Object.create(BB.Case.prototype); + Object.assign(k,{id:c.id,def:c.def,arena:c.arena,seed:c.seed,d:c.d,t:c.t,trauma:0,options:c.options,result:c.result,events:[]}); + if(variant==null){k.rng=Object.create(BB.RNG.prototype);k.rng.a=c.rng.a;k.rng.b=c.rng.b;k.rng.c=c.rng.c;k.rng.d=c.rng.d;} + else k.rng=new BB.RNG((Math.imul(c.seed+1,0x9e3779b1)^Math.imul(c.t+1,0x85ebca6b)^Math.imul(variant+1,0xc2b2ae35))>>>0); + k.body=copyFighter(c.body);k.boss=copyFighter(c.boss); + // Information boundary (decided 2026-11-03, all six scenes): the copied opponent keeps what it has ALREADY decided and is + // carrying out now - held intent, a planned move, a scheduled throw tech (state that exists at this tick and plays out + // over the next 10-23 ticks). It never sees the live RNG, so rolls that do not exist yet stay unknown (the 2026-10-31 + // bug copied the live RNG into the lookahead). An opponent-blind variant was measured and not adopted. + return k; + } + function run(k,subs){for(var s=0;s<6;s++)for(var t=0;t<2;t++){if(k.result)return;k.tick(subs[s]);}} + function score(k,ref){ + var p=k.body,b=k.boss; + if(k.result==='win')return 1e6-k.t; + if(k.result==='loss')return -1e6+k.t; + if(k.result==='timeout')return -5e5; + var v=(ref.bhp-b.hp)-1.25*(ref.php-p.hp); + v+=22*(p.stocks-ref.ps)+.2*(p.meter-ref.pm)-14*(b.stocks-ref.bs); + // MAX is worth a stock only with another stock for the MAX super (v6 scored it 8 < 22 per stock: never used). + if(p.maxMode>0&&p.maxMode=1?30:6; + if(b.stun>0&&b.stunType==='hit')v+=b.knockdown?18:9; + if(p.stun>0&&p.stunType==='hit')v-=p.knockdown?22:11; + if(p.throwPending)v-=60;if(b.throwPending)v+=40; + if(p.stunType==='guard_break')v-=40;if(b.stunType==='guard_break')v+=30; + var edge=Math.min(p.x-.65,26.35-p.x);if(edge<1.2)v-=(1.2-edge)*6; // avoid being cornered + // Closing distance from range (v3): without it every quiet candidate tied at ~0 and the first one ('guard') won, so + // Kyo stood still under a zoning opponent (Orochi / Iori at range 25-55% of a fight). + if(ref.dist>3.4)v+=2*(Math.min(ref.dist,10)-Math.max(Math.abs(p.x-b.x),2.6)); + return v; + } + function evaluate(c,subs,ref){ + var sum=0,worst=Infinity;for(var v=0;vbestV+1e-9){bestV=v;best={name:cand[0],subs:subs};} + } + return best; + } + // ADVANCED resource plan (v3): with two stocks and a quiet mid-range moment, open MAX so the next super is a MAX super. + // The 1.2 s lookahead cannot see MAX's 10 s value, so without this rule it always spent stocks on a plain super. + function maxOpening(c){var r=rel(c),p=r.p,b=r.b; + if(p.stocks<2||p.maxMode>0||p.action||p.stun>0||!p.grounded||p.landLag>0||r.dist<2.8||r.dist>6.5||b.shots.length||b.action&&b.st!=='recovery'||!b.grounded)return null; + return {name:'max_open',subs:pad([K('J','K','L')])};} + var last=typeof WeakMap!=='undefined'?new WeakMap():null; + BB.GAME.scripted=function(c){ + // Round break (rules v7): input is ignored until the next member is in, so skip the lookahead. + var pick=c.boss.roundPause>0?{name:'break',subs:pad([])}:maxOpening(c)||choose(c); + if(last){if(c.t===0)last.delete(c);last.set(c,{t:c.t,name:pick.name});} + return {subs:pick.subs,mouse:[0,0,0]}; + }; + BB.GAME.scriptedInfo='kof97 rollout controller v3.1 (v3 + roll through a stationary orb): '+CANDS.length+' candidate packets x '+(HORIZON+1)+'-packet lookahead x '+VARIANTS+' synthetic opponent RNG streams on deep copies'; + BB.GAME.scriptedLast=function(c){return last&&last.get(c)||null;}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/kof_remake/specs/iori.spec.js b/environments/games/web/games/kof_remake/specs/iori.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..ba2c836557739afadc624b4c82751a133759972b --- /dev/null +++ b/environments/games/web/games/kof_remake/specs/iori.spec.js @@ -0,0 +1,247 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["iori"] = { + "schema": "bossbench/boss-spec@1", + "id": "iori", + "dims": "2d", + "family": "fighter2d", + "archetype": "Fighting-game duel: flame-fist player versus a violet-flame claw fighter; delayed-observation opponent", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "neutral", + "telegraph": "startup", + "active": "active", + "recovery": "recovery" + }, + "timing": { + "idle": { + "knob": "decision" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "delayed_perception", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "fighter_attack", + "active": "fighter_active" + }, + "moves": [ + { + "name": "ground_flame", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.23333, + "active": 0.01667, + "params": { + "startup_frames": 14, + "active_frames": 1, + "recovery_frames": 24, + "normalized": true + }, + "damage": 90, + "cue": "He crouches and pushes out a purple ground fireball", + "punish": "Jump the fireball and close in; the recovery after the shot can be punished" + }, + { + "name": "claw_chain", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.16667, + "active": 0.1, + "params": { + "startup_frames": 10, + "active_frames": 6, + "recovery_frames": 24, + "normalized": true + }, + "damage": 95, + "cue": "He leans in and slashes, and can chain three slashes", + "punish": "Block the last hit and punish; during pressure a power-defense cancel roll can get you out" + }, + { + "name": "rising_flame", + "atoms": [ + "leap" + ], + "telegraph_scale": 0.08333, + "active": 0.21667, + "params": { + "startup_frames": 5, + "active_frames": 13, + "recovery_frames": 30, + "normalized": true + }, + "damage": 155, + "cue": "He spins upward, with a brief invulnerable rise", + "punish": "Bait the dragon punch and counter the long recovery when he lands" + }, + { + "name": "close_grab", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.06667, + "active": 0.01667, + "params": { + "startup_frames": 4, + "active_frames": 1, + "recovery_frames": 15, + "normalized": true + }, + "damage": 0, + "cue": "Up close he spreads both arms", + "punish": "The command throw cannot be teched; jump or keep your distance" + }, + { + "name": "dash_elbow", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.23333, + "active": 0.23333, + "params": { + "startup_frames": 14, + "active_frames": 14, + "recovery_frames": 26, + "normalized": true + }, + "damage": 150, + "cue": "He lowers his body and dashes in with an elbow (restored in rules v8)", + "punish": "The recovery after a block is long enough for a guaranteed punish" + }, + { + "name": "binding_flame", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.36667, + "active": 0.01667, + "params": { + "startup_frames": 22, + "active_frames": 1, + "recovery_frames": 40, + "bind_frames": 90, + "normalized": true + }, + "damage": 40, + "cue": "Costs one bar. He pushes a slow blue-purple flame along the ground; a burn holds you until the next hit (restored in rules v8)", + "punish": "It comes out slowly and recovers slowly: jump it or block and counter. While held, you can only take the next hit" + }, + { + "name": "rush_frenzy", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.2, + "active": 1.2, + "params": { + "startup_frames": 12, + "active_frames": 72, + "recovery_frames": 34, + "normalized": true, + "approximate_combo_contacts": 8 + }, + "damage": 290, + "cue": "After spending one bar he dashes in and chains hits", + "punish": "Stand and block, then wait out the recovery. The MAX super hurts more" + } + ], + "difficulty": { + "hp": [ + 2700, + 3200, + 6400 + ], + "dmg": [ + 0.85, + 1, + 1.15 + ], + "members": [ + 1, + 2, + 3 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "reaction": [ + 24, + 13, + 7 + ], + "decision": [ + 23, + 15, + 10 + ], + "aggression": [ + 0.34, + 0.66, + 0.9 + ], + "defense": [ + 0.18, + 0.54, + 0.8 + ], + "combo": [ + 0.35, + 0.74, + 0.96 + ], + "tech": [ + 0.08, + 0.3, + 0.55 + ], + "gc": [ + 0.03, + 0.12, + 0.28 + ], + "entropy": [ + 1, + 1, + 1 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kof_remake/specs/orochi.spec.js b/environments/games/web/games/kof_remake/specs/orochi.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a82ec72f7a529102a66fdd1db1bbc4f3d8b6be68 --- /dev/null +++ b/environments/games/web/games/kof_remake/specs/orochi.spec.js @@ -0,0 +1,247 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["orochi"] = { + "schema": "bossbench/boss-spec@1", + "id": "orochi", + "dims": "2d", + "family": "fighter2d", + "archetype": "Fighting-game duel: flame-fist player versus a radiant deity (shockwave, mirror, pillar, barriers, screen flash); delayed-observation opponent", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "neutral", + "telegraph": "startup", + "active": "active", + "recovery": "recovery" + }, + "timing": { + "idle": { + "knob": "decision" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "delayed_perception", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "fighter_attack", + "active": "fighter_active" + }, + "moves": [ + { + "name": "triple_wave", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.28333, + "active": 0.01667, + "params": { + "startup_frames": 17, + "active_frames": 1, + "recovery_frames": 26, + "hits": 3, + "normalized": true + }, + "damage": 120, + "cue": "Light gathers in front of his palm, then he pushes out a three-hit shockwave with a large hitbox", + "punish": "Super-jump over it or roll through. The hitbox is tall, so a short hop gets clipped" + }, + { + "name": "mirror", + "atoms": [ + "counter" + ], + "telegraph_scale": 0.06667, + "active": 0.43333, + "params": { + "startup_frames": 4, + "active_frames": 26, + "recovery_frames": 18, + "normalized": true + }, + "damage": 80, + "cue": "He opens an energy mirror with almost no wind-up", + "punish": "It reflects projectiles. Attack after the mirror recovers" + }, + { + "name": "pillar", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.23333, + "active": 0.2, + "params": { + "startup_frames": 14, + "active_frames": 12, + "recovery_frames": 27, + "normalized": true + }, + "damage": 140, + "cue": "He raises a hand and a beam that spans the screen rises at the position he saw (a ring appears on the ground first)", + "punish": "Leave that spot during the wind-up. The pillar does not keep tracking" + }, + { + "name": "barrier", + "atoms": [ + "counter" + ], + "telegraph_scale": 0.05, + "active": 0.33333, + "params": { + "startup_frames": 3, + "active_frames": 20, + "recovery_frames": 22, + "normalized": true + }, + "damage": 90, + "cue": "He opens a barrier in front of him that catches ground strikes and counters (an upward-diagonal barrier catches air attacks; rules v8)", + "punish": "Do not attack when you see the barrier; wait for its recovery. Throws and projectiles are not caught" + }, + { + "name": "pull_grab", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.23333, + "active": 0.4, + "params": { + "startup_frames": 14, + "active_frames": 24, + "recovery_frames": 34, + "pull_range_u": 4.6, + "normalized": true + }, + "damage": 280, + "cue": "Costs one bar. He pulls in and grabs an opponent standing on the ground at mid range (changed to a super in rules v8)", + "punish": "Stay beyond 4.6 units or jump and it whiffs, then the recovery is long" + }, + { + "name": "close_throw", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.01667, + "active": 0.01667, + "params": { + "startup_frames": 1, + "active_frames": 1, + "recovery_frames": 25, + "normalized": true + }, + "damage": 100, + "cue": "A close throw that cannot be teched (rules v8)", + "punish": "Do not stay in throw range" + }, + { + "name": "screen_flash", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.7, + "active": 0.13333, + "params": { + "startup_frames": 42, + "active_frames": 8, + "recovery_frames": 42, + "normalized": true + }, + "damage": 260, + "cue": "Costs one bar. He spreads both arms and gathers a full-screen white flash", + "punish": "The wind-up is long. Block backward to reduce damage, or roll on the timing" + } + ], + "difficulty": { + "hp": [ + 3000, + 3600, + 7900 + ], + "dmg": [ + 0.85, + 1, + 1.15 + ], + "members": [ + 1, + 2, + 3 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "reaction": [ + 30, + 18, + 11 + ], + "decision": [ + 23, + 15, + 10 + ], + "aggression": [ + 0.44, + 0.72, + 0.92 + ], + "defense": [ + 0.12, + 0.4, + 0.66 + ], + "combo": [ + 0, + 0, + 0 + ], + "tech": [ + 0.05, + 0.2, + 0.4 + ], + "gc": [ + 0.02, + 0.08, + 0.18 + ], + "entropy": [ + 1, + 1, + 1 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kof_remake/specs/orochi_chris.spec.js b/environments/games/web/games/kof_remake/specs/orochi_chris.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..d2b404f66d110ae8015f2216b78af75343e4bc0b --- /dev/null +++ b/environments/games/web/games/kof_remake/specs/orochi_chris.spec.js @@ -0,0 +1,238 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["orochi_chris"] = { + "schema": "bossbench/boss-spec@1", + "id": "orochi_chris", + "dims": "2d", + "family": "fighter2d", + "archetype": "Blaze youth: rushdown, slow multi-hit fireball then hop-in rush, unguardable strike-throw; flame-fist player versus a delayed-observation opponent", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "neutral", + "telegraph": "startup", + "active": "active", + "recovery": "recovery" + }, + "timing": { + "idle": { + "knob": "decision" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "delayed_perception", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "fighter_attack", + "active": "fighter_active" + }, + "moves": [ + { + "name": "slow_fireball", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.4, + "active": 0.01667, + "params": { + "startup_frames": 24, + "active_frames": 1, + "recovery_frames": 18, + "normalized": true + }, + "damage": 100, + "cue": "A slow multi-hit fireball with short range", + "punish": "Jump forward or roll as soon as you see the startup" + }, + { + "name": "hop_arm", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.2, + "active": 0.13333, + "params": { + "startup_frames": 12, + "active_frames": 8, + "recovery_frames": 22, + "normalized": true + }, + "damage": 120, + "cue": "After a short hop he swings a flaming arm down into a rush", + "punish": "Crouch (it does not hit a crouching opponent) or block and counter" + }, + { + "name": "rising_arm", + "atoms": [ + "leap" + ], + "telegraph_scale": 0.06667, + "active": 0.2, + "params": { + "startup_frames": 4, + "active_frames": 12, + "recovery_frames": 28, + "normalized": true + }, + "damage": 130, + "cue": "He swings a flaming arm upward as an anti-air", + "punish": "Do not jump in from the front. The landing recovery is long" + }, + { + "name": "strike_throw", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.05, + "active": 0.5, + "params": { + "startup_frames": 3, + "active_frames": 30, + "recovery_frames": 28, + "normalized": true + }, + "damage": 200, + "cue": "Up close, five flaming punches then an upward kick, a strike throw that cannot actually be blocked", + "punish": "Leave close range or jump" + }, + { + "name": "fire_rush", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.16667, + "active": 0.66667, + "params": { + "startup_frames": 10, + "active_frames": 40, + "recovery_frames": 30, + "normalized": true + }, + "damage": 270, + "cue": "Costs one bar. He rushes in wrapped in a fireball", + "punish": "Block it and punish" + }, + { + "name": "dark_sweep", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.26667, + "active": 0.26667, + "params": { + "startup_frames": 16, + "active_frames": 16, + "recovery_frames": 30, + "normalized": true + }, + "damage": 260, + "cue": "Costs one bar. A dark-flame sweep that can be charged", + "punish": "Block or back off" + } + ], + "difficulty": { + "hp": [ + 3000, + 3500, + 7700 + ], + "dmg": [ + 0.85, + 1, + 1.15 + ], + "members": [ + 1, + 2, + 3 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "reaction": [ + 22, + 12, + 7 + ], + "decision": [ + 21, + 14, + 9 + ], + "aggression": [ + 0.4, + 0.68, + 0.9 + ], + "defense": [ + 0.15, + 0.45, + 0.7 + ], + "rush": [ + 0.3, + 0.55, + 0.8 + ], + "wake": [ + 0.15, + 0.3, + 0.5 + ], + "combo": [ + 0.05, + 0.15, + 0.3 + ], + "tech": [ + 0.08, + 0.3, + 0.55 + ], + "gc": [ + 0.03, + 0.12, + 0.28 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kof_remake/specs/orochi_iori.spec.js b/environments/games/web/games/kof_remake/specs/orochi_iori.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..f7ff5f077f0b25f07a549cb03769cd395ba17774 --- /dev/null +++ b/environments/games/web/games/kof_remake/specs/orochi_iori.spec.js @@ -0,0 +1,247 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["orochi_iori"] = { + "schema": "bossbench/boss-spec@1", + "id": "orochi_iori", + "dims": "2d", + "family": "fighter2d", + "archetype": "Frenzied form: faster run/jump, the same 7 moves as the violet-claw fighter (v8); flame-fist player versus a delayed-observation opponent", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "neutral", + "telegraph": "startup", + "active": "active", + "recovery": "recovery" + }, + "timing": { + "idle": { + "knob": "decision" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "delayed_perception", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "fighter_attack", + "active": "fighter_active" + }, + "moves": [ + { + "name": "ground_flame", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.23333, + "active": 0.01667, + "params": { + "startup_frames": 14, + "active_frames": 1, + "recovery_frames": 24, + "normalized": true + }, + "damage": 90, + "cue": "He crouches and pushes out a purple ground fireball (restored in rules v8; it is on the official SNK move list)", + "punish": "Jump the fireball and close in; the recovery after the shot can be punished" + }, + { + "name": "claw_chain", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.16667, + "active": 0.1, + "params": { + "startup_frames": 10, + "active_frames": 6, + "recovery_frames": 24, + "normalized": true + }, + "damage": 95, + "cue": "A frenzied three-slash pressure string", + "punish": "Block the last hit and keep blocking low" + }, + { + "name": "rising_flame", + "atoms": [ + "leap" + ], + "telegraph_scale": 0.08333, + "active": 0.21667, + "params": { + "startup_frames": 5, + "active_frames": 13, + "recovery_frames": 30, + "normalized": true + }, + "damage": 155, + "cue": "A rising purple flame used as an anti-air", + "punish": "Jump safely or counter when he lands" + }, + { + "name": "close_grab", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.06667, + "active": 0.01667, + "params": { + "startup_frames": 4, + "active_frames": 1, + "recovery_frames": 15, + "normalized": true + }, + "damage": 0, + "cue": "A close command grab", + "punish": "The command throw cannot be teched; jump or use spacing" + }, + { + "name": "dash_elbow", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.23333, + "active": 0.23333, + "params": { + "startup_frames": 14, + "active_frames": 14, + "recovery_frames": 26, + "normalized": true + }, + "damage": 150, + "cue": "He lowers his body and dashes in with an elbow (restored in rules v8)", + "punish": "The recovery after a block is long enough for a guaranteed punish" + }, + { + "name": "binding_flame", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.36667, + "active": 0.01667, + "params": { + "startup_frames": 22, + "active_frames": 1, + "recovery_frames": 40, + "bind_frames": 90, + "normalized": true + }, + "damage": 40, + "cue": "Costs one bar. He pushes a slow blue-purple flame along the ground; a burn holds you until the next hit (restored in rules v8)", + "punish": "It comes out slowly and recovers slowly: jump it or block and counter. While held, you can only take the next hit" + }, + { + "name": "rush_frenzy", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.2, + "active": 1.2, + "params": { + "startup_frames": 12, + "active_frames": 72, + "recovery_frames": 34, + "normalized": true, + "approximate_combo_contacts": 8 + }, + "damage": 290, + "cue": "Costs one bar. A high-speed rush", + "punish": "Block and punish. The opponent also needs to build meter" + } + ], + "difficulty": { + "hp": [ + 3100, + 3700, + 7000 + ], + "dmg": [ + 0.85, + 1, + 1.15 + ], + "members": [ + 1, + 2, + 3 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "reaction": [ + 22, + 11, + 6 + ], + "decision": [ + 23, + 15, + 10 + ], + "aggression": [ + 0.48, + 0.8, + 0.97 + ], + "defense": [ + 0.15, + 0.46, + 0.75 + ], + "combo": [ + 0.5, + 0.88, + 0.99 + ], + "tech": [ + 0.08, + 0.3, + 0.55 + ], + "gc": [ + 0.03, + 0.12, + 0.28 + ], + "entropy": [ + 1, + 1, + 1 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kof_remake/specs/orochi_shermie.spec.js b/environments/games/web/games/kof_remake/specs/orochi_shermie.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..4fa0f22827ff8b632f4b0d74f2556a63514acb73 --- /dev/null +++ b/environments/games/web/games/kof_remake/specs/orochi_shermie.spec.js @@ -0,0 +1,238 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["orochi_shermie"] = { + "schema": "bossbench/boss-spec@1", + "id": "orochi_shermie", + "dims": "2d", + "family": "fighter2d", + "archetype": "Storm dancer: keep-away with placed lightning orbs, fast anti-air super; weak up close; flame-fist player versus a delayed-observation opponent", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "neutral", + "telegraph": "startup", + "active": "active", + "recovery": "recovery" + }, + "timing": { + "idle": { + "knob": "decision" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "delayed_perception", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "fighter_attack", + "active": "fighter_active" + }, + "moves": [ + { + "name": "placed_orb", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.36667, + "active": 0.01667, + "params": { + "startup_frames": 22, + "active_frames": 1, + "recovery_frames": 14, + "normalized": true + }, + "damage": 110, + "cue": "After she blows, a thunder ball appears far away (the spot depends on the button) and lasts a long time", + "punish": "Roll through it or wait for it to vanish before moving in. Do not stand on the ball" + }, + { + "name": "spark_shot", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.16667, + "active": 0.01667, + "params": { + "startup_frames": 10, + "active_frames": 1, + "recovery_frames": 22, + "normalized": true + }, + "damage": 90, + "cue": "Two hand chops, then a close electric shot", + "punish": "Block it, then move in" + }, + { + "name": "spin_kick", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.2, + "active": 0.11667, + "params": { + "startup_frames": 12, + "active_frames": 7, + "recovery_frames": 24, + "normalized": true + }, + "damage": 100, + "cue": "A spinning kick with lightning around the foot", + "punish": "Block and counter" + }, + { + "name": "air_heel", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.08333, + "active": 0.16667, + "params": { + "startup_frames": 5, + "active_frames": 10, + "recovery_frames": 14, + "normalized": true + }, + "damage": 90, + "cue": "An aerial heel drop", + "punish": "Anti-air it" + }, + { + "name": "anti_air_spark", + "atoms": [ + "melee_area" + ], + "telegraph_scale": 0.06667, + "active": 0.23333, + "params": { + "startup_frames": 4, + "active_frames": 14, + "recovery_frames": 36, + "normalized": true + }, + "damage": 250, + "cue": "Costs one bar. A fast lightning punch that can anti-air", + "punish": "Do not jump carelessly while she has meter" + }, + { + "name": "flying_kicks", + "atoms": [ + "charge" + ], + "telegraph_scale": 0.2, + "active": 0.66667, + "params": { + "startup_frames": 12, + "active_frames": 40, + "recovery_frames": 30, + "normalized": true + }, + "damage": 270, + "cue": "Costs one bar. A horizontal flying kick, multi-hit but it does not knock down", + "punish": "Block it and punish" + } + ], + "difficulty": { + "hp": [ + 3100, + 3600, + 7500 + ], + "dmg": [ + 0.85, + 1, + 1.15 + ], + "members": [ + 1, + 2, + 3 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "reaction": [ + 26, + 15, + 9 + ], + "decision": [ + 22, + 15, + 10 + ], + "aggression": [ + 0.3, + 0.55, + 0.8 + ], + "defense": [ + 0.18, + 0.5, + 0.75 + ], + "zone": [ + 0.35, + 0.55, + 0.75 + ], + "aa": [ + 0.4, + 0.7, + 0.9 + ], + "combo": [ + 0.3, + 0.65, + 0.9 + ], + "tech": [ + 0.08, + 0.3, + 0.55 + ], + "gc": [ + 0.03, + 0.12, + 0.28 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/kof_remake/specs/orochi_yashiro.spec.js b/environments/games/web/games/kof_remake/specs/orochi_yashiro.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..05b0de5a85a4910ce34fd3c59910156ffa3e5776 --- /dev/null +++ b/environments/games/web/games/kof_remake/specs/orochi_yashiro.spec.js @@ -0,0 +1,248 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["orochi_yashiro"] = { + "schema": "bossbench/boss-spec@1", + "id": "orochi_yashiro", + "dims": "2d", + "family": "fighter2d", + "archetype": "Grappler: every special is a command throw; very solid guard, walking reactive throws; flame-fist player versus a delayed-observation opponent", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "neutral", + "telegraph": "startup", + "active": "active", + "recovery": "recovery" + }, + "timing": { + "idle": { + "knob": "decision" + }, + "telegraph": { + "knob": "telegraph", + "min": 0 + }, + "recovery": { + "knob": "recovery", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1, + "telegraph": 0, + "active": 1, + "recovery": 0 + } + }, + "select": { + "trigger": "delayed_perception", + "policy": "entropy_cycle", + "knob": "entropy", + "face_target": true + }, + "announce": { + "telegraph": "fighter_attack", + "active": "fighter_active" + }, + "moves": [ + { + "name": "instant_grab", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.01667, + "active": 0.03333, + "params": { + "startup_frames": 1, + "active_frames": 2, + "recovery_frames": 30, + "normalized": true + }, + "damage": 170, + "cue": "A 1-frame close command throw (it can be canceled from a normal)", + "punish": "Keep your distance. Jump or back off; the command throw cannot be teched" + }, + { + "name": "back_slam", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.01667, + "active": 0.03333, + "params": { + "startup_frames": 1, + "active_frames": 2, + "recovery_frames": 32, + "normalized": true + }, + "damage": 150, + "cue": "A close back-throw command grab", + "punish": "Same as above" + }, + { + "name": "dash_suplex", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.13333, + "active": 0.16667, + "params": { + "startup_frames": 8, + "active_frames": 10, + "recovery_frames": 30, + "normalized": true + }, + "damage": 140, + "cue": "A forward dash into a German suplex", + "punish": "Punch him out of the dash or jump back" + }, + { + "name": "leap_wrap", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.06667, + "active": 0.13333, + "params": { + "startup_frames": 4, + "active_frames": 8, + "recovery_frames": 10, + "normalized": true + }, + "damage": 0, + "cue": "He leaps, grabs, and circles behind you", + "punish": "Block as soon as he gets behind you; a throw follows immediately" + }, + { + "name": "charge_beam", + "atoms": [ + "projectile" + ], + "telegraph_scale": 0.4, + "active": 0.01667, + "params": { + "startup_frames": 24, + "active_frames": 1, + "recovery_frames": 34, + "normalized": true + }, + "damage": 240, + "cue": "Costs one bar. After charging he fires a beam; a full charge is unblockable", + "punish": "Close in or jump over it when you see the charge" + }, + { + "name": "super_slam", + "atoms": [ + "grab" + ], + "telegraph_scale": 0.01667, + "active": 0.03333, + "params": { + "startup_frames": 1, + "active_frames": 2, + "recovery_frames": 44, + "normalized": true + }, + "damage": 340, + "cue": "Costs one bar. A close super throw", + "punish": "His most painful move. Do not throw out attacks at close range" + } + ], + "difficulty": { + "hp": [ + 2600, + 3400, + 6200 + ], + "dmg": [ + 0.85, + 1, + 1.15 + ], + "members": [ + 1, + 2, + 3 + ], + "telegraph": [ + 1, + 1, + 1 + ], + "recovery": [ + 1, + 1, + 1 + ], + "speed": [ + 1, + 1, + 1 + ], + "entropy": [ + 1, + 1, + 1 + ], + "reaction": [ + 24, + 13, + 7 + ], + "decision": [ + 23, + 15, + 10 + ], + "aggression": [ + 0.3, + 0.55, + 0.8 + ], + "defense": [ + 0.5, + 0.78, + 0.92 + ], + "grab": [ + 0.35, + 0.6, + 0.85 + ], + "grab_react": [ + 10, + 6, + 3 + ], + "beam": [ + 0.15, + 0.3, + 0.45 + ], + "full": [ + 0.2, + 0.4, + 0.6 + ], + "combo": [ + 0.3, + 0.65, + 0.9 + ], + "tech": [ + 0.08, + 0.3, + 0.55 + ], + "gc": [ + 0.03, + 0.12, + 0.28 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/mario64_remake/app3d.js b/environments/games/web/games/mario64_remake/app3d.js new file mode 100644 index 0000000000000000000000000000000000000000..d0640ed695d438120da5966261ce1f18e995bf5f --- /dev/null +++ b/environments/games/web/games/mario64_remake/app3d.js @@ -0,0 +1,67 @@ +/* Human play and exact native-input recording. Game state is owned by each module. */ +(function () { + 'use strict'; + const N=NativeBench, M=window.GAME_MODULE, $=s=>document.querySelector(s), canvas=$('canvas'), context=canvas.getContext('2d'); + let session=new N.Session(M,M.cases[0].id,1,.5),running=false,last=0,accumulator=0; + // A key pressed and released between two ticks stays held until one tick has sampled it (same latch as _native/shell.js), + // so fast taps (jump, ground pound, camera steps) are never lost. + const held=new Set(),pending=new Set(),releaseAfter=new Set(),pointerHeld=new Map(),touchHeld=new Map(); let mouse=[0,0,0],replay=null,replayIndex=0,automatic=false,script=null,scriptTick=0; + const keys={KeyW:'W',KeyA:'A',KeyS:'S',KeyD:'D',Space:'Space',ShiftLeft:'Shift',ShiftRight:'Shift',KeyJ:'J',KeyK:'K',KeyL:'L',KeyQ:'Q',KeyE:'E',KeyR:'R',ArrowUp:'W',ArrowDown:'S',ArrowLeft:'A',ArrowRight:'D'}; + document.body.dataset.game=M.id; + // Public difficulty = three tiers (2026-11-02): rebuilt from Module.tiers when the game declares it. + if(M.tiers&&$('#difficulty')){const sel=$('#difficulty'),names={easy:'Easy',normal:'Normal',hard:'Hard'};sel.textContent=''; + for(const t of ['easy','normal','hard']){const op=document.createElement('option');op.value=String(M.tiers[t]);op.textContent=names[t]+' (d='+M.tiers[t]+')';if(t==='normal')op.selected=true;sel.append(op);}} + for(const def of M.cases){const option=document.createElement('option');option.value=def.id;option.textContent=def.name;$('#case').append(option);} + const controls=Array.isArray(M.controls)?M.controls.map(value=>['',value]):Object.entries(M.controls); + for(const [key,value]of controls){const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=key;dd.textContent=value;$('dl').append(dt,dd);} + function status(value){$('#status').textContent=value;} + function clear(){held.clear();pending.clear();releaseAfter.clear();pointerHeld.clear();touchHeld.clear();mouse=[0,0,0];accumulator=0;} + function inputKeys(){return [...new Set([...held,...[...pointerHeld.values()].flatMap(keys=>[...keys]),...touchHeld.values()])].filter(key=>N.keys.includes(key)).slice(0,4);} + function draw(){ + M.draw(session.game,context); + $('#pause').textContent=running?'Pause':'Resume'; + $('#overlay').hidden=running&&!session.game.outcome; + $('#overlay strong').textContent=session.game.outcome?{win:'Challenge Complete',loss:'Challenge Failed',timeout:'Time up'}[session.game.outcome]:replay?'Replay · Paused':session.game.t?'Paused':'Are You Ready?'; + $('#overlay span').textContent=session.game.outcome?'Restart the challenge or export the replay':session.game.t?'Click Resume to return to battle':'Click Start Challenge, then click the screen to use keyboard and mouse'; + } + function reset(id,seed,difficulty){running=false;automatic=false;replay=null;script=null;scriptTick=0;clear();session=new N.Session(M,id,seed,difficulty);draw();return session.snapshot();} + window.nativeAPI={reset,packet(packet){if(running)throw Error('Pause before a scripted packet');const value=session.packet(packet);draw();return value;}, + state(){return session.snapshot();},recording(){return session.export();}, + render(){draw();return canvas.toDataURL('image/png');}, + renderMetrics(){return M.renderMetrics?M.renderMetrics(context):{};}, + module(){return {id:M.id,hz:M.hz,version:M.version,cases:M.cases};}}; + function start(useScript){try{reset($('#case').value,Number($('#seed').value),Number($('#difficulty').value));automatic=useScript;running=true;status(useScript?'Script verification running':'Battle started; recording this match');canvas.focus();draw();}catch(error){status(error.message);}} + $('#start').onclick=()=>start(false);$('#demo').onclick=()=>start(true); + $('#pause').onclick=()=>{if(session.game.outcome)return;running=!running;clear();if(running)canvas.focus();draw();}; + $('#step').onclick=()=>{running=false;if(replay)replayTick();else session.tick();draw();}; + function openReplay(data){N.Session.import(M,data);reset(data.case,data.seed,data.difficulty);replay=data;replayIndex=0;running=true;$('#case').value=data.case;status('Replay verified; playback started');draw();} + function replayTick(){if(replayIndex{const data=session.export(),url=URL.createObjectURL(new Blob([JSON.stringify(data)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=M.id+'-'+session.seed+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status('Current replay exported');}; + $('#import').onclick=()=>$('#file').click();$('#file').onchange=async event=>{const file=event.target.files[0];if(!file)return;try{if(file.size>12e6)throw Error('Replay file is too large');openReplay(JSON.parse(await file.text()));}catch(error){status('Import failed: '+error.message);}event.target.value='';}; + function release(){clear();if(running){running=false;status('Window lost focus; battle paused');}draw();} + window.addEventListener('blur',release);document.addEventListener('visibilitychange',()=>{if(document.hidden)release();}); + window.addEventListener('keydown',event=>{if(['INPUT','SELECT','BUTTON'].includes(document.activeElement.tagName))return;if(keys[event.code]){event.preventDefault();held.add(keys[event.code]);pending.add(keys[event.code]);releaseAfter.delete(keys[event.code]);}if(event.code==='Escape'){running=false;clear();draw();}}); + window.addEventListener('keyup',event=>{const key=keys[event.code];if(key){event.preventDefault();if(pending.has(key))releaseAfter.add(key);else held.delete(key);}}); + canvas.oncontextmenu=event=>event.preventDefault();canvas.onpointerdown=event=>{if(event.button!==0&&event.button!==2)return;canvas.focus();const keys=pointerHeld.get(event.pointerId)||new Set();keys.add(event.button===2?'RMB':'LMB');pointerHeld.set(event.pointerId,keys);}; + // Pointer Events emits pointerup only after the final mouse button is released. + // pointermove carries changes to the button mask for chorded mouse presses. + function syncMouse(event){if(event.pointerType==='mouse'&&pointerHeld.has(event.pointerId)){const keys=new Set();if(event.buttons&1)keys.add('LMB');if(event.buttons&2)keys.add('RMB');if(keys.size)pointerHeld.set(event.pointerId,keys);else pointerHeld.delete(event.pointerId);}} + window.addEventListener('pointermove',syncMouse); + window.addEventListener('pointerup',event=>{if(event.pointerType==='mouse')syncMouse(event);else pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + window.addEventListener('pointercancel',event=>{pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + canvas.onpointermove=event=>{if(event.buttons||document.pointerLockElement===canvas){mouse[0]+=event.movementX;mouse[1]+=event.movementY;}}; + canvas.onwheel=event=>{event.preventDefault();mouse[2]+=Math.sign(event.deltaY);}; + canvas.ondblclick=()=>canvas.requestPointerLock?.(); + document.querySelectorAll('[data-key]').forEach(button=>{button.onpointerdown=event=>{event.preventDefault();button.setPointerCapture(event.pointerId);touchHeld.set(event.pointerId,button.dataset.key);};button.onpointerup=button.onpointercancel=event=>touchHeld.delete(event.pointerId);}); + function frame(now){const delta=Math.min(.1,(now-last)/1000||0);last=now;const beforeTick=session.game.t,wasRunning=running;try{ + if(running&&!session.game.outcome){accumulator+=delta;while(accumulator>=1/M.hz&&running&&!session.game.outcome){accumulator-=1/M.hz; + if(replay)replayTick();else if(automatic){const count=M.hz/5;if(scriptTick===0)script=(M.scripted||M.oracle).call(M,session.game);const sub=Math.ceil((scriptTick+1)*6/count)-1;session.tick(script.holds[sub],script.mouse.map(value=>value/count));scriptTick=(scriptTick+1)%count;} + else{session.tick(inputKeys(),mouse.map((value,index)=>N.clamp(value,index===2?-5:-1000,index===2?5:1000)));mouse=[0,0,0];pending.clear();for(const key of releaseAfter)held.delete(key);releaseAfter.clear();}} + if(session.game.outcome){running=false;status({win:'Challenge Complete',loss:'Challenge Failed',timeout:'Challenge Timed Out'}[session.game.outcome]+' · export or replay this match');}} + if(session.game.t!==beforeTick||running!==wasRunning)draw(); + }catch(error){running=false;clear();status('Runtime error: '+error.message);$('#overlay').hidden=false;$('#overlay strong').textContent='Unable to resume right now';$('#overlay span').textContent=error.message;} + requestAnimationFrame(frame); + } + window.addEventListener('pagehide',()=>M.closeRenderer?.(context)); + draw();requestAnimationFrame(frame); +})(); diff --git a/environments/games/web/games/mario64_remake/compact_actions.json b/environments/games/web/games/mario64_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..16d74f303dacffc85ace91b5c8421584f2055a70 --- /dev/null +++ b/environments/games/web/games/mario64_remake/compact_actions.json @@ -0,0 +1,1987 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "mario64_remake", + "version": "mario64-compact@4", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "cam_left", + "tap": [ + "Q" + ] + }, + { + "label": "cam_right", + "tap": [ + "E" + ] + }, + { + "label": "cam_reset", + "tap": [ + "R" + ] + }, + { + "label": "w", + "keys": [ + "W" + ] + }, + { + "label": "wa", + "keys": [ + "W", + "A" + ] + }, + { + "label": "a", + "keys": [ + "A" + ] + }, + { + "label": "as", + "keys": [ + "A", + "S" + ] + }, + { + "label": "s", + "keys": [ + "S" + ] + }, + { + "label": "sd", + "keys": [ + "S", + "D" + ] + }, + { + "label": "d", + "keys": [ + "D" + ] + }, + { + "label": "wd", + "keys": [ + "W", + "D" + ] + }, + { + "label": "m_w_a_s_d_w_a", + "subs": [ + [ + "W" + ], + [ + "A" + ], + [ + "S" + ], + [ + "D" + ], + [ + "W" + ], + [ + "A" + ] + ] + }, + { + "label": "m_wa_as_sd_wd_wa_as", + "subs": [ + [ + "W", + "A" + ], + [ + "A", + "S" + ], + [ + "S", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "A" + ], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_a_s_d_w_a_s", + "subs": [ + [ + "A" + ], + [ + "S" + ], + [ + "D" + ], + [ + "W" + ], + [ + "A" + ], + [ + "S" + ] + ] + }, + { + "label": "m_as_sd_wd_wa_as_sd", + "subs": [ + [ + "A", + "S" + ], + [ + "S", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "A" + ], + [ + "A", + "S" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_s_d_w_a_s_d", + "subs": [ + [ + "S" + ], + [ + "D" + ], + [ + "W" + ], + [ + "A" + ], + [ + "S" + ], + [ + "D" + ] + ] + }, + { + "label": "m_sd_wd_wa_as_sd_wd", + "subs": [ + [ + "S", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "A" + ], + [ + "A", + "S" + ], + [ + "S", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_d_w_a_s_d_w", + "subs": [ + [ + "D" + ], + [ + "W" + ], + [ + "A" + ], + [ + "S" + ], + [ + "D" + ], + [ + "W" + ] + ] + }, + { + "label": "m_wd_wa_as_sd_wd_wa", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "A" + ], + [ + "A", + "S" + ], + [ + "S", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_w_x_w_w_w_w", + "subs": [ + [ + "W" + ], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_wa_x_wa_wa_wa_wa", + "subs": [ + [ + "W", + "A" + ], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_a_x_a_a_a_a", + "subs": [ + [ + "A" + ], + [], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ] + ] + }, + { + "label": "m_as_x_as_as_as_as", + "subs": [ + [ + "A", + "S" + ], + [], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_s_x_s_s_s_s", + "subs": [ + [ + "S" + ], + [], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_sd_x_sd_sd_sd_sd", + "subs": [ + [ + "S", + "D" + ], + [], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_d_x_d_d_d_d", + "subs": [ + [ + "D" + ], + [], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_wd_x_wd_wd_wd_wd", + "subs": [ + [ + "W", + "D" + ], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_w_w_x_w_w_w", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_wa_wa_x_wa_wa_wa", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_a_a_x_a_a_a", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ] + ] + }, + { + "label": "m_s_s_x_s_s_s", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_d_d_x_d_d_d", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_wd_wd_x_wd_wd_wd", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_w_w_w_x_w_w", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_wa_wa_wa_x_wa_wa", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_a_a_a_x_a_a", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [ + "A" + ], + [ + "A" + ] + ] + }, + { + "label": "m_as_as_as_x_as_as", + "subs": [ + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [], + [ + "A", + "S" + ], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_s_s_s_x_s_s", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_sd_sd_sd_x_sd_sd", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [], + [ + "S", + "D" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_d_d_d_x_d_d", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_wd_wd_wd_x_wd_wd", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_w_w_w_w_x_w", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [ + "W" + ] + ] + }, + { + "label": "m_wa_wa_wa_wa_x_wa", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_a_a_a_a_x_a", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [ + "A" + ] + ] + }, + { + "label": "m_as_as_as_as_x_as", + "subs": [ + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_s_s_s_s_x_s", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [], + [ + "S" + ] + ] + }, + { + "label": "m_sd_sd_sd_sd_x_sd", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_d_d_d_d_x_d", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [ + "D" + ] + ] + }, + { + "label": "m_wd_wd_wd_wd_x_wd", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_w_w_w_w_w_x", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [] + ] + }, + { + "label": "m_wa_wa_wa_wa_wa_x", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [] + ] + }, + { + "label": "m_a_a_a_a_a_x", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [] + ] + }, + { + "label": "m_as_as_as_as_as_x", + "subs": [ + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [] + ] + }, + { + "label": "m_s_s_s_s_s_x", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [] + ] + }, + { + "label": "m_sd_sd_sd_sd_sd_x", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [] + ] + }, + { + "label": "m_d_d_d_d_d_x", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [] + ] + }, + { + "label": "m_wd_wd_wd_wd_wd_x", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [] + ] + }, + { + "label": "m_x_x_x_w_w_w", + "subs": [ + [], + [], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_w_w_x_x_x_x", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [], + [], + [], + [] + ] + }, + { + "label": "m_wd_wd_wd_d_d_d", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_wa_wa_wa_a_a_a", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ] + ] + }, + { + "label": "m_x_x_x_wd_wd_wd", + "subs": [ + [], + [], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_d_d_d_sd_sd_sd", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_w_x_x_x_x_x", + "subs": [ + [ + "W" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "m_w_w_w_wa_wa_wa", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_wa_wa_wa_w_w_w", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_sd_sd_s_x_x_x", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S" + ], + [], + [], + [] + ] + }, + { + "label": "m_x_x_x_x_x_w", + "subs": [ + [], + [], + [], + [], + [], + [ + "W" + ] + ] + }, + { + "label": "m_x_x_x_x_wa_wa", + "subs": [ + [], + [], + [], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_d_d_d_wd_wd_wd", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_a_a_a_as_as_as", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ], + [ + "A", + "S" + ] + ] + }, + { + "label": "m_a_a_a_wa_wa_wa", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_w_w_w_s_s_s", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_wd_wd_wd_w_w_w", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_x_w_x_w_x_w", + "subs": [ + [], + [ + "W" + ], + [], + [ + "W" + ], + [], + [ + "W" + ] + ] + }, + { + "label": "m_w_w_w_wd_wd_wd", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_x_x_x_x_s_s", + "subs": [ + [], + [], + [], + [], + [ + "S" + ], + [ + "S" + ] + ] + }, + { + "label": "m_s_s_s_x_x_x", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [], + [], + [] + ] + }, + { + "label": "m_x_x_wa_wa_wa_wa", + "subs": [ + [], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ] + ] + }, + { + "label": "m_w_x_w_x_w_x", + "subs": [ + [ + "W" + ], + [], + [ + "W" + ], + [], + [ + "W" + ], + [] + ] + }, + { + "label": "m_s_s_s_sd_sd_sd", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ] + ] + }, + { + "label": "m_x_x_w_w_w_w", + "subs": [ + [], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_sd_sd_sd_d_d_d", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ] + ] + }, + { + "label": "m_x_x_x_x_wd_wd", + "subs": [ + [], + [], + [], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_x_x_x_x_w_w", + "subs": [ + [], + [], + [], + [], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_x_w_w_w_w_w", + "subs": [ + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "m_w_w_w_x_x_x", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [], + [] + ] + }, + { + "label": "m_x_x_wd_wd_wd_wd", + "subs": [ + [], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ] + ] + }, + { + "label": "m_wa_wa_x_x_x_x", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [], + [], + [] + ] + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "punch_s1", + "subs": [ + [ + "J" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "punch_s2", + "subs": [ + [], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "punch_s3", + "subs": [ + [], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "punch_s4", + "subs": [ + [], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "punch_s5", + "subs": [ + [], + [], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "punch_s6", + "subs": [ + [], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "jump_hold", + "keys": [ + "Space" + ] + }, + { + "label": "jump_pound_s2", + "subs": [ + [ + "Space" + ], + [ + "Shift" + ], + [], + [], + [], + [] + ] + }, + { + "label": "jump_pound_s3", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Shift" + ], + [], + [], + [] + ] + }, + { + "label": "jump_short", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [], + [] + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/mario64_remake/draw.js b/environments/games/web/games/mario64_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..26d3947450f0860054a781e250495a3cc575828e --- /dev/null +++ b/environments/games/web/games/mario64_remake/draw.js @@ -0,0 +1,46 @@ +/* HUD for the Super Mario 64 boss trials, drawn over the WebGL frame: SM64-style 8-wedge power meter, boss hits, + * timer, native Hz and tier. Reads state only. */ +(function(root){ + 'use strict';const M=root.Mario64Game,R=root.Mario3D; + const NAMES={whomp:['Toppling Slab','TOPPLING SLAB'],king:['Grappler Orb','GRAPPLER ORB'],bully:['Horned Rammer','HORNED RAMMER'],eyerok:['Twin Sandstone Fists','TWIN SANDSTONE FISTS'],wiggler:['Frenzy Crawler','FRENZY CRAWLER'],bowser:['Fire Shell Beast','FIRE SHELL BEAST']}; + const ACT={idle:'Idle',walking:'Running',decel:'Slowing down',braking:'Braking',turnaround:'Quick turn',jump:'jump',double:'Double jump',triple:'Triple jump',backflip:'Backflip', + sideflip:'Side flip',longjump:'Long jump',freefall:'Falling',dive:'Pounce',diveslide:'Dive slide',divestop:'Rise up',jumpkick:'Jump kick',slidekick:'Slide kick',slidekickslide:'Sliding', + rollout:'Rolling up',gp:'Ground pound',gpLand:'Ground pound landing',crouchIn:'Crouching',crouch:'Crouched',crouchOut:'Rise up',crouchslide:'Crouch slide',punching:'Punching',movepunch:'Punching', + pickup:'Picking up',hold:'Holding',holdwalk:'Walking while holding',heavythrow:'Throwing',land:'Landing',kb:'Knocked back',airkb:'Launched',thrown:'Thrown',grabbed:'Grabbed', + grabbowser:'Tail grabbed',swing:'Swinging',release:'Released',shockwave:'Stunned by shockwave',burnjump:'Burning',burnfall:'Burning',burnground:'Burning',squished:'Squashed',lava:'Burned by lava',dead:'Down'}; + function text(c,s,x,y,size,color,align='left',weight='bold'){c.font=`${weight} ${size}px "Segoe UI","Microsoft YaHei",sans-serif`;c.textAlign=align;c.lineJoin='round'; + c.lineWidth=Math.max(3,size/4.5);c.strokeStyle='rgba(12,14,40,.88)';c.strokeText(s,x,y);c.fillStyle=color;c.fillText(s,x,y);} + // The SM64 power meter: eight wedges, coloured by how many remain (blue / green / yellow / red). + function power(c,x,y,r,health){const units=Math.max(0,Math.min(8,health/256)),whole=Math.floor(units+1e-6),col=whole>=7?'#3fa8ff':whole>=5?'#3cd25a':whole>=3?'#f2c230':'#ef3b2e'; + c.save();c.beginPath();c.arc(x,y,r+5,0,Math.PI*2);c.fillStyle='rgba(18,22,60,.85)';c.fill();c.lineWidth=3;c.strokeStyle='#f6f2e6';c.stroke(); + for(let i=0;i<8;i++){const a0=-Math.PI/2+i*Math.PI/4,a1=a0+Math.PI/4-.06;c.beginPath();c.moveTo(x,y);c.arc(x,y,r,a0,a1);c.closePath(); + c.fillStyle=i12){const w=230;c.fillStyle='rgba(18,22,60,.8)';c.fillRect(x-w/2,y-9,w,14);c.fillStyle=kind==='bully'?'#ff8a2a':'#ffd23a';c.fillRect(x-w/2+2,y-7,(w-4)*n/max,10); + c.strokeStyle='#f6f2e6';c.lineWidth=1.5;c.strokeRect(x-w/2,y-9,w,14);text(c,`${n} / ${max}`,x,y+22,13,'#fff','center');return;} + const gap=22,x0=x-(max-1)*gap/2;for(let i=0;i0&&b.guard>0&&b.act!=='hitmine')text(c,'He just got up. His dim tail cannot be grabbed yet; keep your distance.',427,150,15,'#fff3c4','center','600'); + else if(b.kind==='bowser'&&b.hp>0&&b.act==='walk')text(c,'Get behind him and press J near his tail to grab it.',427,150,15,'#fff3c4','center','600'); + if(b.kind==='bowser')text(c,`Mines ${b.mines.filter(q=>q.alive).length} / 4`,427,96,14,'#ffb0a0','center'); + if(m.action==='squished')text(c,'Squashed!',427,150,26,'#ffd0c0','center'); + if(b.kind==='whomp'&&b.act==='ground'&&b.sub===0&&m.action!=='squished')text(c,'Exposed back! Jump up and ground pound with Shift.',427,150,15,'#fff3c4','center','600'); + if(b.kind==='eyerok'&&b.hands.some(q=>q.act==='eye')&&m.action!=='squished')text(c,'Eye open! Face the palm and punch with J.',427,150,15,'#fff3c4','center','600'); + if(b.kind==='wiggler'&&b.act==='walk'&&b.intro===0&&b.timer<60&&b.hpR.status(ctx);M.renderMetrics=ctx=>R.metrics(ctx);M.closeRenderer=ctx=>R.close(ctx); +})(window); diff --git a/environments/games/web/games/mario64_remake/game.js b/environments/games/web/games/mario64_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..5a264936ae2cb1e0792d501cef95ab84d49fe81c --- /dev/null +++ b/environments/games/web/games/mario64_remake/game.js @@ -0,0 +1,1219 @@ +/* Super Mario 64 (N64, 1996): boss trials as an independent deterministic 60 Hz simulation (rules: M.version). + * Facts come from the n64decomp/sm64 decompilation at commit 9921382a68bb0c865e5e45eb594d9c64db59b1af (read, then + * re-implemented here; no code copied) and Super Mario Wiki. Animation lengths, arena sizes, and camera motion are approximations. Units are SM64 world units and speeds keep the + * original units per 30 Hz frame. SM64 logic runs at 30 Hz (hud.c turns 30 frames into one second), so one original + * frame is two ticks here: durations x2, per-frame increments /2, per-frame factors f -> sqrt(f), turn rates /2, and + * vertical motion uses a two-substep integrator whose even ticks reproduce the 30 Hz trajectory under constant gravity. */ +(function(root){ + 'use strict'; + const N=root.NativeBench,PI=Math.PI,K=2,S16=PI*2/65536; + const fr=n=>Math.round(n*K),inc=v=>v/K,ang=s=>s*S16/K,deg=s=>s*S16,fac=f=>Math.pow(f,1/K); + const wrap=a=>N.angle(a),hd=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z),yawTo=(a,b)=>Math.atan2(b.x-a.x,b.z-a.z); + const approach=(v,t,d)=>vwrap(c+N.clamp(wrap(t-c),-r,r)); + // Objects apply gravity before moving (cur_obj_move_y / calc_new_obj_vel_and_pos_y: vy -= g, then y += vy), unlike + // Mario's air step (move with the old speed, then gravity, S09). Two ticks reproduce one such 30 Hz frame exactly. + function objFall(o,g,terminal){const v0=o.vy;o.vy=Math.max(-terminal,o.vy-g/K);o.y+=o.vy/K+(o.vy-v0)*(K-1)/(2*K);} + // Mario: S05 mario.c, S06 mario_actions_airborne.c, S07 mario_actions_moving.c, S08 mario_actions_object.c, + // S09 mario_step.c, S12 mario_actions_cutscene.c, S13 behavior_data.c (hitbox 37 x 160), S20 stationary actions. + const C={radius:37,height:160,maxHealth:0x880, + jumpVy:42,doubleVy:52,tripleVy:69,flipVy:62,longVy:30,fspeedMul:.25,jumpFwd:.8,backflipFwd:-16,sideflipFwd:8,longMul:1.5, + longCap:48,diveAdd:15,diveCap:48,diveVy:20,kickVy:20,slideKickVy:12,slideKickFwd:32,rolloutVy:30,lavaVy:84, + gravity:4,terminal:75,lightGravity:2,lavaGravity:3.2,lavaTerminal:65, + walkMax:32,walkAccel:1.1,walkDiv:43,walkOver:1,speedCap:48,turn:0x800,heavyMag:.1, + airDrag:.35,airGain:1.5,airSide:10,airOver:1,airBack:2,longThreshold:48, + djFrames:5,tripleNeed:20,longNeed:10,longWindow:16,diveNeed:29,airDiveNeed:28,fastAttack:26, + backAngle:0x471C,brakeNeed:16,brakeDecel:4,decel:1,finishTurnFwd:8,landFric:.98,slideLoss:.92, + gpRise:10,gpVy:-50,kbFric:.9,kbCap:32,thrownFric:.98,airKb:16,bounceGround:-48,bounceAir:-16, + invincFrames:30,fallDamageHeight:1150,lungeFrames:[10,7,5,3,2,1,1,0], + // Animation lengths in original frames, from the decomp's animation headers (S21 assets/anims loopEnd): first punch + // 5 + fast 10, second punch 4 + fast 13, kick 26, breakdance 24, ground-pound start 11 (+4 hover, S06), ground-pound + // landing 6, crouch in/out 6/10, heavy grab 37, heavy throw 25, soft/normal knockback 24/30. Approximated (A1): + // butt-slide stop after a ground-pound landing (10), dive stop, hard knockback, death. + gpWind:15,gpLand:16,crouchIn:6,crouchOut:10,punch1:5,punchFast:10,punch2:4,punchFast2:13,kick:26,breakdance:24,pickUp:3,heavyGrab:37, + heavyThrowRelease:13,heavyThrowEnd:25,diveStop:10,kbSoft:24,kbFwd:30,kbBack:30,kbHard:36,deathFrames:45, + landFrames:{jump:4,double:4,triple:4,backflip:4,side:4,free:4,long:6}}; + // A pressed during a landing: S07 landing table / S20 landing-stop rules. + const LAND_A={jump:'double',free:'double',side:'double',double:'tripleOrJump',triple:null,backflip:'backflipIfZ',long:'longOrJump'}; + const AIR=new Set(['jump','double','triple','backflip','sideflip','longjump','freefall','dive','jumpkick','gp','slidekick','rollout','airkb','thrown','lava','burnjump','burnfall']); + const INVULNERABLE=new Set(['kb','airkb','thrown','squished','lava','dead','grabbed','shockwave','burnjump','burnfall','burnground']); + const PUNCHING=new Set(['punching','movepunch']); + // Public tiers. Each TUNE row is [1996 original, easy, normal, hard] at difficulty 0 /.2 /.5 /.8, so + // difficulty 0 replays the original values. easy keeps the original aggression and damage and only adds hits where the + // 3-hit original is shorter than the easy-tier target of 20–30 s; normal and hard also escalate aggression and damage + // (BossBench calibration for the 1-minute / 3-minute windows, not original behaviour). + const TIERS={easy:.2,normal:.5,hard:.8}; + const TUNE={ + whomp:{hits:[3,5,13,40],fast:[9,9,10.5,12],turn:[0x200,0x200,0x260,0x2c0],range:[300,300,320,340],lie:[100,100,82,66],delay:[30,30,24,18],squish:[3,3,4,5]}, + king:{hits:[3,3,7,19],walk:[3,3,3.6,4.4],turn:[0x100,0x100,0x150,0x1c0],throwHurt:[0,0,1,2],touchHurt:[1,1,1,2],escape:[10,10,12,14]}, + // sight/leave: the Big Bully chases while Mario is within `leave` of his home and resumes when within `sight` (S03: + // 800/1000). On the real platform (corners 1064 from home) the original radii let a corner camper stall him, so the + // public tiers widen both to 1100 to keep the boss engaging (binding rule; deviation T2, original at d = 0). + bully:{lives:[1,2,4,19],charge:[30,30,33,36],slow:[10,10,8,6],recover:[18,18,14,11],lavaHurt:[3,3,3,4],sight:[800,1100,1100,1100],leave:[1000,1100,1100,1100]}, + // hits: both hands together, split evenly (S35 health 4 = 3 hits per hand, 6 in all). every / pounds: the double pound's period + // and length (S35 6, 8). After a double pound the counter stands at r + 7 with r in {0,1} (S35), so a period dividing 7 or 8 + // restarts it at once and chains double pounds: every must stay out of {2,4,7,8}. + eyerok:{hits:[6,7,14,40],every:[6,6,5,5],pounds:[8,8,8,8],push:[50,50,55,60],rush:[50,50,55,60],retreat:[40,40,45,50],smashWait:[20,20,16,12],squish:[3,3,3,4]}, + // hits: stomps to shrink (S40 health 4 = 3). calm / chase / fury: target walking speed before the first stomp, until the last stomp, and on the last (S40 16, 30, 40; + // extra hits keep the middle speed, T6). seek: chases from the start instead of wandering until hit, leash: how far from home he follows; 1996 values at d = 0 (T6). + wiggler:{hits:[3,6,17,46],calm:[16,16,16,16],chase:[30,30,32,34],fury:[40,40,42,44],daze:[30,30,24,24],hurt:[3,3,3,4],seek:[0,1,1,1],leash:[1200,3000,3000,3000]}, + // hits: mines he must hit (S50 sBowserHealth BitDW 1). back: frames until a spent mine returns (the original's mines never return, kept at d = 0; more than 4 hits need it: T7). turn / walk: S50 0x200, 3. + // reach: his landing hurts Mario within it and only stuns him beyond (S50 850). touch / quake: wedges from his body and from a near landing (S50 2, S29 12/4 = 3). + // guard: frames after he stands up from a mine in which his tail cannot be touched, so a chain of grabs cannot lock him out of the fight (T7; never reached at d = 0, where one hit ends the fight). + bowser:{hits:[1,2,5,14],guard:[200,200,200,200],back:[300,300,240,180],turn:[0x200,0x200,0x300,0x400],walk:[3,3,3.6,4.4],reach:[850,850,950,1050],touch:[2,2,2,3],quake:[3,3,3,4]}}; + const tv=(d,[o,e,n,h])=>d<=.2?o+(e-o)*d/.2:d<=.5?e+(n-e)*(d-.2)/.3:n+(h-n)*(d-.5)/.3; + function tune(kind,d){const o={};for(const [k,v] of Object.entries(TUNE[kind]))o[k]=tv(d,v); + for(const k of ['hits','lives','escape','every','pounds','smashWait','daze'])if(k in o)o[k]=Math.max(1,Math.round(o[k])); + for(const k of ['squish','throwHurt','touchHurt','lavaHurt','hurt','seek','touch','quake','guard'])if(k in o)o[k]=Math.max(0,Math.round(o[k]));return o;} + // Arenas measured from the pinned decomp collision (S29 levels/wf, S30 levels/bob, S31 levels/lll): each boss floor's + // outline in local units (world minus the boss's spawn point; y = 0 is that floor) and, per edge (poly[i] -> poly[i+1]), + // the floor height 200 units beyond it. Only these measured numbers are used; no collision or model data is embedded. + // The King's flat top is merged with the near-level east apron (real -3..-104, taken as 0: A2). arrive = where Mario + // reaches the floor (Whomp: the checkerboard elevator in the notch, level object 1035, 2880, -900; King: the mountain + // path's top; Bully: the octagonal mesh platform east of him, level object 1124, 0, -4607). The fight starts as the + // boss's dialog ends, so Mario starts just inside its radius (S01 600, S02 500) on the line to the arrival point. + // farBelow: Mario further below than this resets the boss (S01 1000 in the chase, S02 1200). + const ARENA={ + whomp:{poly:[[-1023,1536],[-1023,-511],[-423,-1959],[1024,-511],[1536,-1023],[1536,1024],[1024,1536]], + drop:[-1024,-1024,-1024,-1024,-1024,-2662,-1703],slip:[0,0,0,0,0,0,1],lava:false,arrive:{x:1035,z:-900},startDist:580,talk:600,farBelow:1000}, + king:{poly:[[-338,1984],[-338,-64],[1436,-1088],[3210,-64],[3210,1984],[2877,1792],[2766,1728],[1436,2496]], + drop:[-460,-604,-885,-1180,-120,-120,-171,-311],lava:false,arrive:{x:2350,z:2050},startDist:480,talk:500,farBelow:1200}, + bully:{poly:[[-767,738],[-767,-670],[768,-670],[768,738]],drop:[-307,-307,-307,-307],lava:true,arrive:{x:1124,z:-222},startDist:0}, + // Eyerok: S35/S38 top floor of the Shifting Sand Land pyramid, boss at (0,-1534,-3693). The sides and front drop 3072 to the + // death plane (deadly: a fall ends the fight); the back edge is behind the wall (handSolid). + eyerok:{poly:[[-946,-261],[-946,1838],[947,1838],[947,-261]],drop:[-3072,-3072,-3072,-3072],lava:false,deadly:true,arrive:{x:0,z:1645},startDist:480,talk:500}, + // Wiggler: S41/S42 the cave at the top of Tiny-Huge Island, walls at world x -2047..2048, z -2047..2048. Closed: nothing to fall off. Mario really drops from + // the hole at (0, 3277, 0) onto the pyramid's top and walks off; the fight starts with him on the floor just off it, at 500 (A10). + wiggler:{poly:[[-2064,-1985],[-2064,2110],[2031,2110],[2031,-1985]],drop:[0,0,0,0],lava:false,room:true,arrive:{x:0,z:1000},startDist:500}, + // Bowser: S53 regular octagon of circumradius 3072 around the world origin, floor y 307, death plane -6143; local z = world z + 1000 (he spawns at (0, 307, -1000)). Mario lands in the middle. + bowser:{poly:[[3072,1000],[2172,3172],[0,4072],[-2171,3172],[-3071,1000],[-2171,-1171],[0,-2071],[2172,-1171]],drop:[-6450,-6450,-6450,-6450,-6450,-6450,-6450,-6450],lava:false,deadly:true,arrive:{x:0,z:1000},startDist:1000}}; + for(const a of Object.values(ARENA)){let A=0,cx=0,cz=0;const P=a.poly; // polygon centroid + for(let i=0;iz)!==(zj>z)&&x<(xj-xi)*(z-zi)/(zj-zi)+xi)c=!c;}return c;} + function nearestEdge(P,x,z){let e=0,best=Infinity;for(let i=0;iMath.max(0,Math.max(Math.abs(x+16.5),Math.abs(z-62.5))-716.5)*.2307; + const wigCeil=(x,z)=>{const a=Math.abs(x+17),c=Math.abs(z-62);return Math.max(Math.abs(x+16.5),Math.abs(z-62.5))>306.5?null:410+Math.max(a,c)/306.5*205;}; + const SLAB={half:300,h0:100,h1:860,d0:-200,d1:-6,top:200}; + const KING={radius:100,height:100,holdY:170,anchorFwd:150,anchorSide:100,anchorY:60,drag:10}; // S13 SET_HITBOX(100,100), drag 1000/100, anchor 100/150 + const BULLY={radius:115,height:235,gravity:5,friction:.93,push:3392}; // S03 big bully hitbox / init, S04 + // Bowser. anim: S54 loopEnd by animation index (only 9 is no-loop). mines: S53 at world (+-2949, 589, 0), (0, 589, +-2949). tail: the anchor follows the tail bone at render time; approximated as + // tailBack behind him, tailY above his feet (A11). flames: S55 even animation frames 46..84 as [y, z, yaw, pitch]. throwF / throwL / throwY: S16 cur_obj_get_thrown_or_placed offset from Mario. + const BOWSER={anim:{0:44,2:30,3:36,6:92,8:20,9:16,10:70,12:80,13:42,14:22,15:44,25:45,26:44},mines:[[2949,1000],[0,-1949],[0,3949],[-2949,1000]],mineY:282,tailBack:200,tailY:60,grabR:400,grabH:400,bodyR:100,bodyH:300,throwF:321.577,throwL:-41.684,throwY:85.859,holdF:315,holdY:-67, + flames:[[229,139,-1,0x803],[222,147,-1,0x928],[221,149,-1,0xA16],[221,150,-1,0xAF6],[222,150,-1,0xB84],[223,149,0x524,0xB9E],[226,147,0xA3F,0xB57],[228,144,0xD00,0xAE5],[232,140,0xD8B,0xA48],[236,136,0xCED,0x96A],[239,132,0xB76,0x863],[244,128,0x970,0x74E],[248,122,0x723,0x649],[253,117,0x4D6,0x579],[256,111,0x2C9,0x509],[261,105,0x141,0x525],[264,100,0x6E,0x619],[268,95,0xC,0x8AF],[272,90,-1,0xC70],[274,86,0x14,0x10B6]]}; + const CASES=[ + {id:'mario64/whomp_king',kind:'whomp',name:'Whomp King · Stone Platform (ground pound his back)'}, + {id:'mario64/king_bobomb',kind:'king',name:'King Bob-omb · Grassy Summit (grab from behind and throw)'}, + {id:'mario64/big_bully',kind:'bully',name:'Big Bully · Lava Platform (push him into lava)'}, + {id:'mario64/eyerok',kind:'eyerok',name:'Eyerok · Desert Platform (strike the open eyes in its palms)'}, + {id:'mario64/wiggler',kind:'wiggler',name:'Wiggler · Cave Chamber (stomp its head; it speeds up each time)'}, + {id:'mario64/bowser_dark_world',kind:'bowser',name:'Bowser · Floating Octagonal Arena (grab his tail and throw him into mines)'}]; + const M=root.Mario64Game={id:'mario64_remake',version:'sm64-bosses@5',hz:60,maxSeconds:300,dimension:'3d',renderer:'webgl-mario64', + title:'Super Mario 64 · Boss Challenges',tiers:TIERS,cases:CASES.map(c=>({id:c.id,name:c.name})),tuning:C,tune:TUNE,arenas:ARENA, + controls:{'W A S D':'Move relative to the camera (full analog stick); hold K to walk slowly','Space':'A: jump; press again on landing for a double or triple jump; press while crouching for a backflip or while turning sharply for a side flip', + 'Shift / RMB':'Z: crouch; press while running to slide, then press Space for a long jump; press in midair to ground pound','J / LMB':'B: punch-punch-kick combo; dive while sprinting, kick in midair, pick up nearby grabbable objects, or throw what you hold', + 'Q / E':'Rotate the follow camera 45° left or right (C◀/C▶)','R':'snap camera behind you, facing the boss','L / Mouse wheel':'Zoom camera','Mouse drag':'Rotate camera continuously (double-click to lock pointer)', + 'When grabbed':'Tap Space or move repeatedly to escape','While holding the tail':'Press W A S D in sequence to swing faster; press J toward a mine to throw'}}; + + function newMario(x,z,yaw){return {x,y:0,z,vy:0,fwd:0,side:0,yaw,action:'idle',timer:0,state:0,arg:0,prev:'idle',health:C.maxHealth, + hurt:0,heal:0,invinc:0,djTimer:0,lastLand:null,peakY:0,squish:0,onBoss:false,punch:null,ctrlJump:false,holding:false,canGrab:false, + grabRelease:0,slowLong:false,lavaBounces:0,kbKind:null};} + function initBully(x,z,fwd,yaw,ratio){if(fwd<0){fwd=-fwd;yaw+=PI;}return {x,z,vx:fwd*Math.sin(yaw),vz:fwd*Math.cos(yaw),ratio};} + // S09 transfer_bully_speed: each body drops its own velocity component along the joining line and gains the other's, scaled. + function transferBully(a,b){const rx=b.x-a.x,rz=b.z-a.z,d2=rx*rx+rz*rz||1e-6,p1=(rx*a.vx+rz*a.vz)/d2,p2=(-rx*b.vx-rz*b.vz)/d2; + b.vx+=b.ratio*p1*rx-p2*-rx;b.vz+=b.ratio*p1*rz-p2*-rz;a.vx+=-p1*rx+a.ratio*p2*-rx;a.vz+=-p1*rz+a.ratio*p2*-rz;} + + class Game{ + constructor(id,seed,d){ + const def=CASES.find(c=>c.id===id);if(!def)throw Error('Unknown Super Mario 64 case'); + this.id=id;this.kind=def.kind;this.rng=seed||0x2545f491;this.d=d;this.t=0;this.outcome=null;this.events=[];this.effects=[];this.lastKeys=[]; + // Warm up the PRNG before sampling the starting position. + for(let i=0;i<8;i++)N.rand(this); + this.T=tune(this.kind,d); + // Arrival: Mario reaches the boss floor at a.arrive and returns there after a fall (entry = 150 inside the edge on + // the line to the boss). Seeds vary the start along the arrival direction by up to +-14 degrees (Bully: +-100). + const a=this.arena,boss={x:0,z:0},len=Math.hypot(a.arrive.x,a.arrive.z);let e={x:a.arrive.x,z:a.arrive.z}; + for(let i=0;i<400&&!this.inside(e.x,e.z,150);i++)e={x:e.x-a.arrive.x/len*10,z:e.z-a.arrive.z/len*10}; + this.entry={x:Math.round(e.x),z:Math.round(e.z)}; + const dir=Math.atan2(a.arrive.x,a.arrive.z)+(N.rand(this)-.5)*.5; + const start=a.startDist?{x:Math.sin(dir)*a.startDist,z:Math.cos(dir)*a.startDist}:{x:this.entry.x,z:this.entry.z+(N.rand(this)-.5)*200}; + this.start={x:Math.round(start.x),z:Math.round(start.z)}; + this.mario=newMario(start.x,start.z,0);this.mario.yaw=yawTo(this.mario,boss); + this.stats={jumps:0,doubleJumps:0,tripleJumps:0,longJumps:0,backflips:0,sideFlips:0,groundPounds:0,dives:0,punches:0,kicks:0, + grabs:0,throws:0,squished:0,lavaBoosts:0,knockbacks:0,falls:0,bossHits:0,bossResets:0,damageTaken:0}; + if(this.kind==='whomp')this.boss={kind:'whomp',x:0,y:0,z:0,vy:0,fwd:0,yaw:yawTo(boss,this.mario),pitch:0,pitchVel:0, + act:'intro',timer:0,sub:0,hp:this.T.hits,maxHp:this.T.hits,shake:0,hitNow:false,squishedMario:false}; + else if(this.kind==='king')this.boss={kind:'king',x:0,y:0,z:0,vy:0,fwd:0,yaw:yawTo(boss,this.mario),act:0,sub:0,timer:0, + hp:this.T.hits,maxHp:this.T.hits,opener:0,wait:0,u104:0,escape:0,held:false,tangible:false,interact:'grab',grabbedMario:false, + homeX:0,homeZ:0,arc:null}; + else if(this.kind==='eyerok'){this.mario.onHand=-1; + const hand=(side,idx)=>({side,idx,homeX:-500*side,homeZ:300,x:224*side,y:0,z:300,vy:0,fwd:0,g:0,move:0,face:-deg(0x4000)*side,act:'sleep',prevAct:'sleep',timer:0, + hp:(side<0?Math.floor(this.T.hits/2):Math.ceil(this.T.hits/2))+1,anim:6,af:-1,open:false,ground:false,edge:false,wall:false,recv:0,pending:0,fc:0,u100:0,blink:3,gone:false,wake:0}); + this.boss={kind:'eyerok',x:0,y:0,z:0,yaw:0,act:'sleep',talk:0,timer:0,hp:this.T.hits,maxHp:this.T.hits,hands:[hand(-1,0),hand(1,1)],handsLeft:0,active:0,eyeHand:0,pound:0,lift:0,dir:0,zt:0,fc:0};} + else if(this.kind==='wiggler'){const seg=()=>({x:0,y:0,z:0,px:0,pz:0,pitch:0,yaw:0}); + this.boss={kind:'wiggler',x:0,y:0,z:0,vy:0,fwd:0,move:0,face:0,pitch:0,target:0,act:'walk',prevAct:'walk',timer:0,intro:30,hp:this.T.hits,maxHp:this.T.hits,sx:4,sy:4,sv:0,away:0,turnIn:0,pending:null,s:[seg(),seg(),seg(),seg()]};} + else if(this.kind==='bowser'){Object.assign(this.mario,{swing:0,twirl:0,burn:0,burnLoss:0,stomp:null});this.stats.burns=0;this.stats.mineHits=0; + this.boss={kind:'bowser',x:0,y:0,z:0,vy:0,fwd:0,yaw:0,drag:10,act:'wait',prev:'wait',sub:0,timer:0,btimer:0,anim:12,af:-1,react:1,hp:this.T.hits,maxHp:this.T.hits,held:false,heldT:0,skip:false,grabbable:false,tail:0,tailT:0,landed:false,onGround:true,op:255,opGoal:255,spin:0,guard:0, + mines:BOWSER.mines.map(([x,z])=>({x,y:BOWSER.mineY,z,alive:true,back:0,blast:0})),flames:[],fires:[]};} + // Act-1 Big Bully patrols at home and charges as Mario steps onto his platform (S03, initial action BULLY_ACT_PATROL). + else this.boss={kind:'bully',x:0,y:0,z:0,vy:0,fwd:0,moveYaw:0,faceYaw:0,act:'patrol',timer:0,counter:0, + lives:this.T.lives,maxLives:this.T.lives,homeX:0,homeZ:0,sinkY:0}; + this.cam={base:yawTo(this.mario,boss),offset:0,offsetTarget:0,yaw:yawTo(this.mario,boss),pitch:.38,dist:1100}; + } + get arena(){return ARENA[this.kind];} + state(){return N.copy(this);} + emit(name){this.events.push(name);} + fx(type,at,life=24,extra={}){this.effects.push({type,x:at.x,y:at.y||0,z:at.z,life,maxLife:life,...extra});} + // ---------------- world ---------------- + inside(x,z,margin=0){const P=this.arena.poly;return inPoly(P,x,z)&&(margin<=0||nearestEdge(P,x,z).d>=margin);} + edgeDist(x,z){return nearestEdge(this.arena.poly,x,z).d;} + slabLocal(x,z){const b=this.boss,fx=Math.sin(b.yaw),fz=Math.cos(b.yaw),px=x-b.x,pz=z-b.z;return {f:px*fx+pz*fz,u:-px*fz+pz*fx};} + lying(){const b=this.boss;return b&&b.kind==='whomp'&&b.pitch>deg(0x3800)&&b.act!=='dead';} + bossTop(x,z){if(!this.lying())return null;const s=this.slabLocal(x,z); + return s.f>=SLAB.h0&&s.f<=SLAB.h1&&Math.abs(s.u)<=SLAB.half?this.boss.y+SLAB.top*Math.sin(this.boss.pitch):null;} + // The boss floor at y = 0; beyond an edge, the measured floor below it (lava around the Bully's platform). + floor(x,z,y){const a=this.arena;let best;if(a.room)return {y:wigFloor(N.clamp(x,a.poly[0][0],a.poly[2][0]),N.clamp(z,a.poly[0][1],a.poly[2][1])),lava:false,boss:false,off:false}; + if(inPoly(a.poly,x,z))best={y:0,lava:false,boss:false,off:false}; + else{const e=nearestEdge(a.poly,x,z).e;best={y:a.drop[e],lava:a.lava,boss:false,off:!a.lava,slip:!!(a.slip&&a.slip[e])};} + const top=this.bossTop(x,z);if(top!==null&&y>=top-30&&top>best.y)best={y:top,lava:false,boss:true,off:false}; + if(this.kind==='eyerok'){const t=this.handTop(x,z,y);if(t!==null&&t>best.y)best={y:t,lava:false,boss:true,off:false};}return best;} + focus(){const b=this.boss;if(!b)return null; + if(b.kind==='whomp'){const f=this.lying()?480:0;return {x:b.x+Math.sin(b.yaw)*f,z:b.z+Math.cos(b.yaw)*f};} + if((b.kind==='king'||b.kind==='bowser')&&b.held)return null;return {x:b.x,z:b.z};} + // Lakitu camera: aims from behind Mario at the boss (the boss sets gSecondCameraFocus, S01/S02); Q/E add 45-degree + // C-button steps, mouse x turns freely, R recentres. The follow rates are engineering choices. + camera(pressed,mouse){const c=this.cam,m=this.mario,f=this.focus(); + if(pressed.has('Q'))c.offsetTarget=wrap(c.offsetTarget+PI/4);if(pressed.has('E'))c.offsetTarget=wrap(c.offsetTarget-PI/4); + if(pressed.has('R')){c.offsetTarget=0;}if(pressed.has('L'))c.dist=c.dist>1400?1100:1650; + c.offsetTarget=wrap(c.offsetTarget-mouse[0]*.0045);c.offset=wrap(c.offset+N.clamp(wrap(c.offsetTarget-c.offset),-.09,.09)); + c.pitch=N.clamp(c.pitch+mouse[1]*.0025,.14,.9);c.dist=N.clamp(c.dist+mouse[2]*70,700,2000); + if(f&&hd(m,f)>260){const d=wrap(yawTo(m,f)-c.base);c.base=wrap(c.base+N.clamp(d*.1,-.05,.05));} + c.yaw=wrap(c.base+c.offset); + } + readInput(keys,pressed){ + const f=(keys.has('W')?1:0)-(keys.has('S')?1:0),s=(keys.has('D')?1:0)-(keys.has('A')?1:0),a=this.cam.yaw,m=this.mario; + const dx=Math.sin(a)*f-Math.cos(a)*s,dz=Math.cos(a)*f+Math.sin(a)*s,len=Math.hypot(dx,dz),stickMag=len?(keys.has('K')?32:64):0; + const mag=Math.pow(stickMag/64,2)*64/(m.squish>0?8:2); // S05 update_mario_joystick_inputs + return {stickMag,mag,yaw:len?Math.atan2(dx,dz):m.yaw,aP:pressed.has('Space'),aD:keys.has('Space'),bP:pressed.has('J')||pressed.has('LMB'), + zP:pressed.has('Shift')||pressed.has('RMB'),zD:keys.has('Shift')||keys.has('RMB')}; + } + // ---------------- Mario helpers ---------------- + invulnerable(){const m=this.mario;return INVULNERABLE.has(m.action)||m.invinc>0;} + hurtMario(units){if(units<=0)return;const m=this.mario;m.hurt+=units*8;this.stats.damageTaken+=units;m.flash=24;this.emit('mario_hurt');} + setAction(name,arg=0){const m=this.mario;m.prev=m.action;m.action=name;m.timer=0;m.state=0;m.arg=arg;m.punch=null;} + go(name,arg=0){this.setAction(name,arg);this.chain=true;} + airborne(name,inp,arg=0){const m=this.mario;if(m.squish>0&&name==='double')name='jump';this.setAction(name,arg); + const yv=(v,mul)=>{m.vy=v+m.fwd*mul;if(m.squish>0)m.vy*=.5;};m.ctrlJump=false; + switch(name){ + case 'jump':yv(C.jumpVy,C.fspeedMul);m.fwd*=C.jumpFwd;m.ctrlJump=true;this.stats.jumps++;this.emit('jump');break; + case 'double':yv(C.doubleVy,C.fspeedMul);m.fwd*=C.jumpFwd;m.ctrlJump=true;this.stats.doubleJumps++;this.emit('double_jump');break; + case 'triple':yv(C.tripleVy,0);m.fwd*=C.jumpFwd;this.stats.tripleJumps++;this.emit('triple_jump');break; + case 'backflip':m.fwd=C.backflipFwd;yv(C.flipVy,0);this.stats.backflips++;this.emit('backflip');break; + case 'sideflip':yv(C.flipVy,0);m.fwd=C.sideflipFwd;m.yaw=inp.yaw;this.stats.sideFlips++;this.emit('side_flip');break; + case 'longjump':yv(C.longVy,0);m.slowLong=m.fwd<=16;m.fwd=Math.min(C.longCap,m.fwd*C.longMul);this.stats.longJumps++;this.emit('long_jump');break; + case 'dive':m.fwd=Math.min(C.diveCap,m.fwd+C.diveAdd);this.stats.dives++;this.emit('dive');break; + case 'jumpkick':m.vy=C.kickVy;this.stats.kicks++;this.emit('jump_kick');break; + case 'slidekick':m.vy=C.slideKickVy;m.fwd=Math.max(m.fwd,C.slideKickFwd);this.emit('slide_kick');break; + case 'rollout':m.vy=C.rolloutVy;break; + case 'lava':m.vy=C.lavaVy;if(!arg)m.fwd=0;m.lavaBounces=0;break; + } + m.peakY=m.y;m.side=0; + } + jumpFromLanding(inp){const m=this.mario,k=m.lastLand;this.chain=true; + if(m.djTimer===0||m.squish>0){m.djTimer=0;return this.airborne('jump',inp);}m.djTimer=0; + if(k==='jump'||k==='free'||k==='side')return this.airborne('double',inp); + if(k==='double')return this.airborne(m.fwd>C.tripleNeed?'triple':'jump',inp); + return this.airborne('jump',inp); + } + walkSpeed(m,inp,scale=1){const target=Math.min(inp.mag*scale,C.walkMax); // S07 update_walking_speed + if(m.fwd<=0)m.fwd+=inc(C.walkAccel);else if(m.fwd<=target)m.fwd+=inc(C.walkAccel-m.fwd/C.walkDiv);else m.fwd-=inc(C.walkOver); + if(m.fwd>C.speedCap)m.fwd=C.speedCap;m.yaw=turnTo(m.yaw,inp.yaw,ang(C.turn));} + airControl(m,inp,threshold=32){m.side=0;m.fwd=approach(m.fwd,0,inc(C.airDrag)); // S06 update_air_without_turn + if(inp.stickMag>0){const dy=wrap(inp.yaw-m.yaw),mag=inp.mag/32;m.fwd+=inc(C.airGain*Math.cos(dy)*mag);m.side=C.airSide*Math.sin(dy)*mag;} + if(m.fwd>threshold)m.fwd-=inc(C.airOver);if(m.fwd<-16)m.fwd+=inc(C.airBack);} + gravity(m,kind,inp){ + if(kind==='light'){m.vy=Math.max(-C.terminal,m.vy-inc(C.lightGravity));return;} + if(kind==='lava'){m.vy=Math.max(-C.lavaTerminal,m.vy-inc(C.lavaGravity));return;} + // Releasing A while rising faster than 20 divides the vertical speed by 4 once (S09 jump-ascent strengthening). + if(m.ctrlJump&&inp&&!inp.aD&&m.vy>20){m.vy/=4;m.ctrlJump=false;return;} + m.vy=Math.max(-C.terminal,m.vy-inc(C.gravity));} + // One tick of airborne motion; returns {landed, floor}. Even ticks match the 30 Hz explicit step exactly. + airMove(m,kind,inp){const sx=Math.sin(m.yaw),sz=Math.cos(m.yaw),vx=m.fwd*sx+m.side*sz,vz=m.fwd*sz-m.side*sx; + m.x+=vx/K;m.z+=vz/K;const v0=m.vy;this.gravity(m,kind,inp);m.y+=v0/K-(m.vy-v0)*(K-1)/(2*K); + if(m.vy>0||m.y>m.peakY)m.peakY=Math.max(m.peakY,m.y); + const fl=this.floor(m.x,m.z,m.y+Math.max(0,-v0/K));if(fl&&m.vy<=0&&m.y<=fl.y){m.y=fl.y;m.onBoss=fl.boss;return fl;}return null;} + groundStep(m){const ny=this.arena.room&&wigFloor(m.x,m.z)>0?.974:1,nx=m.x+ny*m.fwd*Math.sin(m.yaw)/K,nz=m.z+ny*m.fwd*Math.cos(m.yaw)/K,fl=this.floor(nx,nz,m.y);m.x=nx;m.z=nz; + if(!fl||fl.yC.fallDamageHeight&&m.vy<-55&&m.action!=='gp'){this.hurtMario(2);} + m.vy=0;m.side=0; + if(kind==='gp'){this.setAction('gpLand');this.stats.groundPounds++;this.fx('pound',m,26);this.emit('ground_pound_land'); + if(m.onBoss&&this.boss.kind==='whomp')this.boss.hitNow=true;return;} + if(kind==='dive'){this.setAction('diveslide');return;} + if(kind==='slidekick'){this.setAction('slidekickslide');return;} + if(kind==='kb'){this.setAction('kb');m.kbKind=m.fwd>=0?'fwd':'back';return;} + if(kind==='thrown'){const hurt=m.thrownHurt||0;m.thrownHurt=0;this.hurtMario(hurt);this.setAction('kb',hurt>0?1:0);m.kbKind=hurt>0?'hard':'fwd';return;} + m.lastLand=kind;m.djTimer=kind==='triple'||kind==='backflip'?0:fr(C.djFrames);this.setAction('land',0);m.landKind=kind; + } + startKnock(src,units){ // S04 take_damage_and_knock_back / determine_knockback_action; +30 frames invincibility after + const m=this.mario;if(this.invulnerable())return false;this.hurtMario(units);this.stats.knockbacks++; + const to=yawTo(m,src),inFront=Math.abs(wrap(to-m.yaw))<=PI/2;if(m.fwd<16)m.fwd=16; + if(inFront){m.yaw=to;m.fwd=-m.fwd;}else m.yaw=wrap(to+PI); + const hard=m.health-0x20*m.hurt<0x100||units>=4; + if(m.holding)this.dropHeld(); + if(AIR.has(m.action)){this.setAction('airkb',units>0?1:0);}else{this.setAction('kb',units>0?1:0);m.kbKind=hard?'hard':units>=2?(inFront?'back':'fwd'):'soft';} + return true;} + // ---------------- interactions (before Mario's action, as in SM64's mario_process_interactions) ---------------- + attackType(o){const m=this.mario,A=m.action,dy=Math.abs(wrap(yawTo(m,o)-m.yaw));let it=null; // S04 determine_interaction + if(PUNCHING.has(A)||A==='jumpkick'){if(m.punch==='punch'&&dy<=deg(0x2aaa))it='punch';if(m.punch==='kick'&&dy<=deg(0x2aaa))it='kick';if(m.punch==='trip'&&dy<=PI/2)it='trip';} + else if(A==='gp'){if(m.state===1&&m.vy<0)it='pound';} + else if(A==='gpLand'){if(m.timer===0)it='pound';} + else if(A==='slidekick'||A==='slidekickslide')it='slidekick'; + else if((A==='dive'||A==='diveslide')&&Math.abs(m.fwd)>=C.fastAttack)it='fast'; + if(!it&&AIR.has(A)){if(m.vy<0&&m.y>o.y)it='above';else if(m.vy>0&&m.y=min)return; + const nx=d>1e-6?(m.x-o.x)/d:Math.sin(m.yaw+PI),nz=d>1e-6?(m.z-o.z)/d:Math.cos(m.yaw+PI);m.x=o.x+nx*min;m.z=o.z+nz*min;} + interact(inp){const b=this.boss,m=this.mario;if(!b||m.action==='dead')return;m.canGrab=false; + if(b.kind==='king'){ + if(b.held||!b.tangible||m.action==='grabbed')return; + const touch=hd(m,b)<=KING.radius+C.radius+2&&m.y=p.r+C.radius||m.y>p.y+p.h||m.y+C.heightHAND.hitR+C.radius||m.y>=h.y+HAND.hitH||h.y>=m.y+C.height)continue; + const it=this.attackType(h);if(!it||it==='below')continue;h.pending=1; + if(it==='punch'||it==='kick'||it==='trip'){if(m.action==='punching')m.action='movepunch';m.fwd=AIR.has(m.action)?C.bounceAir:C.bounceGround;} + if(it==='above'){m.y=h.y+HAND.hitH;m.vy=30;} + this.fx('hit_star',{x:(m.x+h.x)/2,y:m.y+90,z:(m.z+h.z)/2},18);break;} + }else if(b.kind==='bully'){ + if(b.act==='fall'||b.act==='sink')return; + const touch=hd(m,b)<=BULLY.radius+C.radius&&m.yPI/2;if(back){m.yaw=wrap(m.yaw+PI);m.fwd=-m.fwd;}if(m.holding)this.dropHeld(); + b.act='knockback';b.counter=0;b.timer=0; // both interact_bully branches set INT_STATUS_INTERACTED -> knockback + this.stats.knockbacks++;this.emit('mario_bullied');this.fx('bump',m,16); + if(AIR.has(m.action))this.setAction('airkb',0);else{this.setAction('kb',0);m.kbKind='soft';} + } + } + } + // ---------------- Mario actions ---------------- + marioUpdate(inp){const m=this.mario; + if(m.invinc>0)m.invinc--;if(m.djTimer>0)m.djTimer--;if(m.squish>0&&m.action!=='squished')m.squish--;if(m.flash>0)m.flash--; + if(m.health>=0x100){if(m.hurt>0){m.health-=0x20;m.hurt--;}else if(m.heal>0){m.health+=0x20;m.heal--;}} // S05: 0x40 per frame + m.health=Math.min(C.maxHealth,m.health);if(m.health<0x100)m.health=Math.min(m.health,0xff); + if(m.action!=='dead'){this.interact(inp);for(let i=0;i<4;i++){this.chain=false;this.action(inp);if(!this.chain||m.action==='dead')break;}this.chain=false;}else if(++m.timer>=fr(C.deathFrames))this.outcome='loss'; + if(m.health<0x100&&!['dead','kb','airkb','squished','thrown','grabbed'].includes(m.action)&&(!AIR.has(m.action)||m.action==='lava')){ + this.setAction('dead');m.fwd=0;this.emit('mario_dead');} + if(m.y<-2500&&m.action!=='dead')this.fellOff({y:m.y,failsafe:true}); // failsafe; landings below an edge are handled in land() + } + // Mario landed on the floor below the boss floor (measured per edge). Fall damage follows check_fall_damage (S06): + // falling faster than 55, more than 3000 below the jump peak costs 4 wedges (16, cap on), more than 1150 costs 2 (8), + // but the 1150 rule is skipped on a slippery landing floor (mario_floor_is_slippery, S05) such as the slope north of + // the Whomp summit. The boss resets to full health when Mario is further below him than his far-below distance + // (S01 Whomp King 1000, S02 King Bob-omb 1200). In SM64 that check runs every frame while Mario climbs back (the WF + // elevator, the BOB mountain path); the climb is not simulated, so it is made once, at the landing (A2). + fellOff(fl){const m=this.mario,a=this.arena,b=this.boss,fall=m.peakY-fl.y,above=(b.held?0:b.y||0)-fl.y,fast=m.vy<-55||fl.failsafe; + if(a.deadly){this.stats.falls++;this.emit('fell_off');m.health=0xff;m.hurt=0;m.vy=0;m.fwd=0;m.side=0;m.onBoss=false;this.setAction('dead');this.emit('mario_dead');return;} + if(fast&&fall>3000)this.hurtMario(4);else if(fast&&fall>C.fallDamageHeight&&!fl.slip)this.hurtMario(2); + this.stats.falls++;this.emit('fell_off');if(m.holding)this.dropHeld(); + if(a.farBelow&&above>a.farBelow){if(b.kind==='king'&&b.act!==7)this.kingReset();else if(b.kind==='whomp'&&b.act!=='die'&&b.act!=='dead')this.whompReset();} + // Back on top: the fight-start spot, inside the boss's talk radius, standing for the climb and the walk back to him; + // a reset boss therefore always restarts his speech and the fight (binding rule: the boss must engage). + Object.assign(m,{x:this.start.x,z:this.start.z,y:0,vy:0,fwd:0,side:0,peakY:0,onBoss:false});m.yaw=yawTo(m,this.boss); + this.setAction(m.health<0x100?'dead':'idle');if(m.action==='dead')this.emit('mario_dead');} + whompReset(){const b=this.boss;Object.assign(b,{x:0,y:0,z:0,vy:0,fwd:0,pitch:0,pitchVel:0,act:'intro',timer:0,sub:0,hp:b.maxHp,shake:0,hitNow:false}); + this.stats.bossResets++;this.emit('whomp_reset');} + action(inp){const m=this.mario,A=m.action,stick=inp.stickMag>0; + switch(A){ + case 'idle':m.fwd=0; + if(m.holding)return this.go('hold'); + if(inp.aP)return this.jumpFromLanding(inp); + if(stick){m.yaw=inp.yaw;return this.go('walking');} + if(inp.bP)return this.startPunch('punching'); + if(inp.zD)return this.go('crouchIn'); + return; + case 'walking': + if(inp.aP)return this.jumpFromLanding(inp); + if(inp.bP){if(m.fwd>=C.diveNeed&&inp.stickMag>48){this.goAir('dive',inp,1);m.vy=C.diveVy;return;}return this.startPunch('movepunch');} + if(!stick)return this.go(m.fwd>=C.brakeNeed?'braking':'decel'); + if(Math.abs(wrap(inp.yaw-m.yaw))>deg(C.backAngle)&&m.fwd>=16)return this.go('turnaround'); + if(inp.zP)return this.go('crouchslide'); + this.walkSpeed(m,inp);if(!this.groundStep(m))this.leaveGround(inp);return; + case 'decel':case 'braking': + if(inp.aP)return this.jumpFromLanding(inp);if(inp.bP)return this.startPunch('movepunch'); + if(stick){m.yaw=turnTo(m.yaw,inp.yaw,ang(C.turn));return this.go('walking');} + if(A==='decel'&&inp.zP)return this.go('crouchslide'); // S07 act_decelerating: Z starts a crouch slide + m.fwd=approach(m.fwd,0,inc(A==='braking'?C.brakeDecel:C.decel));if(!this.groundStep(m))return this.leaveGround(inp); + if(m.fwd===0)this.setAction('idle');return; + case 'turnaround': + if(inp.aP)return this.goAir('sideflip',inp); + if(!stick)return this.go('braking'); + if(Math.abs(wrap(inp.yaw-m.yaw))<=deg(C.backAngle))return this.go('walking'); + m.fwd=approach(m.fwd,0,inc(C.brakeDecel));if(!this.groundStep(m))return this.leaveGround(inp); + if(m.fwd===0){m.yaw=inp.yaw;m.fwd=C.finishTurnFwd;this.setAction('walking');}return; + case 'crouchslide':m.timer++; + if(inp.aP)return this.goAir(m.timerC.longNeed?'longjump':'jump',inp); + if(inp.bP){if(m.fwd>=10)return this.goAir('slidekick',inp);return this.startPunch('punching',9);} + {const dy=stick?Math.cos(wrap(inp.yaw-m.yaw))*inp.mag/32:0;m.fwd*=fac(C.slideLoss+.02*dy);} + if(!this.groundStep(m))return this.leaveGround(inp); + if(Math.abs(m.fwd)<4){m.fwd=0;this.setAction(inp.zD?'crouch':'idle');}return; + case 'crouchIn':case 'crouch':case 'crouchOut':m.fwd=0;m.timer++; + if(inp.aP)return this.goAir('backflip',inp); + if(A==='crouchIn'){if(m.timer>=fr(C.crouchIn))this.setAction('crouch');return;} + if(A==='crouchOut'){if(m.timer>=fr(C.crouchOut))this.setAction('idle');return;} + if(!inp.zD)return this.go('crouchOut'); + if(inp.bP)return this.startPunch('punching',9); + return; + case 'punching':case 'movepunch':return this.punchStep(inp); + case 'pickup':m.fwd=0;m.timer++;if(m.timer===fr(C.pickUp))this.grabKing();if(m.timer>=fr(C.pickUp+C.heavyGrab))this.setAction('hold');return; + case 'hold':case 'holdwalk': + if(!m.holding)return this.setAction('idle'); + if(inp.bP)return this.go('heavythrow'); + if(stick){this.walkSpeed(m,inp,C.heavyMag);m.action='holdwalk';}else{m.fwd=0;m.action='hold';} + if(!this.groundStep(m)){this.dropHeld();this.leaveGround(inp);}return; + case 'heavythrow':m.fwd=0;m.timer++;if(m.timer===fr(C.heavyThrowRelease))this.dropHeld(true);if(m.timer>=fr(C.heavyThrowEnd))this.setAction('idle');return; + case 'land':{m.timer++;const k=m.landKind; + // S07 common_landing_cancels refreshes the double-jump timer on every landing frame (0 after triple jump / backflip); + // the landing then ends in a LAND_STOP whose stationary step zeroes the speed (S20 landing_step). Leaving it with the + // stick held goes on to walking, where set_jump_from_landing sees prevAction = *_LAND_STOP: only a side flip keeps + // its double jump there. + m.djTimer=k==='triple'||k==='backflip'?0:fr(C.djFrames); + if(m.timer>=fr(C.landFrames[k]||4)){if(stick){if(k!=='side')m.lastLand=null;return this.setAction('walking');}m.fwd=0;return this.setAction('idle');} + if(inp.aP&&LAND_A[k]){const a=LAND_A[k];m.djTimer=0; + if(a==='tripleOrJump')return this.goAir(m.fwd>C.tripleNeed?'triple':'jump',inp); + if(a==='longOrJump')return this.goAir(inp.zD&&m.fwd>C.longNeed?'longjump':'jump',inp); + if(a==='backflipIfZ')return inp.zD?this.goAir('backflip',inp):undefined; + return this.goAir(a,inp);} + if(inp.bP)return this.startPunch('movepunch'); + if(stick)m.fwd*=fac(C.landFric);else if(m.fwd>=16)m.fwd=approach(m.fwd,0,inc(C.brakeDecel)); + if(!this.groundStep(m))this.leaveGround(inp);return;} + case 'gpLand':m.timer++;m.fwd=0;if(m.timer>=fr(C.gpLand))this.setAction('idle');return; + case 'diveslide':case 'slidekickslide':m.timer++; + if(m.timer>fr(2)&&(inp.aP||inp.bP))return this.goAir('rollout',inp); + m.fwd=approach(m.fwd*fac(C.slideLoss),0,inc(.5));if(!this.groundStep(m))return this.leaveGround(inp); + if(Math.abs(m.fwd)<4){m.fwd=0;this.setAction('divestop');}return; + case 'divestop':m.timer++;if(m.timer>=fr(C.diveStop))this.setAction('idle');return; + case 'kb':return this.groundKnock(inp); + case 'squished':return this.kind==='eyerok'?this.handSquishStep():this.squishedStep(); + case 'grabbed':return; // positioned by King Bob-omb + // S08 act_picking_up_bowser (anim B5 20 frames), act_holding_bowser, act_releasing_bowser (anim B7 40 frames). The spin runs on the 30 Hz frames the decomp counts in. + case 'grabbowser':m.fwd=0;m.timer++;if(m.timer>=fr(20))this.setAction('swing',0);return; + case 'swing':m.fwd=0; + if(inp.bP){this.dropHeld(true);return this.go('release');} + if(this.t%K===0){ + if(m.swing===0){if(m.timer++>120){this.dropHeld(false);return this.go('release');}}else m.timer=0; + if(inp.mag>20){if(m.arg===0){m.arg=1;m.twirl=inp.yaw;}else{const spin=N.clamp(Math.trunc(Math.round(wrap(inp.yaw-m.twirl)/S16)/0x80),-0x80,0x80);m.twirl=inp.yaw;m.swing=N.clamp(m.swing+spin,-0x1000,0x1000);}} + else{m.arg=0;m.swing=approach(m.swing,0,64);}} + m.yaw=wrap(m.yaw+m.swing*S16/K);return; + case 'release':m.fwd=0;m.swing=0;m.timer++;if(m.timer>=fr(40))this.setAction('idle');return; + // S20 act_shockwave_bounce: 48 frames unable to move. The little bounce is only drawn. + case 'shockwave':m.fwd=0;m.timer++;if(m.timer>=fr(48))this.setAction('idle');return; + // S06 act_burning_jump / fall: no air control, burn timer +3 a frame, 10 health a frame, cannot die in the air. S07 act_burning_ground: +2 a frame, out above 160. + case 'burnjump':case 'burnfall':{m.burn+=1.5;this.burnTick();m.health=Math.max(m.health,0xff);m.side=0;const fl=this.airMove(m,'normal',inp);if(!fl)return; + if(fl.off)return this.fellOff(fl);m.vy=0;this.setAction('burnground');return;} + case 'burnground': + if(inp.aP){this.setAction('burnjump');m.vy=31.5;m.fwd=8;m.ctrlJump=false;m.peakY=m.y;return;} + m.burn+=1;if(m.burn>160)return this.setAction('walking'); + m.fwd=N.clamp(m.fwd,8,48);m.fwd=m.fwd<32?Math.min(32,m.fwd+inc(4)):Math.max(32,m.fwd-inc(1));if(stick)m.yaw=turnTo(m.yaw,inp.yaw,ang(0x600)); + if(!this.groundStep(m)){this.setAction('burnfall');m.vy=0;return;} + this.burnTick();return; + case 'gp':return this.gpStep(inp); + case 'lava':return this.lavaStep(inp); + default:return this.airStep(inp); + } + } + startPunch(kind,arg=0){this.go(kind,arg);this.stats.punches++;this.emit(arg===9?'breakdance':'punch');} + goAir(name,inp,arg=0){this.airborne(name,inp,arg);this.chain=true;} + // S08 mario_update_punch_sequence: arg 0 first punch, 2 its follow-up window, 3 second punch, 5 window, 6 kick, 9 breakdance. + punchStep(inp){const m=this.mario,F=Math.floor(m.timer/K);m.punch=null; + if(m.action==='punching'){if(m.arg===0)m.fwd=C.lungeFrames[Math.min(7,F)]; + if(inp.aP)return this.jumpFromLanding(inp);if(inp.stickMag>0&&m.arg!==0&&m.arg!==3&&m.arg!==6&&m.arg!==9){m.yaw=inp.yaw;return this.setAction('walking');}} + else{if(m.fwd>=0)m.fwd=approach(m.fwd,0,inc(1));else m.fwd=Math.min(0,m.fwd+inc(8));} + const end=()=>this.setAction(inp.stickMag>0?'walking':'idle'); + switch(m.arg){ + case 0:if(F>=2){if(m.canGrab){if(this.kind==='bowser')this.grabBowser();else this.setAction('pickup');return;}m.punch='punch';}if(++m.timer>=fr(C.punch1)){m.arg=2;m.timer=0;}break; + case 2:if(F<=0)m.punch='punch';if(inp.bP){m.arg=3;m.timer=0;this.stats.punches++;this.emit('punch');break;}if(++m.timer>=fr(C.punchFast))return end();break; + case 3:if(F>0)m.punch='punch';if(++m.timer>=fr(C.punch2)){m.arg=5;m.timer=0;}break; + case 5:if(F===0)m.punch='punch';if(inp.bP){m.arg=6;m.timer=0;this.stats.kicks++;this.emit('kick');break;}if(++m.timer>=fr(C.punchFast2))return end();break; + case 6:if(F<=7)m.punch='kick';if(++m.timer>=fr(C.kick))return end();break; + case 9:if(F>=2&&F<=7)m.punch='trip';if(++m.timer>=fr(C.breakdance))return this.setAction(inp.zD?'crouch':'idle');break; + } + if(!this.groundStep(m))this.leaveGround(inp); + } + airStep(inp){const m=this.mario,A=m.action; + const canGP=['jump','double','triple','backflip','sideflip','freefall'].includes(A); + if(canGP&&inp.zP){this.go('gp');m.vy=C.gpVy;m.fwd=0;m.side=0;this.emit('ground_pound');return;} + if(inp.bP){if(A==='jump'||A==='double'){this.goAir(m.fwd>C.airDiveNeed?'dive':'jumpkick',inp);return;} + if(A==='triple'||A==='sideflip'){this.goAir('dive',inp);return;}} + m.timer++; + if(A==='jumpkick')m.punch=Math.floor((m.timer-1)/K)<=7?'kick':null; + if(A==='airkb'){m.fwd=(m.fwd>=0?1:-1)*C.airKb;m.side=0;} + else if(A==='thrown'){m.fwd*=fac(C.thrownFric);m.side=0;} + else this.airControl(m,inp,A==='longjump'?C.longThreshold:32); + const fl=this.airMove(m,A==='longjump'||A==='slidekick'?'light':'normal',inp);if(!fl)return; + const kind={jump:'jump',double:'double',triple:'triple',backflip:'backflip',sideflip:'side',longjump:'long',dive:'dive',slidekick:'slidekick', + airkb:'kb',thrown:'thrown'}[A]||'free'; + if(A==='airkb'&&!fl.lava){const arg=m.arg;this.land('kb',inp,fl);m.arg=arg;return;} + this.land(kind,inp,fl); + } + gpStep(inp){const m=this.mario; // S06 act_ground_pound: 10-frame rise (20-2t per frame), hover, then fall from -50 + if(m.state===0){const f=Math.floor(m.timer/K);if(f=fr(C.gpWind))m.state=1;return;} + const fl=this.airMove(m,'normal',inp);if(fl)this.land('gp',inp,fl); + } + lavaStep(inp){const m=this.mario; // S06 act_lava_boost steering and bounces + if(inp.stickMag>0){const dy=wrap(inp.yaw-m.yaw),mag=inp.mag/32;m.fwd+=inc(Math.cos(dy)*mag);m.yaw=wrap(m.yaw+ang(1024*Math.sin(dy)*mag)); + if(m.fwd<0){m.yaw=wrap(m.yaw+PI);m.fwd=-m.fwd;}if(m.fwd>32)m.fwd-=inc(2);}else m.fwd=approach(m.fwd,0,inc(C.airDrag)); + m.side=0;m.timer++;const fl=this.airMove(m,'lava',inp);if(!fl)return; + if(fl.lava){m.lavaBounces=0;this.hurtMario(this.kind==='bully'?this.T.lavaHurt:3);m.vy=C.lavaVy;this.stats.lavaBoosts++;this.fx('lava_burst',m,30);this.emit('lava_boost');return;} + if(m.lavaBounces<2&&m.vy<0){m.vy=-m.vy*.4;m.fwd/=2;m.lavaBounces++;return;} + this.land('free',inp,fl); + } + groundKnock(inp){const m=this.mario,k=m.kbKind||'soft'; // S07 common_ground_knockback_action + const cut={soft:100,fwd:20,back:22,hard:21}[k],len={soft:C.kbSoft,fwd:C.kbFwd,back:C.kbBack,hard:C.kbHard}[k]; + m.fwd=N.clamp(m.fwd,-C.kbCap,C.kbCap);if(Math.floor(m.timer/K)=0?.1:-.1; + m.timer++;if(!this.groundStep(m)){const arg=m.arg;this.setAction('airkb',arg);m.vy=0;return;} + if(m.timer>=fr(len)){if(m.arg>0)m.invinc=fr(C.invincFrames);this.setAction('idle');} + } + squishedStep(){const m=this.mario,b=this.boss;m.fwd=0;m.vy=0;m.timer++; // S12 act_squished states 1-2 + const room=!b||b.kind!=='whomp'||b.act==='chase'||(b.act==='ground'&&b.sub===10&&b.pitchfr(300)){m.health=0xff;m.hurt=0;this.setAction('dead');}return;} + if(m.timer>=fr(15)){if(m.health<0x100){this.setAction('dead');this.emit('mario_dead');}else if(m.hurt===0){m.squish=fr(30);this.setAction('idle');}} + } + squishMario(units){const m=this.mario;if(['squished','dead'].includes(m.action))return;if(m.holding)this.dropHeld(); + const safe=m.invinc>0;this.setAction('squished');m.fwd=0;m.vy=0;m.side=0;m.y=0;m.squish=fr(30); + if(!safe)this.hurtMario(units);this.stats.squished++;this.emit('mario_squished');this.boss.squishedMario=true;} + // ---------------- King Bob-omb (S02 king_bobomb.inc.c, S14 chuckya.inc.c anchor, S15 act_grabbed, S16 object_helpers) ---- + kingGrabsMario(){const m=this.mario,k=this.boss;this.setAction('grabbed');m.yaw=k.yaw;m.fwd=0;m.vy=0;m.side=0;m.grabRelease=0; + k.act=3;k.sub=0;k.timer=0;k.escape=0;k.u104=0;k.grabbedMario=true;this.emit('king_grabs_mario');} + kingReleasesMario(fwd,vy){const m=this.mario,k=this.boss;k.grabbedMario=false;m.yaw=k.yaw;this.setAction('thrown',0);m.fwd=fwd;m.vy=vy;m.peakY=m.y; + m.thrownHurt=fwd>=40?this.T.throwHurt:0;this.emit(fwd>=40?'king_throws_mario':'mario_escapes');} + grabKing(){const m=this.mario,k=this.boss;if(k.kind!=='king')return;m.holding=true;k.held=true;k.tangible=false;k.act=6;k.sub=0;k.timer=0; + this.stats.grabs++;this.emit('grab_king');} + dropHeld(thrown=false){const m=this.mario,k=this.boss;if(!m.holding)return;m.holding=false; + if(k.kind==='bowser')return this.bowserLetGo(thrown); + if(k.kind!=='king')return;k.held=false; + // The heavy throw drops him (mario_drop_held_object: hands' x/z, Mario's own y); being dropped or thrown he gets + // 20 forward / 50 up, one vertical step (gravity 4: vy 46, y + 46), +20 height, action 4, intangible (S02 loop, S16). + // That first frame has no horizontal move, so his flight from here is 23 more frames, 388 units (A01). + k.x=m.x+Math.sin(m.yaw)*30;k.z=m.z+Math.cos(m.yaw)*30;k.y=m.y+66;k.yaw=m.yaw;k.fwd=20;k.vy=46; + k.act=4;k.sub=0;k.timer=0;k.tangible=false;k.skip=K-1;this.stats.throws++;this.emit(thrown?'throw_king':'drop_king');} + kingReset(){const k=this.boss;Object.assign(k,{x:k.homeX,z:k.homeZ,y:0,vy:0,fwd:0,act:0,sub:0,timer:0,hp:k.maxHp,opener:0,wait:0,held:false,tangible:false,interact:'grab',grabbedMario:false}); + this.stats.bossResets++;this.emit('king_reset');} + kingStep(k){const nx=k.x+Math.sin(k.yaw)*k.fwd/K,nz=k.z+Math.cos(k.yaw)*k.fwd/K;if(this.inside(nx,nz,60)){k.x=nx;k.z=nz;}} + kingUpdate(){const k=this.boss,m=this.mario,T=this.T;k.timer++; + if(k.held){k.x=m.x+Math.sin(m.yaw)*30;k.z=m.z+Math.cos(m.yaw)*30;k.y=m.y+KING.holdY;k.yaw=m.yaw;return;} + switch(k.act){ + // Waits at home until Mario comes within 500 (textbox check, S02 act 0), then his speech (dialog skipped: 1 s). + case 0:k.tangible=false;k.fwd=0;if(hd(k,m)>=this.arena.talk&&k.sub===0){k.timer=0;return;}k.sub=1; + k.yaw=turnTo(k.yaw,yawTo(k,m),ang(0x400));if(k.timer>=fr(30)){k.act=2;k.sub=0;k.timer=0;k.tangible=true;k.interact='grab';}return; + case 1:k.fwd=0;k.yaw=turnTo(k.yaw,yawTo(k,m),ang(0x200));if(hd(k,m)<2500){k.act=2;k.timer=0;}return; + case 2:k.tangible=true;k.interact='grab'; + // Opening stomp: anim 4 (26 frames, S18) once per fight, then anim 11 walking. + if(k.opener<2){k.fwd=0;if(k.opener===0&&k.timer>=fr(25)){k.opener=2;k.timer=0;}} + else if(k.wait>0){k.fwd=0;k.wait--;}else{k.fwd=T.walk;k.yaw=turnTo(k.yaw,yawTo(k,m),ang(T.turn));} + this.kingStep(k);return; + case 3: // carrying Mario, then turns to world yaw 0 and throws him 50 forward / 50 up (S02 act 3, S14 case 2) + if(k.sub===0){k.fwd=0;k.u104=0;k.escape=0;if(k.timer>=fr(23)){k.sub=1;k.timer=0;}} // anim 0 = 24 frames (S18) + else if(k.sub===1){ + if(k.escape>T.escape){k.act=2;k.wait=fr(35);k.timer=0;this.anchorMario();this.kingReleasesMario(10,10);return;} + k.fwd=3;if(k.u104>fr(20)){k.yaw=turnTo(k.yaw,0,ang(0x400));if(Math.abs(k.yaw)<1e-9){k.yaw=0;k.sub=2;k.timer=0;}}k.u104++;} + else{if(k.timer===fr(9)){this.anchorMario();this.kingReleasesMario(50,50);}if(k.timer>=fr(26)){k.act=1;k.timer=0;k.sub=0;}} // anim 9 frames 22..48, release at 31 + this.kingStep(k);if(k.grabbedMario)this.anchorMario();return; + case 4:{ // thrown: drag 10 (S13 physics) on each velocity axis, gravity 4, terminal -78 (cur_obj_move_standard, S16) + if(k.skip>0){k.skip--;return;} // rest of the release frame (already stepped in dropHeld) + const vx=Math.sin(k.yaw)*k.fwd,vz=Math.cos(k.yaw)*k.fwd,dk=KING.drag*1e-4/K,nvx=vx-dk*vx*Math.abs(vx),nvz=vz-dk*vz*Math.abs(vz); + k.fwd=Math.hypot(nvx,nvz);k.x+=nvx/K;k.z+=nvz/K;const v0=k.vy;objFall(k,4,78); + if(k.sub===0){const fl=this.floor(k.x,k.z,k.y+40); + if(k.y<=fl.y&&v0<=0){k.y=fl.y;k.vy=0;k.fwd=0; + if(fl.y>-100){k.hp--;this.stats.bossHits++;this.fx('impact',k,30);this.emit('king_hit'); // landed on his summit + if(k.hp<=0){k.act=7;k.timer=0;this.emit('king_defeated');}else{k.act=6;k.sub=0;k.timer=0;k.tangible=true;k.interact='damage';}} + else{k.sub=1;k.timer=0;this.emit('king_off_summit');}}} // landed below it: no damage, gets up (anim 10) then jumps home + else if(k.timer>=fr(24)){k.act=5;k.timer=0;k.arc={x:k.x,y:k.y,z:k.z};} + return;} + case 5:{const T5=fr(50),p=Math.min(1,k.timer/T5),a=k.arc;k.tangible=false;k.x=a.x+(k.homeX-a.x)*p;k.z=a.z+(k.homeZ-a.z)*p; // velY 100, gravity 4: 50 frames + k.y=a.y*(1-p)+Math.sin(PI*p)*900;k.yaw=yawTo(k,m);if(k.timer>=T5+fr(20)){k.y=0;k.act=2;k.timer=0;k.wait=0;}return;} + case 6: // hurt: damaging to touch for four loops of anim 2 (8 frames) and anim 10 (26), then intangible turn (S02 act 6) + if(k.sub===0){k.interact='damage';k.tangible=true;if(k.timer>=fr(32)){k.sub=1;k.timer=0;}} + else if(k.sub===1){if(k.timer>=fr(25)){k.sub=2;k.timer=0;k.interact='grab';k.tangible=false;}} + else{k.yaw=turnTo(k.yaw,yawTo(k,m),ang(0x800));if(Math.abs(wrap(yawTo(k,m)-k.yaw))<1e-6||k.timer>fr(60)){k.act=2;k.timer=0;k.tangible=true;}} + return; + case 7:k.tangible=false;if(k.timer>=fr(30)){this.outcome='win';this.emit('star');}return; + } + } + anchorMario(){const k=this.boss,m=this.mario,fx=Math.sin(k.yaw),fz=Math.cos(k.yaw); + m.x=k.x+fx*KING.anchorFwd+fz*KING.anchorSide;m.z=k.z+fz*KING.anchorFwd-fx*KING.anchorSide;m.y=k.y+KING.anchorY;m.yaw=k.yaw;} + escapeActions(inp){const m=this.mario;let n=0; // S16 player_performed_grab_escape_action + if(inp.stickMag<30)m.grabRelease=0;if(m.grabRelease===0&&inp.stickMag>40){m.grabRelease=1;n=1;}if(inp.aP)n=1;return n;} + // ---------------- Whomp King (S01 whomp.inc.c) ---------------- + whompUpdate(){const b=this.boss,m=this.mario,T=this.T;b.timer++;b.hitNow=b.hitNow&&b.act==='ground'; + const face=yawTo(b,m),inCone=Math.abs(wrap(face-b.yaw))=this.arena.talk&&b.sub===0){b.timer=0;return;}b.sub=1; + b.yaw=turnTo(b.yaw,face,ang(0x200));if(b.timer>=fr(30)){b.act='chase';b.sub=0;b.timer=0;}return; + case 'chase':b.fwd=3;b.yaw=turnTo(b.yaw,face,ang(T.turn)); + if(b.timer>fr(T.delay)&&inCone&&m.action!=='dead'){if(d<1500)b.fwd=T.fast;if(d=fr(14)){b.act='jump';b.timer=0;b.vy=40;this.emit('whomp_slam');}return; // anim 1 = 15 frames (S17), "near end" + case 'jump':case 'land':{objFall(b,4,78);if(b.y<0)b.y=0; + if(b.act==='jump'&&b.timer>=fr(8)){b.pitchVel+=0x100/K;b.pitch+=deg(b.pitchVel/K+0x100/(4*K)); + if(b.pitch>=deg(0x4000)){b.pitch=deg(0x4000);b.pitchVel=0;b.act='land';}} + if(b.act==='land'&&b.y<=0&&b.vy<=0){b.y=0;b.vy=0;b.act='ground';b.sub=0;b.timer=0;b.squishedMario=false;this.fx('slam_dust',this.slabCenter(),30);this.emit('whomp_landed'); + // SM64 squishes through the ceiling over Mario's centre point; a cylinder only clipping the edge is pushed out by the walls. + const s=this.slabLocal(m.x,m.z); + if(s.f>=SLAB.h0&&s.f<=SLAB.h1&&Math.abs(s.u)<=SLAB.half&&m.yfr(T.lie)||(m.action==='squished'&&b.timer>fr(30)))b.sub=10;return;} + if(b.sub===1){b.shake=b.timer%K===0?(Math.floor(b.timer/K)%2?8:-8):b.shake;if(b.timer>=fr(10)){b.shake=0;b.sub=10;}return;} + b.pitch-=ang(0x200); // rises at 0x200 per frame + if(m.onBoss&&b.pitch=fr(30)){b.act='dead';this.outcome='win';this.emit('star');}return; + } + } + slabCenter(){const b=this.boss;return {x:b.x+Math.sin(b.yaw)*480,y:100,z:b.z+Math.cos(b.yaw)*480};} + ejectFromBack(){const m=this.mario,b=this.boss;m.onBoss=false;m.yaw=wrap(b.yaw+PI);this.airborne('freefall',null);m.vy=18;m.fwd=14;} + whompSolid(){const b=this.boss,m=this.mario;if(b.kind!=='whomp'||b.act==='dead'||m.action==='grabbed')return; + const s=this.slabLocal(m.x,m.z),r=C.radius;let lo,hi,top; + // While the slab is coming down it is not a wall: whoever is under it at touchdown is squished (S12). + if(b.pitch=top||m.action==='squished')return; + const cf=N.clamp(s.f,lo,hi),cu=N.clamp(s.u,-SLAB.half,SLAB.half),df=s.f-cf,du=s.u-cu,dist=Math.hypot(df,du);if(dist>=r)return; + let nf,nu;if(dist>1e-6){nf=s.f+df/dist*(r-dist);nu=s.u+du/dist*(r-dist);} + else{const pens=[[s.f-lo+r,'f',lo-r],[hi-s.f+r,'f',hi+r],[s.u+SLAB.half+r,'u',-SLAB.half-r],[SLAB.half-s.u+r,'u',SLAB.half+r]].sort((p,q)=>p[0]-q[0])[0]; + nf=pens[1]==='f'?pens[2]:s.f;nu=pens[1]==='u'?pens[2]:s.u;} + const fx=Math.sin(b.yaw),fz=Math.cos(b.yaw);m.x=b.x+nf*fx-nu*fz;m.z=b.z+nf*fz+nu*fx;} + // ---------------- Big Bully (S03 bully.inc.c) ---------------- + bullyUpdate(){const b=this.boss,m=this.mario,T=this.T,home={x:b.homeX,z:b.homeZ},lavaY=this.arena.drop[0];b.timer++; + if(b.act!=='patrol')b.noBackup=false; + if(b.act==='fall'){objFall(b,BULLY.gravity,75); + if(b.y<=0){b.y=0;b.vy=0;b.act='chase';b.timer=0;this.fx('slam_dust',b,24);this.emit('bully_lands');}return;} + if(b.act==='sink'){b.y-=inc(10);if(b.timer>=fr(31)){b.lives--;this.emit('bully_burned'); + if(b.lives<=0){b.act='dead';this.outcome='win';this.emit('star');return;} + Object.assign(b,{act:'fall',x:b.homeX,z:b.homeZ,y:1800,vy:0,fwd:0,timer:0,counter:0});}return;} + if(b.act==='dead')return; + const old={x:b.x,z:b.z},face=yawTo(b,m); + if(b.act==='chase'){ + // S03: 10 frames at speed 3 turning 0x1000/frame toward Mario (0xA000 = 225 degrees in all), then the charge. The + // tiers shorten the wind-up (`slow`); the turn rate scales with it so the aim budget stays 0xA000 (T1). + if(b.timerfr(35))b.timer=0;if(hd(m,home)>T.leave&&m.action!=='lava'){b.act='patrol';b.timer=0;} + }else if(b.act==='patrol'){b.fwd=5;if(hd(m,home)=fr(T.recover)){b.act='chase';b.timer=0;b.counter=0;}} + else b.fwd*=fac(BULLY.friction);} + }else if(b.act==='backup'){ // S03 bully_act_back_up: reverse, walk backward at 5 for 15 frames, then patrol + if(b.timer===1){let rev=wrap(b.moveYaw+PI);b.backFace=b.faceYaw; + // T3: in a corner the reversed heading leaves by the other edge within the 75-unit back-up; SM64 then stalls + // there for good (with the end-of-back-up bug below). He heads home instead, so he keeps engaging. + if(!this.inside(b.x+Math.sin(rev)*80,b.z+Math.cos(rev)*80))rev=yawTo(b,home);b.moveYaw=rev;} + b.fwd=5;if(b.timer>fr(15)){b.act='patrol';b.timer=0;b.moveYaw=b.backFace;b.noBackup=true;}} + b.x+=Math.sin(b.moveYaw)*b.fwd/K;b.z+=Math.cos(b.moveYaw)*b.fwd/K; + if(b.act!=='knockback'&&b.act!=='backup')b.faceYaw=b.moveYaw; // he backs up facing the edge (flag cleared, S03) + if(!this.inside(b.x,b.z)){ + // S03 bully_backup_check: starting to fall (not in knockback) undoes the step and starts the back-up; already + // backing up, it only blocks (the action does not restart). T3: the decomp's //! bug, re-entering the back-up on + // the frame it ends (which leaves him stuck in it), is not reproduced. + if(b.act!=='knockback'&&b.y===0){b.x=old.x;b.z=old.z;if(b.act!=='backup'&&!b.noBackup){b.act='backup';b.timer=0;}} + else{objFall(b,BULLY.gravity,75); + if(b.y<=lavaY){b.y=lavaY;b.vy=0;b.fwd=0;b.act='sink';b.timer=0;this.stats.bossHits++;this.fx('lava_burst',b,40);this.emit('bully_in_lava');}} + } + } + // ---------------- Eyerok (S35 eyerok.inc.c; hand collision S36; squish S12 act_squished + S05 mario.c 1344) ---------- + // The hands run the original 30 Hz object logic once per two ticks, so every per-frame constant below is the decomp's + // own. Only a squish hurts: the hands deal no contact damage (hitbox damage 0, hurtbox 1 x 1, S35). + handBox(h){return h.open?HAND.open:HAND.fist;} + handLocal(h,x,z){const s=Math.sin(h.face),c=Math.cos(h.face),rx=x-h.x,rz=z-h.z;return {x:rx*c-rz*s,z:rx*s+rz*c};} + handWorld(h,lx,lz){const s=Math.sin(h.face),c=Math.cos(h.face);return {x:h.x+lx*c+lz*s,z:h.z-lx*s+lz*c};} + handOverPoint(h,x,z){const B=this.handBox(h),l=this.handLocal(h,x,z);return l.x>=B.x0&&l.x<=B.x1&&l.z>=B.z0&&l.z<=B.z1;} + solidHands(){return this.boss.hands.filter(h=>!h.gone&&h.act!=='sleep');} + // A hand's top is a floor: Mario can stand on it and is carried (S36 dynamic collision). + handTop(x,z,y){let best=null;for(const h of this.solidHands())if(this.handOverPoint(h,x,z)){const t=h.y+this.handBox(h).y1;if(y>=t-78&&(best===null||t>best))best=t;}return best;} + // Ceiling-to-floor distance over Mario's point, the only quantity act_squished reads (S05 mario.c 1344). The query starts at + // floor + 80 and S39 find_ceil keeps surfaces at least 2 above the floor; a top within 78 of Mario's feet is his floor instead. + // Only the fist has an underside: the open hand's collision has no bottom triangles (S36 070282F8), so it can never squish. + ceilGap(){const m=this.mario,fy=m.onBoss?m.y:0;let gap=Infinity;if(!inPoly(this.arena.poly,m.x,m.z))return gap; + for(const h of this.solidHands())if(!h.open&&this.handOverPoint(h,m.x,m.z)){const B=HAND.fist,under=h.y+B.y0; + if(m.y+78=fy+2)gap=Math.min(gap,under-fy);}return gap;} + handSquishStep(){const m=this.mario,gap=this.ceilGap();m.fwd=0;m.vy=0;m.side=0; // S12 act_squished + if(m.arg++>fr(300)){m.health=0xff;m.hurt=0;this.setAction('dead');this.emit('mario_dead');return;} + if(m.state===0){if(gap>160){m.squish=0;return this.setAction('idle');} + if(gap<10.1){if(m.invinc===0){this.hurtMario(this.T.squish);this.stats.squished++;this.emit('mario_squished');}m.state=1;}return;} + if(m.state===1){if(gap>=30){m.state=2;m.timer=0;}return;} + if(++m.timer>=fr(15)){if(m.health<0x100){this.setAction('dead');this.emit('mario_dead');}else if(m.hurt===0){m.squish=fr(30);this.setAction('idle');}}} + // Hands are walls for Mario: S09 checks (offset 60, radius 50) and (30, 24) on the ground, (150, 50) and (30, 50) in the air, and + // S39 find_wall only acts within the radius, so Mario deep under a fist is not pushed out (that is what lets it squish him). + // A push past the rim drops him to his death (S35 fist push). Boxes approximate the hand's four-sided hull (A7). + handSolid(inp){const m=this.mario;if(m.action==='dead')return;const air=AIR.has(m.action); + for(const h of this.solidHands()){const B=this.handBox(h),lo=h.y+B.y0-5,hi=h.y+B.y1+5; + for(const [off,r] of air?[[150,50],[30,50]]:[[60,50],[30,24]]){const y=m.y+off;if(yhi)continue; + const l=this.handLocal(h,m.x,m.z),cx=N.clamp(l.x,B.x0,B.x1),cz=N.clamp(l.z,B.z0,B.z1),dx=l.x-cx,dz=l.z-cz,dist=Math.hypot(dx,dz);if(dist>=r)continue; + let nx,nz;if(dist>1e-6){nx=l.x+dx/dist*(r-dist);nz=l.z+dz/dist*(r-dist);} + else{const p=[[l.x-B.x0,B.x0-r,l.z],[B.x1-l.x,B.x1+r,l.z],[l.z-B.z0,l.x,B.z0-r],[B.z1-l.z,l.x,B.z1+r]].sort((a,b)=>a[0]-b[0])[0];if(p[0]>r)continue;nx=p[1];nz=p[2];} + const w=this.handWorld(h,nx,nz);m.x=w.x;m.z=w.z;}} + if(m.z=deg(0x3000))return false; + h.hp--;b.hp--;this.stats.bossHits++;this.fx('impact',{x:h.x,y:h.y+150,z:h.z},30);this.emit('eyerok_hit'); + if(h.hp>=2){h.act='attacked';h.vy=30;}else{b.handsLeft--;h.act='die';h.vy=50;this.emit('eyerok_hand_dead');} + h.fwd*=.2;h.move=wrap(h.face+PI);h.ground=false;h.edge=false;h.g=-4;h.blink=3;return true;} + handPound(h){this.fx('slam_dust',{x:h.x,y:0,z:h.z},30);this.emit('eyerok_pound');} + handFrame(h){const b=this.boss,m=this.mario,T=this.T,z400=m.z<400,toM=yawTo(h,m),S=h.side,carry=m.onBoss&&m.onHand===h.idx,ox=h.x,oz=h.z; + switch(h.act){ + case 'sleep': + if(b.act!=='sleep'&&++h.wake>-3*S){ + if(this.animEnd(h,6)){b.handsLeft++;h.act='idle';break;} + h.x=approach(h.x,h.homeX,15);h.y=(200*S+400)*Math.sin(Math.abs(h.x-h.homeX)/724*PI);h.face=turnTo(h.face,h.move,deg(400));h.af++;} + return; // placed directly until awake: no floor or wall step + case 'idle':this.animEnd(h,2); + if(b.act==='fight'){ + if(b.pound!==0){if(b.pound!==1){h.act='begin';h.g=0;}} + else if(b.eyeHand===0&&b.active!==0){ + if(b.active===S){this.emit('eyerok_attack');if(z400||N.rand(this)<.5){h.act='target';h.move=toM;h.g=0;} + else{h.act='push';h.move=wrap(toM+deg(b.x-m.x<0?-0x800:0x800));h.g=-4;}} + else h.act='open';} + }else h.y=b.lift; + break; + case 'open':b.eyeHand=S; + if(this.animEnd(h,4)){h.act='eye';h.fc=2;h.u100=60;h.open=true;this.emit('eyerok_eye'); + if(b.handsLeft!==2){h.move=N.clamp(toM,-deg(0x3000),deg(0x3000));h.fwd=T.rush;}else h.move=0;} + break; + case 'eye':this.animEnd(h,5); + if(!this.handAttacked(h)){ + if(b.active===0){if(h.blink<3)h.blink++;else if(h.af===EYEROK.anim[5]-2)h.act='close';} + else{if(h.u100-->0){if(h.fc!==0)h.fc--;h.blink=EYEROK.blink[h.fc];}else{h.fc=5;h.u100=20+Math.trunc(50*N.rand(this));} + if(b.handsLeft!==2){h.face=turnTo(h.face,h.move,deg(0x800));if(h.timer>10&&(h.z-m.z>0||h.edge)){b.active=0;h.fwd=0;}}}} + break; + case 'close':if(h.anim!==7){h.anim=7;h.af=-1;} // S37 anim 7 is anim 4 played backward from frame 29; the check is frame 1, 28 frames in + if(h.timer>=28){h.open=false; + if(b.handsLeft!==2){h.act='retreat';b.active=S;}else if(b.active===0){h.act='idle';b.eyeHand=0;}} + break; + case 'attacked':if(this.animEnd(h,3)){h.act='recover';h.open=false;}if(h.ground)h.fwd=0;break; + case 'recover':if(this.animEnd(h,0))h.act='become';break; + case 'become':if(b.active===0||b.handsLeft!==2){h.act='retreat';b.active=S;}break; + case 'die':if(this.animEnd(h,1)){b.eyeHand=0;h.gone=true;this.fx('mist',{x:h.x,y:h.y+150,z:h.z},40);this.emit('eyerok_hand_gone');return;} + if(h.ground)h.fwd=0;break; + case 'retreat':{let dist=Math.hypot(h.x-h.homeX,h.z-h.homeZ);const a=Math.atan2(h.x-h.homeX,h.z-h.homeZ);dist=Math.max(0,dist-T.retreat); + h.x=h.homeX+dist*Math.sin(a);h.z=h.homeZ+dist*Math.cos(a);h.face=turnTo(h.face,0,deg(400));h.y=approach(h.y,0,20); + if(h.y===0&&dist===0&&Math.abs(h.face)<1e-9){h.face=0;h.act='idle';b.active-=S;if(b.eyeHand===S)b.eyeHand=0;}break;} + case 'target': + if(z400||h.z-m.z>0||h.z-b.z>1700||Math.abs(h.x-b.x)>900||h.wall){h.fwd=0;h.y=approach(h.y,300,20);if(h.y===300){h.act='smash';this.emit('eyerok_smash');}} + else{h.fwd=approach(h.fwd,50,5);h.y=approach(h.y,300,20);h.move=turnTo(h.move,toM,deg(4000));} + break; + case 'smash':if(h.timer>T.smashWait){ + if(h.ground){if(h.g<-4){this.handPound(h);h.g=-4;} + else{const a=Math.abs(wrap(h.face-toM)); + if(Math.hypot(m.x-h.x,m.y-h.y,m.z-h.z)<300&&a>deg(0x2000)&&a5&&(h.z-m.z>0||h.edge)){h.act='sweep';h.fwd=0;h.move=h.x-m.x<0?deg(0x4000):-deg(0x4000);this.emit('eyerok_sweep');}else h.fwd=T.push;break; + case 'sweep':if(h.z-b.z<1000||h.edge){h.act='retreat';h.fwd=0;}else{h.fwd=approach(h.fwd,5,.02)*1.08;h.timer=0;}break; + case 'begin': + if(b.pound<0||b.active===S){h.act='pound';h.move=wrap(h.face-deg(0x4000)*b.dir);} + else{const tx=b.x+400*b.dir-180*S;h.x=h.homeX+(tx-h.homeX)*b.lift;h.y=300*b.lift;h.z=h.homeZ+(b.zt-h.homeZ)*b.lift;} + break; + case 'pound':if(b.handsLeft!==2)b.active=S; + if(b.pound===1){h.act='retreat';b.eyeHand=S;} + else if(b.active===S){ + if(h.ground){if(h.g<-15){b.active=0;this.handPound(h);h.fwd=0;h.g=-15;}else{h.fwd=30*Math.abs(b.dir);h.vy=100;h.ground=false;h.edge=false;}} + else if(h.vy<=0)h.g=-20;} + break; + } + if(h.act!==h.prevAct){h.prevAct=h.act;h.timer=0;}else h.timer++; + h.af=EYEROK.noloop.has(h.anim)?Math.min(EYEROK.anim[h.anim]-1,h.af+1):(h.af+1)%EYEROK.anim[h.anim]; + // S16 cur_obj_move_standard(-78): a grounded hand stops at an edge, an airborne one may pass it; no drag, no bounce. + const nx=h.x+h.fwd*Math.sin(h.move),nz=h.z+h.fwd*Math.cos(h.move);h.edge=false; + if(h.fwd!==0&&h.ground&&!inPoly(this.arena.poly,nx,nz))h.edge=true;else{h.x=nx;h.z=nz;} + h.wall=h.z=30){b.act='fight';this.emit('eyerok_fight');}break; // dialog 117 skipped: 1 s + case 'fight':if(b.handsLeft===0){b.act='die';b.timer=0;this.emit('eyerok_defeated');break;} + if(b.eyeHand!==0||b.active!==0)break; + if(b.pound!==0){b.lift=approach(b.lift,1,.02); + if(b.lift===1){if(b.pound<0){if(m.z>=400&&++b.pound===0)b.pound=1;}else b.pound--; + if(b.pound!==0&&b.pound!==1){b.fc++;b.active=b.fc&1?1:-1;}}} + else{b.fc++; + if(m.z<400){b.pound=-8;b.lift=1;b.dir=0;} + else if(b.handsLeft===2&&b.fc%T.every===0){b.pound=T.pounds;b.lift=0;b.fc=N.rand(this)<.5?1:0;b.dir=b.fc?-1:1;b.zt=N.clamp(m.z,400,1600);this.emit('eyerok_double');} + else b.active=b.fc&1?1:-1;} + break; + case 'die':if(++b.timer>=30){b.act='dead';this.outcome='win';this.emit('star');}break; // S35 waits 60 frames for dialog 118, then the star (dialog skipped) + } + } + eyerokUpdate(inp){const b=this.boss,m=this.mario; + if(this.t%K===0){for(const h of b.hands)if(!h.gone)this.handFrame(h);this.eyerokBoss();} + if(m.onBoss&&!AIR.has(m.action)&&m.action!=='squished'){const t=this.handTop(m.x,m.z,m.y); + if(t===null||tthis.handOverPoint(q,m.x,m.z)&&q.y+this.handBox(q).y1===t);m.onHand=h?h.idx:-1;}} + else if(!m.onBoss)m.onHand=-1; + this.handSolid(inp); + if(!['squished','dead'].includes(m.action)&&this.ceilGap()<=150){if(m.holding)this.dropHeld();this.setAction('squished');m.fwd=0;m.vy=0;m.side=0;m.y=m.onBoss?m.y:0;} // S05 INPUT_SQUISHED + } + // ---------------- Wiggler (S40 wiggler.inc.c, S43 obj_behaviors_2.c, S04 interact_bounce_top, S41 room) ----------------- + // One object frame every two ticks, as for Eyerok (T5), so every per-frame constant below is the decomp's own. + wigglerParts(){const b=this.boss,s=b.s,h={x:b.x,y:b.y,z:b.z,head:true,r:60*b.sx,h:50*b.sy,hr:30*b.sx,hh:40*b.sy}; // S16 obj_set_hitbox scales the head by scale[1]; the body parts stay at scale[0] (S40) + return [h,...[1,2,3].map(i=>({x:s[i].px,y:s[i].y,z:s[i].pz,head:false,r:20*b.sx,h:20*b.sx,hr:20*b.sx,hh:10*b.sx}))];} + wigglerSpeed(){const b=this.boss,T=this.T;return b.hp===b.maxHp?T.calm:b.hp===1?T.fury:T.chase;} // S40 sWigglerSpeeds by health; extra hits keep the middle speed (T6) + wigglerFrame(){const b=this.boss,m=this.mario,T=this.T,R=this.arena.poly,x0=R[0][0]+60,x1=R[2][0]-60,z0=R[0][1]+60,z1=R[2][1]-60; + // S43 treat_far_home_as_mario, home at the origin; S16 wall resolve flags a wall only while moving into it. + const far=Math.hypot(b.x,b.y,b.z)>T.leash,toM=far?Math.atan2(-b.x,-b.z):yawTo(b,m);let wall=null; + if(b.xx1){b.x=x1;wall=-PI/2;}if(b.zz1){b.z=z1;wall=PI;} + if(wall!==null&&Math.abs(wrap(wall-b.move))<=PI/2)wall=null; + const attack=b.pending;b.pending=null; + switch(b.act){ + case 'walk': + if(b.intro>0){b.intro--;break;} // dialog 150 skipped: 1 s (A9) + b.fwd=approach(b.fwd,this.wigglerSpeed(),1); + if(b.away>0)b.away--; + else{if(far)b.target=toM; + if(wall!==null){b.target=wrap(2*wall-b.move+PI);b.away=30+Math.trunc(30*N.rand(this));} + else if(b.hp0)b.turnIn--; + else{b.target=wrap(b.move+(N.rand(this)<.5?-1:1)*deg(0x4000));b.turnIn=30+Math.trunc(50*N.rand(this));}} + {const turn=deg(30*b.fwd);b.move=turnTo(b.move,b.target,turn);b.face=turnTo(b.face,b.move,2*turn);b.pitch=approach(b.pitch,0,deg(0x320));} + if(b.timer>=60&&attack){ // S40: the first 60 frames of each walk only bounce Mario off + if(attack==='above'||attack==='pound'){b.act='jumped';b.fwd=0;b.vy=0;b.sv=.4;this.stats.bossHits++;this.fx('impact',{x:b.x,y:b.y+120,z:b.z},30);this.emit('wiggler_stomped');} + else{b.act='knockback';const up=attack!=='punch';b.fwd=up?20:50;b.vy=up?50:30;b.move=yawTo(m,b);this.emit('wiggler_knocked');} // S43 obj_set_knockback_action + b.away=0;} + break; + case 'jumped': + b.sv=approach(b.sv,0,.05);if(b.sv===0)b.sy=approach(b.sy,4,.2);else b.sy-=b.sv; + if(b.sy>=4){if(b.timer>T.daze){b.hp--;this.emit('wiggler_hit'); // S40 dialogs 152, 168, 151 skipped + if(b.hp<=0){b.act='shrink';this.emit('wiggler_defeated');} + else{b.act='walk';b.move=b.face;b.target=b.face;if(b.hp===1){b.fwd=10;b.vy=70;this.emit('wiggler_jump');}}}} + else b.timer=-1; + break; + case 'knockback': + if(b.vy>0)b.pitch-=deg(b.vy*30);else b.pitch=approach(b.pitch,0,deg(0x190)); + b.fwd=approach(b.fwd,0,1);if(b.fwd===0&&b.pitch===0){b.act='walk';b.move=b.face;} + break; + case 'shrink':if(b.timer>=20){b.sx=approach(b.sx,1,.1);b.sy=b.sx;if(b.sx===1){b.act='dead';this.outcome='win';this.emit('star');return;}}break; + case 'dead':return; + } + if(b.act!==b.prevAct){b.prevAct=b.act;b.timer=0;}else b.timer++; + // S16 cur_obj_move_standard(-78): drag per axis (S13 strength 10), then x/z, then y with gravity 4 and no bounce. The drag is why speed 40 never reads 40. + const vx0=Math.sin(b.move)*b.fwd,vz0=Math.cos(b.move)*b.fwd,vx=vx0-.001*vx0*Math.abs(vx0),vz=vz0-.001*vz0*Math.abs(vz0); + b.fwd=Math.hypot(vx,vz);b.x+=vx;b.z+=vz;b.vy=Math.max(-78,b.vy-4);b.y+=b.vy; + {const fl=wigFloor(b.x,b.z);if(b.ytop){m.y=top-C.height;if(m.vy>0)m.vy=0;}} // S09: the head stops under the hanging pyramid + } + // ---------------- Bowser in the Dark World (S50 bowser.inc.c, S51 bowser_flame.inc.c, S52 bowser_bomb.inc.c, S16 object_helpers.c) ---------------- + // One object frame every two ticks, as for Eyerok and Wiggler (T5), so every per-frame constant below is the decomp's own. + grabBowser(){const m=this.mario,b=this.boss;m.holding=true;m.yaw=b.yaw;m.fwd=0;m.vy=0;m.side=0;m.y=0;m.swing=0;b.held=true;b.heldT=0;b.grabbable=false;b.act='held';b.prev='held';this.setAction('grabbowser');this.stats.grabs++;this.emit('grab_bowser');} + // S16 cur_obj_get_thrown_or_placed, S50 bowser_thrown_dropped_update: both a throw and a drop leave at the speed of the spin. + bowserLetGo(thrown){const m=this.mario,b=this.boss,fx=Math.sin(m.yaw),fz=Math.cos(m.yaw);let spd=Math.abs(m.swing)/3000*70;if(spd>90)spd*=2.5; + Object.assign(b,{x:m.x+BOWSER.throwF*fx+BOWSER.throwL*fz,y:Math.max(0,m.y+BOWSER.throwY-2),z:m.z+BOWSER.throwF*fz-BOWSER.throwL*fx,yaw:m.yaw,fwd:spd,vy:0,held:false,act:'thrown',prev:'thrown',sub:0,timer:0,btimer:0,landed:false,onGround:false,tail:1,tailT:0,grabbable:false,skip:true}); + if(thrown){this.stats.throws++;this.emit('throw_bowser');}else this.emit('drop_bowser');m.swing=0;} + burnTick(){const m=this.mario;m.health-=5;m.burnLoss+=5;if(m.burnLoss>=0x100){m.burnLoss-=0x100;this.stats.damageTaken++;}} + burnMario(){const m=this.mario,fall=AIR.has(m.action)&&m.vy<=0;if(m.holding)this.dropHeld();m.burn=0;m.flash=24;this.stats.burns++;this.emit('mario_hurt');this.emit('mario_burned'); + this.setAction(fall?'burnfall':'burnjump');if(!fall){m.vy=31.5;m.fwd=8;m.ctrlJump=false;m.peakY=m.y;}m.side=0;} + // Runs in Mario's turn, like every other interaction here. + bowserContact(){const m=this.mario,b=this.boss,T=this.T,box=(o,r,h,down=0)=>hd(m,o)0&&box(q,150,150,150)&&this.startKnock(q,2))return;} + if(b.held||b.act==='dead')return; + if(b.op>=100&&box(b,BOWSER.bodyR,BOWSER.bodyH)&&!this.invulnerable()){m.fwd=40;this.startKnock(b,T.touch);this.emit('bowser_touch');return;} // S50 body anchor, S13 big knockback + if(!b.grabbable||!box(b,BOWSER.grabR,BOWSER.grabH))return; + if(Math.abs(wrap(m.yaw-b.yaw))>deg(0x5555))return; // S04 mario_check_object_grab: Mario must face the way he faces, so never from the front + if(PUNCHING.has(m.action)&&m.arg<2)m.canGrab=true;else if(m.action==='dive'||m.action==='diveslide')this.grabBowser();} // S04 able_to_grab_object + bowserFloor(x,z){return inPoly(this.arena.poly,x,z)?0:this.arena.drop[0];} + bowserAnim(i){const b=this.boss;if(b.anim!==i){b.anim=i;b.af=-1;}} + bowserNear(i){const b=this.boss;this.bowserAnim(i);const L=BOWSER.anim[i];return b.af===L-2||(i===9&&b.af===L-1);} // S16 cur_obj_check_if_near_animation_end + bowserExtend(){const b=this.boss;if(b.af===BOWSER.anim[b.anim]-2)b.af--;} // S16 cur_obj_extend_animation_if_at_end + bowserLand(dist){const b=this.boss,m=this.mario;if(!b.landed)return false;b.fwd=0;b.vy=0;this.bowserAnim(8);b.af=0;this.fx('slam_dust',b,30);this.emit('bowser_land');m.stomp=dist{f.s+=.5;if(f.p>0x800)f.p-=0x200;const c=Math.cos(f.p*S16);f.x+=Math.sin(f.yaw)*c*30;f.y-=Math.sin(f.p*S16)*30;f.z+=Math.cos(f.yaw)*c*30;if(f.s>30)return false; + const fl=this.bowserFloor(f.x,f.z);if(f.y>=fl)return true;b.fires.push({x:f.x,y:fl,z:f.z,yaw:N.rand(this)*PI*2-PI,vy:N.rand(this)<.2?80:20,fwd:10,s:N.rand(this)+1,act:0,t:0,g:4});return false;}); + const wob=Math.sin(((this.t/K)&0x3f)*1024*S16)*4; + b.fires=b.fires.filter(f=>{const vx=Math.sin(f.yaw)*f.fwd,vz=Math.cos(f.yaw)*f.fwd,dx=vx-.001*vx*Math.abs(vx),dz=vz-.001*vz*Math.abs(vz),fl=this.bowserFloor(f.x,f.z);f.x+=dx;f.z+=dz;f.fwd=Math.hypot(dx,dz);f.vy=Math.max(-78,f.vy-f.g);f.y+=f.vy; + const hit=f.yf.s*10+5){f.s-=.15;if(f.s<=0)return false;} + f.t++;return f.y>-600;});} + bowserFrame(){const b=this.boss,m=this.mario,T=this.T,c=this.arena.centre; + this.bowserFlames(); + for(const q of b.mines){if(q.blast>0)q.blast--;if(!q.alive&&this.d>0&&--q.back<=0){q.alive=true;this.emit('mine_back');}} + if(b.held){b.heldT++;return;} + if(b.skip){b.skip=false;return;} + if(b.act!==b.prev){b.prev=b.act;b.timer=0;b.sub=0;} + const dist=Math.hypot(m.x-b.x,m.y-b.y,m.z-b.z),toM=yawTo(b,m),off=Math.abs(wrap(toM-b.yaw)),toC=Math.atan2(c.x-b.x,c.z-b.z),distC=Math.hypot(c.x-b.x,c.z-b.z),flr=this.bowserFloor(b.x,b.z),ready=off=30)b.act='default';break; // the arena cutscene and dialog 67 skipped: 1 s (A12) + case 'default':{this.bowserAnim(12);b.fwd=0;b.vy=0;const r=N.rand(this); // S50 bowser_bitdw_actions: reacts every other time + if(!b.react){b.act=ready?(dist<1500?'breath':'quickjump'):'walk';b.react=1;}else{b.react=0;b.act=r<.1?'dance':'walk';}break;} + case 'breath':b.fwd=0;if(b.timer===0)this.emit('bowser_breath');if(this.bowserNear(6))b.act='default';break; + case 'walk': + b.yaw=turnTo(b.yaw,toM,deg(T.turn)); + if(b.sub===0){b.btimer=0;this.bowserAnim(15);if(b.af===21)b.fwd=T.walk;if(this.bowserNear(15))b.sub=1;} + else if(b.sub===1){b.fwd=T.walk;if(this.bowserNear(13)){b.btimer++;if(ready)b.sub=2;}} + else{this.bowserAnim(14);if(b.af===20)b.fwd=0;if(this.bowserNear(14))b.act='default';} + break; + case 'quickjump': + if(b.sub===0){this.bowserAnim(9);if(b.af===11){b.vy=60;b.fwd=50;b.btimer=0;b.sub=1;this.emit('bowser_jump');}} + else if(b.sub===1){if(this.bowserLand(dist))b.sub=2;} + else if(this.bowserNear(8))b.act='default'; + break; + case 'dance':if(this.bowserNear(10))b.act='default';break; + case 'thrown': // S50 bowser_act_thrown + if(b.timer<2)b.btimer=0; + if(b.sub===0){this.bowserAnim(2);if(b.landed){b.btimer++;this.fx('bump',b,16);}if(b.onGround){b.fwd=0;b.sub=1;}} + else if(this.bowserNear(0))b.act='default'; + this.bowserHitMine();break; + case 'hitmine': // S50 bowser_act_hit_mine: the original's own branch for health left (BitDW never reaches it) + if(b.timer===0){b.fwd=-400;b.vy=100;b.yaw=wrap(toC+PI);} + if(b.sub===0){this.bowserAnim(25);b.sub=1;b.btimer=0;} + else if(b.sub===1){this.bowserAnim(25);this.bowserExtend();if(b.landed){b.btimer++;this.fx('bump',b,16);}if(b.btimer>2){this.bowserAnim(26);b.vy=0;b.fwd=0;b.sub=2;}} + else if(this.bowserNear(26))b.act=b.hp===1?'dance':'default'; + break; + case 'jumpstage': // S50 bowser_act_jump_onto_stage + if(b.sub===0){b.spin+=0x800;if(!(b.spin&0xffff))b.sub=1;this.bowserHide();} + else if(b.sub===1){this.bowserAnim(9);if(b.af===11){b.yaw=toC;b.vy=150;b.btimer=0;b.sub=2;}else this.bowserHide();} + else if(b.sub===2){ + if(b.y>0){b.drag=0;if(distC<2500&&Math.abs(flr)<100)b.fwd=Math.max(0,b.fwd-5);else b.fwd=b.fwd>=150?150:b.fwd+2;} + if(this.bowserLand(dist)){b.drag=10;b.sub=3;} + else if(b.vy<0&&b.y<-300){b.x=c.x;b.z=c.z;b.y=2000;b.vy=0;b.fwd=0;}} + else if(this.bowserNear(8))b.act='default'; + break; + case 'dead': // S50 bowser_act_dead up to the end of his bounce; dialog 119, the walk up to him and the key are skipped + if(b.sub===0){this.bowserAnim(25);b.fwd=-200;b.vy=100;b.yaw=wrap(toC+PI);b.btimer=0;b.sub=1;} + else if(b.onGround){b.fwd=0;this.outcome='win';this.emit('star');return;} + break; + } + {const neg=b.fwd<0,D=b.drag*1e-4,drag=v=>{if(v===0)return 0;const a=v*v*D;if(v>0){v-=a;return v<.001?0:v;}v+=a;return v>-.001?0:v;}; // S16 cur_obj_move_standard(-78), gravity 4, bounciness -0.7 + const vx=drag(Math.sin(b.yaw)*b.fwd),vz=drag(Math.cos(b.yaw)*b.fwd),nx=b.x+vx,nz=b.z+vz; + if(!(this.bowserFloor(nx,nz)-flr<-50&&b.onGround)){b.x=nx;b.z=nz;} + b.vy=Math.max(-78,b.vy-4);b.y+=b.vy; + if(b.y45&&f<85&&!(f&1)){const [y,z,yaw,p]=BOWSER.flames[(f-46)/2];b.flames.push({x:b.x+z*Math.sin(b.yaw)+N.rand(this)*80-40,y:b.y+y,z:b.z+z*Math.cos(b.yaw)+N.rand(this)*80-40,yaw:wrap(b.yaw+yaw*S16),p:p+0xc00,s:3});}} + if(b.guard>0){if(b.act!=='hitmine')b.guard--;} + else if(b.tail===0){const dx=m.x-(b.x-Math.sin(b.yaw)*BOWSER.tailBack),dz=m.z-(b.z-Math.cos(b.yaw)*BOWSER.tailBack),ay=b.y+BOWSER.tailY; // S50 tail anchor: r100 h50, 50 up + if(Math.hypot(dx,dz)<100+C.radius&&m.y30)b.tail=0;} + if(b.op!==b.opGoal)b.op=b.opGoal>b.op?Math.min(255,b.op+20):Math.max(0,b.op-20); + {const L=BOWSER.anim[b.anim];b.af=b.anim===9?Math.min(L-1,b.af+1):(b.af+1)%L;} + b.timer++; + } + bowserUpdate(){const b=this.boss,m=this.mario;if(this.t%K===0)this.bowserFrame();if(this.outcome)return; + if(b.held){b.x=m.x+Math.sin(m.yaw)*BOWSER.holdF;b.z=m.z+Math.cos(m.yaw)*BOWSER.holdF;b.y=m.y+BOWSER.holdY;b.yaw=m.yaw;}} + // ---------------- tick ---------------- + update(keys,pressed,mouse){if(this.outcome)return; + this.camera(pressed,mouse);const inp=this.readInput(keys,pressed),m=this.mario,b=this.boss; + if(b.kind==='king'&&b.act===3&&b.sub===1&&m.action==='grabbed')b.escape+=this.escapeActions(inp); + this.marioUpdate(inp);if(this.outcome){this.lastKeys=[...keys].sort();return;} + if(b.kind==='whomp')this.whompUpdate();else if(b.kind==='king')this.kingUpdate();else if(b.kind==='eyerok')this.eyerokUpdate(inp);else if(b.kind==='wiggler')this.wigglerUpdate(inp);else if(b.kind==='bowser')this.bowserUpdate();else this.bullyUpdate(); + if(b.kind==='whomp')this.whompSolid(); + if(m.onBoss&&!this.lying()&&b.kind!=='eyerok')m.onBoss=false; + if(m.onBoss&&b.kind==='whomp'&&!AIR.has(m.action)){const top=this.bossTop(m.x,m.z);if(top===null){this.leaveGround(inp);}else m.y=top;} + this.effects=this.effects.filter(fx=>--fx.life>0);this.lastKeys=[...keys].sort(); + } + health(){const m=this.mario,b=this.boss,hp=b.kind==='bully'?b.lives:b.hp,max=b.kind==='bully'?b.maxLives:b.maxHp; + return [Math.max(0,Math.floor(m.health/0x100)),8,this.outcome==='win'?0:Math.max(0,hp),max];} + } + M.Game=Game;M.SLAB=SLAB;M.KING=KING;M.BULLY=BULLY;M.HAND=HAND;M.EYEROK=EYEROK;M.BOWSER=BOWSER;M.wigFloor=wigFloor;M.wigCeil=wigCeil;M.helpers={fr,inc,ang,deg,wrap,hd,yawTo}; + + /* Standard scripted reference controller (bossbench scripted hook). Called once per 200 ms packet with the live game; + * it plans each of the six hold sets on a deep copy (two ticks each), may test candidate inputs on further copies, and + * returns only legal holds (<= 4 keys). Deterministic; never touches the live game or its RNG. Mouse stays 0: the + * Lakitu camera's own boss focus is enough, so the script steers with the 8 stick directions relative to cam.yaw. */ + function cloneGame(g){return Object.assign(Object.create(Game.prototype),N.copy(g));} + function simTick(h,keys,mouse=[0,0,0]){const prev=new Set(h.lastKeys);h.events=[];h.update(new Set(keys),new Set(keys.filter(k=>!prev.has(k))),mouse);N.quantize(h);h.t++;} + const STICK=[['W'],['W','A'],['A'],['S','A'],['S'],['S','D'],['D'],['W','D']]; + function stickTo(h,yaw){const r=wrap(yaw-h.cam.yaw),i=((Math.round(r/(PI/4))%8)+8)%8;return STICK[i];} + function toward(h,p){return stickTo(h,yawTo(h.mario,p));} + function tap(h,k){return h.lastKeys.includes(k)?[]:[k];} + // Run a candidate input sequence on a copy and report the first event of interest. + function probe(h,seq,ticks,watch){const s=cloneGame(h);for(let i=0;i!AIR.has(m.action)&&!['squished','grabbed','dead','kb'].includes(m.action); + const free=m=>['idle','walking','decel','braking','land','turnaround'].includes(m.action); + + function planWhomp(h){const m=h.mario,b=h.boss,T=h.T; + if(['squished','dead','kb','airkb'].includes(m.action))return []; + if(b.act==='intro'&&b.sub===0)return toward(h,b); // walk up to him to start the fight + const fx=Math.sin(b.yaw),fz=Math.cos(b.yaw),pt=(f,u)=>({x:b.x+f*fx-u*fz,z:b.z+f*fz+u*fx}),s=h.slabLocal(m.x,m.z); + const danger=s.f>SLAB.h0-C.radius-40&&s.f 377, or back to the gap at his feet. + const exits=[[s.f,SLAB.half+C.radius+60],[s.f,-SLAB.half-C.radius-60],[SLAB.h0-C.radius-35,s.u]].map(([f,u])=>pt(f,u)) + .filter(p=>h.inside(p.x,p.z,50)).map(p=>{const dy=Math.abs(wrap(yawTo(m,p)-m.yaw));return {p,cost:hd(m,p)*(1+(m.fwd>8?dy*.35:0))};}); + if(!exits.length)return toward(h,pt(s.f,0));exits.sort((a,c)=>a.cost-c.cost);return toward(h,exits[0].p); + } + if(b.act==='ground'&&b.sub===0){ + const target=pt(470,0); + if(m.action==='gp'||m.action==='gpLand')return []; + const onTop=m.onBoss&&grounded(m); + if(onTop)return m.action==='land'||m.action==='idle'||m.action==='walking'?tap(h,'Space'):[]; + if(AIR.has(m.action)){const over=s.f>SLAB.h0+30&&s.fSLAB.top+12&&m.action!=='gp')return [...toward(h,target).slice(0,2),...tap(h,'Shift')]; + return [...toward(h,target),'Space'];} + const edge=Math.max(SLAB.h0-s.f,s.f-SLAB.h1,Math.abs(s.u)-SLAB.half); + if(edge<130&&free(m))return [...toward(h,target),...tap(h,'Space')]; + return toward(h,target); + } + if(b.act==='ground'||b.act==='die'||b.act==='dead')return b.act==='ground'&&m.onBoss?toward(h,pt(SLAB.h1+260,0)):[]; + // Chase: stand in his trigger cone, about 30 degrees off his centre line, so the slam can be side-stepped. + const side=s.u>=0?1:-1,f0=Math.max(150,T.range*.78),want=pt(f0,side*f0*.55); + if(!h.inside(want.x,want.z,90)){const alt=pt(f0,-side*f0*.55);return hd(m,alt)>40?toward(h,alt):[];} + return hd(m,want)>45?toward(h,want):[]; + } + // Rim guard for the open summit: keep a 220-unit lookahead on the plateau, turning toward the centre when needed. + function rimSafe(h,yaw){const m=h.mario,ok=y=>h.inside(m.x+Math.sin(y)*220,m.z+Math.cos(y)*220,110);if(ok(yaw))return yaw; + for(const d of [.4,-.4,.8,-.8,1.2,-1.2,1.6,-1.6])if(ok(wrap(yaw+d)))return wrap(yaw+d);const c=h.arena.centre;return Math.atan2(c.x-m.x,c.z-m.z);} + function planKing(h){const keys=planKingRaw(h),m=h.mario;if(!keys.some(k=>'WASD'.includes(k))||!grounded(m))return keys; + const f=(keys.includes('W')?1:0)-(keys.includes('S')?1:0),sd=(keys.includes('D')?1:0)-(keys.includes('A')?1:0),a=h.cam.yaw; + const yaw=Math.atan2(Math.sin(a)*f-Math.cos(a)*sd,Math.cos(a)*f+Math.sin(a)*sd),safe=rimSafe(h,yaw); + return safe===yaw?keys:[...stickTo(h,safe),...keys.filter(k=>!'WASD'.includes(k))];} + function planKingRaw(h){const m=h.mario,k=h.boss,C0=h.arena.centre; + if(m.action==='grabbed')return h.lastKeys.includes('Space')?[]:['Space']; + if(['dead','kb','airkb','thrown','pickup','heavythrow'].includes(m.action))return []; + if(m.holding){ + // His flight is ~530 units straight ahead; aim at the summit centre unless a throw from here already lands well inside. + const land=y=>h.inside(m.x+Math.sin(y)*530,m.z+Math.cos(y)*530,250),goal=land(m.yaw)?m.yaw:Math.atan2(C0.x-m.x,C0.z-m.z); + if(Math.abs(wrap(goal-m.yaw))>.22)return stickTo(h,goal);return tap(h,'J');} + const d=hd(m,k),fx=Math.sin(k.yaw),fz=Math.cos(k.yaw),rel=wrap(yawTo(k,m)-k.yaw),centre=Math.atan2(C0.x-k.x,C0.z-k.z),kc=hd(k,C0); + if(k.act===0)return k.sub===0?toward(h,k):[]; // walk into his 500 talk radius, then wait out the speech + if(k.act!==2||!k.tangible){ // hurt, thrown, returning: keep clear, wait between him and the centre + const away=Math.atan2(m.x-k.x,m.z-k.z);if(d<420)return stickTo(h,away); + const spot={x:C0.x+(k.x-C0.x)*.4,z:C0.z+(k.z-C0.z)*.4};return hd(m,spot)>200&&d>500?toward(h,spot):[]; + } + // His own throw sends Mario toward world yaw 0 (+z): only lure him back toward the middle when a throw from where + // he stands would carry Mario (~900 units) past the summit's far edge. + if(!h.inside(k.x,k.z+900,0)&&kc>500){const lure={x:k.x+Math.sin(centre)*400,z:k.z+Math.cos(centre)*400}; + if(d<330)return stickTo(h,wrap(yawTo(k,m)+(wrap(yawTo(k,m)-centre)>0?-1:1)*(PI/2+.3)));return hd(m,lure)>60?toward(h,lure):[];} // around him, not away + const behind={x:k.x-fx*150,z:k.z-fz*150}; + // Inside his grab reach at 31 units/frame Mario cannot brake (a 16+ turnaround slides ~60): if he is turning toward + // Mario's side and Mario is not already behind him, cut speed by releasing the stick for this hold. + if(d<300&&Math.abs(rel)20&&m.action==='walking')return []; + if(Math.abs(rel)>deg(0x5800)&&d<190){ + if(Math.abs(wrap(yawTo(m,k)-m.yaw))>.35)return toward(h,k); + if(free(m)){const p=probe(h,(s,i)=>i<2?['J']:[],26,['grab_king','king_grabs_mario']);if(p.event==='grab_king')return tap(h,'J');} + return toward(h,k);} + // Orbit at radius ~330 (tangent plus a radial correction) until he is turned away, then close in from behind. + // Dead ahead of him, the orbit side is the one passing between him and the summit centre, so it never dithers. + if(Math.abs(rel)460){ + const out=yawTo(k,m),R=330,inner=wrap(out-centre)>0?-1:1; + // Tangent to the circle, turned inward when outside radius R (toward him) and outward when inside it. + const radial=N.clamp((d-R)/160,-1,1)*.9,cand=s=>wrap(out+s*(PI/2+radial)); + // Short way round to his back; dead ahead of him, keep the side Mario is already running toward (no dithering). + let sgn=Math.abs(rel)>.6?(rel>=0?1:-1):m.fwd>8?(Math.abs(wrap(cand(1)-m.yaw))60?toward(h,centre):[]; + // Hold the middle: he always charges at Mario, so from the centre every counter-punch (pushing along Mario's + // facing, S04) sends him outward, and a lost exchange (soft knockback ~300 units, S07) cannot reach the lava. + const punch=()=>{const p=probe(h,(s,i)=>i<2?[...stickTo(s,yawTo(s.mario,s.boss)),'J']:[],24,['bully_pushed','mario_bullied']);return p.event==='bully_pushed';}; + const ready=free(m)||m.action==='crouch',outward=Math.cos(wrap(toB-Math.atan2(b.x,b.z)))>.2||bc<150; + if(ready&&d<360&&(outward||b.act==='chase')&&punch())return [...stickTo(h,toB),...tap(h,'J')]; + // Follow him outward while he slides or recovers, up to a standing line ~250 inside the rim: from there the next + // counter-punch lands with him beyond Mario, so the push carries him over the edge. + const rad=Math.atan2(b.x,b.z);let follow={x:b.x-Math.sin(rad)*180,z:b.z-Math.cos(rad)*180}; + for(let i=0;i<60&&!h.inside(follow.x,follow.z,250);i++)follow={x:follow.x*.95,z:follow.z*.95}; + if(b.act==='knockback'&&outward)return hd(m,follow)>40?toward(h,follow):stickTo(h,toB).slice(0,1); + if(b.act==='chase'&&d<700){if(!h.inside(m.x,m.z,210))return toward(h,centre);return Math.abs(wrap(toB-m.yaw))>.5&&m.action!=='idle'?stickTo(h,toB):[];} + const home={x:Math.sin(rad)*120,z:Math.cos(rad)*120}; + return hd(m,home)>60?toward(h,home):(Math.abs(wrap(toB-m.yaw))>.5?stickTo(h,toB):[]); + } + // Eyerok: goal selection plus a safety filter. Every candidate stick is played out on a copy whose RNG was replaced in M.scripted by + // planRng (a hand's next attack is not decided yet, so the planner must not see it); already-decided state (which hand is open, a hand + // hovering overhead) is fair to read. + function eyeSafe(h,keys,ticks,hold=ticks){const s=cloneGame(h);for(let i=0;i=30&&!hit)return false;} + return hit;} + function eyeSteer(h,yaw,extra=[],dist=Infinity){const H=56,run=Math.min(H,Math.ceil(dist/12)+4);let best=null,bestT=-1; + const offs=[0,.785,-.785,1.571,-1.571,2.356,-2.356,3.142]; + for(const o of offs){const keys=stickTo(h,wrap(yaw+o)),t=eyeSafe(h,keys,H,o===0?run:H);if(t>=H)return [...keys,...extra];if(t>bestT){bestT=t;best=keys;}} + const t0=eyeSafe(h,[],H);return t0>bestT?[]:[...best,...extra];} + function planEyerok(h){const m=h.mario,b=h.boss; + if(['squished','dead','kb','airkb','gpLand','punching','movepunch','divestop','diveslide'].includes(m.action))return []; + if(AIR.has(m.action))return []; + const brake=p=>m.fwd>16&&hd(m,p)=56; + const go=(p,near=30)=>brake(p)?[]:hd(m,p)>near?eyeSteer(h,yawTo(m,p),[],hd(m,p)):(eyeSafe(h,[],56)>=56?[]:eyeSteer(h,yawTo(m,{x:0,z:700}))); + if(b.act==='sleep')return toward(h,{x:0,z:0}); + if(b.act!=='fight')return go({x:m.x,z:Math.max(m.z,650)}); + // Double pound: leave the band the hands walk along (zt, footprint -201..220 plus Mario's wall radius and a margin). + if(b.pound>1){const lo=b.zt-320,hi=b.zt+340;return go({x:N.clamp(m.x,-500,500),z:lo>=450?Math.min(m.z,lo):Math.max(m.z,hi)});} + // The hand that is opening or open is already decided (b.eyeHand): wait in front of its eye, inside punch reach. + const over=b.hands.find(q=>!q.gone&&!q.open&&q.y>40&&h.handOverPoint(q,m.x,m.z)&&['target','smash','begin','pound'].includes(q.act)); + if(over){const B=HAND.fist,l=h.handLocal(over,m.x,m.z),out=[{x:B.x0-90,z:l.z},{x:B.x1+90,z:l.z},{x:l.x,z:B.z1+90},{x:l.x,z:B.z0-90}].map(p=>h.handWorld(over,p.x,p.z)).filter(p=>h.inside(p.x,p.z,120)&&p.z>=420); + if(out.length){out.sort((p,q)=>hd(m,p)-hd(m,q));return toward(h,out[0]);}} + const eye=b.hands.find(q=>!q.gone&&(q.act==='eye'||q.act==='open')); + if(eye){const toE=yawTo(m,eye),d=hd(m,eye),solo=b.handsLeft!==2; + if(eye.act==='eye'&&d<(solo?760:400)&&(free(m)||m.action==='crouch')){if(eyeStrike(h,eye))return [...stickTo(h,toE),...tap(h,'J')];} + if(solo){ // the last hand rushes faster than Mario runs and only an attack facing it lands: wait turned toward it, never run ahead of it + const face=Math.abs(wrap(toE-m.yaw))<.5?[]:stickTo(h,toE); + if(eye.act==='eye'&&eye.fwd>0&&m.z>eye.z)return face; + if(eye.act==='eye')return go({x:eye.x,z:Math.min(1600,eye.z+190)},24); + const spot={x:N.clamp(eye.homeX*.6,-500,500),z:860};return hd(m,spot)>40?go(spot,40):face;} + const clear=p=>h.inside(p.x,p.z,120)&&!b.hands.some(q=>q!==eye&&!q.gone&&[[0,0],[60,0],[-60,0],[0,60],[0,-60]].some(([a,c])=>h.handOverPoint(q,p.x+a,p.z+c))); + const spots=[{x:eye.x,z:Math.max(450,eye.z+190)},{x:eye.x-150,z:Math.max(430,eye.z+130)},{x:eye.x+150,z:Math.max(430,eye.z+130)}].filter(clear).sort((p,q)=>hd(m,p)-hd(m,q)); + return go(clear({x:eye.x,z:Math.max(450,eye.z+190)})?{x:eye.x,z:Math.max(450,eye.z+190)}:spots[0]||{x:0,z:700},24);} + // Nothing to hit yet: wait in front of the hand that is due to open next (the attacker alternates by b.fc, S35). + const next=b.handsLeft===2?(b.fc+1)&1?-1:1:0,alive=b.hands.find(q=>!q.gone); + return b.handsLeft===2?go({x:-500*next*.55,z:640}):go({x:N.clamp(alive.homeX*.6,-500,500),z:860},40); + } + // Wiggler: wait out his invulnerable 60 frames at a distance, then jump onto his head. Every committed jump and every step is played out on a copy + // whose RNG is planRng (his wander is not decided yet); his state, including the walk timer, is already decided and fair to read. + function wigSafe(h,keys,ticks){const s=cloneGame(h);for(let i=0;i=H)return keys;if(t>bestT){bestT=t;best=keys;}} + return best;} + function wigStrike(h){const p=probe(h,(s,i)=>[...toward(s,s.boss),...(i<30?['Space']:[])],70,['wiggler_stomped','mario_hurt']);return p.event==='wiggler_stomped';} + function planWiggler(h){const m=h.mario,b=h.boss,c=h.arena.centre,d=hd(m,b); + if(['squished','dead','kb','airkb','gpLand','punching','movepunch','divestop','diveslide'].includes(m.action))return []; + const soon=b.act==='walk'&&b.intro===0&&b.timer>=38; + if(AIR.has(m.action)){const rising=m.vy>0&&m.ctrlJump?['Space']:[]; + return soon?[...toward(h,b),...rising]:[...stickTo(h,yawTo(b,m)),...rising];} + if(soon&&free(m)&&d<700&&!h.lastKeys.includes('Space')&&wigStrike(h))return [...toward(h,b),'Space']; + if(soon&&d>360)return wigSteer(h,yawTo(m,b)); + // Otherwise stay out of his reach, turning toward the middle of the room as a wall comes up; he keeps chasing, so this is a slow circle. + const away=yawTo(b,m),ahead={x:m.x+Math.sin(away)*420,z:m.z+Math.cos(away)*420}; + if(d>620&&!soon)return Math.abs(wrap(yawTo(m,b)-m.yaw))>.5&&m.fwd<4?stickTo(h,yawTo(m,b)).slice(0,2):[]; + if(h.inside(ahead.x,ahead.z,120))return wigSteer(h,away); + const side=wrap(yawTo(m,c)-away)>=0?1:-1;return wigSteer(h,wrap(away+side*1.2)); + } + // Bowser: run round to his tail while he breathes or turns, punch, spin at the full rate, let go the moment a copy says the throw reaches a mine. Copies use planRng: flames not yet + // breathed and his next action are not decided; flames in the air, a jump in progress and the mines are. + function bowSafe(h,keys,ticks){const s=cloneGame(h);for(let i=0;i=H)return keys;if(t>bestT){bestT=t;best=keys;}} + return best;} + function bowSpin(h){const m=h.mario,b=h.boss,keys=stickTo(h,m.arg===0?m.yaw:wrap(m.twirl+PI/2)); + if(Math.abs(m.swing)>=0x800&&probe(h,(s,i)=>i===0?['J']:[],110,['mine_explodes']).event)return [...keys,'J']; + // At full spin the 16 headings repeat, so a mine at the edge of the range can stay out of reach for good: after about two turns throw him toward the nearest live mine and grab him closer to it. + if(b.heldT>52&&Math.abs(m.swing)>=0xf11){const live=b.mines.filter(q=>q.alive).sort((p,q)=>hd(m,p)-hd(m,q));if(!live.length||Math.abs(wrap(yawTo(m,live[0])-m.yaw))<.25)return [...keys,'J'];} + return keys;} + // Where a Bowser in flight comes down: his path is already decided (no draw until he has landed), so a copy can follow it. + function bowLanding(h){const s=cloneGame(h);for(let i=0;i<220&&!s.outcome;i++){simTick(s,[]);const b=s.boss;if(b.onGround&&!b.landed&&b.fwd===0)return b;}return s.boss;} + function planBowser(h){const m=h.mario,b=h.boss,c=h.arena.centre,d=hd(m,b); + if(m.action==='swing')return bowSpin(h); + if(m.action==='burnground')return bowSteer(h,yawTo(m,c)); + if(AIR.has(m.action))return m.vy>0&&m.ctrlJump?['Space']:[]; + if(['dead','kb','grabbowser','release','shockwave','punching','movepunch','divestop','diveslide','gpLand'].includes(m.action)||b.act==='dead')return []; + // The landing shakes the whole arena: be in the air on that frame (a jump lasts 42 ticks). + if(free(m)&&!h.lastKeys.includes('Space')&&(b.act==='quickjump'||b.act==='jumpstage')){const p=probe(h,()=>[],30,['bowser_land']);if(p.event)return ['Space'];} + // Flying (thrown, or off a mine): he lands facing the way he faces now, so wait where his tail will be. + if(b.act==='hitmine'||(b.act==='thrown'&&b.sub===0)){const L=bowLanding(h),p={x:L.x-Math.sin(L.yaw)*250,z:L.z-Math.cos(L.yaw)*250},q=h.inside(p.x,p.z,170)?p:c;return hd(m,q)>70?bowSteer(h,yawTo(m,q)):[];} + // Guarded: wait in front at breath range so that he stops to attack; go round him only as the guard runs out, or once he has begun a breath. + if(b.guard>45&&b.act!=='breath'){const out=yawTo(b,m),p={x:b.x+Math.sin(out)*1300,z:b.z+Math.cos(out)*1300},q=h.inside(p.x,p.z,250)?p:c;return hd(m,q)>120?bowSteer(h,yawTo(m,q)):[];} + if(free(m)&&d<430&&b.tail!==1&&Math.abs(wrap(m.yaw-b.yaw))<1.9){const p=probe(h,(s,i)=>i<2?['J']:[],24,['grab_bowser','mario_hurt']);if(p.event==='grab_bowser')return tap(h,'J');} + const fx=Math.sin(b.yaw),fz=Math.cos(b.yaw),back={x:b.x-fx*250,z:b.z-fz*250}; + if(!h.inside(back.x,back.z,170))return d>700?bowSteer(h,yawTo(m,b)):bowSteer(h,yawTo(m,c)); // his back is over the edge: draw him inward + const out=yawTo(b,m),rel=wrap(out-b.yaw),toBack=wrap(b.yaw+PI-out); + if(Math.abs(toBack)<.5)return bowSteer(h,yawTo(m,back)); + // Round him: tight while he walks (he turns as fast as Mario circles at about 330, and only stands still to breathe); wide of the flames once a breath has begun in front of him. + const R=b.act==='breath'&&Math.abs(rel)<1.3?560:330; + // Keep the way round Mario is already running; a change of mind at speed costs a turnaround. + const way=sg=>{const a=wrap(out+sg*Math.min(1.1,Math.abs(sg>0?wrap(toBack+PI*2)%(PI*2)||0:toBack)+.2));return {x:b.x+Math.sin(a)*R,z:b.z+Math.cos(a)*R};}; + const pS=toBack>=0?1:-1,head=sg=>Math.abs(wrap(yawTo(m,way(sg))-m.yaw)); + let sg=m.fwd>12&&Math.abs(toBack)<2.6?(head(1)>>0;x=Math.imul(x^(x>>>16),0x85ebca6b)>>>0;x=Math.imul(x^(x>>>13),0xc2b2ae35)>>>0;return (x^(x>>>16))>>>0||1;} + M.helpers.planRng=planRng; + M.scripted=function(game){const h=cloneGame(game),holds=[];if(h.boss.kind==='eyerok'||h.boss.kind==='wiggler'||h.boss.kind==='bowser')h.rng=planRng(h.rng); + for(let j=0;j<6;j++){const keys=plan(h);holds.push(keys);for(let n=0;n<2&&!h.outcome;n++)simTick(h,keys);} + return {holds,mouse:[0,0,0]};}; + M.oracle=M.scripted; // legacy tool name + // Which stretch of the difficulty table d falls in (a pure function of d): the tuning slope changes at the three tiers. + M.difficultyBand=d=>d===0?'1996':d<=.2?'1996-easy':d<=.5?'easy-normal':d<=.8?'normal-hard':'beyond-hard'; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/mario64_remake/index.html b/environments/games/web/games/mario64_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..eb4665812eaf14cbb2e555ceec40f323544407f7 --- /dev/null +++ b/environments/games/web/games/mario64_remake/index.html @@ -0,0 +1,7 @@ +Super Mario 64 · Boss Challenges
          +
          Super Mario 64 · 1996 · Boss Trials

          Super Mario 64 · Boss Challenges

          Face Whomp King, King Bob-omb, Big Bully, Eyerok, Wiggler, and Bowser. Triple jump, ground pound, grab and throw, knock foes into lava, strike exposed palms, stomp heads, and swing Bowser into mines. Mechanics follow the public SM64 decompilation; the low-poly art is original.

          Back to Game Lobby ↗
          +
          Are You Ready?Click Start Challenge
          +

          The scripted demo reads internal state to verify each fight can be completed. Replays save real inputs, reproduce the entire fight, and verify the final state.

          +
          +
          All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
          + diff --git a/environments/games/web/games/mario64_remake/manifest.json b/environments/games/web/games/mario64_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8781f4ca00acba32436beb9ac09e226c2ee2200a --- /dev/null +++ b/environments/games/web/games/mario64_remake/manifest.json @@ -0,0 +1,34 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "mario64_remake", + "module": "Mario64Game", + "title": "Super Mario 64: Boss Challenges", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-mario64", + "rules": "sm64-bosses@5", + "cases": [ + "mario64/whomp_king", + "mario64/king_bobomb", + "mario64/big_bully", + "mario64/eyerok", + "mario64/wiggler", + "mario64/bowser_dark_world" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "mario64_remake/renderer3d.js", + "mario64_remake/game.js", + "mario64_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "mario64_remake/game.js" + ], + "play_page": "web/games/mario64_remake/index.html", + "original_clock": "SM64 logic runs at 30 Hz (n64decomp/sm64 src/game/hud.c: 30 frames per second); this port runs 60 Hz, two ticks per original frame", + "scripted_controller": "Mario64Game.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]} (plans on deep copies, deterministic; .oracle is an alias)" +} diff --git a/environments/games/web/games/mario64_remake/renderer3d.js b/environments/games/web/games/mario64_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..a53145417681c9b4caa881672d7d531cca25e1cc --- /dev/null +++ b/environments/games/web/games/mario64_remake/renderer3d.js @@ -0,0 +1,387 @@ +/* Original low-poly, N64-flavoured art for the Super Mario 64 boss trials. Three.js 0.160.1 is the vendored shared copy + * (MIT, web/games/_boss3d/vendor, read-only). Every mesh and texture below is built procedurally in this file; no + * Nintendo model, texture or sound is used. Rendering only reads game state: the Lakitu camera, + * every pose clock and every effect come from the simulation, so a frame is a pure function of the state. */ +(function(root){ + 'use strict'; + const T=root.THREE,R=root.Mario3D={}; + if(!T)throw Error('Offline Three.js renderer library is missing'); + const U=.01,byCanvas=new WeakMap(),clamp=(x,a,b)=>Math.max(a,Math.min(b,x)),items=a=>Array.isArray(a)?a:[],PI=Math.PI; + function hash(x,y,s){let n=Math.imul(x*73856093^y*19349663^s*83492791,1274126177);n^=n>>>15;n=Math.imul(n,2246822519);return ((n^(n>>>13))>>>0)/4294967295;} + function canvasTex(w,h,draw,repeat){const c=document.createElement('canvas');c.width=w;c.height=h;draw(c.getContext('2d'),w,h); + const t=new T.CanvasTexture(c);t.colorSpace=T.SRGBColorSpace;if(repeat){t.wrapS=t.wrapT=T.RepeatWrapping;t.repeat.set(repeat[0],repeat[1]);}return t;} + const rgb=(r,g,b)=>`rgb(${r|0},${g|0},${b|0})`; + // Stone tiles: blocks with per-block brightness and a mortar line (Whomp's Fortress, the Bully platform). + function tiles(q,w,h,base,mortar,cols,rows,seed,offset=true){q.fillStyle=mortar;q.fillRect(0,0,w,h);const bw=w/cols,bh=h/rows; + for(let j=0;jcanvasTex(256,256,(q,w,h)=>{tiles(q,w,h,[206,190,160],'#8e806a',4,8,3);speckle(q,w,h,700,4,'rgba(80,60,40,.18)','rgba(255,255,240,.16)');},[9,9]), + wall:()=>canvasTex(256,256,(q,w,h)=>{tiles(q,w,h,[176,160,132],'#776a57',4,8,9);speckle(q,w,h,500,5,'rgba(60,50,40,.2)','rgba(255,250,230,.1)');},[9,4]), + grass:()=>canvasTex(256,256,(q,w,h)=>{q.fillStyle='#4f9a33';q.fillRect(0,0,w,h);speckle(q,w,h,2600,7,'#3f8628','#69b443'); + for(let i=0;i<220;i++){const x=hash(i,8,7)*w,y=hash(i,9,7)*h;q.strokeStyle=hash(i,10,7)<.5?'#2f6e1f':'#7cc452';q.beginPath();q.moveTo(x,y);q.lineTo(x+2-hash(i,11,7)*4,y-4-hash(i,12,7)*5);q.stroke();}},[14,14]), + slope:()=>canvasTex(128,256,(q,w,h)=>{const g=q.createLinearGradient(0,0,0,h);g.addColorStop(0,'#4c8e31');g.addColorStop(.35,'#6f6a3c');g.addColorStop(1,'#5b4b33');q.fillStyle=g;q.fillRect(0,0,w,h); + speckle(q,w,h,1400,13,'rgba(40,30,20,.25)','rgba(255,240,200,.12)');for(let y=30;ycanvasTex(256,256,(q,w,h)=>{tiles(q,w,h,[132,124,118],'#3e3533',4,4,21,false); + q.strokeStyle='rgba(30,24,22,.55)';q.lineWidth=3;for(let i=0;i<=4;i++){q.beginPath();q.moveTo(i*w/4,0);q.lineTo(i*w/4,h);q.stroke();q.beginPath();q.moveTo(0,i*h/4);q.lineTo(w,i*h/4);q.stroke();} + for(let i=0;i<4;i++)for(let j=0;j<4;j++){q.fillStyle='#d9cfc3';q.beginPath();q.arc(i*w/4+10,j*h/4+10,3,0,PI*2);q.fill();}},[6,6]), + lava:()=>canvasTex(256,256,(q,w,h)=>{q.fillStyle='#a3200c';q.fillRect(0,0,w,h); + for(let i=0;i<150;i++){const x=hash(i,1,31)*w,y=hash(i,2,31)*h,r=4+hash(i,3,31)*18;const g=q.createRadialGradient(x,y,0,x,y,r);g.addColorStop(0,'rgba(255,214,90,.95)');g.addColorStop(.5,'rgba(255,120,30,.55)');g.addColorStop(1,'rgba(255,80,10,0)'); + for(const ox of [-w,0,w])for(const oy of [-h,0,h]){q.fillStyle=g;q.save();q.translate(ox,oy);q.beginPath();q.arc(x,y,r,0,PI*2);q.fill();q.restore();}} + speckle(q,w,h,600,33,'rgba(80,10,0,.35)','rgba(255,240,150,.25)');},[24,24]), + sand:()=>canvasTex(256,256,(q,w,h)=>{tiles(q,w,h,[214,178,112],'#9a7a48',4,4,71);speckle(q,w,h,1200,72,'rgba(90,60,20,.2)','rgba(255,240,190,.18)');},[8,8]), + stone:()=>canvasTex(128,128,(q,w,h)=>{q.fillStyle='#a9a8a2';q.fillRect(0,0,w,h);speckle(q,w,h,900,41,'rgba(70,70,70,.28)','rgba(255,255,255,.18)'); + q.strokeStyle='rgba(60,60,60,.35)';for(let i=0;i<5;i++){q.beginPath();const x=hash(i,1,42)*w,y=hash(i,2,42)*h;q.moveTo(x,y);q.lineTo(x+10-hash(i,3,42)*20,y+12);q.lineTo(x+18-hash(i,4,42)*30,y+26);q.stroke();}},[1,1]), + face:()=>canvasTex(256,320,(q,w,h)=>{q.fillStyle='#b3b1aa';q.fillRect(0,0,w,h);speckle(q,w,h,1500,51,'rgba(70,70,70,.25)','rgba(255,255,255,.16)'); + for(const s of [-1,1]){const cx=w/2+s*58,cy=88;q.fillStyle='#fafaf2';q.beginPath();q.ellipse(cx,cy,34,40,0,0,PI*2);q.fill();q.strokeStyle='#2c2b2a';q.lineWidth=5;q.stroke(); + q.fillStyle='#1d1c1c';q.beginPath();q.ellipse(cx-s*6,cy+6,13,18,0,0,PI*2);q.fill();q.fillStyle='#fff';q.fillRect(cx-s*6-4,cy-4,5,6); + q.fillStyle='#3d3b39';q.beginPath();q.moveTo(cx-s*46,cy-50);q.lineTo(cx+s*40,cy-30);q.lineTo(cx+s*38,cy-18);q.lineTo(cx-s*46,cy-36);q.closePath();q.fill();} + q.fillStyle='#3a2a26';q.beginPath();q.moveTo(w/2-60,182);q.quadraticCurveTo(w/2,158,w/2+60,182);q.lineTo(w/2+52,202);q.quadraticCurveTo(w/2,186,w/2-52,202);q.closePath();q.fill(); + q.fillStyle='#ebe6da';for(let i=0;i<5;i++)q.fillRect(w/2-44+i*19,180,13,9); + q.strokeStyle='rgba(50,50,50,.45)';q.lineWidth=3;q.strokeRect(10,10,w-20,h-20);}), + back:()=>canvasTex(256,320,(q,w,h)=>{q.fillStyle='#a7a59e';q.fillRect(0,0,w,h);speckle(q,w,h,1500,61,'rgba(70,70,70,.25)','rgba(255,255,255,.16)'); + q.save();q.translate(w/2,h*.46);for(const a of [-.62,.62]){q.save();q.rotate(a);q.fillStyle='#efe6cf';q.fillRect(-26,-128,52,256);q.fillStyle='rgba(150,130,100,.5)';for(let y=-120;y<128;y+=22)q.fillRect(-26,y,52,3);q.restore();}q.restore(); + q.strokeStyle='rgba(50,50,50,.45)';q.lineWidth=3;q.strokeRect(10,10,w-20,h-20);}), + blob:()=>canvasTex(64,64,(q,w,h)=>{const g=q.createRadialGradient(32,32,2,32,32,31);g.addColorStop(0,'rgba(0,0,0,.62)');g.addColorStop(.7,'rgba(0,0,0,.42)');g.addColorStop(1,'rgba(0,0,0,0)');q.fillStyle=g;q.fillRect(0,0,w,h);}), + cloud:()=>canvasTex(128,64,(q,w,h)=>{for(const [x,y,r] of [[40,38,24],[64,30,28],[90,38,22],[60,44,22]]){const g=q.createRadialGradient(x,y,2,x,y,r);g.addColorStop(0,'rgba(255,255,255,.95)');g.addColorStop(1,'rgba(255,255,255,0)');q.fillStyle=g;q.beginPath();q.arc(x,y,r,0,PI*2);q.fill();}}), + sky:(top,mid,bottom)=>canvasTex(16,256,(q,w,h)=>{const g=q.createLinearGradient(0,0,0,h);g.addColorStop(0,top);g.addColorStop(.55,mid);g.addColorStop(1,bottom);q.fillStyle=g;q.fillRect(0,0,w,h);}) + }; + const COL={red:0xd8262b,blue:0x2a4ed0,skin:0xffc9a0,white:0xf4f4f0,brown:0x7a4422,hair:0x3a2414,yellow:0xf2c230,gold:0xe2aa2a,black:0x1d1e24,stone:0xc9c7bf,iron:0x30333a,horn:0xf3eee0}; + class Scene{ + constructor(canvas){ + this.canvas=canvas;this.resources=new Set();this.times=[];this.ready=false;this.error=null;this.closed=false;this.kind=null; + this.view=document.createElement('canvas');this.view.width=854;this.view.height=480; + this.renderer=new T.WebGLRenderer({canvas:this.view,alpha:false,antialias:true,preserveDrawingBuffer:true,powerPreference:'low-power'}); + this.renderer.setPixelRatio(1);this.renderer.setSize(854,480,false);this.renderer.outputColorSpace=T.SRGBColorSpace; + this.renderer.toneMapping=T.ACESFilmicToneMapping;this.renderer.toneMappingExposure=1.08;this.renderer.info.autoReset=false; + this.view.addEventListener('webglcontextlost',e=>{e.preventDefault();this.ready=false;this.error='WebGL context lost';}); + this.world=new T.Scene();this.camera=new T.PerspectiveCamera(50,854/480,.1,420); + this.hemi=new T.HemisphereLight(0xdcefff,0x6a6250,2.1);this.world.add(this.hemi); + this.sun=new T.DirectionalLight(0xfff1d6,2.6);this.sun.position.set(-30,60,25);this.world.add(this.sun); + this.geo={box:this.keep(new T.BoxGeometry(1,1,1)),sphere:this.keep(new T.SphereGeometry(1,14,10)),half:this.keep(new T.SphereGeometry(1,14,6,0,PI*2,0,PI/2)), + cyl:this.keep(new T.CylinderGeometry(1,1,1,12)),cone:this.keep(new T.ConeGeometry(1,1,10)),disc:this.keep(new T.CircleGeometry(1,24)),ring:this.keep(new T.RingGeometry(.82,1,32)), + ico:this.keep(new T.IcosahedronGeometry(1,0)),oct:this.keep(new T.OctahedronGeometry(1,0)),plane:this.keep(new T.PlaneGeometry(1,1)),torus:this.keep(new T.TorusGeometry(1,.18,6,14))}; + const L=(c,o={})=>this.keep(new T.MeshLambertMaterial({color:c,flatShading:o.flat!==false,...o.extra})); + this.mat={red:L(COL.red),blue:L(COL.blue),skin:L(COL.skin),white:L(COL.white),brown:L(COL.brown),hair:L(COL.hair),yellow:L(COL.yellow), + gold:this.keep(new T.MeshStandardMaterial({color:COL.gold,roughness:.35,metalness:.75,flatShading:true})),black:this.keep(new T.MeshStandardMaterial({color:COL.black,roughness:.38,metalness:.25})), + iron:this.keep(new T.MeshStandardMaterial({color:COL.iron,roughness:.42,metalness:.65,flatShading:true})),horn:L(COL.horn),eye:L(0xffffff),pupil:L(0x101014),orange:L(0xf08a24), + stone:L(0xffffff,{extra:{map:this.keep(TEX.stone())}}),face:L(0xffffff,{flat:false,extra:{map:this.keep(TEX.face())}}),back:L(0xffffff,{flat:false,extra:{map:this.keep(TEX.back())}})}; + this.fxMat={dust:this.keep(new T.MeshLambertMaterial({color:0xe9e2d2,transparent:true,opacity:.8,depthWrite:false})),star:this.keep(new T.MeshBasicMaterial({color:0xffe24a})), + ring:this.keep(new T.MeshBasicMaterial({color:0xfff6d8,transparent:true,opacity:.55,side:T.DoubleSide,depthWrite:false})), + fire:this.keep(new T.MeshBasicMaterial({color:0xff7a1a,transparent:true,opacity:.85,depthWrite:false})),ember:this.keep(new T.MeshBasicMaterial({color:0xffb347}))}; + this.blobMat=this.keep(new T.MeshBasicMaterial({map:this.keep(TEX.blob()),transparent:true,depthWrite:false})); + this.slabShadowMat=this.keep(new T.MeshBasicMaterial({color:0x1a1410,transparent:true,opacity:.0,depthWrite:false})); + this.landMat=this.keep(new T.MeshBasicMaterial({color:0x7a1c10,transparent:true,opacity:0,depthWrite:false})); + this.arenas={};this.mario=this.buildMario();this.world.add(this.mario.root); + this.handShadowMat=this.keep(new T.MeshBasicMaterial({color:0x1a1008,transparent:true,opacity:.42,depthWrite:false})); + this.bosses={whomp:this.buildWhomp(),king:this.buildKing(),bully:this.buildBully(),eyerok:this.buildEyerok(),wiggler:this.buildWiggler(),bowser:this.buildBowser()};for(const b of Object.values(this.bosses)){b.root.visible=false;this.world.add(b.root);} + this.marioBlob=this.blob(.42);this.bossBlob=this.blob(1);this.slabShadow=new T.Mesh(this.geo.plane,this.slabShadowMat);this.slabShadow.rotation.x=-PI/2;this.world.add(this.slabShadow); + this.landZone=new T.Mesh(this.geo.plane,this.landMat);this.landZone.renderOrder=2;this.world.add(this.landZone); + this.pools={dust:this.pool(this.geo.ico,this.fxMat.dust,96),star:this.pool(this.geo.oct,this.fxMat.star,64),ring:this.pool(this.geo.ring,this.fxMat.ring,16),fire:this.pool(this.geo.ico,this.fxMat.fire,220),ember:this.pool(this.geo.box,this.fxMat.ember,48)}; + this.o=new T.Object3D(); + } + keep(x){this.resources.add(x);return x;} + mesh(geo,mat,parent,pos=[0,0,0],scale=[1,1,1],rot=[0,0,0]){const m=new T.Mesh(geo,mat);m.position.set(pos[0],pos[1],pos[2]);m.scale.set(scale[0],scale[1],scale[2]);m.rotation.set(rot[0],rot[1],rot[2]);parent.add(m);return m;} + group(parent,pos=[0,0,0]){const g=new T.Group();g.position.set(pos[0],pos[1],pos[2]);parent.add(g);return g;} + pool(geo,mat,n){const m=new T.InstancedMesh(geo,mat,n);m.count=0;m.frustumCulled=false;this.world.add(m);this.keep(m);return m;} + blob(r){const m=new T.Mesh(this.geo.disc,this.blobMat);m.rotation.x=-PI/2;m.scale.set(r,r,1);m.renderOrder=1;this.world.add(m);return m;} + // ---------------- characters (original low-poly designs) ---------------- + buildMario(){const M=this.mat,g=this.geo,root=new T.Group(),body=this.group(root,[0,.78,0]); + this.mesh(g.sphere,M.blue,body,[0,-.12,0],[.34,.30,.29]);this.mesh(g.sphere,M.red,body,[0,.12,0],[.31,.27,.26]); + for(const s of [-1,1]){this.mesh(g.box,M.blue,body,[s*.12,.13,.2],[.07,.26,.05]);this.mesh(g.sphere,M.yellow,body,[s*.12,.02,.25],[.045,.045,.03]);} + const head=this.group(body,[0,.48,0]);this.mesh(g.sphere,M.skin,head,[0,0,0],[.25,.24,.24]); + this.mesh(g.half,M.red,head,[0,.04,0],[.265,.2,.265]);this.mesh(g.cyl,M.red,head,[0,.05,.16],[.2,.025,.17]); + this.mesh(g.disc,M.white,head,[0,.14,.235],[.07,.07,1],[-.35,0,0]);this.mesh(g.box,M.red,head,[0,.14,.237],[.05,.05,.01],[-.35,0,0]); + this.mesh(g.sphere,M.skin,head,[0,-.02,.24],[.075,.07,.08]);this.mesh(g.box,M.hair,head,[0,-.09,.21],[.22,.05,.05]); + for(const s of [-1,1]){this.mesh(g.sphere,M.eye,head,[s*.075,.06,.2],[.05,.065,.03]);this.mesh(g.sphere,M.blue,head,[s*.07,.055,.225],[.025,.035,.012]); + this.mesh(g.box,M.hair,head,[s*.21,-.02,-.02],[.04,.12,.12]);this.mesh(g.sphere,M.skin,head,[s*.235,-.02,0],[.04,.06,.04]);} + const arms=[],legs=[]; + for(const s of [-1,1]){const sh=this.group(body,[s*.3,.24,0]);this.mesh(g.cyl,M.red,sh,[0,-.14,0],[.07,.28,.07]);const fore=this.group(sh,[0,-.28,0]); + this.mesh(g.cyl,M.red,fore,[0,-.08,0],[.06,.16,.06]);this.mesh(g.sphere,M.white,fore,[0,-.2,0],[.095,.09,.095]);arms.push({sh,fore}); + const hip=this.group(body,[s*.13,-.3,0]);this.mesh(g.cyl,M.blue,hip,[0,-.17,0],[.085,.34,.085]);const shin=this.group(hip,[0,-.32,0]); + this.mesh(g.sphere,M.brown,shin,[0,-.12,.05],[.1,.07,.16]);legs.push({hip,shin});} + return {root,body,head,arms,legs};} + buildWhomp(){const M=this.mat,g=this.geo,s=200*U*1,root=new T.Group(),tilt=this.group(root),slab=this.group(tilt); + // Collision box x -150..150, y 50..430, z -100..-3 at scale 2 (S11): 6 m wide, 1.0..8.6 m high, 1.94 m deep. + const W=6,H0=1,H1=8.6,D0=-2,D1=-.06,cy=(H0+H1)/2,cz=(D0+D1)/2; + this.mesh(g.box,[M.stone,M.stone,M.stone,M.stone,M.face,M.back],slab,[0,cy,cz],[W,H1-H0,D1-D0]); + this.mesh(g.box,M.stone,slab,[0,H1+.12,cz],[W*.92,.24,(D1-D0)*.9]); + const arms=[];for(const sd of [-1,1]){const sh=this.group(slab,[sd*(W/2+.15),5.6,cz]);this.mesh(g.box,M.stone,sh,[sd*.55,-1.2,0],[1.0,2.6,1.0]);this.mesh(g.box,M.stone,sh,[sd*.6,-2.75,.15],[1.2,.8,1.25]);arms.push(sh);} + const feet=[];for(const sd of [-1,1]){const f=this.group(root,[sd*1.6,0,cz+.5]);this.mesh(g.box,M.stone,f,[0,.45,0],[1.25,.9,1.6]);this.mesh(g.box,M.stone,f,[0,.18,.55],[1.35,.36,.9]);feet.push(f);} + return {root,tilt,slab,arms,feet,size:s};} + buildKing(){const M=this.mat,g=this.geo,root=new T.Group(),body=this.group(root,[0,1.32,0]); + this.mesh(g.sphere,M.black,body,[0,0,0],[1.16,1.12,1.16]); + for(const sd of [-1,1]){this.mesh(g.sphere,M.eye,body,[sd*.34,.25,.98],[.25,.36,.15]);this.mesh(g.sphere,M.pupil,body,[sd*.32,.22,1.1],[.1,.17,.06]); + this.mesh(g.sphere,M.white,body,[sd*.33,-.26,1.04],[.42,.15,.16],[0,0,sd*.25]);} + const crown=this.group(body,[0,1.02,0]);this.mesh(g.cyl,M.gold,crown,[0,0,0],[.62,.42,.62]); + for(let i=0;i<6;i++){const a=i*PI/3;this.mesh(g.cone,M.gold,crown,[Math.sin(a)*.5,.36,Math.cos(a)*.5],[.17,.38,.17]);this.mesh(g.sphere,M.red,crown,[Math.sin(a)*.62,.02,Math.cos(a)*.62],[.07,.07,.07]);} + const key=this.group(body,[0,.15,-1.12]);this.mesh(g.cyl,M.gold,key,[0,0,-.18],[.08,.36,.08],[PI/2,0,0]);for(const sd of [-1,1])this.mesh(g.torus,M.gold,key,[sd*.26,0,-.42],[.28,.28,.28],[0,PI/2,0]); + const arms=[];for(const sd of [-1,1]){const sh=this.group(body,[sd*1.08,.05,.1]);this.mesh(g.cyl,M.black,sh,[sd*.25,0,0],[.12,.5,.12],[0,0,PI/2]);this.mesh(g.sphere,M.white,sh,[sd*.6,0,0],[.26,.26,.26]);arms.push(sh);} + const feet=[];for(const sd of [-1,1]){const f=this.group(root,[sd*.55,0,.1]);this.mesh(g.sphere,M.orange,f,[0,.18,.15],[.36,.2,.5]);feet.push(f);} + return {root,body,arms,feet,key};} + buildBully(){const M=this.mat,g=this.geo,root=new T.Group(),body=this.group(root,[0,1.18,0]); + this.mesh(g.sphere,M.iron,body,[0,0,0],[1.15,1.15,1.15]); + for(const sd of [-1,1]){const h=this.mesh(g.cone,M.horn,body,[sd*.62,.92,.05],[.2,.75,.2],[0,0,-sd*.6]); + this.mesh(g.sphere,M.eye,body,[sd*.32,.22,1.0],[.22,.27,.12]);this.mesh(g.sphere,M.pupil,body,[sd*.3,.2,1.09],[.1,.14,.05]); + this.mesh(g.box,M.black,body,[sd*.32,.52,.98],[.34,.08,.08],[0,0,sd*.35]);} + const feet=[];for(const sd of [-1,1]){const f=this.group(root,[sd*.5,0,.05]);this.mesh(g.sphere,M.black,f,[0,.16,.2],[.32,.18,.46]);feet.push(f);} + return {root,body,feet};} + // ---------------- arenas ---------------- + // Extruded outline (local world units): top face at y0, walls down by depth; [top, side] materials. + prism(poly,depth,top,side,y0=0){const s=new T.Shape();poly.forEach(([x,z],i)=>i?s.lineTo(x*U,z*U):s.moveTo(x*U,z*U)); + const m=new T.Mesh(this.keep(new T.ExtrudeGeometry(s,{depth:depth*U,bevelEnabled:false,curveSegments:1})),[top,side]);m.rotation.x=PI/2;m.position.y=y0*U;return m;} + tex(make,rep){const t=this.keep(make());t.repeat.set(rep,rep);return t;} + // Arenas follow the measured outlines (game.js ARENA: decomp collision of WF / BOB / LLL). Beyond each edge a ledge + // is drawn at that edge's measured drop, so a fall looks like the floor the simulation lands Mario on. + // Eyerok's two stone hands. The fist and palm blocks use the measured collision boxes (S36 x 1.5), so what is drawn is what + // squishes or blocks Mario; the model is unmirrored for the same reason. Each hand throws a footprint shadow on the floor. + buildEyerok(){const M=this.mat,g=this.geo,root=new T.Group(),sand=this.keep(new T.MeshLambertMaterial({color:0xb4764a,flatShading:true})),dark=this.keep(new T.MeshLambertMaterial({color:0x7c4a2c,flatShading:true})); + const lid=this.keep(new T.MeshLambertMaterial({color:0x96603a,flatShading:true})),iris=this.keep(new T.MeshLambertMaterial({color:0xd8362a})); + const hands=[];for(const side of [-1,1]){const h=this.group(root); + const fist=this.group(h);this.mesh(g.box,sand,fist,[-.1425,1.5525,.0975],[2.325,3.015,4.215]); + for(let i=0;i<4;i++)this.mesh(g.box,dark,fist,[-1.0+i*.58,2.85,2.05],[.5,.72,.46]); + this.mesh(g.box,dark,fist,[-.1425,.28,-1.75],[2.45,.56,.8]); + const palm=this.group(h);this.mesh(g.box,sand,palm,[.3825,2.535,0],[3.825,5.07,1.53]); + for(let i=0;i<4;i++)this.mesh(g.box,dark,palm,[-1.1+i*.98,5.45,0],[.72,.9,1.16]); + this.mesh(g.box,dark,palm,[.3825,.22,0],[3.95,.44,1.7]); + const eye=this.group(palm,[.3825,2.6,.77]);this.mesh(g.sphere,M.eye,eye,[0,0,0],[1.05,1.05,.22]);const pupil=this.group(eye); + this.mesh(g.sphere,iris,pupil,[0,0,.16],[.5,.5,.12]);this.mesh(g.sphere,M.pupil,pupil,[0,0,.25],[.24,.24,.06]); + const upper=this.mesh(g.box,lid,eye,[0,.55,.27],[2.3,1.1,.16]),lower=this.mesh(g.box,lid,eye,[0,-.55,.27],[2.3,1.1,.16]); + const shadow=new T.Mesh(g.plane,this.handShadowMat);shadow.rotation.x=-PI/2;shadow.renderOrder=1;root.add(shadow); + hands.push({h,fist,palm,eye,pupil,upper,lower,shadow,side});} + return {root,hands};} + // Wiggler: a yellow caterpillar with a flower on his head; his eyes and mouth turn angry after the first stomp, as the walking speed rises (S40). + buildWiggler(){const M=this.mat,g=this.geo,root=new T.Group(),L=c=>this.keep(new T.MeshLambertMaterial({color:c})),body=L(0xf2c230),belly=L(0xf7dd7a),foot=L(0xe8872a),petal=L(0xf0568c),stem=L(0x3f9a3a),angry=L(0xe8562a); + const head=this.group(root),hb=this.group(head);this.mesh(g.sphere,body,hb,[0,1.0,0],[1.2,1.0,1.2]);this.mesh(g.sphere,belly,hb,[0,.78,.72],[.8,.55,.5]); + const eyes=[];for(const s of [-1,1]){const e=this.group(hb,[s*.45,1.3,.92]);this.mesh(g.sphere,M.eye,e,[0,0,0],[.28,.36,.16]);this.mesh(g.sphere,M.pupil,e,[-s*.04,-.03,.13],[.11,.15,.06]);eyes.push(this.mesh(g.box,M.pupil,e,[0,.33,.12],[.5,.1,.08],[0,0,s*.12]));} + this.mesh(g.box,M.pupil,hb,[0,.72,1.17],[.5,.07,.05]);this.mesh(g.cyl,stem,hb,[0,2.1,0],[.07,.3,.07]); + for(let i=0;i<5;i++){const a=i*PI*.4;this.mesh(g.sphere,petal,hb,[Math.sin(a)*.32,2.28,Math.cos(a)*.32],[.26,.11,.26]);}this.mesh(g.sphere,M.yellow,hb,[0,2.32,0],[.15,.1,.15]); + const parts=[];for(let i=0;i<3;i++){const p=this.group(root),q=this.group(p);this.mesh(g.sphere,body,q,[0,.8,0],[.8,.8,.8]);this.mesh(g.sphere,belly,q,[0,.62,.3],[.5,.42,.5]);const feet=[];for(const s of [-1,1])feet.push(this.mesh(g.sphere,foot,p,[s*.5,.2,.1],[.3,.2,.42]));parts.push({p,q,feet});} + const hf=[-1,1].map(s=>this.mesh(g.sphere,foot,head,[s*.7,.2,.2],[.36,.22,.5])); + return {root,head,hb,parts,hf,eyes,mats:[body,angry]};} + // Bowser: a green shell with spikes, a pale belly, horns, a red mane and a bright tail tip (where to grab him). Mines: black spheres with spikes on a post (the post is scenery). Original procedural art. + buildBowser(){const M=this.mat,g=this.geo,root=new T.Group(),L=c=>this.keep(new T.MeshLambertMaterial({color:c})),shell=L(0x2f8a3a),skin=L(0xe2a92c),belly=L(0xf2dc9a),rim=L(0xf4efe0),hair=L(0xd6402a),horn=L(0xf0ead8),dark=L(0x20242c),post=L(0x4a4458); + const body=this.group(root,[0,0,0]);this.mesh(g.sphere,skin,body,[0,1.5,0],[1.35,1.45,1.3]);this.mesh(g.sphere,belly,body,[0,1.4,.72],[1.0,1.15,.72]);this.mesh(g.sphere,shell,body,[0,1.65,-.55],[1.5,1.5,1.15]);this.mesh(g.torus,rim,body,[0,1.65,-.5],[1.42,1.42,1.1]); + for(let i=0;i<9;i++){const a=i*PI*2/9,r=.75;this.mesh(g.cone,horn,body,[Math.sin(a)*r,1.7+Math.cos(a)*r,-1.45],[.2,.55,.2],[-PI/2,0,0]);} + const head=this.group(body,[0,2.75,.65]);this.mesh(g.sphere,skin,head,[0,0,0],[.72,.68,.72]);this.mesh(g.sphere,belly,head,[0,-.18,.55],[.62,.34,.55]); + for(const s of [-1,1]){const e=this.group(head,[s*.3,.25,.56]);this.mesh(g.sphere,M.eye,e,[0,0,0],[.2,.25,.12]);this.mesh(g.sphere,M.pupil,e,[-s*.03,0,.1],[.09,.12,.05]);this.mesh(g.cone,horn,head,[s*.55,.72,-.05],[.16,.55,.16],[0,0,-s*.45]);} + for(let i=0;i<5;i++)this.mesh(g.sphere,hair,head,[(i-2)*.2,.62-Math.abs(i-2)*.08,-.28],[.2,.34,.26]); + const limbs=[[-.95,.42,.25],[.95,.42,.25],[-1.2,1.9,.45],[1.2,1.9,.45]].map(([x,y,z],i)=>{const p=this.group(body,[x,y,z]);this.mesh(g.sphere,skin,p,[0,i<2?-.15:-.25,i<2?.1:.1],i<2?[.48,.48,.68]:[.3,.55,.3]);return p;}); + const tail=this.group(body,[0,.62,-1.05]);this.mesh(g.cone,skin,tail,[0,0,-.65],[.42,1.5,.42],[-PI/2,0,0]);const tip=this.mesh(g.sphere,L(0xffc83a),tail,[0,0,-1.45],[.2,.2,.3]),tipOff=L(0x4a4458),tipOn=tip.material; + const mines=[0,1,2,3].map(()=>{const p=this.group(root.parent||this.world);const q=this.group(p,[0,0,0]);this.mesh(g.sphere,dark,q,[0,0,0],[.5,.5,.5]);for(let i=0;i<8;i++){const a=i*PI/4;this.mesh(g.cone,horn,q,[Math.sin(a)*.5,0,Math.cos(a)*.5],[.1,.3,.1],[PI/2,0,a]);}this.mesh(g.cone,horn,q,[0,.52,0],[.1,.3,.1]);this.mesh(g.cyl,post,p,[0,-1.4,0],[.12,2.8,.12]);p.visible=false;return {p,q};}); + return {root,body,head,limbs,tail,mines,tip,tipOn,tipOff};} + arena(kind,A){if(this.arenas[kind])return this.arenas[kind];const g=new T.Group(),G=this.geo,L=(c,map)=>this.keep(new T.MeshLambertMaterial({color:c,map:map||null})); + const clouds=[],cloudMat=this.keep(new T.SpriteMaterial({map:this.keep(TEX.cloud()),transparent:true,depthWrite:false,fog:false})); + const addClouds=(n,r,y)=>{for(let i=0;i{for(let i=0;i{for(let i=0;i{const p=this.keep(new T.BufferGeometry()),v=[...a,...b,...c,...a,...c,...d],uv=[];for(let i=0;i[hx+q[0]*r,y,hz+q[1]*r],m=quad(pt(a,R,y0),pt(b,R,y0),pt(b,O,H),pt(a,O,H));g.add(m);} + for(let i=0;i<4;i++){const a=i*PI/2;this.mesh(G.box,rock,g,[hx+Math.sin(a)*O,8,hz+Math.cos(a)*O],[Math.abs(Math.cos(a))*41+.3,16,Math.abs(Math.sin(a))*41+.3]);} + this.mesh(G.plane,dark,g,[hx,16,hz],[42,42,1],[PI/2,0,0]); + const px=-.17,pz=.62,tip=this.keep(new T.ConeGeometry(4.33,2.05,4));tip.rotateY(PI/4);tip.rotateX(PI);this.mesh(tip,rock,g,[px,5.125,pz]);this.mesh(G.box,rock,g,[px,6.66,pz],[6.13,1.02,6.13]); + this.mesh(G.cyl,dark,g,[px,12,pz],[.5,8,.5]);} + else{ // Lethal Lava Land: the Big Bully's 1535 x 1408 platform, 307 above the lava; the volcano at the level centre + g.add(this.prism(P,307,L(0xffffff,this.tex(TEX.grate,.3)),L(0x5d524d)));trim(this.mat.iron); + const lavaTex=this.keep(TEX.lava());this.lavaTex=lavaTex; + this.mesh(G.plane,this.keep(new T.MeshBasicMaterial({map:lavaTex,color:0xffffff,fog:true})),g,[0,-3.07,0],[700,700,1],[-PI/2,0,0]); + this.mesh(this.keep(new T.ConeGeometry(16,26,12,1,true)),L(0x3a2622),g,[0,9.9,43.85]);this.mesh(G.sphere,this.keep(new T.MeshBasicMaterial({color:0xffa040})),g,[0,22.5,43.85],[3.4,1.2,3.4]); + for(let i=0;i<8;i++){const a=i*.8+.3,d=40+hash(i,1,19)*60;this.mesh(G.ico,L(0x4a3a35),g,[Math.sin(a)*d,-3,Math.cos(a)*d],[4+hash(i,2,19)*4,2+hash(i,3,19)*3,4]);}} + g.visible=false;this.world.add(g);this.arenas[kind]={group:g,clouds};return this.arenas[kind];} + setKind(kind,A){if(this.kind===kind)return;this.kind=kind;for(const [k,a] of Object.entries(this.arenas))a.group.visible=k===kind;this.arena(kind,A).group.visible=true; + for(const [k,b] of Object.entries(this.bosses))b.root.visible=k===kind; + this.bosses.bowser.mines.forEach(q=>{q.p.visible=false;}); + const sky={whomp:['#3f8be0','#8fc4f2','#e6f3fb'],king:['#3a86e6','#91c9f5','#eaf6fb'],bully:['#2a0d0b','#7a2412','#d9682a'],eyerok:['#1b120a','#4f3518','#a97e42'],wiggler:['#141a10','#2a3320','#4c5a38'],bowser:['#07060f','#120d24','#2c1f47']}[kind]; + if(this.skyTex)this.skyTex.dispose();this.skyTex=TEX.sky(...sky);this.world.background=this.skyTex; + this.world.fog=kind==='bowser'?new T.Fog(0x1a1430,70,240):kind==='wiggler'?new T.Fog(0x2a3320,40,110):kind==='eyerok'?new T.Fog(0x4f3518,60,150):kind==='bully'?new T.Fog(0x8a3418,40,190):new T.Fog(kind==='king'?0xcfe6f6:0xd6eaf7,70,260); + this.hemi.color.set(kind==='eyerok'?0xffe2b0:kind==='bully'?0xffc49a:0xdcefff);this.hemi.groundColor.set(kind==='bully'?0x6a2412:0x6a6250);this.sun.color.set(kind==='bully'?0xffb27a:0xfff1d6);} + // ---------------- poses (pure functions of the game state) ---------------- + poseMario(g){const P=this.mario,m=g.mario,t=g.t,a=m.action; + P.root.position.set(m.x*U,m.y*U,m.z*U);P.root.rotation.set(0,m.yaw,0);P.root.scale.set(1,1,1);P.root.visible=!(m.invinc>0&&m.invinc%6<3&&a!=='dead'); + const B=P.body;B.position.set(0,.78,0);B.rotation.set(0,0,0);P.head.rotation.set(0,0,0); + const arm=(i,x,z=0,fx=0)=>{P.arms[i].sh.rotation.set(x,0,z);P.arms[i].fore.rotation.set(fx,0,0);},leg=(i,x,k=0)=>{P.legs[i].hip.rotation.set(x,0,0);P.legs[i].shin.rotation.set(k,0,0);}; + arm(0,0,.12);arm(1,0,-.12);leg(0,0);leg(1,0); + const run=f=>{const ph=t*(.11+Math.abs(m.fwd)*.009),s=Math.sin(ph),amp=Math.min(1.05,.2+Math.abs(m.fwd)/30);leg(0,s*amp,Math.max(0,-s)*.6);leg(1,-s*amp,Math.max(0,s)*.6);arm(0,-s*amp*.8,.15,-.4);arm(1,s*amp*.8,-.15,-.4); + B.position.y=.78+Math.abs(Math.cos(ph))*.05*amp;B.rotation.x=Math.min(.35,Math.abs(m.fwd)/90);}; + const air=m.y>0?Math.min(1,(m.timer||0)/16):0,tk=m.timer||0; + switch(a){ + case 'walking':run();break; + case 'holdwalk':run();arm(0,-3.0,.3);arm(1,-3.0,-.3);break; + case 'decel':case 'braking':B.rotation.x=-.25;leg(0,.5,.2);leg(1,-.2);arm(0,-.6,.3);arm(1,-.6,-.3);break; + case 'turnaround':B.rotation.x=-.35;B.rotation.z=.2;leg(0,.7,.3);leg(1,-.3);break; + case 'jump':case 'freefall':case 'rollout':leg(0,-.9,1.2);leg(1,.35,.3);arm(0,-2.6,.3);arm(1,.5,-.5);if(a==='rollout')B.rotation.x=tk*.25;break; + case 'double':leg(0,-1.1,1.4);leg(1,-.3,.9);arm(0,-2.8,.2);arm(1,-2.8,-.2);break; + case 'triple':B.rotation.x=Math.min(PI*2,tk*.24);leg(0,-1.3,1.8);leg(1,-1.3,1.8);arm(0,-.4,.9);arm(1,-.4,-.9);break; + case 'backflip':B.rotation.x=-Math.min(PI*2,tk*.2);leg(0,-1.2,1.6);leg(1,-1.2,1.6);arm(0,-2.6,.4);arm(1,-2.6,-.4);break; + case 'sideflip':B.rotation.z=Math.min(PI*2,tk*.22);leg(0,-.6,1);leg(1,.2,.4);arm(0,-.4,1.4);arm(1,-.4,-1.4);break; + case 'longjump':B.rotation.x=1.05;leg(0,.9,0);leg(1,1.1,0);arm(0,-2.9,.15);arm(1,-2.9,-.15);break; + case 'dive':case 'diveslide':case 'divestop':B.rotation.x=1.45;B.position.y=a==='dive'?.78:.32;leg(0,.25);leg(1,.25);arm(0,-3,.2);arm(1,-3,-.2);break; + case 'jumpkick':leg(0,-1.4,0);leg(1,.5,.8);arm(0,-.8,.9);arm(1,-.8,-.9);B.rotation.x=-.25;break; + case 'slidekick':case 'slidekickslide':B.rotation.x=-1.0;B.position.y=.45;leg(0,-1.5,0);leg(1,-1.2,.4);arm(0,-2.2,.6);arm(1,-2.2,-.6);break; + case 'gp':if(m.state===0){B.rotation.x=Math.min(PI*2,tk*.42);leg(0,-1.5,2);leg(1,-1.5,2);arm(0,-.3,.8);arm(1,-.3,-.8);}else{leg(0,-1.6,1.9);leg(1,-1.6,1.9);arm(0,-2.7,.5);arm(1,-2.7,-.5);B.position.y=.95;}break; + case 'gpLand':B.position.y=.55;leg(0,-1.4,1.8);leg(1,-1.4,1.8);arm(0,-.2,1.2);arm(1,-.2,-1.2);break; + case 'crouchIn':case 'crouch':case 'crouchOut':case 'crouchslide':B.position.y=.5;B.rotation.x=a==='crouchslide'?.35:.2;leg(0,-1.2,1.9);leg(1,-1.2,1.9);arm(0,-.4,.2);arm(1,-.4,-.2);break; + case 'punching':case 'movepunch':{const k=m.arg>=6&&m.arg<9,sec=m.arg>=3&&m.arg<6,e=Math.min(1,tk/4); + if(m.arg===9){B.position.y=.4;B.rotation.y=tk*.35;leg(0,-1.6,0);leg(1,.9,0);arm(0,-1.4,.6);arm(1,-1.4,-.6);break;} + if(k){leg(0,-1.5*e,0);arm(0,-.6,.6);arm(1,.4,-.6);B.rotation.x=-.2;}else if(sec){arm(0,-1.55*e,0,0);arm(1,.4,-.3);B.rotation.y=-.3*e;}else{arm(1,-1.55*e,0,0);arm(0,.4,.3);B.rotation.y=.3*e;}break;} + case 'pickup':B.rotation.x=tk<16?.6:.1;arm(0,-1.2-(tk>16?1.2:0),.2);arm(1,-1.2-(tk>16?1.2:0),-.2);break; + case 'hold':arm(0,-3.0,.3);arm(1,-3.0,-.3);break; + case 'heavythrow':{const e=Math.min(1,tk/26);arm(0,-3+e*1.6,.3);arm(1,-3+e*1.6,-.3);B.rotation.x=-.3+e*.6;break;} + case 'grabbowser':B.rotation.x=tk<20?.5:-.1;B.position.y=.6;arm(0,-1.5,.2);arm(1,-1.5,-.2);break; + case 'swing':B.rotation.x=-.35;B.position.y=.72;arm(0,-1.57,.1);arm(1,-1.57,-.1);leg(0,.5,.3);leg(1,-.5,.3);break; + case 'release':{const e=Math.min(1,tk/20);B.rotation.x=-.35+e*.6;arm(0,-1.57+e*.6,.4);arm(1,-1.57+e*.6,-.4);break;} + case 'shockwave':B.position.y=.78+Math.abs(Math.sin(tk*.2))*.25;arm(0,-.2,1.3);arm(1,-.2,-1.3);leg(0,.25);leg(1,-.25);break; + case 'burnjump':case 'burnfall':leg(0,-.9,1.2);leg(1,.35,.3);arm(0,-2.6,.6);arm(1,-2.6,-.6);B.rotation.x=-.2;break; + case 'burnground':run();arm(0,-2.6,.5);arm(1,-2.6,-.5);break; + case 'grabbed':arm(0,-1.5,1.2);arm(1,-1.5,-1.2);leg(0,.4);leg(1,-.4);B.rotation.z=Math.sin(t*.4)*.25;break; + case 'thrown':case 'airkb':B.rotation.x=a==='thrown'?-tk*.15:-.6;arm(0,-2.6,1.1);arm(1,-2.6,-1.1);leg(0,.6,.8);leg(1,-.4,.6);break; + case 'kb':B.rotation.x=(m.fwd<0?-1:1)*Math.min(1.3,tk*.08);B.position.y=.78-Math.min(.35,tk*.02);arm(0,-2,.9);arm(1,-2,-.9);break; + case 'squished':P.root.scale.set(1.8,.06,1.8);break; + case 'lava':B.rotation.x=-.4;leg(0,Math.sin(t*.9)*.9,.6);leg(1,-Math.sin(t*.9)*.9,.6);arm(0,-2.6,.6);arm(1,.6,-.4);break; + case 'dead':B.rotation.x=-1.5;B.position.y=.25;arm(0,-2.8,.6);arm(1,-2.8,-.6);break; + case 'land':B.position.y=.66;leg(0,-.6,1.0);leg(1,-.6,1.0);break; + default:{const br=Math.sin(t*.06)*.015;B.position.y=.78+br;} + } + if(m.squish>0&&a!=='squished'){const k=1-m.squish/120;P.root.scale.set(1+.5*(1-k),Math.max(.3,k),1+.5*(1-k));} + } + poseWhomp(g){const b=g.boss,P=this.bosses.whomp,t=g.t;P.root.position.set(b.x*U,(b.y+(b.shake||0))*U,b.z*U);P.root.rotation.set(0,b.yaw,0);P.tilt.rotation.set(b.pitch,0,0); + P.root.visible=b.act!=='dead';const walk=b.act==='chase'&&b.fwd>0,ph=t*(.04+b.fwd*.012),prep=b.act==='prepare'?Math.min(1,b.timer/26):b.act==='jump'||b.act==='land'?1:0; + P.feet.forEach((f,i)=>{f.position.y=walk?Math.max(0,Math.sin(ph+i*PI))*.5:0;f.rotation.x=0;}); + P.arms.forEach((s,i)=>s.rotation.set(prep*1.1+(walk?Math.sin(ph+i*PI)*.25:0),0,(i?1:-1)*prep*.9)); // arms swing back and out for the dive + if(b.act==='die'){const k=Math.min(1,b.timer/60);P.root.scale.set(1-k*.6,1-k*.9,1-k*.6);}else P.root.scale.set(1,1,1); + // The slab's vertical projection is its own shadow: as it tips forward this rectangle is exactly where it will land. + const p=b.pitch,fs=[100*Math.sin(p)-200*Math.cos(p),860*Math.sin(p)-200*Math.cos(p),100*Math.sin(p)-6*Math.cos(p),860*Math.sin(p)-6*Math.cos(p)]; + const f0=Math.min(...fs),f1=Math.max(...fs),fc=(f0+f1)/2,fx=Math.sin(b.yaw),fz=Math.cos(b.yaw),S=this.slabShadow; + S.visible=b.act!=='dead';S.position.set((b.x+fx*fc)*U,.02,(b.z+fz*fc)*U);S.rotation.set(-PI/2,0,b.yaw);S.scale.set(600*U,(f1-f0)*U,1); + this.slabShadowMat.opacity=b.act==='die'?0:.18+.32*clamp(p/(PI/2),0,1); + // Readability aid (not in the 1996 game): during the wind-up and fall, the exact squish footprint f 100..860, |u|<=300. + const warn=b.act==='prepare'?clamp(b.timer/28,0,1):b.act==='jump'||b.act==='land'?1:0,L=this.landZone;L.visible=warn>0; + if(warn>0){L.position.set((b.x+fx*480)*U,.035,(b.z+fz*480)*U);L.rotation.set(-PI/2,0,b.yaw);L.scale.set(600*U,760*U,1);this.landMat.opacity=.10+.22*warn;}} + poseKing(g){const k=g.boss,P=this.bosses.king,t=g.t;P.root.position.set(k.x*U,k.y*U,k.z*U);P.root.rotation.set(0,k.yaw,0);P.body.rotation.set(0,0,0);P.body.position.set(0,1.32,0); + const walk=k.act===2&&k.fwd>0||(k.act===3&&k.sub===1),ph=t*.12;P.feet.forEach((f,i)=>{f.position.set(f.position.x,walk?Math.max(0,Math.sin(ph+i*PI))*.25:0,walk?Math.sin(ph+i*PI)*.2+.1:.1);}); + P.arms.forEach((s,i)=>s.rotation.set(k.act===3?-1.1:walk?Math.sin(ph+i*PI)*.3:0,0,0)); + if(k.held){P.body.rotation.x=-.3;P.arms.forEach((s,i)=>s.rotation.set(-.8,0,(i?-1:1)*.6));} + if(k.act===4)P.body.rotation.x=-k.timer*.12; + const hurt=k.act===6&&k.sub===0;P.body.children[0].material=hurt&&(t>>2)%2?this.mat.red:this.mat.black; + if(k.act===7){const e=Math.min(1,k.timer/60);P.root.scale.setScalar(1-e*.7);}else P.root.scale.setScalar(1); + P.root.visible=!(k.act===7&&k.timer>55);} + poseBully(g){const b=g.boss,P=this.bosses.bully,t=g.t;P.root.position.set(b.x*U,b.y*U,b.z*U);P.root.rotation.set(0,b.faceYaw,0); + const charge=b.act==='chase'&&b.fwd>10,ph=t*(charge?.5:.15);P.body.rotation.set(charge?.35:b.act==='knockback'&&b.fwd>2?-.35:0,0,0); + P.feet.forEach((f,i)=>{f.position.y=(b.act==='chase'||b.act==='patrol'||b.act==='backup')?Math.max(0,Math.sin(ph+i*PI))*.22:0;}); + P.root.visible=b.act!=='dead'&&!(b.act==='sink'&&b.timer>58);P.body.children[0].material=b.act==='sink'?this.mat.red:this.mat.iron;} + poseEyerok(g){const b=g.boss,P=this.bosses.eyerok,m=g.mario,t=g.t,HB=root.Mario64Game.HAND; + b.hands.forEach((h,i)=>{const H=P.hands[i],dying=h.act==='die',shake=h.act==='attacked'||dying?Math.sin(t*1.7)*.05:0;H.h.visible=!h.gone&&(h.act!=='sleep'||b.act!=='sleep'); + H.h.position.set(h.x*U,h.y*U,h.z*U);H.h.rotation.set(dying?-Math.min(1,(h.af+1)/40)*.5:0,h.face,shake); + // Opening takes anim 4 (30 frames), closing anim 7 (28 frames up to its check), S37: the fist folds into the raised palm. + const p=h.act==='open'?clamp((h.af+1)/30,0,1):h.act==='close'?clamp(1-h.timer/28,0,1):h.open?1:0; + H.fist.visible=p<1;H.palm.visible=p>0;H.fist.scale.set(1,Math.max(.02,1-p),1);H.palm.scale.set(1,Math.max(.02,p),1); + const c=h.blink/3;H.upper.position.y=.55+(1-c)*.95;H.lower.position.y=-.55-(1-c)*.95;const l=Math.atan2(m.x-h.x,m.z-h.z)-h.face;H.pupil.position.set(clamp(Math.sin(l),-1,1)*.4,clamp((m.y-h.y-260)*.001,-.3,.3),0); + const B=h.open?HB.open:HB.fist,w=B.x1-B.x0,dp=B.z1-B.z0,cx=(B.x0+B.x1)/2,cz=(B.z0+B.z1)/2,s=Math.sin(h.face),co=Math.cos(h.face); + H.shadow.visible=H.h.visible;H.shadow.position.set((h.x+cx*co+cz*s)*U,.035,(h.z-cx*s+cz*co)*U);H.shadow.scale.set(w*U,dp*U,1);H.shadow.rotation.z=h.face;});} + poseWiggler(g){const b=g.boss,P=this.bosses.wiggler,t=g.t,run=b.act==='walk'?t*(.05+b.fwd*.012):0,angry=b.hp{e.visible=angry;});P.hb.children[0].material=P.mats[angry?1:0]; + P.hf.forEach((f,i)=>{f.position.y=.2+Math.max(0,Math.sin(run+i*PI))*.25;}); + P.parts.forEach((q,i)=>{const s=b.s[i+1];q.p.position.set((s.px??s.x)*U,s.y*U,(s.pz??s.z)*U);q.p.rotation.set(0,s.yaw,0);q.p.scale.set(sx,sx,sx);q.q.rotation.x=s.pitch;q.q.children[0].material=P.mats[angry?1:0]; + q.feet.forEach((f,j)=>{f.position.y=.2+Math.max(0,Math.sin(run+(i+1)*1.4+j*PI))*.22;});});} + poseBowser(g){const b=g.boss,P=this.bosses.bowser,t=g.t,B=P.body;P.tip.material=b.guard>0||b.tail===1?P.tipOff:P.tipOn;P.root.visible=b.op>=30;P.root.position.set(b.x*U,b.y*U,b.z*U);P.root.rotation.set(0,b.yaw,0);B.rotation.set(0,0,0);B.position.set(0,0,0);P.head.rotation.set(0,0,0);P.tail.rotation.set(0,0,0); + const f=Math.max(0,b.af),walk=(b.act==='walk'&&b.fwd>0)?Math.sin(t*.09):0;P.limbs[0].rotation.x=walk*.5;P.limbs[1].rotation.x=-walk*.5;P.limbs[2].rotation.x=-.6-walk*.3;P.limbs[3].rotation.x=-.6+walk*.3;P.tail.rotation.y=Math.sin(t*.05)*.2; + switch(b.act){ + case 'breath':{const e=f<46?-Math.min(1,f/30)*.5:Math.min(1,(f-46)/8)*.3;P.head.rotation.x=e;B.rotation.x=e*.3;break;} + case 'dance':B.rotation.z=Math.sin(f*.18)*.22;P.limbs[2].rotation.x=-2.5;P.limbs[3].rotation.x=-2.5;break; + case 'quickjump':P.limbs[0].rotation.x=.6;P.limbs[1].rotation.x=.6;break; + case 'held':B.rotation.x=-1.2;B.position.y=.9;B.rotation.z=Math.sin(t*.5)*.08;break; + case 'thrown':if(b.sub===0){B.rotation.x=-1.2+Math.sin(t*.6)*.25;B.position.y=.7;}else{const e=Math.min(1,f/30);B.rotation.x=-1.2*(1-e);B.position.y=.7*(1-e);}break; + case 'hitmine':case 'dead':B.rotation.x=b.sub<2?-(t*.25)%(PI*2):-Math.max(0,1-f/30)*1.5;B.position.y=.9;break; + case 'jumpstage':B.rotation.x=(b.spin&0xffff)/65536*PI*2;break; + } + P.mines.forEach((q,i)=>{const n=b.mines[i];q.p.visible=this.kind==='bowser'&&n.alive;q.p.position.set(n.x*U,n.y*U,n.z*U);q.q.rotation.y=t*.01;});} + // ---------------- effects ---------------- + effects(g){const pools=this.pools,o=this.o,n={dust:0,star:0,ring:0,fire:0,ember:0}; + const put=(pool,x,y,z,s,rx=0,ry=0)=>{const P=pools[pool];if(n[pool]>=P.instanceMatrix.count)return;o.position.set(x,y,z);o.rotation.set(rx,ry,0);o.scale.set(s,s,s);o.updateMatrix();P.setMatrixAt(n[pool]++,o.matrix);}; + const putRing=(x,y,z,r)=>{const P=pools.ring;if(n.ring>=P.instanceMatrix.count)return;o.position.set(x,y,z);o.rotation.set(-PI/2,0,0);o.scale.set(r,r,r);o.updateMatrix();P.setMatrixAt(n.ring++,o.matrix);}; + items(g.effects).forEach((e,idx)=>{const age=1-e.life/e.maxLife,x=e.x*U,y=(e.y||0)*U,z=e.z*U; + switch(e.type){ + case 'pound':case 'slam_dust':case 'bump':{const big=e.type==='slam_dust'?3.2:e.type==='pound'?1.4:.6;putRing(x,y+.05,z,.3+big*age*1.6); + for(let i=0;i<10;i++){const a=i*PI/5+idx,r=.2+big*age*1.4;put('dust',x+Math.sin(a)*r,y+.25+age*.6*big*.3,z+Math.cos(a)*r,(.28+.25*big*.3)*(1-age*.6));} + if(e.type==='pound')for(let i=0;i<6;i++){const a=i*PI/3,r=.4+age*1.5;put('star',x+Math.sin(a)*r,y+.5+Math.sin(age*PI)*.8,z+Math.cos(a)*r,.16,age*6,a);}break;} + case 'impact':case 'hit_star':for(let i=0;i<8;i++){const a=i*PI/4+idx*.3,r=.3+age*1.8;put('star',x+Math.sin(a)*r,y+1.2+Math.cos(a*2)*.4+age*.6,z+Math.cos(a)*r,.2*(1-age*.5),age*8,a);}break; + case 'lava_burst':for(let i=0;i<12;i++){const a=i*PI/6+idx,r=.2+age*1.2;put('fire',x+Math.sin(a)*r,y+.3+age*2.2*(.5+hash(i,idx,3)),z+Math.cos(a)*r,.35*(1-age));}break; + case 'mist':for(let i=0;i<18;i++){const a=i*.7+idx,r=.8+age*3;put('dust',x+Math.sin(a)*r,y+1+age*2+(i%4)*.5,z+Math.cos(a)*r,.9*(1-age*.7));}break; + }}); + if(this.kind==='bowser'){const b=g.boss; + b.flames.forEach((f,i)=>{const r=f.s*.1;put('fire',f.x*U,f.y*U,f.z*U,r,g.t*.1,i);}); + b.fires.forEach((f,i)=>{const r=f.s*.1,k=1+Math.sin(g.t*.3+i)*.15;put('fire',f.x*U,(f.y+f.s*14)*U,f.z*U,r*k,g.t*.08,i);put('fire',f.x*U,(f.y+f.s*30)*U,f.z*U,r*.6/k,g.t*.1,i+1);}); + if(['burnjump','burnfall','burnground'].includes(g.mario.action))for(let i=0;i<7;i++){const a=i*.9+g.t*.25,m=g.mario;put('fire',m.x*U+Math.sin(a)*.3,m.y*U+.5+(i%4)*.35,m.z*U+Math.cos(a)*.3,.2,g.t*.2,i);}} + if(this.kind==='bully')for(let i=0;i<24;i++){const ph=((g.t*.004+hash(i,1,91))%1),a=hash(i,2,91)*PI*2,d=10+hash(i,3,91)*40;put('ember',Math.sin(a)*d,-3+ph*14,Math.cos(a)*d,.12*(1-ph),ph*9,a);} + for(const k of Object.keys(pools)){pools[k].count=n[k];pools[k].instanceMatrix.needsUpdate=true;}} + shadows(g){const m=g.mario,b=g.boss,fl=typeof g.floor==='function'?g.floor(m.x,m.z,m.y+1):{y:0};const my=fl?fl.y:-1e4; + this.marioBlob.visible=!!fl&&m.action!=='squished'&&m.y-my<2500;this.marioBlob.position.set(m.x*U,my*U+.04,m.z*U);const k=clamp(1-(m.y-my)/1600,.35,1);this.marioBlob.scale.set(.45*k,.45*k,1); + const r=b.kind==='whomp'||b.kind==='eyerok'?0:b.kind==='bowser'?(b.op<100||b.held?0:1.9):b.kind==='wiggler'?1.3:b.kind==='king'?1.25:1.2;this.bossBlob.visible=r>0&&b.y>-50&&!(b.kind==='king'&&b.held)&&b.act!=='dead';this.bossBlob.position.set(b.x*U,(b.kind==='wiggler'?g.floor(b.x,b.z,b.y).y*U:0)+.03,b.z*U);this.bossBlob.scale.set(r,r,1);} + render(g,ctx){ + if(this.closed||this.renderer.getContext().isContextLost()){this.ready=false;this.error=this.closed?'3D renderer is closed':'WebGL context lost';throw Error(this.error);}const start=performance.now(); + try{const kind=g.boss.kind;this.setKind(kind,g.arena);this.poseMario(g); + if(kind==='whomp')this.poseWhomp(g);else if(kind==='king')this.poseKing(g);else if(kind==='eyerok')this.poseEyerok(g);else if(kind==='wiggler')this.poseWiggler(g);else if(kind==='bowser')this.poseBowser(g);else this.poseBully(g); + this.slabShadow.visible=kind==='whomp'&&this.slabShadow.visible;this.landZone.visible=kind==='whomp'&&this.landZone.visible;this.shadows(g);this.effects(g); + if(this.lavaTex)this.lavaTex.offset.set((g.t*.0006)%1,(g.t*.0004)%1); + const c=g.cam,m=g.mario,d=c.dist*U,p=c.pitch,tx=m.x*U,ty=Math.max(m.y*U,-2.5)+.95,tz=m.z*U; + this.camera.position.set(tx-Math.sin(c.yaw)*d*Math.cos(p),ty+d*Math.sin(p),tz-Math.cos(c.yaw)*d*Math.cos(p)); + if(kind==='wiggler'){const P=this.camera.position,cl=(v,a,b)=>clamp(v,a+.4,b-.4);P.x=cl(P.x,-20.64,20.31);P.z=cl(P.z,-19.85,21.1);P.y=clamp(P.y,g.floor(P.x/U,P.z/U,1e4).y*U+.6,15.6);} // closed room (S41): the view stays inside its walls + this.camera.lookAt(tx+Math.sin(c.yaw)*1.4,ty+.15,tz+Math.cos(c.yaw)*1.4); + this.renderer.info.reset();this.renderer.render(this.world,this.camera);ctx.drawImage(this.view,0,0,854,480); + this.times.push(performance.now()-start);if(this.times.length>120)this.times.shift();this.ready=true;this.error=null; + }catch(e){this.ready=false;this.error=String(e);throw e;} + } + metrics(){const info=this.renderer.info,sorted=[...this.times].sort((a,b)=>a-b);let geometryBytes=0,textureBytes=0; + for(const r of this.resources){if(r.isBufferGeometry){for(const a of Object.values(r.attributes))geometryBytes+=a.array.byteLength;if(r.index)geometryBytes+=r.index.array.byteLength;} + if(r.isTexture&&r.image)textureBytes+=(r.image.width||0)*(r.image.height||0)*4;if(r.isInstancedMesh)geometryBytes+=r.instanceMatrix.array.byteLength;} + return {renderer:'webgl-mario64',webglVersion:this.renderer.capabilities.isWebGL2?2:1,drawCalls:info.render.calls,triangles:info.render.triangles,geometries:info.memory.geometries, + textures:info.memory.textures,geometryBytes,textureBytes,canvasBytes:854*480*4,resourceBytesEstimate:geometryBytes+textureBytes+854*480*8,staticAssetBytes:669884, + renderSamples:sorted.length,cpuRenderMsP50:sorted.length?sorted[Math.floor((sorted.length-1)*.5)]:null,cpuRenderMsP95:sorted.length?sorted[Math.floor((sorted.length-1)*.95)]:null, + shadows:'blob shadows (N64 style) + projected slab footprint; no shadow maps',postprocess:false};} + close(){if(this.closed)return;this.closed=true;this.ready=false;if(this.skyTex)this.skyTex.dispose();this.resources.forEach(r=>r.dispose?.());this.renderer.dispose();this.renderer.forceContextLoss();this.resources.clear();} + } + R.render=function(g,ctx){let s=byCanvas.get(ctx.canvas);if(!s||s.closed){s=new Scene(ctx.canvas);byCanvas.set(ctx.canvas,s);}s.render(g,ctx);return s;}; + R.status=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);if(s&&!s.closed&&s.renderer.getContext().isContextLost()){s.ready=false;s.error='WebGL context lost';} + return {renderer:'webgl-mario64',kind:'perspective',ready:!!s?.ready&&!s.closed,error:s?.error||null};}; + R.metrics=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);return s?s.metrics():null;}; + R.scene=function(ctx){return ctx&&byCanvas.get(ctx.canvas)||null;}; + R.close=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);if(s){s.close();byCanvas.delete(ctx.canvas);}}; +})(window); diff --git a/environments/games/web/games/mario64_remake/style3d.css b/environments/games/web/games/mario64_remake/style3d.css new file mode 100644 index 0000000000000000000000000000000000000000..ec39215c7a394dd8d0d0758490acf67ca7ec50f9 --- /dev/null +++ b/environments/games/web/games/mario64_remake/style3d.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#14191a;--panel:#1d2425;--edge:#354141;--text:#ebe7dc;--muted:#a5b2ad;--accent:#dfb676}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top,#29312b,transparent 60%),var(--bg);color:var(--text);font:14px/1.7 'Segoe UI','Microsoft YaHei',sans-serif}body[data-game=genshin_remake]{--bg:#101822;--panel:#1b2530;--edge:#374754;--accent:#baacff;background:radial-gradient(ellipse at top,#2b2942,transparent 60%),var(--bg)}body[data-game=mario64_remake]{--bg:#0f1530;--panel:#18214a;--edge:#34407a;--text:#f3f1ea;--muted:#aeb7dd;--accent:#ffd23a;background:radial-gradient(ellipse at top,#2b3a8a,transparent 62%),radial-gradient(ellipse at bottom right,#5a1616,transparent 55%),var(--bg)}body[data-game=mario64_remake] h1{font-family:"Segoe UI","Microsoft YaHei",sans-serif;font-weight:800;letter-spacing:.5px;text-shadow:0 3px 0 #b81d22,0 6px 14px #0008}body[data-game=mario64_remake] button.primary{background:#e52521;color:#fff}body[data-game=mario64_remake] .stage{border-color:#ffd23a55}main{max-width:1220px;margin:auto;padding:28px 24px 40px}header{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:20px}.eyebrow{color:var(--accent);font-size:11px;letter-spacing:2.5px;text-transform:uppercase}h1{font:500 32px/1.35 Georgia,'Microsoft YaHei',serif;letter-spacing:1px;margin:6px 0}header p{color:var(--muted);margin:0;font-size:13px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.layout{display:grid;grid-template-columns:minmax(0,854px) 245px;gap:24px;align-items:start}.stage{position:relative;border:1px solid var(--edge);box-shadow:0 22px 55px #0005;background:#111b1c}canvas{display:block;width:100%;aspect-ratio:854/480;touch-action:none;outline:none}canvas:focus-visible{outline:2px solid var(--accent);outline-offset:3px}#overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#10171b30;pointer-events:none}#overlay[hidden]{display:none}#overlay div{background:#111b23de;padding:19px 32px;border:1px solid #9ba6a655;max-width:80%;text-align:center}#overlay strong{font:500 24px Georgia,'Microsoft YaHei',serif;display:block}#overlay span{display:block;color:var(--muted);font-size:12px;margin-top:7px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;padding:12px;background:var(--panel);border-top:1px solid var(--edge)}button,select,input{font:inherit;background:var(--panel);color:var(--text);border:1px solid var(--edge);border-radius:4px;padding:7px 11px}button{cursor:pointer}button:hover{border-color:var(--accent);background:#ffffff09}button.primary{background:var(--accent);color:var(--bg);font-weight:600}button:focus-visible,select:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}aside{padding:19px;border:1px solid var(--edge);background:var(--panel)}h2{font-size:16px;margin:0 0 8px}label{display:block;font-size:12px;color:var(--muted);margin:12px 0 5px}select,input{width:100%}dl{border-top:1px solid var(--edge);padding-top:16px;margin:18px 0 0}dt{color:var(--accent);font:12px/1.8 Consolas,monospace}dd{color:var(--muted);font-size:12px;margin:0 0 10px}.note{color:var(--muted);font-size:12px}#status{min-height:25px;margin:10px 0;color:var(--accent);overflow-wrap:anywhere}.record-toolbar{border:1px solid var(--edge);padding:10px;background:transparent}.record-toolbar button{font-size:12px}#file{display:none}.mobile{display:none}footer{display:flex;flex-wrap:wrap;gap:22px;border-top:1px solid var(--edge);margin-top:28px;padding-top:15px;font-size:12px}@media(max-width:950px){main{padding:14px}.layout{grid-template-columns:1fr}aside{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}aside dl,aside .note{grid-column:1/-1}dl{columns:2}.mobile{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.mobile button{min-width:45px;touch-action:none}header{align-items:start}h1{font-size:26px}}@media(max-width:500px){header{display:block}header a{font-size:12px}aside{padding:14px}#overlay div{padding:14px 20px}#overlay strong{font-size:19px}.toolbar{gap:6px;padding:8px}button{font-size:12px}h1{font-size:25px}} diff --git a/environments/games/web/games/megaman_remake/arena.js b/environments/games/web/games/megaman_remake/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..24f4628b6fa2272c5f8c23ba8bd9746feeb97e56 --- /dev/null +++ b/environments/games/web/games/megaman_remake/arena.js @@ -0,0 +1,118 @@ +// Mega Man (NES, 1987) on the BB.Case engine: shared rules for the Robot Master rooms. +// World units are NES pixels. A room is 256 x 240 with the origin at the top-left and y growing downward, as the +// original stores positions; one 60 Hz tick is one NES frame. Speeds are px/frame written as the original 8.8 +// fixed-point values (MM.fx(0x4DF) = 4.87109375), so every constant can be checked against the disassembly cited +// in the reference game. Energy and damage are NES units (one bar = 28 units); hit points are reported as points = +// units x 18, so one full NES bar is 504 points at the easy tier. +// Update order of one tick follows the original main loop (bank 5 $915E): player update -> weapon flight +// services -> boss AI -> player i-frame countdown -> player contact -> shot collision -> entity motion -> +// render-time counters (boss i-frames, animation timers). body_megaman.js resolveInteractions() runs the part +// after the boss AI. +(function (g) { + var B = g.BB; + B.ARENA = { W: 256, H: 240 }; + var MM = B.MM = {}; + + MM.fx = function (hex) { return hex / 256; }; // 8.8 fixed point -> px/frame + MM.FLOOR = 192; // floor top of every boss room; a standing 24 px body has its centre at y = 180 + MM.WALL_L = 16; MM.WALL_R = 240; // inner faces of the side walls + MM.UNIT = 18; MM.BAR = 28; + MM.GRAVITY = MM.fx(0x40); // -0.25 px/frame^2 for the player and every entity with gravity + MM.FALL_MAX = 12; // terminal velocity -0C.00 + MM.TOP_EXIT = 4; MM.BOTTOM_EXIT = 0xE8; // entity y outside [4, $E8) has left the screen + + MM.box = function (x, y, hw, hh) { return { x: x, y: y, hw: hw, hh: hh }; }; + // hitbox_overlap_test ($C9BE) on integer pixel positions: e = the tested entity (boss, boss shot), b = the + // probing box (a player shot or the player's touch box). Top/bottom compare strict/inclusive, sides inclusive. + MM.overlap = function (e, b) { + var ex = Math.floor(e.x), ey = Math.floor(e.y), bx = Math.floor(b.x), by = Math.floor(b.y); + return ey - e.hh < by + b.hh && ey + e.hh >= by - b.hh && ex - e.hw <= bx + b.hw && ex + e.hw >= bx - b.hw; + }; + MM.offscreen = function (o) { return o.x < 0 || o.x >= 256 || o.y < MM.TOP_EXIT || o.y >= MM.BOTTOM_EXIT; }; + MM.r = function (v) { return B.r4(v); }; + MM.snapshot = function (v) { + if (typeof v === 'number') return B.r4(v); + if (Array.isArray(v)) return v.map(MM.snapshot); + if (v && typeof v === 'object') { var o = {}; Object.keys(v).forEach(function (k) { o[k] = MM.snapshot(v[k]); }); return o; } + return v; + }; + // tier knobs: spec rows are [easy, normal, hard] at d = 0 / 0.5 / 1, the values BB.GAME.tiers declares, + // so the public tiers read the spec rows exactly and any d in between interpolates (BB.knobs). + MM.knobs = function (spec, d) { return B.knobs(spec.difficulty, d); }; + + // Shared entity physics (boss_walk_tick $EDF8 + vertical_collision $9BC4): x moves by |vx| along dir with a + // wall clamp (o.blocked = the $2A wall probe); y -= vy (up = positive); a falling body that reaches the floor + // snaps onto it with the grounded hold velocity $FF.40 (o.landed = the $2B probe, set again every frame it + // stands); otherwise gravity applies if o.grav. Ice Man's descent relies on the hold value being negative. + MM.GROUND_VY = -(1 - MM.fx(0x40)); + MM.step = function (o) { + o.blocked = false; o.landed = false; + if (o.vx) { + var nx = o.x + o.vx * o.dir, lo = MM.WALL_L + o.hw, hi = MM.WALL_R - o.hw; + if (nx < lo) { nx = lo; o.blocked = true; } else if (nx > hi) { nx = hi; o.blocked = true; } + if (o.room && o.room.length) { var cx = MM.clampX(o.room, o.x, nx, o.hw, o.y, o.hh); if (cx !== nx) { nx = cx; o.blocked = true; } } + o.x = nx; + } + var ny = o.y - o.vy, floor = o.room && o.room.length ? MM.floorUnder(o.room, o.x - o.hw + 1, o.x + o.hw - 1, o.y + o.hh) : MM.FLOOR; + if (o.vy < 0 && ny + o.hh >= floor) { o.y = floor - o.hh; o.vy = MM.GROUND_VY; o.landed = true; o.grounded = true; return; } + o.y = ny; o.grounded = false; + if (o.grav) o.vy = Math.max(-MM.FALL_MAX, o.vy - MM.GRAVITY); + }; + + // Room solids beyond the side walls and the floor: the scene's collision override records and solid step tiles, + // as rectangles {x0, x1, y0, y1} (x1/y1 exclusive). The flat rooms have none (MM.ROOMS has no entry), and every + // caller skips these helpers for an empty list, so their arithmetic is exactly the flat-room one. + MM.ROOMS = {}; + MM.roomOf = function (caseId) { return MM.ROOMS[caseId] || []; }; + // Cut Man's and Guts Man's rooms have the same step: solid tiles x 16-32 and two liftable blocks x 32-64, 64-96 (override + // type 2), top y 160. A lifted block leaves the body's and the boss's own copy of the list, never this table. + MM.blockRoom = function (caseId) { + MM.ROOMS[caseId] = [{ x0: 16, x1: 32, y0: 160, y1: 192 }, { x0: 32, x1: 64, y0: 160, y1: 192, block: true }, { x0: 64, x1: 96, y0: 160, y1: 192, block: true }]; + }; + // override_search on the record bounds: x0 <= x < x1, y0 <= y < y1; returns the liftable block there or null + MM.blockAt = function (room, x, y) { + for (var i = 0; i < room.length; i++) { + var r = room[i]; + if (r.block && r.x0 <= x && x < r.x1 && r.y0 <= y && y < r.y1) return r; + } + return null; + }; + // top of the highest surface under the span [x0, x1] at or below a body whose bottom is at `bottom` + // (vertical_collision probes the two side edges of the body: x +- (half-width - 1) for entities, x +- 7 for Mega Man) + MM.floorUnder = function (room, x0, x1, bottom) { + var f = MM.FLOOR; + for (var i = 0; i < room.length; i++) { + var r = room[i]; + if (x1 >= r.x0 && x0 < r.x1 && r.y0 >= bottom - 1e-9 && r.y0 < f) f = r.y0; + } + return f; + }; + // wall probe against the room solids (move_right/move_left): a body whose bottom is below a solid's top is pushed + // back out to the side it came from + MM.clampX = function (room, x, nx, hw, y, hh) { + for (var i = 0; i < room.length; i++) { + var r = room[i]; + if (y + hh > r.y0 + 1e-9 && y - hh < r.y1 && nx - hw < r.x1 && nx + hw > r.x0) nx = x >= (r.x0 + r.x1) / 2 ? r.x1 + hw : r.x0 - hw; + } + return nx; + }; + + // proportional_velocity ($F8C6) with fraction_divide / divide_24_16: the major axis gets the full speed, the minor one + // speed x minor / major through two 8.8 divisions (truncating like the 16-step long division). dy = source - target + // y; a target below takes |dy| with EOR #$FF (one less, as the original) and a downward Y speed. speedRaw is 8.8 raw. + MM.propVel = function (speedRaw, adx, dy) { + var up = dy >= 0, ady = up ? dy & 0xFF : (~dy) & 0xFF; + function frac(a, divRaw) { return divRaw ? Math.floor(a * 65536 / divRaw) & 0xFFFF : 0xFFFF; } + var major = speedRaw, minor; + if (adx >= ady) minor = frac(ady, frac(adx, major)); else minor = frac(adx, frac(ady, major)); + var vx = (adx >= ady ? major : minor) / 256, vy = (adx >= ady ? minor : major) / 256; + return { vx: vx, vy: up ? vy : -vy, ady: ady }; + }; + + // Boss projectiles live in enemy slots $10-$1F (find_free_slot from $10); the player's contact check tests + // only the slots whose parity matches the frame counter (player_contact_service $A18B). + MM.freeSlot = function (list) { + for (var s = 16; s < 32; s++) if (!list.some(function (p) { return p.slot === s; })) return s; + return -1; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/art/scenes.js b/environments/games/web/games/megaman_remake/art/scenes.js new file mode 100644 index 0000000000000000000000000000000000000000..96032b48b718d00961cf4113d1c61a9650351164 --- /dev/null +++ b/environments/games/web/games/megaman_remake/art/scenes.js @@ -0,0 +1,15 @@ +// Scene hooks the shared renderer expects (ART.scene / ART.ambient). Mega Man draws its whole picture in +// draw/hud.js (BODY_DRAW.megaman.fullHud), so the background and foreground here are empty 1x1 layers. +(function (g) { + var B = g.BB, A = B.ART; + var blank = {}; + A.scene = function (doc, id) { + if (!blank[id]) { + var bg = doc.createElement('canvas'), fg = doc.createElement('canvas'); + bg.width = bg.height = fg.width = fg.height = 1; + blank[id] = { bg: bg, fg: fg }; + } + return blank[id]; + }; + A.ambient = function () {}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/body_megaman.js b/environments/games/web/games/megaman_remake/body_megaman.js new file mode 100644 index 0000000000000000000000000000000000000000..b1e590450c91e78817c917d1a1ad1521787a8470 --- /dev/null +++ b/environments/games/web/games/megaman_remake/body_megaman.js @@ -0,0 +1,471 @@ +// Mega Man, the player body (NES 1987 rules; no slide and no charge shot - those arrived in Mega Man 3 and 4). +// Constants are the ROM's 8.8 values (bank 5 player_update $94A8, TASVideos Rockman data for RM1): +// walk 01.60 after a start-up of 9 frames at 00.20; releasing the d-pad at top speed slides 13 frames at 00.80; +// air X 01.50 (00.20 on the first frame of a fresh press); jump 04.DF up, gravity 00.40, fall cap 12; +// releasing jump while still rising at 02.00 or more sets the rise to 01.00 (player_fall_cap). +// Touch box 14 x 22 (x +-7, y +-11); the wall/floor body is 16 x 24. +// A hit costs the damage, starts 29 frames of knockback (a 01.40 hop, drifting 00.90 along the attacker's facing, +// no control) and 111 ($6F) frames of blinking invulnerability. Weapons: Buster (3 shots, 4 px/frame), Thunder +// Beam (three-way crawling bolt), Ice Slasher (piercing), Fire Storm (wave + 32-frame orbit shield), Hyper Bomb +// (three bounces, 146-frame fuse, 12-way flames), Rolling Cutter (piercing, flies out 42 frames and homes back), Super Arm +// (lifts a block of the room, throws it, it shatters into 4 chunks); 28 units each. +(function (g) { + var B = g.BB, MM = B.MM, fx = MM.fx; + var WALK = fx(0x160), START = fx(0x20), SLIDE = fx(0x80), AIR = fx(0x150); + // knockback (special state 3, $9742): anim $12 runs 30 frames; entering it sets Y velocity 01.40 (a small hop) + // and the speed row for anim $12 ($9DDD list index 5 -> $9DE6 row 9 -> $8643 = 00.90) drifts him along the + // attacker's facing + var JUMP = fx(0x4DF), KNOCK = fx(0x90), KNOCK_VY = fx(0x140); + // anim $12 (30-frame cycle) starts at frame 1 on the frame after the hit, so it wraps after 29 frames and control + // returns on the 30th (player_state_exit). knockT is set on the hit frame and counted down at its end too. + var START_T = 9, SLIDE_T = 13, KNOCK_T = 30, IFRAMES = 0x6F, HW = 7, HH = 11, BODY_HW = 8, BODY_HH = 12; + // Thunder Beam crawl chain (thunder_flight, tables $A5A9 x / $A5B1 y / $A5B9 next anim): when a forward piece's + // 10-frame animation wraps it jumps ahead and changes shape; row = animation - $62. Half sizes from $FAB5/$FB83. + MM.PLAYER_BOLT = { jx: [28, 32, 32, 28, 24, 28, 28, 28], jy: [-4, -24, 0, 28, 16, -12, -4, -4], + next: [5, 6, 7, 1, 2, 3, 4, 5], hw: [4, 8, 4, 4, 4, 8, 8, 4], hh: [8, 4, 8, 8, 8, 4, 4, 8] }; + // records 6-$0A (dx, dy) and the frames until the first wrap: start frames $40,$30,$20,$10,$01 stagger it + var THUNDER = [[16, -4, 2], [20, 8, 4], [24, -4, 6], [32, -20, 8], [40, -20, 9]]; + // Fire Storm shield orbit ($A4FA y / $A502 x): offset index = frames since the shot & 7, gone at 32 + var ORBIT_Y = [20, 14, 0, -14, -20, -14, 0, 14], ORBIT_X = [0, -14, -20, -14, 0, 14, 20, 14]; + // spread_shot_spawn rows 0..11 ($F88A-$F8BA), shared by the boss bomb's shrapnel and the Hyper Bomb's flames: + // [X speed, Y speed (+ = up), facing right ($40 in $F8BA)] + var D = fx(0x160); + MM.SPREAD = [[0, 2, 0], [2, 0, 1], [0, -2, 0], [2, 0, 0], [D, D, 1], [D, -D, 1], [D, -D, 0], [D, D, 0], + [0, fx(0xC0), 0], [fx(0xC0), 0, 1], [0, -fx(0xC0), 0], [fx(0xE0), 0, 0]]; + // Hyper Bomb: record $0D (anim $5D, Y 03.00, X 01.80, dy -4, dx +12); bomb_flight bursts at $61 = $92, cleans up at $A0 + var BOMB_FUSE = 0x92, BOMB_END = 0xA0; + // the quake's stun is special state 2 (anim $13, rate $57 = 48 frames from frame byte 1): 47 frames without control, moving + // backwards at 00.20 (row 1 of $9DE6), with Y velocity 00.E0 re-applied at frame bytes $01, $21, $41 (stunT 47, 31, 15) + var STUN_T = 47, STUN_VY = fx(0xE0); + // Super Arm: block half size by stage ($A888: anim $6C 16 x 16 for Cut Man, $32 14 x 14 for Guts Man); thrown block + // (record 3) Y 03.00, X 03.A0, dy -16, dx +16; chunks ($F826-$F832: x, y, X speed, Y speed), half size 4 x 4 + var BLOCK_HALF = { 'megaman/cut_man': 16, 'megaman/guts_man': 14 }, THROW_VX = fx(0x3A0), THROW_VY = 3, ARM_LIFT = 26; + var CHUNKS = [[8, 8, 4, 2], [24, 8, 4, 0], [8, 24, 3, 2], [24, 24, 3, 0]]; + + function MegaMan() {} + var P = MegaMan.prototype; + P.id = 'megaman'; + P.keys = { left: 'A', right: 'D', up: 'W', down: 'S', jump: 'Space', fire: 'J|LMB', prev: 'Q', next: 'E' }; + P.NAIL = 0; P.HITSTOP = 0; P.slashFacing = 1; + P.manual = [ + 'A/D move left and right (9 slow startup frames and 13 frames of sliding after release, as in the NES original). Space jumps; hold it to jump higher. Releasing while rising immediately slows the ascent', + 'J or left mouse button fires one shot per press; at most three Arm Gun shots can be on screen. The first game has neither sliding nor charged shots', + 'Q/E cycles acquired special weapons (Returning Blade / Pierce Dart / Fuse Lob / Orbit Guard / Tri Arc / Rock Throw). Each shot costs one energy unit, except Fuse Lob and Rock Throw, which cost two; each weapon has 28 units. You cannot switch while a timed bomb or rock remains active', + 'Rock Throw: face a nearby rock and press fire to lift it, then press again to throw it (only the Blade Tosser and Quake Hurler rooms contain rocks). When Quake Hurler lands, grounded players are stunned for about 0.8 seconds; jump to avoid it', + 'Health: 28 units (504 points). Taking damage causes 0.5 seconds of knockback and 1.85 seconds of flashing invulnerability. Defeat a boss to acquire its weapon; bosses have weapon weaknesses' + ]; + P.reset = function (c) { + var o = c.options || {}, self = this; + // entry position: in the original it depends on how the player walked through the boss door; here the seed + // picks it (28..68 px), which also makes the RNG-free Ice Man and Fire Man fights differ between seeds + this.room = MM.roomOf(c.id); + this.x = 28 + c.rng.int(41); this.y = MM.FLOOR - BODY_HH; this.vy = 0; this.facing = 1; this.grounded = true; + if (this.room.length) this.y = MM.floorUnder(this.room, this.x - 7, this.x + 7, 0) - BODY_HH; // walked in onto the step + this.speed = 0; this.walkT = 0; this.slideT = 0; this.airHeld = false; + this.max_hp = this.hp = MM.BAR * MM.UNIT; + this.iframes = 0; this.knockT = 0; this.knockDir = 0; this.shootT = 0; this.stunT = 0; this.airHit = false; this.blockTarget = null; this.blocksGone = []; + this.weapons = MM.loadout(o); this.weapon = 'P'; this.energy = {}; + this.weapons.forEach(function (w) { if (w !== 'P') self.energy[w] = MM.BAR; }); + this.shots = []; this.nextShot = 1; this.shieldN = 0; + this.prev = {}; this.fired = false; this.anyInput = false; this.hits = 0; this.slashHits = {}; + }; + P.hurtBox = function () { return MM.box(this.x, this.y, HW, HH); }; + P.box = P.hurtBox; + P.centre = function () { return { x: this.x, y: this.y }; }; + P.slashBox = function () { return null; }; + P.onSlashContact = function () {}; + + // weapon menu (bank 6 weapon_menu_main): MM1 switches in the SELECT menu, which freezes the world and hides + // entity slot 5 (STA $0605 = F8: the special-weapon slot); Buster shots in slots 2-4 and the other pieces keep + // flying. Here Q/E switch instantly with the same effect on the shots. + P.cycle = function (step) { + var i = this.weapons.indexOf(this.weapon), n = this.weapons.length; + if (n < 2) return; + if (this.count('hyper_bomb') || this.count('hyper_flame') || this.blockOut()) return; // main_select: no menu while $60 is set + this.weapon = this.weapons[(i + step + n) % n]; + // slot 5 is hidden by the menu; the Fire Storm shield (slot 6) loses its orbit service and would hang in + // place forever in the original (an orphan that also blocks the Thunder Beam) - it is dropped here instead + this.shots = this.shots.filter(function (s) { return s.slot !== 5 && s.kind !== 'fire_shield'; }); + }; + // shot_collision_service ($A261) tests the slot range of the CURRENT weapon, whatever occupies it: Buster 2-4, + // Ice 5, Fire 5-6, Thunder 5-11; damage is looked up for the current weapon. A shot left over from another + // weapon outside that range flies on harmlessly. + var HIT_SLOTS = { P: [2, 4], C: [5, 5], I: [5, 5], F: [5, 6], E: [5, 11], G: [5, 7] }; + P.collides = function (s) { + if (this.weapon === 'B') return s.kind === 'hyper_flame'; // shotcoll_bomb: only the explosion window + if (s.kind === 'held_block') return false; // flags $24: bit 5 keeps it out of the collision + if (s.kind === 'block_chunk') return s.slot <= 7; // shotcoll_guts, and thunder_spent after a beam broke a block + var r = HIT_SLOTS[this.weapon]; return s.slot >= r[0] && s.slot <= r[1]; }; + P.spendable = function (w) { return w === 'P' || (this.energy[w] || 0) >= MM.WEAPONS[w].cost; }; + P.spend = function (w) { if (w !== 'P') this.energy[w] = Math.max(0, this.energy[w] - MM.WEAPONS[w].cost); }; + P.count = function (kind) { var n = 0; this.shots.forEach(function (s) { if (s.kind === kind) n++; }); return n; }; + P.slotUsed = function (slot) { return this.shots.some(function (s) { return s.slot === slot; }); }; + P.addShot = function (s) { s.id = this.nextShot++; s.dir = this.facing; s.vy = s.vy || 0; s.age = 0; this.shots.push(s); return s; }; + // $60 "a shot is out" stays set until every player-shot slot (2-15) is empty (shots_gone_check); the Thunder + // Beam's fire handler refuses while it is set, so even a Buster shot still on screen blocks it + P.shotOut = function () { return this.shots.length > 0; }; + P.blockOut = function () { return this.count('held_block') > 0 || this.count('thrown_block') > 0 || this.count('block_chunk') > 0; }; + + // fire_weapon ($A71E) and the per-weapon fire handlers ($A999 spawn records: slot, offset, velocity) + P.fire = function (c) { + var w = this.weapon, f = this.facing, x = this.x, y = this.y, self = this; + if (!this.spendable(w)) return; + if (w === 'P') { + var free = [2, 3, 4].filter(function (k) { return !self.slotUsed(k); })[0]; + if (!free) return; // three shots out + this.addShot({ kind: 'buster', w: 'P', slot: free, x: x + 16 * f, y: y, vx: 4 * f, hw: 4, hh: 4, pierce: false }); + c.emit('mm_shot', x + 16 * f, y); + } else if (w === 'E') { + if (this.shotOut()) return; // one beam at a time + THUNDER.forEach(function (r, i) { // records 6-$0A -> slots 5-9 + self.addShot({ kind: 'thunder', w: 'E', slot: 5 + i, x: x + r[0] * f, y: y + r[1], vx: AIR * f, row: i, t: r[2], + hw: MM.PLAYER_BOLT.hw[i], hh: MM.PLAYER_BOLT.hh[i], pierce: true }); + }); + this.addShot({ kind: 'thunder_v', w: 'E', slot: 10, x: x + 16 * f, y: y - 16, vx: 0, vy: 6, hw: 8, hh: 16, pierce: true }); + this.addShot({ kind: 'thunder_v', w: 'E', slot: 11, x: x + 16 * f, y: y + 16, vx: 0, vy: -6, hw: 8, hh: 16, pierce: true }); + this.spend(w); c.emit('mm_thunder', x, y); + } else if (w === 'I') { + if (this.slotUsed(5)) return; // record 5 needs slot 5 + this.addShot({ kind: 'slasher', w: 'I', slot: 5, x: x + 16 * f, y: y, vx: 4 * f, hw: 8, hh: 8, pierce: true }); + this.spend(w); c.emit('mm_slasher', x, y); + } else if (w === 'F') { + if (this.slotUsed(5)) return; // the wave (record 0) needs slot 5 + this.addShot({ kind: 'fire_wave', w: 'F', slot: 5, x: x + 16 * f, y: y, vx: 4 * f, hw: 8, hh: 8, pierce: true }); + if (!this.slotUsed(6)) this.addShot({ kind: 'fire_shield', w: 'F', slot: 6, x: x, y: y - 20, vx: 0, hw: 8, hh: 8, pierce: true }); + this.shieldN = 0; this.spend(w); c.emit('mm_fire', x, y); // re-firing restarts the 32-frame shield + } else if (w === 'C') { + if (this.shotOut()) return; // single_shot_gate: $60; record $0E, kick 02.80 + this.addShot({ kind: 'cutter', w: 'C', slot: 5, x: x + 12 * f, y: y - 4, vx: 2 * f, vy: 2, hw: 8, hh: 8, pierce: true, n: 0, ret: 0, kick: 0x280 }); + this.spend(w); c.emit('mm_cutter', x, y); + } else if (w === 'B') { + if (this.shotOut()) return; // single_shot_gate: $60 + this.addShot({ kind: 'hyper_bomb', w: 'B', slot: 5, x: x + 12 * f, y: y - 4, vx: fx(0x180) * f, vy: 3, hw: 8, hh: 8, pierce: true, fuse: 0, bounces: 3 }); + this.spend(w); c.emit('mm_hyper_bomb', x, y); + } else if (w === 'G') { // fire_super_arm + var held = this.shots.filter(function (s) { return s.kind === 'held_block'; })[0]; + if (!held) { // lifting costs nothing and has no firing pose + if (this.shotOut() || !this.blockTarget) return; + this.takeBlock(c, this.blockTarget); + this.addShot({ kind: 'held_block', w: 'G', slot: 5, x: x + 16 * f, y: y - 16, vx: 0, hw: BLOCK_HALF[c.id], hh: BLOCK_HALF[c.id], pierce: true, n: 0 }); + c.emit('mm_lift', x, y); + return; + } + this.shots = this.shots.filter(function (s) { return s !== held; }); // the throw replaces it, and only the throw costs energy + this.addShot({ kind: 'thrown_block', w: 'G', slot: 5, x: x + 16 * f, y: y - 16, vx: THROW_VX * f, vy: THROW_VY, hw: held.hw, hh: held.hh, pierce: true, n: 0 }); + this.spend(w); c.emit('mm_throw', x, y); + } + this.shootT = 15; + }; + + // horizontal speed (player_hspeed $9CE7 with the anim -> speed rows $9DDD/$9DE6): the walk-start anim $03 runs + // 9 frames at 00.20, then the walk anim $06 at 01.60. On the release frame the speed of the current anim still + // applies; releasing from $06 starts the stop-step anim $0C (13 more frames at 00.80), from $03 he just stands. + P.walk = function (dx) { + var was = this.prev.left || this.prev.right; + if (this.grounded) { + if (dx) { + if (!was) this.walkT = 0; // from a stop or mid-slowdown: start-up + this.facing = dx; this.slideT = 0; + this.speed = this.walkT < START_T ? START : WALK; this.walkT++; + } else if (was) { // release frame: the current anim's speed + this.speed = this.walkT >= START_T ? WALK : START; + this.slideT = this.walkT >= START_T ? SLIDE_T : 0; this.walkT = 0; + } else if (this.slideT > 0) { this.speed = SLIDE; this.slideT--; } + else this.speed = 0; + this.airHeld = !!dx; + } else { + if (dx) { this.facing = dx; this.speed = this.airHeld ? AIR : START; this.airHeld = true; } + else { this.speed = 0; this.airHeld = false; } + this.slideT = 0; this.walkT = dx ? START_T + 1 : 0; // landing with the d-pad held keeps full walk speed + } + this.moveX(this.speed * this.facing); + }; + P.moveX = function (v) { + var nx = this.x + v, lo = MM.WALL_L + BODY_HW, hi = MM.WALL_R - BODY_HW; + nx = nx < lo ? lo : nx > hi ? hi : nx; + if (this.room.length) nx = MM.clampX(this.room, this.x, nx, BODY_HW, this.y, BODY_HH); + this.x = nx; + }; + // vertical_collision for the player; returns true on the frame it lands + P.fall = function () { + var ny = this.y - this.vy, air = !this.grounded; + var floor = this.room.length ? MM.floorUnder(this.room, this.x - 7, this.x + 7, this.y + BODY_HH) : MM.FLOOR; + if (this.vy <= 0 && ny + BODY_HH >= floor) { this.y = floor - BODY_HH; this.vy = 0; this.grounded = true; return air; } + this.y = ny; this.grounded = false; + this.vy = Math.max(-MM.FALL_MAX, this.vy - MM.GRAVITY); + return false; + }; + + P.update = function (c, i) { + var p = this.prev, dx = (i.right ? 1 : 0) - (i.left ? 1 : 0), landed = false, exit = this.exitKnock; + this.fired = false; this.exitKnock = false; + this.anyInput = !!(i.left || i.right || i.up || i.down || i.jump || i.fire || i.prev || i.next); + if (c.boss.intro > 0 || this.hp <= 0) { this.prev = {}; this.fall(); this.flight(c); return; } // input locked + this.fired = !!i.fire && !p.fire; // p1_new_presses & B: bosses read it even in knockback + if (i.prev && !p.prev) this.cycle(-1); + if (i.next && !p.next) this.cycle(1); + if (exit) this.prev = { jump: p.jump, fire: p.fire }; // player_state_exit clears p1_prev_buttons this frame only + if (this.knockT > 0) { // special state 3: knockback, no control + this.moveX(KNOCK * this.knockDir); + this.speed = 0; this.walkT = 0; this.slideT = 0; this.airHeld = false; + landed = this.fall(); + } else if (this.stunT > 0) { // special state 2 (the quake): no control, drifts backwards + if ((this.stunT & 15) === 15) { this.vy = STUN_VY; this.grounded = false; } + this.moveX(-START * this.facing); + this.speed = 0; this.walkT = 0; this.slideT = 0; this.airHeld = false; + landed = this.fall(); + } else { + this.walk(dx); + if (this.fired) this.fire(c); + if (this.vy < 0 || this.grounded) { // falling or standing: land first, then the jump check + landed = this.fall(); + if (this.grounded && i.jump && !p.jump) { this.vy = JUMP; this.grounded = false; c.emit('mm_jump', this.x, this.y); } + } else { // rising: step, then releasing jump feathers the rise + this.fall(); + if (!this.grounded && !i.jump && this.vy >= 2) this.vy = 1; // player_fall_cap + } + } + if (landed) c.emit('mm_land', this.x, MM.FLOOR); + this.flight(c); + this.prev = { left: !!i.left, right: !!i.right, up: !!i.up, down: !!i.down, jump: !!i.jump, fire: !!i.fire, prev: !!i.prev, next: !!i.next }; + }; + + // weapon flight services, run before the boss AI ($A35C, dispatched by the CURRENT weapon): Thunder Beam crawl + // jumps (thunder_flight; pieces left over after a switch only drift), Fire Storm shield orbit + // (fire_storm_flight: INC the timer, drop the shield at 32, else orbit at offset timer & 7) + P.flight = function (c) { + var self = this, T = MM.PLAYER_BOLT; + this.hyperFlight(); + this.cutterFlight(); + this.armFlight(); + if (this.count('fire_shield') && ++this.shieldN === 32) { + this.shots = this.shots.filter(function (s) { return s.kind !== 'fire_shield'; }); + } + this.shots.forEach(function (s) { + if (s.kind === 'thunder' && s.t <= 0 && self.weapon === 'E') { + s.x += T.jx[s.row] * s.dir; s.y += T.jy[s.row]; s.row = T.next[s.row]; s.hw = T.hw[s.row]; s.hh = T.hh[s.row]; s.t = 10; + } else if (s.kind === 'fire_shield') { + var k = self.shieldN & 7; s.x = self.x + ORBIT_X[k]; s.y = self.y + ORBIT_Y[k]; + } + }); + this.thunderBlocks(c); + }; + + // guts_flight / guts_block_detect: the held block settles for one frame, then floats 26 px over the player. With no + // shot out the Super Arm probes one tile ahead at the player's y (+8 facing right, -9 facing left) for a liftable block. + // guts_thrown: while the throw's $61 runs from $10 to $1F, an airborne player takes the firing pose $6F, one count per frame. + P.armFlight = function () { + if (this.weapon !== 'G') return; + var s = this.shots.filter(function (q) { return q.kind === 'held_block'; })[0]; + if (s) { + if (!s.n) { s.n = 1; return; } + s.x = this.x; s.y = this.y - ARM_LIFT; s.dir = this.facing; + return; + } + if (!this.grounded && this.knockT === 0 && this.stunT === 0) this.shots.forEach(function (q) { if (q.kind === 'thrown_block' && q.n < 15) q.n++; }); + if (this.shotOut()) return; + this.blockTarget = MM.blockAt(this.room, Math.floor(this.x) + (this.facing > 0 ? 8 : -9), Math.floor(this.y)); + }; + // the record becomes type 4: the block is gone for the rest of the fight, for the player and the boss alike + P.takeBlock = function (c, block) { + var rest = function (r) { return r.x0 !== block.x0; }; + this.room = this.room.filter(rest); c.boss.room = c.boss.room.filter(rest); + this.blocksGone.push(block.x0); this.blockTarget = null; + }; + // guts_block_shatter: 4 chunks in slots 5-8 around (x0, y0), the facing of slot 5, slots 9-$F cleared. Chunks move straight + // without tile collision, and pierce: only the block itself breaks on a hit. + P.placeChunks = function (x0, y0, dir, keep) { + var self = this; + this.shots = this.shots.filter(keep); + CHUNKS.forEach(function (r, i) { + self.shots.push({ kind: 'block_chunk', w: 'G', slot: 5 + i, x: x0 + r[0], y: y0 + r[1], vx: r[2] * dir, vy: r[3], hw: 4, hh: 4, pierce: true, + id: self.nextShot++, dir: dir, age: 0 }); + }); + }; + // block_impact_shatter: the fragments start 16 px up-left of the impact + P.blockShatter = function (c, s) { + this.placeChunks(s.x - 16, s.y - 16, s.dir, function (q) { return q !== s; }); + c.emit('mm_block_shatter', s.x, s.y); + }; + // thunder_block_scan: every frame the live beam pieces of one parity probe the override records; a liftable block under one + // breaks (guts_block_pickup), which ends the beam: the chunks take slots 5-8, slots 9-$F are cleared + P.thunderBlocks = function (c) { + if (this.weapon !== 'E' || !this.room.length || (!this.count('thunder') && !this.count('thunder_v'))) return; + var hit = null, self = this; + for (var slot = 5 + (c.t & 1); slot < 12 && !hit; slot += 2) { + this.shots.forEach(function (s) { + if (hit || s.slot !== slot) return; + var b = MM.blockAt(self.room, Math.floor(s.x), Math.floor(s.y)); + if (b) hit = b; + }); + } + if (!hit) return; + this.takeBlock(c, hit); + var five = this.shots.filter(function (q) { return q.slot === 5; })[0]; // the chunks take slot 5's facing + this.placeChunks(hit.x0, hit.y0, five ? five.dir : this.facing, function (q) { return q.slot < 5 || q.slot > 11; }); + c.emit('mm_block_shatter', hit.x0 + 16, hit.y0 + 16); + }; + + // cutter_flight: 42 frames out with Y velocity falling 00.1A per frame, then it homes on the player at 02.80 + 0.08 + // per frame, caught within 12 px on both axes; the throw kick (02.80, -0.20 per frame) comes off the Y velocity. The + // service is dispatched by the current weapon, and a switch removes slot 5, so only the Cutter selected reaches here. + P.cutterFlight = function () { + var s = this.shots.filter(function (q) { return q.kind === 'cutter'; })[0]; + if (!s) return; + if (s.n < 0x2A) { s.n++; s.vy -= fx(0x1A); return; } + if (s.n === 0x2A) { s.n++; s.ret = 0x280; } + var dx = Math.floor(this.x) - Math.floor(s.x), adx = Math.abs(dx); + s.ret += 8; + var v = MM.propVel(s.ret, adx, Math.floor(s.y) - Math.floor(this.y)); + s.vx = v.vx * (dx >= 0 ? 1 : -1); s.vy = v.vy; s.dir = dx >= 0 ? 1 : -1; + if (v.ady < 12 && adx < 12) { s.dead = true; this.shots = this.shots.filter(function (q) { return q !== s; }); return; } + if (s.kick) { s.kick -= 0x20; s.vy -= s.kick / 256; } + }; + + // bomb_flight: the fuse ($61) counts from the firing frame; at $92 slot 5 becomes 12 flames in slots 2-13 (row 11 + // first), which fly straight and are cleared at $A0. The counter lives on the shots, so fights without the bomb + // keep exactly the same state. + P.hyperFlight = function () { + var burst = null; + this.shots.forEach(function (s) { + if (s.kind !== 'hyper_bomb' && s.kind !== 'hyper_flame') return; + s.fuse++; + if (s.kind === 'hyper_bomb' && s.fuse === BOMB_FUSE) burst = s; + }); + if (burst) { + this.shots = this.shots.filter(function (s) { return s !== burst; }); + for (var row = 11; row >= 0; row--) { + var r = MM.SPREAD[row], dir = r[2] ? 1 : -1; + this.shots.push({ kind: 'hyper_flame', w: 'B', slot: 13 - row, x: burst.x, y: burst.y, vx: r[0] * dir, vy: r[1], hw: 8, hh: 8, pierce: false, + fuse: BOMB_FUSE, id: this.nextShot++, dir: dir, age: 0 }); + } + } + if (this.count('hyper_flame')) this.shots = this.shots.filter(function (s) { return s.kind !== 'hyper_flame' || s.fuse < BOMB_END; }); + }; + // entity_pass + react_bubble for the fused bomb: tile collision and gravity. A wall only pushes it out; each landing + // halves the X speed and bounces with Y speed n.n while the counter $62 (3) runs down to 0. + P.hyperMove = function (s) { + var lo = MM.WALL_L + s.hw, hi = MM.WALL_R - s.hw, room = this.room; + s.x = Math.min(hi, Math.max(lo, s.x + s.vx)); s.age++; + if (room.length) s.x = MM.clampX(room, s.x - s.vx, s.x, s.hw, s.y, s.hh); + var ny = s.y - s.vy, floor = room.length ? MM.floorUnder(room, s.x - s.hw + 1, s.x + s.hw - 1, s.y + s.hh) : MM.FLOOR; + if (s.vy < 0 && ny + s.hh >= floor) { + var n = s.bounces; s.y = floor - s.hh; s.vy = n + n / 256; if (n > 0) s.bounces--; + s.vx = (s.vx < 0 ? -1 : 1) * Math.floor(Math.abs(s.vx) * 128) / 256; + return; + } + s.y = ny; s.vy = Math.max(-MM.FALL_MAX, s.vy - MM.GRAVITY); + }; + + // entity_pass for the thrown block (flags $15: tile collision, gravity): a wall or the floor shatters it; at the top of the + // screen a rising block only slows down, a falling one vanishes (react_floater) + P.blockMove = function (c, s) { + var lo = MM.WALL_L + s.hw, hi = MM.WALL_R - s.hw, room = this.room, nx = s.x + s.vx, stop = false; + s.age++; + if (nx < lo) { nx = lo; stop = true; } else if (nx > hi) { nx = hi; stop = true; } + if (room.length) { var cx = MM.clampX(room, s.x, nx, s.hw, s.y, s.hh); if (cx !== nx) { nx = cx; stop = true; } } + s.x = nx; + if (stop) { this.blockShatter(c, s); return; } + var ny = s.y - s.vy, floor = room.length ? MM.floorUnder(room, s.x - s.hw + 1, s.x + s.hw - 1, s.y + s.hh) : MM.FLOOR; + if (ny < MM.TOP_EXIT) { if (s.vy < 0) s.dead = true; else s.vy -= MM.GRAVITY; return; } + if (s.vy < 0 && ny + s.hh >= floor) { s.y = floor - s.hh; this.blockShatter(c, s); return; } + s.y = ny; s.vy = Math.max(-MM.FALL_MAX, s.vy - MM.GRAVITY); + }; + + // ---- the part of the tick after the boss AI (arena.js lists the order) ---- + P.resolveInteractions = function (c) { + var b = c.boss, j; + if (this.iframes > 0) this.iframes--; + if (b.fight && this.hp > 0 && b.hp > 0) { + // player contact (player_contact_service $A18B): boss body every frame, boss shots by slot parity + var hb = this.hurtBox(); + if (this.iframes === 0 && MM.overlap(b.hitBox(), hb)) this.hurt(c, b.contactDamage(), b.dir, b.id + '_body'); + else if (this.iframes === 0) { + for (j = 0; j < b.projectiles.length; j++) { + var q = b.projectiles[j]; + if (q.harmless || (q.slot & 1) !== (c.t & 1)) continue; + if (MM.overlap(q, hb)) { this.hurt(c, q.dmg, q.dir, q.kind); break; } + } + } + // shots vs boss ($C8B2): only the current weapon's slots, skipped while the boss blinks; the damage row is + // the CURRENT weapon (current_weapon indexes $FDEE); a non-piercing shot is consumed by a hit + for (j = 0; j < this.shots.length && b.hp > 0 && this.hp > 0; j++) { + var s = this.shots[j]; + if (b.iframes > 0 || s.dead || !this.collides(s)) continue; + if (MM.overlap(b.hitBox(), s)) { + b.takeHit(c, this.weapon, s.x, s.y); if (!s.pierce) s.dead = true; + if (s.kind === 'thrown_block') { this.blockShatter(c, s); break; } // gutscoll_hit: the service ends here + } + } + } + // entity pass: player shots drift and leave the screen; the boss moves its own projectiles + var self = this; + this.shots.forEach(function (s) { + if (s.dead || s.kind === 'fire_shield') return; + if (s.kind === 'hyper_bomb') { self.hyperMove(s); return; } + if (s.kind === 'held_block') return; + if (s.kind === 'thrown_block') { self.blockMove(c, s); return; } + s.x += s.vx; s.y -= s.vy; s.age++; + if (MM.offscreen(s)) s.dead = true; + }); + this.shots = this.shots.filter(function (s) { return !s.dead; }); + b.entityPass(c); + // render-time counters: animation timers and poses, the boss's blink + this.shots.forEach(function (s) { if (s.kind === 'thunder') s.t--; }); + if (this.shootT > 0) this.shootT--; + if (this.knockT > 0 && --this.knockT === 0) this.exitKnock = true; + if (this.stunT > 0 && --this.stunT === 0) this.exitKnock = true; + b.renderTick(c); + }; + + P.hurt = function (c, dmg, fromDir, kind) { + if (this.iframes > 0 || this.hp <= 0 || !(dmg > 0)) return false; + this.hp = Math.max(0, this.hp - dmg); this.hits++; + c.events.push({ t: c.t, name: 'hurt_by', by: kind }); + if (this.hp <= 0) { this.knockT = 0; this.stunT = 0; this.shots = []; this.shieldN = 0; c.emit('mm_player_dead', this.x, this.y); return true; } + if (this.stunT > 0 && c.boss.shake > 0) { // the NMI rewrites the state to 2 this very frame: anim $13 never changed, so no knockback starts + if (fromDir) this.facing = -fromDir; + this.iframes = IFRAMES; c.emit('mm_hurt', this.x, this.y); + return true; + } + this.stunT = 0; + this.airHit = !this.grounded && !!c.boss.shake; // anim $09 still reads airborne to this frame's NMI: the stun comes one frame later + this.knockDir = fromDir || -this.facing; this.facing = -this.knockDir; + this.knockT = KNOCK_T; this.iframes = IFRAMES; this.speed = 0; this.walkT = 0; this.slideT = 0; + this.vy = KNOCK_VY; this.grounded = false; + c.emit('mm_hurt', this.x, this.y); + return true; + }; + + // The quake (nmi_shake_palette, one call per shake_timer frame at the end of the tick, Guts Man's renderTick): the player + // is forced into special state 2 unless his anim is $09 or $6F, the airborne poses. Knockback is anim $12, so it is + // overwritten, including its last frame (the state exit only runs next frame). An already stunned player does not restart. + P.quake = function () { + if (this.hp <= 0 || this.stunT > 0) return; + if (this.airHit) { this.airHit = false; return; } + if (!this.grounded && this.knockT === 0 && !this.exitKnock) return; + this.stunT = STUN_T; this.knockT = 0; this.exitKnock = false; + }; + + // the player's jump/fall pose anim $09 (player_air_pose); Cut Man reads it. Knockback is anim $12, and for the first + // 15 frames of a thrown Cutter or Hyper Bomb an airborne player is in the firing variant $6F; Buster shots keep $09 + P.airPose = function () { + if (this.grounded || this.knockT > 0 || this.stunT > 0) return false; + return !this.shots.some(function (s) { return (s.kind === 'cutter' && s.n < 0x0F) || (s.kind === 'hyper_bomb' && s.fuse < 0x0F) || (s.kind === 'thrown_block' && s.n < 0x0F); }); + }; + + P.state = function () { + var o = { x: this.x, y: this.y, vy: this.vy, facing: this.facing, grounded: this.grounded, + speed: this.speed, walk_t: this.walkT, slide_t: this.slideT, air_held: this.airHeld, + hp: this.hp, max_hp: this.max_hp, iframes: this.iframes, knock_t: this.knockT, knock_dir: this.knockDir, + shoot_t: this.shootT, weapon: this.weapon, weapons: this.weapons, energy: this.energy, + shots: this.shots, next_shot: this.nextShot, shield_n: this.shieldN, previous: this.prev, + fired: this.fired, any_input: this.anyInput, hits: this.hits }; + // only while they differ from their initial values, so fights without a quake or the Super Arm keep the same state hash + if (this.stunT) o.stun_t = this.stunT; + if (this.blockTarget) o.block_target = this.blockTarget.x0; + if (this.blocksGone.length) o.blocks_gone = this.blocksGone; + return MM.snapshot(o); + }; + B.MegaMan = MegaMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/bomb_man.js b/environments/games/web/games/megaman_remake/bosses/bomb_man.js new file mode 100644 index 0000000000000000000000000000000000000000..538aebc528137e5065d867690bb9273445be72e3 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/bomb_man.js @@ -0,0 +1,162 @@ +// Bomb Man (game mode 2, fixed bank $DFF0). Port of the original 18-state table $E0ED: +// jump_pick face the player, rng & 1 picks jump variant 0 (big leap toward, 02.90 / 07.60) or 1 (hop toward, +// 01.09 / 05.B0) from $E03B; the variant's state number sends the table to walk_idle at index 8 or 17 +// walk_idle fly the jump; landing stops him (X speed 0) -> pattern_roll +// pattern_roll random_mod 6 walks the table back: r odd -> 3 bombs, r 0/4 -> 2, r 2 -> 1 +// throw / land_throw a 15-frame windup ($0641 = $1F: draw_entity counts the low nibble), then a bomb; the next windup waits until the bomb burst +// wait_bomb wait for the last bomb; the second set (index 10) then leap_away: turn away, variant 2 (01.09/05.B0) +// guard during pattern_roll / land_throw / throw, the player within 48 px aborts the state and jumps at once +// Boss bomb (record 0): anim $27 8x8, gravity, X speed (|dx| - 24) / 51, Y 05.B0, dy -11, dx +8 along his look. +// It bursts on the floor or a wall into 12 shrapnel pieces ($F88A-$F8BA, no gravity, no tile collision); a piece +// flies 7-8 frames, turns into dust (still harmful) for 7 more and vanishes. Player shots pass through bombs and +// pieces (no flag bit 2); touching a bomb hurts but does not set it off. Bomb Man has no hit reaction. +// Tier knobs (specs/bomb_man.spec.js): hp, bomb/shrapnel damage, contact damage, windup frames. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + // $E03B variant table: table index after the jump (state - 5), X speed, Y speed + var VARIANTS = [[8, fx(0x290), fx(0x760)], [17, fx(0x109), fx(0x5B0)], [8, fx(0x109), fx(0x5B0)]]; + var SEQ = ['jump_pick', 'wait_bomb', 'throw', 'land_throw', 'throw', 'land_throw', 'throw', 'pattern_roll', 'walk_idle', + 'leap_away', 'wait_bomb', 'throw', 'land_throw', 'throw', 'land_throw', 'throw', 'pattern_roll', 'walk_idle']; + var GUARD = 0x30, LEAD = 0x18, DIV = 0x33, BOMB_VY = fx(0x5B0); + // the shrapnel uses the spread_shot_spawn rows MM.SPREAD (body_megaman.js); the facing also sets a hit's knockback + // anim $39 (9 one-tick frames) starts at frame 1 and wraps to 0 after 8 renders: the pass that sees frame 0 turns + // it into dust $54 (8 one-tick frames from 0), which wraps after 8 more renders and is removed. A piece moves once + // per pass: 7 steps as shrapnel (8 if its slot comes after the bomb's, so the burst pass moves it too), 7 as dust. + var DUST_AT = 8, GONE_AT = 16; + // drop-in: the boss animation reaches frame byte $3C about 51 frames into the 94-frame intro (anim $1E, 13 ticks + // per frame, started at $01); the type $0C bomb (Y 03.30, dy -20, dx +6, no contact flag) only decorates the intro + var INTRO_BOMB_AT = 51, INTRO_BOMB_LIFE = 27; + + function BombMan() {} + var P = BombMan.prototype; + RM.install(P, 'bomb_man', B.SPECS.bomb_man); + P.reset = function (c) { + this.base(c); this.n = 0; this.variant = -1; this.roll = -1; this.lastDx = 0; + this.jumps = 0; this.leaps = 0; this.guards = 0; this.bombs = 0; this.bursts = 0; + }; + P.onFight = function () { this.n = 0; this.st = SEQ[0]; }; + P.go = function (n) { this.n = n; this.st = SEQ[n]; }; + P.back = function () { this.go(this.n - 1); }; + + // bombman_guard_range: |dx| < $30 resets the table to jump_pick and aborts the caller (PLA PLA) + P.guard = function (c) { + var d = this.lastDx = this.face(c); + if (d >= GUARD) return false; + this.go(0); this.guards++; return true; + }; + P.windupStart = function () { this.back(); this.setPose('windup'); this.windup = Math.round(this.k.windup); }; + P.jump = function (c, v) { + var row = VARIANTS[v]; + this.windup = 0; this.variant = v; this.vx = row[1]; this.vy = row[2]; this.grounded = false; + this.setPose(v === 2 ? 'leap' : 'jump'); this.go(row[0]); + c.emit('mm_jump', this.x, this.y); + }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { + if (RM.INTRO - this.intro === INTRO_BOMB_AT) this.spawnBomb(c, 'intro_bomb', this.x + 6 * this.look, this.y - 20, 0, fx(0x330)); + MM.step(this); return; + } + switch (this.st) { + case 'jump_pick': + this.updateFacing(c); this.jumps++; + this.jump(c, c.rng.int(2)); break; + case 'leap_away': + this.updateFacing(c); this.dir = -this.dir; this.leaps++; + this.jump(c, 2); break; + case 'walk_idle': + if (this.walkTick(c)) { this.vx = 0; this.setPose('stand'); this.back(); c.emit('mm_land', this.x, MM.FLOOR); } + break; + case 'pattern_roll': { + if (this.guard(c)) break; + var r = this.roll = c.rng.int(6); + if (r & 1) { this.windupStart(); break; } // 3 bombs + this.go(this.n - 2); + if (!(r & 2)) { this.windupStart(); break; } // r 0 / 4: 2 bombs + this.go(this.n - 2); this.windupStart(); // r 2: 1 bomb + break; + } + case 'land_throw': + if (this.guard(c)) break; + if (this.out === 0) this.windupStart(); + break; + case 'wait_bomb': + if (this.out === 0) this.back(); + break; + case 'throw': { + if (this.guard(c)) break; + if (this.windup > 0) break; + this.back(); + var d = this.lastDx >= LEAD ? this.lastDx - LEAD : this.lastDx; + var vx = Math.floor(d * 256 / DIV) / 256; // divide_16 quotient in 8.8 + if (this.spawnBomb(c, 'bomb', this.x + 8 * this.look, this.y - 11, vx, BOMB_VY)) { this.bombs++; this.setPose('throw'); } + break; + } + } + }; + P.spawnBomb = function (c, kind, x, y, vx, vy) { + var p = this.spawn({ kind: kind, x: x, y: y, dir: this.look, vx: vx, vy: vy, hw: 8, hh: 8, grav: true, + dmg: this.shotDamage(), harmless: kind === 'intro_bomb' }); + if (!p) return null; + this.out++; + if (kind === 'bomb') c.emit('mm_boss_bomb', p.x, p.y); + return p; + }; + // react_boss_bomb: $44--, in the fight the bomb becomes piece 11 in its own slot and pieces 10..0 fill free slots + P.burst = function (c, p) { + this.out = Math.max(0, this.out - 1); + if (!this.fight || p.kind === 'intro_bomb') { p.dead = true; return; } + this.bursts++; + var self = this; + function shard(q, row) { + q.kind = 'shrapnel'; q.row = row; q.vx = MM.SPREAD[row][0]; q.vy = MM.SPREAD[row][1]; q.grav = false; q.age = 0; + q.hw = 8; q.hh = 8; q.dir = MM.SPREAD[row][2] ? 1 : -1; return q; + } + shard(p, 11); + for (var row = 10; row >= 0; row--) { + var q = this.spawn({ x: p.x, y: p.y, dmg: this.shotDamage() }); + if (!q) break; // no free slot: the burst is cut short + shard(q, row); + } + c.emit('mm_boss_burst', p.x, p.y); + }; + // entity_pass over the boss's slots in slot order (pieces spawned into a later slot move in the same pass): + // bombs move x (wall probe, reason 3) then y with gravity (floor probe, reason 4); pieces float straight + P.entityPass = function (c) { + var self = this; + for (var slot = 16; slot < 32; slot++) this.passSlot(c, slot); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + P.passSlot = function (c, slot) { + var self = this, p = null; + this.projectiles.forEach(function (q) { if (q.slot === slot && !q.dead) p = q; }); + if (!p) return; + (function () { + if (p.kind === 'bomb' || p.kind === 'intro_bomb') { + if (p.kind === 'intro_bomb' && p.age >= INTRO_BOMB_LIFE) { self.burst(c, p); return; } + var nx = p.x + p.vx * p.dir, lo = MM.WALL_L + p.hw, hi = MM.WALL_R - p.hw; + if (nx < lo || nx > hi) { p.x = nx < lo ? lo : hi; self.burst(c, p); return; } + p.x = nx; + var ny = p.y - p.vy; + if (p.vy < 0 && ny + p.hh >= MM.FLOOR) { p.y = MM.FLOOR - p.hh; self.burst(c, p); return; } + p.y = ny; p.vy = Math.max(-MM.FALL_MAX, p.vy - MM.GRAVITY); + return; + } + // shrapnel / dust: the one-shot animation ending (age counts renders since the burst) raises reason 0 + if (p.age === DUST_AT) { p.kind = 'dust'; return; } + if (p.age >= GONE_AT) { p.dead = true; return; } + p.x += p.vx * p.dir; + var y = p.y - p.vy; + if (y < MM.TOP_EXIT || y >= MM.BOTTOM_EXIT || p.x < 0 || p.x >= 256) { p.dead = true; return; } + p.y = y; + })(); + }; + P.state = function () { + return this.baseState({ n: this.n, variant: this.variant, roll: this.roll, last_dx: this.lastDx, jumps: this.jumps, + leaps: this.leaps, guards: this.guards, bombs: this.bombs, bursts: this.bursts }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/bomb_man'] = { title: 'Shard Lobber', Body: B.MegaMan, Boss: BombMan }; + B.BombMan = BombMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/cut_man.js b/environments/games/web/games/megaman_remake/bosses/cut_man.js new file mode 100644 index 0000000000000000000000000000000000000000..87eb64fed18caf6c3b76034d33a5660f7749c1f5 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/cut_man.js @@ -0,0 +1,193 @@ +// Cut Man (game mode 0, fixed bank $DC8B). Port of the original 21-entry table $DFC0 ( 1.3): +// 5 retarget |dx| >= 64: walk; else jump - unless the player stands at another height (not in the air): chase +// 6 walk 01.20 toward the player; a wall (the step) -> jump +// 7 jump 06.40 up; random_mod 6 picks the landing class 2 (1/2, 32 px past), 1 (1/3, on him), 0 (1/6, 32 px short); +// X speed = (|dx| + $DFED[class]) / 50 with the original's 8-bit sign quirk +// 8/9/$C the frame after take-off: 2 in 3 (cutter home) the pose timer runs and he throws in mid-air +// $A-$D landing branches (a short 04.E0 hop near the player, coin flips) +// $E/$F land, then the throw stance $43: the cutter leaves on its 16th frame +// $10-$17 timed pose / mid-air throw pairs (timers 8, $12, $12, $15) +// $18 chase: stand 63 frames while the player is on another level, then throw +// hit for the first 32 of his 63 blink frames: turn away and hop (01.40 / 01.20), then state $E +// The Rolling Cutter (record 6, 6x6, no tile collision) is aimed at the player at 02.60 (proportional_velocity), turns +// back outside x [24, 232) / y [24, 216), and homes on him at 02.60 + 0.04 per retarget every 4th frame, caught within +// 8 px; one cutter at a time. AI timing reads the boss animation frame byte ($0441), so the animation counter is kept. +// Tier knobs (specs/cut_man.spec.js): hp, cutter/contact damage, cutter speed scale, chase wait. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + // $DFC0 by seq_step - 5; entry 20 is the forced hit reaction (Y = $28), handled by react() + var SEQ = ['retarget', 'walk', 'jump', 'air_high', 'air_flip', 'descend', 'walk_until_blocked', 'air_land', 'walk_coinflip', + 'land_settle', 'throw_windup', 'timed_pose', 'walk_throw', 'timed_pose', 'walk_throw', 'timed_pose', 'walk_throw', + 'timed_pose', 'walk_throw', 'chase']; + var LAND = [0x08, 0x09, 0x0C], ADJUST = [-0x20, 0, 0x20], AFTER_THROW = [0x0E, 0x0A, 0x05, 0x05]; + // animation rate bytes (advance_anim_counters $D2F8: low nibble = ticks per frame - 1, high nibble = last frame slot) + var RATE = { 0x1B: 0, 0x3F: 0x36, 0x41: 0x00, 0x43: 0x1F, 0x46: 0x18, 0x57: 0x00 }; + var REACT = 0x1F, CUT_SPEED = 0x260, CHASE = 0x3F; + + function CutMan() {} + var P = CutMan.prototype; + RM.install(P, 'cut_man', B.SPECS.cut_man); + var baseRender = P.renderTick; + // the step at the left of the room: tiles x 0-31 and the two liftable blocks x 32-96 (override type 2), top y 160 + MM.blockRoom('megaman/cut_man'); + P.reset = function (c) { + this.base(c); this.seq = 5; this.anim = 0x1B; this.af = 0; this.cut = 0; this.ret = 0; this.timer = 0; + this.jumps = 0; this.throws = 0; this.catches = 0; this.chases = 0; this.reacts = 0; this.lastClass = -1; + }; + P.onFight = function () { this.go(5); }; + P.go = function (n) { this.seq = n; this.st = SEQ[n - 5]; }; + // same height ($0601 == ent_y_px) or the player in the air pose $09: the throw goes ahead; otherwise chase + P.level = function (c) { return Math.floor(this.y) === Math.floor(c.body.y) || c.body.airPose(); }; + P.cutterHome = function () { return this.cut === 0; }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + this.trackCutter(c); + if (this.iframes >= REACT) { this.react(c); return; } + this[this.st](c); + }; + // ---- the cutter service that runs before the state ---- + P.trackCutter = function (c) { + if (!this.cut) return; + var p = this.projectiles.filter(function (q) { return q.kind === 'rolling_cutter'; })[0]; + if (!p) return; + if (this.cut === 1) { + var px = Math.floor(p.x), py = Math.floor(p.y); + if (py < 0x18 || py >= 0xD8 || px < 0x18 || px >= 0xE8) { + this.cut = 2; p.dir = -p.dir; p.vy = -p.vy; this.ret = Math.round(CUT_SPEED * this.k.speed); + } + return; + } + if (c.t & 3) return; // returning: retarget the boss every 4th frame + var dx = Math.floor(this.x) - Math.floor(p.x); + p.dir = dx >= 0 ? 1 : -1; this.ret += 4; + var v = MM.propVel(this.ret, Math.abs(dx), Math.floor(p.y) - Math.floor(this.y)); + p.vx = v.vx; p.vy = v.vy; + if (v.ady < 8 && Math.abs(dx) < 8) { p.dead = true; this.projectiles = this.projectiles.filter(function (q) { return !q.dead; }); this.cut = 0; this.catches++; } + }; + // record 6 inherits the sprite flip at spawn time; the aim afterwards only sets the speeds (proportional_velocity) + P.throwCutter = function (c) { + var f = this.look, p = this.spawn({ kind: 'rolling_cutter', x: this.x + 8 * f, y: this.y - 10, dir: f, vx: 0, vy: 0, hw: 6, hh: 6, dmg: this.shotDamage() }); + if (!p) return; + var adx = this.face(c), v = MM.propVel(Math.round(CUT_SPEED * this.k.speed), adx, Math.floor(this.y) - 10 - Math.floor(c.body.y)); + p.vx = v.vx; p.vy = v.vy; + this.cut = 1; this.throws++; this.setPose('throw'); + c.emit('mm_boss_cutter', p.x, p.y); + }; + // throw stance: anim $43 without resetting the frame byte (the original leaves $0441 alone) + P.throwStance = function () { this.anim = 0x43; this.vx = 0; this.setPose('stance'); this.go(this.seq + 1); }; + + // ---- states ---- + P.retarget = function (c) { + var n = 6; + if (this.face(c) < 0x40) n = this.level(c) ? 7 : 0x18; + this.go(n); + }; + P.walk = function (c) { + this.updateFacing(c); + if (this.anim !== 0x3F) { this.anim = 0x3F; this.af = 0; this.vx = fx(0x120); this.setPose('walk'); } + this.walkTick(c); + if (this.blocked) this.go(7); else this.retarget(c); + }; + P.jump = function (c) { + this.updateFacing(c); this.anim = 0x41; this.af = 0; this.setPose('jump'); + var r = c.rng.int(6), k = 2; + if (!(r & 1)) { k = 1; if (r & 2) k = 0; } + this.lastClass = k; this.jumps++; + this.go(LAND[k]); this.vy = fx(0x640); this.grounded = false; + var v = (this.face(c) + ADJUST[k]) & 0xFF; + if (v & 0x80) v = (256 - v) & 0xFF; // BPL / EOR #$FF / ADC #1 on the 8-bit sum + this.vx = Math.floor(v * 256 / 50) / 256; // divide_16: X speed = v / 50 in 8.8 + }; + P.walkRandom = function (c) { this.walkTick(c); return c.rng.int(3); }; + P.air_high = function (c) { + var r = this.walkRandom(c); + if (!(r & 1) && this.cutterHome()) { this.go(0x10); this.timer = 8; } else this.go(0x0E); + }; + P.air_flip = function (c) { + var r = this.walkRandom(c); + if (!(r & 1) && this.cutterHome()) { this.go(0x12); this.timer = 0x12; } else this.go(this.seq + 1); + }; + P.air_land = function (c) { + var r = this.walkRandom(c); + if (!(r & 1) && this.cutterHome()) { this.go(0x16); this.timer = 0x15; } else this.go(0x0D); + }; + P.descend = function (c) { + if (!this.walkTick(c)) return; + this.go(this.seq + 1); + if (this.face(c) >= 0x0E) { this.go(5); return; } + if ((c.rng.int(3) & 1) && this.cutterHome()) { this.go(0x14); this.timer = 0x12; } + this.vy = fx(0x4E0); this.vx = fx(0xC0); this.grounded = false; // short hop + }; + P.walk_until_blocked = function (c) { if (this.walkTick(c)) this.go(5); }; + P.walk_coinflip = function (c) { + if (!this.walkTick(c)) return; + if (c.rng.int(2)) this.go(5); else this.go(this.seq + 1); + }; + P.land_settle = function (c) { + if (!this.walkTick(c)) return; + if (!this.cutterHome()) { this.go(5); return; } + if (!this.level(c)) { this.go(0x18); return; } + this.throwStance(); + }; + P.throw_windup = function (c) { + this.walkTick(c); + if (this.af === 0) { this.go(5); return; } + if (this.af === 0x10) this.throwCutter(c); + }; + P.timed_pose = function (c) { + this.walkTick(c); + if (--this.timer > 0) return; + this.anim = 0x43; this.af = 0; this.setPose('stance'); this.go(this.seq + 1); + }; + P.walk_throw = function (c) { + if (this.af === 0) this.anim = 0x41; + else if (this.af === 0x10) this.throwCutter(c); + if (!this.walkTick(c)) return; + if (!this.level(c)) { this.go(0x18); return; } + this.go(AFTER_THROW[(this.seq & 7) >> 1]); + }; + P.chase = function (c) { + if (this.anim !== 0x46) { this.anim = 0x46; this.af = 0; this.timer = Math.round(this.k.wait); this.vx = 0; this.chases++; this.setPose('chase'); } + this.walkTick(c); + var same = Math.floor(this.y) === Math.floor(c.body.y); + if (!same || c.body.airPose()) { + if (this.timer > 0 && --this.timer > 0) return; + } + if (!this.cutterHome()) return; + this.go(0x0E); this.throwStance(); + }; + // boss_anim_hop: the first reaction frame turns away and hops; mode 0 restarts at state $E + P.react = function (c) { + if (this.anim !== 0x57) { + this.anim = 0x57; this.af = 0; this.updateFacing(c); this.dir = -this.dir; + this.vy = fx(0x140); this.vx = fx(0x120); this.grounded = false; this.go(0x0E); this.reacts++; this.setPose('hurt'); + } + this.walkTick(c); + }; + + // entity pass: the cutter flies straight (no gravity, no tile collision) and is removed if it leaves the screen + P.entityPass = function () { + var self = this; + this.projectiles.forEach(function (p) { + p.x += p.vx * p.dir; p.y -= p.vy; + if (MM.offscreen(p)) p.dead = true; + }); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + // render: the shared counters, then the animation frame byte the AI reads + P.renderTick = function (c) { + baseRender.call(this, c); + var rate = RATE[this.anim] || 0, lo = this.af & 15; + if (lo < (rate & 15)) this.af++; + else this.af = (this.af & 0xF0) >= (rate & 0xF0) ? 0 : (this.af & 0xF0) + 0x10; + }; + P.state = function () { + return this.baseState({ seq: this.seq, anim: this.anim, af: this.af, cutter: this.cut, ret: this.ret, jumps: this.jumps, + throws: this.throws, catches: this.catches, chases: this.chases, reacts: this.reacts, last_class: this.lastClass }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/cut_man'] = { title: 'Blade Tosser', Body: B.MegaMan, Boss: CutMan }; + B.CutMan = CutMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/elec_man.js b/environments/games/web/games/megaman_remake/bosses/elec_man.js new file mode 100644 index 0000000000000000000000000000000000000000..c359556bd3be0dfbde3ac0a8cc966460b6757abb --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/elec_man.js @@ -0,0 +1,117 @@ +// Elec Man (game mode 4, fixed bank $E434). Port of the original state machine: +// guard walk at 02.00 toward the wall position $E550[step] (176, 128, 48, 128) looking where he goes; +// arriving starts the shot; the player pressing fire (or a wall) makes him leap at once +// halt stop and wind up (15 frames) fire release the Thunder Beam, then wait until it has left +// leap jump 04.00 up / 01.E0 forward toward the player, 1 in 4 a feint away; pressing fire while he is in +// the air makes him wind up and fire in mid-air; landing restarts the pattern +// react for the first 32 of his 63 blink frames after a hit: turn away and hop (01.40 up, 01.20) +// The Thunder Beam (records 7-$0B, 01.50 px/frame) is five pieces that crawl: each time a piece's 10-frame +// animation wraps it jumps ahead and changes shape ($9AF4 x, $9AFC y, $9B04 next; staggered first wraps). +// Tier knobs (specs/elec_man.spec.js): hp, beam/contact damage, walk speed, windup, chance to counter a shot. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + var WALLS = [0xB0, 0x80, 0x30, 0x80]; + MM.ELEC_BOLT = { jx: [29, 33, 33, 29, 25, 29, 29, 29], jy: [-4, -24, 0, 28, 16, -12, -4, -4], + next: [5, 6, 7, 1, 2, 3, 4, 5], hw: [4, 8, 4, 4, 4, 8, 8, 4], hh: [8, 4, 8, 8, 8, 4, 4, 8] }; + var PIECES = [[20, -4, 2], [24, 8, 4], [28, -4, 6], [36, -20, 8], [44, -20, 9]]; // dx, dy, first wrap + var REACT = 0x1F; + + function ElecMan() {} + var P = ElecMan.prototype; + RM.install(P, 'elec_man', B.SPECS.elec_man); + P.reset = function (c) { this.base(c); this.step = 0; this.leaps = 0; this.feints = 0; this.bolts = 0; this.counters = 0; }; + P.onFight = function () { this.st = 'guard'; }; + + P.fireBolt = function (c) { + var self = this, f = this.look, made = 0; + PIECES.forEach(function (r, i) { + var p = self.spawn({ kind: 'thunder_beam', x: self.x + r[0] * f, y: self.y + r[1], dir: f, vx: fx(0x150), row: i, t: r[2], + hw: MM.ELEC_BOLT.hw[i], hh: MM.ELEC_BOLT.hh[i], dmg: self.shotDamage() }); + if (p) made++; + }); + this.out += made; this.bolts++; + c.emit('mm_boss_bolt', this.x, this.y); + }; + P.countered = function (c) { + if (!c.body.fired) return false; + var k = this.k.counter; + return k >= 1 || (k > 0 && c.rng.chance(k)); + }; + P.halt = function () { this.vx = 0; }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + if (this.iframes >= REACT) { this.react(c); return; } + switch (this.st) { + case 'guard': { + if (this.pose !== 'walk') { this.setPose('walk'); this.vx = this.k.walk; } + var target = WALLS[this.step & 3], d = this.faceTo(target); + if (d < 3) this.st = 'halt'; + this.dir = this.look; // boss_update_facing toward the wall position + this.walkNoFace(); + if (this.blocked || this.countered(c)) { this.st = 'leap'; this.counters++; } + break; + } + case 'halt': + this.halt(); this.setPose('fire'); this.windup = this.k.windup; this.st = 'fire'; + this.walkTick(c); break; + case 'fire': + if (this.windup <= 0) { this.fireBolt(c); this.st = 'wait'; } + this.walkTick(c); break; + case 'wait': + this.walkTick(c); + if (this.out <= 0) { this.step = (this.step + 1) & 3; this.st = 'guard'; } + break; + case 'leap': + this.setPose('leap'); this.vx = fx(0x1E0); this.vy = 4; + this.updateFacing(c); this.leaps++; + if (c.rng.int(4) === 0) { this.dir = -this.dir; this.feints++; } + this.st = 'air'; break; + case 'air': + if (this.walkTick(c)) { this.st = 'guard'; break; } + if (c.body.fired) this.st = 'air_pose'; + break; + case 'air_pose': + this.setPose('fire'); this.windup = this.k.windup; this.st = 'air_fire'; + if (this.walkTick(c)) this.halt(); + break; + case 'air_fire': + if (this.windup <= 0) { this.fireBolt(c); this.st = 'air_land'; } + if (this.walkTick(c)) this.halt(); + break; + case 'air_land': + if (this.out <= 0) this.st = 'guard'; + if (this.walkTick(c)) this.halt(); + break; + } + }; + // boss_anim_hop: on the first react frame turn away from the player and hop, the pattern restarts at guard + P.react = function (c) { + if (this.pose !== 'hurt') { + this.setPose('hurt'); this.updateFacing(c); this.dir = -this.dir; + this.vy = fx(0x140); this.vx = fx(0x120); this.st = 'guard'; + } + this.walkTick(c); + }; + + // entity pass for the Thunder Beam pieces (react_pickup $9AF4 chain): wrap -> jump, otherwise drift + P.entityPass = function () { + var self = this, T = MM.ELEC_BOLT; + this.projectiles.forEach(function (p) { + if (p.t <= 0) { + p.x += T.jx[p.row] * p.dir + (p.dir > 0 ? fx(0x50) : 0); p.y += T.jy[p.row]; + p.row = T.next[p.row]; p.hw = T.hw[p.row]; p.hh = T.hh[p.row]; p.t = 10; + } else p.x += p.vx * p.dir; + if (MM.offscreen(p)) { p.dead = true; self.out--; } + }); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + + P.state = function () { + return this.baseState({ step: this.step, leaps: this.leaps, feints: this.feints, bolts: this.bolts, counters: this.counters }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/elec_man'] = { title: 'Pouncer', Body: B.MegaMan, Boss: ElecMan }; + B.ElecMan = ElecMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/fire_man.js b/environments/games/web/games/megaman_remake/bosses/fire_man.js new file mode 100644 index 0000000000000000000000000000000000000000..d129a9b5b6ca9f54475864f30a1a9636cdd0fabb --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/fire_man.js @@ -0,0 +1,119 @@ +// Fire Man (game mode 3, fixed bank $E2E4). Port of the original state machine: +// pace keep |dx| to the player inside the band [95, 97): walk toward him at 01.20 when farther, turn and +// walk away when closer; backed into a wall he turns and walks at (and past) the player +// volley five Fire Storm waves, each followed by a 63-frame stance; after the first 15 stance frames, +// leaving the band cancels the volley; after the fifth wave he holds a pose until the player +// presses anything or leaves the band. Deviation: the original holds that pose forever while the +// player stays perfectly still; BossBench requires a boss to keep engaging, so the pose ends after +// POSE_MAX = 90 frames (1.5 s) and he resumes pacing. +// retaliate 14 frames into his 30 blink frames after a hit he starts a new volley at once +// A wave (record 1) forms at his hand for 23 frames at 00.20, then runs at 05.10 ($37 X-speed row 6). When a +// running wave passes within 8 px of the player, a fire pillar (record 4, 16 x 16) rises there at floor level +// and burns for 131 frames (anim $38, 12 slots x 11 ticks) unless the next wave puts it out. +// Tier knobs (specs/fire_man.spec.js): hp, wave/contact damage, stance length, retaliation on/off. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + var BAND_LO = 0x5F, BAND_HI = 0x61, FORM_T = 23, PILLAR_T = 131, EARLY = 15, POSE_MAX = 90; + var SEQ = ['pace', 'walk_far', 'summon', 'hold', 'spawn', 'hold', 'spawn', 'hold', 'spawn', 'hold', 'spawn', 'pose']; + + function FireMan() {} + var P = FireMan.prototype; + RM.install(P, 'fire_man', B.SPECS.fire_man); + P.reset = function (c) { this.base(c); this.n = 0; this.waves = 0; this.pillars = 0; this.volleys = 0; this.retaliations = 0; }; + P.onFight = function () { this.go(0); }; + P.go = function (n) { this.n = n; this.st = SEQ[n]; }; + P.inBand = function (d) { return d >= BAND_LO && d < BAND_HI; }; + P.hold = function () { return Math.round(this.k.hold); }; + + // record 1 (wave) at 8 px ahead, 8 px above centre; spawning a wave puts out the old pillar + P.spawnWave = function (c) { + this.face(c); + var f = this.look, p = this.spawn({ kind: 'fire_wave', x: this.x + 8 * f, y: this.y - 8, dir: f, vx: fx(0x20), + t: FORM_T, running: false, hw: 8, hh: 16, dmg: this.shotDamage() }); + if (!p) return false; + this.timer = this.hold(); this.waves++; + this.projectiles = this.projectiles.filter(function (q) { return q.kind !== 'fire_pillar'; }); + c.emit('mm_boss_wave', p.x, p.y); + return true; + }; + // pre-dispatch: a running wave within 8 px of the player raises (or moves) the pillar under it + P.tendWaves = function (c) { + for (var i = 0; i < this.projectiles.length; i++) { + var w = this.projectiles[i]; + if (w.kind !== 'fire_wave' || !w.running || Math.abs(c.body.x - w.x) >= 8) continue; + var pillar = null; + this.projectiles.forEach(function (q) { if (q.kind === 'fire_pillar') pillar = q; }); + if (pillar) { pillar.x = w.x; pillar.y = this.y + 4; pillar.t = PILLAR_T; pillar.age = 0; } + else if (this.spawn({ kind: 'fire_pillar', x: w.x, y: this.y + 4, dir: this.look, vx: 0, t: PILLAR_T, hw: 8, hh: 8, dmg: this.shotDamage() })) { + this.pillars++; c.emit('mm_boss_pillar', w.x, this.y + 4); + } + return; + } + }; + P.walkPace = function () { + this.dir = this.look; // sync facing memory + if (this.pose !== 'walk') { this.setPose('walk'); this.vx = fx(0x120); } + this.walkNoFace(); + }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + if (this.iframes === 0x10 && this.k.retaliate >= 0.5) { this.go(2); this.retaliations++; } + this.tendWaves(c); + var d; + switch (this.st) { + case 'pace': + d = this.face(c); + if (this.inBand(d)) { this.go(2); break; } + if (d < BAND_LO) this.look = -this.look; // too close: turn away + this.walkPace(); + if (this.blocked) { this.updateFacing(c); this.go(1); } + break; + case 'walk_far': + var keep = this.look; d = this.face(c); + if (d >= BAND_HI) { this.go(0); break; } + this.look = keep; this.walkNoFace(); + if (this.blocked) { this.updateFacing(c); this.go(0); } + break; + case 'summon': + this.vx = 0; this.setPose('summon'); this.volleys++; + if (this.spawnWave(c)) this.go(this.n + 1); + break; + case 'spawn': + this.vx = 0; this.setPose('summon'); + if (this.spawnWave(c)) this.go(this.n + 1); + break; + case 'hold': + if (this.timer < this.hold() - EARLY) { // original: range check once the timer is below $30 + d = this.face(c); + if (!this.inBand(d)) { this.go(0); break; } + } + if (--this.timer <= 0) this.go(this.n + 1); + break; + case 'pose': // stand down after the volley + d = this.face(c); + if (this.pose !== 'pose') { this.setPose('pose'); this.timer = POSE_MAX; } + if (!this.inBand(d) || c.body.anyInput || --this.timer <= 0) this.go(0); + break; + } + }; + + // entity pass: waves form then run; pillars burn down + P.entityPass = function () { + this.projectiles.forEach(function (p) { + if (p.kind === 'fire_wave') { + if (!p.running && p.t <= 0) { p.running = true; p.vx = fx(0x510); } // react_hyper_bomb: $36 -> $37, row 6 + else p.x += p.vx * p.dir; + } else if (p.kind === 'fire_pillar' && p.t <= 0) p.dead = true; + if (MM.offscreen(p)) p.dead = true; + }); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + P.state = function () { + return this.baseState({ n: this.n, waves: this.waves, pillars: this.pillars, volleys: this.volleys, retaliations: this.retaliations }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/fire_man'] = { title: 'Wave Keeper', Body: B.MegaMan, Boss: FireMan }; + B.FireMan = FireMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/guts_man.js b/environments/games/web/games/megaman_remake/bosses/guts_man.js new file mode 100644 index 0000000000000000000000000000000000000000..4dba6bc6978d5c3795856ce74fa9f8fcff5a9af6 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/guts_man.js @@ -0,0 +1,160 @@ +// Guts Man (game mode 5, fixed bank $E56E). Port of the original 21-entry table $E6CA: +// 5 leap a 15-frame crouch ($0641 = $1F), then straight up at 04.30 -> $19 +// $19 in the air without X speed; landing quakes, and a ceiling rock (record 3) falls into his hands +// $18 / $17 wait for that rock and the quake, 15-frame windup, throw the rock (record 2) at the player +// $16 wait for the rock to shatter; random_mod 3: 0 throw again, 1 three leaps toward, 2 a leap away +// airborne X speed 01.09; the walk tick runs only 3 of every 4 frames (x, y and gravity alike) +// landing shake_timer = $20: the land_* states wait it out, and the NMI stuns a player who is not in the jump +// pose (body_megaman.js quake(); the player's special state 2) +// The thrown rock (anim $32, 14 x 14 half size, no gravity, cannot be shot) flies at 04.00 at the player's feet and +// shatters on any tile or screen edge into 4 chunks (anim $56, 4 x 4, no gravity, no tile collision) placed at the rock's +// position + (8,8) (24,8) (8,24) (24,24): the rock path does not take off the 16 px the player's block path does. +// The ceiling rock has no contact flag: it only decorates the 23 frames before he can throw. Guts Man has no hit reaction. +// Tier knobs (specs/guts_man.spec.js): hp, rock/chunk damage, contact damage, windup frames, rock speed scale. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + // $E6CA by seq_step - 5 + var SEQ = ['leap', 'land_wait', 'airborne', 'land_b', 'airborne', 'land_a', 'airborne', 'land_rehop', 'airborne', 'land_rehop', + 'airborne', 'land_wait', 'airborne', 'land_rehop', 'airborne', 'land_roll', 'airborne', 'pattern_roll', 'throw_rock', + 'windup_rock', 'ceiling_rock']; + var LEAP_VY = fx(0x430), AIR_VX = fx(0x109), SHAKE = 0x20, ROCK_SPEED = 0x400; + // record 3 starts at anim frame byte $19 unless he stands at y $C0, which this room's floor never gives (y $B0): + // anim $32 (rate $2F) wraps after 23 renders, and the pass that sees frame 0 ends it + var CEILING_LIFE = 23, CEILING_VY = -fx(0xC0); + var CHUNKS = [[8, 8, 4, 2], [24, 8, 4, 0], [8, 24, 3, 2], [24, 24, 3, 0]]; // $F826 x, $F82A y, $F82E X speed, $F832 Y speed + + function GutsMan() {} + var P = GutsMan.prototype; + RM.install(P, 'guts_man', B.SPECS.guts_man); + var baseRender = P.renderTick; + MM.blockRoom('megaman/guts_man'); + P.reset = function (c) { + this.base(c); this.y = 0xB0; this.hw = 16; this.hh = 16; this.seq = 5; this.shake = 0; this.roll = -1; + this.leaps = 0; this.quakes = 0; this.rocks = 0; this.ceilings = 0; this.shatters = 0; + }; + P.onFight = function () { this.go(5); }; + P.go = function (n) { this.seq = n; this.st = SEQ[n - 5]; }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + this[this.st](c); + }; + // gutsman_leap: every leap starts from this crouch and goes to $19 unless the caller picks another airborne state + P.startLeap = function () { + this.windup = Math.round(this.k.windup); this.vx = 0; this.vy = LEAP_VY; this.setPose('crouch'); this.leaps++; + this.go(0x19); + }; + // gutsman_leap_away: face the player, leap, but move away from him + P.leapAway = function (c) { this.updateFacing(c); this.startLeap(); this.dir = -this.dir; this.go(0x13); }; + // gutsman_air_tick: returns true on the landing frame (one state back, the quake starts) + P.airTick = function (c) { + if (this.windup > 0 || !(c.t & 3)) return false; + this.setPose('air'); + if (!this.walkTick(c)) return false; + this.go(this.seq - 1); this.setPose('land'); this.shake = SHAKE; this.quakes++; + c.emit('mm_quake', this.x, this.y + this.hh); + return true; + }; + + // ---- states ---- + P.leap = function () { this.startLeap(); }; + P.airborne = function (c) { this.vx = AIR_VX; this.airTick(c); }; + P.land_wait = function () { if (!this.shake) this.go(5); }; + P.land_b = function (c) { if (this.shake) return; this.leapAway(c); this.go(7); }; + P.land_a = function (c) { + if (this.shake) return; + if (c.rng.int(2)) { this.leapAway(c); this.go(9); } else this.go(5); + }; + P.land_rehop = function (c) { + if (this.shake) return; + var s = this.seq; this.updateFacing(c); this.startLeap(); this.go(s - 1); + }; + P.land_roll = function (c) { + if (this.shake) return; + if (c.rng.int(2)) this.go(5); else this.leapAway(c); + }; + P.pattern_roll = function (c) { + if (this.out) return; + this.updateFacing(c); + var r = this.roll = c.rng.int(3); + if (r === 0) { this.go(5); return; } + this.startLeap(); + if (r === 1) this.go(0x0F); else { this.go(0x15); this.dir = -this.dir; } + }; + P.throw_rock = function (c) { + if (this.windup > 0) return; + var adx = this.face(c), f = this.look; this.go(0x16); + var p = this.spawn({ kind: 'rock', x: this.x + 16 * f, y: this.y - 24, dir: f, vx: 0, vy: 0, hw: 14, hh: 14, dmg: this.shotDamage() }); + if (!p) return; + // aimed from the height of the rock over his head at the player's feet (ent_y_px + 12) + var v = MM.propVel(Math.round(ROCK_SPEED * this.k.speed), adx, Math.floor(this.y) - 24 - (Math.floor(c.body.y) + 12)); + p.vx = v.vx; p.vy = v.vy; this.out++; this.rocks++; this.setPose('throw'); + c.emit('mm_boss_rock', p.x, p.y); + }; + // gutsman_windup rewrites $0641 every frame until the rock is gone and the quake over, so the 15 frames start then + P.windup_rock = function () { + if (this.out) return; + this.setPose('lift'); this.windup = Math.round(this.k.windup); + if (!this.shake) this.go(0x17); + }; + P.ceiling_rock = function (c) { + if (!this.airTick(c)) return; + this.setPose('lift'); + var p = this.spawn({ kind: 'ceiling_rock', x: this.x - 10 * this.look, y: 0x20, dir: this.look, vx: 0, vy: CEILING_VY, hw: 14, hh: 14, harmless: true, t: CEILING_LIFE, dmg: 0 }); + if (p) { this.out++; this.ceilings++; } + }; + + // react_thrown_block: $44--, the rock's slot is free for the chunks, which fill free slots from $10 + P.shatter = function (c, p) { + var self = this; + this.out = Math.max(0, this.out - 1); this.shatters++; + this.projectiles = this.projectiles.filter(function (q) { return q !== p; }); + CHUNKS.forEach(function (r) { + self.spawn({ kind: 'rock_chunk', x: p.x + r[0], y: p.y + r[1], dir: p.dir, vx: r[2], vy: r[3], hw: 4, hh: 4, dmg: self.shotDamage() }); + }); + c.emit('mm_boss_shatter', p.x, p.y); + }; + // entity_pass in slot order, so chunks spawned into a later slot than the rock's move in the same pass + P.entityPass = function (c) { + for (var slot = 16; slot < 32; slot++) this.passSlot(c, slot); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + P.passSlot = function (c, slot) { + var p = null; + this.projectiles.forEach(function (q) { if (q.slot === slot && !q.dead) p = q; }); + if (!p) return; + if (p.kind === 'ceiling_rock') { + if (p.t <= 0) { p.dead = true; this.out = Math.max(0, this.out - 1); return; } + p.y -= p.vy; p.vy = Math.max(-MM.FALL_MAX, p.vy - MM.GRAVITY); + return; + } + if (p.kind === 'rock_chunk') { + p.x += p.vx * p.dir; p.y -= p.vy; + if (MM.offscreen(p)) p.dead = true; + return; + } + // the rock: X with the wall probes, then Y with the floor probe while falling; any stop shatters it + var nx = p.x + p.vx * p.dir, lo = MM.WALL_L + p.hw, hi = MM.WALL_R - p.hw, stop = false; + if (nx < lo) { nx = lo; stop = true; } else if (nx > hi) { nx = hi; stop = true; } + if (this.room.length) { var cx = MM.clampX(this.room, p.x, nx, p.hw, p.y, p.hh); if (cx !== nx) { nx = cx; stop = true; } } + p.x = nx; + if (stop) { this.shatter(c, p); return; } + var ny = p.y - p.vy, floor = this.room.length ? MM.floorUnder(this.room, p.x - p.hw + 1, p.x + p.hw - 1, p.y + p.hh) : MM.FLOOR; + if (p.vy < 0 && ny + p.hh >= floor) { p.y = floor - p.hh; this.shatter(c, p); return; } + if (ny < MM.TOP_EXIT || ny >= MM.BOTTOM_EXIT) { this.shatter(c, p); return; } // the vertical exit keeps the old y + p.y = ny; + }; + // render: the shared counters, then the NMI: each shake frame stuns the player and counts down ($20 NMIs) + P.renderTick = function (c) { + baseRender.call(this, c); + if (this.shake > 0) { c.body.quake(); this.shake--; } + }; + P.state = function () { + return this.baseState({ seq: this.seq, shake: this.shake, roll: this.roll, leaps: this.leaps, quakes: this.quakes, + rocks: this.rocks, ceilings: this.ceilings, shatters: this.shatters }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/guts_man'] = { title: 'Quake Hurler', Body: B.MegaMan, Boss: GutsMan }; + B.GutsMan = GutsMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/ice_man.js b/environments/games/web/games/megaman_remake/bosses/ice_man.js new file mode 100644 index 0000000000000000000000000000000000000000..42e7d5045ae10a79000eb0fafa50d3e581628515 --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/ice_man.js @@ -0,0 +1,93 @@ +// Ice Man (game mode 1, fixed bank $E111). Port of the original state machine: +// walk to the waypoint $E2C8[n] (208, 168, 128, 168) at 01.20, stance (15-frame windup), hop straight up +// (04.DF); falling past y 148 / 164 / 180 he fires an Ice Slasher at each level and, with gravity switched +// off, sinks at a slow speed; he hovers $E2D8 frames (48/46/38/27), fires at the bottom, then rises back +// through 164 and 148 firing again - six slashers per cycle in a V; finally gravity returns with a 02.C0 pop +// and he lands. Every landing advances the waypoint and the pattern counter (0..9); counter / 3 picks the +// slasher speed (01.60 / 01.80 / 02.00 / 02.E0), hover time and sink speed, so the pattern speeds up. +// Ice Man has no hit reaction. Tier knobs (specs/ice_man.spec.js): hp, slasher/contact damage, slasher speed +// scale, hover scale, stance windup. +(function (g) { + var B = g.BB, BB = B, MM = B.MM, RM = MM.RobotMaster, fx = MM.fx; + var WAYPOINTS = [0xD0, 0xA8, 0x80, 0xA8]; + var SPEEDS = [fx(0x160), fx(0x180), fx(0x200), fx(0x2E0)]; + var HOVER = [0x30, 0x2E, 0x26, 0x1B]; + var SINK = [-(1 - fx(0x60)), -(1 - fx(0x50)), -(1 - fx(0x2C)), -(2 - fx(0xE0))]; // $FF.60 $FF.50 $FF.2C $FE.E0 + var DOWN = [0x94, 0xA4, 0xB4], UP = [0xA5, 0x95]; + // the 19 states of the mode 1 table, in order + var SEQ = ['leg_start', 'leg_walk', 'stance', 'hop', 'rise', 'fire', 'rise', 'fire', 'rise', 'fire', 'set_timer', + 'hover', 'fire', 'climb', 'fire', 'climb', 'fire', 'drop', 'land']; + + function IceMan() {} + var P = IceMan.prototype; + RM.install(P, 'ice_man', B.SPECS.ice_man); + P.reset = function (c) { this.base(c); this.n = 0; this.wp = 0; this.counter = 0; this.level = 0; this.volleys = 0; this.slashers = 0; }; + P.onFight = function () { this.n = 0; this.st = SEQ[0]; }; + P.next = function () { this.n++; this.st = SEQ[this.n]; }; + P.q = function () { return Math.floor(this.counter / 3); }; + + P.update = function (c) { + if (this.hp <= 0) return; + if (this.introTick()) { MM.step(this); return; } + var wx = WAYPOINTS[this.wp & 3], q = this.q(); + switch (this.st) { + case 'leg_start': + this.setPose('walk'); this.vx = fx(0x120); + this.faceTo(wx); this.dir = this.look; this.next(); break; + case 'leg_walk': + if (this.faceTo(wx) < 2) { // fire stance: anim + 1, nearly stop + this.setPose('stance'); this.windup = this.k.windup; this.vx = fx(0x10); this.next(); + } else this.walkNoFace(); + break; + case 'stance': + if (this.windup > 0) this.walkNoFace(); else this.next(); + break; + case 'hop': + this.face(c); this.vx = 0; this.vy = fx(0x4DF); this.setPose('jump'); this.level = 0; this.next(); break; + case 'rise': // falling past the next level: sink slowly + this.walkTick(c); + if (this.vy < 0 && this.y >= DOWN[this.level]) { this.vy = SINK[q]; this.grav = false; this.level++; this.next(); } + break; + case 'fire': + this.face(c); this.fireSlasher(c, q); this.next(); break; + case 'set_timer': + this.timer = Math.round(HOVER[q] * this.k.hover); this.next(); break; + case 'hover': + this.updateFacing(c); + if (--this.timer <= 0) { this.vy = -this.vy; this.level = 0; this.next(); } + break; + case 'climb': + this.walkTick(c); + if (this.y < UP[this.level]) { this.level++; this.next(); } + break; + case 'drop': + this.grav = true; this.vy = fx(0x2C0); this.next(); break; + case 'land': + if (this.walkTick(c)) { + if (this.counter < 9) this.counter++; + this.wp = (this.wp + 1) & 3; this.volleys++; + this.n = 0; this.st = SEQ[0]; + } + break; + } + }; + // record 5: Ice Slasher 2 px above centre, 8 px ahead, speed $E2CC[counter / 3] + P.fireSlasher = function (c, q) { + var f = this.look; + var p = this.spawn({ kind: 'ice_slasher', x: this.x + 8 * f, y: this.y - 2, dir: f, vx: SPEEDS[q] * this.k.speed, + hw: 4, hh: 4, dmg: this.shotDamage() }); + if (p) { this.slashers++; c.emit('mm_boss_slasher', p.x, p.y); } + this.setPose('shoot'); + }; + P.entityPass = function () { + this.projectiles.forEach(function (p) { p.x += p.vx * p.dir; if (MM.offscreen(p)) p.dead = true; }); + this.projectiles = this.projectiles.filter(function (p) { return !p.dead; }); + }; + P.state = function () { + return this.baseState({ n: this.n, waypoint: this.wp, counter: this.counter, level: this.level, + volleys: this.volleys, slashers: this.slashers }); + }; + B.CASES = B.CASES || {}; + BB.CASES['megaman/ice_man'] = { title: 'V Gunner', Body: B.MegaMan, Boss: IceMan }; + B.IceMan = IceMan; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/bosses/robot_master.js b/environments/games/web/games/megaman_remake/bosses/robot_master.js new file mode 100644 index 0000000000000000000000000000000000000000..8e2b160271080e524589b65f913b74ad576780fd --- /dev/null +++ b/environments/games/web/games/megaman_remake/bosses/robot_master.js @@ -0,0 +1,90 @@ +// Shared parts of a Robot Master fight (boss_fight_controller $DB8C and the fixed-bank boss services $EDC2-$EF36). +// A boss keeps two facings like the original: `look` is the sprite flip ($0421 bit 6, set by boss_face_player) +// and `dir` is the movement memory ($43 bit 6, copied from the flip by boss_update_facing). Bosses stand at +// x $C0 / y $B4 when the fight starts ($ED9A/$EDA3), have gravity, and blink for a per-mode number of frames after +// every hit, during which the player's shots pass through ($C994). The intro locks the player's input while the +// boss drops in and its bar fills (one unit every other frame, boss_hp_fill_tick $F39B). +(function (g) { + var B = g.BB, MM = B.MM; + // intro timer $5E = 94 frames from the drop-in to the fight (boss_fight_controller $DB8C); the bar fills one unit + // every other frame once the timer is below $3A, i.e. 28 units over the last 56 frames + var DROP = 0x5E - 0x3A + 2, FILL = 0x3A - 2; + + var RM = MM.RobotMaster = {}; + RM.install = function (P, id, spec) { + P.id = id; P.spec = spec; P.info = MM.ROBOT_MASTERS[id]; + P.base = function (c) { + var k = this.k = MM.knobs(spec, c.d); + this.room = MM.roomOf(c.id); + this.x = 0xC0; this.y = 0xB4; this.vx = 0; this.vy = 0; this.dir = -1; this.look = -1; + this.hw = 8; this.hh = 12; this.grav = true; this.grounded = true; this.blocked = false; this.landed = false; + this.max_hp = this.hp = Math.round(k.hp) * MM.UNIT; + this.iframes = 0; this.intro = DROP + FILL; this.fight = false; + this.projectiles = []; this.nextId = 1; this.out = 0; + this.windup = 0; this.pose = 'stand'; this.poseT = 0; this.timer = 0; + this.st = 'intro'; this.hitsBy = {}; this.damageBy = {}; this.lastHit = null; + this.dmg = MM.CONTACT * MM.UNIT; + }; + P.introTick = function () { + if (this.intro <= 0) return false; + this.intro--; + if (this.intro === 0) { this.fight = true; this.onFight(); } + return true; + }; + P.hitBox = function () { return MM.box(this.x, this.y, this.hw, this.hh); }; + P.bodyBox = P.hitBox; + P.contactDamage = function () { return Math.round(this.k.contact * MM.UNIT); }; + P.shotDamage = function () { return Math.round(this.k.shot * MM.UNIT); }; + // boss_face_player: sprite flip toward px (default: the player), returns |dx| in whole pixels (the original + // subtracts the integer pixel bytes, so band and arrival checks are integer comparisons) + P.faceTo = function (px) { var d = Math.floor(px) - Math.floor(this.x); this.look = d >= 0 ? 1 : -1; return Math.abs(d); }; + P.face = function (c) { return this.faceTo(c.body.x); }; + P.updateFacing = function (c, px) { this.faceTo(px == null ? c.body.x : px); this.dir = this.look; }; + P.walkNoFace = function () { MM.step(this); return this.landed; }; + P.walkTick = function (c) { this.face(c); return this.walkNoFace(); }; + P.setPose = function (name) { if (this.pose !== name) { this.pose = name; this.poseT = 0; } }; + P.spawn = function (p) { + var slot = MM.freeSlot(this.projectiles); + if (slot < 0) return null; + p.slot = slot; p.id = this.nextId++; p.age = 0; this.projectiles.push(p); return p; + }; + // shot hit on the boss ($C8B2): damage from the table (0 still blinks), lethal hits end the fight + P.takeHit = function (c, w, sx, sy) { + var units = MM.DAMAGE[id][w] || 0, dmg = units * MM.UNIT; + this.hitsBy[w] = (this.hitsBy[w] || 0) + 1; this.damageBy[w] = (this.damageBy[w] || 0) + dmg; + this.lastHit = { t: c.t, w: w, units: units }; + if (dmg >= this.hp) { + this.hp = 0; this.st = 'dead'; this.fight = false; this.projectiles = []; + c.emit('mm_boss_dead', this.x, this.y); return; + } + this.hp -= dmg; this.iframes = this.info.iframes; + c.emit(units ? 'mm_hit' : 'mm_clank', sx, sy); + if (this.onHit) this.onHit(c, w); + }; + // render-time counters: the blink ($56 is ticked by draw_entity), anim-control windups, pose clocks + P.renderTick = function () { + if (this.iframes > 0) this.iframes--; + if (this.windup > 0) this.windup--; + this.poseT++; + this.projectiles.forEach(function (p) { if (p.t != null) p.t--; p.age++; }); + }; + P.baseState = function (extra) { + var o = { x: this.x, y: this.y, vx: this.vx, vy: this.vy, dir: this.dir, look: this.look, grav: this.grav, + grounded: this.grounded, hp: this.hp, max_hp: this.max_hp, iframes: this.iframes, intro: this.intro, + fight: this.fight, fsm: this.st, timer: this.timer, windup: this.windup, pose: this.pose, pose_t: this.poseT, + out: this.out, projectiles: this.projectiles, next_id: this.nextId, hits_by: this.hitsBy, + damage_by: this.damageBy, last_hit: this.lastHit }; + Object.keys(extra || {}).forEach(function (key) { o[key] = extra[key]; }); + return MM.snapshot(o); + }; + // the shared Case wiring (default interact() is replaced by the body's resolveInteractions) + P.onNailHit = function () { return null; }; + P.hazards = function () { + if (this.hp <= 0) return []; + var out = [{ kind: id + '_body', box: { x: this.x, y: this.y, w: this.hw * 2, h: this.hh * 2 }, dmg: this.contactDamage() }]; + this.projectiles.forEach(function (p) { if (!p.harmless) out.push({ kind: p.kind, box: { x: p.x, y: p.y, w: p.hw * 2, h: p.hh * 2 }, dmg: p.dmg }); }); + return out; + }; + }; + RM.INTRO = DROP + FILL; RM.DROP = DROP; RM.FILL = FILL; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/compact_actions.json b/environments/games/web/games/megaman_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..15fb166cafa09cf670ee69601ee970f09e0c2bc6 --- /dev/null +++ b/environments/games/web/games/megaman_remake/compact_actions.json @@ -0,0 +1,373 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "megaman_remake", + "version": "megaman-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "left_half", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [], + [] + ] + }, + { + "label": "right_half", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [], + [] + ] + }, + { + "label": "left_4", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [] + ] + }, + { + "label": "right_4", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [] + ] + } + ] + }, + { + "name": "jump", + "options": [ + { + "label": "none" + }, + { + "label": "hold", + "keys": [ + "Space" + ] + }, + { + "label": "tap", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "from_2", + "subs": [ + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "from_3", + "subs": [ + [], + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "from_4", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "from_5", + "subs": [ + [], + [], + [], + [], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "at_6", + "subs": [ + [], + [], + [], + [], + [], + [ + "Space" + ] + ] + }, + { + "label": "first_2", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [], + [] + ] + }, + { + "label": "first_5", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [] + ] + }, + { + "label": "first_3", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "first_4", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "tap_rehold", + "subs": [ + [ + "Space" + ], + [], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ] + ] + }, + { + "label": "tap_tap6", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [], + [ + "Space" + ] + ] + }, + { + "label": "tap_hold5", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [ + "Space" + ], + [ + "Space" + ] + ] + } + ] + }, + { + "name": "fire", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "subs": [ + [ + "J" + ], + [], + [ + "J" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "next_weapon", + "tap": [ + "E" + ] + }, + { + "label": "prev_weapon", + "tap": [ + "Q" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/megaman_remake/data/weapons.js b/environments/games/web/games/megaman_remake/data/weapons.js new file mode 100644 index 0000000000000000000000000000000000000000..17ce2be7fa23933359c0fc49018ae10dc4cef93e --- /dev/null +++ b/environments/games/web/games/megaman_remake/data/weapons.js @@ -0,0 +1,62 @@ +// Data-driven weapon x boss tables of Mega Man (NES, 1987), transcribed from the ROM via the annotated +// disassembly (plasticsmoke/megaman1-disassembly-ca65 @2771fb3): +// $FDEE weapon damage vs boss, 8 weapons (P C I B F E G M) x game mode (0 Cut 1 Ice 2 Bomb 3 Fire 4 Elec 5 Guts) +// $C994 boss post-hit invulnerability frames per mode +// $FEBB damage a boss projectile deals per mode; boss body contact is a flat 4 (player_contact_service) +// $A8DE weapon energy units per shot ($A8D7 shots-per-charge is 1 for every weapon) +// The built flag identifies available weapons. +(function (g) { + var MM = g.BB.MM; + MM.WEAPON_ORDER = ['P', 'C', 'I', 'B', 'F', 'E', 'G', 'M']; + MM.WEAPONS = { + P: { name: 'Arm Gun', zh: 'Arm Gun', from: null, cost: 0, built: true }, + C: { name: 'Return Blade', zh: 'Returning blade', from: 'cut_man', cost: 1, built: true }, + I: { name: 'Pierce Dart', zh: 'Pierce Dart', from: 'ice_man', cost: 1, built: true }, + B: { name: 'Fuse Lob', zh: 'Fuse Lob', from: 'bomb_man', cost: 2, built: true }, + F: { name: 'Orbit Guard', zh: 'Orbit Guard', from: 'fire_man', cost: 1, built: true }, + E: { name: 'Tri Arc', zh: 'Tri Arc', from: 'elec_man', cost: 1, built: true }, + G: { name: 'Block Toss', zh: 'Boulder throw', from: 'guts_man', cost: 2, built: true }, + M: { name: 'Bridge Ray', zh: 'Bridge Ray', from: null, cost: 2, built: false } + }; + MM.ROBOT_MASTERS = { + cut_man: { mode: 0, zh: 'Blade Tosser', en: 'BLADE TOSSER', weapon: 'C', iframes: 0x3F, shot: 4 }, + ice_man: { mode: 1, zh: 'V Gunner', en: 'V GUNNER', weapon: 'I', iframes: 0x1E, shot: 10 }, + bomb_man: { mode: 2, zh: 'Shard Lobber', en: 'SHARD LOBBER', weapon: 'B', iframes: 0x1E, shot: 4 }, + fire_man: { mode: 3, zh: 'Wave Keeper', en: 'WAVE KEEPER', weapon: 'F', iframes: 0x1E, shot: 4 }, + elec_man: { mode: 4, zh: 'Pouncer', en: 'POUNCER', weapon: 'E', iframes: 0x3F, shot: 10 }, + guts_man: { mode: 5, zh: 'Quake Hurler', en: 'QUAKE HURLER', weapon: 'G', iframes: 0x1E, shot: 4 } + }; + MM.CONTACT = 4; + // P C I B F E G M + var ROWS = { + cut_man: [3, 1, 0, 2, 3, 1, 14, 0], + ice_man: [1, 2, 0, 4, 1, 10, 0, 0], + bomb_man: [2, 2, 0, 1, 4, 2, 0, 0], + fire_man: [2, 2, 4, 1, 1, 1, 0, 0], + elec_man: [1, 10, 0, 2, 1, 1, 4, 0], + guts_man: [2, 1, 0, 10, 2, 1, 1, 0] + }; + MM.DAMAGE = {}; + Object.keys(ROWS).forEach(function (boss) { + var row = MM.DAMAGE[boss] = {}; + MM.WEAPON_ORDER.forEach(function (w, i) { row[w] = ROWS[boss][i]; }); + }); + // the boss a weapon is strongest against (ties are impossible in the table) + MM.weakTo = function (boss) { + var row = MM.DAMAGE[boss], best = 'P'; + MM.WEAPON_ORDER.forEach(function (w) { if (row[w] > row[best]) best = w; }); + return best; + }; + // reset option {weapons: ['E', 'I', ...]}: weapons won from earlier bosses (the Buster is always owned) + MM.loadout = function (options) { + var list = (options && options.weapons) || [], out = ['P']; + if (!Array.isArray(list)) throw new Error('options.weapons must be a list of weapon letters'); + list.forEach(function (w) { + w = String(w).toUpperCase(); + if (!MM.WEAPONS[w]) throw new Error('unknown weapon ' + JSON.stringify(w) + ' (use ' + MM.WEAPON_ORDER.join(' ') + ')'); + if (!MM.WEAPONS[w].built) throw new Error('weapon ' + w + ' (' + MM.WEAPONS[w].name + ') is not implemented in this build'); + if (out.indexOf(w) < 0) out.push(w); + }); + return MM.WEAPON_ORDER.filter(function (w) { return out.indexOf(w) >= 0; }); + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/compose.js b/environments/games/web/games/megaman_remake/draw/compose.js new file mode 100644 index 0000000000000000000000000000000000000000..fe4a17c1d1e5062398938544dfed11d12dfe7496 --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/compose.js @@ -0,0 +1,83 @@ +// Frame compositor for Mega Man: every frame is drawn at the NES's native 256x240 into an offscreen canvas with +// integer-pixel rects only, then scaled 2x (nearest neighbour) into the middle of the 854x480 frame. The side +// panels carry the readable HUD (weapon menu, bars, boss, timer, tier, native Hz); the original's vertical +// energy bars are also drawn inside the room where the NES put them. The shared renderer's layer hooks are +// routed here (BODY_DRAW.megaman.fullHud runs last and owns the whole picture), so one pass draws the room in +// the original's order: background, boss shots, boss, player shots, player, effects, HUD bars. +// Pure presentation: reads the case, never writes it; effects are a function of (event tick, current tick). +(function (g) { + var B = g.BB, MM = B.MM, P = MM.PAL, S = MM.SCREEN; + var low = null, lx = null; + function lowCanvas(doc) { + if (!low) { low = doc.createElement('canvas'); low.width = 256; low.height = 240; lx = low.getContext('2d'); } + return lx; + } + function px(x, X, Y, w, h, col) { x.fillStyle = col; x.fillRect(Math.round(X), Math.round(Y), w, h); } + MM.px = px; + + // ---------- effects from the event log (deterministic: age = c.t - e.t) ---------- + function recent(c, names, maxAge, fn) { + for (var i = c.events.length - 1; i >= 0; i--) { + var e = c.events[i]; if (c.t - e.t > maxAge) break; + if (names.indexOf(e.name) >= 0) fn(e, c.t - e.t); + } + } + function effects(x, c) { + recent(c, ['mm_hit', 'mm_clank'], 8, function (e, a) { // hit spark (anim $19) + var col = e.name === 'mm_clank' ? P.light : P.white, r = 2 + a; + px(x, e.x - r, e.y - 1, r * 2, 2, col); px(x, e.x - 1, e.y - r, 2, r * 2, col); + }); + recent(c, ['mm_hurt'], 10, function (e, a) { // the player's hit spark (knockback entry) + var r = 4 + a; px(x, e.x - r, e.y - 1, r * 2, 2, P.white); px(x, e.x - 1, e.y - r, 2, r * 2, P.white); + px(x, e.x - r + 2, e.y - r + 2, 3, 3, P.yellow); px(x, e.x + r - 5, e.y + r - 5, 3, 3, P.yellow); + }); + recent(c, ['mm_land'], 6, function (e, a) { // landing dust + px(x, e.x - 6 - a, e.y - 2, 3, 2, P.light); px(x, e.x + 3 + a, e.y - 2, 3, 2, P.light); + }); + recent(c, ['mm_boss_dead', 'mm_player_dead'], 120, function (e, a) { // 8-orb radial burst (two speeds) + for (var k = 0; k < 16; k++) { + var ang = k * Math.PI / 8, sp = k < 8 ? 1.5 : 0.75, r = 6 + a * sp, ox = e.x + Math.cos(ang) * r, oy = e.y + Math.sin(ang) * r; + if (oy < 0 || oy > 240) continue; + var ph = (a >> 2) & 1, col = e.name === 'mm_boss_dead' ? (ph ? P.white : P.yellow) : (ph ? P.white : P.sky); + px(x, ox - 3, oy - 3, 6, 6, col); px(x, ox - 1, oy - 1, 2, 2, ph ? P.yellow : P.white); + } + }); + } + + // ---------- NES-style vertical bars (28 units, 7 cells of 4) ---------- + function bar(x, X, units, fill) { + px(x, X, 16, 8, 57, P.black); + for (var u = 0; u < MM.BAR; u++) { + var yy = 16 + 56 - (u + 1) * 2; + if (u < units) { px(x, X + 1, yy + 1, 6, 1, fill); px(x, X + 3, yy + 1, 2, 1, P.white); } + } + } + + function compose(x, c, t) { + var doc = x.canvas.ownerDocument || g.document, L = lowCanvas(doc), bossDraw = B.BOSS_DRAW[c.id]; + L.setTransform(1, 0, 0, 1, 0, 0); + MM.drawRoom(L, c, t); + if (bossDraw && bossDraw.projectiles) bossDraw.projectiles(L, c, t); + if (bossDraw && bossDraw.boss) bossDraw.boss(L, c, t); + MM.drawPlayerShots(L, c, t); + MM.drawPlayer(L, c, t); + effects(L, c); + var b = c.body, o = c.boss, R = MM.RobotMaster; + bar(L, 24, Math.ceil(MM.BAR * b.hp / b.max_hp), P.gold); // life bar + if (b.weapon !== 'P') bar(L, 16, b.energy[b.weapon] || 0, MM.weaponColor(b.weapon)); + // boss bar: the whole tier bar mapped onto 28 cells; it fills during the intro like boss_hp_fill_tick + var fillK = o.fight || o.hp <= 0 ? 1 : Math.max(0, Math.min(1, 1 - o.intro / R.FILL)); + if (o.fight || o.intro < R.FILL || o.hp <= 0) bar(L, 40, Math.ceil(MM.BAR * fillK * o.hp / o.max_hp), P.orange); + x.save(); x.setTransform(1, 0, 0, 1, 0, 0); x.imageSmoothingEnabled = false; + // the quake moves the picture: PPUSCROLL + $D583/$D588[(timer / 2) & 3] on odd timer values, nothing on even ones (o.shake has + // already counted this frame down); a positive scroll moves the picture the other way, and the side panels cover the edges + var sh = o.shake > 0 ? o.shake + 1 : 0, ph = sh & 1 ? (sh >> 1) & 3 : 4; + if (ph !== 4) { x.fillStyle = '#000000'; x.fillRect(S.OX, S.OY, 256 * S.SCALE, 240 * S.SCALE); } + x.drawImage(low, S.OX - [0, 8, 0, -8, 0][ph] * S.SCALE, S.OY - [-24, 0, 8, 0, 0][ph] * S.SCALE, 256 * S.SCALE, 240 * S.SCALE); + x.restore(); + } + MM.compose = compose; + MM.weaponColor = function (w) { + return { P: P.sky, E: P.yellow, I: P.ice, F: P.ember, C: P.light, B: P.green, G: P.orange, M: P.red }[w] || P.white; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/hud.js b/environments/games/web/games/megaman_remake/draw/hud.js new file mode 100644 index 0000000000000000000000000000000000000000..f1b85bf1096a375719be5c72e24e5cc0fe42f971 --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/hud.js @@ -0,0 +1,78 @@ +// HUD side panels around the 512x480 room: left = player (life, weapon menu with energy, counter chain hint), +// right = boss (name, health in points and NES units, state, timer, tier, native Hz). The whole picture is drawn +// by BODY_DRAW.megaman.fullHud, which the shared renderer calls last (renderer.js hud()). +(function (g) { + var B = g.BB, MM = B.MM, P = MM.PAL, S = MM.SCREEN; + var W = 854, H = 480, L = S.OX, R = S.OX + 512; + var FONT = '"Press Start 2P", "Lucida Console", Consolas, monospace'; + function txt(x, s, X, Y, col, size, align) { + x.font = (size || 11) + 'px ' + FONT; x.textAlign = align || 'left'; x.textBaseline = 'alphabetic'; + x.fillStyle = '#000000'; x.fillText(s, X + 1, Y + 1); x.fillStyle = col || '#fcfcfc'; x.fillText(s, X, Y); + } + function hbar(x, X, Y, w, frac, col) { + x.fillStyle = '#000000'; x.fillRect(X, Y, w, 10); + x.fillStyle = '#202020'; x.fillRect(X + 1, Y + 1, w - 2, 8); + var n = 28, cw = (w - 2) / n, k = Math.round(frac * n); + for (var i = 0; i < k; i++) { x.fillStyle = col; x.fillRect(X + 1 + i * cw, Y + 1, cw - 1, 8); x.fillStyle = 'rgba(255,255,255,.55)'; x.fillRect(X + 1 + i * cw, Y + 2, cw - 1, 2); } + } + function panel(x, X) { + x.fillStyle = '#0c0c18'; x.fillRect(X, 0, 171, H); + x.fillStyle = '#1c1c34'; for (var y = 0; y < H; y += 4) x.fillRect(X, y, 171, 1); + x.fillStyle = '#3c3c64'; x.fillRect(X === 0 ? 169 : X, 0, 2, H); + } + function hud(x, c, V, extra) { + var b = c.body, o = c.boss, G = B.GAME; + MM.VIEW_LAST = c; // read-only handle for page tests (never written back) + MM.compose(x, c, c.t / B.FPS); + x.save(); x.setTransform(1, 0, 0, 1, 0, 0); + panel(x, 0); panel(x, R); + // ---- left: player ---- + txt(x, 'BLUE GUNNER', 12, 26, '#3cbcfc', 12); + txt(x, 'LIFE ' + b.hp + '/' + b.max_hp, 12, 46, '#fcfcfc', 9); + hbar(x, 12, 52, 146, b.hp / b.max_hp, '#fce0a8'); + txt(x, 'WEAPON (Q/E)', 12, 84, '#bcbcbc', 9); + MM.WEAPON_ORDER.forEach(function (w, i) { + if (b.weapons.indexOf(w) < 0) return; + var row = b.weapons.indexOf(w), Y = 100 + row * 34, on = w === b.weapon, info = MM.WEAPONS[w]; + if (on) { x.fillStyle = '#28285c'; x.fillRect(6, Y - 12, 158, 32); x.fillStyle = MM.weaponColor(w); x.fillRect(6, Y - 12, 3, 32); } + txt(x, w + ' ' + info.name.toUpperCase(), 14, Y, on ? MM.weaponColor(w) : '#7c7c7c', 8); + if (w === 'P') txt(x, 'UNLIMITED', 14, Y + 14, '#7c7c7c', 7); + else hbar(x, 14, Y + 5, 140, (b.energy[w] || 0) / MM.BAR, MM.weaponColor(w)); + }); + var dmg = MM.DAMAGE[o.id][b.weapon], best = MM.weakTo(o.id), bestHave = b.weapons.indexOf(best) >= 0; + txt(x, 'VS ' + MM.ROBOT_MASTERS[o.id].en + ': ' + dmg + ' / HIT', 12, 380, dmg >= 4 ? '#f8b800' : dmg === 0 ? '#f87858' : '#bcbcbc', 8); + txt(x, 'WEAK: ' + MM.WEAPONS[best].name.toUpperCase() + (bestHave ? '' : ' (X)'), 12, 396, '#7c7c7c', 7); + txt(x, 'A/D MOVE SPACE JUMP', 12, 444, '#5c5c7c', 7); + txt(x, 'J / LMB FIRE P PAUSE', 12, 458, '#5c5c7c', 7); + // ---- right: boss ---- + var info2 = MM.ROBOT_MASTERS[o.id], name = info2.en; + txt(x, name, R + 12, 26, '#f87858', 12); + txt(x, (info2.zh || '') , R + 12, 44, '#bcbcbc', 10); + txt(x, o.hp + '/' + o.max_hp, R + 12, 64, '#fcfcfc', 9); + hbar(x, R + 12, 70, 146, o.max_hp ? o.hp / o.max_hp : 0, '#f87858'); + txt(x, 'NES ' + Math.ceil(o.hp / MM.UNIT) + '/' + Math.round(o.max_hp / MM.UNIT) + ' UNITS', R + 12, 96, '#7c7c7c', 7); + txt(x, 'STATE ' + String(o.st).toUpperCase(), R + 12, 116, '#bcbcbc', 8); + // pattern position, the Robot Masters' equivalent of a phase (all read from the boss state) + var phase = o.id === 'elec_man' ? 'WALL POS ' + ((o.step & 3) + 1) + '/4' + : o.id === 'ice_man' ? 'SPEED LV ' + (Math.floor(o.counter / 3) + 1) + '/4' + : o.id === 'cut_man' ? 'BLADE ' + (o.cut === 0 ? 'HOME' : o.cut === 1 ? 'OUT' : 'BACK') + ' / ' + o.throws + ' THROWN' + : o.id === 'bomb_man' ? 'BOMBS ' + o.out + ' OUT / ' + o.bursts + ' BURST' + : o.id === 'guts_man' ? (b.stunT > 0 ? 'STUNNED ' + b.stunT : 'QUAKES ' + o.quakes + ' / ROCKS ' + o.rocks) + : 'VOLLEY ' + (o.n >= 2 ? Math.min(5, Math.floor((o.n - 2) / 2) + 1) : 0) + '/5'; + txt(x, phase, R + 12, 132, '#bcbcbc', 8); + var secs = c.t / B.FPS, mm = Math.floor(secs / 60), ss = Math.floor(secs % 60), cs = Math.floor((secs * 10) % 10); + txt(x, 'TIME ' + mm + ':' + (ss < 10 ? '0' : '') + ss + '.' + cs, R + 12, 150, '#fcfcfc', 10); + var tier = null; if (G.tiers) Object.keys(G.tiers).forEach(function (k) { if (Math.abs(G.tiers[k] - c.d) < 1e-9) tier = k; }); + txt(x, (tier ? tier.toUpperCase() : 'D=' + c.d.toFixed(2)), R + 12, 172, '#f8b800', 10); + txt(x, (G.hz || B.FPS) + 'Hz', R + 158, 466, '#3cbcfc', 12, 'right'); + txt(x, 'NES 1987 RULES', R + 12, 444, '#5c5c7c', 7); + if (extra) txt(x, extra, R + 12, 200, '#f8b800', 8); + // ---- banners over the room ---- + if (o.intro > 0 && !c.result) txt(x, 'READY', W / 2, 220, (c.t >> 3) & 1 ? '#fcfcfc' : '#3cbcfc', 18, 'center'); + if (c.result === 'win') { txt(x, 'BOSS DEFEATED', W / 2, 200, '#f8b800', 18, 'center'); txt(x, 'YOU GOT ' + MM.WEAPONS[info2.weapon].name.toUpperCase(), W / 2, 232, '#fcfcfc', 11, 'center'); } + else if (c.result === 'loss') txt(x, 'GAME OVER', W / 2, 220, '#f87858', 18, 'center'); + else if (c.result === 'timeout') txt(x, 'TIME UP', W / 2, 220, '#f87858', 18, 'center'); + x.restore(); + } + B.BODY_DRAW.megaman = { draw: function () {}, fullHud: hud }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/palette.js b/environments/games/web/games/megaman_remake/draw/palette.js new file mode 100644 index 0000000000000000000000000000000000000000..261fccbdced8254e4c6bcc5d7bd765225c6a1390 --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/palette.js @@ -0,0 +1,22 @@ +// Original procedural NES-style art for the three Robot Master rooms (no ROM graphics are used or shipped). +// The renderer maps NES pixels to the 854x480 frame with an integer 2x scale: the 256x240 room is drawn at +// 512x480, centred with 171 px side panels that carry the HUD (weapon menu, bars, timer, native Hz). +// Pure presentation: reads the case, never writes it; animation uses presentation time t only. +(function (g) { + var B = g.BB, A = B.ART, MM = B.MM, V = B.VIEW; + var SCALE = 2, OX = 171, OY = 0; + // the shared renderer computed its own layout from BB.ARENA; replace it with the NES room mapping + V.S = SCALE; V.OX = OX; V.FLOOR = OY + MM.FLOOR * SCALE; + V.sx = function (x) { return OX + x * SCALE; }; + V.sy = function (y) { return OY + y * SCALE; }; + V.PAL = { boss: '#3c7cf0', tele: '#f8d878' }; + // NES-like master palette subset (hand-picked RGB, not copied from any emulator palette file) + var NES = MM.PAL = { + black: '#000000', white: '#fcfcfc', grey: '#7c7c7c', light: '#bcbcbc', + blue: '#0078f8', sky: '#3cbcfc', navy: '#0000bc', cyan: '#00e8d8', skin: '#fcd8a8', + red: '#d82800', orange: '#f87858', yellow: '#f8b800', gold: '#fce0a8', green: '#00b800', teal: '#008888', + purple: '#6844fc', ice: '#a4e4fc', frost: '#e4f8fc', fire: '#f83800', ember: '#fca044', brick: '#a81000' + }; + MM.SCREEN = { SCALE: SCALE, OX: OX, OY: OY }; + A.view = { W: 854, H: 480, OX: OX, FLOOR: V.FLOOR, ROOF: OY, S: SCALE }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/player.js b/environments/games/web/games/megaman_remake/draw/player.js new file mode 100644 index 0000000000000000000000000000000000000000..3bf3baa1739ecd0ee6eb967c4e491435ec537411 --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/player.js @@ -0,0 +1,130 @@ +// Original NES-style pixel sprites for Mega Man and the shots, drawn at native resolution (1 unit = 1 NES pixel). +// Shapes are hand-authored here as small character grids; they are not traced from any Capcom sprite sheet. +(function (g) { + var B = g.BB, MM = B.MM, P = MM.PAL, px = MM.px; + // grid painter: each string row is one pixel row; '.' = transparent, other chars index the colour map. + // With `dup` (row indexes to draw twice) the trailing blank rows are dropped and the picture is bottom-aligned + // to a 24-pixel box starting at Y, so a stretched figure stands exactly on the floor line of its hitbox. + function sprite(x, rows, map, X, Y, flip, dup) { + if (dup) { + var keep = rows.slice(), out = []; + while (keep.length && !/[^.]/.test(keep[keep.length - 1])) keep.pop(); + keep.forEach(function (row, i) { out.push(row); if (dup.indexOf(i) >= 0) out.push(row); }); + Y += 24 - out.length; rows = out; + } + var w = rows[0].length; + for (var r = 0; r < rows.length; r++) { + var row = rows[r]; + for (var c = 0; c < w; c++) { + var ch = row.charAt(flip ? w - 1 - c : c); + if (ch === '.') continue; + x.fillStyle = map[ch]; x.fillRect(X + c, Y + r, 1, 1); + } + } + } + MM.sprite = sprite; + // 24 x 24 player frames (body box 16 x 24 centred); k = outline, b = dark armour, l = light armour, s = skin, + // w = eye white, e = pupil + var STAND = [ + '........kkkkk...........', '......kkbbbbbkk.........', '.....kbbbllllbbk........', '....kbbblllllllbk.......', + '....kbbllllwwwlbk.......', '....kbblswwwewwsk.......', '....kbblswwweswsk.......', '.....kbbssssssssk.......', + '......kbbsskkssk........', '.....kkbbbsssskkk.......', '....klllbbbkkbbllk......', '...kllllbbbbbbbllk......', + '...kllkllbbbbbbkllk.....', '...kssk.kbbbbbbkssk.....', '....kk..klllllbk.kk.....', '........kllklllk........', + '.......kbbbk.kbbbk......', '......kbbbbk.kbbbbk.....', '.....kbbbbbk.kbbbbbk....', '.....kkkkkkk.kkkkkkk....', + '........................', '........................', '........................', '........................']; + var SHOOT = [ + '........kkkkk...........', '......kkbbbbbkk.........', '.....kbbbllllbbk........', '....kbbblllllllbk.......', + '....kbbllllwwwlbk.......', '....kbblswwwewwsk.......', '....kbblswwweswsk.......', '.....kbbssssssssk.......', + '......kbbsskkssk........', '.....kkbbbsssskkkkkkk...', '....klllbbbkkbbllbbbbk..', '...kllllbbbbbbbllbbbbbk.', + '...kllkllbbbbbbkllbbbbk.', '...kssk.kbbbbbbk.kkkkk..', '....kk..klllllbk........', '........kllklllk........', + '.......kbbbk.kbbbk......', '......kbbbbk.kbbbbk.....', '.....kbbbbbk.kbbbbbk....', '.....kkkkkkk.kkkkkkk....', + '........................', '........................', '........................', '........................']; + var RUN = [ + '........kkkkk...........', '......kkbbbbbkk.........', '.....kbbbllllbbk........', '....kbbblllllllbk.......', + '....kbbllllwwwlbk.......', '....kbblswwwewwsk.......', '....kbblswwweswsk.......', '.....kbbssssssssk.......', + '......kbbsskkssk........', '....kkkbbbsssskk........', '...kllllbbbkkbbllk......', '..kllllkbbbbbbbllk......', + '..kssk.klbbbbbbkllk.....', '...kk..kbbbbbbkssk......', '......klllllbbkkk.......', '.....kllkkklllbk........', + '....kbbbk..kkbbbk.......', '...kbbbbk...kbbbbk......', '..kbbbbk.....kbbbbk.....', '..kkkkk.......kkkkk.....', + '........................', '........................', '........................', '........................']; + var JUMP = [ + '........kkkkk...........', '......kkbbbbbkk.....kk..', '.....kbbbllllbbk...kssk.', '....kbbblllllllbk..kllk.', + '....kbbllllwwwlbk.kllk..', '....kbblswwwewwsk.kllk..', '....kbblswwweswsk.kbk...', '.....kbbssssssssk.kbk...', + '......kbbsskkssk.kbbk...', '.....kkbbbsssskkkbbk....', '....klllbbbkkbbllbk.....', '...kllllbbbbbbbllk......', + '..kllk.kbbbbbbbbk.......', '..kssk.klllllllbk.......', '...kk..kllllllbbk.......', '......kbbbkk.kbbk.......', + '.....kbbbbk...kbbk......', '.....kbbbk.....kbbk.....', '.....kkkk.......kkk.....', '........................', + '........................', '........................', '........................', '........................']; + var HURT = [ + '...k...kkkkk...k........', '....k.kbbbbbkk.k........', '.....kbbbllllbbk........', '....kbbblllllllbk.......', + '....kbblkkllkkkbk.......', '....kbblskwkskwsk.......', '....kbblswkkswksk.......', '.....kbbssssssssk.......', + '..kk..kbsskkkssk..kk....', '.kssk.kbbbsssskk.kssk...', '.kllkkllbbbkkbbllkllk...', '..kllllbbbbbbbbllllk....', + '...kkkllbbbbbbbllkk.....', '......kbbbbbbbbk........', '.....kllllkkllllk.......', '....kbbbbk..kbbbbk......', + '...kbbbbk....kbbbbk.....', '...kkkkk......kkkkk.....', '........................', '........................', + '........................', '........................', '........................', '........................']; + function colours(w) { + var dark = { P: P.blue, E: '#a87800', I: '#0058f8', F: P.red }[w] || P.blue; + var light = { P: P.sky, E: P.yellow, I: P.frost, F: P.ember }[w] || P.sky; + return { k: P.black, b: dark, l: light, s: P.skin, w: P.white, e: P.black }; + } + MM.drawPlayer = function (x, c, t) { + var b = c.body; + if (b.hp <= 0) return; + if (b.iframes > 0 && (b.iframes & 2)) return; // blink: hidden while bit 1 of the i-frame timer is set + var frame = b.knockT > 0 || b.stunT > 0 ? HURT : !b.grounded ? JUMP : b.shootT > 0 ? SHOOT : b.speed > 0.5 ? RUN : STAND; + if (frame === RUN && (Math.floor(c.t / 8) & 1)) frame = STAND; // two-step run cycle + var map = colours(b.weapon); + // 20-row figure stretched to 22 rows (= the 14x22 touch box) and standing on the 16x24 body's floor line + sprite(x, frame, map, Math.round(b.x) - 12, Math.round(b.y) - 12, b.facing < 0, [10, 16]); + }; + + // ---------- player shots ---------- + MM.drawPlayerShots = function (x, c, t) { + var b = c.body; + b.shots.forEach(function (s) { + var X = Math.round(s.x), Y = Math.round(s.y); + if (s.kind === 'buster') { px(x, X - 3, Y - 2, 6, 4, P.yellow); px(x, X - 2, Y - 3, 4, 6, P.yellow); px(x, X - 1, Y - 1, 2, 2, P.white); } + else if (s.kind === 'slasher') MM.drawSlasher(x, s, 8); + else if (s.kind === 'fire_wave' || s.kind === 'fire_shield') MM.drawFlame(x, X, Y + 8, 16, 16, c.t >> 2, false); + else if (s.kind === 'thunder' || s.kind === 'thunder_v') MM.drawBolt(x, s, c.t, true); + else if (s.kind === 'cutter') MM.drawCutter(x, X, Y, c.t, s.hw); + else if (s.kind === 'hyper_bomb') MM.drawBomb(x, X, Y, c.t, s.fuse > 110); + else if (s.kind === 'hyper_flame') MM.drawFlame(x, X, Y + 8, 16, 16, c.t >> 1, false); + else if (s.kind === 'held_block' || s.kind === 'thrown_block') MM.drawBlock(x, X, Y, s.hw); + else if (s.kind === 'block_chunk') MM.drawChunk(x, X, Y, '#7c7c7c', '#bcbcbc'); + }); + }; + // zigzag electric segment covering the hitbox (hw x hh), flickering between two shapes + MM.drawBolt = function (x, s, tick, player) { + var X = Math.round(s.x), Y = Math.round(s.y), hw = s.hw, hh = s.hh, ph = (tick >> 1) & 1; + var core = ph ? P.white : P.yellow, edge = player ? P.yellow : P.gold, pts = [], k; + // a jagged polyline that spans the hitbox along its long axis, so the picture covers exactly what hurts + if (hh >= hw) for (k = -hh; k <= hh; k += 4) pts.push([X + (((k + hh) >> 2) & 1 ? hw - 1 : 1 - hw) * (ph ? 1 : -1), Y + k]); + else for (k = -hw; k <= hw; k += 4) pts.push([X + k, Y + (((k + hw) >> 2) & 1 ? hh - 1 : 1 - hh) * (ph ? 1 : -1)]); + for (k = 1; k < pts.length; k++) MM.seg(x, pts[k - 1][0], pts[k - 1][1], pts[k][0], pts[k][1], edge, 3); + for (k = 1; k < pts.length; k++) MM.seg(x, pts[k - 1][0], pts[k - 1][1], pts[k][0], pts[k][1], core, 1); + }; + // pixel line: squares of size w stepped along the segment + MM.seg = function (x, x0, y0, x1, y1, col, w) { + var n = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)) || 1, h = w >> 1; + x.fillStyle = col; + for (var i = 0; i <= n; i++) x.fillRect(Math.round(x0 + (x1 - x0) * i / n) - h, Math.round(y0 + (y1 - y0) * i / n) - h, w, w); + }; + // Ice Slasher: a chevron of three ice blades pointing along its flight, filling the hitbox (half = half-size) + MM.drawSlasher = function (x, s, half) { + var X = Math.round(s.x), Y = Math.round(s.y), f = s.dir || 1, h = half; + for (var r = -h; r < h; r++) { + var d = Math.abs(r + 0.5), len = Math.max(2, Math.round(2 * h - d * 1.6)), tip = f > 0 ? X + h - Math.round(d * 0.8) : X - h + Math.round(d * 0.8); + px(x, f > 0 ? tip - len : tip, Y + r, len, 1, d < 1 ? P.white : (r & 1) ? P.ice : '#3cbcfc'); + } + px(x, f > 0 ? X + h - 2 : X - h, Y - 1, 2, 2, P.white); + }; + // a flame of exactly w x h pixels standing on (X, bottom); `ph` animates the tongues + MM.drawFlame = function (x, X, bottom, w, h, ph, dim) { + var outer = dim ? '#a81000' : P.fire, mid = dim ? P.fire : P.ember, core = dim ? P.ember : P.yellow; + for (var c2 = 0; c2 < w; c2++) { + var k = Math.abs(c2 - (w - 1) / 2) / (w / 2), tongue = Math.round(h * (1 - 0.35 * k * k) - (((c2 + ph) & 3) === 0 ? 3 : 0)); + px(x, X - (w >> 1) + c2, bottom - tongue, 1, tongue, outer); + if (k < 0.75) px(x, X - (w >> 1) + c2, bottom - Math.round(tongue * 0.75), 1, Math.round(tongue * 0.75), mid); + if (k < 0.35) px(x, X - (w >> 1) + c2, bottom - Math.round(tongue * 0.45), 1, Math.round(tongue * 0.45), core); + } + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/draw/rooms.js b/environments/games/web/games/megaman_remake/draw/rooms.js new file mode 100644 index 0000000000000000000000000000000000000000..1bb1e0f903a506e5e7697d49a3d2e43b2d934d1a --- /dev/null +++ b/environments/games/web/games/megaman_remake/draw/rooms.js @@ -0,0 +1,241 @@ +// Original procedural backgrounds for the Robot Master rooms at NES resolution, and the boss sprites. +// Rooms: Elec Man's generator hall (circuit panels, conduit), Ice Man's frozen hangar (snow blocks, icicles), +// Fire Man's furnace (brick, lava glow), Bomb Man's demolition yard (girders, hazard stripes, the open roof at +// x 96-159 of the original room). Static layers are cached per case; flicker/scroll uses time only. +(function (g) { + var B = g.BB, MM = B.MM, P = MM.PAL, px = MM.px, sprite = MM.sprite; + var cache = {}; + function H(i) { var s = Math.sin(i * 91.7 + 17.3) * 43758.5453; return s - Math.floor(s); } + + function roomElec(x) { + px(x, 0, 0, 256, 240, '#000000'); + for (var cx = 0; cx < 256; cx += 32) for (var cy = 16; cy < 192; cy += 32) { // circuit panels + px(x, cx + 1, cy + 1, 30, 30, '#00285c'); px(x, cx + 3, cy + 3, 26, 26, '#00184a'); + for (var k = 0; k < 4; k++) { var lx = cx + 5 + Math.floor(H(cx * 7 + cy + k) * 20), ly = cy + 5 + k * 6; px(x, lx, ly, 6, 1, '#0058a8'); px(x, lx + 5, ly, 1, 4, '#0058a8'); } + px(x, cx + 14, cy + 14, 4, 4, '#a87800'); + } + px(x, 0, 0, 256, 16, '#202020'); for (var i = 0; i < 256; i += 8) px(x, i, 12, 6, 2, '#a87800'); + floor(x, '#585858', '#a8a8a8', '#202020'); + walls(x, '#404040', '#787878'); + } + function roomIce(x) { + px(x, 0, 0, 256, 240, '#000028'); + for (var s = 0; s < 70; s++) px(x, Math.floor(H(s) * 256), 16 + Math.floor(H(s + 99) * 170), 1, 1, s % 3 ? '#3cbcfc' : '#fcfcfc'); + for (var cx = 0; cx < 256; cx += 16) { var h = 6 + Math.floor(H(cx) * 18); for (var y = 0; y < h; y += 2) px(x, cx + 4 + (y >> 2), 16 + y, Math.max(1, 8 - y / 2), 2, y < 4 ? '#fcfcfc' : '#a4e4fc'); } + px(x, 0, 0, 256, 16, '#a4e4fc'); for (var i = 0; i < 256; i += 16) px(x, i, 0, 15, 15, '#e4f8fc'); + floor(x, '#a4e4fc', '#fcfcfc', '#3cbcfc'); + walls(x, '#3cbcfc', '#e4f8fc'); + } + function roomFire(x) { + px(x, 0, 0, 256, 240, '#280000'); + for (var cy = 16; cy < 192; cy += 8) for (var cx = ((cy >> 3) & 1) * 8; cx < 256; cx += 16) px(x, cx + 1, cy + 1, 14, 6, (cx + cy) % 48 ? '#580000' : '#781800'); + px(x, 0, 0, 256, 16, '#a81000'); for (var i = 0; i < 256; i += 16) px(x, i + 2, 4, 12, 8, '#d82800'); + floor(x, '#a81000', '#f87858', '#500000'); + walls(x, '#781800', '#d82800'); + } + function roomBomb(x) { + px(x, 0, 0, 256, 240, '#001800'); + for (var cx = 16; cx < 240; cx += 48) { // steel girders + px(x, cx, 32, 6, 160, '#005800'); px(x, cx + 1, 32, 1, 160, '#00a800'); + for (var gy = 40; gy < 192; gy += 24) { px(x, cx + 6, gy, 18, 2, '#005800'); px(x, cx + 6 + ((gy >> 3) % 3) * 4, gy + 2, 2, 10, '#004000'); } + } + for (var s = 0; s < 30; s++) px(x, 96 + Math.floor(H(s) * 64), Math.floor(H(s + 7) * 30), 1, 1, '#fcfcfc'); // sky through the roof gap + [[0, 96], [160, 96]].forEach(function (r) { + px(x, r[0], 0, r[1], 32, '#7c7c7c'); + for (var i = r[0]; i < r[0] + r[1]; i += 16) { px(x, i, 0, 16, 1, '#bcbcbc'); px(x, i + 15, 0, 1, 32, '#3c3c3c'); px(x, i, 16, 16, 1, '#3c3c3c'); } + for (var j = r[0]; j < r[0] + r[1]; j += 8) px(x, j, 28, 4, 4, '#f8b800'); // hazard stripe + }); + floor(x, '#7c7c7c', '#bcbcbc', '#3c3c3c'); + for (var k = 0; k < 256; k += 8) px(x, k, 194, 4, 2, '#f8b800'); + walls(x, '#3c3c3c', '#7c7c7c'); + } + function roomCut(x) { + px(x, 0, 0, 256, 240, '#2c1c00'); + for (var cy = 32; cy < 192; cy += 32) for (var cx = 0; cx < 256; cx += 32) { // timber frames of the logging yard + px(x, cx + 1, cy + 1, 30, 30, '#4c3000'); px(x, cx + 2, cy + 15, 28, 2, '#2c1c00'); px(x, cx + 15, cy + 2, 2, 28, '#2c1c00'); + } + px(x, 0, 0, 256, 32, '#7c5c00'); for (var i = 0; i < 256; i += 16) { px(x, i, 0, 15, 15, '#a87800'); px(x, i + 8, 16, 15, 15, '#a87800'); } + floor(x, '#7c5c00', '#d8a038', '#3c2800'); + walls(x, '#4c3000', '#a87800'); + px(x, 16, 160, 16, 32, '#3c3c3c'); px(x, 16, 160, 16, 2, '#7c7c7c'); // the solid tiles beside the wall + } + function roomGuts(x) { + px(x, 0, 0, 256, 240, '#1c1408'); + for (var cy = 0; cy < 192; cy += 16) for (var cx = ((cy >> 4) & 1) * 12; cx < 256; cx += 24) { // quarry face: offset courses of rough stone + var v = H(cx * 3 + cy); px(x, cx + 1, cy + 1, 22, 14, v < 0.33 ? '#3c2c14' : v < 0.66 ? '#30220e' : '#463418'); + px(x, cx + 3 + Math.floor(v * 12), cy + 4, 5, 1, '#5c4820'); + } + for (var tx = 40; tx < 240; tx += 64) { px(x, tx, 0, 6, 192, '#5c3c10'); px(x, tx + 1, 0, 1, 192, '#8c6420'); } // timber props + floor(x, '#5c4820', '#a88c48', '#2c2008'); + [0, 240].forEach(function (wx) { + px(x, wx, 0, 16, 192, '#463418'); + for (var y = 0; y < 192; y += 16) { px(x, wx, y, 16, 1, '#8c6c30'); px(x, wx + 15, y, 1, 16, '#000000'); } + }); + px(x, 16, 160, 16, 32, '#463418'); px(x, 16, 160, 16, 2, '#a88c48'); // the solid tiles beside the wall + } + // one liftable block (override type 2): 32 x 32 of cracked stone, also what the player carries and throws + MM.drawBlock = function (x, X, Y, h) { + px(x, X - h, Y - h, h * 2, h * 2, '#000000'); px(x, X - h + 1, Y - h + 1, h * 2 - 2, h * 2 - 2, '#7c7c7c'); + px(x, X - h + 1, Y - h + 1, h * 2 - 2, 2, '#bcbcbc'); px(x, X - h + 1, Y - h + 1, 2, h * 2 - 2, '#bcbcbc'); + px(x, X - h + 8, Y - 6, 8, 2, '#3c3c3c'); px(x, X + 2, Y + 2, 8, 2, '#3c3c3c'); + }; + // Guts Man's boulder (28 x 28 hitbox) and a chunk of it (8 x 8): every pixel of the box is drawn, so what you see is what hurts + MM.drawRock = function (x, X, Y, h, t) { + px(x, X - h, Y - h + 3, h * 2, h * 2 - 6, '#000000'); px(x, X - h + 3, Y - h, h * 2 - 6, h * 2, '#000000'); + px(x, X - h + 1, Y - h + 4, h * 2 - 2, h * 2 - 8, '#a87800'); px(x, X - h + 4, Y - h + 1, h * 2 - 8, h * 2 - 2, '#a87800'); + px(x, X - h + 4, Y - h + 3, h - 2, 3, '#f8d878'); px(x, X - 2, Y + 2, 8, 2, '#5c3c10'); px(x, X - 8, Y - 3, 5, 2, '#5c3c10'); + }; + MM.drawChunk = function (x, X, Y, a, b) { px(x, X - 4, Y - 4, 8, 8, '#000000'); px(x, X - 3, Y - 3, 6, 6, a); px(x, X - 3, Y - 3, 3, 2, b); }; + function floor(x, base, top, dark) { + px(x, 0, 192, 256, 48, base); + for (var i = 0; i < 256; i += 16) { px(x, i, 192, 16, 2, top); px(x, i + 15, 192, 1, 16, dark); px(x, i, 207, 16, 1, dark); px(x, i + 7, 208, 1, 16, dark); px(x, i, 223, 16, 1, dark); } + } + function walls(x, base, top) { + [0, 240].forEach(function (wx) { + px(x, wx, 16, 16, 176, base); + for (var y = 16; y < 192; y += 16) { px(x, wx, y, 16, 1, top); px(x, wx + 15, y, 1, 16, '#000000'); } + }); + } + var ROOMS = { 'megaman/elec_man': roomElec, 'megaman/ice_man': roomIce, 'megaman/fire_man': roomFire, 'megaman/bomb_man': roomBomb, 'megaman/cut_man': roomCut, 'megaman/guts_man': roomGuts }; + MM.drawRoom = function (x, c, t) { + var key = c.id, img = cache[key]; + if (!img) { + var doc = x.canvas.ownerDocument || g.document, cv = doc.createElement('canvas'); cv.width = 256; cv.height = 240; + ROOMS[key](cv.getContext('2d')); img = cache[key] = cv; + } + x.drawImage(img, 0, 0); + c.body.room.forEach(function (r) { if (r.block) MM.drawBlock(x, r.x0 + 16, r.y0 + 16, 16); }); // lifted blocks leave the list + if (key === 'megaman/fire_man') { // furnace glow rising from the floor seams + for (var i = 0; i < 16; i++) { var f = (Math.floor(t * 8) + i * 3) % 6; px(x, i * 16 + 6, 186 - f, 3, 2, f < 3 ? P.ember : P.fire); } + } else if (key === 'megaman/elec_man') { + var on = Math.floor(t * 6) % 8; px(x, on * 32 + 14, 30, 4, 4, P.yellow); + } + }; + + // ---------- bosses: 24 x 24 grids, k outline ---------- + var ELEC = [ + '...........kk...........', '..........kyyk..........', '.........kyyyyk.........', '........kkrrrrkk........', + '.......kddrrrrddk.......', '.......kdwwkwwkdk.......', '.......kdswswssdk.......', '.......kdssssssdk.......', + '........kdsskssk........', '......kkkdddddkkkk......', '.....kyyddkkkddyyyk.....', '....kyyyddddddddyyyk....', + '....kyykddddddddkyyk....', '....kssk.kddddddkssk....', '.....kk..kyyyyyyk.kk....', '.........kyykkyyk.......', + '........kdddk.kdddk.....', '.......kddddk.kddddk....', '......kyyyyyk.kyyyyyk...', '......kkkkkkk.kkkkkkk...', + '........................', '........................', '........................', '........................']; + var ICE = [ + '........................', '.........kkkkkk.........', '.......kkbbbbbbkk.......', '......kbbffffffbbk......', + '.....kbbfkkkkkkfbbk.....', '.....kbfkswwswwkfbk.....', '.....kbfkswesweskfbk....', '.....kbfksssssskfbk.....', + '.....kbbfkkkkkkfbbk.....', '......kbbffffffbbk......', '.....kkbbbbbbbbbbkk.....', '....kffbbbbbbbbbbffk....', + '....kffkbbbbbbbbkffk....', '....kssk.kbbbbbbkssk....', '.....kk..kffffffk.kk....', '.........kffkkffk.......', + '........kbbbk.kbbbk.....', '.......kbbbbk.kbbbbk....', '.......kffffk.kffffk....', '.......kkkkkk.kkkkkk....', + '........................', '........................', '........................', '........................']; + var FIRE = [ + '.........y..y...........', '........yoyyoy..........', '.......yooooooy.........', '.......kkookookk........', + '......kgggkkkgggk.......', '......kgwwkkwwkgk.......', '......kgwekkewkgk.......', '......kgkkkkkkkgk.......', + '.......kgggggggk........', '......kkrrrrrrrkkk......', '.....krrrrkkkrrrrrk.....', '....krrrgrrrrrgrrrrk....', + '....krrkrrrrrrrrkrrk....', '....kook.krrrrrrkook....', '.....kk..kgggggok.kk....', '.........kggkkggk.......', + '........krrrk.krrrk.....', '.......krrrrk.krrrrk....', '.......kggggk.kggggk....', '.......kkkkkk.kkkkkk....', + '........................', '........................', '........................', '........................']; + var BOMB = [ + '..........kkk...........', '.........kwwwk..........', '.........kkkkk..........', '.......kkggggkk.........', + '......kgggggggggk.......', '......kgwwkkwwkgk.......', '......kgwekkewkgk.......', '......kgkssssskgk.......', + '.......kgggggggk........', '......kkllllllllkk......', '.....kllllkkkllllk......', '....kllgllllllllgllk....', + '....kllkllllllllkllk....', '....kssk.kllllllkssk....', '.....kk..kggggggk.kk....', '.........kggkkggk.......', + '........klllk.klllk.....', '.......kllllk.kllllk....', '.......kggggk.kggggk....', '.......kkkkkk.kkkkkk....', + '........................', '........................', '........................', '........................']; + var CUT = [ + '..........k....k........', '.........krk..krk.......', '..........krkkrk........', '...........krrk.........', + '.......kkkkkkkkkk.......', '......krrrrrrrrrrk......', '......krwwkrrwwkrk......', '......krwekssewkrk......', + '.......kssssssssk.......', '......kkrrrrrrrrkkk.....', '.....krrrrkkkrrrrrk.....', '....krrrwrrrrrwrrrrk....', + '....krrkrrrrrrrrkrrk....', '....kssk.krrrrrrkssk....', '.....kk..kwwwwwwk.kk....', '.........kwwkkwwk.......', + '........krrrk.krrrk.....', '.......krrrrk.krrrrk....', '.......kwwwwk.kwwwwk....', '.......kkkkkk.kkkkkk....', + '........................', '........................', '........................', '........................']; + var MAPS = { + elec_man: { k: '#000000', y: '#f8b800', r: '#d82800', d: '#a87800', w: '#fcfcfc', s: '#fcd8a8', e: '#000000' }, + ice_man: { k: '#000000', b: '#0078f8', f: '#fcfcfc', w: '#fcfcfc', s: '#fcd8a8', e: '#000000' }, + fire_man: { k: '#000000', y: '#f8b800', o: '#f87858', r: '#d82800', g: '#7c7c7c', w: '#fcfcfc', e: '#000000' }, + bomb_man: { k: '#000000', g: '#00a800', l: '#b8f818', w: '#fcfcfc', s: '#fcd8a8', e: '#000000' }, + cut_man: { k: '#000000', r: '#d82800', w: '#fcfcfc', s: '#fcd8a8', e: '#000000' } + }; + var GRIDS = { elec_man: ELEC, ice_man: ICE, fire_man: FIRE, bomb_man: BOMB, cut_man: CUT }; + var WHITE = {}; 'kyrdwsebfogl'.split('').forEach(function (ch) { WHITE[ch] = '#fcfcfc'; }); + // bosses stand on the floor with a 16x24 body box: the 20-row grids are stretched to 24 rows by doubling the + // torso and leg rows, so the drawn body covers the hitbox exactly (feet on the floor, head at the box top) + var BOSS_DUP = [10, 11, 16, 17]; + // Guts Man fills his 32 x 32 hitbox (anims $25-$30 are 16 x 16 half size), so he is drawn from rectangles, not the 24-grid + function gutsBody(x, o, white) { + var X = Math.round(o.x), Y = Math.round(o.y), f = o.look, crouch = o.pose === 'crouch' || o.pose === 'land' ? 3 : 0, up = o.pose === 'lift' || o.pose === 'air'; + function r(rx, ry, w, h, col) { px(x, f > 0 ? X + rx : X - rx - w, Y + ry, w, h, white ? '#fcfcfc' : col); } + r(-11, 8, 10, 8, '#000000'); r(1, 8, 10, 8, '#000000'); r(-10, 9, 8, 6, '#d82800'); r(2, 9, 8, 6, '#d82800'); // boots + r(-12, -4 + crouch, 24, 13 - crouch, '#000000'); r(-11, -3 + crouch, 22, 11 - crouch, '#a81000'); r(-5, 0 + crouch, 10, 4, '#f8b800'); // torso, belt plate + r(-16, up ? -16 : -4 + crouch, 5, up ? 14 : 12, '#000000'); r(-15, up ? -15 : -3 + crouch, 3, up ? 12 : 10, '#fcd8a8'); // back arm + r(11, up ? -16 : -4 + crouch, 5, up ? 14 : 12, '#000000'); r(12, up ? -15 : -3 + crouch, 3, up ? 12 : 10, '#fcd8a8'); // front arm + r(-10, -16 + crouch, 20, 13, '#000000'); r(-9, -15 + crouch, 18, 11, '#f8b800'); r(-9, -15 + crouch, 18, 2, '#fce0a8'); // helmet + r(-2, -13 + crouch, 4, 2, '#d82800'); + r(-5, -10 + crouch, 13, 7, '#fcd8a8'); r(1, -9 + crouch, 2, 2, '#000000'); r(6, -9 + crouch, 2, 2, '#000000'); r(-3, -5 + crouch, 11, 2, '#fcfcfc'); // face, jaw + } + function bossSprite(x, c, t) { + var o = c.boss, id = o.id; + if (o.hp <= 0) return; + var R = MM.RobotMaster, since = R.INTRO - o.intro; + if (o.intro > 0 && since < 24 && ((since >> 2) & 1)) return; // the boss materialises during its intro + if (id === 'guts_man') { + if (o.pose === 'lift' && o.st === 'throw_rock') MM.drawRock(x, Math.round(o.x) + 16 * o.look, Math.round(o.y) - 24, 14, c.t); // the boulder he is about to throw + gutsBody(x, o, ((o.iframes + 1) & 2) !== 0); + return; + } + // white flash: draw_entity tests bit 1 of boss_iframes BEFORE its render-time decrement; the simulation has + // already decremented it at the end of the tick, so the pre-decrement value is iframes + 1 + if ((o.iframes + 1) & 2) { sprite(x, GRIDS[id], WHITE, Math.round(o.x) - 12, Math.round(o.y) + 12 - 24, o.look < 0, BOSS_DUP); return; } + sprite(x, GRIDS[id], MAPS[id], Math.round(o.x) - 12, Math.round(o.y) + 12 - 24, o.look < 0, BOSS_DUP); + if (id === 'bomb_man' && o.pose === 'windup') { // the bomb held over his head while he winds up + MM.drawBomb(x, Math.round(o.x) - 4 * o.look, Math.round(o.y) - 18, c.t, o.windup < 8); + } + if (o.windup > 0 && (o.pose === 'fire' || o.pose === 'stance' || o.pose === 'summon' || o.pose === 'windup')) { // telegraph glint + var gx = Math.round(o.x) + 10 * o.look, gy = Math.round(o.y) - 4; + if ((o.windup >> 1) & 1) { px(x, gx - 2, gy - 2, 4, 4, '#fcfcfc'); px(x, gx - 4, gy, 8, 1, '#fcfcfc'); px(x, gx, gy - 4, 1, 8, '#fcfcfc'); } + } + } + // every hazard is drawn to its exact hitbox (hw x hh around its centre), so what you see is what hurts + function projectiles(x, c, t) { + c.boss.projectiles.forEach(function (p) { + var X = Math.round(p.x), Y = Math.round(p.y); + if (p.kind === 'thunder_beam') MM.drawBolt(x, p, c.t, false); + else if (p.kind === 'ice_slasher') { px(x, X - 6, Y - 5, 12, 10, 'rgba(0,0,40,.55)'); MM.drawSlasher(x, p, 4); } + else if (p.kind === 'fire_wave') MM.drawFlame(x, X, Y + p.hh, p.hw * 2, p.hh * 2, (c.t >> 2) + p.id, false); // harmful while forming too + else if (p.kind === 'bomb' || p.kind === 'intro_bomb') MM.drawBomb(x, X, Y, c.t, false); + else if (p.kind === 'shrapnel' || p.kind === 'dust') MM.drawShard(x, p, c.t); + else if (p.kind === 'rolling_cutter') MM.drawCutter(x, X, Y, c.t, p.hw); + else if (p.kind === 'rock' || p.kind === 'ceiling_rock') MM.drawRock(x, X, Y, p.hw, c.t); + else if (p.kind === 'rock_chunk') MM.drawChunk(x, X, Y, '#a87800', '#f8d878'); + else if (p.kind === 'fire_pillar') { + MM.drawFlame(x, X, Y + p.hh, p.hw * 2, p.hh * 2, (c.t >> 1) + 1, p.t < 30 && (c.t & 4)); + } + }); + } + // the Rolling Cutter: open scissors spinning through four shapes, filling its hitbox + MM.drawCutter = function (x, X, Y, t, h) { + var k = (t >> 2) & 3, a = [[1, 1], [1, 0], [1, -1], [0, 1]][k], n = h + 1; + for (var i = -n; i <= n; i++) { + px(x, X + i * a[0] - 1, Y + i * a[1] - 1, 3, 3, i < 0 ? '#fcfcfc' : '#bcbcbc'); + px(x, X - i * a[1] - 1, Y + i * a[0] - 1, 3, 3, '#fcfcfc'); + } + px(x, X - 1, Y - 1, 3, 3, '#d82800'); + }; + // the boss bomb: an 8x8-radius black sphere with a fuse spark (16x16 hitbox drawn as 14 px + outline) + MM.drawBomb = function (x, X, Y, t, flash) { + px(x, X - 6, Y - 5, 12, 12, '#000000'); px(x, X - 7, Y - 3, 14, 8, '#000000'); px(x, X - 5, Y - 7, 10, 2, '#000000'); + px(x, X - 5, Y - 4, 10, 9, flash && (t & 2) ? '#fcfcfc' : '#3c3c3c'); px(x, X - 3, Y - 3, 3, 2, '#bcbcbc'); + px(x, X + 1, Y - 9, 2, 3, '#7c7c7c'); px(x, X + 2, Y - 11, 2, 2, (t >> 1) & 1 ? '#f8b800' : '#fcfcfc'); + }; + // shrapnel: a white-hot star; dust: an orange-brown puff (both harmful, both drawn to the 16x16 box) + MM.drawShard = function (x, p, t) { + var X = Math.round(p.x), Y = Math.round(p.y), dust = p.kind === 'dust', k = (t + p.slot) & 1; + var hot = dust ? '#c84c0c' : '#fcfcfc', mid = dust ? '#7c3c00' : '#f8b800'; + px(x, X - 2, Y - 7, 4, 14, mid); px(x, X - 7, Y - 2, 14, 4, mid); + px(x, X - 4, Y - 4, 8, 8, hot); if (!dust) { px(x, X - 5 - k, Y - 5 - k, 2, 2, mid); px(x, X + 3 + k, Y + 3 + k, 2, 2, mid); } + else px(x, X - 6, Y - 6 + k, 3, 3, '#7c3c00'); + }; + ['megaman/elec_man', 'megaman/ice_man', 'megaman/fire_man', 'megaman/bomb_man', 'megaman/cut_man', 'megaman/guts_man'].forEach(function (id) { + B.BOSS_DRAW[id] = { hazards: function () {}, body: function () {}, boss: bossSprite, projectiles: projectiles, + bar: function () { return '#f87858'; } }; + }); +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/game.js b/environments/games/web/games/megaman_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..3f01b0b86451b1621972d86a88592c2ddaf165fa --- /dev/null +++ b/environments/games/web/games/megaman_remake/game.js @@ -0,0 +1,34 @@ +// Mega Man (NES, 1987) · Robot Masters - game manifest for the BB.Case shell (engine/app.js). +// Public difficulty is three tiers; the spec rows (specs/*.spec.js) are written at exactly these values, so +// tier = spec column and any d in between interpolates. Rule version bumps whenever rules or tiers change. +(function (g) { + var B = g.BB, MM = B.MM; + B.GAME = { + id: 'megaman_remake', + title: 'Mega Man · Boss Rush', + rules: 'megaman-nes-20261105-r4', + tiers: { easy: 0, normal: 0.5, hard: 1 }, + hz: 60, + defaultCase: 'megaman/elec_man', + hitstop: false, // the NES game has no hit-stop + results: { win: 'BOSS DEFEATED', loss: 'GAME OVER', timeout: 'TIME UP' }, + roster: [ + { id: 'megaman/elec_man', name: 'POUNCER · Counterattack Unit', arch: 'Fast movement · Counters every shot · Crawling zigzag arcs (10 damage). Weak to the returning blade' }, + { id: 'megaman/ice_man', name: 'V GUNNER · V-Shot Unit', arch: 'Fixed barrage · Jumps straight up and fires six blades in a V, faster as the fight goes on. Weak to the tri arc (10 damage)' }, + { id: 'megaman/fire_man', name: 'WAVE KEEPER · Ground-Wave Unit', arch: 'Keeps 96 px away · Ground-hugging fire waves and flames beneath your feet · Counterattacks when hit. Weak to the pierce dart (4 damage)' }, + { id: 'megaman/bomb_man', name: 'SHARD LOBBER · Bomb Unit', arch: 'Random jumps · Throws 1–3 bombs that burst into 12-way shrapnel on landing · Leaps away at close range. Weak to orbit guard (4 damage)' }, + { id: 'megaman/cut_man', name: 'BLADE TOSSER · Returning-Blade Unit', arch: 'Random jumps · Throws a blade that returns · The room has steps and two liftable rocks. Weak to the rock throw (14 damage)' }, + { id: 'megaman/guts_man', name: 'QUAKE HURLER · Ground-Shock Unit', arch: 'Landing shakes the screen and stuns grounded players · Catches falling ceiling rocks and throws them, splitting each into four · Two rocks can be lifted. Weak to the timed bomb (10 damage)' } + ], + // weapon x boss damage, the demonstrable counter chain of this round (data/weapons.js is the source) + chain: [['elec_man', 'E', 'ice_man'], ['ice_man', 'I', 'fire_man'], ['fire_man', 'F', 'bomb_man'], ['cut_man', 'C', 'elec_man'], ['guts_man', 'G', 'cut_man'], ['bomb_man', 'B', 'guts_man']], + // human play on the page: the weapons won so far (page.js keeps them); the harness passes options itself + resetOptions: function () { return { weapons: (B.MM_PAGE && B.MM_PAGE.loadout()) || [] }; } + }; + B.GAME.skillText = {}; + B.GAME.roster.forEach(function (r) { + var id = r.id.split('/')[1], spec = B.SPECS[id], text = B.GAME.skillText[r.id] = {}; + spec.moves.forEach(function (m) { text[m.name] = m.cue + ' → ' + m.punish; }); + }); + MM.caseBoss = function (caseId) { return String(caseId).split('/')[1]; }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/index.html b/environments/games/web/games/megaman_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e97c340e09c92d9a0a077f6451a263670d261c36 --- /dev/null +++ b/environments/games/web/games/megaman_remake/index.html @@ -0,0 +1,14 @@ +Mega Man · Boss Rush — BossBench +
          BOSSBENCH / 2DNES 1987 · 60 Hz

          MEGA MAN BOSS RUSH

          Boss battles recreated from the 1987 NES rules. Defeat bosses to acquire their weapons and follow the weakness chain. No slide or charge shot.

          +

          STAGE SELECT · Select Boss

          0.50

          Select acquired weapons to bring them into the challenge. Defeating a boss unlocks its weapon. Hard uses original values (boss projectile damage: 10 units; contact damage: 4 units).

          +
          + +

          Controls · CONTROLS

          • AD / arrow keys to move; Space / Z to jump; hold for more height
          • J / X / left mouse button to fire (one shot per press, up to three Arm Gun shots on screen)
          • Q / E switch weapons (replaces the original pause menu: switching recalls the active special shot; fired Arm Gun shots continue moving but no longer deal damage)
          • P/Esc to pause; then Q to go back; after a result, press R to retry. Scripted Demo runs reference script BB.GAME.scripted
          • Sliding was added in Mega Man 3 and charge shots in Mega Man 4; neither is available here

          Weapon × boss damage table (NES units)

          Skill list

            +
            Replay and step playback
            One packet every 200 ms; replays are deterministic with the same seed, options, and rules
            +
            All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
            + + + + diff --git a/environments/games/web/games/megaman_remake/page.js b/environments/games/web/games/megaman_remake/page.js new file mode 100644 index 0000000000000000000000000000000000000000..4e51a86ab7b93d2fcfbadd0289873182a135e0fe --- /dev/null +++ b/environments/games/web/games/megaman_remake/page.js @@ -0,0 +1,71 @@ +// Play-page extras (browser only; harmless in Node and in the policy-env page, where the DOM nodes are absent): +// the weapon loadout chooser (weapons won so far, unlocked automatically by a win), the weapon x boss damage +// table rendered from data/weapons.js, and the "YOU GOT ..." line on the result screen. +(function (g) { + var B = g.BB, MM = B.MM; + var owned = {}; + try { owned = JSON.parse(g.localStorage && g.localStorage.getItem('bb.megaman.weapons') || '{}') || {}; } catch (e) { owned = {}; } + function save() { try { g.localStorage.setItem('bb.megaman.weapons', JSON.stringify(owned)); } catch (e) { /* file:// may refuse */ } } + B.MM_PAGE = { loadout: function () { return MM.WEAPON_ORDER.filter(function (w) { return owned[w] && MM.WEAPONS[w].built; }); } }; + var doc = g.document; + if (!doc || !doc.getElementById || !doc.getElementById('loadout')) return; + var $ = function (id) { return doc.getElementById(id); }; + + function renderLoadout() { + var host = $('loadout'); host.textContent = ''; + var lab = doc.createElement('span'); lab.textContent = 'Acquired weapons: '; host.appendChild(lab); + MM.WEAPON_ORDER.forEach(function (w) { + var info = MM.WEAPONS[w]; + if (!info.from || !info.built) return; + var l = doc.createElement('label'), cb = doc.createElement('input'); + cb.type = 'checkbox'; cb.checked = !!owned[w]; cb.dataset.weapon = w; + cb.addEventListener('change', function () { owned[w] = cb.checked; save(); }); + l.appendChild(cb); l.appendChild(doc.createTextNode(info.name + ' (defeat ' + MM.ROBOT_MASTERS[info.from].zh + ')')); + host.appendChild(l); + }); + } + function renderTable() { + var bosses = ['elec_man', 'ice_man', 'fire_man', 'cut_man', 'bomb_man', 'guts_man']; + var weapons = MM.WEAPON_ORDER.filter(function (w) { return w !== 'M'; }); + var t = doc.createElement('table'); t.className = 'dmg'; + var head = doc.createElement('tr'); head.appendChild(doc.createElement('th')); + weapons.forEach(function (w) { var th = doc.createElement('th'); th.textContent = MM.WEAPONS[w].zh; th.title = MM.WEAPONS[w].name; head.appendChild(th); }); + t.appendChild(head); + bosses.forEach(function (id) { + var tr = doc.createElement('tr'), th = doc.createElement('th'), weak = MM.weakTo(id); + th.textContent = MM.ROBOT_MASTERS[id].zh + (B.CASES['megaman/' + id] ? '' : '*'); tr.appendChild(th); + weapons.forEach(function (w) { + var td = doc.createElement('td'), v = MM.DAMAGE[id][w]; td.textContent = v; + if (w === weak) td.className = 'weak'; else if (v === 0) td.className = 'zero'; + tr.appendChild(td); + }); + t.appendChild(tr); + }); + var note = doc.createElement('p'); note.className = 'note'; + note.textContent = 'Each cell is one NES energy unit (a boss has 28 at full health). Gold marks a weakness. Values come from the original ROM. Weakness chain: Pouncer → Tri Arc → V Gunner → Pierce Dart → Wave Keeper → Orbit Guard → Shard Lobber → Fuse Lob → Quake Hurler → Rock Throw → Blade Tosser → Returning Blade → Pouncer.'; + $('dmgtable').appendChild(t); $('dmgtable').appendChild(note); + } + // the subtitle names the scenes from the roster, so the count never drifts from the code (hand-written counts did) + function renderSub() { + var el = $('mmsub'), names = B.GAME.roster.map(function (r) { return MM.ROBOT_MASTERS[MM.caseBoss(r.id)].zh; }); + var chain = B.GAME.chain.filter(function (k) { return MM.WEAPONS[k[1]].built && B.CASES['megaman/' + k[2]]; }) + .map(function (k) { return MM.WEAPONS[k[1]].zh + ' is strong against ' + MM.ROBOT_MASTERS[k[2]].zh; }); + if (el) el.textContent = 'Faithful to the 1987 NES rules across ' + names.length + ' boss battles: ' + names.join(', ') + + '. Defeat bosses to acquire their weapons. The weakness chain is: ' + chain.join(', ') + '. There is no slide or charge shot.'; + } + renderLoadout(); renderTable(); renderSub(); + // a win unlocks the boss's weapon for later fights (only for human or demo play on this page) + var result = $('result'), seen = null; + new g.MutationObserver(function () { + if (result.classList.contains('hidden')) return; + var run = g.BossBench && g.BossBench.lastRun; + if (!run || run === seen) return; + seen = run; + var boss = MM.caseBoss(run.case), info = MM.ROBOT_MASTERS[boss], w = info && info.weapon; + if (run.verifier && run.verifier.outcome === 'win' && w && MM.WEAPONS[w].built) { + var fresh = !owned[w]; owned[w] = true; save(); renderLoadout(); + $('rweapon').textContent = (fresh ? 'New weapon acquired: ' : 'Already owned: ') + MM.WEAPONS[w].name + '. Strong against: ' + + Object.keys(MM.DAMAGE).filter(function (id) { return MM.weakTo(id) === w; }).map(function (id) { return MM.ROBOT_MASTERS[id].zh; }).join(', '); + } else $('rweapon').textContent = ''; + }).observe(result, { attributes: true, attributeFilter: ['class'] }); +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/scripted.js b/environments/games/web/games/megaman_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..f49d9f7b2842f0a5812d54ee013052de5bfd51da --- /dev/null +++ b/environments/games/web/games/megaman_remake/scripted.js @@ -0,0 +1,163 @@ +// Standard scripted reference controller for the Mega Man cases (BossBench protocol section 3). +// BB.GAME.scripted(c) is called once per 200 ms packet with the live BB.Case. It plans by receding-horizon +// search: a systematic set of action sequences (direction x jump start x jump height x fire pattern), 48 ticks +// long, plus the previous best plan shifted by one packet, is simulated on deep copies of the case (the live +// case, its RNG and its event list are never touched) and scored on damage taken (dominant), damage dealt and a +// small positional heuristic; the first packet of the best sequence is played. +// Deterministic (no Math.random, no clock); emits legal packets (<= 4 keys per hold set). It reads privileged +// state and simulates the boss, but rolls not yet made are re-drawn from a synthetic RNG: a trusted demo/recording +// tool, not a policy. +(function (g) { + var B = g.BB, MM = B.MM; + if (!B || !B.GAME) return; + var SUBS = 24, TICKS = 2; // horizon: 24 hold sets x 2 ticks = 48 ticks = 4 packets + var MEMORY = typeof WeakMap === 'function' ? new WeakMap() : null; + var JUMP_AT = [0, 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 18], JUMP_LEN = [14, 5]; + + function clone(o) { return JSON.parse(JSON.stringify(o)); } + function copyCase(c, k) { + var n = Object.create(Object.getPrototypeOf(c)); Object.assign(n, c); + n.body = Object.assign(Object.create(Object.getPrototypeOf(c.body)), clone(c.body)); + n.boss = Object.assign(Object.create(Object.getPrototypeOf(c.boss)), clone(c.boss)); + // the look-ahead gets its own RNG: decisions already taken are readable, rolls not yet made are not + n.rng = new B.RNG(((c.t + 1) * 2654435761 + 97 + k * 40503) >>> 0); + n.events = []; return n; + } + function blank() { var a = []; for (var i = 0; i < SUBS; i++) a.push(0); return a; } + function fill(a, from, to, v) { for (var i = Math.max(0, from); i < Math.min(SUBS, to); i++) a[i] = v; return a; } + function pulses(from, every) { var a = blank(); for (var i = from; i < SUBS; i += every) a[i] = 1; return a; } + function plan(dir, jump, fire) { return { dir: dir, jump: jump, fire: fire }; } + function holdSet(p, i) { + var k = {}; + if (p.dir[i] < 0) k.A = true; else if (p.dir[i] > 0) k.D = true; + if (p.jump[i]) k.Space = true; + if (p.fire[i]) k.J = true; + return k; + } + + // ---------------- scoring ---------------- + // The plan's 48 ticks are followed by a short continuation (keep the direction, release jump, keep firing) so a + // jump that lands on a pillar or into a shot just past the horizon is still seen; its damage counts half. + var EXTRA = 24, STUN_COST = 1.5; + function evaluate(c, p, k) { + var sim = copyCase(c, k), b = sim.body, o = sim.boss, score = 0, hp = b.hp, bhp = o.hp, t; + for (var i = 0; i < SUBS; i++) { + var keys = holdSet(p, i); + for (var k = 0; k < TICKS; k++) { + sim.tick(keys); t = i * TICKS + k; + if (b.hp < hp) { score -= (hp - b.hp) / MM.UNIT * 400 * (1 - t / 200); hp = b.hp; } + if (b.stunT > 0) score -= STUN_COST; // a stunned player cannot dodge the rock that follows (Guts Man only) + if (o.hp < bhp) { score += (bhp - o.hp) / MM.UNIT * 40 * (1 - t / 120); bhp = o.hp; } + if (sim.result === 'loss') return score - 1e6; + if (sim.result === 'win') return score + 1e6 - t * 10; + } + } + var last = p.dir[SUBS - 1], tail = {}; + if (last < 0) tail.A = true; else if (last > 0) tail.D = true; + for (var e = 0; e < EXTRA && !sim.result; e++) { + tail.J = !(e & 2); + sim.tick(tail); + if (b.hp < hp) { score -= (hp - b.hp) / MM.UNIT * 200; hp = b.hp; } + } + if (sim.result === 'loss') return score - 5e5; + // terminal heuristic: margin from boss shots, room from the boss and the walls, shots on their way to hit + var hb = b.hurtBox(), margin = 40; + o.projectiles.forEach(function (q) { + if (q.harmless) return; + var dx = Math.max(0, Math.abs(q.x - hb.x) - q.hw - hb.hw), dy = Math.max(0, Math.abs(q.y - hb.y) - q.hh - hb.hh); + margin = Math.min(margin, Math.max(dx, dy)); + }); + score += margin * 1.2; + if (o.hp > 0) score -= Math.max(0, 52 - Math.abs(o.x - b.x)) * (Math.abs(o.y - b.y) < 40 ? 7 : 2); + score -= Math.max(0, 32 - Math.min(b.x - MM.WALL_L, MM.WALL_R - b.x)) * 0.8; + b.shots.forEach(function (s) { + if (Math.abs(s.y - o.y) < o.hh + s.hh && (o.x - s.x) * (s.vx || 0) > 0) score += 6; + }); + if (b.knockT > 0) score -= 20; + return score; + } + + // ---------------- candidate sequences ---------------- + function candidates(c, mem) { + var b = c.body, out = [], grounded = b.grounded, held = !!b.prev.jump; + var fireAll = pulses(0, 2), fireNone = blank(); + if (mem.best) { // previous best, shifted one packet + var s = mem.best, keep = plan(s.dir.slice(6), s.jump.slice(6), s.fire.slice(6)); + while (keep.dir.length < SUBS) { keep.dir.push(keep.dir[keep.dir.length - 1]); keep.jump.push(0); keep.fire.push(keep.fire.length % 2 ? 0 : 1); } + out.push(keep); + } + [-1, 0, 1].forEach(function (d) { + var dir = fill(blank(), 0, SUBS, d); + [fireAll, fireNone].forEach(function (fire) { + // no new jump: keep holding Space while airborne (full height) or release now (feather) + out.push(plan(dir, !grounded && held ? fill(blank(), 0, 14, 1) : blank(), fire)); + if (!grounded && held) out.push(plan(dir, blank(), fire)); + JUMP_AT.forEach(function (at) { + JUMP_LEN.forEach(function (len) { + var jump = blank(), start = at; + if (start === 0 && held) start = 1; // a new press needs a released sub-step first + fill(jump, start, start + len, 1); + if (!grounded && held && at > 0) fill(jump, 0, 1, 1); + out.push(plan(dir, jump, fire)); + }); + }); + }); + }); + // move-then-stop plans (step out of the way, then hold position), with and without a jump + [-1, 1].forEach(function (d) { + [3, 6, 10].forEach(function (k) { + [blank(), fill(blank(), held ? 1 : 0, 14, 1), fill(blank(), k, k + 14, 1)].forEach(function (jump) { + [fireAll, fireNone].forEach(function (fire) { out.push(plan(fill(fill(blank(), 0, k, d), k, SUBS, 0), jump, fire)); }); + }); + }); + }); + // a few two-segment plans (turn around mid-horizon) + [-1, 1].forEach(function (d) { + [6, 12].forEach(function (cut) { + out.push(plan(fill(fill(blank(), 0, cut, d), cut, SUBS, -d), fill(blank(), held ? 1 : 0, 14, 1), fireAll)); + out.push(plan(fill(fill(blank(), 0, cut, d), cut, SUBS, -d), blank(), fireAll)); + }); + }); + return out; + } + + // the owned weapon with the best damage RATE against this boss that still has energy: shots are limited by the boss's + // blink, the Hyper Bomb by its 160-frame fuse-and-flames cycle, the Rolling Cutter by its roughly 64-frame round trip + function bestWeapon(c) { + var b = c.body, row = MM.DAMAGE[c.boss.id], blink = c.boss.info.iframes + 1, best = 'P'; + function rate(w) { return row[w] / Math.max(blink, w === 'B' ? 160 : w === 'C' ? 64 : 0); } + // the Super Arm needs a block: one left in the room, or one held, thrown or broken into chunks + function usable(w) { return b.spendable(w) && (w !== 'G' || b.blockOut() || b.room.some(function (r) { return r.block; })); } + var weak = MM.weakTo(c.boss.id); + if (b.weapons.indexOf(weak) >= 0 && usable(weak)) return weak; // the counter chain: the boss's weakness first + b.weapons.forEach(function (w) { if (usable(w) && rate(w) > rate(best)) best = w; }); + return best; + } + + // Bosses whose AI rolls dice get several sampled futures per plan, scored half worst case, half mean, so a plan is + // not chosen for surviving only one outcome of a roll not yet made. RNG-free bosses need a single evaluation. + var ROLLS = { elec_man: 3, bomb_man: 3, cut_man: 3, guts_man: 3 }; + function robust(c, p) { + var n = ROLLS[c.boss.id] || 1, worst = Infinity, sum = 0; + for (var k = 0; k < n; k++) { var v = evaluate(c, p, k); sum += v; if (v < worst) worst = v; } + return n === 1 ? worst : 0.5 * worst + 0.5 * sum / n; + } + + B.GAME.scripted = function (c) { + var mem = MEMORY ? MEMORY.get(c) : null; + if (!mem || c.t === 0 || mem.t > c.t) { mem = { t: c.t, best: null }; if (MEMORY) MEMORY.set(c, mem); } + mem.t = c.t; + var b = c.body, o = c.boss, idle = [{}, {}, {}, {}, {}, {}]; + if (o.intro > 0 || b.hp <= 0 || o.hp <= 0) { mem.best = null; return idle; } + if (b.weapon !== bestWeapon(c) && !b.count('hyper_bomb') && !b.count('hyper_flame')) { mem.best = null; return [{ E: true }, {}, {}, {}, {}, {}]; } // one step per press + var cands = candidates(c, mem), bestScore = -Infinity, best = null; + for (var i = 0; i < cands.length; i++) { + var s = robust(c, cands[i]); + if (s > bestScore + 1e-9) { bestScore = s; best = cands[i]; } + } + mem.best = best; + var out = []; + for (var k = 0; k < 6; k++) out.push(holdSet(best, k)); + return out; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/bomb_man.spec.js b/environments/games/web/games/megaman_remake/specs/bomb_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5e9bbba709c1903bb0054086b2257fe0cd25fe5b --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/bomb_man.spec.js @@ -0,0 +1,104 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["bomb_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "bomb_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Bomb Man: random leap toward the player, lobs 1-3 bombs that burst into 12-way shrapnel, jumps at a player who closes in", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "walk_idle", + "telegraph": "throw", + "active": "land_throw", + "recovery": "wait_bomb" + }, + "timing": { + "telegraph": { + "knob": "windup", + "min": 1 + }, + "recovery": { + "knob": "windup", + "until": "timer" + } + }, + "locomotion": { + "knob": "windup", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "pattern_step", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "lob_bomb", + "atoms": [ + "projectile" + ], + "damage": 4, + "cue": "After landing he raises a bomb and charges for about 0.25 seconds, then throws it at you. The bomb lands after 49 frames, about 20 px short of you. He waits for each bomb to explode before throwing the next, 1-3 per volley", + "punish": "The bomb itself cannot be shot (bullets pass through). Read the landing spot, jump over the horizontal fragments, or back out of their range (about 30 px)" + }, + { + "name": "shrapnel", + "atoms": [ + "burst" + ], + "damage": 4, + "cue": "The bomb explodes into 12 pieces when it lands or hits a wall: fast pieces about 30 px up, down, left, and right, diagonal pieces about 20 px, plus four slow pieces", + "punish": "The ground-level horizontal pieces are only 16 px tall, so a jump clears them. Do not stand directly above the landing spot" + }, + { + "name": "leap", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "Each volley starts with a random jump: a long pounce toward you (about 154 px) or a short hop closer (about 49 px). After a short-hop volley he jumps away with his back to you", + "punish": "The long jump carries him over you, so walk under him. He only starts charging after he lands and settles, which is the damage window" + }, + { + "name": "close_guard", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "If you walk within 48 px, he drops the current bomb and jumps at you immediately", + "punish": "You can use this to break his throw rhythm, but he jumps over your head, so watch the contact damage" + } + ], + "difficulty": { + "hp": [ + 66, + 180, + 520 + ], + "shot": [ + 2, + 3, + 4 + ], + "contact": [ + 2, + 3, + 4 + ], + "windup": [ + 30, + 20, + 15 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/cut_man.spec.js b/environments/games/web/games/megaman_remake/specs/cut_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..ef33a0ec56c5bb66c0ae4622957aefb8e6fc0ec9 --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/cut_man.spec.js @@ -0,0 +1,109 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["cut_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "cut_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Cut Man: random leaps at the player, a homing Rolling Cutter that flies out and back, a step and two blocks in the room", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "retarget", + "telegraph": "land_settle", + "active": "throw_windup", + "recovery": "chase" + }, + "timing": { + "telegraph": { + "knob": "wait", + "min": 1 + }, + "recovery": { + "knob": "wait", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "pattern_step", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "return_blade", + "atoms": [ + "boomerang" + ], + "damage": 4, + "cue": "After landing he stands, raises the cutter for about 16 frames, and throws it at you. It turns around at the room edge and speeds back to his hand, and the return pass sweeps through where you are", + "punish": "While the cutter is out he has no weapon, so close in and shoot. The return path follows him; do not stand between him and the blade" + }, + { + "name": "leap", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "Within 64 px he jumps (6.4 px/frame upward): a 1/2 chance to land 32 px past you, 1/3 to land on you, and 1/6 to land in front of you", + "punish": "When he jumps, walk under him or the other way. He may throw the cutter in the air" + }, + { + "name": "chase", + "atoms": [ + "wait" + ], + "damage": 4, + "cue": "If you are on a ledge and he is on the ground, he runs in place for about 1 second, then throws the cutter", + "punish": "The ledge is a safe place to watch, but the cutter flies at you when the wait ends" + }, + { + "name": "hop_back", + "atoms": [ + "hop" + ], + "damage": 4, + "cue": "After a hit he flashes for 63 frames and hops away with his back to you for the first 32 frames", + "punish": "Bullets pass through him while he is flashing" + } + ], + "difficulty": { + "hp": [ + 60, + 170, + 520 + ], + "shot": [ + 2, + 3, + 4 + ], + "contact": [ + 2, + 3, + 4 + ], + "speed": [ + 0.8, + 0.9, + 1.0 + ], + "wait": [ + 63, + 63, + 63 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/elec_man.spec.js b/environments/games/web/games/megaman_remake/specs/elec_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..3c365cc10557637269c108bc95f8868eab3d018d --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/elec_man.spec.js @@ -0,0 +1,117 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["elec_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "elec_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Elec Man: wall-position patrol, counter-leap on the player's shot, crawling Thunder Beam", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "guard", + "telegraph": "halt", + "active": "fire", + "recovery": "wait" + }, + "timing": { + "telegraph": { + "knob": "windup", + "min": 1 + }, + "recovery": { + "knob": "windup", + "until": "timer" + } + }, + "locomotion": { + "knob": "walk", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "pattern_step", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "zigzag_arc", + "atoms": [ + "crawling_bolt" + ], + "damage": 10, + "cue": "He stops, raises his hand for 15 frames, then fires a five-segment jagged arc. Each segment hops forward and changes shape every 10 frames, averaging about 4 px/frame", + "punish": "The high arc arrives first and you can let it pass while standing. Jump before the low arc arrives; jumping toward him makes it easier to pass through" + }, + { + "name": "counter_leap", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "If you press fire while he is walking, he immediately jumps at you (a 1/4 chance it is a feint the other way)", + "punish": "Do not fire while he is repositioning. Wait until he stands and fires the arc" + }, + { + "name": "air_arc", + "atoms": [ + "crawling_bolt" + ], + "damage": 10, + "cue": "If you fire again while he is in the air, he charges in the air and releases one arc", + "punish": "The air arc stays at his height, so watch where he lands" + }, + { + "name": "hop_back", + "atoms": [ + "hop" + ], + "damage": 4, + "cue": "After a hit he flashes for 63 frames and jumps away with his back to you for the first 32 frames", + "punish": "Bullets pass through him while he flashes, so save shots until the flash ends" + } + ], + "difficulty": { + "hp": [ + 19, + 40, + 150 + ], + "shot": [ + 4, + 7, + 10 + ], + "contact": [ + 2, + 3, + 4 + ], + "walk": [ + 1.5, + 1.75, + 2.0 + ], + "windup": [ + 30, + 20, + 15 + ], + "counter": [ + 0.35, + 0.7, + 1.0 + ] + }, + "kinds": { + "counter": "continuous" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/fire_man.spec.js b/environments/games/web/games/megaman_remake/specs/fire_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..79aeb8d23120e0db429dc26ff0fb4d11483d2bbc --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/fire_man.spec.js @@ -0,0 +1,121 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["fire_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "fire_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Fire Man: keeps a 96 px band, five-wave Fire Storm volleys, floor pillars, retaliates when hit", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "pace", + "telegraph": "summon", + "active": "hold", + "recovery": "pose" + }, + "timing": { + "telegraph": { + "knob": "hold", + "min": 1 + }, + "recovery": { + "knob": "hold", + "until": "timer" + } + }, + "locomotion": { + "knob": "hold", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "distance_band", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "ground_wave", + "atoms": [ + "projectile" + ], + "damage": 4, + "cue": "He stands about 96 px away. The flame in his hand forms for 23 frames, then rushes along the ground at 5 px/frame. A volley is at most five shots, about 1 second apart", + "punish": "Get ready to jump when the flame forms. The wave is 32 px tall, so clear it near the top of the jump" + }, + { + "name": "fire_pillar", + "atoms": [ + "hazard" + ], + "damage": 4, + "cue": "Where a fire wave passes under you, a pillar rises and lasts about 2.2 seconds", + "punish": "Avoid the pillar when you land. The old pillar goes out when he fires the next wave" + }, + { + "name": "keep_distance", + "atoms": [ + "walk" + ], + "damage": 4, + "cue": "He backs away when you close in and advances when you retreat, holding about 96 px. Cornered against a wall, he turns and walks straight through you", + "punish": "Shoot while he is backing up. Watch the contact damage when he is against the wall" + }, + { + "name": "retaliate", + "atoms": [ + "projectile" + ], + "damage": 4, + "cue": "About 14 frames (0.23 seconds) after a hit, he immediately starts a new fire volley", + "punish": "Get ready to jump right after a hit connects" + }, + { + "name": "stand_down", + "atoms": [ + "pose" + ], + "damage": 0, + "cue": "After five shots he poses and stops firing. Any key you press, or leaving the distance band, makes him start again", + "punish": "Original behavior: if you do not move at all, he will not attack again" + } + ], + "difficulty": { + "hp": [ + 66, + 86, + 270 + ], + "shot": [ + 2, + 3, + 4 + ], + "contact": [ + 2, + 3, + 4 + ], + "hold": [ + 90, + 75, + 63 + ], + "retaliate": [ + 0, + 1, + 1 + ] + }, + "kinds": { + "retaliate": "unlock" + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/guts_man.spec.js b/environments/games/web/games/megaman_remake/specs/guts_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..0db6d262704874bb4465dbe48e13cd5c50112db7 --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/guts_man.spec.js @@ -0,0 +1,100 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["guts_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "guts_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Guts Man: heavy leaps that quake the room and stun anyone standing on the floor, a boulder from the ceiling thrown at you that shatters into four chunks", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "land_wait", + "telegraph": "windup_rock", + "active": "throw_rock", + "recovery": "pattern_roll" + }, + "timing": { + "telegraph": { + "knob": "windup", + "min": 1 + }, + "recovery": { + "knob": "windup", + "until": "timer" + } + }, + "locomotion": { + "knob": "windup", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "pattern_step", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "quake_leap", + "atoms": [ + "leap" + ], + "damage": 4, + "cue": "He crouches for about 0.25 seconds, then leaps. The landing shakes the screen for about 0.5 seconds, and if you are on the ground (or were just knocked back) you are stuck for about 0.8 seconds", + "punish": "Jump as he is about to land, and stay off the ground until the shake ends, or you will be stuck. His rise and fall are slow, so you can walk under him" + }, + { + "name": "boulder_throw", + "atoms": [ + "projectile" + ], + "damage": 4, + "cue": "He jumps in place. On landing a rock drops from the ceiling into his hands. He holds it for about 0.25 seconds, then throws it in a straight line at your feet", + "punish": "The rock cannot be shot (bullets pass through). While he stands holding it, that is the damage window. Jump or move the moment he throws" + }, + { + "name": "chunks", + "atoms": [ + "burst" + ], + "damage": 4, + "cue": "The rock shatters into four pieces on a wall, the ground, or a step. They keep flying the original way at 3-4 px/frame, and two of them rise", + "punish": "The pieces appear at the lower right of the impact (they are not mirrored with direction) and fly the original way. After the rock lands, walk back or jump" + } + ], + "difficulty": { + "hp": [ + 56, + 165, + 470 + ], + "shot": [ + 2, + 3, + 4 + ], + "contact": [ + 2, + 3, + 4 + ], + "windup": [ + 30, + 20, + 15 + ], + "speed": [ + 0.8, + 0.9, + 1.0 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/megaman_remake/specs/ice_man.spec.js b/environments/games/web/games/megaman_remake/specs/ice_man.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..d4e62f1c9eba6d54e4f347a3a36be5950ef30b01 --- /dev/null +++ b/environments/games/web/games/megaman_remake/specs/ice_man.spec.js @@ -0,0 +1,96 @@ +(function (g) { var BB = g.BB = g.BB || {}; BB.SPECS = BB.SPECS || {}; +BB.SPECS["ice_man"] = { + "schema": "bossbench/boss-spec@1", + "id": "ice_man", + "dims": "2d", + "family": "megaman_nes", + "archetype": "Mega Man (NES 1987) Ice Man: four-waypoint patrol, vertical hop firing a six-shot V of Ice Slashers that speeds up", + "hp_model": { + "knob": "hp", + "integer": true + }, + "states": { + "idle": "leg_walk", + "telegraph": "stance", + "active": "fire", + "recovery": "land" + }, + "timing": { + "telegraph": { + "knob": "windup", + "min": 1 + }, + "recovery": { + "knob": "hover", + "until": "timer" + } + }, + "locomotion": { + "knob": "speed", + "when": "before_select", + "speed_by_state": { + "idle": 1.0, + "telegraph": 0.0, + "active": 0.0, + "recovery": 0.0 + } + }, + "select": { + "trigger": "waypoint_cycle", + "policy": "first", + "face_target": true + }, + "moves": [ + { + "name": "v_volley", + "atoms": [ + "projectile" + ], + "damage": 10, + "cue": "He walks to a stance, charges 15 frames, and jumps straight up. On the way down he fires one blade at each of three heights, hovers at the ground, then rises in reverse and fires three more (six blades in a V)", + "punish": "Only the ground-level blade needs a jump. The middle and high blades can be let past while standing. Jumping too high hits the upper blade" + }, + { + "name": "patrol", + "atoms": [ + "walk" + ], + "damage": 4, + "cue": "He walks back and forth among the stances at 208, 168, 128, and 168. Every third landing raises the blade speed and the hover and sink timing by one level, up to four", + "punish": "Walking and charging are the safest windows to shoot. He has no hit reaction" + } + ], + "difficulty": { + "hp": [ + 29, + 85, + 245 + ], + "shot": [ + 4, + 7, + 10 + ], + "contact": [ + 2, + 3, + 4 + ], + "speed": [ + 0.8, + 0.9, + 1.0 + ], + "hover": [ + 1.4, + 1.2, + 1.0 + ], + "windup": [ + 30, + 20, + 15 + ] + } +}; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/minecraft_remake/compact_actions.json b/environments/games/web/games/minecraft_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..21868930586fa555c44f5c17d06f429a98df9a65 --- /dev/null +++ b/environments/games/web/games/minecraft_remake/compact_actions.json @@ -0,0 +1,224 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "minecraft", + "version": "minecraft-compact@2", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W" + ] + }, + { + "label": "back", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "sprint", + "keys": [ + "W", + "Shift" + ] + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "swing", + "tap": [ + "LMB" + ] + }, + { + "label": "swing_late", + "subs": [ + [], + [], + [], + [], + [ + "LMB" + ], + [] + ] + }, + { + "label": "draw", + "keys": [ + "RMB" + ] + }, + { + "label": "jump", + "subs": [ + [ + "Space" + ], + [ + "Space" + ], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "switch", + "dz": 1 + } + ] + }, + { + "name": "aim", + "options": [ + { + "label": "none" + }, + { + "label": "r8_c0", + "dx": 8 + }, + { + "label": "l8_c0", + "dx": -8 + }, + { + "label": "c0_d40", + "dy": 40 + }, + { + "label": "c0_u40", + "dy": -40 + }, + { + "label": "r25_c0", + "dx": 25 + }, + { + "label": "r25_d40", + "dx": 25, + "dy": 40 + }, + { + "label": "r25_u40", + "dx": 25, + "dy": -40 + }, + { + "label": "l25_c0", + "dx": -25 + }, + { + "label": "l25_d40", + "dx": -25, + "dy": 40 + }, + { + "label": "l25_u40", + "dx": -25, + "dy": -40 + }, + { + "label": "r60_c0", + "dx": 60 + }, + { + "label": "r60_d40", + "dx": 60, + "dy": 40 + }, + { + "label": "r60_u40", + "dx": 60, + "dy": -40 + }, + { + "label": "l60_c0", + "dx": -60 + }, + { + "label": "l60_d40", + "dx": -60, + "dy": 40 + }, + { + "label": "l60_u40", + "dx": -60, + "dy": -40 + }, + { + "label": "r150_c0", + "dx": 150 + }, + { + "label": "r150_d40", + "dx": 150, + "dy": 40 + }, + { + "label": "r150_u40", + "dx": 150, + "dy": -40 + }, + { + "label": "l150_c0", + "dx": -150 + }, + { + "label": "l150_d40", + "dx": -150, + "dy": 40 + }, + { + "label": "l150_u40", + "dx": -150, + "dy": -40 + }, + { + "label": "r300_c0", + "dx": 300 + }, + { + "label": "l300_c0", + "dx": -300 + }, + { + "label": "r600_c0", + "dx": 600 + }, + { + "label": "l600_c0", + "dx": -600 + } + ] + } + ] +} diff --git a/environments/games/web/games/minecraft_remake/index.html b/environments/games/web/games/minecraft_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..acdac3624cfe336901e15d24f9a2cbb531efe522 --- /dev/null +++ b/environments/games/web/games/minecraft_remake/index.html @@ -0,0 +1,86 @@ + + + + + + +Minecraft · Voxel Arena + + + +
            +
            +

            Minecraft · Voxel Arena

            +

            Java Edition 1.21 combat subset · Six boss arenas · Three public difficulty tiers · ModernGL rendering · 60 Hz · Recording and replay · Rules minecraft-arena@7

            + Back to Game Lobby +
            +
            +
            +
            + Game screen rendered by the local Python server +
            +
            Select a boss to start
            + +
            +
            + + + + + + + +
            +
            + + + +
            +

            Connecting to local server…

            +

            Every 200 ms, your input becomes a standard action packet: six 33 ms key windows, each with up to four keys plus mouse movement. The packet goes to the same simulation as make_policy_env. Pausing stops the world. Replays use bossbench/policy-replay@1; import simulates each packet again and checks the final-state hash. Scripted Demo is a reference controller that reads internal state, not a trained model; it does not start RL training.

            +
            + +
            +
            All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
            +
            + + + diff --git a/environments/games/web/games/minecraft_remake/manifest.json b/environments/games/web/games/minecraft_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..dd2b90b6faca1a8cb741532060e190c97c5163d8 --- /dev/null +++ b/environments/games/web/games/minecraft_remake/manifest.json @@ -0,0 +1,67 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "python", + "game": "minecraft_remake", + "title": "Minecraft: Voxel Arena", + "dimension": "3d", + "native_hz": 60, + "max_seconds": { + "3d/minecraft_iron_golem": 300, + "3d/minecraft_zombie": 90, + "3d/minecraft_ender_dragon": 300, + "3d/minecraft_wither": 300, + "3d/minecraft_warden": 300, + "3d/minecraft_skeleton": 300, + "3d/minecraft_zombie_leader": 300 + }, + "renderer": "moderngl", + "rules": "minecraft-arena@7", + "tiers": { + "easy": 0.0, + "normal": 0.5, + "hard": 1.0 + }, + "tiers_source": "prototype/bossbench/mc4d.py TIERS (read by bossbench.make_policy_env and the play server)", + "cases": [ + "3d/minecraft_iron_golem", + "3d/minecraft_ender_dragon", + "3d/minecraft_wither", + "3d/minecraft_warden", + "3d/minecraft_skeleton", + "3d/minecraft_zombie_leader" + ], + "retired_cases": { + "3d/minecraft_zombie": "2026-11-10 user request: remove the green-skinned grappler. It remains registered in FORMAL_CASES under frozen @4 rules, but is excluded from the benchmark list (scope.BENCH_RETIRED). Its media was moved to archived history." + }, + "formal_cases": [ + "3d/minecraft_iron_golem", + "3d/minecraft_zombie", + "3d/minecraft_ender_dragon", + "3d/minecraft_wither" + ], + "kits": { + "diamond": "diamond sword 7 + full diamond armor 20 / 8 (flung giant, green-skinned grappler, purple-breathing flyer, triple-headed floating cannon, shockwave beast)", + "iron": "iron sword 6 + full iron armor 15 / 0 (mobile archer, summoner)", + "source": "prototype/bossbench/mc4d.py KITS / SCENE_KIT (the same on every tier)" + }, + "options": { + "weapon": [ + "sword", + "bow" + ], + "camera": [ + "first", + "third" + ] + }, + "play_page": "web/games/minecraft_remake/index.html", + "server": "prototype/bossbench/play_server.py", + "launch": "python games/prototype/bossbench/play_server.py", + "url": "http://127.0.0.1:8765/", + "simulation": [ + "prototype/bossbench/mc4d.py", + "prototype/bossbench/mcskin.py", + "prototype/bossbench/rig.py" + ], + "scripted_controller": "bossbench.mc_scripted.scripted(case) -> packet text (prototype/bossbench/mc_scripted.py)" +} diff --git a/environments/games/web/games/minecraft_remake/play.js b/environments/games/web/games/minecraft_remake/play.js new file mode 100644 index 0000000000000000000000000000000000000000..72e9a13984988b33c006aec21c22d46aa042ef33 --- /dev/null +++ b/environments/games/web/games/minecraft_remake/play.js @@ -0,0 +1,338 @@ +/* Minecraft remake play page client: samples real keyboard/mouse input into standard 200 ms packets + (6 hold sets of <= 4 keys + mouse dx dy dz), sends them to the local Python play server, and plays back the + 6 frames per packet that the real ModernGL renderer returns. The page itself simulates nothing. */ +(function () { + 'use strict'; + const $ = s => document.querySelector(s); + const KEYS = ['W', 'A', 'S', 'D', 'Space', 'Shift', 'J', 'K', 'L', 'Q', 'E', 'R', 'LMB', 'RMB']; + const CODE = {KeyW: 'W', KeyA: 'A', KeyS: 'S', KeyD: 'D', Space: 'Space', ShiftLeft: 'Shift', ShiftRight: 'Shift', + KeyJ: 'J', KeyK: 'RMB'}; + const SUB_MS = 200 / 6; + const view = $('#view'), capture = $('#capture'); + let API = '', sid = null, meta = null, state = null, running = false, mode = 'idle'; // idle | play | demo | replay + let down = new Set(), taps = new Set(), mouse = [0, 0, 0], subs = [], timer = null; + let queue = [], sending = false, clock0 = 0, subsDone = 0; + let frames = [], lastShown = 0, replayQueue = [], replayExpect = null, pending = false, epoch = 0; + + function status(text) { $('#status').textContent = text; } + function overlay(text) { + $('#overlay').hidden = !text; + $('#overlay-text').textContent = text || ''; + } + + // ------------------------------------------------------------------ server connection + async function api(path, body) { + const opt = body === undefined ? {} : {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)}; + const r = await fetch(API + path, opt); + const data = await r.json(); + if (!r.ok) throw Error(data.error || r.statusText); + return data; + } + async function connect() { + const bases = location.protocol.startsWith('http') && location.port === '8765' ? [''] : + ['', 'http://127.0.0.1:8765']; + for (const base of bases) { + try { + const r = await fetch(base + '/api/meta', {cache: 'no-store'}); + if (!r.ok) continue; + meta = await r.json(); + API = base; + $('#offline').hidden = true; + $('#rules').textContent = meta.rules; + const sel = $('#case'); + if (!sel.options.length) for (const c of meta.cases) { + const o = document.createElement('option'); + o.value = c.id; o.textContent = c.name; sel.appendChild(o); + } + tierControl(); + $('#hz').textContent = meta.native_hz + ' Hz'; + status('Connected to local server (' + meta.rules + ' · ' + meta.native_hz + ' Hz). Select a boss, then click Start Challenge.'); + overlay('Select a boss to start'); + return true; + } catch (e) { /* try next */ } + } + $('#offline').hidden = false; + overlay(''); + status('Could not connect. Start the local Python server using the command shown on screen.'); + return false; + } + $('#retry').onclick = connect; + + // ------------------------------------------------------------------ public difficulty: three tiers + // Rebuilt from the server's declaration (mc4d.TIERS via /api/meta), the same source make_policy_env reads, so the + // page can never offer a difficulty the public interface does not. Each option shows the reference-controller target window. + function tierControl() { + const sel = $('#difficulty'), keep = sel.value || meta.default_tier; + if (!meta.tiers || !meta.tiers.length) return; + sel.textContent = ''; + for (const t of meta.tiers) { + const o = document.createElement('option'); + o.value = t.name; o.textContent = t.label + '(d=' + t.difficulty + ')'; + o.selected = t.name === keep; sel.appendChild(o); + } + tierHint(); + } + function tierInfo(name) { return meta && meta.tiers ? meta.tiers.find(t => t.name === name) : null; } + function tierHint() { + const t = tierInfo($('#difficulty').value); + $('#tier-hint').textContent = t ? 'Reference script target: ' + t.target_seconds[0] + '–' + t.target_seconds[1] + ' seconds to win' : ''; + } + $('#difficulty').onchange = tierHint; + + // ------------------------------------------------------------------ input sampling + function heldNow() { + const all = new Set([...down, ...taps]); + taps.clear(); + const out = []; + for (const k of ['W', 'S', 'A', 'D']) if (all.has(k)) { out.push(k); break; } + for (const k of ['Space', 'Shift', 'LMB', 'J', 'RMB']) if (all.has(k) && out.length < 4) out.push(k); + return out; + } + function packetText(sets, m) { + const mx = m.map((v, i) => Math.max(i === 2 ? -5 : -1000, Math.min(i === 2 ? 5 : 1000, Math.round(v)))); + return '<|action_start|> ' + mx.join(' ') + ' ; ' + sets.map(s => s.join(',')).join(' ; ') + ' <|action_end|>'; + } + function takePacket() { + while (subs.length < 6) subs.push(heldNow()); + const p = packetText(subs, mouse); + subs = []; mouse = [0, 0, 0]; + return p; + } + // Wall-clock scheduler: one hold set per 33.3 ms of real time, whatever the timer jitter, so the world runs at + // real speed; packets go out in order, one request at a time (a lagging server gets up to 5 per request). + function sampleClock() { + if (!running || mode !== 'play') return; + const due = Math.floor((performance.now() - clock0) / SUB_MS); + if (due - subsDone > 18) subsDone = due - 6; // tab stalled: drop the backlog instead of a burst + while (subsDone < due) { + if (arrows.has('ArrowLeft')) mouse[0] -= 7; + if (arrows.has('ArrowRight')) mouse[0] += 7; + if (arrows.has('ArrowUp')) mouse[1] -= 4; + if (arrows.has('ArrowDown')) mouse[1] += 4; + subs.push(heldNow()); + subsDone++; + if (subs.length >= 6) queue.push(takePacket()); + } + pump(); + } + async function pump() { + if (sending || !queue.length || !sid) return; + sending = true; + const batch = queue.splice(0, 5), my = epoch; + try { + const r = await api('/api/step', {sid, packets: batch, frames: true}); + if (my === epoch) accept(r); + } catch (e) { status('Server error: ' + e.message); pause(); } + finally { sending = false; if (queue.length && my === epoch) pump(); } + } + function lock() { + try { const p = capture.requestPointerLock && capture.requestPointerLock(); if (p && p.catch) p.catch(() => {}); } catch (e) { /* headless */ } + } + document.addEventListener('pointerlockchange', () => { + if (document.pointerLockElement !== capture && running && mode === 'play') { + pause(); status('Mouse unlocked (Esc) · Paused. Click Resume to continue.'); + } + }); + const arrows = new Set(); + window.addEventListener('keydown', e => { + if (['INPUT', 'SELECT', 'TEXTAREA'].includes(document.activeElement.tagName)) return; + if (e.code === 'Escape' || e.code === 'KeyP') { if (running) pause(); return; } + if (e.code.startsWith('Arrow')) { arrows.add(e.code); e.preventDefault(); return; } + if (e.code === 'KeyQ' || e.code === 'Digit1' || e.code === 'Digit2') { + const want = e.code === 'Digit1' ? 'sword' : e.code === 'Digit2' ? 'bow' : null; + if (!want || (state && state.player.weapon !== want)) mouse[2] += 1; + e.preventDefault(); return; + } + const k = CODE[e.code]; + if (k) { e.preventDefault(); down.add(k); taps.add(k); } + }); + window.addEventListener('keyup', e => { + if (e.code.startsWith('Arrow')) arrows.delete(e.code); + const k = CODE[e.code]; + if (k) down.delete(k); + }); + capture.addEventListener('contextmenu', e => e.preventDefault()); + capture.addEventListener('pointerdown', e => { + capture.focus(); + if (running && mode === 'play' && document.pointerLockElement !== capture) lock(); + const k = e.button === 2 ? 'RMB' : e.button === 0 ? 'LMB' : null; + if (k) { down.add(k); taps.add(k); } + e.preventDefault(); + }); + window.addEventListener('pointerup', e => { down.delete(e.button === 2 ? 'RMB' : 'LMB'); }); + window.addEventListener('mousemove', e => { + if (document.pointerLockElement === capture) { mouse[0] += e.movementX; mouse[1] += e.movementY; } + else if (e.buttons && e.target === capture) { mouse[0] += e.movementX; mouse[1] += e.movementY; } + }); + capture.addEventListener('wheel', e => { e.preventDefault(); mouse[2] += e.deltaY > 0 ? 1 : -1; }, {passive: false}); + document.querySelectorAll('[data-key]').forEach(b => { + b.onpointerdown = e => { e.preventDefault(); b.setPointerCapture(e.pointerId); down.add(b.dataset.key); taps.add(b.dataset.key); }; + b.onpointerup = b.onpointercancel = () => down.delete(b.dataset.key); + }); + document.querySelectorAll('[data-wheel]').forEach(b => { b.onclick = () => { mouse[2] += 1; }; }); + function releaseAll() { down.clear(); taps.clear(); arrows.clear(); } + window.addEventListener('blur', () => { releaseAll(); if (running && mode === 'play') { pause(); status('Window lost focus · Paused. Click Resume to continue.'); } }); + document.addEventListener('visibilitychange', () => { if (document.hidden) { releaseAll(); if (running) pause(); } }); + + // ------------------------------------------------------------------ stepping and frames + function accept(r) { + state = r.state || r; + if (r.frames && r.frames.length) { + if (frames.length > 12) frames = frames.slice(-6); // keep latency bounded + frames.push(...r.frames); + } + panel(); + if (state.outcome) finish(); + } + function showFrames(now) { + if (frames.length && now - lastShown >= SUB_MS - 2) { + view.src = frames.shift(); + lastShown = now; + } + requestAnimationFrame(showFrames); + } + requestAnimationFrame(showFrames); + async function still() { + if (!sid) return; + const r = await api('/api/still', {sid}); + frames = [r.frame]; + state = r.state; panel(); + } + function panel() { + if (!state) return; + const p = state.player, b = state.boss; + $('#time').textContent = state.t.toFixed(1) + ' / ' + state.max_seconds + ' s'; + const o = state.options || {}, tier = tierInfo(o.resolved_from_tier); + $('#tier').textContent = tier ? tier.label + ' · d=' + o.difficulty : 'd=' + o.difficulty; + $('#php').textContent = p.hp.toFixed(1) + ' / ' + p.max_hp + (p.wither_effect_s > 0 ? ' (Wither damage for ' + p.wither_effect_s.toFixed(0) + 's)' : ''); + $('#wpn').textContent = (p.kit === 'iron' ? 'Iron ' : 'Diamond ') + (p.weapon === 'sword' ? 'sword ' + Math.round(p.attack_charge * 100) + '%' : + 'Bow ' + (p.bow_drawing ? Math.round(p.bow_charge * 100) + '%' : 'ready') + ' · Hits ' + p.arrows_hit + '/' + p.arrows_fired); + $('#bname').textContent = b.name; + $('#bhp').textContent = b.hp.toFixed(1) + ' / ' + b.max_hp; + $('#bphase').textContent = b.phase + (b.armored ? ' · Half-health armor' : '') + (b.crystals !== null ? ' · Crystals ' + b.crystals : '') + + (b.minions !== null && b.minions !== undefined ? ' · Minions ' + b.minions : '') + + (b.darkness_s ? ' · Darkness ' + b.darkness_s.toFixed(0) + 's' : ''); + } + function finish() { + stopLoop(); + // Show the terminal frame at once: frames play back ~0.2 s behind the simulation, so the result overlay would + // otherwise sit on a frame where the boss still has health left. + if (frames.length) { view.src = frames[frames.length - 1]; frames = []; } + window.__bbOutcome = state.outcome; + const label = {win: 'Victory', loss: 'Failure', timeout: 'Time up'}[state.outcome] || state.outcome; + overlay(label + ' · ' + state.t.toFixed(2) + ' seconds'); + if (mode === 'replay' && replayExpect) verifyReplay(); + else status('Match over: ' + label + ' · ' + state.packets + ' action packets. You can export the replay.'); + } + + // ------------------------------------------------------------------ loop control + function stopLoop() { running = false; clearInterval(timer); timer = null; $('#pause').textContent = 'Resume'; } + function startLoop() { + if (!sid || (state && state.outcome)) return; + running = true; $('#pause').textContent = 'Pause'; overlay(''); + clearInterval(timer); + if (mode === 'play') { subs = []; mouse = [0, 0, 0]; clock0 = performance.now(); subsDone = 0; timer = setInterval(sampleClock, 8); } + else timer = setInterval(tickAuto, 200); + } + function pause() { stopLoop(); releaseAll(); if (document.pointerLockElement) document.exitPointerLock(); overlay(state && state.outcome ? $('#overlay-text').textContent : 'Paused'); } + async function tickAuto() { + if (pending || !running) return; + pending = true; + const my = epoch; + try { + if (mode === 'demo') { + const r = await api('/api/scripted', {sid, n: 1, frames: true}); + if (my === epoch) accept(r); + } else if (mode === 'replay') { + if (!replayQueue.length) { if (state && !state.outcome) { stopLoop(); verifyReplay(); } } + else { const r = await api('/api/step', {sid, packets: [replayQueue.shift()], frames: true}); if (my === epoch) accept(r); } + } + } catch (e) { status('Server error: ' + e.message); stopLoop(); } + finally { pending = false; } + } + async function newSession(caseId, useMode, tier) { + if (!meta && !(await connect())) return false; + epoch++; stopLoop(); frames = []; replayQueue = []; replayExpect = null; queue = []; window.__bbOutcome = null; + if (sid) api('/api/close', {sid}).catch(() => {}); + const body = {case: caseId || $('#case').value, seed: Number($('#seed').value), tier: tier || $('#difficulty').value, + weapon: $('#weapon').value, camera: $('#camera').value}; + $('#case').value = body.case; + $('#difficulty').value = body.tier; tierHint(); + const r = await api('/api/new', body); + sid = r.sid; state = r.state; mode = useMode; panel(); + await still(); + return true; + } + $('#start').onclick = async () => { + try { + if (!(await newSession(null, 'play'))) return; + status('Match in progress: click the screen to lock the mouse (Esc unlocks and pauses). One action packet every 200 ms.'); + capture.focus(); startLoop(); + } catch (e) { status('Unable to start: ' + e.message); } + }; + $('#pause').onclick = () => { + if (running) pause(); + else if (sid && state && !state.outcome) { startLoop(); capture.focus(); if (mode === 'play') lock(); } + }; + $('#step').onclick = async () => { + if (!sid || (state && state.outcome)) return; + if (running) pause(); + overlay('Step'); + const sets = Array.from({length: 6}, () => heldNow()); + if (mode === 'demo') { accept(await api('/api/scripted', {sid, n: 1, frames: true})); } + else if (mode === 'replay') { if (replayQueue.length) accept(await api('/api/step', {sid, packets: [replayQueue.shift()], frames: true})); } + else { const p = packetText(sets, mouse); mouse = [0, 0, 0]; accept(await api('/api/step', {sid, packets: [p], frames: true})); } + }; + async function demo(caseId, tier) { + if (!(await newSession(caseId, 'demo', tier))) return false; + status('Scripted Demo: a reference controller reads internal state and emits valid 200 ms action packets.'); + startLoop(); + return true; + } + $('#demo').onclick = () => demo(null).catch(e => status('Demo failed: ' + e.message)); + $('#export').onclick = async () => { + if (!sid) { status('No match is available to export yet.'); return; } + const data = await api('/api/replay?sid=' + sid); + const blob = new Blob([JSON.stringify(data, null, 1)], {type: 'application/json'}); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = data.case_id.replace('/', '__') + '-seed' + data.engine_seed + '.replay.json'; + a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); + status('Exported ' + data.steps + ' action packets (' + data.rules + ') · Final-state hash: ' + data.final_hash.slice(0, 12)); + }; + $('#import').onclick = () => $('#file').click(); + $('#file').onchange = async e => { + const file = e.target.files[0]; e.target.value = ''; + if (!file) return; + try { + if (file.size > 12e6) throw Error('Replay must be 12 MB or smaller'); + await importReplay(JSON.parse(await file.text())); + } catch (err) { status('Import failed: ' + err.message); } + }; + async function importReplay(data) { + if (!meta && !(await connect())) return; + epoch++; stopLoop(); frames = []; + const r = await api('/api/import', {replay: data}); + if (sid) api('/api/close', {sid}).catch(() => {}); + sid = r.sid; state = r.state; mode = 'replay'; panel(); + replayQueue = data.packets.slice(); replayExpect = r.expect; + $('#case').value = data.case_id; + await still(); + status('Replay rules verified (' + data.rules + ') · Playing back ' + replayQueue.length + ' action packets…'); + startLoop(); + } + async function verifyReplay() { + const v = await api('/api/verify', {sid}); + const ok = v.final_hash === replayExpect.final_hash && v.outcome === replayExpect.outcome && v.ticks === replayExpect.ticks; + status('Replay finished: ' + ({win: 'Victory', loss: 'Failure', timeout: 'Time up'}[v.outcome] || 'Replay ended before the match concluded') + ' · ' + v.ticks + ' ticks · ' + (ok ? 'Final-state hash matches ✓' : 'Final state differs from replay ✗ (' + v.final_hash.slice(0, 10) + ' vs ' + String(replayExpect.final_hash).slice(0, 10) + ')')); + replayExpect = null; + } + + // ------------------------------------------------------------------ Browser automation interface + window.bossbenchUI = { + demo: (caseId, tier) => demo(caseId, tier), + start: (caseId, tier) => newSession(caseId, 'play', tier).then(() => { startLoop(); return true; }), + state: () => state, connected: () => !!meta, + }; + connect(); +})(); diff --git a/environments/games/web/games/minecraft_remake/style.css b/environments/games/web/games/minecraft_remake/style.css new file mode 100644 index 0000000000000000000000000000000000000000..44bae1e3b5b021f240b86cb2bcba75afd399786f --- /dev/null +++ b/environments/games/web/games/minecraft_remake/style.css @@ -0,0 +1,44 @@ +:root{color-scheme:dark;--paper:#ece6d6;--muted:#a7b3a2;--accent:#8fd16a;--bg:#1b1f17;--panel:#262c21;--edge:#4a5940;--warn:#e7b35d} +*{box-sizing:border-box} +body{margin:0;background:var(--bg) radial-gradient(circle at 20% -10%,#2f3a26 0,transparent 55%);color:var(--paper);font:15px/1.6 'Segoe UI','Microsoft YaHei',sans-serif} +main{max-width:1180px;margin:auto;padding:24px 24px 40px} +header{display:flex;gap:24px;align-items:baseline;justify-content:space-between;margin-bottom:18px} +h1{font-family:Georgia,'Microsoft YaHei',serif;font-size:29px;font-weight:600;line-height:1.3;margin:6px 0;letter-spacing:.5px} +header p{margin:0;color:var(--muted);font-size:13px} +code{font-family:Consolas,monospace;font-size:12px;color:var(--accent)} +a{color:var(--accent)} +a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,#capture:focus-visible{outline:3px solid var(--accent);outline-offset:3px} +.layout{display:grid;grid-template-columns:minmax(0,854px) 240px;gap:20px} +.stage{position:relative;align-self:start;border:2px solid #10130d;box-shadow:0 0 0 1px var(--edge);background:#0b0d09;aspect-ratio:854/480} +#view{display:block;width:100%;height:100%;image-rendering:pixelated;user-select:none} +#capture{position:absolute;inset:0;cursor:crosshair;touch-action:none} +#overlay{pointer-events:none;position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#0d110a55} +#overlay[hidden]{display:none} +#overlay div{padding:12px 25px;background:#141a10ee;text-align:center;border:2px solid var(--edge);font-size:22px;font-family:Georgia,'Microsoft YaHei',serif} +#offline{position:absolute;inset:0;display:flex;flex-direction:column;justify-content:center;padding:28px 40px;background:#12160fef;font-size:14px} +#offline[hidden]{display:none} +#offline h2{margin:0 0 8px;font-size:20px;color:var(--warn)} +#offline pre{white-space:pre-wrap;background:#0a0c08;border:1px solid var(--edge);padding:10px 12px;font:13px Consolas,monospace;color:#d8f0c4} +.toolbar{display:flex;flex-wrap:wrap;gap:9px;padding:12px;background:var(--panel);border:1px solid var(--edge);border-top:0} +button,select,input{font:inherit;border:1px solid var(--edge);border-radius:2px;background:#30382a;color:var(--paper);padding:7px 10px} +button{cursor:pointer;box-shadow:inset 0 -3px 0 #1d2318} +button:hover{border-color:var(--accent)} +button.primary{background:#5d8f3c;color:#0f140b;font-weight:700;box-shadow:inset 0 -3px 0 #3d6524} +select,input[type=number]{width:100%} +aside label{display:block;margin:12px 0 5px;color:var(--muted);font-size:13px} +.hint{margin:5px 0 0;color:var(--muted);font-size:12px} +aside h2{font-size:17px;margin:18px 0 10px} +aside>div:first-child h2{margin-top:0} +.panel{margin-top:16px;padding:10px 12px;background:var(--panel);border:1px solid var(--edge)} +.row{display:flex;justify-content:space-between;gap:10px;font-size:13px;color:var(--muted)} +.row b{color:var(--paper);font-weight:600;text-align:right} +dl{margin:8px 0} +dt{color:var(--accent);font-family:Consolas,monospace;font-size:12px} +dd{margin:0 0 10px;font-size:13px;color:var(--muted)} +#status{min-height:28px;margin:10px 0;color:var(--warn);font-size:13px;overflow-wrap:anywhere} +.note{color:var(--muted);font-size:13px} +.mobile{display:none;gap:6px;flex-wrap:wrap;padding:10px;background:var(--panel);border:1px solid var(--edge);border-top:0} +.mobile button{flex:1 1 22%;padding:12px 4px} +footer{border-top:1px solid var(--edge);margin-top:25px;padding-top:14px;display:flex;gap:18px;flex-wrap:wrap;font-size:13px} +@media (max-width:900px){.layout{grid-template-columns:1fr}main{padding:14px}header{flex-direction:column;gap:6px}.mobile{display:flex}} +@media (pointer:coarse){.mobile{display:flex}} diff --git a/environments/games/web/games/nfsmw_remake/compact_actions.json b/environments/games/web/games/nfsmw_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..3dfceed74e5a159168bef656ae8271180700cf4b --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/compact_actions.json @@ -0,0 +1,269 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "nfsmw_remake", + "version": "nfsmw-compact@1", + "note": "A 200 ms packet contains six sub-steps. Pedal and steering options hold keyboard inputs for different numbers of sub-steps to control throttle and steering angle. The game uses keyboard input.", + "heads": [ + { + "name": "pedal", + "options": [ + { + "label": "none" + }, + { + "label": "throttle_light", + "note": "the reference's corner exit: drive force limited by the friction circle", + "subs": [ + [], + [], + [], + [], + [], + [ + "W" + ] + ] + }, + { + "label": "throttle", + "keys": [ + "W" + ] + }, + { + "label": "brake", + "keys": [ + "S" + ] + } + ], + "note": "full throttle 65% of the reference packets, brake 16%, one sub-step in six 11% (corner exits, where the friction circle leaves little drive). A half throttle option was tried and dropped: it changed no result (v6 vs v7)." + }, + { + "name": "steer", + "options": [ + { + "label": "none" + }, + { + "label": "left_tap", + "note": "drag series: A and D are lane changes on a press (modes_drag.js input), so one press per packet", + "tap": [ + "A" + ] + }, + { + "label": "left_ease", + "subs": [ + [], + [], + [ + "A" + ], + [], + [ + "A" + ], + [] + ] + }, + { + "label": "left_hold", + "subs": [ + [ + "A" + ], + [], + [ + "A" + ], + [], + [ + "A" + ], + [] + ] + }, + { + "label": "left_hold_late", + "subs": [ + [], + [ + "A" + ], + [], + [ + "A" + ], + [], + [ + "A" + ] + ] + }, + { + "label": "left_more", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [], + [ + "A" + ], + [], + [ + "A" + ] + ] + }, + { + "label": "left_full", + "keys": [ + "A" + ] + }, + { + "label": "right_tap", + "tap": [ + "D" + ] + }, + { + "label": "right_ease", + "subs": [ + [], + [], + [ + "D" + ], + [], + [ + "D" + ], + [] + ] + }, + { + "label": "right_hold", + "subs": [ + [ + "D" + ], + [], + [ + "D" + ], + [], + [ + "D" + ], + [] + ] + }, + { + "label": "right_hold_late", + "subs": [ + [], + [ + "D" + ], + [], + [ + "D" + ], + [], + [ + "D" + ] + ] + }, + { + "label": "right_more", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [], + [ + "D" + ], + [], + [ + "D" + ] + ] + }, + { + "label": "right_full", + "keys": [ + "D" + ] + } + ], + "note": "left_tap / right_tap: one press per packet, the lane change of the drag series (modes_drag.js reads pressed A / D there). The duty options steer everywhere else." + }, + { + "name": "nitrous", + "options": [ + { + "label": "none" + }, + { + "label": "nitrous", + "note": "only burns while the throttle is down (nfscore.js carStep)", + "keys": [ + "Shift" + ] + } + ], + "note": "only burns while the throttle is down (nfscore.js carStep: engaged needs thr > 0)" + }, + { + "name": "press", + "note": "J (slow motion), K / L (gears, drag series only) and R (reset) act on a press (pressed.has in game.js), so each is one press at the start of the packet. The handbrake is held, and it shares this head because a handbrake turn and a gear change or a reset are never wanted in the same 200 ms.", + "options": [ + { + "label": "none" + }, + { + "label": "shift_up", + "tap": [ + "K" + ] + }, + { + "label": "shift_down", + "tap": [ + "L" + ] + }, + { + "label": "slowmo", + "tap": [ + "J" + ] + }, + { + "label": "reset", + "tap": [ + "R" + ] + }, + { + "label": "handbrake", + "note": "held, not a press: carStep reads it every tick. The reference controller never uses it; kept because it is a basic control of the event. It shares this head with the single presses because a handbrake turn and a gear change or a reset are never wanted in the same 200 ms", + "keys": [ + "Space" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/nfsmw_remake/cops.js b/environments/games/web/games/nfsmw_remake/cops.js new file mode 100644 index 0000000000000000000000000000000000000000..7c4d43a227d7de5861b5401ab8effb10b5e53439 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/cops.js @@ -0,0 +1,158 @@ +/* Police. Rules read from AI/Common/AIPursuit.cpp unless noted (all values in the VLT pursuitlevels table are approximations, by tier): + - busted meter: :1887-1940, up while a cop sees the player, the player is under BustSpeed and the nearest cop is within 15 m, down twice + as fast otherwise, busted above 5 (kBustedTimeout, kBustedCopDistance :1607-8; Sim/Common/Simulation.cpp:345 for the task rates); + - during a manual-reset flash the distance is x6 and the rate x4 (:1895-1909); + - sight: 150 m ahead of the cop, 50 m behind it, and the world ray must be clear (AIVehicleCopCar.cpp:88-168), helicopter 250 m (AIVehicleHelicopter.cpp:114); + - evade: more than 7 s unseen, then (unseen + hidden time) / evadetimeout reaches 1 (:2027-2061); seen again, it decays x0.93 per task (:2097); + - roadblocks: a request every 8-12 s with a probability (:2459-2507); a roadblock's cops join the chase after a spike hit (SpikesHit :2791); + - formations: FOLLOW, ROLLING_BLOCK, BOX_IN, PIT (:976-1010), cops within 60 m qualify (kFormationCandidateDistance :1221); + - spikes: a tyre over the strip punctures and blows 0.5 s later (DamageRacer.cpp:12), grip x0.3 (SuspensionRacer.cpp:1569); + - destroying cops: bonus multiplier up to 3 inside DestroyCopBonusTime (IncNumCopsDestroyed :917). + A cop is a free body, not on rails: with sight it drives straight at its slot (sight means the straight line is clear), without sight it follows + the route towards where the player was last seen. All decisions draw from the game RNG, and the controller never copies the game. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, N = root.NativeBench, clamp = C.clamp, P = C.PLAYER; + const BUST_MAX = 5, BUST_DIST = 15, FRONT_LOS = 150, REAR_LOS = 50, HELI_LOS = 250, EVADE_AFTER = 7, RESET_DIST = 6, RESET_RATE = 4, RECYCLE_DIST = 320, RECYCLE_S = 6, BARRIER_R = 2.6, BARRIER_KEEP = 0.62; + const wrapTo = (R, v, ref) => { if (!R.loop) return v; let ds = (v - ref) % R.L; if (ds > R.L / 2) ds -= R.L; else if (ds < -R.L / 2) ds += R.L; return ref + ds; }; + M.wrapTo = wrapTo; + // o: copsMax, top, grip, accel, spawnGap, formations, rbChance, spikeChance, heli, heliAfter, heliFuel, heliGap, bustKph + M.initPolice = (g, o) => { + g.pol = Object.assign({ bust: 0, seen: 0, sinceSeen: 0, evade: 0, spawnT: o.spawnGap, rbT: 9, formT: 4, formation: 'FOLLOW', pursuitT: 0, destroyed: 0, bonusT: 0, bonusMult: 1, lockT: 0, lastS: g.s, heliT: o.heliAfter, combo: 0, sawNow: 1, inSight: 1 }, o); + g.cops = []; g.props = []; g.blocks = []; g.heli = null; g.puncT = 0; g.punc = 0; + }; + M.spawnCop = (g, s, lat, dir, state = 'chase', h) => { + const R = g.route, a = C.routeAt(R, s, lat), c = { x: a.x, y: a.y, h: h !== undefined ? h : dir > 0 ? a.h : a.h + Math.PI, v: state === 'rb' ? 0 : 20, s, lat, hp: 100, state, chasing: state === 'chase' ? 1 : 0, dead: 0, gone: 0, slot: g.cops.length, sees: 0, hitT: 0, deadT: 0, lostT: 0 }; + g.cops.push(c); return c; + }; + const destroy = (g, c, why) => { + c.dead = 1; c.chasing = 0; c.deadT = 4; const p = g.pol; p.destroyed++; + p.bonusMult = p.bonusT > 0 ? Math.min(3, p.bonusMult + 1) : 1; p.bonusT = 8; p.combo = p.bonusMult; + g.events.push({ type: 'cop_destroyed', why, mult: p.bonusMult }); + }; + M.destroyCop = destroy; + // Slot offsets in the player's frame: [metres ahead, metres to the left]. Numbers are original: the formation classes' tables are VLT-driven. + const SLOTS = { FOLLOW: [[-11, -2.5], [-11, 2.5], [-22, 0], [-30, -4], [-30, 4]], ROLLING_BLOCK: [[14, -3.2], [14, 3.2], [24, 0], [-12, 0], [-22, 3]], BOX_IN: [[-6, -4.2], [-6, 4.2], [12, 0], [-14, 0], [-22, 0]], PIT: [[-3, -3.4], [-3, 3.4], [-12, 0], [-22, 3], [-22, -3]] }; + function stepCop(g, c, wdt, losTick) { + const p = g.pol, R = g.route, car = g.car; + if (c.deadT > 0) { c.deadT -= wdt; c.v = Math.max(0, c.v - 12 * wdt); c.x += Math.cos(c.h) * c.v * wdt; c.y += Math.sin(c.h) * c.v * wdt; if (c.deadT <= 0) c.gone = 1; return; } + const dx = car.x - c.x, dy = car.y - c.y, dist = Math.hypot(dx, dy); + c.s = C.routeNear(R, c.x, c.y, wrapTo(R, c.s, g.s), 30, 30); c.lat = C.routeLat(R, c.x, c.y, c.s); + if (losTick) { const dot = (Math.cos(c.h) * dx + Math.sin(c.h) * dy) / (dist || 1); c.sees = (dist < REAR_LOS || (dist < FRONT_LOS && dot > 0)) && C.lineClear(c.x, c.y, car.x, car.y) ? 1 : 0; } + if (c.state === 'rb') { // parked across the road; joins in once the player is past or a strip was hit + if (g.s - c.s > 12 || c.join) { c.state = 'chase'; c.chasing = 1; } + else return; + } + let tx, ty; + if (c.sees && dist < 60) { // in formation (kFormationCandidateDistance) + const slots = SLOTS[p.formation], sl = slots[c.slot % slots.length], ch = Math.cos(car.h), sh = Math.sin(car.h), lead = C.speed(car) * 0.25; + tx = car.x + ch * (sl[0] + lead) - sh * sl[1]; ty = car.y + sh * (sl[0] + lead) + ch * sl[1]; + if (p.formation === 'PIT' && (c.slot % slots.length) < 2 && dist < 9) { tx = car.x + ch * lead; ty = car.y + sh * lead; } // the ram itself + } else if (c.sees) { const lead = C.speed(car) * 0.35; tx = car.x + Math.cos(car.h) * lead; ty = car.y + Math.sin(car.h) * lead; } + else { // search: along the route towards the last known position (the route is where the sim keeps its cops) + const dS = wrapTo(R, p.lastS, c.s) - c.s, dirn = dS >= 0 ? 1 : -1, a = C.routeAt(R, c.s + dirn * Math.max(10, c.v * 0.6), clamp(c.lat, -3, 3)); tx = a.x; ty = a.y; + } + let want = Math.atan2(ty - c.y, tx - c.x) - c.h; want = Math.atan2(Math.sin(want), Math.cos(want)); + const grip = P.grip * p.grip, rate = grip / Math.max(c.v, 6); + c.h += clamp(want, -rate * wdt, rate * wdt); + // Speed: the road's limit ahead, its class top, and the gap to its slot when it has sight (it has to hold station, not overshoot). + const prof = C.profile(R, grip, P.aero, P.brake * 0.9, p.top); let lim = Math.min(C.profileAt(R, prof, c.s + c.v * 0.3), C.profileAt(R, prof, c.s - c.v * 0.3)); + if (Math.abs(want) > 0.9) lim = Math.min(lim, 12); + if (!c.sees) lim = Math.min(lim, p.searchTop); + else if (dist < 60) { const sd = Math.hypot(tx - c.x, ty - c.y), ahead = Math.cos(want) > 0; lim = Math.min(lim, Math.max(4, C.speed(car) + (ahead ? clamp(sd * 0.5, -6, p.close) : -6))); } + if (c.v > lim) c.v = Math.max(lim, c.v - P.brake * 0.9 * wdt); + else c.v = Math.min(lim, c.v + Math.max(0.5, C.driveAt(c.v) * p.accel - P.drag * c.v * c.v - P.roll) * wdt); + c.x += Math.cos(c.h) * c.v * wdt; c.y += Math.sin(c.h) * c.v * wdt; + const q = C.road(c.x, c.y), over = q.d + 1.2; if (over > 0) { c.x -= q.nx * over; c.y -= q.ny * over; c.v *= 1 - Math.min(0.4, 2 * wdt); } + } + // Contact with the player: equal masses along the normal, closing speed scrapes the cop's damage (DamageVehicle::OnImpact; the table is VLT). + function contact(g, c) { + const car = g.car, dx = car.x - c.x, dy = car.y - c.y, d2 = dx * dx + dy * dy, R2 = M.carRadius * 2; if (d2 >= R2 * R2) return; + const d = Math.max(0.01, Math.sqrt(d2)), nx = dx / d, ny = dy / d, cvx = Math.cos(c.h) * c.v, cvy = Math.sin(c.h) * c.v, rel = (car.vx - cvx) * nx + (car.vy - cvy) * ny, push = R2 - d; + car.x += nx * push * 0.5; car.y += ny * push * 0.5; c.x -= nx * push * 0.5; c.y -= ny * push * 0.5; + if (rel >= 0) return; + const j = -0.75 * rel; car.vx += nx * j; car.vy += ny * j; c.v = Math.max(0, c.v - j * (Math.cos(c.h) * -nx + Math.sin(c.h) * -ny) * -1); if (c.v > 90) c.v = 90; + if (c.hitT <= 0 && -rel > 3) { + c.hitT = 0.4; g.lastHit = 0.25; g.hits++; const dmg = -rel * g.pol.copFrail; c.hp -= dmg; + if (c.state === 'rb') { c.join = 1; for (const o of g.cops) if (o.state === 'rb') o.join = 1; } + g.events.push({ type: 'cop_contact', speed: -rel, hp: c.hp }); + if (c.hp <= 0) destroy(g, c, 'ram'); + } + } + const spawnAway = (g) => { + const p = g.pol, R = g.route, ahead = (p.sawNow || p.aheadBlind) && N.rand(g) < p.aheadChance, S = g.s + (ahead ? 320 + N.rand(g) * 120 : -(210 + N.rand(g) * 90)), lat = (N.rand(g) < 0.5 ? -1 : 1) * R.halfW * 0.4; + if (!R.loop && (S < 20 || S > R.L - 20)) return; + const c = M.spawnCop(g, S, lat, ahead ? -1 : 1, 'chase'); + c.slot = p.nextSlot = (p.nextSlot || 0) + 1; + }; + function stepRoadblocks(g, wdt) { + const p = g.pol, R = g.route; p.rbT -= wdt; + // AIPursuit.cpp:2459: a request every 8-12 s; the probability and the spike chance are the heat level's VLT values (approximations). + if (p.rbT <= 0) { + p.rbT = 8 + N.rand(g) * 4; + if (!g.props.some(x => x.type === 'barrier') && p.rbChance > 0 && N.rand(g) < p.rbChance && C.speed(g.car) > 15 && !p.lockT) { + const S = g.s + Math.max(180, C.speed(g.car) * 5.5), a = C.routeAt(R, S), h = a.h, kN = Math.abs(a.k); if (kN < 0.012) { + const hw = R.halfW, gapSide = N.rand(g) < 0.5 ? -1 : 1, gapW = p.rbGap, block = []; for (let l = -hw + 1.8; l < hw - 1.6; l += 4.3) if (gapSide * l < hw - gapW || Math.abs(l) < 0) block.push(l); + block.forEach((l, i) => { if (i % 2 === 0) { const c = M.spawnCop(g, S, l, 1, 'rb', h + Math.PI / 2); c.slot = i; } else { const b = C.routeAt(R, S, l); g.props.push({ type: 'barrier', x: b.x, y: b.y, h: h + Math.PI / 2, s: S, lat: l, ttl: 40 }); } g.blocks.push({ s: S, lat: l }); }); + if (N.rand(g) < p.spikeChance) { const S2 = S - 26, side = -gapSide, L = hw + 3, l0 = gapSide * (hw - gapW) + side * 0 - gapSide * L / 2, b = C.routeAt(R, S2, l0); g.props.push({ type: 'spike', x: b.x, y: b.y, h: h, s: S2, lat: l0, len: L, ttl: 40 }); } + g.events.push({ type: 'roadblock', s: S, gap: gapSide }); + } + } + } + for (const o of g.props) if (o.ttl !== undefined) { o.ttl -= wdt; if (o.ttl <= 0 || g.s - wrapTo(R, o.s, g.s) > 160) o.gone = 1; } + g.props = g.props.filter(o => !o.gone); + g.blocks = g.blocks.filter(b => g.s - wrapTo(R, b.s, g.s) < 40); + for (const o of g.props) if (o.type === 'barrier' && !o.gone) { const dx = g.car.x - o.x, dy = g.car.y - o.y; if (dx * dx + dy * dy < BARRIER_R * BARRIER_R) { const v = C.speed(g.car); g.car.vx *= BARRIER_KEEP; g.car.vy *= BARRIER_KEEP; o.gone = 1; g.hits++; g.lastHit = 0.3; g.events.push({ type: 'barrier', speed: v }); for (const k of g.cops) if (k.state === 'rb') k.join = 1; } } + // Spikes: wheels are ±0.9 m off the centreline; each side over the strip is two tyres, punctured now and blown 0.5 s later. + const c = g.car; + for (const o of g.props) if (o.type === 'spike' && !o.used) { + const a = C.routeAt(R, o.s), ds = (c.x - a.x) * Math.cos(a.h) + (c.y - a.y) * Math.sin(a.h); + if (Math.abs(ds) < C.speed(c) * wdt + 0.6) { let n = 0; for (const w of [-0.9, 0.9]) if (Math.abs(g.lat + w - o.lat) < o.len / 2) n += 2; if (n && !g.flash) { o.used = 1; g.punc = Math.max(g.punc, n); g.puncT = 0.5; for (const k of g.cops) if (k.state === 'rb') k.join = 1; g.events.push({ type: 'spikes', tyres: n }); } } + } + if (g.puncT > 0) { g.puncT -= wdt; if (g.puncT <= 0) c.tires = Math.max(c.tires, g.punc); } + } + function stepHeli(g, wdt) { + const p = g.pol, car = g.car; if (!p.heli) return; + if (!g.heli) { p.heliT -= wdt; if (p.heliT <= 0 && !p.lockT) { g.heli = { x: car.x - Math.cos(car.h) * 200, y: car.y - Math.sin(car.h) * 200, z: 34, h: car.h, fuel: p.heliFuel, sees: 0, gone: 0 }; g.events.push({ type: 'helicopter' }); } return; } + const h = g.heli, sp = C.speed(car), lead = sp * 0.4 + 30, ch = Math.cos(car.h), sh = Math.sin(car.h), tx = car.x + ch * lead, ty = car.y + sh * lead, dx = tx - h.x, dy = ty - h.y, d = Math.hypot(dx, dy) || 1, v = Math.min(85, d * 1.4); // AIActionHeliPursuit.cpp:26,leadDist + h.x += dx / d * v * wdt; h.y += dy / d * v * wdt; h.h = Math.atan2(dy, dx); h.fuel -= wdt; h.sees = Math.hypot(car.x - h.x, car.y - h.y) < HELI_LOS ? 1 : 0; + if (h.fuel <= 0) { g.heli = null; p.heliT = p.heliGap; g.events.push({ type: 'helicopter_leaves' }); } + } + // Returns nothing; updates sight, the bust meter, spawns and contacts. evadeOn: whether the evade meter runs (pursuit only). + M.stepPolice = (g, wdt, evadeOn) => { + const p = g.pol, car = g.car, R = g.route, losTick = g.t % 4 === 0; + if (p.bonusT > 0) p.bonusT = Math.max(0, p.bonusT - wdt); + if (p.lockT > 0) p.lockT = Math.max(0, p.lockT - wdt); + p.formT -= wdt; if (p.formT <= 0) { p.formT = 9 + N.rand(g) * 6; p.formation = p.formations[Math.floor(N.rand(g) * p.formations.length) % p.formations.length]; } + let seen = 0, near = Infinity; + for (const c of g.cops) { if (c.gone) continue; c.hitT = Math.max(0, c.hitT - wdt); stepCop(g, c, wdt, losTick); if (!c.dead && c.state !== 'rb') { if (c.sees) seen = 1; near = Math.min(near, Math.hypot(car.x - c.x, car.y - c.y)); } contact(g, c); } + // Out of sight and far behind for a while: gone, so the slot can spawn a cop that can still engage (RemoveUnwantedVehicles / StartFlee; the distances are approximations). + for (const c of g.cops) { if (c.dead || c.state === 'rb') continue; const far = !c.sees && Math.hypot(car.x - c.x, car.y - c.y) > RECYCLE_DIST; c.lostT = far ? c.lostT + wdt : 0; if (c.lostT > RECYCLE_S) c.gone = 1; } + g.cops = g.cops.filter(c => !c.gone); + for (let i = 0; i < g.cops.length; i++) for (let j = i + 1; j < g.cops.length; j++) { const a = g.cops[i], b = g.cops[j]; if (a.dead || b.dead) continue; const dx = a.x - b.x, dy = a.y - b.y, d2 = dx * dx + dy * dy; if (d2 < 10 && d2 > 1e-4 && a.state !== 'rb' && b.state !== 'rb') { const d = Math.sqrt(d2), pu = (3.2 - d) * 0.5; a.x += dx / d * pu; a.y += dy / d * pu; b.x -= dx / d * pu; b.y -= dy / d * pu; } } + stepHeli(g, wdt); if (g.heli && g.heli.sees) seen = 1; + stepRoadblocks(g, wdt); + p.sawNow = seen; + const active = g.cops.filter(c => !c.dead && c.state !== 'rb').length; + p.spawnT -= wdt; if (p.spawnT <= 0 && active < p.copsMax && !p.lockT) { p.spawnT = p.spawnGap; spawnAway(g); } + // Bust meter (AIPursuit.cpp:1889-1940, the flash rules at :1895-1909). + const flashing = g.flash > 0, bdist = BUST_DIST * (flashing ? RESET_DIST : 1), slow = flashing || C.speed(car) < p.bustSpeed; + if (seen) { p.seen += wdt; p.sinceSeen = 0; p.lastS = g.s; p.pursuitT += wdt; } else p.sinceSeen += wdt; + // mIsPerpInSight is "a cop saw the perp within the last 7 s" (AIPursuit.cpp:2000), not "a cop sees the perp now". + p.inSight = p.sinceSeen < EVADE_AFTER ? 1 : 0; + p.bust = Math.max(0, p.bust + (p.inSight && slow && near < bdist ? (flashing ? RESET_RATE : 1) : -2) * wdt); + if (evadeOn) { + if (seen) p.evade *= Math.pow(0.93, wdt * 15); + else if (p.sinceSeen > EVADE_AFTER) p.evade = Math.max(p.evade, Math.min(1, p.sinceSeen / p.evadeTimeout)); + } + if (p.bust > BUST_MAX) { p.bust = BUST_MAX; g.lose('busted'); } + }; + M.BUST_MAX = BUST_MAX; + M.bustHp = g => Math.round((BUST_MAX - g.pol.bust) * 10); + // Road users for the controller: decided poses only. + M.copUsers = (g, R, out) => { + const add = (s, lat, vs, cop, vl = 0) => out.push({ s: wrapTo(R, s, g.s), lat, vs, r: 2, cop, vl }); + for (const c of g.cops) { if (c.gone) continue; const dh = c.h - C.routeAt(R, c.s).h, still = c.dead || c.state === 'rb'; add(c.s, c.lat, still ? 0 : c.v * Math.cos(dh), still ? 0 : 1, still ? 0 : c.v * Math.sin(dh)); } + for (const o of g.props) if (o.type === 'barrier') add(o.s, o.lat, 0); else if (o.type === 'spike' && !o.used) for (let l = -o.len / 2; l <= o.len / 2 + 0.01; l += 2) add(o.s, o.lat + l, 0); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/draw.js b/environments/games/web/games/nfsmw_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..09c5cd581b317a7f8c194d576c34cad689dcc524 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/draw.js @@ -0,0 +1,166 @@ +/* NFS Most Wanted events - Module.draw: the WebGL chase view plus an original Canvas 2D HUD (speed, gear, nitrous and Speedbreaker + gauges, route minimap, event panel). BossBench additions: both public health bars, fight timer and the native tick rate. + Read-only on the game state. + 2026-11-08: what the agent needs from the picture alone. + - Threat telegraphs: a warning strip when a roadblock or spike strip is on the road ahead, when a cop holds a ramming slot + beside the car, when the helicopter's light is on the car, when the bust meter rises; edge arrows for cops and rivals + outside the picture (behind, round a corner); a frame around the rear-view mirror when a cop is in it. + - The drag series' manual box: a tachometer with the shift window (the perfect-shift band of carStep) and a light that turns + green there, the launch band during staging, and the keys to press. A player who only holds W knew none of this. + - HUD panels keep to the screen edges and are smaller, so more of the road and the cars stays visible. + Everything here is drawn from state the simulation already decided this tick; nothing is written back. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, R = M.R3; + const W = 854, H = 480; + const panel = (c, x, y, w, h, a = 0.58) => { c.fillStyle = `rgba(10,14,22,${a})`; c.beginPath(); c.roundRect(x, y, w, h, 6); c.fill(); }; + const bar = (c, x, y, w, h, v, col, back = 'rgba(255,255,255,.14)') => { c.fillStyle = back; c.fillRect(x, y, w, h); c.fillStyle = col; c.fillRect(x, y, w * C.clamp(v, 0, 1), h); }; + const LABEL = { time: 'Time expired', gap: 'Rival pulled away', blown: 'Engine blown', totaled: 'Crash wreck', busted: 'Busted', knocked: 'Eliminated in last place', score: 'Lost on total score' }; + // HUD rectangles [x0, y0, x1, y1]; the view metric counts a target under one of these as not visible. + const RECT = { tier: [8, 8, 150, 46], event: [158, 8, 696, 46], clock: [704, 8, 846, 46], speedo: [708, 392, 846, 472], map: [10, 372, 108, 470], tach: [708, 352, 846, 382] }; + M.hudRects = Object.values(RECT); + const FONT = '"Microsoft YaHei",Consolas,sans-serif'; + function minimap(g, c) { + const R0 = g.route, size = 98, x0 = RECT.map[0], y0 = RECT.map[1], big = R0.name === 'downtown', span = R0.name === 'strip' ? 700 : big ? 200 : 460, k = size / 2 / span; + panel(c, x0, y0, size, size, 0.62); c.save(); c.beginPath(); c.rect(x0, y0, size, size); c.clip(); + const car = g.car, tx = u => x0 + size / 2 + (u - car.x) * k, ty = v => y0 + size / 2 - (v - car.y) * k; + c.lineWidth = Math.max(2.4, 8 * k * 6); c.strokeStyle = 'rgba(190,200,215,.28)'; + for (const st of C.streets) { c.beginPath(); st.forEach((p, i) => i ? c.lineTo(tx(p[0]), ty(p[1])) : c.moveTo(tx(p[0]), ty(p[1]))); c.stroke(); } + c.strokeStyle = 'rgba(245,240,225,.85)'; c.beginPath(); for (let i = 0; i <= R0.n; i += 6) { const u = i % R0.n; const px = tx(R0.x[u]), py = ty(R0.y[u]); i ? c.lineTo(px, py) : c.moveTo(px, py); } if (R0.loop) c.closePath(); c.stroke(); + const dot = (x, y, col, r = 3) => { c.fillStyle = col; c.beginPath(); c.arc(tx(x), ty(y), r, 0, 7); c.fill(); }; + for (const gt of g.gates || []) if (!gt.done) { const a = C.routeAt(R0, gt.s !== undefined ? gt.s : g.s0 + gt.at); dot(a.x, a.y, gt.kind === 'trap' ? '#ffb037' : '#7dff9a', 3.2); } + for (const r of g.rivals) if (!r.gone) dot(r.x, r.y, r.name === 'champion' ? '#ff4a3a' : '#ffffff'); + for (const b of g.breakers || []) if (!(b.rearm > 0)) dot(b.x, b.y, '#ff8a3c', 3); + for (const p of g.cops) if (!p.gone && !p.dead) dot(p.x, p.y, (g.t >> 4) % 2 ? '#4a8cff' : '#ff4a5a'); + for (const p of g.props || []) if (!p.gone && p.type !== 'cone') dot(p.x, p.y, p.type === 'spike' ? '#ffd020' : '#ffe030', 2.4); + if (g.heli && !g.heli.gone) dot(g.heli.x, g.heli.y, '#ffffff', 2.6); + c.translate(tx(car.x), ty(car.y)); c.rotate(-car.h); c.fillStyle = '#ffb060'; c.beginPath(); c.moveTo(7, 0); c.lineTo(-4, 4); c.lineTo(-4, -4); c.closePath(); c.fill(); c.restore(); + } + // ---- telegraphs: everything here is a fact the sim decided already (a placed prop, a cop's position, the formation) ---- + const warnings = []; + function threats(g, info) { + warnings.length = 0; info.warn = []; info.arrows = []; info.flames = []; info.cover = []; + const car = g.car, R = g.route, sp = Math.max(C.speed(car), 5), ch = Math.cos(car.h), sh = Math.sin(car.h); + if (g.outcome) return; + // roadblock / spikes on the road ahead (cops.js places them max(180, 5.5 v) m ahead; the original 250 m) + let rb = null, sk = null; + for (const p of g.props || []) { if (p.gone || p.used) continue; const ds = M.wrapTo ? M.wrapTo(R, p.s, g.s) - g.s : p.s - g.s; if (ds <= 0 || ds > 320) continue; if (p.type === 'spike') { if (!sk || ds < sk.ds) sk = { ds, p }; } else if (p.type === 'barrier') { if (!rb || ds < rb.ds) rb = { ds, p }; } } + if (rb) { warnings.push({ col: '#ffb020', text: `Roadblock ahead: ${Math.round(rb.ds)} m (${(rb.ds / sp).toFixed(1)} s)` }); info.warn.push('roadblock'); } + if (sk) { warnings.push({ col: '#ffd020', text: `Spike strip: ${Math.round(sk.ds)} m · on the ${sk.p.lat > 0 ? 'left' : 'right'} side` }); info.warn.push('spikes'); } + // ramming formation: a cop with sight inside 12 m while PIT or BOX_IN is the formation + if (g.pol) { + const close = g.cops.filter(k => !k.dead && !k.gone && k.state !== 'rb' && k.sees && Math.hypot(k.x - car.x, k.y - car.y) < 12); + if (close.length && (g.pol.formation === 'PIT' || g.pol.formation === 'BOX_IN')) { const k = close[0], side = (-(k.x - car.x) * sh + (k.y - car.y) * ch) > 0 ? 'left' : 'right'; warnings.push({ col: '#ff4a5a', text: g.pol.formation === 'PIT' ? `Police car ${side} rear ready to ram` : 'Police car box-in' }); info.warn.push('pit'); } + if (g.heli && !g.heli.gone && g.heli.sees) { warnings.push({ col: '#cfe0ff', text: 'Helicopter spotlight locked on' }); info.warn.push('heli'); } + if (g.pol.bust > 0.03) info.warn.push('bust'); + } + // edge arrows: cops within 160 m and rivals within 200 m that are not in the main picture + const sc = R3sc(g); + const arrow = (kind, ref, x, y, col) => { + if (!sc) return; const p = sc.project(x, y, 0.8); const inside = p.front && p.x > 8 && p.x < W - 8 && p.y > 50 && p.y < H - 8; if (inside) return; + // direction in the car's frame -> a point on an ellipse around the screen centre + const dx = x - car.x, dy = y - car.y, fwd = dx * ch + dy * sh, left = -dx * sh + dy * ch, ang = Math.atan2(-left, fwd); // 0 = ahead, +pi/2 = right + info.arrows.push({ kind, ref, ang, dist: Math.hypot(dx, dy), col }); + }; + g.cops.forEach((k, i) => { if (!k.gone && !k.dead && Math.hypot(k.x - car.x, k.y - car.y) < 160) arrow('cop', i, k.x, k.y, (g.t >> 3) % 2 ? '#ff4a5a' : '#4a8cff'); }); + g.rivals.forEach((r, i) => { if (!r.gone && !r.out && Math.hypot(r.x - car.x, r.y - car.y) < 200) arrow('rival', i, r.x, r.y, r.name === 'champion' ? '#ff4a3a' : '#ffffff'); }); + g.rivals.forEach((r, i) => { if (!r.gone && !r.out && (r.nosT > 0 || r.trapNos > 0) && r.nos > 0.02) info.flames.push(i); }); + if (g.heli && !g.heli.gone) arrow('heli', 0, g.heli.x, g.heli.y, '#e8f0ff'); + } + let cur = null; const R3sc = () => cur; // the scene this frame was rendered with (R3.render returns it) + function drawArrows(c, info) { + // one arrow per side of the screen at most: overlapping arrows (two rivals right behind) read as one, the nearest wins + const drawn = []; + for (const a of [...info.arrows].sort((p, q) => p.dist - q.dist)) { + const s = Math.sin(a.ang), co = Math.cos(a.ang), x = W / 2 + s * 380, y = H / 2 + 24 - co * 200; + let cx = C.clamp(x, 26, W - 26), cy = C.clamp(y, 64, H - 70); + if (cy >= H - 100 && Math.abs(cx - W / 2) < 130) cx = W / 2 + (s >= 0 ? 130 : -130); // behind: either side of the car, not over it + if (cy > 350 && (cx < 122 || cx > 696)) cy = 350; // clear of the minimap and the speedometer + if (drawn.some(d => Math.hypot(d[0] - cx, d[1] - cy) < 34)) continue; drawn.push([cx, cy]); + const near = C.clamp(1 - a.dist / 160, 0.25, 1), size = 9 + 9 * near; + c.save(); c.translate(cx, cy); c.rotate(a.ang); c.globalAlpha = 0.55 + 0.45 * near; c.fillStyle = 'rgba(0,0,0,.6)'; c.beginPath(); c.moveTo(0, -size - 3); c.lineTo(size * 0.85 + 3, size * 0.6 + 2); c.lineTo(-size * 0.85 - 3, size * 0.6 + 2); c.closePath(); c.fill(); + c.fillStyle = a.col; c.beginPath(); c.moveTo(0, -size); c.lineTo(size * 0.85, size * 0.6); c.lineTo(-size * 0.85, size * 0.6); c.closePath(); c.fill(); c.restore(); + c.globalAlpha = 1; c.font = 'bold 10px Consolas,monospace'; c.fillStyle = '#ffffff'; c.textAlign = 'center'; c.fillText(Math.round(a.dist) + 'm', cx, cy + (cy > H / 2 ? -14 : 22)); c.textAlign = 'left'; + } + } + // One row at the bottom centre, on the road just in front of the bumper: the horizon band (y 150-190), where a roadblock + // 200 m ahead appears, stays clear. + function drawWarnings(c, g) { + if (!warnings.length) return; + c.font = `bold 14px ${FONT}`; const widths = warnings.map(w => c.measureText(w.text).width + 30), total = widths.reduce((a, b) => a + b, 0) + 8 * (warnings.length - 1), y = H - 32; + let x = W / 2 - total / 2; + M.hudInfo.cover.push([x, y, x + total, y + 24]); + for (const [i, w] of warnings.entries()) { + const tw = widths[i], on = (g.t >> 3) % 2 === 0; + c.fillStyle = 'rgba(10,10,14,.72)'; c.beginPath(); c.roundRect(x, y, tw, 24, 4); c.fill(); c.strokeStyle = w.col; c.lineWidth = on ? 3 : 1.5; c.stroke(); + c.fillStyle = w.col; c.beginPath(); c.moveTo(x + 9, y + 18); c.lineTo(x + 15, y + 6); c.lineTo(x + 21, y + 18); c.closePath(); c.fill(); c.fillStyle = '#111'; c.fillRect(x + 14.2, y + 10, 1.6, 4.5); + c.fillStyle = '#ffffff'; c.textAlign = 'left'; c.fillText(w.text, x + 25, y + 17); x += tw + 8; + } + } + // mirror frame (renderer3d draws the mirror image itself); red border while a cop is in it + function mirrorFrame(c, g) { + const sc = R3sc(g); if (!sc || !sc.mirrorOn) return; const [x0, y0, x1, y1] = sc.mirrorRect; + const copIn = g.cops.some(k => { if (k.gone || k.dead) return false; const dx = k.x - g.car.x, dy = k.y - g.car.y, fwd = dx * Math.cos(g.car.h) + dy * Math.sin(g.car.h); return fwd < 0 && Math.hypot(dx, dy) < 120; }); + c.strokeStyle = copIn && (g.t >> 3) % 2 ? '#ff4a5a' : 'rgba(230,236,245,.85)'; c.lineWidth = 2.5; c.strokeRect(x0 - 1, y0 - 1, x1 - x0 + 2, y1 - y0 + 2); + c.font = `10px ${FONT}`; c.fillStyle = 'rgba(230,236,245,.85)'; c.fillText('Rearview mirror', x0 + 3, y1 + 11); + } + // tachometer: fraction of the current gear's top speed (carStep's u), shift band 0.88-0.99, limiter at 1 + function tach(g, c) { + const car = g.car, [x, y, x1, y1] = RECT.tach, w = x1 - x, h = y1 - y, staging = g.pre > 0 && g.rev !== undefined; + const fwd = Math.max(0, car.vx * Math.cos(car.h) + car.vy * Math.sin(car.h)), u = staging ? g.rev : C.clamp(fwd / C.TOPS[car.gear], 0, 1.05); + const band = staging ? [0.62, 0.86] : [0.88, 0.99], inBand = u >= band[0] && u <= band[1]; + panel(c, x, y, w, h, 0.7); const bx = x + 6, bw = w - 12, by = y + 6; + c.fillStyle = 'rgba(255,255,255,.12)'; c.fillRect(bx, by, bw, 9); + c.fillStyle = 'rgba(90,255,140,.55)'; c.fillRect(bx + bw * band[0], by, bw * (band[1] - band[0]), 9); + if (!staging) { c.fillStyle = 'rgba(255,70,60,.55)'; c.fillRect(bx + bw * 0.99, by, bw * 0.01 + 2, 9); } + c.fillStyle = inBand ? '#7dff9a' : u > band[1] ? '#ff5a4a' : '#ffd08a'; c.fillRect(bx, by + 2, bw * C.clamp(u, 0, 1), 5); + c.font = `bold 11px ${FONT}`; c.fillStyle = inBand ? '#7dff9a' : '#c6d0dc'; + c.fillText(staging ? (inBand ? 'Launch RPM ✓ Hold steady' : g.rev < band[0] ? 'Hold W to raise RPM into the green zone' : 'RPM too high; release W briefly') : car.gear >= 5 ? 'Top gear · Stay below the redline' : inBand ? '▶ Press K to upshift' : u > band[1] ? 'Press K to upshift now!' : `RPM → Green zone: press K`, bx, by + 21); + if (inBand && !staging && car.gear < 5 && (g.t >> 2) % 2) { c.strokeStyle = '#7dff9a'; c.lineWidth = 2; c.strokeRect(x + 1, y + 1, w - 2, h - 2); } + } + M.draw = function (g, c) { + const sc = R.render(g, c), info = {}; cur = sc; + M.hudInfo = info; + const car = g.car, kmh = C.speed(car) * 3.6, h = g.health(), hud = (M.MODES[g.key].hud || (() => ({ label: '', detail: '' })))(g); + threats(g, info); + // knockout: the mode's text measures the last rival still in, and after the win none is left ( 11-06 item 7) + if (g.key === 'knockout' && g.outcome === 'win') hud.detail = `${g.laps} / ${g.laps} laps · All rivals eliminated`; + if (g.sb) { const v = c.createRadialGradient(W / 2, H / 2, 150, W / 2, H / 2, 520); v.addColorStop(0, 'rgba(120,170,255,0)'); v.addColorStop(1, 'rgba(70,110,220,.42)'); c.fillStyle = v; c.fillRect(0, 0, W, H); } + // hit: a red vignette at the edges, not a full-screen wash, so the road stays readable + if (g.lastHit > 0) { const v = c.createRadialGradient(W / 2, H / 2, 170, W / 2, H / 2, 500); v.addColorStop(0, 'rgba(220,40,30,0)'); v.addColorStop(1, `rgba(220,40,30,${Math.min(0.75, g.lastHit * 1.6)})`); c.fillStyle = v; c.fillRect(0, 0, W, H); } + if (g.flash > 0 && (g.t >> 3) % 2) { c.fillStyle = 'rgba(255,255,255,.1)'; c.fillRect(0, 0, W, H); } + mirrorFrame(c, g); + info.cover.push(RECT.tier, RECT.event, RECT.clock, RECT.speedo, RECT.map); if (g.manual) info.cover.push(RECT.tach); if (sc && sc.mirrorOn) info.cover.push(sc.mirrorRect); + // event panel: boss_hp and player_hp under their event-specific names + const [ex0, ey0, ex1] = RECT.event; panel(c, ex0, ey0, ex1 - ex0, 38); + c.font = `bold 12px ${FONT}`; c.fillStyle = '#f2ecdc'; c.textAlign = 'left'; c.fillText(hud.label || '', ex0 + 8, ey0 + 14); + c.font = `11px ${FONT}`; c.fillStyle = '#c6d0dc'; c.textAlign = 'right'; c.fillText(hud.detail || '', ex1 - 8, ey0 + 14); c.textAlign = 'left'; + bar(c, ex0 + 8, ey0 + 20, ex1 - ex0 - 16, 5, h[3] ? h[2] / h[3] : 0, '#ff8a3c'); + bar(c, ex0 + 8, ey0 + 28, ex1 - ex0 - 16, 5, h[1] ? h[0] / h[1] : 0, h[0] / (h[1] || 1) < 0.25 ? '#ff4a3a' : '#5bd18a'); + // clock and tier + const [cx0, cy0, cx1] = RECT.clock; panel(c, cx0, cy0, cx1 - cx0, 38); c.textAlign = 'right'; c.font = 'bold 16px Consolas,monospace'; c.fillStyle = '#f2ecdc'; c.fillText((g.t / M.hz).toFixed(1) + ' s', cx1 - 8, cy0 + 18); + c.font = 'bold 10px Consolas,monospace'; c.fillStyle = '#9fd0ff'; c.fillText(M.hz + 'Hz · tick ' + g.t, cx1 - 8, cy0 + 32); c.textAlign = 'left'; + const [tx0, ty0, tx1] = RECT.tier; panel(c, tx0, ty0, tx1 - tx0, 38); c.font = 'bold 11px Consolas,monospace'; c.fillStyle = '#ffd08a'; c.fillText((g.tier || '').toUpperCase() + ' d=' + g.d, tx0 + 8, ty0 + 16); c.fillStyle = '#b8c2cc'; c.font = '10px Consolas,monospace'; c.fillText(M.version, tx0 + 8, ty0 + 30); + // speedometer + const [sx0, sy0, sx1, sy1] = RECT.speedo; panel(c, sx0, sy0, sx1 - sx0, sy1 - sy0); c.textAlign = 'right'; c.font = 'bold 32px Consolas,monospace'; c.fillStyle = '#ffffff'; c.fillText(String(Math.round(kmh)), sx1 - 40, sy0 + 34); + c.font = '10px Consolas,monospace'; c.fillStyle = '#a8b4c0'; c.fillText('KM/H', sx1 - 8, sy0 + 34); + c.font = 'bold 18px Consolas,monospace'; c.fillStyle = car.over ? '#ff5a4a' : '#ffd08a'; c.textAlign = 'center'; c.fillText(String(car.gear + 1), sx0 + 14, sy0 + 26); c.textAlign = 'left'; + c.font = '9px Consolas,monospace'; c.fillStyle = '#9fc8ff'; c.fillText('NOS', sx0 + 6, sy0 + 52); bar(c, sx0 + 34, sy0 + 45, sx1 - sx0 - 42, 7, car.nos, car.nosOn ? '#bfe4ff' : '#4aa0ff'); + c.fillStyle = '#ffd08a'; c.fillText('SLOW', sx0 + 6, sy0 + 64); bar(c, sx0 + 34, sy0 + 57, sx1 - sx0 - 42, 7, g.sbMeter, g.sb ? '#ffffff' : '#ffb84a'); + if (g.manual) { c.fillStyle = '#ff9a7a'; c.fillText('HEAT', sx0 + 6, sy0 + 76); bar(c, sx0 + 34, sy0 + 70, sx1 - sx0 - 42, 6, car.heat, car.heat > 0.6 ? '#ff4a3a' : '#ffa14a'); } + if (g.manual) tach(g, c); + minimap(g, c); + if (M.MODES[g.key].hudExtra) M.MODES[g.key].hudExtra(g, c, { panel, bar, W, H }); + drawArrows(c, info); drawWarnings(c, g); + if (g.pre > 0) { + c.font = 'bold 54px Consolas,monospace'; c.textAlign = 'center'; c.fillStyle = '#ffe28a'; c.fillText(String(Math.ceil(g.pre)), W / 2, 210); + if (g.manual) { c.font = `bold 14px ${FONT}`; c.fillStyle = '#ffffff'; c.fillText('Manual gears: K upshift · L downshift · A / D change lanes', W / 2, 238); } + c.textAlign = 'left'; + } + if (g.outcome) { c.fillStyle = 'rgba(0,0,0,.42)'; c.fillRect(0, H / 2 - 44, W, 88); c.font = 'bold 36px "Microsoft YaHei",sans-serif'; c.textAlign = 'center'; c.fillStyle = g.outcome === 'win' ? '#7dff9a' : '#ff6a5a'; c.fillText(g.outcome === 'win' ? 'Challenge complete' : g.outcome === 'timeout' ? 'Time up' : (LABEL[g.lossReason] || 'Challenge Failed'), W / 2, H / 2 + 13); c.textAlign = 'left'; } + return sc; + }; + M.renderStatus = ctx => R.status(ctx); + M.renderMetrics = ctx => R.metrics(ctx); + M.closeRenderer = ctx => R.close(ctx); +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/game.js b/environments/games/web/games/nfsmw_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..8e6cce586e5ee2da82d8eb76c6e3bb7bc72e3f6a --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/game.js @@ -0,0 +1,167 @@ +/* Need for Speed: Most Wanted (2005) events, rules nfsmw-arena@2 - the module: cases, tiers, the tick, the health mapping. + A race has no health bars, so the public contract maps onto the event's own win and loss conditions: + boss_hp is what is left of the event (route metres from a high-water mark, so it never jumps back), and player_hp + is what the opponent still needs to beat you (clock, gap, score margin, bust meter). See + Independent reimplementation; facts read from the CC0 decompilation dbalatoni13/nfsmw@80993f3 are cited as file:line + in that repository. All art is procedural; no game data (VLT attributes, models, textures, audio, maps) is used. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.NfsmwGame, C = M.C; + const HZ = 60, DT = 1 / HZ; + // Tiers are one fight at three paces: event length, opponent skill, traffic and police pressure all scale continuously. + // The original has no mode gate on these values (GRace.h: Easy/Medium/Hard is a per-event parameter), so hard stays 0.85. + const TIERS = { easy: 0.2, normal: 0.5, hard: 0.85 }; + // Piecewise linear through the three tier values, extrapolated beyond them, so any d in [0,1] is a valid fight. + const tierValue = (d, [e, n, h]) => d <= TIERS.normal ? n + (e - n) * (TIERS.normal - d) / (TIERS.normal - TIERS.easy) : n + (h - n) * (d - TIERS.normal) / (TIERS.hard - TIERS.normal); + const tierOf = d => d <= (TIERS.easy + TIERS.normal) / 2 ? 'easy' : d <= (TIERS.normal + TIERS.hard) / 2 ? 'normal' : 'hard'; + M.MODES = M.MODES || {}; + + const CASES = [ + { id: 'nfsmw/tollbooth', name: 'Tollbooth Race (Coastal Highway)' }, + { id: 'nfsmw/drag', name: 'Drag Series (Highway 99)' }, + { id: 'nfsmw/speedtrap', name: 'Speed Trap (Coastal Highway)' }, + { id: 'nfsmw/knockout', name: 'Lap Knockout (Downtown Night Race)' }, + { id: 'nfsmw/pursuit', name: 'Police Pursuit (Bounty + Escape)' }, + { id: 'nfsmw/street_champion', name: 'Street Champion Showdown (Multi-leg Race + Police)' }, + ]; + Object.assign(M, { + id: 'nfsmw_remake', version: 'nfsmw-arena@2', hz: HZ, maxSeconds: 300, dimension: '3d', renderer: 'webgl-nfsmw', + title: 'Need for Speed: Most Wanted · Street Challenges', cases: CASES, tiers: TIERS, tierValue, tierOf, DT, + controls: { + 'W': 'throttle', 'S': 'brake; reverse at low speed', 'A / D': 'Steer left / right (steering increases while held and decreases at higher speed)', 'Space': 'Handbrake (drift)', + 'Shift': 'nitrous', 'J': 'Toggle slow motion (time slows and downforce increases)', 'K / L': 'Manual upshift / downshift in drag races (A / D change lanes)', 'R': 'Reset onto the route (easier to bust during the 2-second flashing period)', + }, + }); + + // SB: world time scale is in the ITimeManager data (not in the repository), approximation 0.45; the handling side is + // SuspensionRacer.cpp:936 Tweak_GameBreakerExtraGs (-2 g of extra downforce) with a 1/3 s physics ramp-out (:937). + const SB_SCALE = 0.45, SB_GRIP = 2 * 9.81, SB_RAMP = 1 / 3, SB_SECONDS = 6; + const RESET_INVULN = 2; // ResetCar.cpp:26 Tweak_ResetInvulnerablitiyTime + + class Game { + constructor(id, seed, d) { + this.id = id; this.key = id.split('/')[1]; this.d = d; this.tier = tierOf(d); + this.t = 0; this.outcome = null; this.events = []; this.seed = seed; + // The multiply decorrelates neighbouring seeds; xorshift has a fixed point at zero. + this.rng = (Math.imul((seed >>> 0) + 1, 2654435761) >>> 0) || 1; + this.pre = 1.2; this.clock = 0; // staging countdown; event clock in world seconds + this.sb = 0; this.sbMeter = 1; this.sbRamp = 0; // Speedbreaker + this.flash = 0; this.resets = 0; this.hits = 0; this.nearMisses = 0; this.manual = 0; this.lastHit = 0; + this.slowT = 0; this.s = 0; this.s0 = 0; this.prog = 0; this.total = 1; this.lat = 0; this.offRoute = 0; + this.traffic = []; this.rivals = []; this.cops = []; this.props = []; this.gates = []; this.status = ''; + const mode = M.MODES[this.key]; if (!mode) throw Error('Unknown event ' + id); + this.routeKey = mode.route(d); + mode.init(this, d); + this.camH = this.car.h; this.heldBrake = 0; this.flashT = 0; this.heli = null; + } + get route() { return C.routes[this.routeKey]; } + placeCar(s, lat, speed = 0) { + const a = C.routeAt(this.route, s, lat), c = C.newCar(a.x, a.y, a.h); + c.vx = Math.cos(a.h) * speed; c.vy = Math.sin(a.h) * speed; + this.car = c; this.s = s; this.lat = lat; + } + update(keys, pressed) { + const mode = M.MODES[this.key], car = this.car; + this.heldBrake = keys.has('S') ? 1 : 0; + // Chase camera: lags the heading (state only the renderer reads; it cannot affect the simulation). + { let dh = car.h - this.camH; dh = Math.atan2(Math.sin(dh), Math.cos(dh)); this.camH += dh * Math.min(1, DT * 5.5); } + if (this.lastHit > 0) this.lastHit = Math.max(0, this.lastHit - DT); + if (this.flash > 0) this.flash = Math.max(0, this.flash - DT); + if (pressed.has('J') && (this.sb || this.sbMeter > 0.05)) { this.sb = this.sb ? 0 : 1; if (!this.sb) this.sbRamp = SB_RAMP; this.events.push({ type: this.sb ? 'slowmo_on' : 'slowmo_off' }); } + if (this.sb) { this.sbMeter = Math.max(0, this.sbMeter - DT / SB_SECONDS); if (this.sbMeter <= 0) { this.sb = 0; this.sbRamp = SB_RAMP; } } + else if (this.sbRamp > 0) this.sbRamp = Math.max(0, this.sbRamp - DT); + const wdt = DT * (this.sb ? SB_SCALE : 1); + if (this.pre > 0) { // staging: the world runs, the car is held at the line + this.pre = Math.max(0, this.pre - DT); + if (mode.staging) mode.staging(this, keys, pressed, DT); + M.stepTraffic(this, wdt); if (mode.idle) mode.idle(this, wdt); + return; + } + if (pressed.has('R')) this.resetCar(); + const speed = C.speed(car), fwd = car.vx * Math.cos(car.h) + car.vy * Math.sin(car.h); + const inp = { + thr: keys.has('W') ? 1 : 0, brk: keys.has('S'), steer: (keys.has('A') ? 1 : 0) - (keys.has('D') ? 1 : 0), hb: keys.has('Space'), nos: keys.has('Shift'), + up: this.manual && pressed.has('K'), down: this.manual && pressed.has('L'), manual: !!this.manual, reverse: keys.has('S') && fwd < 2 && speed < 6, + sbGrip: this.sb ? SB_GRIP : SB_GRIP * this.sbRamp / SB_RAMP, + }; + if (mode.input) mode.input(this, inp, keys, pressed); + C.carStep(car, inp, wdt, this.P || C.PLAYER); + if (car.hit > 3) { this.hits++; if (car.hit > 6) this.lastHit = 0.4; this.events.push({ type: 'wall', speed: car.hit }); } + if (!this.sb && speed > 35) this.sbMeter = Math.min(1, this.sbMeter + wdt * 0.02); + this.slowT = C.speed(car) < 2 ? this.slowT + DT : 0; + this.clock += wdt; + this.trackProgress(); + M.stepTraffic(this, wdt); + mode.tick(this, wdt); + } + // Progress is route distance from a high-water mark, inside a short window so a junction can't jump to another leg. + trackProgress() { + const R = this.route, c = this.car; + this.s = C.routeNear(R, c.x, c.y, this.s); + this.lat = C.routeLat(R, c.x, c.y, this.s); + this.offRoute = Math.abs(this.lat) > R.halfW + 3 ? 1 : 0; + if (!this.offRoute && this.s - this.s0 > this.prog) this.prog = Math.min(this.total, this.s - this.s0); + } + resetCar() { + const s = this.s0 + this.prog, a = C.routeAt(this.route, s, 0), keep = this.car; + Object.assign(keep, { x: a.x, y: a.y, h: a.h, vx: 0, vy: 0, r: 0, steer: 0, gear: 0, clutch: 0, tires: 0 }); // tyres: approximation + this.s = s; this.lat = 0; this.slowT = 0; this.flash = RESET_INVULN; this.resets++; + this.events.push({ type: 'reset' }); + } + win() { if (!this.outcome) { this.outcome = 'win'; this.events.push({ type: 'win' }); } } + lose(why) { if (!this.outcome) { this.outcome = 'loss'; this.lossReason = why; this.events.push({ type: 'loss', why }); } } + health() { return M.MODES[this.key].health(this); } + } + Object.assign(M, { Game, DT, copyGame: g => Object.assign(Object.create(Game.prototype), N.copy(g)) }); + + // ---------------- traffic (AIActionTraffic: stays in lane at the speed limit, does not race, does not dodge) ---------------- + const carRadius = 1.6; + M.carRadius = carRadius; + M.spawnTraffic = (g, n, opt = {}) => { + g.trafficOpt = { ahead: opt.ahead || 420, spread: opt.spread || 620, opposing: opt.opposing === undefined ? 0.35 : opt.opposing, lanes: opt.lanes || null }; + for (let i = 0; i < n; i++) { + const t = { s: 0, lat: 0, dir: 1, v: 0, x: 0, y: 0, h: 0, crash: 0, vx: 0, vy: 0, nm: 0, paint: i % 6 }; + placeTraffic(g, t, g.s + 90 + (g.trafficOpt.spread + g.trafficOpt.ahead) * (i + N.rand(g)) / n); + g.traffic.push(t); + } + }; + const lanesOf = (R, dir) => dir > 0 ? [-R.halfW * 0.25, -R.halfW * 0.72] : [R.halfW * 0.25, R.halfW * 0.72]; + function placeTraffic(g, t, s) { + const R = g.route, o = g.trafficOpt; + t.dir = N.rand(g) < o.opposing ? -1 : 1; t.nm = 0; t.crash = 0; t.vx = 0; t.vy = 0; + const lanes = o.lanes || lanesOf(R, t.dir); t.lat = lanes[Math.floor(N.rand(g) * lanes.length) % lanes.length]; + t.v = t.dir * (17 + N.rand(g) * 9); t.s = s; + if (!R.loop) t.s = C.clamp(s, 40, R.L - 40); + const a = C.routeAt(R, t.s, t.lat); t.x = a.x; t.y = a.y; t.h = t.dir > 0 ? a.h : a.h + Math.PI; + } + M.stepTraffic = (g, wdt) => { + const R = g.route, c = g.car; + for (const t of g.traffic) { + if (t.crash) { // knocked out of lane: a free body that coasts to a stop + t.x += t.vx * wdt; t.y += t.vy * wdt; const f = Math.max(0, 1 - 1.6 * wdt); t.vx *= f; t.vy *= f; t.h += t.crash * wdt; t.crash *= f; + const q = C.road(t.x, t.y), over = q.d + 1.2; if (over > 0) { t.x -= q.nx * over; t.y -= q.ny * over; t.vx = 0; t.vy = 0; } + t.s = C.routeNear(R, t.x, t.y, t.s, 10, 10); t.lat = C.routeLat(R, t.x, t.y, t.s); + } else { + t.s += t.v * wdt; const a = C.routeAt(R, t.s, t.lat); t.x = a.x; t.y = a.y; t.h = t.dir > 0 ? a.h : a.h + Math.PI; + } + const rel = t.s - g.s; + if (rel < -140 || rel > g.trafficOpt.ahead + g.trafficOpt.spread + 60 || (!R.loop && (t.s < 30 || t.s > R.L - 30))) { placeTraffic(g, t, g.s + g.trafficOpt.ahead + N.rand(g) * g.trafficOpt.spread); continue; } + const dx = c.x - t.x, dy = c.y - t.y, dist2 = dx * dx + dy * dy; + if (dist2 < 30 && !t.nm && C.speed(c) > 25) { const d = Math.sqrt(dist2); if (d > carRadius * 2 + 0.4 && d < 4.6) { t.nm = 1; g.nearMisses++; g.sbMeter = Math.min(1, g.sbMeter + 0.04); } } + if (dist2 < (carRadius * 2) * (carRadius * 2)) M.bump(g, t, dx, dy, dist2, 0.8); + } + }; + // Player against a lighter body: momentum exchange along the contact normal. Returns the closing speed. + M.bump = (g, o, dx, dy, dist2, mass) => { + const c = g.car, d = Math.max(0.01, Math.sqrt(dist2)), nx = dx / d, ny = dy / d; + const moving = o.v !== undefined && !o.crash, ovx = moving ? Math.cos(o.h) * Math.abs(o.v) : o.vx, ovy = moving ? Math.sin(o.h) * Math.abs(o.v) : o.vy; + const rel = (c.vx - ovx) * nx + (c.vy - ovy) * ny, push = carRadius * 2 - d; + c.x += nx * push * 0.6; c.y += ny * push * 0.6; + if (rel >= 0) return 0; + const j = -(1.3) * rel * mass / (1 + mass); + c.vx += nx * j; c.vy += ny * j; c.r += ((nx * c.vy - ny * c.vx) > 0 ? 1 : -1) * Math.min(0.8, -rel * 0.02); + o.vx = ovx - nx * j / mass * 1.0; o.vy = ovy - ny * j / mass * 1.0; if (o.v !== undefined && !o.crash) o.crash = nx * Math.sin(o.h) - ny * Math.cos(o.h) > 0 ? 0.8 : -0.8; + if (-rel > 4) { g.hits++; g.lastHit = 0.4; g.events.push({ type: 'crash', speed: -rel }); } + return -rel; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/index.html b/environments/games/web/games/nfsmw_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..b75619531efe73e043ff789f1da90e7112473197 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/index.html @@ -0,0 +1,7 @@ + +Need for Speed: Most Wanted · Street Challenges(nfsmw-arena@2)
            +

            Need for Speed: Most Wanted · Street Challenges

            2005 original rules, independently recreated from CC0 decompilation · Native 60 Hz · Third-person WebGL · Original procedural city

            Back to Game Lobby
            +
            Select an event, then start the challenge

            Replays save inputs and the seed, then simulate the match again and verify the final state. Scripted Demo reads internal state for verification; it does not start RL training.

            +
            +
            All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
            + diff --git a/environments/games/web/games/nfsmw_remake/manifest.json b/environments/games/web/games/nfsmw_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..6f3b1ed29b505f97b6f72819ddf7e05aa2c3ef25 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/manifest.json @@ -0,0 +1,52 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "nfsmw_remake", + "module": "NfsmwGame", + "title": "Need for Speed Most Wanted: Street Challenges", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-nfsmw", + "rules": "nfsmw-arena@2", + "cases": [ + "nfsmw/tollbooth", + "nfsmw/drag", + "nfsmw/speedtrap", + "nfsmw/knockout", + "nfsmw/pursuit", + "nfsmw/street_champion" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "nfsmw_remake/nfscore.js", + "nfsmw_remake/game.js", + "nfsmw_remake/rivals.js", + "nfsmw_remake/modes_tollbooth.js", + "nfsmw_remake/modes_drag.js", + "nfsmw_remake/modes_speedtrap.js", + "nfsmw_remake/modes_knockout.js", + "nfsmw_remake/cops.js", + "nfsmw_remake/modes_pursuit.js", + "nfsmw_remake/scripted.js", + "nfsmw_remake/renderer3d.js", + "nfsmw_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "nfsmw_remake/nfscore.js", + "nfsmw_remake/game.js", + "nfsmw_remake/rivals.js", + "nfsmw_remake/modes_tollbooth.js", + "nfsmw_remake/modes_drag.js", + "nfsmw_remake/modes_speedtrap.js", + "nfsmw_remake/modes_knockout.js", + "nfsmw_remake/cops.js", + "nfsmw_remake/modes_pursuit.js", + "nfsmw_remake/scripted.js" + ], + "play_page": "web/games/nfsmw_remake/index.html", + "scripted_controller": "NfsmwGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]}; pure car-model look-ahead, others extrapolated at constant speed (NfsmwGame.oracle is an alias)", + "source": "https://github.com/dbalatoni13/nfsmw/tree/80993f35224c61d2f1b135beba76c6f8234c7940 (CC0-1.0)" +} diff --git a/environments/games/web/games/nfsmw_remake/modes_drag.js b/environments/games/web/games/nfsmw_remake/modes_drag.js new file mode 100644 index 0000000000000000000000000000000000000000..560f4e8b7775bbe6f015ed4effd1be8ebbaa8511 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_drag.js @@ -0,0 +1,113 @@ +/* Drag (GRace.h kRaceType_Drag), run as a series the way a Blacklist rival is fought (Wikipedia: "win against the racer in a + successive series of races"). Rules that exist only here, all from the decompilation: + - manual gearbox with a perfect-shift bonus (EngineRacer EPerfectShift; the window width is VLT, approximation); + - over-rev heat, EngineRacer.cpp:1340-1345: +0.45/s on the limiter, -0.1/s otherwise, torque -25% from 0.6, blown at 1; + - the car steers itself and the driver changes lanes (AIVehicle.cpp IsDragSteering, ChangeDragLanes); + - total on hard contact, DamageDragster.cpp: above 100 mph, losing more than 40 mph in one impact destroys the car; + - launch: GetPerfectLaunchRange, EngineRacer.cpp:127-135 (a band a quarter of the rev range below the redline). + boss_hp = metres left in the whole series; player_hp = metres the rival still needs in this heat. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, clamp = C.clamp; + const MPH = C.MPH, KILL_SPEED = 100 * MPH, KILL_DELTA = 40 * MPH, STAGE = 2.5; // AIActionRace.cpp:99 Tweak_UnstageTime + const LANES = [-7.5, -2.5, 2.5, 7.5], REV_UP = 1.5, REV_DOWN = 1.1, LAUNCH = [0.62, 0.86], START_S = 60, LANE_RATE = 7, LANE_GAIN = 2.2; + const startHeat = g => { + const lane = g.heat % 2 ? 2 : 1, rl = g.heat % 2 ? 1 : 2; + g.placeCar(START_S, LANES[lane]); g.s0 = START_S; g.lane = lane; g.pre = STAGE; g.rev = 0; g.prevV = 0; g.heatProg = 0; + g.gates = [{ s: START_S + g.heatLen, at: g.heatLen, done: 0 }]; + g.rivals = [M.newRival(g, { s: START_S, lat: LANES[rl], skill: clamp(g.rivalSkill + M.formOf(g), 0, 1), drag: true, paint: 1 })]; + g.traffic = []; M.spawnTraffic(g, g.trafficN, { opposing: 0, lanes: LANES, spread: Math.max(0, g.heatLen - 240), ahead: 140 }); + // highwater across heats: every heat restarts the car at the line, and prog is measured from heatBase + g.prog = 0; g.total = g.heatLen; + }; + M.MODES.drag = { + route: () => 'strip', + init(g, d) { + g.P = Object.assign({}, C.PLAYER, { overheat: true }); + g.manual = 1; g.noGlue = 1; + g.heats = Math.round(M.tierValue(d, [1, 2, 6])); g.heatLen = M.tierValue(d, [1000, 1500, 1500]); g.seriesLen = g.heats * g.heatLen; + g.rivalSkill = M.tierValue(d, [0.2, 0.5, 0.8]); g.trafficN = Math.round(M.tierValue(d, [3, 6, 10])); + g.heat = 0; g.launch = 0; + startHeat(g); + }, + staging(g, keys, pressed, dt) { + g.rev = clamp(g.rev + (keys.has('W') ? REV_UP : -REV_DOWN) * dt, 0, 1); + if (g.pre <= 0) { const inBand = g.rev >= LAUNCH[0] && g.rev <= LAUNCH[1]; g.launch = inBand ? 1 : 0; if (inBand) { g.car.bonus = 1.2; g.events.push({ type: 'perfect_launch' }); } else if (g.rev > LAUNCH[1]) g.car.clutch = 0.45; } + g.prevV = 0; + }, + idle(g) { for (const r of g.rivals) { const a = C.routeAt(g.route, r.s, r.lat); r.x = a.x; r.y = a.y; r.h = a.h; } }, + input(g, inp, keys, pressed) { + if (pressed.has('A') && g.lane < LANES.length - 1) g.lane++; + if (pressed.has('D') && g.lane > 0) g.lane--; + // Lane keeper: the driver has no wheel here (IsDragSteering), a fixed servo turns the lane error into steering. + const R = g.route, c = g.car, a = C.routeAt(R, g.s), lat = C.routeLat(R, c.x, c.y, g.s), v = Math.max(C.speed(c), 6); + let dh = c.h - a.h; dh = Math.atan2(Math.sin(dh), Math.cos(dh)); + // Lateral error -> a heading limited to LANE_RATE across the road -> the yaw rate that reaches it -> the wheel for that rate. + const lim = LANE_RATE / v, want = clamp((LANES[g.lane] - lat) * LANE_GAIN / v, -lim, lim), full = v * Math.tan(C.steerRange(v / C.MPH) * Math.PI / 180) / C.PLAYER.wheelbase; + inp.steer = clamp((want - dh) * 3 / full, -1, 1); inp.hb = false; + }, + tick(g, wdt) { + const c = g.car, v = C.speed(c); + if (g.prevV > KILL_SPEED && g.prevV - v > KILL_DELTA) return g.lose('totaled'); + g.prevV = v; + if (c.blown) return g.lose('blown'); + for (const r of g.rivals) M.stepRival(g, r, wdt); + const rv = g.rivals[0]; + if (g.prog >= g.heatLen) { + g.events.push({ type: 'heat_won', heat: g.heat, gap: g.heatLen - rv.prog }); + g.heat++; + if (g.heat >= g.heats) return g.win(); + startHeat(g); + return; + } + if (rv.prog >= g.heatLen) g.lose('gap'); + }, + health(g) { + const rv = g.rivals[0], left = Math.max(0, g.heatLen - rv.prog), done = g.outcome === 'win' ? g.seriesLen : g.heat * g.heatLen + g.prog; + return [g.outcome === 'loss' ? 0 : left, g.heatLen, Math.max(0, g.seriesLen - done), g.seriesLen]; + }, + hud(g) { const rv = g.rivals[0]; return { label: 'Drag Race', detail: `Heat ${Math.min(g.heat + 1, g.heats)} / ${g.heats} · Rival needs ${Math.max(0, g.heatLen - rv.prog).toFixed(0)} m · ${g.pre > 0 ? 'RPM ' + Math.round(g.rev * 100) + '%' : 'Gear ' + (g.car.gear + 1)}` }; }, + // Reference: launch inside the band, shift inside the window, change lanes for traffic, nitrous when nothing is close. + scripted(g) { + const holds = [[], [], [], [], [], []], c = g.car; + if (g.pre > 0) { // feather the throttle so the revs sit in the launch band when the lights go + let rev = g.rev, left = g.pre; + for (let i = 0; i < 6; i++) { const on = rev < (LAUNCH[0] + LAUNCH[1]) / 2 - 0.02 && left < 1.2; if (on) holds[i].push('W'); rev = clamp(rev + (on ? REV_UP : -REV_DOWN) * (2 / 60), 0, 1); left -= 2 / 60; } + return { holds, mouse: [0, 0, 0] }; + } + const P = g.P, k = M.ctl.copyCar(c), fwd0 = Math.max(0, c.vx * Math.cos(c.h) + c.vy * Math.sin(c.h)); let press = -1; + // After a hit the box is still in a tall gear with almost no drive: one gear down per packet until the revs are useful. + const lug = c.gear > 0 && c.clutch <= 0 && fwd0 < C.TOPS[c.gear - 1] * 0.8; + for (let i = 0; i < 6; i++) { + const u = Math.max(0, k.vx * Math.cos(k.h) + k.vy * Math.sin(k.h)) / C.TOPS[k.gear]; + if (press < 0 && k.gear < 5 && u >= 0.9) press = i; + C.carStep(k, { thr: 1, brk: false, steer: 0, hb: false, nos: false, manual: true, up: false, down: false, sbGrip: 0 }, 1 / 30, P); + } + // Lane plan: for each lane and a short wait before moving, the time until first contact with anything on the road. + const users = M.ctl.roadUsers(g, g.route), v = C.speed(c), lane = g.lane, HORIZON_S = 6, STAY_S = 3.4; + const contact = (target, wait) => { + // The same first-order lane servo the car runs (rate capped, gain LANE_GAIN), started 0.2 s late for the wheel to slew. + let lat = g.lat; + for (let t = 0.1; t < HORIZON_S; t += 0.1) { + if (t > wait + 0.2) lat += clamp((LANES[target] - lat) * LANE_GAIN, -LANE_RATE, LANE_RATE) * 0.1; + const sp = g.s + v * t; + for (const o of users) { const ds = o.s + o.vs * t - sp, ds0 = o.s + o.vs * (t - 0.1) - (g.s + v * (t - 0.1)); if (o.s > g.s + 1 && Math.abs(o.lat - lat) < 3.6 && ((ds > 1 && ds < 6.5) || (ds0 > 1 && ds <= 1))) return t; } + } + return HORIZON_S; + }; + const here = contact(lane, 0); + let bestT = here, go = lane; + // Stay put until contact is near: a move costs nothing only if nothing else is decided on the way. Then take the lane + // that stays clear longest, nearer lanes first on a tie. A wrong late move is cheaper than weaving through everything. + if (here < STAY_S) { let bs = here; for (let l = 0; l < LANES.length; l++) { if (l === lane) continue; const t = contact(l, 0), v2 = t - 0.25 * Math.abs(l - lane); if (t > here + 0.5 && v2 > bs) { bs = v2; bestT = t; go = l; } } } + const move = Math.sign(go - lane); + // A blocked lane with nowhere to go: braking costs seconds on this gearing, a total above 100 mph costs the event. + const blocked = bestT < 0.8 && !move, coast = bestT < 1.2 && !move; + // Top gear on the limiter only cooks the engine (EngineRacer.cpp:1340): lift until the speed is back under it. + const onLimiter = c.gear === 5 && Math.max(0, c.vx * Math.cos(c.h) + c.vy * Math.sin(c.h)) >= C.TOPS[5] * 0.995; + const nos = c.nos > 0.02 && v > 30 && here > 3 && c.clutch <= 0 && !c.over && v < C.TOPS[5] * 0.97; + for (let i = 0; i < 6; i++) { if (blocked) holds[i].push('S'); else if (!onLimiter && !coast) holds[i].push('W'); if (nos && !blocked) holds[i].push('Shift'); if (i === press && !lug) holds[i].push('K'); if (i === 0 && lug) holds[i].push('L'); if (i === 0 && move) holds[i].push(move > 0 ? 'A' : 'D'); } + return { holds, mouse: [0, 0, 0] }; + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/modes_knockout.js b/environments/games/web/games/nfsmw_remake/modes_knockout.js new file mode 100644 index 0000000000000000000000000000000000000000..d035954274a5042f62631a0c9aabc80b0c77e9ba --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_knockout.js @@ -0,0 +1,57 @@ +/* Lap Knockout (GRace.h kRaceType_Knockout; GRaceStatus.h GRacerInfo::KnockOut, mKnockedOut). A short downtown circuit at night: + when every car but one has finished the lap, that last car is out. One lap per rival, so the field sets the length. + boss_hp = route metres left in the whole event; player_hp = metres the slowest remaining rival still needs to finish this + lap (at 0 every rival is home and the player is the one knocked out). The field and the circuit are original: race data is VLT. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, S0 = 40, ROW = 9; + M.MODES.knockout = { + route: () => 'downtown', + init(g, d) { + const R = g.route, field = Math.round(M.tierValue(d, [1, 2, 5])); + // The grid is short of the line, so lap 1 is partial and its length is part of the event's pace. + const first = Math.min(R.L, M.tierValue(d, [420, 520, 694])), start = R.L - first + S0; + g.L = R.L; g.first = first; g.laps = field; g.total = first + (field - 1) * R.L; g.lap = 0; g.s0 = start; g.placeCar(start, -2.2); + const lo = M.tierValue(d, [0.12, 0.2, 0.3]), hi = M.tierValue(d, [0.12, 0.34, 0.62]); + g.rivals = []; + // Two columns, a full row apart: the player is alone on the last row. Skill runs from the back of the grid to the front, as a Blacklist field does. + for (let i = 0; i < field; i++) { + const r = M.newRival(g, { s: start + ROW * (Math.floor(i / 2) + 1), lat: i % 2 ? -2.2 : 2.2, skill: C.clamp((field > 1 ? C.lerp(lo, hi, i / (field - 1)) : lo) + M.formOf(g), 0, 1), paint: i % 4 }); + r.s0 = start; r.prog = r.s - start; g.rivals.push(r); + } + g.gates = [{ s: R.L + S0, at: 0, kind: 'line', keep: 1, done: 0 }]; + M.spawnTraffic(g, Math.round(M.tierValue(d, [0, 2, 3])), { ahead: 120, spread: 260, opposing: 0 }); + }, + idle() {}, + tick(g, wdt) { + const alive = g.rivals.filter(r => !r.out); + for (const r of alive) M.stepRival(g, r, wdt); + // Rivals ride rails, so they part sideways here rather than drive through each other. + for (let i = 0; i < alive.length; i++) for (let j = i + 1; j < alive.length; j++) { + const a = alive[i], b = alive[j], ds = a.s - b.s, dl = a.lat - b.lat; + if (Math.abs(ds) < 6 && Math.abs(dl) < 3.2) { const push = (dl >= 0 ? 1 : -1) * 2.4 * wdt, e = g.route.halfW - 2.1; a.lat = C.clamp(a.lat + push, -e, e); b.lat = C.clamp(b.lat - push, -e, e); if (Math.abs(ds) < 4.4 && a.v !== b.v) { const back = ds < 0 ? a : b; back.v = Math.max(0, back.v - 6 * wdt); } } + } + const end = g.first + g.lap * g.L, pending = alive.filter(r => r.prog < end), youIn = g.prog >= end; + if (!youIn && pending.length === 0) return g.lose('knocked'); + // <= 1, not === 1: two rivals crossing on the same tick take pending from 2 to 0, and the last car still goes out. + if (youIn && pending.length <= 1) { + const out = pending[0] || alive.reduce((a, b) => b.prog < a.prog ? b : a); out.out = 1; out.gone = 1; g.events.push({ type: 'knockout', lap: g.lap }); g.lap++; + if (g.rivals.every(r => r.out)) { g.prog = g.total; g.win(); } + } + }, + health(g) { + const end = g.first + g.lap * g.L; let worst = 0; + for (const r of g.rivals) if (!r.out) worst = Math.max(worst, end - r.prog); + // A win knocks out the last rival, so no rival is left to measure: player_hp stays full rather than reading as a loss. + return [g.outcome === 'loss' ? 0 : g.outcome === 'win' ? g.L : C.clamp(worst, 0, g.L), g.L, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total]; + }, + hud(g) { const alive = g.rivals.filter(r => !r.out); const place = 1 + alive.filter(r => r.prog > g.prog).length; return { label: 'Lap Knockout', detail: `Lap ${Math.min(g.lap + 1, g.laps)} / ${g.laps} · Place ${place} / ${alive.length + 1} · Last-place rival needs ${M.MODES.knockout.health(g)[0].toFixed(0)} m` }; }, // draw.js calls hud unbound: no `this` + // Reference: a tighter line, and slow motion (J, the public Speedbreaker key: +2 g of downforce) only while it would brake, + // for a corner or for a car ahead. + scripted(g) { + const opt = { margin: 0.96 }, pk = M.ctl.drive(g, opt); + if (g.pre <= 0) { const why = M.ctl.planDrive(g, opt).why, want = why === 'speed' || why === 'contact'; if (want !== !!g.sb && (g.sb || g.sbMeter > 0.15) && pk.holds[0].length < 4) pk.holds[0].push('J'); } + return pk; + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/modes_pursuit.js b/environments/games/web/games/nfsmw_remake/modes_pursuit.js new file mode 100644 index 0000000000000000000000000000000000000000..e89d566ff7575de56d414bcf2d3a67df2aaa3e86 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_pursuit.js @@ -0,0 +1,437 @@ +/* Free-roam pursuit (AI/Common/AIPursuit.cpp, rules listed in cops.js). The event is the Blacklist's own gate: raise a bounty, then get away. + Bounty accrues only while a cop can see the player (:1920 AddToPendingRepPointsNormal runs inside the in-sight branch) and in lumps for + destroying cops, with the multiplier up to 3 (:917). Then the evade meter must fill. Clearing a stage raises the heat: after the lock-out + (:2061 LockoutCops) a new pursuit starts at the next level. The heat values are VLT data, so every number below is an approximation. + Pursuit Breakers: EPursuitBreaker exists in the decompilation, the placement and radius are map data; here two per lap, original. + boss_hp = stages x 200 minus bounty and evade progress, both from high-water marks, so it never jumps back; player_hp = the bust meter. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, N = root.NativeBench, clamp = C.clamp; + const BOUNTY_UNITS = 100, EVADE_UNITS = 100, S0 = 5560, BREAKER_R = 46; + const heat = (g, d) => { + const lvl = g.stage / Math.max(1, g.stages - 1); // inside the event the heat climbs a little, tier sets the base + return { copsMax: Math.round(M.tierValue(d, [2, 3, 5])) + (g.stage > 1 ? 1 : 0), top: M.tierValue(d, [52, 66, 70]) + lvl * 4 }; + }; + const startStage = (g, d) => { + const p = g.pol, h = heat(g, d); + p.copsMax = h.copsMax; p.top = h.top; p.seen = 0; p.sinceSeen = 0; p.evade = 0; p.lockT = g.stage ? 3 : 0; p.spawnT = g.stage ? 3.5 : p.spawnGap; + g.stageBounty = 0; g.stageEvadeHW = 0; + if (!g.stage) { const c = M.spawnCop(g, g.s - 85, 2, 1); c.slot = 0; c.v = 34; } + else g.events.push({ type: 'heat_up', stage: g.stage }); + }; + // ---------------- Reference controllers for these two events. Only these two events call them; the shared + // planDrive / drive in scripted.js are untouched. Read decided state only (poses, timers, the episode seed), never the live RNG: the + // champion's look-ahead rolls copies forward in a fixed independent scenario. Both keep a little memory per game object (WeakMap); a + // repeated call on the same state returns the same packet. + + // Pursuit. The strategy follows whether this heat level brings a helicopter (g.pol.heli, fixed when the pursuit starts; the HUD shows + // helicopter once one is up). In the block's tight corners the cops lose sight within seconds, so without a helicopter (250 m sight) the bounty + // stops growing there: d = 0.65-0.7 timed out 8/8 when the switch was the stage count instead. + // - no helicopter: the 11-06 controller. While bounty is owed, hold station just ahead of the chase so it keeps sight; once the 7 s in-sight + // grace (cops.js inSight, AIPursuit.cpp:2000) covers what is owed with 5 s to spare, or the bounty is full, run on the racing line with + // nitrous, through any Pursuit Breaker with a cop near. Same rule at every tier (the 11-06 version started early on easy only). + // - helicopter: the downtown block, reused from the trajectory-collection environment + // (read-only there; its route table, path smoothing and follower, config speed 42, owed 34, lane spread 3). Into the block by one of + // five connector streets, laps of its tight corners until the stage clears, back out to the coast between stages. + // Added to both: blown tyres are reset once no chasing cop is within 95 m (11-06 rule); on the block, a cop within 6 m with the car under + // BustSpeed + 2 means it is pinned, so it floors it instead of braking for the corner. + const pursuitPolicy = (() => { + const HIDE = true, HIDE_GAP = 175, HIDE_SEE = 520, SPEED = 42, OWED = 34, REENTER_OWED = 8, LANE_SPREAD = 3, EARLY_MARGIN = 5, RESET_NEAR = 95, UNPIN_R = 6, FAR_COP = 110, MID_COP = 70, TOP_FAR = 20, TOP_MID = 30; + const memory = new WeakMap(); + function choice(g) { let n = g.seed ^ Math.imul(g.stage + 1, 0x9e3779b1); n = Math.imul(n ^ (n >>> 16), 0x21f0aaad); n = Math.imul(n ^ (n >>> 15), 0x735a2d97); return ((n ^ (n >>> 15)) >>> 0) / 4294967296; } + const lane = g => (choice(g) - 0.5) * 2 * LANE_SPREAD; + // Connector streets from the coast road into the downtown block (nfscore.js STREETS), outer end first. + const routes = [[[0, -520], [0, -80]], [[420, -520], [420, 3], [46, 3]], [[-400, -520], [-400, 0], [-85, 0]], [[0, 400], [0, 80]], [[-400, 560], [-400, 0], [-85, 0]]]; + const nearestCop = g => { let near = Infinity; for (const k of g.cops) if (!k.dead && k.state !== 'rb') near = Math.min(near, Math.hypot(g.car.x - k.x, g.car.y - k.y)); return near; }; + function sixSteer(c, target, sp, scale) { + const rate = (sp < 15 ? 7 : sp < 40 ? 5 : 3.6) * scale / 30, keys = []; let st = c.steer; + for (let i = 0; i < 6; i++) { let k0 = 0, error = Infinity; for (const k of [0, 1, -1]) { const n = st + clamp(k - st, -rate, rate), e = Math.abs(n - target); if (e < error) { error = e; k0 = k; } } keys.push(k0); st += clamp(k0 - st, -rate, rate); } + return keys; + } + // Drop collinear points, then round each corner with the largest arc (16, 12, 8 m) that stays on the road. + function smooth(points) { + const sparse = [points[0]]; + for (let i = 1; i < points.length - 1; i++) { + const a = sparse[sparse.length - 1], b = points[i], c = points[i + 1], ux = b[0] - a[0], uy = b[1] - a[1], vx = c[0] - b[0], vy = c[1] - b[1], L = Math.hypot(ux, uy) * Math.hypot(vx, vy); + if (L < 0.01) continue; + if (Math.abs(ux * vy - uy * vx) / L < 0.01 && (ux * vx + uy * vy) / L > 0.999) continue; + sparse.push(b); + } + sparse.push(points[points.length - 1]); points = sparse; + const out = [points[0]]; + for (let i = 1; i < points.length - 1; i++) { + const a = points[i - 1], b = points[i], c = points[i + 1], la = Math.hypot(b[0] - a[0], b[1] - a[1]), lc = Math.hypot(c[0] - b[0], c[1] - b[1]); + if (la < 30 || lc < 30) { out.push(b); continue; } + const ux = (a[0] - b[0]) / la, uy = (a[1] - b[1]) / la, vx = (c[0] - b[0]) / lc, vy = (c[1] - b[1]) / lc; + const theta = Math.acos(clamp(ux * vx + uy * vy, -1, 1)); if (theta < 0.3 || theta > 2.9) { out.push(b); continue; } + let arc = null; + for (const radius of [16, 12, 8]) { + const tangent = radius / Math.tan(theta / 2); if (tangent > Math.min(la, lc) * 0.4) continue; + const hl = Math.hypot(ux + vx, uy + vy), distance = radius / Math.sin(theta / 2), cx = b[0] + (ux + vx) / hl * distance, cy = b[1] + (uy + vy) / hl * distance; + const ax = b[0] + ux * tangent, ay = b[1] + uy * tangent, angle = Math.atan2(ay - cy, ax - cx), sign = -Math.sign(ux * vy - uy * vx), sweep = Math.PI - theta; + const n = Math.ceil(radius * sweep / 2), candidate = []; + for (let j = 0; j <= n; j++) { const t = angle + sign * sweep * j / n; candidate.push([cx + Math.cos(t) * radius, cy + Math.sin(t) * radius]); } + if (candidate.every(p => C.road(p[0], p[1]).d < -1.8)) { arc = candidate; break; } + } + out.push(...(arc || [b])); + } + out.push(points[points.length - 1]); return out; + } + // Pure pursuit along mem.points, speed limited by the path's curvature and the tyres; null at the end of the path. + function follow(g, mem) { + if (mem.rawPoints !== mem.points) { mem.points = smooth(mem.points); mem.rawPoints = mem.points; } + const c = g.car, sp = C.speed(c), points = mem.points; let i = mem.i; + while (i < points.length - 1) { const a = points[i], b = points[i + 1], dx = b[0] - a[0], dy = b[1] - a[1], l2 = dx * dx + dy * dy; const t = ((c.x - a[0]) * dx + (c.y - a[1]) * dy) / l2; if (t > 1 || Math.hypot(c.x - b[0], c.y - b[1]) < 3.5) { i++; continue; } break; } + mem.i = i; + if (i >= points.length - 1) return null; + const a = points[i], b = points[i + 1], dx = b[0] - a[0], dy = b[1] - a[1], length = Math.hypot(dx, dy); + const t = clamp(((c.x - a[0]) * dx + (c.y - a[1]) * dy) / (length * length), 0, 1), remaining = length * (1 - t); + let look = Math.max(5, sp * 0.45), x = a[0] + dx * t, y = a[1] + dy * t, j = i; + while (look > 0 && j < points.length - 1) { const dest = points[j + 1], d = Math.hypot(dest[0] - x, dest[1] - y); if (d >= look) { x += (dest[0] - x) * look / d; y += (dest[1] - y) * look / d; break; } look -= d; x = dest[0]; y = dest[1]; j++; } + const lag = 0.1 * (g.sb ? 0.45 : 1); let angle = Math.atan2(y - c.y - c.vy * lag, x - c.x - c.vx * lag) - c.h - c.r * lag; angle = Math.atan2(Math.sin(angle), Math.cos(angle)); + const L = Math.max(3, Math.hypot(x - c.x, y - c.y)), kappa = 2 * Math.sin(angle) / L; + const nose = C.road(c.x + Math.cos(c.h) * 3.2, c.y + Math.sin(c.h) * 3.2).d > -0.5; + if (sp < 7 && (Math.abs(angle) > 0.9 || nose)) { + const clear = C.road(c.x - Math.cos(c.h) * 3.5, c.y - Math.sin(c.h) * 3.5).d < -0.6, side = angle > 0 ? 1 : -1; + const pk = M.ctl.toPacket({ keys: sixSteer(c, clear ? -side : side, sp, g.sb ? 0.45 : 1), thr: clear ? 0 : 6, brk: clear, nos: false }); + if (g.sb) pk.holds[0].push('J'); return pk; + } + const target = clamp(Math.atan(kappa * C.PLAYER.wheelbase) / (C.steerRange(sp / C.MPH) * Math.PI / 180), -1, 1); + const end = !mem.continuous && i + 1 === points.length - 1; + let future = SPEED, ds = -length * t, upcoming = 0; + const grip = (C.PLAYER.grip + (g.sb ? 19.62 : 0)) * C.tireFactor(c) * 0.78; + for (let k = i; k < points.length - 2 && ds < 150; k++) { + const a = points[k], b = points[k + 1], c0 = points[k + 2], d1 = Math.hypot(b[0] - a[0], b[1] - a[1]), d2 = Math.hypot(c0[0] - b[0], c0[1] - b[1]), d3 = Math.hypot(c0[0] - a[0], c0[1] - a[1]); + ds += d1; const curv = Math.abs(2 * ((b[0] - a[0]) * (c0[1] - b[1]) - (b[1] - a[1]) * (c0[0] - b[0])) / Math.max(0.001, d1 * d2 * d3)); + if (ds < sp * 1.5 + 10) upcoming = Math.max(upcoming, curv); + if (curv > 0.0001) future = Math.min(future, Math.sqrt(grip / curv + 2 * 8 * Math.max(0, ds - 6))); + } + const limit = Math.min(future, Math.sqrt(grip / (Math.abs(kappa) + 0.0001)), end ? Math.sqrt(2 * 8 * Math.max(0, remaining - 3)) : SPEED); + const brk = sp > limit + 0.8, keys = sixSteer(c, brk ? target / 1.45 : target, sp, g.sb ? 0.45 : 1); + const spare = Math.max(0, 1 - sp * sp * Math.abs(kappa) / grip); + const thr = Math.max(1, Math.min(6, Math.round(6 * spare / 0.55))); + let pinned = false; for (const k of g.cops) if (!k.dead && k.state !== 'rb' && Math.hypot(c.x - k.x, c.y - k.y) < UNPIN_R) pinned = true; + pinned = pinned && sp < g.pol.bustSpeed + 2; + const pk = pinned ? M.ctl.toPacket({ keys: sixSteer(c, target, sp, g.sb ? 0.45 : 1), thr: 6, brk: false, nos: c.nos > 0.02 }) : M.ctl.toPacket({ keys, thr: brk ? 0 : thr, brk, nos: false }); + const want = (upcoming > 0.035 || Math.abs(angle) > 0.3) && sp > 10; + if (want !== !!g.sb && (g.sb || g.sbMeter > 0.2) && pk.holds[0].length < 4) pk.holds[0].push('J'); + return pk; + } + const nearestS = (R, x, y) => { let best = 0, dist = Infinity; for (let i = 0; i < R.n; i++) { const d = Math.hypot(R.x[i] - x, R.y[i] - y); if (d < dist) { dist = d; best = i * R.ds; } } return best; }; + // One lap of the downtown block starting at the point nearest (x, y). routeAt returns one shared object: copy before the next call. + function lapFrom(x, y) { const R = C.routes.downtown, best = nearestS(R, x, y), pts = []; for (let s = 4; s < R.L + 4; s += 4) { const p = C.routeAt(R, best + s); pts.push([p.x, p.y]); } const last = C.routeAt(R, best); pts.push([last.x, last.y]); return pts; } + function startReturn(g, mem, escape, entryS) { + const join = { ...C.routeAt(g.route, entryS + 35) }; + mem.points = [[g.car.x, g.car.y], ...escape.slice(0, -1).reverse(), [join.x, join.y]]; mem.i = 0; mem.mode = 'return'; mem.continuous = false; mem.returnPending = false; + mem.escape = escape; mem.entryS = entryS; + } + // One heat stage: the 11-06 coast run. + function coastRun(g, owed, p) { + const R = g.route, nearest = nearestCop(g), opt = { ram: true }, covered = 7 - p.sinceSeen - EARLY_MARGIN > owed; + // Hide: bounty full, nobody sees the car, and a roadblock is already set up ahead (g.blocks, decided state). Driving past it re-sights the + // car (50 m all round, AIVehicleCopCar.cpp:88-89) and restarts the 7 s + evade clock; instead stop HIDE_GAP m short of it, outside its + // 150 m view, and let the evade meter run. A car under 15 m/s draws no new roadblock (cops.js stepRoadblocks). + if (HIDE && owed <= 0 && !p.sawNow) { let ahead = Infinity; for (const b of g.blocks) { const ds = M.wrapTo(R, b.s, g.s) - g.s; if (ds > 0 && ds < ahead) ahead = ds; } + if (ahead < HIDE_SEE) { const room = ahead - HIDE_GAP, sp = C.speed(g.car); if (room < 3) return M.ctl.toPacket({ thr: 0, brk: sp > 2, nos: false }); return M.ctl.drive(g, { ram: true, nos: false, top: Math.max(4, Math.sqrt(2 * 8 * Math.max(0, room - 3))) }); } } + if (owed > 0 && !covered) { opt.nos = false; if (nearest > FAR_COP || !p.sawNow) opt.top = TOP_FAR; else if (nearest > MID_COP) opt.top = TOP_MID; } + if (owed <= 0 || covered) for (const b of g.breakers) { const ds = M.wrapTo(R, b.s, g.s) - g.s; if (ds > 0 && ds < 130 && !b.rearm && nearest < 90) opt.lat = b.lat; } + return M.ctl.drive(g, opt); + } + return function policy(g) { + let mem = memory.get(g); if (!mem) { mem = { stage: g.stage, mode: 'coast' }; memory.set(g, mem); } + if (g.car.tires > 0 && g.flash <= 0 && nearestCop(g) > RESET_NEAR) { mem.mode = 'coast'; mem.reenter = mem.reenter || g.bountyNeed - g.stageBounty > 0; return { holds: [['R'], [], [], [], [], []], mouse: [0, 0, 0] }; } + const owed = g.bountyNeed - g.stageBounty, p = g.pol; + if (!g.pol.heli) return coastRun(g, owed, p); + if (g.stage !== mem.stage) { + mem.stage = g.stage; + if (mem.mode === 'city') mem.returnPending = false; + else if (mem.mode !== 'coast') startReturn(g, mem, mem.escape, mem.entryS); + } + if (mem.mode === 'city') { + const pk = follow(g, mem); if (pk) return pk; + if (mem.returnPending) { startReturn(g, mem, mem.escape, mem.entryS); return follow(g, mem); } + mem.points = [[g.car.x, g.car.y], ...mem.cityPoints]; mem.i = 0; return follow(g, mem); + } + if (mem.mode === 'return' || mem.mode === 'inside') { + if (mem.mode === 'inside' && mem.i >= mem.points.length - 2) mem.continuous = true; + const pk = follow(g, mem); if (pk) return pk; + mem.continuous = false; mem.mode = 'coast'; + } + if (mem.mode === 'coast' && owed <= (mem.reenter ? REENTER_OWED : OWED)) { + mem.reenter = false; + const R = g.route, choices = routes.map(points => { const best = nearestS(R, points[0][0], points[0][1]); let ds = (best - g.s) % R.L; if (ds < 30) ds += R.L; return { points, s: g.s + ds, ds }; }); + const ranked = choices.sort((a, b) => a.ds - b.ds), options = ranked.filter(r => r.ds < ranked[0].ds + 1100).slice(0, 3); + const target = options[Math.min(options.length - 1, Math.floor(choice(g) * options.length))]; + mem.escape = target.points.map(q => q.slice()); mem.entryS = target.s; mem.mode = 'approach'; + } + if (mem.mode === 'approach') { + const distance = mem.entryS - g.s; + if (distance < 100) { + const approach = { ...C.routeAt(g.route, mem.entryS - 150) }, end = mem.escape[mem.escape.length - 1]; + mem.cityPoints = lapFrom(end[0], end[1]); + mem.points = [[approach.x, approach.y], ...mem.escape, ...mem.cityPoints]; mem.i = 0; mem.mode = 'city'; mem.continuous = true; + return follow(g, mem); + } + return M.ctl.drive(g, { ram: true, lat: lane(g), margin: 0.9, top: Math.min(70, Math.sqrt(12 * 12 + 2 * 8 * Math.max(0, distance - 12))) }); + } + return M.ctl.drive(g, { ram: true, lat: lane(g), margin: 0.9 }); + }; + })(); + + // Street champion. Reused from the trajectory-collection environment. v42 + // replaced the page's M.ctl with a modified copy of scripted.js; here that copy is private to this event. Kept from v42: lane choice with + // hysteresis, Speedbreaker grip in the racing line and friction circle, and each packet picks one of nine driving choices by rolling copies + // of the game 120 ticks forward with the RNG set to one fixed scenario (never the live RNG). Added: blown tyres are reset once no chasing + // cop is within 95 m (the 11-06 rule v42 dropped), and a roadblock already placed ahead (g.blocks, decided state) adds its widest gap as a + // candidate lane and pulls the score towards it: a 2 s rollout cannot see a block 300 m away, and at 55 m/s the car cannot cross the + // road in the 2 s it does see (seeds 4, 8, 13, 22, 24 hard: busted or out-run behind a block). + const championPolicy = (() => { + const HOLD_SETS = 6, DT = 1 / 60, CONTACT = 3.5, RESET_NEAR = 95, GAP_AHEAD = 360, GAP_CLEAR = 3.3, GAP_EDGE = 1.6, GAP_PULL = 8; + const laneMem = new WeakMap(); + function laneTarget(g, R, S, others, speed, base) { + const edge = R.halfW - 2.2, prev = laneMem.get(g) ?? g.lat; + const lanes = [clamp(prev, -edge, edge), base, -edge, edge, -edge * .5, 0, edge * .5]; + let best = lanes[0], bs = -Infinity; + for (const lat of lanes) { + let sc = -Math.abs(lat - prev) * 3 - .15 * Math.abs(lat - base); + for (const o of others) { + const ds = o.s - S; if (ds < -10 || ds > 200) continue; + const closing = speed - o.vs, tt = closing > 1 ? Math.max(0, ds) / closing : ds < 30 ? 0.5 : 99; + if (tt > 4) continue; + const gap = Math.abs(o.lat + (o.vl || 0) * Math.min(tt, 1) - lat); + if (gap < 3.8) sc -= (3.8 - gap) * (5 - tt) * 5; + } + if (sc > bs) { bs = sc; best = lat; } + } + laneMem.set(g, best); return best; + } + function roadUsers(g, R) { + const out = [], L = R.L; + const near = v => { if (!R.loop) return v; let ds = (v - g.s) % L; if (ds > L / 2) ds -= L; else if (ds < -L / 2) ds += L; return Math.abs(v - g.s) <= L / 2 ? v : g.s + ds; }; + for (const t of g.traffic) out.push({ s: near(t.s), lat: t.lat, vs: t.crash ? 0 : t.v, r: 2 }); + for (const r of g.rivals) if (!r.out) out.push({ s: near(r.s), lat: r.lat, vs: r.v, r: 2, a: r.v < 25 ? 5 : 0 }); + M.copUsers(g, R, out); + return out; + } + const lines = new Map(); + function racingLine(R, P, grip, brake, top) { + let L = lines.get(R.name); + if (!L) { + const n = R.n, lat = new Float64Array(n), edge = R.halfW - 2.4, wrap = i => R.loop ? (i + n) % n : Math.max(0, Math.min(n - 1, i)), K = Math.max(2, Math.round(10 / R.ds)); + const nx = i => -Math.sin(R.h[i]), ny = i => Math.cos(R.h[i]), px = i => R.x[i] + nx(i) * lat[i], py = i => R.y[i] + ny(i) * lat[i]; + for (let it = 0; it < 400; it++) for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), tx = (px(a) + px(b)) / 2 - px(i), ty = (py(a) + py(b)) / 2 - py(i); lat[i] = clamp(lat[i] + 0.5 * (tx * nx(i) + ty * ny(i)), -edge, edge); } + const kap = new Float64Array(n); + for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), x1 = px(i) - px(a), y1 = py(i) - py(a), x2 = px(b) - px(i), y2 = py(b) - py(i), l1 = Math.hypot(x1, y1), l2 = Math.hypot(x2, y2), l3 = Math.hypot(x1 + x2, y1 + y2); kap[i] = l1 && l2 && l3 ? Math.abs(2 * (x1 * y2 - y1 * x2) / (l1 * l2 * l3)) : 0; } + L = { lat, kap, prof: new Map() }; lines.set(R.name, L); + } + const key = [grip, brake, top].map(v => v.toFixed(3)).join('|'); let v = L.prof.get(key); + if (!v) { + v = new Float64Array(R.n); + for (let i = 0; i < R.n; i++) v[i] = L.kap[i] > P.aero + 1e-5 ? Math.min(top, Math.sqrt(grip / (L.kap[i] - P.aero))) : top; + for (let p = 0; p < (R.loop ? 2 : 1); p++) for (let i = R.n - 1; i >= 0; i--) { const j = i + 1 < R.n ? i + 1 : R.loop ? 0 : i, lim = Math.sqrt(v[j] * v[j] + 2 * brake * R.ds); if (lim < v[i]) v[i] = lim; } + L.prof.set(key, v); + } + return { lat: L.lat, prof: v }; + } + const lineLat = (R, lat, s) => { let i = Math.round(s / R.ds); if (R.loop) { i %= R.n; if (i < 0) i += R.n; } else i = clamp(i, 0, R.n - 1); return lat[i]; }; + function contactTime(g, others, S, speed, lat) { + const rate = 4, HORIZON_S = 3; + for (let t = 0.1; t < HORIZON_S; t += 0.1) { + const dl = lat - g.lat, l = g.lat + Math.sign(dl) * Math.min(Math.abs(dl), rate * t), sp = S + speed * t; + for (const o of others) { + if (o.s <= S) continue; + const ol = o.lat + (o.vl || 0) * Math.min(t, 2), ds = o.s + o.vs * t + 0.5 * (o.a || 0) * t * t - sp, t0 = t - 0.1, ds0 = o.s + o.vs * t0 + 0.5 * (o.a || 0) * t0 * t0 - (S + speed * t0); + if (Math.abs(ol - l) < CONTACT && ((ds > 0 && Math.hypot(ds, ol - l) < CONTACT) || (ds0 > 0 && ds <= 0))) return t; + } + } + return HORIZON_S; + } + function steerKeys(c, target, speed, wscale) { + const rate = (speed < 15 ? 7 : speed < 40 ? 5 : 3.6) * wscale * 2 * DT, out = []; let st = c.steer; + for (let i = 0; i < HOLD_SETS; i++) { + let best = 0, bd = Infinity; + for (const k of [0, 1, -1]) { const n = st + clamp(k - st, -rate, rate), e = Math.abs(n - target); if (e < bd - 1e-9) { bd = e; best = k; } } + out.push(best); st += clamp(best - st, -rate, rate); + } + return out; + } + function planDrive(g, opt = {}) { + const R = g.route, c = g.car, P = g.P || C.PLAYER, S = g.s, speed = C.speed(c), tire = C.tireFactor(c); + const margin = opt.margin || 0.92, top = opt.top || C.TOPS[5], wscale = g.sb ? 0.45 : 1; + const line = racingLine(R, P, (P.grip + 19.62 * (g.sb ? 1 : g.sbRamp / (1 / 3))) * tire * margin, P.brake * 0.8, top), prof = line.prof; + const others = roadUsers(g, R), base = opt.lat !== undefined ? opt.lat : lineLat(R, line.lat, S + speed * 0.8), lat = opt.fixedLane ? base : laneTarget(g, R, S, others, speed, base), onLine = lat === base && opt.lat === undefined; + const lag = 0.1 * wscale, px = c.x + c.vx * lag, py = c.y + c.vy * lag, ph = c.h + c.r * lag, Ld = Math.max(7, speed * 0.62); + const sNear = C.routeNear(R, px, py, S, 8, 16), aim = C.routeAt(R, sNear + Ld, onLine ? lineLat(R, line.lat, sNear + Ld) : lat); + let alpha = Math.atan2(aim.y - py, aim.x - px) - ph; alpha = Math.atan2(Math.sin(alpha), Math.cos(alpha)); + const far = C.routeAt(R, S + 18, lat); let off = Math.atan2(far.y - c.y, far.x - c.x) - c.h; off = Math.atan2(Math.sin(off), Math.cos(off)); + const nose = C.road(c.x + Math.cos(c.h) * 3.2, c.y + Math.sin(c.h) * 3.2).d > -0.5; + if (speed < 7 && (Math.abs(off) > 0.9 || nose)) { + const clearBehind = C.road(c.x - Math.cos(c.h) * 3.5, c.y - Math.sin(c.h) * 3.5).d < -0.6, side = off > 0 ? 1 : -1; + return { keys: steerKeys(c, clearBehind ? -side : side, speed, wscale), thr: clearBehind ? 0 : HOLD_SETS, brk: clearBehind, nos: false, lat, contact: 3, why: 'recover' }; + } + const kappa = 2 * Math.sin(alpha) / Ld, delta = Math.atan(kappa * P.wheelbase), range = C.steerRange(speed / C.MPH) * Math.PI / 180; + const vlim = Math.min(C.profileAt(R, prof, S + speed * 0.2), C.profileAt(R, prof, S + speed * 0.45)); + const contact = contactTime(g, opt.ram ? others.filter(o => !o.cop) : others, S, speed, lat), over = speed > vlim + 0.8, brk = over || contact < 0.8, coast = !brk && contact < 1.2; + const grip = (P.grip + 19.62 * (g.sb ? 1 : g.sbRamp / (1 / 3)) + P.aero * speed * speed) * tire, ay = speed * speed * Math.abs(kappa), spare = Math.max(0, 1 - ay / grip); + const allowed = spare / 0.55 * grip * 1.1, drive = Math.max(1, C.driveAt(speed) * P.accel), thr = coast ? 0 : Math.round(HOLD_SETS * clamp(allowed / drive, 0.17, 1)); + const nos = !brk && !coast && (opt.forceNos ? c.nos > 0.02 && speed > 12 : c.nos > 0.02 && speed > 18 && opt.nos !== false && thr === HOLD_SETS && C.profileAt(R, prof, S + speed * 1.8) > speed + 8); + return { keys: steerKeys(c, clamp(delta / range, -1, 1), speed, wscale), thr: brk ? 0 : thr, brk, nos, lat, contact, why: over ? 'speed' : contact < 0.8 ? 'contact' : coast ? 'coast' : 'drive' }; + } + function toPacket(plan) { + const holds = []; + for (let i = 0; i < HOLD_SETS; i++) { + const h = [], k = plan.keys ? plan.keys[i] : 0; + if (plan.brk) h.push('S'); else if (plan.thr >= HOLD_SETS || Math.floor((i + 1) * plan.thr / HOLD_SETS) > Math.floor(i * plan.thr / HOLD_SETS)) h.push('W'); + if (k) h.push(k > 0 ? 'A' : 'D'); + if (plan.nos) h.push('Shift'); + holds.push(h); + } + return { holds, mouse: [0, 0, 0] }; + } + function packet(g, choice) { + if (g.pre > .21) return toPacket({ thr: HOLD_SETS, brk: false, nos: false }); + const opt = { ram: true, margin: 1.02 }; if (choice.lat !== null) { opt.lat = choice.lat; opt.fixedLane = true; } + const p = planDrive(g, opt), sp = C.speed(g.car); + if (choice.gas && p.why !== 'recover') { p.brk = false; p.thr = 6; p.nos = g.car.nos > .02 && sp > 18; } + const pk = toPacket(p); + const sb = choice.sb === undefined ? (sp > 18 && (p.why === 'speed' || Math.abs(g.car.steer) > .65)) : choice.sb; + if (sb !== !!g.sb && (g.sb || g.sbMeter > .2) && pk.holds[0].length < 4) pk.holds[0].push('J'); + return pk; + } + // Keys held at the end of the last packet, kept per game tick so a repeated call on one state starts every rollout from the same keys. + const heldMem = new WeakMap(); + const heldBefore = g => { const m = heldMem.get(g); return !m ? [] : m.t === g.t ? m.prev : m.next; }; + const heldAfter = (g, next) => heldMem.set(g, { t: g.t, prev: heldBefore(g), next }); + function session(g, held) { + const s = Object.create(N.Session.prototype); s.module = M; s.game = M.copyGame(g); + s.game.rng = 2463534242; s.game.seed = 0; s.held = held.slice(); s.inputs = []; s.recording = false; s.events = []; // one fixed scenario, not the live draws + return s; + } + // The widest free stretch across the next roadblock within GAP_AHEAD m: between parked cars, barriers and the road edges. + function roadblockGap(g) { + const R = g.route, hw = R.halfW; let S = Infinity; + for (const b of g.blocks) { const bs = M.wrapTo(R, b.s, g.s); if (bs > g.s + 3 && bs < S) S = bs; } + if (S === Infinity || S - g.s > GAP_AHEAD) return null; + const occ = []; for (const b of g.blocks) if (Math.abs(M.wrapTo(R, b.s, g.s) - S) < 1) occ.push([b.lat - GAP_CLEAR, b.lat + GAP_CLEAR]); + occ.sort((x, y) => x[0] - y[0]); + let lo = -hw + GAP_EDGE, best = null; const hi = hw - GAP_EDGE; + for (const [x, y] of occ) { if (x > lo && (!best || Math.min(x, hi) - lo > best[1] - best[0])) best = [lo, Math.min(x, hi)]; lo = Math.max(lo, y); } + if (hi > lo && (!best || hi - lo > best[1] - best[0])) best = [lo, hi]; + return best && best[1] > best[0] ? { s: S, lat: (best[0] + best[1]) / 2 } : null; + } + return function policy(g) { + if (g.car.tires > 0 && g.flash <= 0) { + let near = Infinity; for (const k of g.cops) if (!k.dead && k.state !== 'rb') near = Math.min(near, Math.hypot(g.car.x - k.x, g.car.y - k.y)); + if (near > RESET_NEAR) { heldAfter(g, []); return { holds: [['R'], [], [], [], [], []], mouse: [0, 0, 0] }; } + } + const held = heldBefore(g), edge = g.route.halfW - 2.6; + const choices = [{ lat: null }, { lat: g.lat }, { lat: -edge * .85 }, { lat: edge * .85 }, { lat: -edge * .4 }, { lat: edge * .4 }, + { lat: null, gas: true }, { lat: g.lat, gas: true }, { lat: null, sb: true }]; + const gap = roadblockGap(g); if (gap) choices.push({ lat: gap.lat }, { lat: gap.lat, gas: true }); + let best = null, bestScore = -Infinity; + for (const choice of choices) { + const s = session(g, held), first = packet(s.game, choice); let proximity = 0; + for (let t = 0; t < 120 && !s.game.outcome; t += 12) { + s.packet(t === 0 ? first : packet(s.game, choice)); + const z = s.game, sp = C.speed(z.car); + for (const cop of z.cops) if (!cop.dead && !cop.gone) { const d = Math.hypot(z.car.x - cop.x, z.car.y - cop.y); proximity = Math.max(proximity, Math.max(0, 4 - d) * (sp < 15 ? 3 : 1)); } + } + const z = s.game, road = C.routeAt(z.route, z.s), a = N.angle(z.car.h - road.h); + const score = (z.prog - g.prog) * 3 + C.speed(z.car) * .65 - (z.hits - g.hits) * 8 + - (z.pol.bust - g.pol.bust) * 90 - (z.car.tires - g.car.tires) * 200 - proximity * 12 + - Math.max(0, Math.abs(z.lat) - edge) * 10 - a * a * 5 + (z.car.nos - g.car.nos) * 8 + + (z.outcome === 'win' ? 100000 : 0) - (z.outcome && z.outcome !== 'win' ? 100000 : 0) + - (gap && z.s < gap.s ? Math.abs(z.lat - gap.lat) * GAP_PULL : 0); + if (score > bestScore) { bestScore = score; best = first; } + } + heldAfter(g, best.holds[5].slice().sort()); return best; + }; + })(); + + M.MODES.pursuit = { + route: () => 'coast', + init(g, d) { + g.s0 = S0; g.total = 1e9; g.pre = 0; g.placeCar(S0, -2.5, 34); g.car.gear = 3; // spotted at speed: a pursuit has no starting grid + g.stages = Math.round(M.tierValue(d, [1, 1, 3])); g.stage = 0; g.diff = d; + g.bountyNeed = M.tierValue(d, [10, 32, 34]); g.prog = 0; + M.initPolice(g, { copsMax: 2, top: 60, grip: M.tierValue(d, [0.78, 0.85, 0.92]), accel: M.tierValue(d, [0.8, 0.95, 1.05]), spawnGap: M.tierValue(d, [12, 9, 7]), formations: d < 0.35 ? ['FOLLOW'] : d < 0.7 ? ['FOLLOW', 'ROLLING_BLOCK', 'PIT'] : ['FOLLOW', 'ROLLING_BLOCK', 'BOX_IN', 'PIT'], + rbChance: M.tierValue(d, [0, 0.45, 0.7]), spikeChance: M.tierValue(d, [0, 0.25, 0.5]), rbGap: M.tierValue(d, [8, 7, 6]), heli: d > 0.7, heliAfter: 30, heliFuel: 22, heliGap: 30, bustSpeed: M.tierValue(d, [7, 10, 13]), searchTop: M.tierValue(d, [34, 42, 50]), close: M.tierValue(d, [8, 11, 14]), copFrail: 3.2, aheadChance: M.tierValue(d, [0.25, 0.35, 0.45]), evadeTimeout: M.tierValue(d, [8, 13, 15]) }); + g.breakers = []; const R = g.route; + for (const off of [500, 1500, 2600, 3600, 4600]) { for (const side of [1]) { const s = (S0 + off) % R.L, a = C.routeAt(R, s, side * (R.halfW - 1.5)); g.breakers.push({ s, lat: side * (R.halfW - 2.5), x: a.x, y: a.y, h: a.h, fired: 0, rearm: 0 }); } } + g.bountyTotal = 0; + startStage(g, d); + M.spawnTraffic(g, Math.round(M.tierValue(d, [4, 7, 10]))); + }, + idle(g) { for (const c of g.cops) { const a = C.routeAt(g.route, c.s, c.lat); c.x = a.x; c.y = a.y; c.h = a.h; } }, + tick(g, wdt) { + const p = g.pol, R = g.route, before = p.destroyed; + M.stepPolice(g, wdt, g.stageBounty >= g.bountyNeed); + if (g.outcome) return; + // Pursuit Breaker: driving through the structure brings it down on whatever is around it. + for (const b of g.breakers) { + if (b.rearm > 0) b.rearm -= wdt; + const bs = M.wrapTo(R, b.s, g.s); + if (!b.rearm && Math.abs(g.s - bs) < C.speed(g.car) * wdt + 2 && Math.abs(g.lat - b.lat) < 3.4) { + b.rearm = 60; g.events.push({ type: 'trap_collapse' }); + for (const c of g.cops) if (!c.dead && c.state !== 'rb' && Math.hypot(c.x - b.x, c.y - b.y) < BREAKER_R) M.destroyCop(g, c, 'breaker'); + for (const t of g.traffic) if (!t.crash && Math.hypot(t.x - b.x, t.y - b.y) < 14) { t.crash = 0.6; t.vx = Math.cos(t.h) * Math.abs(t.v) * 0.4; t.vy = Math.sin(t.h) * Math.abs(t.v) * 0.4; } + } + } + // Bounty: seconds in sight, plus a lump per destroyed cop x the multiplier. + if (g.stageBounty < g.bountyNeed) { + if (p.inSight) g.stageBounty += wdt; + if (p.destroyed > before) g.stageBounty += 1.5 * p.bonusMult * (p.destroyed - before); + g.stageBounty = Math.min(g.bountyNeed, g.stageBounty); + } + g.stageEvadeHW = Math.max(g.stageEvadeHW, g.stageBounty >= g.bountyNeed ? p.evade : 0); + if (p.evade >= 1 && g.stageBounty >= g.bountyNeed) { + g.events.push({ type: 'evaded', stage: g.stage }); g.stage++; + if (g.stage >= g.stages) return g.win(); + for (const c of g.cops) c.gone = 1; g.cops = []; + p.evade = 0; startStage(g, g.diff); + } + }, + health(g) { + const total = g.stages * (BOUNTY_UNITS + EVADE_UNITS); + if (g.outcome === 'win') return [M.bustHp(g), 50, 0, total]; + const done = g.stage * (BOUNTY_UNITS + EVADE_UNITS) + BOUNTY_UNITS * g.stageBounty / g.bountyNeed + EVADE_UNITS * g.stageEvadeHW; + return [g.outcome === 'loss' ? 0 : M.bustHp(g), 50, Math.max(0, total - done), total]; + }, + hud(g) { const p = g.pol, s = Math.min(g.stage + 1, g.stages); return { label: 'Police pursuit', detail: `Heat ${s} / ${g.stages} · Bounty ${(100 * g.stageBounty / g.bountyNeed).toFixed(0)}% · Escape ${(100 * p.evade).toFixed(0)}% · Cops ${g.cops.filter(c => !c.dead).length}${g.heli ? ' · Helicopter' : ''}` }; }, + // Reference controller: pursuitPolicy above. + scripted(g) { return pursuitPolicy(g); }, + hudExtra(g, c, u) { const p = g.pol; if (p.bust > 0.03) { c.font = 'bold 13px "Microsoft YaHei",sans-serif'; c.fillStyle = '#ff6a5a'; c.textAlign = 'center'; c.fillText('Busted ' + Math.round(100 * p.bust / M.BUST_MAX) + '%', u.W / 2, 78); c.textAlign = 'left'; } }, + }; + // Razor. GRace kRaceType_P2P with GetIsPursuitRace: the rival and the police at once. Wikipedia: the rematch is "another 5-street racing pink + // slip". Streets are legs of the route here; the player must keep ahead of Razor while the chase is on. + // boss_hp = route metres left; player_hp = the lesser of Razor's remaining share and the bust meter's, per mille. + M.MODES.street_champion = { + route: () => 'coast', + init(g, d) { + const S = 1500; g.s0 = S; g.total = Math.max(120, M.tierValue(d, [920, 2500, 7000])); g.legs = Math.max(1, Math.round(M.tierValue(d, [1, 2, 5]))); /* floors: d < 0.05 extrapolated to a negative route and 0 streets */ g.placeCar(S, -2.2); + g.rivals = [M.newRival(g, { s: S + 9, lat: 2.2, skill: C.clamp(M.tierValue(d, [0.1, 0.3, 0.5]) + M.formOf(g), 0, 1), paint: 3, name: 'champion' })]; + g.rivals[0].s0 = S; g.rivals[0].prog = 9; g.glue = 0.7; + M.initPolice(g, { copsMax: Math.round(M.tierValue(d, [1, 2, 4])), top: M.tierValue(d, [56, 62, 66]), grip: M.tierValue(d, [0.75, 0.82, 0.9]), accel: M.tierValue(d, [0.75, 0.9, 1]), spawnGap: M.tierValue(d, [16, 12, 9]), formations: d < 0.35 ? ['FOLLOW'] : ['FOLLOW', 'ROLLING_BLOCK', 'PIT'], rbChance: M.tierValue(d, [0, 0.35, 0.6]), spikeChance: M.tierValue(d, [0, 0.15, 0.4]), rbGap: M.tierValue(d, [8, 7.5, 6.5]), heli: false, heliAfter: 1e6, heliFuel: 0, heliGap: 1e6, bustSpeed: M.tierValue(d, [6, 9, 12]), searchTop: 40, close: M.tierValue(d, [6, 9, 12]), copFrail: 3.2, aheadChance: M.tierValue(d, [0.2, 0.5, 0.6]), aheadBlind: 1, evadeTimeout: 1e9 }); + g.gates = []; for (let i = 1; i <= g.legs; i++) g.gates.push({ at: g.total * i / g.legs, done: 0, kind: 'line' }); + g.next = 0; + M.spawnTraffic(g, Math.round(M.tierValue(d, [5, 8, 11]))); + }, + idle(g) { for (const r of g.rivals) { const a = C.routeAt(g.route, r.s, r.lat); r.x = a.x; r.y = a.y; r.h = a.h; } }, + tick(g, wdt) { + const r = g.rivals[0]; + M.stepRival(g, r, wdt); M.stepPolice(g, wdt, false); + if (g.outcome) return; + while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) { g.gates[g.next].done = 1; g.next++; g.events.push({ type: 'leg', leg: g.next }); } + if (g.prog >= g.total) return g.win(); + if (r.prog >= g.total) g.lose('gap'); + }, + health(g) { + const r = g.rivals[0], a = clamp((g.total - r.prog) / g.total, 0, 1), b = M.bustHp(g) / 50, hp = g.outcome === 'loss' ? 0 : Math.round(Math.min(a, b) * 1000); + return [hp, 1000, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total]; + }, + hud(g) { const r = g.rivals[0], lead = g.prog - r.prog; return { label: 'Street Champion Showdown', detail: `Leg ${Math.min(g.next + 1, g.legs)} / ${g.legs} · ${lead >= 0 ? 'Ahead by' : 'Behind by'} ${Math.abs(lead).toFixed(0)} m · Cops ${g.cops.filter(c => !c.dead).length}` }; }, + scripted(g) { return championPolicy(g); }, + hudExtra(g, c, u) { M.MODES.pursuit.hudExtra(g, c, u); }, + }; + void N; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/modes_speedtrap.js b/environments/games/web/games/nfsmw_remake/modes_speedtrap.js new file mode 100644 index 0000000000000000000000000000000000000000..9b700bd358225027132863b0ab9f116d4c67a5c1 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_speedtrap.js @@ -0,0 +1,62 @@ +/* Speed Trap (GRace.h kRaceType_SpeedTrap). Crossing order does not matter: "each checkpoint's total speed is accumulated to + determine the winner" (Wikipedia). The speed at each camera is what counts, so the driver saves nitrous for the camera, and the + rival does the same (AIActionRace.cpp CheckSpeedTraps: nitrous 1-3 s ahead by skill, Tweak_SpeedTrapSkillBoost :50), with + half the usual catch-up glue (AIVehicle.cpp:2053 Tweak_SpeedTrapCatchupGlue 0.5). GRaceStatus.h keeps one speed per trap. + boss_hp = route metres left to the last camera; player_hp = cushion + score lead over the traps both cars have crossed. The + camera positions and the cushion are original (the race database is VLT data): cameras sit on the fastest ground nearby. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, P = C.PLAYER, KMH = 3.6, S0 = 900; + M.MODES.speedtrap = { + route: () => 'coast', + init(g, d) { + const R = g.route, v = C.profile(R, P.grip, P.aero, P.brake, C.TOPS[5]); + g.total = M.tierValue(d, [900, 3100, 7800]); g.s0 = S0; g.placeCar(S0, -2.1); g.glue = 0.5; + const count = Math.max(2, Math.round(g.total / 480)), reach = C.reachable(R, v, S0, g.total + 100, P); + g.gates = []; + for (let i = 1; i <= count; i++) { + let at = g.total * i / count; + if (i < count) { let best = at, bv = -1; for (let x = at - 150; x <= at + 150; x += 6) { const u = reach[Math.round(x / R.ds)]; if (u > bv) { bv = u; best = x; } } at = best; } + g.gates.push({ at, kind: 'trap', done: 0, you: 0, them: 0, themDone: 0 }); + } + // Pretraining engineering target from the existing deterministic vehicle/route + // reachability profile. No policy, sampled rival score or evaluation result is used. + // Freeze once at reset; keep health(), HUD, finish and win/loss rules unchanged. + g.reward_target_version = 'speedtrap-reachable-profile@1'; + g.reward_target_cameras = g.gates.map(t => Math.round(reach[Math.round(t.at / R.ds)] * KMH * 1e6) / 1e6); + g.reward_target_score = Math.round(g.reward_target_cameras.reduce((a,b) => a+b, 0) * 1e6) / 1e6; + if (!Number.isFinite(g.reward_target_score) || g.reward_target_score <= 0) throw Error('invalid fixed speedtrap target'); + g.next = 0; g.rNext = 0; g.you = 0; g.them = 0; g.flashT = 0; g.cushion = M.tierValue(d, [130, 95, 70]); + g.rivals = [M.newRival(g, { s: S0, lat: 2.1, skill: C.clamp(M.tierValue(d, [0.15, 0.42, 0.68]) + M.formOf(g), 0, 1), paint: 2 })]; + M.spawnTraffic(g, Math.round(M.tierValue(d, [6, 9, 13]))); + }, + idle() {}, + lead(g) { let lead = 0; for (let i = 0; i < g.gates.length; i++) { const t = g.gates[i]; if (t.done && t.themDone) lead += t.you - t.them; } return lead; }, + tick(g, wdt) { + if (g.flashT > 0) g.flashT = Math.max(0, g.flashT - wdt); + const r = g.rivals[0]; + while (g.rNext < g.gates.length && r.prog >= g.gates[g.rNext].at) { const t = g.gates[g.rNext]; t.them = r.v * KMH; t.themDone = 1; g.them += t.them; g.rNext++; } + if (g.rNext < g.gates.length) { const ahead = g.gates[g.rNext].at - r.prog, tt = ahead / Math.max(r.v, 5); if (tt < C.lerp(1, 3, r.skill)) r.trapNos = 0.2; } + M.stepRival(g, r, wdt); + while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) { const t = g.gates[g.next]; t.done = 1; t.keep = 0; t.you = C.speed(g.car) * KMH; g.you += t.you; g.next++; g.flashT = 0.15; g.events.push({ type: 'speedtrap', kmh: t.you }); } + if (g.next >= g.gates.length) { + // The player's last camera ends the event. Cameras the rival has not reached yet are scored at the speed it would carry there. + let them = g.them; for (let i = g.rNext; i < g.gates.length; i++) them += M.projectRival(g, r, g.s0 + g.gates[i].at) * KMH; + g.themFinal = them; + if (g.you >= them) g.win(); else g.lose('score'); + return; + } + if (g.cushion + this.lead(g) <= 0) g.lose('score'); + }, + health(g) { + const max = g.cushion * 2, hp = g.outcome === 'loss' ? 0 : C.clamp(g.cushion + this.lead(g), 0, max); + return [hp, max, g.outcome === 'win' ? 0 : Math.max(0, g.total - g.prog), g.total]; + }, + hud(g) { return { label: 'Speed Trap', detail: `Checkpoint ${Math.min(g.next + 1, g.gates.length)} / ${g.gates.length} · You: ${g.you.toFixed(0)} · Rival: ${g.them.toFixed(0)} km/h` }; }, + // Reference: drive the line, and spend nitrous only in the last seconds before a camera. + scripted(g) { + const v = Math.max(C.speed(g.car), 5), t = g.gates[g.next], ahead = t ? (t.at - g.prog) / v : 99; + return M.ctl.drive(g, ahead < 2.8 ? { forceNos: true } : { nos: false }); + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/modes_tollbooth.js b/environments/games/web/games/nfsmw_remake/modes_tollbooth.js new file mode 100644 index 0000000000000000000000000000000000000000..eabf8c7729cf21c7acaf61587589c8e0de6da1cb --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/modes_tollbooth.js @@ -0,0 +1,41 @@ +/* Tollbooth (GRace.h kRaceType_Tollbooth): a solo run against the clock. Each gate grants more time and leftover seconds + carry over (Wikipedia, "Need for Speed: Most Wanted (2005)": "a checkpoint-styled solo race, in which players must hit + a set of checkpoints, each one within a set amount of time"; GRaceStatus.h NotifyTollboothCrossed counts them). + boss_hp = route metres left to the last gate; player_hp = clock in tenths of a second. The gate timings live in the + game's race database (VLT), so the allowance here is an approximation: slack x the car's own ideal time. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C; + const P = C.PLAYER, TOP = C.TOPS[5]; + M.MODES.tollbooth = { + route: () => 'coast', + init(g, d) { + const R = g.route, S0 = 3640; + g.total = M.tierValue(d, [860, 3250, 8000]); + g.s0 = S0; g.placeCar(S0, -2.1); + const slack = M.tierValue(d, [1.55, 1.34, 1.2]), v = C.profile(R, P.grip, P.aero, P.brake, TOP), spacing = 620; + const count = Math.max(2, Math.round(g.total / spacing)); + g.gates = []; + let at = 0; + for (let i = 1; i <= count; i++) { const end = g.total * i / count; g.gates.push({ at: end, grant: C.driveTime(R, v, S0 + at, end - at, P, i === 1 ? 0 : 30) * slack, done: 0 }); at = end; } + g.next = 0; g.bank = g.gates[0].grant + 3; g.bankMax = g.bank; + M.spawnTraffic(g, Math.round(M.tierValue(d, [7, 11, 16]))); + }, + idle() {}, + tick(g, wdt) { + g.bank -= wdt; + while (g.next < g.gates.length && g.prog >= g.gates[g.next].at) { + const gate = g.gates[g.next]; gate.done = 1; g.next++; + g.events.push({ type: 'gate', left: g.bank }); + if (g.next < g.gates.length) { g.bank += g.gates[g.next].grant; g.bankMax = Math.max(g.bankMax, g.bank); } + } + if (g.prog >= g.total) return g.win(); + if (g.bank <= 0) { g.bank = 0; g.lose('time'); } + }, + health(g) { + const left = Math.max(0, g.total - g.prog); + return [Math.max(0, g.outcome === 'loss' ? 0 : Math.round(g.bank * 10)), Math.ceil(g.bankMax * 10), g.outcome === 'win' ? 0 : left, g.total]; + }, + hud(g) { return { label: 'Tollbooth', detail: `Gate ${Math.min(g.next + 1, g.gates.length)} / ${g.gates.length} · Time left: ${g.bank.toFixed(1)} s` }; }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/nfscore.js b/environments/games/web/games/nfsmw_remake/nfscore.js new file mode 100644 index 0000000000000000000000000000000000000000..c23768b7b1708bbe8da239eb8587146ce84c06bd --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/nfscore.js @@ -0,0 +1,237 @@ +/* Need for Speed: Most Wanted (2005) events, rules nfsmw-arena@1 - world and vehicle core. + Original procedural city: the roads are a union of capsules around authored polylines, so a car is free inside the + union and everything outside is a wall; sight lines sample the same function. Routes are rounded polylines sampled + every 2 m and measured along their own length (progress is route distance, never distance to a target). + Vehicle rules read from the CC0 decompilation dbalatoni13/nfsmw@80993f3 are cited inline; values that live in the + game's VLT data (mass, torque, grip) are not in that repository and are original approximations. + Nothing here touches a game's RNG: every function is pure except for the car it is handed. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame = root.NfsmwGame || {}, C = M.C = {}; + const q4 = v => Math.round(v * 1e4) / 1e4; // static geometry is rounded once so trig ULPs cannot reach a replay + const clamp = (v, a, b) => v < a ? a : v > b ? b : v; + C.clamp = clamp; C.lerp = (a, b, t) => a + (b - a) * t; + C.MPH = 0.44704; C.KPH = 1 / 3.6; + + // ---------------- authored routes: [x, y, corner radius] (original layout) ---------------- + const ROUTES = { + // Coastal loop: the 1.5 km highway along the south shore, sweepers in the east, a chicane in the north, hills west. + coast: { loop: true, width: 17, pts: [[-760, -520, 90], [860, -520, 220], [980, -120, 160], [760, 260, 120], [820, 520, 100], [300, 560, 80], [220, 400, 45], [-60, 400, 45], [-140, 560, 70], [-620, 560, 120], [-820, 260, 90], [-640, 60, 70], [-860, -140, 90]] }, + // Downtown block: the short circuit for the knockout, four fast corners and an inner chicane. + downtown: { loop: true, width: 15, pts: [[-85, -80, 26], [90, -80, 22], [90, -22, 15], [46, -22, 13], [46, 28, 13], [90, 28, 15], [90, 80, 22], [-85, 80, 26]] }, + // Highway 99 drag strip: dead straight, four lanes, not connected to the city. + strip: { loop: false, width: 22, pts: [[-1500, -1000, 0], [1500, -1000, 0]] }, + }; + // Cross streets: never raced, they are what the pursuit is about (sight breaks, cops arriving from the side). + const STREETS = [ + [[0, -520], [0, -80]], [[0, 80], [0, 400]], [[46, 3], [420, 3], [420, 260], [760, 260]], [[-85, 0], [-400, 0], [-400, 60], [-640, 60]], + [[420, 0], [420, -520]], [[-400, 0], [-400, -520]], [[420, 260], [300, 560]], [[-400, 60], [-400, 560]], + ]; + const STREET_W = 13, DS = 2; + + function buildRoute(name, def) { + const P = def.pts, n = P.length; // each corner becomes a tangent arc between two straights + const corner = i => { + const [x, y, r] = P[i], a = P[(i + n - 1) % n], b = P[(i + 1) % n]; + const ax = a[0] - x, ay = a[1] - y, bx = b[0] - x, by = b[1] - y, la = Math.hypot(ax, ay), lb = Math.hypot(bx, by); + const ux = ax / la, uy = ay / la, vx = bx / lb, vy = by / lb, cos = clamp(ux * vx + uy * vy, -1, 1), th = Math.acos(cos); + const t = r / Math.tan(th / 2); + if (t > Math.min(la, lb) * 0.5 + 1e-6) throw Error(`${name}: corner ${i} radius too large`); + const hx = ux + vx, hy = uy + vy, hl = Math.hypot(hx, hy), dist = r / Math.sin(th / 2); + const cx = x + hx / hl * dist, cy = y + hy / hl * dist, sx = x + ux * t, sy = y + uy * t, ex = x + vx * t, ey = y + vy * t; + const turn = -Math.sign(ux * vy - uy * vx); // +1 = counter-clockwise + return { sx, sy, ex, ey, cx, cy, r, sweep: Math.PI - th, turn }; + }; + const out = { x: [], y: [], h: [], k: [] }; + const push = (x, y, h, k) => { out.x.push(q4(x)); out.y.push(q4(y)); out.h.push(q4(h)); out.k.push(Math.round(k * 1e7) / 1e7); }; + const dense = []; // 0.25 m polyline with curvature, resampled to DS below + const line = (ax, ay, bx, by) => { const L = Math.hypot(bx - ax, by - ay), m = Math.max(1, Math.ceil(L / 0.25)), h = Math.atan2(by - ay, bx - ax); for (let i = 0; i < m; i++) dense.push([ax + (bx - ax) * i / m, ay + (by - ay) * i / m, h, 0]); }; + if (def.loop) { + const cs = P.map((_, i) => corner(i)); + for (let i = 0; i < n; i++) { + const c = cs[i], d = cs[(i + 1) % n], a0 = Math.atan2(c.sy - c.cy, c.sx - c.cx), m = Math.max(1, Math.ceil(c.r * c.sweep / 0.25)); + for (let j = 0; j < m; j++) { const a = a0 + c.turn * c.sweep * j / m; dense.push([c.cx + Math.cos(a) * c.r, c.cy + Math.sin(a) * c.r, a + c.turn * Math.PI / 2, c.turn / c.r]); } + line(c.ex, c.ey, d.sx, d.sy); + } + } else { for (let i = 0; i + 1 < n; i++) line(P[i][0], P[i][1], P[i + 1][0], P[i + 1][1]); dense.push([P[n - 1][0], P[n - 1][1], dense[dense.length - 1][2], 0]); } + let acc = 0, next = 0, last = dense[0]; + dense.forEach((p, i) => { if (i) acc += Math.hypot(p[0] - last[0], p[1] - last[1]); last = p; while (acc >= next - 1e-9) { push(p[0], p[1], p[2], p[3]); next += DS; } }); + const L = out.x.length * DS; + return { name, loop: !!def.loop, width: def.width, halfW: def.width / 2, ds: DS, n: out.x.length, L, x: out.x, y: out.y, h: out.h, k: out.k }; + } + C.routes = {}; for (const [k, d] of Object.entries(ROUTES)) C.routes[k] = buildRoute(k, d); + // Route position (s is unbounded on a loop). Writes to a shared scratch object: copy the fields you keep. + const at = { x: 0, y: 0, h: 0, k: 0, nx: 0, ny: 0 }; + C.routeAt = (R, s, lat = 0) => { + let u = s / R.ds; if (R.loop) { u %= R.n; if (u < 0) u += R.n; } else u = clamp(u, 0, R.n - 1.0001); + const i = Math.floor(u), f = u - i, j = (i + 1) % R.n; + let dh = R.h[j] - R.h[i]; if (dh > Math.PI) dh -= 2 * Math.PI; else if (dh < -Math.PI) dh += 2 * Math.PI; + at.h = R.h[i] + dh * f; at.k = R.k[i]; at.nx = -Math.sin(at.h); at.ny = Math.cos(at.h); + at.x = R.x[i] + (R.x[j] - R.x[i]) * f + at.nx * lat; at.y = R.y[i] + (R.y[j] - R.y[i]) * f + at.ny * lat; + return at; + }; + // Nearest route distance within a window around a guess: junctions can never teleport progress to another leg. + C.routeNear = (R, x, y, guess, back = 40, fwd = 60) => { + let best = guess, bd = Infinity; + const g0 = Math.round(guess / R.ds) * R.ds; + for (let s = g0 - back; s <= g0 + fwd; s += R.ds) { + if (!R.loop && (s < 0 || s > R.L)) continue; + let u = Math.round(s / R.ds); if (R.loop) { u %= R.n; if (u < 0) u += R.n; } else u = clamp(u, 0, R.n - 1); + const dx = x - R.x[u], dy = y - R.y[u], d = dx * dx + dy * dy; if (d < bd) { bd = d; best = s; } + } + // refine inside the winning 2 m cell with the segment projection + const a = C.routeAt(R, best), ax = Math.cos(a.h), ay = Math.sin(a.h); + return best + clamp((x - a.x) * ax + (y - a.y) * ay, -R.ds, R.ds); + }; + C.routeLat = (R, x, y, s) => { const a = C.routeAt(R, s); return (x - a.x) * a.nx + (y - a.y) * a.ny; }; + + // ---------------- the road union: 10 m grid of candidate capsules ---------------- + const SEGS = []; const addPoly = (pts, hw, closed) => { const m = closed ? pts.length : pts.length - 1; for (let i = 0; i < m; i++) { const a = pts[i], b = pts[(i + 1) % pts.length]; SEGS.push({ ax: a[0], ay: a[1], bx: b[0], by: b[1], hw }); } }; + for (const R of Object.values(C.routes)) { const pts = []; const step = R.name === 'strip' ? 50 : R.name === 'downtown' ? 2 : 4; for (let i = 0; i < R.n; i += step) pts.push([R.x[i], R.y[i]]); if (!R.loop) pts.push([R.x[R.n - 1], R.y[R.n - 1]]); addPoly(pts, R.halfW, R.loop); } + for (const st of STREETS) addPoly(st, STREET_W / 2, false); + C.streets = STREETS; C.streetW = STREET_W; + const CELL = 10, X0 = -1560, Y0 = -1060, NX = 310, NY = 180, GRID = new Array(NX * NY); + SEGS.forEach((g, gi) => { + const pad = g.hw + CELL * 1.5, x0 = Math.floor((Math.min(g.ax, g.bx) - pad - X0) / CELL), x1 = Math.floor((Math.max(g.ax, g.bx) + pad - X0) / CELL), y0 = Math.floor((Math.min(g.ay, g.by) - pad - Y0) / CELL), y1 = Math.floor((Math.max(g.ay, g.by) + pad - Y0) / CELL); + for (let j = Math.max(0, y0); j <= Math.min(NY - 1, y1); j++) for (let i = Math.max(0, x0); i <= Math.min(NX - 1, x1); i++) { const px = X0 + (i + 0.5) * CELL, py = Y0 + (j + 0.5) * CELL, dx = g.bx - g.ax, dy = g.by - g.ay, t = clamp(((px - g.ax) * dx + (py - g.ay) * dy) / (dx * dx + dy * dy || 1), 0, 1); if (Math.hypot(px - g.ax - t * dx, py - g.ay - t * dy) <= pad) { const c = i + j * NX; (GRID[c] || (GRID[c] = [])).push(gi); } } + }); + // d > 0 means d metres outside the union; (nx, ny) points from the road centre towards the car. + const hit = { d: 0, nx: 0, ny: 0 }; + C.road = (x, y) => { + const i = Math.floor((x - X0) / CELL), j = Math.floor((y - Y0) / CELL); + hit.d = 99; hit.nx = 0; hit.ny = 0; + if (i < 0 || j < 0 || i >= NX || j >= NY) return hit; + const c = GRID[i + j * NX]; if (!c) return hit; + for (let k = 0; k < c.length; k++) { + const g = SEGS[c[k]], dx = g.bx - g.ax, dy = g.by - g.ay, t = clamp(((x - g.ax) * dx + (y - g.ay) * dy) / (dx * dx + dy * dy || 1), 0, 1), px = x - g.ax - t * dx, py = y - g.ay - t * dy, l = Math.sqrt(px * px + py * py), d = l - g.hw; + if (d < hit.d) { hit.d = d; if (l > 1e-6) { hit.nx = px / l; hit.ny = py / l; } else { hit.nx = 0; hit.ny = 0; } } + } + return hit; + }; + C.onRoad = (x, y, margin = 0) => C.road(x, y).d < -margin; + // Sight line: buildings stand everywhere the road is not (AIVehicleCopCar::CanSeeTarget's world ray, sampled). + C.lineClear = (ax, ay, bx, by) => { const L = Math.hypot(bx - ax, by - ay), m = Math.ceil(L / 5); for (let i = 1; i < m; i++) if (C.road(ax + (bx - ax) * i / m, ay + (by - ay) * i / m).d > 2) return false; return true; }; + C.bounds = { X0, Y0, NX, NY, CELL }; + + // ---------------- vehicle ---------------- + const lookup = (tab, v, max) => { const u = clamp(v / max, 0, 1) * (tab.length - 1), i = Math.min(tab.length - 2, Math.floor(u)); return tab[i] + (tab[i + 1] - tab[i]) * (u - i); }; + // SuspensionRacer.cpp:1077 SteeringRangeData, degrees over 0..160 mph; :1072 BrakeSteeringRangeMultiplier 1.45. + const STEER_RANGE = [40, 20, 10, 5.5, 4.5, 3.25, 2.9, 2.9, 2.9, 2.9], BRAKE_STEER = 1.45; + // Approximation (VLT transmission/engine data is not in the repository): an original six-speed road car. + const TOPS = [17, 30, 43, 55, 67, 84], DRIVE = [10.5, 8.2, 6.4, 5.0, 4.0, 3.1]; + const PLAYER = { wheelbase: 2.7, grip: 12.5, aero: 0.0012, drag: 0.00039, roll: 0.25, brake: 13, accel: 1, radius: 1.5, nosBoost: 0.35, nosSeconds: 6, overheat: false }; + C.PLAYER = PLAYER; C.TOPS = TOPS; + C.newCar = (x, y, h) => ({ x, y, h, vx: 0, vy: 0, r: 0, steer: 0, gear: 0, clutch: 0, bonus: 0, perfect: 0, nos: 1, nosOn: 0, heat: 0, blown: 0, tires: 0, hit: 0, drift: 0, over: 0 }); + const NOS_MIN_MPH = 10; // EngineRacer.cpp:926 Tweak_MinSpeedForNosMPH; half of it keeps nitrous engaged (:950) + // Over-rev heat, EngineRacer.cpp:1340-1345: +0.45/s on the limiter, -0.1/s otherwise, blown at 1, -25% torque from 0.6. + const HEAT_UP = 0.45, HEAT_DOWN = -0.1, HEAT_PENALTY = 0.6, HEAT_TORQUE = 0.75; + const CLUTCH = 0.25, CLUTCH_FIRST = 0.05; // EngineRacer.cpp:34-35 + C.steerRange = mph => lookup(STEER_RANGE, mph, 160); + C.tireFactor = c => 1 - 0.7 * (c.tires / 4); // SuspensionRacer.cpp:1569 Tweak_BlownTireTraction 0.3 on all four + // One step. inp: {thr, brk, steer in [-1,1] (+ = left), hb, nos, up, down, manual, reverse, sbGrip}. dt is world time. + C.carStep = (c, inp, dt, P = PLAYER) => { + const ch = Math.cos(c.h), sh = Math.sin(c.h); + let vf = c.vx * ch + c.vy * sh, vl = -c.vx * sh + c.vy * ch; + const speed = Math.hypot(vf, vl), mph = speed / C.MPH, tire = C.tireFactor(c); + // steering: input slews, range comes from the speed table + const rate = speed < 15 ? 7 : speed < 40 ? 5 : 3.6, want = clamp(inp.steer, -1, 1); + c.steer += clamp(want - c.steer, -rate * dt, rate * dt); + const range = lookup(STEER_RANGE, mph, 160) * (inp.hb || inp.brk ? BRAKE_STEER : 1), delta = c.steer * range * Math.PI / 180; + const grip0 = (P.grip + P.aero * speed * speed + (inp.sbGrip || 0)) * tire; + let target = vf * Math.tan(delta) / P.wheelbase, rmax = grip0 * 1.05 / Math.max(speed, 3); + if (inp.hb) rmax *= 1.9; + target = clamp(target, -rmax, rmax); + c.r += (target - c.r) * Math.min(1, dt * 9); + c.h += c.r * dt; + // gearbox and drive + if (c.clutch > 0) c.clutch = Math.max(0, c.clutch - dt); + if (c.bonus > 0) c.bonus = Math.max(0, c.bonus - dt); + const u = Math.max(vf, 0) / TOPS[c.gear]; + if (inp.manual) { + if (inp.up && c.gear < 5) { const perfect = u >= 0.88 && u <= 0.99; c.clutch = perfect ? CLUTCH_FIRST : CLUTCH; if (perfect) { c.bonus = 1; c.perfect++; } c.gear++; } + else if (inp.down && c.gear > 0) { c.gear--; c.clutch = CLUTCH; } + } else if (c.clutch <= 0) { + if (u > 0.97 && c.gear < 5) { c.clutch = c.gear === 0 ? CLUTCH_FIRST : CLUTCH; c.gear++; } + else if (c.gear > 0 && vf < TOPS[c.gear - 1] * 0.82) c.gear--; + } + // nitrous, EngineRacer::DoNos + let boost = 1; + const engaged = !!inp.nos && inp.thr > 0 && c.nos > 0 && !c.blown && (mph >= NOS_MIN_MPH || (c.nosOn && mph >= NOS_MIN_MPH / 2)); + if (engaged) { c.nos = Math.max(0, c.nos - dt / P.nosSeconds); boost = 1 + P.nosBoost; c.nosOn = 1; } + else { c.nosOn = 0; if (speed > 10) c.nos = Math.min(1, c.nos + dt * (speed > 50 ? 0.07 : 0.035)); } + const uNow = Math.max(vf, 0) / TOPS[c.gear], limiter = uNow >= 1; + c.over = limiter && inp.thr > 0 ? 1 : 0; + if (P.overheat && c.gear > 0) { c.heat = Math.max(0, c.heat + (c.over ? HEAT_UP : HEAT_DOWN) * dt); if (c.heat >= 1) c.blown = 1; } + let drive = 0; + if (!c.blown && c.clutch <= 0 && inp.thr > 0) { + const curve = uNow < 0.35 ? 0.75 + 0.25 * uNow / 0.35 : uNow < 0.9 ? 1 : uNow < 1 ? 1 - (uNow - 0.9) * 2 : 0; + drive = DRIVE[c.gear] * curve * inp.thr * boost * P.accel * tire * (c.heat > HEAT_PENALTY ? HEAT_TORQUE : 1) * (c.bonus > 0 ? 1.1 : 1); + } + // re-express velocity in the turned frame; rear tyres scrub the lateral part (handbrake drops them) + const ch2 = Math.cos(c.h), sh2 = Math.sin(c.h); + vf = c.vx * ch2 + c.vy * sh2; vl = -c.vx * sh2 + c.vy * ch2; + let ax = drive - P.drag * vf * Math.abs(vf) - P.roll * (Math.abs(vf) > 0.2 ? Math.sign(vf) : 0); + if (inp.brk) { if (vf > 0.3) ax -= P.brake * tire; else if (inp.reverse) ax -= 4.5; } + if (inp.hb && Math.abs(vf) > 0.3) ax -= 6 * Math.sign(vf); + const longLim = grip0 * 1.1; ax = clamp(ax, -longLim, longLim); + const used = Math.min(0.75, Math.abs(ax) / longLim * 0.55), latCap = grip0 * (inp.hb ? 0.42 : 1) * (1 - used); + vf += ax * dt; + if (inp.brk && !inp.reverse && vf < 0) vf = 0; + const dl = clamp(vl, -latCap * dt, latCap * dt); vl -= dl; + c.drift = Math.abs(vl) > 2.5 ? 1 : 0; + if (c.drift) vf -= Math.sign(vf) * Math.min(Math.abs(vf), 0.8 * dt); + c.vx = vf * ch2 - vl * sh2; c.vy = vf * sh2 + vl * ch2; + c.x += c.vx * dt; c.y += c.vy * dt; + // walls: everything outside the road union + const q = C.road(c.x, c.y), over = q.d + 1; + c.hit = 0; + if (over > 0) { + c.x -= q.nx * over; c.y -= q.ny * over; + const vn = c.vx * q.nx + c.vy * q.ny; + if (vn > 0) { + c.vx -= 1.25 * vn * q.nx; c.vy -= 1.25 * vn * q.ny; + const scrub = 1 - Math.min(0.3, vn * 0.012); c.vx *= scrub; c.vy *= scrub; c.hit = vn; if (vn > 3) c.r *= 0.3; + } else { c.vx *= 1 - 0.3 * dt; c.vy *= 1 - 0.3 * dt; } + } + }; + C.speed = c => Math.hypot(c.vx, c.vy); + // Point-mass speed profile along a route: curvature limit with a backward braking pass. grip follows + // AIActionRace::GetPotentialSpeed (grip scaled by skill); the player's controller uses the player's own numbers. + const profiles = new Map(); + C.profile = (R, grip, aero, brake, top) => { + const key = R.name + '|' + [grip, aero, brake, top].map(v => v.toFixed(3)).join('|'); + let v = profiles.get(key); if (v) return v; + v = new Float64Array(R.n); + // Curvature is taken over +-6 m: a car starts turning before the arc begins and has not finished when it ends. + for (let i = 0; i < R.n; i++) { + let k = 0; for (let j = -3; j <= 3; j++) { const m = R.loop ? (i + j + R.n) % R.n : clamp(i + j, 0, R.n - 1); k = Math.max(k, Math.abs(R.k[m])); } + // k * v^2 = grip + aero v^2 -> v^2 = grip / (k - aero) + v[i] = k > aero + 1e-5 ? Math.min(top, Math.sqrt(grip / (k - aero))) : top; + } + const passes = R.loop ? 2 : 1; + for (let p = 0; p < passes; p++) for (let i = R.n - 1; i >= 0; i--) { + const j = i + 1 < R.n ? i + 1 : R.loop ? 0 : i; + const lim = Math.sqrt(v[j] * v[j] + 2 * brake * R.ds); if (lim < v[i]) v[i] = lim; + } + profiles.set(key, v); return v; + }; + // Drive force at a speed in the gear an automatic box would hold: the same curve as carStep. Rivals and estimates use it. + C.driveAt = u => { let gear = 0; while (gear < 5 && u > TOPS[gear] * 0.97) gear++; const un = u / TOPS[gear], curve = un < 0.35 ? 0.75 + 0.25 * un / 0.35 : un < 0.9 ? 1 : Math.max(0, 1 - (un - 0.9) * 2); return DRIVE[gear] * curve; }; + // Speed a car can actually carry along a stretch: forward pass over the limits. The profile alone reads top speed on the exit of any corner. + C.reachable = (R, v, s0, len, P = PLAYER, v0 = 0) => { + const out = []; let u = v0; + for (let s = 0; s <= len; s += R.ds) { const a = Math.max(0, C.driveAt(u) * P.accel - P.drag * u * u - P.roll); u = Math.min(C.profileAt(R, v, s0 + s), Math.sqrt(u * u + 2 * a * R.ds)); out.push(u); } + return out; + }; + // Time for the car to cover a stretch: the profile's corner and braking limits with the gearbox's acceleration on top. + C.driveTime = (R, v, s0, len, P = PLAYER, v0 = 0) => { + let t = 0, u = v0; + for (let s = 0; s < len; s += R.ds) { + const vmax = C.profileAt(R, v, s0 + s), a = Math.max(0.2, C.driveAt(u) * P.accel - P.drag * u * u - P.roll); + u = Math.min(vmax, Math.sqrt(u * u + 2 * a * R.ds)); + t += R.ds / Math.max(u, 3); + } + return t; + }; + C.profileAt = (R, v, s) => { let i = Math.round(s / R.ds); if (R.loop) { i %= R.n; if (i < 0) i += R.n; } else i = clamp(i, 0, R.n - 1); return v[i]; }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/page.js b/environments/games/web/games/nfsmw_remake/page.js new file mode 100644 index 0000000000000000000000000000000000000000..15efa5035cf621d8e32f9cc8666348c607eea8b7 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/page.js @@ -0,0 +1,135 @@ +/* Page-only layer for the human play page. Not listed in manifest.json: the public interface, the recordings and the source + fingerprint never load it, so nothing here can change a fight. The shared shell (_native/shell.js) owns the loop, the session, + the keys, and since 2026-11-08 also: restart after a result (click on the picture, Enter, R; not after a replay), focus back + to the picture after a button, a frame loop that survives a throw from M.draw (pause + reason in the status bar), and the + Module.pointerLock opt-out. This file only adds what the shell does not do ("only one race"): + - a panel over the picture before a race, while paused and after the result, with buttons that stay on the picture + (retry / next event), the event's control hints, and a hint for the reason a race was lost; + - N for the next event, Enter to start from the idle panel and to resume from the pause panel; + - focus back to the picture after picking an event or a tier in the lists, and when a game key is pressed on a button; + - pointer lock off (this game never uses the mouse; a locked cursor could not reach the buttons); + - a new 3D scene after a renderer failure: the shell pauses the race, but the old scene keeps its dead WebGL context. + It drives the shell only through its own buttons, so a race started here is exactly a race started from the toolbar. + Restart keys and clicks are never handled twice: Enter / R after a result are the shell's (its capture listener runs first + and stops the event), and the panel covers the canvas, so the shell's canvas click and the panel's click never both fire. */ +(function () { + 'use strict'; + const M = window.GAME_MODULE, $ = s => document.querySelector(s), canvas = $('canvas'), panel = $('#nfs-panel'); + if (!M || !canvas || !panel) return; + M.pointerLock = false; // read by the shell's double-click handler (shell.js, 2026-11-08) + let game = null, resultAt = 0, shown = '', broken = null, retryAt = 0; + const HINT = { + tollbooth: ['Passing a tollbooth adds time; you lose when the timer reaches zero', 'Release W or tap S before turns; use Shift for nitrous on straights'], + drag: ['Manual gears: press K to upshift when the RPM needle reaches green (L downshifts)', 'Hold W during the countdown to keep RPM in the green launch zone', 'Use A / D to change lanes and avoid traffic. Staying in the red zone blows the engine; a high-speed crash totals the car'], + speedtrap: ['Your speed is added at each checkpoint; beat the rival’s total to win', 'Use nitrous (Shift) 2–3 seconds before a speed checkpoint'], + knockout: ['The last-place driver is eliminated each lap; stay ahead', 'J toggles slow motion for stronger grip; use it before entering a turn'], + pursuit: ['Build the required bounty while police can see you, then lose them', 'The escape meter starts filling after seven seconds out of sight; nearby cops can bust you at low speed', 'Drive through orange pursuit breakers to crush nearby police cars'], + street_champion: ['Reach the final leg’s finish before your rival', 'Avoid arrest too: keep moving and never stop beside police cars'], + }; + const TIP = { + 'drag|gap': 'Drag races use manual gears: press K when RPM enters green. Holding only W leaves you in first gear.', + 'drag|blown': 'Staying in the red zone overheats and blows the engine. Upshift with K promptly or release W briefly.', + 'drag|totaled': 'A high-speed collision totals the car. Change lanes with A / D before reaching traffic.', + 'tollbooth|time': 'Ease off the throttle before turns and use nitrous (Shift) on straights. Hitting walls wastes the most time.', + 'speedtrap|score': 'Save nitrous for speed checkpoints and cross each one as fast as possible.', + 'knockout|knocked': 'Press J before a turn for slow motion, better grip, and easier passing.', + 'pursuit|busted': 'The bust meter rises only when police are close and you are moving slowly. Keep moving and use orange pursuit breakers.', + 'street_champion|busted': 'The bust meter rises only when police are close and you are moving slowly. Keep your speed up.', + 'street_champion|gap': 'Your rival uses nitrous. Hold Shift on straights and take the inside line through turns.', + }; + const LOSS = { time: 'Time expired', gap: 'Rival reached the finish first', blown: 'Engine blown', totaled: 'Crash wreck', busted: 'Busted', knocked: 'Eliminated in last place', score: 'Lost on total score' }; + const nameOf = id => (M.cases.find(c => c.id === id) || { name: id }).name; + const running = () => $('#pause').textContent === 'Pause'; + // Replay or race: the shell keeps that in a closure. Its status line says which one started (a replay: 'Replay verified…'; + // a race or the demo: 'Recording this match…' / 'Scripted demo running…'), so a flag follows only those two kinds of message; anything else the + // status shows later (an export, an error) leaves it alone. After a replay the shell does not restart on Enter / R or on a + // click, so neither does the panel. (2026-11-08: reading the status text directly broke after an export rewrote it.) + let inReplay = false; + new MutationObserver(() => { const t = $('#status').textContent; if (/^Replay verified/.test(t)) inReplay = true; else if (/^(Recording this match|Scripted demo running)/.test(t)) inReplay = false; }) + .observe($('#status'), { childList: true, characterData: true, subtree: true }); + const replayMode = () => inReplay; + // A different event picked in the list after a result or while paused: the panel offers that event, not the old race. + const state = () => !game ? 'idle' : running() ? 'run' : $('#case').value !== game.id ? 'idle' : game.outcome ? 'result' : game.t > 0 ? 'paused' : 'idle'; + const again = () => $('#start').click(); + const resume = () => $('#pause').click(); + function next() { const s = $('#case'); s.selectedIndex = (s.selectedIndex + 1) % s.options.length; s.dispatchEvent(new Event('change')); again(); } + const esc = s => String(s).replace(/[&<>]/g, ch => ({ '&': '&', '<': '<', '>': '>' })[ch]); + + // ---- renderer failure (WebGL context lost). The shell catches a throw from M.draw and pauses the race with the reason in the + // status bar; the old scene, though, keeps its dead context and would fail on every frame. Here the scene is closed so the + // next draw builds a new one with a new context, at most once a second, and the error is passed on to the shell. ---- + const draw0 = M.draw; + let lastT = -1; + M.draw = function (g, ctx) { + const advanced = g === game && g.t !== lastT; // the race ran since the last picture of this game + game = g; lastT = g.t; + if (broken && performance.now() < retryAt) { + paintBroken(ctx); + // Resumed before the new scene is up: pause again through the shell's own lost-focus path (it pauses only a running race). + if (advanced) { window.dispatchEvent(new Event('blur')); $('#status').textContent = 'Rebuilding 3D scene. Please wait before resuming.'; } + return; + } + try { + draw0.call(this, g, ctx); + if (broken) { broken = null; shown = ''; $('#status').textContent = '3D scene restored. Press Enter or click Resume to continue.'; } + } catch (e) { + broken = String(e && e.message || e).slice(0, 120); retryAt = performance.now() + 1000; shown = ''; + try { M.closeRenderer(ctx); } catch (_) { /* a lost context cannot be cleaned further */ } + paintBroken(ctx); + throw e; // the shell's frame loop catches it: it pauses the race and shows the reason + } + }; + function paintBroken(ctx) { + ctx.fillStyle = '#0b1016'; ctx.fillRect(0, 0, 854, 480); ctx.fillStyle = '#ffd08a'; ctx.font = 'bold 20px "Microsoft YaHei",sans-serif'; ctx.textAlign = 'center'; + ctx.fillText('Screen error. Rebuilding 3D scene…', 427, 220); ctx.font = '13px Consolas,monospace'; ctx.fillStyle = '#a8b4c0'; ctx.fillText(broken || '', 427, 250); ctx.textAlign = 'left'; + } + + function render(st) { + const k = st === 'idle' ? ($('#case').value || '').split('/')[1] : game.key, title = st === 'idle' ? nameOf($('#case').value) : nameOf(game.id); + const hints = (HINT[k] || []).map(h => `
          • ${esc(h)}
          • `).join(''), base = '
          • W accelerate · S brake / reverse · A / D steer · Space handbrake · Shift nitrous · J slow motion · R reset
          • '; + let html = ''; + if (st === 'idle') html = `

            ${esc(title)}

              ${hints}${base}

            You can also click the screen to start

            `; + else if (st === 'paused') html = `

            ${broken ? 'Screen error; paused' : 'Paused'}

            ${broken ? '

            The 3D scene is rebuilding. When the picture returns, press Enter or click Resume.

            ' : ''}
              ${hints}${base}
            `; + else if (st === 'result' && replayMode()) { + html = `

            Replay Finished

            ${esc(title)} · ${(game.t / M.hz).toFixed(2)} seconds · Result: ${esc(game.outcome)}

            `; + } else if (st === 'result') { + const win = game.outcome === 'win', why = game.lossReason, tip = !win && TIP[k + '|' + why]; + html = `

            ${win ? 'Challenge complete' : game.outcome === 'timeout' ? 'Time up' : esc(LOSS[why] || 'Challenge Failed')}

            ${esc(title)} · ${(game.t / M.hz).toFixed(2)} seconds

            ${tip ? `

            Tip: ${esc(tip)}

            ` : ''}

            You can also click anywhere on the screen to retry

            `; + } + panel.querySelector('.nfs-card').innerHTML = html; + } + function tick() { + const st = state(); + if (st === 'result' && !resultAt) resultAt = performance.now(); + if (st !== 'result') resultAt = 0; + const tag = [st, $('#case').value, game && game.id, game && game.outcome, game && game.lossReason, !!broken, replayMode()].join('|'); + if (tag !== shown) { shown = tag; panel.hidden = st === 'run'; if (st !== 'run') render(st); } + requestAnimationFrame(tick); + } + panel.addEventListener('click', e => { + const b = e.target.closest('button'), st = state(); + if (b) { const a = b.dataset.act; if (a === 'again') again(); else if (a === 'next') next(); else if (a === 'resume') resume(); return; } + if (e.target.closest('.nfs-card') && st !== 'result') return; + if (st === 'result' && (replayMode() || performance.now() - resultAt < 600)) return; // after a replay: buttons only; and never a click meant for the race + if (st === 'paused') resume(); else again(); + }); + // A game key while a button has focus (reached with Tab): the shell ignores keys on a BUTTON, so the key would be lost. Move the + // focus to the picture first; this capture listener runs before the shell's own key listener, which then sees the canvas. + // Enter and Space keep their button meaning. + const GAME_KEYS = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ShiftLeft', 'ShiftRight', 'KeyJ', 'KeyK', 'KeyL', 'KeyQ', 'KeyE', 'KeyR', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']); + window.addEventListener('keydown', e => { const a = document.activeElement; if (a && a.tagName === 'BUTTON' && GAME_KEYS.has(e.code)) canvas.focus(); }, true); + // Enter / R after a result are the shell's; N (next event), Enter on the idle panel and Enter on the pause panel are added here. + window.addEventListener('keydown', e => { + const tag = document.activeElement && document.activeElement.tagName; + if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || (tag === 'BUTTON' && (e.code === 'Enter' || e.code === 'Space')) || e.repeat) return; + const st = state(), enter = e.code === 'Enter' || e.code === 'NumpadEnter'; + let act = null; + if (st === 'result' && e.code === 'KeyN' && performance.now() - resultAt >= 600) act = next; + else if (st === 'idle' && enter) act = again; + else if (st === 'paused' && enter) act = resume; + if (act) { e.preventDefault(); e.stopImmediatePropagation(); act(); } + }, true); + for (const id of ['#case', '#difficulty']) $(id).addEventListener('change', () => { shown = ''; canvas.focus(); }); + $('#seed').addEventListener('change', () => { shown = ''; }); // typing a seed: keep the focus in the box + requestAnimationFrame(tick); +})(); diff --git a/environments/games/web/games/nfsmw_remake/renderer3d.js b/environments/games/web/games/nfsmw_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..c850ea9f050d84dd863b669fe607e4c847a671fa --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/renderer3d.js @@ -0,0 +1,385 @@ +/* NFS Most Wanted events - WebGL renderer (three.js r160, vendored): third-person chase view of an original procedural city. + Everything is built from code at start-up: road ribbons from the route samples, barriers along the real collision edge of + the road union (what you see is what you hit), instanced buildings, palms, lamps, and original low-poly cars. A render is a + pure function of the game state; the only local randomness is a fixed-seed generator for scenery. No original game art. + 2026-11-08: police light bars on every live cop (roadblocks flash too), blinking barrier + lamps and spike-strip beacons, rival markers and rival nitrous flames, a light column over the next gate, glossy paint, + car head/tail light glows, street-lamp halos at night, sparks on impact, tyre smoke while sliding, camera shake on a hit, + the helicopter's spot on the ground. Particles are placed from the current state only (no history), so a frame is still a + pure function of the game state and the page, the recordings and the agent see the same picture. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.NfsmwGame, C = M && M.C; + if (!T || !M) return; + const R3 = M.R3 = {}, byCanvas = new WeakMap(); + const STYLE = { // sky top, sky mid, horizon, sun colour, sun [azimuth, elevation], hemisphere sky/ground/intensity, sun intensity, fog, window glow, lamp glow + tollbooth: { sky: ['#2a4f8c', '#e8926a', '#ffd9a0'], sun: 0xffc48a, dir: [-0.75, 0.18], hemi: [0xffe2c4, 0x51402f, 1.25], sunI: 2.6, fog: [0xefb48c, 240, 1300], win: 0.55, lamp: 0.5 }, + drag: { sky: ['#2f74c8', '#8fc3ea', '#e6f1f2'], sun: 0xfff4e0, dir: [0.4, 0.7], hemi: [0xdcebff, 0x8a8066, 1.5], sunI: 2.5, fog: [0xd6e6ee, 500, 2400], win: 0, lamp: 0 }, + speedtrap: { sky: ['#3c6fb4', '#a7c6dc', '#f4e6cf'], sun: 0xffedd0, dir: [0.7, 0.42], hemi: [0xe7eeff, 0x6f6a52, 1.4], sunI: 2.5, fog: [0xdfe2d8, 320, 1600], win: 0.05, lamp: 0 }, + knockout: { sky: ['#070b1e', '#17204a', '#5a3b66'], sun: 0x9fb4ff, dir: [0.3, 0.6], hemi: [0x5f6fa8, 0x201a26, 1.15], sunI: 0.75, fog: [0x2a2542, 90, 620], win: 1.5, lamp: 1.5 }, + pursuit: { sky: ['#141a44', '#7a3f73', '#ff9a62'], sun: 0xff9d73, dir: [-0.6, 0.08], hemi: [0xb09ac8, 0x2b2430, 1.15], sunI: 1.5, fog: [0x8a5a70, 170, 950], win: 1.15, lamp: 1.2 }, + street_champion: { sky: ['#222a3e', '#6e7a8c', '#d9cdb4'], sun: 0xffe2bc, dir: [0.8, 0.22], hemi: [0xc6d0dc, 0x4c4a44, 1.3], sunI: 1.6, fog: [0xaeb0ac, 170, 1000], win: 0.5, lamp: 0.6 }, + }; + const rngOf = seed => () => { seed = (seed + 0x6D2B79F5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; + const canvasTex = (w, h, paint, repeat, srgb = true) => { const c = document.createElement('canvas'); c.width = w; c.height = h; paint(c.getContext('2d'), w, h); const t = new T.CanvasTexture(c); if (repeat) t.wrapS = t.wrapT = T.RepeatWrapping; t.anisotropy = 4; if (srgb) t.colorSpace = T.SRGBColorSpace; return t; }; + const qv = (x, y, z, v) => (v || new T.Vector3()).set(x, z, -y); // sim (x, y, up) -> three (x, up, -y); heading h is rotation.y + const speckle = (q, w, h, n, a, seed) => { const r = rngOf(seed); for (let i = 0; i < n; i++) { const v = r() < 0.5 ? 255 : 0; q.fillStyle = `rgba(${v},${v},${v},${a * r()})`; q.fillRect(r() * w, r() * h, 1 + r() * 2, 1 + r() * 2); } }; + // Non-indexed merge with per-part vertex colours: every car is one draw call. + function merge(parts) { + let n = 0; const list = parts.map(([g, col]) => { const q = g.index ? g.toNonIndexed() : g; n += q.attributes.position.count; return [q, new T.Color(col)]; }); + const pos = new Float32Array(n * 3), nor = new Float32Array(n * 3), colr = new Float32Array(n * 3); let o = 0; + for (const [q, c] of list) { const m = q.attributes.position.count; pos.set(q.attributes.position.array, o * 3); nor.set(q.attributes.normal.array, o * 3); for (let i = 0; i < m; i++) { colr[(o + i) * 3] = c.r; colr[(o + i) * 3 + 1] = c.g; colr[(o + i) * 3 + 2] = c.b; } o += m; } + const g = new T.BufferGeometry(); g.setAttribute('position', new T.BufferAttribute(pos, 3)); g.setAttribute('normal', new T.BufferAttribute(nor, 3)); g.setAttribute('color', new T.BufferAttribute(colr, 3)); return g; + } + const moved = (g, x, y, z, rx = 0, ry = 0, rz = 0) => { const q = g.clone(); if (rx || ry || rz) q.rotateX(rx).rotateY(ry).rotateZ(rz); q.translate(x, y, z); q.computeVertexNormals(); return q; }; + const boxG = (x, y, z, w, h, d) => moved(new T.BoxGeometry(w, h, d), x, y, z); + // Side profile extruded across the car; +X is forward. L = length, W = width. `pts` run around the silhouette. + const profile = (pts, W) => { const s = new T.Shape(); pts.forEach((p, i) => i ? s.lineTo(p[0], p[1]) : s.moveTo(p[0], p[1])); const g = new T.ExtrudeGeometry(s, { depth: W, bevelEnabled: false, curveSegments: 1 }); g.translate(0, 0, -W / 2); g.computeVertexNormals(); return g; }; + const CAR_SHAPES = { + // Original wedge coupe, fastback sedan, tall van, police interceptor: silhouettes drawn for this project, no real vehicle. + coupe: { w: 1.86, body: [[-2.2, 0.34], [2.25, 0.3], [2.3, 0.56], [1.05, 0.82], [-1.9, 0.92], [-2.25, 0.86]], glass: [[0.82, 0.8], [0.05, 1.2], [-0.95, 1.2], [-1.75, 0.9]], wing: true }, + sedan: { w: 1.82, body: [[-2.3, 0.34], [2.25, 0.34], [2.3, 0.68], [1.0, 0.9], [-1.9, 0.96], [-2.32, 0.9]], glass: [[0.92, 0.88], [0.2, 1.38], [-1.2, 1.38], [-1.85, 0.94]] }, + van: { w: 1.95, body: [[-2.5, 0.38], [2.4, 0.38], [2.45, 0.9], [1.75, 1.08], [1.35, 1.9], [-2.5, 2.0]], glass: [[1.74, 1.06], [1.36, 1.72], [0.4, 1.76], [0.4, 1.06]] }, + cop: { w: 1.88, body: [[-2.35, 0.34], [2.35, 0.32], [2.4, 0.66], [1.05, 0.9], [-1.95, 0.96], [-2.35, 0.9]], glass: [[0.9, 0.88], [0.2, 1.34], [-1.15, 1.34], [-1.88, 0.94]] }, + }; + function carGeometry(kind) { + const S = CAR_SHAPES[kind], W = S.w, parts = [[profile(S.body, W), 0xffffff], [profile(S.glass, W - 0.14), 0x1c2733]]; + parts.push([boxG(0, 0.26, 0, 4.1, 0.14, W - 0.1), 0x15151a]); + for (const [x, z] of [[1.42, W / 2 - 0.12], [1.42, -W / 2 + 0.12], [-1.42, W / 2 - 0.12], [-1.42, -W / 2 + 0.12]]) { parts.push([moved(new T.CylinderGeometry(0.36, 0.36, 0.26, 12), x, 0.36, z, Math.PI / 2), 0x121215]); parts.push([moved(new T.CylinderGeometry(0.2, 0.2, 0.27, 8), x, 0.36, z, Math.PI / 2), 0xb9bdc4]); } + if (S.wing) { parts.push([boxG(-2.05, 1.14, 0, 0.42, 0.05, W - 0.1), 0xffffff]); parts.push([boxG(-2.05, 1.0, 0.62, 0.2, 0.26, 0.06), 0x24242a], [boxG(-2.05, 1.0, -0.62, 0.2, 0.26, 0.06), 0x24242a]); } + if (kind === 'cop') { parts.push([boxG(0.1, 0.66, W / 2 + 0.002, 1.7, 0.42, 0.01), 0xf4f4f4], [boxG(0.1, 0.66, -W / 2 - 0.002, 1.7, 0.42, 0.01), 0xf4f4f4]); parts.push([boxG(-0.45, 1.42, 0, 0.3, 0.1, 1.2), 0x22232a]); parts.push([boxG(2.42, 0.42, 0, 0.12, 0.34, W * 0.7), 0x18181c]); } + // 2026-11-08 details: side mirrors, a dark lower body line, front splitter, twin exhaust tips, number plate recess (original shapes) + if (kind !== 'van') { + const tip = new T.CylinderGeometry(0.07, 0.07, 0.16, 8); + parts.push([boxG(0.62, 0.86, W / 2 + 0.08, 0.16, 0.1, 0.16), 0x15151a], [boxG(0.62, 0.86, -W / 2 - 0.08, 0.16, 0.1, 0.16), 0x15151a]); + parts.push([boxG(0, 0.37, W / 2 - 0.02, 3.4, 0.1, 0.06), 0x202024], [boxG(0, 0.37, -W / 2 + 0.02, 3.4, 0.1, 0.06), 0x202024]); + parts.push([boxG(2.26, 0.3, 0, 0.18, 0.05, W - 0.2), 0x121214]); + parts.push([moved(tip, -2.3, 0.36, 0.42, 0, 0, Math.PI / 2), 0xc8ccd2], [moved(tip, -2.3, 0.36, -0.42, 0, 0, Math.PI / 2), 0xc8ccd2]); + parts.push([boxG(-2.26, 0.56, 0, 0.03, 0.14, 0.5), 0xe8e8e0]); + } + return merge(parts); + } + function lampGeometry(kind) { + const W = CAR_SHAPES[kind].w, x = kind === 'van' ? 2.42 : 2.3, y = kind === 'van' ? 0.72 : 0.5, b = kind === 'van' ? -2.52 : -2.3, by = kind === 'van' ? 0.95 : 0.74; + return merge([[boxG(x, y, W * 0.34, 0.06, 0.13, 0.4), 0xfff4d0], [boxG(x, y, -W * 0.34, 0.06, 0.13, 0.4), 0xfff4d0], [boxG(b, by, W * 0.32, 0.06, 0.12, 0.5), 0xff2614], [boxG(b, by, -W * 0.32, 0.06, 0.12, 0.5), 0xff2614]]); + } + const PAINT = [0x2c6fd1, 0xc33a2c, 0xd9d9d6, 0x1f2024, 0x4c8c5a, 0xd9a73a]; + class Scene { + constructor(canvas) { + this.canvas = canvas; this.res = []; this.times = []; this.ready = false; this.error = null; this.closed = false; this.pools = {}; this.skies = {}; + this.view = document.createElement('canvas'); this.view.width = 854; this.view.height = 480; + const r = this.renderer = new T.WebGLRenderer({ canvas: this.view, antialias: true, preserveDrawingBuffer: true, powerPreference: 'low-power' }); + r.setPixelRatio(1); r.setSize(854, 480, false); r.outputColorSpace = T.SRGBColorSpace; r.toneMapping = T.ACESFilmicToneMapping; r.toneMappingExposure = 1.0; + this.view.addEventListener('webglcontextlost', e => { e.preventDefault(); this.ready = false; this.error = 'WebGL context lost'; }); + this.world = new T.Scene(); this.world.fog = new T.Fog(0xffffff, 200, 1200); + this.camera = new T.PerspectiveCamera(58, 854 / 480, 0.5, 3200); + // Rear-view mirror: a second camera on the roof looking back, drawn into a strip at the top centre of the same frame. + // Shown only where something can come from behind (police events, rivals); MIRROR is that strip in canvas pixels. + this.mirrorCam = new T.PerspectiveCamera(50, 260 / 62, 0.5, 3200); this.mirrorRect = [297, 64, 557, 126]; this.mirrorOn = false; + this.hemi = new T.HemisphereLight(0xffffff, 0x444444, 1); this.world.add(this.hemi); + this.sun = new T.DirectionalLight(0xffffff, 2); this.world.add(this.sun); + this.buildSky(); this.buildGround(); this.buildRoads(); this.buildCity(); this.buildCars(); this.buildProps(); this.buildFx(); this.buildChevrons(); + } + keep(x) { this.res.push(x); return x; } + lam(o) { return this.keep(new T.MeshLambertMaterial(o)); } + paint(color) { return this.keep(new T.MeshPhongMaterial({ color, vertexColors: true, shininess: 60, specular: 0x4a4a4a })); } + basic(o) { return this.keep(new T.MeshBasicMaterial(o)); } + buildSky() { this.sky = new T.Mesh(this.keep(new T.SphereGeometry(2600, 20, 12)), this.basic({ side: T.BackSide, fog: false, depthWrite: false })); this.sky.renderOrder = -10; this.world.add(this.sky); } + skyTex(key) { + if (this.skies[key]) return this.skies[key]; + const st = STYLE[key], t = canvasTex(1024, 512, (q, w, h) => { + const g = q.createLinearGradient(0, 0, 0, h / 2); g.addColorStop(0, st.sky[0]); g.addColorStop(0.72, st.sky[1]); g.addColorStop(1, st.sky[2]); q.fillStyle = g; q.fillRect(0, 0, w, h); + const sx = ((Math.atan2(st.dir[0], Math.sqrt(1 - st.dir[0] * st.dir[0])) / (2 * Math.PI) + 1.0) % 1) * w, sy = h / 2 - st.dir[1] * h * 0.5, c = new T.Color(st.sun).getStyle(); + for (const ox of [-w, 0, w]) { const glow = q.createRadialGradient(sx + ox, sy, 2, sx + ox, sy, 170); glow.addColorStop(0, 'rgba(255,250,235,.95)'); glow.addColorStop(0.08, c.replace('rgb', 'rgba').replace(')', ',.65)')); glow.addColorStop(1, 'rgba(255,200,150,0)'); q.fillStyle = glow; q.fillRect(0, 0, w, h / 2); } + const rr = rngOf(key.length * 977 + 5); const nightly = st.win > 1; + if (nightly) for (let i = 0; i < 260; i++) { q.fillStyle = `rgba(255,255,255,${0.2 + rr() * 0.7})`; q.fillRect(rr() * w, rr() * h * 0.36, 1, 1); } + for (let i = 0; i < 44; i++) { const cx = rr() * w, cy = h * (0.2 + rr() * 0.26), cw = 40 + rr() * 150; q.fillStyle = nightly ? 'rgba(120,110,160,.08)' : 'rgba(255,240,226,.14)'; for (let j = 0; j < 7; j++) { q.beginPath(); q.ellipse(cx + (rr() - 0.5) * cw, cy + (rr() - 0.5) * 7, cw * (0.2 + rr() * 0.3), 3 + rr() * 6, 0, 0, 7); q.fill(); } } + for (const [base, amp, col] of [[0.5, 26, st.sky[1]], [0.502, 14, st.sky[0]]]) { q.fillStyle = col; q.globalAlpha = 0.55; q.beginPath(); q.moveTo(0, h); for (let x = 0; x <= w; x += 6) q.lineTo(x, h * base - amp * (0.55 + 0.45 * Math.sin(x * 0.012 + base * 40) * Math.sin(x * 0.031))); q.lineTo(w, h); q.fill(); q.globalAlpha = 1; } + q.fillStyle = st.sky[2]; q.fillRect(0, h / 2, w, h / 2); + }); + return (this.skies[key] = this.keep(t)); + } + buildGround() { + const grass = this.keep(canvasTex(256, 256, (q, w, h) => { q.fillStyle = '#6d7a52'; q.fillRect(0, 0, w, h); speckle(q, w, h, 3200, 0.16, 7); for (let i = 0; i < 12; i++) { q.fillStyle = 'rgba(120,108,70,.1)'; q.beginPath(); q.arc(i * 37 % w, i * 91 % h, 20 + i * 2, 0, 7); q.fill(); } }, true)); grass.repeat.set(70, 40); + const land = new T.Mesh(this.keep(new T.PlaneGeometry(3600, 1650)), this.lam({ map: grass })); land.rotation.x = -Math.PI / 2; qv(0, 280, -0.06, land.position); this.world.add(land); + const sand = new T.Mesh(this.keep(new T.PlaneGeometry(3600, 26)), this.lam({ color: 0xd8c394 })); sand.rotation.x = -Math.PI / 2; qv(0, -558, -0.05, sand.position); this.world.add(sand); + this.seaTex = this.keep(canvasTex(256, 256, (q, w, h) => { q.fillStyle = '#2d6f8f'; q.fillRect(0, 0, w, h); const r = rngOf(9); for (let i = 0; i < 240; i++) { q.fillStyle = `rgba(190,232,240,${0.04 + r() * 0.1})`; q.fillRect(r() * w, r() * h, 8 + r() * 34, 1); } }, true)); this.seaTex.repeat.set(26, 8); + const sea = new T.Mesh(this.keep(new T.PlaneGeometry(4400, 1700)), this.lam({ map: this.seaTex })); sea.rotation.x = -Math.PI / 2; qv(0, -1410, -1.4, sea.position); this.world.add(sea); + } + // A ribbon following samples [x, y]; `sides` gives the half width. v runs along the road in metres / tile length. + ribbon(pts, hw, closed, z, tile) { + const n = pts.length, N = closed ? n + 1 : n, pos = new Float32Array(N * 6), nor = new Float32Array(N * 6), uv = new Float32Array(N * 4), idx = []; let along = 0; + for (let i = 0; i < N; i++) { + const p = pts[i % n], a = pts[(i - 1 + n) % n], b = pts[(i + 1) % n], f = !closed && i === 0 ? p : a, t = !closed && i === n - 1 ? p : b, dx = t[0] - f[0], dy = t[1] - f[1], l = Math.hypot(dx, dy) || 1, nx = -dy / l, ny = dx / l; + if (i) along += Math.hypot(p[0] - pts[(i - 1) % n][0], p[1] - pts[(i - 1) % n][1]); + pos.set([p[0] + nx * hw, z, -(p[1] + ny * hw), p[0] - nx * hw, z, -(p[1] - ny * hw)], i * 6); nor.set([0, 1, 0, 0, 1, 0], i * 6); uv.set([0, along / tile, 1, along / tile], i * 4); + if (i < N - 1) idx.push(i * 2, i * 2 + 1, i * 2 + 2, i * 2 + 1, i * 2 + 3, i * 2 + 2); + } + const g = new T.BufferGeometry(); g.setAttribute('position', new T.BufferAttribute(pos, 3)); g.setAttribute('normal', new T.BufferAttribute(nor, 3)); g.setAttribute('uv', new T.BufferAttribute(uv, 2)); g.setIndex(idx); return this.keep(g); + } + buildRoads() { + const asphalt = (lanes, edge, yellow = true) => this.keep(canvasTex(256, 512, (q, w, h) => { + q.fillStyle = '#34363b'; q.fillRect(0, 0, w, h); speckle(q, w, h, 5200, 0.09, lanes * 13 + 1); + for (let i = 0; i < 3; i++) { q.fillStyle = 'rgba(16,16,18,.18)'; q.fillRect(w * (0.2 + i * 0.3), 0, 12, h); } + q.fillStyle = '#d8d6cc'; q.fillRect(edge, 0, 4, h); q.fillRect(w - edge - 4, 0, 4, h); + if (yellow) { q.fillStyle = '#d6a32e'; q.fillRect(w / 2 - 5, 0, 3, h); q.fillRect(w / 2 + 2, 0, 3, h); } else { q.fillStyle = '#d8d6cc'; for (let y = 0; y < h; y += 256) q.fillRect(w / 2 - 2, y, 4, 128); } + q.fillStyle = '#d8d6cc'; for (let k = 1; k < lanes; k++) { const u = (w / 2) * k / lanes; for (let y = 0; y < h; y += 256) { q.fillRect(w / 2 + u - 2, y, 4, 128); q.fillRect(w / 2 - u - 2, y, 4, 128); } } + }, true)); + const walkTex = this.keep(canvasTex(64, 64, (q, w, h) => { q.fillStyle = '#9d9a90'; q.fillRect(0, 0, w, h); speckle(q, w, h, 300, 0.1, 3); q.fillStyle = 'rgba(40,40,40,.28)'; q.fillRect(0, 0, w, 1); }, true)); + const walkMat = this.lam({ map: walkTex }), wallTex = this.keep(canvasTex(128, 32, (q, w, h) => { q.fillStyle = '#b7b4aa'; q.fillRect(0, 0, w, h); speckle(q, w, h, 300, 0.1, 21); q.fillStyle = 'rgba(30,30,32,.55)'; q.fillRect(0, h - 5, w, 5); for (let i = 0; i < 8; i++) { q.fillStyle = i % 2 ? '#c8452c' : '#e8e4da'; q.fillRect(i * 16, 2, 16, 6); } }, true)); + const wallMat = this.lam({ map: wallTex }), wallPos = [], wallUv = [], wallIdx = []; + const wall = (ax, ay, bx, by, len) => { const n = wallPos.length / 3, h = 1.05, low = -1.5; wallPos.push(ax, low, -ay, bx, low, -by, bx, h, -by, ax, h, -ay); wallUv.push(0, 0, len / 8, 0, len / 8, 1, 0, 1); wallIdx.push(n, n + 1, n + 2, n, n + 2, n + 3, n, n + 2, n + 1, n, n + 3, n + 2); }; + const edge = (pts, hw, closed) => { + for (let i = 0; i + (closed ? 0 : 1) < pts.length; i++) { + const p = pts[i], q = pts[(i + 1) % pts.length], dx = q[0] - p[0], dy = q[1] - p[1], l = Math.hypot(dx, dy) || 1, nx = -dy / l, ny = dx / l, mx = (p[0] + q[0]) / 2, my = (p[1] + q[1]) / 2; + for (const sgn of [1, -1]) if (C.road(mx + sgn * nx * (hw + 0.45), my + sgn * ny * (hw + 0.45)).d > 0.1) wall(p[0] + sgn * nx * hw, p[1] + sgn * ny * hw, q[0] + sgn * nx * hw, q[1] + sgn * ny * hw, l); + } + }; + for (const R of Object.values(C.routes)) { + const step = R.name === 'strip' ? 50 : 3, pts = []; for (let i = 0; i < R.n; i += step) pts.push([R.x[i], R.y[i]]); if (!R.loop) pts.push([R.x[R.n - 1], R.y[R.n - 1]]); + const tile = R.name === 'strip' ? 24 : 16, mesh = new T.Mesh(this.ribbon(pts, R.halfW, R.loop, R.name === 'downtown' ? 0.024 : 0.02, tile), this.lam({ map: asphalt(2, 9, R.name !== 'strip') })); this.world.add(mesh); + if (R.name !== 'strip') { const w = new T.Mesh(this.ribbon(pts, R.halfW + 4.5, R.loop, 0.006, 4), walkMat); this.world.add(w); } + edge(pts, R.halfW, R.loop); + } + const stMat = this.lam({ map: asphalt(1, 7) }); + for (const st of C.streets) { + const pts = []; for (let i = 0; i + 1 < st.length; i++) { const a = st[i], b = st[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]), m = Math.ceil(L / 6); for (let j = 0; j < m; j++) pts.push([a[0] + (b[0] - a[0]) * j / m, a[1] + (b[1] - a[1]) * j / m]); } pts.push(st[st.length - 1]); + this.world.add(new T.Mesh(this.ribbon(pts, C.streetW / 2, false, 0.012, 16), stMat)); this.world.add(new T.Mesh(this.ribbon(pts, C.streetW / 2 + 4, false, 0.004, 4), walkMat)); edge(pts, C.streetW / 2, false); + } + const g = new T.BufferGeometry(); g.setAttribute('position', new T.BufferAttribute(new Float32Array(wallPos), 3)); g.setAttribute('uv', new T.BufferAttribute(new Float32Array(wallUv), 2)); g.setIndex(wallIdx); g.computeVertexNormals(); this.keep(g); this.world.add(new T.Mesh(g, wallMat)); + } + buildCity() { + const r = rngOf(20051116), towers = { low: [], mid: [], tall: [] }, palms = [], lamps = []; + const facade = (cols, rows, lit, base) => { const paint = emit => (q, w, h) => { const rr = rngOf(cols * 31 + rows); q.fillStyle = emit ? '#000' : base; q.fillRect(0, 0, w, h); const cw = w / cols, ch = h / rows; for (let j = 0; j < rows; j++) for (let i = 0; i < cols; i++) { const on = rr() < lit; q.fillStyle = emit ? (on ? (rr() < 0.3 ? '#a8d8ff' : '#ffd48a') : '#000') : (on ? '#5a6878' : '#2c3644'); q.fillRect(i * cw + cw * 0.18, j * ch + ch * 0.2, cw * 0.64, ch * 0.6); } if (!emit) { q.fillStyle = '#3a3a3e'; q.fillRect(w - 8, 0, 8, 8); } else { q.fillStyle = '#000'; q.fillRect(w - 8, 0, 8, 8); } }; return this.lam({ map: this.keep(canvasTex(256, 256, paint(false))), emissive: 0xffffff, emissiveMap: this.keep(canvasTex(256, 256, paint(true))), emissiveIntensity: 1 }); }; + const X = C.bounds.X0, Y = C.bounds.Y0; + for (let y = -500; y < 960; y += 34) for (let x = -1320; x < 1320; x += 34) { + const px = x + (r() - 0.5) * 12, py = y + (r() - 0.5) * 12, w = 16 + r() * 16, d = 16 + r() * 16, gap = C.road(px, py).d - Math.hypot(w, d) / 2 - 4.5; if (gap < 0) continue; + if (C.road(px, py).d > 150) continue; + const down = Math.max(0, 1 - Math.hypot(px, py) / 480), h = 7 + r() * 10 + r() * r() * 90 * down + (r() < 0.04 ? 30 : 0); + (h < 16 ? towers.low : h < 36 ? towers.mid : towers.tall).push([px, py, w, h, d, r()]); + } + const box = new T.BoxGeometry(1, 1, 1); box.translate(0, 0.5, 0); const uv = box.attributes.uv; for (const i of [8, 9, 10, 11, 12, 13, 14, 15]) uv.setXY(i, 0.995, 0.995); this.keep(box); + this.mats = { win: [] }; const mk = (list, mat) => { const m = new T.InstancedMesh(box, mat, list.length), o = new T.Object3D(), c = new T.Color(); list.forEach((b, i) => { qv(b[0], b[1], 0, o.position); o.rotation.y = 0; o.scale.set(b[2], b[3], b[4]); o.updateMatrix(); m.setMatrixAt(i, o.matrix); c.setHSL(0.07 + b[5] * 0.1, 0.12 + b[5] * 0.18, 0.46 + b[5] * 0.34); m.setColorAt(i, c); }); this.world.add(m); this.mats.win.push(mat); this.keep(m); }; + mk(towers.low, facade(4, 3, 0.45, '#b9ad98')); mk(towers.mid, facade(6, 8, 0.4, '#a8a39a')); mk(towers.tall, facade(8, 22, 0.42, '#8f9aa8')); + const R = C.routes.coast; + for (let i = 0; i < R.n; i += 9) { const a = C.routeAt(R, i * R.ds), side = i % 18 ? 1 : -1, off = R.halfW + 2.6; const lx = a.x + a.nx * side * off, ly = a.y + a.ny * side * off; if (C.road(lx, ly).d > 0.6) (a.y < -300 || a.x > 700 ? palms : lamps).push([lx, ly, side * a.h]); } + for (const key of ['downtown']) { const D = C.routes[key]; for (let i = 0; i < D.n; i += 12) { const a = C.routeAt(D, i * D.ds), off = D.halfW + 2.2; for (const s of [1, -1]) { const lx = a.x + a.nx * s * off, ly = a.y + a.ny * s * off; if (C.road(lx, ly).d > 0.6) lamps.push([lx, ly, 0]); } } } + const inst = (geo, mat, list, sy = 1) => { const m = new T.InstancedMesh(this.keep(geo), mat, list.length), o = new T.Object3D(); list.forEach((p, i) => { qv(p[0], p[1], 0, o.position); o.rotation.y = p[2] || 0; const k = 0.85 + ((i * 7) % 5) * 0.08; o.scale.set(k, k * sy, k); o.updateMatrix(); m.setMatrixAt(i, o.matrix); }); this.world.add(this.keep(m)); return m; }; + const trunk = new T.CylinderGeometry(0.16, 0.3, 9, 6); trunk.translate(0, 4.5, 0); inst(trunk, this.lam({ color: 0x705a40 }), palms); + const fronds = []; for (let k = 0; k < 7; k++) { const g = new T.ConeGeometry(0.62, 4.6, 4); g.translate(0, 2.3, 0); g.rotateZ(-1.9); g.rotateY(k * Math.PI * 2 / 7); g.translate(0, 9, 0); fronds.push(g); } inst(merge(fronds.map(g => [g, 0xffffff])), this.lam({ color: 0x4a7a3c, vertexColors: true }), palms); + const pole = new T.CylinderGeometry(0.07, 0.1, 7.5, 5); pole.translate(0, 3.75, 0); inst(pole, this.lam({ color: 0x45484e }), lamps); + const head = new T.BoxGeometry(0.5, 0.12, 0.28); head.translate(0, 7.5, 0); this.lampMat = this.basic({ color: 0xffdca0 }); inst(head, this.lampMat, lamps); this.lampSpots = lamps; + const haloTex = this.keep(canvasTex(64, 64, (q, w, h) => { const g = q.createRadialGradient(32, 32, 1, 32, 32, 32); g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.4, 'rgba(255,255,255,.28)'); g.addColorStop(1, 'rgba(255,255,255,0)'); q.fillStyle = g; q.fillRect(0, 0, w, h); })); this.haloTex = haloTex; + } + buildCars() { + this.carGeo = {}; this.lampGeo = {}; for (const k of Object.keys(CAR_SHAPES)) { this.carGeo[k] = this.keep(carGeometry(k)); this.lampGeo[k] = this.keep(lampGeometry(k)); } + this.lampMatCar = this.basic({ vertexColors: true }); + this.shadowTex = this.keep(canvasTex(64, 64, (q, w, h) => { const g = q.createRadialGradient(32, 32, 6, 32, 32, 32); g.addColorStop(0, 'rgba(0,0,0,.62)'); g.addColorStop(0.7, 'rgba(0,0,0,.38)'); g.addColorStop(1, 'rgba(0,0,0,0)'); q.fillStyle = g; q.fillRect(0, 0, w, h); })); + this.shadowMat = this.basic({ map: this.shadowTex, transparent: true, depthWrite: false }); this.shadowGeo = this.keep(new T.PlaneGeometry(5.6, 2.9)); this.shadowGeo.rotateX(-Math.PI / 2); + this.paints = PAINT.map(c => this.paint(c)); + this.playerMat = this.paint(0xe8701f); this.rivalMat = this.paint(0xc8cdd8); this.copMat = this.paint(0x17181d); + // Police light bar: two lamps per cop, swapped between a lit and a dark material every 8 ticks (red and blue out of phase). + this.barMat = { r1: this.basic({ color: 0xff2a3a }), r0: this.basic({ color: 0x3a0c10 }), b1: this.basic({ color: 0x3a78ff }), b0: this.basic({ color: 0x0c1438 }) }; + this.barGeo = this.keep(new T.BoxGeometry(0.34, 0.13, 0.52)); + this.halo = col => this.keep(new T.SpriteMaterial({ map: this.haloTex, color: col, blending: T.AdditiveBlending, depthWrite: false, transparent: true, fog: false })); + this.player = this.spawnCar('coupe', this.playerMat); + const flame = this.basic({ color: 0x7fc4ff, transparent: true, opacity: 0.85, blending: T.AdditiveBlending, depthWrite: false }); const cone = new T.ConeGeometry(0.13, 1.1, 8); cone.rotateZ(Math.PI / 2); this.keep(cone); this.flames = [0.45, -0.45].map(z => { const m = new T.Mesh(cone, flame); m.position.set(-2.82, 0.55, z); m.visible = false; this.player.add(m); return m; }); + const brk = this.basic({ color: 0xff3020 }); this.brake = new T.Mesh(this.keep(new T.BoxGeometry(0.03, 0.09, 1.5)), brk); this.brake.position.set(-2.34, 0.76, 0); this.player.add(this.brake); + } + spawnCar(kind, mat) { + const g = new T.Group(); g.add(new T.Mesh(this.carGeo[kind], mat)); g.add(new T.Mesh(this.lampGeo[kind], this.lampMatCar)); const s = new T.Mesh(this.shadowGeo, this.shadowMat); s.position.y = 0.05; g.add(s); + if (kind === 'cop') { const r = new T.Mesh(this.barGeo, this.barMat.r1), b = new T.Mesh(this.barGeo, this.barMat.b0); r.position.set(-0.45, 1.5, 0.3); b.position.set(-0.45, 1.5, -0.3); g.add(r, b); g.userData.bar = [r, b]; } + this.world.add(g); return g; + } + pool(name, make) { return this.pools[name] || (this.pools[name] = { list: [], make, used: 0 }); } + take(p) { if (p.used === p.list.length) p.list.push(p.make()); const o = p.list[p.used++]; o.visible = true; return o; } + buildProps() { + const steel = this.lam({ color: 0x585c63 }), glow = this.basic({ color: 0x7dff9a }), red = this.basic({ color: 0xff4632 }), amber = this.basic({ color: 0xffb037 }); + const col = this.keep(new T.BoxGeometry(0.7, 8, 0.7)); col.translate(0, 4, 0); const beam = this.keep(new T.BoxGeometry(0.9, 0.9, 1)), strip = this.keep(new T.BoxGeometry(0.2, 0.5, 1)), cone = this.keep(new T.ConeGeometry(0.35, 0.9, 8)), rail = this.keep(new T.BoxGeometry(0.5, 0.9, 3)), spike = this.keep(new T.BoxGeometry(0.9, 0.1, 1)), tooth = this.keep(new T.ConeGeometry(0.1, 0.34, 4)); + this.gateMake = kind => { const g = new T.Group(), hw = 10; const a = new T.Mesh(col, steel); a.position.z = hw; const b = new T.Mesh(col, steel); b.position.z = -hw; const top = new T.Mesh(beam, steel); top.position.y = 8; top.scale.z = hw * 2 + 0.7; const bar = new T.Mesh(strip, glow); bar.position.set(-0.55, 8, 0); bar.scale.z = hw * 2 - 1; g.add(a, b, top, bar); g.userData.bar = bar; this.world.add(g); return g; }; + this.redDark = this.basic({ color: 0x401010 }); + this.barrierMake = () => { const g = new T.Group(); const m = new T.Mesh(rail, this.lam({ color: 0xe8d030 })); m.position.y = 0.45; g.add(m); const l = new T.Mesh(this.keep(new T.BoxGeometry(0.1, 0.15, 2.6)), red); l.position.set(0.28, 0.75, 0); g.add(l); g.userData.lamp = l; g.userData.red = red; this.world.add(g); return g; }; + const hazard = this.keep(canvasTex(64, 16, (q, w, h) => { q.fillStyle = '#e8c020'; q.fillRect(0, 0, w, h); q.fillStyle = '#18181a'; for (let x = -16; x < w; x += 16) { q.beginPath(); q.moveTo(x, h); q.lineTo(x + 8, 0); q.lineTo(x + 16, 0); q.lineTo(x + 8, h); q.fill(); } }, true)); + this.spikeMake = () => { const g = new T.Group(); const m = new T.Mesh(spike, this.lam({ map: hazard })); m.position.y = 0.06; g.add(m); g.userData.base = m; const teeth = new T.InstancedMesh(tooth, this.lam({ color: 0xe8ecf2, emissive: 0x303438 }), 16); g.add(teeth); g.userData.teeth = teeth; this.keep(teeth); this.world.add(g); return g; }; + this.haloMake = () => { const s = new T.Sprite(this.halo(0xffffff)); this.world.add(s); return s; }; + this.coneMake = () => { const m = new T.Mesh(cone, this.lam({ color: 0xff7a1e })); this.world.add(m); return m; }; + this.lightAmber = amber; + } + // ---- effects: three point clouds rebuilt per frame (one draw call each), sprites for markers, a beacon, light pools ---- + buildFx() { + const pts = (n, size, blending, opacity) => { const g = this.keep(new T.BufferGeometry()); g.setAttribute('position', new T.BufferAttribute(new Float32Array(n * 3), 3)); g.setAttribute('color', new T.BufferAttribute(new Float32Array(n * 3), 3)); g.setDrawRange(0, 0); const m = new T.Points(g, this.keep(new T.PointsMaterial({ size, map: this.haloTex, vertexColors: true, transparent: true, opacity, depthWrite: false, blending, fog: false }))); m.frustumCulled = false; m.renderOrder = 5; this.world.add(m); return { m, g, n, used: 0 }; }; + this.glow = pts(260, 1.5, T.AdditiveBlending, 1); this.spark = pts(80, 0.42, T.AdditiveBlending, 1); this.smoke = pts(60, 3.2, T.NormalBlending, 0.38); + const lamps = this.lampSpots || []; this.lampHalo = pts(lamps.length, 3.6, T.AdditiveBlending, 0.55); for (const l of lamps) this.pushPt(this.lampHalo, l[0], l[1], 7.35, 1, 0.82, 0.55); this.flushPts(this.lampHalo); + // rival marker: a downward chevron, constant size on screen + const chev = this.keep(canvasTex(64, 64, (q, w, h) => { q.fillStyle = 'rgba(0,0,0,.55)'; q.beginPath(); q.moveTo(6, 10); q.lineTo(58, 10); q.lineTo(32, 56); q.closePath(); q.fill(); q.fillStyle = '#ffffff'; q.beginPath(); q.moveTo(12, 14); q.lineTo(52, 14); q.lineTo(32, 48); q.closePath(); q.fill(); })); + this.markerMake = () => { const sp = new T.Sprite(this.keep(new T.SpriteMaterial({ map: chev, sizeAttenuation: false, depthWrite: false, transparent: true, fog: false }))); sp.scale.set(0.045, 0.045, 1); sp.renderOrder = 6; this.world.add(sp); return sp; }; + // next-gate beacon: a tall additive column that rises above the roofs + const beamTex = this.keep(canvasTex(8, 128, (q, w, h) => { const g = q.createLinearGradient(0, 0, 0, h); g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.5, 'rgba(255,255,255,.55)'); g.addColorStop(1, 'rgba(255,255,255,.9)'); q.fillStyle = g; q.fillRect(0, 0, w, h); })); + this.beaconMake = () => { const m = new T.Mesh(this.keep(new T.CylinderGeometry(1.1, 1.1, 70, 10, 1, true)), this.keep(new T.MeshBasicMaterial({ map: beamTex, color: 0x7dff9a, transparent: true, opacity: 0.5, depthWrite: false, side: T.DoubleSide, fog: false }))); m.position.y = 35; const g = new T.Group(); g.add(m); g.userData.beam = m; this.world.add(g); return g; }; + // rival nitrous flame + const cone = this.keep(new T.ConeGeometry(0.13, 1.1, 8)); cone.rotateZ(Math.PI / 2); const flame = this.basic({ color: 0x7fc4ff, transparent: true, opacity: 0.85, blending: T.AdditiveBlending, depthWrite: false }); + this.rflameMake = () => { const g = new T.Group(); for (const z of [0.45, -0.45]) { const m = new T.Mesh(cone, flame); m.position.set(-2.82, 0.55, z); g.add(m); } this.world.add(g); return g; }; + // light pools on the road: player headlights at night, the helicopter's searchlight + const pool = this.keep(canvasTex(64, 64, (q, w, h) => { const g = q.createRadialGradient(32, 32, 2, 32, 32, 32); g.addColorStop(0, 'rgba(255,255,255,.75)'); g.addColorStop(1, 'rgba(255,255,255,0)'); q.fillStyle = g; q.fillRect(0, 0, w, h); })); + const quad = this.keep(new T.PlaneGeometry(1, 1)); quad.rotateX(-Math.PI / 2); + this.headPool = new T.Mesh(quad, this.keep(new T.MeshBasicMaterial({ map: pool, color: 0xfff0c8, transparent: true, opacity: 0.28, blending: T.AdditiveBlending, depthWrite: false }))); this.headPool.scale.set(12, 1, 22); this.headPool.visible = false; this.world.add(this.headPool); + this.heliSpot = new T.Mesh(quad, this.keep(new T.MeshBasicMaterial({ map: pool, color: 0xd8e8ff, transparent: true, opacity: 0.7, blending: T.AdditiveBlending, depthWrite: false }))); this.heliSpot.scale.set(18, 1, 18); this.heliSpot.visible = false; this.world.add(this.heliSpot); + } + pushPt(p, x, y, z, r, g, b) { if (p.used >= p.n) return; const i = p.used++; const a = p.g.attributes.position.array, c = p.g.attributes.color.array; a[i * 3] = x; a[i * 3 + 1] = z; a[i * 3 + 2] = -y; c[i * 3] = r; c[i * 3 + 1] = g; c[i * 3 + 2] = b; } + flushPts(p) { p.g.setDrawRange(0, p.used); p.g.attributes.position.needsUpdate = true; p.g.attributes.color.needsUpdate = true; } + // head and tail lights of one car in world space; night sets how strong the headlights read + carLights(x, y, h, kind, braking, night) { + const ch = Math.cos(h), sh = Math.sin(h), W = CAR_SHAPES[kind].w * 0.34, f = kind === 'van' ? 2.5 : 2.36, b = kind === 'van' ? -2.56 : -2.36, fy = kind === 'van' ? 0.72 : 0.5, by = kind === 'van' ? 0.95 : 0.74; + for (const s of [1, -1]) { + const lx = -sh * W * s, ly = ch * W * s; + if (night > 0) this.pushPt(this.glow, x + ch * f + lx, y + sh * f + ly, fy, night, night * 0.94, night * 0.78); + const k = braking ? 1 : 0.42; this.pushPt(this.glow, x + ch * b + lx, y + sh * b + ly, by, k, k * 0.1, k * 0.06); + } + } + drawFx(g, st) { + const night = st.lamp > 0 ? Math.min(1, 0.45 + st.lamp * 0.35) : 0.18, c = g.car, sp = C.speed(c), t = g.t; + this.glow.used = 0; this.spark.used = 0; this.smoke.used = 0; + this.carLights(c.x, c.y, c.h, 'coupe', g.heldBrake || sp < 0.5, night); + for (const o of g.traffic) this.carLights(o.x, o.y, o.h, o.paint % 6 === 3 ? 'van' : 'sedan', o.crash, night * 0.8); + for (const r of g.rivals) if (!r.gone) this.carLights(r.x, r.y, r.h, 'coupe', 0, night * 0.9); + for (const k of g.cops) if (!k.gone) this.carLights(k.x, k.y, k.h, 'cop', k.state === 'rb', k.dead ? 0 : night * 0.9); + for (const k of g.cops) if (k.dead && !k.gone) for (let i = 0; i < 5; i++) { const gr = 0.2 + i * 0.05; this.pushPt(this.smoke, k.x + Math.sin(i * 2.1 + t * 0.05) * 0.5, k.y + Math.cos(i * 1.7 + t * 0.04) * 0.5, 1.2 + i * 0.9 + ((t * 0.04 + i * 0.3) % 1), gr, gr, gr); } + // nitrous glow behind the player's exhausts + if (c.nosOn) { const ch = Math.cos(c.h), sh = Math.sin(c.h); for (let i = 1; i <= 4; i++) this.pushPt(this.glow, c.x - ch * (2.6 + i * 0.55), c.y - sh * (2.6 + i * 0.55), 0.55, 0.35, 0.6, 1); } + // sparks: a hit sets lastHit (0.25-0.4 s); 14 sparks thrown from the front corners along fixed pseudo-random paths + if (g.lastHit > 0) { + const age = 0.4 - g.lastHit, ch = Math.cos(c.h), sh = Math.sin(c.h); + for (let i = 0; i < 14; i++) { const u = Math.sin(i * 12.9898 + (t >> 4) * 78.233) * 43758.5453, r1 = u - Math.floor(u), r2 = (u * 7.13) - Math.floor(u * 7.13), side = i % 2 ? 1 : -1, sx = 2.1, sy = side * 0.9, a = c.h + side * (0.6 + r1 * 1.2) + Math.PI * (r2 < 0.3 ? 1 : 0), v = 6 + r2 * 9, d = v * age; + this.pushPt(this.spark, c.x + ch * sx - sh * sy + Math.cos(a) * d, c.y + sh * sx + ch * sy + Math.sin(a) * d, 0.4 + 3 * age - 9 * age * age + r1 * 0.3, 1, 0.75 + r2 * 0.25, 0.3); } + } + // tyre smoke while the rear slides (carStep drift); puffs trail back along the velocity + if (c.drift && sp > 4) { const vx = c.vx / sp, vy = c.vy / sp, ch = Math.cos(c.h), sh = Math.sin(c.h); for (let i = 0; i < 8; i++) for (const s of [1, -1]) { const back = 1.4 + i * 1.1, lx = -sh * 0.8 * s, ly = ch * 0.8 * s, gr = 0.62 + i * 0.03; this.pushPt(this.smoke, c.x - ch * 1.4 + lx - vx * back, c.y - sh * 1.4 + ly - vy * back, 0.5 + i * 0.12, gr, gr, gr); } } + this.flushPts(this.glow); this.flushPts(this.spark); this.flushPts(this.smoke); + this.lampHalo.m.visible = st.lamp > 0; + this.headPool.visible = st.lamp > 0; if (this.headPool.visible) { qv(c.x + Math.cos(c.h) * 9, c.y + Math.sin(c.h) * 9, 0.05, this.headPool.position); this.headPool.rotation.y = c.h; } + const hl = g.heli; this.heliSpot.visible = !!(hl && !hl.gone && hl.sees); if (this.heliSpot.visible) qv(c.x + (hl.x - c.x) * 0.15, c.y + (hl.y - c.y) * 0.15, 0.06, this.heliSpot.position); + } + // Corner boards: a red board with white chevrons on the outside wall of every corner tighter than 90 m, one every 9 m of arc, + // facing the car that is about to turn. They are what shows where the road goes when the road itself is behind a building. + buildChevrons() { + const tex = dir => this.keep(canvasTex(128, 64, (q, w, h) => { q.fillStyle = '#c8261c'; q.fillRect(0, 0, w, h); q.fillStyle = '#ffffff'; q.fillRect(0, 0, w, 4); q.fillRect(0, h - 4, w, 4); + for (let i = 0; i < 3; i++) { const x0 = 18 + i * 34; q.beginPath(); if (dir < 0) { q.moveTo(x0 + 20, 10); q.lineTo(x0, h / 2); q.lineTo(x0 + 20, h - 10); q.lineTo(x0 + 30, h - 10); q.lineTo(x0 + 10, h / 2); q.lineTo(x0 + 30, 10); } else { q.moveTo(x0, 10); q.lineTo(x0 + 20, h / 2); q.lineTo(x0, h - 10); q.lineTo(x0 + 10, h - 10); q.lineTo(x0 + 30, h / 2); q.lineTo(x0 + 10, 10); } q.closePath(); q.fill(); } })); + const geo = this.keep(new T.PlaneGeometry(2.6, 1.3)); geo.translate(0, 2.0, 0); + const post = this.keep(new T.BoxGeometry(0.12, 1.4, 0.12)); post.translate(0, 0.7, 0); + const lists = { left: [], right: [] }; this.chevrons = []; + for (const R of [C.routes.coast, C.routes.downtown]) { + for (let i = 0; i < R.n; i += Math.max(1, Math.round(9 / R.ds))) { + const k = R.k[i]; if (Math.abs(k) < 1 / 90) continue; + const a = C.routeAt(R, i * R.ds), out = k > 0 ? -1 : 1, lat = out * (R.halfW + 0.7), x = a.x + a.nx * lat, y = a.y + a.ny * lat; + if (C.road(x, y).d < 0.1) continue; // another road joins here: no wall, no board + (k > 0 ? lists.left : lists.right).push([x, y, a.h]); this.chevrons.push({ x, y, s: i * R.ds, route: R.name }); + } + } + const o = new T.Object3D(); + for (const [side, list] of Object.entries(lists)) { + if (!list.length) continue; + const board = new T.InstancedMesh(geo, this.basic({ map: tex(side === 'left' ? -1 : 1), side: T.DoubleSide }), list.length), legs = new T.InstancedMesh(post, this.lam({ color: 0x3a3c40 }), list.length); + list.forEach((p, j) => { qv(p[0], p[1], 0, o.position); o.rotation.set(0, p[2] - Math.PI / 2, 0); o.updateMatrix(); board.setMatrixAt(j, o.matrix); legs.setMatrixAt(j, o.matrix); }); + this.world.add(this.keep(board), this.keep(legs)); + } + } + // Screen position of a sim point with the frame's camera: {x, y} in canvas pixels, front = in front of the camera. + project(x, y, z) { const v = qv(x, y, z, this.tmpV || (this.tmpV = new T.Vector3())); v.applyMatrix4(this.camera.matrixWorldInverse); const front = v.z < -0.3; qv(x, y, z, v).project(this.camera); return { x: (v.x * 0.5 + 0.5) * 854, y: (-v.y * 0.5 + 0.5) * 480, front }; } + breakerMake() { const g = new T.Group(), steel = this.lam({ color: 0x8a5a30 }), red = this.basic({ color: 0xff5a2a }); for (const [x, z] of [[-1.8, -1.8], [1.8, -1.8], [-1.8, 1.8], [1.8, 1.8]]) { const m = new T.Mesh(this.keep(new T.BoxGeometry(0.4, 9, 0.4)), steel); m.position.set(x, 4.5, z); g.add(m); } const top = new T.Mesh(this.keep(new T.BoxGeometry(5, 1.6, 5)), steel); top.position.y = 9.5; g.add(top); const sign = new T.Mesh(this.keep(new T.BoxGeometry(5.2, 0.5, 5.2)), red); sign.position.y = 8.5; g.add(sign); this.world.add(g); return g; } + // ---------------- per-frame ---------------- + placeCar(o, x, y, h, lift = 0) { qv(x, y, lift, o.position); o.rotation.y = h; } + drawProps(g) { + for (const p of Object.values(this.pools)) { for (const o of p.list) o.visible = false; p.used = 0; } + const R = g.route; + const blink = (g.t >> 3) % 2 === 0, nextGate = (g.gates || []).find(q => !q.done); + if (nextGate && !g.outcome) { const gs = nextGate.s !== undefined ? nextGate.s : g.s0 + nextGate.at, ds = R.loop && M.wrapTo ? M.wrapTo(R, gs, g.s) - g.s : gs - g.s; if (ds > 12 && ds < 900) { const a = C.routeAt(R, g.s + ds), o = this.take(this.pool('beacon', () => this.beaconMake())); this.placeCar(o, a.x, a.y, a.h); o.userData.beam.material.color.setHex(nextGate.kind === 'trap' ? 0xffb037 : nextGate.kind === 'line' ? 0xffffff : 0x7dff9a); } } + for (const gate of g.gates || []) { + const a = C.routeAt(R, (gate.s !== undefined ? gate.s : g.s0 + gate.at)); if (gate.done && !gate.keep) continue; + const o = this.take(this.pool(gate.kind === 'trap' ? 'gateT' : 'gate', () => this.gateMake(gate.kind === 'trap' ? 'trap' : 'toll'))); + this.placeCar(o, a.x, a.y, a.h); const bar = o.userData.bar; bar.material.color.setHex(gate.kind === 'trap' ? (g.flashT > 0 ? 0xffffff : 0xffb037) : (gate.next ? 0x7dff9a : 0x7dff9a)); + } + for (const t of g.traffic) { const o = this.take(this.pool('tr' + (t.paint % 6), () => this.spawnCar(t.paint % 6 === 3 ? 'van' : 'sedan', this.paints[t.paint % 6]))); this.placeCar(o, t.x, t.y, t.h); } + for (const r of g.rivals) { + if (r.gone) continue; const o = this.take(this.pool('rv' + (r.paint || 0), () => this.spawnCar('coupe', this.paint([0x9fb0c8, 0xb0242c, 0x28402c, 0x4b3d84][(r.paint || 0) % 4])))); this.placeCar(o, r.x, r.y, r.h); + // marker: the champion red, every other rival white; nitrous flames while its boost runs (rivals.js nosT / trapNos) + const mk = this.take(this.pool('marker', () => this.markerMake())); qv(r.x, r.y, 2.5, mk.position); mk.material.color.setHex(r.name === 'champion' ? 0xff4a3a : 0xffffff); + if ((r.nosT > 0 || r.trapNos > 0) && r.nos > 0.02 && !r.out) { const f = this.take(this.pool('rflame', () => this.rflameMake())); this.placeCar(f, r.x, r.y, r.h); f.scale.set(1 + ((g.t * 7) % 3) * 0.2, 1, 1); } + } + for (const c of g.cops) { + if (c.gone) continue; const o = this.take(this.pool('cop', () => this.spawnCar('cop', this.copMat))); this.placeCar(o, c.x, c.y, c.h); + const live = !c.dead, ph = (c.slot || 0) % 2 ? !blink : blink, bar = o.userData.bar; bar[0].material = live && ph ? this.barMat.r1 : this.barMat.r0; bar[1].material = live && !ph ? this.barMat.b1 : this.barMat.b0; + if (live) { const s = this.take(this.pool('halo', () => this.haloMake())); qv(c.x, c.y, 1.7, s.position); s.scale.setScalar(c.state === 'rb' ? 6 : 4.4); s.material.color.setHex(ph ? 0xff2a3a : 0x3a70ff); } + } + for (const b of g.breakers || []) { if (b.rearm > 0) continue; const o = this.take(this.pool('breaker', () => this.breakerMake())); this.placeCar(o, b.x, b.y, b.h); } + for (const p of g.props) { + if (p.gone) continue; const a = { x: p.x, y: p.y, h: p.h || 0 }; + if (p.type === 'spike') { const o = this.take(this.pool('spike', () => this.spikeMake())), L = p.len || 14; this.placeCar(o, a.x, a.y, a.h); o.userData.base.scale.z = L; const t = o.userData.teeth, m = new T.Object3D(); for (let i = 0; i < 16; i++) { m.position.set((i % 2) * 0.3 - 0.15, 0.2, (i / 15 - 0.5) * L); m.updateMatrix(); t.setMatrixAt(i, m.matrix); } t.instanceMatrix.needsUpdate = true; + if (!p.used) for (const e of [-1, 1]) { const b = this.take(this.pool('halo', () => this.haloMake())), ex = a.x - Math.sin(a.h) * e * (L / 2 + 0.6), ey = a.y + Math.cos(a.h) * e * (L / 2 + 0.6); qv(ex, ey, 0.5, b.position); b.scale.setScalar(blink ? 3.4 : 1.6); b.material.color.setHex(0xffb020); } } + else if (p.type === 'barrier') { const o = this.take(this.pool('barrier', () => this.barrierMake())); this.placeCar(o, a.x, a.y, a.h, p.lift || 0); o.rotation.x = p.spin || 0; o.userData.lamp.material = blink ? o.userData.red : this.redDark; } + else if (p.type === 'cone') { const o = this.take(this.pool('cone', () => this.coneMake())); qv(a.x, a.y, 0.45, o.position); } + } + } + render(g, ctx) { + if (this.closed || this.renderer.getContext().isContextLost()) { this.ready = false; this.error = this.closed ? '3D renderer is closed' : 'WebGL context lost'; throw Error(this.error); } + const t0 = performance.now(); + try { + const key = g.key, st = STYLE[key] || STYLE.tollbooth, c = g.car; + if (this.key !== key) { + this.key = key; this.world.fog.color.setHex(st.fog[0]); this.world.fog.near = st.fog[1]; this.world.fog.far = st.fog[2]; + this.hemi.color.setHex(st.hemi[0]); this.hemi.groundColor.setHex(st.hemi[1]); this.hemi.intensity = st.hemi[2]; this.sun.color.setHex(st.sun); this.sun.intensity = st.sunI; + this.sun.position.set(st.dir[0], Math.max(0.12, st.dir[1]) + 0.25, -0.5); this.sky.material.map = this.skyTex(key); this.sky.material.needsUpdate = true; + for (const m of this.mats.win) m.emissiveIntensity = st.win; this.lampMat.color.setHex(st.lamp > 0 ? 0xffdca0 : 0x77767a); + } + this.seaTex.offset.x = g.t * 0.0006; this.seaTex.offset.y = g.t * 0.0003; + this.placeCar(this.player, c.x, c.y, c.h); const sp = C.speed(c); + // Body motion: roll outward in a turn (local +X is forward, so YXZ order makes x roll and z pitch), nose dive under braking. + // (Before 2026-11-08 this set rotation.z from the steering, which pitched the nose instead of rolling the body.) + this.player.rotation.order = 'YXZ'; this.player.rotation.x = C.clamp(c.r * sp * 0.006, -0.07, 0.07); this.player.rotation.z = g.heldBrake && sp > 3 ? -0.022 : c.nosOn ? 0.012 : 0; + this.flames.forEach(f => { f.visible = !!c.nosOn; f.scale.set(1 + ((g.t * 7) % 3) * 0.2, 1, 1); }); + this.brake.visible = g.heldBrake || sp < 0.5; + this.drawProps(g); this.drawHeli(g); this.drawFx(g, st); + const yaw = g.camH === undefined ? c.h : g.camH, back = 6.6 + Math.min(1.8, sp * 0.022), up = 2.45 + Math.min(0.5, sp * 0.006); + qv(c.x - Math.cos(yaw) * back, c.y - Math.sin(yaw) * back, up, this.camera.position); + const hit = Math.max(0, g.lastHit || 0), shake = (c.nosOn ? 0.03 * Math.sin(g.t * 1.7) : 0) + hit * 0.5 * Math.sin(g.t * 2.9); + if (hit > 0) { this.camera.position.x += hit * 0.35 * Math.sin(g.t * 3.7); this.camera.position.y += hit * 0.25 * Math.cos(g.t * 4.3); } + this.camera.lookAt(qv(c.x + Math.cos(yaw) * 7, c.y + Math.sin(yaw) * 7, 1.15 + shake)); + this.camera.fov = 58 + Math.min(16, sp * 0.2) + (c.nosOn ? 4 : 0) - (g.sb ? 5 : 0); this.camera.updateProjectionMatrix(); + this.sky.position.copy(this.camera.position); + this.renderer.setScissorTest(false); this.renderer.setViewport(0, 0, 854, 480); + this.renderer.render(this.world, this.camera); + this.mirrorOn = !!(g.cops.length || g.rivals.length || g.pol); + if (this.mirrorOn) { + const [x0, y0, x1, y1] = this.mirrorRect, mh = c.h; + qv(c.x + Math.cos(mh) * 0.4, c.y + Math.sin(mh) * 0.4, 1.75, this.mirrorCam.position); + this.mirrorCam.lookAt(qv(c.x - Math.cos(mh) * 30, c.y - Math.sin(mh) * 30, 0.9)); + this.mirrorCam.updateMatrixWorld(); this.sky.position.copy(this.mirrorCam.position); + const vy = 480 - y1; this.renderer.setViewport(x0, vy, x1 - x0, y1 - y0); this.renderer.setScissor(x0, vy, x1 - x0, y1 - y0); this.renderer.setScissorTest(true); + // the player's own car, its light glows and the particles sit right in front of the mirror camera: hidden for this pass + const fx = [this.player, this.glow.m, this.spark.m, this.smoke.m, this.headPool], was = fx.map(o => o.visible); fx.forEach(o => { o.visible = false; }); + this.renderer.render(this.world, this.mirrorCam); fx.forEach((o, i) => { o.visible = was[i]; }); + this.renderer.setScissorTest(false); this.renderer.setViewport(0, 0, 854, 480); this.sky.position.copy(this.camera.position); + } + ctx.drawImage(this.view, 0, 0, 854, 480); + this.times.push(performance.now() - t0); if (this.times.length > 120) this.times.shift(); + this.ready = true; this.error = null; + } catch (e) { this.ready = false; this.error = String(e && e.stack || e); throw e; } + } + drawHeli(g) { + if (!g.heli || g.heli.gone) { if (this.heliObj) this.heliObj.visible = false; return; } + if (!this.heliObj) { + const H = this.heliObj = new T.Group(), body = this.lam({ color: 0x1c2230, vertexColors: true }); + H.add(new T.Mesh(this.keep(merge([[moved(new T.SphereGeometry(1.5, 10, 8), 0.6, 0, 0), 0xffffff], [moved(new T.BoxGeometry(4.2, 0.5, 0.45), -2.4, 0.2, 0), 0xffffff], [boxG(-4.5, 0.75, 0, 0.5, 1.2, 0.12), 0xffffff], [boxG(0.4, -1.45, 0.9, 2.8, 0.1, 0.12), 0x777777], [boxG(0.4, -1.45, -0.9, 2.8, 0.1, 0.12), 0x777777], [moved(new T.SphereGeometry(0.9, 8, 6), 1.5, 0.15, 0), 0x223a55]])), body)); + const rotor = this.heliRotor = new T.Mesh(this.keep(new T.BoxGeometry(9, 0.05, 0.3)), this.lam({ color: 0x26282c })); rotor.position.y = 1.65; H.add(rotor); + const beam = this.heliBeam = new T.Mesh(this.keep(new T.ConeGeometry(4.5, 26, 16, 1, true)), this.basic({ color: 0xd8e8ff, transparent: true, opacity: 0.13, blending: T.AdditiveBlending, depthWrite: false, side: T.DoubleSide })); beam.position.y = -13.5; H.add(beam); this.world.add(H); + } + const h = g.heli; this.heliObj.visible = true; qv(h.x, h.y, h.z, this.heliObj.position); this.heliObj.rotation.y = h.h; this.heliRotor.rotation.y = g.t * 1.1; + this.heliBeam.visible = !!h.sees; + } + metrics() { const s = [...this.times].sort((a, b) => a - b), i = this.renderer.info; return { renderer: 'webgl-nfsmw', drawCalls: i.render.calls, triangles: i.render.triangles, samples: s.length, cpuRenderMsP50: s.length ? s[Math.floor((s.length - 1) * 0.5)] : null, cpuRenderMsP95: s.length ? s[Math.floor((s.length - 1) * 0.95)] : null }; } + close() { if (this.closed) return; this.closed = true; this.ready = false; for (const r of this.res) r.dispose && r.dispose(); this.renderer.dispose(); this.renderer.forceContextLoss(); this.res = []; } + } + R3.render = (g, ctx) => { let s = byCanvas.get(ctx.canvas); if (!s || s.closed) { s = new Scene(ctx.canvas); byCanvas.set(ctx.canvas, s); } s.render(g, ctx); return s; }; + R3.status = ctx => { const s = ctx && byCanvas.get(ctx.canvas); if (s && !s.closed && s.renderer.getContext().isContextLost()) { s.ready = false; s.error = 'WebGL context lost'; } return { renderer: 'webgl-nfsmw', kind: 'perspective', ready: !!(s && s.ready && !s.closed), error: s ? s.error : null }; }; + R3.metrics = ctx => { const s = ctx && byCanvas.get(ctx.canvas); return s && !s.closed ? s.metrics() : null; }; + R3.close = ctx => { const s = ctx && byCanvas.get(ctx.canvas); if (s) { s.close(); byCanvas.delete(ctx.canvas); } }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/rivals.js b/environments/games/web/games/nfsmw_remake/rivals.js new file mode 100644 index 0000000000000000000000000000000000000000..a4e4bd687cf4e9101e1dbacc8047a309486b7536 --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/rivals.js @@ -0,0 +1,66 @@ +/* Rival racers. The driver model is AIActionRace with its own skill tables (AI/Actions/AIActionRace.cpp): speed scale {0.85, 1}, + acceleration scale {0.65, 1} (drag {0.82, 1}), catch-up acceleration table {1, 1.33, 1.66, 2} (:70), nitrous availability + {0.33, 1} (:42-43), on for 2-4 s (:38-39) and off for 20-4 s by skill (:36-37), speed-trap nitrous 1-3 s ahead (:40-41). + Catch-up gain by skill {0.33, 0.66, 1} and slow-down {1, 1, 0.66} are AI/Common/AIVehicle.cpp:2053-2059; the error scale + that feeds them lives in GRaceStatus::ComputeCatchUpSkill (body not in the repository), so the gaps below are approximations. + A rival rides route coordinates (s, lat), so it can never leave the road or get lost. Nothing here reads the RNG. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, P = C.PLAYER, lerp = C.lerp, clamp = C.clamp; + const tableAt = (t, x) => { const u = clamp(x, 0, 1) * (t.length - 1), i = Math.min(t.length - 2, Math.floor(u)); return t[i] + (t[i + 1] - t[i]) * (u - i); }; + // A rival's form on the day: drawn once at the start of a heat from the game RNG, so a seed is a different race, not a relabelled one. + M.formOf = g => (root.NativeBench.rand(g) - 0.5) * 0.06; + M.newRival = (g, o) => { + const a = C.routeAt(g.route, o.s, o.lat); + return { s: o.s, s0: o.s, lat: o.lat, latGoal: o.lat, v: 0, x: a.x, y: a.y, h: a.h, skill: o.skill, drag: !!o.drag, paint: o.paint || 0, out: 0, gone: 0, + nos: lerp(0.33, 1, o.skill), nosT: 0, nosCool: 2, trapNos: 0, prog: 0, finished: 0, top: o.top || 84, grip: o.grip || lerp(0.74, 0.98, o.skill), name: o.name || '' }; + }; + // Speed a rival would carry past a route point, integrated from where it is now: its own limits and drive, no glue, no nitrous, + // no traffic. Used only to score a camera the event ended before it reached. + M.projectRival = (g, r, target) => { + const R = g.route, accelScale = lerp(0.65, 1, r.skill), prof = C.profile(R, P.grip * r.grip, P.aero, P.brake * 0.9, r.top * lerp(0.85, 1, r.skill)); + let v = r.v; + for (let s = r.s; s < target; s += R.ds) { const a = Math.max(0, C.driveAt(v) * accelScale - P.drag * v * v - P.roll); v = Math.min(C.profileAt(R, prof, s + R.ds), Math.sqrt(v * v + 2 * a * R.ds)); } + return v; + }; + M.stepRival = (g, r, wdt) => { + if (r.out || r.finished) r.v = Math.max(0, r.v - 7 * wdt); + const R = g.route, skill = r.skill, speedScale = lerp(0.85, 1, skill), accelScale = r.drag ? lerp(0.82, 1, skill) : lerp(0.65, 1, skill); + const prof = C.profile(R, P.grip * r.grip, P.aero, P.brake * 0.9, r.top * speedScale), vlim = Math.min(C.profileAt(R, prof, r.s + r.v * 0.25), C.profileAt(R, prof, r.s + r.v * 0.5)); + // Catch-up glue: acceleration up to x2 when behind the player, a gentler speed limit when ahead (it never parks and waits). + const gap = (g.s - g.s0) - (r.s - r.s0), glue = g.glue === undefined ? 1 : g.glue, behind = glue * clamp(gap / 120, 0, 1) * tableAt([0.33, 0.66, 1], skill), ahead = glue * clamp(-gap / 240, 0, 1) * tableAt([1, 1, 0.66], skill); + const catchup = g.noGlue ? 1 : tableAt([1, 1.33, 1.66, 2], behind), limit = vlim * (g.noGlue ? 1 : 1 - 0.1 * ahead); + // Nitrous: skill sets how often and how much; a coming speed trap overrides the cool-down (CheckSpeedTraps). + if (r.nosT > 0) r.nosT -= wdt; else if (r.nosCool > 0) r.nosCool -= wdt; + const trapNear = r.trapNos > 0 && r.nos > 0.02; + if (!r.out && r.nosT <= 0 && r.nosCool <= 0 && r.nos > 0.02 && r.v > 10 && limit > r.v + 5) { r.nosT = lerp(2, 4, skill); r.nosCool = lerp(20, 4, skill); } + const on = (r.nosT > 0 || trapNear) && r.nos > 0 && r.v < limit - 1 && !r.out && !r.finished; + if (on) r.nos = Math.max(0, r.nos - wdt / P.nosSeconds); + if (r.trapNos > 0) r.trapNos -= wdt; + if (!r.out && !r.finished) { + if (r.v > limit) r.v = Math.max(limit, r.v - P.brake * 0.9 * wdt); + else { const a = C.driveAt(r.v) * accelScale * catchup * (on ? 1 + P.nosBoost : 1) - P.drag * r.v * r.v - P.roll; r.v = Math.min(limit, r.v + Math.max(0, a) * wdt); } + } + r.s += r.v * wdt; + // Lane: separation from the player and from traffic within two seconds; otherwise back to its own line. + const edge = R.halfW - 2.1; + if (!g.laneLocked) { + let goal = r.latGoal; + const clear = lat => { for (const t of g.traffic) { let ds = t.s - r.s; if (R.loop) { ds %= R.L; if (ds > R.L / 2) ds -= R.L; else if (ds < -R.L / 2) ds += R.L; } const cl = r.v - t.v; if (ds > -6 && ds < 8 + Math.max(cl, 0) * 2 && Math.abs(t.lat - lat) < 3.6) return false; } for (const b of g.blocks || []) { const ds = b.s - r.s; if (ds > -6 && ds < 10 + r.v * 2 && Math.abs(b.lat - lat) < 3.6) return false; } const ds = g.s - r.s; return !(ds > -6 && ds < 14 && Math.abs(g.lat - lat) < 3.4); }; + if (!clear(r.lat)) { let best = r.lat, bd = Infinity; for (let lat = -edge; lat <= edge + 1e-6; lat += edge / 2.5) if (clear(lat) && Math.abs(lat - r.lat) < bd) { bd = Math.abs(lat - r.lat); best = lat; } goal = best; } + const rate = Math.min(4.2, 0.6 + r.v * 0.09), dl = clamp(goal - r.lat, -rate * wdt, rate * wdt); r.lat = clamp(r.lat + dl, -edge, edge); + } + const a = C.routeAt(R, r.s, r.lat); r.x = a.x; r.y = a.y; r.h = a.h; + r.prog = r.s - r.s0; + // Contact. A rail car takes the impulse as a speed change and a sideways shove. + if (r.gone || g.pre > 0) return; + for (const t of g.traffic) { if (t.crash) continue; const dx = r.x - t.x, dy = r.y - t.y; if (dx * dx + dy * dy < 9) { r.v *= 0.55; t.crash = r.lat > t.lat ? -0.8 : 0.8; t.vx = Math.cos(t.h) * Math.abs(t.v); t.vy = Math.sin(t.h) * Math.abs(t.v); g.events.push({ type: 'rival_crash' }); } } + const c = g.car, dx = c.x - r.x, dy = c.y - r.y, d2 = dx * dx + dy * dy, R2 = M.carRadius * 2; + if (d2 < R2 * R2) { + const d = Math.max(0.01, Math.sqrt(d2)), nx = dx / d, ny = dy / d, rvx = Math.cos(r.h) * r.v, rvy = Math.sin(r.h) * r.v, rel = (c.vx - rvx) * nx + (c.vy - rvy) * ny, push = R2 - d; + c.x += nx * push * 0.5; c.y += ny * push * 0.5; + const nl = -Math.sin(r.h) * nx + Math.cos(r.h) * ny; r.lat = clamp(r.lat - nl * push * 0.5, -edge, edge); + if (rel < 0) { const j = -0.65 * rel; c.vx += nx * j; c.vy += ny * j; r.v = Math.max(0, r.v - (Math.cos(r.h) * nx + Math.sin(r.h) * ny) * j); if (-rel > 4) { g.hits++; g.lastHit = 0.4; g.events.push({ type: 'rival_contact', speed: -rel }); } } + } + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/nfsmw_remake/scripted.js b/environments/games/web/games/nfsmw_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..9a5a7aaea2105cca996954f97e469efed739da0c --- /dev/null +++ b/environments/games/web/games/nfsmw_remake/scripted.js @@ -0,0 +1,147 @@ +/* The standard scripted reference controller (BossBench, not part of the original game). NfsmwGame.scripted(game) runs once per + 200 ms packet. It reads already-decided state (poses, speeds, gates) and looks ahead only with the pure car model on a + copy of the player's car: other vehicles are extrapolated at constant speed, so it has no channel to a future random + draw at all. + Scoring is speed-weighted route progress minus wall and traffic risk. Never distance to a target (a target switch would + punish reaching it). Deterministic: no Math.random, no clock. */ +(function (root) { + 'use strict'; + const M = root.NfsmwGame, C = M.C, N = root.NativeBench; + const PACKET_TICKS = 12, HOLD_SETS = 6, DT = 1 / 60; + // Cars collide as two circles (game.js carRadius 1.6, 3.2 m between centres). A car alongside at 3.3 m is passing, not crashing. + const CONTACT = 3.5, LANE_GAP = 3.7; + // Duty-cycle steering: digital keys held for k of the 6 hold sets. The wheel slews towards the key and back to centre at + // the same rate, so duty 3 holds whatever angle it has, above 3 winds on, below 3 unwinds. + const STEER = [-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]; + const copyCar = c => Object.assign({}, c); + + // Same input mapping as Game.update; `plan` = {steer duty, thr, brk, hb, nos}. Mutates c. + function rollout(g, c, plan, ticks, P, wscale) { + for (let i = 0; i < ticks; i++) { + const set = Math.floor(i * HOLD_SETS / PACKET_TICKS) % HOLD_SETS, on = set < Math.abs(plan.duty); + C.carStep(c, { thr: plan.thr, brk: plan.brk, steer: on ? Math.sign(plan.duty) : 0, hb: plan.hb, nos: plan.nos, manual: false, sbGrip: 0 }, DT * wscale, P); + } + } + // Lateral target for the next stretch: keep off traffic that will be alongside, otherwise hold the racing line. + function laneTarget(g, R, S, others, speed, base) { + const edge = R.halfW - 2.2, lanes = [base, -edge * 0.75, edge * 0.75, -edge * 0.35, edge * 0.35, -edge, edge]; + let best = base, bs = -Infinity; + for (const lat of lanes) { + let sc = -Math.abs(lat - g.lat) * 0.5 - Math.abs(lat - base) * 0.2; + for (const o of others) { + const ds = o.s - S; if (ds < -8 || ds > 200) continue; // a car behind the door mirrors is not a reason to change lane + // A car close ahead at matching speed blocks the lane however small the closing speed is. + const closing = speed - o.vs, tt = ds < 30 && ds > -8 ? Math.max(0, ds) / Math.max(closing, 8) : closing > 1 ? ds / closing : 99; if (tt > 5) continue; + const gap = Math.abs(o.lat + (o.vl || 0) * Math.min(tt, 2) - lat); if (gap < LANE_GAP) sc -= (LANE_GAP - gap) * (6 - tt) * 2.4; + } + if (sc > bs) { bs = sc; best = lat; } + } + return best; + } + // Decided state of everything on the road, projected onto route coordinates. + function roadUsers(g, R) { + const out = [], L = R.L; + // On a circuit every position is one lap from itself: put each car on the player's lap so distances are real. + const near = v => { if (!R.loop) return v; let ds = (v - g.s) % L; if (ds > L / 2) ds -= L; else if (ds < -L / 2) ds += L; return Math.abs(v - g.s) <= L / 2 ? v : g.s + ds; }; + for (const t of g.traffic) out.push({ s: near(t.s), lat: t.lat, vs: t.crash ? 0 : t.v, r: 2 }); + for (const r of g.rivals) if (!r.out) out.push({ s: near(r.s), lat: r.lat, vs: r.v, r: 2, a: r.v < 25 ? 5 : 0 }); // a car pulling away is not a parked car + if (M.copUsers) M.copUsers(g, R, out); + return out; + } + // Minimum-curvature line: an elastic band pulled tight between the road edges. Controller-only and a pure function of the route, so + // it is cached outside the game state. Returns the lateral offset per sample and the speed profile on that line's own curvature. + const lines = new Map(); + function racingLine(R, P, grip, brake, top) { + let L = lines.get(R.name); + if (!L) { + const n = R.n, lat = new Float64Array(n), edge = R.halfW - 2.4, wrap = i => R.loop ? (i + n) % n : Math.max(0, Math.min(n - 1, i)), K = Math.max(2, Math.round(10 / R.ds)); + const nx = i => -Math.sin(R.h[i]), ny = i => Math.cos(R.h[i]), px = i => R.x[i] + nx(i) * lat[i], py = i => R.y[i] + ny(i) * lat[i]; + for (let it = 0; it < 400; it++) for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), tx = (px(a) + px(b)) / 2 - px(i), ty = (py(a) + py(b)) / 2 - py(i); lat[i] = C.clamp(lat[i] + 0.5 * (tx * nx(i) + ty * ny(i)), -edge, edge); } + const kap = new Float64Array(n); + for (let i = 0; i < n; i++) { const a = wrap(i - K), b = wrap(i + K), x1 = px(i) - px(a), y1 = py(i) - py(a), x2 = px(b) - px(i), y2 = py(b) - py(i), l1 = Math.hypot(x1, y1), l2 = Math.hypot(x2, y2), l3 = Math.hypot(x1 + x2, y1 + y2); kap[i] = l1 && l2 && l3 ? Math.abs(2 * (x1 * y2 - y1 * x2) / (l1 * l2 * l3)) : 0; } + L = { lat, kap, prof: new Map() }; lines.set(R.name, L); + } + const key = [grip, brake, top].map(v => v.toFixed(3)).join('|'); let v = L.prof.get(key); + if (!v) { + v = new Float64Array(R.n); + for (let i = 0; i < R.n; i++) v[i] = L.kap[i] > P.aero + 1e-5 ? Math.min(top, Math.sqrt(grip / (L.kap[i] - P.aero))) : top; + for (let p = 0; p < (R.loop ? 2 : 1); p++) for (let i = R.n - 1; i >= 0; i--) { const j = i + 1 < R.n ? i + 1 : R.loop ? 0 : i, lim = Math.sqrt(v[j] * v[j] + 2 * brake * R.ds); if (lim < v[i]) v[i] = lim; } + L.prof.set(key, v); + } + return { lat: L.lat, prof: v }; + } + const lineLat = (R, lat, s) => { let i = Math.round(s / R.ds); if (R.loop) { i %= R.n; if (i < 0) i += R.n; } else i = C.clamp(i, 0, R.n - 1); return lat[i]; }; + // Speed comes from the profile, steering from pure pursuit on the wanted line. Nothing here scores "slower is safer". + // First contact on the way to a lane, in route coordinates, with the other cars at their current speed. + function contactTime(g, others, S, speed, lat) { + const rate = 4, HORIZON_S = 3; + for (let t = 0.1; t < HORIZON_S; t += 0.1) { + const dl = lat - g.lat, l = g.lat + Math.sign(dl) * Math.min(Math.abs(dl), rate * t), sp = S + speed * t; + for (const o of others) { + if (o.s <= S) continue; + const ol = o.lat + (o.vl || 0) * Math.min(t, 2), ds = o.s + o.vs * t + 0.5 * (o.a || 0) * t * t - sp, t0 = t - 0.1, ds0 = o.s + o.vs * t0 + 0.5 * (o.a || 0) * t0 * t0 - (S + speed * t0); + // Inside the window now, or it went from ahead of the bumper to behind it during this step: sampling alone misses a fast closing car. + if (Math.abs(ol - l) < CONTACT && ((ds > 0 && Math.hypot(ds, ol - l) < CONTACT) || (ds0 > 0 && ds <= 0))) return t; + } + } + return HORIZON_S; + } + // The wheel slews towards the key held and back to centre (nfscore carStep), so a target angle is tracked one substep at a time. + function steerKeys(c, target, speed, wscale) { + const rate = (speed < 15 ? 7 : speed < 40 ? 5 : 3.6) * wscale * 2 * DT, out = []; let st = c.steer; + for (let i = 0; i < HOLD_SETS; i++) { + let best = 0, bd = Infinity; + for (const k of [0, 1, -1]) { const n = st + C.clamp(k - st, -rate, rate), e = Math.abs(n - target); if (e < bd - 1e-9) { bd = e; best = k; } } + out.push(best); st += C.clamp(best - st, -rate, rate); + } + return out; + } + function planDrive(g, opt = {}) { + const R = g.route, c = g.car, P = g.P || C.PLAYER, S = g.s, speed = C.speed(c), tire = C.tireFactor(c); + const margin = opt.margin || 0.92, top = opt.top || C.TOPS[5], wscale = g.sb ? 0.45 : 1; + const line = racingLine(R, P, P.grip * tire * margin, P.brake * 0.8, top), prof = line.prof; + const others = roadUsers(g, R), base = opt.lat !== undefined ? opt.lat : lineLat(R, line.lat, S + speed * 0.8), lat = laneTarget(g, R, S, others, speed, base), onLine = lat === base && opt.lat === undefined; + // Pure pursuit from where the car will be when this packet lands, at a lookahead that grows with speed. + const lag = 0.1 * wscale, px = c.x + c.vx * lag, py = c.y + c.vy * lag, ph = c.h + c.r * lag, Ld = Math.max(7, speed * 0.62); + const sNear = C.routeNear(R, px, py, S, 8, 16), aim = C.routeAt(R, sNear + Ld, onLine ? lineLat(R, line.lat, sNear + Ld) : lat); + let alpha = Math.atan2(aim.y - py, aim.x - px) - ph; alpha = Math.atan2(Math.sin(alpha), Math.cos(alpha)); + // Nose in a wall or a cop, too slow for the front wheels to turn it: back out on opposite lock (or, with a wall behind, full lock forward). + const far = C.routeAt(R, S + 18, lat); let off = Math.atan2(far.y - c.y, far.x - c.x) - c.h; off = Math.atan2(Math.sin(off), Math.cos(off)); + const nose = C.road(c.x + Math.cos(c.h) * 3.2, c.y + Math.sin(c.h) * 3.2).d > -0.5; + if (speed < 7 && (Math.abs(off) > 0.9 || nose)) { + const clearBehind = C.road(c.x - Math.cos(c.h) * 3.5, c.y - Math.sin(c.h) * 3.5).d < -0.6, side = off > 0 ? 1 : -1; + return { keys: steerKeys(c, clearBehind ? -side : side, speed, wscale), thr: clearBehind ? 0 : HOLD_SETS, brk: clearBehind, nos: false, lat, contact: 3, why: 'recover' }; + } + const kappa = 2 * Math.sin(alpha) / Ld, delta = Math.atan(kappa * P.wheelbase), range = C.steerRange(speed / C.MPH) * Math.PI / 180; + const vlim = Math.min(C.profileAt(R, prof, S + speed * 0.2), C.profileAt(R, prof, S + speed * 0.45)); + // In a chase, slowing down is what a rolling block wants: a moving cop is steered round or rammed, never braked for. + const contact = contactTime(g, opt.ram ? others.filter(o => !o.cop) : others, S, speed, lat), over = speed > vlim + 0.8, brk = over || contact < 0.8, coast = !brk && contact < 1.2; + // Friction circle (carStep): drive force eats lateral capacity, so in a corner the throttle is only what the tyres can spare. + const grip = (P.grip + P.aero * speed * speed) * tire, ay = speed * speed * Math.abs(kappa), spare = Math.max(0, 1 - ay / grip); + const allowed = spare / 0.55 * grip * 1.1, drive = Math.max(1, C.driveAt(speed) * P.accel), thr = coast ? 0 : Math.round(HOLD_SETS * C.clamp(allowed / drive, 0.17, 1)); + const nos = !brk && !coast && (opt.forceNos ? c.nos > 0.02 && speed > 12 : c.nos > 0.02 && speed > 18 && opt.nos !== false && thr === HOLD_SETS && C.profileAt(R, prof, S + speed * 1.8) > speed + 8); + return { keys: steerKeys(c, C.clamp(delta / range, -1, 1), speed, wscale), thr: brk ? 0 : thr, brk, nos, lat, contact, why: over ? 'speed' : contact < 0.8 ? 'contact' : coast ? 'coast' : 'drive' }; + } + function toPacket(plan, extra = []) { + const holds = []; + for (let i = 0; i < HOLD_SETS; i++) { + const h = [], k = plan.keys ? plan.keys[i] : 0; + // Throttle is spread evenly through the packet: both ticks of a set see the same keys. + if (plan.brk) h.push('S'); else if (plan.thr >= HOLD_SETS || Math.floor((i + 1) * plan.thr / HOLD_SETS) > Math.floor(i * plan.thr / HOLD_SETS)) h.push('W'); + if (k) h.push(k > 0 ? 'A' : 'D'); + if (plan.nos) h.push('Shift'); + for (const [key, set] of extra) if (set === i && h.length < 4) h.push(key); + holds.push(h); + } + return { holds, mouse: [0, 0, 0] }; + } + // Staging, then the line. Pinned for a while: the original's manual reset, which costs the speed that was left, so never a first resort. + const drive = (g, opt) => { if (g.pre > 0.21) return toPacket({ thr: HOLD_SETS, brk: false, nos: false }); let cop = Infinity; for (const k of g.cops) if (!k.dead && !k.gone) cop = Math.min(cop, Math.hypot(g.car.x - k.x, g.car.y - k.y)); return toPacket(planDrive(g, opt), g.slowT > 2.5 && cop > 90 ? [['R', 0]] : []); }; // a reset near a cop flashes the car: bust distance x6, rate x4 (AIPursuit.cpp:1895-1909) + M.ctl = { planDrive, toPacket, rollout, roadUsers, copyCar, drive }; + M.scripted = function (g) { + const mode = M.MODES[g.key]; + if (mode.scripted) return mode.scripted(g); // an event with its own rules plans its own staging too + return drive(g, {}); + }; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/LICENSE.fdlibm b/environments/games/web/games/quake2_remake/LICENSE.fdlibm new file mode 100644 index 0000000000000000000000000000000000000000..b0247953f8084557757ed42eef788d75fc879150 --- /dev/null +++ b/environments/games/web/games/quake2_remake/LICENSE.fdlibm @@ -0,0 +1,6 @@ +Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunSoft, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. diff --git a/environments/games/web/games/quake2_remake/compact_actions.json b/environments/games/web/games/quake2_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..074a8adeb485f957c7cc3bb7b72038d98b0f2162 --- /dev/null +++ b/environments/games/web/games/quake2_remake/compact_actions.json @@ -0,0 +1,165 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "quake2_remake", + "version": "quake2-compact@1", + "note": "A 200 ms packet combines eight-way running, yaw, pitch, and one attack, jump, or weapon action. Late fire starts in sub-step five. One mouse count is 0.066 degrees. Positive dy looks down.", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W", + "Shift" + ] + }, + { + "label": "back", + "keys": [ + "S", + "Shift" + ] + }, + { + "label": "left", + "keys": [ + "A", + "Shift" + ] + }, + { + "label": "right", + "keys": [ + "D", + "Shift" + ] + }, + { + "label": "forward_left", + "keys": [ + "W", + "A", + "Shift" + ] + }, + { + "label": "forward_right", + "keys": [ + "W", + "D", + "Shift" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A", + "Shift" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D", + "Shift" + ] + } + ] + }, + { + "name": "turn", + "options": [ + { + "label": "none" + }, + { + "label": "left_3", + "dx": -45 + }, + { + "label": "right_3", + "dx": 45 + }, + { + "label": "left_10", + "dx": -152 + }, + { + "label": "right_10", + "dx": 152 + }, + { + "label": "left_30", + "dx": -455 + }, + { + "label": "right_30", + "dx": 455 + } + ] + }, + { + "name": "pitch", + "options": [ + { + "label": "none" + }, + { + "label": "up_2", + "dy": -30 + }, + { + "label": "down_2", + "dy": 30 + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "keys": [ + "J" + ] + }, + { + "label": "fire_late", + "subs": [ + [], + [], + [], + [], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "jump", + "tap": [ + "Space" + ] + }, + { + "label": "next_weapon", + "tap": [ + "K" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/quake2_remake/draw.js b/environments/games/web/games/quake2_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..4f61ef950a3daae3cc5d9ebb9d7f561384abf68e --- /dev/null +++ b/environments/games/web/games/quake2_remake/draw.js @@ -0,0 +1,95 @@ +/* Quake II boss arenas - Module.draw: the WebGL first-person view plus a Canvas 2D HUD in the Quake II layout + (health / ammo / armor numbers along the bottom, pickup string, pain flash), with BossBench additions: boss name, + health bar and phase, fight timer, skill / tier and the native tick rate. Read-only on the game state. */ +(function (root) { + 'use strict'; + const M = root.Quake2Game, Q = M.Q, R = M.R3; + const WEAPON_LABEL = { blaster: 'ENERGY PISTOL', shotgun: 'SHOTGUN', supershotgun: 'DOUBLE SHOTGUN', machinegun: 'MACHINEGUN', chaingun: 'CHAINGUN', + rocketlauncher: 'ROCKET LAUNCHER', hyperblaster: 'PULSE CANNON', railgun: 'COILGUN' }; + const AMMO_LABEL = { shells: 'SHELLS', bullets: 'BULLETS', rockets: 'ROCKETS', cells: 'CELLS', slugs: 'SLUGS' }; + const ITEM_LABEL = { health: 'Health', health_large: 'Large Health', stimpack: 'Med Injector', armor_shard: 'Armor Shard', armor_jacket: 'Jacket Armor', + armor_combat: 'Combat Armor', armor_body: 'Body Armor', ammo_shells: 'Shells', ammo_bullets: 'Bullets', ammo_cells: 'Cells', ammo_rockets: 'Rockets', ammo_slugs: 'Slugs' }; + const MOVE_LABEL = { + monster_supertank: { attack1: 'Chain-gun burst', end_attack1: 'Chain-gun cooldown', attack2: 'Triple rockets', pain1: 'Hurt', pain2: 'Hurt', pain3: 'Hurt', death: 'Explosion' }, + monster_boss2: { attack_pre_mg: 'Twin guns spin up', attack_mg: 'Twin machine guns', attack_post_mg: 'Machine guns wind down', attack_rocket: 'Rocket salvo', pain_light: 'Hurt', pain_heavy: 'Heavy hit', death: 'Crash' }, + monster_jorg: { start_attack1: 'Twin chain guns spin up', attack1: 'Twin chain guns', end_attack1: 'Chain guns wind down', attack2: 'Energy orb', pain1: 'Hurt', pain2: 'Hurt', pain3: 'Heavy hit', death: 'Collapse' }, + monster_makron: { sight: 'Leap out', attack3: 'Energy orb', attack4: 'Energy burst', attack5: 'Railgun aiming', pain4: 'Hurt', pain5: 'Hurt', pain6: 'Heavy hit', death2: 'Fall' }, + monster_tank_commander: { attack_blast: 'Triple blaster shot', reattack_blast: 'Blaster follow-up', attack_post_blast: 'Weapon lowered', attack_pre_rocket: 'Rockets ready', attack_fire_rocket: 'Triple rockets', + attack_post_rocket: 'Rockets end', attack_chain: 'Chain-gun sweep', attack_strike: 'heavy punch', start_run: 'Launch', pain1: 'Hurt', pain2: 'Hurt', pain3: 'Heavy hit', death: 'Fall' }, + monster_gladiator: { attack_melee: 'Blade slash', attack_gun: 'Railgun aiming', pain: 'Hurt', pain_air: 'Hurt', death: 'Fall' }, + monster_mutant: { attack: 'Claw combo', jump: 'Pounce', pain1: 'Hurt', pain2: 'Hurt', pain3: 'Hurt', death1: 'Fall', death2: 'Fall' }, + }; + function panel(c, x, y, w, h) { c.fillStyle = 'rgba(14,12,10,0.62)'; c.fillRect(x, y, w, h); c.strokeStyle = 'rgba(180,150,90,0.45)'; c.lineWidth = 1; c.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1); } + function bigNumber(c, value, x, y, color, label) { + c.textAlign = 'right'; c.font = 'bold 34px Consolas, "Courier New", monospace'; c.fillStyle = '#000a'; c.fillText(String(value), x + 2, y + 2); + c.fillStyle = color; c.fillText(String(value), x, y); + c.font = '11px Consolas, monospace'; c.fillStyle = '#c8b88a'; c.fillText(label, x, y + 14); c.textAlign = 'left'; + } + M.draw = function (g, c) { + R.render(g, c); + const p = g.ents[1], W = 854, H = 480; + // pain / pickup blend (SV_CalcBlend damage_alpha, bonus_alpha) + if (p.damage_alpha > 0) { c.fillStyle = 'rgba(200,20,10,' + Math.min(0.55, p.damage_alpha) + ')'; c.fillRect(0, 0, W, H); } + if (p.bonus_alpha > 0) { c.fillStyle = 'rgba(255,230,120,' + Math.min(0.3, p.bonus_alpha) + ')'; c.fillRect(0, 0, W, H); } + if (p.health <= 0) { c.fillStyle = 'rgba(90,0,0,0.35)'; c.fillRect(0, 0, W, H); } + // crosshair + if (p.health > 0) { c.strokeStyle = 'rgba(255,240,200,0.85)'; c.lineWidth = 1.5; c.beginPath(); c.moveTo(W / 2 - 7, H / 2); c.lineTo(W / 2 - 2, H / 2); c.moveTo(W / 2 + 2, H / 2); c.lineTo(W / 2 + 7, H / 2); + c.moveTo(W / 2, H / 2 - 7); c.lineTo(W / 2, H / 2 - 2); c.moveTo(W / 2, H / 2 + 2); c.lineTo(W / 2, H / 2 + 7); c.stroke(); } + // direction of the last hit: relative yaw (Quake yaw grows to the left) -> rotation of an "ahead" marker + if (p.damage_alpha > 0.05 && p.damage_from_dir) { + const yaw = Math.atan2(p.damage_from_dir[1], p.damage_from_dir[0]) * 180 / Math.PI - p.v_angle[1], a = -yaw * Math.PI / 180; + c.save(); c.translate(W / 2, H / 2); c.rotate(a); c.fillStyle = 'rgba(255,60,40,' + Math.min(0.9, p.damage_alpha * 1.6) + ')'; + c.beginPath(); c.moveTo(0, -120); c.lineTo(-14, -98); c.lineTo(14, -98); c.closePath(); c.fill(); c.restore(); + } + // bottom status bar (Quake II order: ammo | health | armor) + panel(c, 8, H - 58, 838, 50); + const it = Q.ITEMS[p.weapon] || {}, ammo = it.ammo ? p.inv[it.ammo] : null; + bigNumber(c, ammo === null ? '--' : ammo, 120, H - 22, ammo !== null && ammo < 5 ? '#ff7050' : '#f0d070', it.ammo ? AMMO_LABEL[it.ammo] : 'NO AMMO'); + bigNumber(c, Math.max(0, p.health), 300, H - 22, p.health < 25 ? '#ff5040' : '#f0d070', 'HEALTH'); + const ak = Q.armorIndex(p); + bigNumber(c, ak ? p.inv[ak] : 0, 470, H - 22, '#9fd27a', ak ? ak.toUpperCase() + ' ARMOR' : 'ARMOR'); + c.font = 'bold 13px Consolas, monospace'; c.fillStyle = '#e8dcb8'; c.fillText(WEAPON_LABEL[p.weapon] || '', 500, H - 36); + c.font = '11px Consolas, monospace'; c.fillStyle = '#a99e84'; + const inv = Q.WEAPON_ORDER.filter(w => p.inv[w]).map(w => (w === p.weapon ? '[' : ' ') + WEAPON_LABEL[w].split(' ')[0].slice(0, 7) + (w === p.weapon ? ']' : ' ')).join(''); + c.fillText(inv, 500, H - 19); + // clock: fight timer and the native tick rate + panel(c, 676, 8, 170, 46); c.textAlign = 'right'; c.font = 'bold 18px Consolas, monospace'; c.fillStyle = '#f0e4c0'; + c.fillText((g.t / M.hz).toFixed(1) + ' s', 838, 30); c.font = 'bold 12px Consolas, monospace'; c.fillStyle = '#9fd0ff'; c.fillText(M.hz + 'Hz · tick ' + g.t, 838, 46); c.textAlign = 'left'; + // boss bar + const h = g.health(), bi = g.bossEnt(), b = g.ents[bi], def = Q.MONSTERS[b.classname] || {}; + panel(c, 187, 8, 480, 46); + const frac = h[3] ? h[2] / h[3] : 0; + c.fillStyle = '#2a1410'; c.fillRect(197, 30, 460, 14); + c.fillStyle = b.classname === 'monster_makron' ? '#c040e0' : '#d23a20'; c.fillRect(197, 30, 460 * frac, 14); + if (g.bossClass === 'monster_jorg') { const split = g.makronHealth / h[3]; c.fillStyle = '#f2e6c0'; c.fillRect(197 + 460 * split - 1, 28, 2, 18); } + c.font = 'bold 14px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#f2e6c0'; + const phase = g.bossClass === 'monster_jorg' ? (b.classname === 'monster_makron' ? 'Second form' : 'First form') : 'Single phase'; + c.fillText((def.name || '') + ' · ' + phase, 197, 24); + const mv = (b.monsterinfo && MOVE_LABEL[b.classname] && MOVE_LABEL[b.classname][b.monsterinfo.currentmove]) || (b.deadflag ? 'Fall' : 'Chase'); + c.textAlign = 'right'; c.font = '12px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = '#e8b070'; + c.fillText(mv + ' ' + Math.ceil(h[2]) + ' / ' + h[3], 657, 24); c.textAlign = 'left'; + // skill / tier tag + panel(c, 8, 8, 170, 46); + c.font = 'bold 12px Consolas, monospace'; c.fillStyle = '#f0d070'; c.fillText('QUAKE II · ' + M.skillNames[g.skill].toUpperCase(), 16, 26); + c.font = '11px Consolas, monospace'; c.fillStyle = '#a99e84'; c.fillText('skill ' + g.skill + (g.tier ? ' · tier ' + g.tier : '') + ' · d=' + g.d, 16, 44); + // pickup message (3 s, like STAT_PICKUP_STRING) + if (p.pickup && g.ms < p.pickup_time) { c.font = '14px "Segoe UI", sans-serif'; c.fillStyle = '#f2e6c0'; c.textAlign = 'center'; c.fillText(ITEM_LABEL[p.pickup] || p.pickup, W / 2, H - 70); c.textAlign = 'left'; } + // telegraphs: railguns lock the shot ahead of time (Makron one frame, Gladiator 0.4 s); the Mutant's leap + const tele = (text, color) => { c.font = 'bold 15px "Segoe UI", "Microsoft YaHei", sans-serif'; c.fillStyle = color; c.textAlign = 'center'; c.fillText(text, W / 2, 78); c.textAlign = 'left'; }; + const mvName = b.monsterinfo && !b.deadflag ? b.monsterinfo.currentmove : null; + if (b.classname === 'monster_makron' && mvName === 'attack5' && b.frame >= 235 && b.frame <= 242) tele(b.frame >= 241 ? 'Railgun locked on! Strafe!' : 'Railgun charging', '#7fc8ff'); + if (b.classname === 'monster_gladiator' && mvName === 'attack_gun' && b.frame <= 48) tele('Railgun aimed at your previous position — strafe!', '#7fc8ff'); + if (b.classname === 'monster_mutant' && mvName === 'jump' && b.frame <= 4) tele('Pounce!', '#ff9a60'); + if (b.classname === 'monster_tank_commander' && mvName === 'attack_chain') tele('Chain-gun sweep: get behind cover', '#ffd070'); + // result banner: above the centre, where the play page puts its own result box over the canvas + if (g.outcome) { + c.fillStyle = 'rgba(8,6,4,0.55)'; c.fillRect(0, 96, W, 80); + c.textAlign = 'center'; c.font = 'bold 30px "Segoe UI", "Microsoft YaHei", sans-serif'; + c.fillStyle = g.outcome === 'win' ? '#f0d070' : '#ff6a50'; + c.fillText(g.outcome === 'win' ? 'Boss defeated · ' + (g.t / M.hz).toFixed(1) + ' s' : g.outcome === 'loss' ? 'You died' : 'Time up', W / 2, 147); c.textAlign = 'left'; + } + }; + M.renderStatus = ctx => R.status(ctx); + M.renderMetrics = ctx => R.metrics(ctx); + M.closeRenderer = ctx => R.close(ctx); +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/game.js b/environments/games/web/games/quake2_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..246ec9c74922b3443a24d46942a66a5e0d16a13b --- /dev/null +++ b/environments/games/web/games/quake2_remake/game.js @@ -0,0 +1,292 @@ +/* Quake II (1997) boss arenas, rules q2-arena@4 - the BossBench module: cases, tiers, original arenas, the server + frame (sv_main.c SV_Frame -> SV_RunGameFrame -> g_main.c G_RunFrame) and the public declaration. + Native clock (q2-arena@3, 2026-11-06): 60 Hz, the original client at cl_maxfps 60. One BossBench tick = one host + frame of 16/17 ms: one usercmd (ClientThink -> Pmove, cmd.msec 16/17) and entity physics for that slice. Game + logic keeps the original 10 Hz server frame (g_local.h FRAMETIME 0.1): thinks fire on nextthink in ms, and the + server-frame parts run on every sixth tick. A 200 ms action packet is twelve ticks. See + Independent reimplementation from id Software's GPL-2.0 source release (commit + 372afde46e7defc9dd2d719a1732b8ace1fa096e). Arenas, items placement and loadouts are original; all art is + procedural; no game data (pak, models, textures, sounds, maps) is used. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.Quake2Game, Q = M.Q; + const { copy3 } = Q; + + // ---------------- public tiers (2026-11-02) ---------------- + // Tiers on Quake II's skill cvar: easy = skill 0 Easy (the player takes half damage, the default M_CheckAttack + // chance is halved), normal = skill 1 Medium, hard = skill 3 Hard+ (no boss pain animations and a 5 s pain lock-out: + // the only skill rule that raises the aggression of every boss; it includes the skill >= 2 rules: attack chance + // doubled, the Super Tank and the Tank Commander ignore pain while firing, the Tank Commander refires). d in [0.6, 0.8) + // is skill 2 Hard. All of this is the original game's own skill cvar with its own parameters, the same fight on every + // tier, so hard stays at 0.9. Boss spawn health per tier is a BossBench extension (Quake II never scales monster + // health), calibrated to the script windows, which are the criterion (easy 20-30 s, normal 45-90 s, hard 150-240 s; the + // easy-tier health is an approximate target): anchors at the three tier values, linear between them, held outside. + const TIERS = { easy: 0.15, normal: 0.45, hard: 0.9 }, TIER_D = [TIERS.easy, TIERS.normal, TIERS.hard]; + const HEALTH = { + monster_supertank: [650, 4500, 10400], + monster_boss2: [620, 5000, 12500], + monster_jorg: [260, 2700, 6600], + monster_makron: [220, 2250, 5500], + monster_tank_commander: [750, 5000, 10500], + monster_gladiator: [780, 5000, 14000], + monster_mutant: [800, 5500, 13000], + }; + const SKILL_NAMES = ['Easy', 'Medium', 'Hard', 'Hard+']; + const skillOf = d => d < 0.3 ? 0 : d < 0.6 ? 1 : d < 0.8 ? 2 : 3; + const tierOf = d => Object.keys(TIERS).find(t => Math.abs(TIERS[t] - d) < 1e-9) || null; + function healthOf(classname, d) { + const h = HEALTH[classname]; + if (d <= TIER_D[0]) return h[0]; + if (d >= TIER_D[2]) return h[2]; + const k = d <= TIER_D[1] ? 0 : 1, f = (d - TIER_D[k]) / (TIER_D[k + 1] - TIER_D[k]); + return Math.round(h[k] + (h[k + 1] - h[k]) * f); + } + + // ---------------- original arenas (Quake II map units, z up; brushes are axis-aligned boxes) ---------------- + const B = (x0, y0, z0, x1, y1, z1, mat, extra) => Object.assign({ mins: [x0, y0, z0], maxs: [x1, y1, z1], contents: Q.CONTENTS_SOLID, mat }, extra || {}); + function shell(w, h, height, opts) { // floor, four walls, ceiling (sky or roof) + const t = 64, out = [B(-t, -t, -t, w + t, h + t, 0, opts.floor || 'floor')]; + out.push(B(-t, -t, 0, 0, h + t, height, opts.wall || 'wall'), B(w, -t, 0, w + t, h + t, height, opts.wall || 'wall')); + out.push(B(0, -t, 0, w, 0, height, opts.wall || 'wall'), B(0, h, 0, w, h + t, height, opts.wall || 'wall')); + out.push(B(-t, -t, height, w + t, h + t, height + t, opts.sky ? 'sky' : 'roof', opts.sky ? { sky: true } : null)); + return out; + } + const ARENAS = { + // Super Tank: a walled Strogg supply yard under an open sky; crate stacks and two pylons give cover against the + // hitscan chaingun, the open middle lets the rockets be side-stepped. + supertank: { + title: 'Walled supply yard (original layout)', size: [1664, 1664, 384], sky: 'dusk', + brushes: () => [...shell(1664, 1664, 384, { sky: true, wall: 'wall' }), + B(360, 520, 0, 456, 616, 96, 'crate'), B(1208, 520, 0, 1304, 616, 96, 'crate'), + B(360, 1048, 0, 456, 1144, 96, 'crate'), B(1208, 1048, 0, 1304, 1144, 96, 'crate'), + B(392, 552, 96, 456, 616, 160, 'crate'), B(1208, 1080, 96, 1272, 1144, 160, 'crate'), + B(768, 780, 0, 896, 884, 320, 'pylon'), + B(96, 760, 0, 160, 904, 64, 'tech'), B(1504, 760, 0, 1568, 904, 64, 'tech'), + B(560, 300, 0, 736, 340, 80, 'barrier'), B(928, 300, 0, 1104, 340, 80, 'barrier'), + ], + player: { origin: [832, 200, 24], yaw: 90 }, + boss: { classname: 'monster_supertank', origin: [832, 1430, 0], yaw: 270 }, + loadout: { weapons: ['blaster', 'shotgun', 'supershotgun', 'machinegun', 'rocketlauncher'], weapon: 'rocketlauncher', + ammo: { shells: 100, bullets: 200, rockets: 50 }, armor: ['combat', 50] }, + items: [['health_large', 160, 160], ['health_large', 1504, 160], ['health', 160, 1504], ['health', 1504, 1504], + ['health_large', 408, 832], ['health_large', 1256, 832], ['health', 832, 230], ['armor_jacket', 832, 1300], + ['ammo_rockets', 120, 832], ['ammo_rockets', 1544, 832], ['ammo_rockets', 832, 1544], ['ammo_rockets', 600, 120], ['ammo_rockets', 1064, 120], + ['ammo_shells', 832, 120], ['ammo_bullets', 120, 1200], ['ammo_bullets', 1544, 1200], ['armor_shard', 408, 680], ['armor_shard', 1256, 680], + ['armor_shard', 408, 984], ['armor_shard', 1256, 984], ['stimpack', 640, 160], ['stimpack', 1024, 160]], + }, + // Hornet: a tall hangar bay; the boss flies at the player's eye level, cargo blocks can hide the player from + // the twin machineguns but not from rockets over the top. + hornet: { + title: 'Hangar bay (original layout)', size: [1792, 1792, 512], sky: 'none', + brushes: () => [...shell(1792, 1792, 512, { sky: false, wall: 'hangar' }), + B(380, 640, 0, 572, 736, 128, 'cargo'), B(1220, 640, 0, 1412, 736, 128, 'cargo'), + B(380, 1056, 0, 572, 1152, 128, 'cargo'), B(1220, 1056, 0, 1412, 1152, 128, 'cargo'), + B(832, 832, 0, 960, 960, 512, 'pylon'), + B(0, 1600, 0, 1792, 1792, 48, 'tech'), + ], + player: { origin: [896, 220, 24], yaw: 90 }, + boss: { classname: 'monster_boss2', origin: [896, 1380, 72], yaw: 270 }, + loadout: { weapons: ['blaster', 'machinegun', 'chaingun', 'hyperblaster', 'railgun'], weapon: 'chaingun', + ammo: { bullets: 200, cells: 200, slugs: 50 }, armor: ['combat', 50] }, + items: [['health_large', 160, 160], ['health_large', 1632, 160], ['health', 160, 896], ['health', 1632, 896], + ['ammo_bullets', 896, 120], ['ammo_bullets', 896, 1500], ['ammo_slugs', 120, 520], ['ammo_slugs', 1672, 520], ['ammo_slugs', 120, 1300], ['ammo_slugs', 1672, 1300], + ['ammo_cells', 896, 600], ['ammo_cells', 300, 900], + ['armor_shard', 476, 600], ['armor_shard', 1316, 600], ['stimpack', 680, 160], ['stimpack', 1112, 160]], + }, + // Jorg + Makron: the final showdown chamber; four broad pillars for the chaingun stream, enough room for the + // 160-unit Jorg to walk around them and for BFG orbs to be outrun. + makron: { + title: 'Final showdown chamber (original layout)', size: [1920, 1920, 448], sky: 'none', + brushes: () => [...shell(1920, 1920, 448, { sky: false, wall: 'strogg' }), + B(480, 480, 0, 640, 640, 448, 'pillar'), B(1280, 480, 0, 1440, 640, 448, 'pillar'), + B(480, 1280, 0, 640, 1440, 448, 'pillar'), B(1280, 1280, 0, 1440, 1440, 448, 'pillar'), + B(864, 864, 0, 1056, 1056, 24, 'dais'), + ], + player: { origin: [960, 200, 24], yaw: 90 }, + boss: { classname: 'monster_jorg', origin: [960, 1560, 0], yaw: 270 }, + loadout: { weapons: ['blaster', 'supershotgun', 'chaingun', 'rocketlauncher', 'hyperblaster', 'railgun'], weapon: 'railgun', + ammo: { shells: 50, bullets: 200, rockets: 50, cells: 200, slugs: 50 }, armor: ['body', 100] }, + items: [['health_large', 160, 160], ['health_large', 1760, 160], ['health_large', 160, 1760], ['health_large', 1760, 1760], + ['health', 960, 140], ['ammo_slugs', 300, 960], ['ammo_slugs', 1620, 960], ['ammo_rockets', 960, 360], ['ammo_cells', 960, 1760], + ['armor_shard', 560, 720], ['armor_shard', 1360, 720], ['armor_shard', 560, 1200], ['armor_shard', 1360, 1200], + ['stimpack', 760, 160], ['stimpack', 1160, 160]], + }, + // Tank Commander: a Strogg factory floor. Machine blocks stop the chaingun sweep (19 hitscan bullets of 20 fired + // along a fixed +-40 degree arc), the open aisles leave room to side-step blaster bolts and rockets. + tank_commander: { + title: 'Factory floor (original layout)', size: [1792, 1792, 448], sky: 'none', + brushes: () => [...shell(1792, 1792, 448, { sky: false, wall: 'factory' }), + B(352, 560, 0, 608, 688, 160, 'machine'), B(1184, 560, 0, 1440, 688, 160, 'machine'), + B(352, 1104, 0, 608, 1232, 160, 'machine'), B(1184, 1104, 0, 1440, 1232, 160, 'machine'), + B(832, 832, 0, 960, 960, 448, 'pylon'), + B(640, 320, 0, 800, 352, 72, 'barrier'), B(992, 320, 0, 1152, 352, 72, 'barrier'), + ], + player: { origin: [896, 180, 24], yaw: 90 }, + boss: { classname: 'monster_tank_commander', origin: [896, 1500, 24], yaw: 270 }, + loadout: { weapons: ['blaster', 'shotgun', 'supershotgun', 'machinegun', 'chaingun', 'rocketlauncher'], weapon: 'rocketlauncher', + ammo: { shells: 100, bullets: 200, rockets: 50 }, armor: ['combat', 50] }, + items: [['health_large', 160, 160], ['health_large', 1632, 160], ['health', 160, 1632], ['health', 1632, 1632], + ['health_large', 480, 896], ['health_large', 1312, 896], ['ammo_rockets', 120, 896], ['ammo_rockets', 1672, 896], + ['ammo_rockets', 896, 1672], ['ammo_rockets', 560, 120], ['ammo_rockets', 1232, 120], ['ammo_bullets', 896, 120], + ['ammo_shells', 480, 1400], ['ammo_shells', 1312, 1400], ['armor_shard', 480, 760], ['armor_shard', 1312, 760], + ['armor_shard', 480, 1032], ['armor_shard', 1312, 1032], ['stimpack', 720, 200], ['stimpack', 1072, 200]], + }, + // Gladiator: an open-sky fighting pit. A ring of six columns breaks the railgun's line (aimed at the spot the + // player stood on 0.4 s before the shot); the floor is flat so the cleaver can always be out-run. + gladiator: { + title: 'Fighting pit (original layout)', size: [1664, 1664, 384], sky: 'dusk', + brushes: () => [...shell(1664, 1664, 384, { sky: true, wall: 'arena' }), + B(800, 400, 0, 864, 464, 320, 'column'), B(800, 1200, 0, 864, 1264, 320, 'column'), + B(456, 600, 0, 520, 664, 320, 'column'), B(1144, 600, 0, 1208, 664, 320, 'column'), + B(456, 1000, 0, 520, 1064, 320, 'column'), B(1144, 1000, 0, 1208, 1064, 320, 'column'), + B(96, 96, 0, 224, 224, 64, 'arena'), B(1440, 96, 0, 1568, 224, 64, 'arena'), + B(96, 1440, 0, 224, 1568, 64, 'arena'), B(1440, 1440, 0, 1568, 1568, 64, 'arena'), + ], + player: { origin: [832, 180, 24], yaw: 90 }, + boss: { classname: 'monster_gladiator', origin: [832, 1480, 32], yaw: 270 }, + loadout: { weapons: ['blaster', 'shotgun', 'supershotgun', 'chaingun', 'rocketlauncher', 'hyperblaster'], weapon: 'rocketlauncher', + ammo: { shells: 50, bullets: 200, rockets: 50, cells: 200 }, armor: ['combat', 50] }, + items: [['health_large', 300, 300], ['health_large', 1364, 300], ['health', 300, 1364], ['health', 1364, 1364], + ['health_large', 832, 832], ['ammo_rockets', 120, 832], ['ammo_rockets', 1544, 832], ['ammo_rockets', 832, 1544], + ['ammo_rockets', 600, 120], ['ammo_rockets', 1064, 120], ['ammo_cells', 832, 640], ['ammo_cells', 832, 1024], + ['ammo_bullets', 640, 832], ['ammo_bullets', 1024, 832], ['armor_shard', 488, 760], ['armor_shard', 1176, 760], + ['armor_shard', 488, 904], ['armor_shard', 1176, 904], ['stimpack', 640, 200], ['stimpack', 1024, 200]], + }, + // Mutant: a containment lab. No ranged attack: the mutant claws at 80 units and leaps (600 forward, 250 up) from + // 100 units out; the long benches (48 high: above the 18 step, above its 39-unit leap) and the pillars are what the + // player kites it around. + mutant: { + title: 'Containment lab (original layout)', size: [1920, 1600, 384], sky: 'none', + brushes: () => [...shell(1920, 1600, 384, { sky: false, wall: 'lab' }), + B(480, 560, 0, 864, 624, 48, 'bench'), B(1056, 560, 0, 1440, 624, 48, 'bench'), + B(480, 976, 0, 864, 1040, 48, 'bench'), B(1056, 976, 0, 1440, 1040, 48, 'bench'), + B(272, 768, 0, 368, 864, 384, 'column'), B(1552, 768, 0, 1648, 864, 384, 'column'), + B(912, 768, 0, 1008, 832, 384, 'column'), + ], + player: { origin: [960, 200, 24], yaw: 90 }, + boss: { classname: 'monster_mutant', origin: [960, 1380, 32], yaw: 270 }, + loadout: { weapons: ['blaster', 'shotgun', 'supershotgun', 'machinegun', 'chaingun'], weapon: 'supershotgun', + ammo: { shells: 100, bullets: 200 }, armor: ['combat', 50] }, + items: [['health_large', 160, 160], ['health_large', 1760, 160], ['health', 160, 1440], ['health', 1760, 1440], + ['health_large', 960, 700], ['ammo_shells', 120, 800], ['ammo_shells', 1800, 800], ['ammo_shells', 960, 1480], + ['ammo_shells', 640, 120], ['ammo_shells', 1280, 120], ['ammo_bullets', 640, 1480], ['ammo_bullets', 1280, 1480], + ['armor_shard', 672, 800], ['armor_shard', 1248, 800], ['stimpack', 800, 200], ['stimpack', 1120, 200]], + }, + }; + for (const [key, a] of Object.entries(ARENAS)) { a.key = key; Q.worlds[key] = { brushes: a.brushes() }; } + const caseKey = id => id.split('/')[1]; + // 60 Hz clock (q2-arena@3): tick t ends at floor(t * 100 / 6) ms, so host frames are 16, 17, 17 ms and every sixth + // tick lands exactly on a 100 ms server frame. + const HZ = 60, msAt = t => Math.floor(t * 100 / 6); + const STARTER = { weapons: ['blaster', 'shotgun'], weapon: 'shotgun', ammo: { shells: 50 }, armor: null }; + + const CASES = [ + { id: 'quake2/supertank', name: 'Tracked Gun Carrier' }, + { id: 'quake2/hornet', name: 'Flying Gunship' }, + { id: 'quake2/makron', name: 'Twin-Cannon Mech → Armoured Pilot' }, + { id: 'quake2/tank_commander', name: 'Chain-Gun Heavy Trooper' }, + { id: 'quake2/gladiator', name: 'Blade-Arm Gunner' }, + { id: 'quake2/mutant', name: 'Clawed Pouncer' }, + ]; + Object.assign(M, { + id: 'quake2_remake', version: 'q2-arena@4', hz: HZ, maxSeconds: 300, dimension: '3d', renderer: 'webgl-quake2', + title: 'Quake II · Boss Arena', cases: CASES, tiers: TIERS, pointerLock: true, + controls: { + 'W / S': 'Forward / backward (cl_forwardspeed 200; Pmove maximum 300)', 'A / D': 'Strafe left / right', 'Shift': 'Run (+speed doubles movement input, capped by pm_maxspeed 300)', + 'mouse dx / dy': 'Turn / pitch (freelook; sensitivity 3 × m_yaw 0.022 = 0.066° per count; pitch ±89°)', 'Q / E': 'Turn left / right with keyboard (cl_yawspeed 140°/s)', + 'Space': 'Jump (+moveup; takeoff speed 270)', 'L': 'Crouch (+movedown; speed capped at 100)', 'J / LMB': 'Fire (hold for repeated shots)', + 'K / RMB / wheel up': 'Next weapon (weapnext)', 'R / wheel down': 'Previous weapon (weapprev)', + }, + }); + + class Game { + constructor(id, seed, d) { + this.id = id; this.key = caseKey(id); this.d = d; this.skill = skillOf(d); this.tier = tierOf(d); + this.t = 0; this.framenum = 0; this.ms = 0; this.dt = 0; this.outcome = null; this.events = []; this.fx = []; this.damageLog = []; + this.rnd = seed >>> 0; this.ai = { enemy_vis: false, enemy_infront: false, enemy_range: 0, enemy_yaw: 0 }; + this.sight_entity = -1; this.sight_entity_framenum = -10; this.sound_entity = -1; this.sound_entity_framenum = -10; this.sound2_entity = -1; this.sound2_entity_framenum = -10; + this.sight_client = -1; this.bossKilled = 0; this.fxSeq = 0; + const a = ARENAS[this.key]; + // Edict layout of a single-player level: 0 world, 1 the client, 2..9 the body queue (SP_worldspawn), then the + // map entities in map order, then the eight player trail markers (PlayerTrail_Init at the end of SpawnEntities). + this.ents = [Object.assign(Q.blankEdict(), { classname: 'worldspawn', solid: Q.SOLID_BSP, movetype: 'push' }), { inuse: false, freetime: 0, classname: 'client', solid: 0 }]; + for (let k = 0; k < 8; k++) { const i = Q.spawn(this); this.ents[i].classname = 'bodyque'; } + // ED_SpawnEntities inhibits entities by SPAWNFLAG_NOT_EASY / _NOT_MEDIUM / _NOT_HARD (skill 2 and 3 are hard). + const inhibit = this.skill === 0 ? 256 : this.skill === 1 ? 512 : 1024; + for (const [type, x, y, flags] of a.items) if (!((flags || 0) & inhibit)) Q.spawnItem(this, type, [x, y, 15]); + this.bossClass = a.boss.classname; + this.makronHealth = healthOf('monster_makron', d); + const final = a.boss.classname !== 'monster_jorg'; + this.boss = Q.spawnMonster(this, a.boss.classname, a.boss.origin, a.boss.yaw, { health: healthOf(a.boss.classname, d), engage: true, final }); + this.bossMax = this.ents[this.boss].health + (final ? 0 : this.makronHealth); + for (let k = 0; k < 8; k++) { const i = Q.spawn(this); this.ents[i].classname = 'player_trail'; } + Q.playerTrailInit(this); + // skill 0 starts with Quake II's new-game inventory (InitClientPersistant: Blaster, 100 health, no armor) plus + // the first weapon of unit 1, the Shotgun with 50 shells; higher skills carry the arena kit (BossBench practice + // loadouts). + const L = this.skill === 0 ? STARTER : a.loadout, inv = { jacket: 0, combat: 0, body: 0, shells: 0, bullets: 0, rockets: 0, cells: 0, slugs: 0 }; + for (const w of L.weapons) inv[w] = 1; + Object.assign(inv, L.ammo); if (L.armor) inv[L.armor[0]] = L.armor[1]; + Q.spawnPlayer(this, { origin: a.player.origin, yaw: a.player.yaw, inventory: inv, weapon: L.weapon }); + } + // One native tick (60 Hz, q2-arena@3): a host frame of 16 or 17 ms (SV_Frame draws one rand() per host frame), + // the client's usercmd for it (ClientThink -> Pmove with cmd.msec 16/17, the original client at cl_maxfps 60), + // then entity physics for this slice of time. Thinks still fire on their nextthink in ms, so monster frames, AI + // and weapon frames keep the original 100 ms server frame; the server-frame-only parts (ClientBeginServerFrame, + // AI_SetSightClient, old_origin, ClientEndServerFrame) run on the tick that crosses a 100 ms boundary. + update(keys, pressed, mouse) { + const prevMs = this.ms, nextMs = msAt(this.t + 1), frame = nextMs % Q.FRAMETIME_MS === 0; + this.dt = (nextMs - prevMs) / 1000; + this.fx = this.fx.filter(f => nextMs - f.t0 < (f.life || 300)); + if (this.damageLog.length > 64) this.damageLog = this.damageLog.slice(-64); + Q.rand(this); + const p = this.ents[1]; + if (p.health > 0) { + this.framenum = Math.floor(prevMs / Q.FRAMETIME_MS); // usercmds run before the tick advances level.time + const cmd = Q.buildUsercmd(this, keys, pressed, mouse, nextMs - prevMs); + Q.clientThink(this, cmd); + } + this.ms = nextMs; this.framenum = Math.floor(nextMs / Q.FRAMETIME_MS); + if (frame) this.sight_client = p.inuse && p.health > 0 ? 1 : -1; // AI_SetSightClient (one client) + for (let i = 0; i < this.ents.length; i++) { + const e = this.ents[i]; + if (!e.inuse) continue; + if (frame) e.old_origin = copy3(e.origin); + if (i === 0) continue; + if (i === 1) { if (frame) Q.clientBeginServerFrame(this); continue; } + if (e.movetype === 'step') Q.physicsStep(this, i); + else if (e.movetype === 'flymissile' || e.movetype === 'toss' || e.movetype === 'bounce') Q.physicsToss(this, i); + else Q.runThink(this, i); + } + if (frame) Q.clientEndServerFrame(this); + if (!this.outcome && p.health <= 0) this.outcome = 'loss'; + else if (!this.outcome && this.bossKilled) this.outcome = 'win'; + } + health() { + const p = this.ents[1]; + let boss = 0; + for (const e of this.ents) if (e.inuse && e.svflags & Q.SVF_MONSTER && e.deadflag !== Q.DEAD_DEAD) boss += Math.max(0, e.health); + if (this.bossClass === 'monster_jorg' && !this.ents.some(e => e.inuse && e.classname === 'monster_makron')) { + const jorg = this.ents[this.boss]; + boss = (jorg.inuse && jorg.classname === 'monster_jorg' && jorg.deadflag !== Q.DEAD_DEAD ? Math.max(0, jorg.health) : 0) + this.makronHealth; + } + // Stimpacks ignore max_health (HEALTH_IGNORE_MAX), so health can exceed 100; the reported maximum follows it so + // the normalized value stays in [0, 1] as the engine contract requires. + return [Math.max(0, p.health), Math.max(100, p.health), boss, this.bossMax]; + } + bossEnt() { // the boss currently fighting (Makron once he has been spawned) + const mak = this.ents.findIndex(e => e.inuse && e.classname === 'monster_makron'); + return mak >= 0 ? mak : this.boss; + } + } + // Cosmetic effects live in the state so renders are a pure function of it; they never touch the RNG. + Q.fx = (g, kind, origin, normal, extra) => { + const life = { tracer: 100, rail: 900, explosion: 500, blood: 300, puff: 300, spark: 250, mflash: 100, gibs: 1600, railcharge: 800, blasterhit: 250, bfgblast: 600 }[kind] || 300; + g.fx.push(Object.assign({ kind, o: copy3(origin), n: normal ? copy3(normal) : null, t0: g.ms, life, id: g.fxSeq++ }, extra || {})); + if (g.fx.length > 160) g.fx.splice(0, g.fx.length - 160); + }; + Object.assign(M, { + msAt, Game, arenas: ARENAS, health: HEALTH, skillOf, tierOf, healthOf, skillNames: SKILL_NAMES, + copyGame: g => Object.assign(Object.create(Game.prototype), N.copy(g)), + }); +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/index.html b/environments/games/web/games/quake2_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..26e20e4be9eda15ec260adaea45b0a43f25007c8 --- /dev/null +++ b/environments/games/web/games/quake2_remake/index.html @@ -0,0 +1,7 @@ + +Quake II · Boss Arena(q2-arena@4)
            +

            Quake II · Boss Arena

            1997 original rules, independently recreated from id Software GPL source · 60 Hz simulation (10 Hz server frames) · First-person WebGL

            Back to Game Lobby
            +
            Select a boss to start

            Replays save inputs and the seed, then simulate the match again and verify the final state. Scripted Demo reads internal state for verification; it does not start RL training.

            +
            +
            All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
            + diff --git a/environments/games/web/games/quake2_remake/input-hold.js b/environments/games/web/games/quake2_remake/input-hold.js new file mode 100644 index 0000000000000000000000000000000000000000..ddd345da59abd0bfe426b052dd508a251a5160f7 --- /dev/null +++ b/environments/games/web/games/quake2_remake/input-hold.js @@ -0,0 +1,30 @@ +/* The shared shell (_native/shell.js) latches a tapped key only until the next macrotask, so a tap released before + the next native tick is lost. Since q2-arena@3 the tick is 16.7 ms (60 Hz), so a 20 ms minimum hold is enough: + this page delays every key / pointer release until 20 ms after the press. Page input only: the rules, the policy interface and recordings are + unaffected (a recording stores the keys each tick actually saw). */ +(function () { + 'use strict'; + const HOLD = 20, down = new Map(), pdown = new Map(); + const tracked = e => /^(Key[WASDJKLQER]|Space|ShiftLeft|ShiftRight|Arrow(Up|Down|Left|Right))$/.test(e.code); + const late = new WeakSet(); + window.addEventListener('keydown', e => { if (tracked(e) && !down.has(e.code)) down.set(e.code, performance.now()); }, true); + window.addEventListener('keyup', e => { + if (late.has(e) || !tracked(e)) return; + const t0 = down.get(e.code); down.delete(e.code); + const wait = t0 === undefined ? 0 : HOLD - (performance.now() - t0); + if (wait <= 0) return; + e.stopImmediatePropagation(); e.preventDefault(); + const target = e.target || window; + setTimeout(() => { const ev = new KeyboardEvent('keyup', { code: e.code, key: e.key, bubbles: true, cancelable: true }); late.add(ev); target.dispatchEvent(ev); }, wait); + }, true); + window.addEventListener('pointerdown', e => { pdown.set(e.pointerId, performance.now()); }, true); + window.addEventListener('pointerup', e => { + if (late.has(e)) return; + const t0 = pdown.get(e.pointerId); pdown.delete(e.pointerId); + const wait = t0 === undefined ? 0 : HOLD - (performance.now() - t0); + if (wait <= 0) return; + e.stopImmediatePropagation(); + const target = e.target || window; + setTimeout(() => { const ev = new PointerEvent('pointerup', { bubbles: true, button: e.button, pointerId: e.pointerId }); late.add(ev); target.dispatchEvent(ev); }, wait); + }, true); +})(); diff --git a/environments/games/web/games/quake2_remake/manifest.json b/environments/games/web/games/quake2_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f2838ef29916360adcfd5631d066336b7aff6a42 --- /dev/null +++ b/environments/games/web/games/quake2_remake/manifest.json @@ -0,0 +1,42 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "quake2_remake", + "module": "Quake2Game", + "title": "Quake II: Boss Arena", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-quake2", + "rules": "q2-arena@4", + "cases": [ + "quake2/supertank", + "quake2/hornet", + "quake2/makron", + "quake2/tank_commander", + "quake2/gladiator", + "quake2/mutant" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "quake2_remake/q2core.js", + "quake2_remake/q2player.js", + "quake2_remake/q2monsters.js", + "quake2_remake/game.js", + "quake2_remake/scripted.js", + "quake2_remake/renderer3d.js", + "quake2_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "quake2_remake/q2core.js", + "quake2_remake/q2player.js", + "quake2_remake/q2monsters.js", + "quake2_remake/game.js", + "quake2_remake/scripted.js" + ], + "play_page": "web/games/quake2_remake/index.html", + "scripted_controller": "Quake2Game.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,0]}; deterministic look-ahead on copies (Quake2Game.oracle is an alias)", + "source": "https://github.com/id-Software/Quake-2/tree/372afde46e7defc9dd2d719a1732b8ace1fa096e (GPL-2.0)" +} diff --git a/environments/games/web/games/quake2_remake/q2core.js b/environments/games/web/games/quake2_remake/q2core.js new file mode 100644 index 0000000000000000000000000000000000000000..193e437d5538a98d9ff26e584f52bdb244d34ad5 --- /dev/null +++ b/environments/games/web/games/quake2_remake/q2core.js @@ -0,0 +1,262 @@ +/* Quake II (1997) boss arenas - core rules: units, Win32 CRT rand(), Quake II vector/angle helpers, the + axis-aligned brush world, box traces with CM_ClipBoxToBrush semantics and the edict slot allocator. + Independent JavaScript reimplementation written from id Software's GPL-2.0 source release + (github.com/id-Software/Quake-2, commit 372afde46e7defc9dd2d719a1732b8ace1fa096e): q_shared.c (AngleVectors, + anglemod), g_utils.c (vectoyaw, vectoangles, G_ProjectSource, G_Spawn, findradius), qcommon/cmodel.c + (CM_ClipBoxToBrush, CM_TestBoxInBrush), server/sv_world.c (SV_Trace, SV_ClipMoveToEntities). No engine code is + copied. Game data (pak files, models, textures, sounds, maps) is not part of the GPL release and none is used. */ +(function (root) { + 'use strict'; + const M = root.Quake2Game = root.Quake2Game || {}; + const Q = M.Q = M.Q || {}; + + // ---------------- constants (q_shared.h / g_local.h) ---------------- + Q.FRAMETIME_MS = 100; // g_local.h FRAMETIME 0.1, sv_main.c sv.time = framenum*100 + Q.CONTENTS_SOLID = 1; Q.CONTENTS_WINDOW = 2; Q.CONTENTS_LAVA = 8; Q.CONTENTS_SLIME = 16; Q.CONTENTS_WATER = 32; + Q.CONTENTS_PLAYERCLIP = 0x10000; Q.CONTENTS_MONSTERCLIP = 0x20000; Q.CONTENTS_MONSTER = 0x2000000; Q.CONTENTS_DEADMONSTER = 0x4000000; + Q.MASK_SOLID = Q.CONTENTS_SOLID | Q.CONTENTS_WINDOW; + Q.MASK_PLAYERSOLID = Q.CONTENTS_SOLID | Q.CONTENTS_PLAYERCLIP | Q.CONTENTS_WINDOW | Q.CONTENTS_MONSTER; + Q.MASK_MONSTERSOLID = Q.CONTENTS_SOLID | Q.CONTENTS_MONSTERCLIP | Q.CONTENTS_WINDOW | Q.CONTENTS_MONSTER; + Q.MASK_SHOT = Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_WINDOW | Q.CONTENTS_DEADMONSTER; + Q.MASK_OPAQUE = Q.CONTENTS_SOLID | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA; + Q.MASK_WATER = Q.CONTENTS_WATER | Q.CONTENTS_LAVA | Q.CONTENTS_SLIME; + Q.SOLID_NOT = 0; Q.SOLID_TRIGGER = 1; Q.SOLID_BBOX = 2; Q.SOLID_BSP = 3; + Q.SVF_NOCLIENT = 1; Q.SVF_DEADMONSTER = 2; Q.SVF_MONSTER = 4; + Q.FL_FLY = 1; Q.FL_SWIM = 2; Q.FL_IMMUNE_LASER = 4; Q.FL_PARTIALGROUND = 256; Q.FL_NO_KNOCKBACK = 2048; + Q.DAMAGE_NO = 0; Q.DAMAGE_YES = 1; Q.DAMAGE_AIM = 2; + Q.DAMAGE_RADIUS = 1; Q.DAMAGE_NO_ARMOR = 2; Q.DAMAGE_ENERGY = 4; Q.DAMAGE_NO_KNOCKBACK = 8; Q.DAMAGE_BULLET = 16; + Q.DEAD_NO = 0; Q.DEAD_DYING = 1; Q.DEAD_DEAD = 2; + Q.STEPSIZE = 18; Q.MELEE_DISTANCE = 80; Q.DIST_EPSILON = 0.03125; + Q.RANGE_MELEE = 0; Q.RANGE_NEAR = 1; Q.RANGE_MID = 2; Q.RANGE_FAR = 3; + Q.SV_GRAVITY = 800; Q.SV_MAXVELOCITY = 2000; Q.SV_STOPSPEED = 100; Q.SV_FRICTION = 6; + Q.YAW = 1; Q.PITCH = 0; Q.ROLL = 2; + + // ---------------- Win32 CRT rand() (the shipped 1997 build is MSVC; Quake II never calls srand) ---------------- + // holdrand = holdrand * 214013 + 2531011; return (holdrand >> 16) & 0x7fff. The BossBench engine seed is the + // initial holdrand. random() and crandom() are the g_local.h macros. + Q.rand = g => { g.rnd = (Math.imul(g.rnd, 214013) + 2531011) >>> 0; return (g.rnd >>> 16) & 0x7fff; }; + Q.random = g => (Q.rand(g) & 0x7fff) / 0x7fff; + Q.crandom = g => 2 * (Q.random(g) - 0.5); + Q.drawRand = (g, n) => { for (let i = 0; i < n; i++) Q.rand(g); }; // RNG draws of cosmetic effects (debris/gibs) + + // ---------------- vectors (vec3_t as [x, y, z]) ---------------- + // Deterministic trigonometry adapted from fdlibm. See LICENSE.fdlibm. + // The kernels use arithmetic operations and Cody-Waite range reduction for |x| < 2^20. + const PIO2_1 = 1.57079632673412561417e+00, PIO2_1T = 6.07710050650619224932e-11, INVPIO2 = 6.36619772367581382433e-01; + const S1 = -1.66666666666666324348e-01, S2 = 8.33333333332248946124e-03, S3 = -1.98412698298579493134e-04, + S4 = 2.75573137070700676789e-06, S5 = -2.50507602534068634195e-08, S6 = 1.58969099521155010221e-10; + const C1 = 4.16666666666666019037e-02, C2 = -1.38888888888741095749e-03, C3 = 2.48015872894767294178e-05, + C4 = -2.75573143513906633035e-07, C5 = 2.08757232129817482790e-09, C6 = -1.13596475577881948265e-11; + const ksin = x => { const z = x * x; return x + x * z * (S1 + z * (S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))))); }; + const kcos = x => { const z = x * x; return 1 - 0.5 * z + z * z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))))); }; + function reduce(x) { const k = Math.round(x * INVPIO2); return [k & 3, (x - k * PIO2_1) - k * PIO2_1T]; } + Q.sin = x => { const [q, r] = reduce(x); return q === 0 ? ksin(r) : q === 1 ? kcos(r) : q === 2 ? -ksin(r) : -kcos(r); }; + Q.cos = x => { const [q, r] = reduce(x); return q === 0 ? kcos(r) : q === 1 ? -ksin(r) : q === 2 ? -kcos(r) : ksin(r); }; + const ATANHI = [4.63647609000806093515e-01, 7.85398163397448278999e-01, 9.82793723247329054082e-01, 1.57079632679489655800e+00]; + const ATANLO = [2.26987774529616870924e-17, 3.06161699786838301793e-17, 1.39033110312309984516e-17, 6.12323399573676603587e-17]; + const AT = [3.33333333333329318027e-01, -1.99999999998764832476e-01, 1.42857142725034663711e-01, -1.11111104054623557880e-01, + 9.09088713343650656196e-02, -7.69187620504482999495e-02, 6.66107313738753120669e-02, -5.83357013379057348645e-02, + 4.97687799461593236017e-02, -3.65315727442169155270e-02, 1.62858201153657823623e-02]; + function atan(x) { + const neg = x < 0; let a = neg ? -x : x, id = -1; + if (a !== a) return a; + if (a >= 7.378697629483821e+19) return neg ? -(ATANHI[3] + ATANLO[3]) : ATANHI[3] + ATANLO[3]; // >= 2^66 + if (a < 0.4375) { if (a < 1.862645149230957e-09) return x; } + else if (a < 1.1875) { if (a < 0.6875) { id = 0; a = (2 * a - 1) / (2 + a); } else { id = 1; a = (a - 1) / (a + 1); } } + else if (a < 2.4375) { id = 2; a = (a - 1.5) / (1 + 1.5 * a); } + else { id = 3; a = -1 / a; } + const z = a * a, w = z * z; + const s1 = z * (AT[0] + w * (AT[2] + w * (AT[4] + w * (AT[6] + w * (AT[8] + w * AT[10]))))); + const s2 = w * (AT[1] + w * (AT[3] + w * (AT[5] + w * (AT[7] + w * AT[9])))); + if (id < 0) { const r = a - a * (s1 + s2); return neg ? -r : r; } + const r = ATANHI[id] - ((a * (s1 + s2) - ATANLO[id]) - a); + return neg ? -r : r; + } + const PI = 3.1415926535897931160e+00, PI_LO = 1.2246467991473531772e-16; + Q.atan2 = (y, x) => { + if (x !== x || y !== y) return NaN; + if (y === 0) return (x > 0 || (x === 0 && 1 / x > 0)) ? y : (1 / y > 0 ? PI : -PI); + if (x === 0) return y > 0 ? PI / 2 : -PI / 2; + const z = atan(Math.abs(y / x)); + if (x > 0) return y > 0 ? z : -z; + return y > 0 ? PI - (z - PI_LO) : (z - PI_LO) - PI; + }; + const DEG = Math.PI / 180; + Q.add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; + Q.sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + Q.scale = (a, s) => [a[0] * s, a[1] * s, a[2] * s]; + Q.ma = (a, s, b) => [a[0] + s * b[0], a[1] + s * b[1], a[2] + s * b[2]]; // VectorMA + Q.dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + Q.len = a => Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); + Q.cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + Q.norm = a => { const l = Q.len(a); return l ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0]; }; // VectorNormalize + Q.eq = (a, b) => a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; + Q.copy3 = a => [a[0], a[1], a[2]]; + Q.angleVectors = angles => { + const y = angles[1] * DEG, p = angles[0] * DEG, r = angles[2] * DEG; + const sy = Q.sin(y), cy = Q.cos(y), sp = Q.sin(p), cp = Q.cos(p), sr = Q.sin(r), cr = Q.cos(r); + return { + forward: [cp * cy, cp * sy, -sp], + right: [-1 * sr * sp * cy + -1 * cr * -sy, -1 * sr * sp * sy + -1 * cr * cy, -1 * sr * cp], + up: [cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp], + }; + }; + // anglemod: 16-bit wrap; vectoyaw / vectoangles truncate to whole degrees exactly as g_utils.c does. + Q.anglemod = a => (360 / 65536) * (Math.trunc(a * (65536 / 360)) & 65535); + Q.vectoyaw = v => { + if (v[0] === 0) return v[1] > 0 ? 90 : v[1] < 0 ? -90 : 0; + let yaw = Math.trunc(Q.atan2(v[1], v[0]) * 180 / Math.PI); + if (yaw < 0) yaw += 360; + return yaw; + }; + Q.vectoangles = v => { + let yaw, pitch; + if (v[1] === 0 && v[0] === 0) { yaw = 0; pitch = v[2] > 0 ? 90 : 270; } + else { + if (v[0]) yaw = Math.trunc(Q.atan2(v[1], v[0]) * 180 / Math.PI); else yaw = v[1] > 0 ? 90 : -90; + if (yaw < 0) yaw += 360; + const forward = Math.sqrt(v[0] * v[0] + v[1] * v[1]); + pitch = Math.trunc(Q.atan2(v[2], forward) * 180 / Math.PI); + if (pitch < 0) pitch += 360; + } + return [-pitch, yaw, 0]; + }; + Q.projectSource = (point, d, forward, right) => [ // G_ProjectSource + point[0] + forward[0] * d[0] + right[0] * d[1], + point[1] + forward[1] * d[0] + right[1] * d[1], + point[2] + forward[2] * d[0] + right[2] * d[1] + d[2]]; + Q.ANGLE2SHORT = x => { const s = Math.trunc(x * 65536 / 360) & 65535; return s > 32767 ? s - 65536 : s; }; + Q.SHORT2ANGLE = x => x * (360 / 65536); + + // ---------------- world: axis-aligned brushes ---------------- + // A brush is {mins, maxs, contents, mat}. The world of a case is static, so it is kept outside the game state + // (looked up by case key) and never copied or hashed per tick. + Q.worlds = {}; + // CM_ClipBoxToBrush on the six axial planes of one box brush, with the trace box pushed into each plane. + function clipBoxToBox(tr, start, end, mins, maxs, bmin, bmax, contents, isPoint, sky) { + let enterfrac = -1, leavefrac = 1, clip = -1, getout = false, startout = false; + for (let k = 0; k < 6; k++) { + const axis = k >> 1, positive = (k & 1) === 0; + let dist = positive ? bmax[axis] : -bmin[axis]; + if (!isPoint) dist -= positive ? mins[axis] : -maxs[axis]; + const d1 = (positive ? start[axis] : -start[axis]) - dist, d2 = (positive ? end[axis] : -end[axis]) - dist; + if (d2 > 0) getout = true; + if (d1 > 0) startout = true; + if (d1 > 0 && d2 >= d1) return false; // completely in front of this face + if (d1 <= 0 && d2 <= 0) continue; + if (d1 > d2) { const f = (d1 - Q.DIST_EPSILON) / (d1 - d2); if (f > enterfrac) { enterfrac = f; clip = k; } } + else { const f = (d1 + Q.DIST_EPSILON) / (d1 - d2); if (f < leavefrac) leavefrac = f; } + } + if (!startout) { tr.startsolid = true; if (!getout) tr.allsolid = true; return true; } + if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < tr.fraction) { + if (enterfrac < 0) enterfrac = 0; + tr.fraction = enterfrac; const axis = clip >> 1, n = [0, 0, 0]; n[axis] = (clip & 1) === 0 ? 1 : -1; + tr.normal = n; tr.contents = contents; tr.sky = !!sky; return true; + } + return false; + } + // CM_TestBoxInBrush (start == end): inside unless outside some pushed plane. + function testBoxInBox(tr, p, mins, maxs, bmin, bmax, contents) { + for (let axis = 0; axis < 3; axis++) { + if (p[axis] + mins[axis] - bmax[axis] > 0) return false; // pushed +axis plane: dot(p) - (bmax - mins) + if (bmin[axis] - (p[axis] + maxs[axis]) > 0) return false; + } + tr.startsolid = tr.allsolid = true; tr.fraction = 0; tr.contents = contents; return true; + } + function boxTrace(brushes, start, mins, maxs, end, mask) { + const tr = { fraction: 1, startsolid: false, allsolid: false, normal: [0, 0, 0], contents: 0, ent: 0, sky: false }; + const isPoint = !mins[0] && !mins[1] && !mins[2] && !maxs[0] && !maxs[1] && !maxs[2]; + const position = start[0] === end[0] && start[1] === end[1] && start[2] === end[2]; + for (const b of brushes) { + if (!(b.contents & mask)) continue; + if (position) { if (testBoxInBox(tr, start, mins, maxs, b.mins, b.maxs, b.contents)) return tr; continue; } + clipBoxToBox(tr, start, end, mins, maxs, b.mins, b.maxs, b.contents, isPoint, b.sky); + if (!tr.fraction) return tr; // CM_TraceToLeaf stops once something is hit at 0 + } + return tr; + } + const Z3 = [0, 0, 0]; + // SV_Trace: world first, then SOLID_BBOX edicts (owner/passent rules of SV_ClipMoveToEntities). + Q.trace = (g, start, mins, maxs, end, passent, mask) => { + mins = mins || Z3; maxs = maxs || Z3; + const tr = boxTrace(Q.worlds[g.key].brushes, start, mins, maxs, end, mask); + if (tr.fraction !== 0 && (mask & (Q.CONTENTS_MONSTER | Q.CONTENTS_DEADMONSTER))) { + const pass = passent >= 0 ? g.ents[passent] : null; + for (let i = 1; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse || e.solid !== Q.SOLID_BBOX || i === passent) continue; + if (tr.allsolid) break; + if (pass && (e.owner === passent || pass.owner === i)) continue; + if (!(mask & Q.CONTENTS_DEADMONSTER) && (e.svflags & Q.SVF_DEADMONSTER)) continue; + if (!(mask & Q.CONTENTS_MONSTER)) continue; + const t2 = { fraction: 1, startsolid: false, allsolid: false, normal: [0, 0, 0], contents: 0, ent: i }; + const bmin = Q.add(e.origin, e.mins), bmax = Q.add(e.origin, e.maxs); + if (start[0] === end[0] && start[1] === end[1] && start[2] === end[2]) testBoxInBox(t2, start, mins, maxs, bmin, bmax, Q.CONTENTS_MONSTER); + else clipBoxToBox(t2, start, end, mins, maxs, bmin, bmax, Q.CONTENTS_MONSTER, !mins[0] && !mins[1] && !mins[2] && !maxs[0] && !maxs[1] && !maxs[2]); + if (t2.allsolid || t2.startsolid || t2.fraction < tr.fraction) { + const wasStart = tr.startsolid; + tr.fraction = t2.fraction; tr.normal = t2.normal; tr.contents = t2.contents; tr.ent = i; tr.allsolid = t2.allsolid; tr.sky = false; + tr.startsolid = wasStart || t2.startsolid; + } else if (t2.startsolid) tr.startsolid = true; + } + } + tr.endpos = tr.fraction === 1 ? Q.copy3(end) : [start[0] + tr.fraction * (end[0] - start[0]), start[1] + tr.fraction * (end[1] - start[1]), start[2] + tr.fraction * (end[2] - start[2])]; + return tr; + }; + Q.pointcontents = (g, p) => { + let c = 0; + for (const b of Q.worlds[g.key].brushes) + if (p[0] >= b.mins[0] && p[0] <= b.maxs[0] && p[1] >= b.mins[1] && p[1] <= b.maxs[1] && p[2] >= b.mins[2] && p[2] <= b.maxs[2]) c |= b.contents; + return c; + }; + // SV_LinkEdict absolute bounds, expanded by one unit on every side. + Q.absmin = e => [e.origin[0] + e.mins[0] - 1, e.origin[1] + e.mins[1] - 1, e.origin[2] + e.mins[2] - 1]; + Q.absmax = e => [e.origin[0] + e.maxs[0] + 1, e.origin[1] + e.maxs[1] + 1, e.origin[2] + e.maxs[2] + 1]; + Q.boxesOverlap = (a, b) => { + const amin = Q.absmin(a), amax = Q.absmax(a), bmin = Q.absmin(b), bmax = Q.absmax(b); + return amin[0] <= bmax[0] && amax[0] >= bmin[0] && amin[1] <= bmax[1] && amax[1] >= bmin[1] && amin[2] <= bmax[2] && amax[2] >= bmin[2]; + }; + Q.center = e => [e.origin[0] + (e.mins[0] + e.maxs[0]) * 0.5, e.origin[1] + (e.mins[1] + e.maxs[1]) * 0.5, e.origin[2] + (e.mins[2] + e.maxs[2]) * 0.5]; + // findradius: inuse, not SOLID_NOT, centre of the box within rad. + Q.findradius = (g, org, rad) => { + const out = []; + for (let i = 1; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse || e.solid === Q.SOLID_NOT) continue; + if (Q.len(Q.sub(org, Q.center(e))) > rad) continue; + out.push(i); + } + return out; + }; + + // ---------------- edicts ---------------- + // Slot 0 is the world, slot 1 the player (maxclients 1). G_Spawn reuses a free slot freed more than 0.5 s ago + // (or at level start); the slot index decides the think order inside G_RunFrame. + Q.blankEdict = () => ({ + inuse: true, classname: '', origin: [0, 0, 0], old_origin: [0, 0, 0], velocity: [0, 0, 0], avelocity: [0, 0, 0], angles: [0, 0, 0], + mins: [0, 0, 0], maxs: [0, 0, 0], solid: Q.SOLID_NOT, clipmask: 0, svflags: 0, flags: 0, movetype: 'none', owner: -1, enemy: -1, + takedamage: 0, health: 0, max_health: 0, mass: 0, deadflag: 0, think: null, nextthink: 0, touch: null, groundentity: -1, + freetime: 0, viewheight: 0, frame: 0, dmg: 0, radius_dmg: 0, dmg_radius: 0, count: 0, spawnflags: 0, gravity: 1, waterlevel: 0, linkcount: 0, + }); + Q.spawn = g => { + for (let i = 2; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse && (e.freetime < 2000 || g.ms - e.freetime > 500)) { g.ents[i] = Q.blankEdict(); return i; } + } + g.ents.push(Q.blankEdict()); return g.ents.length - 1; + }; + Q.freeEdict = (g, i) => { g.ents[i] = { inuse: false, freetime: g.ms, classname: 'freed', solid: Q.SOLID_NOT }; }; + // SV_RunThink: nextthink in ms; think when nextthink <= level.time (+1 ms tolerance of the 0.001 s epsilon). + Q.runThink = (g, i) => { + const e = g.ents[i]; + if (!e.nextthink || e.nextthink <= 0 || e.nextthink > g.ms + 1) return true; + e.nextthink = 0; + const fn = Q.THINK[e.think]; + if (!fn) throw Error('NULL think ' + e.think); + fn(g, i); + return false; + }; + Q.THINK = { G_FreeEdict: (g, i) => Q.freeEdict(g, i) }; + Q.TOUCH = {}; + Q.event = (g, type, data) => { g.events.push(Object.assign({ type, t: g.t }, data || {})); }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/q2monsters.js b/environments/games/web/games/quake2_remake/q2monsters.js new file mode 100644 index 0000000000000000000000000000000000000000..a0eb058d7d4ea0e8d18cbc730d573771900aded7 --- /dev/null +++ b/environments/games/web/games/quake2_remake/q2monsters.js @@ -0,0 +1,1181 @@ +/* Quake II (1997) boss arenas - monsters: the monster framework (g_monster.c M_MoveFrame, monster_think, + monster_start_go, M_CheckGround, monster_fire_*; g_ai.c ai_stand / ai_run / ai_charge / ai_move, + ai_checkattack, M_CheckAttack, FoundTarget / HuntTarget, visible / infront / range; m_move.c SV_movestep for + walking and flying monsters, M_CheckBottom, M_ChangeYaw, SV_StepDirection, SV_NewChaseDir, M_MoveToGoal; + g_phys.c SV_Physics_Step / SV_FlyMove; g_combat.c M_ReactToDamage) and the six boss fights of this game: + Super Tank (m_supertank.c, models/monsters/boss1), Hornet (m_boss2.c, boss2), Jorg + Makron (m_boss31.c / + m_boss32.c, boss3), Tank Commander (m_tank.c), Gladiator (m_gladiator.c) and Mutant (m_mutant.c). Move tables keep the original absolute frame numbers (m_*.h) because the code tests them. + Independent reimplementation from the GPL-2.0 source release, commit 372afde46e7defc9dd2d719a1732b8ace1fa096e. */ +(function (root) { + 'use strict'; + const M = root.Quake2Game, Q = M.Q; + const { add, sub, scale, ma, dot, len, norm, copy3 } = Q; + const AI_STAND_GROUND = 1, AI_TEMP_STAND_GROUND = 2, AI_SOUND_TARGET = 4, AI_LOST_SIGHT = 8, AI_PURSUIT_LAST_SEEN = 16, + AI_PURSUE_NEXT = 32, AI_PURSUE_TEMP = 64, AI_HOLD_FRAME = 128, AI_GOOD_GUY = 256, AI_BRUTAL = 512, AI_DUCKED = 2048, AI_COMBAT_POINT = 4096; + const AS_STRAIGHT = 1, AS_SLIDING = 2, AS_MELEE = 3, AS_MISSILE = 4; + Q.AS = { AS_STRAIGHT, AS_SLIDING, AS_MELEE, AS_MISSILE }; + + // ---------------- move tables ---------------- + // name: [firstframe, lastframe, frames, endfunc]; frame token [:][x], ai s/w/r/c/m/t/n. + const AI_OF = { s: 'stand', w: 'walk', r: 'run', c: 'charge', m: 'move', t: 'turn', n: null }; + function moves(spec) { + const out = {}; + for (const [name, [first, last, frames, end]] of Object.entries(spec)) { + const list = []; + for (const tok of frames.trim().split(/\s+/)) { + const m = /^([swrcmtn])(-?\d+(?:\.\d+)?)(?::(\w+?))?(?:x(\d+))?$/.exec(tok); + if (!m) throw Error('bad frame token ' + tok); + for (let n = Number(m[4] || 1); n > 0; n--) list.push([AI_OF[m[1]], Number(m[2]), m[3] && m[3] !== 'NULL' ? m[3] : null]); + } + if (list.length !== last - first + 1) throw Error('frame count ' + name); + out[name] = { first, last, frames: list, end }; + } + return out; + } + const DEFS = Q.MONSTERS = {}; + + // ---------------- helpers (g_ai.c) ---------------- + const eye = e => [e.origin[0], e.origin[1], e.origin[2] + e.viewheight]; + Q.visible = (g, self, other) => { + const tr = Q.trace(g, eye(g.ents[self]), null, null, eye(g.ents[other]), self, Q.MASK_OPAQUE); + return tr.fraction === 1.0; + }; + Q.visiblePoint = (g, self, point) => Q.trace(g, eye(g.ents[self]), null, null, point, self, Q.MASK_OPAQUE).fraction === 1.0; + Q.infront = (g, self, other) => { + const s = g.ents[self], forward = Q.angleVectors(s.angles).forward; + return dot(norm(sub(g.ents[other].origin, s.origin)), forward) > 0.3; + }; + Q.range = (g, self, other) => { + const l = len(sub(g.ents[self].origin, g.ents[other].origin)); + return l < Q.MELEE_DISTANCE ? Q.RANGE_MELEE : l < 500 ? Q.RANGE_NEAR : l < 1000 ? Q.RANGE_MID : Q.RANGE_FAR; + }; + const link = (g, i) => { g.ents[i].linkcount++; }; + const def = e => DEFS[e.classname]; + const setMove = (e, name) => { e.monsterinfo.currentmove = name; }; + const call = (g, i, fn, ...args) => { const f = def(g.ents[i])[fn]; if (f) f(g, i, ...args); }; + + // ---------------- movement (m_move.c) ---------------- + function checkBottom(g, i) { + const e = g.ents[i], mins = add(e.origin, e.mins), maxs = add(e.origin, e.maxs); + let easy = true; + for (let x = 0; x <= 1 && easy; x++) for (let y = 0; y <= 1; y++) { + const p = [x ? maxs[0] : mins[0], y ? maxs[1] : mins[1], mins[2] - 1]; + if (Q.pointcontents(g, p) !== Q.CONTENTS_SOLID) { easy = false; break; } + } + if (easy) return true; + const start = [(mins[0] + maxs[0]) * 0.5, (mins[1] + maxs[1]) * 0.5, mins[2]], stop = [start[0], start[1], start[2] - 2 * Q.STEPSIZE]; + let tr = Q.trace(g, start, null, null, stop, i, Q.MASK_MONSTERSOLID); + if (tr.fraction === 1.0) return false; + const mid = tr.endpos[2]; + for (let x = 0; x <= 1; x++) for (let y = 0; y <= 1; y++) { + const s = [x ? maxs[0] : mins[0], y ? maxs[1] : mins[1], mins[2]], t = [s[0], s[1], stop[2]]; + tr = Q.trace(g, s, null, null, t, i, Q.MASK_MONSTERSOLID); + if (tr.fraction === 1.0 || mid - tr.endpos[2] > Q.STEPSIZE) return false; + } + return true; + } + function movestep(g, i, move, relink) { + const e = g.ents[i], oldorg = copy3(e.origin); + if (e.flags & (Q.FL_SWIM | Q.FL_FLY)) { + for (let k = 0; k < 2; k++) { + const neworg = add(e.origin, move); + if (k === 0 && e.enemy >= 0) { + if (e.goalentity < 0) e.goalentity = e.enemy; + const goal = g.ents[e.goalentity], dz = e.origin[2] - goal.origin[2]; + if (goal.client) { if (dz > 40) neworg[2] -= 8; if (dz < 30) neworg[2] += 8; } + else { if (dz > 8) neworg[2] -= 8; else if (dz > 0) neworg[2] -= dz; else if (dz < -8) neworg[2] += 8; else neworg[2] += dz; } + } + const tr = Q.trace(g, e.origin, e.mins, e.maxs, neworg, i, Q.MASK_MONSTERSOLID); + if (tr.fraction === 1) { e.origin = copy3(tr.endpos); if (relink) link(g, i); return true; } + if (e.enemy < 0) break; + } + return false; + } + const stepsize = (e.monsterinfo.aiflags & 0) ? 1 : Q.STEPSIZE; + const neworg = add(e.origin, move); neworg[2] += stepsize; + const end = copy3(neworg); end[2] -= stepsize * 2; + let tr = Q.trace(g, neworg, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID); + if (tr.allsolid) return false; + if (tr.startsolid) { + neworg[2] -= stepsize; + tr = Q.trace(g, neworg, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID); + if (tr.allsolid || tr.startsolid) return false; + } + if (tr.fraction === 1) { + if (e.flags & Q.FL_PARTIALGROUND) { e.origin = add(e.origin, move); if (relink) link(g, i); e.groundentity = -1; return true; } + return false; // walked off an edge + } + e.origin = copy3(tr.endpos); + if (!checkBottom(g, i)) { + if (e.flags & Q.FL_PARTIALGROUND) { if (relink) link(g, i); return true; } + e.origin = oldorg; return false; + } + e.flags &= ~Q.FL_PARTIALGROUND; + e.groundentity = tr.ent; + if (relink) link(g, i); + return true; + } + Q.changeYaw = (g, i) => { // M_ChangeYaw + const e = g.ents[i], current = Q.anglemod(e.angles[1]), ideal = e.ideal_yaw; + if (current === ideal) return; + let move = ideal - current; const speed = e.yaw_speed; + if (ideal > current) { if (move >= 180) move -= 360; } else { if (move <= -180) move += 360; } + if (move > 0) { if (move > speed) move = speed; } else { if (move < -speed) move = -speed; } + e.angles[1] = Q.anglemod(current + move); + }; + function stepDirection(g, i, yaw, dist) { + const e = g.ents[i]; + e.ideal_yaw = yaw; Q.changeYaw(g, i); + const r = yaw * Math.PI * 2 / 360, move = [Q.cos(r) * dist, Q.sin(r) * dist, 0], old = copy3(e.origin); + if (movestep(g, i, move, false)) { + const delta = e.angles[1] - e.ideal_yaw; + if (delta > 45 && delta < 315) e.origin = old; // not turned far enough, so don't take the step + link(g, i); + return true; + } + link(g, i); + return false; + } + function newChaseDir(g, i, goal, dist) { + const e = g.ents[i]; + if (goal < 0) return; + const olddir = Q.anglemod(Math.trunc(e.ideal_yaw / 45) * 45), turnaround = Q.anglemod(olddir - 180); + const gorg = g.ents[goal].origin, deltax = gorg[0] - e.origin[0], deltay = gorg[1] - e.origin[1], d = [0, 0, 0]; + d[1] = deltax > 10 ? 0 : deltax < -10 ? 180 : -1; + d[2] = deltay < -10 ? 270 : deltay > 10 ? 90 : -1; + if (d[1] !== -1 && d[2] !== -1) { + const tdir = d[1] === 0 ? (d[2] === 90 ? 45 : 315) : (d[2] === 90 ? 135 : 215); + if (tdir !== turnaround && stepDirection(g, i, tdir, dist)) return; + } + if (((Q.rand(g) & 3) & 1) || Math.abs(Math.trunc(deltay)) > Math.abs(Math.trunc(deltax))) { const t = d[1]; d[1] = d[2]; d[2] = t; } + if (d[1] !== -1 && d[1] !== turnaround && stepDirection(g, i, d[1], dist)) return; + if (d[2] !== -1 && d[2] !== turnaround && stepDirection(g, i, d[2], dist)) return; + if (olddir !== -1 && stepDirection(g, i, olddir, dist)) return; + if (Q.rand(g) & 1) { for (let t = 0; t <= 315; t += 45) if (t !== turnaround && stepDirection(g, i, t, dist)) return; } + else { for (let t = 315; t >= 0; t -= 45) if (t !== turnaround && stepDirection(g, i, t, dist)) return; } + if (turnaround !== -1 && stepDirection(g, i, turnaround, dist)) return; + e.ideal_yaw = olddir; // can't move + if (!checkBottom(g, i)) e.flags |= Q.FL_PARTIALGROUND; + } + function closeEnough(g, i, goal, dist) { + const e = g.ents[i], t = g.ents[goal], amin = Q.absmin(e), amax = Q.absmax(e), gmin = Q.absmin(t), gmax = Q.absmax(t); + for (let k = 0; k < 3; k++) { if (gmin[k] > amax[k] + dist) return false; if (gmax[k] < amin[k] - dist) return false; } + return true; + } + function moveToGoal(g, i, dist) { + const e = g.ents[i], goal = e.goalentity; + if (e.groundentity < 0 && !(e.flags & (Q.FL_FLY | Q.FL_SWIM))) return; + if (e.enemy >= 0 && closeEnough(g, i, e.enemy, dist)) return; + if ((Q.rand(g) & 3) === 1 || !stepDirection(g, i, e.ideal_yaw, dist)) { if (g.ents[i].inuse) newChaseDir(g, i, goal, dist); } + } + const walkmove = (g, i, yaw, dist) => { + const e = g.ents[i]; + if (e.groundentity < 0 && !(e.flags & (Q.FL_FLY | Q.FL_SWIM))) return false; + const r = yaw * Math.PI * 2 / 360; + return movestep(g, i, [Q.cos(r) * dist, Q.sin(r) * dist, 0], true); + }; + Q.walkmove = walkmove; + function checkGround(g, i) { // M_CheckGround + const e = g.ents[i]; + if (e.flags & (Q.FL_SWIM | Q.FL_FLY)) return; + if (e.velocity[2] > 100) { e.groundentity = -1; return; } + const point = [e.origin[0], e.origin[1], e.origin[2] - 0.25]; + const tr = Q.trace(g, e.origin, e.mins, e.maxs, point, i, Q.MASK_MONSTERSOLID); + if (tr.normal[2] < 0.7 && !tr.startsolid) { e.groundentity = -1; return; } + if (!tr.startsolid && !tr.allsolid) { e.origin = copy3(tr.endpos); e.groundentity = tr.ent; e.velocity[2] = 0; } + } + + // ---------------- AI (g_ai.c) ---------------- + function foundTarget(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + if (g.ents[e.enemy].client) { g.sight_entity = i; g.sight_entity_framenum = g.framenum; } + e.show_hostile = g.ms + 1000; + mi.last_sighting = copy3(g.ents[e.enemy].origin); mi.trail_time = g.ms; + huntTarget(g, i); + } + function huntTarget(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + e.goalentity = e.enemy; + if (mi.aiflags & AI_STAND_GROUND) call(g, i, 'stand'); else call(g, i, 'run'); + e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin)); + if (!(mi.aiflags & AI_STAND_GROUND)) mi.attack_finished = g.ms + 1000; // AttackFinished (self, 1) + } + // FindTarget: the sight entity (a monster that just found the player), the player's own noise (firing, jumping), + // impact noise for idle monsters, else the sight client checked by range / visibility / facing. Arena light is + // above light_level 5 everywhere, the arena is one PHS / area, and no monster here is an ambusher. + function findTarget(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + let client, heardit = false; + if (g.sight_entity_framenum >= g.framenum - 1) { + client = g.sight_entity; + if (g.ents[client].enemy === e.enemy) return false; + } else if (g.sound_entity_framenum >= g.framenum - 1) { client = g.sound_entity; heardit = true; } + else if (e.enemy < 0 && g.sound2_entity_framenum >= g.framenum - 1) { client = g.sound2_entity; heardit = true; } + else { client = g.sight_client; if (client < 0) return false; } + const c = g.ents[client]; + if (!c || !c.inuse) return false; + if (client === e.enemy) return true; + if (c.client) { /* FL_NOTARGET is never set */ } + else if (c.svflags & Q.SVF_MONSTER) { if (c.enemy < 0) return false; } + else if (!heardit) return false; + if (!heardit) { + const r = Q.range(g, i, client); + if (r === Q.RANGE_FAR) return false; + if (!Q.visible(g, i, client)) return false; + if (r === Q.RANGE_NEAR) { if ((c.show_hostile || 0) < g.ms && !Q.infront(g, i, client)) return false; } + else if (r === Q.RANGE_MID) { if (!Q.infront(g, i, client)) return false; } + e.enemy = client; + if (c.classname !== 'player_noise') { + mi.aiflags &= ~AI_SOUND_TARGET; + if (!g.ents[e.enemy].client) { + e.enemy = g.ents[e.enemy].enemy; + if (e.enemy < 0 || !g.ents[e.enemy].client) { e.enemy = -1; return false; } + } + } + } else { + const temp = sub(c.origin, e.origin); + if (len(temp) > 1000) return false; // too far to hear + e.ideal_yaw = Q.vectoyaw(temp); Q.changeYaw(g, i); + mi.aiflags |= AI_SOUND_TARGET; + e.enemy = client; + } + foundTarget(g, i); + if (!(mi.aiflags & AI_SOUND_TARGET)) call(g, i, 'sight'); + return true; + } + const AIF = { + stand(g, i, dist) { + const e = g.ents[i], mi = e.monsterinfo; + if (dist) walkmove(g, i, e.angles[1], dist); + if (mi.aiflags & AI_STAND_GROUND) { + if (e.enemy >= 0) { + e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin)); + if (e.angles[1] !== e.ideal_yaw && (mi.aiflags & AI_TEMP_STAND_GROUND)) { mi.aiflags &= ~(AI_STAND_GROUND | AI_TEMP_STAND_GROUND); call(g, i, 'run'); } + Q.changeYaw(g, i); + aiCheckAttack(g, i, 0); + } else findTarget(g, i); + return; + } + if (findTarget(g, i)) return; + // pausetime is set far ahead in every path here, so the walk branch never runs; idle sounds do not exist. + }, + walk(g, i, dist) { moveToGoal(g, i, dist); findTarget(g, i); }, + turn(g, i, dist) { if (dist) walkmove(g, i, g.ents[i].angles[1], dist); if (findTarget(g, i)) return; Q.changeYaw(g, i); }, + move(g, i, dist) { walkmove(g, i, g.ents[i].angles[1], dist); }, + charge(g, i, dist) { + const e = g.ents[i]; + e.ideal_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin)); + Q.changeYaw(g, i); + if (dist) walkmove(g, i, e.angles[1], dist); + }, + run(g, i, dist) { aiRun(g, i, dist); }, + }; + // M_CheckAttack (default) with the skill scaling of the attack chance. + Q.M_CheckAttack = (g, i) => { + const e = g.ents[i], mi = e.monsterinfo, en = g.ents[e.enemy]; + if (en.health > 0) { + const tr = Q.trace(g, eye(e), null, null, eye(en), i, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA | Q.CONTENTS_WINDOW); + if (tr.ent !== e.enemy) return false; + } + if (g.ai.enemy_range === Q.RANGE_MELEE) { + if (g.skill === 0 && (Q.rand(g) & 3)) return false; + mi.attack_state = def(e).melee ? AS_MELEE : AS_MISSILE; return true; + } + if (!def(e).attack) return false; + if (g.ms < mi.attack_finished) return false; + if (g.ai.enemy_range === Q.RANGE_FAR) return false; + let chance; + if (mi.aiflags & AI_STAND_GROUND) chance = 0.4; + else if (g.ai.enemy_range === Q.RANGE_NEAR) chance = 0.1; + else if (g.ai.enemy_range === Q.RANGE_MID) chance = 0.02; + else return false; + if (g.skill === 0) chance *= 0.5; else if (g.skill >= 2) chance *= 2; + if (Q.random(g) < chance) { mi.attack_state = AS_MISSILE; mi.attack_finished = g.ms + 2000 * Q.random(g); return true; } + if (e.flags & Q.FL_FLY) mi.attack_state = Q.random(g) < 0.3 ? AS_SLIDING : AS_STRAIGHT; + return false; + }; + // Boss2_CheckAttack / Jorg_CheckAttack / Makron_CheckAttack share one shape: no skill scaling, own chances. + function bossCheckAttack(near, mid) { + return (g, i) => { + const e = g.ents[i], mi = e.monsterinfo, en = g.ents[e.enemy]; + if (en.health > 0) { + const tr = Q.trace(g, eye(e), null, null, eye(en), i, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_SLIME | Q.CONTENTS_LAVA); + if (tr.ent !== e.enemy) return false; + } + const range = Q.range(g, i, e.enemy); + e.ideal_yaw = Q.vectoyaw(sub(en.origin, e.origin)); + if (range === Q.RANGE_MELEE) { mi.attack_state = def(e).melee ? AS_MELEE : AS_MISSILE; return true; } + if (!def(e).attack) return false; + if (g.ms < mi.attack_finished) return false; + if (range === Q.RANGE_FAR) return false; + let chance; + if (mi.aiflags & AI_STAND_GROUND) chance = 0.4; + else if (range === Q.RANGE_NEAR) chance = near; + else if (range === Q.RANGE_MID) chance = mid; + else return false; + if (Q.random(g) < chance) { mi.attack_state = AS_MISSILE; mi.attack_finished = g.ms + 2000 * Q.random(g); return true; } + if (e.flags & Q.FL_FLY) mi.attack_state = Q.random(g) < 0.3 ? AS_SLIDING : AS_STRAIGHT; + return false; + }; + } + const facingIdeal = e => { const d = Q.anglemod(e.angles[1] - e.ideal_yaw); return !(d > 45 && d < 315); }; + function aiCheckAttack(g, i, dist) { + const e = g.ents[i], mi = e.monsterinfo; + if (e.goalentity >= 0 && (mi.aiflags & AI_SOUND_TARGET)) { + if (g.ms - (g.ents[e.enemy].teleport_time || 0) > 5000) { + if (e.goalentity === e.enemy) e.goalentity = -1; // no movetarget in these arenas + mi.aiflags &= ~AI_SOUND_TARGET; + if (mi.aiflags & AI_TEMP_STAND_GROUND) mi.aiflags &= ~(AI_STAND_GROUND | AI_TEMP_STAND_GROUND); + } else { e.show_hostile = g.ms + 1000; return false; } + } + g.ai.enemy_vis = false; + const en = e.enemy >= 0 ? g.ents[e.enemy] : null; + // hesDeadJim: AI_BRUTAL monsters (the Tank) keep going until the enemy is below -80; a player_noise target has + // no health either. + const dead = !en || !en.inuse || (en.health || 0) <= ((mi.aiflags & AI_BRUTAL) ? -80 : 0); + if (dead) { + e.enemy = -1; + if (e.oldenemy >= 0 && g.ents[e.oldenemy].inuse && g.ents[e.oldenemy].health > 0) { e.enemy = e.oldenemy; e.oldenemy = -1; huntTarget(g, i); } + else { mi.pausetime = g.ms + 100000000000; call(g, i, 'stand'); return true; } + } + e.show_hostile = g.ms + 1000; + g.ai.enemy_vis = Q.visible(g, i, e.enemy); + if (g.ai.enemy_vis) { mi.search_time = g.ms + 5000; mi.last_sighting = copy3(g.ents[e.enemy].origin); } + g.ai.enemy_infront = Q.infront(g, i, e.enemy); + g.ai.enemy_range = Q.range(g, i, e.enemy); + g.ai.enemy_yaw = Q.vectoyaw(sub(g.ents[e.enemy].origin, e.origin)); + if (mi.attack_state === AS_MISSILE) { // ai_run_missile + e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i); + if (facingIdeal(e)) { call(g, i, 'attack'); mi.attack_state = AS_STRAIGHT; } + return true; + } + if (mi.attack_state === AS_MELEE) { + e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i); + if (facingIdeal(e)) { call(g, i, 'melee'); mi.attack_state = AS_STRAIGHT; } + return true; + } + if (!g.ai.enemy_vis) return false; + return (def(e).checkattack || Q.M_CheckAttack)(g, i); + } + function aiRun(g, i, dist) { + const e = g.ents[i], mi = e.monsterinfo; + if (mi.aiflags & AI_SOUND_TARGET) { + if (len(sub(e.origin, g.ents[e.enemy].origin)) < 64) { mi.aiflags |= AI_STAND_GROUND | AI_TEMP_STAND_GROUND; call(g, i, 'stand'); return; } + moveToGoal(g, i, dist); + if (!findTarget(g, i)) return; + } + if (aiCheckAttack(g, i, dist)) return; + if (mi.attack_state === AS_SLIDING) { // ai_run_slide + e.ideal_yaw = g.ai.enemy_yaw; Q.changeYaw(g, i); + const ofs = mi.lefty ? 90 : -90; + if (walkmove(g, i, e.ideal_yaw + ofs, dist)) return; + mi.lefty = 1 - mi.lefty; + walkmove(g, i, e.ideal_yaw - ofs, dist); + return; + } + if (g.ai.enemy_vis) { + moveToGoal(g, i, dist); + mi.aiflags &= ~AI_LOST_SIGHT; + mi.last_sighting = copy3(g.ents[e.enemy].origin); mi.trail_time = g.ms; + mi.stall_pos = copy3(e.origin); mi.stall_t = g.ms; mi.chase_until = 0; + return; + } + // BossBench engagement rule: the lost-sight + // pursuit below can ping-pong between two course-correction targets when a large boss is flush against a pillar, + // and since every PURSUE_NEXT renews search_time the original 20 s fallback never fires. If the boss has neither + // seen the player nor moved 48 units for 3 s, it takes that original fallback early: 2 s of M_MoveToGoal straight + // at its enemy (SV_NewChaseDir steps around the obstacle). + if (mi.chase_until > g.ms) { moveToGoal(g, i, dist); return; } + if (!mi.stall_pos || len(sub(e.origin, mi.stall_pos)) > 48) { mi.stall_pos = copy3(e.origin); mi.stall_t = g.ms; } + else if (g.ms - mi.stall_t >= 3000) { + mi.chase_until = g.ms + 2000; mi.stall_pos = null; + mi.aiflags &= ~(AI_LOST_SIGHT | AI_PURSUIT_LAST_SEEN | AI_PURSUE_NEXT | AI_PURSUE_TEMP); + Q.event(g, 'boss_unstick', { classname: e.classname }); + moveToGoal(g, i, dist); + return; + } + if (mi.search_time && g.ms > mi.search_time + 20000) { moveToGoal(g, i, dist); mi.search_time = 0; return; } + // Lost sight: chase last_sighting, then the player trail, with the course correction traces. + const save = e.goalentity, tempgoal = Q.spawn(g); + e.goalentity = tempgoal; + let fresh = false; + if (!(mi.aiflags & AI_LOST_SIGHT)) { mi.aiflags |= AI_LOST_SIGHT | AI_PURSUIT_LAST_SEEN; mi.aiflags &= ~(AI_PURSUE_NEXT | AI_PURSUE_TEMP); fresh = true; } + if (mi.aiflags & AI_PURSUE_NEXT) { + mi.aiflags &= ~AI_PURSUE_NEXT; + mi.search_time = g.ms + 5000; + let marker = null; + if (mi.aiflags & AI_PURSUE_TEMP) { mi.aiflags &= ~AI_PURSUE_TEMP; mi.last_sighting = copy3(mi.saved_goal); fresh = true; } + else if (mi.aiflags & AI_PURSUIT_LAST_SEEN) { mi.aiflags &= ~AI_PURSUIT_LAST_SEEN; marker = Q.trailPick(g, i, true); } + else marker = Q.trailPick(g, i, false); + if (marker) { mi.last_sighting = copy3(marker.origin); mi.trail_time = marker.timestamp; e.angles[1] = e.ideal_yaw = marker.yaw; fresh = true; } + } + let d1 = len(sub(e.origin, mi.last_sighting)); + if (d1 <= dist) { mi.aiflags |= AI_PURSUE_NEXT; dist = d1; } + g.ents[tempgoal].origin = copy3(mi.last_sighting); + if (fresh) { + let tr = Q.trace(g, e.origin, e.mins, e.maxs, mi.last_sighting, i, Q.MASK_PLAYERSOLID); + if (tr.fraction < 1) { + const v = sub(g.ents[tempgoal].origin, e.origin); + d1 = len(v); + let center = tr.fraction; + const d2 = d1 * ((center + 1) / 2); + e.angles[1] = e.ideal_yaw = Q.vectoyaw(v); + const av = Q.angleVectors(e.angles); + let left_target = Q.projectSource(e.origin, [d2, -16, 0], av.forward, av.right); + tr = Q.trace(g, e.origin, e.mins, e.maxs, left_target, i, Q.MASK_PLAYERSOLID); + const left = tr.fraction; + let right_target = Q.projectSource(e.origin, [d2, 16, 0], av.forward, av.right); + tr = Q.trace(g, e.origin, e.mins, e.maxs, right_target, i, Q.MASK_PLAYERSOLID); + const right = tr.fraction; + center = (d1 * center) / d2; + if (left >= center && left > right) { + if (left < 1) left_target = Q.projectSource(e.origin, [d2 * left * 0.5, -16, 0], av.forward, av.right); + mi.saved_goal = copy3(mi.last_sighting); mi.aiflags |= AI_PURSUE_TEMP; + g.ents[tempgoal].origin = copy3(left_target); mi.last_sighting = copy3(left_target); + e.angles[1] = e.ideal_yaw = Q.vectoyaw(sub(g.ents[tempgoal].origin, e.origin)); + } else if (right >= center && right > left) { + if (right < 1) right_target = Q.projectSource(e.origin, [d2 * right * 0.5, 16, 0], av.forward, av.right); + mi.saved_goal = copy3(mi.last_sighting); mi.aiflags |= AI_PURSUE_TEMP; + g.ents[tempgoal].origin = copy3(right_target); mi.last_sighting = copy3(right_target); + e.angles[1] = e.ideal_yaw = Q.vectoyaw(sub(g.ents[tempgoal].origin, e.origin)); + } + } + } + moveToGoal(g, i, dist); + Q.freeEdict(g, tempgoal); + if (g.ents[i].inuse) g.ents[i].goalentity = save; + } + // M_ReactToDamage: the player is the only other combatant; damage from the monster itself is ignored. + Q.reactToDamage = (g, targ, attacker) => { + const t = g.ents[targ], a = g.ents[attacker]; + if (!a || (!a.client && !(a.svflags & Q.SVF_MONSTER))) return; + if (attacker === targ || attacker === t.enemy) return; + if (a.client) { + t.monsterinfo.aiflags &= ~AI_SOUND_TARGET; + if (t.enemy >= 0 && g.ents[t.enemy].client) { + if (Q.visible(g, targ, t.enemy)) { t.oldenemy = attacker; return; } + t.oldenemy = t.enemy; + } + t.enemy = attacker; + if (!(t.monsterinfo.aiflags & AI_DUCKED)) foundTarget(g, targ); + } + }; + Q.AI_DUCKED = AI_DUCKED; + Q.monsterPain = (g, i, attacker, kick, damage) => call(g, i, 'pain', attacker, kick, damage); + Q.monsterDie = (g, i, inflictor, attacker, damage, point) => call(g, i, 'die', inflictor, attacker, damage, point); + // monster_death_use: fliers drop out of the air; the case decides what the death triggers (Makron's spawn, the win). + Q.monsterDeathUse = (g, i) => { + const e = g.ents[i]; + e.flags &= ~(Q.FL_FLY | Q.FL_SWIM); + e.monsterinfo.aiflags &= AI_GOOD_GUY; + Q.event(g, 'boss_killed', { classname: e.classname }); + if (e.final) g.bossKilled = g.t + 1; + }; + + // ---------------- framework (g_monster.c) ---------------- + function moveFrame(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + let move = def(e).moves[mi.currentmove]; + e.nextthink = g.ms + Q.FRAMETIME_MS; + if (mi.nextframe && mi.nextframe >= move.first && mi.nextframe <= move.last) { e.frame = mi.nextframe; mi.nextframe = 0; } + else { + if (e.frame === move.last && move.end) { + call(g, i, move.end); + move = def(e).moves[mi.currentmove]; + if (e.svflags & Q.SVF_DEADMONSTER) return; + } + if (e.frame < move.first || e.frame > move.last) { mi.aiflags &= ~AI_HOLD_FRAME; e.frame = move.first; } + else if (!(mi.aiflags & AI_HOLD_FRAME)) { e.frame++; if (e.frame > move.last) e.frame = move.first; } + } + const [ai, dist, think] = move.frames[e.frame - move.first]; + if (ai) AIF[ai](g, i, (mi.aiflags & AI_HOLD_FRAME) ? 0 : dist * mi.scale); + if (think && g.ents[i].inuse) call(g, i, think); + } + Q.THINK.monster_think = (g, i) => { + moveFrame(g, i); + const e = g.ents[i]; + if (!e.inuse) return; + if (e.linkcount !== e.monsterinfo.linkcount) { e.monsterinfo.linkcount = e.linkcount; checkGround(g, i); } + }; + // SV_Physics_Step: gravity, fly / ground friction and SV_FlyMove for a monster with velocity, then think. At 60 Hz + // (q2-arena@3) the physics runs every host frame with that frame's length (g.dt); the think still fires on its + // nextthink, i.e. every 100 ms server frame. lerp keeps the displacement of the last think for the renderer, which + // spreads it over the next 100 ms like the original client (cl_ents.c lerpfrac); it never feeds back into the rules. + // Friction in SV_Physics_Step is speed * (1 - frametime * friction) once per 100 ms server frame (x0.4 on the + // ground, x0.8 for a flier's vertical speed). Applied per 16/17 ms host frame it keeps the per-second decay with + // k^(ms/100) (precomputed, so Node and the browser agree bit for bit); below stopspeed the original subtracts a + // constant per second, which the linear form already keeps. + const FRICTION_K = { 16: [0.86363373567437107, 0.96492686487423818], 17: [0.85575648417344741, 0.96277609334680192] }; + const frictionK = (g, fly) => { const k = FRICTION_K[Math.round(g.dt * 1000)]; if (!k) throw Error('host frame ' + g.dt); return k[fly ? 1 : 0]; }; + Q.physicsStep = (g, i) => { + let e = g.ents[i]; + if (e.groundentity < 0) checkGround(g, i); + for (let k = 0; k < 3; k++) e.velocity[k] = Math.max(-Q.SV_MAXVELOCITY, Math.min(Q.SV_MAXVELOCITY, e.velocity[k])); + const wasonground = e.groundentity >= 0, ft = g.dt; + if (!wasonground && !(e.flags & Q.FL_FLY)) e.velocity[2] -= e.gravity * Q.SV_GRAVITY * ft; + if ((e.flags & Q.FL_FLY) && e.velocity[2] !== 0) { + const speed = Math.abs(e.velocity[2]), control = speed < Q.SV_STOPSPEED ? Q.SV_STOPSPEED : speed; + let ns = speed < Q.SV_STOPSPEED ? speed - ft * control * Q.SV_FRICTION / 3 : speed * frictionK(g, true); if (ns < 0) ns = 0; e.velocity[2] *= ns / speed; + } + if (e.velocity[0] || e.velocity[1] || e.velocity[2]) { + if ((wasonground || (e.flags & (Q.FL_SWIM | Q.FL_FLY))) && !(e.health <= 0 && !checkBottom(g, i))) { + const speed = Math.sqrt(e.velocity[0] ** 2 + e.velocity[1] ** 2); + if (speed) { + const control = speed < Q.SV_STOPSPEED ? Q.SV_STOPSPEED : speed; + let ns = speed < Q.SV_STOPSPEED ? speed - ft * control * Q.SV_FRICTION : speed * frictionK(g, false); if (ns < 0) ns = 0; ns /= speed; + e.velocity[0] *= ns; e.velocity[1] *= ns; + } + } + flyMove(g, i, ft, (e.svflags & Q.SVF_MONSTER) ? Q.MASK_MONSTERSOLID : Q.MASK_SOLID); + link(g, i); + if (!g.ents[i].inuse) return; + } + const before = copy3(g.ents[i].origin); + if (Q.runThink(g, i) || !g.ents[i].inuse) return; + const after = g.ents[i].origin; + g.ents[i].lerp = [before[0] - after[0], before[1] - after[1], before[2] - after[2], g.ms]; + }; + function flyMove(g, i, time, mask) { // SV_FlyMove + const e = g.ents[i], primal = copy3(e.velocity), planes = []; + let original = copy3(e.velocity), time_left = time; + e.groundentity = -1; + for (let bump = 0; bump < 4; bump++) { + const end = [0, 1, 2].map(k => e.origin[k] + time_left * e.velocity[k]); + const tr = Q.trace(g, e.origin, e.mins, e.maxs, end, i, mask); + if (tr.allsolid) { e.velocity = [0, 0, 0]; return 3; } + if (tr.fraction > 0) { e.origin = copy3(tr.endpos); original = copy3(e.velocity); planes.length = 0; } + if (tr.fraction === 1) break; + if (tr.normal[2] > 0.7 && tr.ent === 0) e.groundentity = 0; + Q.impact(g, i, tr); + if (!g.ents[i].inuse) break; + time_left -= time_left * tr.fraction; + if (planes.length >= 5) { e.velocity = [0, 0, 0]; return 3; } + planes.push(tr.normal); + let k; + for (k = 0; k < planes.length; k++) { + const backoff = dot(original, planes[k]), nv = [0, 1, 2].map(c => { const v = original[c] - planes[k][c] * backoff; return v > -0.1 && v < 0.1 ? 0 : v; }); + let j; + for (j = 0; j < planes.length; j++) if (j !== k && !Q.eq(planes[k], planes[j]) && dot(nv, planes[j]) < 0) break; + if (j === planes.length) { e.velocity = nv; break; } + } + if (k === planes.length) { + if (planes.length !== 2) { e.velocity = [0, 0, 0]; return 7; } + const dir = Q.cross(planes[0], planes[1]); e.velocity = scale(dir, dot(dir, e.velocity)); + } + if (dot(e.velocity, primal) <= 0) { e.velocity = [0, 0, 0]; return 0; } + } + return 0; + } + // Spawn: SP_monster_* + monster_start; the first think is walkmonster_start_go / flymonster_start_go. + Q.spawnMonster = (g, classname, origin, yaw, opts) => { + const i = Q.spawn(g), e = g.ents[i], d = DEFS[classname]; + Object.assign(e, { + classname, origin: copy3(origin), old_origin: copy3(origin), angles: [0, yaw, 0], ideal_yaw: yaw, mins: copy3(d.mins), maxs: copy3(d.maxs), + movetype: 'step', solid: Q.SOLID_BBOX, health: opts.health, gib_health: d.gib_health, mass: d.mass, flags: d.fly ? Q.FL_FLY : 0, + svflags: Q.SVF_MONSTER, takedamage: Q.DAMAGE_AIM, clipmask: Q.MASK_MONSTERSOLID, yaw_speed: 0, viewheight: 0, final: !!opts.final, + goalentity: -1, oldenemy: -1, movetarget: -1, show_hostile: 0, pain_debounce_time: 0, skinnum: 0, pos1: [0, 0, 0], count: 0, + think: d.fly ? 'flymonster_start_go' : 'walkmonster_start_go', nextthink: g.ms + Q.FRAMETIME_MS, + monsterinfo: { currentmove: d.startMove || 'stand', nextframe: 0, aiflags: 0, scale: 1, pausetime: 0, attack_finished: 0, attack_state: 0, lefty: 0, + search_time: 0, trail_time: 0, last_sighting: [0, 0, 0], saved_goal: [0, 0, 0], linkcount: 0, idle_time: 0, + stall_pos: null, stall_t: 0, chase_until: 0 }, + }); + if (d.immuneLaser) e.flags |= Q.FL_IMMUNE_LASER; + e.max_health = e.health; + const mv = d.moves[e.monsterinfo.currentmove]; + e.frame = mv.first + (Q.rand(g) % (mv.last - mv.first + 1)); // monster_start picks a random first frame + if (opts.engage) e.engage = true; + return i; + }; + function dropToFloor(g, i) { // M_droptofloor: lift one unit, trace 256 down, rest DIST_EPSILON above the floor + const e = g.ents[i]; + e.origin[2] += 1; + const end = copy3(e.origin); end[2] -= 256; + const tr = Q.trace(g, e.origin, e.mins, e.maxs, end, i, Q.MASK_MONSTERSOLID); + if (tr.fraction === 1 || tr.allsolid) return; + e.origin = copy3(tr.endpos); link(g, i); + checkGround(g, i); + } + function startGo(g, i, fly) { + const e = g.ents[i]; + if (!fly) { if (g.ms < 1000) dropToFloor(g, i); } else walkmove(g, i, 0, 0); + if (!e.yaw_speed) e.yaw_speed = fly ? 10 : 20; + e.viewheight = 25; + if (e.health <= 0) return; // monster_start_go: killed before it ever thought + e.monsterinfo.pausetime = 100000000000; call(g, i, 'stand'); + e.think = 'monster_think'; e.nextthink = g.ms + Q.FRAMETIME_MS; + // monster_use by the arena trigger: an alerted boss hunts the player from the first frame. + if (e.engage && g.ents[1].health > 0) { e.enemy = 1; foundTarget(g, i); } + } + Q.THINK.walkmonster_start_go = (g, i) => startGo(g, i, false); + Q.THINK.flymonster_start_go = (g, i) => startGo(g, i, true); + // Muzzle helpers (G_ProjectSource with monster_flash_offset, monster yaw only). + const muzzle = (e, ofs) => { const av = Q.angleVectors(e.angles); return Q.projectSource(e.origin, ofs, av.forward, av.right); }; + const aimAt = (g, start, target) => norm(sub(target, start)); + const enemyEye = (g, e, lag) => { const en = g.ents[e.enemy], t = ma(en.origin, lag, en.velocity); t[2] += en.viewheight; return t; }; + function flash(g, i, weapon, at, extra) { Q.fx(g, 'mflash', at, null, Object.assign({ weapon, owner: i }, extra || {})); } + Q.monsterFireBullet = (g, i, start, dir, damage, kick) => Q.fireBullet(g, i, start, dir, damage, kick, 300, 500, 'monster'); + Q.monsterFireRocket = (g, i, start, dir, damage, speed) => Q.fireRocket(g, i, start, dir, damage, speed, damage + 20, damage); + // BossExplode: nine explosions a frame apart around the body, then the gibs (cosmetic; their RNG draws kept). + Q.THINK.BossExplode = (g, i) => { + const e = g.ents[i]; + e.think = 'BossExplode'; + const org = copy3(e.origin); org[2] += 24 + (Q.rand(g) & 15); + const OFS = [[-24, -24], [24, 24], [24, -24], [-24, 24], [-48, -48], [48, 48], [-48, 48], [48, -48]]; + const n = e.count++; + if (n < 8) { + org[0] += OFS[n][0]; org[1] += OFS[n][1]; + Q.fx(g, 'explosion', org, null, { big: true }); + e.nextthink = g.ms + Q.FRAMETIME_MS; + return; + } + // case 8: four meat chunks, eight metal chunks, the chest, then the boss itself becomes the gear head. + for (let k = 0; k < 4; k++) Q.throwGib(g, i, 'meat', 500, true); + for (let k = 0; k < 8; k++) Q.throwGib(g, i, 'metal', 500, false); + Q.throwGib(g, i, 'chest', 500, true); + Q.throwHead(g, i, 'gear', 500, false); + g.ents[i].deadflag = Q.DEAD_DEAD; g.ents[i].gibbed = true; + Q.fx(g, 'gibs', Q.center(g.ents[i]), null, { size: 64 }); + }; + function bossDead(mins, maxs) { + return (g, i) => { const e = g.ents[i]; e.mins = mins; e.maxs = maxs; e.movetype = 'toss'; e.svflags |= Q.SVF_DEADMONSTER; e.nextthink = 0; }; + } + const stand = (g, i) => setMove(g.ents[i], 'stand'); + const runOrStand = (g, i) => setMove(g.ents[i], (g.ents[i].monsterinfo.aiflags & AI_STAND_GROUND) ? 'stand' : 'run'); + const debounced = (g, e) => g.ms < e.pain_debounce_time; + const sound = () => {}; + + // ================= Super Tank (m_supertank.c) ================= + DEFS.monster_supertank = { + name: 'Tracked Gun Carrier', health: 1500, gib_health: -500, mass: 800, mins: [-64, -64, 0], maxs: [64, 64, 112], gibs: 13, + moves: moves({ + stand: [194, 253, 's0x60', null], + run: [128, 145, 'r12:TreadSound r12x17', null], + forward: [128, 145, 'w4:TreadSound w4x17', null], + pain3: [172, 175, 'm0x4', 'run'], pain2: [168, 171, 'm0x4', 'run'], pain1: [164, 167, 'm0x4', 'run'], + death: [98, 121, 'm0x23 m0:BossExplode', 'dead'], + attack2: [20, 46, 'c0x7 c0:supertankRocket m0x2 m0:supertankRocket m0x2 m0:supertankRocket m0x13', 'run'], + attack1: [0, 5, 'c0:supertankMachineGunx6', 'reattack1'], + end_attack1: [6, 19, 'm0x14', 'run'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'forward'), run: runOrStand, TreadSound: sound, + reattack1(g, i) { + const e = g.ents[i]; + if (Q.visible(g, i, e.enemy)) setMove(e, Q.random(g) < 0.9 ? 'attack1' : 'end_attack1'); else setMove(e, 'end_attack1'); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + if (damage <= 25 && Q.random(g) < 0.2) return; // lessen the chance of pain frames + if (g.skill >= 2 && e.frame >= 20 && e.frame <= 33) return; // no pain while firing rockets + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; // no pain anims in nightmare + setMove(e, damage <= 10 ? 'pain1' : damage <= 25 ? 'pain2' : 'pain3'); + }, + supertankRocket(g, i) { + const e = g.ents[i]; + const ofs = e.frame === 27 ? [16.0, -22.5, 91.2] : e.frame === 30 ? [16.0, -33.4, 86.7] : [16.0, -42.8, 83.3]; + const start = muzzle(e, ofs); + Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 500); + flash(g, i, 'rocket', start); + }, + supertankMachineGun(g, i) { + const e = g.ents[i], av = Q.angleVectors([0, e.angles[1], 0]); + const start = Q.projectSource(e.origin, [30.0, 30.0, 88.5], av.forward, av.right); + let forward = av.forward; + if (e.enemy >= 0) forward = aimAt(g, start, enemyEye(g, e, 0)); + Q.monsterFireBullet(g, i, start, forward, 6, 4); + flash(g, i, 'mg', start); + }, + attack(g, i) { + const e = g.ents[i], range = len(sub(g.ents[e.enemy].origin, e.origin)); + if (range <= 160) setMove(e, 'attack1'); + else setMove(e, Q.random(g) < 0.3 ? 'attack1' : 'attack2'); // fire rockets more often at distance + }, + die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); }, + dead: bossDead([-60, -60, 0], [60, 60, 72]), + BossExplode: (g, i) => Q.THINK.BossExplode(g, i), + }; + + // ================= Hornet (m_boss2.c) ================= + DEFS.monster_boss2 = { + name: 'Flying Gunship', health: 2000, gib_health: -200, mass: 1000, mins: [-56, -56, 0], maxs: [56, 56, 80], fly: true, immuneLaser: true, gibs: 13, + moves: moves({ + stand: [0, 20, 's0x21', null], + walk: [50, 69, 'w8x20', null], + run: [50, 69, 'r8x20', null], + attack_pre_mg: [70, 78, 'c1x8 c1:boss2_attack_mg', null], + attack_mg: [79, 84, 'c1:Boss2MachineGunx5 c1:boss2_reattack_mg', null], + attack_post_mg: [85, 88, 'c1x4', 'run'], + attack_rocket: [89, 109, 'c1x12 m-20:Boss2Rocket c1x8', 'run'], + pain_heavy: [110, 127, 'm0x18', 'run'], + pain_light: [128, 131, 'm0x4', 'run'], + death: [132, 180, 'm0x48 m0:BossExplode', 'dead'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, + checkattack: bossCheckAttack(0.8, 0.8), + attack(g, i) { + const e = g.ents[i], range = len(sub(g.ents[e.enemy].origin, e.origin)); + if (range <= 125) setMove(e, 'attack_pre_mg'); else setMove(e, Q.random(g) <= 0.6 ? 'attack_pre_mg' : 'attack_rocket'); + }, + boss2_attack_mg: (g, i) => setMove(g.ents[i], 'attack_mg'), + boss2_reattack_mg(g, i) { + const e = g.ents[i]; + if (Q.infront(g, i, e.enemy)) setMove(e, Q.random(g) <= 0.7 ? 'attack_mg' : 'attack_post_mg'); else setMove(e, 'attack_post_mg'); + }, + Boss2MachineGun(g, i) { + const e = g.ents[i]; + for (const ofs of [[32, -40, 70], [32, 40, 70]]) { // boss2_firebullet_left, then _right + const start = muzzle(e, ofs); + Q.monsterFireBullet(g, i, start, aimAt(g, start, enemyEye(g, e, -0.2)), 6, 4); + flash(g, i, 'mg', start); + } + }, + Boss2Rocket(g, i) { + const e = g.ents[i]; + for (const ofs of [[22.0, 16.0, 10.0], [22.0, 8.0, 10.0], [22.0, -8.0, 10.0], [22.0, -16.0, 10.0]]) { + const start = muzzle(e, ofs); + Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 500); + flash(g, i, 'rocket', start); + } + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + e.pain_debounce_time = g.ms + 3000; + setMove(e, damage < 30 ? 'pain_light' : 'pain_heavy'); + }, + die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); }, + dead: bossDead([-56, -56, 0], [56, 56, 80]), + BossExplode: (g, i) => Q.THINK.BossExplode(g, i), + }; + + // ================= Jorg (m_boss31.c), first form of the final boss ================= + DEFS.monster_jorg = { + name: 'Twin-Cannon Mech', health: 3000, gib_health: -2000, mass: 1000, mins: [-80, -80, 0], maxs: [80, 80, 140], gibs: 13, + moves: moves({ + stand: [112, 162, 's0:jorg_idle s0x32 s19 s11:jorg_step_left s0x2 s6 s9:jorg_step_right s0x7 s-2 s-17:jorg_step_left s0 s-12 s-14:jorg_step_right', null], + run: [168, 181, 'r17:jorg_step_left r0x3 r12 r8 r10 r33:jorg_step_right r0x3 r9x3', null], + walk: [168, 181, 'w17 w0x3 w12 w8 w10 w33 w0x3 w9x3', null], + pain3: [87, 111, 'm-28 m-6 m-3:jorg_step_left m-9 m0:jorg_step_right m0x3 m-7 m1 m-11 m-4 m0x2 m10 m11 m0 m10 m3 m10 m7:jorg_step_left m17 m0x2 m0:jorg_step_right', 'run'], + pain2: [84, 86, 'm0x3', 'run'], pain1: [81, 83, 'm0x3', 'run'], + death: [31, 80, 'm0x48 m0:MakronToss m0:BossExplode', 'dead'], + attack2: [18, 30, 'c0x6 c0:jorgBFG m0x6', 'run'], + start_attack1: [0, 7, 'c0x8', 'attack1'], + attack1: [8, 13, 'c0:jorg_firebulletx6', 'reattack1'], + end_attack1: [14, 17, 'm0x4', 'run'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, jorg_idle: sound, jorg_step_left: sound, jorg_step_right: sound, + checkattack: bossCheckAttack(0.4, 0.2), + attack(g, i) { setMove(g.ents[i], Q.random(g) <= 0.75 ? 'start_attack1' : 'attack2'); }, + attack1: (g, i) => setMove(g.ents[i], 'attack1'), + reattack1(g, i) { + const e = g.ents[i]; + if (Q.visible(g, i, e.enemy)) setMove(e, Q.random(g) < 0.9 ? 'attack1' : 'end_attack1'); else setMove(e, 'end_attack1'); + }, + jorg_firebullet(g, i) { + const e = g.ents[i]; + for (const ofs of [[78.5, -47.1, 96], [78.5, 46.7, 96]]) { // jorg_firebullet_left, then _right + const start = muzzle(e, ofs); + Q.monsterFireBullet(g, i, start, aimAt(g, start, enemyEye(g, e, -0.2)), 6, 4); + flash(g, i, 'mg', start); + } + }, + jorgBFG(g, i) { + const e = g.ents[i], start = muzzle(e, [6.3, -9, 111.2]); + Q.fireBFG(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 300, 200); + flash(g, i, 'bfg', start); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + if (damage <= 40 && Q.random(g) <= 0.6) return; + if (e.frame >= 0 && e.frame <= 7 && Q.random(g) <= 0.005) return; + if (e.frame >= 8 && e.frame <= 13 && Q.random(g) <= 0.00005) return; + if (e.frame >= 18 && e.frame <= 25 && Q.random(g) <= 0.005) return; + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; + if (damage <= 50) setMove(e, 'pain1'); else if (damage <= 100) setMove(e, 'pain2'); else if (Q.random(g) <= 0.3) setMove(e, 'pain3'); + }, + die(g, i) { const e = g.ents[i]; e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_NO; e.count = 0; setMove(e, 'death'); }, + dead: bossDead([-60, -60, 0], [60, 60, 72]), + MakronToss(g, i) { // spawn Makron 0.8 s later at Jorg's origin + const k = Q.spawn(g), t = g.ents[k]; + Object.assign(t, { classname: 'makron_spawner', origin: copy3(g.ents[i].origin), think: 'MakronSpawn', nextthink: g.ms + 800 }); + }, + BossExplode: (g, i) => Q.THINK.BossExplode(g, i), + }; + // MakronSpawn: SP_monster_makron on the spawner edict, then jump at the player (400 forward, 200 up). + Q.THINK.MakronSpawn = (g, i) => { + const origin = copy3(g.ents[i].origin), d = DEFS.monster_makron, e = g.ents[i]; + Object.assign(e, Q.blankEdict(), { + classname: 'monster_makron', origin, old_origin: copy3(origin), mins: copy3(d.mins), maxs: copy3(d.maxs), movetype: 'step', solid: Q.SOLID_BBOX, + health: g.makronHealth, gib_health: d.gib_health, mass: d.mass, svflags: Q.SVF_MONSTER, takedamage: Q.DAMAGE_AIM, clipmask: Q.MASK_MONSTERSOLID, + final: true, goalentity: -1, oldenemy: -1, movetarget: -1, show_hostile: 0, pain_debounce_time: 0, skinnum: 0, pos1: [0, 0, 0], count: 0, + yaw_speed: 0, viewheight: 0, think: 'walkmonster_start_go', nextthink: g.ms + Q.FRAMETIME_MS, angles: [0, 0, 0], ideal_yaw: 0, + monsterinfo: { currentmove: 'sight', nextframe: 0, aiflags: 0, scale: 1, pausetime: 0, attack_finished: 0, attack_state: 0, lefty: 0, + search_time: 0, trail_time: 0, last_sighting: [0, 0, 0], saved_goal: [0, 0, 0], linkcount: 0, idle_time: 0, + stall_pos: null, stall_t: 0, chase_until: 0 }, + }); + e.max_health = e.health; + const mv = d.moves.sight; e.frame = mv.first + (Q.rand(g) % (mv.last - mv.first + 1)); + const p = g.ents[1]; + if (p.health <= 0) return; + let vec = sub(p.origin, e.origin); + e.angles[1] = Q.vectoyaw(vec); // ideal_yaw stays 0 until HuntTarget + vec = norm(vec); + e.velocity = scale(vec, 400); e.velocity[2] = 200; e.groundentity = -1; + Q.event(g, 'makron_spawn'); + }; + + // ================= Makron (m_boss32.c), second form ================= + const MAKRON_BLASTER = [[-3.6, -24.1, 59.5], [-1.6, -19.3, 59.5], [-0.1, -14.4, 59.5], [2.0, -7.6, 59.5], [3.4, 1.3, 59.5], [3.7, 11.1, 59.5], + [-0.3, 22.3, 59.5], [-6, 33, 59.5], [-9.3, 36.4, 59.5], [-7, 35, 59.5], [-2.1, 29, 59.5], [3.9, 17.3, 59.5], [6.1, 5.8, 59.5], [5.9, -4.4, 59.5], + [4.2, -14.1, 59.5], [2.4, -18.8, 59.5], [-1.8, -25.5, 59.5]]; + DEFS.monster_makron = { + name: 'Armored Pilot', health: 3000, gib_health: -2000, mass: 500, mins: [-30, -30, 0], maxs: [30, 30, 90], gibs: 5, startMove: 'sight', + moves: moves({ + stand: [414, 473, 's0x60', null], + run: [477, 486, 'r3:makron_step_left r12 r8x2 r8:makron_step_right r6 r12 r9 r6 r12', null], + walk: [477, 486, 'r3:makron_step_left r12 r8x2 r8:makron_step_right r6 r12 r9 r6 r12', null], + pain6: [387, 413, 'm0x15 m0:makron_popup m0x7 m0:makron_taunt m0x3', 'run'], + pain5: [383, 386, 'm0x4', 'run'], pain4: [379, 382, 'm0x4', 'run'], + death2: [251, 345, 'm-15 m3 m-12 m0:makron_step_left m0x11 m11 m12 m11:makron_step_right m0x15 m5 m7 m6:makron_step_left m0x2 m-1 m2 m0x13 m-6 m-4 m-6:makron_step_right m-4 m-4:makron_step_left m0x4 m-2 m-5 m-3:makron_step_right m-8 m-3:makron_step_left m-7 m-4 m-4:makron_step_right m-6 m-7 m0:makron_step_left m0x12 m-2 m0x2 m2 m0 m27:makron_hit m26 m0:makron_brainsplorch m0x2', 'dead'], + sight: [188, 200, 'm0x13', 'run'], + attack3: [201, 208, 'c0x3 c0:makronBFG m0x4', 'run'], + attack4: [209, 234, 'c0x4 m0:MakronHyperblasterx17 m0x5', 'run'], + attack5: [235, 250, 'c0:makron_prerailgun c0x6 c0:MakronSaveloc m0:MakronRailgun m0x7', 'run'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, sight: (g, i) => setMove(g.ents[i], 'sight'), + makron_step_left: sound, makron_step_right: sound, makron_popup: sound, makron_hit: sound, makron_brainsplorch: sound, + makron_taunt: (g) => { Q.random(g); }, makron_prerailgun: (g, i) => Q.fx(g, 'railcharge', g.ents[i].origin, null, { owner: i }), + checkattack: bossCheckAttack(0.4, 0.2), + attack(g, i) { + const r = Q.random(g), e = g.ents[i]; + setMove(e, r <= 0.3 ? 'attack3' : r <= 0.6 ? 'attack4' : 'attack5'); + }, + makronBFG(g, i) { + const e = g.ents[i], start = muzzle(e, [17, -19.5, 62.9]); + Q.fireBFG(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 300, 300); + flash(g, i, 'bfg', start); + }, + MakronSaveloc(g, i) { const e = g.ents[i], en = g.ents[e.enemy]; e.pos1 = copy3(en.origin); e.pos1[2] += en.viewheight; }, + MakronRailgun(g, i) { + const e = g.ents[i], start = muzzle(e, [-17.3, 7.8, 72.4]); + Q.fireRail(g, i, start, norm(sub(e.pos1, start)), 50, 100); + flash(g, i, 'rail', start); + }, + MakronHyperblaster(g, i) { + const e = g.ents[i], start = muzzle(e, MAKRON_BLASTER[e.frame - 213]); + const dir = [0, 0, 0]; + if (e.enemy >= 0) { const v = enemyEye(g, e, 0); dir[0] = Q.vectoangles(sub(v, start))[0]; } + dir[1] = e.frame <= 221 ? e.angles[1] - 10 * (e.frame - 221) : e.angles[1] + 10 * (e.frame - 229); + Q.fireBlaster(g, i, start, Q.angleVectors(dir).forward, 15, 1000, 'blaster', false); + flash(g, i, 'blaster', start); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + if (damage <= 25 && Q.random(g) < 0.2) return; + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; + if (damage <= 40) setMove(e, 'pain4'); + else if (damage <= 110) setMove(e, 'pain5'); + else if (damage <= 150) { // C's dangling else: the 0.35 retry belongs to this branch, >150 gives no pain + if (Q.random(g) <= 0.45) setMove(e, 'pain6'); else if (Q.random(g) <= 0.35) setMove(e, 'pain6'); + } + }, + die(g, i) { + const e = g.ents[i]; + if (e.deadflag === Q.DEAD_DEAD) return; + e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_YES; setMove(e, 'death2'); + }, + dead: bossDead([-60, -60, 0], [60, 60, 72]), + }; + + // ---------------- shared helpers of the three unit monsters ---------------- + // fire_hit (g_weapon.c), the melee hit of the Gladiator and the Mutant. Kept as in the source: `dir` is not + // normalized before VectorMA, so the trace runs from the attacker's origin far past the enemy along that line. + Q.fireHit = (g, i, aim, damage, kick) => { + const self = g.ents[i], en = g.ents[self.enemy]; + let dir = sub(en.origin, self.origin); + let range = len(dir); + if (range > aim[0]) return false; + aim = copy3(aim); + if (aim[1] > self.mins[0] && aim[1] < self.maxs[0]) range -= en.maxs[0]; // straight on: back up to the box edge + else aim[1] = aim[1] < 0 ? en.mins[0] : en.maxs[0]; // side hit: out to the box edge + let point = ma(self.origin, range, dir); + const tr = Q.trace(g, self.origin, null, null, point, i, Q.MASK_SHOT); + let target = tr.ent; + if (tr.fraction < 1) { + const h = g.ents[tr.ent]; + if (!h.takedamage) return false; + if ((h.svflags & Q.SVF_MONSTER) || h.client) target = self.enemy; // whatever it hits, it hits the enemy + } + const av = Q.angleVectors(self.angles); + point = ma(ma(ma(self.origin, range, av.forward), aim[1], av.right), aim[2], av.up); + dir = sub(point, en.origin); + Q.damage(g, target, i, i, dir, point, [0, 0, 0], damage, Math.trunc(kick / 2), Q.DAMAGE_NO_KNOCKBACK, 'hit'); + const t = g.ents[target]; + if (!(t.svflags & Q.SVF_MONSTER) && !t.client) return false; + // the special knockback: from the hit point towards the middle of the enemy's absolute box + const mid = [Q.absmin(en)[0] + 0.5 * (en.maxs[0] - en.mins[0]), Q.absmin(en)[1] + 0.5 * (en.maxs[1] - en.mins[1]), Q.absmin(en)[2] + 0.5 * (en.maxs[2] - en.mins[2])]; + en.velocity = ma(en.velocity, kick, norm(sub(mid, point))); + if (en.velocity[2] > 0) en.groundentity = -1; + Q.fx(g, 'slash', point, null, { owner: i }); + return true; + }; + // Regular (non-boss) death: gib below gib_health, else the death move; the corpse can still take damage. + function unitDie(gibs, deathMove) { + return (g, i, inflictor, attacker, damage) => { + const e = g.ents[i]; + if (e.health <= e.gib_health) { + for (const [kind, n, organic] of gibs.body) for (let k = 0; k < n; k++) Q.throwGib(g, i, kind, damage, organic); + Q.throwHead(g, i, gibs.head[0], damage, gibs.head[1]); + e.deadflag = Q.DEAD_DEAD; e.gibbed = true; + Q.fx(g, 'gibs', Q.center(e), null, { size: 32 }); + return; + } + if (e.deadflag === Q.DEAD_DEAD) return; + e.deadflag = Q.DEAD_DEAD; e.takedamage = Q.DAMAGE_YES; + setMove(e, typeof deathMove === 'function' ? deathMove(g, e) : deathMove); + }; + } + // M_FlyCheck / M_FliesOn / M_FliesOff: flies around a corpse (an effect, with its own random draws). + function flyCheck(g, i) { + const e = g.ents[i]; + if (Q.random(g) > 0.5) return; + e.think = 'M_FliesOn'; e.nextthink = g.ms + 5000 + 10000 * Q.random(g); + } + Q.THINK.M_FliesOn = (g, i) => { const e = g.ents[i]; e.flies = true; e.think = 'M_FliesOff'; e.nextthink = g.ms + 60000; }; + Q.THINK.M_FliesOff = (g, i) => { g.ents[i].flies = false; }; + + // ================= Tank Commander (m_tank.c, monster_tank_commander: the Tank with 1000 health, skin 2) ================= + const TANK_MG = [[22.9, -0.7, 25.3], [22.2, 6.2, 22.3], [19.4, 13.1, 18.6], [19.4, 18.8, 18.6], [17.9, 25.0, 18.6], [14.1, 30.5, 20.6], + [9.3, 35.3, 22.1], [4.7, 38.4, 22.1], [-1.1, 40.4, 24.1], [-6.5, 41.2, 24.1], [3.2, 40.1, 24.7], [11.7, 36.7, 26.0], [18.9, 31.3, 26.0], + [24.4, 24.4, 26.4], [27.1, 17.1, 27.2], [28.5, 9.1, 28.0], [27.1, 2.2, 28.0], [24.9, -2.8, 28.0], [21.6, -7.0, 26.4]]; + DEFS.monster_tank_commander = { + name: 'Chain-Gun Heavy Trooper', health: 1000, gib_health: -225, mass: 500, mins: [-32, -32, -16], maxs: [32, 32, 72], skin: 2, + moves: moves({ + stand: [0, 29, 's0x30', null], + start_walk: [30, 33, 'w0 w6x2 w11:tank_footstep', 'walk'], + walk: [34, 49, 'w4 w5 w3 w2 w5x2 w4 w4:tank_footstep w3 w5 w4 w5 w7x2 w6 w6:tank_footstep', null], + start_run: [30, 33, 'r0 r6x2 r11:tank_footstep', 'run'], + run: [34, 49, 'r4 r5 r3 r2 r5x2 r4 r4:tank_footstep r3 r5 r4 r5 r7x2 r6 r6:tank_footstep', null], + pain1: [197, 200, 'm0x4', 'run'], pain2: [201, 205, 'm0x5', 'run'], + pain3: [206, 221, 'm-7 m0x3 m2 m0x2 m3 m0 m2 m0x5 m0:tank_footstep', 'run'], + attack_blast: [55, 70, 'c0x4 c-1 c-2 c-1x2 c0 c0:TankBlaster c0x2 c0:TankBlaster c0x2 c0:TankBlaster', 'reattack_blaster'], + reattack_blast: [65, 70, 'c0x2 c0:TankBlaster c0x2 c0:TankBlaster', 'reattack_blaster'], + attack_post_blast: [71, 76, 'm0x2 m2 m3 m2 m-2:tank_footstep', 'run'], + attack_strike: [77, 114, 'm3 m2x2 m1 m6 m7 m9:tank_footstep m2 m1 m2 m2:tank_footstep m2 m0x4 m-2x2 m0:tank_windup m0x6 m0:TankStrike m0 m-1x5 m-3 m-10x2 m-2 m-3 m-2:tank_footstep', 'poststrike'], + attack_pre_rocket: [115, 135, 'c0x11 c1 c2 c7x2 c7:tank_footstep c0x4 c-3', 'doattack_rocket'], + attack_fire_rocket: [136, 144, 'c-3 c0 c0:TankRocket c0x2 c0:TankRocket c0x2 c-1:TankRocket', 'refire_rocket'], + attack_post_rocket: [145, 167, 'c0 c-1x2 c0 c2 c3 c4 c2 c0x3 c-9 c-8 c-7 c-1 c-1:tank_footstep c0x7', 'run'], + attack_chain: [168, 196, 'c0x5 n0:TankMachineGunx19 c0x5', 'run'], + death: [222, 253, 'm-7 m-2x2 m1 m3 m6 m1x2 m2 m0x3 m-2 m0x2 m-3 m0x6 m-4 m-6 m-4 m-5 m-7 m-15:tank_thud m-5 m0x3', 'dead'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), sight: sound, + tank_footstep: sound, tank_thud: sound, tank_windup: sound, TankStrike: sound, + // tank_run: AI_BRUTAL against a client; from walk / start_run straight into run, otherwise via start_run. + run(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + if (e.enemy >= 0 && g.ents[e.enemy].client) mi.aiflags |= AI_BRUTAL; else mi.aiflags &= ~AI_BRUTAL; + if (mi.aiflags & AI_STAND_GROUND) { setMove(e, 'stand'); return; } + setMove(e, mi.currentmove === 'walk' || mi.currentmove === 'start_run' ? 'run' : 'start_run'); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum |= 1; + if (damage <= 10) return; + if (debounced(g, e)) return; + if (damage <= 30 && Q.random(g) > 0.2) return; + if (g.skill >= 2 && ((e.frame >= 115 && e.frame <= 144) || (e.frame >= 55 && e.frame <= 70))) return; // not while attacking + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; + setMove(e, damage <= 30 ? 'pain1' : damage <= 60 ? 'pain2' : 'pain3'); + }, + TankBlaster(g, i) { + const e = g.ents[i], ofs = e.frame === 64 ? [20.7, -18.5, 28.7] : e.frame === 67 ? [16.6, -21.5, 30.1] : [11.8, -23.9, 32.1]; + const start = muzzle(e, ofs); + Q.fireBlaster(g, i, start, sub(enemyEye(g, e, 0), start), 30, 800, 'blaster', false); + flash(g, i, 'blaster', start); + }, + TankRocket(g, i) { + const e = g.ents[i], ofs = e.frame === 138 ? [6.2, 29.1, 49.1] : e.frame === 141 ? [6.9, 23.8, 49.1] : [8.3, 17.8, 49.5]; + const start = muzzle(e, ofs); + Q.monsterFireRocket(g, i, start, aimAt(g, start, enemyEye(g, e, 0)), 50, 550); + flash(g, i, 'rocket', start); + }, + // The chaingun sweep: pitch at the enemy's eye, yaw by frame from +40 to -32 and back to +40 degrees off the facing + // it had when the burst started (the 19 firing frames have no AI function, so the Tank does not turn meanwhile). + TankMachineGun(g, i) { + const e = g.ents[i], start = muzzle(e, TANK_MG[e.frame - 173]), dir = [0, 0, 0]; + if (e.enemy >= 0) dir[0] = Q.vectoangles(sub(enemyEye(g, e, 0), start))[0]; + dir[1] = e.frame <= 182 ? e.angles[1] - 8 * (e.frame - 178) : e.angles[1] + 8 * (e.frame - 186); + Q.monsterFireBullet(g, i, start, Q.angleVectors(dir).forward, 20, 4); + flash(g, i, 'mg', start); + }, + reattack_blaster(g, i) { // skill >= 2 only: 60 % another two bolts while the enemy is visible and alive + const e = g.ents[i]; + if (g.skill >= 2 && Q.visible(g, i, e.enemy) && g.ents[e.enemy].health > 0 && Q.random(g) <= 0.6) { setMove(e, 'reattack_blast'); return; } + setMove(e, 'attack_post_blast'); + }, + doattack_rocket: (g, i) => setMove(g.ents[i], 'attack_fire_rocket'), + refire_rocket(g, i) { // skill >= 2 only: 40 % another volley + const e = g.ents[i]; + if (g.skill >= 2 && g.ents[e.enemy].health > 0 && Q.visible(g, i, e.enemy) && Q.random(g) <= 0.4) { setMove(e, 'attack_fire_rocket'); return; } + setMove(e, 'attack_post_rocket'); + }, + poststrike(g, i) { g.ents[i].enemy = -1; DEFS.monster_tank_commander.run(g, i); }, + attack(g, i) { + const e = g.ents[i], mi = e.monsterinfo; + if (g.ents[e.enemy].health < 0) { setMove(e, 'attack_strike'); mi.aiflags &= ~AI_BRUTAL; return; } + const range = len(sub(g.ents[e.enemy].origin, e.origin)), r = Q.random(g); + if (range <= 125) setMove(e, r < 0.4 ? 'attack_chain' : 'attack_blast'); + else if (range <= 250) setMove(e, r < 0.5 ? 'attack_chain' : 'attack_blast'); + else if (r < 0.33) setMove(e, 'attack_chain'); + else if (r < 0.66) { setMove(e, 'attack_pre_rocket'); e.pain_debounce_time = g.ms + 5000; } // no pain for a while + else setMove(e, 'attack_blast'); + }, + die: unitDie({ body: [['meat', 1, true], ['metal', 4, false], ['chest', 1, true]], head: ['gear', false] }, 'death'), + dead: bossDead([-16, -16, -16], [16, 16, 0]), + }; + + // ================= Gladiator (m_gladiator.c) ================= + DEFS.monster_gladiator = { + name: 'Blade-Arm Gunner', health: 400, gib_health: -175, mass: 400, mins: [-32, -32, -24], maxs: [32, 32, 64], + moves: moves({ + stand: [0, 6, 's0x7', null], + walk: [7, 22, 'w15 w7 w6 w5 w2 w0 w2 w8 w12 w8 w5x2 w2x2 w1 w8', null], + run: [23, 28, 'r23 r14x2 r21 r12 r13', null], + attack_melee: [29, 45, 'c0x4 c0:gladiator_cleaver_swing c0 c0:GaldiatorMelee c0x3 c0:gladiator_cleaver_swing c0x2 c0:GaldiatorMelee c0x3', 'run'], + attack_gun: [46, 54, 'c0x3 c0:GladiatorGun c0x5', 'run'], + pain: [55, 60, 'm0x6', 'run'], + pain_air: [83, 89, 'm0x7', 'run'], + death: [61, 82, 'm0x22', 'dead'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, sight: sound, gladiator_cleaver_swing: sound, + melee: (g, i) => setMove(g.ents[i], 'attack_melee'), + GaldiatorMelee(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].mins[0], -4], 20 + (Q.rand(g) % 5), 300); }, + // gladiator_attack: nothing inside MELEE_DISTANCE + 32 (a small safe zone); otherwise the eye position is saved + // NOW and the railgun fires along it on the fourth frame of attack_gun (0.4 s later). + attack(g, i) { + const e = g.ents[i], en = g.ents[e.enemy]; + if (len(sub(e.origin, en.origin)) <= Q.MELEE_DISTANCE + 32) return; + e.pos1 = copy3(en.origin); e.pos1[2] += en.viewheight; + setMove(e, 'attack_gun'); + }, + GladiatorGun(g, i) { + const e = g.ents[i], start = muzzle(e, [30.0, 18.0, 28.0]); + Q.fireRail(g, i, start, norm(sub(e.pos1, start)), 50, 100); + flash(g, i, 'rail', start); + }, + pain(g, i, other, kick, damage) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) { + if (e.velocity[2] > 100 && e.monsterinfo.currentmove === 'pain') setMove(e, 'pain_air'); + return; + } + e.pain_debounce_time = g.ms + 3000; + Q.random(g); // which pain sound + if (g.skill === 3) return; + setMove(e, e.velocity[2] > 100 ? 'pain_air' : 'pain'); + }, + die: unitDie({ body: [['bone', 2, true], ['meat', 4, true]], head: ['head', true] }, 'death'), + dead: bossDead([-16, -16, -24], [16, 16, -8]), + }; + + // ================= Mutant (m_mutant.c) ================= + function mutantCheckJump(g, i) { + const e = g.ents[i], en = g.ents[e.enemy], esize = en.maxs[2] - en.mins[2], emin = Q.absmin(en)[2]; + if (Q.absmin(e)[2] > emin + 0.75 * esize) return false; + if (Q.absmax(e)[2] < emin + 0.25 * esize) return false; + const d = Math.sqrt((e.origin[0] - en.origin[0]) ** 2 + (e.origin[1] - en.origin[1]) ** 2); + if (d < 100) return false; + if (d > 100 && Q.random(g) < 0.9) return false; + return true; + } + DEFS.monster_mutant = { + name: 'Clawed Pouncer', health: 300, gib_health: -120, mass: 300, mins: [-32, -32, -24], maxs: [32, 32, 48], + moves: moves({ + stand: [62, 112, 's0x51', null], + start_walk: [126, 129, 'w5x2 w-2 w1', 'mutant_walk_loop'], + walk: [130, 141, 'w3 w1 w5 w10 w13 w10 w0 w5 w6 w16 w15 w6', null], + run: [56, 61, 'r40 r40:mutant_step r24 r5:mutant_step r17 r10', null], + attack: [8, 14, 'c0x2 c0:mutant_hit_left c0x2 c0:mutant_hit_right c0:mutant_check_refire', 'run'], + jump: [0, 7, 'c0 c17 c15:mutant_jump_takeoff c15 c15:mutant_check_landing c0 c3 c0', 'run'], + pain1: [34, 38, 'm4 m-3 m-8 m2 m5', 'run'], pain2: [39, 44, 'm-24 m11 m5 m-2 m6 m4', 'run'], + pain3: [45, 55, 'm-22 m3x2 m2 m1x2 m6 m3 m2 m0 m1', 'run'], + death1: [15, 23, 'm0x9', 'dead'], death2: [24, 33, 'm0x10', 'dead'], + }), + stand, walk: (g, i) => setMove(g.ents[i], 'start_walk'), mutant_walk_loop: (g, i) => setMove(g.ents[i], 'walk'), run: runOrStand, + sight: sound, + mutant_step: g => { Q.rand(g); }, // (rand() + 1) % 3 picks a footstep sound + melee: (g, i) => setMove(g.ents[i], 'attack'), + mutant_hit_left(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].mins[0], 8], 10 + (Q.rand(g) % 5), 100); }, + mutant_hit_right(g, i) { Q.fireHit(g, i, [Q.MELEE_DISTANCE, g.ents[i].maxs[0], 8], 10 + (Q.rand(g) % 5), 100); }, + mutant_check_refire(g, i) { // claw again while in melee range (and half the time anyway on skill 3) + const e = g.ents[i], en = e.enemy >= 0 ? g.ents[e.enemy] : null; + if (!en || !en.inuse || en.health <= 0) return; + if ((g.skill === 3 && Q.random(g) < 0.5) || Q.range(g, i, e.enemy) === Q.RANGE_MELEE) e.monsterinfo.nextframe = 8; + }, + attack: (g, i) => setMove(g.ents[i], 'jump'), + // The leap: 600 forward and 250 up from the facing at takeoff; AI_DUCKED suppresses pain until it lands. + mutant_jump_takeoff(g, i) { + const e = g.ents[i], forward = Q.angleVectors(e.angles).forward; + e.origin[2] += 1; + e.velocity = scale(forward, 600); e.velocity[2] = 250; + e.groundentity = -1; + e.monsterinfo.aiflags |= AI_DUCKED; + e.monsterinfo.attack_finished = g.ms + 3000; + e.touch = 'mutant_jump_touch'; + Q.event(g, 'mutant_leap'); + }, + mutant_check_landing(g, i) { // hold this frame until landing; after 3 s in the air jump again + const e = g.ents[i], mi = e.monsterinfo; + if (e.groundentity >= 0) { mi.attack_finished = 0; mi.aiflags &= ~AI_DUCKED; return; } + mi.nextframe = g.ms > mi.attack_finished ? 1 : 4; + }, + checkattack(g, i) { // mutant_checkattack: melee range first, then the 10 % leap check + const e = g.ents[i], mi = e.monsterinfo; + if (e.enemy < 0 || g.ents[e.enemy].health <= 0) return false; + if (Q.range(g, i, e.enemy) === Q.RANGE_MELEE) { mi.attack_state = AS_MELEE; return true; } + if (mutantCheckJump(g, i)) { mi.attack_state = AS_MISSILE; return true; } + return false; + }, + pain(g, i) { + const e = g.ents[i]; + if (e.health < e.max_health / 2) e.skinnum = 1; + if (debounced(g, e)) return; + e.pain_debounce_time = g.ms + 3000; + if (g.skill === 3) return; + const r = Q.random(g); + setMove(e, r < 0.33 ? 'pain1' : r < 0.66 ? 'pain2' : 'pain3'); + }, + die: unitDie({ body: [['bone', 2, true], ['meat', 4, true]], head: ['head', true] }, (g, e) => { e.skinnum = 1; return Q.random(g) < 0.5 ? 'death1' : 'death2'; }), + dead(g, i) { + const e = g.ents[i]; + e.mins = [-16, -16, -24]; e.maxs = [16, 16, -8]; e.movetype = 'toss'; e.svflags |= Q.SVF_DEADMONSTER; + flyCheck(g, i); + }, + }; + // mutant_jump_touch: a hit at more than 400 u/s does 40 + 10 * random() with as much knockback. + Q.TOUCH.mutant_jump_touch = (g, i, other, plane) => { + const e = g.ents[i]; + if (e.health <= 0) { e.touch = null; return; } + if (other > 0 && g.ents[other].takedamage && len(e.velocity) > 400) { + const normal = norm(e.velocity), point = ma(e.origin, e.maxs[0], normal); + const damage = Math.trunc(40 + 10 * Q.random(g)); + Q.damage(g, other, i, i, e.velocity, point, normal, damage, damage, 0, 'mutant_leap'); + } + if (!checkBottom(g, i)) { + if (e.groundentity >= 0) { e.monsterinfo.nextframe = 1; e.touch = null; } + return; + } + e.touch = null; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/q2player.js b/environments/games/web/games/quake2_remake/q2player.js new file mode 100644 index 0000000000000000000000000000000000000000..35a029bd1577602e9fc1934a3450bdbd3fd9631e --- /dev/null +++ b/environments/games/web/games/quake2_remake/q2player.js @@ -0,0 +1,852 @@ +/* Quake II (1997) boss arenas - the player: client input (cl_input.c CL_BaseMove, in_win.c IN_MouseMove), + player movement (qcommon/pmove.c Pmove), ClientThink / ClientBeginServerFrame (p_client.c), ClientEndServerFrame + (p_view.c falling damage, damage feedback), weapons (p_weapon.c Weapon_Generic and the eight weapons used here), + projectiles and hitscan (g_weapon.c), damage (g_combat.c T_Damage / T_RadiusDamage / CheckArmor / CanDamage) and + items (g_items.c armor, health, ammo). Independent reimplementation from the GPL-2.0 source release, commit + 372afde46e7defc9dd2d719a1732b8ace1fa096e; see q2core.js. */ +(function (root) { + 'use strict'; + const M = root.Quake2Game, Q = M.Q; + const { add, sub, scale, ma, dot, len, norm, copy3 } = Q; + + // ---------------- pmove.c constants and client cvar defaults (cl_main.c) ---------------- + const PM = { stopspeed: 100, maxspeed: 300, duckspeed: 100, accelerate: 10, airaccelerate: 0, friction: 6 }; + const PMF_DUCKED = 1, PMF_JUMP_HELD = 2, PMF_ON_GROUND = 4, PMF_TIME_WATERJUMP = 8, PMF_TIME_LAND = 16, PMF_TIME_TELEPORT = 32; + const CL = { forwardspeed: 200, sidespeed: 200, upspeed: 200, yawspeed: 140, anglespeedkey: 1.5, sensitivity: 3, m_yaw: 0.022, m_pitch: 0.022 }; + const MIN_STEP_NORMAL = 0.7, STOP_EPSILON = 0.1, MAX_CLIP_PLANES = 5; + Q.PM = PM; Q.CL = CL; + const PLAYER_MINS = [-16, -16, -24], PLAYER_MAXS = [16, 16, 32]; + + // ---------------- items (g_items.c itemlist order; weapnext walks down the list, weapprev up) ---------------- + const ITEMS = { + blaster: { index: 7, kind: 'weapon', name: 'Energy Pistol', ammo: null, quantity: 0 }, + shotgun: { index: 8, kind: 'weapon', name: 'Shotgun', ammo: 'shells', quantity: 1 }, + supershotgun: { index: 9, kind: 'weapon', name: 'Double Shotgun', ammo: 'shells', quantity: 2 }, + machinegun: { index: 10, kind: 'weapon', name: 'Machinegun', ammo: 'bullets', quantity: 1 }, + chaingun: { index: 11, kind: 'weapon', name: 'Chaingun', ammo: 'bullets', quantity: 1 }, + rocketlauncher: { index: 14, kind: 'weapon', name: 'Rocket Launcher', ammo: 'rockets', quantity: 1 }, + hyperblaster: { index: 15, kind: 'weapon', name: 'Pulse Cannon', ammo: 'cells', quantity: 1 }, + railgun: { index: 16, kind: 'weapon', name: 'Coilgun', ammo: 'slugs', quantity: 1 }, + }; + const WEAPON_ORDER = Object.keys(ITEMS).sort((a, b) => ITEMS[a].index - ITEMS[b].index); + const AMMO_MAX = { bullets: 200, shells: 100, rockets: 50, cells: 200, slugs: 50 }; + const AMMO_PICKUP = { shells: 10, bullets: 50, cells: 50, rockets: 5, slugs: 10 }; + // gitem_armor_t: base_count, max_count, normal_protection, energy_protection. ArmorIndex checks jacket, combat, body. + const ARMOR = { jacket: [25, 50, 0.30, 0.00], combat: [50, 100, 0.60, 0.30], body: [100, 200, 0.80, 0.60] }; + const ARMOR_ORDER = ['jacket', 'combat', 'body']; + Q.ITEMS = ITEMS; Q.ARMOR = ARMOR; Q.AMMO_MAX = AMMO_MAX; Q.WEAPON_ORDER = WEAPON_ORDER; + Q.armorIndex = p => ARMOR_ORDER.find(a => p.inv[a] > 0) || null; + + // ---------------- player spawn (PutClientInServer + ChangeWeapon) ---------------- + Q.spawnPlayer = (g, spec) => { + const p = g.ents[1] = Q.blankEdict(); + Object.assign(p, { + classname: 'player', client: true, origin: copy3(spec.origin), old_origin: copy3(spec.origin), mins: copy3(PLAYER_MINS), maxs: copy3(PLAYER_MAXS), + viewheight: 22, health: 100, max_health: 100, mass: 200, takedamage: Q.DAMAGE_AIM, solid: Q.SOLID_BBOX, clipmask: Q.MASK_PLAYERSOLID, + movetype: 'walk', pain_debounce_time: 0, air_finished: 12000, + viewangles: [0, spec.yaw, 0], v_angle: [0, spec.yaw, 0], + pm: { origin: spec.origin.map(v => Math.trunc(v * 8)), velocity: [0, 0, 0], flags: 0, time: 0 }, old_pmove: null, + buttons: 0, oldbuttons: 0, latched: 0, weapon_thunk: false, inv: Object.assign({}, spec.inventory), + weapon: null, newweapon: spec.weapon, lastweapon: null, weaponstate: 0, gunframe: 0, machinegun_shots: 0, + kick_angles: [0, 0, 0], kick_origin: [0, 0, 0], oldvelocity: [0, 0, 0], damage_blood: 0, damage_armor: 0, damage_knockback: 0, + damage_from: [0, 0, 0], damage_alpha: 0, bonus_alpha: 0, fall_value: 0, fall_time: 0, mynoise: -1, mynoise2: -1, pickup: null, pickup_time: 0, fired: 0, + }); + changeWeapon(g, p); + }; + + // ---------------- client side: usercmd from held keys and the per-tick mouse delta ---------------- + // keys: Set of held key names, pressed: newly pressed keys, mouse: [dx, dy, dz] for this tick. msec is this host + // frame (16 or 17 ms at 60 Hz, q2-arena@3): one usercmd per client frame, as the original client at cl_maxfps 60. + Q.buildUsercmd = (g, keys, pressed, mouse, msec) => { + const p = g.ents[1], frametime = msec / 1000, speed = keys.has('Shift'); + // CL_AdjustAngles: keyboard turning, cl_yawspeed 140 deg/s, x1.5 with the speed key held. + const turn = (speed ? frametime * CL.anglespeedkey : frametime) * CL.yawspeed; + if (keys.has('E')) p.viewangles[1] -= turn; + if (keys.has('Q')) p.viewangles[1] += turn; + // IN_MouseMove with freelook: yaw -= m_yaw*sensitivity*dx, pitch += m_pitch*sensitivity*dy. + p.viewangles[1] -= CL.m_yaw * CL.sensitivity * (mouse[0] || 0); + p.viewangles[0] += CL.m_pitch * CL.sensitivity * (mouse[1] || 0); + p.viewangles[1] = ((p.viewangles[1] % 360) + 360) % 360; // client angles stay unquantized; ANGLE2SHORT wraps + // CL_ClampPitch (delta_angles are zero here): +-89 degrees. + if (p.viewangles[0] > 89) p.viewangles[0] = 89; + if (p.viewangles[0] < -89) p.viewangles[0] = -89; + const cmd = { msec, buttons: 0, angles: p.viewangles.map(Q.ANGLE2SHORT), forwardmove: 0, sidemove: 0, upmove: 0 }; + if (keys.has('D')) cmd.sidemove += CL.sidespeed; + if (keys.has('A')) cmd.sidemove -= CL.sidespeed; + if (keys.has('Space')) cmd.upmove += CL.upspeed; + if (keys.has('L')) cmd.upmove -= CL.upspeed; + if (keys.has('W')) cmd.forwardmove += CL.forwardspeed; + if (keys.has('S')) cmd.forwardmove -= CL.forwardspeed; + if (speed) { cmd.forwardmove *= 2; cmd.sidemove *= 2; cmd.upmove *= 2; } // (in_speed ^ cl_run 0) + if (keys.has('J') || keys.has('LMB')) cmd.buttons |= 1; // BUTTON_ATTACK + // Console commands bound to keys arrive before the move: weapnext (K / RMB / wheel up), weapprev (R / wheel down). + const next = pressed.has('K') || pressed.has('RMB') || (mouse[2] || 0) > 0, prev = pressed.has('R') || (mouse[2] || 0) < 0; + if (next) Q.cmdWeapCycle(g, -1); else if (prev) Q.cmdWeapCycle(g, +1); + return cmd; + }; + // Cmd_WeapNext_f / Cmd_WeapPrev_f walk itemlist away from the current weapon and call Use_Weapon on every owned + // weapon; the loop only stops when it comes back to pers.weapon (Use_Weapon sets newweapon, not weapon), so the + // last successful use wins: weapnext ends on the nearest higher-index weapon (wrapping), weapprev on the nearest + // lower one. dir -1 = weapnext, +1 = weapprev (the order the C loop visits indices). + Q.cmdWeapCycle = (g, dir) => { + const p = g.ents[1]; + if (!p.weapon || p.health <= 0) return; + const cur = WEAPON_ORDER.indexOf(p.weapon), n = WEAPON_ORDER.length; + for (let k = 1; k < n; k++) { + const w = WEAPON_ORDER[(cur + dir * k + n * 2) % n]; + if (p.inv[w]) useWeapon(g, p, w); + } + }; + function useWeapon(g, p, w) { // Use_Weapon + if (w === p.weapon) return; + const it = ITEMS[w]; + if (it.ammo && (!p.inv[it.ammo] || p.inv[it.ammo] < it.quantity)) return; + p.newweapon = w; + } + Q.useWeapon = useWeapon; + + // ---------------- Pmove ---------------- + function pmTrace(g, start, mins, maxs, end) { return Q.trace(g, start, mins, maxs, end, 1, Q.MASK_PLAYERSOLID); } + function clipVelocity(v, n, overbounce) { + const backoff = dot(v, n) * overbounce, out = [0, 0, 0]; + for (let i = 0; i < 3; i++) { out[i] = v[i] - n[i] * backoff; if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) out[i] = 0; } + return out; + } + function stepSlideMove_(g, pm, pml) { + const primal = copy3(pml.velocity), planes = []; + let time_left = pml.frametime; + for (let bump = 0; bump < 4; bump++) { + const end = [0, 1, 2].map(i => pml.origin[i] + time_left * pml.velocity[i]); + const tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, end); + if (tr.allsolid) { pml.velocity[2] = 0; return; } + if (tr.fraction > 0) { pml.origin = copy3(tr.endpos); planes.length = 0; } + if (tr.fraction === 1) break; + if (pm.touch.length < 32) pm.touch.push(tr.ent); + time_left -= time_left * tr.fraction; + if (planes.length >= MAX_CLIP_PLANES) { pml.velocity = [0, 0, 0]; break; } + planes.push(tr.normal); + let i; + for (i = 0; i < planes.length; i++) { + pml.velocity = clipVelocity(pml.velocity, planes[i], 1.01); + let j; + for (j = 0; j < planes.length; j++) if (j !== i && dot(pml.velocity, planes[j]) < 0) break; + if (j === planes.length) break; + } + if (i === planes.length) { + if (planes.length !== 2) { pml.velocity = [0, 0, 0]; break; } + const dir = Q.cross(planes[0], planes[1]); pml.velocity = scale(dir, dot(dir, pml.velocity)); + } + if (dot(pml.velocity, primal) <= 0) { pml.velocity = [0, 0, 0]; break; } + } + if (pm.s.time) pml.velocity = primal; + } + function stepSlideMove(g, pm, pml) { + const start_o = copy3(pml.origin), start_v = copy3(pml.velocity); + stepSlideMove_(g, pm, pml); + const down_o = copy3(pml.origin), down_v = copy3(pml.velocity); + const up = copy3(start_o); up[2] += Q.STEPSIZE; + let tr = pmTrace(g, up, pm.mins, pm.maxs, up); + if (tr.allsolid) return; // can't step up + pml.origin = up; pml.velocity = copy3(start_v); + stepSlideMove_(g, pm, pml); + const down = copy3(pml.origin); down[2] -= Q.STEPSIZE; + tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, down); + if (!tr.allsolid) pml.origin = copy3(tr.endpos); + const down_dist = (down_o[0] - start_o[0]) ** 2 + (down_o[1] - start_o[1]) ** 2; + const up_dist = (pml.origin[0] - start_o[0]) ** 2 + (pml.origin[1] - start_o[1]) ** 2; + if (down_dist > up_dist || tr.normal[2] < MIN_STEP_NORMAL) { pml.origin = down_o; pml.velocity = down_v; return; } + pml.velocity[2] = down_v[2]; + } + function friction(pm, pml) { + const v = pml.velocity, speed = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + if (speed < 1) { v[0] = 0; v[1] = 0; return; } + let drop = 0; + // SV_Trace always reports a ground surface (CM_BoxTrace starts from nullsurface); no slick surfaces here. + if (pm.groundentity >= 0) { const control = speed < PM.stopspeed ? PM.stopspeed : speed; drop += control * PM.friction * pml.frametime; } + let newspeed = speed - drop; if (newspeed < 0) newspeed = 0; newspeed /= speed; + v[0] *= newspeed; v[1] *= newspeed; v[2] *= newspeed; + } + function accelerate(pml, wishdir, wishspeed, accel) { + const currentspeed = dot(pml.velocity, wishdir), addspeed = wishspeed - currentspeed; + if (addspeed <= 0) return; + let accelspeed = accel * pml.frametime * wishspeed; if (accelspeed > addspeed) accelspeed = addspeed; + for (let i = 0; i < 3; i++) pml.velocity[i] += accelspeed * wishdir[i]; + } + function airMove(g, pm, pml) { + const fmove = pm.cmd.forwardmove, smove = pm.cmd.sidemove; + let wishvel = [pml.forward[0] * fmove + pml.right[0] * smove, pml.forward[1] * fmove + pml.right[1] * smove, 0]; + let wishspeed = len(wishvel); const wishdir = norm(wishvel); + const maxspeed = (pm.s.flags & PMF_DUCKED) ? PM.duckspeed : PM.maxspeed; + if (wishspeed > maxspeed) { wishvel = scale(wishvel, maxspeed / wishspeed); wishspeed = maxspeed; } + if (pm.groundentity >= 0) { + pml.velocity[2] = 0; + accelerate(pml, wishdir, wishspeed, PM.accelerate); + pml.velocity[2] = 0; // gravity > 0 + if (!pml.velocity[0] && !pml.velocity[1]) return; + stepSlideMove(g, pm, pml); + } else { + accelerate(pml, wishdir, wishspeed, 1); // pm_airaccelerate 0 + pml.velocity[2] -= Q.SV_GRAVITY * pml.frametime; + stepSlideMove(g, pm, pml); + } + } + function catagorizePosition(g, pm, pml) { + const point = [pml.origin[0], pml.origin[1], pml.origin[2] - 0.25]; + if (pml.velocity[2] > 180) { pm.s.flags &= ~PMF_ON_GROUND; pm.groundentity = -1; } + else { + const tr = pmTrace(g, pml.origin, pm.mins, pm.maxs, point); + pml.groundsurface = tr.fraction < 1 || tr.startsolid; + if (tr.normal[2] < 0.7 && !tr.startsolid) { pm.groundentity = -1; pm.s.flags &= ~PMF_ON_GROUND; } + else { + pm.groundentity = tr.ent; + if (pm.s.flags & PMF_TIME_WATERJUMP) { pm.s.flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND | PMF_TIME_TELEPORT); pm.s.time = 0; } + if (!(pm.s.flags & PMF_ON_GROUND)) { + pm.s.flags |= PMF_ON_GROUND; + if (pml.velocity[2] < -200) { pm.s.flags |= PMF_TIME_LAND; pm.s.time = pml.velocity[2] < -400 ? 25 : 18; } + } + } + if (pm.touch.length < 32) pm.touch.push(tr.ent); + } + pm.waterlevel = 0; + } + function checkJump(pm, pml) { + if (pm.s.flags & PMF_TIME_LAND) return; + if (pm.cmd.upmove < 10) { pm.s.flags &= ~PMF_JUMP_HELD; return; } + if (pm.s.flags & PMF_JUMP_HELD) return; + if (pm.groundentity < 0) return; + pm.s.flags |= PMF_JUMP_HELD; pm.groundentity = -1; + pml.velocity[2] += 270; if (pml.velocity[2] < 270) pml.velocity[2] = 270; + } + function checkDuck(g, pm, pml) { + pm.mins = [-16, -16, -24]; pm.maxs = [16, 16, 32]; + if (pm.cmd.upmove < 0 && (pm.s.flags & PMF_ON_GROUND)) pm.s.flags |= PMF_DUCKED; + else if (pm.s.flags & PMF_DUCKED) { const tr = pmTrace(g, pml.origin, pm.mins, [16, 16, 32], pml.origin); if (!tr.allsolid) pm.s.flags &= ~PMF_DUCKED; } + if (pm.s.flags & PMF_DUCKED) { pm.maxs[2] = 4; pm.viewheight = -2; } else { pm.maxs[2] = 32; pm.viewheight = 22; } + } + const goodPosition = (g, pm) => { const o = pm.s.origin.map(v => v * 0.125); return !pmTrace(g, o, pm.mins, pm.maxs, o).allsolid; }; + function snapPosition(g, pm, pml) { + const JITTER = [0, 4, 1, 2, 3, 5, 6, 7], sign = [0, 0, 0]; + pm.s.velocity = pml.velocity.map(v => Math.trunc(v * 8)); + for (let i = 0; i < 3; i++) { + sign[i] = pml.origin[i] >= 0 ? 1 : -1; + pm.s.origin[i] = Math.trunc(pml.origin[i] * 8); + if (pm.s.origin[i] * 0.125 === pml.origin[i]) sign[i] = 0; + } + const base = copy3(pm.s.origin); + for (let j = 0; j < 8; j++) { + const bits = JITTER[j]; pm.s.origin = copy3(base); + for (let i = 0; i < 3; i++) if (bits & (1 << i)) pm.s.origin[i] += sign[i]; + if (goodPosition(g, pm)) return; + } + pm.s.origin = copy3(pml.previous_origin); + } + function initialSnapPosition(g, pm, pml) { + const OFS = [0, -1, 1], base = copy3(pm.s.origin); + for (let z = 0; z < 3; z++) for (let y = 0; y < 3; y++) for (let x = 0; x < 3; x++) { + pm.s.origin = [base[0] + OFS[x], base[1] + OFS[y], base[2] + OFS[z]]; + if (goodPosition(g, pm)) { pml.origin = pm.s.origin.map(v => v * 0.125); pml.previous_origin = copy3(pm.s.origin); return; } + } + } + function pmove(g, pm) { + pm.touch = []; pm.viewangles = [0, 0, 0]; pm.viewheight = 0; pm.groundentity = -1; pm.waterlevel = 0; + const pml = { origin: pm.s.origin.map(v => v * 0.125), velocity: pm.s.velocity.map(v => v * 0.125), previous_origin: copy3(pm.s.origin), frametime: pm.cmd.msec * 0.001, groundsurface: false }; + // PM_ClampAngles (delta_angles 0) + pm.viewangles = pm.cmd.angles.map(Q.SHORT2ANGLE); + if (pm.viewangles[0] > 89 && pm.viewangles[0] < 180) pm.viewangles[0] = 89; + else if (pm.viewangles[0] < 271 && pm.viewangles[0] >= 180) pm.viewangles[0] = 271; + let av = Q.angleVectors(pm.viewangles); pml.forward = av.forward; pml.right = av.right; + checkDuck(g, pm, pml); + if (pm.snapinitial) initialSnapPosition(g, pm, pml); + catagorizePosition(g, pm, pml); + if (pm.s.time) { + let msec = pm.cmd.msec >> 3; if (!msec) msec = 1; + if (msec >= pm.s.time) { pm.s.flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND | PMF_TIME_TELEPORT); pm.s.time = 0; } else pm.s.time -= msec; + } + checkJump(pm, pml); + friction(pm, pml); + const angles = copy3(pm.viewangles); + if (angles[0] > 180) angles[0] -= 360; + angles[0] /= 3; + av = Q.angleVectors(angles); pml.forward = av.forward; pml.right = av.right; + airMove(g, pm, pml); + catagorizePosition(g, pm, pml); + snapPosition(g, pm, pml); + } + + // ---------------- ClientThink ---------------- + Q.clientThink = (g, cmd) => { + const p = g.ents[1]; + const pm = { s: { origin: p.origin.map(v => Math.trunc(v * 8)), velocity: p.velocity.map(v => Math.trunc(v * 8)), flags: p.pm.flags, time: p.pm.time }, cmd }; + pm.snapinitial = !p.old_pmove || JSON.stringify(p.old_pmove) !== JSON.stringify(pm.s); + pmove(g, pm); + p.pm = { origin: copy3(pm.s.origin), velocity: copy3(pm.s.velocity), flags: pm.s.flags, time: pm.s.time }; + p.old_pmove = JSON.parse(JSON.stringify(p.pm)); + p.origin = pm.s.origin.map(v => v * 0.125); p.velocity = pm.s.velocity.map(v => v * 0.125); + p.mins = copy3(pm.mins); p.maxs = copy3(pm.maxs); + if (p.groundentity >= 0 && pm.groundentity < 0 && cmd.upmove >= 10) { Q.playerNoise(g, p.origin, 'self'); Q.event(g, 'jump'); } + p.viewheight = pm.viewheight; p.groundentity = pm.groundentity; + p.v_angle = copy3(pm.viewangles); + touchTriggers(g, 1); + const seen = new Set(); + for (const other of pm.touch) { + if (other <= 0 || seen.has(other)) continue; seen.add(other); + const o = g.ents[other]; + if (o && o.inuse && o.touch && Q.TOUCH[o.touch]) Q.TOUCH[o.touch](g, other, 1, null); + } + p.oldbuttons = p.buttons; p.buttons = cmd.buttons; p.latched |= p.buttons & ~p.oldbuttons; + if ((p.latched & 1) && !p.weapon_thunk) { p.weapon_thunk = true; thinkWeapon(g); } + }; + function touchTriggers(g, i) { // G_TouchTriggers for the player: item triggers overlapping the absolute box + const e = g.ents[i]; + for (let k = 1; k < g.ents.length; k++) { + const t = g.ents[k]; + if (!t.inuse || t.solid !== Q.SOLID_TRIGGER || !t.touch) continue; + if (Q.boxesOverlap(e, t)) Q.TOUCH[t.touch](g, k, i, null); + if (!e.inuse) return; + } + } + + // ---------------- ClientBeginServerFrame / ClientEndServerFrame ---------------- + Q.clientBeginServerFrame = g => { + const p = g.ents[1]; + if (!p.weapon_thunk) thinkWeapon(g); else p.weapon_thunk = false; + if (p.deadflag) return; + if (!Q.visiblePoint(g, 1, Q.trailLastSpot(g).origin)) Q.playerTrailAdd(g, p.old_origin); + p.latched = 0; + }; + Q.clientEndServerFrame = g => { + const p = g.ents[1]; + fallingDamage(g, p); + damageFeedback(g, p); + // SV_CalcBlend drops the flashes after P_DamageFeedback added to them. + p.damage_alpha = Math.max(0, p.damage_alpha - 0.06); p.bonus_alpha = Math.max(0, p.bonus_alpha - 0.1); + p.oldvelocity = copy3(p.velocity); + p.kick_origin = [0, 0, 0]; p.kick_angles = [0, 0, 0]; + }; + function fallingDamage(g, p) { // P_FallingDamage + let delta; + if (p.oldvelocity[2] < 0 && p.velocity[2] > p.oldvelocity[2] && p.groundentity < 0) delta = p.oldvelocity[2]; + else { if (p.groundentity < 0) return; delta = p.velocity[2] - p.oldvelocity[2]; } + delta = delta * delta * 0.0001; + if (delta < 15) return; + p.fall_value = Math.min(40, delta * 0.5); p.fall_time = g.ms + 300; + if (delta > 30) { + p.pain_debounce_time = g.ms; + let damage = Math.trunc((delta - 30) / 2); if (damage < 1) damage = 1; + Q.damage(g, 1, 0, 0, [0, 0, 1], p.origin, [0, 0, 0], damage, 0, 0, 'falling'); + } + } + function damageFeedback(g, p) { // P_DamageFeedback: screen flash, and one rand() for the pain sound + let count = p.damage_blood + p.damage_armor; + if (!count) return; + if (count < 10) count = 10; // always make a visible effect + if (g.ms > p.pain_debounce_time) { Q.rand(g); p.pain_debounce_time = g.ms + 700; } + if (p.damage_alpha < 0) p.damage_alpha = 0; + p.damage_alpha = Math.min(0.6, Math.max(0.2, p.damage_alpha + count * 0.01)); + p.damage_from_dir = sub(p.damage_from, p.origin); + p.damage_blood = 0; p.damage_armor = 0; p.damage_knockback = 0; + } + // PlayerNoise: the first call spawns the two player noise edicts (they hold slots in the edict list). Weapon + // and self noise (firing, jumping) go to mynoise / level.sound_entity, impact noise to mynoise2 / sound2_entity. + Q.playerNoise = (g, where, type) => { + const p = g.ents[1]; + if (p.mynoise < 0) { + for (const k of ['mynoise', 'mynoise2']) { p[k] = Q.spawn(g); Object.assign(g.ents[p[k]], { classname: 'player_noise', svflags: Q.SVF_NOCLIENT, owner: 1, mins: [-8, -8, -8], maxs: [8, 8, 8], solid: Q.SOLID_NOT }); } + } + const n = type === 'impact' ? p.mynoise2 : p.mynoise; + if (type === 'impact') { g.sound2_entity = n; g.sound2_entity_framenum = g.framenum; } else { g.sound_entity = n; g.sound_entity_framenum = g.framenum; } + g.ents[n].origin = copy3(where || p.origin); g.ents[n].teleport_time = g.ms; + }; + + // ---------------- weapons ---------------- + const READY = 0, ACTIVATING = 1, DROPPING = 2, FIRING = 3; + // Weapon_Generic(FRAME_ACTIVATE_LAST, FRAME_FIRE_LAST, FRAME_IDLE_LAST, FRAME_DEACTIVATE_LAST, pause, fire) + const WDEF = { + blaster: { frames: [4, 8, 52, 55], pause: [19, 32], fire: [5], fn: 'blaster' }, + shotgun: { frames: [7, 18, 36, 39], pause: [22, 28, 34], fire: [8, 9], fn: 'shotgun' }, + supershotgun: { frames: [6, 17, 57, 61], pause: [29, 42, 57], fire: [7], fn: 'supershotgun' }, + machinegun: { frames: [3, 5, 45, 49], pause: [23, 45], fire: [4, 5], fn: 'machinegun' }, + chaingun: { frames: [4, 31, 61, 64], pause: [38, 43, 51, 61], fire: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21], fn: 'chaingun' }, + rocketlauncher: { frames: [4, 12, 50, 54], pause: [25, 33, 42, 50], fire: [5], fn: 'rocket' }, + hyperblaster: { frames: [5, 20, 49, 53], pause: [], fire: [6, 7, 8, 9, 10, 11], fn: 'hyperblaster' }, + railgun: { frames: [3, 18, 56, 61], pause: [56], fire: [4], fn: 'railgun' }, + }; + Q.WDEF = WDEF; + function changeWeapon(g, p) { + p.lastweapon = p.weapon; p.weapon = p.newweapon; p.newweapon = null; p.machinegun_shots = 0; + if (!p.weapon) return; + p.weaponstate = ACTIVATING; p.gunframe = 0; + } + function noAmmoWeaponChange(g, p) { + const has = (w, ammo, n = 1) => p.inv[w] && p.inv[ammo] >= n; + p.newweapon = has('railgun', 'slugs') ? 'railgun' : has('hyperblaster', 'cells') ? 'hyperblaster' : has('chaingun', 'bullets') ? 'chaingun' + : has('machinegun', 'bullets') ? 'machinegun' : has('supershotgun', 'shells', 2) ? 'supershotgun' : has('shotgun', 'shells') ? 'shotgun' : 'blaster'; + } + function thinkWeapon(g) { + const p = g.ents[1]; + if (p.health < 1) { p.newweapon = null; changeWeapon(g, p); } + if (p.weapon) weaponGeneric(g, p, WDEF[p.weapon]); + } + function weaponGeneric(g, p, w) { + const [ACT_LAST, FIRE_LAST, IDLE_LAST, DEACT_LAST] = w.frames; + const FIRE_FIRST = ACT_LAST + 1, IDLE_FIRST = FIRE_LAST + 1, DEACT_FIRST = IDLE_LAST + 1; + if (p.deadflag) return; + if (p.weaponstate === DROPPING) { if (p.gunframe === DEACT_LAST) { changeWeapon(g, p); return; } p.gunframe++; return; } + if (p.weaponstate === ACTIVATING) { if (p.gunframe === ACT_LAST) { p.weaponstate = READY; p.gunframe = IDLE_FIRST; return; } p.gunframe++; return; } + if (p.newweapon && p.weaponstate !== FIRING) { p.weaponstate = DROPPING; p.gunframe = DEACT_FIRST; return; } + if (p.weaponstate === READY) { + if ((p.latched | p.buttons) & 1) { + p.latched &= ~1; + const it = ITEMS[p.weapon]; + if (!it.ammo || p.inv[it.ammo] >= it.quantity) { p.gunframe = FIRE_FIRST; p.weaponstate = FIRING; } + else { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); } + } else { + if (p.gunframe === IDLE_LAST) { p.gunframe = IDLE_FIRST; return; } + for (const f of w.pause) if (p.gunframe === f && (Q.rand(g) & 15)) return; + p.gunframe++; return; + } + } + if (p.weaponstate === FIRING) { + let fired = false; + for (const f of w.fire) if (p.gunframe === f) { FIRE[w.fn](g, p); fired = true; break; } + if (!fired) p.gunframe++; + if (p.gunframe === IDLE_FIRST + 1) p.weaponstate = READY; + } + } + // P_ProjectSource (right handed), from the eye height. + const projectSource = (p, offset, forward, right) => Q.projectSource(p.origin, offset, forward, right); + const FIRE = { + blaster(g, p) { blasterFire(g, p, [0, 0, 0], 10, false, 'blaster'); p.gunframe++; }, + hyperblaster(g, p) { + if (!(p.buttons & 1)) p.gunframe++; + else { + if (!p.inv.cells) { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); } + else { + const rotation = (p.gunframe - 5) * 2 * Math.PI / 6; + blasterFire(g, p, [-4 * Q.sin(rotation), 0, 4 * Q.cos(rotation)], 20, true, 'hyperblaster'); + p.inv.cells--; + } + p.gunframe++; + if (p.gunframe === 12 && p.inv.cells) p.gunframe = 6; + } + }, + machinegun(g, p) { + if (!(p.buttons & 1)) { p.machinegun_shots = 0; p.gunframe++; return; } + p.gunframe = p.gunframe === 5 ? 4 : 5; + if (p.inv.bullets < 1) { p.gunframe = 6; if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); return; } + for (let i = 1; i < 3; i++) { p.kick_origin[i] = Q.crandom(g) * 0.35; p.kick_angles[i] = Q.crandom(g) * 0.7; } + p.kick_origin[0] = Q.crandom(g) * 0.35; p.kick_angles[0] = p.machinegun_shots * -1.5; + p.machinegun_shots = Math.min(9, p.machinegun_shots + 1); + const av = Q.angleVectors(add(p.v_angle, p.kick_angles)); + const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right); + Q.fireBullet(g, 1, start, av.forward, 8, 2, 300, 500, 'machinegun'); + Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'machinegun'); p.inv.bullets--; + }, + chaingun(g, p) { + if (p.gunframe === 14 && !(p.buttons & 1)) { p.gunframe = 32; return; } + else if (p.gunframe === 21 && (p.buttons & 1) && p.inv.bullets) p.gunframe = 15; + else p.gunframe++; + let shots = p.gunframe <= 9 ? 1 : p.gunframe <= 14 ? ((p.buttons & 1) ? 2 : 1) : 3; + if (p.inv.bullets < shots) shots = p.inv.bullets; + if (!shots) { if (g.ms >= p.pain_debounce_time) p.pain_debounce_time = g.ms + 1000; noAmmoWeaponChange(g, p); return; } + for (let i = 0; i < 3; i++) { p.kick_origin[i] = Q.crandom(g) * 0.35; p.kick_angles[i] = Q.crandom(g) * 0.7; } + for (let i = 0; i < shots; i++) { + const av = Q.angleVectors(p.v_angle), r = 7 + Q.crandom(g) * 4, u = Q.crandom(g) * 4; + const start = projectSource(p, [0, r, u + p.viewheight - 8], av.forward, av.right); + Q.fireBullet(g, 1, start, av.forward, 8, 2, 300, 500, 'chaingun'); + } + Q.playerNoise(g, p.origin, 'weapon'); muzzle(g, p, 'chaingun'); p.inv.bullets -= shots; + }, + shotgun(g, p) { + if (p.gunframe === 9) { p.gunframe++; return; } + const av = Q.angleVectors(p.v_angle); + p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -2; + const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right); + Q.fireShotgun(g, 1, start, av.forward, 4, 8, 500, 500, 12, 'shotgun'); + p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'shotgun'); p.inv.shells--; + }, + supershotgun(g, p) { + const av = Q.angleVectors(p.v_angle); + p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -2; + const start = projectSource(p, [0, 8, p.viewheight - 8], av.forward, av.right); + let f = Q.angleVectors([p.v_angle[0], p.v_angle[1] - 5, p.v_angle[2]]).forward; + Q.fireShotgun(g, 1, start, f, 6, 12, 1000, 500, 10, 'sshotgun'); + f = Q.angleVectors([p.v_angle[0], p.v_angle[1] + 5, p.v_angle[2]]).forward; + Q.fireShotgun(g, 1, start, f, 6, 12, 1000, 500, 10, 'sshotgun'); + p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'supershotgun'); p.inv.shells -= 2; + }, + rocket(g, p) { + const damage = 100 + Math.trunc(Q.random(g) * 20.0); + const av = Q.angleVectors(p.v_angle); + p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -1; + const start = projectSource(p, [8, 8, p.viewheight - 8], av.forward, av.right); + Q.fireRocket(g, 1, start, av.forward, damage, 650, 120, 120); + p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'rocketlauncher'); p.inv.rockets--; + }, + railgun(g, p) { + const av = Q.angleVectors(p.v_angle); + p.kick_origin = scale(av.forward, -3); p.kick_angles[0] = -3; + const start = projectSource(p, [0, 7, p.viewheight - 8], av.forward, av.right); + Q.fireRail(g, 1, start, av.forward, 150, 250); + p.gunframe++; Q.playerNoise(g, start, 'weapon'); muzzle(g, p, 'railgun'); p.inv.slugs--; + }, + }; + function blasterFire(g, p, g_offset, damage, hyper, effect) { + const av = Q.angleVectors(p.v_angle); + const start = projectSource(p, add([24, 8, p.viewheight - 8], g_offset), av.forward, av.right); + p.kick_origin = scale(av.forward, -2); p.kick_angles[0] = -1; + Q.fireBlaster(g, 1, start, av.forward, damage, 1000, effect, hyper); + Q.playerNoise(g, start, 'weapon'); muzzle(g, p, hyper ? 'hyperblaster' : 'blaster'); + } + function muzzle(g, p, weapon) { p.fired = g.ms; p.firedWeapon = weapon; } + + // ---------------- hitscan and projectiles (g_weapon.c) ---------------- + // check_dodge: skill 0 skips three out of four checks; no monster here has a dodge function. + function checkDodge(g, self) { if (g.skill === 0 && Q.random(g) > 0.25) return; } + function fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod) { + const se = g.ents[self]; + let tr = Q.trace(g, se.origin, null, null, start, self, Q.MASK_SHOT); + let end = null; + if (!(tr.fraction < 1.0)) { + const av = Q.angleVectors(Q.vectoangles(aimdir)); + const r = Q.crandom(g) * hspread, u = Q.crandom(g) * vspread; + end = ma(ma(ma(start, 8192, av.forward), r, av.right), u, av.up); + tr = Q.trace(g, start, null, null, end, self, Q.MASK_SHOT); + } + if (tr.fraction < 1.0 && !tr.sky) { + const hit = g.ents[tr.ent]; + if (tr.ent > 0 && hit.takedamage) Q.damage(g, tr.ent, self, self, aimdir, tr.endpos, tr.normal, damage, kick, Q.DAMAGE_BULLET, mod); + else { Q.fx(g, 'puff', tr.endpos, tr.normal); if (g.ents[self].client) Q.playerNoise(g, tr.endpos, 'impact'); } + } + Q.fx(g, 'tracer', start, null, { to: tr.endpos, from: self === 1 ? 'player' : 'monster' }); + } + Q.fireBullet = (g, self, start, aimdir, damage, kick, hspread, vspread, mod) => fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod); + Q.fireShotgun = (g, self, start, aimdir, damage, kick, hspread, vspread, count, mod) => { for (let i = 0; i < count; i++) fireLead(g, self, start, aimdir, damage, kick, hspread, vspread, mod); }; + Q.fireBlaster = (g, self, start, dir, damage, speed, effect, hyper) => { + dir = norm(dir); + const i = Q.spawn(g), b = g.ents[i]; + Object.assign(b, { classname: 'bolt', svflags: Q.SVF_DEADMONSTER, origin: copy3(start), old_origin: copy3(start), angles: Q.vectoangles(dir), velocity: scale(dir, speed), + movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect, owner: self, touch: 'blaster_touch', nextthink: g.ms + 2000, think: 'G_FreeEdict', dmg: damage, spawnflags: hyper ? 1 : 0 }); + if (g.ents[self].client) checkDodge(g, self); + const tr = Q.trace(g, g.ents[self].origin, null, null, b.origin, i, Q.MASK_SHOT); + if (tr.fraction < 1.0) { b.origin = ma(b.origin, -10, dir); Q.TOUCH.blaster_touch(g, i, tr.ent, null); } + }; + Q.TOUCH.blaster_touch = (g, i, other, plane, sky) => { + const b = g.ents[i]; + if (other === b.owner) return; + if (sky) { Q.freeEdict(g, i); return; } + if (g.ents[b.owner] && g.ents[b.owner].client) Q.playerNoise(g, b.origin, 'impact'); + const o = g.ents[other]; + if (other > 0 && o.takedamage) Q.damage(g, other, i, b.owner, b.velocity, b.origin, plane || [0, 0, 0], b.dmg, 1, Q.DAMAGE_ENERGY, b.spawnflags & 1 ? 'hyperblaster' : 'blaster'); + else Q.fx(g, 'blasterhit', b.origin, plane); + Q.freeEdict(g, i); + }; + Q.fireRocket = (g, self, start, dir, damage, speed, damage_radius, radius_damage) => { + const i = Q.spawn(g), r = g.ents[i]; + Object.assign(r, { classname: 'rocket', origin: copy3(start), old_origin: copy3(start), movedir: copy3(dir), angles: Q.vectoangles(dir), velocity: scale(dir, speed), + movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect: 'rocket', owner: self, touch: 'rocket_touch', nextthink: g.ms + 8000000 / speed, think: 'G_FreeEdict', + dmg: damage, radius_dmg: radius_damage, dmg_radius: damage_radius }); + if (g.ents[self].client) checkDodge(g, self); + }; + Q.TOUCH.rocket_touch = (g, i, other, plane, sky) => { + const r = g.ents[i]; + if (other === r.owner) return; + if (sky) { Q.freeEdict(g, i); return; } + if (g.ents[r.owner] && g.ents[r.owner].client) Q.playerNoise(g, r.origin, 'impact'); + const o = g.ents[other]; + if (other > 0 && o.takedamage) Q.damage(g, other, i, r.owner, r.velocity, r.origin, plane || [0, 0, 0], r.dmg, 0, 0, 'rocket'); + else if (other === 0) { let n = Q.rand(g) % 5; while (n--) Q.throwDebris(g, i, 2, r.origin); } // single player only + Q.radiusDamage(g, i, r.owner, r.radius_dmg, other, r.dmg_radius, 'r_splash'); + Q.fx(g, 'explosion', ma(r.origin, -0.02, r.velocity), null, { big: r.dmg > 60 }); + Q.freeEdict(g, i); + }; + Q.fireRail = (g, self, start, aimdir, damage, kick) => { + const end = ma(start, 8192, aimdir); + let from = copy3(start), ignore = self, tr = null; + const mask = Q.MASK_SHOT; + let guard = 0; + while (ignore >= 0 && guard++ < 16) { + tr = Q.trace(g, from, null, null, end, ignore, mask); + const hit = g.ents[tr.ent]; + if (tr.ent > 0 && (hit.svflags & Q.SVF_MONSTER || hit.client)) ignore = tr.ent; else ignore = -1; + if (tr.ent !== self && tr.ent > 0 && hit.takedamage) Q.damage(g, tr.ent, self, self, aimdir, tr.endpos, tr.normal, damage, kick, 0, 'railgun'); + from = copy3(tr.endpos); + if (tr.fraction === 1) break; + } + if (g.ents[self].client) Q.playerNoise(g, tr.endpos, 'impact'); + Q.fx(g, 'rail', start, null, { to: tr.endpos, from: self === 1 ? 'player' : 'monster' }); + }; + Q.fireBFG = (g, self, start, dir, damage, speed, damage_radius) => { + const i = Q.spawn(g), b = g.ents[i]; + Object.assign(b, { classname: 'bfg blast', origin: copy3(start), old_origin: copy3(start), movedir: copy3(dir), angles: Q.vectoangles(dir), velocity: scale(dir, speed), + movetype: 'flymissile', clipmask: Q.MASK_SHOT, solid: Q.SOLID_BBOX, effect: 'bfg', owner: self, touch: 'bfg_touch', radius_dmg: damage, dmg_radius: damage_radius, + think: 'bfg_think', nextthink: g.ms + Q.FRAMETIME_MS, lasers: [] }); + if (g.ents[self].client) checkDodge(g, self); + }; + Q.TOUCH.bfg_touch = (g, i, other, plane, sky) => { + const b = g.ents[i]; + if (other === b.owner) return; + if (sky) { Q.freeEdict(g, i); return; } + const o = g.ents[other]; + if (other > 0 && o.takedamage) Q.damage(g, other, i, b.owner, b.velocity, b.origin, plane || [0, 0, 0], 200, 0, 0, 'bfg_blast'); + Q.radiusDamage(g, i, b.owner, 200, other, 100, 'bfg_blast'); + b.solid = Q.SOLID_NOT; b.touch = null; + b.origin = ma(b.origin, -0.1, b.velocity); b.velocity = [0, 0, 0]; + b.effect = 'bfgexplode'; b.frame = 0; b.think = 'bfg_explode'; b.nextthink = g.ms + Q.FRAMETIME_MS; b.enemy = other; b.lasers = []; + Q.fx(g, 'bfgblast', b.origin); + }; + Q.THINK.bfg_explode = (g, i) => { + const b = g.ents[i]; + if (b.frame === 0) { + for (const k of Q.findradius(g, b.origin, b.dmg_radius)) { + const e = g.ents[k]; + if (!e.takedamage || k === b.owner) continue; + if (!Q.canDamage(g, k, i) || !Q.canDamage(g, k, b.owner)) continue; + const dist = len(sub(b.origin, Q.center(e))); + const points = b.radius_dmg * (1.0 - Math.sqrt(dist / b.dmg_radius)); + Q.damage(g, k, i, b.owner, b.velocity, e.origin, [0, 0, 0], Math.trunc(points), 0, Q.DAMAGE_ENERGY, 'bfg_effect'); + } + } + b.nextthink = g.ms + Q.FRAMETIME_MS; b.frame++; + if (b.frame === 5) b.think = 'G_FreeEdict'; + }; + Q.THINK.bfg_think = (g, i) => { + const b = g.ents[i], dmg = 10; + b.lasers = []; + for (const k of Q.findradius(g, b.origin, 256)) { + const e = g.ents[k]; + if (k === i || k === b.owner || !e.takedamage) continue; + if (!(e.svflags & Q.SVF_MONSTER) && !e.client) continue; + const point = Q.center(e), dir = norm(sub(point, b.origin)); + let ignore = i, start = copy3(b.origin), end = ma(start, 2048, dir), tr = null, guard = 0; + while (guard++ < 8) { + tr = Q.trace(g, start, null, null, end, ignore, Q.CONTENTS_SOLID | Q.CONTENTS_MONSTER | Q.CONTENTS_DEADMONSTER); + if (tr.fraction === 1 && tr.ent === 0) break; + const h = g.ents[tr.ent]; + if (tr.ent > 0 && h.takedamage && !(h.flags & Q.FL_IMMUNE_LASER) && tr.ent !== b.owner) Q.damage(g, tr.ent, i, b.owner, dir, tr.endpos, [0, 0, 0], dmg, 1, Q.DAMAGE_ENERGY, 'bfg_laser'); + if (tr.ent <= 0 || (!(h.svflags & Q.SVF_MONSTER) && !h.client)) break; + ignore = tr.ent; start = copy3(tr.endpos); + } + b.lasers.push(tr.endpos); + } + b.nextthink = g.ms + Q.FRAMETIME_MS; + }; + // SV_Physics_Toss for MOVETYPE_FLYMISSILE (no gravity), MOVETYPE_TOSS and MOVETYPE_BOUNCE (gibs, debris). + Q.physicsToss = (g, i) => { + Q.runThink(g, i); + let e = g.ents[i]; + if (!e.inuse) return; + if (e.velocity[2] > 0) e.groundentity = -1; + if (e.groundentity >= 0) return; + for (let k = 0; k < 3; k++) e.velocity[k] = Math.max(-Q.SV_MAXVELOCITY, Math.min(Q.SV_MAXVELOCITY, e.velocity[k])); + const ft = g.dt; // 60 Hz host frame (q2-arena@3) + if (e.movetype !== 'flymissile') e.velocity[2] -= e.gravity * Q.SV_GRAVITY * ft; + e.angles = add(e.angles, scale(e.avelocity, ft)); + const move = scale(e.velocity, ft); + const start = copy3(e.origin), end = add(start, move); + for (let retry = 0; retry < 2; retry++) { + const tr = Q.trace(g, start, e.mins, e.maxs, end, i, e.clipmask || Q.MASK_SOLID); + e.origin = copy3(tr.endpos); + if (tr.fraction !== 1.0) { + impact(g, i, tr); + if (!g.ents[i].inuse) return; + e = g.ents[i]; + if (tr.ent > 0 && !g.ents[tr.ent].inuse) { e.origin = copy3(start); continue; } + e.velocity = clipVelocity(e.velocity, tr.normal, e.movetype === 'bounce' ? 1.5 : 1); + if (tr.normal[2] > 0.7 && (e.velocity[2] < 60 || e.movetype !== 'bounce')) { e.groundentity = tr.ent; e.velocity = [0, 0, 0]; e.avelocity = [0, 0, 0]; } + } + break; + } + }; + // g_misc.c ThrowGib / ThrowHead / ThrowDebris: real edicts (they hold slots and draw the same rand() calls). + function velocityForDamage(g, damage) { + const v = [100.0 * Q.crandom(g), 100.0 * Q.crandom(g), 200.0 + 100.0 * Q.random(g)]; + return scale(v, damage < 50 ? 0.7 : 1.2); + } + const clipGibVelocity = v => [Math.max(-300, Math.min(300, v[0])), Math.max(-300, Math.min(300, v[1])), Math.max(200, Math.min(500, v[2]))]; + Q.throwGib = (g, self, kind, damage, organic) => { + const s = g.ents[self], size = scale(sub(s.maxs, s.mins), 0.5), base = add(Q.absmin(s), size); + const i = Q.spawn(g), e = g.ents[i]; + e.classname = 'gib'; e.gib = kind; + e.origin = [base[0] + Q.crandom(g) * size[0], base[1] + Q.crandom(g) * size[1], base[2] + Q.crandom(g) * size[2]]; + e.old_origin = copy3(e.origin); + Object.assign(e, { solid: Q.SOLID_NOT, flags: Q.FL_NO_KNOCKBACK, takedamage: Q.DAMAGE_YES, movetype: organic ? 'toss' : 'bounce', touch: organic ? 'gib_touch' : null }); + e.velocity = clipGibVelocity(ma(s.velocity, organic ? 0.5 : 1.0, velocityForDamage(g, damage))); + e.avelocity = [Q.random(g) * 600, Q.random(g) * 600, Q.random(g) * 600]; + e.think = 'G_FreeEdict'; e.nextthink = g.ms + 10000 + Q.random(g) * 10000; + }; + Q.throwHead = (g, self, kind, damage, organic) => { + const e = g.ents[self]; + Object.assign(e, { skinnum: 0, frame: 0, mins: [0, 0, 0], maxs: [0, 0, 0], solid: Q.SOLID_NOT, flags: e.flags | Q.FL_NO_KNOCKBACK, takedamage: Q.DAMAGE_YES, + movetype: organic ? 'toss' : 'bounce', touch: organic ? 'gib_touch' : null, classname: 'gib', gib: kind, head: true }); + e.svflags &= ~Q.SVF_MONSTER; + e.velocity = clipGibVelocity(ma(e.velocity, organic ? 0.5 : 1.0, velocityForDamage(g, damage))); + e.avelocity = [0, Q.crandom(g) * 600, 0]; + e.think = 'G_FreeEdict'; e.nextthink = g.ms + 10000 + Q.random(g) * 10000; + }; + Q.TOUCH.gib_touch = (g, i) => { const e = g.ents[i]; if (e.groundentity < 0) return; e.touch = null; }; + Q.throwDebris = (g, self, speed, origin) => { + const s = g.ents[self], i = Q.spawn(g), e = g.ents[i]; + const v = [100 * Q.crandom(g), 100 * Q.crandom(g), 100 + 100 * Q.crandom(g)]; + Object.assign(e, { classname: 'debris', origin: copy3(origin), old_origin: copy3(origin), velocity: ma(s.velocity, speed, v), movetype: 'bounce', solid: Q.SOLID_NOT, takedamage: Q.DAMAGE_YES }); + e.avelocity = [Q.random(g) * 600, Q.random(g) * 600, Q.random(g) * 600]; + e.think = 'G_FreeEdict'; e.nextthink = g.ms + 5000 + Q.random(g) * 5000; e.flags = 0; + }; + function impact(g, i, tr) { // SV_Impact + const e1 = g.ents[i], e2 = g.ents[tr.ent]; + if (e1.touch && e1.solid !== Q.SOLID_NOT) Q.TOUCH[e1.touch](g, i, tr.ent, tr.normal, tr.sky); + if (tr.ent > 0 && e2.inuse && e2.touch && e2.solid !== Q.SOLID_NOT && g.ents[i].inuse) Q.TOUCH[e2.touch](g, tr.ent, i, null, false); + } + Q.impact = impact; + + // ---------------- damage (g_combat.c) ---------------- + Q.canDamage = (g, targ, inflictor) => { + const t = g.ents[targ], from = g.ents[inflictor].origin; + const test = d => Q.trace(g, from, null, null, d, inflictor, Q.MASK_SOLID).fraction === 1.0; + if (test(t.origin)) return true; + for (const [dx, dy] of [[15, 15], [15, -15], [-15, 15], [-15, -15]]) if (test([t.origin[0] + dx, t.origin[1] + dy, t.origin[2]])) return true; + return false; + }; + function checkArmor(g, ent, damage, dflags) { + if (!damage || !ent.client || (dflags & Q.DAMAGE_NO_ARMOR)) return 0; + const a = Q.armorIndex(ent); + if (!a) return 0; + let save = Math.ceil(((dflags & Q.DAMAGE_ENERGY) ? ARMOR[a][3] : ARMOR[a][2]) * damage); + if (save >= ent.inv[a]) save = ent.inv[a]; + if (!save) return 0; + ent.inv[a] -= save; + return save; + } + Q.damage = (g, targ, inflictor, attacker, dir, point, normal, damage, knockback, dflags, mod) => { + const t = g.ents[targ]; + if (!t.takedamage) return; + if (g.skill === 0 && t.client) { damage = Math.trunc(damage * 0.5); if (!damage) damage = 1; } // easy mode takes half damage + dir = norm(dir); + const a = g.ents[attacker]; + if (!(dflags & Q.DAMAGE_RADIUS) && (t.svflags & Q.SVF_MONSTER) && a && a.client && t.enemy < 0 && t.health > 0) damage *= 2; + if (t.flags & Q.FL_NO_KNOCKBACK) knockback = 0; + if (!(dflags & Q.DAMAGE_NO_KNOCKBACK) && knockback && t.movetype !== 'none') { + const mass = t.mass < 50 ? 50 : t.mass; + const kvel = scale(dir, (t.client && attacker === targ ? 1600.0 : 500.0) * knockback / mass); + t.velocity = add(t.velocity, kvel); + } + let take = damage; + const asave = checkArmor(g, t, take, dflags); // no power armor, god mode or invulnerability in these arenas + take -= asave; + if (asave) Q.fx(g, 'spark', point, normal); + g.damageLog.push([targ, attacker, take, asave, mod]); + if (take) { + Q.fx(g, (t.svflags & Q.SVF_MONSTER) || t.client ? 'blood' : 'spark', point, normal); + t.health -= take; + if (t.health <= 0) { + if ((t.svflags & Q.SVF_MONSTER) || t.client) t.flags |= Q.FL_NO_KNOCKBACK; + killed(g, targ, inflictor, attacker, take, point); + return; + } + } + if (t.svflags & Q.SVF_MONSTER) { + Q.reactToDamage(g, targ, attacker); + // AI_DUCKED (the Mutant in mid-leap) suppresses the pain reaction + if (!(t.monsterinfo.aiflags & Q.AI_DUCKED) && take) { Q.monsterPain(g, targ, attacker, knockback, take); if (g.skill === 3) g.ents[targ].pain_debounce_time = g.ms + 5000; } + } + if (t.client) { t.damage_blood += take; t.damage_armor += asave; t.damage_knockback += knockback; t.damage_from = copy3(point); } + }; + function killed(g, targ, inflictor, attacker, damage, point) { + const t = g.ents[targ]; + if (t.health < -999) t.health = -999; + t.enemy = attacker; + if (t.client) { t.deadflag = Q.DEAD_DEAD; t.takedamage = Q.DAMAGE_NO; Q.event(g, 'player_die'); return; } + if ((t.svflags & Q.SVF_MONSTER) && t.deadflag !== Q.DEAD_DEAD) { t.touch = null; Q.monsterDeathUse(g, targ); } + Q.monsterDie(g, targ, inflictor, attacker, damage, point); + } + Q.radiusDamage = (g, inflictor, attacker, damage, ignore, radius, mod) => { + const inf = g.ents[inflictor]; + for (const k of Q.findradius(g, inf.origin, radius)) { + if (k === ignore) continue; + const e = g.ents[k]; + if (!e.takedamage) continue; + let points = damage - 0.5 * len(sub(inf.origin, Q.center(e))); + if (k === attacker) points *= 0.5; + if (points > 0 && Q.canDamage(g, k, inflictor)) { + const dir = sub(e.origin, inf.origin); + Q.damage(g, k, inflictor, attacker, dir, inf.origin, [0, 0, 0], Math.trunc(points), Math.trunc(points), Q.DAMAGE_RADIUS, mod); + } + } + }; + + // ---------------- items (Touch_Item) ---------------- + Q.spawnItem = (g, type, origin) => { + const i = Q.spawn(g), e = g.ents[i]; + Object.assign(e, { classname: type, item: type, origin: copy3(origin), mins: [-15, -15, -15], maxs: [15, 15, 15], solid: Q.SOLID_TRIGGER, touch: 'Touch_Item', movetype: 'toss', groundentity: 0 }); // droptofloor done + return i; + }; + const PICKUP = { + health: (p) => healthPickup(p, 10, false), health_large: (p) => healthPickup(p, 25, false), stimpack: (p) => healthPickup(p, 2, true), + armor_shard: (p) => { const a = Q.armorIndex(p); if (!a) p.inv.jacket = 2; else p.inv[a] += 2; return true; }, + armor_jacket: p => armorPickup(p, 'jacket'), armor_combat: p => armorPickup(p, 'combat'), armor_body: p => armorPickup(p, 'body'), + ammo_shells: p => ammoPickup(p, 'shells'), ammo_bullets: p => ammoPickup(p, 'bullets'), ammo_cells: p => ammoPickup(p, 'cells'), + ammo_rockets: p => ammoPickup(p, 'rockets'), ammo_slugs: p => ammoPickup(p, 'slugs'), + }; + Q.PICKUP = PICKUP; + function healthPickup(p, count, ignoreMax) { + if (!ignoreMax && p.health >= p.max_health) return false; + p.health += count; + if (!ignoreMax && p.health > p.max_health) p.health = p.max_health; + return true; + } + function armorPickup(p, kind) { // Pickup_Armor with salvage + const old = Q.armorIndex(p), info = ARMOR[kind]; + if (!old) { p.inv[kind] = info[0]; return true; } + const oldinfo = ARMOR[old]; + if (info[2] > oldinfo[2]) { + const salvagecount = Math.trunc((oldinfo[2] / info[2]) * p.inv[old]); + let newcount = info[0] + salvagecount; if (newcount > info[1]) newcount = info[1]; + p.inv[old] = 0; p.inv[kind] = newcount; + } else { + const salvagecount = Math.trunc((info[2] / oldinfo[2]) * info[0]); + let newcount = p.inv[old] + salvagecount; if (newcount > oldinfo[1]) newcount = oldinfo[1]; + if (p.inv[old] >= newcount) return false; + p.inv[old] = newcount; + } + return true; + } + function ammoPickup(p, ammo) { + if (p.inv[ammo] === AMMO_MAX[ammo]) return false; + p.inv[ammo] = Math.min(AMMO_MAX[ammo], (p.inv[ammo] || 0) + AMMO_PICKUP[ammo]); + return true; + } + // Touch_Item. Health and armor are single-player items: taken once, then freed (G_FreeEdict), never respawned + // (q2-arena@4, 2026-11-07: a respawning medkit lets a player stand and trade hits with the boss). Ammo keeps the + // deathmatch timer (SetRespawn 30 s, original DoRespawn) so a three-minute fight cannot run out of rounds; ammo + // heals nothing. q2-arena@1-3 also respawned health (30 s) and armor (20 s). + const RESPAWN = { ammo_shells: 30, ammo_bullets: 30, ammo_cells: 30, ammo_rockets: 30, ammo_slugs: 30 }; + Q.TOUCH.Touch_Item = (g, i, other) => { + const it = g.ents[i], p = g.ents[other]; + if (!p.client || p.health < 1) return; + if (!PICKUP[it.item](p)) return; + p.bonus_alpha = 0.25; p.pickup = it.item; p.pickup_time = g.ms + 3000; + Q.event(g, 'pickup', { item: it.item }); + if (!RESPAWN[it.item]) { Q.freeEdict(g, i); return; } + it.svflags |= Q.SVF_NOCLIENT; it.solid = Q.SOLID_NOT; it.nextthink = g.ms + RESPAWN[it.item] * 1000; it.think = 'DoRespawn'; + }; + Q.THINK.DoRespawn = (g, i) => { const it = g.ents[i]; it.svflags &= ~Q.SVF_NOCLIENT; it.solid = Q.SOLID_TRIGGER; Q.event(g, 'item_respawn', { item: it.item }); }; + + // ---------------- player trail (p_trail.c) ---------------- + Q.playerTrailInit = g => { g.trail = { head: 0, spots: Array.from({ length: 8 }, () => ({ origin: [0, 0, 0], timestamp: 0, yaw: 0 })) }; }; + Q.playerTrailAdd = (g, spot) => { + const tr = g.trail, prev = tr.spots[(tr.head - 1) & 7]; + tr.spots[tr.head] = { origin: copy3(spot), timestamp: g.ms, yaw: Q.vectoyaw(sub(spot, prev.origin)) }; + tr.head = (tr.head + 1) & 7; + }; + Q.trailLastSpot = g => g.trail.spots[(g.trail.head - 1) & 7]; + Q.trailPick = (g, self, first) => { + const tr = g.trail, mi = g.ents[self].monsterinfo; + let marker = tr.head; + for (let n = 8; n; n--) { if (tr.spots[marker].timestamp <= mi.trail_time) marker = (marker + 1) & 7; else break; } + if (!first) return tr.spots[marker]; + if (Q.visiblePoint(g, self, tr.spots[marker].origin)) return tr.spots[marker]; + const prev = tr.spots[(marker - 1) & 7]; + if (Q.visiblePoint(g, self, prev.origin)) return prev; + return tr.spots[marker]; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/renderer3d.js b/environments/games/web/games/quake2_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..1e233d3c6cdbf1d8c7d1f02a60f3d702ae345b8e --- /dev/null +++ b/environments/games/web/games/quake2_remake/renderer3d.js @@ -0,0 +1,503 @@ +/* Quake II boss arenas - original procedural 3D art on Three.js r160 (MIT, shared read-only vendor copy in + web/games/_boss3d/vendor). First-person perspective from the player's eye with Quake II's 90 degree horizontal + field of view. Rendering is a pure function of the game state: it never writes the simulation and never draws + gameplay RNG; animation time comes from the state's tick counter. No Quake II models, skins or textures are used. */ +(function (root) { + 'use strict'; + const T = root.THREE, M = root.Quake2Game, Q = M && M.Q; + if (!T) throw Error('Three.js is missing (web/games/_boss3d/vendor/three.min.js)'); + const R = M.R3 = {}; + const S = 1 / 32; // one Quake II unit = 1/32 scene unit + const byCanvas = new WeakMap(); + const DEG = Math.PI / 180; + const qv = (x, y, z, out) => (out || new T.Vector3()).set(x * S, z * S, -y * S); // Quake (x fwd, y left, z up) -> three + function hash(x, y, s) { let n = Math.imul(x + 374761393 * s, 668265263) ^ Math.imul(y + s, 2246822519); n = Math.imul(n ^ (n >>> 13), 1274126177); return ((n ^ (n >>> 16)) >>> 0) / 4294967295; } + + // ---------------- procedural textures (deterministic, generated once per scene) ---------------- + function canvasTex(w, h, paint, opts = {}) { + const c = document.createElement('canvas'); c.width = w; c.height = h; + const q = c.getContext('2d'); paint(q, w, h); + const t = new T.CanvasTexture(c); t.colorSpace = T.SRGBColorSpace; t.wrapS = t.wrapT = T.RepeatWrapping; t.anisotropy = 2; + if (opts.nearest) { t.magFilter = T.NearestFilter; } + return t; + } + function noiseFill(q, w, h, base, amp, seed, grain = 1) { + const im = q.createImageData(w, h); + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { + const n = (hash(Math.floor(x / grain), Math.floor(y / grain), seed) - 0.5) * amp + (hash(x >> 3, y >> 3, seed + 7) - 0.5) * amp * 0.6; + const i = (y * w + x) * 4; im.data[i] = base[0] + n; im.data[i + 1] = base[1] + n; im.data[i + 2] = base[2] + n * 0.9; im.data[i + 3] = 255; + } + q.putImageData(im, 0, 0); + } + const rivets = (q, xs, ys, col) => { q.fillStyle = col; for (const x of xs) for (const y of ys) { q.fillRect(x - 2, y - 2, 4, 4); } }; + const PAINT = { + floor(q, w, h) { noiseFill(q, w, h, [74, 70, 62], 26, 3); q.strokeStyle = '#2b2925'; q.lineWidth = 3; for (let k = 0; k <= w; k += 64) { q.beginPath(); q.moveTo(k, 0); q.lineTo(k, h); q.stroke(); q.beginPath(); q.moveTo(0, k); q.lineTo(w, k); q.stroke(); } + q.strokeStyle = '#5c584e'; q.lineWidth = 1; for (let k = 8; k < w; k += 16) { q.beginPath(); q.moveTo(k, 0); q.lineTo(k, h); q.stroke(); } rivets(q, [6, 58, 70, 122, 134, 186, 198, 250], [6, 58, 70, 122, 134, 186, 198, 250], '#8e8778'); }, + wall(q, w, h) { noiseFill(q, w, h, [96, 72, 52], 30, 11); q.fillStyle = '#3a2b20'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 5); q.fillStyle = '#6e5440'; + for (let x = 0; x < w; x += 128) q.fillRect(x + 60, 0, 8, h); rivets(q, [12, 116, 140, 244], [14, 50, 78, 114, 142, 178, 206, 242], '#b29470'); q.fillStyle = 'rgba(40,24,12,.35)'; q.fillRect(0, h - 40, w, 40); }, + crate(q, w, h) { noiseFill(q, w, h, [72, 82, 58], 22, 21); q.strokeStyle = '#3a4430'; q.lineWidth = 10; q.strokeRect(5, 5, w - 10, h - 10); q.lineWidth = 8; q.beginPath(); q.moveTo(10, 10); q.lineTo(w - 10, h - 10); q.moveTo(w - 10, 10); q.lineTo(10, h - 10); q.stroke(); + q.fillStyle = '#c9b34a'; q.font = 'bold 34px monospace'; q.fillText('S-7', w * 0.36, h * 0.56); }, + pylon(q, w, h) { noiseFill(q, w, h, [104, 100, 92], 24, 31); for (let x = -h; x < w; x += 40) { q.fillStyle = '#d9a722'; q.beginPath(); q.moveTo(x, h); q.lineTo(x + 20, h); q.lineTo(x + 60, h - 40); q.lineTo(x + 40, h - 40); q.fill(); } + q.fillStyle = '#2a2826'; q.fillRect(0, h - 44, w, 4); q.fillStyle = '#5b5852'; for (let y = 16; y < h - 50; y += 48) q.fillRect(0, y, w, 4); }, + tech(q, w, h) { noiseFill(q, w, h, [46, 52, 58], 18, 41); q.fillStyle = '#1a1f24'; q.fillRect(20, 30, w - 40, 90); q.fillRect(20, 150, w - 40, 70); + for (let k = 0; k < 9; k++) { q.fillStyle = k % 3 ? '#2fa36b' : '#7be0a8'; q.fillRect(30 + k * 22, 44 + (k * 37 % 50), 14, 8); } q.fillStyle = '#d9a722'; q.fillRect(0, 0, w, 8); }, + techGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); for (let k = 0; k < 9; k++) { q.fillStyle = k % 3 ? '#1c7a4c' : '#5ce9a0'; q.fillRect(30 + k * 22, 44 + (k * 37 % 50), 14, 8); } q.fillStyle = '#123'; q.fillRect(20, 150, w - 40, 70); }, + hangar(q, w, h) { noiseFill(q, w, h, [78, 86, 94], 20, 51); q.fillStyle = '#2f353b'; for (let y = 0; y < h; y += 128) q.fillRect(0, y, w, 6); for (let x = 0; x < w; x += 128) q.fillRect(x, 0, 6, h); + q.fillStyle = '#c99a2a'; q.fillRect(0, h - 26, w, 10); rivets(q, [16, 112, 144, 240], [16, 112, 144, 240], '#a9b3bb'); }, + cargo(q, w, h) { noiseFill(q, w, h, [150, 78, 34], 22, 61); for (let x = 0; x < w; x += 16) { q.fillStyle = x % 32 ? 'rgba(0,0,0,.18)' : 'rgba(255,220,180,.08)'; q.fillRect(x, 0, 8, h); } + q.strokeStyle = '#4a2a14'; q.lineWidth = 8; q.strokeRect(4, 4, w - 8, h - 8); q.fillStyle = '#efe3c8'; q.font = 'bold 26px monospace'; q.fillText('CRG 4410', 40, 70); }, + strogg(q, w, h) { noiseFill(q, w, h, [104, 66, 58], 30, 71); q.fillStyle = '#3e2420'; for (let y = 24; y < h; y += 64) q.fillRect(0, y, w, 10); q.fillStyle = '#a06a58'; + for (let x = 16; x < w; x += 64) { q.fillRect(x, 0, 6, h); q.fillRect(x + 12, 0, 3, h); } rivets(q, [40, 104, 168, 232], [8, 72, 136, 200], '#b5806a'); }, + pillar(q, w, h) { noiseFill(q, w, h, [92, 80, 78], 24, 81); q.fillStyle = '#3a3032'; for (let x = 0; x < w; x += 64) q.fillRect(x, 0, 10, h); q.fillStyle = '#ff7a1a'; for (let y = 40; y < h; y += 96) q.fillRect(0, y, w, 6); }, + pillarGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#ff6a10'; for (let y = 40; y < h; y += 96) q.fillRect(0, y, w, 6); }, + dais(q, w, h) { noiseFill(q, w, h, [66, 58, 56], 22, 91); q.strokeStyle = '#a3241a'; q.lineWidth = 6; q.beginPath(); q.arc(w / 2, h / 2, w * 0.4, 0, Math.PI * 2); q.stroke(); q.lineWidth = 3; q.beginPath(); q.arc(w / 2, h / 2, w * 0.28, 0, Math.PI * 2); q.stroke(); + for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; q.beginPath(); q.moveTo(w / 2 + Math.cos(a) * w * 0.28, h / 2 + Math.sin(a) * w * 0.28); q.lineTo(w / 2 + Math.cos(a) * w * 0.4, h / 2 + Math.sin(a) * w * 0.4); q.stroke(); } }, + roof(q, w, h) { noiseFill(q, w, h, [40, 40, 44], 16, 101); q.fillStyle = '#1b1b1e'; for (let k = 0; k < w; k += 128) { q.fillRect(k, 0, 8, h); q.fillRect(0, k, w, 8); } q.fillStyle = '#e8dcb0'; q.fillRect(48, 48, 32, 32); q.fillRect(176, 176, 32, 32); }, + roofGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#c9b98a'; q.fillRect(48, 48, 32, 32); q.fillRect(176, 176, 32, 32); }, + metal(q, w, h) { noiseFill(q, w, h, [92, 92, 96], 22, 111); q.fillStyle = '#3c3c40'; q.fillRect(0, h / 2 - 3, w, 6); rivets(q, [10, w - 10], [10, h - 10], '#b8b8bc'); }, + factory(q, w, h) { noiseFill(q, w, h, [96, 92, 84], 24, 131); q.fillStyle = '#4a4640'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 6); + for (let x = 0; x < w; x += 128) { q.fillStyle = '#d9a722'; q.fillRect(x + 8, h - 30, 48, 10); q.fillStyle = '#2a2826'; q.fillRect(x + 56, h - 30, 48, 10); } rivets(q, [24, 104, 152, 232], [24, 88, 152, 216], '#c0b8a6'); }, + machine(q, w, h) { noiseFill(q, w, h, [70, 84, 92], 20, 141); q.fillStyle = '#1e262c'; q.fillRect(24, 24, w - 48, h - 48); q.fillStyle = '#ff8a2a'; + for (let k = 0; k < 6; k++) q.fillRect(40 + k * 30, 40, 18, 6); q.fillStyle = '#5ad0ff'; q.fillRect(40, h - 70, w - 80, 8); q.strokeStyle = '#9aa8b0'; q.lineWidth = 4; q.strokeRect(8, 8, w - 16, h - 16); }, + machineGlow(q, w, h) { q.fillStyle = '#000'; q.fillRect(0, 0, w, h); q.fillStyle = '#ff8a2a'; for (let k = 0; k < 6; k++) q.fillRect(40 + k * 30, 40, 18, 6); q.fillStyle = '#5ad0ff'; q.fillRect(40, h - 70, w - 80, 8); }, + arena(q, w, h) { noiseFill(q, w, h, [124, 104, 80], 26, 151); q.fillStyle = '#6a5440'; for (let y = 0; y < h; y += 48) { const o = (y / 48 % 2) * 64; for (let x = -64 + o; x < w; x += 128) q.fillRect(x, y, 4, 48); q.fillRect(0, y, w, 4); } }, + column(q, w, h) { noiseFill(q, w, h, [150, 138, 120], 20, 161); q.fillStyle = 'rgba(60,44,30,.35)'; for (let x = 0; x < w; x += 32) q.fillRect(x, 0, 8, h); q.fillStyle = '#7a3020'; q.fillRect(0, 16, w, 10); q.fillRect(0, h - 26, w, 10); }, + lab(q, w, h) { noiseFill(q, w, h, [176, 184, 176], 14, 171); q.fillStyle = '#7a8a86'; for (let y = 0; y < h; y += 64) q.fillRect(0, y, w, 3); for (let x = 0; x < w; x += 64) q.fillRect(x, 0, 3, h); + q.fillStyle = '#3a8a5a'; q.fillRect(0, h - 40, w, 14); q.fillStyle = '#d8d040'; for (let x = 0; x < w; x += 32) q.fillRect(x, h - 44, 16, 4); }, + bench(q, w, h) { noiseFill(q, w, h, [130, 140, 146], 16, 181); q.fillStyle = '#3c464c'; q.fillRect(0, 0, w, 10); q.fillStyle = '#60c890'; for (let k = 0; k < 4; k++) q.fillRect(20 + k * 56, 30, 34, 20); }, + flesh(q, w, h) { noiseFill(q, w, h, [120, 62, 58], 36, 121, 2); q.strokeStyle = 'rgba(60,20,20,.6)'; q.lineWidth = 3; for (let k = 0; k < 10; k++) { q.beginPath(); q.moveTo(hash(k, 1, 9) * w, 0); q.bezierCurveTo(hash(k, 2, 9) * w, h * 0.3, hash(k, 3, 9) * w, h * 0.7, hash(k, 4, 9) * w, h); q.stroke(); } }, + }; + + // Box geometry with world-scaled UVs (one texture tile = 128 Quake units) so walls never stretch. + function brushGeometry(b) { + const [x0, y0, z0] = b.mins, [x1, y1, z1] = b.maxs, pos = [], uv = [], nor = [], idx = []; + const face = (corners, n, ua, va) => { + const base = pos.length / 3; + for (const c of corners) { const p = qv(c[0], c[1], c[2]); pos.push(p.x, p.y, p.z); uv.push(c[ua] / 128, c[va] / 128); nor.push(n.x, n.y, n.z); } + idx.push(base, base + 1, base + 2, base, base + 2, base + 3); + }; + const N = (x, y, z) => qv(x / S, y / S, z / S).normalize(); + face([[x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]], N(0, 0, 1), 0, 1); // top + face([[x0, y1, z0], [x1, y1, z0], [x1, y0, z0], [x0, y0, z0]], N(0, 0, -1), 0, 1); // bottom + face([[x0, y0, z0], [x1, y0, z0], [x1, y0, z1], [x0, y0, z1]], N(0, -1, 0), 0, 2); // -y + face([[x1, y1, z0], [x0, y1, z0], [x0, y1, z1], [x1, y1, z1]], N(0, 1, 0), 0, 2); // +y + face([[x0, y1, z0], [x0, y0, z0], [x0, y0, z1], [x0, y1, z1]], N(-1, 0, 0), 1, 2); // -x + face([[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], N(1, 0, 0), 1, 2); // +x + const geo = new T.BufferGeometry(); + geo.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); geo.setAttribute('uv', new T.Float32BufferAttribute(uv, 2)); + geo.setAttribute('normal', new T.Float32BufferAttribute(nor, 3)); geo.setIndex(idx); + // Inward faces of the arena shell are what the camera sees; render both sides. + return geo; + } + + // ---------------- the scene ---------------- + const ARENA_STYLE = { + supertank: { fog: 0x2c2420, near: 900, far: 3400, hemi: [0xffd2a6, 0x3a2a20, 1.35], sun: [0xffb070, 1.6, [-0.5, 1, 0.35]], sky: ['#1c1424', '#5a2e3a', '#d0773a'], lamps: [] }, + hornet: { fog: 0x161b20, near: 700, far: 3000, hemi: [0xb9cde0, 0x282624, 1.15], sun: null, sky: null, lamps: [[896, 900, 470, 0xfff2d2, 1.6, 2400], [300, 300, 300, 0xffb050, 1.0, 1200], [1500, 1500, 300, 0x9fd0ff, 1.0, 1200]] }, + makron: { fog: 0x2a1a16, near: 1100, far: 3600, hemi: [0xffd0c0, 0x4a3028, 2.3], sun: null, sky: null, lamps: [[960, 960, 420, 0xff7a4a, 2.4, 2600], [560, 560, 300, 0xff9a50, 1.4, 1300], [1360, 1360, 300, 0xff9a50, 1.4, 1300], [560, 1360, 300, 0xffc890, 1.2, 1300], [1360, 560, 300, 0xffc890, 1.2, 1300]] }, + tank_commander: { fog: 0x24201c, near: 1000, far: 3400, hemi: [0xffe2c0, 0x3a342c, 2.0], sun: null, sky: null, lamps: [[896, 896, 420, 0xffd8a0, 2.0, 2600], [480, 620, 300, 0xff9a40, 1.2, 1200], [1312, 620, 300, 0xff9a40, 1.2, 1200], [480, 1170, 300, 0x9ad0ff, 1.2, 1200], [1312, 1170, 300, 0x9ad0ff, 1.2, 1200]] }, + gladiator: { fog: 0x3a2a22, near: 1200, far: 3400, hemi: [0xffd8b0, 0x4a3426, 1.5], sun: [0xffb070, 1.6, [0.4, 1, -0.3]], sky: ['#241828', '#6a3a3a', '#e08a4a'], lamps: [] }, + mutant: { fog: 0x1e2624, near: 1100, far: 3400, hemi: [0xe0fff0, 0x2a3430, 1.9], sun: null, sky: null, lamps: [[960, 800, 360, 0xd8fff0, 2.0, 2400], [480, 400, 300, 0x8affc0, 1.0, 1200], [1440, 400, 300, 0x8affc0, 1.0, 1200], [480, 1200, 300, 0xfff0c0, 1.0, 1200], [1440, 1200, 300, 0xfff0c0, 1.0, 1200]] }, + }; + class Scene { + constructor(key, canvas) { + this.key = key; this.canvas = canvas; this.resources = []; this.times = []; this.ready = false; this.error = null; this.closed = false; + this.view = document.createElement('canvas'); this.view.width = 854; this.view.height = 480; + this.renderer = new T.WebGLRenderer({ canvas: this.view, antialias: true, preserveDrawingBuffer: true, powerPreference: 'low-power' }); + this.renderer.setPixelRatio(1); this.renderer.setSize(854, 480, false); this.renderer.outputColorSpace = T.SRGBColorSpace; + this.renderer.toneMapping = T.ACESFilmicToneMapping; this.renderer.toneMappingExposure = 1.15; this.renderer.autoClear = false; this.renderer.info.autoReset = false; + this.view.addEventListener('webglcontextlost', e => { e.preventDefault(); this.ready = false; this.error = 'WebGL context lost'; }); + const st = ARENA_STYLE[key]; + this.world = new T.Scene(); this.world.fog = new T.Fog(st.fog, st.near * S, st.far * S); + this.world.background = st.sky ? this.keep(canvasTex(8, 256, (q, w, h) => { const gr = q.createLinearGradient(0, 0, 0, h); gr.addColorStop(0, st.sky[0]); gr.addColorStop(0.55, st.sky[1]); gr.addColorStop(1, st.sky[2]); q.fillStyle = gr; q.fillRect(0, 0, w, h); })) : new T.Color(st.fog); + // Quake II fov 90 is horizontal: vertical = 2*atan(tan(45)*480/854) = 58.7 degrees. + this.camera = new T.PerspectiveCamera(2 * Math.atan(Math.tan(45 * DEG) * 480 / 854) / DEG, 854 / 480, 2 * S, 6000 * S); + this.world.add(new T.HemisphereLight(st.hemi[0], st.hemi[1], st.hemi[2])); + if (st.sun) { const sun = new T.DirectionalLight(st.sun[0], st.sun[1]); sun.position.set(st.sun[2][0], st.sun[2][1], st.sun[2][2]); this.world.add(sun); } + for (const [x, y, z, c, i, d] of st.lamps) { const l = new T.PointLight(c, i, d * S, 1.2); qv(x, y, z, l.position); this.world.add(l); } + this.flashLight = new T.PointLight(0xffc070, 0, 500 * S, 1.5); this.world.add(this.flashLight); + this.boomLight = new T.PointLight(0xff8a30, 0, 600 * S, 1.4); this.world.add(this.boomLight); + this.tex = {}; this.mat = {}; + const tex = name => this.tex[name] || (this.tex[name] = this.keep(canvasTex(256, 256, PAINT[name]))); + const lam = (name, color = 0xffffff, glow) => { const m = new T.MeshLambertMaterial({ map: tex(name), color, side: T.DoubleSide }); if (glow) { m.emissive = new T.Color(0xffffff); m.emissiveMap = tex(glow); m.emissiveIntensity = 1.3; } return this.keep(m); }; + this.mat.brush = { floor: lam('floor'), wall: lam('wall'), crate: lam('crate'), pylon: lam('pylon'), tech: lam('tech', 0xffffff, 'techGlow'), hangar: lam('hangar'), cargo: lam('cargo'), + strogg: lam('strogg'), pillar: lam('pillar', 0xffffff, 'pillarGlow'), dais: lam('dais'), roof: lam('roof', 0xffffff, 'roofGlow'), barrier: lam('pylon', 0xc8c4bc), + factory: lam('factory'), machine: lam('machine', 0xffffff, 'machineGlow'), arena: lam('arena'), column: lam('column'), lab: lam('lab'), bench: lam('bench') }; + for (const b of Q.worlds[key].brushes) { + if (b.sky) continue; + const mesh = new T.Mesh(this.keep(brushGeometry(b)), this.mat.brush[b.mat] || this.mat.brush.wall); + this.world.add(mesh); + } + this.buildShared(); this.buildBosses(); this.buildWeapons(); + } + keep(r) { this.resources.push(r); return r; } + std(color, opts = {}) { return this.keep(new T.MeshLambertMaterial(Object.assign({ color }, opts))); } + glow(color, opacity = 1) { return this.keep(new T.MeshBasicMaterial({ color, transparent: opacity < 1, opacity, depthWrite: opacity >= 1, blending: opacity < 1 ? T.AdditiveBlending : T.NormalBlending, fog: false })); } + buildShared() { + const G = this.geo = { + box: this.keep(new T.BoxGeometry(1, 1, 1)), sphere: this.keep(new T.SphereGeometry(1, 14, 10)), lowSphere: this.keep(new T.SphereGeometry(1, 8, 6)), + cyl: this.keep(new T.CylinderGeometry(1, 1, 1, 12)), cyl6: this.keep(new T.CylinderGeometry(1, 1, 1, 6)), cone: this.keep(new T.ConeGeometry(1, 1, 10)), + ico: this.keep(new T.IcosahedronGeometry(1, 0)), ring: this.keep(new T.TorusGeometry(1, 0.06, 6, 24)), plane: this.keep(new T.PlaneGeometry(1, 1)), + }; + const pool = (n, make) => { const out = []; for (let k = 0; k < n; k++) { const o = make(); o.visible = false; this.world.add(o); out.push(o); } return out; }; + this.mats = { + rocketBody: this.std(0x5b5f58), flame: this.glow(0xffa040, 0.9), smoke: this.keep(new T.MeshBasicMaterial({ color: 0x8a8580, transparent: true, opacity: 0.32, depthWrite: false })), + bolt: this.glow(0xffe060, 0.95), boltCore: this.glow(0xfff8d0), bfg: this.glow(0x5cff6a, 0.85), bfgCore: this.glow(0xe8ffe0), bfgHalo: this.keep(new T.MeshBasicMaterial({ color: 0x40ff60, transparent: true, opacity: 0.08, depthWrite: false, wireframe: true })), + boom: this.glow(0xff8a30, 0.8), boomCore: this.glow(0xfff0b0, 0.9), blood: this.keep(new T.MeshBasicMaterial({ color: 0x8a0d08, transparent: true, opacity: 0.8, depthWrite: false })), + puff: this.keep(new T.MeshBasicMaterial({ color: 0x9a948a, transparent: true, opacity: 0.6, depthWrite: false })), spark: this.glow(0xffd070, 0.9), + meat: this.std(0x7a1c16), gibMetal: this.std(0x6a6a70), debris: this.std(0x4a4440), mflash: this.glow(0xffd890, 0.95), warn: this.glow(0xff2a20, 0.65), + tracer: this.keep(new T.LineBasicMaterial({ color: 0xffe0a0, transparent: true, opacity: 0.55 })), railCore: this.keep(new T.LineBasicMaterial({ color: 0xe8f4ff, transparent: true, opacity: 0.9 })), + railSpiral: this.keep(new T.LineBasicMaterial({ color: 0x3a7cff, transparent: true, opacity: 0.9 })), laser: this.keep(new T.LineBasicMaterial({ color: 0x6aff70, transparent: true, opacity: 0.85 })), + aimLine: this.keep(new T.LineBasicMaterial({ color: 0xff3020, transparent: true, opacity: 0.85 })), + }; + this.rockets = pool(24, () => { const g = new T.Group(); const body = new T.Mesh(G.cyl, this.mats.rocketBody); body.scale.set(2.2 * S, 18 * S, 2.2 * S); body.rotation.z = Math.PI / 2; g.add(body); + const fl = new T.Mesh(G.cone, this.mats.flame); fl.scale.set(3.4 * S, 14 * S, 3.4 * S); fl.rotation.z = Math.PI / 2; fl.position.x = -15 * S; g.add(fl); + for (let k = 0; k < 4; k++) { const sm = new T.Mesh(G.lowSphere, this.mats.smoke); sm.position.x = -(28 + k * 16) * S; sm.scale.setScalar((4 + k * 2.2) * S); g.add(sm); } return g; }); + this.bolts = pool(48, () => { const g = new T.Group(); const a = new T.Mesh(G.sphere, this.mats.bolt); a.scale.set(16 * S, 3.2 * S, 3.2 * S); g.add(a); const c = new T.Mesh(G.sphere, this.mats.boltCore); c.scale.set(9 * S, 1.6 * S, 1.6 * S); g.add(c); return g; }); + this.bfgs = pool(4, () => { const g = new T.Group(); const a = new T.Mesh(G.sphere, this.mats.bfg); a.scale.setScalar(14 * S); g.add(a); const c = new T.Mesh(G.sphere, this.mats.bfgCore); c.scale.setScalar(7 * S); g.add(c); + const h = new T.Mesh(G.lowSphere, this.mats.bfgHalo); h.scale.setScalar(256 * S); g.add(h); return g; }); + this.booms = pool(24, () => { const g = new T.Group(); const a = new T.Mesh(G.ico, this.mats.boom); g.add(a); const c = new T.Mesh(G.sphere, this.mats.boomCore); c.scale.setScalar(0.5); g.add(c); return g; }); + this.puffs = pool(64, () => new T.Mesh(G.lowSphere, this.mats.puff)); + this.gibs = pool(40, () => new T.Mesh(G.ico, this.mats.meat)); + this.flashes = pool(12, () => new T.Mesh(G.sphere, this.mats.mflash)); + const lines = (n, mat, pts) => pool(n, () => { const geo = this.keep(new T.BufferGeometry()); geo.setAttribute('position', new T.BufferAttribute(new Float32Array(pts * 3), 3)); return new T.Line(geo, mat); }); + this.tracers = lines(40, this.mats.tracer, 2); this.railCores = lines(6, this.mats.railCore, 2); this.railSpirals = lines(6, this.mats.railSpiral, 96); + this.lasers = lines(12, this.mats.laser, 2); this.aimLines = lines(2, this.mats.aimLine, 2); + this.items = {}; + const itemMat = { health: this.std(0xe8e4dc), health_large: this.std(0xf2eee6), stimpack: this.std(0xd0f0ff), armor_shard: this.glow(0x4ae07a, 0.95), armor_jacket: this.std(0x6e7b4a), + armor_combat: this.std(0x8a8f96), armor_body: this.std(0xc0a246), ammo_shells: this.std(0xa0382a), ammo_bullets: this.std(0xb89a34), ammo_rockets: this.std(0x3c5a34), ammo_cells: this.std(0x3a6aa8), ammo_slugs: this.std(0x5a6a5a) }; + this.itemMat = itemMat; this.crossMat = this.glow(0xd01818); + } + // ---------------- boss models (original silhouettes after the Quake II designs) ---------------- + // Quake-local position (fwd, left, up) and sizes in units; rx rolls about forward, ry turns a vertical cylinder to + // point forward (three z), rz yaws about up. + part(parent, geo, mat, x, y, z, sx, sy, sz, rx = 0, ry = 0, rz = 0) { + const m = new T.Mesh(geo, mat); qv(x, y, z, m.position); m.scale.set(sx * S, sz * S, sy * S); m.rotation.set(rx, rz, ry); parent.add(m); return m; + } + group(parent, x = 0, y = 0, z = 0) { const g = new T.Group(); qv(x, y, z, g.position); parent.add(g); return g; } + buildBosses() { + const G = this.geo, P = this.part.bind(this); + const steel = this.std(0x9a9ea6), dark = this.std(0x4a4d52), rust = this.std(0xa06a44), olive = this.std(0x76844f), flesh = this.std(0xc07a62, { map: this.keep(canvasTex(128, 128, PAINT.flesh)) }); + const red = this.glow(0xff3010), amber = this.glow(0xffa030), green = this.glow(0x60ff70), cyan = this.glow(0x60c8ff), purple = this.std(0x7a5a88); + this.bossMats = { steel, dark, rust, olive, flesh, red, amber, green, cyan }; + this.models = {}; + // Super Tank (boss1): tracked base, armoured hull, chaingun arm on the right, triple rocket pod on the left. + { const root = new T.Group(), m = { root }; this.world.add(root); + for (const s of [1, -1]) { const tr = this.group(root, 0, s * 44, 0); P(tr, G.box, dark, 0, 0, 22, 132, 34, 44); for (let k = -2; k <= 2; k++) P(tr, G.cyl, steel, k * 26, 0, 18, 13, 13, 37, Math.PI / 2, 0, 0); m['tread' + (s > 0 ? 'L' : 'R')] = tr; } + const hull = this.group(root, 0, 0, 44); P(hull, G.box, olive, 0, 0, 16, 104, 80, 32); P(hull, G.box, steel, 46, 0, 10, 16, 70, 18); m.hull = hull; + const torso = this.group(hull, -6, 0, 32); P(torso, G.box, olive, 0, 0, 20, 66, 62, 40); P(torso, G.box, dark, 0, 0, 42, 40, 40, 8); P(torso, G.box, rust, 18, 0, 34, 20, 24, 18); + m.eye = P(torso, G.box, red, 29, 0, 36, 3, 14, 4); m.torso = torso; + const gun = this.group(torso, 30, -30, 12); P(gun, G.cyl, dark, 0, 0, 0, 16, 16, 30, 0, Math.PI / 2, 0); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; P(gun, G.cyl6, steel, 26, Math.cos(a) * 4.5, Math.sin(a) * 4.5, 2.6, 2.6, 34, 0, Math.PI / 2, 0); } m.gun = gun; + const pod = this.group(torso, 12, 32, 18); P(pod, G.box, rust, 0, 0, 0, 30, 30, 22); for (let k = 0; k < 3; k++) P(pod, G.cyl, dark, 12, -10 + k * 10, 2, 6, 6, 20, 0, Math.PI / 2, 0); m.podGlow = P(pod, G.box, amber, 16, 0, 2, 2, 28, 10); m.pod = pod; + this.models.monster_supertank = m; } + // Hornet (boss2): flying insectoid gunship, two wing pairs, twin machinegun pods, rocket rack under the nose. + { const root = new T.Group(), m = { root }; this.world.add(root); + const body = this.group(root, 0, 0, 40); P(body, G.sphere, rust, 0, 0, 0, 62, 34, 24); P(body, G.sphere, flesh, -40, 0, -4, 46, 26, 22); P(body, G.sphere, dark, 34, 0, 4, 26, 22, 18); + m.eyes = [P(body, G.sphere, red, 52, 8, 8, 4, 4, 4), P(body, G.sphere, red, 52, -8, 8, 4, 4, 4)]; + for (const s of [1, -1]) { P(body, G.cyl, steel, 22, s * 40, 30, 7, 7, 34, 0, Math.PI / 2, 0); P(body, G.box, dark, 6, s * 30, 22, 24, 20, 10); } + for (let k = 0; k < 4; k++) P(body, G.cyl, dark, 22, [16, 8, -8, -16][k], -24, 4, 4, 22, 0, Math.PI / 2, 0); + m.wings = []; const wingMat = this.keep(new T.MeshLambertMaterial({ color: 0x9fb2a0, transparent: true, opacity: 0.55, side: T.DoubleSide })); + for (const s of [1, -1]) for (const f of [12, -18]) { const w = this.group(body, f, s * 22, 18); const blade = P(w, G.box, wingMat, 0, s * 44, 0, 34, 88, 1.5); m.wings.push({ w, s, f }); } + for (const s of [1, -1]) for (const f of [20, 0, -20]) P(body, G.cyl6, dark, f, s * 18, -26, 2.5, 2.5, 22, s * 0.4, 0, 0); + m.body = body; this.models.monster_boss2 = m; } + // Jorg (boss3 walker): huge bipedal mech with twin chainguns and the Makron rider on top. + { const root = new T.Group(), m = { root }; this.world.add(root); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, -6, s * 46, 78); const thigh = P(hip, G.box, steel, 0, 0, -18, 34, 30, 44); const knee = this.group(hip, 0, 0, -38); + P(knee, G.box, dark, 8, 0, -16, 30, 26, 40); const foot = P(knee, G.box, steel, 14, 0, -38, 56, 36, 10); m.legs.push({ hip, knee, s }); } + const body = this.group(root, 0, 0, 84); P(body, G.box, steel, 0, 0, 22, 112, 104, 44); P(body, G.box, dark, 0, 0, 48, 80, 72, 12); P(body, G.box, rust, 50, 0, 18, 18, 60, 30); + m.vents = P(body, G.box, amber, 58, 0, 24, 2, 40, 6); + for (const s of [1, -1]) { const arm = this.group(body, 40, s * 47, 12); P(arm, G.box, dark, 0, 0, 0, 40, 26, 30); for (let k = 0; k < 4; k++) { const a = k * Math.PI / 2 + 0.785; P(arm, G.cyl6, steel, 34, Math.cos(a) * 7, Math.sin(a) * 7, 4, 4, 44, 0, Math.PI / 2, 0); } m['arm' + (s > 0 ? 'L' : 'R')] = arm; } + m.bfg = P(body, G.sphere, green, 6, -9, 27, 9, 9, 9); + const rider = this.group(body, -10, 0, 54); P(rider, G.box, purple, 0, 0, 14, 22, 30, 30); P(rider, G.sphere, flesh, 0, 0, 36, 10, 10, 12); P(rider, G.box, dark, 6, 18, 18, 14, 10, 26); m.rider = rider; + m.body = body; this.models.monster_jorg = m; } + // Makron: armoured cyborg; railgun on the right arm, BFG / hyperblaster cannon on the left. + { const root = new T.Group(), m = { root }; this.world.add(root); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, 0, s * 12, 46); P(hip, G.box, dark, 0, 0, -10, 16, 14, 26); const knee = this.group(hip, 0, 0, -24); P(knee, G.box, steel, 2, 0, -10, 14, 12, 24); P(knee, G.box, dark, 6, 0, -22, 24, 16, 6); m.legs.push({ hip, knee, s }); } + const torso = this.group(root, 0, 0, 48); P(torso, G.box, purple, 0, 0, 14, 28, 38, 30); P(torso, G.box, steel, 2, 0, 30, 22, 30, 10); P(torso, G.sphere, flesh, 4, 0, 42, 9, 9, 11); m.eyes = P(torso, G.box, red, 12, 0, 43, 2, 10, 3); + const rail = this.group(torso, -6, -8, 24); P(rail, G.box, dark, 0, 0, 0, 22, 12, 12); P(rail, G.cyl, steel, 22, 0, 0, 5, 5, 34, 0, Math.PI / 2, 0); m.railGlow = P(rail, G.cyl, cyan, 22, 0, 0, 2.5, 2.5, 36, 0, Math.PI / 2, 0); m.rail = rail; + const cannon = this.group(torso, 8, 20, 14); P(cannon, G.box, rust, 0, 0, 0, 26, 14, 16); P(cannon, G.cyl, dark, 16, 0, 0, 9, 9, 16, 0, Math.PI / 2, 0); m.cannonGlow = P(cannon, G.sphere, green, 25, 0, 0, 6, 6, 6); m.cannon = cannon; + m.torso = torso; this.models.monster_makron = m; } + // Tank Commander: a heavy biped (box -32..32 x -16..72), blaster on the right forearm, chaingun on the left, a + // rocket pack on the shoulder; skin 2 is the commander's darker red plating. + { const root = new T.Group(), m = { root }; this.world.add(root); const plate = this.std(0x8a3a2c), plateD = this.std(0x5a2a22); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, 0, s * 16, 22); P(hip, G.box, plateD, 0, 0, -10, 22, 18, 26); const knee = this.group(hip, 0, 0, -22); P(knee, G.box, steel, 4, 0, -8, 18, 16, 20); P(knee, G.box, dark, 10, 0, -16, 34, 22, 8); m.legs.push({ hip, knee, s }); } + const torso = this.group(root, 0, 0, 26); P(torso, G.box, plate, 0, 0, 18, 46, 56, 38); P(torso, G.box, plateD, -8, 0, 40, 34, 44, 12); P(torso, G.sphere, flesh, 14, 0, 44, 8, 9, 9); m.eye = P(torso, G.box, red, 22, 0, 46, 2, 10, 3); + const mgArm = this.group(torso, 8, 34, 14); P(mgArm, G.box, dark, 0, 0, 0, 30, 14, 14); const mg = this.group(mgArm, 22, 0, 0); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; P(mg, G.cyl6, steel, 14, Math.cos(a) * 3.5, Math.sin(a) * 3.5, 2.2, 2.2, 26, 0, Math.PI / 2, 0); } m.mg = mg; m.mgArm = mgArm; + const blast = this.group(torso, 10, -32, 12); P(blast, G.box, steel, 0, 0, 0, 34, 14, 14); m.blastGlow = P(blast, G.sphere, amber, 18, 0, 0, 5, 5, 5); + const pod = this.group(torso, -14, 20, 46); P(pod, G.box, plateD, 0, 0, 0, 24, 20, 18); for (let k = 0; k < 3; k++) P(pod, G.cyl, dark, 8, -6 + k * 6, 2, 3.5, 3.5, 14, 0, Math.PI / 2, 0); m.podGlow = P(pod, G.box, amber, 14, 0, 2, 2, 18, 8); m.pod = pod; + m.torso = torso; this.models.monster_tank_commander = m; } + // Gladiator: a lanky biped (box -32..32 x -24..64) with a cleaver on the right arm and a railgun on the left. + { const root = new T.Group(), m = { root }; this.world.add(root); const hide = this.std(0x8a7a5a), armour = this.std(0x5a6a74); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, 0, s * 12, 6); P(hip, G.box, armour, 0, 0, -14, 12, 12, 28); const knee = this.group(hip, 0, 0, -26); P(knee, G.box, dark, 4, 0, -2, 12, 10, 10); m.legs.push({ hip, knee, s }); } + const torso = this.group(root, 0, 0, 8); P(torso, G.box, hide, 0, 0, 22, 26, 34, 34); P(torso, G.box, armour, 4, 0, 34, 22, 40, 12); P(torso, G.sphere, flesh, 6, 0, 48, 8, 8, 10); P(torso, G.box, red, 13, 0, 50, 2, 8, 2); + const cleaver = this.group(torso, 6, -26, 30); P(cleaver, G.box, armour, 0, 0, -8, 10, 10, 22); P(cleaver, G.box, steel, 14, 0, -18, 30, 3, 18); m.cleaver = cleaver; + const rail = this.group(torso, 8, 24, 26); P(rail, G.box, dark, 0, 0, 0, 22, 10, 10); P(rail, G.cyl, steel, 18, 0, 0, 3.5, 3.5, 26, 0, Math.PI / 2, 0); m.railGlow = P(rail, G.cyl, cyan, 18, 0, 0, 2.5, 2.5, 28, 0, Math.PI / 2, 0); + m.torso = torso; this.models.monster_gladiator = m; } + // Mutant: a hunched quadruped-ish brute (box -32..32 x -24..48), long clawed arms, no weapon. + { const root = new T.Group(), m = { root }; this.world.add(root); const skin = this.std(0xd8a882), bone = this.std(0xf4ead0); + m.legs = []; + for (const s of [1, -1]) { const hip = this.group(root, -10, s * 16, -2); P(hip, G.box, skin, 0, 0, -10, 14, 14, 24); P(hip, G.box, bone, 6, 0, -22, 18, 12, 4); m.legs.push({ hip, s }); } + const body = this.group(root, 0, 0, 4); P(body, G.sphere, skin, 0, 0, 18, 30, 26, 20); P(body, G.sphere, skin, 18, 0, 30, 16, 16, 14); P(body, G.sphere, flesh, 30, 0, 34, 9, 10, 9); P(body, G.box, red, 38, 4, 36, 2, 3, 2); P(body, G.box, red, 38, -4, 36, 2, 3, 2); + for (let k = 0; k < 5; k++) P(body, G.cone, bone, -10 + k * 7, 0, 36 - k * 1.5, 3, 3, 8); + for (const s of [1, -1]) { const arm = this.group(body, 16, s * 24, 28); P(arm, G.box, skin, 6, 0, -12, 10, 10, 28); for (let k = -1; k <= 1; k++) P(arm, G.cone, bone, 12, k * 3, -28, 2, 2, 10, Math.PI, 0, 0); m[s > 0 ? 'armL' : 'armR'] = arm; } + m.body = body; this.models.monster_mutant = m; } + for (const m of Object.values(this.models)) m.root.visible = false; + } + buildWeapons() { // first-person view models, drawn in their own pass over the world + this.vscene = new T.Scene(); this.vcam = new T.PerspectiveCamera(52, 854 / 480, 0.01, 10); + this.vscene.add(new T.HemisphereLight(0xfff0e0, 0x302820, 1.5)); const key = new T.DirectionalLight(0xffffff, 1.2); key.position.set(-0.4, 1, 0.6); this.vscene.add(key); + const G = this.geo, dark = this.std(0x2a2b2e), steel = this.std(0x7a7d82), brass = this.std(0x9a7a3a), wood = this.std(0x5a3c24), blue = this.glow(0x6ab8ff), orange = this.glow(0xffa040); + const box = (g, x, y, z, sx, sy, sz, m) => { const o = new T.Mesh(G.box, m); o.position.set(x, y, z); o.scale.set(sx, sy, sz); g.add(o); return o; }; + const tube = (g, x, y, z, r, l, m) => { const o = new T.Mesh(G.cyl, m); o.position.set(x, y, z); o.scale.set(r, l, r); o.rotation.x = Math.PI / 2; g.add(o); return o; }; + const W = this.vweapons = {}; + const mk = (name, build) => { const g = new T.Group(), inner = new T.Group(); build(inner); inner.scale.setScalar(0.62); g.add(inner); g.userData.spin = inner.userData.spin; g.visible = false; this.vscene.add(g); W[name] = g; }; + mk('blaster', g => { box(g, 0, 0, 0, 0.07, 0.09, 0.26, dark); tube(g, 0, 0.02, -0.17, 0.022, 0.12, steel); box(g, 0, -0.08, 0.06, 0.05, 0.12, 0.07, wood); box(g, 0, 0.055, -0.02, 0.03, 0.02, 0.12, orange); }); + mk('shotgun', g => { tube(g, 0, 0.02, -0.12, 0.022, 0.5, steel); box(g, 0, -0.01, 0.1, 0.06, 0.07, 0.24, wood); box(g, 0, -0.025, -0.12, 0.05, 0.035, 0.18, wood); }); + mk('supershotgun', g => { tube(g, -0.022, 0.02, -0.12, 0.022, 0.5, steel); tube(g, 0.022, 0.02, -0.12, 0.022, 0.5, steel); box(g, 0, -0.01, 0.12, 0.08, 0.08, 0.22, wood); }); + mk('machinegun', g => { box(g, 0, 0, 0, 0.07, 0.08, 0.34, dark); tube(g, 0, 0.01, -0.24, 0.018, 0.16, steel); box(g, 0, -0.09, -0.02, 0.04, 0.12, 0.05, brass); }); + mk('chaingun', g => { const spin = new T.Group(); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; tube(spin, Math.cos(a) * 0.035, Math.sin(a) * 0.035, -0.18, 0.012, 0.42, steel); } g.add(spin); g.userData.spin = spin; box(g, 0, -0.02, 0.1, 0.12, 0.12, 0.2, dark); }); + mk('rocketlauncher', g => { tube(g, 0, 0.03, -0.08, 0.055, 0.6, this.std(0x44523a)); box(g, 0, -0.06, 0.08, 0.06, 0.1, 0.12, dark); tube(g, 0, 0.03, -0.39, 0.06, 0.03, steel); }); + mk('hyperblaster', g => { const spin = new T.Group(); for (let k = 0; k < 4; k++) { const a = k * Math.PI / 2; tube(spin, Math.cos(a) * 0.03, Math.sin(a) * 0.03, -0.2, 0.012, 0.38, steel); } g.add(spin); g.userData.spin = spin; box(g, 0, -0.03, 0.08, 0.1, 0.1, 0.2, dark); box(g, 0, 0.06, 0.06, 0.04, 0.02, 0.16, orange); }); + mk('railgun', g => { box(g, 0, 0, -0.06, 0.07, 0.07, 0.6, dark); tube(g, 0, 0.0, -0.06, 0.03, 0.62, blue); box(g, 0, -0.07, 0.12, 0.05, 0.1, 0.1, steel); }); + this.vflash = new T.Mesh(G.sphere, this.glow(0xffd890, 0.9)); this.vflash.scale.setScalar(0.045); this.vflash.visible = false; this.vscene.add(this.vflash); + } + // ---------------- per-frame update ---------------- + render(g, ctx) { + if (this.closed || this.renderer.getContext().isContextLost()) { this.ready = false; this.error = this.closed ? '3D renderer is closed' : 'WebGL context lost'; throw Error(this.error); } + const t0 = performance.now(); + try { + const p = g.ents[1], time = g.ms / 1000; + const eye = [p.origin[0], p.origin[1], p.origin[2] + (p.viewheight || 22)]; + const ang = p.health > 0 ? p.v_angle : [-15, p.v_angle[1], 40]; + qv(eye[0], eye[1], eye[2] - (p.health > 0 ? 0 : 16), this.camera.position); + const cp = Math.cos(ang[0] * DEG), sp = Math.sin(ang[0] * DEG), cy = Math.cos(ang[1] * DEG), sy = Math.sin(ang[1] * DEG); + const look = qv(eye[0] + cp * cy * 100, eye[1] + cp * sy * 100, eye[2] - sp * 100); + this.camera.up.set(0, 1, 0); this.camera.lookAt(look); + this.camera.rotateZ(-(ang[2] || 0) * DEG); + this.updateBosses(g, time); this.updateMissiles(g, time); this.updateFx(g, time); this.updateItems(g, time); + this.renderer.info.reset(); this.renderer.clear(); this.renderer.render(this.world, this.camera); + this.updateViewWeapon(g, p, time); + this.renderer.clearDepth(); this.renderer.render(this.vscene, this.vcam); + ctx.drawImage(this.view, 0, 0, 854, 480); + this.times.push(performance.now() - t0); if (this.times.length > 120) this.times.shift(); + this.ready = true; this.error = null; + } catch (e) { this.ready = false; this.error = String(e && e.stack || e); throw e; } + } + updateBosses(g, time) { + for (const m of Object.values(this.models)) m.root.visible = false; + for (let i = 2; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse || !this.models[e.classname] || e.gibbed) continue; + const m = this.models[e.classname], def = Q.MONSTERS[e.classname], mi = e.monsterinfo || {}, mv = def.moves[mi.currentmove] || def.moves.stand; + const f = Math.max(0, e.frame - mv.first), n = mv.last - mv.first + 1, ph = f / n, move = mi.currentmove || 'stand'; + // A monster moves its ai_run distance on its 100 ms think; the original client spreads that step over the next + // server frame (cl_ents.c lerpfrac). The state keeps the step as e.lerp, read-only here. + const lf = e.lerp ? Math.max(0, 1 - (g.ms - e.lerp[3]) / Q.FRAMETIME_MS) : 0, lo = lf ? e.lerp : [0, 0, 0]; + m.root.visible = true; qv(e.origin[0] + lo[0] * lf, e.origin[1] + lo[1] * lf, e.origin[2] + lo[2] * lf, m.root.position); m.root.rotation.set(0, e.angles[1] * DEG, 0); + const dying = e.deadflag === Q.DEAD_DEAD, hurt = e.skinnum === 1; + if (e.classname === 'monster_supertank') { + const walk = move === 'run' || move === 'forward'; + m.treadL.position.y = (walk ? Math.sin(ph * Math.PI * 4) * 1.2 : 0) * S; m.treadR.position.y = (walk ? -Math.sin(ph * Math.PI * 4) * 1.2 : 0) * S; + m.torso.rotation.y = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.18 : 0; + m.gun.rotation.x = move === 'attack1' ? time * 9 : 0; + const charging = move === 'attack2' && e.frame >= 20 && e.frame < 34; + m.pod.rotation.z = charging ? -0.25 : 0; m.podGlow.visible = charging; m.podGlow.material.opacity = 1; + m.hull.rotation.z = dying ? Math.min(1, ph * 1.3) * 0.3 : 0; m.root.position.y -= dying ? ph * 22 * S : 0; + m.eye.visible = !dying; + } else if (e.classname === 'monster_boss2') { + for (const w of m.wings) w.w.rotation.x = w.s * (Math.sin(time * 38 + w.f) * 0.5 + 0.2); + const pitch = move === 'attack_rocket' ? -0.12 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.3 : 0; + m.body.rotation.z = pitch + (dying ? -ph * 0.8 : 0); m.body.rotation.x = Math.sin(time * 2.1) * 0.05 + (dying ? ph * 0.6 : 0); + m.body.position.y = (40 + Math.sin(time * 3) * 2) * S; + } else if (e.classname === 'monster_jorg') { + const walk = move === 'run' || move === 'walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.35; L.knee.rotation.z = -Math.max(0, a) * 0.5; } + const fire = move === 'attack1' || move === 'start_attack1'; + m.armL.rotation.x = fire ? time * 6 : 0; m.armR.rotation.x = fire ? -time * 6 : 0; + m.bfg.visible = !dying; m.bfg.scale.setScalar((move === 'attack2' && e.frame < 25 ? 9 + (e.frame - 18) * 1.6 : 6) * S); + m.body.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.12 : dying ? Math.min(1, ph * 1.2) * 0.35 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 50 * S : 0; + m.rider.visible = !(dying && e.frame >= 79); + } else if (e.classname === 'monster_makron') { + const walk = move === 'run' || move === 'walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.5; L.knee.rotation.z = -Math.max(0, a) * 0.6; } + const railCharge = move === 'attack5' && e.frame <= 243, sweep = move === 'attack4' && e.frame >= 213 && e.frame <= 229, bfgCharge = move === 'attack3' && e.frame <= 204; + m.railGlow.visible = railCharge; m.railGlow.scale.set(2.5 * S * (1 + (e.frame - 235) * 0.12), 36 * S, 2.5 * S * (1 + (e.frame - 235) * 0.12)); + m.rail.rotation.z = railCharge ? 0.1 : 0; + m.cannon.rotation.y = sweep ? (e.frame <= 221 ? -(221 - e.frame) * 10 : (229 - e.frame) * 10) * DEG : 0; + m.cannonGlow.visible = bfgCharge || sweep; m.cannonGlow.scale.setScalar((bfgCharge ? 6 + (e.frame - 201) * 2 : 4) * S); + m.torso.rotation.z = move === 'sight' ? Math.sin(ph * Math.PI) * -0.2 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.25 : dying ? Math.min(1, ph * 1.4) * 1.2 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.6) * 40 * S : 0; + } else if (e.classname === 'monster_tank_commander') { + const walk = move === 'run' || move === 'start_run' || move === 'walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.4; L.knee.rotation.z = -Math.max(0, a) * 0.5; } + m.mg.rotation.x = move === 'attack_chain' ? time * 12 : 0; + m.mgArm.rotation.y = move === 'attack_chain' && e.frame >= 173 && e.frame <= 191 ? (e.frame <= 182 ? -(e.frame - 178) * 8 : (e.frame - 186) * 8) * DEG : 0; + m.blastGlow.visible = move === 'attack_blast' || move === 'reattack_blast'; + const pre = move === 'attack_pre_rocket' || move === 'attack_fire_rocket'; m.podGlow.visible = pre; m.pod.rotation.z = pre ? -0.3 : 0; + m.torso.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.2 : dying ? Math.min(1, ph * 1.3) * 0.9 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 30 * S : 0; + } else if (e.classname === 'monster_gladiator') { + const walk = move === 'run' || move === 'walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.6; L.knee.rotation.z = -Math.max(0, a) * 0.7; } + const swing = move === 'attack_melee', railing = move === 'attack_gun' && e.frame <= 49; + m.cleaver.rotation.z = swing ? Math.sin(ph * Math.PI * 4) * 1.1 : 0.2; + const charge = 1 + Math.max(0, Math.min(3, e.frame - 46)) * 0.35; m.railGlow.visible = railing; m.railGlow.scale.set(2.5 * S * charge, 30 * S, 2.5 * S * charge); + m.torso.rotation.z = move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.3 : dying ? Math.min(1, ph * 1.4) * 1.3 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.6) * 40 * S : 0; + } else if (e.classname === 'monster_mutant') { + const walk = move === 'run' || move === 'walk' || move === 'start_walk'; + for (const L of m.legs) { const a = walk ? Math.sin(ph * Math.PI * 2 + (L.s > 0 ? 0 : Math.PI)) : 0; L.hip.rotation.z = a * 0.7; } + const claw = move === 'attack', leap = move === 'jump'; + m.armL.rotation.z = claw ? Math.sin(ph * Math.PI * 2) * 1.2 : leap ? -1.2 : 0.3; m.armR.rotation.z = claw ? -Math.sin(ph * Math.PI * 2 + 1) * 1.2 : leap ? -1.2 : 0.3; + m.body.rotation.z = leap ? -0.5 : move.startsWith('pain') ? Math.sin(ph * Math.PI) * 0.4 : dying ? Math.min(1, ph * 1.5) * 1.4 : 0; + m.root.position.y -= dying ? Math.max(0, ph - 0.5) * 30 * S : 0; + } + for (const mat of [this.bossMats.red]) mat.color.setHex(hurt ? 0xff8040 : 0xff3010); + } + // Railgun aim lines once the target point is locked (Makron: MakronSaveloc on frame 242, fires on 243; Gladiator: + // gladiator_attack saves pos1 in the tick it picks attack_gun, still on the previous move's frame, and fires on frame + // 49, four ticks later). The line is the exact shot line. + for (const l of this.aimLines) l.visible = false; + let ai = 0; + for (let i = 2; i < g.ents.length && ai < this.aimLines.length; i++) { + const e = g.ents[i]; + if (!e.inuse || e.deadflag || !e.monsterinfo) continue; + let ofs = null; + if (e.classname === 'monster_makron' && e.monsterinfo.currentmove === 'attack5' && e.frame === 242) ofs = [-17.3, 7.8, 72.4]; + else if (e.classname === 'monster_gladiator' && e.monsterinfo.currentmove === 'attack_gun' && e.frame <= 48) ofs = [30.0, 18.0, 28.0]; + if (!ofs) continue; + const av = Q.angleVectors(e.angles), start = Q.projectSource(e.origin, ofs, av.forward, av.right), dir = Q.norm(Q.sub(e.pos1, start)), end = Q.ma(start, 2400, dir); + this.setLine(this.aimLines[ai++], start, end); + } + } + setLine(line, a, b) { + const arr = line.geometry.attributes.position.array, A = qv(a[0], a[1], a[2]), Bv = qv(b[0], b[1], b[2]); + arr[0] = A.x; arr[1] = A.y; arr[2] = A.z; arr[3] = Bv.x; arr[4] = Bv.y; arr[5] = Bv.z; + line.geometry.attributes.position.needsUpdate = true; line.geometry.computeBoundingSphere(); line.visible = true; + } + orient(obj, origin, vel) { + qv(origin[0], origin[1], origin[2], obj.position); + const yaw = Math.atan2(vel[1], vel[0]), pitch = Math.atan2(vel[2], Math.hypot(vel[0], vel[1])); + obj.rotation.set(0, yaw, pitch, 'YZX'); + } + updateMissiles(g, time) { + let r = 0, b = 0, f = 0, l = 0; + for (const o of [...this.rockets, ...this.bolts, ...this.bfgs, ...this.lasers]) o.visible = false; + for (let i = 2; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse) continue; + if (e.classname === 'rocket' && r < this.rockets.length) { const o = this.rockets[r++]; this.orient(o, e.origin, e.velocity); o.visible = true; } + else if (e.classname === 'bolt' && b < this.bolts.length) { const o = this.bolts[b++]; this.orient(o, e.origin, e.velocity); o.visible = true; } + else if (e.classname === 'bfg blast' && f < this.bfgs.length) { + const o = this.bfgs[f++]; qv(e.origin[0], e.origin[1], e.origin[2], o.position); o.visible = true; + const exploding = e.think === 'bfg_explode' || e.effect === 'bfgexplode'; + o.children[0].scale.setScalar((exploding ? 40 + (e.frame || 0) * 30 : 14 + Math.sin(time * 20) * 2) * S); o.children[2].visible = !exploding; + for (const end of e.lasers || []) if (l < this.lasers.length) this.setLine(this.lasers[l++], e.origin, end); + } + } + } + updateFx(g, time) { + let bo = 0, pu = 0, tr = 0, rc = 0, gi = 0, fl = 0; + for (const o of [...this.booms, ...this.puffs, ...this.tracers, ...this.railCores, ...this.railSpirals, ...this.gibs, ...this.flashes]) o.visible = false; + let flash = 0, boom = 0, flashPos = null, boomPos = null; + for (const fx of g.fx) { + const age = (g.ms - fx.t0) / fx.life; + if (age < 0 || age > 1) continue; + if (fx.kind === 'explosion' && bo < this.booms.length) { + const o = this.booms[bo++], s = (fx.big ? 70 : 48) * (0.35 + age * 0.8); + qv(fx.o[0], fx.o[1], fx.o[2], o.position); o.scale.setScalar(s * S); o.rotation.set(fx.id, fx.id * 1.3, 0); o.visible = true; + o.children[0].material.opacity = 0.85 * (1 - age); if (1 - age > boom) { boom = 1 - age; boomPos = fx.o; } + } else if ((fx.kind === 'blood' || fx.kind === 'puff' || fx.kind === 'spark' || fx.kind === 'blasterhit') && pu < this.puffs.length) { + const o = this.puffs[pu++]; qv(fx.o[0], fx.o[1], fx.o[2] + age * 10, o.position); o.scale.setScalar((fx.kind === 'blood' ? 5 : 3.5) * (1 + age) * S); + o.material = fx.kind === 'blood' ? this.mats.blood : fx.kind === 'puff' ? this.mats.puff : this.mats.spark; o.visible = true; + } else if (fx.kind === 'tracer' && fx.from === 'monster' && tr < this.tracers.length) { + this.setLine(this.tracers[tr++], fx.o, fx.to); + } else if (fx.kind === 'rail' && rc < this.railCores.length) { + this.setLine(this.railCores[rc], fx.o, fx.to); + const sp = this.railSpirals[rc++], arr = sp.geometry.attributes.position.array, d = Q.sub(fx.to, fx.o), L = Q.len(d), dir = Q.norm(d); + const side = Q.norm(Q.cross(dir, Math.abs(dir[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0])), up = Q.cross(side, dir), n = arr.length / 3, v = new T.Vector3(); + for (let k = 0; k < n; k++) { const t = k / (n - 1), a = t * L / 18, rr = 5 + age * 6, p = Q.ma(Q.ma(Q.ma(fx.o, t * L, dir), Math.cos(a) * rr, side), Math.sin(a) * rr, up); qv(p[0], p[1], p[2], v); arr[k * 3] = v.x; arr[k * 3 + 1] = v.y; arr[k * 3 + 2] = v.z; } + sp.geometry.attributes.position.needsUpdate = true; sp.geometry.computeBoundingSphere(); sp.visible = true; + sp.material.opacity = 0.9 * (1 - age); this.railCores[rc - 1].material.opacity = 0.9 * (1 - age); + } else if (fx.kind === 'mflash' && fl < this.flashes.length) { + const o = this.flashes[fl++]; qv(fx.o[0], fx.o[1], fx.o[2], o.position); o.scale.setScalar((fx.weapon === 'bfg' ? 14 : fx.weapon === 'rocket' ? 9 : 6) * S); o.visible = true; + flash = 1; flashPos = fx.o; + } else if (fx.kind === 'railcharge' && fl < this.flashes.length) { + const e = g.ents[fx.owner]; if (!e || !e.inuse) continue; + } + } + for (let i = 2; i < g.ents.length && gi < this.gibs.length; i++) { + const e = g.ents[i]; + if (!e.inuse || (e.classname !== 'gib' && e.classname !== 'debris')) continue; + const o = this.gibs[gi++]; qv(e.origin[0], e.origin[1], e.origin[2], o.position); o.rotation.set(e.angles[0] * DEG, e.angles[1] * DEG, e.angles[2] * DEG); + o.scale.setScalar((e.classname === 'debris' ? 3 : e.head ? 9 : e.gib === 'chest' ? 8 : 5) * S); + o.material = e.classname === 'debris' ? this.mats.debris : e.gib === 'metal' || e.gib === 'gear' ? this.mats.gibMetal : this.mats.meat; o.visible = true; + } + this.flashLight.intensity = flash ? 2.2 : 0; if (flashPos) qv(flashPos[0], flashPos[1], flashPos[2], this.flashLight.position); + this.boomLight.intensity = boom * 3.2; if (boomPos) qv(boomPos[0], boomPos[1], boomPos[2] + 24, this.boomLight.position); + } + updateItems(g, time) { + const seen = new Set(); + for (let i = 2; i < g.ents.length; i++) { + const e = g.ents[i]; + if (!e.inuse || e.solid !== Q.SOLID_TRIGGER || !e.item) continue; + let o = this.items[i]; + if (!o || o.userData.item !== e.item) { if (o) this.world.remove(o); o = this.items[i] = this.itemModel(e.item); this.world.add(o); } + seen.add(String(i)); o.visible = true; + qv(e.origin[0], e.origin[1], e.origin[2] - 6 + Math.sin(time * 2.4 + i) * 3, o.position); o.rotation.y = time * 1.6 + i; + } + for (const k of Object.keys(this.items)) if (!seen.has(k)) this.items[k].visible = false; + } + itemModel(item) { + const g = new T.Group(); g.userData.item = item; const G = this.geo, m = this.itemMat[item] || this.itemMat.health; + const add = (geo, mat, x, y, z, sx, sy, sz) => { const o = new T.Mesh(geo, mat); o.position.set(x * S, z * S, -y * S); o.scale.set(sx * S, sz * S, sy * S); g.add(o); return o; }; + if (item.startsWith('health') || item === 'stimpack') { + const s = item === 'health_large' ? 1.3 : item === 'stimpack' ? 0.55 : 1; + add(G.box, m, 0, 0, 0, 22 * s, 16 * s, 14 * s); add(G.box, this.crossMat, 0, 0, 7.5 * s, 14 * s, 4 * s, 1); add(G.box, this.crossMat, 0, 0, 7.5 * s, 4 * s, 14 * s, 1); + } else if (item === 'armor_shard') { add(G.ico, m, 0, 0, 2, 7, 7, 10); } + else if (item.startsWith('armor')) { add(G.box, m, 0, 0, 0, 10, 26, 24); add(G.box, m, 4, 0, 10, 8, 30, 6); } + else { add(G.box, m, 0, 0, 0, 18, 14, 12); add(G.box, this.std(0xd8d0b0), 0, 0, 6.5, 12, 10, 1); } + return g; + } + updateViewWeapon(g, p, time) { + for (const w of Object.values(this.vweapons)) w.visible = false; + this.vflash.visible = false; + if (p.health <= 0 || !p.weapon) return; + const w = this.vweapons[p.weapon]; if (!w) return; + const def = Q.WDEF[p.weapon], [act, fireLast, idleLast, deact] = def.frames; + let drop = 0; + if (p.weaponstate === 2) drop = (p.gunframe - idleLast) / Math.max(1, deact - idleLast); + else if (p.weaponstate === 1) drop = 1 - p.gunframe / Math.max(1, act); + const speed = Math.hypot(p.velocity[0], p.velocity[1]), bob = p.groundentity >= 0 ? Math.min(1, speed / 300) : 0; + const since = g.ms - (p.fired || -9999), recoil = since >= 0 && since < 200 ? (1 - since / 200) : 0; + w.visible = true; + w.position.set(0.15 + Math.cos(time * 7.5) * 0.008 * bob, -0.13 - drop * 0.25 + Math.abs(Math.sin(time * 7.5)) * 0.008 * bob, -0.34 + recoil * 0.035); + w.rotation.set(recoil * 0.12, 0, 0); + if (w.userData.spin && p.weaponstate === 3) w.userData.spin.rotation.z = time * 14; + if (since >= 0 && since < 100) { this.vflash.visible = true; this.vflash.position.set(0.15, -0.11 - drop * 0.25, -0.55); this.vflash.scale.setScalar(0.03); } + } + metrics() { + const sorted = [...this.times].sort((a, b) => a - b), info = this.renderer.info; + return { renderer: 'webgl-quake2', drawCalls: info.render.calls, triangles: info.render.triangles, samples: sorted.length, + cpuRenderMsP50: sorted.length ? sorted[Math.floor((sorted.length - 1) * 0.5)] : null, cpuRenderMsP95: sorted.length ? sorted[Math.floor((sorted.length - 1) * 0.95)] : null }; + } + close() { if (this.closed) return; this.closed = true; this.ready = false; for (const r of this.resources) r.dispose && r.dispose(); this.renderer.dispose(); this.renderer.forceContextLoss(); this.resources = []; } + } + R.render = (g, ctx) => { + let m = byCanvas.get(ctx.canvas); if (!m) { m = new Map(); byCanvas.set(ctx.canvas, m); } + let s = m.get(g.key); if (!s || s.closed) { s = new Scene(g.key, ctx.canvas); m.set(g.key, s); } + s.render(g, ctx); m.last = s; return s; + }; + R.status = ctx => { + const m = ctx && byCanvas.get(ctx.canvas); let ready = false, error = null; + if (m) for (const s of m.values()) { if (!s.closed && s.renderer.getContext().isContextLost()) { s.ready = false; s.error = 'WebGL context lost'; } ready = ready || (s.ready && !s.closed); error = error || s.error; } + return { renderer: 'webgl-quake2', kind: 'perspective', ready, error }; + }; + R.metrics = ctx => { const m = ctx && byCanvas.get(ctx.canvas); return m && m.last && !m.last.closed ? m.last.metrics() : null; }; + R.close = ctx => { const m = ctx && byCanvas.get(ctx.canvas); if (!m) return; for (const s of m.values()) s.close(); byCanvas.delete(ctx.canvas); }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/quake2_remake/scripted.js b/environments/games/web/games/quake2_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..e66569c2bbe3f2eef703342f23edd2361c71746a --- /dev/null +++ b/environments/games/web/games/quake2_remake/scripted.js @@ -0,0 +1,305 @@ +/* Quake II boss arenas - the standard scripted reference controller (BossBench, not part of the original game). + Quake2Game.scripted(game) is called once per 200 ms packet with the live simulation. It reads privileged state, + looks ahead on deep copies (M.copyGame never touches the live RNG or state), and returns only legal packets: + six hold sets of at most four keys and one mouse delta. Deterministic: no Math.random, no clock. + At 60 Hz (q2-arena@3) a packet is twelve ticks, two per hold set; the controller holds its move keys in all six + sets and taps weapon keys in sets 1-3 so the press lands on the first tick and is released after 100 ms. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.Quake2Game, Q = M.Q; + const MOUSE_DEG = Q.CL.m_yaw * Q.CL.sensitivity; // 0.066 degrees per mouse count + const memory = new WeakMap(); + const angleDiff = a => ((a % 360) + 540) % 360 - 180; + const MOVES = [[], ['W'], ['S'], ['A'], ['D'], ['W', 'A'], ['W', 'D'], ['S', 'A'], ['S', 'D']]; + const SPEED = { rocketlauncher: 650, hyperblaster: 1000, blaster: 1000 }; + const LOOK = Math.round(1.4 * M.hz); // look-ahead per candidate move: 1.4 s (14 ticks at @2) + M.LOOK_K = 1; // blinded futures per candidate move (see M.scripted) + + // Seed planning copies from the tick so they cannot read future draws from the live simulation. + function simulate(g, keys, mouseTicks, ticks, k = 0) { + const h = M.copyGame(g), ks = new Set(keys), none = new Set(); + let x = Math.imul((g.t + 0x9e3779b9 + Math.imul(k, 0x632be5ab)) >>> 0, 0x85ebca6b) >>> 0; x ^= x >>> 13; x = Math.imul(x, 0xc2b2ae35) >>> 0; x ^= x >>> 16; + h.rnd = x >>> 0; + // At 60 Hz the shared per-tick quantize (a walk over the whole state) was 87 % of the controller's time; the copy is + // a plan, not a replay, so it is quantized once at the end (still deterministic; off by micro-units at most). + for (let t = 0; t < ticks && !h.outcome; t++) { + h.events = []; + h.update(ks, none, mouseTicks[t] || [0, 0, 0]); // the turn happens in the first packet only + h.t++; + } + N.quantize(h); + return h; + } + const center = e => Q.center(e); + const eyeOf = p => [p.origin[0], p.origin[1], p.origin[2] + p.viewheight]; + function lineOfFire(g, from, to, boss) { + const tr = Q.trace(g, from, null, null, to, 1, Q.MASK_SHOT); + return tr.ent === boss || tr.fraction === 1; + } + // Weapon wanted for this target: highest-value weapon with ammo whose range rule holds. + function wantWeapon(g, p, b, dist) { + const has = (w, ammo, n = 1) => p.inv[w] && (!ammo || p.inv[ammo] >= n); + const surface = dist - (b.maxs[0] || 0); + const order = []; + if (b.classname === 'monster_supertank') { + // Rockets from RANGE_MID, then the machinegun from mid range; the shotguns are the last resort: their range puts + // the player in RANGE_NEAR (attack checks 5x as often) or inside 160 units (always the chaingun). + if (surface > 150) order.push(['rocketlauncher', 'rockets']); + order.push(['machinegun', 'bullets'], ['supershotgun', 'shells', 2], ['shotgun', 'shells']); + } else if (b.classname === 'monster_boss2') { + // Railgun first: hitscan 150 suits peek-shoot-hide against a flier (rockets and bolts miss it often). + order.push(['railgun', 'slugs'], ['chaingun', 'bullets'], ['hyperblaster', 'cells']); + } else if (b.classname === 'monster_jorg') { + if (dist < 800) order.push(['chaingun', 'bullets', 20]); + order.push(['hyperblaster', 'cells'], ['railgun', 'slugs']); + if (surface > 190) order.push(['rocketlauncher', 'rockets']); + } else if (b.classname === 'monster_tank_commander') { + // Rockets from range (750 health per hit-set is a lot of 8-damage bullets); the chaingun when it is close. + if (surface > 150) order.push(['rocketlauncher', 'rockets']); + order.push(['chaingun', 'bullets', 20], ['supershotgun', 'shells', 2], ['machinegun', 'bullets']); + } else if (b.classname === 'monster_gladiator') { + // Keep outside the cleaver: rockets and the hyperblaster from mid range. + if (surface > 150) order.push(['rocketlauncher', 'rockets']); + order.push(['hyperblaster', 'cells'], ['chaingun', 'bullets', 20], ['supershotgun', 'shells', 2]); + } else if (b.classname === 'monster_mutant') { + // No ranged attack to answer: shotguns at close range, the chaingun while kiting. + if (dist < 420) order.push(['supershotgun', 'shells', 2]); + order.push(['chaingun', 'bullets', 20], ['machinegun', 'bullets'], ['supershotgun', 'shells', 2]); + } else { + order.push(['railgun', 'slugs'], ['hyperblaster', 'cells'], ['chaingun', 'bullets']); + if (surface > 190) order.push(['rocketlauncher', 'rockets']); + } + order.push(['machinegun', 'bullets'], ['shotgun', 'shells'], ['supershotgun', 'shells', 2], ['blaster', null]); + for (const [w, ammo, n] of order) if (has(w, ammo, n || 1)) return w; + return 'blaster'; + } + // Hitscan streams that keep firing while the boss can see the player: the counter is to break line of sight. The + // Hornet's 0.9 s pre-mg windup deals no damage, so the controller keeps shooting through it and hides on attack_mg. + const STREAM = { monster_supertank: ['attack1'], monster_boss2: ['attack_mg'], monster_jorg: ['start_attack1', 'attack1'], + monster_tank_commander: ['attack_chain'] }; + const PREFERRED = { + monster_supertank: [['rocketlauncher', 'rockets'], ['machinegun', 'bullets']], + monster_boss2: [['railgun', 'slugs'], ['chaingun', 'bullets'], ['hyperblaster', 'cells']], + monster_jorg: [['chaingun', 'bullets'], ['hyperblaster', 'cells'], ['railgun', 'slugs'], ['rocketlauncher', 'rockets']], + monster_makron: [['railgun', 'slugs'], ['hyperblaster', 'cells'], ['chaingun', 'bullets'], ['rocketlauncher', 'rockets']], + monster_tank_commander: [['rocketlauncher', 'rockets'], ['chaingun', 'bullets']], + monster_gladiator: [['rocketlauncher', 'rockets'], ['hyperblaster', 'cells'], ['chaingun', 'bullets']], + monster_mutant: [['supershotgun', 'shells'], ['chaingun', 'bullets']], + }; + // Cover spots: points beside the arena's cover brushes (not the shell) that the boss's eye cannot see. + function hiddenSpots(g, b) { + const be = [b.origin[0], b.origin[1], b.origin[2] + b.viewheight], out = [], brushes = Q.worlds[g.key].brushes; + for (let k = 6; k < brushes.length; k++) { + const br = brushes[k]; + if (br.maxs[2] < 64) continue; // too low to hide behind + const cx = (br.mins[0] + br.maxs[0]) / 2, cy = (br.mins[1] + br.maxs[1]) / 2; + for (const [px, py] of [[br.mins[0] - 40, cy], [br.maxs[0] + 40, cy], [cx, br.mins[1] - 40], [cx, br.maxs[1] + 40], + [br.mins[0] - 40, br.mins[1] - 40], [br.maxs[0] + 40, br.mins[1] - 40], [br.mins[0] - 40, br.maxs[1] + 40], [br.maxs[0] + 40, br.maxs[1] + 40]]) { + const pt = [px, py, br.mins[2] + 24]; + if (Q.pointcontents(g, pt) & Q.CONTENTS_SOLID) continue; + if (Q.trace(g, be, null, null, [px, py, pt[2] + 22], -1, Q.MASK_OPAQUE).fraction < 1) out.push(pt); + } + } + return out; + } + // Stalemate breaker (5 s without sight, while the normal seek after 1 s has not found the boss): the nearest point the + // player can walk to in a straight line from which the boss's eye is visible now. Without it, player and boss can + // mirror each other on the two sides of a full-height pillar (each one's distance term only matches the other's + // position along the pillar, and a 1.4 s straight look-ahead never comes out of it). + function sightSpot(g, b, p) { + const be = [b.origin[0], b.origin[1], b.origin[2] + b.viewheight]; + let best = null, bestD = 1e9; + for (const r of [96, 192, 288, 384]) { + for (let k = 0; k < 16; k++) { + const a = k * Math.PI / 8, pt = [p.origin[0] + Q.cos(a) * r, p.origin[1] + Q.sin(a) * r, p.origin[2]]; + if (r >= bestD) continue; + if (Q.trace(g, p.origin, [-16, -16, -24], [16, 16, 32], pt, 1, Q.MASK_SOLID).fraction < 1) continue; + if (Q.trace(g, [pt[0], pt[1], pt[2] + p.viewheight], null, null, be, -1, Q.MASK_OPAQUE).fraction < 1) continue; + best = pt; bestD = r; + } + if (best) break; + } + return best; + } + // The boss's view of a candidate player position: eye-to-eye trace through the world only. + const seenBy = (g, b, q) => Q.trace(g, [b.origin[0], b.origin[1], b.origin[2] + b.viewheight], null, null, [q.origin[0], q.origin[1], q.origin[2] + q.viewheight], -1, Q.MASK_OPAQUE).fraction === 1; + function threats(h) { // enemy projectiles and BFG orbs near the player at the end of a look-ahead + const p = h.ents[1]; let s = 0; + for (const e of h.ents) { + if (!e.inuse || e.owner === 1 || e.owner < 0) continue; + if (e.classname === 'rocket') { + const v = Q.norm(e.velocity), rel = Q.sub(p.origin, e.origin), along = Q.dot(rel, v); + if (along > 0) { const off = Q.len(Q.sub(rel, Q.scale(v, along))); s += Math.max(0, 110 - off) * (along < 700 ? 1 : 0.3); } + } else if (e.classname === 'bfg blast') { + const dd = Q.len(Q.sub(p.origin, e.origin)); s += Math.max(0, 420 - dd) * 2.5; + } else if (e.classname === 'bolt') { + const v = Q.norm(e.velocity), rel = Q.sub(p.origin, e.origin), along = Q.dot(rel, v); + if (along > 0) { const off = Q.len(Q.sub(rel, Q.scale(v, along))); s += Math.max(0, 60 - off) * 0.5; } + } + } + return s; + } + M.scripted = function (g) { + const noop = { holds: Array.from({ length: 6 }, () => []), mouse: [0, 0, 0] }; + const p = g.ents[1]; + if (g.outcome || p.health <= 0) return noop; + // Memory across packets (hysteresis, time out of sight) is rolled once per tick, so asking twice about the same + // state gives the same packet; a new episode (tick 0) starts fresh. + let mem = memory.get(g); + if (!mem || (g.t === 0 && mem.t !== 0)) { mem = { t: -1, move: 0, unseen: 0, base: null }; memory.set(g, mem); } + if (mem.t !== g.t) { mem.base = { move: mem.move, unseen: mem.unseen }; mem.t = g.t; } + const bi = g.bossEnt(), b = g.ents[bi]; + const alive = b && b.inuse && (b.svflags & Q.SVF_MONSTER) && b.deadflag !== Q.DEAD_DEAD && b.health > 0; + const eye = eyeOf(p); + let dx = 0, dy = 0, fire = false, want = p.weapon, dist = 1e9; + if (alive) { + const c = center(b); + dist = Q.len(Q.sub(c, p.origin)); + want = wantWeapon(g, p, b, dist); + // Aim: the centre of the body, led by the boss's last-frame motion for projectile weapons. + let aim = [c[0], c[1], b.origin[2] + (b.maxs[2] - b.mins[2]) * 0.45]; + const speed = SPEED[p.weapon]; + if (speed) { const vel = Q.scale(Q.sub(b.origin, b.old_origin), 10), tf = Q.len(Q.sub(aim, eye)) / speed; aim = Q.ma(aim, tf, vel); } + const dvec = Q.sub(aim, eye), yaw = Q.atan2(dvec[1], dvec[0]) * 180 / Math.PI; + // Machinegun climb: each held shot adds machinegun_shots * -1.5 degrees of pitch kick; pull down to match. + const climb = p.weapon === 'machinegun' && (p.buttons & 1) ? Math.min(9, p.machinegun_shots + 0.5) * 1.5 : 0; + const pitch = -Q.atan2(dvec[2], Math.sqrt(dvec[0] * dvec[0] + dvec[1] * dvec[1])) * 180 / Math.PI + climb; + const dyaw = angleDiff(yaw - p.viewangles[1]), dpitch = pitch - p.viewangles[0]; + dx = Math.max(-1000, Math.min(1000, Math.round(-dyaw / MOUSE_DEG))); + dy = Math.max(-1000, Math.min(1000, Math.round(dpitch / MOUSE_DEG))); + const residual = Math.abs(dyaw + dx * MOUSE_DEG) + Math.abs(dpitch - dy * MOUSE_DEG); + const radius = Math.max(b.maxs[0], 24), tol = Q.atan2(radius * 0.8, Math.max(1, dist)) * 180 / Math.PI; + const clear = lineOfFire(g, eye, aim, bi); + const selfSplash = p.weapon === 'rocketlauncher' && dist - b.maxs[0] < 170; + // Pellet spread is +-hspread/8192 radians (shotgun 500, super shotgun 1000 plus +-5 degrees per barrel): against + // the 128-unit Super Tank or 160-unit Jorg most pellets still land at 900 units, against Makron (60) they do not. + const outOfRange = /shotgun/.test(p.weapon) && dist > (b.maxs[0] >= 60 ? 1000 : 640); + fire = clear && residual < tol + 2 && !selfSplash && !outOfRange && Math.abs(dyaw) < 60; + } + // Weapon switch: tap weapnext / weapprev toward the wanted weapon when idle. + let tap = null; + const switching = !!p.newweapon || p.weaponstate === 1 || p.weaponstate === 2; + if (!switching && want && want !== p.weapon && p.weaponstate !== 3) { + const owned = Q.WEAPON_ORDER.filter(w => p.inv[w]), cur = owned.indexOf(p.weapon), tgt = owned.indexOf(want); + if (tgt >= 0) tap = ((tgt - cur + owned.length) % owned.length) <= owned.length / 2 ? 'K' : 'R'; + } + // Movement: one-second look-ahead per candidate move on copies; score survival, damage, range and threats. + const fireKeys = fire ? ['J'] : []; + const PT = M.hz / 5, mouseTicks = Array.from({ length: PT }, () => [dx / PT, dy / PT, 0]); // the packet's split + const hp0 = p.health + armor(p) * 0.6, boss0 = g.health()[2]; + // Super Tank: rockets from the edge of RANGE_FAR. M_CheckAttack never attacks at >= 1000 units and only at 0.02 + // per frame (x2 on hard) in RANGE_MID, against 0.1 (x2) in RANGE_NEAR; the tank walks 120 u/s, the player runs 300. + const stBand = p.weapon === 'rocketlauncher' ? [880, 1250] : [650, 1000]; + const band = !alive ? [400, 900] : b.classname === 'monster_supertank' ? stBand : /shotgun/.test(p.weapon) ? [170, 380] + : b.classname === 'monster_boss2' ? [260, 620] : b.classname === 'monster_jorg' ? [360, 760] + : b.classname === 'monster_tank_commander' ? (p.weapon === 'rocketlauncher' ? [560, 900] : [300, 600]) + : b.classname === 'monster_gladiator' ? [420, 780] : b.classname === 'monster_mutant' ? [200, 420] : [320, 700]; + let best = 0, bestScore = -Infinity; + const stream = alive && (STREAM[b.classname] || []).includes(b.monsterinfo.currentmove); + const fragile = p.health + armor(p) * 0.6 < 70; + // Hiding is a tactic, not a plan: after 1 s without line of sight (and no burst in progress) the controller goes + // looking for the boss; cover is only taken while a hitscan burst is actually running. + const visNow = alive && Q.visible(g, bi, 1); + mem.unseen = visNow ? 0 : mem.base.unseen + 1; + const seek = alive && mem.unseen >= 5 && !fragile && !(STREAM[b.classname] || []).includes(b.monsterinfo.currentmove); + const spot = seek && mem.unseen >= 25 ? sightSpot(g, b, p) : null; + // Against hitscan bosses stay within a short dash of cover at all times (peek, shoot, step back): the burst only + // continues while the boss can see the player at its reattack check. + const hitscanBoss = alive && STREAM[b.classname]; + const spots = alive && (stream || fragile || hitscanBoss) ? hiddenSpots(g, b) : []; + // Ammo the preferred weapons of this fight are short of (below half of the carry limit); the main weapon first. + const needAmmo = []; + if (alive) for (const [w, ammo] of PREFERRED[b.classname] || []) if (p.inv[w] && p.inv[ammo] < Q.AMMO_MAX[ammo] / 2) needAmmo.push('ammo_' + ammo); + const main = alive && (PREFERRED[b.classname] || []).find(([w]) => p.inv[w]); + const lowMain = !!main && p.inv[main[1]] < Q.AMMO_MAX[main[1]] * 0.5; + // Out of the preferred weapons' ammo (while owning one of them): only the close-range fallbacks are left, so + // restocking comes first. The easy kit owns none of them and is never starving. + const owned = alive ? (PREFERRED[b.classname] || []).filter(([w]) => p.inv[w]) : []; + const starving = owned.length > 0 && !owned.some(([w, ammo]) => p.inv[ammo] >= 6); + for (let m = 0; m < MOVES.length; m++) { + const keys = ['Shift', ...MOVES[m], ...fireKeys]; + const scores = []; + for (let k = 0; k < M.LOOK_K; k++) { + const h = simulate(g, keys, mouseTicks, LOOK, k), q = h.ents[1]; + let score = -(hp0 - (q.health + armor(q) * 0.6)) * 25 + (boss0 - h.health()[2]) * 0.4; + if (h.outcome === 'loss' || q.health <= 0) score -= 1e6; + if (h.outcome === 'win') score += 1e5; + if (alive) { + const hb = h.ents[h.bossEnt()], nd = Q.len(Q.sub(Q.center(hb), q.origin)); + const seen = hb.inuse && hb.health > 0 && Q.visible(h, 1, h.bossEnt()); + if (!starving) score -= Math.max(0, band[0] - nd) * 0.5 + Math.max(0, nd - band[1]) * 0.25; + else score -= Math.max(0, 480 - nd) * 1.0; // restocking: stay out of RANGE_NEAR / the chaingun + if (seen) score += stream ? -90 : fragile ? 5 : (/shotgun/.test(p.weapon) && b.maxs[0] < 60 && nd > 640 ? -30 : 20); + if (seek) { if (seen) score += 80; score -= nd * 0.04; if (spot) score -= Math.sqrt((spot[0] - q.origin[0]) ** 2 + (spot[1] - q.origin[1]) ** 2) * 0.25; } + // During a hitscan stream the live boss does not move (attack1 is ai_charge 0): judge cover against it too. + if (stream && !seenBy(h, b, q)) score += 60; + if (spots.length) { + let near = 1e9; for (const s of spots) near = Math.min(near, Math.sqrt((s[0] - q.origin[0]) ** 2 + (s[1] - q.origin[1]) ** 2)); + score -= stream || fragile ? near * (stream ? 0.4 : 0.08) : seek ? 0 : Math.max(0, near - 140) * 0.06; + } + } + score -= threats(h) * 1.5; + // Room to manoeuvre: free distance in eight directions (corners trap the player in a hitscan stream). + let room = 0; + for (let k = 0; k < 8; k++) { + const a = k * Math.PI / 4, to = [q.origin[0] + Q.cos(a) * 200, q.origin[1] + Q.sin(a) * 200, q.origin[2]]; + room += Q.trace(h, q.origin, [-16, -16, -24], [16, 16, 32], to, 1, Q.MASK_SOLID).fraction; + } + score -= (8 - room) * 14; + if (m === mem.base.move) score += 6; + if (q.health < 90 || armor(q) < 40) { + // Health and armor pickups (and the ones about to respawn): strong pull when hurt, a mild one otherwise. + let near = 1e9; + for (const e of h.ents) { + if (!e.inuse || !e.item) continue; + const useful = /health/.test(e.item) ? q.health < 100 : e.item === 'stimpack' || (e.item === 'armor_shard' && armor(q) < 100); + if (!useful) continue; + const soon = e.solid !== Q.SOLID_TRIGGER && e.think === 'DoRespawn' && e.nextthink - h.ms < 3000; + if (e.solid === Q.SOLID_TRIGGER || soon) near = Math.min(near, Q.len(Q.sub(e.origin, q.origin)) + (soon ? 60 : 0)); + } + // Like the ammo boxes below: a health or armor item taken inside the look-ahead is gone from the floor (q2-arena@4 + // frees it), so "nearest item" would measure the next one and punish the move that heals. Taking one counts as + // distance 0 plus a bonus that grows with the damage taken. + let healed = 0; + for (let k = 0; k < h.ents.length && k < g.ents.length; k++) { + const ge = g.ents[k], he = h.ents[k]; + if (ge.inuse && ge.solid === Q.SOLID_TRIGGER && /^(health|stimpack|armor)/.test(ge.item || '') && !(he.inuse && he.item === ge.item && he.solid === Q.SOLID_TRIGGER)) healed++; + } + if (healed) score += (q.health < 50 ? 160 : q.health < 80 ? 60 : 20) * healed; + else if (near < 1e9) score -= near * (q.health < 50 ? 0.2 : q.health < 80 ? 0.08 : 0.03); + } + if (needAmmo.length) { + // Boxes on the floor, and boxes that respawn within the next 3 s (waiting next to them is the restock). + let near = 1e9; + for (const e of h.ents) { + if (!e.inuse || !needAmmo.includes(e.item)) continue; + const soon = e.solid !== Q.SOLID_TRIGGER && e.think === 'DoRespawn' && e.nextthink - h.ms < 3000; + if (e.solid === Q.SOLID_TRIGGER || soon) near = Math.min(near, Q.len(Q.sub(e.origin, q.origin)) + (soon ? 60 : 0)); + } + // A box taken inside the look-ahead has left the floor, so "nearest box" would then measure the next one and + // punish the very move that restocks: taking a needed box counts as distance 0 plus a bonus. + let taken = 0; + for (let k = 0; k < h.ents.length && k < g.ents.length; k++) if (needAmmo.includes(h.ents[k].item) && h.ents[k].solid !== Q.SOLID_TRIGGER && g.ents[k].solid === Q.SOLID_TRIGGER) taken++; + // During a hitscan burst cover beats restocking (the burst stops at the first reattack check without sight). + if (taken) score += stream ? 30 : starving ? 200 : lowMain ? 120 : 40; + else if (near < 1e9) score -= near * (stream ? 0.03 : starving ? 0.5 : lowMain ? 0.22 : 0.07); + } + scores.push(score); + } + // Several blinded futures per move (M.LOOK_K): half the worst, half the mean, so one lucky draw cannot pick a move. + const score = scores.length > 1 ? 0.5 * Math.min(...scores) + 0.5 * scores.reduce((x, y) => x + y, 0) / scores.length : scores[0]; + if (score > bestScore) { bestScore = score; best = m; } + } + mem.move = best; + const holds = Array.from({ length: 6 }, (_, k) => { + const ks = ['Shift', ...MOVES[best]]; + // A new press fires at once inside ClientThink while the packet's turn is still under way (60 Hz); start it on hold + // set 5 (turn 2/3 done), close to the 10 Hz packet whose first sample came half-way. Held fire stays in every set. + if (tap && k < 3) ks.push(tap); else if (fire && (k >= 4 || (p.buttons & 1))) ks.push('J'); + return ks.slice(0, 4); + }); + return { holds, mouse: [dx, dy, 0] }; + }; + const armor = p => p.inv.jacket + p.inv.combat + p.inv.body; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/sekiro_remake/app3d.js b/environments/games/web/games/sekiro_remake/app3d.js new file mode 100644 index 0000000000000000000000000000000000000000..e90265f4395c5d75549b1d6b20d7bb66f3ca2eb8 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/app3d.js @@ -0,0 +1,77 @@ +/* Human play and exact native-input recording. Game state is owned by each module. */ +(function () { + 'use strict'; + const N=NativeBench, M=window.GAME_MODULE, $=s=>document.querySelector(s), canvas=$('canvas'), context=canvas.getContext('2d'); + let session=new N.Session(M,M.cases[0].id,1,.5),running=false,last=0,accumulator=0; + // A key pressed and released between two ticks stays latched until one tick has sampled it (same rule as + // _native/shell.js since 2026-11-01), so fast taps, macro keys and Playwright press() are never lost. Until 2026-11-09 this + // page released the key on a setTimeout(0), which can run before the next tick and drop the tap; now it is the tick that releases it. + const held=new Set(),pending=new Set(),releaseAfterTick=new Set(),pointerHeld=new Map(),touchHeld=new Map(); let mouse=[0,0,0],replay=null,replayIndex=0,automatic=false,script=null,scriptTick=0; + const keys={KeyW:'W',KeyA:'A',KeyS:'S',KeyD:'D',Space:'Space',ShiftLeft:'Shift',ShiftRight:'Shift',KeyJ:'J',KeyK:'K',KeyL:'L',KeyQ:'Q',KeyE:'E',KeyR:'R',ArrowUp:'W',ArrowDown:'S',ArrowLeft:'A',ArrowRight:'D'}; + document.body.dataset.game=M.id; + // Public difficulty = three tiers (2026-11-02): rebuilt from Module.tiers when the game declares it. + if(M.tiers&&$('#difficulty')){const sel=$('#difficulty'),names={easy:'Easy',normal:'Normal',hard:'Hard'};sel.textContent=''; + for(const t of ['easy','normal','hard']){const op=document.createElement('option');op.value=String(M.tiers[t]);op.textContent=names[t]+'(d='+M.tiers[t]+')';if(t==='normal')op.selected=true;sel.append(op);}} + for(const def of M.cases){const option=document.createElement('option');option.value=def.id;option.textContent=def.name;$('#case').append(option);} + const controls=Array.isArray(M.controls)?M.controls.map(value=>['',value]):Object.entries(M.controls); + for(const [key,value]of controls){const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=key;dd.textContent=value;$('dl').append(dt,dd);} + function status(value){$('#status').textContent=value;} + function clear(){held.clear();pending.clear();releaseAfterTick.clear();pointerHeld.clear();touchHeld.clear();mouse=[0,0,0];accumulator=0;} + function inputKeys(){return [...new Set([...held,...[...pointerHeld.values()].flatMap(keys=>[...keys]),...touchHeld.values()])].filter(key=>N.keys.includes(key)).slice(0,4);} + function draw(){ + M.draw(session.game,context); + $('#pause').textContent=running?'Pause':'Resume'; + $('#overlay').hidden=running&&!session.game.outcome; + $('#overlay strong').textContent=session.game.outcome?{win:'Challenge Complete',loss:'Challenge Failed',timeout:'Time up'}[session.game.outcome]:replay?'Replay · Paused':session.game.t?'Paused':'Are You Ready?'; + $('#overlay span').textContent=session.game.outcome?'Restart the challenge or export this replay':session.game.t?'Click the screen or press Resume to return to battle':'Click Start Challenge, then click the screen to lock the mouse and turn the camera'; + } + function reset(id,seed,difficulty){running=false;automatic=false;replay=null;script=null;scriptTick=0;clear();session=new N.Session(M,id,seed,difficulty);draw();return session.snapshot();} + window.nativeAPI={reset,packet(packet){if(running)throw Error('Pause before a scripted packet');const value=session.packet(packet);draw();return value;}, + state(){return session.snapshot();},recording(){return session.export();}, + render(){draw();return canvas.toDataURL('image/png');}, + renderMetrics(){return M.renderMetrics?M.renderMetrics(context):{};}, + module(){return {id:M.id,hz:M.hz,version:M.version,cases:M.cases};}}; + // PC-style mouse look (2026-11-09): the first click on the canvas during a fight locks the pointer, after which plain mouse + // movement turns the camera and the buttons stay attack / guard. Not on the start / resume buttons: while the pointer is + // locked every click goes to the canvas, so the toolbar would be unreachable until Esc. Dragging still works without a lock. + function lockPointer(){if(document.pointerLockElement===canvas||!canvas.requestPointerLock)return;try{const r=canvas.requestPointerLock();if(r&&r.catch)r.catch(()=>{});}catch(error){}} + document.addEventListener('pointerlockchange',()=>{if(document.pointerLockElement===canvas)status('Mouse locked · Press Esc to unlock');else if(running&&!automatic&&!replay){running=false;clear();status('Paused (mouse unlocked) · Click the screen to resume and lock the mouse');draw();} + else if(!running&&!automatic&&!replay&&!session.game.outcome&&session.game.t>0)status('Paused (Esc) · Click the screen to resume and lock the mouse');}); + function start(useScript){try{reset($('#case').value,Number($('#seed').value),Number($('#difficulty').value));automatic=useScript;running=true;status(useScript?'Verification script running':'Battle started · Recording this match · Click the screen to lock the mouse; move it to turn the camera');canvas.focus();draw();}catch(error){status(error.message);}} + $('#start').onclick=()=>start(false);$('#demo').onclick=()=>start(true); + $('#pause').onclick=()=>{if(session.game.outcome)return;running=!running;clear();if(running)canvas.focus();draw();}; + $('#step').onclick=()=>{running=false;if(replay)replayTick();else session.tick();draw();}; + function openReplay(data){N.Session.import(M,data);reset(data.case,data.seed,data.difficulty);replay=data;replayIndex=0;running=true;$('#case').value=data.case;status('Replay verified · Starting playback');draw();} + function replayTick(){if(replayIndex{const data=session.export(),url=URL.createObjectURL(new Blob([JSON.stringify(data)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=M.id+'-'+session.seed+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status('Current replay exported');}; + $('#import').onclick=()=>$('#file').click();$('#file').onchange=async event=>{const file=event.target.files[0];if(!file)return;try{if(file.size>12e6)throw Error('Replay file is too large');openReplay(JSON.parse(await file.text()));}catch(error){status('Import failed: '+error.message);}event.target.value='';}; + function release(){clear();if(running){running=false;status('Window lost focus · Battle paused');}draw();} + window.addEventListener('blur',release);document.addEventListener('visibilitychange',()=>{if(document.hidden)release();}); + window.addEventListener('keydown',event=>{if(['INPUT','SELECT','BUTTON'].includes(document.activeElement.tagName))return;if(keys[event.code]){event.preventDefault();held.add(keys[event.code]);pending.add(keys[event.code]);releaseAfterTick.delete(keys[event.code]);}if(event.code==='Escape'){const wasRunning=running;running=false;clear();if(document.pointerLockElement===canvas)document.exitPointerLock?.();if(wasRunning&&!automatic&&!replay&&!session.game.outcome)status('Paused (Esc) · Click the screen to resume and lock the mouse');draw();}}); + window.addEventListener('keyup',event=>{const key=keys[event.code];if(key){event.preventDefault();if(pending.has(key))releaseAfterTick.add(key);else held.delete(key);}}); + canvas.oncontextmenu=event=>event.preventDefault();canvas.onpointerdown=event=>{if(event.button!==0&&event.button!==2)return;canvas.focus(); + // A click on the canvas while the pointer is free re-locks it and resumes a paused fight; that click is not an attack. + if(document.pointerLockElement!==canvas&&!automatic&&!replay&&!session.game.outcome&&session.game.t>0&&!running){lockPointer();running=true;clear();draw();return;} + if(document.pointerLockElement!==canvas&&running&&!automatic&&!replay)lockPointer();const keys=pointerHeld.get(event.pointerId)||new Set();keys.add(event.button===2?'RMB':'LMB');pointerHeld.set(event.pointerId,keys);}; + // Pointer Events emits pointerup only after the final mouse button is released. + // pointermove carries changes to the button mask for chorded mouse presses. + function syncMouse(event){if(event.pointerType==='mouse'&&pointerHeld.has(event.pointerId)){const keys=new Set();if(event.buttons&1)keys.add('LMB');if(event.buttons&2)keys.add('RMB');if(keys.size)pointerHeld.set(event.pointerId,keys);else pointerHeld.delete(event.pointerId);}} + window.addEventListener('pointermove',syncMouse); + window.addEventListener('pointerup',event=>{if(event.pointerType==='mouse')syncMouse(event);else pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + window.addEventListener('pointercancel',event=>{pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + canvas.onpointermove=event=>{if(event.buttons||document.pointerLockElement===canvas){mouse[0]+=event.movementX;mouse[1]+=event.movementY;}}; + canvas.onwheel=event=>{event.preventDefault();mouse[2]+=Math.sign(event.deltaY);}; + canvas.ondblclick=()=>canvas.requestPointerLock?.(); + document.querySelectorAll('[data-key]').forEach(button=>{button.onpointerdown=event=>{event.preventDefault();button.setPointerCapture(event.pointerId);touchHeld.set(event.pointerId,button.dataset.key);};button.onpointerup=button.onpointercancel=event=>touchHeld.delete(event.pointerId);}); + function frame(now){const delta=Math.min(.1,(now-last)/1000||0);last=now;const beforeTick=session.game.t,wasRunning=running;try{ + if(running&&!session.game.outcome){accumulator+=delta;while(accumulator>=1/M.hz&&running&&!session.game.outcome){accumulator-=1/M.hz; + if(replay)replayTick();else if(automatic){const count=M.hz/5;if(scriptTick===0)script=(M.scripted||M.oracle).call(M,session.game);const sub=Math.ceil((scriptTick+1)*6/count)-1;session.tick(script.holds[sub],script.mouse.map(value=>value/count));scriptTick=(scriptTick+1)%count;} + else{session.tick(inputKeys(),mouse.map((value,index)=>N.clamp(value,index===2?-5:-1000,index===2?5:1000)));mouse=[0,0,0];pending.clear();for(const key of releaseAfterTick)held.delete(key);releaseAfterTick.clear();}} + if(session.game.outcome){running=false;status({win:'Challenge Complete',loss:'Challenge Failed',timeout:'Challenge Timed Out'}[session.game.outcome]+' · You can export or replay this match');}} + if(session.game.t!==beforeTick||running!==wasRunning)draw(); + }catch(error){running=false;clear();status('Runtime error: '+error.message);$('#overlay').hidden=false;$('#overlay strong').textContent='Unable to resume right now';$('#overlay span').textContent=error.message;} + requestAnimationFrame(frame); + } + window.addEventListener('pagehide',()=>M.closeRenderer?.(context)); + draw();requestAnimationFrame(frame); +})(); diff --git a/environments/games/web/games/sekiro_remake/compact_actions.json b/environments/games/web/games/sekiro_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..13d86ba2c536855ddacfcdd53c2e68c6a2f5dbf1 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/compact_actions.json @@ -0,0 +1,1135 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "sekiro_remake", + "version": "sekiro-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W" + ] + }, + { + "label": "forward_start", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [], + [] + ] + }, + { + "label": "forward_end", + "subs": [ + [], + [], + [], + [ + "W" + ], + [ + "W" + ], + [ + "W" + ] + ] + }, + { + "label": "forward_tap", + "subs": [ + [ + "W" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "back", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D" + ] + }, + { + "label": "turn_left_30", + "dx": -175 + }, + { + "label": "turn_right_30", + "dx": 175 + } + ] + }, + { + "name": "act", + "options": [ + { + "label": "none" + }, + { + "label": "attack_0", + "subs": [ + [ + "J" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "attack_1", + "subs": [ + [], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "attack_2", + "subs": [ + [], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "attack_3", + "subs": [ + [], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "attack_4", + "subs": [ + [], + [], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "attack_5", + "subs": [ + [], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_0", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "deflect_1", + "subs": [ + [], + [ + "RMB" + ], + [], + [], + [], + [] + ] + }, + { + "label": "deflect_2", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [], + [] + ] + }, + { + "label": "deflect_3", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [], + [] + ] + }, + { + "label": "deflect_4", + "subs": [ + [], + [], + [], + [], + [ + "RMB" + ], + [] + ] + }, + { + "label": "deflect_5", + "subs": [ + [], + [], + [], + [], + [], + [ + "RMB" + ] + ] + }, + { + "label": "deflect_attack_0_1", + "subs": [ + [ + "RMB" + ], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "deflect_attack_0_2", + "subs": [ + [ + "RMB" + ], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "deflect_attack_0_3", + "subs": [ + [ + "RMB" + ], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "deflect_attack_0_4", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "deflect_attack_0_5", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_attack_1_2", + "subs": [ + [], + [ + "RMB" + ], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "deflect_attack_1_3", + "subs": [ + [], + [ + "RMB" + ], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "deflect_attack_1_4", + "subs": [ + [], + [ + "RMB" + ], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "deflect_attack_1_5", + "subs": [ + [], + [ + "RMB" + ], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_attack_2_3", + "subs": [ + [], + [], + [ + "RMB" + ], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "deflect_attack_2_4", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "deflect_attack_2_5", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_attack_3_4", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [ + "J" + ], + [] + ] + }, + { + "label": "deflect_attack_3_5", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [], + [ + "J" + ] + ] + }, + { + "label": "deflect_attack_4_5", + "subs": [ + [], + [], + [], + [], + [ + "RMB" + ], + [ + "J" + ] + ] + }, + { + "label": "deflect_0_4", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [ + "RMB" + ], + [] + ] + }, + { + "label": "deflect_0_5", + "subs": [ + [ + "RMB" + ], + [], + [], + [], + [], + [ + "RMB" + ] + ] + }, + { + "label": "deflect_2_4", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [ + "RMB" + ], + [] + ] + }, + { + "label": "deflect_2_5", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [], + [ + "RMB" + ] + ] + }, + { + "label": "deflect_3_5", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [], + [ + "RMB" + ] + ] + }, + { + "label": "step_alt_0", + "subs": [ + [ + "Shift" + ], + [], + [ + "Shift" + ], + [], + [ + "Shift" + ], + [] + ] + }, + { + "label": "step_alt_1", + "subs": [ + [], + [ + "Shift" + ], + [], + [ + "Shift" + ], + [], + [ + "Shift" + ] + ] + }, + { + "label": "deflect_2_4_5", + "subs": [ + [], + [], + [ + "RMB" + ], + [], + [ + "RMB" + ], + [ + "RMB" + ] + ] + }, + { + "label": "step_0", + "subs": [ + [ + "Shift" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "step_1", + "subs": [ + [], + [ + "Shift" + ], + [], + [], + [], + [] + ] + }, + { + "label": "step_2", + "subs": [ + [], + [], + [ + "Shift" + ], + [], + [], + [] + ] + }, + { + "label": "step_3", + "subs": [ + [], + [], + [], + [ + "Shift" + ], + [], + [] + ] + }, + { + "label": "step_4", + "subs": [ + [], + [], + [], + [], + [ + "Shift" + ], + [] + ] + }, + { + "label": "jump_0", + "subs": [ + [ + "Space" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "jump_1", + "subs": [ + [], + [ + "Space" + ], + [], + [], + [], + [] + ] + }, + { + "label": "jump_2", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "jump_3", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "jump_4", + "subs": [ + [], + [], + [], + [], + [ + "Space" + ], + [] + ] + }, + { + "label": "jump_5", + "subs": [ + [], + [], + [], + [], + [], + [ + "Space" + ] + ] + }, + { + "label": "jump_kick_0", + "subs": [ + [ + "Space" + ], + [], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "jump_kick_1", + "subs": [ + [], + [ + "Space" + ], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "jump_kick_2", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [ + "Space" + ], + [] + ] + }, + { + "label": "jump_kick_3", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [ + "Space" + ] + ] + }, + { + "label": "jump_attack_0_1", + "subs": [ + [ + "Space" + ], + [ + "J" + ], + [], + [], + [], + [] + ] + }, + { + "label": "jump_attack_0_2", + "subs": [ + [ + "Space" + ], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "jump_attack_0_3", + "subs": [ + [ + "Space" + ], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "jump_attack_1_2", + "subs": [ + [], + [ + "Space" + ], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "jump_attack_1_3", + "subs": [ + [], + [ + "Space" + ], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "jump_attack_1_4", + "subs": [ + [], + [ + "Space" + ], + [], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "jump_attack_2_3", + "subs": [ + [], + [], + [ + "Space" + ], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "jump_attack_2_4", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [ + "J" + ], + [] + ] + }, + { + "label": "jump_attack_2_5", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "jump_attack_3_4", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [ + "J" + ], + [] + ] + }, + { + "label": "jump_attack_3_5", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [ + "J" + ] + ] + }, + { + "label": "jump_attack_4_5", + "subs": [ + [], + [], + [], + [], + [ + "Space" + ], + [ + "J" + ] + ] + }, + { + "label": "guard_hold_2", + "subs": [ + [ + "RMB" + ], + [ + "RMB" + ], + [], + [], + [], + [] + ] + }, + { + "label": "guard_hold_3", + "subs": [ + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ], + [], + [], + [] + ] + }, + { + "label": "guard_hold_6", + "subs": [ + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ] + ] + }, + { + "label": "guard_hold_late", + "subs": [ + [], + [], + [], + [ + "RMB" + ], + [ + "RMB" + ], + [ + "RMB" + ] + ] + }, + { + "label": "run", + "keys": [ + "Shift" + ] + }, + { + "label": "heal_0", + "subs": [ + [ + "Q" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "heal_2", + "subs": [ + [], + [], + [ + "Q" + ], + [], + [], + [] + ] + }, + { + "label": "heal_4", + "subs": [ + [], + [], + [], + [], + [ + "Q" + ], + [] + ] + }, + { + "label": "revive", + "tap": [ + "R" + ] + }, + { + "label": "lock_toggle", + "tap": [ + "E" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/sekiro_remake/draw.js b/environments/games/web/games/sekiro_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..79e2772e37593cb5bd20356ab26a1bef3c932e9e --- /dev/null +++ b/environments/games/web/games/sekiro_remake/draw.js @@ -0,0 +1,70 @@ +/* Sekiro HUD drawn over the WebGL frame: boss name, deathblow markers and vitality at the top left, posture gauges + * growing from the centre (boss at the top, Sekiro at the bottom), Sekiro's vitality, resurrection nodes, gourd and + * ailment gauges at the bottom left, the red perilous kanji above Sekiro, the deathblow mark on the target, the blue lock-on + * reticle (only while locked) and an edge arrow toward an off-screen boss, native Hz. */ +(function(root){ + 'use strict';const M=root.SekiroGame,B=root.Boss3D,clamp=(x,a,b)=>Math.max(a,Math.min(b,x)); + const TIER_NAMES={easy:'Easy',normal:'Normal',hard:'Hard'}; + function font(c,size,weight='',serif=false){c.font=`${weight} ${size}px ${serif?'"Noto Serif SC","Songti SC","SimSun","Microsoft YaHei",serif':'"Segoe UI","Microsoft YaHei",sans-serif'}`;} + function text(c,s,x,y,size,color,align='left',o={}){font(c,size,o.weight||'',o.serif);c.textAlign=align;c.textBaseline='alphabetic'; + if(o.glow){c.shadowColor=o.glow;c.shadowBlur=o.blur||12;}c.fillStyle='rgba(6,8,10,.75)';c.fillText(s,x+1,y+1.5);c.fillStyle=color;c.fillText(s,x,y);c.shadowBlur=0;} + function bar(c,x,y,w,h,v,fill,back='rgba(10,12,14,.72)'){c.fillStyle=back;c.fillRect(x,y,w,h);c.fillStyle=fill;c.fillRect(x+1,y+1,Math.max(0,(w-2)*clamp(v,0,1)),h-2); + c.strokeStyle='rgba(220,205,170,.55)';c.lineWidth=1;c.strokeRect(x+.5,y+.5,w-1,h-1);} + // Posture grows outward from the middle; it turns hotter as it nears a break and darker while low vitality slows recovery. + function posture(c,cx,y,w,h,v,slow,flash){if(v<=0.002)return;const half=w/2*clamp(v,0,1);c.fillStyle='rgba(10,10,12,.7)';c.fillRect(cx-w/2,y,w,h); + const hot=v>.85&&flash,col=hot?'#ff4f1f':v>.6?'#f08a2a':'#e6b143';const g=c.createLinearGradient(cx-half,0,cx+half,0);g.addColorStop(0,col);g.addColorStop(.5,'#ffe5a0');g.addColorStop(1,col); + c.fillStyle=g;c.fillRect(cx-half,y+1,half*2,h-2);if(slow){c.fillStyle='rgba(120,20,10,.35)';c.fillRect(cx-half,y+1,half*2,h-2);} + c.fillStyle='rgba(255,240,200,.9)';c.fillRect(cx-1,y-2,2,h+4);c.strokeStyle='rgba(230,200,150,.5)';c.strokeRect(cx-w/2+.5,y+.5,w-1,h-1);} + function dot(c,x,y,r,full,color){c.beginPath();c.arc(x,y,r,0,Math.PI*2);c.fillStyle=full?color:'rgba(30,26,26,.85)';c.fill();c.lineWidth=1.5;c.strokeStyle=full?'rgba(255,190,170,.9)':'rgba(140,120,118,.8)';c.stroke();} + // Lock-on aids, drawn in 2D over the frame so walls and pillars never hide them (as zelda_oot_remake/draw.js reticle / edgeArrow). + // Cool blue, so the lock never reads as the red deathblow dot or the red perilous kanji; the ring sits at the deathblow height and circles that dot. + const LOCK='#8fdcff',PI2=Math.PI*2; + function reticle(c,x,y,r,a,dot){c.save();c.translate(x,y);c.lineWidth=4;c.strokeStyle='rgba(8,12,20,.85)';c.beginPath();c.arc(0,0,r,0,PI2);c.stroke(); + c.lineWidth=2;c.strokeStyle=LOCK;c.beginPath();c.arc(0,0,r,0,PI2);c.stroke(); + for(let i=0;i<4;i++){c.save();c.rotate(a+i*PI2/4);c.beginPath();c.moveTo(0,-r-2);c.lineTo(-5,-r-11);c.lineTo(5,-r-11);c.closePath();c.fillStyle=LOCK;c.fill();c.lineWidth=1.2;c.strokeStyle='rgba(8,12,20,.85)';c.stroke();c.restore();} + if(dot){c.beginPath();c.arc(0,0,3,0,PI2);c.fillStyle=LOCK;c.fill();c.lineWidth=1.2;c.strokeStyle='rgba(8,12,20,.85)';c.stroke();}c.restore();} + function edgeArrow(c,ax,ay,col,label){const m=36,k=Math.min((427-m)/Math.max(1e-6,Math.abs(ax)),(240-m)/Math.max(1e-6,Math.abs(ay))),x=427+ax*k,y=240+ay*k,a=Math.atan2(ay,ax); + c.save();c.translate(x,y);c.rotate(a);c.beginPath();c.moveTo(18,0);c.lineTo(-10,-13);c.lineTo(-4,0);c.lineTo(-10,13);c.closePath();c.fillStyle=col;c.fill();c.lineWidth=2.5;c.strokeStyle='rgba(8,12,20,.92)';c.stroke();c.restore(); + text(c,label,x-Math.cos(a)*30,y-Math.sin(a)*30+5,12,col,'center');} + function gourd(c,x,y){c.fillStyle='#9a5a28';c.beginPath();c.arc(x,y+5,6.5,0,Math.PI*2);c.arc(x,y-4,4.5,0,Math.PI*2);c.fill();c.fillStyle='#d9b56a';c.fillRect(x-1.5,y-12,3,4);c.fillStyle='rgba(255,240,200,.3)';c.beginPath();c.arc(x-2,y+3,2,0,Math.PI*2);c.fill();} + M.draw=function(g,c){const scene=B.render('sekiro',g,c),p=g.player,b=g.boss,kind=g.kind||'genichiro',K=M.bosses[kind],tm=g.t/M.hz; + // ---- boss: deathblow markers, name and vitality (top left) + const [shown,left]=K.markers(b),name=K.names[Math.min(K.names.length-1,(b.phase||1)-1)]; + for(let i=0;i0){c.strokeStyle='#1a1214';c.lineWidth=3;c.beginPath();c.moveTo(30,414);c.lineTo(62,405);c.stroke();text(c,'Resurrection sealed',70,414,11,'#c9b0bb');} + bar(c,30,422,236,8,(p.hp||0)/(p.maxHp||1),p.poisoned>0?'#7d9a3a':'#c7392f'); + let gy=416;for(const [v,label,col] of [[p.poison||0,'Poison',p.poisoned>0?'#a8d050':'#7da040'],[p.terror||0,'Terror','#9b1a2a'],...(p.burn!==undefined?[[p.burning>0?100:p.burn,'Burn',p.burning>0?'#ff7a2a':'#d4602a']]:[])]){if(v<=0.5&&!(label==='Poison'&&p.poisoned>0))continue;gy-=13;text(c,label,272,gy+8,11,col);bar(c,286,gy,70,6,label==='Poison'&&p.poisoned>0?1:v/100,col);} + gourd(c,40,452);text(c,'× '+(p.gourds??0),52,458,14,'#e8d9b8'); + posture(c,427,446,300,7,(p.posture||0)/(p.maxPosture||100),(p.hp||0)/(p.maxHp||1)<.5,Math.floor(g.t/6)%2===0); + // ---- perilous kanji above Sekiro, deathblow mark on the target + if(scene&&b.perilous&&b.telegraph&&!p.dead){const s=scene.project(p.x,(p.y||0)+2.05,p.z),pulse=1+.08*Math.sin(g.t*.5); + c.save();c.globalAlpha=.85;const rg=c.createRadialGradient(s.x,s.y-14,2,s.x,s.y-14,36*pulse);rg.addColorStop(0,'rgba(255,40,20,.55)');rg.addColorStop(1,'rgba(255,40,20,0)');c.fillStyle=rg;c.fillRect(s.x-40,s.y-56,80,84);c.restore(); + text(c,'PERIL',s.x,s.y,Math.round(40*pulse),'#ff3b26','center',{weight:'bold',serif:true,glow:'rgba(255,40,10,.9)',blur:14});} + // Lock reticle while locked; when the boss is out of the picture (behind the camera, or past an edge) an arrow at the edge points to it. + if(scene&&b.state!=='dead'&&!g.outcome&&!p.dead){const h=kind==='ape'?2.1:kind==='gyoubu'?2.7:kind==='demon'?3.6:1.2,s=scene.project(b.x,(b.y||0)+h,b.z),on=s.visible&&s.x>8&&s.x<846&&s.y>8&&s.y<472; + if(on&&g.lockOn)reticle(c,s.x,s.y,20,g.t*.04,!b.deathblowAvailable); + else if(!on){const yaw=g.cameraYaw||0,dx=b.x-p.x,dz=b.z-p.z,right=-dx*Math.cos(yaw)+dz*Math.sin(yaw),ahead=dx*Math.sin(yaw)+dz*Math.cos(yaw); + // In front: the projected direction; behind the camera the projection flips, so use the camera frame (screen-right, and down for behind). + const [ax,ay]=s.visible&&ahead>0?[s.x-427,s.y-240]:[right,-ahead];edgeArrow(c,ax,ay,g.lockOn?LOCK:'#ffcf8a',g.lockOn?'Lock':'Boss');}} + if(scene&&b.deathblowAvailable){const h=kind==='ape'?2.1:kind==='gyoubu'?2.7:kind==='demon'?3.6:1.2,s=scene.project(b.x,(b.y||0)+h,b.z),r=7+Math.sin(g.t*.25)*1.5; + c.beginPath();c.arc(s.x,s.y,r+7,0,Math.PI*2);c.strokeStyle='rgba(255,60,40,.5)';c.lineWidth=2;c.stroke();c.beginPath();c.arc(s.x,s.y,r,0,Math.PI*2);c.fillStyle='#e0261c';c.shadowColor='#ff3020';c.shadowBlur=12;c.fill();c.shadowBlur=0;} + if(p.lightning>0&&!p.dead){const s=scene?scene.project(p.x,(p.y||0)+2.2,p.z):{x:427,y:200};text(c,'Lightning strike',s.x,s.y,20,'#ffe39a','center',{weight:'bold',glow:'rgba(255,220,120,.9)'});} + // ---- Shinobi Execution banner (the guardian ape's first one is a deception, S14) + const banner=(b.executing>0&&(b.phase===b.bars||kind==='ape'))||g.outcome==='win'||(b.state==='dead'&&(b.deadTicks||0)>110); + if(banner){const u=g.outcome==='win'?1:clamp(b.state==='dead'?((b.deadTicks||0)-110)/40:(58-(b.executing||0))/14,0,1);c.save();c.globalAlpha=u; + c.fillStyle='rgba(0,0,0,.35)';c.fillRect(0,196,854,92);text(c,'DEATHBLOW',427,262,62,'#e9e2d2','center',{weight:'bold',serif:true,glow:'rgba(180,20,20,.9)',blur:18}); + text(c,kind==='isshin'?'FINAL EXECUTION':'EXECUTION',427,282,12,'#c9b9a0','center');c.restore();} + if(p.dead&&!g.outcome){c.fillStyle='rgba(30,0,0,.28)';c.fillRect(0,0,854,480);text(c,'DEAD',427,252,92,'#c7261e','center',{weight:'bold',serif:true,glow:'rgba(200,0,0,.8)',blur:20}); + text(c,p.terrorDeath?'Killed by terror · Cannot resurrect':lives>0&&!p.resurrectionLocked?'Press R to resurrect':'Cannot resurrect',427,296,17,'#efe0d1','center');} + // ---- clock, tier and native rate (bottom right) + const tierName=Object.entries(M.tiers).find(([,v])=>Math.abs(v-g.d)<1e-9)?.[0]; + text(c,`${M.hz}Hz`,826,442,13,'#e8c983','right',{weight:'bold'});text(c,(tierName?TIER_NAMES[tierName]+' · ':'d='+(+g.d).toFixed(2)+' · ')+tm.toFixed(1)+'s',826,460,12,'#d6d2c6','right'); + }; + M.renderStatus=ctx=>B.status('sekiro',ctx);M.renderMetrics=ctx=>B.metrics('sekiro',ctx);M.closeRenderer=ctx=>B.close('sekiro',ctx); +})(window); diff --git a/environments/games/web/games/sekiro_remake/game.js b/environments/games/web/games/sekiro_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..29a6747fa8e1c49a46df108699faf2006b01e171 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/game.js @@ -0,0 +1,1167 @@ +/* Sekiro: Shadows Die Twice - six boss duels in one deterministic 60 Hz engine (rules sekiro@10). + * sekiro/genichiro Ashina Castle top: two armored bars, then Way of Tomoe (three deathblows) + * sekiro/guardian_ape Sunken Valley watering hole: the white beast, a false Shinobi Execution, the headless apparition + * sekiro/lady_butterfly Hirata Estate audience chamber: threads and kunai, then illusions and spirit butterflies + * sekiro/isshin Silvergrass field: Way of Tomoe Genichiro, then Isshin with sword, spear and matchlock, lightning (four deathblows) + * sekiro/gyoubu Ashina Castle Gate: the mounted Gyoubu, charges past and away, rope spear, hind-leg kick (two deathblows) + * sekiro/demon The burning gate: the Demon of Hatred, fire arms, fireballs, the fire ring and Burn (three deathblows) + * Mechanics follow public guides (Fextralife, BWIKI parameter pages, GameWith/VGR guides). + * The hard tier's vitality / posture / recovery anchors are BWIKI base parameters; move timings, reaches, speeds and the + * player's numbers are calibration values, not extracted FromSoftware data. */ +(function(root){ + 'use strict'; + const N=root.NativeBench,A=(x,z)=>Math.atan2(x,z),dist=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z); + // Public tiers (2026-11-02). Boss magnitudes run geometrically through the easy / normal / hard anchors. + const TIERS={easy:.2,normal:.5,hard:.8}; + function tier(d,[e,n,h]){return d>=TIERS.normal?n*Math.pow(h/n,(d-TIERS.normal)/(TIERS.hard-TIERS.normal)):n*Math.pow(e/n,(TIERS.normal-d)/(TIERS.normal-TIERS.easy));} + const C={playerHP:100,posture:100,move:.075,run:.125,dodge:.2,dodgeFrames:16,dodgeInv:6, + deflectFrames:12,spamFloor:3,spamInterval:24,spamReset:60, + // Sekiro waits about a second before posture recovers; enemy posture has no delay (S04). + playerPostureDelay:60,postureRate:.26,guardRecovery:2.7,deflectChainWindow:40,deflectChainBonus:.06,deflectChainMax:.3, + jumpSpeed:.215,gravity:.0115,sweepHeight:.55,grabJumpHeight:.6, + slashWind:7,slashEnd:25,thrustCharge:25,thrustWind:10,thrustEnd:34, + // Kusabimaru normal cut at Attack Power 1 deals 80 vitality (S13: 80 at AP 1, +20 per point). Posture numbers are + // percent units of Genichiro's armored posture (660, S22): postureUnit converts them to absolute posture. + slashDamage:80,thrustDamage:120,slashPosture:9,thrustPosture:12,blockPosture:7,thrustBlockPosture:9,postureUnit:3.3, + mikiriPosture:25,mikiriStun:30,stompPosture:22,hitStun:20, + deathblowWindow:180,deathblowMissFraction:.75,executionFrames:58,deathblowReach:2.15, + guardBreakStagger:58,safetyRollAfter:14,safetyRollRemain:12, + gourdStock:7,gourdHeal:45,gourdFrames:66,gourdApply:26,resurrectionNodes:2,reviveFrames:50,reviveFraction:.5, + // Status ailments: buildup gauges decay when not fed; a full poison gauge drains vitality for a while, a full + // terror gauge kills outright (S20/S21; rates are calibration). + poisonDecay:.08,poisonTicks:360,poisonDrain:.06,terrorDecay:.12}; + // Posture recovery cut by remaining vitality. Bosses: BWIKI per-boss tables (S22, S16, S18); Sekiro: S04 quartiles. + const REGEN={gen12:[[.8,1],[.6,.5],[.4,.167],[0,.083]],std:[[.8,1],[.6,.6],[.4,.3],[0,.1]],player:[[.75,1],[.5,.66],[.25,.33],[0,.01]]}; + // Small seeds give nearly identical first xorshift draws; scramble the seed so seeds 1..8 differ from the start. + function mixSeed(seed){let x=(seed>>>0)^0x9e3779b9;x=Math.imul(x^(x>>>16),0x85ebca6b);x=Math.imul(x^(x>>>13),0xc2b2ae35);x^=x>>>16;return (x>>>0)||0x6d2b79f5;} + function regenFactor(table,h){for(const [at,f] of REGEN[table])if(h>at||at===0)return f;return 0;} + const H=(t,o={})=>Object.assign({t,type:'slash',reach:2.8,hp:12,posture:15},o); + // One draw per choice; entries listed in w get that relative weight (all 1 = the plain uniform pick). + function pickW(g,list,w={}){const ws=list.map(n=>w[n]??1),total=ws.reduce((a,b)=>a+b,0);let r=N.rand(g)*total;for(let i=0;iH(t,{reach:2.9,hp:i===8?18:10,posture:i===8?25:11,parry:i===8?14:6,push:i===8?.7:0,final:i===8}))}, + jump_slam:{duration:57,hits:[{t:42,type:'slam',reach:2.65,hp:19,posture:23}],whiff:[[42,57]]}, + tomoe_slash:{duration:44,hits:[H(16,{reach:3.0,hp:14,posture:17})]}, + swipe5:{duration:100,hits:[16,30,44,58,74].map(t=>H(t,{reach:2.9,hp:10,posture:12,parry:9})),open:[[86,100]]}, + thrust:{duration:58,perilous:'thrust',hits:[{t:33,type:'thrust',reach:3.4,hp:25,posture:27}],open:[[46,58]]}, + sweep:{duration:61,perilous:'sweep',hits:[{t:34,type:'sweep',reach:3.5,hp:25,posture:29}],open:[[42,61]]}, + grab:{duration:68,perilous:'grab',hits:[{t:34,type:'grab',dodge:true,reach:1.95,hp:34,posture:20}],whiff:[[40,68]]}, + running_grab:{duration:78,perilous:'grab',hits:[{t:48,type:'grab',dodge:true,reach:2.05,hp:36,posture:25}],whiff:[[54,78]]}, + leap_thrust:{duration:67,perilous:'thrust',hits:[{t:40,type:'thrust',reach:3.1,hp:28,posture:30}],whiff:[[48,67]]}, + dive_ready:{duration:G.diveReady,hits:[],next:'leap_thrust'}, + bow:{duration:53,hits:[],shots:[22],open:[[0,53]]}, + bow_roll:{duration:96,hits:[H(70,{hp:14,posture:16})],shots:[20],open:[[0,46]]}, + quick_bow:{duration:36,hits:[],shots:[10],open:[[0,36]]}, + charged_bow:{duration:96,hits:[],shots:[70],heavy:[70],open:[[0,96]]}, + volley:{duration:88,hits:[],shots:[30,38,46,65],open:[[0,88]]}, + lightning_slash:{duration:125,perilous:'lightning',hits:[{t:100,type:'lightning',reach:10,hp:0,posture:0,arc:.42}],open:[[0,100],[104,125]]}, + lightning_sweep:{duration:125,perilous:'lightning',hits:[{t:100,type:'lightning',reach:8.5,hp:0,posture:0,arc:1.7}],open:[[0,100],[104,125]]}, + lightning_bow:{duration:125,perilous:'lightning',hits:[],shots:[96],open:[[0,125]]}, + tomoe_awaken:{duration:72,hits:[],invulnerable:true,next:'leap_thrust'} + }; + const GENICHIRO={moves:GEN_MOVES,radius:.5,height:1.95,kickRange:2.15,names:['Bow-and-Blade Swordsman','Bow-and-Blade Swordsman','Lightning Swordsman'],forms:['genichiro','genichiro','tomoe'], + // [easy, normal, hard] pools, calibrated to the tier time windows with the reference controller. BWIKI base (S22) + // fixes the shape: bars 1-2 HP 1598 / posture 660 / 60 per s (full recovery 11 s), bar 3 x1.6 HP, x1.36 posture, 22.5 s. + anchors:{hp:[170,1129,3768],posture:[371,903,1556],recover:11,tomoeHP:1.6,tomoePosture:1.36,tomoeRecover:22.5,rest:[70,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]}, + tune(d){const a=this.anchors,hp=tier(d,a.hp),posture=tier(d,a.posture); + const armored={hp:Math.round(hp),posture:Math.round(posture),regen:Math.round(posture)/(a.recover*60),table:'gen12'},tp=Math.round(posture*a.tomoePosture); + return {bars:[armored,{...armored},{hp:Math.round(hp*a.tomoeHP),posture:tp,regen:tp/(a.tomoeRecover*60),table:'std'}], + rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({lightning:false,lastLightningAt:-999,extraShot:0}), + start(g){g.startMove('opening');}, + idle(g){const b=g.boss,p=g.player;g.face(b,p);if(dist(b,p)>2.25)g.advance(.058*g.tune.chase,2.2); + if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));}, + choose(g){const b=g.boss,p=g.player,d=dist(b,p),tomoe=b.form_id==='tomoe'; + // If idle, he always answers healing: a charged shot (armored) or a sword-dive thrust (Way of Tomoe) (S01). + if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return tomoe?'dive_ready':'charged_bow';} + const r=N.rand(g); + // Way of Tomoe keeps returning to lightning; the pacing rule is an engineering calibration, not a measured rate. + if(tomoe&&r<(g.t-b.lastLightningAt>G.lightningDue?G.lightningDueChance:G.lightningChance))return ['lightning_slash','lightning_sweep','lightning_bow'][Math.floor(N.rand(g)*3)]; + if(g.t-b.attackedAt<90){const q=N.rand(g);if(q<.3)return 'jump_slam';if(q<.45&&!tomoe)return 'volley';} + if(d>5)return tomoe?(r<.6?'leap_thrust':'volley'):b.healthbar_phase===2?(r<.4?'charged_bow':r<.7?'volley':r<.85?'bow':'bow_roll'):(r<.45?'charged_bow':r<.75?'volley':'bow_roll'); + const list=b.healthbar_phase===1?['slash','double','kick_arrow','passage','jump_slam','grab','thrust','bow_roll','volley']: + b.healthbar_phase===2?['slash','double','kick_arrow','passage','jump_slam','sweep','grab','thrust','bow_roll','volley','bow_roll','bow']: + ['double','passage','swipe5','jump_slam','leap_thrust','running_grab','sweep','thrust','kick_arrow','bow_roll']; + return list[Math.floor(r*list.length)];}, + onStart(g,name){const b=g.boss;b.lightning=name.startsWith('lightning');if(b.lightning)b.lastLightningAt=g.t;b.extraShot=name==='bow_roll'&&N.rand(g)<.5?36:0;}, + followUp(g,move){const b=g.boss; + if(b.chainNext==='thrust_followup')return dist(b,g.player)>G.thrustFollowRange?'quick_bow':'running_grab'; + if(b.chainNext)return b.chainNext; + if(GEN_MOVES[move].next)return GEN_MOVES[move].next; + if(move==='jump_slam')return b.healthbar_phase===1?'thrust':b.healthbar_phase===2?(N.rand(g)=18&&t<80)g.advance(.025*ch,1.6); + if(move==='opening'&&t>=32&&t<58)g.advance(.17,1.9); + if(move==='bow_roll'&&t>=46&&t<62)g.advance(.16,1.8); + if(move==='jump_slam'){b.y=t<42?Math.max(0,Math.sin(Math.PI*N.clamp((t-12)/30,0,1))*2.1):0;if(t>=15&&t<38)g.advance(.17,1.7);} + if(move==='leap_thrust'){b.y=t<40?Math.max(0,Math.sin(Math.PI*N.clamp((t-13)/27,0,1))*1.5):0;if(t>=19&&t<40)g.advanceCommitted(.32,1.1);} + if(move==='running_grab'&&t<46){if(t<35)g.advance(.13*ch,1.1);else g.advanceCommitted(.13,1.1);} + if((move==='grab'||move==='sweep')&&t<18){const side=move==='grab'?-1:1;g.move(b,Math.cos(b.yaw)*.035*side,-Math.sin(b.yaw)*.035*side);} + if(move==='thrust'&&t>=25&&t<=33)g.advanceCommitted(.17,1.15); + if(move==='volley'){b.y=Math.max(0,Math.sin(Math.PI*N.clamp((t-12)/66,0,1))*1.8);if(t<20)g.move(b,-Math.sin(b.yaw)*.05,-Math.cos(b.yaw)*.05);} + // Lightning of Tomoe: grip and crouch, leap, the bolt meets the blade, then the strike ~1.4 s after takeoff (S05). + if(move.startsWith('lightning'))b.y=Math.max(0,Math.sin(Math.PI*N.clamp((t-16)/90,0,1))*2.6); + }, + afterHits(g,move,m,t){const b=g.boss,p=g.player; + for(const hit of m.hits)if(t===hit.t&&hit.type==='lightning')g.hazards.push({type:move==='lightning_sweep'?'lightning_arc':'lightning_line',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:hit.reach,age:0,life:14}); + for(const shot of m.shots||[])if(t===shot)g.arrow(!!m.heavy?.includes(shot),move==='lightning_bow'); + if(move==='bow_roll'&&b.extraShot&&t===b.extraShot)g.arrow(false,false); + // Floating Passage cancel: a distant player gets a fast bow shot, usually only after he lost a bar (S01). + if(move==='passage'&&t===92&&b.healthbar_phase>=2&&dist(b,p)>4.5){g.stats.passageCancels++;g.emit('passage_cancel');g.startMove('quick_bow');} + }, + // His guard: two blocks, then a perfect parry that starts the Floating Passage string (S01) or a quick counter. + playerHit(g,kind,open){const b=g.boss,p=g.player,busy=b.state==='attack'; + if(open){g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);g.interruptBoss(C.hitStun);g.fx('cut',b);return;} + b.guardCount++; + if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+4);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect'); + if(!busy||b.moveTick<9)g.startMove(N.rand(g)b.phase<3?[2,3-b.phase]:[1,1] + }; + + /* ---------------------------------------------------------------- Guardian Ape (Sunken Valley watering hole) */ + const P={fakeDeath:330,flinchSmall:44,flinchBig:118,flinchRoll:46,poiseReset:1500,poiseSlash:50,poiseThrust:75,headPosture:2, + smallFlinchPosture:6,bigFlinchPosture:4.5,neckBonus:2,turn:.07,turnHeadless:.055,screamDeflectChance:.45}; + const APE_MOVES={ + // Phase 1: the white beast roams on all fours; nearly all its blows can be guarded, the grabs cannot (S14/S15). + slam_combo:{duration:100,hits:[30,44,58,74].map(t=>H(t,{type:'slam',reach:3.4,arc:1.3,hp:13,posture:16,parry:7})),open:[[84,100]]}, + swipe_leap:{duration:110,hits:[H(26,{reach:3.5,arc:1.5,hp:14,posture:17}),H(42,{reach:3.5,arc:1.5,hp:14,posture:17}),H(84,{type:'slam',reach:3.2,arc:3.2,hp:22,posture:26})],open:[[88,110]]}, + swipe_grab:{duration:86,perilous:'grab',hits:[{t:42,type:'grab',reach:3.8,arc:1.7,hp:34,posture:20}],whiff:[[46,86]]}, + belly_flop:{duration:102,perilous:'grab',hits:[{t:58,type:'grab',noJump:true,reach:2.2,arc:3.2,hp:36,posture:24}],whiff:[[62,102]]}, + back_thrash:{duration:118,hits:[26,38,50,62,74].map(t=>H(t,{type:'slam',reach:3.1,arc:3.2,hp:11,posture:14,parry:6})),open:[[98,118]],head:[[14,98]]}, + fart:{duration:52,hits:[],gas:[22],next:'flee_poo'}, + flee_poo:{duration:134,hits:[],poo:[66],open:[[88,134]]}, + roar:{duration:86,hits:[],open:[[26,86]]}, + bound:{duration:58,hits:[]}, + roll_away:{duration:46,hits:[]}, + // Phase 2: the headless apparition, sword in the right hand and its head in the left (S14, S15). + sword4:{duration:114,hits:[28,46,62,82].map((t,i)=>H(t,{reach:4.6,arc:1.6,hp:15,posture:18,parry:12,window:4,ltr:i===1})),open:[[96,114]]}, + diving_lunge:{duration:126,hits:[H(36,{reach:4.1,arc:1.1,hp:22,posture:24,parry:14,window:4})],open:[[46,114]],neck:[[46,114]]}, + jump_sweep:{duration:74,perilous:'sweep',hits:[{t:54,type:'sweep',reach:4.9,arc:1.8,hp:26,posture:28}],next:'overhead_slam'}, + overhead_slam:{duration:82,hits:[H(56,{type:'slam',reach:4.3,arc:.8,hp:28,posture:30,parry:30,window:8,stun:96})],whiff:[[62,82]]}, + scream_long:{duration:226,perilous:'terror',hits:[],scream:{from:62,to:206,radius:8.5,rate:1.3,drain:.11},open:[[206,226]]}, + scream_short:{duration:102,perilous:'terror',hits:[],scream:{from:20,to:72,radius:6.2,rate:1.6,drain:.12},open:[[74,102]]}, + headless_rise:{duration:140,hits:[],invulnerable:true} + }; + APE_MOVES.rising=APE_MOVES.headless_rise; + const APE={moves:APE_MOVES,radius:1.2,height:3.0,kickRange:2.9,kickAnyHeight:true,names:['Valley Giant Ape','Valley Giant Ape'],forms:['ape','headless'], + // [easy, normal, hard] pools, calibrated like Genichiro's. BWIKI base (S16): HP 3520, posture 1140, 60 per s (19 s), poise + // 400 then 520; the risen apparition gets x1.1 HP and posture. + anchors:{hp:[480,2327,10012],posture:[860,1810,3242],recover:19,poise:[220,300,400],poise2:1.3,rise:1.1,pressure:[.4,1,1],rest:[120,34,22],restStun:[20,12,6],dmg:[.6,.85,1],chase:[.85,1,1.12]}, + tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),p2=Math.round(posture*a.rise); + return {bars:[{hp,posture,regen:posture/(a.recover*60),table:'std',poise},{hp:Math.round(hp*a.rise),posture:p2,regen:p2/(a.recover*60),table:'std',poise:Math.round(poise*a.poise2)}],pressure:tier(d,a.pressure), + rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,flinch:0,deadTicks:0,roam:1}), + start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;b.state='idle';b.action='idle';b.cooldown=40;}, + // The beast roams around Sekiro on all fours at a middle distance and answers anyone who closes in (S14); the + // headless apparition walks in to sword range. + idle(g){const b=g.boss,p=g.player,d=dist(b,p),head=b.form_id==='headless',to=A(p.x-b.x,p.z-b.z),ch=g.tune.chase; + g.turn(b,to,head?P.turnHeadless:P.turn); + if(head){if(d>3.4)g.advance(.062*ch,3.2);} + else{if(d>5)g.advance(.1*ch,4.6);else{const out=d<3.8?-.05:0,side=b.roam*.06*ch;g.move(b,Math.sin(to)*out+Math.cos(to)*side,Math.cos(to)*out-Math.sin(to)*side);if(room(g,b.x,b.z)a[Math.floor(N.rand(g)*a.length)]; + // An easier tier screams less often (the long blood scream is its deadliest and longest move). + if(b.form_id==='headless'){const w={scream_long:g.tune.pressure}; + if(d>9)return r<.55?'jump_sweep':'diving_lunge'; + if(d>5)return pickW(g,['diving_lunge','jump_sweep','scream_long','sword4'],w); + return pickW(g,['sword4','sword4','overhead_slam','scream_long','jump_sweep','diving_lunge'],w);} + // The fart is often used when Sekiro is behind it, and is always followed by the flight and the poo throw (S14). + const behind=Math.abs(N.angle(A(p.x-b.x,p.z-b.z)-b.yaw))>1.9; + if(behind&&d<5&&r<.6)return 'fart'; + if(d>9)return r<.6?'bound':'belly_flop'; + if(d>6)return pick(['belly_flop','swipe_leap','roar','bound','flee_poo']); + if(d>3.2)return pick(['slam_combo','swipe_leap','belly_flop','swipe_grab','slam_combo','roar']); + return pick(['slam_combo','swipe_leap','swipe_grab','back_thrash','slam_combo','swipe_grab','fart']);}, + onStart(g,name){const b=g.boss,p=g.player;b.aimX=p.x;b.aimZ=p.z;}, + followUp(g,move){const b=g.boss;if(b.chainNext)return b.chainNext;return APE_MOVES[move].next||null;}, + step(g,move,m,t){const b=g.boss,p=g.player,to=A(p.x-b.x,p.z-b.z),ch=g.tune.chase; + const track=(until,rate=.09)=>{if(t=56&&t<84?Math.sin(Math.PI*(t-56)/28)*2.6:0;if(t>=56&&t<84)g.advanceCommitted(.2,1.6);} + if(move==='swipe_grab'){track(30,.08);} + if(move==='belly_flop'){track(20,.12);b.y=t>=20&&t<58?Math.sin(Math.PI*(t-20)/38)*3.6:0;if(t>=20&&t<58)g.toward(b,b.aimX,b.aimZ,.26,.4);} + if(move==='back_thrash'){track(10,.1);} + if(move==='flee_poo'){if(t<40){g.turn(b,to+Math.PI,.2);g.move(b,-Math.sin(to)*.2,-Math.cos(to)*.2);} + else{track(66,.2);b.y=t>=44&&t<80?Math.sin(Math.PI*(t-44)/36)*4.2:0;}} + if(move==='roar'){if(t<20)g.move(b,-Math.sin(to)*.12,-Math.cos(to)*.12);track(26,.1);} + if(move==='roll_away'){if(t<30){const away=A(b.x-p.x,b.z-p.z);g.move(b,Math.sin(away)*.2,Math.cos(away)*.2);}b.y=t<30?Math.abs(Math.sin(Math.PI*t/15))*.8:0;} + if(move==='bound'){track(14,.15);b.y=t>=14&&t<50?Math.sin(Math.PI*(t-14)/36)*3.2:0;if(t>=14&&t<50)g.toward(b,b.aimX,b.aimZ,.28,3.2);} + if(move==='sword4'){track(76,.05);if(t<84)g.advance(.03*ch,3.0);} + if(move==='diving_lunge'){track(18,.1);if(t>=18&&t<40)g.advanceCommitted(.3,1.3);} + if(move==='jump_sweep'){track(10,.12);b.y=t>=6&&t<54?Math.sin(Math.PI*(t-6)/48)*3.6:0;if(t>=6&&t<50)g.toward(b,b.aimX,b.aimZ,.22,2.6);} + if(move==='overhead_slam'){track(40,.06);} + if(m.scream&&t>=m.scream.from&&tb.moveTick>=w[0]&&b.moveTick0||(b.state==='attack'&&(m?.neck||[]).some(w=>b.moveTick>=w[0]&&b.moveTick0)b.neckExposed--; + // A big flinch that ends unbroken resets the ladder; a recorded small flinch lasts until the poise resets (S16). + if(b.flinch===2&&b.state!=='stunned')b.flinch=0; + if(b.flinch&&g.t-b.poiseAt>P.poiseReset)b.flinch=0; + if(g.t-b.poiseAt>P.poiseReset)b.poise=b.poiseMax; + if(b.state!=='dead')return false; + if(--b.deadTicks<=0){g.nextBar();b.form_id='headless';b.source_phase=2;b.poise=b.poiseMax=g.tune.bars[1].poise;b.flinch=0;g.emit('form:headless');g.startMove('headless_rise');} + return true;}, + // The first deathblow decapitates it and shows SHINOBI EXECUTION, a deception: it rises with a hidden bar (S14). + finish(g){const b=g.boss;if(b.phase===2){g.win();return;} + b.state='dead';b.action='fake_death';b.actionTick=0;b.deadTicks=P.fakeDeath;b.hp=0;b.posture=0;g.hazards=[];g.stats.falseExecutions++;g.emit('false_execution');}, + markers:b=>[1,b.state==='dead'?0:1] + }; + + /* ---------------------------------------------------------------- Lady Butterfly (Hirata Estate) */ + const L={hover:3.8,guardReset:90,spell:720,interrupted:240,respawn:24,cooldown:900,runDispel:150,illusions:4,kick:34,hitFlinch:14, + illusionSpeed:.032,butterflySpeed:.105,butterflyTurn:.05,butterflyLaunch:26,butterflyHoming:110,butterflyLife:260,dartSpeed:.2,dartTurn:.03,dartLaunch:12,dartHoming:24,kunaiSpeed:.42}; + const BUT_MOVES={ + // Phase 1: kunai, threads strung between the pillars and an aerial grab (S17, S19). + kunai_throw:{duration:66,hits:[],kunai:[[24,3],[40,3]],open:[[48,66]]}, + three_strike:{duration:84,hits:[H(16,{reach:2.5,hp:9,posture:12}),H(28,{reach:2.5,hp:9,posture:12}),H(54,{type:'slam',reach:2.3,arc:1.6,hp:14,posture:18})],open:[[58,84]]}, + leg_drop:{duration:80,hits:[H(50,{type:'slam',reach:2.1,arc:3.2,hp:16,posture:20})],open:[[56,80]]}, + kunai_dash:{duration:124,hits:[H(54,{reach:2.4,hp:10,posture:13}),H(80,{reach:2.4,hp:10,posture:13})],kunai:[[14,3],[30,3]],whiff:[[86,124]]}, + sweep:{duration:76,perilous:'sweep',hits:[{t:34,type:'sweep',reach:3.0,arc:1.5,hp:20,posture:22},{t:46,type:'sweep',reach:3.0,arc:1.5,hp:20,posture:22}],open:[[52,76]]}, + thread_up:{duration:46,hits:[],air:true}, + thread_hover:{duration:100,hits:[],air:true,kunai:[[22,3],[50,3],[78,3]]}, + thread_dive:{duration:76,hits:[H(26,{reach:2.4,hp:9,posture:12}),H(34,{reach:2.4,hp:9,posture:12}),H(42,{reach:2.4,hp:10,posture:13})],open:[[56,76]]}, + drop_grab:{duration:84,perilous:'grab',hits:[{t:42,type:'grab',noJump:true,reach:2.3,arc:1.5,hp:30,posture:20}],whiff:[[46,84]]}, + counter2:{duration:44,hits:[H(10,{reach:2.5,hp:8,posture:11}),H(22,{reach:2.5,hp:8,posture:11})]}, + deflect_kick:{duration:40,hits:[{t:12,type:'kick',reach:2.2,hp:6,posture:16,push:1.1}]}, + hop_back:{duration:30,hits:[]}, + // Phase 2: illusions of villagers, spirit butterflies and a flurry that ends in a perilous sweep (S17, S19). + illusion:{duration:64,hits:[],summon:[32],open:[[0,16]]}, + dispel:{duration:56,hits:[],dispel:[30],open:[[34,56]],invulnerableUntil:32}, + flurry:{duration:156,perilous:'sweep',perilousFrom:96,hits:[{t:12,type:'kick',reach:2.2,hp:6,posture:14,push:1.3},...[56,66,76,86,96].map(t=>H(t,{reach:2.5,hp:8,posture:10})),{t:122,type:'sweep',reach:3.0,arc:1.6,hp:22,posture:24}],butterflies:[[26,4]],open:[[128,156]]}, + kunai_butterfly:{duration:84,hits:[],butterflies:[[16,4]],kunai:[[32,3],[40,3],[48,3]],open:[[60,84]]}, + waltz:{duration:104,hits:[],air:true,butterflies:[[22,3],[62,3]],kunai:[[42,3],[80,3]]}, + // "Lose yourself in my illusions": she rises from the first deathblow and opens the illusion phase (S17). + rising:{duration:78,hits:[],summon:[60],open:[[62,78]],invulnerableUntil:62} + }; + const BUTTERFLY={moves:BUT_MOVES,radius:.42,height:1.6,kickRange:2.15,names:['Thread Kunoichi','Thread Kunoichi'],forms:['butterfly','illusionist'], + // [easy, normal, hard] pools, calibrated like Genichiro's. BWIKI base (S18): HP 2073, posture 600, 60 per s (10 s), + // recovery cuts 0/40/70/90 %. + anchors:{hp:[340,1201,3593],posture:[380,675,1040],recover:10,spell:[300,540,720],pressure:[.45,1,1],rest:[44,30,18],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.12]}, + tune(d){const a=this.anchors,posture=Math.round(tier(d,a.posture)),bar={hp:Math.round(tier(d,a.hp)),posture,regen:posture/(a.recover*60),table:'std'}; + return {bars:[bar,{...bar}],spell:Math.round(tier(d,a.spell)),pressure:tier(d,a.pressure),rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({hoverX:0,hoverZ:0,guardAt:-999,counterNext:false,spell:0,dispelDue:false,illusionCooldown:0,spawnTimer:0}), + start(g){const b=g.boss;b.state='idle';b.action='idle';b.cooldown=30;}, + idle(g){const b=g.boss,p=g.player,d=dist(b,p);g.face(b,p);if(b.y>0)b.y=Math.max(0,b.y-.2); + if(d>2.4)g.advance(.07*g.tune.chase,2.3);else if(d<1.6)g.move(b,-Math.sin(b.yaw)*.04,-Math.cos(b.yaw)*.04); + if(b.counterNext){b.counterNext=false;g.startMove('counter2');return;} + if(--b.cooldown<=0)g.startMove(this.choose(g));}, + // An easier tier spends less time on the threads and in the flurry. + choose(g){const b=g.boss,p=g.player,d=dist(b,p),w={thread_up:g.tune.pressure,flurry:g.tune.pressure},pick=a=>pickW(g,a,w); + if(b.form_id==='illusionist'){ + // Kept running, or left alone long enough, she turns the illusions into homing butterflies (S17, S18). + if(b.dispelDue||(b.spell>0&&p.runTicks>=L.runDispel))return 'dispel'; + if(b.spell<=0&&b.illusionCooldown<=0&&!g.minions.some(q=>q.alive))return 'illusion'; + if(d>6)return pick(['kunai_butterfly','thread_up','kunai_dash','leg_drop']); + return pick(['flurry','three_strike','sweep','kunai_butterfly','thread_up','flurry']);} + if(d>6)return pick(['kunai_throw','kunai_dash','thread_up','leg_drop']); + if(d>3)return pick(['kunai_dash','leg_drop','thread_up','sweep','three_strike']); + return pick(['three_strike','sweep','three_strike','kunai_throw','thread_up','leg_drop']);}, + onStart(g,name){const b=g.boss,p=g.player;b.aimX=p.x;b.aimZ=p.z; + if(name==='thread_up'){// a hover point on the threads, away from the pillars, about five units from Sekiro + const a=A(b.x-p.x,b.z-p.z)+(N.rand(g)-.5)*1.2,ar=g.arena;b.hoverX=N.clamp(p.x+Math.sin(a)*5,-ar.halfWidth+2,ar.halfWidth-2);b.hoverZ=N.clamp(p.z+Math.cos(a)*5,-ar.halfDepth+2,ar.halfDepth-2);}}, + followUp(g,move){const b=g.boss; + if(move==='thread_up')return b.form_id==='illusionist'?'waltz':'thread_hover'; + if(move==='thread_hover'||move==='waltz')return N.rand(g)<.6?'thread_dive':'drop_grab'; + return null;}, + step(g,move,m,t){const b=g.boss,p=g.player,ch=g.tune.chase; + const track=until=>{if(t=34&&t<52?Math.sin(Math.PI*(t-34)/18)*1.6:0;} + if(move==='leg_drop'){track(30);b.y=t>=8&&t<50?Math.sin(Math.PI*(t-8)/84)*3.0*(t<29?1:1):0;if(t>=29)b.y=Math.max(0,3.0*(50-t)/21);if(t>=8&&t<50)g.toward(b,b.aimX,b.aimZ,.12,.3);} + if(move==='kunai_dash'){track(40);if((t>=40&&t<52)||(t>=66&&t<78))g.advanceCommitted(.3,1.2);if(t===60){b.aim=A(p.x-b.x,p.z-b.z);b.yaw=b.aim;b.commitDistance=dist(b,p);}} + if(move==='sweep'){track(20);if(t<26)g.advance(.04*ch,1.8);} + if(move==='thread_up'){g.face(b,p);b.y=Math.min(L.hover,L.hover*Math.sin(Math.PI/2*N.clamp((t-6)/30,0,1)));g.toward(b,b.hoverX,b.hoverZ,.16,0);} + if(move==='thread_hover'||move==='waltz'){g.face(b,p);b.y=L.hover;} + if(move==='thread_dive'){track(10);b.y=t<24?L.hover*(1-t/24):0;if(t<26)g.toward(b,b.aimX,b.aimZ,.24,1.2);} + // she tracks Sekiro until she drops (S19: a side step is caught, a retreat straight back as she falls is not) + if(move==='drop_grab'){track(34);b.y=t<26?L.hover:t<40?L.hover*(40-t)/14:0;if(t>=26&&t<42)g.toward(b,b.aimX,b.aimZ,.3,.9);} + if(move==='counter2'){track(16);if(t<20)g.advance(.05,1.6);} + if(move==='deflect_kick'){track(8);} + if(move==='hop_back'){track(4);if(t<20)g.move(b,-Math.sin(b.yaw)*.13,-Math.cos(b.yaw)*.13);b.y=Math.sin(Math.PI*N.clamp(t/20,0,1))*.7;} + if(move==='illusion'||move==='dispel'){g.face(b,p);} + if(move==='rising'){g.face(b,p);b.y=t<52?Math.sin(Math.PI*t/52)*2.4:0;if(t<52)g.toward(b,b.aimX,b.aimZ,.12,0);} + if(move==='flurry'){track(50);if(t>=40&&t<100)g.advance(.06*ch,1.6);} + if(move==='kunai_butterfly'){track(48);} + }, + afterHits(g,move,m,t){const b=g.boss; + for(const [at,n] of m.kunai||[])if(t===at)g.kunai(n); + for(const [at,n] of m.butterflies||[])if(t===at)for(let i=0;i1.2)return; + if(open){if(b.action==='illusion'&&b.state==='attack'){b.illusionCooldown=L.interrupted;g.emit('spell_interrupted');} + g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);if(!b.deathblowAvailable){g.interruptBoss(L.hitFlinch);b.counterNext=true;}g.fx('cut',b);return;} + if(g.t-b.guardAt>L.guardReset)b.guardCount=0;b.guardAt=g.t;b.guardCount++; + if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+6);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect'); + if(b.state!=='attack'||b.moveTick<8)g.startMove(N.rand(g)<.5?'deflect_kick':'hop_back');} + else{g.stats.bossBlocks++;g.fx('boss_block',b);g.emit('boss_block');g.bossPosture((kind==='thrust'?C.thrustBlockPosture:C.blockPosture)*C.postureUnit);}}, + onDeflect(){}, + special(g){const b=g.boss;if(b.illusionCooldown>0)b.illusionCooldown--; + if(b.spell>0){if(--b.spell===0)b.dispelDue=true;if(g.minions.filter(q=>q.alive).length[1,1] + }; + /* ---------------------------------------------------------------- Isshin, the Sword Saint (silvergrass field) */ + // Way of Tomoe Genichiro (one bar, no Lightning of Tomoe, S29), then Isshin: sword, spear and matchlock, then lightning (S27, S28). + const I={tomoeHP:2556/2240,tomoePosture:750/660,tomoeRecover:25,spearHP:1.27,waveSpeed:.42,bulletSpeed:.6,waveLeak:.35,stompPush:2.2,stompReach:5.5, + mortalChance:.16,passageThrust:.8,lightningChance:.2,lightningDue:420,lightningDueChance:.55,counterThrust:.5,ichimonjiWave:.75,leapThrust:.6,retreatChop:.5,quadThrust:.7}; + const ISSHIN_MOVES={ + // Genichiro's own table (his third phase minus the lightning, S29) plus the black Mortal Blade: run or step through it (S27, S30). + ...Object.fromEntries(['double','passage','swipe5','jump_slam','tomoe_slash','leap_thrust','dive_ready','running_grab','sweep','thrust','kick_arrow','bow_roll','volley','quick_bow','counter','lightning_slash','lightning_sweep'].map(n=>[n,GEN_MOVES[n]])), + mortal_blade:{duration:132,track:50,hits:[{t:62,type:'mortal',reach:7.2,arc:1.5,hp:32,posture:30},{t:96,type:'mortal',reach:7.2,arc:1.5,hp:32,posture:30}],rings:[62,96],open:[[66,90],[108,132]]}, + isshin_emerge:{duration:96,hits:[],invulnerable:true,cinematic:true,next:'cross'}, + // Sword: Ashina Cross, its close-range cancel into a perilous sweep, Ichimonji (a deflect chains the vertical wave), Dragon Flash, the spiral (S27, S28, S30). + cross:{duration:70,hits:[H(36,{reach:3.4,hp:16,posture:18,parry:12}),H(44,{reach:3.4,hp:16,posture:18,parry:12})],adv:[[20,36,.22,1.6]],open:[[56,70]]}, + smack_sweep:{duration:78,perilous:'sweep',perilousFrom:22,hits:[H(14,{reach:2.8,hp:10,posture:14}),{t:46,type:'sweep',reach:4,arc:2,hp:24,posture:26}],open:[[56,78]]}, + ichimonji:{duration:58,hits:[H(26,{type:'slam',reach:3,arc:.9,hp:20,posture:26,parry:15})],open:[[44,58]]}, + dragon_flash:{duration:82,hits:[],waves:[[40,'v'],[54,'v']],open:[[0,24],[64,82]]}, + wind_v:{duration:56,hits:[],waves:[[24,'v']],open:[[34,56]]}, + spiral:{duration:80,hits:[H(40,{ring:true,reach:6.4,arc:3.2,hp:18,posture:22})],rings:[40],open:[[52,80]]}, + combo:{duration:108,hits:[24,42,58,84].map(t=>H(t,{reach:3,hp:12,posture:14,parry:9})),adv:[[0,80,.03,1.7,true]],open:[[96,108]]}, + overhead:{duration:64,hits:[H(30,{type:'slam',reach:3,arc:.9,hp:18,posture:24}),H(46,{reach:2.8})],open:[[54,64]]}, + pose_thrust:{duration:74,perilous:'thrust',track:30,hits:[{t:44,type:'thrust',reach:3.8,hp:26,posture:28}],adv:[[36,44,.2,1.15]],open:[[56,74]]}, + dash_slash:{duration:60,hits:[H(30,{reach:3.2,hp:18,posture:20})],adv:[[10,30,.34,1.6]],open:[[44,60]]}, + // Spear and matchlock: the stomp, Double Projected Force, the leap, the retreating sweep, four shots (the last delayed) into a perilous (S27, S30). + stomp:{duration:82,hits:[H(62,{reach:3.4,arc:3.2,hp:12,posture:14})],stomp:[30],open:[[72,82]]}, + double_disc:{duration:74,hits:[],waves:[[26,'h'],[44,'h']],open:[[54,74]]}, + leap_slam:{duration:66,hits:[H(42,{type:'slam',reach:3.1,hp:22,posture:26})],leap:[14,42,2.4],adv:[[14,42,.2,1.7,true]],whiff:[[46,66]]}, + retreat_sweep:{duration:62,hits:[H(30,{reach:5,arc:1.8,hp:18,posture:20,window:-4})],back:[0,14,.16],open:[[44,62]]}, + quad_shot:{duration:116,track:96,hits:[],gun:[26,40,54,92],back:[0,14,.2],open:[[100,116]]}, + quick_gun:{duration:36,hits:[],gun:[12],open:[[20,36]]}, + spear_thrust:{duration:66,perilous:'thrust',track:24,hits:[{t:36,type:'thrust',reach:4.7,hp:26,posture:28}],adv:[[22,36,.24,1.4]],open:[[48,66]]}, + spear_sweep:{duration:70,perilous:'sweep',hits:[{t:36,type:'sweep',reach:5,arc:2,hp:26,posture:28}],open:[[46,70]]}, + spear_spiral:{duration:90,hits:[H(46,{ring:true,reach:8.5,arc:3.2,hp:20,posture:22})],rings:[46],open:[[58,90]]}, + three_thrust:{duration:92,hits:[22,40,56,74].map(t=>H(t,{reach:3.6,hp:12,posture:14,parry:9})),adv:[[0,70,.03,2,true]],next:'spear_thrust'}, + heavy_chops:{duration:96,hits:[30,60].map(t=>H(t,{type:'slam',reach:3.6,arc:.9,hp:20,posture:30,parry:14})),adv:[[0,40,.03,2,true]],open:[[80,96]]}, + // Lightning: Tomoe's bolt and the double slanted flash join the spear arsenal (S27, S28, S30); the reversal stuns him. + double_flash:{duration:76,hits:[],waves:[[30,'h'],[44,'h']],open:[[54,76]]}, + thunder_chop:{duration:72,hits:[H(42,{type:'slam',reach:3.6,arc:.9,hp:24,posture:30,parry:20,window:-4})],adv:[[0,30,.04,2,true]],open:[[58,72]]} + }; + const ISSHIN={moves:ISSHIN_MOVES,radius:.5,height:1.95,kickRange:2.15,names:['Lightning Swordsman','Old Sword-and-Spear Master','Old Sword-and-Spear Master','Old Sword-and-Spear Master'],forms:['tomoe','isshin_sword','isshin_spear','isshin_lightning'], + // [easy, normal, hard] pools for Isshin's sword bar. BWIKI base (S28, S29): Genichiro 2556 / 750 / 30 per s (25 s), Isshin 2240 / 660 / 60 per s + // (11 s); his spear and lightning bars carry HP x1.27 each. The page leaves stacking open: read as not stacked (engineering choice). + anchors:{hp:[148,700,2500],posture:[330,800,1560],recover:11,rest:[70,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]}, + tune(d){const a=this.anchors,hp=tier(d,a.hp),posture=tier(d,a.posture),bar=(h,x,s,table)=>{const px=Math.round(x);return {hp:Math.round(h),posture:px,regen:px/(s*60),table};}; + return {bars:[bar(hp*I.tomoeHP,posture*I.tomoePosture,I.tomoeRecover,'std'),bar(hp,posture,a.recover,'gen12'),bar(hp*I.spearHP,posture,a.recover,'gen12'),bar(hp*I.spearHP,posture,a.recover,'gen12')], + rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({lightning:false,lastLightningAt:-999,extraShot:0}), + start(g){g.startMove('mortal_blade');}, + idle(g){const b=g.boss,p=g.player;g.face(b,p);if(dist(b,p)>2.25)g.advance(.058*g.tune.chase,2.2); + if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));}, + choose(g){const b=g.boss,p=g.player,d=dist(b,p),r=N.rand(g),phase=b.phase,pick=a=>a[Math.floor(N.rand(g)*a.length)]; + // Items and distance both draw the dash or the leap (S27); Genichiro answers healing with his sword dive (S01). + if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return phase===1?'dive_ready':phase===2?'dash_slash':'leap_slam';} + if(phase===1){if(N.rand(g)5)return r<.6?'leap_thrust':'volley'; + return pick(['double','passage','swipe5','jump_slam','leap_thrust','running_grab','sweep','thrust','kick_arrow','bow_roll']);} + if(phase===4&&N.rand(g)<(g.t-b.lastLightningAt>I.lightningDue?I.lightningDueChance:I.lightningChance))return N.rand(g)<.5?'lightning_slash':'lightning_sweep'; + if(phase===2){if(d>6)return pick(['dash_slash','dragon_flash','wind_v','cross']); + if(d<2.6&&r<.3)return 'smack_sweep'; + return pick(['cross','ichimonji','dragon_flash','spiral','combo','overhead','pose_thrust','smack_sweep','dash_slash']);} + if(d>7)return pick(phase===4?['quad_shot','double_flash','leap_slam','spear_spiral']:['quad_shot','double_disc','leap_slam','spear_spiral']); + const list=['double_disc','leap_slam','quad_shot','spear_thrust','spear_sweep','spear_spiral','three_thrust','heavy_chops','wind_v']; + return pick(phase===4?[...list,'double_flash','thunder_chop']:list);}, + onStart(g,name){GENICHIRO.onStart(g,name);}, + followUp(g,move){const b=g.boss; + if(b.chainNext==='thrust_followup')return dist(b,g.player)>G.thrustFollowRange?'quick_bow':'running_grab'; + if(b.chainNext)return b.chainNext; + const next=ISSHIN_MOVES[move].next;if(next)return next; + if(move==='jump_slam')return 'tomoe_slash'; + if(move==='tomoe_slash')return 'thrust'; + if(move==='passage'&&N.rand(g)=from&&t=m.back[0]&&t=m.leap[0]&&t4.5){g.stats.passageCancels++;g.emit('passage_cancel');g.startMove('quick_bow');} + return;} + for(const [at,kind] of m.waves||[])if(t===at)g.airWave(kind); + for(const at of m.gun||[])if(t===at)g.bullet(); + for(const at of m.rings||[])if(t===at){const reach=m.hits.find(h=>h.t===at)?.reach||6;g.hazards.push({type:move==='mortal_blade'?'mortal_arc':'ring',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:reach,age:0,life:18});g.emit(move==='mortal_blade'?'mortal_blade':'ring');}}, + // Genichiro: as on the castle top. Isshin's middle stance turns the third cut: two guards, then a plain counter or a pose and a perilous thrust (S28, S30). + playerHit(g,kind,open){const b=g.boss,p=g.player,busy=b.state==='attack'; + if(b.phase===1){GENICHIRO.playerHit(g,kind,open);return;} + // Engineering choice, extrapolated from S28's general note on hyper armor: a cut lands on the gathering bolt but does not stop the leap, so the reversal stays the answer (S27, S30). + if(open){const armored=busy&&b.lightning&&b.moveTick<100;g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);if(!armored)g.interruptBoss(C.hitStun);g.fx('cut',b);return;} + b.guardCount++; + if(b.guardCount>=3){b.guardCount=0;g.stats.bossDeflects++;p.posture=Math.min(p.maxPosture,p.posture+4);p.postureDelay=C.playerPostureDelay;g.fx('boss_deflect',b);g.emit('boss_deflect'); + // Repeated cuts against the spear draw the retreating sweep (S27). + if(!busy||b.moveTick<9)g.startMove(b.phase>=3?(N.rand(g)b.phase===1?[1,1]:[3,5-b.phase] + }; + /* ---------------------------------------------------------------- Gyoubu Masataka Oniwa (Ashina Castle Gate) */ + // The only mounted boss: no guard, hyper armor until his poise breaks, the horse carries him past and away (S31, S32). There is no + // grappling hook here: after riding off he always wheels and charges back, and his rope spear punishes standing far away. + const O={poiseSlash:50,poiseThrust:75,poiseReset:1500,flinch:44,sharp:.6,upper:3,lower:.7,upperFrom:.6,walk:.09,turn:.05,turnRide:.2,rideOffNext:.6,tripleSweep:.6,flickRide:.7,comboRide:.35,rearAngle:2.4,sideAngle:.6}; + const GYOUBU_MOVES={ + // He talks first and can be cut during it (S31). + intro:{duration:150,hits:[],open:[[0,150]],next:'charge_sweep'}, + // On foot-pace: three cuts, the third staggers him when deflected (S31); the flick from his right flank usually rides off (S31, S32). + combo3:{duration:112,track:20,hits:[H(28,{reach:3.8,arc:1.5,hp:14,posture:16,parry:10}),H(46,{reach:3.8,arc:1.5,hp:12,posture:20}),H(84,{type:'slam',reach:4,arc:1.3,hp:18,posture:22,parry:22,stun:54})],open:[[96,112]]}, + flick:{duration:52,track:10,hits:[H(20,{reach:3.4,arc:1.6,hp:12,posture:16})],open:[[34,52]]}, + thrust_near:{duration:70,perilous:'thrust',track:28,hits:[{t:40,type:'thrust',reach:4.6,hp:24,posture:26}],open:[[52,70]]}, + horse_kick:{duration:54,track:0,hits:[{t:22,type:'kick',rear:true,reach:3.2,arc:1.2,hp:16,posture:18,stagger:20}],open:[[34,54]]}, + // Charges ride through: speed is set when the horse commits so it arrives at the contact tick, then carries on past (S31). + charge_sweep:{duration:96,perilous:'sweep',track:20,ride:[20,76,.3],arrive:52,hits:[{t:52,type:'sweep',reach:4.4,arc:2.2,hp:24,posture:26}],next:'wheel'}, + figure8:{duration:100,track:18,ride:[18,80,.28],arrive:50,hits:[42,50,58].map(t=>H(t,{reach:4,arc:1.8,hp:11,posture:14,parry:8,window:-3})),next:'wheel'}, + triple_charge:{duration:96,track:18,ride:[18,76,.28],arrive:54,hits:[44,54,64].map(t=>H(t,{reach:4,arc:1.8,hp:12,posture:22,parry:9}))}, + late_charge:{duration:92,track:18,ride:[18,72,.28],arrive:46,hits:[H(58,{reach:4.2,arc:3.2,hp:14,posture:18,parry:12})],next:'wheel'}, + // The horse turns round after a pass: this is the opening that closing in with the hook gives in the original. + wheel:{duration:64,track:64,trot:[18,64,.06],hits:[],open:[[0,64]]}, + turn_about:{duration:26,track:26,hits:[]}, + ride_off:{duration:50,track:0,away:[0,44,.3],hits:[]}, + gallop:{duration:40,track:40,chaseAt:.32,chaseTo:9,hits:[]}, + jump_attack:{duration:96,track:12,leap:[12,50,3.2],hits:[H(50,{type:'slam',reach:3.6,arc:1.6,hp:18,posture:22,parry:24}),H(68,{type:'slam',reach:3.6,arc:1.6,hp:18,posture:22,parry:24})],open:[[82,96]]}, + // The spearhead on its rope: three wide circles that can be guarded or deflected, and a line that can only be deflected (S31, S34). + rope_sweep:{duration:122,track:100,hits:[40,68,96].map(t=>H(t,{reach:9.5,arc:3.2,hp:12,posture:16,parry:11})),rings:[40,68,96],open:[[106,122]]}, + rope_thrust:{duration:78,perilous:'thrust',track:36,hits:[{t:44,type:'rope',noBlock:true,reach:12,arc:.3,hp:22,posture:24,parry:18}],line:[44],open:[[56,78]]}, + rising:{duration:1,hits:[]} + }; + const GYOUBU={moves:GYOUBU_MOVES,radius:1,height:2.9,kickRange:2.6,kickAnyHeight:true,names:['Mounted Spear General','Mounted Spear General'],forms:['gyoubu','gyoubu'], + // [easy, normal, hard] pools, calibrated to the windows. BWIKI base (S32): HP 2552, posture 660, 30 per s (22 s), total poise 360, reset 25 s. No source gives a difference between his two bars. + anchors:{hp:[650,1800,6500],posture:[1200,2000,2400],recover:22,poise:[220,300,360],rest:[90,32,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.15]}, + tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),bar={hp,posture,regen:posture/(a.recover*60),table:'std',poise}; + return {bars:[bar,{...bar}],rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,rideX:0,rideZ:0}), + start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;g.startMove('intro');}, + idle(g){const b=g.boss,p=g.player;g.turn(b,A(p.x-b.x,p.z-b.z),O.turn);if(dist(b,p)>3.4)g.advance(O.walk*g.tune.chase,3.2); + if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));}, + // Right flank: the spear hand; left flank: he prefers to turn; directly behind: the hind legs (S32). + choose(g){const b=g.boss,p=g.player,d=dist(b,p),rel=N.angle(A(p.x-b.x,p.z-b.z)-b.yaw),pick=a=>a[Math.floor(N.rand(g)*a.length)]; + if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return d>6?'rope_thrust':'triple_charge';} + if(d>9)return pick(['rope_sweep','rope_thrust','gallop']); + if(d>5)return pick(['triple_charge','figure8','late_charge','jump_attack','rope_sweep','rope_thrust','charge_sweep']); + if(Math.abs(rel)>O.rearAngle)return 'horse_kick'; + if(rel>O.sideAngle)return 'turn_about'; + return pick(rel<-O.sideAngle?['combo3','flick','thrust_near','flick','ride_off']:['combo3','thrust_near','jump_attack','ride_off','ride_off']);}, + onStart(g,name){g.boss.lightning=false;}, + followUp(g,move){const b=g.boss;if(b.chainNext)return b.chainNext;const next=GYOUBU_MOVES[move].next;if(next)return next; + if(move==='triple_charge')return N.rand(g){const r=N.rand(g);return r<.4?'charge_sweep':r<.7?'triple_charge':r<.85?'figure8':'late_charge';}; + if(move==='ride_off'){if(N.rand(g)>=O.rideOffNext)return N.rand(g)<.5?'rope_sweep':'rope_thrust';return dist(b,g.player)>12?'gallop':charge();} + if(move==='gallop')return dist(b,g.player)>12?'gallop':charge(); + if(move==='turn_about'){const r=N.rand(g);return r<.4?'combo3':r<.7?'thrust_near':'flick';} + if(move==='combo3'&&N.rand(g)=from&&t=from)g.turn(b,b.aim,O.turnRide);} + if(m.away&&t>=m.away[0]&&t=m.trot[0]&&t=a&&t=a&&t=32&&t<40)g.advanceCommitted(.2,2);}, + afterHits(g,move,m,t){const b=g.boss; + for(const at of m.rings||[])if(t===at){g.hazards.push({type:'ring',x:b.x,y:.3,z:b.z,yaw:b.yaw,radius:9.5,age:0,life:18});g.emit('rope_sweep');} + for(const at of m.line||[])if(t===at){g.hazards.push({type:'rope_line',x:b.x,y:1.9,z:b.z,yaw:b.aim,radius:12,age:0,life:12});g.emit('rope_thrust');}}, + // He cannot guard and hyper armor carries his attacks through; only a broken poise staggers him (S32). Cuts above the waist + // take x3 posture, the horse and his legs x0.7, and the blade takes x0.6 vitality (S32). + playerHit(g,kind){const b=g.boss,p=g.player,part=p.y>O.upperFrom?O.upper:O.lower; + g.damageBoss((kind==='thrust'?C.thrustDamage:C.slashDamage)*O.sharp,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit*part);g.fx('cut',b);if(b.deathblowAvailable||b.hp<=0)return; + if(b.action==='intro'&&b.state==='attack'){g.emit('intro_interrupted');g.startMove('charge_sweep');return;} + b.poise-=kind==='thrust'?O.poiseThrust:O.poiseSlash;b.poiseAt=g.t; + if(b.poise<=0){b.poise=b.poiseMax;g.stats.flinches++;g.stagger('stagger',O.flinch);g.emit('flinch_small');}}, + onDeflect(g,hit){const b=g.boss;if(hit.stun&&b.state==='attack'){g.stagger('stagger',hit.stun);g.emit('combo_staggered');}}, + special(g){const b=g.boss;if(g.t-b.poiseAt>O.poiseReset)b.poise=b.poiseMax;return false;}, + finish(g){const b=g.boss;if(b.phase===2){g.win();return;} + g.nextBar();b.poise=b.poiseMax=g.tune.bars[1].poise;b.source_phase=2;b.state='stunned';b.stun=G.riseOpen;b.action='rising';b.actionTick=0;}, + markers:b=>[2,3-b.phase] + }; + /* ---------------------------------------------------------------- Demon of Hatred (Ashina Castle Gate, in flames) */ + // Three bars, no guard, hyper armor until its poise breaks; most blows miss the space under its belly (S37, S39). Fire arms cannot be + // deflected and guarding them still builds Burn, which drains vitality and stops posture recovery (S38, S39). Timings are calibration values. + const D={poiseSlash:50,poiseThrust:75,poiseReset:1500,flinch:40,turn:.045,walk:.06,belly:2.05,rise3:80, + burnDecay:.15,burnTicks:300,burnDrain:.05,fireLeak:.3,fireRate:1.4,ringRadius:7.5,ringWidth:.55,ringLife:480,ringBurn:30,ringPush:1.4, + lobFlight:52,lobGravity:.012,lobBlast:1.5,homingSpeed:.2,homingTurn:.075,homingClimb:.07,homingFor:66,homingFall:.006,shotSpeed:.34,waveSpeed:.36, + doubleCharge:.75,fireSweep:.5,secondVolley:.35,headbutt2:.3,chargeRanged:.55,burstRadius:5,burstPush:2.5}; + const FIRE=o=>H(o.t,Object.assign({noDeflect:true,burn:24,leak:D.fireLeak,reach:4.3,arc:1.5,inner:D.belly,hp:15,posture:14},o)); + const DEMON_MOVES={ + arm_swing:{duration:72,track:24,hits:[H(32,{reach:4.3,arc:1.5,inner:D.belly,hp:14,posture:16,parry:12})],open:[[52,72]]}, + // Right foot held up about a second (S36); both feet on his left (S36), weaker than the single stomp (S39). + stomp:{duration:84,track:30,hits:[H(50,{type:'slam',reach:3.2,arc:2.2,hp:18,posture:20,parry:16})],open:[[64,84]]}, + double_stomp:{duration:100,track:24,hits:[40,66].map(t=>H(t,{type:'slam',reach:3.2,arc:2.4,hp:13,posture:15,parry:12})),open:[[80,100]]}, + headbutt:{duration:76,track:30,hits:[H(42,{type:'slam',reach:4.6,arc:.75,inner:D.belly,hp:20,posture:22,parry:16})],open:[[56,76]]}, + // Fire arm twice, a stomp, the fire arm again (S39). + fire_combo:{duration:154,track:20,hits:[FIRE({t:30}),FIRE({t:52}),H(90,{type:'slam',reach:3.2,arc:2.2,hp:15,posture:17,parry:13}),FIRE({t:124,hp:17})],open:[[138,154]]}, + fire_throw:{duration:92,track:30,shots:[34,58],hits:[],open:[[70,92]]}, + // Fireballs lobbed with each wave of the hands, the last with the last wave (S36). + fireballs:{duration:124,track:96,lobs:[40,52,64,76,98],hits:[],open:[[0,30],[104,124]]}, + whip_slam:{duration:104,track:40,hits:[FIRE({t:58,type:'slam',reach:12.5,arc:.15,inner:0,hp:18,posture:18,burn:30})],trail:58,open:[[70,104]]}, + // Unblockable: run, or be in the air as it lands; about a second open after landing, in place of the grappling hook (S36, S39). + blast_leap:{duration:154,track:50,leap:[50,82,3.6],hits:[{t:82,type:'blast',reach:6,arc:Math.PI,hp:28,posture:30,burn:45,push:2.4}],open:[[96,154]]}, + charge:{duration:88,perilous:'sweep',track:30,ride:[30,78,.3],arrive:54,hits:[{t:54,type:'sweep',reach:3.6,arc:1.4,hp:24,posture:24}]}, + charge_back:{duration:76,perilous:'sweep',track:18,ride:[18,66,.3],arrive:42,hits:[{t:42,type:'sweep',reach:3.6,arc:1.4,hp:24,posture:24}]}, + fire_sweep:{duration:74,perilous:'sweep',track:26,hits:[{t:38,type:'sweep',reach:4.4,arc:1.7,hp:18,posture:20,burn:30}],open:[[52,74]]}, + kick_wave:{duration:92,track:36,waves:[46],hits:[],open:[[60,92]]}, + // Homing fireballs; the stomp and pose at the end is the opening (S36). + homing:{duration:164,track:90,homing:[34,44,54,64,74,84],hits:[],open:[[124,164]]}, + // Phase 3 opens with the fire ring, then three whip swings: jump the low one, stay down under the high one, get behind the last (S36, S39). + fire_ring:{duration:196,perilous:'sweep',track:150,ringAt:40,hits:[FIRE({t:84,type:'sweep',reach:6,arc:Math.PI,inner:0,burn:26,hp:16,posture:18}),FIRE({t:128,onlyAir:true,reach:6,arc:Math.PI,inner:0,burn:26,hp:16,posture:18}),FIRE({t:166,type:'slam',reach:5.5,arc:1.0,inner:0,burn:26,hp:18,posture:20})],open:[[178,196]]}, + turn_about:{duration:30,track:30,hits:[]}, + // After the first deathblow: crouched and immune, a small blast that pushes without damage, then a leap back (S36). + crouch:{duration:150,invulnerable:true,hits:[],burst:140,next:'leap_back'}, + leap_back:{duration:56,track:0,back:[24,48,.18],hits:[],open:[[0,26]]}, + rising:{duration:1,hits:[]} + }; + const DEMON={moves:DEMON_MOVES,radius:1.1,height:4.4,kickRange:3.0,kickAnyHeight:true,names:['Flame Behemoth','Flame Behemoth','Flame Behemoth'],forms:['demon','demon','demon'], + // [easy, normal, hard] per-bar pools, calibrated to the windows. BWIKI base (S37): HP 3195, posture 1050, 30 per s (35 s), poise 640, reset 25 s. + // No source gives a per-bar difference, so the three bars are equal. + anchors:{hp:[600,1600,4200],posture:[1200,2000,3200],recover:35,poise:[400,520,640],rest:[80,34,20],restStun:[18,11,6],dmg:[.6,.85,1],chase:[.85,1,1.1]}, + tune(d){const a=this.anchors,hp=Math.round(tier(d,a.hp)),posture=Math.round(tier(d,a.posture)),poise=Math.round(tier(d,a.poise)),bar={hp,posture,regen:posture/(a.recover*60),table:'std',poise}; + return {bars:[bar,{...bar},{...bar}],rest:Math.round(tier(d,a.rest)),restStun:Math.round(tier(d,a.restStun)),dmg:tier(d,a.dmg),chase:tier(d,a.chase)};}, + extra:()=>({poise:0,poiseMax:0,poiseAt:-9999,rideX:0,rideZ:0,leapSpeed:0,ringDue:false,waveDue:false,repeat:0,lastMove:''}), + playerExtra:()=>({burn:0,burning:0,burnFed:false}),statsExtra:()=>({burns:0}), + start(g){const b=g.boss;b.poise=b.poiseMax=g.tune.bars[0].poise;b.state='idle';b.action='idle';b.cooldown=40;}, + idle(g){const b=g.boss,p=g.player;g.turn(b,A(p.x-b.x,p.z-b.z),D.turn);if(dist(b,p)>3.6)g.advance(D.walk*g.tune.chase,3.4); + if(p.healTick>0||--b.cooldown<=0)g.startMove(this.choose(g));}, + // Negative relative angle = his right flank (same sign as Gyoubu's). + choose(g){const b=g.boss,p=g.player,d=dist(b,p),rel=N.angle(A(p.x-b.x,p.z-b.z)-b.yaw),ph=b.phase,pick=a=>a[Math.floor(N.rand(g)*a.length)]; + if(b.ringDue)return 'fire_ring'; + if(b.waveDue){b.waveDue=false;if(d>6)return 'kick_wave';} + if(p.healTick>0){g.stats.healPunishes++;g.emit('heal_punish');return d>6?'fireballs':'charge';} + if(d>9)return pick(ph>=2?['fireballs','whip_slam','charge','kick_wave','homing']:['fireballs','whip_slam','charge']); + if(d>5)return pick(ph>=2?['fire_throw','charge','whip_slam','blast_leap','homing','kick_wave']:['fire_throw','charge','whip_slam','blast_leap']); + if(Math.abs(rel)>2.3)return N.rand(g)<.5?'turn_about':'blast_leap'; + if(d.6)return pick(['double_stomp','arm_swing','fire_combo']); + return pick(['headbutt','arm_swing','fire_combo','charge']);}, + onStart(g,name){const b=g.boss;b.lightning=false;b.repeat=name===b.lastMove?b.repeat+1:1;b.lastMove=name;}, + followUp(g,move){const b=g.boss,d=dist(b,g.player),next=DEMON_MOVES[move].next,pick=a=>a[Math.floor(N.rand(g)*a.length)];if(next)return next; + if(move==='charge'&&b.phase===3&&N.rand(g)=2?['fireballs','whip_slam','fire_throw','homing','kick_wave']:['fireballs','whip_slam','fire_throw']);return null;} + if(move==='fireballs'&&b.repeat<2&&d>6&&N.rand(g)=from&&t=a&&t=a&&t=m.back[0]&&t=2; + for(let r=2.5;r<=12.5;r+=2)for(const s of wide?[-1.6,0,1.6]:[0])g.hazards.push({type:'fire',x:b.x+Math.sin(a)*r+Math.cos(a)*s,y:0,z:b.z+Math.cos(a)*r-Math.sin(a)*s,radius:1,age:0,life:150,rate:D.fireRate});g.emit('fire_trail');}, + playerHit(g,kind){const b=g.boss; + g.damageBoss(kind==='thrust'?C.thrustDamage:C.slashDamage,(kind==='thrust'?C.thrustPosture:C.slashPosture)*C.postureUnit);g.fx('cut',b);if(b.deathblowAvailable||b.hp<=0)return; + b.poise-=kind==='thrust'?D.poiseThrust:D.poiseSlash;b.poiseAt=g.t; + if(b.poise<=0){b.poise=b.poiseMax;g.stats.flinches++;g.stagger('stagger',D.flinch);g.emit('flinch_small');}}, + onDeflect(){}, + special(g){const b=g.boss;if(g.t-b.poiseAt>D.poiseReset)b.poise=b.poiseMax;return false;}, + finish(g){const b=g.boss;if(b.phase===3){g.win();return;} + g.nextBar();b.poise=b.poiseMax=g.tune.bars[b.phase-1].poise;b.source_phase=b.phase; + if(b.phase===2){b.waveDue=true;g.startMove('crouch');} + else{b.ringDue=true;b.state='stunned';b.stun=D.rise3;b.action='rising';b.actionTick=0;}}, + markers:b=>[3,4-b.phase] + }; + const KINDS={genichiro:GENICHIRO,ape:APE,butterfly:BUTTERFLY,isshin:ISSHIN,gyoubu:GYOUBU,demon:DEMON}; + const CASES={ + 'sekiro/genichiro':{kind:'genichiro',name:'Bow-and-Blade Swordsman · Castle rooftop (three deathblows)',arena:{shape:'rect',halfWidth:8,halfDepth:6,pillars:[]},player:[0,4.2],boss:[0,-3.6]}, + 'sekiro/guardian_ape':{kind:'ape',name:'Guardian Ape · Valley pool (feigned death and second phase)',arena:{shape:'circle',radius:14.5,pillars:[]},player:[0,6.5],boss:[0,-5]}, + 'sekiro/lady_butterfly':{kind:'butterfly',name:'Thread-Wielding Shinobi · Old estate courtyard (threads and illusions)',arena:{shape:'rect',halfWidth:9.5,halfDepth:7.5,pillars:[-6.6,-2.2,2.2,6.6].flatMap(x=>[{x,z:-4.6,r:.42},{x,z:4.6,r:.42}])},player:[0,3.2],boss:[0,-3.2]}, + 'sekiro/isshin':{kind:'isshin',name:'Old Sword-and-Spear Master · Pampas field (Lightning Swordsman and three master phases)',arena:{shape:'circle',radius:13,pillars:[]},player:[0,4.5],boss:[0,-4.5]}, + 'sekiro/gyoubu':{kind:'gyoubu',name:'Mounted Spear General · Castle gate (charges and rope spear)',arena:{shape:'circle',radius:19,pillars:[]},player:[0,6],boss:[0,-6]}, + 'sekiro/demon':{kind:'demon',name:'Flame Behemoth · Burning castle gate (fire and burn)',arena:{shape:'circle',radius:17,pillars:[]},player:[0,6.5],boss:[0,-6.5]} + }; + + const M=root.SekiroGame={id:'sekiro_remake',version:'sekiro@12',hz:60,maxSeconds:300,dimension:'3d',renderer:'webgl-boss3d', + title:'Sekiro · Shadows Die Twice',tiers:TIERS,cases:Object.entries(CASES).map(([id,c])=>({id,name:c.name})), + tuning:C,genichiro:G,ape:P,butterfly:L,moves:GEN_MOVES,isshin:I,gyoubu:O,demon:D,bosses:{genichiro:GENICHIRO,ape:APE,butterfly:BUTTERFLY,isshin:ISSHIN,gyoubu:GYOUBU,demon:DEMON},caseKinds:Object.fromEntries(Object.entries(CASES).map(([id,c])=>[id,c.kind])), + controls:{'W A S D':'Move relative to the camera; there is no stamina bar. Hold Shift to sprint','mouse dx':'Turn the free camera with horizontal mouse movement. After pressing E to lock on, the camera tracks the boss and horizontal mouse movement no longer turns it', + 'J / LMB':'Tap to slash or hold to charge a thrust. When the red marker appears nearby, press attack again for a deathblow','K / RMB':'Hold to block; press just before impact to deflect. Repeated presses shorten the deflect window', + 'Shift':'Press to dodge. Dodge toward a perilous thrust to counter it; dodge sideways or backward to escape a perilous grab','Space':'Jump over a perilous low sweep, then press jump again near the enemy to kick off them', + 'Q':'Healing gourd (the Bow-and-Blade Swordsman always punishes healing while idle)','E':'Toggle lock-on (off at the start)','R':'Resurrect after death (subject to resurrection nodes and seals; terror deaths cannot be reversed)', + 'Airborne J / LMB':'Lightning reversal: catch lightning in the air, then attack again before landing to send it back','Posture broken':'Press Shift or Space during stagger to recover sooner', + 'Status':'Poison builds from gas and dung, then drains health. Terror builds from the ape’s phase-two scream and kills at full gauge; move away to avoid it','Illusions':'The shinobi’s summoned illusions vanish after one hit. Homing butterflies pursue you; pillars can block them','Mounted Spear General':'The mounted general does not block. Hits land but interrupt him only when his poise breaks. Jumping slashes to his upper body deal more posture damage. He turns and charges back after riding away (there is no grappling rope); standing directly behind the horse risks a kick','Flame Behemoth':'The behemoth does not block and staggers only when its poise breaks. Staying under its belly avoids most moves. Its flaming arm cannot be deflected; blocking reduces damage but builds burn. Full burn drains health and prevents posture recovery. Jump over perilous charges and fire-ring sweeps. Run from the explosive leap or be airborne at impact. The phase-three fire ring knocks you back and burns you','Old Sword-and-Spear Master':'Red-blade ranged slashes cannot be blocked; dodge or run away. Spirit blades chip through blocks, while deflecting avoids posture damage; jumping and sidestepping also work. Blocking bullets from the spear phase costs heavy posture. A four-shot volley is always followed by a perilous attack'}}; + function newBody(x,z,hp,r){return {x,y:0,z,yaw:Math.PI,hp,maxHp:hp,r,posture:0,maxPosture:C.posture,postureDelay:0,action:'idle',actionTick:0,flash:0,hurt:0};} + function openAt(m,tick,connected=true){const inside=w=>tick>=w[0]&&ticks+b.hp,0);this.nextMinion=1; + this.stats={moves:{},deflects:0,blocks:0,guardBreaks:0,safetyRolls:0,mikiri:0,sweepJumps:0,stomps:0,grabEscapes:0, + lightningReversals:0,lightningCatches:0,lightningFailures:0,deathblows:0,resurrections:0,deaths:0,gourdsUsed:0,healsApplied:0, + healPunishes:0,passageOpenings:0,passageCancels:0,healthHits:0,bossDeflects:0,bossBlocks:0,playerAttacks:0,perilousFailures:0,playerHits:0, + postureBreaks:0,vitalityBreaks:0,poisoned:0,terrorDeaths:0,flinches:0,apeRolls:0,neckOpenings:0,falseExecutions:0,illusionsSummoned:0,illusionsKilled:0,butterflies:0,butterflyHits:0,pillarBlocks:0,...K.statsExtra?.()}; + K.start(this); + } + get K(){return KINDS[this.kind];} + get moves(){return KINDS[this.kind].moves;} + state(){return N.copy(this);} + emit(name){this.events.push(name);} + fx(type,at,life=15){this.effects.push({type,x:at.x,y:(at.y||0)+.9,z:at.z,life,maxLife:life});} + face(o,target){o.yaw=A(target.x-o.x,target.z-o.z);} + turn(o,yaw,rate){o.yaw=N.angle(o.yaw+N.clamp(N.angle(yaw-o.yaw),-rate,rate));} + confine(o){const a=this.arena; + if(a.shape==='circle'){const r=Math.hypot(o.x,o.z),lim=a.radius-o.r;if(r>lim){o.x*=lim/r;o.z*=lim/r;}} + else{o.x=N.clamp(o.x,-a.halfWidth+o.r,a.halfWidth-o.r);o.z=N.clamp(o.z,-a.halfDepth+o.r,a.halfDepth-o.r);} + for(const q of a.pillars){const dx=o.x-q.x,dz=o.z-q.z,d=Math.hypot(dx,dz),min=q.r+o.r;if(d1e-9?dx/d:1,nz=d>1e-9?dz/d:0;o.x=q.x+nx*min;o.z=q.z+nz*min;}}} + move(o,dx,dz){o.x+=dx;o.z+=dz;this.confine(o);} + // Steer around a pillar standing in the straight line to the target, so no boss can stall behind one. + heading(o,tx,tz){let a=A(tx-o.x,tz-o.z);const far=Math.hypot(tx-o.x,tz-o.z); + for(const q of this.arena.pillars){const qx=q.x-o.x,qz=q.z-o.z,along=qx*Math.sin(a)+qz*Math.cos(a),side=qx*Math.cos(a)-qz*Math.sin(a); + if(along>0&&along1e-3?-1:1,tx2=-k*vz/len,tz2=k*vx/len;a=A(tx2*.8+Math.sin(a)*.4,tz2*.8+Math.cos(a)*.4);break;}} + return a;} + toward(o,tx,tz,speed,min){const d=Math.hypot(tx-o.x,tz-o.z);if(d<=min)return;const a=this.heading(o,tx,tz),s=Math.min(speed,d-min);this.move(o,Math.sin(a)*s,Math.cos(a)*s);} + advance(speed,min=.9){const b=this.boss,p=this.player;this.toward(b,p.x,p.z,speed,min+(b.r-.5));} + advanceCommitted(speed,min=.9){const b=this.boss,travel=Math.min(speed,Math.max(0,b.commitDistance-min-(b.r-.5))); + this.move(b,Math.sin(b.aim)*travel,Math.cos(b.aim)*travel);b.commitDistance=Math.max(0,b.commitDistance-travel);} + postureFactor(o){const h=o.hp/o.maxHp;return o===this.boss?regenFactor(this.tune.bars[this.boss.phase-1].table,h):regenFactor('player',h);} + recoverPosture(o,boost=1){if(o.postureDelay>0||o.burning>0)return;const rate=o===this.boss?this.tune.bars[this.boss.phase-1].regen:C.postureRate;o.posture=Math.max(0,o.posture-rate*this.postureFactor(o)*boost);} + setPlayerAction(action){const p=this.player;if(p.action!==action){p.action=action;p.actionTick=0;}} + dodgeToward(){const p=this.player,b=this.boss,a=A(b.x-p.x,b.z-p.z);return p.dodgeX*Math.sin(a)+p.dodgeZ*Math.cos(a);} + startMove(name){ + const b=this.boss,m=this.moves[name],p=this.player;if(!m)throw Error('Unknown move '+name); + b.state='attack';b.action=name;b.actionTick=0;b.moveTick=0;b.moveDuration=m.duration;b.perilous=m.perilous||null;b.chainNext=null;b.connected=false; + b.telegraph=m.perilousFrom?null:b.perilous;b.aim=A(p.x-b.x,p.z-b.z);if(this.kind!=='ape'&&this.kind!=='gyoubu'&&this.kind!=='demon')b.yaw=b.aim;b.commitDistance=dist(p,b); + this.K.onStart?.(this,name);this.stats.moves[name]=(this.stats.moves[name]||0)+1;this.emit('move:'+name); + } + stagger(action,ticks){const b=this.boss;b.state='stunned';b.stun=ticks;b.action=action;b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;b.y=0;} + interruptBoss(ticks){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return;b.state='stunned';b.stun=Math.max(b.stun,ticks);b.action='stagger';b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;} + // Apparent posture cap: the beast's posture cannot be broken by deflection alone in its first life (S16). + bossPosture(amount,deflect=false){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return; + b.posture=Math.min(b.maxPosture,b.posture+amount);b.postureDelay=0; + if(deflect&&this.kind==='ape'&&b.form_id==='ape'&&b.posture>=b.maxPosture){b.posture=b.maxPosture-1;return;} + if(b.posture>=b.maxPosture)this.breakBoss();} + damageBoss(amount,posture=0){const b=this.boss;if(b.deathblowAvailable||b.executing||b.state==='dead')return;b.hp=Math.max(0,b.hp-amount);b.flash=8;this.stats.healthHits++;this.emit('boss_health_hit'); + if(b.hp<=0)this.breakBoss();else this.bossPosture(posture);} + breakBoss(){const b=this.boss;if(b.executing||b.deathblowAvailable)return;if(b.hp<=0)this.stats.vitalityBreaks++;else this.stats.postureBreaks++;b.deathblowAvailable=true;b.deathblow=b.hp===0?-1:C.deathblowWindow;b.state='deathblow';b.action='posture_break';b.actionTick=0;b.perilous=null;b.telegraph=null;b.lightning=false;b.chainNext=null;b.neckExposed=0;this.emit('deathblow_available');} + execute(){ + const b=this.boss,p=this.player;if(!b.deathblowAvailable||dist(p,b)>C.deathblowReach+b.r||p.y>.2||p.dead)return false; + b.deathblowAvailable=false;b.executing=C.executionFrames;b.state='execution';b.action='deathblow';b.actionTick=0;b.hp=0;b.y=0; + p.inv=C.executionFrames+8;p.stagger=0;p.postureBroken=false;p.lightning=0;p.attackTick=-1;p.charge=0;p.healTick=0;p.dodgeTicks=0;this.setPlayerAction('deathblow'); + this.hazards=[];this.minions=[];this.stats.deathblows++;p.resurrectionLocked=false;this.emit('deathblow');return true; + } + finishExecution(){this.K.finish(this);} + win(){this.outcome='win';this.emit('shinobi_execution');} + nextBar(){const b=this.boss,bar=this.tune.bars[b.phase];b.phase++;b.healthbar_phase=b.phase; + b.hp=b.maxHp=bar.hp;b.maxPosture=bar.posture;b.posture=0;b.postureDelay=0;b.guardCount=0;b.y=0;b.stun=0;b.perilous=null;b.telegraph=null;b.neckExposed=0; + const p=this.player;p.posture=0;p.postureDelay=0;p.inv=25;p.lightning=0;this.setPlayerAction('idle'); + this.hazards=[];this.minions=[];this.emit('phase:'+b.phase);} + breakPlayer(){const p=this.player;p.stagger=C.guardBreakStagger;p.posture=35;p.postureBroken=true;p.attackTick=-1;p.charge=0;p.healTick=0;this.stats.guardBreaks++;this.setPlayerAction('posture_break');this.emit('guard_break');} + die(terror=false){const p=this.player;p.dead=true;p.deathTimer=180;p.vy=0;p.guarding=false;p.lightning=0;p.postureBroken=false;p.terrorDeath=terror;this.stats.deaths++;if(terror)this.stats.terrorDeaths++;this.setPlayerAction('dead');this.emit(terror?'terror_death':'player_dead');} + hurtPlayer(hp,posture=0,stagger=16,bypass=false,scaled=true){ + const p=this.player;if(p.dead||(!bypass&&p.inv>0))return; + p.hp=Math.max(0,p.hp-hp*(scaled?this.tune.dmg:1));p.posture=Math.min(p.maxPosture,p.posture+posture);p.postureDelay=C.playerPostureDelay; + p.hurt=12;p.inv=bypass?0:5;p.stagger=Math.max(p.stagger,stagger);p.attackTick=-1;p.charge=0;p.healTick=0;p.dodgeTicks=0;this.stats.playerHits++; + this.setPlayerAction('hurt');this.emit('player_hit'); + if(p.hp<=0){this.die();return;} + if(p.posture>=p.maxPosture)this.breakPlayer(); + } + revive(){const p=this.player;if(!p.dead||p.nodes<=0||p.resurrectionLocked||p.terrorDeath)return false; + p.nodes--;p.resurrections=p.nodes;p.resurrectionLocked=true;p.dead=false;p.hp=p.maxHp*C.reviveFraction;p.posture=0;p.stagger=0;p.y=0;p.vy=0;p.terror=0; + p.revive=C.reviveFrames;p.inv=C.reviveFrames+10;if(p.burning!==undefined){p.burn=0;p.burning=0;}p.attackTick=-1;p.healTick=0;this.setPlayerAction('revive'); + this.interruptBoss(45);this.hazards=this.hazards.filter(q=>q.type==='gas');this.stats.resurrections++;this.emit('resurrection');return true; + } + guardFacing(source){return Math.abs(N.angle(A(source.x-this.player.x,source.z-this.player.z)-this.player.yaw))<1.55;} + blockOrDeflect(hit,source,kind='melee',move=null){ + const p=this.player,b=this.boss;if(!p.guarding||p.stagger>0||!this.guardFacing(source))return false; + // A fire arm cannot be deflected: a fresh press takes the blow in full (S39). + if(hit.noDeflect&&p.guardAge=p.maxPosture)this.breakPlayer(); + // Guarding fire still builds Burn (S38) and lets some of it through (S36, S39). + if(hit.burn&&!p.dead){this.burnUp(hit.burn);if(hit.leak){p.hp=Math.max(0,p.hp-hit.hp*hit.leak*this.tune.dmg);if(p.hp<=0)this.die();}} + } + p.postureDelay=C.playerPostureDelay;if(hit.push){const a=A(p.x-source.x,p.z-source.z);this.move(p,Math.sin(a)*hit.push,Math.cos(a)*hit.push);}return true; + } + reaches(hit,src){const p=this.player,d=dist(src,p),angle=Math.abs(N.angle(A(p.x-src.x,p.z-src.z)-src.yaw));return d<=hit.reach&&d>=(hit.inner||0)&&(hit.rear?Math.PI-angle:angle)<=(hit.arc||1.13);} + strike(hit,move,src){ + const b=this.boss,p=this.player,fromBoss=src===b;if(p.dead||p.revive||b.executing||(fromBoss&&b.deathblowAvailable))return; + // onlyAir: a high swing that passes over a grounded Sekiro (S36). + const reach=this.reaches(hit,src)&&!(hit.onlyAir&&p.y<=C.sweepHeight); + if(this.probe)this.probe.push({i:this.probeTick,kind:'melee',type:hit.type,move,reach,src:fromBoss?'boss':'minion',noJump:!!hit.noJump,dodge:!!hit.dodge,noDeflect:!!hit.noDeflect,facing:this.guardFacing(src)}); + if(!reach)return; + if(hit.type==='sweep'){ + if(p.y>C.sweepHeight){this.stats.sweepJumps++;this.emit('sweep_avoided');return;} + b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,25,true);if(hit.burn)this.burnUp(hit.burn);return; + } + // The Demon's explosive landing: no guard; be out of reach or in the air (S36, S39). + if(hit.type==='blast'){if(p.y>.9){this.emit('blast_avoided');return;}b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,30,true); + if(!p.dead){const a=A(p.x-src.x,p.z-src.z);this.move(p,Math.sin(a)*hit.push,Math.cos(a)*hit.push);this.burnUp(hit.burn);}return;} + if(hit.type==='grab'){ + // No deflect or guard. Genichiro: jump or step aside; a forward (Mikiri) step is still caught. The ape's floor + // swipe is jumped; its belly flop and Lady Butterfly's aerial grab are escaped only by distance (S05, S14, S19). + if((!hit.noJump&&p.y>C.grabJumpHeight)||(hit.dodge&&p.dodgeTicks>=C.dodgeFrames-C.dodgeInv&&this.dodgeToward()<=.55)){this.stats.grabEscapes++;this.emit('grab_avoided');return;} + b.connected=true;this.stats.perilousFailures++;this.emit('grabbed');this.hurtPlayer(hit.hp,hit.posture,40,true);return; + } + if(hit.type==='lightning'){this.catchLightning();return;} + // Isshin's circular force wave: jump it, deflect it as his arm moves, or be elsewhere (S27). + if(hit.ring&&p.y>C.sweepHeight){this.emit('ring_jumped');return;} + if(hit.type==='mortal'){if(p.dodgeTicks>=C.dodgeFrames-C.dodgeInv){this.emit('mortal_avoided');return;}b.connected=true;this.stats.perilousFailures++;this.hurtPlayer(hit.hp,hit.posture,30,true);return;} + if(p.y>1.9&&hit.type!=='slam')return; + if(hit.type==='thrust'&&p.dodgeTicks>0&&p.y<.3&&this.dodgeToward()>.55){ + this.stats.mikiri++;this.fx('mikiri',b,25);this.emit('mikiri');this.bossPosture(C.mikiriPosture*C.postureUnit);this.interruptBoss(C.mikiriStun);p.dodgeTicks=0;p.inv=12;return; + } + if(this.blockOrDeflect(hit,src,'melee',move)){if(fromBoss)b.connected=true;return;} + if(hit.type!=='thrust'&&p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)return; + if(fromBoss){b.connected=true;if(hit.type==='thrust')this.stats.perilousFailures++;this.K.onLanded?.(this,hit);} + this.hurtPlayer(hit.hp,hit.posture,hit.stagger??(hit.type==='slam'?24:16));if(hit.burn)this.burnUp(hit.burn); + } + // Burn (S38): fire fills the gauge, guarded or not; full, it drains vitality and stops posture recovery for a while. + burnUp(x){const p=this.player;if(p.burn===undefined||p.dead)return;p.burnFed=true;if(p.burning>0)return; + p.burn=Math.min(100,p.burn+x*this.tune.dmg);if(p.burn>=100){p.burn=0;p.burning=D.burnTicks;this.stats.burns++;this.emit('burning');}} + catchLightning(){const p=this.player;if(p.dead)return; + if(p.y>.2){p.hp=Math.max(0,p.hp-G.lightningChip);p.lightning=G.lightningCarry;p.lightningCaughtAt=this.t;this.stats.lightningCatches++;this.fx('lightning_catch',p,20);this.emit('lightning_caught'); + if(p.hp<=0)this.hurtPlayer(1,0,0,true); + }else{this.stats.lightningFailures++;this.fx('shock',p,35);this.emit('grounded_lightning');this.hurtPlayer(G.lightningDamage,G.lightningPosture,G.lightningShock,true);} + } + reverseLightning(){const p=this.player,b=this.boss;if(!p.lightning||p.y<=.1||this.t===p.lightningCaughtAt)return false; + p.lightning=0;this.stats.lightningReversals++;this.emit('lightning_reversal');this.fx('lightning_return',b,30); + if(dist(p,b)<=G.reversalRange&&Math.abs(N.angle(A(b.x-p.x,b.z-p.z)-p.yaw))<1.6){this.damageBoss(Math.round(b.maxHp*G.lightningBossDamage),G.lightningBossPosture*C.postureUnit);this.interruptBoss(G.lightningStun);} + else this.emit('reversal_out_of_range'); + this.hazards=this.hazards.filter(q=>q.type!=='lightning_arrow');return true; + } + // Area terror: the headless ape's blood scream fills the gauge with distance falloff; guarding does not stop it (S20). + terrorWave(s){const p=this.player,b=this.boss;if(p.dead||p.revive||b.executing)return;const d=dist(p,b); + if(this.probe&&d<=s.radius)this.probe.push({i:this.probeTick,kind:'aoe',type:'terror',reach:true}); + if(d>s.radius)return;const fall=Math.sqrt(1-d/s.radius);p.terror=Math.min(100,p.terror+s.rate*fall*this.tune.dmg);p.terrorFed=true; + p.hp=Math.max(0,p.hp-s.drain*fall*this.tune.dmg);if(p.terror>=100){this.emit('terror_full');this.die(true);}else if(p.hp<=0)this.die();} + playerAttack(kind){const p=this.player;if(p.attackTick<0)return; + const wind=kind==='thrust'?C.thrustWind:C.slashWind;if(p.attackTick!==wind||p.attackHit)return;p.attackHit=true; + const b=this.boss,range=kind==='thrust'?3.05:2.55,facing=o=>Math.abs(N.angle(A(o.x-p.x,o.z-p.z)-p.yaw)); + for(const q of this.minions)if(q.alive&&dist(p,q)<=range+q.r-.3&&facing(q)<=1.2){q.alive=false;q.fade=24;this.stats.illusionsKilled++;this.fx('illusion_cut',q);this.emit('illusion_cut');} + if(dist(p,b)>range+b.r-.5||facing(b)>1.2||Math.abs((b.y||0)-(p.y||0))>1.5||b.executing||b.deathblowAvailable||b.state==='dead')return; + const m=this.moves[b.action],busy=b.state==='attack';if(busy&&(m?.invulnerable||b.moveTick<(m?.invulnerableUntil||0)))return; + b.attackedAt=this.t;this.K.playerHit(this,kind,b.state==='stunned'||(busy&&openAt(m,b.moveTick,b.connected)),b.action); + } + arrow(heavy=false,lightning=false){const b=this.boss,p=this.player; + const sy=b.y+1.35,dy=p.y+.9-sy,dx=p.x-b.x,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=lightning?.42:.4; + this.hazards.push({type:lightning?'lightning_arrow':'arrow',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed, + sourceX:b.x,sourceZ:b.z,owner:'boss',age:0,life:120,radius:.2,charged:heavy,damage:heavy?24:12,posture:heavy?27:12});this.emit(lightning?'lightning_arrow':'arrow'); + } + // Matchlock shot: fast, and guarding one costs heavy posture, so deflect it (S27). + bullet(){const b=this.boss,p=this.player,sy=b.y+1.3,dy=p.y+.9-sy,dx=p.x-b.x,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=I.bulletSpeed; + this.hazards.push({type:'bullet',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed,sourceX:b.x,sourceZ:b.z,age:0,life:60,radius:.14,damage:10,posture:24});this.emit('gunshot');} + // Force waves run along the ground: step aside from a vertical one, jump a flat one; guarding leaks vitality, deflecting does no posture damage (S27). + airWave(kind){const b=this.boss,p=this.player,a=A(p.x-b.x,p.z-b.z),speed=I.waveSpeed; + this.hazards.push({type:'wave',wide:kind==='h',x:b.x,y:.9,z:b.z,yaw:a,vx:Math.sin(a)*speed,vy:0,vz:Math.cos(a)*speed,sourceX:b.x,sourceZ:b.z,age:0,life:60,radius:kind==='h'?.95:.5,damage:kind==='h'?18:16,posture:kind==='h'?22:20});this.emit('force_wave');} + // The poo flies in a straight line at about 60 m/s and lasts three seconds (S16); a hit poisons at once (S14). + throwPoo(){const b=this.boss,p=this.player,sy=b.y+2.2,dx=p.x-b.x,dy=p.y+.9-sy,dz=p.z-b.z,len=Math.hypot(dx,dy,dz)||1,speed=1; + this.hazards.push({type:'poo',x:b.x,y:sy,z:b.z,vx:dx/len*speed,vy:dy/len*speed,vz:dz/len*speed,sourceX:b.x,sourceZ:b.z,age:0,life:180,radius:.42,damage:30,posture:20});this.emit('poo');} + kunai(n){const b=this.boss,p=this.player,sy=b.y+1.25; + for(let i=0;i=4&&a.pillars.every(q=>Math.hypot(x-q.x,z-q.z)>1)){this.minions.push({id:this.nextMinion++,x,y:0,z,yaw:A(p.x-x,p.z-z),r:.36,alive:true,state:'walk',t:0,fade:0,age:0});this.stats.illusionsSummoned++;return;}}} + summonIllusions(){const b=this.boss;b.spell=this.tune.spell||L.spell;b.dispelDue=false;while(this.minions.filter(q=>q.alive).length1.7&&!p.dead)this.toward(q,p.x,p.z,L.illusionSpeed,1.6);else if(!p.dead){q.state='attack';q.t=0;}} + else if(q.state==='attack'){if(++q.t<20)q.yaw=to;if(q.t===34)this.strike({type:'slash',reach:2.1,arc:1.1,hp:7,posture:11,stagger:8},'illusion',q);if(q.t>=40){q.state='recover';q.t=0;}} + else if(++q.t>=50){q.state='walk';q.t=0;}} + this.minions=this.minions.filter(q=>q.alive||q.fade>0);} + projectiles(){const p=this.player,a=this.arena; + for(const q of this.hazards){q.age++;q.life--; + if(q.type==='gas'){if(!p.dead&&p.y<1.6&&dist(q,p)0)q.cool--;const d=dist(q,p); + if(!p.dead&&!p.revive&&p.y<1&&q.cool<=0&&Math.abs(d-q.radius)a.radius+1:Math.abs(q.x)>a.halfWidth+1||Math.abs(q.z)>a.halfDepth+1; + if(out||q.y<-.2){q.life=0;continue;} + if(a.pillars.some(c=>Math.hypot(q.x-c.x,q.z-c.z)2&&!(q.type==='butterfly'&&q.age<(q.swarm?L.butterflyLaunch:L.dartLaunch))&&!p.dead&&!p.revive&&Math.hypot(p.x-old.x-u*dx,q.type==='wave'&&!q.wide?0:p.y+.9-old.y-u*dy,p.z-old.z-u*dz)0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)continue; + q.life=0; + const src={x:q.sourceX,z:q.sourceZ};if(q.type==='butterfly'){src.x=old.x;src.z=old.z;this.stats.butterflyHits++;} + const blocks=this.stats.blocks;if(this.blockOrDeflect({type:q.type,hp:q.damage,posture:q.posture,push:q.charged?.55:0,burn:q.burn,leak:q.leak},src,q.swarm?'butterfly':'arrow')){if(q.type==='wave'&&this.stats.blocks>blocks){p.hp=Math.max(0,p.hp-q.damage*I.waveLeak*this.tune.dmg);if(p.hp<=0)this.die();}continue;} + this.hurtPlayer(q.damage,q.posture,18);if(q.burn&&!p.dead)this.burnUp(q.burn); + if(q.type==='poo'&&!p.dead){p.poisoned=C.poisonTicks;p.poison=0;this.stats.poisoned++;this.emit('poisoned');} + } + } + this.hazards=this.hazards.filter(q=>q.life>0); + } + // Lobbed fireballs burst where they land and leave a fire; homing ones steer with a limited turn and sink to the ground (S36, S39). + fireball(q){const p=this.player; + if(q.lob)q.vy-=D.lobGravity;else{if(q.age>12&&q.age<12+D.homingFor){const want=A(p.x-q.x,p.z-q.z),now=A(q.vx,q.vz),yaw=N.angle(now+N.clamp(N.angle(want-now),-D.homingTurn,D.homingTurn));q.vx=Math.sin(yaw)*D.homingSpeed;q.vz=Math.cos(yaw)*D.homingSpeed;q.vy=N.clamp((p.y+.9-q.y)*.08,-D.homingClimb,D.homingClimb);}else if(q.age<=12)q.vy*=.9;else q.vy-=D.homingFall;} + const old={x:q.x,y:q.y,z:q.z};q.x+=q.vx;q.y+=q.vy;q.z+=q.vz; + const hitP=()=>{if(this.probe)this.probe.push({i:this.probeTick,kind:'projectile',type:'fireball',reach:true});if(p.inv>0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv)return; + if(!this.blockOrDeflect({type:'fireball',hp:q.damage,posture:q.posture,burn:q.burn,leak:D.fireLeak,noDeflect:true},{x:q.sourceX,z:q.sourceZ},'arrow')){this.hurtPlayer(q.damage,q.posture,18);this.burnUp(q.burn);}}; + if(q.y<=0){q.life=0;this.hazards.push({type:'fire',x:q.x,y:0,z:q.z,radius:1.1,age:0,life:q.lob?100:60,rate:D.fireRate});this.emit('fireball_burst'); + if(!p.dead&&!p.revive&&p.y<.8&&Math.hypot(p.x-q.x,p.z-q.z)2&&!p.dead&&!p.revive){const dx=q.x-old.x,dy=q.y-old.y,dz=q.z-old.z,len=dx*dx+dy*dy+dz*dz,u=N.clamp(((p.x-old.x)*dx+(p.y+.9-old.y)*dy+(p.z-old.z)*dz)/(len||1),0,1); + if(Math.hypot(p.x-old.x-u*dx,p.y+.9-old.y-u*dy,p.z-old.z-u*dz)0||p.dodgeTicks>=C.dodgeFrames-C.dodgeInv){if(this.probe)this.probe.push({i:this.probeTick,kind:'projectile',type:'fireball',reach:true});return;}q.life=0;hitP();}}} + statuses(){const p=this.player;if(p.dead){p.poisonFed=p.terrorFed=false;if(p.burnFed!==undefined)p.burnFed=false;return;} + if(p.poison>=100){p.poison=0;p.poisoned=C.poisonTicks;this.stats.poisoned++;this.emit('poisoned');} + if(p.poisoned>0){p.poisoned--;p.hp=Math.max(0,p.hp-C.poisonDrain);if(p.hp<=0)this.die();} + if(!p.poisonFed)p.poison=Math.max(0,p.poison-C.poisonDecay);if(!p.terrorFed)p.terror=Math.max(0,p.terror-C.terrorDecay);p.poisonFed=p.terrorFed=false; + if(p.burning!==undefined){if(p.burning>0&&!p.dead){p.burning--;p.hp=Math.max(0,p.hp-D.burnDrain*this.tune.dmg);if(p.hp<=0)this.die();}if(!p.burnFed)p.burn=Math.max(0,p.burn-D.burnDecay);p.burnFed=false;}} + bossUpdate(){const b=this.boss,p=this.player,K=this.K; + b.actionTick++;if(b.flash>0)b.flash--; + if(b.executing){b.executing--;if(!b.executing)this.finishExecution();return;} + if(b.deathblowAvailable){b.y=Math.max(0,b.y-.15);if(b.deathblow>0&&--b.deathblow===0){b.deathblowAvailable=false;b.posture=b.maxPosture*C.deathblowMissFraction;b.state='idle';b.action='idle';b.cooldown=25;this.emit('deathblow_missed');}return;} + if(K.special&&K.special(this))return; + if(p.dead)return; + if(b.state==='stunned'){if(b.action!=='flinch_big')b.y=Math.max(0,b.y-.15);if(--b.stun<=0){b.state='idle';b.action='idle';b.cooldown=this.tune.restStun;}return;} + // Enemy posture has no recovery delay (S04) and keeps recovering during his own attacks; it pauses while he is + // staggered (returned above, by analogy with the S04 clause for Sekiro) and while a deathblow is open. + this.recoverPosture(b); + if(b.state==='idle'){K.idle(this);return;} + const move=b.action,m=this.moves[move],t=b.moveTick++; + if(m.perilousFrom&&t===m.perilousFrom)b.telegraph=b.perilous; + K.step(this,move,m,t);if(b.state!=='attack'||b.action!==move)return; + for(const hit of m.hits)if(t===hit.t)this.strike(hit,move,b); + if(b.state!=='attack'||b.action!==move)return; + K.afterHits(this,move,m,t);if(b.state!=='attack'||b.action!==move)return; + if(t>=m.duration-1){if(!m.air)b.y=0;const next=K.followUp(this,move); + if(next){this.startMove(next);return;} + b.state='idle';b.action='idle';b.perilous=null;b.telegraph=null;b.lightning=false;b.cooldown=this.tune.rest; + } + } + vertical(){const p=this.player; + if(p.y>0||p.vy>0){p.y+=p.vy;p.vy-=C.gravity;if(p.y<=0){p.y=0;p.vy=0;p.stomped=false;if(p.lightning){p.lightning=0;this.stats.lightningFailures++;this.emit('lightning_grounded');this.hurtPlayer(G.lightningDamage,G.lightningPosture,G.lightningShock,true);}}} + if(p.lightning>0)p.lightning--; + } + kick(){const p=this.player,b=this.boss,K=this.K;if(p.stomped||p.y<=.5||b.executing||b.state==='dead'||b.deathblowAvailable||dist(p,b)>=K.kickRange+b.r-.5)return false; + if(!K.kickAnyHeight&&p.y<=b.y+.5)return false; + p.stomped=true;p.vy=C.jumpSpeed*.8;this.stats.stomps++;const perilousSweep=b.state==='attack'&&b.perilous==='sweep'; + this.bossPosture((this.kind==='butterfly'&&perilousSweep?L.kick:C.stompPosture)*C.postureUnit);this.fx('stomp',b,22);this.emit('head_stomp');K.onKick?.(this);return true;} + playerUpdate(keys,pressed,mouse){const p=this.player,b=this.boss; + if(pressed.has('E'))this.lockOn=!this.lockOn; + if(this.lockOn){this.face(p,b);this.cameraYaw=p.yaw;}else{this.cameraYaw=N.angle(this.cameraYaw-mouse[0]*.003);p.yaw=this.cameraYaw;}p.actionTick++; + // Physical holds continue through death/cinematics; returning to play must + // never synthesize a fresh deflect, charged attack or dodge press. + const guard=keys.has('K')||keys.has('RMB'),attack=keys.has('J')||keys.has('LMB'),dodge=keys.has('Shift'); + const guardPress=guard&&!p.guardHeld,attackPress=attack&&!p.attackHeld,dodgePress=dodge&&!p.dodgeHeld; + p.guardHeld=guard;p.attackHeld=attack;p.dodgeHeld=dodge;p.running=false; + for(const name of ['inv','stagger','hurt','flash','revive'])if(p[name]>0)p[name]--; + if(p.stagger===0)p.postureBroken=false; + if(p.dead){p.guarding=false;p.guardAge=999;p.runTicks=0;if(pressed.has('R'))this.revive();if(p.dead&&--p.deathTimer<=0)this.outcome='loss';return;} + if(b.executing||p.revive||(b.state==='attack'&&(b.action==='tomoe_awaken'||this.moves[b.action]?.cinematic))){p.guarding=false;p.guardAge=999;this.vertical();return;} + if(this.t-p.lastGuardPress>C.spamReset)p.spam=0; + if(guardPress){p.spam=this.t-p.lastGuardPress>p.spam);p.guardAge=0; + }else p.guardAge++; + p.guarding=guard&&p.stagger===0&&p.healTick===0&&(p.attackTick<0||p.attackTick>13); + if(guardPress&&p.charge){p.charge=0;p.attackTick=-1;this.setPlayerAction('guard');} + if(p.lightning&&attackPress&&this.reverseLightning())return; + if(attackPress&&b.deathblowAvailable&&this.execute())return; + if(p.stagger>0){p.guarding=false;p.dodgeTicks=0; + // Safety roll: Step Dodge or Jump makes a posture-break stun much shorter (S04). + if(p.postureBroken&&(dodgePress||pressed.has('Space'))&&C.guardBreakStagger-p.stagger>=C.safetyRollAfter&&p.stagger>C.safetyRollRemain){p.stagger=C.safetyRollRemain;this.stats.safetyRolls++;this.setPlayerAction('safety_roll');this.emit('safety_roll');} + this.vertical();return;} + if(pressed.has('Q')&&p.gourds>0&&p.hpC.gourdFrames){p.healTick=0;this.setPlayerAction('idle');}this.recoverPosture(p);p.runTicks=0;return;} + if(pressed.has('Space')){ + if(p.y===0){p.vy=C.jumpSpeed;p.stomped=false;this.setPlayerAction('jump');this.emit('jump');} + else this.kick(); + } + this.vertical(); + const f=(keys.has('W')?1:0)-(keys.has('S')?1:0),side=(keys.has('D')?1:0)-(keys.has('A')?1:0),a=this.cameraYaw; + let dx=Math.sin(a)*f-Math.cos(a)*side,dz=Math.cos(a)*f+Math.sin(a)*side,len=Math.hypot(dx,dz);if(len){dx/=len;dz/=len;} + if(dodgePress&&p.y===0&&!p.charge&&p.attackTick<0){if(!len){dx=Math.sin(p.yaw);dz=Math.cos(p.yaw);}p.dodgeX=dx;p.dodgeZ=dz;p.dodgeTicks=C.dodgeFrames;this.setPlayerAction('dodge');this.emit('step');} + const stepping=p.dodgeTicks>0; + if(stepping){this.move(p,p.dodgeX*C.dodge,p.dodgeZ*C.dodge);p.dodgeTicks--;} + else if(len){p.running=dodge&&!p.guarding;const speed=p.guarding?C.move*.55:p.running?C.run:C.move;this.move(p,dx*speed,dz*speed);if(p.attackTick<0&&!p.charge&&p.y===0)this.setPlayerAction(p.running?'run':'walk');} + p.runTicks=p.running?p.runTicks+1:0; + if(attackPress&&p.attackTick<0&&!p.guarding&&p.dodgeTicks===0){p.charge=1;this.setPlayerAction('charge');} + if(p.charge){if(!attack||p.charge>=C.thrustCharge){p.attackKind=attack?'thrust':'slash';p.attackTick=0;p.attackHit=false;p.charge=0;this.stats.playerAttacks++;this.setPlayerAction(p.attackKind);}else p.charge++;} + if(p.attackTick>=0){this.playerAttack(p.attackKind);p.attackTick++;if(p.attackTick>(p.attackKind==='thrust'?C.thrustEnd:C.slashEnd)){p.attackTick=-1;this.setPlayerAction('idle');}} + // No posture recovery while attacking, sprinting, dodging, airborne or staggered; guarding speeds it up (S04). + if(p.attackTick<0&&!p.charge&&!stepping&&p.y===0&&!p.running){if(!len)this.setPlayerAction(p.guarding?'guard':'idle');this.recoverPosture(p,p.guarding?C.guardRecovery:1);} + } + separate(o,q,heightO,heightQ){const d=dist(o,q),min=o.r+q.r;if(!(o.y=min)return; + const nx=d>1e-8?(o.x-q.x)/d:Math.sin(o.yaw),nz=d>1e-8?(o.z-q.z)/d:Math.cos(o.yaw),push=(min-d)*.5; + this.move(o,nx*push,nz*push);this.move(q,-nx*push,-nz*push); + const residual=min-dist(o,q);if(residual>1e-6){this.move(o,nx*residual,nz*residual);const remain=min-dist(o,q);if(remain>1e-6)this.move(q,-nx*remain,-nz*remain);}} + update(keys,pressed,mouse){if(this.outcome)return; + for(const body of [this.player,this.boss])if(body.postureDelay>0)body.postureDelay--; + this.playerUpdate(keys,pressed,mouse);if(!this.outcome)this.bossUpdate();if(this.outcome)return; + this.minionUpdate();if(!this.player.dead)this.projectiles();this.statuses(); + const p=this.player,b=this.boss; + // A horse at the gallop rides through: without this it pushes Sekiro along in front of it and can never pass him. + if(!b.executing&&b.state!=='dead'&&!(b.state==='attack'&&this.moves[b.action]?.ride))this.separate(p,b,1.75,b.height); + for(const q of this.minions)if(q.alive)this.separate(p,q,1.75,1.7); + if(this.lockOn){this.face(p,b);this.cameraYaw=p.yaw;} + this.effects=this.effects.filter(fx=>--fx.life>0);this.lastKeys=[...keys].sort(); + } + health(){const b=this.boss,later=this.tune.bars.slice(b.phase).reduce((s,x)=>s+x.hp,0); + return [this.player.hp,C.playerHP,this.outcome==='win'?0:(b.state==='dead'?0:b.hp)+later,this.totalBossHP];} + } + M.Game=Game;M.openAt=openAt;M.regenFactor=regenFactor;M.tier=tier; + + /* Standard scripted reference controller (bossbench scripted hook). Called once per 200 ms packet with the live + * game; it reads privileged state on a deep copy, predicts the next contacts by simulating that copy with no input, + * and returns only legal holds (<= 4 keys each). Deterministic; never touches the live game or its RNG. */ + function cloneGame(g){return Object.assign(Object.create(Game.prototype),N.copy(g));} + function simTick(h,keys,mouse){const prev=new Set(h.lastKeys);h.events=[];h.update(new Set(keys),new Set(keys.filter(k=>!prev.has(k))),mouse);N.quantize(h);h.t++;} + function contacts(h,horizon){const s=cloneGame(h);s.probe=[]; + let first=-1;for(let i=0;ic.reach))first=i;if(first>=0&&i>=first+8)break;} + return s.probe.filter(c=>c.reach); + } + function room(h,x,z){const a=h.arena;/* free distance to the arena edge or a pillar */let r=a.shape==='circle'?a.radius-Math.hypot(x,z):Math.min(a.halfWidth-Math.abs(x),a.halfDepth-Math.abs(z)); + for(const q of a.pillars)r=Math.min(r,Math.hypot(x-q.x,z-q.z)-q.r);return r;} + function sideKey(h,reach=3.2){const p=h.player,a=h.cameraYaw,rx=-Math.cos(a),rz=Math.sin(a); + // Step toward the side with more room. + return room(h,p.x+rx*reach,p.z+rz*reach)>=room(h,p.x-rx*reach,p.z-rz*reach)?'D':'A';} + // Best of eight run directions away from a point, keeping room to keep running (walls, pillars). + function escape(h,x,z){const p=h.player,a=h.cameraYaw,f=[Math.sin(a),Math.cos(a)],r=[-Math.cos(a),Math.sin(a)];let best=null,score=-1e9; + for(const [keys,u,v] of [[['S'],-1,0],[['S','A'],-1,-1],[['S','D'],-1,1],[['A'],0,-1],[['D'],0,1],[['W','A'],1,-1],[['W','D'],1,1],[['W'],1,0]]){ + const len=Math.hypot(u,v),dx=(f[0]*u+r[0]*v)/len,dz=(f[1]*u+r[1]*v)/len;let px=p.x,pz=p.z,stuck=0; + for(let k=1;k<=6;k++){const nx=px+dx*.6,nz=pz+dz*.6;if(room(h,nx,nz)score){score=sc;best=keys;}} + return [...best,'Shift'];} + // Drinking takes 66 ticks: simulate the whole animation on a copy and heal only if nothing lands meanwhile. + function safeHeal(h){const s=cloneGame(h),hits=s.stats.playerHits;simTick(s,['Q'],[0,0,0]); + for(let i=0;ih.stats.healsApplied;} + function swarmCenter(list,p){if(!list.length)return [p.x,p.z];let x=0,z=0;for(const q of list){x+=q.x;z+=q.z;}return [x/list.length,z/list.length];} + function plan(h){ + const p=h.player,b=h.boss,prev=new Set(h.lastKeys),d=dist(p,b),tap=k=>prev.has(k)?[]:[k],kind=h.kind,head=b.form_id==='headless'; + if(h.outcome)return []; + if(p.dead)return p.nodes>0&&!p.resurrectionLocked&&!p.terrorDeath?tap('R'):[]; + if(b.executing||p.revive||(b.state==='attack'&&(b.action==='tomoe_awaken'||h.moves[b.action]?.cinematic)))return []; + if(p.stagger>0)return p.postureBroken&&C.guardBreakStagger-p.stagger>=C.safetyRollAfter?tap('Shift'):[]; + if(p.lightning>0&&p.y>.1)return tap('J'); + if(p.healTick>0)return []; + if(b.deathblowAvailable)return d>C.deathblowReach+b.r-.15?['W']:tap('J'); + const grounded=p.y===0&&p.vy===0,free=grounded&&!p.charge&&p.attackTick<0&&p.dodgeTicks===0; + if(!grounded&&!p.stomped&&p.y>.55&&db.y+.5)&&b.perilous==='sweep'&&b.state==='attack')return tap('Space'); + const swarm=h.hazards.filter(q=>q.type==='butterfly'&&q.swarm&&dist(q,p)<7.5&&q.agec.kind==='melee'&&!['sweep','grab','lightning','mortal'].includes(c.type)); + let threat=all[0]; + // A projectile followed closely by a guardable blow: guard (deflect) the blow instead of stepping into it. + if(threat&&(threat.type==='butterfly'||threat.type==='poo')&&melee&&melee.i<=threat.i+6)threat=melee; + const eta=threat?threat.i:99; + if(threat&&threat.src==='minion'&&!threat.facing){const q=h.minions.filter(m=>m.alive&&m.state==='attack').sort((a,c)=>dist(a,p)-dist(c,p))[0]; + if(free&&eta<=3&&!prev.has('Shift'))return escape(h,q?q.x:p.x,q?q.z:p.z);if(eta<=3)return [];} + if(threat){ + const type=threat.type; + if(type==='terror')return escape(h,b.x,b.z); + if(type==='gas'){const q=h.hazards.find(z=>z.type==='gas');return escape(h,q?q.x:b.x,q?q.z:b.z);} + if(type==='fire'&&!all.some(c=>c.kind!=='aoe'&&c.i<=6))return escape(h,threat.x,threat.z); + if(type==='fire_ring'&&eta<=6)return escape(h,b.x,b.z); + if(type==='blast'){if(grounded&&eta>=4&&eta<=14)return tap('Space');if(eta<=14)return [];} + // Fire arms and fireballs cannot be deflected: be guarding well before they land. + // A fire arm cannot be deflected and guarding it builds Burn: walk in under the belly, where it misses (S36, S37), else hold the guard early. + if(threat.noDeflect&&threat.kind==='melee'&&grounded&&free&&d>D.belly-.1&&(d-D.belly+.1)/C.move=4&&d>D.belly&&p.attackTick<0&&!p.charge)return ['W','Shift']; + if(type==='fireball'&&free&&eta<=2&&!prev.has('Shift'))return [sideKey(h,1.6),'Shift']; + if(type==='fireball'&&eta<=2&&prev.has('Shift'))return []; + if(threat.noDeflect||type==='fireball'){if(eta<=29)return ['RMB'];} + if(type==='lightning'||type==='lightning_arrow'){ + if(grounded&&eta<=1+(type==='lightning'?3:0))return tap('Space'); + if(grounded&&eta>8&&d>7)return ['W']; + if(eta<=8)return []; + }else if(type==='mortal'){ + if(free&&eta<=5&&!prev.has('Shift'))return [sideKey(h),'Shift']; + if(eta<=5)return []; + }else if(type==='sweep'){ + if(grounded&&eta>=3&&eta<=8)return tap('Space'); + if(eta<=8)return []; + }else if(type==='grab'){ + if(threat.noJump){// distance only: retreat straight back as it commits (the aerial grab tracks a side step, S19) + const away=escape(h,b.x,b.z);if(free&&eta<=16&&!prev.has('Shift'))return away; + return eta<=18?(prev.has('Shift')?away.filter(k=>k!=='Shift'):away):[];} + if(threat.dodge&&free&&eta<=3&&!prev.has('Shift'))return [sideKey(h),'Shift']; + if(grounded&&eta>=3&&eta<=8&&!prev.has('Space'))return ['Space']; + if(eta<=8)return prev.has('Shift')||prev.has('Space')?[]:threat.dodge?[sideKey(h)]:[]; + }else if(type==='thrust'){ + if(free&&eta>=1&&eta<=6&&!prev.has('Shift'))return ['W','Shift']; + if(eta<=1)return ['RMB']; + if(eta<=6)return prev.has('Shift')?[]:['W']; + }else if(type==='poo'||type==='butterfly'){ + if(type==='butterfly'&&!swarm.length){if(eta<=1)return ['RMB'];if(eta<=4)return [];} + else{if(free&&eta<=2&&!prev.has('Shift'))return type==='butterfly'?escape(h,...swarmCenter(swarm,p)):[sideKey(h,1.6),'Shift']; + if(eta<=2)return [];} + }else{ + if(eta<=1)return ['RMB']; + if(eta<=4&&!swarm.length)return []; + } + } + // Spirit butterflies outrun a walk but not a sprint: kite them (pillars break them), and back away from the + // flurry instead of guarding it, coming back after its perilous finisher (S17, S19). + if(swarm.length&&grounded)return escape(h,...swarmCenter(swarm,p)); + if(b.state==='attack'&&b.action==='flurry'&&b.moveTick>=6&&b.moveTick<100&&grounded)return d<5.5?escape(h,b.x,b.z):[]; + if(b.state==='attack'&&b.action==='flurry'&&b.moveTick>=100&&b.moveTick<124&&grounded)return d>3.4?['W']:[]; + const ms=b.state==='attack'&&h.moves[b.action]?.scream;if(ms&&b.moveTick['arrow','lightning_arrow','kunai','poo','butterfly','bullet','wave'].includes(q.type)); + const calm=eta>=30&&!arrowsInFlight&&(b.state==='idle'||b.state==='stunned'||b.state==='dead')&&h.minions.every(q=>!q.alive||dist(q,p)>3); + if(p.hp<=50&&p.gourds>0&&free&&!prev.has('Q')&&calm&&(kind!=='genichiro'||b.state!=='idle'||d>=2)&&safeHeal(h))return ['Q']; + if(b.state==='dead'){if(p.hp<=75&&p.gourds>0&&free&&!prev.has('Q')&&safeHeal(h))return ['Q'];return d<6?['S']:[];} + // Lightning: wait for the airborne catch and reversal (heavier payoff) instead of cutting him out of the leap. + const lightningMove=b.state==='attack'&&b.lightning&&b.moveTick<100; + const m=h.moves[b.action],open=!lightningMove&&(b.state==='stunned'||b.state==='idle'||(b.state==='attack'&&openAt(m,b.moveTick+9,b.connected))); + if(lightningMove&&grounded&&d>6.5)return ['W']; + // Illusions: cut one that has closed in when nothing else is coming. + const near=h.minions.find(q=>q.alive&&dist(q,p)<2.3&&Math.abs(N.angle(A(q.x-p.x,q.z-p.z)-p.yaw))<1.1); + if(near&&free&&eta>=14)return tap('J'); + const reach=2.45+b.r-.5,safe=eta>=19&&!(b.state==='attack'&&m?.invulnerable); + if(free&&safe&&open&&d<=reach&&b.y<1.2)return tap('J'); + // The headless ape outranges Sekiro: keep a middle distance unless it is open (S14). + // Its delayed overhead chop is the opening: step in and deflect it to stun it with the neck exposed (S14, S15). + if(head&&b.state==='attack'&&(b.action==='overhead_slam'||b.action==='jump_sweep'&&b.moveTick>40)&&!open){return d>3.5&&b.moveTick<44?['W']:[];} + if(head&&!open&&b.state!=='stunned'){if(b.state==='attack'&&d<4.8)return [];if(d<4.6)return ['S'];if(d>7.5)return ['W'];return [];} + if(kind==='ape'&&b.state==='attack'&&!open&&d<3.6)return []; + if(kind==='gyoubu'&&d>5&&p.attackTick<0&&!p.charge&&grounded)return ['W','Shift']; + if(d>reach-.15&&p.attackTick<0&&!p.charge)return ['W']; + return []; + } + // The fight opens unlocked (free camera, sekiro@11): the script locks on in its first sub-step and never toggles again, + // so from then on it plays exactly as it did when the fight opened locked (camera already faces the boss at tick 0). + M.scripted=function(game){ + const h=cloneGame(game),p=h.player,b=h.boss,holds=[],lock=!h.lockOn; + const mouse=[h.lockOn?0:N.clamp(Math.round(-N.angle(A(b.x-p.x,b.z-p.z)-h.cameraYaw)/.003),-1000,1000),0,0]; + for(let j=0;j<6;j++){ + const keys=j===0&&lock?['E',...plan(h)].slice(0,4):plan(h).slice(0,4);holds.push(keys); + for(let n=0;n<2&&!h.outcome;n++)simTick(h,keys,mouse.map(v=>v/12)); + } + return {holds,mouse}; + }; + M.oracle=M.scripted; // legacy tool name + M.debug={plan:g=>plan(cloneGame(g)),contacts:(g,n=30)=>contacts(cloneGame(g),n)}; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/sekiro_remake/index.html b/environments/games/web/games/sekiro_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..31c3b216a06edf67d280da4f4723a71a05c81cfe --- /dev/null +++ b/environments/games/web/games/sekiro_remake/index.html @@ -0,0 +1,7 @@ +Sekiro · Six Bosses
            +
            Sekiro · Shadows Die Twice

            Sekiro · Six Bosses

            Face six foes: a bow-and-blade swordsman, a deceptive guardian ape, an illusion-wielding shinobi, a sword-and-spear master, a mounted general, and a flame behemoth. Read their attacks and break their posture.

            Back to Game Lobby ↗
            +
            Are You Ready?Click Start Challenge
            +

            Verify Script reads game state to check the mechanics. Replays save real inputs and simulate the full battle again.

            +
            +
            All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
            + diff --git a/environments/games/web/games/sekiro_remake/manifest.json b/environments/games/web/games/sekiro_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..fda36d3d14ded323b2a3b894f6d719917950a40c --- /dev/null +++ b/environments/games/web/games/sekiro_remake/manifest.json @@ -0,0 +1,33 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "sekiro_remake", + "module": "SekiroGame", + "title": "Sekiro: Archer Swordsman / Valley Ape / Thread Ninja / Veteran Swordsman / Mounted Spearman / Blazing Beast", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-boss3d", + "rules": "sekiro@12", + "cases": [ + "sekiro/genichiro", + "sekiro/guardian_ape", + "sekiro/lady_butterfly", + "sekiro/isshin", + "sekiro/gyoubu", + "sekiro/demon" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "sekiro_remake/renderer3d.js", + "sekiro_remake/game.js", + "sekiro_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "sekiro_remake/game.js" + ], + "play_page": "web/games/sekiro_remake/index.html", + "scripted_controller": "SekiroGame.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,dz]} (deep-copy lookahead, deterministic; .oracle is an alias)" +} diff --git a/environments/games/web/games/sekiro_remake/renderer3d.js b/environments/games/web/games/sekiro_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..4bb4b53d6bb531bdb5ac312ebdcd97bc7684005f --- /dev/null +++ b/environments/games/web/games/sekiro_remake/renderer3d.js @@ -0,0 +1,666 @@ +/* Sekiro renderer: original low-poly Three.js art (r160, MIT, vendored under _boss3d/vendor). Characters are rigid + * skinned meshes (one draw call each) posed from the simulation's action clocks; arenas are merged static meshes. + * Rendering is a pure function of the game state: it never writes game state and never draws from the game RNG. */ +(function(root){ + 'use strict'; + const T=root.THREE,B=root.Boss3D={}; + if(!T)throw Error('Offline Three.js renderer library is missing'); + const byCanvas=new WeakMap(),clamp=(x,a,b)=>Math.max(a,Math.min(b,x)),lerp=(a,b,u)=>a+(b-a)*u, + smooth=u=>{u=clamp(u,0,1);return u*u*(3-2*u);},band=(t,a,b)=>smooth((t-a)/(b-a)),v3=(x,y,z)=>new T.Vector3(x,y,z),items=a=>Array.isArray(a)?a:[]; + const M4=(x=0,y=0,z=0,rx=0,ry=0,rz=0,sx=1,sy=sx,sz=sx)=>new T.Matrix4().compose(v3(x,y,z),new T.Quaternion().setFromEuler(new T.Euler(rx,ry,rz)),v3(sx,sy,sz)); + const MY=(x,y,z,yaw,pitch,sx,sy,sz)=>new T.Matrix4().compose(v3(x,y,z),new T.Quaternion().setFromEuler(new T.Euler(pitch,yaw,0,'YXZ')),v3(sx,sy,sz)); + function hash(a,b=0){let n=Math.imul(a|0,374761393)^Math.imul(b|0,668265263);n=Math.imul(n^(n>>>13),1274126177);return ((n^(n>>>16))>>>0)/4294967296;} + // Template primitives, used only on the CPU while merging (never uploaded). + const P={box:new T.BoxGeometry(1,1,1),ball:new T.IcosahedronGeometry(1,1),gem:new T.IcosahedronGeometry(1,0),oct:new T.OctahedronGeometry(1,0), + cyl:(rt,rb,h,s=7)=>new T.CylinderGeometry(rt,rb,h,s,1),cone:(r,h,s=7)=>new T.ConeGeometry(r,h,s,1),disc:new T.CylinderGeometry(1,1,1,12,1)}; + // Mesher: merges primitives with per-face colours (slight jitter gives faceted fabric/fur/stone) and optional bone index. + class Mesher{ + constructor(){this.p=[];this.c=[];this.k=[];} + add(geo,color,m,bone=0,jitter=0){const g=geo.index?geo.toNonIndexed():geo.clone();g.applyMatrix4(m);const a=g.attributes.position.array,base=new T.Color(color),col=new T.Color(); + for(let i=0;i{const g=P.cyl(r0,r1,len,s);g.translate(0,-len/2,0);return g;}; + function canvasTexture(size,paint,repeat=1){const c=document.createElement('canvas');c.width=c.height=size;paint(c.getContext('2d'),size);const t=new T.CanvasTexture(c);t.colorSpace=T.SRGBColorSpace;t.wrapS=t.wrapT=T.RepeatWrapping;t.repeat.set(repeat,repeat);t.anisotropy=4;return t;} + function glowTexture(){return canvasTexture(64,(q,s)=>{const g=q.createRadialGradient(s/2,s/2,0,s/2,s/2,s/2);for(let i=0;i<=16;i++){const r=i/16,v=(r<.25?1-r*1.8:.55*(1-r)/.75)*(1-r*r*r*r);g.addColorStop(r,'rgba(255,255,255,'+v.toFixed(4)+')');}q.fillStyle=g;q.fillRect(0,0,s,s);});} + + /* ------------------------------------------------------------------ humanoid rig */ + const HUMAN=[['root',null,[0,0,0]],['hips','root',[0,.94,0]],['spine','hips',[0,.12,0]],['chest','spine',[0,.22,0]],['neck','chest',[0,.24,0]],['head','neck',[0,.08,0]], + ['lSh','chest',[.2,.17,0]],['lEl','lSh',[0,-.29,0]],['lWr','lEl',[0,-.25,0]],['rSh','chest',[-.2,.17,0]],['rEl','rSh',[0,-.29,0]],['rWr','rEl',[0,-.25,0]], + ['lHip','hips',[.1,-.03,0]],['lKnee','lHip',[0,-.44,0]],['lAnk','lKnee',[0,-.42,0]],['rHip','hips',[-.1,-.03,0]],['rKnee','rHip',[0,-.44,0]],['rAnk','rKnee',[0,-.42,0]], + ['blade','rWr',[0,-.07,.02]],['scab','hips',[.17,.02,-.04]],['tool','lWr',[0,-.06,.03]],['back','chest',[0,.06,-.16]],['tail','head',[0,.1,-.1]],['armor','chest',[0,0,0]],['skirt','hips',[0,0,0]],['sodeL','lSh',[0,0,0]],['sodeR','rSh',[0,0,0]]]; + function rig(bonesSpec){const bones={},list=[];for(const [name,parent,o] of bonesSpec){const b=new T.Bone();b.name=name;b.position.set(...o);if(parent)bones[parent].add(b);bones[name]=b;list.push(b);} + list[0].updateMatrixWorld(true);return {bones,list};} + function skinned(scene,r,build,{scale=1,roughness=.82,metalness=.05,shadow=true}={}){const m=new Mesher(),idx=n=>r.list.indexOf(r.bones[n]); + build((bone,geo,color,mat,jitter=0)=>{const bm=r.bones[bone].matrixWorld;m.add(geo,color,new T.Matrix4().multiplyMatrices(bm,mat),idx(bone),jitter);}); + const geo=scene.keep(m.geometry(true)),mat=scene.keep(new T.MeshStandardMaterial({vertexColors:true,flatShading:true,roughness,metalness})); + const mesh=new T.SkinnedMesh(geo,mat);mesh.add(r.list[0]);mesh.updateMatrixWorld(true);mesh.bind(new T.Skeleton(r.list));mesh.frustumCulled=false;mesh.castShadow=shadow;mesh.receiveShadow=false; + const holder=new T.Group();holder.add(mesh);holder.scale.setScalar(scale);return {holder,mesh,bones:r.bones,mat};} + // Shared limb kit for the three humans. + function limbs(add,c){ + add('lSh',seg(.3,.072,.06),c.sleeveL,M4(),.06);add('rSh',seg(.3,.072,.06),c.sleeveR,M4(),.06); + add('lEl',seg(.26,.058,.046),c.foreL,M4(),.04);add('rEl',seg(.26,.058,.046),c.foreR,M4(),.04); + add('lWr',P.ball,c.handL,M4(0,-.05,0,0,0,0,.05,.065,.045));add('rWr',P.ball,c.handR,M4(0,-.05,0,0,0,0,.05,.065,.045)); + for(const s of ['l','r']){add(s+'Hip',seg(.45,c.thighR||.1,c.thighR2||.085),c.thigh,M4(),.05);add(s+'Knee',seg(.42,.07,.055),c.shin,M4(),.04); + add(s+'Ank',P.box,c.foot,M4(0,-.05,.06,0,0,0,.1,.07,.24),.03);} + } + function katana(add,bone,steel=0xd9dde2){add(bone,P.box,0x17171a,M4(0,.1,0,0,0,0,.032,.24,.032));add(bone,P.disc,0x2a2622,M4(0,-.025,0,0,0,0,.06,.018,.06)); + add(bone,P.box,steel,M4(0,-.5,0,0,0,0,.012,.92,.034));add(bone,P.cone(.018,.07,4),steel,M4(0,-.995,0,Math.PI,0,0,1,1,.5));} + function sekiroModel(scene){const r=rig(HUMAN),c={sleeveL:0x3a3631,sleeveR:0x403b35,foreL:0x6e5b3a,foreR:0x3b3733,handL:0x4a4a4f,handR:0xb89377,thigh:0x3c3833,shin:0x9a9182,foot:0x2a2622,thighR:.12,thighR2:.115}; + return skinned(scene,r,add=>{ + add('hips',P.box,0x37332e,M4(0,-.02,0,0,0,0,.34,.18,.22),.04);add('spine',P.box,0x2f2c29,M4(0,.04,0,0,0,0,.32,.16,.2),.04);add('spine',P.box,0x1e1c1b,M4(0,.0,0,0,0,0,.34,.06,.22)); + add('chest',P.box,0x403a33,M4(0,.1,0,0,0,0,.4,.3,.23),.05);add('chest',P.box,0x8b8476,M4(.05,.16,.112,0,0,.5,.05,.24,.02));add('chest',P.box,0x8b8476,M4(-.05,.16,.112,0,0,-.5,.05,.24,.02)); + // ash scarf wrapped at the neck, its tail streaming behind + add('chest',P.cyl(.14,.17,.13,8),0xa69f92,M4(0,.27,-.01),.08);add('back',P.box,0xa69f92,M4(.06,-.14,0,.25,0,.15,.12,.34,.025),.08);add('back',P.box,0x989183,M4(-.04,-.22,-.02,.35,0,-.1,.09,.38,.02),.08); + add('neck',P.cyl(.05,.055,.1,6),0xb08c70,M4(0,.03,0));add('head',P.ball,0xb89377,M4(0,.1,.01,0,0,0,.1,.12,.105),.03); + add('head',P.ball,0x1c1917,M4(0,.165,-.04,0,0,0,.108,.085,.1),.06);add('head',P.box,0x1c1917,M4(0,.12,-.085,0,0,0,.17,.12,.06),.06);add('head',P.box,0x1c1917,M4(0,.22,-.07,-.5,0,0,.08,.1,.06),.06);add('tail',P.cone(.045,.22,5),0x1c1917,M4(0,.04,-.04,-2.2,0,0),.06); + add('head',P.box,0x241d1a,M4(.035,.115,.105,0,0,0,.028,.012,.01));add('head',P.box,0x241d1a,M4(-.035,.115,.105,0,0,0,.028,.012,.01)); + limbs(add,c); + // Shinobi prosthetic: brass and iron bands over the left forearm + for(let i=0;i<3;i++)add('lEl',P.cyl(.064,.064,.03,8),i%2?0x4b4c52:0x8d7442,M4(0,-.06-i*.07,0)); + katana(add,'blade');add('scab',P.box,0x141416,M4(0,0,0,0,0,0,.035,.9,.045),0);add('tool',P.ball,0x8a5a2b,M4(0,-.04,.02,0,0,0,.06,.08,.06)); + },{roughness:.86});} + function genichiroModel(scene){const r=rig(HUMAN),c={sleeveL:0xd4d0c6,sleeveR:0xd4d0c6,foreL:0x23232a,foreR:0x23232a,handL:0xb68c71,handR:0xb68c71,thigh:0x1b1b20,shin:0x26262c,foot:0x161618,thighR:.115,thighR2:.105}; + return skinned(scene,r,add=>{ + add('hips',P.box,0x1d1d22,M4(0,-.02,0,0,0,0,.35,.18,.23),.03);add('spine',P.box,0xd6d1c4,M4(0,.04,0,0,0,0,.32,.16,.2),.03);add('spine',P.box,0x2a2730,M4(0,0,0,0,0,0,.34,.06,.22)); + add('chest',P.box,0xd6d1c4,M4(0,.1,0,0,0,0,.39,.3,.23),.03);add('chest',P.box,0x1d1d22,M4(0,.13,.115,0,0,0,.08,.22,.01)); + add('neck',P.cyl(.05,.056,.1,6),0xb38a6f,M4(0,.03,0));add('head',P.ball,0xb68c71,M4(0,.1,.01,0,0,0,.1,.125,.105),.03); + add('head',P.ball,0x121214,M4(0,.165,-.045,0,0,0,.11,.085,.1),.05);add('head',P.box,0x121214,M4(0,.11,-.09,0,0,0,.18,.13,.06),.05);add('tail',P.box,0x121214,M4(0,-.1,-.02,.3,0,0,.06,.32,.04),.05); + add('head',P.box,0x2a1d1a,M4(.035,.115,.105,0,0,0,.03,.012,.01));add('head',P.box,0x2a1d1a,M4(-.035,.115,.105,0,0,0,.03,.012,.01)); + limbs(add,c);katana(add,'blade');add('scab',P.box,0x101012,M4(0,0,0,0,0,0,.036,.92,.046)); + // black lacquered armour with crimson lacing (removed for the Way of Tomoe) + add('armor',P.box,0x18181c,M4(0,.1,.005,0,0,0,.43,.31,.26),.04);add('armor',P.box,0x18181c,M4(0,.27,.0,0,0,0,.36,.06,.24),.04); + for(let i=0;i<4;i++)add('armor',P.box,0x8a2424,M4(0,-.01+i*.075,.133,0,0,0,.41,.014,.004)); + for(const [bone,s] of [['sodeL',1],['sodeR',-1]])for(let i=0;i<3;i++)add(bone,P.box,i%2?0x22222a:0x18181c,M4(s*.07,-.04-i*.075,0,0,0,s*.25,.05,.09,.24),.03),add(bone,P.box,0x8a2424,M4(s*.095,-.08-i*.075,0,0,0,s*.25,.004,.012,.24)); + for(const [x,z,ry] of [[0,.12,0],[0,-.12,0],[.15,0,1.57],[-.15,0,1.57]])for(let i=0;i<2;i++)add('skirt',P.box,i?0x7c2222:0x18181c,M4(x,-.14-i*.1,z,ry?0:(z>0?-.12:.12),ry,ry?(x>0?.12:-.12):0,.2,i?.012:.12,.03)); + // the great bow: in the left hand for shots, slung across the back otherwise + for(const bone of ['tool','back'])for(let i=-5;i<=5;i++){const a=i*.19,y=Math.sin(a)*.75,z=(Math.cos(a)-1)*.22;add(bone,P.box,0x221a14,M4(0,y+(bone==='back'?.05:0),z,-a,0,0,.022,.15,.03));} + add('tool',P.box,0xe8e2d4,M4(0,0,-.26,0,0,0,.004,1.45,.004)); + },{roughness:.6,metalness:.15});} + function isshinModel(scene){const r=rig([...HUMAN,['spear','rWr',[0,-.07,.02]],['gun','rWr',[0,-.07,.02]]]),c={sleeveL:0xc9c3b4,sleeveR:0xc9c3b4,foreL:0xa98a6e,foreR:0xa98a6e,handL:0xa98a6e,handR:0xa98a6e,thigh:0x34343c,shin:0x2b2b33,foot:0x1c1c20,thighR:.13,thighR2:.125}; + return skinned(scene,r,add=>{ + add('hips',P.box,0x2d2d35,M4(0,-.02,0,0,0,0,.36,.2,.25),.03);add('spine',P.box,0xa98a6e,M4(0,.04,0,0,0,0,.3,.16,.19),.03);add('spine',P.box,0x7a2a26,M4(0,-.04,0,0,0,0,.33,.07,.22)); + // the robe worn off the left shoulder over a bare, scarred chest + add('chest',P.box,0xa98a6e,M4(0,.1,0,0,0,0,.38,.3,.22),.03);add('chest',P.box,0xc9c3b4,M4(-.09,.1,.005,0,0,0,.22,.31,.235),.04);add('chest',P.box,0x8d6f58,M4(.08,.14,.113,0,0,.7,.012,.2,.004)); + add('neck',P.cyl(.052,.058,.1,6),0xa98a6e,M4(0,.03,0));add('head',P.ball,0xad8e72,M4(0,.1,.01,0,0,0,.1,.125,.105),.03); + // long white hair tied back, heavy brows and beard + add('head',P.ball,0xe6e3da,M4(0,.165,-.04,0,0,0,.115,.09,.105),.05);add('head',P.box,0xe6e3da,M4(0,.11,-.09,0,0,0,.19,.15,.06),.05);add('tail',P.box,0xe6e3da,M4(0,-.2,-.03,.25,0,0,.09,.52,.05),.06); + add('head',P.box,0xe6e3da,M4(0,.035,.09,.25,0,0,.1,.09,.04),.05);add('head',P.box,0xe6e3da,M4(.035,.118,.105,0,0,0,.038,.016,.012));add('head',P.box,0xe6e3da,M4(-.035,.118,.105,0,0,0,.038,.016,.012)); + limbs(add,c);katana(add,'blade');add('scab',P.box,0x1a1416,M4(0,0,0,0,0,0,.036,.92,.046)); + // wide hakama + for(const [x,z,ry] of [[0,.13,0],[0,-.13,0],[.17,0,1.57],[-.17,0,1.57]])for(let i=0;i<2;i++)add('skirt',P.box,i?0x26262d:0x34343c,M4(x,-.16-i*.17,z,ry?0:(z>0?-.1:.1),ry,ry?(x>0?.1:-.1):0,.24,.2,.03),.03); + // the long spear: held in the right hand, slung across the back between its moves + for(const [bone,o] of [['spear',[0,-.65,0]],['back',[0,0,0]]]){const tilt=bone==='back'?.5:0; + add(bone,P.box,0x3a2a1c,M4(o[0],o[1],o[2],0,0,tilt,.024,2.0,.024),.04);add(bone,P.box,0xd9dde2,M4(o[0]+Math.sin(tilt)*1.12,o[1]-Math.cos(tilt)*1.12,o[2],0,0,tilt,.012,.3,.05));add(bone,P.box,0xd9dde2,M4(o[0]+Math.sin(tilt)*1.02,o[1]-Math.cos(tilt)*1.02,o[2],0,0,tilt+1.57,.012,.26,.03));} + // the matchlock pistol + add('gun',P.box,0x2a1e16,M4(0,-.02,.02,0,0,0,.05,.13,.06));add('gun',P.box,0x24242a,M4(0,-.26,.03,0,0,0,.03,.42,.03));add('gun',P.box,0x8d7442,M4(0,-.1,.03,0,0,0,.042,.03,.042)); + },{roughness:.72,metalness:.08});} + function gyoubuModel(scene){const r=rig([...HUMAN,['spear','rWr',[0,-.07,.02]],['hBody','root',[0,1.32,0]],['hNeck','hBody',[0,.12,.72]],['hFL','hBody',[.2,-.1,.62]],['hFR','hBody',[-.2,-.1,.62]],['hBL','hBody',[.2,-.1,-.62]],['hBR','hBody',[-.2,-.1,-.62]]]),c={sleeveL:0x3a1416,sleeveR:0x3a1416,foreL:0x2a2024,foreR:0x2a2024,handL:0x8d6f58,handR:0x8d6f58,thigh:0x2d2226,shin:0x241c20,foot:0x151214,thighR:.12,thighR2:.1}; + return skinned(scene,r,add=>{ + // the rider: lacquered armour over crimson, a horned helm and a heavy beard + add('hips',P.box,0x2d2226,M4(0,-.02,0,0,0,0,.36,.2,.25),.03);add('spine',P.box,0x4a1a1c,M4(0,.04,0,0,0,0,.33,.17,.21),.03);add('chest',P.box,0x1f1c20,M4(0,.1,0,0,0,0,.42,.32,.26),.04); + for(let i=0;i<3;i++)add('chest',P.box,0x8a2424,M4(0,.0+i*.09,.134,0,0,0,.4,.016,.004)); + add('neck',P.cyl(.055,.06,.1,6),0x8d6f58,M4(0,.03,0));add('head',P.ball,0x94745c,M4(0,.1,.01,0,0,0,.11,.13,.11),.03);add('head',P.box,0x141214,M4(0,.03,.08,.2,0,0,.13,.11,.05),.05); + add('head',P.ball,0x1a181c,M4(0,.17,0,0,0,0,.135,.085,.13),.04);add('head',P.box,0x1a181c,M4(0,.13,-.02,0,0,0,.34,.018,.3));for(const s of [1,-1])add('head',P.cone(.03,.26,5),0xb09050,M4(s*.11,.29,.03,0,0,-s*.42)); + limbs(add,c);katana(add,'blade');add('scab',P.box,0x141214,M4(0,0,0,0,0,0,.036,.92,.046)); + // the long spear + add('spear',P.box,0x2c2118,M4(0,-.75,0,0,0,0,.028,2.5,.028),.04);add('spear',P.box,0xd9dde2,M4(0,-2.14,0,0,0,0,.014,.34,.06));add('spear',P.box,0xd9dde2,M4(0,-2.02,0,0,0,1.57,.014,.34,.035)); + // Onikage: a big dark horse with a red harness + add('hBody',P.box,0x201a1a,M4(0,0,0,0,0,0,.46,.5,1.5),.05);add('hBody',P.box,0x2a2120,M4(0,.04,-.62,0,0,0,.48,.52,.42),.05);add('hBody',P.box,0x6e1a1c,M4(0,.27,-.05,0,0,0,.5,.06,.62),.03); + add('hBody',P.box,0x141010,M4(0,.12,-.92,-.5,0,0,.08,.08,.62),.06); + add('hNeck',P.box,0x201a1a,M4(0,.22,.14,-.75,0,0,.2,.34,.7),.05);add('hNeck',P.box,0x141010,M4(0,.36,.02,-.75,0,0,.05,.3,.66),.06);add('hNeck',P.box,0x241d1c,M4(0,.54,.5,.35,0,0,.18,.2,.46),.05);for(const s of [1,-1])add('hNeck',P.cone(.03,.13,4),0x201a1a,M4(s*.06,.7,.36));add('hNeck',P.box,0x6e1a1c,M4(0,.56,.5,.35,0,0,.2,.03,.3)); + for(const [bone,s] of [['hFL',1],['hFR',-1],['hBL',1],['hBR',-1]]){add(bone,seg(.62,.075,.05),0x201a1a,M4(),.05);add(bone,seg(.56,.05,.04),0x1a1515,M4(0,-.58,0),.05);add(bone,P.box,0x0e0c0c,M4(0,-1.14,.02,0,0,0,.09,.07,.13));} + },{roughness:.68,metalness:.1});} + function butterflyModel(scene){const r=rig(HUMAN),c={sleeveL:0x574263,sleeveR:0x574263,foreL:0x574263,foreR:0x574263,handL:0xd8c2ad,handR:0xd8c2ad,thigh:0x382b40,shin:0xe9e3d8,foot:0xe9e3d8,thighR:.1,thighR2:.09}; + return skinned(scene,r,add=>{ + add('hips',P.box,0x4b3956,M4(0,-.02,0,0,0,0,.3,.17,.2),.05);add('spine',P.box,0x8a7d9a,M4(0,.03,0,0,0,0,.31,.14,.2),.04); + add('chest',P.box,0x574263,M4(0,.09,0,0,0,0,.33,.26,.2),.06);add('chest',P.box,0xcfc6d4,M4(.04,.15,.1,0,0,.5,.04,.2,.02));add('chest',P.box,0xcfc6d4,M4(-.04,.15,.1,0,0,-.5,.04,.2,.02)); + // butterfly crests on the sleeves and back + for(const [b,x] of [['lSh',.07],['rSh',-.07]])add(b,P.oct,0xe0ccff,M4(x,-.16,0,0,0,.8,.05,.035,.02));add('back',P.oct,0xe0ccff,M4(0,-.08,-.01,0,0,.8,.1,.06,.02));add('hips',P.oct,0xe0ccff,M4(.12,-.06,.1,0,0,.8,.05,.03,.02)); + add('neck',P.cyl(.045,.05,.09,6),0xd2bba6,M4(0,.03,0));add('head',P.ball,0xd8c2ad,M4(0,.1,.01,0,0,0,.092,.112,.098),.03); + add('head',P.ball,0xe8e6e2,M4(0,.16,-.04,0,0,0,.1,.08,.095),.05);add('head',P.box,0xe8e6e2,M4(0,.11,-.08,0,0,0,.16,.11,.05),.05);add('tail',P.ball,0xe8e6e2,M4(0,.04,-.04,0,0,0,.075,.065,.07),.05);add('tail',P.box,0x8d6a2c,M4(0,.05,-.05,0,0,1.3,.008,.18,.008)); + add('head',P.box,0x5a4038,M4(.03,.11,.095,0,0,0,.024,.01,.01));add('head',P.box,0x5a4038,M4(-.03,.11,.095,0,0,0,.024,.01,.01)); + limbs(add,c); + for(const b of ['blade','tool'])add(b,P.box,0x2c2c32,M4(0,-.14,0,0,0,0,.016,.22,.03)); + },{scale:.93,roughness:.8});} + // Guardian Ape: hunched white beast (S14: white fur, a red scar across the left eye, a nodachi through the neck). + const APE_BONES=[['root',null,[0,0,0]],['hips','root',[0,1.25,0]],['spine','hips',[0,.42,.12]],['chest','spine',[0,.5,.1]],['neck','chest',[0,.46,.42]],['head','neck',[0,.16,.22]], + ['lSh','chest',[.62,.28,.05]],['lEl','lSh',[0,-.78,0]],['lWr','lEl',[0,-.72,0]],['rSh','chest',[-.62,.28,.05]],['rEl','rSh',[0,-.78,0]],['rWr','rEl',[0,-.72,0]], + ['lHip','hips',[.32,-.08,0]],['lKnee','lHip',[0,-.6,0]],['lAnk','lKnee',[0,-.55,0]],['rHip','hips',[-.32,-.08,0]],['rKnee','rHip',[0,-.6,0]],['rAnk','rKnee',[0,-.55,0]], + ['neckBlade','neck',[0,.06,0]],['blade','rWr',[0,-.16,0]],['held','lWr',[0,-.2,.1]],['stump','neck',[0,.04,.04]]]; + function apeModel(scene){const r=rig(APE_BONES),fur=0xdedbd0,furD=0xbdb8ab,skin=0x8f4336; + return skinned(scene,r,add=>{ + add('hips',P.ball,furD,M4(0,.05,0,0,0,0,.52,.42,.46),.12);add('spine',P.ball,fur,M4(0,.12,0,0,0,0,.66,.55,.55),.12);add('chest',P.ball,fur,M4(0,.12,0,0,0,0,.82,.62,.62),.12); + add('chest',P.ball,0xc9a99a,M4(0,.0,.38,0,0,0,.45,.4,.2),.06); + for(let i=0;i<14;i++){const a=i/14*Math.PI*2;add('neck',P.cone(.14,.5,5),i%2?fur:furD,M4(Math.sin(a)*.35,.05,Math.cos(a)*.3-.05,Math.cos(a)*.9,0,-Math.sin(a)*.9),.15);} + add('head',P.ball,fur,M4(0,.12,-.02,0,0,0,.33,.32,.32),.12);add('head',P.ball,skin,M4(0,.08,.2,0,0,0,.22,.2,.16),.05); + add('head',P.box,0x2a1713,M4(.09,.15,.33,0,0,0,.05,.02,.02));add('head',P.box,0x2a1713,M4(-.09,.15,.33,0,0,0,.05,.02,.02));add('head',P.box,0xb3201a,M4(.1,.16,.34,0,0,1.1,.016,.13,.012)); + add('head',P.box,0x3b1b16,M4(0,-.02,.32,0,0,0,.12,.03,.03)); + for(const s of ['l','r']){add(s+'Sh',P.ball,fur,M4(0,-.05,0,0,0,0,.3,.3,.3),.12);add(s+'Sh',seg(.8,.24,.19),fur,M4(),.14);add(s+'El',seg(.72,.18,.15),furD,M4(),.14); + add(s+'Wr',P.ball,0x4a3b35,M4(0,-.1,.02,0,0,0,.17,.14,.2),.06); + add(s+'Hip',seg(.6,.26,.2),fur,M4(),.14);add(s+'Knee',seg(.55,.18,.14),furD,M4(),.14);add(s+'Ank',P.box,0x4a3b35,M4(0,-.06,.12,0,0,0,.22,.12,.4),.05);} + // the nodachi through its neck (phase 1) and the same blade in its right hand (headless phase) + add('neckBlade',P.box,0xcfd3d8,M4(0,0,0,0,0,1.5,.04,2.4,.1));add('neckBlade',P.box,0x2b2018,M4(-1.25,.02,0,0,0,1.5,.06,.4,.06)); + add('blade',P.box,0xcfd3d8,M4(0,-1.3,.0,0,0,0,.05,2.6,.12));add('blade',P.box,0x2b2018,M4(0,.05,0,0,0,0,.07,.42,.07)); + add('held',P.ball,fur,M4(0,0,0,0,0,0,.3,.28,.28),.12);add('held',P.ball,skin,M4(0,-.04,.18,0,0,0,.2,.18,.14),.05);add('held',P.box,0xb3201a,M4(.08,.02,.31,0,0,1.1,.016,.12,.012)); + add('stump',P.cyl(.24,.27,.12,8),0x7d1414,M4(0,0,0),.1);for(let i=0;i<6;i++)add('stump',P.ball,i%2?0x2a1712:0x4d2a1d,M4(Math.sin(i*1.1)*.05,.1+i*.07,Math.cos(i*1.3)*.04,0,0,0,.06,.045,.06)); + },{roughness:.95});} + + // The Demon of Hatred: a hulking burnt-red ogre with a horned head, a fire-wreathed left arm and a ragged cape (original procedural art). + const DEMON_BONES=APE_BONES.filter(([n])=>!['neckBlade','blade','held','stump'].includes(n)).map(([n,p,o])=>[n,p,n==='hips'?[0,1.9,0]:n==='lKnee'||n==='rKnee'?[0,-.9,0]:n==='lAnk'||n==='rAnk'?[0,-.85,0]:n==='lEl'||n==='rEl'?[0,-1.05,0]:n==='lWr'||n==='rWr'?[0,-.95,0]:n==='lSh'?[.85,.4,.05]:n==='rSh'?[-.85,.4,.05]:n==='chest'?[0,.6,.1]:n==='spine'?[0,.5,.1]:o]).concat([['flame','lWr',[0,-.2,0]],['cape','chest',[0,.3,-.4]]]); + function demonModel(scene){const r=rig(DEMON_BONES),skin=0x9a4634,dark=0x5a3026,horn=0xe6d6b0,ash=0x6a5e56; + return skinned(scene,r,add=>{ + add('hips',P.ball,dark,M4(0,.05,0,0,0,0,.7,.5,.58),.1);add('spine',P.ball,skin,M4(0,.12,0,0,0,0,.85,.62,.66),.12);add('chest',P.ball,skin,M4(0,.15,0,0,0,0,1.05,.75,.78),.12); + for(let i=0;i<5;i++)add('chest',P.box,0x1d1210,M4(-.4+i*.2,.1,.68,0,0,(i-2)*.25,.04,.5,.04)); + add('neck',P.ball,skin,M4(0,.1,.1,0,0,0,.42,.38,.42),.1);add('head',P.ball,0x6a3026,M4(0,.15,.1,0,0,0,.4,.36,.4),.1);add('head',P.box,0x1a0d0b,M4(0,.02,.42,0,0,0,.36,.12,.1)); + for(const s of [1,-1]){add('head',P.box,0xffb040,M4(s*.14,.2,.46,0,0,0,.08,.035,.02));add('head',P.cone(.1,.62,5),horn,M4(s*.3,.42,0,-.3,0,-s*.7),.05);add('head',P.cone(.06,.32,5),horn,M4(s*.18,.48,.18,.4,0,-s*.3),.04);} + for(let i=0;i<9;i++){const a=(i/8-.5)*2.2;add('head',P.cone(.1,.5,4),0xd8d0c0,M4(Math.sin(a)*.38,.25-Math.abs(a)*.08,-.22,-.9-Math.abs(a)*.2,0,-a*.6),.12);} + for(const s of ['l','r']){add(s+'Sh',P.ball,skin,M4(0,-.05,0,0,0,0,.42,.42,.42),.1);add(s+'Sh',seg(1.05,.3,.24),s==='l'?0x3a1610:skin,M4(),.12);add(s+'El',seg(.95,.24,.19),s==='l'?0x241008:dark,M4(),.12); + add(s+'Wr',P.ball,0x1d100c,M4(0,-.14,.03,0,0,0,.24,.2,.28),.06);for(let k=0;k<3;k++)add(s+'Wr',P.cone(.04,.22,4),horn,M4((k-1)*.1,-.36,.1,.3,0,0)); + add(s+'Hip',seg(.9,.32,.26),dark,M4(),.12);add(s+'Knee',seg(.85,.24,.2),skin,M4(),.12);add(s+'Ank',P.box,0x1d100c,M4(0,-.08,.16,0,0,0,.34,.16,.56),.05);} + // the burning left arm: glowing cracks and a crown of flame at the fist + for(let i=0;i<6;i++)add('lEl',P.box,0xff7a2a,M4(Math.sin(i*1.7)*.18,-.15-i*.13,.18,0,0,i*.4,.03,.16,.02)); + for(let i=0;i<7;i++){const a=i/7*Math.PI*2;add('flame',P.cone(.12,.55,5),i%2?0xff9a32:0xffd060,M4(Math.sin(a)*.14,.1,Math.cos(a)*.14,Math.cos(a)*.5,0,-Math.sin(a)*.5));} + for(let i=0;i<5;i++)add('cape',P.box,i%2?ash:0x2a2420,M4(-.6+i*.3,-.9,0,.15,0,(i-2)*.08,.32,1.8,.04),.15); + },{roughness:.9});} + /* ------------------------------------------------------------------ poses */ + const J=['hips','spine','chest','neck','head','lSh','lEl','lWr','rSh','rEl','rWr','lHip','lKnee','lAnk','rHip','rKnee','rAnk','blade']; + const pose=o=>{const p={y:0,lean:0};for(const j of J)p[j]=o[j]||[0,0,0];if('y' in o)p.y=o.y;return p;}; + function mixPose(a,b,u){if(u<=0)return a;if(u>=1)return b;const p={y:lerp(a.y,b.y,u)};for(const j of J)p[j]=[lerp(a[j][0],b[j][0],u),lerp(a[j][1],b[j][1],u),lerp(a[j][2],b[j][2],u)];return p;} + const add3=(p,j,v)=>{p[j]=[p[j][0]+v[0],p[j][1]+v[1],p[j][2]+v[2]];}; + // Shared human poses. Arms hang along -Y; negative shoulder X raises an arm forward; the blade runs along the hand. + const H={ + stance:pose({y:-.05,spine:[.1,0,0],chest:[.04,.2,0],head:[-.06,-.15,0],rSh:[-.45,0,-.28],rEl:[-.75,0,0],rWr:[-.85,0,0],lSh:[-.35,0,.2],lEl:[-.9,0,0], + lHip:[-.32,0,.06],lKnee:[.5,0,0],lAnk:[-.18,0,0],rHip:[.15,0,-.08],rKnee:[.4,0,0],rAnk:[-.25,0,0]}), + guard:pose({y:-.08,spine:[.12,0,0],chest:[.05,.35,0],head:[-.05,-.3,0],rSh:[-1.25,0,-.15],rEl:[-1.05,0,0],rWr:[-.25,0,1.35],lSh:[-.9,0,.25],lEl:[-1.3,0,0], + lHip:[-.35,0,.06],lKnee:[.55,0,0],lAnk:[-.2,0,0],rHip:[.2,0,-.08],rKnee:[.45,0,0],rAnk:[-.25,0,0]}), + raise:pose({y:-.04,spine:[-.05,0,0],chest:[-.05,.55,0],head:[0,-.4,0],rSh:[-2.55,0,-.35],rEl:[-.55,0,0],rWr:[-.2,0,0],lSh:[-.6,0,.3],lEl:[-.8,0,0], + lHip:[-.3,0,.06],lKnee:[.4,0,0],lAnk:[-.15,0,0],rHip:[.25,0,-.08],rKnee:[.35,0,0],rAnk:[-.2,0,0]}), + cut:pose({y:-.12,spine:[.3,0,0],chest:[.15,-.65,0],head:[-.1,.45,0],rSh:[-.75,0,.55],rEl:[-.15,0,0],rWr:[-.25,0,0],lSh:[-.2,0,.45],lEl:[-.5,0,0], + lHip:[-.6,0,.06],lKnee:[.7,0,0],lAnk:[-.15,0,0],rHip:[.35,0,-.08],rKnee:[.25,0,0],rAnk:[-.3,0,0]}), + backRaise:pose({y:-.05,chest:[0,-.6,0],head:[0,.45,0],rSh:[-1.6,0,.9],rEl:[-1.2,0,0],rWr:[-.3,0,0],lSh:[-.4,0,.3],lEl:[-.7,0,0],lHip:[-.3,0,.06],lKnee:[.4,0,0],rHip:[.2,0,-.08],rKnee:[.35,0,0]}), + backCut:pose({y:-.1,spine:[.2,0,0],chest:[.1,.7,0],head:[-.05,-.45,0],rSh:[-1.25,0,-1.0],rEl:[-.2,0,0],rWr:[-.3,0,0],lSh:[-.3,0,.3],lEl:[-.6,0,0],lHip:[-.5,0,.06],lKnee:[.6,0,0],rHip:[.3,0,-.08],rKnee:[.3,0,0]}), + pull:pose({y:-.1,spine:[.2,0,0],chest:[.1,.6,0],head:[-.05,-.5,0],rSh:[-.25,0,-.35],rEl:[-1.7,0,0],rWr:[-1.35,0,0],lSh:[-.8,0,.3],lEl:[-.9,0,0],lHip:[-.45,0,.06],lKnee:[.65,0,0],rHip:[.35,0,-.08],rKnee:[.45,0,0],rAnk:[-.3,0,0]}), + lunge:pose({y:-.2,spine:[.35,0,0],chest:[.15,-.25,0],head:[-.2,.2,0],rSh:[-1.55,0,0],rEl:[-.05,0,0],rWr:[-1.55,0,0],lSh:[.3,0,.35],lEl:[-.3,0,0],lHip:[-.95,0,.06],lKnee:[1.0,0,0],lAnk:[-.1,0,0],rHip:[.55,0,-.08],rKnee:[.15,0,0],rAnk:[-.3,0,0]}), + low:pose({y:-.42,spine:[.55,0,0],chest:[.15,.5,0],head:[-.35,-.4,0],rSh:[-.5,0,-.9],rEl:[-.2,0,0],rWr:[-1.4,0,0],lSh:[-.4,0,.4],lEl:[-.6,0,0],lHip:[-1.1,0,.2],lKnee:[1.45,0,0],lAnk:[-.35,0,0],rHip:[.3,0,-.3],rKnee:[1.2,0,0],rAnk:[-.2,0,0]}), + lowCut:pose({y:-.42,spine:[.55,0,0],chest:[.15,-.75,0],head:[-.35,.4,0],rSh:[-.6,0,.95],rEl:[-.1,0,0],rWr:[-1.45,0,0],lSh:[-.2,0,.6],lEl:[-.4,0,0],lHip:[-1.1,0,.2],lKnee:[1.45,0,0],lAnk:[-.35,0,0],rHip:[.3,0,-.3],rKnee:[1.2,0,0],rAnk:[-.2,0,0]}), + overhead:pose({y:0,spine:[-.15,0,0],chest:[-.1,0,0],head:[.1,0,0],rSh:[-2.9,0,-.1],rEl:[-.2,0,0],rWr:[-.3,0,0],lSh:[-2.8,0,.1],lEl:[-.3,0,0],lHip:[-.2,0,.06],lKnee:[.3,0,0],rHip:[.1,0,-.06],rKnee:[.3,0,0]}), + chop:pose({y:-.25,spine:[.6,0,0],chest:[.2,0,0],head:[-.4,0,0],rSh:[-1.1,0,-.05],rEl:[-.1,0,0],rWr:[-.6,0,0],lSh:[-1.1,0,.05],lEl:[-.1,0,0],lHip:[-.8,0,.06],lKnee:[.9,0,0],rHip:[.4,0,-.06],rKnee:[.3,0,0]}), + reach:pose({y:-.15,spine:[.45,0,0],chest:[.1,-.3,0],head:[-.3,.2,0],lSh:[-1.5,0,.1],lEl:[-.1,0,0],rSh:[-.2,0,-.3],rEl:[-.5,0,0],rWr:[-.8,0,0],lHip:[-.9,0,.06],lKnee:[.9,0,0],rHip:[.5,0,-.06],rKnee:[.2,0,0]}), + kick:pose({y:-.02,spine:[-.2,0,0],chest:[-.1,.2,0],rSh:[-.4,0,-.5],rEl:[-.6,0,0],rWr:[-.8,0,0],lSh:[-.4,0,.5],lEl:[-.6,0,0],lHip:[-1.45,0,.05],lKnee:[.1,0,0],lAnk:[.4,0,0],rHip:[.15,0,-.05],rKnee:[.3,0,0]}), + draw:pose({y:-.02,chest:[0,-.95,0],head:[0,.9,0],lSh:[-1.55,0,.1],lEl:[0,0,0],lWr:[0,0,0],rSh:[-1.5,0,-.3],rEl:[-2.3,0,0],lHip:[-.25,0,.15],lKnee:[.25,0,0],rHip:[.2,0,-.15],rKnee:[.25,0,0]}), + release:pose({y:-.02,chest:[0,-.95,0],head:[0,.9,0],lSh:[-1.55,0,.1],lEl:[0,0,0],rSh:[-1.2,0,-1.1],rEl:[-.6,0,0],lHip:[-.25,0,.15],lKnee:[.25,0,0],rHip:[.2,0,-.15],rKnee:[.25,0,0]}), + tuck:pose({y:.1,spine:[.3,0,0],chest:[.1,0,0],rSh:[-1.2,0,-.4],rEl:[-1.0,0,0],rWr:[-.5,0,0],lSh:[-1.0,0,.4],lEl:[-1.1,0,0],lHip:[-1.4,0,.1],lKnee:[1.9,0,0],rHip:[-1.0,0,-.1],rKnee:[1.7,0,0]}), + hurt:pose({y:-.06,spine:[-.25,0,0],chest:[-.2,.2,0],head:[-.35,0,.15],rSh:[-.2,0,-.7],rEl:[-.4,0,0],rWr:[-.5,0,0],lSh:[-.2,0,.7],lEl:[-.4,0,0],lHip:[.1,0,.1],lKnee:[.3,0,0],rHip:[.35,0,-.1],rKnee:[.3,0,0]}), + kneel:pose({y:-.48,spine:[.55,0,0],chest:[.25,.1,0],head:[.45,0,0],rSh:[-.25,0,-.25],rEl:[-.4,0,0],rWr:[-.2,0,0],lSh:[-.1,0,.25],lEl:[-.4,0,0],lHip:[-1.45,0,.1],lKnee:[1.5,0,0],lAnk:[-.1,0,0],rHip:[.25,0,-.1],rKnee:[1.75,0,0],rAnk:[.3,0,0]}), + drink:pose({y:-.03,spine:[-.05,0,0],chest:[-.1,.1,0],head:[-.45,0,0],lSh:[-1.9,0,.5],lEl:[-1.8,0,0],rSh:[-.3,0,-.25],rEl:[-.4,0,0],rWr:[-.6,0,0],lHip:[-.15,0,.06],lKnee:[.2,0,0],rHip:[.1,0,-.06],rKnee:[.2,0,0]}), + cast:pose({y:-.02,chest:[-.1,-.3,0],head:[-.2,.3,0],rSh:[-2.6,0,-.4],rEl:[-.3,0,0],lSh:[-.9,0,.4],lEl:[-.6,0,0],lHip:[-.2,0,.06],lKnee:[.2,0,0],rHip:[.1,0,-.06],rKnee:[.2,0,0]}), + spread:pose({y:-.02,spine:[-.15,0,0],chest:[-.2,0,0],head:[-.4,0,0],rSh:[-.4,0,-1.4],rEl:[-.2,0,0],lSh:[-.4,0,1.4],lEl:[-.2,0,0],lHip:[-.1,0,.1],rHip:[-.1,0,-.1]}), + hover:pose({y:0,spine:[.1,0,0],chest:[0,0,0],head:[.3,0,0],rSh:[-.9,0,-.9],rEl:[-.6,0,0],rWr:[-.5,0,0],lSh:[-.9,0,.9],lEl:[-.6,0,0],lHip:[-1.2,0,.25],lKnee:[1.6,0,0],rHip:[-.2,0,-.2],rKnee:[.6,0,0]}), + aim:pose({y:-.04,chest:[0,-.5,0],head:[0,.45,0],rSh:[-1.55,0,.2],rEl:[0,0,0],rWr:[-1.5,0,0],lSh:[-.35,0,.3],lEl:[-.7,0,0],lHip:[-.3,0,.1],lKnee:[.35,0,0],rHip:[.2,0,-.1],rKnee:[.3,0,0]}), + dead:pose({y:-.9,spine:[-.2,0,0],head:[-.3,.5,0],rSh:[-.1,0,-1.3],lSh:[-.2,0,1.1],lHip:[-.2,0,.2],lKnee:[.3,0,0],rHip:[.1,0,-.2],rKnee:[.5,0,0]}) + }; + const ISSHIN_SPEAR=/^(spear_|lightning_|three_thrust|retreat_sweep|stomp|double_disc|leap_slam)/; + function walkCycle(p,phase,amount,run){if(amount<=0)return p;const s=Math.sin(phase),c=Math.cos(phase),a=amount*(run?1.15:.75);const q={...p}; + add3(q,'lHip',[-s*a,0,0]);add3(q,'rHip',[s*a,0,0]);add3(q,'lKnee',[Math.max(0,c)*a*1.1,0,0]);add3(q,'rKnee',[Math.max(0,-c)*a*1.1,0,0]); + add3(q,'lSh',[s*a*.5,0,0]);add3(q,'chest',[0,s*a*.18,0]);q.y=p.y+Math.abs(c)*.035*amount-(run?.05:0);if(run)add3(q,'spine',[.18,0,0]);return q;} + // Melee timeline for a move: windup -> strike -> follow-through around each contact tick; alternate fore/back hands. + function strikePose(base,hits,t,o={}){let p=base;const W=o.wind||12,F=o.follow||10; + for(let i=0;ik+F+6)continue;const back=(o.alternate!==false)&&i%2===1; + const type=h.type||'slash',raise=type==='thrust'?H.pull:type==='sweep'?H.low:type==='slam'?H.overhead:type==='grab'?H.stance:type==='kick'?H.stance:back?H.backRaise:H.raise; + const hitP=type==='thrust'?H.lunge:type==='sweep'?H.lowCut:type==='slam'?H.chop:type==='grab'?H.reach:type==='kick'?H.kick:back?H.backCut:H.cut; + if(t{e.preventDefault();this.ready=false;this.error='WebGL context lost';}); + this.world=new T.Scene();this.world.fog=new T.Fog(0xb0a9a3,30,90); + this.camera=new T.PerspectiveCamera(50,854/480,.1,260); + this.hemi=new T.HemisphereLight(0xd8e2f0,0x5a4a3c,1.4);this.world.add(this.hemi); + this.sun=new T.DirectionalLight(0xffe2b5,2.6);this.sun.castShadow=true;this.sun.shadow.mapSize.set(1024,1024); + const sc=this.sun.shadow.camera;sc.left=-14;sc.right=14;sc.top=14;sc.bottom=-14;sc.near=1;sc.far=80;this.sun.shadow.bias=-.0006;this.sun.shadow.normalBias=.03; + this.world.add(this.sun);this.world.add(this.sun.target); + this.flashLight=new T.PointLight(0xffe7b0,0,40,1.6);this.world.add(this.flashLight); + this.glowTex=this.keep(glowTexture()); + this.mats={add:this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:1,blending:T.AdditiveBlending,depthWrite:false,fog:false})), + soft:this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:.55,depthWrite:false})), + solid:this.keep(new T.MeshStandardMaterial({color:0xffffff,roughness:.6,metalness:.2,flatShading:true})), + glow:this.keep(new T.MeshBasicMaterial({map:this.glowTex,color:0xffffff,transparent:true,blending:T.AdditiveBlending,depthWrite:false,fog:false})), + ghost:this.keep(new T.MeshStandardMaterial({color:0x9fd8ff,emissive:0x4a8cc8,emissiveIntensity:.7,transparent:true,opacity:.42,roughness:.4,flatShading:true,depthWrite:false}))}; + this.geo={box:this.keep(new T.BoxGeometry(1,1,1)),ball:this.keep(new T.IcosahedronGeometry(1,0)),ring:this.keep(new T.TorusGeometry(1,.035,4,40)),quad:this.keep(new T.PlaneGeometry(1,1)), + wing:this.keep((()=>{const g=new T.BufferGeometry();g.setAttribute('position',new T.Float32BufferAttribute([0,0,0,.5,.1,.35,.55,.05,-.15, 0,0,0,-.5,.1,.35,-.55,.05,-.15],3));g.computeVertexNormals();return g;})())}; + this.player=sekiroModel(this);this.world.add(this.player.holder); + this.bosses={genichiro:genichiroModel(this),ape:apeModel(this),butterfly:butterflyModel(this),isshin:isshinModel(this),gyoubu:gyoubuModel(this),demon:demonModel(this)};for(const m of Object.values(this.bosses)){m.holder.visible=false;this.world.add(m.holder);} + const sev=new Mesher();sev.add(P.ball,0xdedbd0,M4(0,0,0,0,0,0,.33,.32,.32),0,.12);sev.add(P.ball,0x8f4336,M4(0,-.04,.2,0,0,0,.22,.2,.16),0,.05);sev.add(P.box,0xb3201a,M4(.1,.04,.34,0,0,1.1,.016,.13,.012));sev.add(P.disc,0x7d1414,M4(0,-.3,0,0,0,0,.22,.04,.22)); + this.severed=new T.Mesh(this.keep(sev.geometry()),this.material(0xffffff,{vertex:true,roughness:.95}));this.severed.castShadow=true;this.severed.visible=false;this.world.add(this.severed); + this.ghosts=[];const ghostGeo=this.keep((()=>{const m=new Mesher();m.add(P.cyl(.16,.26,.95,6),0xffffff,M4(0,.6,0));m.add(P.ball,0xffffff,M4(0,1.22,.05,0,0,0,.13,.15,.13));m.add(P.cone(.36,.16,8),0xffffff,M4(0,1.36,.03)); + m.add(seg(.55,.05,.04),0xffffff,M4(.2,1.0,.08,-1.2,0,.2));m.add(P.box,0xffffff,M4(.22,.85,.6,-.2,0,0,.02,.04,.4));return m.geometry();})()); + for(let i=0;i<6;i++){const g=new T.Mesh(ghostGeo,this.mats.ghost);g.visible=false;this.world.add(g);this.ghosts.push(g);} + this.pool=(geo,mat,n)=>{const m=new T.InstancedMesh(geo,mat,n);m.count=0;m.frustumCulled=false;m.instanceColor=new T.InstancedBufferAttribute(new Float32Array(n*3),3);this.world.add(m);this.keep(m);return m;}; + this.fx={spark:this.pool(this.geo.box,this.mats.add,96),flash:this.pool(this.geo.quad,this.mats.glow,24),blood:this.pool(this.geo.ball,this.keep(new T.MeshBasicMaterial({color:0xffffff})),64), + bolt:this.pool(this.geo.box,this.mats.add,90),proj:this.pool(this.geo.box,this.mats.solid,48),wings:this.pool(this.geo.wing,this.keep(new T.MeshBasicMaterial({color:0xffffff,side:T.DoubleSide,transparent:true,opacity:.9,blending:T.AdditiveBlending,depthWrite:false,fog:false})),64), + puff:this.pool(this.geo.ball,this.keep(new T.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:.28,depthWrite:false})),48),rings:this.pool(this.geo.ring,this.mats.add,10), + mote:this.pool(this.geo.ball,this.mats.add,90),leaf:this.pool(this.geo.quad,this.keep(new T.MeshBasicMaterial({color:0xffffff,side:T.DoubleSide})),40),flame:this.pool(this.keep(new T.ConeGeometry(1,1,6)),this.keep(new T.MeshBasicMaterial({color:0xffffff})),260)}; + this.dummy=new T.Object3D();this.tmp=new T.Color(); + // Sword trails: a ribbon per fighter, rebuilt from the pose clock (past ticks are re-evaluated, no history kept). + this.trails=[0,1].map(()=>{const g=this.keep(new T.BufferGeometry()),n=6;g.setAttribute('position',new T.BufferAttribute(new Float32Array(n*2*3),3).setUsage(T.DynamicDrawUsage)); + g.setAttribute('color',new T.BufferAttribute(new Float32Array(n*2*4),4).setUsage(T.DynamicDrawUsage));const ix=[];for(let i=0;i{const g=q.createLinearGradient(0,0,0,s);g.addColorStop(0,top);g.addColorStop(.55,mid);g.addColorStop(1,low);q.fillStyle=g;q.fillRect(0,0,s,s); + for(let i=0;i<26;i++){const y=s*(.35+hash(i,3)*.4),x=hash(i,5)*s,w=s*(.2+hash(i,9)*.5);q.fillStyle=`rgba(255,240,225,${.05+hash(i,11)*.08})`;q.beginPath();q.ellipse(x,y,w,4+hash(i,13)*9,0,0,Math.PI*2);q.fill();q.beginPath();q.ellipse(x-s,y,w,4+hash(i,13)*9,0,0,Math.PI*2);q.fill();}})); + tex.wrapT=T.ClampToEdgeWrapping;tex.repeat.set(1,1);const dome=new T.Mesh(this.keep(new T.SphereGeometry(200,24,12,0,Math.PI*2,0,Math.PI*.62)),this.keep(new T.MeshBasicMaterial({map:tex,side:T.BackSide,fog:false,depthWrite:false}))); + dome.rotation.x=0;dome.position.y=-30;group.add(dome); + if(sunDir){const sun=new T.Sprite(this.keep(new T.SpriteMaterial({map:this.glowTex,color:sunColor,transparent:true,blending:T.AdditiveBlending,depthWrite:false,fog:false})));sun.position.copy(sunDir.clone().multiplyScalar(170));sun.scale.setScalar(55);group.add(sun);} + return dome;} + + /* ---------------- arenas */ + arena(kind){if(this.arenas[kind])return this.arenas[kind];const group=new T.Group();group.visible=false;this.world.add(group); + const a=kind==='genichiro'?this.castleTop(group):kind==='ape'?this.wateringHole(group):kind==='isshin'?this.silvergrass(group):kind==='gyoubu'?this.castleGate(group):kind==='demon'?this.burningGate(group):this.audienceChamber(group);a.group=group;this.arenas[kind]=a;return a;} + castleTop(group){ + const stone=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#4a4641';q.fillRect(0,0,s,s);const n=8,w=s/n; + for(let y=0;y{for(let k=0;k<4;k++){const out=.9+k*1.15,y=-.42-k*.5,ox=cx+Math.sin(ry)*out,oz=cz+Math.cos(ry)*out;roof.add(P.box,0x34414c,MY(ox,y,oz,ry,.42,len+k*2.3,.16,1.3),0,.05); + for(let i=-len/2-k;i<=len/2+k;i+=.6)roof.add(P.box,0x27313a,MY(ox+Math.cos(ry)*i,y+.1,oz-Math.sin(ry)*i,ry,.42,.08,.09,1.3),0,.03);}}; + skirt(0,6.6,17,0);skirt(0,-6.6,17,Math.PI);skirt(8.6,0,13,Math.PI/2);skirt(-8.6,0,13,-Math.PI/2); + for(const [x,z] of [[-9.4,-7.2],[9.4,-7.2],[-9.4,7.2],[9.4,7.2]]){const yaw=Math.atan2(x,z);roof.add(P.box,0x34414c,MY(x,-.75,z,yaw,.5,1.6,.2,3.2),0,.04);gold.add(P.cone(.16,.7,5),0xc99a45,MY(x*1.12,-.2,z*1.12,yaw,-.9,1,1,1),0,.08);} + // gold shachihoko on the ridge ends of the keep roof below + for(const s of [-1,1]){gold.add(P.ball,0xd2a24c,M4(s*8.9,-1.2,-8.9,0,0,s*.3,.28,.5,.22),0,.08);gold.add(P.cone(.2,.5,5),0xd2a24c,M4(s*8.9,-.7,-9.05,-.6,0,0),0,.08);} + // lower castle tiers and the town, stepping away below the keep + for(let i=0;i<9;i++){const a=-1.2+i*.3,r=26+(i%3)*6,x=Math.sin(a)*r,z=-Math.cos(a)*r,y=-9-(i%3)*3,w=4+hash(i,1)*3; + wall.add(P.box,0xd7d1c2,M4(x,y,z,0,a,0,w,2.4,w*.7),0,.03);roof.add(P.cone(w*.86,1.7,4),0x2f3b45,M4(x,y+2.0,z,0,a+Math.PI/4,0,1,1,.75),0,.04); + for(let k=-1;k<=1;k++)wall.add(P.box,0x24201c,M4(x+Math.cos(a)*k*w*.3,y+.2,z+Math.sin(a)*k*w*.3,0,a,0,.5,.7,w*.72),0,.02);} + for(let i=0;i<40;i++){const a=hash(i,21)*Math.PI*2,r=48+hash(i,22)*40,y=-22+hash(i,23)*4;far.add(P.box,0x6f6c6a,M4(Math.sin(a)*r,y,Math.cos(a)*r,0,a,0,3+hash(i,24)*4,2.5,3),0,.08);} + const mats={wood:this.material(0xffffff,{vertex:true,roughness:.92}),roof:this.material(0xffffff,{vertex:true,roughness:.7,metalness:.1}),wall:this.material(0xffffff,{vertex:true}),gold:this.material(0xffffff,{vertex:true,roughness:.35,metalness:.75}),far:this.material(0xffffff,{vertex:true,roughness:1})}; + this.static(group,wood,mats.wood);this.static(group,roof,mats.roof);this.static(group,wall,mats.wall,false);this.static(group,gold,mats.gold,false);this.static(group,far,mats.far,false); + this.ridges(group,[0x5b6475,0x75808f,0x98a0ad],[46,70,100],-14,18); + const sunDir=v3(-.82,.3,-.2).normalize();this.sky(group,'#3d5470','#c9a98f','#f2c58f',sunDir,0xffc98a); + return {sun:v3(-.72,.62,.3).normalize(),sunColor:0xffd09a,sunI:2.7,hemiSky:0xc8d4e8,hemiGround:0x6a5444,hemiI:1.45,fog:0xc4a994,fogNear:28,fogFar:120,exposure:1.05,shadowR:11,leaves:true};} + ridges(group,colors,radii,base,height){for(let layer=0;layer{const a=i*Math.PI/32,k=.45+.16*Math.sin(a*3+layer*1.7)+.12*Math.sin(a*7+1)+.08*Math.cos(a*13);return [Math.sin(a)*rad,base+h*k,Math.cos(a)*rad];}; + const geo=new T.BufferGeometry(),pos=[];for(let i=0;i<64;i++){const p=pt(i),q=pt(i+1);pos.push(p[0],base-30,p[2],p[0],p[1],p[2],q[0],q[1],q[2],p[0],base-30,p[2],q[0],q[1],q[2],q[0],base-30,q[2]);} + geo.setAttribute('position',new T.Float32BufferAttribute(pos,3));geo.computeVertexNormals();const mesh=new T.Mesh(this.keep(geo),this.material(colors[layer],{side:T.DoubleSide,roughness:1}));group.add(mesh);}} + wateringHole(group){ + const ground=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#5e6a45';q.fillRect(0,0,s,s);for(let i=0;i<2600;i++){const v=hash(i,1);q.fillStyle=v<.5?`rgba(90,104,60,${.5})`:`rgba(120,110,80,${.35})`;q.fillRect(hash(i,2)*s,hash(i,3)*s,3+hash(i,4)*6,2+hash(i,5)*4);}},6),roughness:1}); + const floor=new T.Mesh(this.keep(new T.CylinderGeometry(20,20,.4,48)),ground);floor.position.y=-.2;floor.receiveShadow=true;group.add(floor); + const water=new T.Mesh(this.keep(new T.CircleGeometry(9.5,48)),this.material(0x3f7f86,{transparent:true,opacity:.62,roughness:.12,metalness:.3,flat:false}));water.rotation.x=-Math.PI/2;water.position.y=.03;water.receiveShadow=true;group.add(water); + const rock=new Mesher(),grass=new Mesher(),tree=new Mesher(),lotus=new Mesher(); + for(let i=0;i<34;i++){const a=i/34*Math.PI*2+hash(i,1)*.2,r=16.5+hash(i,2)*3,h=7+hash(i,3)*12,w=2.6+hash(i,4)*2.5;rock.add(P.gem,i%3?0x6a665e:0x5d5a52,M4(Math.sin(a)*r,h/2-1,Math.cos(a)*r,hash(i,5),a,hash(i,6)*.3,w,h/2,w*.8),0,.12); + if(i%2)grass.add(P.cone(.9,1.6,5),0x4e6b38,M4(Math.sin(a)*(r-1.2),h*.8,Math.cos(a)*(r-1.2),0,a,.4),0,.12);} + for(let i=0;i<220;i++){const a=hash(i,7)*Math.PI*2,r=9.6+hash(i,8)*5.2;grass.add(P.cone(.07+hash(i,9)*.05,.5+hash(i,10)*.9,3),hash(i,11)<.5?0x7f9a4a:0x99a35a,M4(Math.sin(a)*r,.3,Math.cos(a)*r,(hash(i,12)-.5)*.5,a,(hash(i,13)-.5)*.5),0,.15);} + for(let i=0;i<14;i++){const a=hash(i,14)*Math.PI*2,r=10+hash(i,15)*4;rock.add(P.gem,0x77736a,M4(Math.sin(a)*r,.1,Math.cos(a)*r,hash(i,16),hash(i,17),0,.4+hash(i,18)*.7,.3+hash(i,19)*.4,.5),0,.1);} + for(let i=0;i<16;i++){const a=hash(i,24)*Math.PI*2,r=2+hash(i,25)*6.5;lotus.add(P.disc,0x4f7a3c,M4(Math.sin(a)*r,.05,Math.cos(a)*r,0,0,0,.35,.02,.35));if(i%3===0)lotus.add(P.cone(.12,.18,6),0xe7c6d4,M4(Math.sin(a)*r,.16,Math.cos(a)*r));} + // a great tree leaning over the pool, hung with vines + tree.add(seg(11,.9,1.3,8),0x4c3b2c,M4(-11,11,-9,.12,0,.18),0,.1);for(let i=0;i<9;i++)tree.add(P.gem,0x3d5a31,M4(-9+hash(i,30)*5-2.5,10.5+hash(i,31)*2,-7.5+hash(i,32)*4-2,hash(i,33),hash(i,34),0,2.4,1.6,2.4),0,.12); + for(let i=0;i<7;i++)tree.add(P.box,0x3e5a2e,M4(-8.5+i*.9,7.5,-6.4+i*.3,0,0,0,.05,4+hash(i,35)*2,.05)); + const mats={rock:this.material(0xffffff,{vertex:true}),grass:this.material(0xffffff,{vertex:true,side:T.DoubleSide}),tree:this.material(0xffffff,{vertex:true}),lotus:this.material(0xffffff,{vertex:true})}; + this.static(group,rock,mats.rock);this.static(group,grass,mats.grass,false);this.static(group,tree,mats.tree);this.static(group,lotus,mats.lotus,false); + this.ridges(group,[0x55604f,0x6b7766,0x8a9586],[34,52,80],-4,16); + const sunDir=v3(.35,.85,-.4).normalize();this.sky(group,'#7d98a8','#c5cfc9','#e4e5d6',sunDir,0xfff1d2); + return {sun:sunDir,sunColor:0xfff0d6,sunI:2.4,hemiSky:0xdde8e4,hemiGround:0x4e5a3c,hemiI:1.35,fog:0xb7c2b5,fogNear:24,fogFar:95,exposure:1.0,shadowR:16,water};} + audienceChamber(group){ + const planks=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{for(let y=0;y<16;y++){const v=58+Math.round(hash(y,1)*22);q.fillStyle=`rgb(${v+16},${v},${v-12})`;q.fillRect(0,y*s/16,s,s/16-2); + for(let i=0;i<30;i++){q.fillStyle=`rgba(20,12,8,${hash(i,y)*.25})`;q.fillRect(hash(i,y+5)*s,y*s/16+hash(i,y+9)*s/16,30+hash(i,y+3)*60,1);}}},3),roughness:.55}); + const floor=new T.Mesh(this.keep(new T.BoxGeometry(19.6,.3,15.6)),planks);floor.position.y=-.15;floor.receiveShadow=true;group.add(floor); + const wood=new Mesher(),paper=new Mesher(),dark=new Mesher(),fire=new Mesher(); + const pillars=[-6.6,-2.2,2.2,6.6].flatMap(x=>[[x,-4.6],[x,4.6]]); + for(const [x,z] of pillars){wood.add(P.cyl(.42,.46,5.6,10),0x6d3d2c,M4(x,2.8,z),0,.05);wood.add(P.cyl(.47,.5,.09,10),0x2a1a12,M4(x,1.0,z));wood.add(P.cyl(.47,.5,.09,10),0x2a1a12,M4(x,3.0,z));wood.add(P.cyl(.47,.5,.09,10),0x2a1a12,M4(x,4.9,z));wood.add(P.box,0x2b1a14,M4(x,.12,z,0,0,0,1.1,.24,1.1));wood.add(P.box,0x3a2219,M4(x,5.45,z,0,0,0,1.0,.3,1.0));} + for(const z of [-4.6,4.6])wood.add(P.box,0x4a281d,M4(0,5.3,z,0,0,0,19.4,.42,.5));for(const x of [-6.6,-2.2,2.2,6.6])wood.add(P.box,0x4a281d,M4(x,5.55,0,0,0,0,.45,.4,15.4)); + dark.add(P.box,0x1b120e,M4(0,5.95,0,0,0,0,19.8,.2,15.8)); + // shoji walls lit from behind by the burning estate; some panels burnt through + for(const z of [-7.75,7.75])for(let x=-9;x<9;x+=1.5){const burnt=hash(Math.round(x*3),z>0?1:2)<.22;(burnt?fire:paper).add(P.box,burnt?0xff7a2a:0xe7b98a,M4(x+.75,2.3,z,0,0,0,1.38,3.8,.04)); + wood.add(P.box,0x2a1a12,M4(x,2.3,z,0,0,0,.08,4.6,.1));for(let y=.5;y<4.3;y+=.6)wood.add(P.box,0x2a1a12,M4(x+.75,y,z,0,0,0,1.5,.04,.06));} + for(const x of [-9.75,9.75])for(let z=-7.5;z<7.5;z+=1.5){paper.add(P.box,0xd9a679,M4(x,2.3,z+.75,0,0,0,.04,3.8,1.38));wood.add(P.box,0x2a1a12,M4(x,2.3,z,0,0,0,.1,4.6,.08));} + for(const s of [-1,1])wood.add(P.box,0x2a1a12,M4(0,4.35,s*7.7,0,0,0,19.6,.25,.2)); + const mats={wood:this.material(0xffffff,{vertex:true,roughness:.7}),paper:this.material(0xffffff,{vertex:true,emissive:0xff9a4a,emissiveIntensity:.42,roughness:1}),dark:this.material(0xffffff,{vertex:true}),fire:this.keep(new T.MeshBasicMaterial({vertexColors:true,fog:false}))}; + this.static(group,wood,mats.wood);this.static(group,paper,mats.paper,false);this.static(group,dark,mats.dark,false);const f=new T.Mesh(this.keep(fire.geometry()),mats.fire);group.add(f); + // illusory strands between the pillar tops (S17: she walks on threads strung around the hall) + const lines=[];const tops=pillars.map(([x,z])=>[x,4.6,z]);for(let i=0;i{const l=new T.PointLight(0xff8a3a,6,14,1.4);l.position.set(...p);group.add(l);return l;}); + return {sun:v3(.3,1,.25).normalize(),sunColor:0xb4c2ee,sunI:2.1,hemiSky:0x7a7fa6,hemiGround:0x4a2e20,hemiI:1.9,fog:0x231915,fogNear:14,fogFar:44,exposure:1.3,shadowR:12,fireLights,embers:true,background:0x140d0b};} + + /* ---------------- per-frame */ + // Original set for the final duel: a wide field of silver grass under a low sun, cliffs and a far castle (S27). + silvergrass(group){ + const ground=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#8d8a6a';q.fillRect(0,0,s,s);for(let i=0;i<3000;i++){const v=hash(i,1);q.fillStyle=v<.5?'rgba(170,165,125,.45)':'rgba(92,92,66,.4)';q.fillRect(hash(i,2)*s,hash(i,3)*s,2+hash(i,4)*7,1+hash(i,5)*2);}},6),roughness:1}); + const floor=new T.Mesh(this.keep(new T.CylinderGeometry(60,60,.4,48)),ground);floor.position.y=-.2;floor.receiveShadow=true;group.add(floor); + const grass=new Mesher(),rock=new Mesher(),far=new Mesher(); + // low trampled tufts inside the fighting circle, full stems with pale plumes outside it + for(let i=0;i<150;i++){const a=hash(i,6)*Math.PI*2,r=2+hash(i,7)*10.6;grass.add(P.cone(.05+hash(i,8)*.04,.22+hash(i,9)*.2,3),hash(i,10)<.5?0xa8a47c:0x8f9068,M4(Math.sin(a)*r,.13,Math.cos(a)*r,(hash(i,11)-.5)*.5,a,(hash(i,12)-.5)*.5),0,.12);} + for(let i=0;i<620;i++){const a=hash(i,13)*Math.PI*2,r=13.4+hash(i,14)*hash(i,14)*24,h=.9+hash(i,15)*1.1,x=Math.sin(a)*r,z=Math.cos(a)*r,lean=.15+hash(i,16)*.3; + grass.add(P.cone(.028,h,3),hash(i,17)<.5?0xc2bd8c:0xaeb07f,M4(x,h/2,z,0,a,lean),0,.1);grass.add(P.gem,hash(i,18)<.6?0xf6f1e2:0xe8e1c8,M4(x+Math.sin(lean)*h*.5,h+.02,z,lean,a,0,.03,.13,.03),0,.06);} + for(let i=0;i<30;i++){const a=i/30*Math.PI*2+hash(i,19)*.2,r=52+hash(i,20)*10,h=5+hash(i,21)*8,w=4+hash(i,22)*4;rock.add(P.gem,i%3?0x9a9586:0xa8a292,M4(Math.sin(a)*r,h/2-1,Math.cos(a)*r,hash(i,23),a,hash(i,24)*.3,w,h/2,w*.8),0,.12);} + // the far castle keep on its rise, as a silhouette + for(let i=0;i<4;i++){const w=9-i*1.7,y=11+i*2.8;far.add(P.box,0x4a4b52,M4(-40,y,-74,0,0,0,w,2.3,w));far.add(P.box,0x33343a,M4(-40,y+1.35,-74,0,0,0,w*1.3,.45,w*1.3));}far.add(P.box,0x55565a,M4(-40,4,-74,0,0,0,18,10,18),0,.05); + const mats={grass:this.material(0xffffff,{vertex:true,side:T.DoubleSide}),rock:this.material(0xffffff,{vertex:true}),far:this.material(0xffffff,{vertex:true})}; + this.static(group,grass,mats.grass,false);this.static(group,rock,mats.rock);this.static(group,far,mats.far); + this.ridges(group,[0x62687a,0x7b8294,0x9da3b1],[60,84,120],-6,20); + const sunDir=v3(-.55,.6,-.55).normalize();this.sky(group,'#7d8aa3','#d6b89a','#f0d7ae',sunDir,0xffe2b0); + return {sun:sunDir,sunColor:0xffe7c4,sunI:2.3,hemiSky:0xdde0e6,hemiGround:0x6f6c50,hemiI:1.3,fog:0xd8c9ad,fogNear:22,fogFar:92,exposure:1,shadowR:15,plumes:true};} + // Original set: a wide packed-earth yard before a castle gate at dusk, low walls, a burning brazier ring and far ridges (S31 names only "a large arena"). + castleGate(group){ + const ground=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#6d5f4a';q.fillRect(0,0,s,s);for(let i=0;i<3200;i++){q.fillStyle=hash(i,1)<.5?'rgba(120,104,82,.45)':'rgba(70,60,46,.4)';q.fillRect(hash(i,2)*s,hash(i,3)*s,2+hash(i,4)*6,1+hash(i,5)*3);}},8),roughness:1}); + const floor=new T.Mesh(this.keep(new T.CylinderGeometry(70,70,.4,48)),ground);floor.position.y=-.2;floor.receiveShadow=true;group.add(floor); + const wall=new Mesher(),wood=new Mesher(),roof=new Mesher(),fire=new Mesher(); + for(let i=0;i<40;i++){const a=i/40*Math.PI*2,r=23,x=Math.sin(a)*r,z=Math.cos(a)*r;wall.add(P.box,i%2?0x8a8476:0x7c7668,M4(x,1.1,z,0,a,0,3.9,2.2,.9),0,.08);roof.add(P.box,0x2e2c30,M4(x,2.35,z,0,a,0,4.3,.25,1.5),0,.05);} + // the gate across the far side, in timber with a tiled roof + wood.add(P.box,0x3a2a20,M4(0,3.4,-23.4,0,0,0,9,6.8,1.2),0,.05);wood.add(P.box,0x241a14,M4(0,2.6,-22.7,0,0,0,5,5.2,.3),0,.05);for(const x of [-3.6,3.6])wood.add(P.box,0x2c2018,M4(x,3.4,-22.6,0,0,0,.6,6.8,.6));roof.add(P.box,0x26252a,M4(0,7.2,-23.4,0,0,0,12,.7,3.2));roof.add(P.box,0x1f1e22,M4(0,7.9,-23.4,0,0,0,8,.6,2)); + for(let i=0;i<8;i++){const a=(i+.5)/8*Math.PI*2,x=Math.sin(a)*21,z=Math.cos(a)*21;wood.add(P.cyl(.14,.2,1.5,6),0x2c2420,M4(x,.75,z),0,.05);fire.add(P.cone(.17,.42,6),0xff8a3a,M4(x,1.66,z));} + const mats={wall:this.material(0xffffff,{vertex:true}),wood:this.material(0xffffff,{vertex:true}),roof:this.material(0xffffff,{vertex:true}),fire:this.keep(new T.MeshBasicMaterial({vertexColors:true}))}; + this.static(group,wall,mats.wall);this.static(group,wood,mats.wood);this.static(group,roof,mats.roof);this.static(group,fire,mats.fire,false); + this.ridges(group,[0x4f4a58,0x635c68,0x847a80],[60,84,120],-6,20); + const sunDir=v3(.5,.5,-.7).normalize();this.sky(group,'#58607c','#c79a84','#efc79a',sunDir,0xffd8a8); + return {sun:sunDir,sunColor:0xffdcb8,sunI:2.2,hemiSky:0xd6d6e4,hemiGround:0x5e5240,hemiI:1.25,fog:0xc9b49c,fogNear:30,fogFar:130,exposure:1,shadowR:18};} + // The gate yard again, burning: the same wall ring, charred timber, fires everywhere, a red sky and embers (S36). + burningGate(group){ + const ground=this.material(0xffffff,{map:canvasTexture(512,(q,s)=>{q.fillStyle='#5a4636';q.fillRect(0,0,s,s);for(let i=0;i<3200;i++){q.fillStyle=hash(i,1)<.5?'rgba(96,70,52,.45)':'rgba(28,20,16,.45)';q.fillRect(hash(i,2)*s,hash(i,3)*s,2+hash(i,4)*6,1+hash(i,5)*3);}},8),roughness:1}); + const floor=new T.Mesh(this.keep(new T.CylinderGeometry(70,70,.4,48)),ground);floor.position.y=-.2;floor.receiveShadow=true;group.add(floor); + const wall=new Mesher(),wood=new Mesher(),roof=new Mesher(),fire=new Mesher(); + for(let i=0;i<40;i++){const a=i/40*Math.PI*2,r=21,x=Math.sin(a)*r,z=Math.cos(a)*r;wall.add(P.box,i%2?0x4e4842:0x423c38,M4(x,1.1,z,0,a,0,3.4,2.2,.9),0,.08);if(i%3)roof.add(P.box,0x1c1a1c,M4(x,2.35,z,0,a,.06*(i%4-1.5),3.8,.25,1.5),0,.05); + if(i%4===1)for(let k=0;k<3;k++)fire.add(P.cone(.35-k*.08,1.2+k*.3,6),k%2?0xff7a2a:0xffb84a,M4(x*.98+k*.3-.3,2.9+k*.3,z*.98));} + wood.add(P.box,0x241a14,M4(0,3.4,-21.4,0,0,0,9,6.8,1.2),0,.05);wood.add(P.box,0x140e0a,M4(0,2.6,-20.7,0,0,0,5,5.2,.3),0,.05);for(const x of [-3.6,3.6])wood.add(P.box,0x1c140e,M4(x,3.4,-20.6,0,0,0,.6,6.8,.6));roof.add(P.box,0x1a191c,M4(0,7.2,-21.4,.06,0,.05,12,.7,3.2)); + for(let i=0;i<9;i++){const x=-4+i,h=1+hash(i,7)*1.6;fire.add(P.cone(.5,h+.6,6),i%2?0xff6a20:0xffa840,M4(x,7.6+h*.3,-21.4));} + for(let i=0;i<10;i++){const a=(i+.5)/10*Math.PI*2,x=Math.sin(a)*18.4,z=Math.cos(a)*18.4;wood.add(P.box,0x1a120e,M4(x,.4,z,.2,a,.3,1.6,.3,.3),0,.05);fire.add(P.cone(.3,.9+hash(i,3)*.6,6),0xff8a3a,M4(x,.9,z));} + const mats={wall:this.material(0xffffff,{vertex:true}),wood:this.material(0xffffff,{vertex:true}),roof:this.material(0xffffff,{vertex:true}),fire:this.keep(new T.MeshBasicMaterial({vertexColors:true}))}; + this.static(group,wall,mats.wall);this.static(group,wood,mats.wood);this.static(group,roof,mats.roof);this.static(group,fire,mats.fire,false); + this.ridges(group,[0x2a1c1c,0x3a2424,0x52302a],[60,84,120],-6,20); + const sunDir=v3(-.4,.45,-.8).normalize();this.sky(group,'#1e1014','#7a2a1c','#e0743a',sunDir,0xff9a50); + return {sun:sunDir,sunColor:0xffb27a,sunI:1.8,hemiSky:0xe0a890,hemiGround:0x6a4030,hemiI:1.6,fog:0x5a3428,fogNear:30,fogFar:120,exposure:1.2,shadowR:18,embersWide:true};} + setArena(kind){if(this.kind===kind)return;for(const [k,a] of Object.entries(this.arenas))a.group.visible=false;const a=this.arena(kind);a.group.visible=true;this.kind=kind; + for(const [k,m] of Object.entries(this.bosses))m.holder.visible=k===kind; + this.world.background=a.background!=null?new T.Color(a.background):null;this.world.fog.color.set(a.fog);this.world.fog.near=a.fogNear;this.world.fog.far=a.fogFar; + this.hemi.color.set(a.hemiSky);this.hemi.groundColor.set(a.hemiGround);this.sun.color.set(a.sunColor);this.renderer.toneMappingExposure=a.exposure; + const sc=this.sun.shadow.camera;sc.left=-a.shadowR;sc.right=a.shadowR;sc.top=a.shadowR;sc.bottom=-a.shadowR;sc.updateProjectionMatrix();} + place(pool,i,pos,scale,rot,color){if(i>=pool.instanceMatrix.count)return i;const d=this.dummy;d.position.set(pos[0],pos[1],pos[2]); + if(Array.isArray(scale))d.scale.set(scale[0],scale[1],scale[2]);else d.scale.setScalar(scale);if(rot&&rot.isQuaternion)d.quaternion.copy(rot);else d.rotation.set(...(rot||[0,0,0])); + d.updateMatrix();pool.setMatrixAt(i,d.matrix);pool.setColorAt(i,this.tmp.set(color??0xffffff));return i+1;} + dir(dx,dy,dz){const a=v3(dx,dy,dz);if(a.lengthSq()<1e-12)return new T.Quaternion();return new T.Quaternion().setFromUnitVectors(v3(0,0,1),a.normalize());} + link(pool,i,a,b,w,color){const dx=b[0]-a[0],dy=b[1]-a[1],dz=b[2]-a[2];return this.place(pool,i,[(a[0]+b[0])/2,(a[1]+b[1])/2,(a[2]+b[2])/2],[w,w,Math.hypot(dx,dy,dz)],this.dir(dx,dy,dz),color);} + finish(pool,n){pool.count=n;pool.instanceMatrix.needsUpdate=true;if(pool.instanceColor)pool.instanceColor.needsUpdate=true;} + playerPose(p,tm){const a=String(p.action||''),t=Number(p.actionTick||0);let q=H.stance; + const moving=a==='walk'||a==='run'; + if(p.dead)q=H.dead; + else if(a==='posture_break'||a==='safety_roll')q=mixPose(H.hurt,H.kneel,band(t,0,8)); + else if(a==='hurt')q=mixPose(H.hurt,H.stance,band(t,6,16)); + else if(a==='heal')q=mixPose(H.stance,H.drink,band(t,0,10)*(1-band(t,56,66))); + else if(a==='revive')q=mixPose(H.kneel,H.stance,band(t,10,48)); + else if(a==='deathblow')q=t<26?mixPose(H.pull,H.lunge,band(t,12,20)):mixPose(H.lunge,H.cut,band(t,30,44)); + else if(p.charge>0)q=mixPose(H.stance,H.pull,band(p.charge,0,8)); + else if(p.attackTick>=0)q=p.attackKind==='thrust'?(p.attackTick<10?mixPose(H.pull,H.lunge,band(p.attackTick,6,10)):mixPose(H.lunge,H.stance,band(p.attackTick,18,34))): + (p.attackTick<5?mixPose(H.stance,H.raise,band(p.attackTick,0,4)):p.attackTick<9?mixPose(H.raise,H.cut,band(p.attackTick,5,8)):mixPose(H.cut,H.stance,band(p.attackTick,12,25))); + else if(p.y>0)q=p.stomped&&p.vy>0?H.kick:H.tuck; + else if(p.dodgeTicks>0)q=mixPose(H.stance,H.low,.45); + else if(p.guarding)q=p.guardAge<6?mixPose(H.guard,H.backCut,.35*(1-p.guardAge/6)):H.guard; + if(moving&&!p.guarding)q=walkCycle(q,tm*(a==='run'?13:9),1,a==='run');else if(moving)q=walkCycle(q,tm*7,.5,false); + return q;} + posePlayer(g){const p=g.player,m=this.player,a=String(p.action||''),t=Number(p.actionTick||0),tm=g.t/60; + applyPose(m,this.playerPose(p,tm));const b=m.bones;b.sodeL.scale.setScalar(.001);b.sodeR.scale.setScalar(.001);b.tool.scale.setScalar(a==='heal'?1:.001);b.blade.scale.setScalar(1);b.scab.rotation.set(.5,0,.2);b.back.rotation.set(.3+Math.sin(tm*3)*.08,0,0); + const dead=p.dead?1:0,lie=dead?-1.45*band(t,0,24):0; + m.holder.position.set(p.x||0,(p.y||0)+(dead?.12:0),p.z||0);m.holder.rotation.set(0,p.yaw||0,0);m.mesh.rotation.set(lie,0,0); + return m;} + humanPose(g,b,moves,kind){const a=String(b.action||''),mv=moves?.[a],t=Number(b.state==='attack'?b.moveTick:b.actionTick||0),tm=g.t/60;let q=H.stance,tool=false; + if(b.state==='execution'||b.action==='deathblow')q=mixPose(H.kneel,H.dead,band(t,20,50)); + else if(b.state==='deathblow'||a==='posture_break')q=mixPose(H.hurt,H.kneel,band(t,0,10)); + else if(a==='stagger'||a==='rising')q=a==='rising'&&kind==='genichiro'?mixPose(H.kneel,H.stance,band(t,4,36)):H.hurt; + else if(b.state==='attack'&&mv){ + const bow=/bow|volley|charged|quick_bow|opening/.test(a)&&kind==='genichiro'; + if(bow&&(mv.shots||[]).length&&!(a==='bow_roll'&&t>46)&&!(a==='opening'&&t>30)){tool=true;const shot=(mv.shots||[]).find(s=>t<=s+10)??mv.shots.at(-1);q=tt<=x+7)??mv.gun.at(-1);q=mixPose(H.stance,H.aim,band(t,at-14,at-6)*(1-band(t,at+8,at+16)));} + else if(kind==='isshin'&&(mv.waves||mv.stomp))q=strikePose(H.stance,[...mv.hits,...(mv.waves||[]).map(([at,w])=>({t:at,type:w==='v'?'slam':'sweep'})),...(mv.stomp||[]).map(at=>({t:at,type:'slam'}))].sort((x,y)=>x.t-y.t),t,{wind:12,follow:10}); + else if(kind==='butterfly'&&(a==='thread_up'||a==='thread_hover'||a==='waltz'))q=H.hover; + else if(kind==='butterfly'&&(a==='illusion'||a==='dispel'))q=mixPose(H.stance,H.cast,band(t,8,24)*(1-band(t,40,56))); + else if(kind==='butterfly'&&a==='kunai_throw'||mv.kunai&&!mv.hits.length){const k=(mv.kunai||[]).find(([s])=>t<=s+8);q=k?mixPose(H.backRaise,H.cut,band(t,k[0]-4,k[0])):H.stance;} + else q=strikePose(H.stance,mv.hits,t,{wind:kind==='butterfly'?8:12,follow:kind==='butterfly'?7:10}); + if(kind==='butterfly'&&(a==='leg_drop'||a==='three_strike')&&b.y>.3)q=mixPose(q,H.tuck,.6); + if(kind==='butterfly'&&a==='sweep')q=mixPose(q,H.low,.7); + } + const moving=kind!=='gyoubu'&&b.state==='idle'&&Math.hypot((g.player.x||0)-(b.x||0),(g.player.z||0)-(b.z||0))>2.4;if(moving)q=walkCycle(q,tm*8,.8,false); + if(kind==='gyoubu'){q={...q,y:.72+(q.y||0)*.25,lHip:[-.95,0,.75],rHip:[-.95,0,-.75],lKnee:[1.25,0,0],rKnee:[1.25,0,0],lAnk:[-.3,0,0],rAnk:[-.3,0,0]};} + return {q,tool};} + poseHuman(g,m,b,moves,kind){const a=String(b.action||''),t=Number(b.state==='attack'?b.moveTick:b.actionTick||0),tm=g.t/60,{q,tool}=this.humanPose(g,b,moves,kind); + applyPose(m,q);const bones=m.bones;bones.tool.scale.setScalar(tool?1:.001);if(kind==='genichiro')bones.tool.rotation.set(tool?1.45:0,0,0); + if(kind==='genichiro'){const armored=b.form_id!=='tomoe'||(a==='tomoe_awaken'&&t<40);for(const n of ['armor','skirt','sodeL','sodeR'])bones[n].scale.setScalar(armored?1:.001);bones.back.scale.setScalar(tool?.001:1);} + if(kind!=='genichiro'){bones.tool.scale.setScalar(1);bones.back.scale.setScalar(1);bones.sodeL.scale.setScalar(.001);bones.sodeR.scale.setScalar(.001);} + // Which weapon he holds follows the move: spear, matchlock or katana; the slung spear appears with his second life (S27). + if(kind==='isshin'){const st=b.state==='attack',spear=st&&ISSHIN_SPEAR.test(a),gun=st&&/^(quad_shot|quick_gun)$/.test(a);bones.spear.scale.setScalar(spear?1:.001);bones.gun.scale.setScalar(gun?1:.001);bones.blade.scale.setScalar(spear||gun?.001:1);bones.back.scale.setScalar((b.phase||1)>=3&&!spear?1:.001);bones.active=spear?bones.spear:null;} + if(kind==='gyoubu'){bones.blade.scale.setScalar(.001);bones.back.scale.setScalar(.001);bones.tool.scale.setScalar(.001);bones.active=bones.spear; + const mv=root.SekiroGame?.bosses?.gyoubu?.moves?.[a],run=b.state==='attack'&&(mv?.ride||mv?.away)?1:b.state==='idle'?.35:0,ph=tm*(run>.5?15:7),amp=run>.5?.75:.28*run/.35; + for(const [n,o] of [['hFL',0],['hBR',.4],['hFR',1.6],['hBL',2]])bones[n].rotation.set(Math.sin(ph+o)*amp,0,0);bones.hBody.rotation.set((b.y||0)>.3?-.28:Math.sin(ph*2)*.03*run,0,0);bones.hBody.position.y=1.32+Math.abs(Math.sin(ph))*.07*run;bones.hNeck.rotation.set(Math.sin(ph)*.1*run,0,0);} + bones.scab.rotation.set(.5,0,.2);bones.tail.rotation.set(.2+Math.sin(tm*2.5)*.06,0,0); + const lie=(b.state==='execution'?-1.4*band(t,24,50):0);m.holder.position.set(b.x||0,b.y||0,b.z||0);m.holder.rotation.set(0,b.yaw||0,0);m.mesh.rotation.set(lie,0,0); + const flash=(b.flash||0)/8;m.mat.emissive.setRGB(.3*flash,.25*flash,.25*flash);m.mat.emissiveIntensity=1; + return {};} + poseApe(g,m,b){applyPose(m,this.apePose(g,b),{hipY:1.25});const bn=m.bones,head=b.form_id==='headless'; + const off=head||b.state==='dead';bn.head.scale.setScalar(off?.001:1);bn.neckBlade.scale.setScalar(off?.001:1);bn.blade.scale.setScalar(head?1:.001);bn.held.scale.setScalar(head?1:.001);bn.stump.scale.setScalar(off?1:.001); + m.holder.position.set(b.x||0,b.y||0,b.z||0);m.holder.rotation.set(0,b.yaw||0,0); + // the severed head lies beside the body during the false Shinobi Execution (S14) + this.severed.visible=b.state==='dead';if(this.severed.visible){const s=Math.sin(b.yaw||0),c=Math.cos(b.yaw||0);this.severed.position.set((b.x||0)+s*1.8+c*.8,.28,(b.z||0)+c*1.8-s*.8);this.severed.rotation.set(.4,(b.yaw||0)+2.2,.5);} + const flash=(b.flash||0)/8;m.mat.emissive.setRGB(.3*flash,.25*flash,.25*flash); + return {};} + // The demon stands upright on the ape-style rig; each move gets a readable key pose from its hit times. + poseDemon(g,m,b){const a=String(b.action||''),mv=root.SekiroGame?.bosses?.demon?.moves?.[a],t=Number(b.state==='attack'?b.moveTick:b.actionTick||0),tm=g.t/60; + const q={hips:[.15,0,0],spine:[.12,0,0],chest:[.08,0,0],neck:[-.2,0,0],head:[-.1,0,0],lSh:[-.3,0,.35],lEl:[-.5,0,0],lWr:[0,0,0],rSh:[-.25,0,-.35],rEl:[-.4,0,0],rWr:[0,0,0],lHip:[-.25,0,.12],lKnee:[.4,0,0],lAnk:[-.15,0,0],rHip:[-.25,0,-.12],rKnee:[.4,0,0],rAnk:[-.15,0,0],y:-.1}; + const set=(j,x,y,z)=>{q[j]=[x,y,z];},ad=(j,x,y,z)=>{q[j]=[q[j][0]+x,q[j][1]+y,q[j][2]+z];}; + if(b.state==='idle'){const s=Math.sin(tm*4);ad('lHip',-s*.25,0,0);ad('rHip',s*.25,0,0);ad('chest',Math.abs(s)*.05,0,0);} + if(b.state==='attack'&&mv){const hits=mv.hits||[],near=hits.find(h=>t>=h.t-20&&t<=h.t+12); + const arm=(side,u,v)=>{ad(side+'Sh',-2.6*u+2.4*v,0,0);ad(side+'El',-.4*u,0,0);ad('chest',0,(side==='l'?1:-1)*(.5*u-1.0*v),0);}; + if(near){const u=band(t,near.t-18,near.t-4),v=band(t,near.t-3,near.t+1); + if(near.type==='slam'&&/stomp/.test(a)){const side=a==='double_stomp'&&hits.indexOf(near)===1?'r':a==='double_stomp'?'l':'r';ad(side+'Hip',-1.3*u+1.3*v,0,0);ad(side+'Knee',1.0*u-1.0*v,0,0);} + else if(a==='headbutt'){ad('chest',-.6*u+1.1*v,0,0);ad('neck',-.4*u+.6*v,0,0);} + else if(near.type==='sweep'){set('rSh',-.5,0,-.2);ad('hips',.7*u,0,0);ad('rSh',-.8*u,0,-1.2*u+1.6*v);} + else arm(near.noDeflect||a==='whip_slam'?'l':'r',u,v);} + if(mv.ride&&t>=mv.ride[0]&&t.3;if(air){set('lHip',-1.4,0,.3);set('rHip',-1.4,0,-.3);set('lKnee',1.6,0,0);set('rKnee',1.6,0,0);set('lSh',-2.4,0,.6);set('rSh',-2.4,0,-.6);}else if(tt<=x+8)??0;const u=band(t,at-20,at-4),v=band(t,at-3,at+1);if(mv.waves){ad('rHip',-1.6*u+1.0*v,0,-.8*u);}else arm('l',u,v);} + if(a==='fire_ring'&&t<84){set('lSh',-1.2,0,1.4);set('rSh',-1.2,0,-1.4);ad('chest',0,Math.sin(t*.3)*.4,0);} + if(a==='crouch'){set('hips',.9,0,0);q.y=-.9;set('lSh',-1.6,0,.4);set('rSh',-1.6,0,-.4);ad('lKnee',1.2,0,0);ad('rKnee',1.2,0,0);} + } + if(b.state==='stunned')ad('chest',-.35,0,0); + if(b.state==='deathblow'){ad('chest',.6,0,0);q.y-=.5;ad('lKnee',.8,0,0);ad('rKnee',.8,0,0);} + if(b.state==='dead'||b.state==='execution'){set('hips',1.4,0,0);set('lSh',-2.6,0,.6);set('rSh',-2.6,0,-.6);q.y=-1.5;} + applyPose(m,q,{hipY:1.9});const bn=m.bones;bn.flame.scale.setScalar(1+Math.sin(tm*14)*.12);bn.cape.rotation.set(.2+Math.sin(tm*2)*.06,0,0); + m.holder.position.set(b.x||0,b.y||0,b.z||0);m.holder.rotation.set(0,b.yaw||0,0); + const flash=(b.flash||0)/8;m.mat.emissive.setRGB(.3*flash,.25*flash,.25*flash);return {};} + apePose(g,b){const a=String(b.action||''),mv=root.SekiroGame?.bosses?.ape?.moves?.[a],t=Number(b.state==='attack'?b.moveTick:b.actionTick||0),tm=g.t/60,head=b.form_id==='headless'; + const q={hips:[0,0,0],spine:[0,0,0],chest:[0,0,0],neck:[0,0,0],head:[0,0,0],lSh:[0,0,0],lEl:[0,0,0],lWr:[0,0,0],rSh:[0,0,0],rEl:[0,0,0],rWr:[0,0,0],lHip:[0,0,0],lKnee:[0,0,0],lAnk:[0,0,0],rHip:[0,0,0],rKnee:[0,0,0],rAnk:[0,0,0],y:0}; + const set=(j,x,y,z)=>{q[j]=[x,y,z];},ad=(j,x,y,z)=>{q[j]=[q[j][0]+x,q[j][1]+y,q[j][2]+z];}; + // quadruped base: body pitched forward onto the knuckles; headless form stands hunched upright + if(!head){set('hips',.9,0,0);set('spine',.25,0,0);set('chest',.1,0,0);set('neck',-.85,0,0);set('head',-.25,0,0);set('lSh',-.95,0,.08);set('rSh',-.95,0,-.08);set('lEl',.2,0,0);set('rEl',.2,0,0); + set('lHip',-.95,0,.12);set('rHip',-.95,0,-.12);set('lKnee',1.35,0,0);set('rKnee',1.35,0,0);set('lAnk',-.4,0,0);set('rAnk',-.4,0,0);q.y=-.22;} + else{set('hips',.25,0,0);set('spine',.2,0,0);set('chest',.1,0,0);set('lSh',-.5,0,.25);set('lEl',-.9,0,0);set('rSh',-.6,0,-.25);set('rEl',-.4,0,0);set('rWr',-.6,0,0); + set('lHip',-.45,0,.1);set('rHip',-.25,0,-.1);set('lKnee',.7,0,0);set('rKnee',.6,0,0);set('lAnk',-.25,0,0);q.y=-.15;} + const moving=b.state==='idle'&&!head;if(moving){const s=Math.sin(tm*7),c=Math.cos(tm*7);ad('lSh',s*.45,0,0);ad('rSh',-s*.45,0,0);ad('lHip',-s*.4,0,0);ad('rHip',s*.4,0,0);q.y+=Math.abs(c)*.08;} + if(head&&b.state==='idle'){const s=Math.sin(tm*5);ad('lHip',-s*.25,0,0);ad('rHip',s*.25,0,0);} + if(b.state==='attack'&&mv){ + const hits=mv.hits||[],near=hits.find(h=>t>=h.t-16&&t<=h.t+10); + if(!head&&(a==='slam_combo'||a==='swipe_leap'&&t<50)&&near){const i=hits.indexOf(near),side=i%2?'l':'r',u=band(t,near.t-14,near.t-4),v=band(t,near.t-3,near.t); + ad('hips',-.75*u+.5*v,0,0);ad('chest',-.2*u,0,0);ad(side+'Sh',-2.4*u+2.6*v,0,0);ad(side+'El',-.3*u,0,0);} + if(a==='swipe_leap'&&t>=50){const u=band(t,56,72),v=band(t,80,84);ad('hips',-.6*u+.4*v,0,0);ad('lSh',-2.6*u+2.4*v,0,0);ad('rSh',-2.6*u+2.4*v,0,0);} + if(a==='swipe_grab'){const u=band(t,20,34),v=band(t,36,44);ad('hips',.2*u,0,0);ad('rSh',-.6*u-.6*v,0,0);ad('rSh',0,0,-1.2*u+1.6*v);ad('chest',0,.6*u-1.2*v,0);} + if(a==='belly_flop'){const air=b.y>.4;if(air){set('hips',1.5,0,0);set('lSh',-2.2,0,1.0);set('rSh',-2.2,0,-1.0);set('lHip',-.2,0,.4);set('rHip',-.2,0,-.4);set('lKnee',.4,0,0);set('rKnee',.4,0,0);} + if(t>=58){set('hips',1.55,0,0);set('lSh',-2.9,0,.8);set('rSh',-2.9,0,-.8);q.y=-.55;}} + if(a==='back_thrash'&&t>=10){set('hips',-1.45,0,0);set('spine',-.1,0,0);set('neck',.3,0,0);q.y=-.65;const s=Math.sin(t*.55);set('lSh',-1.5+s*.9,0,.9);set('rSh',-1.5-s*.9,0,-.9);set('lHip',-1.2-s*.5,0,.3);set('rHip',-1.2+s*.5,0,-.3);set('lKnee',.8,0,0);set('rKnee',.8,0,0);} + if(a==='fart'){ad('hips',.3,0,0);ad('lKnee',.4,0,0);ad('rKnee',.4,0,0);q.y-=.15;} + if(a==='flee_poo'&&t>=44){set('hips',.2,0,0);ad('rSh',-2.6*band(t,48,62)+2.2*band(t,64,70),0,0);} + if(a==='roar'&&t>=20){set('hips',.15,0,0);set('chest',-.3,0,0);set('neck',-.2,0,0);set('head',-.5,0,0);set('lSh',-1.2,0,1.1);set('rSh',-1.2,0,-1.1);set('lHip',-.4,0,.1);set('rHip',-.4,0,-.1);set('lKnee',.6,0,0);set('rKnee',.6,0,0);q.y=-.1;} + if((a==='bound'||a==='roll_away')&&b.y>.3){set('lHip',-1.6,0,.2);set('rHip',-1.6,0,-.2);set('lKnee',1.8,0,0);set('rKnee',1.8,0,0);set('lSh',-2.2,0,0);set('rSh',-2.2,0,0);} + if(a==='sword4'&&near){const i=hits.indexOf(near),dir=i%3===0?1:-1,u=band(t,near.t-14,near.t-3),v=band(t,near.t-3,near.t+2);set('rSh',-1.4,0,-.4);set('rEl',-.2,0,0);ad('chest',0,dir*(.9*u-1.8*v),0);ad('spine',0,dir*(.5*u-1.0*v),0);} + if(a==='diving_lunge'){if(t<40){set('rSh',-1.6-.8*band(t,10,24)+1.2*band(t,30,36),0,-.3);ad('hips',.6*band(t,18,36),0,0);}else{set('hips',1.5,0,0);q.y=-.9+.6*band(t,108,124);set('rSh',-2.6,0,-.6);set('lSh',-2.4,0,.6);}} + if(a==='jump_sweep'){set('rSh',-1.0,0,-1.2);if(b.y>.3){set('lHip',-1.2,0,.2);set('rHip',-1.0,0,-.2);set('lKnee',1.4,0,0);set('rKnee',1.4,0,0);}ad('chest',0,-1.4*band(t,48,54),0);} + if(a==='overhead_slam'){const u=band(t,8,40),v=band(t,52,56);set('rSh',-3.0*u+1.7*v,0,-.15);set('rEl',-.3*u,0,0);ad('spine',-.2*u+.8*v,0,0);} + if(mv.scream){const u=band(t,mv.scream.from-40,mv.scream.from-8);set('lSh',-1.6-1.0*u,0,.2);set('lEl',-1.6*u,0,0);if(t>=mv.scream.from&&t=54&&t<100){const tip=this.bladePoints(this.bosses[kind==='isshin'?'isshin':'genichiro'],kind==='isshin'?1.75:1)[1];let last=[tip.x+Math.sin(t)*.4,tip.y+14,tip.z]; + for(let i=1;i<=8;i++){const s=i/8,j=i===8?0:(hash(i,t>>1)-.5)*1.2,next=[tip.x+j*(1-s),tip.y+14*(1-s),tip.z+j*(1-s)*.6];bo=this.link(this.fx.bolt,bo,last,next,.07,0xfff1c2);last=next;} + fl=this.place(this.fx.flash,fl,[tip.x,tip.y,tip.z],1.6+Math.sin(t*.7)*.4,camQ,0xffe9a0);}} + if(p.lightning>0){for(let i=0;i<6;i++){const a=hash(i,g.t>>1)*Math.PI*2;sp=this.link(this.fx.spark,sp,[p.x,(p.y||0)+1,p.z],[p.x+Math.cos(a)*.5,(p.y||0)+1+hash(i,g.t)-.5,p.z+Math.sin(a)*.5],.018,0xffe08a);}} + for(const h of items(g.hazards)){const k=h.type; + if(k==='arrow'||k==='lightning_arrow'||k==='kunai'){const q=this.dir(h.vx,h.vy,h.vz);pr=this.place(this.fx.proj,pr,[h.x,h.y,h.z],k==='kunai'?[.03,.03,.26]:[.025,.025,.75],q,k==='kunai'?0x2b2c33:h.charged?0xb38b52:0x8a6a44); + if(k==='lightning_arrow'){fl=this.place(this.fx.flash,fl,[h.x,h.y,h.z],.9,camQ,0xffe39a);}} + else if(k==='bullet'){const q=this.dir(h.vx,h.vy,h.vz);pr=this.place(this.fx.proj,pr,[h.x,h.y,h.z],[.03,.03,.3],q,0xffd27a);fl=this.place(this.fx.flash,fl,[h.x,h.y,h.z],h.age<4?1.1:.4,camQ,0xffc46a);} + else if(k==='wave'){// a force wave: a standing crescent (vertical) or a wide flat disc (horizontal) + const fx0=Math.cos(h.yaw),fz0=-Math.sin(h.yaw),n=7,w=h.wide?1.5:.55,tall=h.wide?.12:1.15;let last=null; + for(let i=0;i<=n;i++){const v=i/n*2-1,bow=1-v*v,pt=[h.x+fx0*v*w+Math.sin(h.yaw)*bow*.35,h.y+(h.wide?0:v*tall),h.z+fz0*v*w+Math.cos(h.yaw)*bow*.35];if(last)bo=this.link(this.fx.bolt,bo,last,pt,h.wide?.05:.04,h.burn?0xff9a40:0xdff3ff);last=pt;} + fl=this.place(this.fx.flash,fl,[h.x,h.y,h.z],h.wide?1.4:1,camQ,h.burn?0xff8a30:0xbfe6ff);} + else if(k==='ring'){const u=1-h.life/18,r=h.radius*(.25+u*.75);for(let i=0;i<24;i++){const a0=i/24*Math.PI*2,a1=(i+1)/24*Math.PI*2;bo=this.link(this.fx.bolt,bo,[h.x+Math.sin(a0)*r,.7,h.z+Math.cos(a0)*r],[h.x+Math.sin(a1)*r,.7,h.z+Math.cos(a1)*r],.028*(1-u)+.008,0xdff3ff);}} + else if(k==='mortal_arc'){// the black Mortal Blade's reach: a dark crimson sweep along its arc + const u=1-h.life/18;let last=null;for(let i=0;i<=8;i++){const a=(h.yaw||0)+(i/8-.5)*3,r=h.radius*(.45+u*.55),pt=[h.x+Math.sin(a)*r,.9+Math.sin(i/8*Math.PI)*.5,h.z+Math.cos(a)*r];if(last)pr=this.link(this.fx.proj,pr,last,pt,.14*(1-u)+.02,i%2?0x8e1016:0x2a0a10);last=pt;}} + else if(k==='rope_line'){const a=h.yaw||0;pr=this.link(this.fx.proj,pr,[h.x,h.y,h.z],[h.x+Math.sin(a)*h.radius,h.y-.8,h.z+Math.cos(a)*h.radius],.03,0x2c2118);pr=this.place(this.fx.proj,pr,[h.x+Math.sin(a)*h.radius,h.y-.8,h.z+Math.cos(a)*h.radius],[.05,.05,.34],this.dir(Math.sin(a),0,Math.cos(a)),0xd9dde2);} + else if(k==='fire'){const life=Math.min(1,(h.life||0)/30,(h.age||0)/6);for(let i=0;i<4;i++){const a=i*1.6+h.x,r=(h.radius||1)*.45,fy=.25+(.5+.5*Math.sin(g.t*.4+i*2))*.5; + fm=this.place(this.fx.flame,fm,[h.x+Math.cos(a)*r,fy*.5*life,h.z+Math.sin(a)*r],[.26*life,fy*1.3*life,.26*life],[0,a,0],i%2?0xff7a2a:0xffb040);}} + else if(k==='fireball'||k==='fire_shot'){pr=this.place(this.fx.proj,pr,[h.x,h.y,h.z],[(h.radius||.35)*1.3,(h.radius||.35)*1.3,(h.radius||.35)*1.3],[h.age*.3,h.age*.2,0],0xff8a2a); + fl=this.place(this.fx.flash,fl,[h.x,h.y,h.z],(h.radius||.35)*3.2,camQ,0xffa040);} + else if(k==='fire_ring'){const life=Math.min(1,(h.life||0)/40,(h.age||0)/12),n=64;for(let i=0;i=s.from&&t=54&&t<102?(.5+.5*Math.sin(t*.9))*(t>96?2:1):0;} + for(const h of items(g.hazards))if(h.type==='lightning_line'||h.type==='lightning_arc')flash=Math.max(flash,(h.life||0)/14*2.5);} + if(ar.fireLights)ar.fireLights.forEach((l,i)=>{l.intensity=5+Math.sin(tm*7+i*2)*1.2+Math.sin(tm*13+i)*.7;}); + if(ar.water)ar.water.material.color.setHSL(.51,.36,.36+Math.sin(tm*.8)*.02); + this.sun.intensity=sunI;this.hemi.intensity=hemiI;this.flashLight.intensity=flash*9;this.flashLight.position.set(b.x||0,6,b.z||0); + // Lock-on camera: behind and to the right of Sekiro, framing the target; pulled back and up for the ape. + const yaw=g.cameraYaw??Math.atan2((b.x||0)-(p.x||0),(b.z||0)-(p.z||0)),fx=Math.sin(yaw),fz=Math.cos(yaw),rx=-Math.cos(yaw),rz=Math.sin(yaw); + const sep=Math.hypot((b.x||0)-(p.x||0),(b.z||0)-(p.z||0)),big=kind==='ape'||kind==='gyoubu'||kind==='demon',huge=kind==='demon',air=Math.max(0,(b.y||0)-(p.y||0)); + const orbit=clamp(.9-sep*.08,.3,.8)*(big?.75:1),dist=clamp(3.6+sep*.17,3.8,5.5)+(big?2.2:0)+(huge?1.6:0),height=2.1+sep*.05+(big?1.4:0)+(huge?.9:0)+(p.y||0)*.6; + // an airborne target (leaps, threads, lightning) pulls the camera back and up so both stay in frame + const lift=clamp(air-.6,0,3.4),ox=Math.sin(yaw-orbit),oz=Math.cos(yaw-orbit);let pos=v3(p.x-ox*(dist+lift*.55),height+lift*.3,p.z-oz*(dist+lift*.55)); + const bodyH=huge?2.6:big?(b.form_id==='headless'?2.0:1.8):1.15;const wy=air>1?.52:.6;let look=v3(lerp(p.x,b.x,.62),lerp((p.y||0)+1.0,(b.y||0)+bodyH,wy),lerp(p.z,b.z,.62)); + if(kind==='butterfly'){pos.x=clamp(pos.x,-9.3,9.3);pos.z=clamp(pos.z,-7.3,7.3);pos.y=Math.min(pos.y,5.0); + // a pillar in the way: raise the eye and shorten the boom instead of looking through timber + for(const q of g.arena?.pillars||[]){const dx=pos.x-p.x,dz=pos.z-p.z,len=Math.hypot(dx,dz)||1,t=clamp(((q.x-p.x)*dx+(q.z-p.z)*dz)/(len*len),0,1),cx=p.x+dx*t,cz=p.z+dz*t; + // a pillar blocks the line of sight: shorten the boom towards Sekiro, then keep the eye out of any column + if(Math.hypot(cx-q.x,cz-q.z)15){pos.x*=15/r;pos.z*=15/r;}} + // a side angle during a deathblow; a little shake on clashes + if(b.executing>0||(p.action==='deathblow')){const u=band(p.actionTick||0,0,10);pos.lerp(v3(cx+rx*(big?6:3.8)-fx*1.2,big?2.6:1.7,cz+rz*(big?6:3.8)-fz*1.2),u);look.lerp(v3(cx,big?1.6:1.15,cz),u);} + let shake=0;for(const fx2 of items(g.effects))if(/deflect|mikiri|stomp/.test(fx2.type||''))shake=Math.max(shake,(fx2.life||0)/(fx2.maxLife||15)); + if(p.hurt>0)shake=Math.max(shake,p.hurt/12*.7);if(shake){pos.x+=Math.sin(g.t*1.7)*.04*shake;pos.y+=Math.cos(g.t*2.3)*.04*shake;} + if(g.view){pos=v3(...g.view.pos);look=v3(...g.view.look);} + this.camera.position.copy(pos);this.camera.lookAt(look);this.camera.updateMatrixWorld(); + this.effects(g,this.camera); + // sword trails while blades are swinging + const pa=p.attackTick>=(p.attackKind==='thrust'?8:5)&&p.attackTick<=(p.attackKind==='thrust'?12:10)?{alpha:.7,len:1.0}:null; + this.trail(0,this.player,pa,0xdfe9ff,k=>{if(p.attackTick-k<(p.attackKind==='thrust'?7:4))return false;applyPose(this.player,this.playerPose({...p,attackTick:p.attackTick-k,actionTick:(p.actionTick||0)-k},(g.t-k)/60));return true;}); + const mv=root.SekiroGame?.bosses?.[kind]?.moves?.[b.action],swing=b.state==='attack'&&mv&&(mv.hits||[]).some(h=>b.moveTick>=h.t&&b.moveTick<=h.t+4&&h.type!=='grab'&&h.type!=='kick'&&h.type!=='lightning'); + const bossBlade=kind==='ape'?(b.form_id==='headless'?{alpha:.7,len:2.7}:null):kind==='genichiro'?{alpha:.75,len:1}:kind==='isshin'?(model.bones.active?null:{alpha:.75,len:1}):kind==='gyoubu'||kind==='demon'?null:{alpha:.5,len:.3}; + const moves=root.SekiroGame?.bosses?.[kind]?.moves; + const hitT=(mv?.hits||[]).filter(h=>h.t<=b.moveTick).map(h=>h.t).pop()??0; + this.trail(1,model,swing&&bossBlade?bossBlade:null,kind==='genichiro'&&b.form_id==='tomoe'?0xffe7a0:0xffffff,k=>{if(b.moveTick-k120)this.times.shift();this.ready=true;this.error=null; + }catch(e){this.ready=false;this.error=String(e);throw e;} + } + project(x,y,z){const v=v3(x,y,z).project(this.camera);return {x:(v.x+1)*427,y:(1-v.y)*240,visible:v.z<1&&v.z>-1};} + metrics(){ + const info=this.renderer.info,sorted=[...this.times].sort((a,b)=>a-b);let geometryBytes=0,textureBytes=0; + for(const r of this.resources){if(r.isBufferGeometry){for(const a of Object.values(r.attributes))geometryBytes+=a.array.byteLength;if(r.index)geometryBytes+=r.index.array.byteLength;}if(r.isTexture&&r.image)textureBytes+=(r.image.width||0)*(r.image.height||0)*4;if(r.isInstancedMesh)geometryBytes+=r.instanceMatrix.array.byteLength;} + return {renderer:'webgl-boss3d',webglVersion:this.renderer.capabilities.isWebGL2?2:1,drawCalls:info.render.calls,triangles:info.render.triangles,geometries:info.memory.geometries,textures:info.memory.textures,geometryBytes,textureBytes,shadowMapBytes:1024*1024*4,canvasBytes:854*480*4,resourceBytesEstimate:geometryBytes+textureBytes+1024*1024*4+854*480*8,staticAssetBytes:669884,renderSamples:sorted.length,cpuRenderMsP50:sorted.length?sorted[Math.floor((sorted.length-1)*.5)]:null,cpuRenderMsP95:sorted.length?sorted[Math.floor((sorted.length-1)*.95)]:null,shadows:'one 1024x1024 directional map; fighters cast',postprocess:false,arena:this.kind}; + } + close(){if(this.closed)return;this.closed=true;this.ready=false;this.resources.forEach(r=>r.dispose?.());this.renderer.dispose();this.renderer.forceContextLoss();this.resources.clear();} + } + B.render=function(style,g,ctx){let m=byCanvas.get(ctx.canvas);if(!m){m=new Map();byCanvas.set(ctx.canvas,m);}let scene=m.get(style);if(!scene||scene.closed){scene=new Scene(ctx.canvas);m.set(style,scene);}scene.render(g,ctx);return scene;}; + B.scene=function(style,ctx){return ctx&&byCanvas.get(ctx.canvas)?.get(style)||null;}; + B.status=function(style,ctx){const s=ctx&&byCanvas.get(ctx.canvas)?.get(style);if(s&&!s.closed&&s.renderer.getContext().isContextLost()){s.ready=false;s.error='WebGL context lost';}return {renderer:'webgl-boss3d',kind:'perspective',ready:!!s?.ready&&!s.closed,error:s?.error||null};}; + B.metrics=function(style,ctx){const s=ctx&&byCanvas.get(ctx.canvas)?.get(style);return s?s.metrics():null;}; + B.close=function(style,ctx){const m=ctx&&byCanvas.get(ctx.canvas),s=m?.get(style);if(s){s.close();m.delete(style);}}; + B.bar=function(c,x,y,w,h,value,color){c.fillStyle='rgba(12,20,29,.8)';c.fillRect(x,y,w,h);c.fillStyle=color;c.fillRect(x+1,y+1,(w-2)*clamp(value,0,1),h-2);c.strokeStyle='rgba(229,210,169,.6)';c.strokeRect(x+.5,y+.5,w-1,h-1);}; + B.text=function(c,text,x,y,size=16,color='#f3ead9',align='left'){c.font=size+'px "Segoe UI","Microsoft YaHei",sans-serif';c.textAlign=align;c.fillStyle='rgba(8,15,23,.8)';c.fillText(text,x+1,y+1);c.fillStyle=color;c.fillText(text,x,y);}; +})(window); diff --git a/environments/games/web/games/sekiro_remake/style3d.css b/environments/games/web/games/sekiro_remake/style3d.css new file mode 100644 index 0000000000000000000000000000000000000000..df673172470e9188762c19cb2ab95c394082b9f0 --- /dev/null +++ b/environments/games/web/games/sekiro_remake/style3d.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#14191a;--panel:#1d2425;--edge:#354141;--text:#ebe7dc;--muted:#a5b2ad;--accent:#dfb676}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top,#29312b,transparent 60%),var(--bg);color:var(--text);font:14px/1.7 'Segoe UI','Microsoft YaHei',sans-serif}body[data-game=genshin_remake]{--bg:#101822;--panel:#1b2530;--edge:#374754;--accent:#baacff;background:radial-gradient(ellipse at top,#2b2942,transparent 60%),var(--bg)}main{max-width:1220px;margin:auto;padding:28px 24px 40px}header{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:20px}.eyebrow{color:var(--accent);font-size:11px;letter-spacing:2.5px;text-transform:uppercase}h1{font:500 32px/1.35 Georgia,'Microsoft YaHei',serif;letter-spacing:1px;margin:6px 0}header p{color:var(--muted);margin:0;font-size:13px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.layout{display:grid;grid-template-columns:minmax(0,854px) 245px;gap:24px;align-items:start}.stage{position:relative;border:1px solid var(--edge);box-shadow:0 22px 55px #0005;background:#111b1c}canvas{display:block;width:100%;aspect-ratio:854/480;touch-action:none;outline:none}canvas:focus-visible{outline:2px solid var(--accent);outline-offset:3px}#overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#10171b30;pointer-events:none}#overlay[hidden]{display:none}#overlay div{background:#111b23de;padding:19px 32px;border:1px solid #9ba6a655;max-width:80%;text-align:center}#overlay strong{font:500 24px Georgia,'Microsoft YaHei',serif;display:block}#overlay span{display:block;color:var(--muted);font-size:12px;margin-top:7px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;padding:12px;background:var(--panel);border-top:1px solid var(--edge)}button,select,input{font:inherit;background:var(--panel);color:var(--text);border:1px solid var(--edge);border-radius:4px;padding:7px 11px}button{cursor:pointer}button:hover{border-color:var(--accent);background:#ffffff09}button.primary{background:var(--accent);color:var(--bg);font-weight:600}button:focus-visible,select:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}aside{padding:19px;border:1px solid var(--edge);background:var(--panel)}h2{font-size:16px;margin:0 0 8px}label{display:block;font-size:12px;color:var(--muted);margin:12px 0 5px}select,input{width:100%}dl{border-top:1px solid var(--edge);padding-top:16px;margin:18px 0 0}dt{color:var(--accent);font:12px/1.8 Consolas,monospace}dd{color:var(--muted);font-size:12px;margin:0 0 10px}.note{color:var(--muted);font-size:12px}#status{min-height:25px;margin:10px 0;color:var(--accent);overflow-wrap:anywhere}.record-toolbar{border:1px solid var(--edge);padding:10px;background:transparent}.record-toolbar button{font-size:12px}#file{display:none}.mobile{display:none}footer{display:flex;flex-wrap:wrap;gap:22px;border-top:1px solid var(--edge);margin-top:28px;padding-top:15px;font-size:12px}@media(max-width:950px){main{padding:14px}.layout{grid-template-columns:1fr}aside{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}aside dl,aside .note{grid-column:1/-1}dl{columns:2}.mobile{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.mobile button{min-width:45px;touch-action:none}header{align-items:start}h1{font-size:26px}}@media(max-width:500px){header{display:block}header a{font-size:12px}aside{padding:14px}#overlay div{padding:14px 20px}#overlay strong{font-size:19px}.toolbar{gap:6px;padding:8px}button{font-size:12px}h1{font-size:25px}} diff --git a/environments/games/web/games/soulknight_remake/compact_actions.json b/environments/games/web/games/soulknight_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..5dd4f8530deb990893e055cc10bc6fc901061e2e --- /dev/null +++ b/environments/games/web/games/soulknight_remake/compact_actions.json @@ -0,0 +1,176 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "soulknight_remake", + "version": "soulknight-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "down_right", + "keys": [ + "S", + "D" + ] + }, + { + "label": "down", + "keys": [ + "S" + ] + }, + { + "label": "down_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "up_left", + "keys": [ + "W", + "A" + ] + }, + { + "label": "up", + "keys": [ + "W" + ] + }, + { + "label": "up_right", + "keys": [ + "W", + "D" + ] + } + ] + }, + { + "name": "aim", + "options": [ + { + "label": "none" + }, + { + "label": "right_40", + "dx": 40, + "dy": 0 + }, + { + "label": "down_right_40", + "dx": 28, + "dy": 28 + }, + { + "label": "down_40", + "dx": 0, + "dy": 40 + }, + { + "label": "down_left_40", + "dx": -28, + "dy": 28 + }, + { + "label": "left_40", + "dx": -40, + "dy": 0 + }, + { + "label": "up_left_40", + "dx": -28, + "dy": -28 + }, + { + "label": "up_40", + "dx": 0, + "dy": -40 + }, + { + "label": "up_right_40", + "dx": 28, + "dy": -28 + } + ] + }, + { + "name": "act", + "options": [ + { + "label": "none" + }, + { + "label": "fire", + "keys": [ + "J" + ] + }, + { + "label": "fire_skill", + "subs": [ + [ + "J", + "K" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "switch", + "subs": [ + [ + "Q" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/soulknight_remake/draw.js b/environments/games/web/games/soulknight_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..a9194ba1bb62c91173417eb47ec97b74c9f1812d --- /dev/null +++ b/environments/games/web/games/soulknight_remake/draw.js @@ -0,0 +1,852 @@ +/* Soul Knight arena renderer (read-only). Procedural pixel art: every sprite is painted at + * art resolution, alpha-thresholded, given a 1-art-pixel outline and blitted at 2x without + * smoothing. Never mutates the game object or consumes game RNG; screen shake and decorations + * use hashes of the tick / tile coordinates, so a frame is a pure function of the state. + */ +(function (root) { + 'use strict'; + const M = root.SoulKnightGame, TAU = Math.PI * 2, R = M.room, TILE = M.tile; + const FONT = "'Microsoft YaHei','PingFang SC','Noto Sans CJK SC','Noto Sans SC',sans-serif"; + const cache = new Map(); + const hash = (a, b) => { let h = (Math.imul(a | 0, 73856093) ^ Math.imul(b | 0, 19349663) ^ 0x5bd1e995) >>> 0; h = Math.imul(h ^ (h >>> 15), 2246822519) >>> 0; h = Math.imul(h ^ (h >>> 13), 3266489917) >>> 0; return ((h ^ (h >>> 16)) >>> 0) / 4294967296; }; + const mk = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }; + // cached art lives in software-backed canvases: the harness reads every captured frame back (toDataURL), which + // moves the frame canvas to software; GPU-backed sources would then cost a GPU->CPU copy per drawImage + const ctx2d = c => c.getContext('2d', { willReadFrequently: true }); + const poly = (x, pts) => { x.beginPath(); x.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) x.lineTo(pts[i][0], pts[i][1]); x.closePath(); x.fill(); }; + const ell = (x, col, cx, cy, rx, ry, rot) => { x.fillStyle = col; x.beginPath(); x.ellipse(cx, cy, rx, ry, rot || 0, 0, TAU); x.fill(); }; + const starPath = (x, cx, cy, r1, r2, n, rot) => { x.beginPath(); for (let i = 0; i < n * 2; i++) { const a = (rot || -Math.PI / 2) + i * Math.PI / n, r = i % 2 ? r2 : r1; x.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); } x.closePath(); }; + + // ---------- sprite pipeline ---------- + function sprite(key, w, h, paint, outline) { + let s = cache.get(key); + if (s) return s; + const c = mk(w + 2, h + 2), x = ctx2d(c); + x.translate(1, 1); paint(x); x.setTransform(1, 0, 0, 1, 0, 0); + const img = x.getImageData(0, 0, c.width, c.height), d = img.data, n = c.width * c.height, cw = c.width; + const solid = new Uint8Array(n); + for (let i = 0; i < n; i++) { const on = d[i * 4 + 3] >= 110; d[i * 4 + 3] = on ? 255 : 0; solid[i] = on; } + if (outline !== false) { + const oc = outline || [18, 14, 26]; + for (let y = 0; y < c.height; y++) for (let xx = 0; xx < cw; xx++) { + const i = y * cw + xx; + if (solid[i]) continue; + if ((xx > 0 && solid[i - 1]) || (xx < cw - 1 && solid[i + 1]) || (y > 0 && solid[i - cw]) || (y < c.height - 1 && solid[i + cw])) { + d[i * 4] = oc[0]; d[i * 4 + 1] = oc[1]; d[i * 4 + 2] = oc[2]; d[i * 4 + 3] = 255; + } + } + } + x.putImageData(img, 0, 0); + const f = mk(c.width, c.height), fx = ctx2d(f); + fx.drawImage(c, 0, 0); fx.globalCompositeOperation = 'source-atop'; fx.fillStyle = '#ffffff'; fx.fillRect(0, 0, f.width, f.height); + s = { c, f, w: c.width, h: c.height }; + cache.set(key, s); + return s; + } + function fromMatrix(key, rows, pal) { + const w = Math.max(...rows.map(r => r.length)); + return sprite(key, w, rows.length, x => { rows.forEach((row, y) => { for (let i = 0; i < row.length; i++) { const col = pal[row[i]]; if (col) { x.fillStyle = col; x.fillRect(i, y, 1, 1); } } }); }); + } + // anchor = bottom centre at (x, y) in screen px, k = pixel scale + function blit(c, s, x, y, k, flip, flash, alpha) { + const w = s.w * k, h = s.h * k; + c.save(); c.translate(Math.round(x), Math.round(y)); + if (flip) c.scale(-1, 1); + if (alpha !== undefined) c.globalAlpha = alpha; + c.drawImage(s.c, -Math.round(w / 2), -h, w, h); + if (flash) { c.globalAlpha = (alpha === undefined ? 1 : alpha) * (flash === true ? 0.7 : flash); c.drawImage(s.f, -Math.round(w / 2), -h, w, h); } + c.restore(); + } + + // ---------- characters ---------- + const KPAL = { w: '#f2f6fa', s: '#c4cdd8', g: '#8d98a8', d: '#5d6676', v: '#222a3a', e: '#ffe46b', r: '#e5483f', R: '#a52f2c', b: '#3b4152' }; + const KBODY = ['....wwss....', '...wssssg...', '..wsssssgg..', '..sssvvvvg..', '..ssvvvevg..', '..gssvvvvg..', '..ggsssssg..', + '.rrrrrrrrRR.', '..RRrssgRR..', '.Rsswsssggd.', '..ssssssggd.', '..ssssssgd..', '..gsgggsgd..']; + const KLEGS = [['...gd..gd...', '...bb..bb...', '..bbb..bbb..'], ['..gd....gd..', '..bb....bb..', '.bbb....bbb.']]; + const knight = f => fromMatrix('knight' + f, KBODY.concat(KLEGS[f]), KPAL); + + function paintGP(x, angry) { + const fe = ['#e8833a', '#f6d65a']; + for (let i = 0; i < 5; i++) { x.fillStyle = fe[i % 2]; const bx = 6 + i * 3; poly(x, [[bx, 8], [bx + 1.5, Math.abs(i - 2) * 1.2], [bx + 3, 8]]); } + x.fillStyle = '#4f9a3f'; poly(x, [[8, 9], [0, 5], [8, 14]]); poly(x, [[18, 9], [26, 5], [18, 14]]); + x.fillStyle = '#d98b8b'; poly(x, [[7, 10], [3, 7], [7, 12]]); poly(x, [[19, 10], [23, 7], [19, 12]]); + ell(x, '#5fae4a', 13, 11.5, 6.5, 5.5); ell(x, '#88d06a', 11, 9.5, 3.5, 2.4); + x.fillStyle = '#f2c94c'; x.fillRect(6, 6, 14, 2); x.fillStyle = '#e04a4a'; x.fillRect(12, 6, 2, 2); + x.fillStyle = angry ? '#ff3020' : '#ffd23a'; x.fillRect(9, 10, 3, 2); x.fillRect(15, 10, 3, 2); + x.fillStyle = '#16181c'; x.fillRect(11, 10, 1, 2); x.fillRect(17, 10, 1, 2); + if (angry) { x.fillRect(9, 9, 3, 1); x.fillRect(15, 9, 3, 1); } + x.fillStyle = '#2a1414'; x.fillRect(10, 14, 7, 1); x.fillStyle = '#f4efe6'; x.fillRect(11, 14, 1, 1); x.fillRect(15, 14, 1, 1); + x.fillStyle = '#6c3fa0'; poly(x, [[8, 16], [18, 16], [22, 29], [4, 29]]); + x.fillStyle = '#4a2a73'; poly(x, [[15, 16], [18, 16], [22, 29], [16, 29]]); + x.fillStyle = '#9a6ad0'; poly(x, [[8, 16], [10, 16], [7, 29], [4, 29]]); + x.fillStyle = '#f2c94c'; x.fillRect(4, 27, 18, 2); x.fillRect(12, 17, 2, 10); + x.fillStyle = '#7a4a2a'; x.fillRect(7, 21, 12, 2); + x.fillStyle = '#f4efe6'; x.fillRect(9, 16, 2, 1); x.fillRect(12, 17, 2, 1); x.fillRect(15, 16, 2, 1); + ell(x, '#5fae4a', 5, 21, 2, 2); ell(x, '#5fae4a', 21, 21, 2, 2); + } + function paintCT(x, angry) { + x.fillStyle = '#7a5230'; x.fillRect(11, 37, 6, 8); x.fillRect(21, 37, 6, 8); + x.fillStyle = '#5a3a20'; x.fillRect(15, 37, 2, 8); x.fillRect(25, 37, 2, 8); + x.fillStyle = '#a0703f'; x.fillRect(11, 37, 2, 8); x.fillRect(21, 37, 2, 8); + for (const [top, bot, hw] of [[6, 16, 8], [14, 27, 12], [22, 39, 16]]) { + x.fillStyle = angry ? '#2c5f30' : '#2d6a3a'; poly(x, [[19, top - 5], [19 - hw, bot], [19 + hw, bot]]); + x.fillStyle = angry ? '#3b7c3e' : '#3f8f4c'; poly(x, [[19, top - 5], [19 - hw, bot], [17, bot]]); + x.fillStyle = '#eef6fb'; poly(x, [[19, top - 5], [19 - hw * 0.55, top + 3], [19 - hw * 0.25, top + 1], [19, top + 4], [19 + hw * 0.3, top + 1], [19 + hw * 0.55, top + 3]]); + x.fillStyle = '#d6e8f3'; x.fillRect(19 - hw + 2, bot - 1, hw * 2 - 4, 1); + } + x.fillStyle = '#16181c'; x.fillRect(14, 28, 3, 3); x.fillRect(22, 28, 3, 3); + x.fillStyle = angry ? '#ff3a2a' : '#ffffff'; x.fillRect(15, 28, 1, 1); x.fillRect(23, 28, 1, 1); + if (angry) { x.fillStyle = '#16181c'; x.fillRect(13, 26, 2, 1); x.fillRect(15, 27, 2, 1); x.fillRect(24, 26, 2, 1); x.fillRect(22, 27, 2, 1); } + x.fillStyle = '#5a2a1a'; x.fillRect(17, 32, 5, 2); + x.fillStyle = '#d7303a'; x.fillRect(8, 35, 23, 3); x.fillStyle = '#f4f4f4'; for (let i = 9; i < 31; i += 4) x.fillRect(i, 35, 2, 3); + x.fillStyle = '#d7303a'; x.fillRect(26, 38, 4, 6); x.fillStyle = '#a32028'; x.fillRect(28, 38, 2, 6); + for (const [ox, oy, oc] of [[12, 21, '#ff4a4a'], [26, 19, '#ffd23a'], [16, 12, '#5ac8ff'], [24, 25, '#ff4a4a'], [10, 31, '#ffd23a'], [29, 30, '#5ac8ff'], [20, 8, '#ff4a4a']]) { + x.fillStyle = oc; x.fillRect(ox, oy, 2, 2); x.fillStyle = '#ffffff'; x.fillRect(ox, oy, 1, 1); + } + x.fillStyle = '#ffd23f'; starPath(x, 19, 3, 4, 1.8, 5); x.fill(); + } + function paintDS(x, open) { + const cx = 22, cy = 21; + for (let i = 0; i < 6; i++) { const a = i * TAU / 6 + 0.3; ell(x, i % 2 ? '#2f7a3f' : '#46a052', cx + Math.cos(a) * 13, cy + 7 + Math.sin(a) * 8, 8.5, 4.5, a); } + if (!open) { + ell(x, '#7a2f8f', cx, cy - 2, 12, 14); ell(x, '#a24bb8', cx - 3, cy - 4, 7, 10); ell(x, '#c77ad8', cx - 5, cy - 8, 2.5, 3.5); + x.fillStyle = '#4e1a60'; x.fillRect(cx - 1, cy - 15, 2, 26); x.fillRect(cx - 7, cy - 10, 1, 18); x.fillRect(cx + 6, cy - 10, 1, 18); + x.fillStyle = '#f2d24a'; for (const [sx, sy] of [[cx - 6, cy - 5], [cx + 3, cy - 8], [cx + 7, cy + 2], [cx - 4, cy + 5], [cx + 2, cy]]) x.fillRect(sx, sy, 2, 2); + x.fillStyle = '#c86ad8'; x.fillRect(cx - 4, cy - 20, 1, 5); x.fillRect(cx, cy - 21, 1, 6); x.fillRect(cx + 3, cy - 20, 1, 5); + } else { + for (let i = 0; i < 6; i++) { const a = i * TAU / 6 - Math.PI / 2; ell(x, i % 2 ? '#c2459a' : '#e06ab8', cx + Math.cos(a) * 11, cy + Math.sin(a) * 10, 8.5, 5, a); ell(x, '#f7a0d8', cx + Math.cos(a) * 13, cy + Math.sin(a) * 12, 3, 1.6, a); } + ell(x, '#4e1240', cx, cy, 9, 9); + ell(x, '#8fd65a', cx, cy, 6.5, 6.5); ell(x, '#b8f08a', cx - 2, cy - 2, 3, 2.5); + x.fillStyle = '#ffffff'; x.fillRect(cx - 3, cy - 4, 6, 4); x.fillStyle = '#e02a2a'; x.fillRect(cx - 1, cy - 3, 2, 2); + x.fillStyle = '#16181c'; x.fillRect(cx - 4, cy + 2, 8, 2); x.fillStyle = '#f4efe6'; for (let i = -3; i < 4; i += 2) x.fillRect(cx + i, cy + 2, 1, 1); + } + } + // ---------- 11-02 expansion bosses (original art; half-resolution art blitted at 2x like every other sprite) ---------- + function paintGS(x, angry) { // Grand Slime 36x28: wobbling red-pink jelly with a crown; enraged = darker, angry brows + const body = angry ? '#d8344a' : '#ef5a6a', dark = angry ? '#9a1a30' : '#c23a4c', light = angry ? '#f27a88' : '#ff9aa6'; + ell(x, dark, 18, 17.5, 17, 10.5); + ell(x, body, 18, 17, 16.5, 10); + ell(x, light, 13, 13, 6, 3.5); ell(x, '#ffd8de', 10, 12, 2, 1.2); + x.fillStyle = dark; for (const [dx, h] of [[5, 2], [11, 3], [25, 3], [31, 2]]) x.fillRect(dx, 25, 1.5, h); + x.fillStyle = '#16181c'; x.fillRect(12, 15, 2, 3); x.fillRect(22, 15, 2, 3); + x.fillStyle = '#ffffff'; x.fillRect(12, 15, 1, 1); x.fillRect(22, 15, 1, 1); + if (angry) { x.fillStyle = '#16181c'; x.fillRect(11, 13, 4, 1); x.fillRect(21, 13, 4, 1); } + x.fillStyle = '#4a1018'; x.fillRect(15, 21, 6, 1); x.fillStyle = '#f4efe6'; x.fillRect(16, 21, 1, 1); x.fillRect(19, 21, 1, 1); + x.fillStyle = '#f2c94c'; poly(x, [[12, 7.5], [13, 2], [15, 5], [18, 1], [21, 5], [23, 2], [24, 7.5]]); + x.fillStyle = '#c99a2a'; x.fillRect(12, 6, 12, 1.5); x.fillStyle = '#5ac8ff'; x.fillRect(17, 3.5, 2, 1.5); + } + function paintVL(x, angry) { // Varkolyn Leader 18x32: tall void alien in a hooded cloak, swirl mark on the leg + const cloak = angry ? '#5a2a8a' : '#3e2a6a', trim = angry ? '#c46aff' : '#8a6ad8'; + x.fillStyle = cloak; poly(x, [[6, 10], [12, 10], [16, 31], [2, 31]]); + x.fillStyle = '#2a1a4a'; poly(x, [[9, 10], [12, 10], [16, 31], [10, 31]]); + x.fillStyle = trim; x.fillRect(2, 30, 14, 1); x.fillRect(8.5, 11, 1, 18); + ell(x, '#1a1030', 9, 6, 6, 6); ell(x, '#2a1a4a', 9, 5.5, 5.5, 5.5); + ell(x, '#9ff4c8', 9, 7, 3.5, 2.6); + x.fillStyle = angry ? '#ff3a6a' : '#16181c'; x.fillRect(6.5, 6, 1.5, 1.5); x.fillRect(10, 6, 1.5, 1.5); + x.strokeStyle = angry ? '#ff6af0' : '#6af0ff'; x.lineWidth = 0.8; x.beginPath(); x.arc(5.5, 22, 1.8, 0, 5.2); x.stroke(); + x.fillStyle = '#6ad8b0'; x.fillRect(1, 15, 2, 2); x.fillRect(15, 15, 2, 2); + } + function paintVS(x, angry) { // Volcanic Sandworm 22x40: armoured segmented worm rearing out of the ground + const plate = angry ? '#d0602a' : '#b06a3a', dark = '#5a2a14', glow = angry ? '#ffd04a' : '#ff8a3a'; + for (let i = 0; i < 5; i++) { + const y = 36 - i * 6.5, w = 6.8 - i * 0.3; + ell(x, dark, 11, y + 0.5, w + 0.5, 3); ell(x, plate, 11, y, w, 2.7); + x.fillStyle = glow; x.fillRect(11 - w + 1.5, y - 0.5, 1, 1); x.fillRect(11 + w - 2.5, y - 0.5, 1, 1); + } + ell(x, dark, 11, 6, 8, 5); ell(x, plate, 11, 5.5, 7.5, 4.5); + x.fillStyle = '#2a0e06'; poly(x, [[6, 6], [16, 6], [13, 10], [9, 10]]); + x.fillStyle = '#f4efe6'; for (const dx of [7.5, 10, 12.5, 15]) poly(x, [[dx - 0.6, 6], [dx + 0.6, 6], [dx, 7.8]]); + x.fillStyle = glow; x.fillRect(6, 2, 2, 1); x.fillRect(14, 2, 2, 1); + } + const bossSprite = (kind, alt) => kind === 'goblin_priest' ? sprite('gp' + alt, 26, 30, x => paintGP(x, alt)) + : kind === 'christmas_treant' ? sprite('ct' + alt, 38, 46, x => paintCT(x, alt)) + : kind === 'grand_slime' ? sprite('gs' + alt, 36, 28, x => paintGS(x, alt)) + : kind === 'varkolyn_leader' ? sprite('vl' + alt, 18, 32, x => paintVL(x, alt)) + : kind === 'volcanic_sandworm' ? sprite('vs' + alt, 22, 40, x => paintVS(x, alt)) + : sprite('ds' + alt, 44, 42, x => paintDS(x, alt)); + // minions: slime 10x8 (body = hit circle), tentacle 10x18 (body = hit capsule [-16, 0] r 10) + const minionSprite = (kind, f) => kind === 'slime' ? sprite('slime' + f, 10, 8, x => { + ell(x, '#c23a4c', 5, 4.5, 5, 3.5 - f * 0.4); ell(x, '#ef5a6a', 5, 4, 4.5, 3 - f * 0.4); ell(x, '#ff9aa6', 3.5, 2.8, 1.5, 0.9); + x.fillStyle = '#16181c'; x.fillRect(3, 4, 1, 1.5); x.fillRect(6, 4, 1, 1.5); + }) : sprite('tent' + f, 10, 18, x => { + for (let i = 0; i < 5; i++) { const y = 16 - i * 3, w = 4.5 - i * 0.5, o = Math.sin(i * 0.9 + f * 1.4) * 0.8; ell(x, i % 2 ? '#5a2a8a' : '#7a3aaa', 5 + o, y, w, 2); } + ell(x, '#c46aff', 5, 2.5, 2.2, 2.2); x.fillStyle = '#e8fff4'; x.fillRect(4.5, 1.8, 1, 1); + }); + + // ---------- props ---------- + const PROPS = { + tepee: () => sprite('tepee', 36, 30, x => { + x.fillStyle = '#c9a36a'; poly(x, [[18, 3], [1, 30], [35, 30]]); x.fillStyle = '#a8814a'; poly(x, [[18, 3], [26, 30], [35, 30]]); + x.fillStyle = '#8a3a2a'; for (const y of [12, 18, 24]) { const hw = (y - 3) * 17 / 27; x.fillRect(18 - hw, y, hw * 2, 2); } + x.fillStyle = '#f2c94c'; for (const y of [15, 21]) { const hw = (y - 3) * 17 / 27; for (let i = -hw + 2; i < hw - 1; i += 4) x.fillRect(18 + i, y, 2, 1); } + x.fillStyle = '#2e2014'; poly(x, [[18, 15], [13, 30], [23, 30]]); + x.fillStyle = '#6a4a2a'; x.fillRect(15, 0, 1, 7); x.fillRect(20, 0, 1, 7); x.fillRect(17, 0, 1, 6); + }), + totem: () => sprite('totem', 12, 28, x => { + x.fillStyle = '#8a5a2a'; x.fillRect(3, 2, 6, 26); x.fillStyle = '#6a4220'; x.fillRect(7, 2, 2, 26); + x.fillStyle = '#c84a3a'; x.fillRect(0, 9, 12, 3); x.fillStyle = '#e8833a'; x.fillRect(0, 9, 3, 1); x.fillRect(9, 9, 3, 1); + x.fillStyle = '#f2c94c'; x.fillRect(4, 4, 1, 2); x.fillRect(7, 4, 1, 2); x.fillStyle = '#2a1a10'; x.fillRect(4, 16, 4, 2); x.fillRect(4, 21, 4, 1); + x.fillStyle = '#3a8acf'; x.fillRect(4, 13, 4, 1); x.fillStyle = '#5a3a1a'; x.fillRect(2, 0, 8, 2); + }), + torch: () => sprite('torch', 6, 14, x => { x.fillStyle = '#6a4a2a'; x.fillRect(2, 4, 2, 10); x.fillStyle = '#4a3220'; x.fillRect(1, 3, 4, 2); }), + stone: () => sprite('stone', 24, 30, x => { + x.fillStyle = '#7d8a8f'; x.fillRect(0, 6, 24, 24); x.fillStyle = '#a2afb3'; x.fillRect(0, 0, 24, 8); + x.fillStyle = '#5f6b70'; x.fillRect(0, 26, 24, 4); x.fillRect(20, 7, 4, 23); + x.fillStyle = '#4f8a3f'; x.fillRect(0, 0, 24, 2); x.fillRect(2, 2, 6, 2); x.fillRect(14, 2, 5, 1); x.fillRect(0, 8, 2, 5); + x.fillStyle = '#56626a'; x.fillRect(6, 14, 5, 1); x.fillRect(10, 15, 1, 4); x.fillRect(15, 20, 4, 1); x.fillRect(4, 22, 1, 3); + }), + tree: () => sprite('tree', 24, 38, x => { + x.fillStyle = '#6b4527'; x.fillRect(10, 30, 4, 8); + for (const [top, bot, hw] of [[2, 14, 6], [9, 22, 9], [16, 31, 12]]) { + x.fillStyle = '#2b6236'; poly(x, [[12, top - 2], [12 - hw, bot], [12 + hw, bot]]); x.fillStyle = '#3a8046'; poly(x, [[12, top - 2], [12 - hw, bot], [11, bot]]); + x.fillStyle = '#eef6fb'; poly(x, [[12, top - 2], [12 - hw * 0.5, top + 4], [12, top + 3], [12 + hw * 0.5, top + 4]]); x.fillRect(12 - hw + 1, bot - 1, hw * 2 - 2, 1); + } + }), + crate: d => sprite('crate' + d, 12, 14, x => { + x.fillStyle = '#d29a52'; x.fillRect(0, 0, 12, 4); x.fillStyle = '#aa763c'; x.fillRect(0, 3, 12, 11); + x.fillStyle = '#7a4f24'; x.fillRect(0, 3, 12, 1); x.fillRect(0, 13, 12, 1); x.fillRect(0, 3, 1, 11); x.fillRect(11, 3, 1, 11); + x.fillStyle = '#8a5a2a'; for (let i = 0; i < 9; i++) x.fillRect(1 + i, 4 + i, 2, 1); + if (d) { x.fillStyle = '#3a2410'; x.fillRect(3, 6, 1, 3); x.fillRect(4, 8, 2, 1); x.fillRect(8, 5, 1, 2); x.fillRect(7, 10, 2, 1); } + }), + // Grand Slime room: smiling-face boxes (doc) and weapon crates + smile: d => sprite('smile' + d, 12, 14, x => { + x.fillStyle = '#e8c070'; x.fillRect(0, 0, 12, 4); x.fillStyle = '#c99a4a'; x.fillRect(0, 3, 12, 11); + x.fillStyle = '#8a6224'; x.fillRect(0, 3, 12, 1); x.fillRect(0, 13, 12, 1); x.fillRect(0, 3, 1, 11); x.fillRect(11, 3, 1, 11); + x.fillStyle = '#3a2410'; x.fillRect(3, 6, 2, 2); x.fillRect(7, 6, 2, 2); x.fillRect(3, 10, 6, 1); x.fillRect(2, 9, 1, 1); x.fillRect(9, 9, 1, 1); + if (d) { x.fillRect(5, 4, 1, 2); x.fillRect(9, 11, 2, 1); } + }), + wcrate: d => sprite('wcrate' + d, 14, 14, x => { + x.fillStyle = '#8a94a2'; x.fillRect(0, 0, 14, 4); x.fillStyle = '#5a6270'; x.fillRect(0, 3, 14, 11); + x.fillStyle = '#2f343c'; x.fillRect(0, 3, 14, 1); x.fillRect(0, 13, 14, 1); x.fillStyle = '#f2c94c'; x.fillRect(5, 6, 4, 3); x.fillRect(6, 9, 2, 2); + if (d) { x.fillStyle = '#1a1e24'; x.fillRect(2, 5, 1, 3); x.fillRect(11, 10, 2, 1); } + }), + // Volcanic Sandworm room: one pillar (doc) + pillar: () => sprite('pillar', 24, 34, x => { + x.fillStyle = '#4a3a34'; x.fillRect(1, 6, 22, 28); x.fillStyle = '#6a544a'; x.fillRect(1, 6, 6, 28); + x.fillStyle = '#2a1e1a'; x.fillRect(17, 6, 6, 28); x.fillStyle = '#8a7060'; x.fillRect(0, 0, 24, 7); x.fillStyle = '#a88a74'; x.fillRect(0, 0, 24, 2); + x.fillStyle = '#ff7a2a'; x.fillRect(8, 14, 2, 8); x.fillRect(10, 20, 4, 2); x.fillRect(13, 22, 2, 6); x.fillStyle = '#ffd04a'; x.fillRect(8, 15, 1, 5); + }) + }; + const WEAPON_ART = { + pistol: () => sprite('w-pistol', 9, 6, x => { x.fillStyle = '#9aa3ad'; x.fillRect(0, 0, 9, 3); x.fillStyle = '#d4dbe2'; x.fillRect(1, 0, 7, 1); x.fillStyle = '#4a3a2a'; x.fillRect(1, 3, 3, 3); }), + rifle: () => sprite('w-rifle', 16, 6, x => { x.fillStyle = '#5a6270'; x.fillRect(3, 0, 13, 3); x.fillStyle = '#8a94a2'; x.fillRect(4, 0, 11, 1); x.fillStyle = '#7a5230'; x.fillRect(0, 1, 4, 3); x.fillStyle = '#2f343c'; x.fillRect(7, 3, 3, 3); x.fillRect(4, 3, 2, 2); }), + sword: () => sprite('w-sword', 22, 7, x => { x.fillStyle = '#d8e0e8'; x.fillRect(6, 2, 16, 3); x.fillStyle = '#ffffff'; x.fillRect(7, 2, 14, 1); x.fillStyle = '#9aa6b2'; x.fillRect(6, 4, 15, 1); x.fillStyle = '#c9a227'; x.fillRect(4, 0, 2, 7); x.fillStyle = '#7a4a2a'; x.fillRect(0, 2, 4, 3); }) + }; + const ICONS = { + hp: () => fromMatrix('i-hp', ['.RR.RR.', 'RrrRrrR', 'RrwrrrR', '.RrrrR.', '..RrR..', '...R...'], { R: '#b5282c', r: '#ff5050', w: '#ffc0c0' }), + armor: () => fromMatrix('i-armor', ['SSSSSSS', 'SwsssgS', 'SsssssS', '.SsssS.', '..SsS..', '...S...'], { S: '#6b7686', s: '#c4cdd8', w: '#ffffff', g: '#9aa4b2' }), + energy: () => fromMatrix('i-energy', ['...B...', '..BwB..', '.BbbbB.', 'BbbbbbB', '.BbbbB.', '..BbB..', '...B...'], { B: '#2a6ad0', b: '#5ab4ff', w: '#e0f4ff' }), + angry: () => fromMatrix('i-angry', ['.R...R.', 'RrR.RrR', '.RrrrR.', '..RrR..', '.RrrrR.', 'RrR.RrR', '.R...R.'], { R: '#a01818', r: '#ff3a3a' }), + orb: () => sprite('i-orb', 6, 7, x => { x.fillStyle = '#3a8aff'; poly(x, [[3, 0], [6, 3.5], [3, 7], [0, 3.5]]); x.fillStyle = '#bfe4ff'; x.fillRect(2, 2, 1, 2); }) + }; + + // ---------- bullets (screen resolution, cached) ---------- + function bulletSprite(kind, r) { + const key = 'b' + kind + r; + let s = cache.get(key); + if (s) return s; + const pad = 3, size = Math.ceil(r * 2 + pad * 2 + 6), c = mk(size, size), x = ctx2d(c), m = size / 2; + const disc = (rr, col) => ell(x, col, m, m, rr, rr); + if (kind === 'star') { + x.fillStyle = '#3a2a06'; starPath(x, m, m, r + 3, r * 0.5 + 2, 5); x.fill(); + x.fillStyle = '#ffd43a'; starPath(x, m, m, r + 1, r * 0.5, 5); x.fill(); + x.fillStyle = '#fff4b0'; starPath(x, m - 1, m - 1, r * 0.45, r * 0.2, 5); x.fill(); + } else if (kind === 'cross') { + const arm = (w, h, col) => { x.fillStyle = col; x.fillRect(m - w / 2, m - h / 2, w, h); x.fillRect(m - h / 2, m - w / 2, h, w); }; + arm(r * 2 + 4, r * 0.9 + 4, '#3a1406'); arm(r * 2, r * 0.9, '#ff8a2a'); arm(r * 1.1, r * 0.35, '#ffe0a0'); + } else if (kind === 'bubble') { + disc(r + 2, 'rgba(58,20,70,0.85)'); disc(r, 'rgba(226,128,236,0.75)'); disc(r - 2, 'rgba(250,190,255,0.55)'); ell(x, '#ffffff', m - r * 0.35, m - r * 0.35, 2, 1.6); + } else if (kind === 'homing') { + disc(r + 2, '#1a1640'); disc(r, '#6f74ff'); disc(r * 0.55, '#d4d6ff'); ell(x, '#ffffff', m - 1.5, m - 1.5, 1.4, 1.4); + } else if (kind === 'diamond' || kind === 'slam' || kind === 'petal') { // Grand Slime bullets + const col = kind === 'diamond' ? ['#3a0612', '#ff2a4a', '#ffd0d8'] : kind === 'petal' ? ['#3a1a06', '#ffb03a', '#fff0c0'] : ['#3a0612', '#ff5a6a', '#ffd0d8']; + if (kind === 'diamond') { x.fillStyle = col[0]; poly(x, [[m, m - r - 3], [m + r + 3, m], [m, m + r + 3], [m - r - 3, m]]); x.fillStyle = col[1]; poly(x, [[m, m - r], [m + r, m], [m, m + r], [m - r, m]]); x.fillStyle = col[2]; x.fillRect(m - 1.5, m - r * 0.5, 2, 3); } + else { disc(r + 2, col[0]); disc(r, col[1]); disc(r * 0.5, col[2]); } + } else if (kind === 'vorb') { // Varkolyn spiral emitter + disc(r + 3, '#12061e'); disc(r + 1, '#6a2aaa'); disc(r - 2, '#c46aff'); disc(r * 0.45, '#f6e0ff'); + x.strokeStyle = '#f6e0ff'; x.lineWidth = 2; for (let i = 0; i < 4; i++) { const a = i * Math.PI / 2 + 0.4; x.beginPath(); x.moveTo(m + Math.cos(a) * (r - 4), m + Math.sin(a) * (r - 4)); x.lineTo(m + Math.cos(a) * (r + 1), m + Math.sin(a) * (r + 1)); x.stroke(); } + } else if (kind === 'shell' || kind === 'big') { // Sandworm explosive / big bullet + const col = kind === 'shell' ? ['#2a0e04', '#8a3a14', '#ffb04a'] : ['#2a0606', '#ff4a2a', '#ffd08a']; + disc(r + 2, col[0]); disc(r, col[1]); disc(r * 0.55, col[2]); x.fillStyle = '#fff4d0'; x.fillRect(m - r * 0.45, m - r * 0.45, 2, 2); + } else if (kind === 'bouncy') { + disc(r + 2, '#2a1006'); disc(r, '#ff8a2a'); disc(r * 0.5, '#fff0a0'); + } else { + const col = kind === 'beam' ? ['#0f3a12', '#6dff4a', '#e0ffd0'] : kind === 'rail' ? ['#2a0f3a', '#c86aff', '#f6dcff'] : ['#2a0a10', '#ff5440', '#ffb070']; + disc(r + 2, col[0]); disc(r, col[1]); disc(r * 0.55, col[2]); ell(x, '#ffffff', m - r * 0.35, m - r * 0.35, Math.max(1, r * 0.25), Math.max(1, r * 0.25)); + } + s = { c, m }; + cache.set(key, s); + return s; + } + function capsule(c, x, y, a, len, w, cols) { + c.save(); c.translate(x, y); c.rotate(a); + c.fillStyle = cols[0]; c.beginPath(); c.ellipse(0, 0, len / 2 + 2, w / 2 + 2, 0, 0, TAU); c.fill(); + c.fillStyle = cols[1]; c.beginPath(); c.ellipse(0, 0, len / 2, w / 2, 0, 0, TAU); c.fill(); + c.fillStyle = cols[2]; c.beginPath(); c.ellipse(len * 0.12, -w * 0.12, len * 0.28, w * 0.22, 0, 0, TAU); c.fill(); + c.restore(); + } + + // ---------- room background (cached per case) ---------- + function background(kind) { + const key = 'bg' + kind; + let s = cache.get(key); + if (s) return s; + const c = mk(854, 480), x = ctx2d(c); + x.fillStyle = '#0a110d'; x.fillRect(0, 0, 854, 480); + // per-biome floor: Forest (green), Knight Kingdom (castle flagstone), Spaceship (steel deck), Volcano (basalt) + const theme = kind === 'christmas_treant' ? { a: '#5d8a58', b: '#567f51', lo: '#4a7046', hi: '#76a06e', snow: 0.2 } + : kind === 'devils_snare' ? { a: '#3f6a3d', b: '#3b6439', lo: '#30562f', hi: '#548752', snow: 0 } + : kind === 'grand_slime' ? { a: '#8a8072', b: '#80766a', lo: '#6c6458', hi: '#a09484', snow: 0, stone: 1, wall: ['#5a5048', '#665a50', '#7a6e62'], cap: ['#3a3430', '#4a423a', '#2a2622'] } + : kind === 'varkolyn_leader' ? { a: '#2c3440', b: '#283039', lo: '#1e252e', hi: '#3c4654', snow: 0, deck: 1, wall: ['#1e2a38', '#243244', '#34465c'], cap: ['#121a24', '#1a2430', '#0c1218'] } + : kind === 'volcanic_sandworm' ? { a: '#3a2a26', b: '#352622', lo: '#2a1e1a', hi: '#4a3630', snow: 0, lava: 1, wall: ['#2a1e1a', '#34261f', '#4a3428'], cap: ['#1a1210', '#2a1a14', '#120c0a'] } + : { a: '#4f7d3d', b: '#4a7639', lo: '#3f6630', hi: '#6a9a50', snow: 0 }; + const cols = (R.x1 - R.x0) / TILE, rows = (R.y1 - R.y0) / TILE, forest = !theme.wall; + for (let r = 0; r < rows; r++) for (let q = 0; q < cols; q++) { + const X = R.x0 + q * TILE, Y = R.y0 + r * TILE; + x.fillStyle = (q + r) % 2 ? theme.a : theme.b; x.fillRect(X, Y, TILE, TILE); + for (let i = 0; i < 7; i++) { const u = hash(q * 7 + i, r * 13), v = hash(r * 11 + i, q * 5 + 3); x.fillStyle = u < 0.5 ? theme.lo : theme.hi; x.fillRect(X + Math.floor(u * 11) * 2, Y + Math.floor(v * 11) * 2, 2, 2); } + x.fillStyle = 'rgba(0,0,0,0.10)'; x.fillRect(X, Y + TILE - 2, TILE, 2); x.fillRect(X + TILE - 2, Y, 2, TILE); + const h = hash(q + 101, r + 37); + if (forest) { + if (h < 0.12) { x.fillStyle = theme.hi; const gx = X + 6 + Math.floor(hash(q, r + 5) * 6) * 2, gy = Y + 8 + Math.floor(hash(q + 3, r) * 4) * 2; x.fillRect(gx, gy, 2, 6); x.fillRect(gx - 3, gy + 2, 2, 4); x.fillRect(gx + 3, gy + 2, 2, 4); } + else if (h < 0.16) { const fc = ['#f2d24a', '#e86aa8', '#ffffff', '#7ac8ff'][Math.floor(hash(q, r) * 4)]; const fx = X + 8 + Math.floor(hash(r, q) * 4) * 2, fy = Y + 8; x.fillStyle = fc; x.fillRect(fx - 2, fy, 2, 2); x.fillRect(fx + 2, fy, 2, 2); x.fillRect(fx, fy - 2, 2, 2); x.fillRect(fx, fy + 2, 2, 2); x.fillStyle = '#e0a020'; x.fillRect(fx, fy, 2, 2); } + else if (h < 0.19) { x.fillStyle = '#7d8a7a'; x.fillRect(X + 10, Y + 12, 4, 2); x.fillStyle = '#a2ad9e'; x.fillRect(X + 10, Y + 12, 2, 1); } + } else if (theme.stone && h < 0.1) { x.fillStyle = '#5a5248'; x.fillRect(X + 4, Y + 10, 8, 1); x.fillRect(X + 11, Y + 10, 1, 6); } + else if (theme.deck) { x.fillStyle = '#3c4654'; x.fillRect(X + 2, Y + 2, 2, 2); x.fillRect(X + TILE - 4, Y + 2, 2, 2); x.fillRect(X + 2, Y + TILE - 4, 2, 2); x.fillRect(X + TILE - 4, Y + TILE - 4, 2, 2); if (h < 0.08) { x.fillStyle = '#5ac8ff'; x.fillRect(X + 8, Y + 11, 8, 2); } } + else if (theme.lava && h < 0.09) { x.fillStyle = '#ff6a2a'; x.fillRect(X + 6, Y + 8, 2, 6); x.fillRect(X + 8, Y + 12, 6, 2); x.fillStyle = '#ffc04a'; x.fillRect(X + 6, Y + 9, 1, 3); } + if (theme.snow && hash(q + 9, r + 77) < theme.snow) { x.fillStyle = 'rgba(240,248,255,0.85)'; const sx = X + Math.floor(hash(q, r + 9) * 6) * 2, sy = Y + Math.floor(hash(q + 4, r) * 6) * 2; x.fillRect(sx, sy, 10, 4); x.fillRect(sx + 2, sy - 2, 6, 2); x.fillRect(sx + 2, sy + 4, 8, 2); } + } + if (kind === 'devils_snare') { // moss ring around the stationary boss + for (let i = 0; i < 90; i++) { const a = hash(i, 3) * TAU, d = 50 + hash(i, 4) * 90; x.fillStyle = i % 3 ? '#2e5a2c' : '#5a8a3a'; x.fillRect(Math.round((427 + Math.cos(a) * d) / 2) * 2, Math.round((256 + Math.sin(a) * d) / 2) * 2, 4, 2); } + } + // walls: hedge caps + stone brick face at the top (later biomes: their own masonry colours) + const W = theme.wall || ['#4a584c', '#435046', '#5c6b5e'], C = theme.cap || ['#244d29', '#2f6234', '#1b3d20']; + const hedge = (X, Y, w, h) => { x.fillStyle = C[0]; x.fillRect(X, Y, w, h); for (let i = 0; i < w * h / 18; i++) { const u = hash(X + i, Y), v = hash(Y + i, X + 1); x.fillStyle = u < 0.5 ? C[1] : C[2]; x.fillRect(X + Math.floor(u * w / 2) * 2, Y + Math.floor(v * h / 2) * 2, 2, 2); } }; + x.fillStyle = '#3e4a40'; x.fillRect(R.x0 - 12, 40, R.x1 - R.x0 + 24, 24); + x.save(); x.beginPath(); x.rect(R.x0 - 12, 40, R.x1 - R.x0 + 24, 24); x.clip(); + for (let row = 0; row < 2; row++) for (let i = 0; i < 34; i++) { + const bx = R.x0 - 12 + i * 24 - (row ? 12 : 0), by = 40 + row * 12; + x.fillStyle = (i + row) % 3 ? W[0] : W[1]; x.fillRect(bx + 1, by + 1, 22, 10); x.fillStyle = W[2]; x.fillRect(bx + 1, by + 1, 22, 2); + } + x.restore(); + x.fillStyle = '#2a332c'; x.fillRect(R.x0 - 12, 63, R.x1 - R.x0 + 24, 1); + hedge(R.x0 - 12, 26, R.x1 - R.x0 + 24, 14); hedge(R.x0 - 12, 26, 12, R.y1 - 26 + 10); hedge(R.x1, 26, 12, R.y1 - 26 + 10); hedge(R.x0 - 12, R.y1, R.x1 - R.x0 + 24, 8); + x.fillStyle = '#16301a'; x.fillRect(R.x0 - 12, 38, R.x1 - R.x0 + 24, 2); + const grd = x.createLinearGradient(0, R.y0, 0, R.y0 + 14); grd.addColorStop(0, 'rgba(0,0,0,0.35)'); grd.addColorStop(1, 'rgba(0,0,0,0)'); x.fillStyle = grd; x.fillRect(R.x0, R.y0, R.x1 - R.x0, 14); + x.fillStyle = 'rgba(0,0,0,0.25)'; x.fillRect(R.x0, R.y0, 6, R.y1 - R.y0); x.fillRect(R.x1 - 4, R.y0, 4, R.y1 - R.y0); + s = c; + cache.set(key, s); + return s; + } + + // ---------- helpers ---------- + function txt(c, s, x, y, size, col, align, weight) { + c.font = (weight || 'bold') + ' ' + size + 'px ' + FONT; c.textAlign = align || 'left'; c.textBaseline = 'alphabetic'; + c.lineJoin = 'round'; c.lineWidth = Math.max(2, size / 4); c.strokeStyle = '#0b0a10'; c.strokeText(s, x, y); c.fillStyle = col; c.fillText(s, x, y); + } + function panel(c, x, y, w, h) { + c.fillStyle = 'rgba(16,14,22,0.84)'; c.fillRect(x, y, w, h); + c.strokeStyle = '#06050a'; c.lineWidth = 2; c.strokeRect(x + 1, y + 1, w - 2, h - 2); + c.strokeStyle = 'rgba(150,140,170,0.45)'; c.lineWidth = 1; c.strokeRect(x + 3.5, y + 3.5, w - 7, h - 7); + } + function bar(c, x, y, w, h, v, max, fg, bg, label) { + c.fillStyle = '#06050a'; c.fillRect(x - 1, y - 1, w + 2, h + 2); c.fillStyle = bg; c.fillRect(x, y, w, h); + const f = Math.max(0, Math.min(1, v / max)); + c.fillStyle = fg; c.fillRect(x, y, Math.round(w * f), h); c.fillStyle = 'rgba(255,255,255,0.28)'; c.fillRect(x, y, Math.round(w * f), 2); + if (label) txt(c, label, x + w / 2, y + h - 2, 11, '#ffffff', 'center'); + } + const shadow = (c, x, y, rx, ry) => { c.fillStyle = 'rgba(0,0,0,0.28)'; c.beginPath(); c.ellipse(x, y, rx, ry, 0, 0, TAU); c.fill(); }; + + // ---------- world ---------- + function drawKnight(c, g) { + const p = g.player, t = g.t; + const frame = p.moving && Math.floor(p.step / 8) % 2 ? 1 : 0, bob = p.moving && Math.floor(p.step / 8) % 2 ? -2 : 0; + const flip = p.face < 0, flash = t - p.hurtT < 5, blink = p.inv > 0 && Math.floor(t / 4) % 2 === 1; + shadow(c, p.x, p.y + 11, 10, 4); + if (p.dead > 0 || (p.hp <= 0)) { + c.save(); c.translate(p.x, p.y + 8); c.rotate(-Math.PI / 2); c.globalAlpha = 0.9; c.drawImage(knight(0).c, -14, -16, 28, 34); c.restore(); + return; + } + if (p.dual > 0) { c.strokeStyle = 'rgba(255,210,80,' + (0.35 + 0.2 * Math.sin(t * 0.3)) + ')'; c.lineWidth = 2; c.beginPath(); c.ellipse(p.x, p.y + 11, 15, 6, 0, 0, TAU); c.stroke(); } + const wid = M.slots[p.slot], back = Math.sin(p.aimA) < -0.2; + if (back) drawWeapon(c, g, wid); + blit(c, knight(frame), p.x, p.y + 13 + bob, 2, flip, flash, blink ? 0.35 : undefined); + if (p.poison > 0) { c.fillStyle = 'rgba(90,220,70,0.25)'; c.fillRect(p.x - 12, p.y - 20, 24, 32); } + if (!back) drawWeapon(c, g, wid); + } + function drawWeapon(c, g, wid) { + const p = g.player, t = g.t, s = WEAPON_ART[wid](), a = p.aimA, flipY = Math.cos(a) < 0; + const one = (side, last) => { + c.save(); c.translate(p.x, p.y + 4); c.rotate(a); c.translate(4, side); if (flipY) c.scale(1, -1); + if (wid === 'sword') { + if (p.swing > 0 && p.swingKind !== 'knife') c.rotate(((p.swing / 8) - 0.5) * -2.2); + c.drawImage(s.c, -2, -s.h, s.w * 2, s.h * 2); + } else { + const kick = t - last < 3 ? -2 : 0; + c.drawImage(s.c, kick, -s.h + 1, s.w * 2, s.h * 2); + if (t - last < 3) { const mx = s.w * 2 + kick + 2; c.fillStyle = '#fff6c0'; c.fillRect(mx, -2, 8, 4); c.fillRect(mx + 2, -5, 4, 10); c.fillStyle = '#ffc23a'; c.fillRect(mx + 7, -1, 4, 2); } + } + c.restore(); + }; + one(0, p.lastShot); + if (p.dual > 0) one(7, p.lastCopy); + } + function drawSwing(c, g) { + const p = g.player; + if (p.swing <= 0 || p.dead > 0) return; + const knife = p.swingKind === 'knife', k = p.swing / (knife ? 10 : 8); + const reach = knife ? 24 : M.weapons.sword.reach, arc = knife ? 0.9 : M.weapons.sword.arc * Math.PI / 180; + c.save(); c.globalAlpha = 0.25 + 0.6 * k; + c.strokeStyle = '#ffffff'; c.lineWidth = knife ? 3 : 7; c.beginPath(); c.arc(p.x, p.y, reach - 4, p.swingA - arc, p.swingA + arc); c.stroke(); + c.strokeStyle = knife ? '#ffd0a0' : '#9fd8ff'; c.lineWidth = knife ? 2 : 3; c.beginPath(); c.arc(p.x, p.y, reach - 10, p.swingA - arc * 0.85, p.swingA + arc * 0.85); c.stroke(); + if (!knife) { c.globalAlpha *= 0.18; c.fillStyle = '#cfefff'; c.beginPath(); c.moveTo(p.x, p.y); c.arc(p.x, p.y, reach, p.swingA - arc, p.swingA + arc); c.closePath(); c.fill(); } + c.restore(); + } + function drawBoss(c, g) { + const b = g.boss, t = g.t; + if (b.hp <= 0 && b.state !== 'dying') return; + // Show a light two-tick tint on hit. + const dying = b.state === 'dying', since = t - b.flash, flash = since < 2 ? 0.32 : (dying && Math.floor(t / 4) % 2 === 0) ? 0.8 : 0; + let alpha = dying ? Math.min(1, b.deadT / 30) : undefined; + if (b.kind === 'goblin_priest') { + const s = bossSprite('goblin_priest', b.enraged), flip = b.face < 0, walk = (b.vx || b.vy) ? Math.floor(t / 10) % 2 * -2 : 0; + shadow(c, b.x, b.y + 18, 20, 6); + blit(c, s, b.x, b.y + 20 + walk, 2, flip, flash, alpha); + drawStaff(c, g); + } else if (b.kind === 'christmas_treant') { + const s = bossSprite('christmas_treant', b.enraged), charging = b.atk === 'charge' && b.vars.ph === 'dash'; + shadow(c, b.x, b.y + 28, 30, 9); + c.save(); + if (charging) { + c.translate(b.x, b.y + 30); c.rotate(Math.cos(b.vars.a) * 0.25); c.translate(-b.x, -(b.y + 30)); + c.strokeStyle = 'rgba(255,255,255,0.55)'; c.lineWidth = 2; + for (let i = 0; i < 5; i++) { const o = (i - 2) * 12, ca = Math.cos(b.vars.a), sa = Math.sin(b.vars.a); c.beginPath(); c.moveTo(b.x - ca * 44 - sa * o, b.y - sa * 44 + ca * o); c.lineTo(b.x - ca * (70 + i * 6) - sa * o, b.y - sa * (70 + i * 6) + ca * o); c.stroke(); } + } + const stomp = (b.atk === 'waves' || b.atk === 'line' || b.atk === 'transform') && b.at % 30 < 8 ? 3 : 0; + blit(c, s, b.x, b.y + 32 + stomp, 2, b.face < 0, flash, alpha); + c.restore(); + if ((b.atk === 'hold' && b.at >= 6 && b.at < 172) || (b.atk === 'throw' && b.at < 30)) drawLaserBall(c, b.x, b.y - 48, 16, t); + if (b.atk === 'homing' && b.at < 22) { c.fillStyle = 'rgba(160,170,255,0.5)'; c.beginPath(); c.arc(b.x, b.y - 58, 10 + b.at * 0.6, 0, TAU); c.fill(); } + } else if (b.kind === 'grand_slime') { + // sprite bottom-centre at y+20: the jelly body (art 1..55 x 7..43) spans the hurt capsule [-16, 2] r 28 + const s = bossSprite('grand_slime', b.enraged), squash = 1 + 0.06 * Math.sin(t * 0.25) + ((b.atk === 'slam' || b.atk === 'goo') && b.at % 30 > 18 ? 0.12 : 0); + const swell = b.boom > 0 ? 1 + 0.18 * (1 - b.boom / M.SLIME_SWELL) : 1; + shadow(c, b.x, b.y + 20, 32, 8); + c.save(); c.translate(b.x, b.y + 17); c.scale(swell * squash, swell / squash); c.translate(-b.x, -(b.y + 17)); + blit(c, s, b.x, b.y + 17, 2, b.face < 0, flash || (b.boom > 0 && Math.floor(t / 4) % 2 ? 0.5 : 0), alpha); + c.restore(); + } else if (b.kind === 'varkolyn_leader') { + const s = bossSprite('varkolyn_leader', b.enraged), walk = (b.vx || b.vy) ? Math.floor(t / 10) % 2 * -2 : 0; + shadow(c, b.x, b.y + 8, 16, 5); + // shield: doc "becomes semi-transparent" while invulnerable in its pool + const a = b.shield > 0 ? 0.45 : alpha; + blit(c, s, b.x, b.y + 8 + walk, 2, b.face < 0, flash, a); + if (b.shield > 0) { c.strokeStyle = 'rgba(200,140,255,' + (0.5 + 0.3 * Math.sin(t * 0.4)) + ')'; c.lineWidth = 2; c.beginPath(); c.ellipse(b.x, b.y - 24, 22, 38, 0, 0, TAU); c.stroke(); } + if (b.atk === 'laser' && !b.vars.on) { // doc: raises its head, swirl mark glows before the chime -> laser + c.fillStyle = 'rgba(255,90,140,' + (0.3 + 0.3 * Math.sin(t * 0.8)) + ')'; c.beginPath(); c.arc(b.x, b.y - M.VARK_EYE, 10, 0, TAU); c.fill(); + } + } else if (b.kind === 'volcanic_sandworm') { + const v = b.vars; + if (b.under) { // doc: "a dirt pile where the boss is burrowed. It will move and can serve as an indicator" + drawMound(c, b.x, b.y, t, v.ph === 'rise' ? 1 - v.c / M.WORM_RISE : 0); + } else { + const sink = v.ph === 'sink' ? 1 - v.c / Math.max(1, Math.round(M.WORM_SINK * (b.enraged ? 0.7 : 1))) : 0; + const tilt = (b.atk === 'explosive' || b.atk === 'spread') && b.at < 24 ? -0.12 * Math.min(1, b.at / 12) : 0; + shadow(c, b.x, b.y + 4, 24, 7); + c.save(); c.beginPath(); c.rect(b.x - 40, b.y - 120, 80, 126); c.clip(); + c.translate(b.x, b.y + 4); c.rotate(tilt); c.translate(-b.x, -(b.y + 4)); + blit(c, bossSprite('volcanic_sandworm', b.enraged), b.x, b.y + 4 + sink * 84, 2, b.face < 0, flash, alpha); + c.restore(); + drawMound(c, b.x, b.y + 6, t, 0, true); + } + } else { + const s = bossSprite('devils_snare', b.enraged), pulse = (b.atk === 'bubbles' && b.at < 20) ? 1 + 0.08 * Math.sin(b.at * 0.8) : 1; + shadow(c, b.x, b.y + 38, 36, 10); + for (const tn of b.tentacles) drawTentacle(c, b, tn, t, b.atk === 'corner' && b.at < 22); + // anchor so the flower centre (art 22,21) sits exactly on the boss / hurt circle centre + c.save(); c.translate(b.x, b.y + 44); c.scale(pulse, pulse); c.translate(-b.x, -(b.y + 44)); + blit(c, s, b.x, b.y + 44, 2, false, flash, alpha); + c.restore(); + if (b.atk === 'beams' && b.at < 22) { c.fillStyle = 'rgba(110,255,80,0.25)'; c.beginPath(); c.arc(b.x, b.y, 36 + b.at, 0, TAU); c.fill(); } + } + const iconUp = ['grand_slime', 'varkolyn_leader', 'volcanic_sandworm'].includes(b.kind) ? -M.bosses[b.kind].hurt[0] + 30 : b.r * 1.7; // above the tall new sprites + if (b.enraged && !dying && !b.under) blit(c, ICONS.angry(), b.x + b.r * 0.8, b.y - iconUp + Math.sin(t * 0.2) * 2, 2); + } + function drawMound(c, x, y, t, rise, rim) { // Sandworm dirt mound (moving indicator) / ring of rubble at the hole + const n = rim ? 7 : 9, w = rim ? 26 : 22 + rise * 8; + for (let i = 0; i < n; i++) { + const a = i * TAU / n + (rim ? 0 : t * 0.05), j = rim ? 0 : Math.sin(t * 0.6 + i) * 1.5 * (1 + rise * 2); + ell(c, i % 2 ? '#5a3a24' : '#7a5232', x + Math.cos(a) * w * 0.6 + j, y + Math.sin(a) * w * 0.25, 7, 4); + } + if (!rim) { ell(c, '#3a2414', x, y, w * 0.5, w * 0.2); if (rise > 0) { c.fillStyle = 'rgba(255,140,60,' + (0.3 + 0.4 * rise) + ')'; c.beginPath(); c.ellipse(x, y, w * 0.4, w * 0.15, 0, 0, TAU); c.fill(); } } + } + function drawMinions(c, g) { + const t = g.t; + for (const m of g.minions) { + const e = m.emerge > 0 ? 1 - m.emerge / (m.kind === 'slime' ? 24 : 40) : 1, f = Math.floor(t / 10) % 2; + if (m.kind === 'slime') { + shadow(c, m.x, m.y + 8, 9, 3); + c.save(); if (e < 1) c.globalAlpha = 0.4 + 0.6 * e; + blit(c, minionSprite('slime', f), m.x, m.y + 9, 2, false, t - m.flash < 3 ? 0.5 : 0); c.restore(); + } else { + // tentacle grows out of the floor (emerging = harmless, not yet firing) + shadow(c, m.x, m.y + 10, 10, 3); + c.save(); c.beginPath(); c.rect(m.x - 20, m.y - 40, 40, 62); c.clip(); + blit(c, minionSprite('tentacle', f), m.x, m.y + 20 + (1 - e) * 40, 2, false, t - m.flash < 3 ? 0.5 : 0); c.restore(); + if (e >= 1 && m.fire < 20) { c.fillStyle = 'rgba(196,106,255,' + (0.6 - m.fire * 0.025) + ')'; c.beginPath(); c.arc(m.x, m.y - 10, 8 + (20 - m.fire) * 0.5, 0, TAU); c.fill(); } + } + } + } + function drawStaff(c, g) { + const b = g.boss, front = b.face > 0 ? 1 : -1; + const hx = b.x + front * 18, top = b.y - 34; + c.fillStyle = '#1a120a'; c.fillRect(hx - 3, top - 2, 6, 58); c.fillStyle = '#8a5a2a'; c.fillRect(hx - 1, top, 3, 54); c.fillStyle = '#b07a40'; c.fillRect(hx - 1, top, 1, 54); + const col = { meteor: '#ff7a2a', orbs: '#6ad8ff', turrets: '#d0d8e0', stars: '#ffd43a' }[b.atk] || '#a8e68e'; + const glow = b.state === 'cast' ? 9 + Math.sin(g.t * 0.5) * 2 : 6; + c.fillStyle = col; c.globalAlpha = 0.35; c.beginPath(); c.arc(hx, top - 4, glow + 5, 0, TAU); c.fill(); c.globalAlpha = 1; + c.fillStyle = '#16120a'; starPath(c, hx, top - 4, 9, 4, 5); c.fill(); c.fillStyle = col; starPath(c, hx, top - 4, 7, 3, 5); c.fill(); + } + function drawTentacle(c, b, tn, t, glow) { + const n = 7; + for (let i = 0; i <= n; i++) { + const k = i / n, w = Math.sin(t * 0.12 + i * 0.9) * 5 * (1 - Math.abs(k - 0.5) * 2); + const dx = tn.x - b.x, dy = tn.y - b.y, L = Math.hypot(dx, dy) || 1; + const x = b.x + dx * k - dy / L * w, y = b.y + dy * k + dx / L * w, r = 9 - k * 2; + ell(c, '#24082c', x, y, r + 2, r + 2); ell(c, i % 2 ? '#7a2f8f' : '#9a45ad', x, y, r, r); + } + ell(c, '#24082c', tn.x, tn.y, tn.r + 2, tn.r + 2); ell(c, glow ? '#e88aff' : '#a24bb8', tn.x, tn.y, tn.r, tn.r); ell(c, '#d47ad8', tn.x - 4, tn.y - 4, 4, 3); + c.fillStyle = '#f4efe6'; for (let i = 0; i < 4; i++) { const a = i * Math.PI / 2 + t * 0.03; c.fillRect(tn.x + Math.cos(a) * (tn.r + 1) - 1, tn.y + Math.sin(a) * (tn.r + 1) - 1, 3, 3); } + } + function drawLaserBall(c, x, y, r, t) { + const gr = c.createRadialGradient(x, y, 2, x, y, r + 10); + gr.addColorStop(0, '#ffffff'); gr.addColorStop(0.45, '#9ff4ff'); gr.addColorStop(0.75, 'rgba(80,190,255,0.6)'); gr.addColorStop(1, 'rgba(80,190,255,0)'); + c.fillStyle = gr; c.beginPath(); c.arc(x, y, r + 10, 0, TAU); c.fill(); + c.strokeStyle = '#ffffff'; c.lineWidth = 2; + for (let i = 0; i < 4; i++) { const a = t * 0.25 + i * Math.PI / 2; c.beginPath(); c.moveTo(x + Math.cos(a) * (r - 4), y + Math.sin(a) * (r - 4)); c.lineTo(x + Math.cos(a) * (r + 6), y + Math.sin(a) * (r + 6)); c.stroke(); } + } + function drawShuriken(c, x, y, r, a) { + c.save(); c.translate(x, y); c.rotate(a); + c.fillStyle = '#14161c'; starPath(c, 0, 0, r + 2, r * 0.35 + 2, 4, 0); c.fill(); + c.fillStyle = '#c0c8d4'; starPath(c, 0, 0, r, r * 0.35, 4, 0); c.fill(); + c.fillStyle = '#5a6270'; c.fillRect(-2, -2, 4, 4); + c.restore(); + } + + function drawGround(c, g) { + const t = g.t, b = g.boss; + for (const tile of g.tiles) { // Grand Slime room: Slow (down arrows) / Boost (up arrows) tiles + const slow = tile.kind === 'slow'; + c.fillStyle = slow ? 'rgba(90,60,140,0.55)' : 'rgba(40,140,200,0.5)'; c.fillRect(tile.x + 2, tile.y + 2, tile.w - 4, tile.h - 4); + c.strokeStyle = slow ? '#b08aff' : '#7ad8ff'; c.lineWidth = 2; c.strokeRect(tile.x + 3, tile.y + 3, tile.w - 6, tile.h - 6); + c.fillStyle = slow ? '#d8c4ff' : '#c8f4ff'; + for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) { + const x = tile.x + 12 + i * 24, y = tile.y + 12 + j * 24, s = slow ? 1 : -1, o = ((t * 0.5) % 8) * s; + poly(c, [[x - 6, y - 3 * s + o * 0.3], [x + 6, y - 3 * s + o * 0.3], [x, y + 5 * s + o * 0.3]]); + } + } + for (const pool of g.pools) { + const k = Math.min(1, pool.life / 30), purple = pool.purple; + if (pool.form > 0) { // forming: harmless; the dashed ring is the exact pool radius it will have + c.save(); c.globalAlpha = 0.85; c.strokeStyle = purple ? '#d48aff' : '#a8ff6a'; c.lineWidth = 2; c.setLineDash([5, 4]); + c.beginPath(); c.arc(pool.x, pool.y, pool.r, 0, TAU); c.stroke(); c.restore(); + c.globalAlpha = 0.25 * (1 - pool.form / 24); ell(c, purple ? '#8a3ad0' : '#4ec23a', pool.x, pool.y, pool.r, pool.r); c.globalAlpha = 1; + continue; + } + c.globalAlpha = 0.5 * k; ell(c, purple ? '#7a2ac0' : '#4ec23a', pool.x, pool.y, pool.r, pool.r); + c.globalAlpha = 0.6 * k; c.strokeStyle = purple ? '#d48aff' : '#a8ff6a'; c.lineWidth = 2; c.beginPath(); c.arc(pool.x, pool.y, pool.r - 1, 0, TAU); c.stroke(); + for (let i = 0; i < 6; i++) { const ph = (t * 0.04 + hash(i, pool.x | 0)) % 1, a = hash(i + 4, pool.y | 0) * TAU, d = hash(i, 9) * pool.r * 0.7; ell(c, purple ? '#f0c8ff' : '#c8ff9a', pool.x + Math.cos(a) * d, pool.y + Math.sin(a) * d - ph * 6, 2 + ph * 2, 2 + ph * 2); } + c.globalAlpha = 1; + } + // Grand Slime swell: the growing ring reaches the exact explosion radius when it bursts + if (b.kind === 'grand_slime' && b.boom > 0) { + const k = 1 - b.boom / M.SLIME_SWELL; + c.fillStyle = 'rgba(255,60,80,' + (0.10 + 0.22 * k) + ')'; c.beginPath(); c.arc(b.x, b.y, M.SLIME_BLAST * k, 0, TAU); c.fill(); + c.strokeStyle = 'rgba(255,90,110,0.9)'; c.lineWidth = 2; c.beginPath(); c.arc(b.x, b.y, M.SLIME_BLAST, 0, TAU); c.stroke(); + } + // Sandworm: shockwave rings (expanding, hit band drawn) and the burrow / surface warning radius + for (const q of g.quakes) { + const k = Math.min(1, q.age / q.total); + c.save(); c.globalAlpha = 1 - Math.max(0, (q.age - q.total) / 6); c.fillStyle = 'rgba(255,150,80,0.28)'; c.beginPath(); c.arc(q.x, q.y, q.rc, 0, TAU); c.fill(); + c.strokeStyle = '#ffb06a'; c.lineWidth = 6; c.beginPath(); c.arc(q.x, q.y, q.rc, 0, TAU); c.stroke(); + c.strokeStyle = '#7a3a14'; c.lineWidth = 2; c.beginPath(); c.arc(q.x, q.y, q.rc + 4, 0, TAU); c.stroke(); c.restore(); + void k; + } + if (b.kind === 'volcanic_sandworm' && (b.vars.ph === 'sink' || b.vars.ph === 'rise' || b.vars.ph === 'peek')) { + c.save(); c.strokeStyle = 'rgba(255,150,80,0.85)'; c.lineWidth = 2; c.setLineDash([6, 5]); + c.beginPath(); c.arc(b.x, b.y, M.QUAKE_R, 0, TAU); c.stroke(); c.restore(); + } + // Varkolyn laser: during the charge the whole swept arc is drawn (start edge bright, sweep direction arrow); + // while firing, the beam itself and the part of the arc still to be swept + if (b.atk === 'laser' && b.vars.a0 !== undefined) { + const v = b.vars, oy = b.y - M.VARK_EYE, end = v.a0 + v.dir * M.LASER_ARC, cur = v.on ? v.a : v.a0; + c.save(); c.globalAlpha = v.on ? 0.16 : 0.14 + 0.08 * Math.sin(t * 0.7); c.fillStyle = '#ff3a6a'; + c.beginPath(); c.moveTo(b.x, oy); c.arc(b.x, oy, 1100, Math.min(cur, end), Math.max(cur, end)); c.closePath(); c.fill(); + c.globalAlpha = 0.9; c.strokeStyle = v.on ? '#ffffff' : '#ff8aa8'; c.lineWidth = v.on ? M.LASER_W * 2 : 2; + if (!v.on) c.setLineDash([10, 6]); + c.beginPath(); c.moveTo(b.x, oy); c.lineTo(b.x + Math.cos(cur) * 1100, oy + Math.sin(cur) * 1100); c.stroke(); + if (v.on) { c.strokeStyle = '#ff3a8a'; c.lineWidth = M.LASER_W * 2 + 6; c.globalAlpha = 0.35; c.stroke(); } + c.restore(); + } + for (const m of g.meteors) { + const k = 1 - m.fall / m.total; + c.fillStyle = 'rgba(255,60,30,' + (0.12 + 0.22 * k) + ')'; c.beginPath(); c.arc(m.x, m.y, m.r * k, 0, TAU); c.fill(); + c.strokeStyle = 'rgba(255,90,50,0.9)'; c.lineWidth = 2; c.beginPath(); c.arc(m.x, m.y, m.r, 0, TAU); c.stroke(); + } + for (const L of g.lines) { + // upcoming nodes drawn at their real hit radius (11-02: 4 px dots hid an 18 px hazard), and only up to the + // first wall/obstacle, where game.js stops the line + const ca = Math.cos(L.a), sa = Math.sin(L.a); + c.lineWidth = 1.5; + for (let k = L.k + 1; k <= L.n; k++) { + const d = L.start + k * L.gap, x = L.x + ca * d, y = L.y + sa * d; + if (g.solidAt(x, y, 4, false)) break; + const near = k - L.k <= 2; + c.strokeStyle = near ? 'rgba(220,240,255,0.75)' : 'rgba(220,240,255,0.32)'; + c.beginPath(); c.arc(x, y, M.NODE_R, 0, TAU); c.stroke(); + c.fillStyle = near ? 'rgba(200,235,255,0.18)' : 'rgba(200,235,255,0.07)'; c.fill(); + } + } + for (const n of g.nodes) { + const k = n.life / 14; + c.globalAlpha = Math.min(1, k * 1.6); + ell(c, 'rgba(190,230,255,0.35)', n.x, n.y, n.r, n.r); + for (let i = 0; i < 5; i++) { + const a = i * TAU / 5 + n.x * 0.1, sx = n.x + Math.cos(a) * n.r * 0.55, sy = n.y + Math.sin(a) * n.r * 0.55, hgt = 8 + 6 * k; + c.fillStyle = '#2a4a66'; poly(c, [[sx - 5, sy + 2], [sx, sy - hgt - 2], [sx + 5, sy + 2]]); + c.fillStyle = i % 2 ? '#dff4ff' : '#a8dcf6'; poly(c, [[sx - 3, sy], [sx, sy - hgt], [sx + 3, sy]]); + } + c.globalAlpha = 1; + } + if (b.atk === 'charge' && (b.vars.ph === 'aim' || b.vars.ph === 'dash')) { + // telegraph band = the exact swept ram capsule (game.js M.ramBand), centred on the capsule middle and + // starting behind the boss by the capsule's rear extent, so the drawn band always contains the hit area. + // Tracking: faint + dashed edges; locked (last M.RAM_LOCK ticks): bright solid edges; dash: faint trail. + const a = b.vars.a, ca = Math.cos(a), sa = Math.sin(a), h = M.bosses[b.kind].hurt, half = M.ramBand(b.kind, a), cy = b.y + (h[0] + h[1]) / 2; + const back = h[2] + M.RAM_PAD + (h[1] - h[0]) / 2 * Math.abs(sa), locked = b.vars.ph === 'aim' && b.vars.lock, dash = b.vars.ph === 'dash'; + const L = M.ramReach(g) + back; // the band ends where this dash really ends (wall / dash length) + c.save(); c.translate(b.x, cy); c.rotate(a); c.fillStyle = '#ff3a2a'; + c.globalAlpha = dash ? 0.14 : locked ? 0.30 + 0.10 * Math.sin(t * 1.3) : 0.13 + 0.05 * Math.sin(t * 0.6); + c.fillRect(-back, -half, L + back, half * 2); + if (locked) { c.globalAlpha = 0.95; c.fillStyle = '#ffd0c0'; c.fillRect(-back, -half, L + back, 3); c.fillRect(-back, half - 3, L + back, 3); } + else if (!dash) { c.globalAlpha = 0.7; for (let x = -back; x < L; x += 24) { c.fillRect(x, -half, 12, 2); c.fillRect(x, half - 2, 12, 2); } } + c.restore(); + if (!dash) { + c.fillStyle = locked ? 'rgba(255,220,200,0.95)' : 'rgba(255,90,60,0.7)'; + for (let i = 1; i <= 4; i++) { const d = 40 + i * 34 + (t % 12) * 2; if (d > L) break; const x = b.x + ca * d, y = b.y + sa * d; poly(c, [[x + ca * 10, y + sa * 10], [x - sa * 10, y + ca * 10], [x + sa * 10, y - ca * 10]]); } + } + } + if (b.atk === 'pull' && b.vars.on) { + c.strokeStyle = 'rgba(200,120,255,0.55)'; c.lineWidth = 3; + for (let i = 0; i < 3; i++) { const r = 60 + ((300 - (t * 4 + i * 100) % 300)); c.beginPath(); c.arc(b.x, b.y, r, 0, TAU); c.stroke(); } + } + } + + function drawProjectiles(c, g) { + const t = g.t; + for (const o of g.orbs) { + c.fillStyle = 'rgba(110,220,255,0.35)'; c.beginPath(); c.arc(o.x, o.y, o.r + 6, 0, TAU); c.fill(); + ell(c, '#10203a', o.x, o.y, o.r + 2, o.r + 2); ell(c, '#5ad0ff', o.x, o.y, o.r, o.r); ell(c, '#e0faff', o.x - 2, o.y - 2, o.r * 0.45, o.r * 0.45); + } + for (const q of g.turrets) drawShuriken(c, q.x, q.y, q.r, t * 0.2); + for (const q of g.carriers) drawShuriken(c, q.x, q.y, 11, t * 0.4); + for (const ball of g.balls) { + // blast-radius telegraph (11-02): the burst hurts within M.BLAST_R of the ball (body overlap), wider than its glow + c.save(); c.globalAlpha = 0.45 + 0.15 * Math.sin(t * 0.5); c.strokeStyle = '#9ff4ff'; c.lineWidth = 2; c.setLineDash([6, 5]); + c.beginPath(); c.arc(ball.x, ball.y, M.BLAST_R, 0, TAU); c.stroke(); c.restore(); + drawLaserBall(c, ball.x, ball.y, ball.r, t); + } + for (const st of g.stars) { // Sandworm star turret: spinning cross, its four firing lanes drawn faintly + const lanes = st.shots > 0; + if (lanes) { c.save(); c.globalAlpha = 0.18; c.strokeStyle = '#ffd04a'; c.lineWidth = 6; for (let i = 0; i < 4; i++) { const a = st.a0 + i * Math.PI / 2; c.beginPath(); c.moveTo(st.x, st.y); c.lineTo(st.x + Math.cos(a) * 900, st.y + Math.sin(a) * 900); c.stroke(); } c.restore(); } + c.save(); c.translate(st.x, st.y); c.rotate(t * 0.15); + c.fillStyle = '#2a1406'; starPath(c, 0, 0, st.r + 3, st.r * 0.45 + 2, 4, 0); c.fill(); + c.fillStyle = st.kind === 'long' ? '#ffd04a' : '#ff8a2a'; starPath(c, 0, 0, st.r, st.r * 0.45, 4, 0); c.fill(); + c.restore(); + } + for (const s of g.shots) { + const a = Math.atan2(s.vy, s.vx); + capsule(c, s.x, s.y, a, s.crit ? 14 : 11, s.crit ? 7 : 5, s.crit ? ['#4a1a00', '#ff9a2a', '#fff4c0'] : ['#3a2a00', '#ffd23a', '#fff8d0']); + } + for (const q of g.bullets) { + if (q.kind === 'beam') { capsule(c, q.x, q.y, Math.atan2(q.vy, q.vx), 18, 7, ['#0f3a12', '#6dff4a', '#e0ffd0']); continue; } + if (q.kind === 'rail') { capsule(c, q.x, q.y, Math.atan2(q.vy, q.vx), 22, 9, ['#2a0f3a', '#c86aff', '#f6dcff']); continue; } + if (q.kind === 'long') { capsule(c, q.x, q.y, Math.atan2(q.vy, q.vx), 16, 6, ['#3a1a04', '#ffb03a', '#fff0c0']); continue; } + if (q.blast) { // shells / big bullets: the blast radius rides with the projectile (== the explosion's hit radius) + c.save(); c.globalAlpha = q.kind === 'shell' ? 0.7 : 0.35; c.strokeStyle = q.kind === 'shell' ? '#ff8a3a' : '#ff6a4a'; c.lineWidth = q.kind === 'shell' ? 2 : 1; c.setLineDash([5, 4]); + c.beginPath(); c.arc(q.x, q.y, q.blast, 0, TAU); c.stroke(); c.restore(); + } + if (q.kind === 'homing' && q.hover > 0) { c.globalAlpha = 0.5 + 0.5 * Math.sin(t * 0.5); } + const s = bulletSprite(q.kind, Math.round(q.r)); + c.drawImage(s.c, Math.round(q.x - s.m), Math.round(q.y - s.m)); + c.globalAlpha = 1; + } + for (const m of g.meteors) { + const h = m.fall * 5, x = m.x + m.fall * 1.5, y = m.y - h; + c.fillStyle = 'rgba(255,140,40,0.45)'; c.beginPath(); c.moveTo(x - 7, y); c.lineTo(x + 18, y - 40); c.lineTo(x + 7, y); c.fill(); + ell(c, '#2a1206', x, y, 11, 11); ell(c, '#b4552a', x, y, 9, 9); ell(c, '#ffb04a', x - 2, y - 2, 4, 4); + } + for (const q of g.pickups) { + const s = ICONS.orb(), bob = Math.sin((t + q.x) * 0.15) * 2; + c.fillStyle = 'rgba(80,170,255,0.3)'; c.beginPath(); c.arc(q.x, q.y + bob - 6, 8, 0, TAU); c.fill(); + blit(c, s, q.x, q.y + bob + 2, 2); + } + } + + function drawFx(c, g) { + const t = g.t; + for (const f of g.fx) { + const age = t - f.t; + if (f.k === 'spark' && age < 8) { + c.strokeStyle = f.c ? '#bfe8ff' : '#fff2a0'; c.lineWidth = 2; const r = 3 + age * 1.5; + for (let i = 0; i < 4; i++) { const a = i * Math.PI / 2 + Math.PI / 4; c.beginPath(); c.moveTo(f.x + Math.cos(a) * r * 0.4, f.y + Math.sin(a) * r * 0.4); c.lineTo(f.x + Math.cos(a) * r, f.y + Math.sin(a) * r); c.stroke(); } + } else if (f.k === 'boom' && age < 18) { + const k = age / 18; + c.fillStyle = 'rgba(255,240,200,' + (0.6 * (1 - k)) + ')'; c.beginPath(); c.arc(f.x, f.y, f.r * (0.4 + k * 0.6), 0, TAU); c.fill(); + c.strokeStyle = 'rgba(255,140,60,' + (1 - k) + ')'; c.lineWidth = 3; c.beginPath(); c.arc(f.x, f.y, f.r * (0.6 + k * 0.6), 0, TAU); c.stroke(); + } else if (f.k === 'debris' && age < 22) { + for (let i = 0; i < 7; i++) { const a = hash(i, f.x | 0) * TAU, v = 1.5 + hash(f.y | 0, i) * 2.5; c.fillStyle = i % 2 ? '#aa763c' : '#7a4f24'; c.fillRect(f.x + Math.cos(a) * v * age - 2, f.y + Math.sin(a) * v * age + age * age * 0.05 - 2, 4, 3); } + } else if (f.k === 'num' && age < 40) { + c.globalAlpha = Math.min(1, (40 - age) / 14); + txt(c, String(f.v), f.x, f.y - age * 0.8, f.crit ? 19 : 14, f.crit ? '#ffd23a' : '#ffffff', 'center'); + c.globalAlpha = 1; + } else if (f.k === 'pnum' && age < 36) { + c.globalAlpha = Math.min(1, (36 - age) / 12); + txt(c, '-' + f.v, f.x, f.y - age * 0.7, 14, f.s ? '#8aff6a' : '#ff5a5a', 'center'); + c.globalAlpha = 1; + } else if (f.k === 'txt' && age < 44) { + c.globalAlpha = Math.min(1, (44 - age) / 14); + txt(c, f.s, f.x, f.y - age * 0.5, f.big ? 20 : 13, f.big ? '#ff6a4a' : '#d8dde4', 'center'); + c.globalAlpha = 1; + } + } + const b = g.boss; + if (b.state === 'dying') for (let i = 0; i < 3; i++) { + const h1 = hash(Math.floor(t / 6) * 3 + i, 7), h2 = hash(i, Math.floor(t / 6)), x = b.x + (h1 - 0.5) * b.r * 2.4, y = b.y + (h2 - 0.6) * b.r * 2.4, k = (t % 6) / 6; + c.fillStyle = 'rgba(255,220,140,' + (0.8 - k * 0.6) + ')'; c.beginPath(); c.arc(x, y, 6 + k * 10, 0, TAU); c.fill(); + } + } + + function drawReticle(c, g) { + const p = g.player; + if (p.dead > 0 || g.outcome) return; + const x = Math.round(p.aimX), y = Math.round(p.aimY), manual = p.manual > 0; + c.strokeStyle = '#0b0a10'; c.lineWidth = 4; + const arms = () => { c.beginPath(); c.moveTo(x - 9, y); c.lineTo(x - 3, y); c.moveTo(x + 3, y); c.lineTo(x + 9, y); c.moveTo(x, y - 9); c.lineTo(x, y - 3); c.moveTo(x, y + 3); c.lineTo(x, y + 9); c.stroke(); }; + arms(); c.strokeStyle = manual ? '#ffffff' : '#ffd23a'; c.lineWidth = 2; arms(); + } + + // ---------- HUD ---------- + function drawHud(c, g) { + const p = g.player, b = g.boss, t = g.t, w = M.weapons[M.slots[p.slot]]; + panel(c, 6, 4, 190, 60); + const rows = [['hp', p.hp, p.maxHp, '#e84848', '#4a1c22'], ['armor', p.armor, p.maxArmor, '#aab6c4', '#2c3240'], ['energy', p.energy, p.maxEnergy, '#3f9cff', '#1a2848']]; + rows.forEach(([icon, v, max, fg, bg], i) => { + const y = 10 + i * 17; + blit(c, ICONS[icon](), 20, y + 15, 2); + bar(c, 34, y + 2, 120, 12, v, max, fg, bg, v + '/' + max); + }); + if (p.armor < p.maxArmor && p.sinceHit < 180 && p.dead === 0) { c.fillStyle = 'rgba(170,182,196,0.6)'; c.fillRect(160, 30, Math.round(30 * p.sinceHit / 180), 3); } + if (p.poison > 0) { txt(c, 'Poisoned', 160, 28, 11, '#8aff6a'); } + // boss bar + const name = M.cases.find(q => q.id === g.id), bw = 330, bx = 427 - bw / 2; + panel(c, bx - 12, 4, bw + 24, 38); + txt(c, name.name + ' · ' + name.en, bx, 19, 12, '#f2e6c8'); + txt(c, b.enraged ? 'Phase 2: Enraged' : 'Phase 1', bx + bw, 19, 11, b.enraged ? '#ff7a5a' : '#b8c0cc', 'right'); + const pulse = b.enraged ? (Math.floor(t / 10) % 2 ? '#ff5a3a' : '#e83a2a') : '#d83a3a'; + bar(c, bx, 24, bw, 11, b.hp, b.maxHp, pulse, '#3a1414', Math.ceil(b.hp) + ' / ' + b.maxHp); + c.fillStyle = '#f2e6c8'; c.fillRect(bx + bw / 2 - 1, 23, 2, 13); + const status = b.inv ? 'Invulnerable' : b.under ? 'Burrowed: cannot attack' : b.shield > 0 ? 'Poison-pool shield: immune' : b.boom > 0 ? 'Expanding: about to explode' : ''; + if (status) txt(c, status, bx + bw / 2, 51, 11, b.boom > 0 ? '#ff8a8a' : '#d8dde4', 'center'); + // doc (Grand Slime): enraged charge bar fills after 15 hits + if (b.kind === 'grand_slime' && b.enraged && b.boom === 0) { c.fillStyle = '#06050a'; c.fillRect(bx - 1, 37, bw + 2, 4); c.fillStyle = '#ff7a3a'; c.fillRect(bx, 38, Math.round(bw * b.charge / M.SLIME_HITS), 2); } + // timer + public tier + native clock (2026-11-02: every HUD shows the native Hz) + panel(c, 700, 4, 148, 38); + const sec = t / 60, mm = Math.floor(sec / 60), ss = (sec % 60).toFixed(1).padStart(4, '0'), lim = M.maxSeconds; + txt(c, '⏱ ' + mm + ':' + ss, 712, 23, 14, '#f2f2f2'); + txt(c, '/ ' + Math.floor(lim / 60) + ':' + String(lim % 60).padStart(2, '0'), 840, 23, 10, '#a8b0bc', 'right', 'normal'); + const tier = M.tierOf(g.d), TL = { easy: ['Easy EASY', '#7fe08a'], normal: ['Normal NORMAL', '#ffd23a'], hard: ['Hard HARD', '#ff6a4a'] }[tier] || ['Custom d=' + g.d.toFixed(2), '#c8d0dc']; + txt(c, TL[0], 712, 37, 10, TL[1], 'left'); + txt(c, M.hz + 'Hz', 840, 37, 10, '#9fd8ff', 'right'); + // bottom strip: hints, weapon card, skill + txt(c, 'WASD Move · J Attack · K Duplicate Weapon · Q Switch Weapon · Mouse aim', 12, 472, 11, '#c8d0c0', 'left', 'normal'); + panel(c, 560, 452, 234, 27); + const art = WEAPON_ART[M.slots[p.slot]](); + c.drawImage(art.c, 572, 465 - art.h, art.w * 2, art.h * 2); + txt(c, w.name, 624, 470, 12, '#f2e6c8'); + const lowE = w.cost > p.energy; + txt(c, '⚡' + w.cost, 712, 470, 12, lowE ? (Math.floor(t / 15) % 2 ? '#ff5a5a' : '#ffffff') : '#7ac0ff'); + for (let i = 0; i < M.slots.length; i++) { c.fillStyle = i === p.slot ? '#ffd23a' : '#4a4658'; c.fillRect(746 + i * 13, 461, 9, 9); c.strokeStyle = '#06050a'; c.lineWidth = 1; c.strokeRect(746.5 + i * 13, 461.5, 9, 9); } + // skill button (Dual Wield) + const sx = 822, sy = 452, r = 14; + c.fillStyle = '#06050a'; c.beginPath(); c.arc(sx, sy, r + 3, 0, TAU); c.fill(); + c.fillStyle = p.dual > 0 ? '#5a4410' : '#2a3a5a'; c.beginPath(); c.arc(sx, sy, r, 0, TAU); c.fill(); + const pistol = WEAPON_ART.pistol(); + c.save(); c.translate(sx, sy); c.rotate(-0.5); c.drawImage(pistol.c, -11, -9, pistol.w * 2, pistol.h * 2); c.rotate(1.0); c.drawImage(pistol.c, -11, -2, pistol.w * 2, pistol.h * 2); c.restore(); + if (p.dual > 0) { + c.strokeStyle = '#ffd23a'; c.lineWidth = 3; c.beginPath(); c.arc(sx, sy, r + 1, -Math.PI / 2, -Math.PI / 2 + TAU * p.dual / 300); c.stroke(); + txt(c, (p.dual / 60).toFixed(1), sx, sy + 5, 12, '#ffd23a', 'center'); + } else if (p.skillCd > 0) { + c.fillStyle = 'rgba(0,0,0,0.6)'; c.beginPath(); c.moveTo(sx, sy); c.arc(sx, sy, r, -Math.PI / 2, -Math.PI / 2 + TAU * p.skillCd / 600); c.closePath(); c.fill(); + txt(c, Math.ceil(p.skillCd / 60) + '', sx, sy + 5, 13, '#ffffff', 'center'); + } else { c.strokeStyle = 'rgba(140,200,255,' + (0.5 + 0.4 * Math.sin(t * 0.2)) + ')'; c.lineWidth = 2; c.beginPath(); c.arc(sx, sy, r + 1, 0, TAU); c.stroke(); } + txt(c, 'K', sx + 12, sy + 16, 9, '#c8d0dc', 'center'); + } + function drawResult(c, g) { + if (!g.outcome) return; + const map = { win: ['Victory: Boss Defeated', 'BOSS DEFEATED', '#ffd23a'], loss: ['Defeat: Gunner Down', 'GUNNER DOWN', '#ff5a4a'], timeout: ['Time up', 'TIME UP', '#d8dde4'] }[g.outcome]; + const tier = { easy: 'Easy EASY', normal: 'Normal NORMAL', hard: 'Hard HARD' }[M.tierOf(g.d)] || 'd=' + g.d.toFixed(2); + // upper third (11-02): the shared play-page overlay box (_native/shell.js) sits at the stage centre and hid the + // second line of the old centred banner in the result screenshots + c.fillStyle = 'rgba(8,8,14,0.62)'; c.fillRect(0, 112, 854, 86); + c.fillStyle = map[2]; c.fillRect(0, 112, 854, 2); c.fillRect(0, 196, 854, 2); + txt(c, map[0], 427, 154, 30, map[2], 'center'); + txt(c, map[1] + ' · ' + (g.t / 60).toFixed(2) + ' s · ' + tier + ' · Health ' + g.player.hp + '/' + g.player.maxHp, 427, 182, 13, '#e8e8f0', 'center', 'normal'); + } + + // Build sprite variants on the first frame to avoid allocation during the fight. + let warmed = false; + function warm() { + warmed = true; + for (const kind of ['goblin_priest', 'christmas_treant', 'devils_snare', 'grand_slime', 'varkolyn_leader', 'volcanic_sandworm']) { bossSprite(kind, false); bossSprite(kind, true); } + for (const f of [0, 1]) { minionSprite('slime', f); minionSprite('tentacle', f); } + knight(0); knight(1); + for (const k of Object.keys(PROPS)) { if (k === 'crate' || k === 'smile' || k === 'wcrate') { PROPS[k](0); PROPS[k](1); } else PROPS[k](); } + for (const k of Object.keys(WEAPON_ART)) WEAPON_ART[k](); + for (const k of Object.keys(ICONS)) ICONS[k](); + for (const [kind, r] of [['small', 4], ['small', 5], ['star', 7], ['cross', 9], ['bubble', 7], ['bubble', 8], ['homing', 6], ['beam', 5], ['rail', 6], + ['slam', 5], ['diamond', 6], ['petal', 5], ['vorb', 13], ['shell', 11], ['big', 8], ['bouncy', 5]]) bulletSprite(kind, r); + } + + M.draw = function (g, c) { + if (!warmed) warm(); + c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = 'source-over'; c.imageSmoothingEnabled = false; + c.drawImage(background(g.kind), 0, 0); + const age = g.t - g.shake.t, sh = age >= 0 && age < 8 ? g.shake.a * (1 - age / 8) : 0; + const ox = Math.round(Math.sin(g.t * 12.9898) * sh), oy = Math.round(Math.cos(g.t * 78.233) * sh); + c.save(); c.translate(ox, oy); + c.beginPath(); c.rect(R.x0 - 12, 20, R.x1 - R.x0 + 24, R.y1 - 12); c.clip(); + drawGround(c, g); + const items = []; + for (const o of g.obstacles) items.push([o.y + o.h, () => { + const cx = o.x + o.w / 2, by = o.y + o.h; + if (o.kind === 'torch') { blit(c, PROPS.torch(), cx, by + 2, 2); const fl = Math.sin(g.t * 0.6 + o.y) * 1.5; ell(c, 'rgba(255,170,60,0.35)', cx, by - 26, 10, 10); ell(c, '#ff8a2a', cx, by - 25 + fl * 0.3, 4, 6); ell(c, '#ffe08a', cx, by - 24, 2, 3); } + else { shadow(c, cx, by - 2, o.w / 2, 6); blit(c, PROPS[o.kind](), cx, by + 2, 2); } + }]); + // crate art: the Grand Slime room's boxes are smiling-face boxes (doc) and two weapon crates + const crateArt = g.kind === 'grand_slime' ? (cr => cr.kind === 'wcrate' ? PROPS.wcrate : PROPS.smile) : () => PROPS.crate; + for (const cr of g.crates) items.push([cr.y + cr.h, () => blit(c, crateArt(cr)(cr.hp < 6 ? 1 : 0), cr.x + cr.w / 2, cr.y + cr.h + 2, 2)]); + items.push([g.player.y + 10, () => drawKnight(c, g)]); + items.push([g.boss.y + g.boss.r * 0.8, () => drawBoss(c, g)]); + for (const m of g.minions) items.push([m.y + 8, () => drawMinions(c, { t: g.t, minions: [m] })]); + items.sort((a, b) => a[0] - b[0]); + for (const it of items) it[1](); + drawSwing(c, g); + drawProjectiles(c, g); + drawFx(c, g); + drawReticle(c, g); + c.restore(); + drawHud(c, g); + drawResult(c, g); + c.restore(); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/soulknight_remake/game.js b/environments/games/web/games/soulknight_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..610d9ee050ea7c8c2fe69b8c690a82818d23eea4 --- /dev/null +++ b/environments/games/web/games/soulknight_remake/game.js @@ -0,0 +1,1572 @@ +/* Soul Knight (Soul Knight) boss arena, rules knight-arena@6 (@2-@4 = 2026-11-01 rounds 1-3; @5 = 2026-11-02 three + * public tiers easy/normal/hard; @6 = 2026-11-02 expansion to six bosses: Forest 1-5 + Grand Slime (2-5 Knight + * Kingdom), Varkolyn Leader (3-5 Spaceship), Volcanic Sandworm (3-5 Volcano)). + * Pure simulation (Node + browser). + * 60 Hz ticks; 1 tile = 24 px; whole room visible. Values marked "doc" come from the wiki + * from the game references. Other values are approximations. + */ +(function (root) { + 'use strict'; + // Bind the builtins once: under Node's vm sandbox (tests, harness symbolic path) every lookup of a global goes + // through the context interceptor and is ~30x slower (same functions, identical results in the browser). + const Math = root.Math, JSON = root.JSON, Object = root.Object, Set = root.Set, Map = root.Map, WeakMap = root.WeakMap; + const Int16Array = root.Int16Array, Uint8Array = root.Uint8Array, Error = root.Error, Infinity = root.Infinity; + const N = root.NativeBench, TAU = Math.PI * 2, DEG = Math.PI / 180; + const HZ = 60, TILE = 24; + const ROOM = { x0: 55, y0: 64, x1: 799, y1: 448 }; // 31 x 16 tiles + const clamp = (v, a, b) => (v < a ? a : v > b ? b : v); + const hyp = Math.hypot; + + const M = root.SoulKnightGame = { + // maxSeconds 300: the hard tier's target window is 150-240 s (the old 180 s limit would cut it off) + id: 'soulknight_remake', version: 'knight-arena@6', hz: HZ, maxSeconds: 300, dimension: '2d', + renderer: 'canvas-native', title: 'Soul Knight: Dungeon Bosses', pointerLock: true, + // public difficulty = three tiers (2026-11-02); the continuous d underneath follows LADDER below + tiers: { easy: 0.2, normal: 0.5, hard: 0.8 }, + cases: [ + { id: 'soulknight/goblin_priest', name: 'Meteor Caller', en: 'Meteor Caller' }, + { id: 'soulknight/christmas_treant', name: 'Ram Timber', en: 'Ram Timber' }, + { id: 'soulknight/devils_snare', name: 'Spin Bloom', en: 'Spin Bloom' }, + // 11-02 expansion; Chinese names from the zh wiki Boss page (evidence/wiki-cache/zh_Boss.json) + { id: 'soulknight/grand_slime', name: 'Swell Jelly', en: 'Swell Jelly' }, + { id: 'soulknight/varkolyn_leader', name: 'Violet Sweeper', en: 'Violet Sweeper' }, + { id: 'soulknight/volcanic_sandworm', name: 'Burrow Bomber', en: 'Burrow Bomber' } + ], + controls: { + 'W A S D': 'Move in eight directions (6.5 tiles/s; weapon use slows movement while attacking)', + 'J / LMB': 'Hold to attack: sidearm and burst gun fire repeatedly; the blade swings and clears bullets in its arc. At close range, guns automatically use a knife.', + 'mouse dx dy': 'Move the crosshair by relative displacement; auto-aim engages after 2 seconds without mouse input when a boss is visible', + 'K / RMB': 'Duplicate Weapon skill: copy the current weapon for 5 seconds (each copy consumes energy), followed by a 10-second cooldown. Switching weapons ends it immediately.', + 'Q': 'Switch weapons: Basic Sidearm → Burst Gun → Cutting Blade', + 'Space Shift E L R': 'No dodge roll or jump (these keys do nothing)' + }, + room: ROOM, tile: TILE + }; + + // ---- Knight, level 0 (doc: 6 HP / 5 armor / 180 energy / crit 5 / melee 4; Dual Wield 5 s, CD 10 s) + const K = M.knight = { + hp: 6, armor: 5, energy: 180, crit: 5, melee: 4, r: 9, + speed: 6.5 * TILE / HZ, // doc 6.5 tiles/s + regenDelay: 180, regenEvery: 60, // doc: 3 s without damage, then 1/s + iframes: 36, // approx 0.6 s + dual: 300, skillCd: 600, // doc 5 s / 10 s (starts after the skill ends) + copyDelay: 4, swordCopyDelay: 6, // approx "minor time difference" + knifeReach: 22, knifeCd: 60, // doc: once per second in ranged combat + switchLock: 8, poison: 240, poisonEvery: 120 + }; + // doc: damage / energy / crit / rate; approx: bullet speed, spread angle mapping, swing geometry + const WEAPONS = M.weapons = { + pistol: { name: 'Basic Sidearm', en: 'Basic Sidearm', kind: 'gun', damage: 3, cost: 0, crit: 0, spread: 2.5, interval: 18, speed: 8, move: 0.9 }, + rifle: { name: 'Burst Gun', en: 'Burst Gun', kind: 'gun', damage: 3, cost: 1, crit: 10, spread: 5, interval: 10, speed: 9, move: 6 / 6.5 }, + sword: { name: 'Cutting Blade', en: 'Cutting Blade', kind: 'melee', damage: 12, cost: 0, crit: -5, interval: 40, reach: 58, arc: 75, active: 8, move: 5.5 / 6.5 } + }; + const SLOTS = M.slots = ['pistol', 'rifle', 'sword']; + const BOSS = M.bosses = { + // The hurt capsule is [top offset, bottom offset, radius]. The movement radius is r. + goblin_priest: { hp: 480, r: 20, gap: 72, first: 70, speed: 0.9, hurt: [-22, 6, 17] }, + christmas_treant: { hp: 510, r: 30, gap: 66, first: 60, speed: 0.9, hurt: [-34, 12, 26] }, + devils_snare: { hp: 600, r: 32, gap: 56, first: 60, speed: 0, hurt: [0, 0, 32] }, + // Boss health follows the reference game. The collision capsules follow the drawn bodies. + grand_slime: { hp: 840, r: 26, gap: 70, first: 60, speed: 0.7, hurt: [-12, -6, 25] }, + varkolyn_leader: { hp: 960, r: 16, gap: 62, first: 60, speed: 0.7, hurt: [-44, -4, 13] }, + volcanic_sandworm: { hp: 950, r: 22, gap: 56, first: 50, speed: 0, hurt: [-64, -8, 14] } + }; + + // ---- difficulty ladder (knight-arena@5). Knots at d = 0, easy, normal, hard, 1; piecewise linear. + // Anchored on the original's own difficulty systems (wiki): + // easy = Normal mode boss: original cadence, projectile speed and damage + // normal = Champion boss: "attacks more frequently", same attacks and damage + // hard = Badass Mode: always Champion, "+1 damage from all sources" (status effects included), + // "enemy projectile velocity greatly increased", enemies attack more frequently + // hp multiplies the documented HP per boss (for the Forest bosses d = 0 is exactly the documented value; the + // later-floor bosses' documented 840-960 lies inside their easy..hard range). The + // original's own HP scales (Champion x1.25, co-op +50 % per extra player, at most x3.125 for a 4-player + // Champion) cannot give the normal and hard duration targets, so hp is calibrated per boss to the + // seconds windows with the standard scripted controller (the Priest walks in the open and is the + // quickest to shoot down; the Treant hides in two crate rings and is immune while charging). + // gap = attack-interval multiplier, shot = projectile speed, move = boss walk / charge / pull speed, + // dmg = extra damage per hit (rounded), chase = how close the walking bosses come to the Knight. + const H = (gp, ct, ds, gs, vl, vs) => ({ goblin_priest: gp, christmas_treant: ct, devils_snare: ds, grand_slime: gs, varkolyn_leader: vl, volcanic_sandworm: vs }); + const LADDER = [ + { d: 0.0, hp: H(1.0, 1.0, 1.0, 0.6, 0.46, 0.35), gap: 1.15, shot: 0.92, move: 0.95, dmg: 0, chase: 0 }, + { d: 0.2, hp: H(1.35, 1.15, 1.1, 0.75, 0.615, 0.43), gap: 1.0, shot: 1.0, move: 1.0, dmg: 0, chase: 0.1 }, // easy + { d: 0.5, hp: H(2.5, 2.15, 2.05, 1.4, 1.1, 0.9), gap: 0.85, shot: 1.1, move: 1.05, dmg: 0, chase: 0.5 }, // normal + { d: 0.8, hp: H(6.0, 5.1, 5.0, 3.2, 2.5, 1.9), gap: 0.72, shot: 1.3, move: 1.12, dmg: 1, chase: 0.9 }, // hard + { d: 1.0, hp: H(7.2, 6.1, 6.0, 3.8, 2.75, 2.3), gap: 0.65, shot: 1.4, move: 1.18, dmg: 1, chase: 1 } + ]; + M.ladder = function (d, kind) { + let i = 0; + while (i < LADDER.length - 2 && d > LADDER[i + 1].d) i++; + const a = LADDER[i], b = LADDER[i + 1], k = clamp((d - a.d) / (b.d - a.d), 0, 1), mix = (x, y) => x * (1 - k) + y * k; // exact at the knots + const out = { d, hp: mix(a.hp[kind], b.hp[kind]) }; + for (const key of ['gap', 'shot', 'move', 'dmg', 'chase']) out[key] = mix(a[key], b[key]); + out.dmg = Math.round(out.dmg); + return out; + }; + M.tierOf = d => ['easy', 'normal', 'hard'].find(t => Math.abs(M.tiers[t] - d) < 1e-9) || null; + + const tileRect = (c, r, w, h, kind, hp) => { + const o = { x: ROOM.x0 + c * TILE, y: ROOM.y0 + r * TILE, w: (w || 1) * TILE, h: (h || 1) * TILE, kind }; + if (hp) o.hp = hp; + return o; + }; + const crate = (c, r) => tileRect(c, r, 1, 1, 'crate', 6); + const LAYOUTS = { + // doc: little cover; tepee with 2 wooden totems at the top; torches at the edges; six crates on the walls + goblin_priest() { + return { + boss: [427, 232], player: [427, 404], + obstacles: [tileRect(14, 0, 3, 2, 'tepee'), tileRect(12, 1, 1, 1, 'totem'), tileRect(18, 1, 1, 1, 'totem'), + { x: 59, y: 160, w: 12, h: 12, kind: 'torch' }, { x: 59, y: 340, w: 12, h: 12, kind: 'torch' }, + { x: 783, y: 160, w: 12, h: 12, kind: 'torch' }, { x: 783, y: 340, w: 12, h: 12, kind: 'torch' }], + crates: [crate(3, 0), crate(27, 0), crate(0, 8), crate(30, 7), crate(8, 15), crate(22, 15)] + }; + }, + // doc: two layers of wooden crates around the boss; two trees in corners + christmas_treant() { + const crates = []; + for (let r = 7 - 3; r <= 7 + 3; r++) for (let c = 15 - 3; c <= 15 + 3; c++) { + const k = Math.max(Math.abs(c - 15), Math.abs(r - 7)); + if (k === 2 || k === 3) crates.push(crate(c, r)); + } + return { + boss: [427, 244], player: [427, 412], + obstacles: [tileRect(1, 12, 2, 2, 'tree'), tileRect(28, 12, 2, 2, 'tree')], crates + }; + }, + // doc: four stone blocks at equidistant positions on all four sides; boxes stacked in the corners + devils_snare() { + const crates = []; + for (const [c, r] of [[0, 0], [1, 0], [0, 1], [30, 0], [29, 0], [30, 1], [0, 15], [1, 15], [0, 14], [30, 15], [29, 15], [30, 14]]) crates.push(crate(c, r)); + return { + boss: [427, 256], player: [331, 436], // entrance off the stone's shadow so the boss is visible at start + // doc: "four stone blocks at equidistant positions": 140 px from the boss on all four sides + obstacles: [{ x: 403, y: 92, w: 48, h: 48, kind: 'stone' }, { x: 403, y: 372, w: 48, h: 48, kind: 'stone' }, + { x: 263, y: 232, w: 48, h: 48, kind: 'stone' }, { x: 543, y: 232, w: 48, h: 48, kind: 'stone' }], + crates + }; + }, + // doc (Grand Slime, Room Layout): 3 Slow Tiles with 2 Boost Tiles beside them in the centre; smiling-face boxes + // around them, 2 weapon crates among the boxes (approx: 2x2-tile pads, boxes as ordinary 6-HP crates) + grand_slime() { + const tiles = [['boost', 9], ['slow', 11], ['slow', 14], ['slow', 17], ['boost', 20]].map(([kind, c]) => tileRect(c, 7, 2, 2, kind)); + const crates = [[8, 5], [8, 10], [22, 5], [22, 10], [12, 5], [18, 5], [12, 10], [18, 10]].map(([c, r]) => crate(c, r)); + crates.push(Object.assign(crate(15, 5), { kind: 'wcrate' }), Object.assign(crate(15, 10), { kind: 'wcrate' })); + return { boss: [427, 150], player: [427, 412], obstacles: [], crates, tiles }; + }, + // doc (Varkolyn Leader, Room): "The room is clear and has no cover at all." + varkolyn_leader() { + return { boss: [427, 196], player: [427, 412], obstacles: [], crates: [] }; + }, + // doc (Volcanic Sandworm, Room): one pillar and 3 layers of crates in each corner (approx: pillar in the centre, + // each corner a 3-2-1 stack) + volcanic_sandworm() { + const crates = []; + for (const [cx, cy, sx, sy] of [[0, 0, 1, 1], [30, 0, -1, 1], [0, 15, 1, -1], [30, 15, -1, -1]]) + for (let i = 0; i < 3; i++) for (let j = 0; j < 3 - i; j++) crates.push(crate(cx + sx * j, cy + sy * i)); + return { boss: [427, 150], player: [427, 412], obstacles: [tileRect(14, 7, 2, 2, 'pillar')], crates }; + } + }; + M.layouts = LAYOUTS; + + const BAG = { grand_slime: 1, varkolyn_leader: 1, volcanic_sandworm: 1 }; + const POOLS = { + goblin_priest: [['meteor', 'orbs', 'turrets', 'stars'], ['meteor', 'orbs', 'turrets', 'stars']], + christmas_treant: [['hold', 'throw', 'waves'], ['charge', 'homing', 'cross', 'line', 'throw', 'waves', 'hold', 'charge']], + // doc (Devil's Snare/Tactics, Strengths): the boss sits in an almost permanent poison pool -> pool weighted x2, 9 s life + devils_snare: [['bubbles', 'rotate', 'beams', 'bubbles', 'rotate', 'beams', 'pool', 'pool'], + ['bubbles', 'rotate', 'beams', 'pool', 'pool', 'corner', 'corner', 'pull', 'rotate']], + // doc: 4 normal attacks; enraged adds the 15-hit explosion (runs beside the pool, see updateBoss) and 5-damage slams + grand_slime: [['slam', 'rings', 'spawn', 'goo', 'slam', 'rings'], ['slam', 'rings', 'spawn', 'goo', 'slam', 'rings', 'goo']], + // doc: 5 attacks; enraged attacks much more frequently, faster laser (gap x0.6 + laser timing) + varkolyn_leader: [['pools', 'tentacles', 'ring', 'laser', 'orb', 'pools', 'ring'], ['pools', 'tentacles', 'ring', 'laser', 'orb', 'pools', 'ring', 'laser']], + // doc: explosive / big spread / dig (+ resurface); enraged digs and resurfaces much faster, continuous dives + volcanic_sandworm: [['explosive', 'spread', 'dig', 'explosive', 'spread', 'dig'], ['explosive', 'spread', 'dig', 'dive', 'explosive', 'spread', 'dive']] + }; + + function rectHit(x, y, r, o) { + const cx = clamp(x, o.x, o.x + o.w), cy = clamp(y, o.y, o.y + o.h); + const dx = x - cx, dy = y - cy; + return dx * dx + dy * dy < r * r; + } + function segRect(ax, ay, bx, by, o) { // Liang-Barsky: does segment a-b cross rect o? + let t0 = 0, t1 = 1; + const dx = bx - ax, dy = by - ay; + const p = [-dx, dx, -dy, dy], q = [ax - o.x, o.x + o.w - ax, ay - o.y, o.y + o.h - ay]; + for (let i = 0; i < 4; i++) { + if (p[i] === 0) { if (q[i] < 0) return false; continue; } + const t = q[i] / p[i]; + if (p[i] < 0) { if (t > t1) return false; if (t > t0) t0 = t; } + else { if (t < t0) return false; if (t < t1) t1 = t; } + } + return t0 <= t1; + } + const angDiff = (a, b) => Math.abs(Math.atan2(Math.sin(a - b), Math.cos(a - b))); + // Reject segments outside the expanded bounding box before measuring their distance. + const segNear = (p, a, b, R) => !(p.x < Math.min(a.x, b.x) - R - 1 || p.x > Math.max(a.x, b.x) + R + 1 || + p.y < Math.min(a.y, b.y) - R - 1 || p.y > Math.max(a.y, b.y) + R + 1) && N.segmentDistance(p, a, b) < R; + + class Game { + constructor(id, seed, d) { + const kind = id.split('/')[1]; + if (!LAYOUTS[kind]) throw Error('Unknown case ' + id); + this.id = id; this.kind = kind; this.rng = Game.mixSeed(seed); this.d = d; this.t = 0; + this.outcome = null; this.events = []; + const T = this.tier = M.ladder(d, kind); // knight-arena@5 difficulty ladder (see LADDER) + this.spd = T.shot; // projectile speed multiplier + this.gapMul = T.gap; // attack interval multiplier + this.moveMul = T.move; // boss walk / charge / pull speed multiplier + this.dmgUp = T.dmg; // extra damage per hit (Badass rule: all sources) + const L = LAYOUTS[kind](); + this.obstacles = L.obstacles; this.crates = L.crates; this.tiles = L.tiles || []; + this.player = { + x: L.player[0], y: L.player[1], r: K.r, hp: K.hp, maxHp: K.hp, armor: K.armor, maxArmor: K.armor, + energy: K.energy, maxEnergy: K.energy, inv: 0, sinceHit: 9999, poison: 0, poisonT: 0, + slot: 0, cd: 0, lock: 0, copy: 0, copyW: '', dual: 0, skillCd: 0, knifeCd: 0, + swing: 0, swingA: 0, swingKind: '', aimX: L.boss[0], aimY: L.boss[1], aimA: -Math.PI / 2, manual: 0, + face: 1, lastShot: -99, lastCopy: -99, hurtT: -99, dead: 0, moving: 0, step: 0, tileT: 0, tileK: '' + }; + this.held = []; + const B = BOSS[kind], hp = Math.round(B.hp * T.hp); + this.boss = { + kind, x: L.boss[0], y: L.boss[1], r: B.r, hp, maxHp: hp, enraged: false, state: 'idle', + timer: Math.round(B.first * T.gap), atk: '', at: 0, last: '', vars: {}, vx: 0, vy: 0, face: 1, flash: -99, inv: false, + tx: L.boss[0], ty: L.boss[1], tentacles: [], deadT: 0, seq: 0, phaseT: -99, + tileT: 0, tileK: '', under: false, shield: 0, vuln: 0, wasInPool: false, charge: 0, boom: 0 + }; + this.shots = []; this.bullets = []; this.meteors = []; this.lines = []; this.nodes = []; this.pools = []; + this.orbs = []; this.turrets = []; this.carriers = []; this.balls = []; this.pickups = []; this.fx = []; + this.minions = []; this.booms = []; this.stars = []; this.quakes = []; + this.shake = { t: -99, a: 0 }; + this.stats = { shots: 0, hits: 0, damageDealt: 0, damageTaken: 0, cuts: 0, crits: 0, knife: 0, swings: 0 }; + } + + ev(name) { this.events.push(name); } + health() { return [this.player.hp, this.player.maxHp, this.boss.hp, this.boss.maxHp]; } + rand() { return N.rand(this); } + shakeIt(a) { if (this.t - this.shake.t > 6 || a > this.shake.a) this.shake = { t: this.t, a }; } + + // ---------------- geometry ---------------- + solidAt(x, y, r, withCrates) { + if (x - r < ROOM.x0 || x + r > ROOM.x1 || y - r < ROOM.y0 || y + r > ROOM.y1) return true; + for (const o of this.obstacles) if (rectHit(x, y, r, o)) return true; + if (withCrates) for (const c of this.crates) if (rectHit(x, y, r, c)) return true; + return false; + } + obstacleAt(x, y, r) { + for (const o of this.obstacles) if (rectHit(x, y, r, o)) return o; + return null; + } + crateAt(x, y, r) { + for (const c of this.crates) if (c.hp > 0 && rectHit(x, y, r, c)) return c; + return null; + } + sight(a, b) { + for (const o of this.obstacles) if (o.kind !== 'torch' && segRect(a.x, a.y, b.x, b.y, o)) return false; + for (const c of this.crates) if (c.hp > 0 && segRect(a.x, a.y, b.x, b.y, c)) return false; + return true; + } + capDist(x, y) { // distance from (x, y) to the boss hurt capsule axis + const b = this.boss, h = BOSS[b.kind].hurt; + return hyp(x - b.x, y - clamp(y, b.y + h[0], b.y + h[1])); + } + bossHurt(x, y, r) { return this.capDist(x, y) < BOSS[this.boss.kind].hurt[2] + r; } + bodyBlock(nx, ny, ox, oy, r) { // the boss body is solid for the Knight; moving out is always allowed + const b = this.boss; + if (b.hp <= 0 || b.state === 'dying' || b.under) return false; + const lim = BOSS[b.kind].hurt[2] + r - 4, dn = this.capDist(nx, ny); + return dn < lim && dn < this.capDist(ox, oy); + } + // doc (Status Effects): Slow tile = -50 % speed for 2 s, Boost tile = +20 % for 2 s; a running effect is neither + // refreshed nor replaced by another tile, and Slow blocks Boost; tiles affect enemies too + tileStatus(o) { + if (o.tileT > 0 && --o.tileT === 0) o.tileK = ''; + if (o.tileT > 0) return; + for (const t of this.tiles) if (o.x >= t.x && o.x < t.x + t.w && o.y >= t.y && o.y < t.y + t.h) { o.tileK = t.kind; o.tileT = M.TILE_FX; this.ev(t.kind); return; } + } + speedMul(o, poisoned) { return poisoned || o.tileK === 'slow' ? 0.5 : o.tileK === 'boost' ? 1.2 : 1; } // slows do not stack + canHit() { const b = this.boss; return b.hp > 0 && b.state !== 'dying' && !b.under; } + moveBody(o, dx, dy, smash) { + const r = o.r, crates = !smash, isP = o === this.player; + if (dx && !this.solidAt(o.x + dx, o.y, r, crates) && !(isP && this.bodyBlock(o.x + dx, o.y, o.x, o.y, r))) o.x += dx; + if (dy && !this.solidAt(o.x, o.y + dy, r, crates) && !(isP && this.bodyBlock(o.x, o.y + dy, o.x, o.y, r))) o.y += dy; + if (smash) for (const c of this.crates) if (c.hp > 0 && rectHit(o.x, o.y, r, c)) this.breakCrate(c); + } + damageCrate(c, dmg) { c.hp -= dmg; if (c.hp <= 0) this.breakCrate(c); } + breakCrate(c) { + if (c.hp === -1) return; + c.hp = -1; + this.fx.push({ k: 'debris', x: c.x + c.w / 2, y: c.y + c.h / 2, t: this.t }); + this.ev('crate_break'); + } + + // ---------------- update ---------------- + update(keys, pressed, mouse) { + this.held = [...keys].sort(); + this.updatePlayer(keys, pressed, mouse); + this.updateBoss(); + this.updateShots(); + this.updateBullets(); + this.updateHazards(); + this.updatePickups(); + if (this.crates.some(c => c.hp <= 0)) this.crates = this.crates.filter(c => c.hp > 0); + const keep = this.t - 48; + if (this.fx.length && this.fx[0].t < keep) this.fx = this.fx.filter(f => f.t >= keep); + if (this.fx.length > 90) this.fx = this.fx.slice(-90); + const b = this.boss, p = this.player; + if (!this.outcome && this.t + 1 >= HZ * M.maxSeconds) { + if (b.state === 'dying') this.outcome = 'win'; + else if (p.dead > 0) this.outcome = 'loss'; + } + } + + updatePlayer(keys, pressed, mouse) { + const p = this.player, b = this.boss; + if (p.inv > 0) p.inv--; + if (p.cd > 0) p.cd--; + if (p.lock > 0) p.lock--; + if (p.knifeCd > 0) p.knifeCd--; + if (p.swing > 0) p.swing--; + if (p.dead > 0) { + p.dead--; + if (p.dead === 0 && !this.outcome) this.outcome = 'loss'; + return; + } + p.sinceHit++; + if (p.armor < p.maxArmor && p.sinceHit >= K.regenDelay && (p.sinceHit - K.regenDelay) % K.regenEvery === 0) { + p.armor++; this.ev('armor_regen'); + } + if (p.poison > 0) { + p.poison--; p.poisonT++; + if (p.poisonT % K.poisonEvery === 0) this.applyDamage(1, 'poison'); + if (p.dead > 0) return; + } + // skill: Dual Wield (press) + if ((pressed.has('K') || pressed.has('RMB')) && p.dual === 0 && p.skillCd === 0) { p.dual = K.dual; this.ev('dual_wield'); } + if (p.dual > 0) { + p.dual--; + if (p.dual === 0) { p.skillCd = K.skillCd; this.ev('dual_end'); } + } else if (p.skillCd > 0) p.skillCd--; + // weapon switch (press); doc: switching ends Dual Wield immediately + if (pressed.has('Q')) { + p.slot = (p.slot + 1) % SLOTS.length; p.lock = K.switchLock; p.copy = 0; p.swing = 0; + if (p.dual > 0) { p.dual = 0; p.skillCd = K.skillCd; this.ev('dual_end'); } + this.ev('switch'); + } + // aim: relative mouse reticle, auto-aim fallback + if (mouse[0] || mouse[1]) { + p.aimX = clamp(p.aimX + mouse[0], ROOM.x0, ROOM.x1); p.aimY = clamp(p.aimY + mouse[1], ROOM.y0, ROOM.y1); p.manual = 120; + } else if (p.manual > 0) p.manual--; + else if (b.hp > 0 && this.sight(p, b)) { p.aimX += (b.x - p.aimX) * 0.3; p.aimY += (b.y - p.aimY) * 0.3; } + const ax = p.aimX - p.x, ay = p.aimY - p.y; + if (ax * ax + ay * ay > 16) p.aimA = Math.atan2(ay, ax); + p.face = Math.cos(p.aimA) >= 0 ? 1 : -1; + // movement + const mx = (keys.has('D') ? 1 : 0) - (keys.has('A') ? 1 : 0), my = (keys.has('S') ? 1 : 0) - (keys.has('W') ? 1 : 0); + const attacking = keys.has('J') || keys.has('LMB'); + const wid = SLOTS[p.slot], w = WEAPONS[wid]; + if (this.tiles.length) this.tileStatus(p); + if (mx || my) { + const n = hyp(mx, my), sp = K.speed * (attacking ? w.move : 1) * this.speedMul(p, p.poison > 0); + this.moveBody(p, mx / n * sp, my / n * sp, false); + p.moving = 1; p.step++; + } else p.moving = 0; + // attack + if (attacking && p.cd <= 0 && p.lock <= 0) this.attack(wid, false); + if (p.copy > 0) { + p.copy--; + if (p.copy === 0 && p.dual > 0 && SLOTS[p.slot] === p.copyW) this.attack(p.copyW, true); + } + if (p.swing > 0 && p.swingKind !== 'knife') this.cut(p.swingA, WEAPONS.sword); + } + + attack(wid, copy) { + const p = this.player, b = this.boss, w = WEAPONS[wid]; + const alive = b.hp > 0 && b.state !== 'dying' && !b.under; + if (w.kind === 'gun' && alive && this.capDist(p.x, p.y) - BOSS[b.kind].hurt[2] - p.r < K.knifeReach && (copy || p.knifeCd <= 0)) { + if (!copy) { p.knifeCd = K.knifeCd; p.cd = Math.max(p.cd, 14); if (p.dual > 0) { p.copy = K.copyDelay; p.copyW = wid; } } + const crit = this.rand() * 100 < K.crit; + p.swing = 10; p.swingKind = 'knife'; p.swingA = Math.atan2(b.y - p.y, b.x - p.x); + this.stats.knife++; + this.hitBoss(K.melee * (crit ? 2 : 1), crit); + this.ev('knife'); + return true; + } + if (w.kind === 'gun') { + if (p.energy < w.cost) { if (!copy) { p.cd = 8; this.ev('no_energy'); } return false; } + p.energy -= w.cost; + const crit = this.rand() * 100 < w.crit + K.crit; + const a = p.aimA + (this.rand() * 2 - 1) * w.spread * DEG; + const side = copy ? 7 : 0, c = Math.cos(a), s = Math.sin(a); + this.shots.push({ x: p.x + c * 15 - s * side, y: p.y + 3 + s * 15 + c * side, vx: c * w.speed, vy: s * w.speed, + r: 3, dmg: w.damage * (crit ? 2 : 1), crit, life: 100, w: wid }); + if (copy) p.lastCopy = this.t; else { + p.lastShot = this.t; p.cd = w.interval; + if (p.dual > 0) { p.copy = K.copyDelay; p.copyW = wid; } + } + this.stats.shots++; + this.ev('fire'); + return true; + } + // melee weapon: wide swing (doc), destroys hostile projectiles (doc), damage once per swing + if (!copy) { p.cd = w.interval; if (p.dual > 0) { p.copy = K.swordCopyDelay; p.copyW = wid; } } + p.swing = w.active; p.swingA = p.aimA; p.swingKind = copy ? 'sword2' : 'sword'; + this.stats.swings++; + const crit = this.rand() * 100 < w.crit + K.crit; + const h = BOSS[b.kind].hurt; + if (alive && this.inArc(b.x, b.y + (h[0] + h[1]) / 2, h[2] + (h[1] - h[0]) / 2, p.aimA, w.reach, w.arc)) this.hitBoss(w.damage * (crit ? 2 : 1), crit); + for (const m of this.minions) if (m.hp > 0 && !m.emerge && this.inArc(m.x, m.y, m.r, p.aimA, w.reach, w.arc)) this.hitMinion(m, w.damage * (crit ? 2 : 1)); + for (const cr of this.crates) if (cr.hp > 0 && this.inArc(cr.x + cr.w / 2, cr.y + cr.h / 2, 12, p.aimA, w.reach, w.arc)) this.damageCrate(cr, w.damage); + this.cut(p.aimA, w); + this.ev('swing'); + return true; + } + inArc(x, y, r, a, reach, arc) { + const p = this.player, dx = x - p.x, dy = y - p.y, dist = hyp(dx, dy); + if (dist > reach + r) return false; + if (dist < r + p.r) return true; + return angDiff(Math.atan2(dy, dx), a) <= arc * DEG + Math.asin(Math.min(1, r / dist)); + } + cut(a, w) { + let n = 0; + for (const q of this.bullets) if (!q.dead && q.cut && this.inArc(q.x, q.y, q.r, a, w.reach, w.arc)) { + q.dead = 1; n++; + if (n <= 6) this.fx.push({ k: 'spark', x: q.x, y: q.y, t: this.t, c: 1 }); + } + for (const q of this.turrets) if (!q.dead && this.inArc(q.x, q.y, q.r, a, w.reach, w.arc)) { q.dead = 1; n++; this.fx.push({ k: 'spark', x: q.x, y: q.y, t: this.t, c: 1 }); } + for (const q of this.carriers) if (!q.dead && this.inArc(q.x, q.y, 8, a, w.reach, w.arc)) { q.dead = 1; n++; } + // doc: the Sandworm's star "can be destroyed if a melee weapon is slashed at it"; the Varkolyn orb is a projectile too + for (const q of this.stars) if (!q.dead && this.inArc(q.x, q.y, q.r, a, w.reach, w.arc)) { q.dead = 1; n++; this.fx.push({ k: 'spark', x: q.x, y: q.y, t: this.t, c: 1 }); } + if (n) { + this.bullets = this.bullets.filter(q => !q.dead); + this.turrets = this.turrets.filter(q => !q.dead); + this.carriers = this.carriers.filter(q => !q.dead); + this.stars = this.stars.filter(q => !q.dead); + this.stats.cuts += n; this.ev('cut'); + } + } + + hitBoss(dmg, crit) { + const b = this.boss; + if (b.hp <= 0 || b.state === 'dying' || b.under) return false; + if (b.inv || b.shield > 0) { + if (!this.fx.some(f => f.k === 'txt' && this.t - f.t < 24)) this.fx.push({ k: 'txt', x: b.x, y: b.y - b.r - 10, s: 'Immune', t: this.t }); + return false; + } + const v = Math.min(dmg, b.hp); + b.hp -= v; b.flash = this.t; + this.stats.damageDealt += v; this.stats.hits++; + if (crit) { this.stats.crits++; this.shakeIt(2); } + const j = (this.stats.hits * 37) % 29 - 14; + this.fx.push({ k: 'num', x: b.x + j, y: b.y - b.r - 4, v: dmg, crit: !!crit, t: this.t }); + this.ev(crit ? 'crit' : 'boss_hit'); + // doc (Grand Slime, enraged): after 15 hits the charge bar fills and it explodes on its position + if (b.kind === 'grand_slime' && b.enraged && b.boom === 0 && b.hp > 0 && ++b.charge >= M.SLIME_HITS) { b.charge = 0; b.boom = M.SLIME_SWELL; this.ev('swell'); } + if (b.hp <= 0) this.bossDeath(); + else if (!b.enraged && b.hp < b.maxHp / 2) this.enrage(); + return true; + } + hitMinion(m, dmg) { + if (m.hp <= 0 || m.emerge > 0) return false; + m.hp -= dmg; m.flash = this.t; + if (m.hp <= 0) { + m.dead = 1; this.ev(m.kind + '_down'); + if (m.kind === 'slime') { // doc: after 1 second, 8 projectiles in all directions (2 dmg); approx: drops 1 energy orb + this.booms.push({ kind: 'burst8', x: m.x, y: m.y, t: 60, total: 60 }); + this.dropOrbs(1, m.x, m.y); + } else if (m.kind === 'tentacle') { // doc: leaves purple poison gas when killed + this.pools.push({ x: m.x, y: m.y, r: 34, life: 360, purple: 1, form: 0 }); + } + } + return true; + } + hurt(dmg, src) { + const p = this.player; + if (p.inv > 0 || p.hp <= 0 || p.dead > 0) return false; + this.applyDamage(dmg, src); + p.inv = K.iframes; + return true; + } + applyDamage(dmg, src) { + const p = this.player; + if (p.hp <= 0 || this.boss.state === 'dying') return; + dmg += this.dmgUp; // hard tier, doc (Badass Mode): 1 extra damage from all sources, status effects included + p.sinceHit = 0; p.hurtT = this.t; this.stats.damageTaken += dmg; + if (p.armor >= dmg) { p.armor -= dmg; this.ev(p.armor ? 'armor_hit' : 'armor_break'); } + else { // doc: excess damage goes to health (no Strong Shield at level 0) + const had = p.armor, over = dmg - p.armor; + p.armor = 0; p.hp = Math.max(0, p.hp - over); this.ev(had ? 'armor_break' : 'hurt'); + } + this.fx.push({ k: 'pnum', x: p.x, y: p.y - 22, v: dmg, t: this.t, s: src === 'poison' ? 1 : 0 }); + this.shakeIt(src === 'poison' ? 1 : 3); + if (p.hp <= 0 && !p.dead) { p.dead = 40; p.poison = 0; this.ev('player_down'); } + } + poisonPlayer() { + const p = this.player; + if (p.hp <= 0) return; + if (p.poison === 0) p.poisonT = 0; + p.poison = K.poison; + } + + // ---------------- boss ---------------- + bspeed(v) { return v * this.spd * (this.boss.enraged ? 1.2 : 1); } + aimAt(x, y) { const p = this.player; return Math.atan2(p.y - y, p.x - x); } + bullet(x, y, a, speed, o) { + let s = this.bspeed(speed); + if (o && o.cap) { s = Math.min(s, o.cap); o = Object.assign({}, o); delete o.cap; } + const q = Object.assign({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, r: 5, dmg: 2, kind: 'small', cut: true, age: 0, life: 600 }, o || {}); + this.bullets.push(q); + return q; + } + ring(x, y, n, a0, speed, o) { for (let i = 0; i < n; i++) this.bullet(x, y, a0 + i * TAU / n, speed, o); } + // the lane is drawn M.LINE_LEAD ticks before its first node (11-02 audit: node 1 used to spawn - and hurt - in the + // tick the line was cast, before any lane was drawn); c is decremented once in the casting tick, hence + 1 + line(x, y, a, n, every, start) { this.lines.push({ x, y, a, k: 0, n, gap: 30, every, c: M.LINE_LEAD + 1, start, dmg: 3 }); } + dropOrbs(n, x, y) { + for (let i = 0; i < n; i++) { + const a = i * TAU / n + this.rand() * 0.5, s = 1.6 + this.rand() * 1.6; + this.pickups.push({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, age: 0, v: 4 }); + } + } + enrage() { + const b = this.boss; + b.enraged = true; b.phaseT = this.t; + this.dropOrbs(10, b.x, b.y); // doc: 10 energy orbs at half health + this.ev('enrage'); this.shakeIt(4); + this.fx.push({ k: 'txt', x: b.x, y: b.y - b.r - 18, s: 'Enraged!', t: this.t, big: 1 }); + // transform scripts: Treant 7 shockwave lines, Snare opens with 4 tentacles, Grand Slime explodes once (doc); + // the Varkolyn Leader and the Sandworm have no documented transform and keep their current attack + if (b.kind === 'christmas_treant' || b.kind === 'devils_snare' || b.kind === 'grand_slime') { + b.state = 'transform'; b.atk = 'transform'; b.at = 0; b.vars = {}; b.inv = false; + } + } + bossDeath() { + const b = this.boss; + b.hp = 0; b.state = 'dying'; b.deadT = 60; b.inv = false; b.atk = ''; b.under = false; b.shield = 0; b.boom = 0; + this.bullets = []; this.meteors = []; this.lines = []; this.nodes = []; this.pools = []; + this.orbs = []; this.turrets = []; this.carriers = []; this.balls = []; + this.minions = []; this.booms = []; this.stars = []; this.quakes = []; + this.player.poison = 0; + this.dropOrbs(10, b.x, b.y); + this.ev('boss_defeated'); this.shakeIt(6); + this.fx.push({ k: 'boom', x: b.x, y: b.y, r: b.r * 2, t: this.t }); + } + pickAttack() { + const b = this.boss, pool = POOLS[b.kind][b.enraged ? 1 : 0]; + if (BAG[b.kind]) { + // Draw from a shuffled bag so every attack appears once per cycle without an immediate repeat. + const key = b.enraged ? 1 : 0; + if (!b.bag || b.bagPhase !== key || !b.bag.length) { b.bag = pool.slice(); b.bagPhase = key; } + let i = Math.floor(this.rand() * b.bag.length); + if (b.bag[i] === b.last && b.bag.length > 1) i = (i + 1) % b.bag.length; + return b.bag.splice(i, 1)[0]; + } + let name = b.last; + for (let i = 0; i < 6 && name === b.last; i++) name = pool[Math.floor(this.rand() * pool.length)]; + return name; + } + updateBoss() { + const b = this.boss, p = this.player; + b.vx = 0; b.vy = 0; + if (b.state === 'dying') { + b.deadT--; + if (b.deadT <= 0 && !this.outcome) this.outcome = 'win'; + return; + } + if (b.hp <= 0) return; + b.face = p.x >= b.x ? 1 : -1; + if (b.state === 'idle') { + this.idleMove(); + if (--b.timer <= 0) { + const name = this.pickAttack(); + b.state = 'cast'; b.atk = name; b.at = 0; b.vars = {}; b.last = name; b.seq++; + this.ev('boss_attack'); + } + } else { + const done = ATTACKS[b.kind][b.atk].call(this, b, b.at, b.vars); + b.at++; + if (done && b.state !== 'dying') { + b.state = 'idle'; b.atk = ''; b.vars = {}; b.inv = false; + b.timer = Math.max(12, Math.round(BOSS[b.kind].gap * this.gapMul * (b.enraged ? 0.6 : 1))); + } + } + if (b.tentacles.length && p.dead === 0) for (const t of b.tentacles) if (hyp(p.x - t.x, p.y - t.y) < p.r + t.r) this.hurt(2, 'tentacle'); + if (b.kind === 'grand_slime') this.slimeTick(b, p); + else if (b.kind === 'varkolyn_leader') this.shieldTick(b); + } + slimeTick(b, p) { + // doc: "can deal damage upon contact, especially when enraged" (approx 2 / 3 damage) + if (p.dead === 0 && this.capDist(p.x, p.y) < BOSS[b.kind].hurt[2] + p.r) this.hurt(b.enraged ? 3 : 2, 'contact'); + // doc: explosion on its current position after 15 hits while enraged, and once right after enraging; the swell + // (M.SLIME_SWELL ticks) is drawn as a growing ring with the exact blast radius + if (b.boom > 0 && --b.boom === 0) { + this.fx.push({ k: 'boom', x: b.x, y: b.y, r: M.SLIME_BLAST, t: this.t }); this.shakeIt(6); this.ev('slime_blast'); + if (p.dead === 0 && hyp(p.x - b.x, p.y - b.y) < M.SLIME_BLAST + p.r) this.hurt(5, 'blast'); + for (const c of this.crates) if (c.hp > 0 && rectHit(b.x, b.y, M.SLIME_BLAST, c)) this.breakCrate(c); + } + } + shieldTick(b) { + // Entering a purple pool grants temporary invulnerability followed by a forced vulnerability window. + const inPool = this.pools.some(q => q.purple && !(q.form > 0) && hyp(b.x - q.x, b.y - q.y) < q.r), entered = inPool && !b.wasInPool; + b.wasInPool = inPool; + if (b.shield > 0) { if (--b.shield === 0 || !inPool) { b.shield = 0; b.vuln = M.VARK_VULN; this.ev('shield_end'); } } + else if (b.vuln > 0) b.vuln--; + else if (entered && !b.under) { b.shield = M.VARK_SHIELD; this.ev('shield'); } + } + idleMove() { + const b = this.boss, p = this.player; + const ox = b.x, oy = b.y; + if (b.kind === 'goblin_priest') { + if (hyp(b.tx - b.x, b.ty - b.y) < 6) this.newWalkTarget(); + const a = Math.atan2(b.ty - b.y, b.tx - b.x), s = BOSS[b.kind].speed * this.moveMul; + this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); + if (hyp(b.x - ox, b.y - oy) < 0.2) this.newWalkTarget(); + } else if (b.kind === 'christmas_treant' && b.enraged) { + // The enraged boss closes in. If it lacks a clear firing line, it paths around obstacles. + const d = hyp(p.x - b.x, p.y - b.y), stop = 170 - 60 * this.tier.chase, s = BOSS[b.kind].speed * this.moveMul; + if (!this.clearLine(b, p, M.FIRE_PAD)) this.navStep(b, s); + else if (d > stop) { const a = Math.atan2(p.y - b.y, p.x - b.x); this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); } + } else if (b.kind === 'grand_slime' && b.boom === 0) { + // walks toward the Knight (walking animation, contact damage); enraged it presses into contact; tiles affect it + this.tileStatus(b); + const d = hyp(p.x - b.x, p.y - b.y), stop = b.enraged ? 60 - 30 * this.tier.chase : 150 - 60 * this.tier.chase; + const s = BOSS[b.kind].speed * this.moveMul * (b.enraged ? 1.2 : 1) * this.speedMul(b, false); + if (d > stop) { const a = Math.atan2(p.y - b.y, p.x - b.x); this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); } + } else if (b.kind === 'varkolyn_leader') { + if (hyp(b.tx - b.x, b.ty - b.y) < 6) this.newWalkTarget(); + const a = Math.atan2(b.ty - b.y, b.tx - b.x), s = BOSS[b.kind].speed * this.moveMul; + this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); + if (hyp(b.x - ox, b.y - oy) < 0.2) this.newWalkTarget(); + } + b.vx = b.x - ox; b.vy = b.y - oy; + } + clearLine(a, b, pad) { // line of fire ignoring crates (the Treant rams them) and torches; pad widens obstacles + const m = pad || 0; + for (const o of this.obstacles) if (o.kind !== 'torch' && segRect(a.x, a.y, b.x, b.y, m ? { x: o.x - m, y: o.y - m, w: o.w + 2 * m, h: o.h + 2 * m } : o)) return false; + return true; + } + navStep(b, s) { // one step down a BFS field toward the nearest standable tile with a padded line of fire + const p = this.player, F = navGrid(this, b), cols = F.cols; + const tile = (x, y) => clamp(Math.floor((y - ROOM.y0) / TILE), 0, F.rows - 1) * cols + clamp(Math.floor((x - ROOM.x0) / TILE), 0, cols - 1); + const dist = navField(this, F, tile(p.x, p.y)), here = tile(b.x, b.y), hx = here % cols, hy = (here - hx) / cols; + let best = -1; + for (let r = 1; r <= 3 && best < 0; r++) for (let Y = hy - r; Y <= hy + r; Y++) for (let X = hx - r; X <= hx + r; X++) { + if (X < 0 || Y < 0 || X >= cols || Y >= F.rows) continue; + const k = Y * cols + X; + if (dist[k] < 0) continue; + if (best < 0 || dist[k] < dist[best] || (dist[k] === dist[best] && hyp(F.pt[k].x - b.x, F.pt[k].y - b.y) < hyp(F.pt[best].x - b.x, F.pt[best].y - b.y))) best = k; + } + // already on a firing tile (the exact line still grazes): close in on the Knight directly + const t = best < 0 || (dist[here] === 0 && dist[best] === 0) ? p : F.pt[best], a = Math.atan2(t.y - b.y, t.x - b.x); + if (hyp(t.x - b.x, t.y - b.y) > 1) this.moveBody(b, Math.cos(a) * s, Math.sin(a) * s, true); + } + newWalkTarget() { // 3 random points; keep the one closest to the tier's preferred distance from the Knight + const b = this.boss, p = this.player, want = b.kind === 'varkolyn_leader' ? 300 - 140 * this.tier.chase : 360 - 200 * this.tier.chase; + let best = null, bd = Infinity; + for (let i = 0; i < 3; i++) { + const x = ROOM.x0 + 110 + this.rand() * (ROOM.x1 - ROOM.x0 - 220), y = ROOM.y0 + 90 + this.rand() * (ROOM.y1 - ROOM.y0 - 200); + const d = Math.abs(hyp(x - p.x, y - p.y) - want); + if (d < bd) { bd = d; best = [x, y]; } + } + b.tx = best[0]; b.ty = best[1]; + } + + // ---------------- projectiles & hazards ---------------- + updateShots() { + const b = this.boss, live = b.hp > 0 && b.state !== 'dying' && !b.under; + for (const s of this.shots) { + const old = { x: s.x, y: s.y }; + s.x += s.vx; s.y += s.vy; s.life--; + let hitM = null; + for (const m of this.minions) if (m.hp > 0 && !m.emerge && segNear(m, old, s, m.r + s.r)) { hitM = m; break; } + if (hitM) { this.hitMinion(hitM, s.dmg); s.dead = 1; this.fx.push({ k: 'spark', x: s.x, y: s.y, t: this.t, c: 0 }); continue; } + if (live && (this.bossHurt(s.x, s.y, s.r) || this.bossHurt((old.x + s.x) / 2, (old.y + s.y) / 2, s.r))) { + this.hitBoss(s.dmg, s.crit); s.dead = 1; + this.fx.push({ k: 'spark', x: s.x, y: s.y, t: this.t, c: 0 }); + continue; + } + if (s.x < ROOM.x0 || s.x > ROOM.x1 || s.y < ROOM.y0 || s.y > ROOM.y1 || this.obstacleAt(s.x, s.y, 1)) { + s.dead = 1; this.fx.push({ k: 'spark', x: clamp(s.x, ROOM.x0, ROOM.x1), y: clamp(s.y, ROOM.y0, ROOM.y1), t: this.t, c: 0 }); + continue; + } + const c = this.crateAt(s.x, s.y, 1); + if (c) { this.damageCrate(c, s.dmg); s.dead = 1; continue; } + if (s.life <= 0) s.dead = 1; + } + this.shots = this.shots.filter(s => !s.dead); + } + updateBullets() { + const p = this.player; + for (const q of this.bullets) { + if (q.split !== undefined) { + if (--q.split <= 0) { + q.dead = 1; + const a0 = this.rand() * TAU; + for (let i = 0; i < 3; i++) this.bullet(q.x, q.y, a0 + i * TAU / 3, 2.6, { r: 4, dmg: 2 }); + continue; + } + } + if (q.kind === 'homing') { + if (q.hover > 0) { + q.hover--; + if (q.hover === 0) { const a = this.aimAt(q.x, q.y), s = this.bspeed(2.6); q.vx = Math.cos(a) * s; q.vy = Math.sin(a) * s; } + } else { + const a = Math.atan2(q.vy, q.vx), want = this.aimAt(q.x, q.y); + let d = Math.atan2(Math.sin(want - a), Math.cos(want - a)); + d = clamp(d, -0.035, 0.035); + const s = hyp(q.vx, q.vy); + q.vx = Math.cos(a + d) * s; q.vy = Math.sin(a + d) * s; + } + } + if (q.trail !== undefined && --q.trail <= 0) { + q.trail = 5; + const a = Math.atan2(q.vy, q.vx), life = this.boss.enraged ? 360 : 240; + this.bullet(q.x, q.y, a + Math.PI / 2, 0.8, { kind: 'bubble', r: 7, dmg: 3, life }); + this.bullet(q.x, q.y, a - Math.PI / 2, 0.8, { kind: 'bubble', r: 7, dmg: 3, life }); + } + if (q.drag) { // decelerating projectile (Sandworm big bullets) + const s = hyp(q.vx, q.vy), ns = Math.max(q.minSpeed || 0, s * q.drag); + if (s > 0) { q.vx *= ns / s; q.vy *= ns / s; } + } + if (q.kind === 'vorb' && q.age > 0 && q.age % q.emitEvery === 0) { // rotating, 4-way spiral emitter + q.spin += 0.35; + for (let i = 0; i < 4; i++) this.bullet(q.x, q.y, q.spin + i * Math.PI / 2, 1.9, { r: 4, dmg: 3 }); + } + const old = { x: q.x, y: q.y }; + q.x += q.vx; q.y += q.vy; q.age++; + if (q.age >= q.life) { q.dead = 1; continue; } + if (q.hover > 0) continue; // still forming above the Treant's star: not yet a ground projectile + if (q.stop !== undefined) { // travels a set distance, then lingers in place (Grand Slime rings / goo) + q.dist = (q.dist || 0) + hyp(q.x - old.x, q.y - old.y); + if (q.dist >= q.stop) { q.vx = 0; q.vy = 0; q.life = q.age + q.linger; delete q.stop; } + } + if (q.x < ROOM.x0 || q.x > ROOM.x1 || q.y < ROOM.y0 || q.y > ROOM.y1 || this.obstacleAt(q.x, q.y, Math.min(q.r, 3))) { + if (q.bounce > 0) { // bouncy bullets reflect off walls and obstacles + const sx = this.solidAt(q.x, old.y, Math.min(q.r, 3), false), sy = this.solidAt(old.x, q.y, Math.min(q.r, 3), false); + if (sx || !sy) q.vx = -q.vx; + if (sy || !sx) q.vy = -q.vy; + q.x = old.x + q.vx; q.y = old.y + q.vy; q.bounce--; + if (!this.solidAt(q.x, q.y, Math.min(q.r, 3), false)) continue; + } + q.dead = 1; + if (q.blast) this.blastAt(clamp(old.x, ROOM.x0, ROOM.x1), clamp(old.y, ROOM.y0, ROOM.y1), q.blast, q.dmg, 'bigblast'); + continue; + } + const c = this.crateAt(q.x, q.y, Math.min(q.r, 3)); + if (c) { this.damageCrate(c, q.dmg); q.dead = 1; if (q.blast) this.blastAt(q.x, q.y, q.blast, q.dmg, 'bigblast'); continue; } + if (p.dead === 0 && p.hp > 0 && segNear(p, old, q, p.r + q.r * 0.8)) { + if (q.blast) { q.dead = 1; this.blastAt(q.x, q.y, q.blast, q.dmg, 'bigblast'); continue; } // explodes on the Knight + if (this.hurt(q.dmg, 'bullet')) { q.dead = 1; if (q.poison) this.poisonPlayer(); } + } + } + if (this.bullets.length) this.bullets = this.bullets.filter(q => !q.dead); + } + blastAt(x, y, r, dmg, src) { // circular blast: the radius drawn around the projectile in flight is exactly r + const p = this.player; + this.fx.push({ k: 'boom', x, y, r, t: this.t }); this.shakeIt(r > 40 ? 4 : 2); + if (p.dead === 0 && p.hp > 0 && hyp(p.x - x, p.y - y) < r + p.r) this.hurt(dmg, src); + for (const c of this.crates) if (c.hp > 0 && rectHit(x, y, r, c)) this.breakCrate(c); + } + quake(x, y) { this.quakes.push({ x, y, r0: 16, r1: M.QUAKE_R, age: 0, total: 15, rc: 16, dmg: 4, hit: 0 }); this.shakeIt(4); } + updateHazards() { + const p = this.player, b = this.boss, alive = p.dead === 0 && p.hp > 0; + for (const m of this.meteors) { + if (--m.fall <= 0) { + m.dead = 1; + this.fx.push({ k: 'boom', x: m.x, y: m.y, r: m.r, t: this.t }); + this.shakeIt(2); + if (alive && hyp(p.x - m.x, p.y - m.y) < m.r + p.r) this.hurt(m.dmg, 'meteor'); + for (const c of this.crates) if (c.hp > 0 && rectHit(m.x, m.y, m.r, c)) this.breakCrate(c); + } + } + if (this.meteors.length) this.meteors = this.meteors.filter(m => !m.dead); + for (const o of this.orbs) { + o.a += o.w; o.x = b.x + Math.cos(o.a) * o.rad; o.y = b.y + Math.sin(o.a) * o.rad; + if (--o.life <= 0) o.dead = 1; + else if (alive && hyp(p.x - o.x, p.y - o.y) < p.r + o.r) this.hurt(o.dmg, 'orb'); + } + if (this.orbs.length) this.orbs = this.orbs.filter(o => !o.dead); + for (const c of this.carriers) { + c.x += c.vx; c.y += c.vy; + // doc: "fires a projectile which leaves a line of turrets" - the shuriken itself hits like a projectile + // (11-02 audit: it used to pass through the Knight and drop a turret on him, a 1-tick-warning contact hit) + if (alive && hyp(p.x - c.x, p.y - c.y) < p.r + M.CARRIER_R && this.hurt(2, 'carrier')) { c.dead = 1; continue; } + if (--c.drop <= 0 && c.n < 6) { this.turrets.push({ x: c.x, y: c.y, a: c.a, fire: 26, life: 240, r: 8 }); c.n++; c.drop = 14; } + if (c.n >= 6 || this.solidAt(c.x, c.y, 6, false)) c.dead = 1; + } + if (this.carriers.length) this.carriers = this.carriers.filter(c => !c.dead); + for (const t of this.turrets) { + if (--t.life <= 0) { t.dead = 1; continue; } + if (--t.fire <= 0) { + t.fire = 26; + this.bullet(t.x, t.y, t.a + Math.PI / 2, 2.4, { r: 4 }); + this.bullet(t.x, t.y, t.a - Math.PI / 2, 2.4, { r: 4 }); + } + if (alive && hyp(p.x - t.x, p.y - t.y) < p.r + t.r) this.hurt(2, 'turret'); + } + if (this.turrets.length) this.turrets = this.turrets.filter(t => !t.dead); + for (const ball of this.balls) { + ball.x += ball.vx; ball.y += ball.vy; ball.th += 0.4; + if (--ball.emit <= 0) { ball.emit = 10; this.ring(ball.x, ball.y, 6, ball.th, 2.2, { r: 4 }); } + for (const c of this.crates) if (c.hp > 0 && rectHit(ball.x, ball.y, ball.r, c)) this.breakCrate(c); + const hitP = alive && hyp(p.x - ball.x, p.y - ball.y) < p.r + ball.r; + if (hitP || --ball.life <= 0 || this.solidAt(ball.x, ball.y, ball.r * 0.6, false)) { + ball.dead = 1; + this.ring(ball.x, ball.y, 14, ball.th, 2.4, { r: 5 }); + this.fx.push({ k: 'boom', x: ball.x, y: ball.y, r: M.BLAST_R, t: this.t }); + this.shakeIt(3); + if (alive && hyp(p.x - ball.x, p.y - ball.y) < M.BLAST_R + p.r) this.hurt(4, 'laser_ball'); + for (const c of this.crates) if (c.hp > 0 && rectHit(ball.x, ball.y, M.BLAST_R, c)) this.breakCrate(c); + } + } + if (this.balls.length) this.balls = this.balls.filter(x => !x.dead); + for (const L of this.lines) { + if (--L.c > 0) continue; + L.c = L.every; L.k++; + const dist = L.start + L.k * L.gap, x = L.x + Math.cos(L.a) * dist, y = L.y + Math.sin(L.a) * dist; + if (L.k > L.n || this.solidAt(x, y, 4, false)) { L.dead = 1; continue; } + this.nodes.push({ x, y, r: M.NODE_R, life: 14, dmg: L.dmg }); + for (const c of this.crates) if (c.hp > 0 && rectHit(x, y, M.NODE_R, c)) this.breakCrate(c); + } + if (this.lines.length) this.lines = this.lines.filter(L => !L.dead); + for (const n of this.nodes) { + if (--n.life <= 0) { n.dead = 1; continue; } + if (alive && n.life > 2 && hyp(p.x - n.x, p.y - n.y) < p.r + n.r) this.hurt(n.dmg, 'shockwave'); + } + if (this.nodes.length) this.nodes = this.nodes.filter(n => !n.dead); + for (const pool of this.pools) { + if (--pool.life <= 0) { pool.dead = 1; continue; } + if (pool.form > 0) { pool.form--; continue; } // still forming (drawn as a dashed ring): harmless + // green and purple pools both poison (doc: purple pools "slow down the player and deal constant damage"; the + // Poison Buff counters them) + if (alive && hyp(p.x - pool.x, p.y - pool.y) < pool.r) this.poisonPlayer(); + } + if (this.pools.length) this.pools = this.pools.filter(x => !x.dead); + this.updateExpansion(p, b, alive); + } + updateExpansion(p, b, alive) { + // delayed bursts (dead slimes: doc "after 1 second, 8 projectiles in all directions, 2 damage") + for (const e of this.booms) { + if (--e.t > 0) continue; + e.dead = 1; + if (e.kind === 'burst8') this.ring(e.x, e.y, 8, this.rand() * TAU, 2.2, { r: 4, dmg: 2 }); + } + if (this.booms.length) this.booms = this.booms.filter(e => !e.dead); + // Sandworm stars: fire long bullets in a cross (diagonal when enraged), destroyable by melee + for (const st of this.stars) { + if (--st.life <= 0) { st.dead = 1; continue; } + if (--st.fire <= 0 && st.shots > 0) { + st.fire = st.every; st.shots--; st.k = (st.k || 0) + 1; + this.bullet(st.x, st.y, st.a0 + (st.k % 4) * Math.PI / 2, 2.6, { kind: 'long', r: 4, dmg: 3 }); + } + if (st.shots <= 0 && st.fire <= 0) st.dead = 1; + } + if (this.stars.length) this.stars = this.stars.filter(s => !s.dead); + // burrow / surface shockwave rings (doc: 4 damage); the ring grows to M.QUAKE_R and hits once + for (const q of this.quakes) { + q.age++; + q.rc = q.r0 + (q.r1 - q.r0) * Math.min(1, q.age / q.total); + // The growing disc deals damage inside the dashed ring that marks its final radius. + if (!q.hit && alive && q.age <= q.total && hyp(p.x - q.x, p.y - q.y) < q.rc + p.r && q.age > 2) { q.hit = 1; this.hurt(q.dmg, 'quake'); } + if (q.age >= q.total + 6) q.dead = 1; + } + if (this.quakes.length) this.quakes = this.quakes.filter(q => !q.dead); + // minions: slimes walk at the Knight and hurt on contact; tentacles stand still and fire rings + for (const m of this.minions) { + if (m.emerge > 0) { m.emerge--; continue; } + if (m.kind === 'slime') { + const a = Math.atan2(p.y - m.y, p.x - m.x), s = M.SLIME_SPEED * this.moveMul; + this.moveBody(m, Math.cos(a) * s, Math.sin(a) * s, false); + if (m.cd > 0) m.cd--; + else if (alive && hyp(p.x - m.x, p.y - m.y) < p.r + m.r) { m.cd = 30; this.hurt(2, 'slime'); } + } else if (--m.fire <= 0) { + m.fire = Math.round(M.TENTACLE_EVERY * this.gapMul); + // doc: round bullets in all directions, 3 dmg; tactics: "their bullets are quite easily avoidable" -> slow + this.ring(m.x, m.y, 8, this.rand() * TAU, 1.5, { r: 4, dmg: 3 }); + } + } + if (this.minions.some(m => m.dead)) this.minions = this.minions.filter(m => !m.dead); + } + updatePickups() { + const p = this.player; + for (const q of this.pickups) { + q.age++; + if (q.age < 24) { q.x += q.vx; q.y += q.vy; q.vx *= 0.9; q.vy *= 0.9; } + else if (p.dead === 0 && (hyp(p.x - q.x, p.y - q.y) < 90 || q.age > 150)) { + const a = Math.atan2(p.y - q.y, p.x - q.x); q.x += Math.cos(a) * 5; q.y += Math.sin(a) * 5; + } + q.x = clamp(q.x, ROOM.x0 + 6, ROOM.x1 - 6); q.y = clamp(q.y, ROOM.y0 + 6, ROOM.y1 - 6); + if (p.dead === 0 && hyp(p.x - q.x, p.y - q.y) < p.r + 7) { + q.dead = 1; p.energy = Math.min(p.maxEnergy, p.energy + q.v); this.ev('energy'); + } + } + if (this.pickups.length) this.pickups = this.pickups.filter(q => !q.dead); + } + } + + // walkable tiles for a boss body (walls/obstacles only: crates are rammed through); static per layout, so cached + const NAV8 = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]], NAV = {}; + function navGrid(g, b) { + const key = g.kind + ':' + b.r; + if (NAV[key]) return NAV[key]; + const cols = (ROOM.x1 - ROOM.x0) / TILE, rows = (ROOM.y1 - ROOM.y0) / TILE, open = new Uint8Array(cols * rows), pt = []; + for (let i = 0; i < cols * rows; i++) { + const x = ROOM.x0 + TILE / 2 + (i % cols) * TILE, y = ROOM.y0 + TILE / 2 + Math.floor(i / cols) * TILE; + pt.push({ x, y }); open[i] = g.solidAt(x, y, b.r, false) ? 0 : 1; + } + return (NAV[key] = { cols, rows, open, pt, fields: new Map() }); + } + // BFS distance field to the standable tiles whose padded line (FIRE_PAD + 6, a margin over the movement trigger) reaches + // the centre of the Knight's tile. A pure function of (layout, body radius, Knight tile): the cache can never make a + // replay depend on which states were visited before. + function navField(g, F, goal) { + let dist = F.fields.get(goal); + if (dist) return dist; + const cols = F.cols, n = F.open.length, queue = [], gp = F.pt[goal]; + dist = new Int16Array(n).fill(-1); + for (let k = 0; k < n; k++) if (F.open[k] && g.clearLine(F.pt[k], gp, M.FIRE_PAD + 6)) { dist[k] = 0; queue.push(k); } + for (let q = 0; q < queue.length; q++) { + const k = queue[q], x = k % cols, y = (k - x) / cols; + for (const [dx, dy] of NAV8) { + const X = x + dx, Y = y + dy, m = Y * cols + X; + if (X < 0 || Y < 0 || X >= cols || Y >= F.rows || !F.open[m] || dist[m] >= 0) continue; + if (dx && dy && (!F.open[y * cols + X] || !F.open[Y * cols + x])) continue; + dist[m] = dist[k] + 1; queue.push(m); + } + } + F.fields.set(goal, dist); + return dist; + } + + // ---------------- boss attack scripts: fn(b, t, vars) -> done ---------------- + const ATTACKS = M.attacks = { + goblin_priest: { + meteor(b, t, v) { // doc: 3 meteors around the target, 4 when enraged + const n = b.enraged ? 4 : 3, p = this.player; + if (t >= 10 && (t - 10) % 20 === 0 && (v.n | 0) < n) { + v.n = (v.n | 0) + 1; + const x = clamp(p.x + (this.rand() * 2 - 1) * 32, ROOM.x0 + 20, ROOM.x1 - 20), y = clamp(p.y + (this.rand() * 2 - 1) * 32, ROOM.y0 + 20, ROOM.y1 - 20); + this.meteors.push({ x, y, r: 36, fall: 54, total: 54, dmg: 4 }); + this.ev('meteor'); + } + return t >= 10 + 20 * n + 10; + }, + orbs(b, t) { // doc: 2 orbs circling, 4 damage, stackable + if (t === 20) { const a = this.rand() * TAU; for (let i = 0; i < 2; i++) this.orbs.push({ a: a + i * Math.PI, rad: 54, w: 0.07 * this.spd, life: 300, r: 9, dmg: 4, x: b.x, y: b.y }); } + return t >= 40; + }, + turrets(b, t) { // doc: projectile leaving a line of turrets firing perpendicular + if (t === 24) { const a = this.aimAt(b.x, b.y), s = 3.2 * this.spd; this.carriers.push({ x: b.x, y: b.y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, a, drop: 10, n: 0 }); } + return t >= 40; + }, + stars(b, t) { // doc: one wave of 6 stars, each releasing 3 smaller bullets + if (t === 20) this.ring(b.x, b.y, 6, this.aimAt(b.x, b.y), 2.2, { kind: 'star', r: 7, dmg: 3, split: 40 }); + return t >= 40; + } + }, + christmas_treant: { + hold(b, t, v) { // doc: holds a giant laser ball spewing bullets in all directions + if (t >= 20 && t < 170 && (t - 20) % 8 === 0) { + v.th = (v.th || this.rand() * TAU) + 0.33; + for (let i = 0; i < 3; i++) this.bullet(b.x, b.y - 48, v.th + i * TAU / 3, 2.4, { r: 4 }); + } + return t >= 190; + }, + throw(b, t) { // doc: fires the ball at the player, emitting bullets, explodes on impact + if (t === 30) { + const a = this.aimAt(b.x, b.y - 48), s = 2.0 * this.spd; // leaves from the held position (drawn at y-48) + this.balls.push({ x: b.x, y: b.y - 48, vx: Math.cos(a) * s, vy: Math.sin(a) * s, r: 16, life: 240, emit: 10, th: 0 }); + this.ev('laser_ball'); + } + return t >= 50; + }, + waves(b, t) { // doc: lines of shockwaves in three directions + if (t === 20 || t === 50) { const a = this.aimAt(b.x, b.y); for (const d of [-35, 0, 35]) this.line(b.x, b.y + 10, a + d * DEG, 9, 6, b.r); this.ev('shockwave'); } + return t >= 90; + }, + transform(b, t) { // doc: upon starting the enraged phase, shockwaves in 7 lines + if (t === 10) { const a = this.aimAt(b.x, b.y); for (let i = 0; i < 7; i++) this.line(b.x, b.y + 10, a + i * TAU / 7, 12, 5, b.r); this.ev('shockwave'); } + return t >= 40; + }, + charge(b, t, v) { // doc: charges and rams, through crates, no damage taken while charging + const p = this.player; + // The warning band tracks the player and locks for M.RAM_LOCK ticks before the dash. + if (t === 0) { v.n = 0; v.ph = 'aim'; v.c = 36; v.a = this.aimAt(b.x, b.y); } + if (v.ph === 'aim') { + v.lock = v.c <= M.RAM_LOCK; + if (!v.lock) v.a = this.aimAt(b.x, b.y); + if (--v.c <= 0) { v.ph = 'dash'; v.c = M.RAM_TICKS; v.lock = false; b.inv = true; this.ev('charge'); } + } else if (v.ph === 'dash') { + // the dash only ever moves along the locked line, so the swept ram area stays inside the drawn band: + // a step that would enter a wall/obstacle ends the dash in place (11-02: the old axis-by-axis move let + // a 45-degree dash slide along the wall, outside the telegraph). Crates are rammed through (doc). + const s = 9 * this.moveMul, nx = b.x + Math.cos(v.a) * s, ny = b.y + Math.sin(v.a) * s; + const crash = this.solidAt(nx, ny, b.r, false); + if (!crash) { + b.vx = nx - b.x; b.vy = ny - b.y; b.x = nx; b.y = ny; + for (const c of this.crates) if (c.hp > 0 && rectHit(b.x, b.y, b.r, c)) this.breakCrate(c); + } + // doc: ram area ~ the (larger) charging sprite -> hurt capsule + RAM_PAD (same band drawn as the telegraph) + if (p.dead === 0 && this.capDist(p.x, p.y) < BOSS[b.kind].hurt[2] + M.RAM_PAD + p.r) this.hurt(4, 'charge'); + if (--v.c <= 0 || crash) { v.ph = 'rest'; v.c = 20; b.inv = false; this.shakeIt(3); } + } else if (--v.c <= 0) { + v.n++; + if (v.n >= 3) return true; + v.ph = 'aim'; v.c = 30; + } + return false; + }, + homing(b, t) { // doc: 5 homing bullets from the star, moving after a short delay + if (t === 20) for (let i = 0; i < 5; i++) this.bullets.push({ x: b.x + (i - 2) * 16, y: b.y - 54 + Math.abs(i - 2) * 6, vx: 0, vy: 0, r: 6, dmg: 3, kind: 'homing', cut: true, age: 0, life: 230, hover: 40 }); + return t >= 40; + }, + cross(b, t, v) { // doc: big cross-shaped bullets in every direction + if (t === 20) { v.a = this.rand() * TAU; this.ring(b.x, b.y, 12, v.a, 2.0, { kind: 'cross', r: 9, dmg: 3 }); } + if (t === 45) this.ring(b.x, b.y, 12, v.a + 15 * DEG, 2.0, { kind: 'cross', r: 9, dmg: 3 }); + return t >= 60; + }, + line(b, t) { // doc: a line of shockwaves (like King Snow Ape) + if (t === 20) { this.line(b.x, b.y + 10, this.aimAt(b.x, b.y), 14, 4, b.r); this.ev('shockwave'); } + return t >= 50; + } + }, + devils_snare: { + bubbles(b, t) { // doc: 18 slow bubbles, vanish after 4 s (travel further when enraged) + if (t === 20) this.ring(b.x, b.y, 18, this.rand() * TAU, 1.0, { kind: 'bubble', r: 8, dmg: 3, life: b.enraged ? 360 : 240 }); + return t >= 40; + }, + rotate(b, t, v) { // doc: bullets from 4 points in 4 directions, rotating, slower than the player + if (t === 0) { v.a0 = this.rand() * TAU; v.dir = this.rand() < 0.5 ? 1 : -1; } + if (t >= 10 && t < 190 && (t - 10) % 6 === 0) { + for (let i = 0; i < 4; i++) { + const a = v.a0 + v.dir * 0.025 * t + i * Math.PI / 2; + // doc: these bullets are slower than the player -> capped at 0.9 x Knight speed at every difficulty + this.bullet(b.x + Math.cos(a) * 26, b.y + Math.sin(a) * 26, a, 2.0, { r: 5, cap: 0.9 * K.speed }); + } + } + if (b.enraged && t >= 10 && t < 190 && (t - 10) % 60 === 30) this.beamVolley(b, this.rand() * TAU); // doc: poison during rotation + return t >= 200; + }, + beams(b, t, v) { // doc: beam-like green bullets all around, cause poison + if (t === 20) { v.a = this.rand() * TAU; this.beamVolley(b, v.a); } + if (t === 40) this.beamVolley(b, v.a + 15 * DEG); + return t >= 55; + }, + pool(b, t) { // doc: poison pool on itself, no self-damage + if (t === 15) { this.pools = this.pools.filter(q => q.x !== b.x || q.y !== b.y); this.pools.push({ x: b.x, y: b.y, r: 64, life: 540 }); } + return t >= 30; + }, + transform(b, t) { // doc: flower unfolds, 4 tentacles spawn + if (t === 20) b.tentacles = [0, 1, 2, 3].map(i => ({ x: b.x + Math.cos(Math.PI / 4 + i * Math.PI / 2) * 52, y: b.y + Math.sin(Math.PI / 4 + i * Math.PI / 2) * 52, r: 14 })); + return t >= 45; + }, + corner(b, t) { // doc: 4 fast bullets toward the corners leaving spreading bubble trails + if (t === 20) { + const corners = [[ROOM.x0, ROOM.y0], [ROOM.x1, ROOM.y0], [ROOM.x0, ROOM.y1], [ROOM.x1, ROOM.y1]]; + for (const [cx, cy] of corners) { + const src = b.tentacles.length ? b.tentacles.reduce((m, q) => (hyp(q.x - cx, q.y - cy) < hyp(m.x - cx, m.y - cy) ? q : m)) : b; + this.bullet(src.x, src.y, Math.atan2(cy - src.y, cx - src.x), 6, { kind: 'rail', r: 6, dmg: 3, trail: 5 }); + } + } + return t >= 40; + }, + pull(b, t, v) { // doc: wave that pulls the player toward itself; walls hamper it; no damage + const p = this.player; + v.on = t >= 10 && t < 100; + if (v.on && p.dead === 0 && this.sight(p, b)) { + const a = Math.atan2(b.y - p.y, b.x - p.x), s = 1.4 * this.moveMul; // < Knight speed at every tier + if (hyp(b.x - p.x, b.y - p.y) > b.r + p.r + 4) this.moveBody(p, Math.cos(a) * s, Math.sin(a) * s, false); + } + return t >= 110; + } + }, + grand_slime: { + // doc: "Slams the ground, releasing clusters of red bullets in random directions, at random speeds; 3 damage" + // (5.5.0+ version; diamond bullets 5 damage when enraged); two slams (pre-5.5.0 text: "slams the ground twice") + slam(b, t, v) { + if (t === 24 || t === 54) { + const n = b.enraged ? 14 : 12; + for (let i = 0; i < n; i++) this.bullet(b.x, b.y + 6, this.rand() * TAU, 1.4 + this.rand() * 1.8, + b.enraged ? { kind: 'diamond', r: 6, dmg: 5 } : { kind: 'slam', r: 5, dmg: 3 }); + this.quakeFx(b.x, b.y + 14); this.ev('slam'); + } + return t >= 74; + }, + // doc: "4 rings of bullets in quick succession; they travel 10 tiles then linger, gradually forming a flower; 2 dmg". + // Approx: each bullet stops at 10 tiles x a 5-petal profile, so the lingering bullets draw a flower whose gaps + // between the petals stay passable (a uniform circle would be a closed cage). + rings(b, t, v) { + if (t === 0) v.a = this.rand() * TAU; + if (t >= 16 && t < 16 + 4 * 10 && (t - 16) % 10 === 0) { + const k = (t - 16) / 10; + for (let i = 0; i < 12; i++) { + const a = v.a + i * TAU / 12 + k * TAU / 48, rel = a - v.a; + const stop = 10 * TILE * (0.45 + 0.55 * Math.abs(Math.cos(2.5 * rel))) - k * 14; + this.bullet(b.x, b.y, a, 2.0, { kind: 'petal', r: 5, dmg: 2, stop, linger: M.PETAL_LINGER, life: 600 }); + } + } + return t >= 70; + }, + // doc: "Spawns a Slime on its position" (Slime: 12 HP, 2 contact damage; endless while the boss lives) + spawn(b, t) { + if (t === 20 && this.minions.filter(m => m.kind === 'slime').length < M.SLIME_MAX) { + this.minions.push({ kind: 'slime', x: b.x, y: b.y + 20, r: 9, hp: 12, cd: 0, emerge: 24, flash: -99 }); + this.ev('summon'); + } + return t >= 40; + }, + // doc: "Slams the ground, leaving a green Poison pool and multiple bullets that linger; 3 damage each" + goo(b, t) { + if (t === 28) { + this.pools.push({ x: b.x, y: b.y + 8, r: 58, life: 420, form: 0 }); + this.ring(b.x, b.y + 8, 10, this.rand() * TAU, 1.6, { kind: 'slam', r: 5, dmg: 3, stop: 60, linger: 200, life: 600 }); + this.quakeFx(b.x, b.y + 14); this.ev('slam'); + } + return t >= 50; + }, + // doc: "The boss will also explode once right after being enraged" (the swell is the telegraph) + transform(b, t) { + if (t === 0) { b.boom = M.SLIME_SWELL; b.charge = 0; this.ev('swell'); } + return t >= M.SLIME_SWELL + 10; + } + }, + varkolyn_leader: { + // doc: "Spawns 4 purple poison circles in a line, aimed in the direction of the target" (pools form first) + pools(b, t, v) { + if (t === 0) v.a = this.aimAt(b.x, b.y); + if (t >= 20 && t < 20 + 4 * 8 && (t - 20) % 8 === 0) { + const k = (t - 20) / 8, d = 44 + k * 52, x = clamp(b.x + Math.cos(v.a) * d, ROOM.x0 + 20, ROOM.x1 - 20), y = clamp(b.y + Math.sin(v.a) * d, ROOM.y0 + 20, ROOM.y1 - 20); + this.pools.push({ x, y, r: 36, life: 480, purple: 1, form: 24 }); + } + return t >= 60; + }, + // doc: "Spawn 4 Tentacles randomly around the room"; cannot spawn more if there is already a good amount + tentacles(b, t) { + if (t === 24) { + const have = this.minions.filter(m => m.kind === 'tentacle').length; + for (let i = 0; i < Math.min(4, M.TENTACLE_MAX - have); i++) { + let x = 0, y = 0; + for (let k = 0; k < 8; k++) { + x = ROOM.x0 + 60 + this.rand() * (ROOM.x1 - ROOM.x0 - 120); y = ROOM.y0 + 60 + this.rand() * (ROOM.y1 - ROOM.y0 - 120); + if (hyp(x - this.player.x, y - this.player.y) > 120 && hyp(x - b.x, y - b.y) > 60) break; + } + this.minions.push({ kind: 'tentacle', x, y, r: 14, hp: 40, fire: 50 + Math.floor(this.rand() * 40), emerge: 40, flash: -99 }); + } + this.ev('summon'); + } + return t >= 50; + }, + // doc: "Fires small bullets in every direction" + ring(b, t, v) { + if (t === 16 || t === 34) { v.a = (v.a === undefined ? this.rand() * TAU : v.a + TAU / 32); this.ring(b.x, b.y - M.VARK_EYE, 16, v.a, 2.3, { r: 4, dmg: 3 }); } + return t >= 50; + }, + // doc: "Emits a sharp chime, then fires a sweeping laser (6 damage)"; enraged: slightly shorter charge, faster + // rotation; the boss does nothing else while firing. Telegraph = the start line of the sweep plus the swept arc. + laser(b, t, v) { + const charge = b.enraged ? M.LASER_CHARGE - 12 : M.LASER_CHARGE, sweep = b.enraged ? M.LASER_SWEEP - 20 : M.LASER_SWEEP; + if (t === 0) { v.dir = this.rand() < 0.5 ? 1 : -1; v.a0 = this.aimAt(b.x, b.y - M.VARK_EYE) - v.dir * M.LASER_ARC / 2; v.a = v.a0; v.on = 0; this.ev('chime'); } + if (t === charge) { v.on = 1; this.ev('laser'); } + if (v.on) { + v.a = v.a0 + v.dir * M.LASER_ARC * Math.min(1, (t - charge) / sweep); + const p = this.player, oy = b.y - M.VARK_EYE, ex = b.x + Math.cos(v.a) * 1000, ey = oy + Math.sin(v.a) * 1000; + if (p.dead === 0 && N.segmentDistance(p, { x: b.x, y: oy }, { x: ex, y: ey }) < M.LASER_W + p.r) this.hurt(6, 'laser'); + } + return t >= charge + sweep; + }, + // doc: "Fires a large bullet that fires spirals of smaller bullets around itself until it is destroyed"; it + // rotates but keeps a 4-way pattern + orb(b, t) { + if (t === 24) { + const a = this.aimAt(b.x, b.y - M.VARK_EYE), s = 1.3 * this.spd; + this.bullets.push({ x: b.x, y: b.y - M.VARK_EYE, vx: Math.cos(a) * s, vy: Math.sin(a) * s, r: 13, dmg: 4, kind: 'vorb', cut: true, age: 0, life: 480, spin: 0, emitEvery: 10 }); + } + return t >= 44; + } + }, + volcanic_sandworm: { + // doc: "Tilts its body backwards, then fires a giant Explosive (5 damage, explodes on impact, massive area of + // effect)"; enraged: 3 in one volley. A straight shell that explodes on the first wall / obstacle / crate / Knight + // it touches; its blast radius M.SHELL_BLAST is drawn around it in flight. + explosive(b, t) { + if (t === 24) { + const n = b.enraged ? 3 : 1, a = this.aimAt(b.x, b.y - M.WORM_MOUTH); + for (let i = 0; i < n; i++) this.bullet(b.x, b.y - M.WORM_MOUTH, a + (n === 1 ? 0 : (i - 1) * 22 * DEG), M.SHELL_SPEED, + { kind: 'shell', r: 11, dmg: 5, blast: M.SHELL_BLAST, life: 400, cut: false }); + this.ev('explosive'); + } + return t >= 44; + }, + // doc: "fires a wide spread of 8 Big bullets that make a small red radial blast upon impact, 4 damage; velocity + // decreases over time"; enraged: 12 + spread(b, t) { + if (t === 24) { + const n = b.enraged ? 12 : 8, a = this.aimAt(b.x, b.y - M.WORM_MOUTH), arc = 100 * DEG; + for (let i = 0; i < n; i++) this.bullet(b.x, b.y - M.WORM_MOUTH, a - arc / 2 + arc * i / (n - 1), 4.2, + { kind: 'big', r: 8, dmg: 4, drag: 0.982, minSpeed: 0.9, blast: 22, life: 260, cut: true }); + this.ev('spread'); + } + return t >= 44; + }, + // doc: digs underground (intangible, cannot be targeted, does not attack), leaves a temporary star that fires 13 + // long bullets in a cross; it may surface at the player and then re-burrow; resurfacing makes a star that fires 12 + // bouncy bullets in all directions; burrowing/surfacing creates a 4-damage shockwave; enraged: diagonal stars, + // faster digs, 12 lingering bubbles on every resurface + dig(b, t, v) { return this.wormDig(b, t, v, false); }, + dive(b, t, v) { return this.wormDig(b, t, v, true); } + } + }; + Game.prototype.quakeFx = function (x, y) { this.fx.push({ k: 'boom', x, y, r: 28, t: this.t }); this.shakeIt(3); }; + // Sandworm dig: sink (wind-up, the burrow shockwave radius is drawn) -> travel underground (moving dirt mound, + // intangible) -> rise (stops, the surface shockwave radius is drawn) -> surface (shockwave, bouncy star) -> rest. + // Enraged "dive": several hops with a short vulnerable peek between them (doc: "momentarily vulnerable during a + // continuous dive. It surfaces but quickly burrows"). + Game.prototype.wormDig = function (b, t, v, dive) { + const fast = b.enraged ? 0.7 : 1; + if (t === 0) { v.ph = 'sink'; v.c = Math.round(M.WORM_SINK * fast); v.hops = dive ? 3 : 1; this.ev('burrow'); } + if (v.ph === 'sink' || v.ph === 'peek') { + if (--v.c <= 0) { + b.under = true; this.quake(b.x, b.y); this.stars.push(this.wormStar(b.x, b.y, 'long')); + v.ph = 'travel'; v.c = Math.round((dive ? 50 : 80) * fast); this.wormTarget(b, v); + } + } else if (v.ph === 'travel') { + const a = Math.atan2(v.ty - b.y, v.tx - b.x), s = M.WORM_SPEED * this.moveMul, d = hyp(v.tx - b.x, v.ty - b.y); + if (d > s) { b.x += Math.cos(a) * s; b.y += Math.sin(a) * s; b.vx = Math.cos(a) * s; b.vy = Math.sin(a) * s; } + else { b.x = v.tx; b.y = v.ty; } + // Travel time ends the dig once the worm can surface clear of the pillar. + if ((--v.c <= 0 && !this.solidAt(b.x, b.y, b.r, false)) || d <= s) { v.ph = 'rise'; v.c = M.WORM_RISE; this.ev('rise'); } + } else if (v.ph === 'rise') { + if (--v.c <= 0) { + b.under = false; this.quake(b.x, b.y); this.ev('surface'); + this.stars.push(this.wormStar(b.x, b.y, 'bouncy')); + if (b.enraged) this.ring(b.x, b.y, 12, this.rand() * TAU, 0.8, { kind: 'bubble', r: 8, dmg: 3, life: 300 }); + v.hops--; v.ph = v.hops > 0 ? 'peek' : 'rest'; v.c = Math.round((v.hops > 0 ? 34 : 30) * fast); + } + } else if (--v.c <= 0) return true; + return false; + }; + // Select a reachable surfacing point near the player. Fall back to the midpoint or the current position. + Game.prototype.wormTarget = function (b, v) { + const p = this.player, ok = (x, y) => !this.solidAt(x, y, b.r, false) && hyp(x - b.x, y - b.y) >= 60; + let x = b.x, y = b.y, found = false; + for (let k = 0; k < 6 && !found; k++) { + const a = this.rand() * TAU, d = 90 + this.rand() * 60; + x = clamp(p.x + Math.cos(a) * d, ROOM.x0 + 40, ROOM.x1 - 40); y = clamp(p.y + Math.sin(a) * d, ROOM.y0 + 50, ROOM.y1 - 30); + found = ok(x, y); + } + if (!found) { x = clamp(b.x + (p.x - b.x) * 0.5, ROOM.x0 + 40, ROOM.x1 - 40); y = clamp(b.y + (p.y - b.y) * 0.5, ROOM.y0 + 50, ROOM.y1 - 30); found = ok(x, y); } + if (!found) { x = b.x; y = b.y; } + v.tx = x; v.ty = y; + }; + Game.prototype.wormStar = function (x, y, kind) { + const b = this.boss; + if (kind === 'long') return { x, y, r: 10, a0: b.enraged ? Math.PI / 4 : 0, every: 6, fire: 14, shots: 13, life: 120, kind, k: 0 }; + // resurface star: 12 bouncy bullets in all directions, once (doc: 4 damage, cannot be reflected) + this.ring(x, y, 12, this.rand() * TAU, 2.4, { kind: 'bouncy', r: 5, dmg: 4, bounce: 2, life: 300, cut: true }); + return { x, y, r: 10, a0: 0, every: 99, fire: 99, shots: 0, life: 24, kind }; + }; + // xorshift32 started from a small seed (1, 2, 3 ...) yields tiny first outputs (every early shot + // would crit, the first attack would always be pool[0]); scramble the seed with a murmur3 finaliser. + Game.mixSeed = function (seed) { + let x = ((seed >>> 0) ^ 0x9e3779b9) >>> 0; + x = Math.imul(x ^ (x >>> 16), 0x85ebca6b) >>> 0; + x = Math.imul(x ^ (x >>> 13), 0xc2b2ae35) >>> 0; + x = (x ^ (x >>> 16)) >>> 0; + return x || 0x6d2b79f5; + }; + Game.prototype.beamVolley = function (b, a0) { this.ring(b.x, b.y, 12, a0, 4.5, { kind: 'beam', r: 5, dmg: 2, poison: true }); }; + + M.Game = Game; + M.RAM_PAD = 8; + // hazard radii shared by the hit test and the drawn telegraph (draw.js reads these, never its own numbers) + M.NODE_R = 18; // shockwave node + M.BLAST_R = 40; // laser-ball burst + M.CARRIER_R = 8; // turret-line shuriken (drawn 11 px star; hit like a bullet at ~0.8 of the drawn size) + M.LINE_LEAD = 12; // ticks a shockwave lane is drawn before its first node + M.FIRE_PAD = 10; // margin a line of fire must keep from trees/walls (shot radius + rifle spread at ~100 px) + M.RAM_LOCK = 20; // ticks the charge direction is fixed (and drawn locked) before the dash + M.RAM_TICKS = 45; // dash length in ticks + // 11-02 expansion (approximations unless marked doc) + M.TILE_FX = 120; // doc: Slow / Boost tile effect lasts 2 s + M.SLIME_HITS = 15; // doc: Grand Slime explodes after 15 hits while enraged + M.SLIME_SWELL = 50; // swell before the explosion (drawn as a growing ring of the blast radius) + M.SLIME_BLAST = 92; // explosion radius + M.SLIME_MAX = 4; // summoned slimes alive at once + M.SLIME_SPEED = 1.1; // slime walk speed (px/tick) + M.PETAL_LINGER = 120; // how long the flower bullets linger + M.VARK_SHIELD = 180; // doc "several seconds" of invulnerability in its own purple pool + M.VARK_VULN = 120; // doc "brief enforced vulnerability period" + M.TENTACLE_EVERY = 180; // doc "every few seconds" (approx 3 s, x tier gap); tactics: "quite easily avoidable" + M.TENTACLE_MAX = 6; // doc: no more tentacles once there is "a good amount" + M.LASER_CHARGE = 60; // doc: the chime is heard "a second before" the laser + M.LASER_SWEEP = 90; // sweep duration (enraged -20: "rotates faster") + M.LASER_ARC = 110 * DEG; + M.LASER_W = 7; // half-width of the beam + M.VARK_EYE = 44; // laser / bullets leave from the Varkolyn's head (drawn at y - 46) + M.WORM_MOUTH = 60; // Sandworm shells / big bullets leave from its mouth (drawn at y - 62) + M.SHELL_BLAST = 46; // doc "massive area of effect" explosive + M.SHELL_SPEED = 2.6; // explosive shell speed (x projectile speed via bullet()) + M.QUAKE_R = 70; // burrow / surface shockwave radius + M.WORM_SPEED = 2.2; // burrowed travel speed (x move) + M.WORM_RISE = 24; // doc: it no longer moves during resurface -> it stops and the mound shakes for this long + M.WORM_SINK = 18; // burrow wind-up at its visible position + // Distance the boss centre will still travel on the current charge line (pure: the same stepping as the + // dash; walls/obstacles stop it, crates do not). The telegraph band and the scripted controller use it, so + // the drawn band ends where the ram really ends instead of running 900 px across the room. + M.ramReach = function (g) { + const b = g.boss, v = b.vars, a = v.a, s = 9 * g.moveMul, n = v.ph === 'dash' ? v.c : M.RAM_TICKS; + let x = b.x, y = b.y, k = 0; + for (; k < n; k++) { const nx = x + Math.cos(a) * s, ny = y + Math.sin(a) * s; if (g.solidAt(nx, ny, b.r, false)) break; x = nx; y = ny; } + return k * s; + }; + // perpendicular half-width of the swept ram capsule for a charge direction a (without the Knight radius) + M.ramBand = function (kind, a) { const h = BOSS[kind].hurt; return h[2] + M.RAM_PAD + (h[1] - h[0]) / 2 * Math.abs(Math.cos(a)); }; + + // ======================= standard scripted controller ======================= + // Reads privileged state, never mutates it: lookahead runs on a JSON deep copy with its own rng copy. + const MOVES = [[0, 0], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; + const SHORT = 18; // follow-up ticks at which positions are scored (the whole look-ahead for the Forest bosses) + // Varkolyn: doc tactics "stay close to him ... dodging the laser is easier this way"; "far away ... almost certain to be hit" + const RANGE = { goblin_priest: 210, christmas_treant: 240, devils_snare: 190, grand_slime: 210, varkolyn_leader: 115, volcanic_sandworm: 200 }; + // bosses that walk at the Knight / surface beside it: extra keep-away distance and a corner penalty (new bosses only, + // so the Forest fights keep their validated controller behaviour) + const CHASERS = { grand_slime: 120, volcanic_sandworm: 90 }; + const TWO_PLY = { grand_slime: 1, varkolyn_leader: 1, volcanic_sandworm: 1 }; + const memory = new WeakMap(); + const AIM = b => ({ x: b.x, y: b.y + (BOSS[b.kind].hurt[0] + BOSS[b.kind].hurt[1]) / 2 }); // middle of the hurt capsule + // the first of middle / top / bottom of the hurt capsule with a padded line of fire from p, or null + const aimPoint = (g, p, b) => { + const h = BOSS[b.kind].hurt; + for (const dy of [(h[0] + h[1]) / 2, h[0], h[1]]) { const q = { x: b.x, y: b.y + dy }; if (g.sight(p, q) && g.clearLine(p, q, M.FIRE_PAD)) return q; } + return null; + }; + function moveKeys(m) { + const k = []; + if (m[0] > 0) k.push('D'); else if (m[0] < 0) k.push('A'); + if (m[1] > 0) k.push('S'); else if (m[1] < 0) k.push('W'); + return k; + } + M.clone = function (g) { const c = N.copy(g); Object.setPrototypeOf(c, Game.prototype); return c; }; + function simTick(sim, keys, mouse) { + const held = [...keys].sort(), pressed = held.filter(k => !sim.held.includes(k)); + sim.events = []; + sim.update(new Set(held), new Set(pressed), mouse); + sim.t++; + if (!sim.outcome && sim.t >= HZ * M.maxSeconds) sim.outcome = 'timeout'; + } + function holdIndex(n, count) { return Math.ceil(n * 6 / count) - 1; } + function evaluate(g, holds, mouse, follow, horizon, holds2) { + const sim = M.clone(g), p0 = sim.player, hp0 = p0.hp, ar0 = p0.armor, poison0 = p0.poison, dealt0 = sim.stats.damageDealt; + // Re-seed the planning copy from the tick so candidates share a stream independent of live future rolls. + if (TWO_PLY[g.kind]) sim.rng = Game.mixSeed((g.t * 2654435761 + 0x51ed27) >>> 0); + const count = HZ / 5, per = mouse.map(v => v / count); + let lost1 = 0; + for (let n = 1; n <= count && !sim.outcome; n++) simTick(sim, holds[holdIndex(n, count)], per); + // two-ply: a second packet (another move) before the follow-up + if (holds2) for (let n = 1; n <= count && !sim.outcome; n++) simTick(sim, holds2[holdIndex(n, count)], [0, 0, 0]); + const p1 = sim.player; + lost1 = (hp0 - p1.hp) * 1.6 + (ar0 - p1.armor); + for (let n = 0; n < Math.min(horizon, SHORT) && !sim.outcome; n++) simTick(sim, follow, [0, 0, 0]); + const p = sim.player, b = sim.boss; + const lost2 = (hp0 - p.hp) * 1.6 + (ar0 - p.armor) - lost1; + let score = -1000 * lost1 - 650 * Math.max(0, lost2); + if (sim.outcome === 'loss' || p.dead > 0) score -= 1e6; + if (sim.outcome === 'win' || b.state === 'dying') score += 5000; + // Poison deals two ticks of damage, blocks armor regeneration, and halves speed for four seconds. + if (p.poison > poison0 + 2) score -= TWO_PLY[g.kind] ? 4000 : 160; + score += 3 * (sim.stats.damageDealt - dealt0); + if (b.hp > 0 && b.state !== 'dying') { + const d = hyp(p.x - b.x, p.y - b.y), R = RANGE[g.kind]; + score -= 0.7 * Math.abs(d - R); + // Stay close enough to evade the sweeping laser by moving around the boss. + if (g.kind === 'varkolyn_leader' && d > 150) score -= 2.5 * (d - 150); + if (d < b.r + 70) score -= (b.r + 70 - d) * 4; + // Prefer a clear shot to any exposed part of the boss’s hurt capsule. + if (TWO_PLY[g.kind] ? aimPoint(sim, p, b) !== null : sim.sight(p, b)) score += TWO_PLY[g.kind] ? 160 : 70; + } + const margin = Math.min(p.x - ROOM.x0, ROOM.x1 - p.x, p.y - ROOM.y0, ROOM.y1 - p.y); + if (margin < 56) score -= (56 - margin) * 1.6; + for (const q of sim.bullets) { const dd = hyp(q.x - p.x, q.y - p.y); if (dd < 64) score -= (64 - dd) * 0.45 * (q.dmg || 2); } + for (const m of sim.meteors) { const dd = hyp(m.x - p.x, m.y - p.y); if (dd < m.r + 18) score -= (m.r + 18 - dd) * 6; } + for (const n of sim.nodes) { const dd = hyp(n.x - p.x, n.y - p.y); if (dd < 40) score -= (40 - dd) * 3; } + for (const pool of sim.pools) { + const dd = hyp(pool.x - p.x, pool.y - p.y); + // Keep clear of purple pools because poison reduces the speed needed to dodge the laser. + if (pool.purple) { if (dd < pool.r + 30) score -= (pool.r + 30 - dd) * 12; } + else if (dd < pool.r + 20) score -= (pool.r + 20 - dd) * 3; + } + for (const L of sim.lines) { // shockwave line still travelling: avoid its ray + const ex = L.x + Math.cos(L.a) * (L.start + L.n * L.gap), ey = L.y + Math.sin(L.a) * (L.start + L.n * L.gap); + const dd = N.segmentDistance(p, { x: L.x, y: L.y }, { x: ex, y: ey }); + if (dd < 34) score -= (34 - dd) * 4; + } + if (b.atk === 'charge' && (b.vars.ph === 'aim' || b.vars.ph === 'dash')) { + const h = BOSS[b.kind].hurt, a = b.vars.a, cy = b.y + (h[0] + h[1]) / 2; + const half = M.ramBand(b.kind, a) + p.r + 16; + const reach = M.ramReach(sim) + h[2] + M.RAM_PAD + (h[1] - h[0]) / 2; + const dd = N.segmentDistance(p, { x: b.x, y: cy }, { x: b.x + Math.cos(a) * reach, y: cy + Math.sin(a) * reach }); + if (dd < half) score -= (half - dd) * 10; + } + // 11-02 expansion hazards (these arrays stay empty in the Forest rooms, so those scores are unchanged) + for (const q of sim.bullets) if (q.blast) { // shells / big bullets: keep out of the blast around the rest of their path + const end = blastEnd(sim, q), dd = N.segmentDistance(p, q, end), de = hyp(p.x - end.x, p.y - end.y), R = q.blast + p.r + 10; + if (dd < R) score -= (R - dd) * (q.kind === 'shell' ? 4 : 1.5); + if (de < R) score -= (R - de) * (q.kind === 'shell' ? 6 : 2); + } + for (const q of sim.quakes) if (!q.hit) { const dd = hyp(q.x - p.x, q.y - p.y); if (dd < q.r1 + 20) score -= (q.r1 + 20 - dd) * 3; } + for (const m of sim.minions) { + const dd = hyp(m.x - p.x, m.y - p.y); + if (dd < m.r + 44) score -= (m.r + 44 - dd) * 3; + // Keep away from charging tentacles until their bullet rings spread out. + if (m.kind === 'tentacle' && !m.emerge && m.fire < 40 && dd < 110) score -= (110 - dd) * 4; + } + // Penalize destinations crossed by an incoming projectile within about 40 ticks. + if (TWO_PLY[g.kind]) { + for (const q of sim.bullets) { + const rx = p.x - q.x, ry = p.y - q.y, vv = q.vx * q.vx + q.vy * q.vy; + if (vv < 1e-6 || rx * rx + ry * ry > 160 * 160) continue; + const tc = Math.max(0, Math.min(40, (rx * q.vx + ry * q.vy) / vv)), cx = rx - q.vx * tc, cy = ry - q.vy * tc, miss = hyp(cx, cy), R = p.r + q.r + 6; + if (miss < R) score -= (R - miss) * (q.dmg || 2) * (1 - tc / 50) * 6; + } + } + for (const st of sim.stars) if (st.shots > 0) { // keep off the star's four firing lanes + for (let i = 0; i < 4; i++) { + const a = st.a0 + i * Math.PI / 2, dd = N.segmentDistance(p, st, { x: st.x + Math.cos(a) * 600, y: st.y + Math.sin(a) * 600 }); + if (dd < 22) score -= (22 - dd) * 3; + } + } + if (p.tileK === 'slow') score -= 40; + if (CHASERS[g.kind] && b.hp > 0) { // pursuing bosses: keep escape room - corners and walls near the boss trap the Knight + const mx = Math.min(p.x - ROOM.x0, ROOM.x1 - p.x), my = Math.min(p.y - ROOM.y0, ROOM.y1 - p.y); + score -= Math.max(0, 120 - mx) * Math.max(0, 120 - my) / 30; + // Keep away from walls during the Sandworm fight to leave space to dodge. + if (g.kind === 'volcanic_sandworm') score -= Math.max(0, 90 - Math.min(mx, my)) * 2; + const d = hyp(p.x - b.x, p.y - b.y); + if (d < CHASERS[g.kind]) score -= (CHASERS[g.kind] - d) * 3; + } + if (b.kind === 'grand_slime' && b.boom > 0) { const dd = hyp(b.x - p.x, b.y - p.y); if (dd < M.SLIME_BLAST + 34) score -= (M.SLIME_BLAST + 34 - dd) * 8; } + if (b.kind === 'volcanic_sandworm' && (b.under || b.vars.ph === 'sink' || b.vars.ph === 'peek')) { + for (const [x, y] of [[b.x, b.y], [b.vars.tx, b.vars.ty]]) { + if (x === undefined) continue; + const dd = hyp(x - p.x, y - p.y); + if (dd < M.QUAKE_R + 34) score -= (M.QUAKE_R + 34 - dd) * 5; + } + } + if (b.atk === 'laser') { + // inside the part of the arc the beam has not swept yet: run for the far end of the arc (the beam sweeps toward + // it and is outrun only close to the boss); the start edge only while the charge still leaves time to clear it + const v = b.vars, cur = v.on ? v.a : v.a0, end = v.a0 + v.dir * M.LASER_ARC, left = Math.abs(end - cur); + const R = Math.max(20, hyp(p.x - b.x, p.y - b.y + M.VARK_EYE)); + const ang = Math.atan2(p.y - (b.y - M.VARK_EYE), p.x - b.x), rel = v.dir * Math.atan2(Math.sin(ang - cur), Math.cos(ang - cur)); + const m = Math.atan2(M.LASER_W + p.r + 6, R); + if (rel > -m && rel < left + m) { + const charge = b.enraged ? M.LASER_CHARGE - 12 : M.LASER_CHARGE, spare = v.on ? 0 : Math.max(0, charge - b.at); + const toEnd = left + m - rel, toStart = rel + m, canStart = toStart * R < spare * K.speed * 0.8; + score -= 300 + 900 * (canStart ? Math.min(toEnd, toStart) : toEnd) / M.LASER_ARC + 0.8 * Math.max(0, R - 110); + } + } + // Score position at the short horizon and continue the rollout to account for persistent threats. + let lost3 = 0; + if (horizon > SHORT && !sim.outcome) { + const hpS = p.hp, arS = p.armor; + for (let n = SHORT; n < horizon && !sim.outcome; n++) simTick(sim, follow, [0, 0, 0]); + lost3 = (hpS - sim.player.hp) * 1.6 + (arS - sim.player.armor); + score -= 500 * Math.max(0, lost3); + if (sim.outcome === 'loss' || sim.player.dead > 0) score -= 1e5; + } + return { score, sim, danger: lost1 > 0 || lost2 > 0 || lost3 > 0 }; + } + // where a blast projectile (Sandworm shell / big bullet) will explode: march its own motion until it would hit a + // wall, obstacle or crate (pure; same tests as updateBullets, life-limited) + function blastEnd(g, q) { + let x = q.x, y = q.y, vx = q.vx, vy = q.vy; + const r = Math.min(q.r, 3); + for (let i = 0; i < 160 && q.age + i < q.life; i++) { + if (q.drag) { const s = hyp(vx, vy), ns = Math.max(q.minSpeed || 0, s * q.drag); if (s > 0) { vx *= ns / s; vy *= ns / s; } } + const nx = x + vx, ny = y + vy; + if (nx < ROOM.x0 || nx > ROOM.x1 || ny < ROOM.y0 || ny > ROOM.y1 || g.obstacleAt(nx, ny, r) || g.crateAt(nx, ny, r)) break; + x = nx; y = ny; + } + return { x, y }; + } + // Extend the follow-up horizon until persistent threats can resolve. + function threatHorizon(g) { + const b = g.boss, v = b.vars; + let h = 18; + if (b.atk === 'laser') { + const end = (b.enraged ? M.LASER_CHARGE - 12 : M.LASER_CHARGE) + (b.enraged ? M.LASER_SWEEP - 20 : M.LASER_SWEEP); + h = Math.max(h, end - b.at - 12); + } + for (const q of g.bullets) if (q.blast) { + const e = blastEnd(g, q), s = Math.max(0.5, hyp(q.vx, q.vy)); + h = Math.max(h, hyp(e.x - q.x, e.y - q.y) / s - 8); + } + if (b.boom > 0) h = Math.max(h, b.boom - 8); + if (b.kind === 'volcanic_sandworm' && (v.ph === 'travel' || v.ph === 'rise')) h = Math.max(h, (v.ph === 'rise' ? v.c : v.c + M.WORM_RISE) - 8); + return Math.min(140, Math.round(h)); + } + M.scripted = function (g) { + const p = g.player, b = g.boss; + let mem = memory.get(g); + if (!mem || g.t === 0) { mem = { last: 0 }; memory.set(g, mem); } + const count = HZ / 5; + // Lead the target and aim at an exposed part of the hurt capsule. Forest encounters aim at the feet. + const ap = TWO_PLY[g.kind] ? aimPoint(g, p, b) || AIM(b) : b; + let tx = ap.x, ty = ap.y; + const w = WEAPONS[SLOTS[p.slot]]; + if (b.hp > 0 && w.kind === 'gun') { + const d = hyp(b.x - p.x, b.y - p.y), lead = d / w.speed; + tx += b.vx * lead; ty += b.vy * lead; + } + const mouse = [clamp(Math.round(tx - p.aimX), -1000, 1000), clamp(Math.round(ty - p.aimY), -1000, 1000), 0]; + // weapon choice: rifle while energy lasts, pistol as the free fallback; hysteresis (back to the rifle at + // 12 energy) so single energy orbs do not cause switch thrash (11-02: the old fixed 24-energy reserve was + // never spent - the Knight's skill costs no energy) + const want = p.energy >= (p.slot === 1 ? 1 : 12) ? 1 : 0; + // the burrowed Sandworm and the shielded Varkolyn Leader cannot be damaged: hold fire instead of spending energy + let hold = b.under || b.shield > 0; + if (b.kind === 'volcanic_sandworm' && w.kind === 'gun') { + // Time shots to reach the worm after it surfaces and before it sinks again. + const v = b.vars, tt = Math.max(0, hyp(AIM(b).x - p.x, AIM(b).y - p.y) - BOSS[b.kind].hurt[2]) / w.speed; + if (v.ph === 'rise') hold = tt < v.c - 1; + else if (!hold && (v.ph === 'sink' || v.ph === 'peek')) hold = v.c < tt + 2; + } + let switchPress = 0; + if (p.dead === 0 && b.state !== 'dying' && p.slot !== want && p.lock === 0 && !(p.dual > 0 && p.energy >= 2)) switchPress = (want - p.slot + SLOTS.length) % SLOTS.length; + const skill = p.dead === 0 && b.hp > 0 && b.state !== 'dying' && !b.inv && !hold && p.dual === 0 && p.skillCd === 0 && switchPress === 0 && g.sight(p, b) && (p.slot === 0 || p.energy >= 40); + let best = null; + const cands = [], H = threatHorizon(g); + for (let i = 0; i < MOVES.length; i++) { + const mk = moveKeys(MOVES[i]); + const holds = []; + for (let j = 0; j < 6; j++) { + const k = [...mk]; + const press = (switchPress >= 1 && j === 0) || (switchPress >= 2 && j === 2); + if (press) k.push('Q'); else if (!hold) k.push('J'); + if (skill && j === 0) k.push('K'); + holds.push(k); + } + const follow = hold ? [...mk] : [...mk, 'J']; + const r = evaluate(g, holds, mouse, follow, H); + const c = { s: r.score + (i === mem.last ? 12 : 0), holds, i, danger: r.danger }; + cands.push(c); + if (!best || c.s > best.s) best = c; + } + // Use two-ply planning for expansion encounters. Forest encounters use one ply. + if (TWO_PLY[g.kind]) { + let best2 = null; + // Consider all nine first moves for the Varkolyn Leader and during its laser. Use the top four otherwise. + for (const c of [...cands].sort((a, b) => b.s - a.s).slice(0, b.atk === 'laser' || g.kind === 'varkolyn_leader' ? 9 : 4)) { + for (let j = 0; j < MOVES.length; j++) { + const mk2 = moveKeys(MOVES[j]), f2 = hold ? [...mk2] : [...mk2, 'J'], holds2 = [f2, f2, f2, f2, f2, f2]; + const s2 = evaluate(g, c.holds, mouse, f2, H, holds2).score + (c.i === mem.last ? 12 : 0); + if (!best2 || s2 > best2.s) best2 = { s: s2, c }; + } + } + best = best2.c; + } + mem.last = best.i; + return { holds: best.holds.map(h => h.slice(0, 4)), mouse }; + }; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/soulknight_remake/index.html b/environments/games/web/games/soulknight_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..ae0b6cbca50ec4bf5678e873d930ff817f46ef9e --- /dev/null +++ b/environments/games/web/games/soulknight_remake/index.html @@ -0,0 +1,7 @@ + +Soul Knight: Dungeon Bosses
            +

            Soul Knight: Dungeon Bosses

            Six bosses · Armored Gunner · knight-arena@6 · 60 Hz · Easy/Normal/Hard · Recording and Replay

            Back to Game Lobby
            +
            Select a boss to start

            The gunner has 6 health, 5 armor, and 180 energy. Armor regenerates by 1 per second after 3 seconds without damage. Bosses enrage at half health. The blade can cut ordinary bullets, turrets, star turrets, and vortex shots, but not shockwaves, meteors, laser orbs, explosive shots, or beams. Hold the left mouse button and drag to aim manually, or double-click the screen to lock the pointer for free aim (Esc unlocks it). When the mouse is idle, auto-aim targets a visible boss. Replays save inputs and the seed for deterministic verification. The scripted demo reads internal state and emits only valid keyboard and mouse actions; it does not start RL training.

            +
            +
            All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
            + diff --git a/environments/games/web/games/soulknight_remake/manifest.json b/environments/games/web/games/soulknight_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..964f24342d5a48df2b8b698fb09c56cbb6a09e29 --- /dev/null +++ b/environments/games/web/games/soulknight_remake/manifest.json @@ -0,0 +1,31 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "soulknight_remake", + "module": "SoulKnightGame", + "title": "Soul Knight: Dungeon Bosses", + "dimension": "2d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "canvas-native", + "rules": "knight-arena@6", + "cases": [ + "soulknight/goblin_priest", + "soulknight/christmas_treant", + "soulknight/devils_snare", + "soulknight/grand_slime", + "soulknight/varkolyn_leader", + "soulknight/volcanic_sandworm" + ], + "scripts": [ + "_native/runtime.js", + "soulknight_remake/game.js", + "soulknight_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "soulknight_remake/game.js" + ], + "play_page": "web/games/soulknight_remake/index.html", + "scripted_controller": "SoulKnightGame.scripted(game) -> {holds:[6 key arrays], mouse:[dx,dy,dz]} (falls back to .oracle)" +} diff --git a/environments/games/web/games/terraria_remake/arena.js b/environments/games/web/games/terraria_remake/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..c56f491f5f3d7f75018ed0191004eed57e3607ac --- /dev/null +++ b/environments/games/web/games/terraria_remake/arena.js @@ -0,0 +1,9 @@ +// Arena geometry, in game units (u). Origin = left wall surface / floor surface, y up. +// Scale: 1 u = 2 tiles = 32 px of the source game (a tile is 16 px); its 60 Hz tick is kept, so +// speed px/tick x 1.875 = u/s acceleration px/tick^2 x 112.5 = u/s^2 +// 27 x 15 u = a 54 x 30 tile arena (engine/renderer.js: 30 px per u on screen, keep W <= 28). +// Platforms (one-way, like wooden platforms) are per case: BB.CASES[id].platforms = [[x0, x1, y], ...]. +(function (g) { + var BB = g.BB; + BB.ARENA = { W: 27, H: 15 }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/terraria_remake/art/scenes.js b/environments/games/web/games/terraria_remake/art/scenes.js new file mode 100644 index 0000000000000000000000000000000000000000..6c42e6d8c0fa3dcac326bcb6455d37d074fe3950 --- /dev/null +++ b/environments/games/web/games/terraria_remake/art/scenes.js @@ -0,0 +1,119 @@ +(function(g){ + var BB=g.BB,ART=BB.ART; + // Original procedural backdrops, cached once per case (bg + fg) plus a cached day/night alternate. + // Seeded by a fixed hash (ART.hash), never by the game RNG. + var H=ART.hash; + function sky(x,top,bottom){var gr=x.createLinearGradient(0,0,0,466);gr.addColorStop(0,top);gr.addColorStop(1,bottom);x.fillStyle=gr;x.fillRect(0,0,854,480);} + function hills(x,base,amp,col,seed,step){x.fillStyle=col;x.beginPath();x.moveTo(0,480);for(var px=0;px<=854;px+=step){x.lineTo(px,base-amp*(.5+.5*Math.sin(px*.011+seed))-amp*.35*H(seed+px));}x.lineTo(854,480);x.closePath();x.fill();} + function tree(x,px,base,h,trunk,leaf,leaf2){ + x.fillStyle=trunk;x.fillRect(px-4,base-h,8,h);x.fillRect(px-9,base-6,18,6); + x.fillStyle=leaf;x.beginPath();x.arc(px,base-h,h*.32,0,Math.PI*2);x.arc(px-h*.22,base-h*.82,h*.24,0,Math.PI*2);x.arc(px+h*.22,base-h*.82,h*.24,0,Math.PI*2);x.fill(); + x.fillStyle=leaf2;x.beginPath();x.arc(px-h*.08,base-h*1.06,h*.17,0,Math.PI*2);x.fill(); + } + function stars(x,n,seed){for(var i=0;i.5?'rgba(0,0,0,.12)':'rgba(255,255,255,.05)';x.fillRect(px,y+5,15,10);} + x.fillStyle=top;x.fillRect(0,y-2,854,6); + if(kind!=='dungeon'&&kind!=='hive')for(px=0;px<854;px+=6){var gh=2+Math.floor(H(px*3.1)*5);x.fillRect(px,y-2-gh,2,gh);} + } + // Honeycomb wall for the underground hive (original procedural pattern). + function honeycomb(x,top){ + var r=19,hx=r*1.5,hy=r*Math.sqrt(3); + for(var col=0,cx=-r;cx<880;col++,cx+=hx)for(var cy=top+(col%2)*hy/2;cy<480;cy+=hy){ + var s=H(col*13.7+cy);x.beginPath(); + for(var k=0;k<6;k++){var a=k*Math.PI/3;x.lineTo(cx+Math.cos(a)*(r-1.5),cy+Math.sin(a)*(r-1.5));} + x.closePath();x.fillStyle=s>.86?'#6a4818':s>.5?'#3e2a10':'#35230c';x.fill(); + x.strokeStyle='rgba(18,10,2,.7)';x.lineWidth=2;x.stroke(); + if(s>.86){x.fillStyle='rgba(255,200,90,.12)';x.beginPath();x.arc(cx-4,cy-4,5,0,Math.PI*2);x.fill();} + } + } + ART.scene=function(doc,id){ + var bg=doc.createElement('canvas'),fg=doc.createElement('canvas');bg.width=fg.width=854;bg.height=fg.height=480; + var x=bg.getContext('2d'),V=BB.VIEW,kind=BB.CASES[id].arena; + var night=kind==='night',cave=kind==='dungeon'||kind==='hive',evil=kind==='corruption',crimson=kind==='crimson'; + function paint(x,isNight){ + if(kind==='hive'){ + // underground hive: warm gradient, honeycomb wall, dripping honey and jungle vines (no day/night) + sky(x,'#140c04','#24170a');honeycomb(x,70); + x.fillStyle='rgba(10,6,2,.35)';x.fillRect(0,0,854,480); + for(var d=0;d<14;d++){var hx=30+d*62+H(d)*30,len=30+H(d+3)*90;x.fillStyle='rgba(190,120,30,.6)';x.fillRect(hx-2,60,4,len);x.beginPath();x.arc(hx,60+len,4,0,Math.PI*2);x.fill();} + for(d=0;d<9;d++){var vx=H(d+20)*854;x.strokeStyle='#2c4a1e';x.lineWidth=3;x.beginPath();x.moveTo(vx,40);x.quadraticCurveTo(vx+18,140,vx-6,180+H(d)*120);x.stroke(); + x.fillStyle='#365f24';for(var l=0;l<5;l++){x.beginPath();x.ellipse(vx+6-l*2,70+l*28,6,3,.6,0,Math.PI*2);x.fill();}} + [[150,250],[700,250]].forEach(function(p){ART.glow(x,p[0],p[1],70,'255,170,60',.12);}); + return; + } + if(crimson){ + // crimson: blood-red sky, flesh hills, vertebra spires and veiny ground growths + sky(x,isNight?'#200a10':'#5a1f26',isNight?'#4a1820':'#8a3a3a'); + if(isNight){stars(x,40,5);moon(x,690,84,20);}else sun(x,700,90,20); + hills(x,320,60,isNight?'#3a121a':'#6a2a30',2.7,6); + for(var i=0;i<8;i++){var sx=50+i*110+H(i+11)*40,sh=100+H(i+2)*120; + for(var v=0;v.7?'#33415a':s>.35?'#2d3a50':'#283447';x.fillRect(a,y,50,20); + x.fillStyle='rgba(255,255,255,.04)';x.fillRect(a,y,50,2);} + [110,330,524,744].forEach(function(px){x.fillStyle='#1a2230';x.fillRect(px-20,96,40,370);x.fillStyle='#3d4c63';x.fillRect(px-26,90,52,10);x.fillRect(px-26,450,52,16);}); + [220,634].forEach(function(px){x.fillStyle='#0b0f17';x.beginPath();x.moveTo(px-26,250);x.lineTo(px-26,170);x.arc(px,170,26,Math.PI,0);x.lineTo(px+26,250);x.closePath();x.fill(); + ART.glow(x,px,190,40,'90,140,255',.18);}); + for(var k=0;k<6;k++){var cx=70+k*150+H(k)*30;x.strokeStyle='#4b525c';x.lineWidth=2;x.setLineDash([3,2]);x.beginPath();x.moveTo(cx,96);x.lineTo(cx,96+40+H(k+9)*60);x.stroke();x.setLineDash([]);} + [[180,300],[680,300]].forEach(function(p){ART.glow(x,p[0],p[1],46,'255,170,80',.35);x.fillStyle='#ffcc6a';x.fillRect(p[0]-3,p[1]-6,6,9);x.fillStyle='#5a4632';x.fillRect(p[0]-5,p[1]+3,10,4);}); + return; + } + if(evil){ + sky(x,isNight?'#1d1426':'#4a3a5c',isNight?'#3a2a44':'#7a6585'); + if(isNight){stars(x,50,3);moon(x,120,78,18);}else sun(x,700,90,20); + hills(x,320,60,isNight?'#2c2036':'#4f3f5e',1.3,6); + // ebonstone spires and thorny dead trees + for(var i=0;i<9;i++){var px=40+i*100+H(i)*40,hgt=90+H(i+3)*120;x.fillStyle=isNight?'#231a2c':'#3d2f4a';x.beginPath();x.moveTo(px-26,466);x.lineTo(px-8,466-hgt);x.lineTo(px+4,466-hgt*.82);x.lineTo(px+26,466);x.closePath();x.fill();} + hills(x,380,40,isNight?'#2a1f33':'#46385a',4.1,5); + for(i=0;i<7;i++){var tx=60+i*125+H(i*2)*30,th=60+H(i+8)*40;x.strokeStyle=isNight?'#1a1220':'#2c2235';x.lineWidth=5;x.beginPath();x.moveTo(tx,466);x.lineTo(tx,466-th);x.stroke(); + x.lineWidth=2;x.beginPath();x.moveTo(tx,466-th*.6);x.lineTo(tx-16,466-th*.85);x.moveTo(tx,466-th*.75);x.lineTo(tx+14,466-th);x.stroke();} + for(i=0;i<16;i++){x.fillStyle='rgba(180,140,220,.35)';x.fillRect(H(i+40)*854,140+H(i+60)*300,2,2);} + return; + } + if(isNight){sky(x,'#0e1830','#2c4468');stars(x,90,1);moon(x,700,90,22);} + else{sky(x,'#6fb6e6','#cfe8f2');sun(x,700,92,24); + for(var cl=0;cl<5;cl++){var ccx=60+cl*190+H(cl)*40,ccy=60+H(cl+4)*60;x.fillStyle='rgba(255,255,255,.75)';x.beginPath();x.ellipse(ccx,ccy,46,14,0,0,Math.PI*2);x.ellipse(ccx+24,ccy-8,30,12,0,0,Math.PI*2);x.fill();}} + hills(x,300,70,isNight?'#1d3042':'#8fb9b0',.4,6); + hills(x,350,50,isNight?'#1b3a35':'#5f9670',2.2,5); + for(var j=0;j<12;j++)tree(x,20+j*76+H(j)*30,466,90+H(j+5)*60,isNight?'#2a2620':'#5c3d27',isNight?'#1e4436':'#3f8a4a',isNight?'#2a5a46':'#5aa85c'); + } + paint(x,night); + ground(x,kind,V); + var f=fg.getContext('2d'); + (BB.CASES[id].platforms||[]).forEach(function(p){var x0=Math.round(V.sx(p[0])),w=Math.round((p[1]-p[0])*V.S),y=Math.round(V.sy(p[2])); + f.fillStyle='#4c3423';f.fillRect(x0,y,w,7);f.fillStyle='#c9925a';f.fillRect(x0,y,w,3); + for(var n=0;n0?4:0);return this.status.broken_armor>0?Math.floor(d/2):d;}; + // r7 (2026-11-07): no natural health regeneration. The source regenerates over time (RT/eRT formula), which in a + // single-boss arena let a controller stand and trade hits. Life comes back only from dropped hearts. + // Poisoned: 2 life per second for players (Debuffs Wiki), applied as one point every 30 ticks. + P.updateLifeDrain=function(c){ + if(this.status.poisoned>0&&this.hp>0){this.poisonCounter++;if(this.poisonCounter>=30){this.poisonCounter=0;this.hp=Math.max(0,this.hp-1);c.emit('poison_tick',this.x,this.y+K.H);}} + else this.poisonCounter=0; + }; + P.update=function(c,i){ + var dt=BB.DT,pv=this.prev,oldY=this.y; + function decay(v){return v<=dt+1e-9?0:v-dt;} + this.invul=decay(this.invul);this.atkCd=decay(this.atkCd);this.atkT=decay(this.atkT);this.dropT=decay(this.dropT); + for(var name in this.status)this.status[name]=decay(this.status[name]); + // Confused swaps the movement controls (left with right, jump/up with drop/down); attacks are unchanged. + if(this.status.confused>0)i=Object.assign({},i,{left:i.right,right:i.left,jump:i.drop,drop:i.jump}); + if(this.status.cursed>0)i=Object.assign({},i,{attack:false,bow:false,sword:false}); + if(this.atkT>0){ + this.slashPreviousAngle=this.slashAngle; + var arc=2.2-3.3*(1-this.atkT/K.SWORD_CD);this.slashAngle=this.slashFacing>0?arc:Math.PI-arc; + } + this.knock*=0.89; + var dir=(i.right?1:0)-(i.left?1:0),slow=(this.status.slow>0?0.5:1)*(this.status.weak>0?0.9:1); + // Weak also lowers melee damage and melee speed by 5.1 %; the instance NAIL is what the engine deals per slash. + this.NAIL=this.status.weak>0?K.SWORD*0.949:K.SWORD; + this.vx=TR.playerHorizontal(this.vx,dir,K.BASE_RUN*slow,K.RUN*slow,K.ACC,K.DEC,true); + if(dir&&this.atkT<=0)this.facing=dir; + if(i.switchWeapon&&!pv.switchWeapon)this.weapon=this.weapon==='bow'?'sword':'bow'; + if(i.drop&&this.y>0&&this.grounded){this.dropT=0.18;this.grounded=false;this.y=Math.max(0,this.y-0.06);this.jumpTicks=0;} + if(i.jump&&!pv.jump&&this.grounded&&!i.drop){this.jumpTicks=K.JUMP_TICKS;this.grounded=false;c.emit('jump',this.x,this.y);} + if(!i.jump)this.jumpTicks=0; + this.flying=false;this.gliding=false; + if(this.jumpTicks>0){this.vy=K.JUMP-K.GRAV*dt;this.jumpTicks--;} + else{ + this.vy=Math.max(-K.FALL,this.vy-K.GRAV*dt); + if(i.jump&&!this.grounded&&this.flight>0){ + this.flying=true;this.vy=Math.min(K.FLY,this.vy+60*dt);this.flight=decay(this.flight); + }else if(i.jump&&!this.grounded&&this.vy<0){this.gliding=true;this.vy=Math.max(this.vy,-K.FALL/3);} + } + this.x=BB.clamp(this.x+this.vx*dt,K.W/2,BB.ARENA.W-K.W/2); + this.y=Math.min(BB.ARENA.H-K.H,this.y+this.vy*dt);this.grounded=false; + if(this.y<=0){this.y=0;this.vy=0;this.grounded=true;} + if(this.vy<=0&&this.dropT<=0){ + var landing=-Infinity; + TR.platforms(c).forEach(function(p){ + if(this.x+K.W/2>p[0]&&this.x-K.W/2=p[2]-0.001&&this.y<=p[2])landing=Math.max(landing,p[2]); + },this); + if(landing>-Infinity){this.y=landing;this.vy=0;this.grounded=true;} + } + if(this.grounded){this.flight=K.WINGS;this.jumpTicks=0;this.flying=false;this.gliding=false;} + if(this.y>=BB.ARENA.H-K.H&&this.vy>0){this.vy=0;this.jumpTicks=0;} + if((i.attack||i.bow||i.sword)&&this.atkCd<=0){ + var weapon=i.bow?'bow':i.sword?'sword':this.weapon; + var b=this.centre(),a=Math.atan2(this.aimY-b.y,this.aimX-b.x); + this.facing=Math.cos(a)>=0?1:-1; + if(weapon==='bow'){ + this.atkCd=K.BOW_CD; + this.arrows.push({id:++this.nextId,x:b.x,y:b.y,vx:Math.cos(a)*K.ARROW_SPEED,vy:Math.sin(a)*K.ARROW_SPEED,age:0,life:K.ARROW_LIFE});c.emit('arrow',b.x,b.y); + }else{ + this.atkCd=K.SWORD_CD/(this.status.weak>0?0.949:1);this.atkT=K.SWORD_CD;this.slashFacing=this.facing; + this.slashAngle=this.facing>0?2.2:Math.PI-2.2;this.slashPreviousAngle=this.slashAngle;this.slashHits={};c.emit('slash',b.x,b.y); + } + } + this.arrows=this.arrows.filter(function(p){ + var ox=p.x,oy=p.y; + p.age=(p.age||0)+1;if(p.age>=K.ARROW_GRAV_DELAY)p.vy=Math.max(-K.FALL,p.vy-K.ARROW_GRAV*dt); + p.x+=p.vx*dt;p.y+=p.vy*dt;p.life-=dt; + var shape={x0:ox,y0:oy,x1:p.x,y1:p.y,r:0.08}; + if(TR.resolveArrow(c.boss,c,K.BOW,shape,p.vx>=0?1:-1))return false; + return p.life>0&&p.x>=0&&p.x<=BB.ARENA.W&&p.y>=0&&p.y<=BB.ARENA.H; + },this); + var slash=this.slashBox(); + if(slash)TR.slashExtras(c.boss,c,this.NAIL,slash.pts,this.slashHits); + this.updateLifeDrain(c); + if(typeof TR.updatePickups==='function')TR.updatePickups(c); + this.prev={jump:!!i.jump,switchWeapon:!!i.switchWeapon}; + }; + P.onSlashContact=function () {}; + P.hurt=function(c,base,fromX,hazard){ + if(this.invul>0||this.hp<=0)return false; + var damage=TR.playerDamage(c,base,this.defense(),TR.defFactor(c)); + this.hp=Math.max(0,this.hp-damage);this.invul=damage===1?K.INVUL/2:K.INVUL; + this.knock=this.x>fromX?4.5*TR.PX:-4.5*TR.PX;this.vx=this.knock;this.vy=3.5*TR.PX;this.grounded=false;this.jumpTicks=0; + if(hazard&&hazard.debuff&&c.rng.chance(hazard.debuffChance==null?1:hazard.debuffChance)){ + var duration=hazard.debuffDuration; + if(Array.isArray(duration))duration=c.rng.uniform(duration[0],duration[1]); + this.applyStatus(hazard.debuff,+duration||0); + } + // A weighted debuff pool (Brain of Cthulhu Expert contacts): one roll picks one debuff and its duration range. + if(hazard&&hazard.debuffPool&&c.rng.chance(hazard.debuffChance==null?1:hazard.debuffChance)){ + var pool=hazard.debuffPool,pick=pool[c.rng.pick(pool.map(function(e){return e[1];}))]; + this.applyStatus(pick[0],c.rng.uniform(pick[2][0],pick[2][1])); + } + TR.emitHit(c,'player_hit',this.x,this.y+K.H,damage);return true; + }; + P.state=function(){return TR.snapshot(this,{attacking:this.atkT>0,flight_max:K.WINGS});}; + BB.Adventurer=Adventurer;BB.TR.BODY=K; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js b/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js new file mode 100644 index 0000000000000000000000000000000000000000..580954a211b80b99e08dd2fcbef6b2de7aec349d --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/brain_of_cthulhu.js @@ -0,0 +1,128 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.brain_of_cthulhu; + // Desktop 1.4.5.8 ordinary single-player Classic / Expert Brain of Cthulhu (aiStyle 54) and its Creepers. + // Published: brain 1250/2125 life, 30/54 damage, defense 14; 20 Creepers 100/170 life, 20/36 damage, defense 10, + // never respawn; the brain cannot be damaged until every Creeper is dead; a Creeper drops a heart 1/2 when the + // player is hurt; Expert contacts roll one debuff from a nine-entry pool (Creepers always, phase-2 brain 1/3); + // Expert phase 2 adds three mirror illusions around the player whose opacity rises as health drops. + // Unpublished (estimates): teleport and charge timing, speeds, orbit radius, the 1.4.4 + // phase-1 safe radius. + var W=110/32,H=86/32; + // Expert contact debuff pool: [name, weight out of 81, duration range s] (Creeper / Brain of Cthulhu pages). + var POOL=[['poisoned',11,[5.23,10.4]],['darkness',11,[3,5.93]],['cursed',2,[.73,1.47]],['bleeding',11,[15,29.8]], + ['confused',2,[1.5,2.97]],['slow',11,[5.23,10.4]],['weak',11,[11.23,22.33]],['silenced',11,[1.5,2.97]],['broken_armor',11,[9.73,19.37]]]; + function Brain(){} + var P=Brain.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,20,9,W,H);this.expert=this.k.expert>=.5; + // Boss health is the published combined total (brain + 20 Creepers, 3250 / 5525), like the Eater's segment sum, + // so the HUD, verifier and reward count Creeper kills. The brain's own health is brainHp. + this.brainHp=this.brainMax=TR.paceHp(this,this.expert?2125:1250,10,this.pace.brainHp);this.dmg=TR.paceDmg(this,this.expert?54:30);this.defense=14; + this.creeperHp=TR.paceHp(this,this.expert?170:100);this.creeperDmg=TR.paceDmg(this,this.expert?36:20); + this.sourceProfile=this.expert?'desktop-expert':'desktop-classic';this.phase=1;this.fade=1;this.tpTimer=0;this.chargeTimer=1.2/this.pace.aggr; + this.knockbackResist=this.expert?.6:.55; + this.orbitAngle=0;this.illusions=[];this.illusionAlpha=0; + for(var i=0;i<20;i++){ + // The 20 Creepers spawn on three rings around the brain, evenly spread (no cluster a single sword arc clears). + var a=i/20*Math.PI*2,r=2.2+(i%3)*.55; + this.minions.push({id:++this.nextId,kind:'creeper',x:this.x+TR.cos(a)*r,y:this.y+TR.sin(a)*r,vx:0,vy:0,w:34/32,h:34/32, + hp:this.creeperHp,max_hp:this.creeperHp,dmg:this.creeperDmg,defense:10,knockbackResist:this.expert?.28:.2,floating:true, + drop:'creeper_heart',slot:a,ring:r,st:'orbit',t:0,debuffPool:this.expert?POOL:null,debuffChance:1}); + } + this.max_hp=this.brainMax+20*this.creeperHp;this.sync(); + this.go(c,'idle',0,'creeper_charge'); + }; + P.sync=function(){this.hp=this.brainHp+this.minions.reduce(function(a,m){return a+(m.kind==='creeper'?Math.max(0,m.hp):0);},0);}; + P.alive=function(){return this.minions.filter(function(m){return m.kind==='creeper'&&m.hp>0;});}; + // Phase 1: invulnerable; a teleporting brain is not solid until it has mostly faded in. + P.hitTargets=function(){return this.phase===1||this.fade<.5||this.st==='dead'?[]:[{id:'brain',box:this.bodyBox()}];}; + P.onNailHit=function(c,base,dir,f,id){ + if(this.phase===1||this.fade<.5||this.brainHp<=0)return null; + var hit=TR.rollDetails(c,base,this.defense,.5,.04);this.brainHp=Math.max(0,this.brainHp-hit.damage);this.hitFlash=.12; + TR.emitHit(c,'boss_hit',this.x,this.y,hit.damage,hit.critical);this.sync(); + if(!this.brainHp){this.hp=0;this.st='dead';this.minions=[];this.shots=[];c.emit('boss_dead',this.x,this.y);return 'flesh';} + // "The only boss that is affected by knockback" (Wiki trivia): phase-2 knockback resistance 55 % / 60 % + // (1.4.4). Arrow KB 2, sword KB 5; the push uses the shared NPC knockback rule on the brain's own velocity. + TR.enemyKnockback(c,this,hit.damage,hit.critical,{facing:f<0?-1:1,knockback:dir==='arrow'?TR.BODY.BOW_KB:TR.BODY.SWORD_KB}); + return 'flesh'; + }; + P.teleport=function(c,near){ + // A random spot around the player, away from the player and inside the arena (phase 1 keeps the safe radius). + var b=c.body.centre(),best=null; + for(var k=0;k<12;k++){ + var a=c.rng.uniform(0,Math.PI*2),r=near?c.rng.uniform(5,8):c.rng.uniform(7,11),x=b.x+TR.cos(a)*r,y=b.y+Math.abs(TR.sin(a))*r*.8+1; + if(x>this.w/2&&xthis.h/2+.5&&y.9||m.xBB.ARENA.W-m.w/2||m.yBB.ARENA.H-m.h/2){m.st='return';m.t=0;} + m.x=BB.clamp(m.x,m.w/2,BB.ARENA.W-m.w/2);m.y=BB.clamp(m.y,m.h/2,BB.ARENA.H-m.h/2); + }else{ + // Irregular circles around the brain: each Creeper has its own ring radius and a wobble. + var a=m.slot+self.orbitAngle,r=m.ring+TR.sin(self.orbitAngle*1.7+m.id)*.5; + var tx=self.x+TR.cos(a)*r,ty=self.y+TR.sin(a)*r; + TR.moveToward(m,tx,ty,(m.st==='return'?9:12)*self.pace.speed,m.st==='return'?30:60); + if(m.st==='return'&&Math.hypot(m.x-tx,m.y-ty)<.6)m.st='orbit'; + } + return true; + }); + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre();this.sync(); + this.fade=Math.min(1,this.fade+dt/(this.phase===1?.6:.35)); + if(this.phase===1){ + // Translucent and invulnerable: drift toward the player, then teleport away in a random direction. The drift + // stops short of the player so the orbiting ring cannot simply sit on them: Creepers reach the player by + // charging (the source behaviour), not by the ring overlapping a player the brain is parked next to. + var bx=b.x,by=b.y+1.5,dd=Math.hypot(this.x-bx,this.y-by),keep=4.5; + if(dd>keep)TR.moveToward(this,bx,by,2.4*TR.PX*this.pace.speed,4); + else{this.vx*=.9;this.vy*=.9;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2);this.y=BB.clamp(this.y+this.vy*dt,this.h/2,BB.ARENA.H-this.h/2);} + this.tpTimer+=dt; + if(this.tpTimer>=(this.expert?4:5.5)/this.pace.aggr){this.tpTimer=0;this.teleport(c,false);} + this.updateCreepers(c,b);this.sync(); + if(!this.alive().length){this.phase=2;this.tpTimer=0;this.go(c,'transform',.8,'teleport');c.emit('boss_escalate',this.x,this.y);} + return; + } + if(this.st==='transform'){this.vx=this.vy=0;if(this.timer<=0)this.go(c,'attack',0,'teleport');} + else{ + // When visible in phase two, the heart pursues the player while its illusions mirror its movement. + if(this.fade>=1)TR.moveToward(this,b.x,b.y,(this.expert?4:3)*TR.PX*this.pace.speed,this.expert?12:8); + this.tpTimer+=dt; + if(this.tpTimer>=(this.expert?2.4:3.2)/this.pace.aggr){this.tpTimer=0;this.teleport(c,true);} + } + // Expert illusions mirror the brain through the player; opacity rises as the brain's own health drops. + if(this.expert){var dx=this.x-b.x,dy=this.y-b.y; + this.illusions=[{x:b.x-dx,y:b.y+dy},{x:b.x+dx,y:b.y-dy},{x:b.x-dx,y:b.y-dy}].map(function(p){ + return {x:BB.clamp(p.x,.5,BB.ARENA.W-.5),y:BB.clamp(p.y,.5,BB.ARENA.H-.5)};}); + this.illusionAlpha=.25+.75*(1-this.brainHp/this.brainMax);} + this.minions=this.minions.filter(function(m){return m.hp>0;});this.sync(); + }; + P.hazards=function(){ + if(this.st==='dead')return []; + var out=[]; + // A fading brain cannot touch the player; it becomes solid as it finishes appearing. + if(this.fade>=.5){var h={kind:this.phase===1?'brain':'brain_heart',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}; + if(this.expert&&this.phase===2){h.debuffPool=POOL;h.debuffChance=1/3;}out.push(h);} + return out.concat(TR.extraHazards(this)); + }; + BB.CASES['terraria/brain_of_cthulhu'] = TR.register('brain_of_cthulhu','Teleporting Flesh Brain',Brain,'crimson'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js b/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js new file mode 100644 index 0000000000000000000000000000000000000000..af96ae65ebe8fe46fca9d82311d9f21ecbba2a00 --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/eater_of_worlds.js @@ -0,0 +1,170 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.eater_of_worlds; + var EXPLOSIVES={grenade:1,sticky_grenade:1,bouncy_grenade:1,bomb:1,sticky_bomb:1,bouncy_bomb:1, + dynamite:1,sticky_dynamite:1,bouncy_dynamite:1,power_bomb:1,sticky_power_bomb:1,explosives:1, + explosive_bunny:1,confetti_grenade:1,bomb_fish:1,scarab_bomb:1,beenade:1,bee:1,giant_bee:1,tnt_barrel:1}; + var EXPLOSIVE_IDS={30:1,397:1,517:1,28:1,37:1,516:1,29:1,470:1,637:1,1086:1,1087:1, + 108:1,281:1,588:1,519:1,773:1,183:1,181:1,566:1,1002:1}; + function snap(v){return Math.floor(v/TR.TILE)*TR.TILE;} + function Eater(){} + var P=Eater.prototype;TR.boss(P,S); + P.stats=function(type){ + return {hp:TR.paceHp(this,this.expert?210:150,1),dmg:TR.paceDmg(this,this.expert?(type==='head'?48:type==='body'?21:18):(type==='head'?22:type==='body'?13:11)), + defense:(type==='head'?2:type==='body'?4:8)+(this.expert?2:0)}; + }; + P.reset=function(c){ + this.setup(c,20,-1,1.375,1.375);this.expert=this.k.expert>=.5;this.segments=[];this.chains=[]; + this.sourceProfile=this.expert?'desktop-expert':'desktop-classic';this.spacing=46/32; + // Tier aggression (tiers.js) scales top speed by sqrt(aggr) and steering by aggr; 1 at normal. + this.maxSpeed=16*(this.expert?1.2:1)*this.pace.speed;this.acceleration=(this.expert?16.875:7.875)*this.pace.aggr; + // The available reference gives ballistic peak heights (~31/44 tiles), rather than raw AI gravity. + // This approximation is constrained to those peaks; exact continuous steering remains documented. + this.airGravity=16*16/(31*TR.TILE*2);this.max_hp=0; + var n=Math.max(8,Math.round((this.expert?72:67)*this.pace.segments)),size=this.expert?1.2:1; + for(var i=0;i1){ + var first=run[0],prev=old.find(function(ch){return ch.ids[0]===first.id;}),newHead=first.type!=='head'; + run.forEach(function(s,n){self.retype(s,n===0?'head':n===run.length-1?'tail':'body');}); + // A surviving head keeps its momentum. Every new split head must fall and reach material first. + chains.push({ids:run.map(function(s){return s.id;}),st:prev?prev.st:'burrow',timer:0,digTimer:prev?prev.digTimer:0, + target:prev?prev.target:c.body.centre(),vx:prev?prev.vx:0,vy:prev?prev.vy:0, + forceFall:newHead||(!prev&&old.length>0)}); + }run=[]; + } + this.segments.forEach(function(s){if(s.hp>0)run.push(s);else finish();});finish();this.chains=chains; + this.hp=this.segments.reduce(function(a,s){return a+s.hp;},0); + if(!this.hp){this.st='dead';this.shots=[];c.emit('boss_dead',this.x,this.y);} + }; + P.hitTargets=function(){ + // Initial coiled segments are invisible but remain hittable, as in the source game. + return this.segments.filter(function(s){return s.hp>0&&s.y>-s.h/2;}).map(function(s){return {id:s.id,box:TR.box(s)};}); + }; + P.damageMultiplier=function(attack){ + var kind=typeof attack==='string'?attack:attack&&(attack.kind||attack.projectileKind), + id=attack&&typeof attack==='object'?attack.projectileId:null; + if(kind==='molotov_fire'||kind==='obsidian_swordfish_fire')return .65; + return this.expert&&(EXPLOSIVES[kind]||EXPLOSIVE_IDS[id])?.2:1; + }; + P.onNailHit=function(c,base,dir,f,id){ + var s=this.segments.find(function(v){return v.id===id;});if(!s||s.hp<=0)return null; + var hit=TR.rollDetails(c,base*this.damageMultiplier(dir),s.defense,0.5,0.04),damage=hit.damage; + s.hp=Math.max(0,s.hp-damage);this.hitFlash=.12;TR.emitHit(c,'boss_hit',s.x,s.y,damage,hit.critical); + if(!s.hp){if(TR.dropSegment)TR.dropSegment(c,this,s);c.emit('worm_split',s.x,s.y);this.rebuild(c);} + else this.hp=this.segments.reduce(function(a,v){return a+v.hp;},0); + return 'flesh'; + }; + P.inMaterial=function(c,s){ + var solid=function(x,y){return TR.solidAt?TR.solidAt(c,x,y,{platforms:true}):y<=0;}; + return solid(s.x,s.y)||solid(s.x,s.y-s.h/2)||solid(s.x-s.w/2,s.y)||solid(s.x+s.w/2,s.y); + }; + // Source worm steering (vanilla aiStyle 6, as mirrored by tModLoader ExampleMod WormHead): per-axis steps + // of `acceleration` toward the target direction, plus the source's anti-stall terms. When the head moves + // away from a nearly level/vertical target it curves along the other axis (x2 step); when it is slower than + // half its top speed it keeps pushing along its current sign. Without those terms a head below a target + // that is higher than its standing hop hovers at the surface forever (r4 bug). + // y is up here and down in the source, so a zero vertical velocity breaks toward "up" in both. + function toward(v,t,a){return vt?v-a:v;} + P.steerToward=function(ch,dirX,dirY){ + var speed=this.maxSpeed,acc=this.acceleration*BB.DT,len=Math.hypot(dirX,dirY),absX=Math.abs(dirX),absY=Math.abs(dirY),vx=ch.vx,vy=ch.vy; + if(len>0){dirX*=speed/len;dirY*=speed/len;} + if(len>0&&((vx>0&&dirX>0)||(vx<0&&dirX<0)||(vy>0&&dirY>0)||(vy<0&&dirY<0))){ + vx=toward(vx,dirX,acc);vy=toward(vy,dirY,acc); + if(Math.abs(dirY)0&&dirX<0)||(vx<0&&dirX>0)))vy+=vy<0?-acc*2:acc*2; + if(Math.abs(dirX)0&&dirY<0)||(vy<0&&dirY>0)))vx+=vx>0?acc*2:-acc*2; + }else if(absX>absY){ + vx=toward(vx,dirX,acc*1.1); + if(Math.abs(vx)+Math.abs(vy)0)vy=toward(vy,dirY,acc*1.1); + if(Math.abs(vx)+Math.abs(vy)0?acc:-acc; + } + ch.vx=vx;ch.vy=vy; + }; + // Out of material: constant gravity (fitted to the published peaks, EOW-05) and the source's horizontal + // terms: a slow head keeps accelerating along its sign, a head at terminal fall turns toward the target, + // a fast-falling head loses horizontal speed. dirX is the raw tile-snapped distance, compared in source px. + P.fall=function(ch,dirX){ + var speed=this.maxSpeed,acc=this.acceleration*BB.DT; + ch.vy=Math.max(-speed,ch.vy-this.airGravity*BB.DT); + if(Math.abs(ch.vx)+Math.abs(ch.vy)dpx)ch.vx-=acc;} + else if(ch.vy<-4*TR.PX)ch.vx+=ch.vx<0?acc*.9:-acc*.9; + }; + P.spitChance=function(s){return s.type==='head'?1/390+(1-s.hp/s.max_hp)*(1/90-1/390):s.type==='body'?1/900:0;}; + P.spitAllowed=function(c,s){ + if(s.hp<=0||s.type==='tail')return false; + var b=c.body.centre(); + if(TR.lineOfSight&&!TR.lineOfSight(c,s.x,s.y,b.x,b.y))return false; + if(s.type==='body'&&(s.y<=0||(TR.backgroundWallAt&&TR.backgroundWallAt(c,s.x,s.y))))return false; + return true; + }; + P.spit=function(c,s){ + TR.shoot(this,c,s.x,s.y,7*TR.PX,'vile_spit',false); + var shot=this.shots[this.shots.length-1];shot.sourceSegment=s.id;shot.dmg=TR.paceDmg(this,64);shot.destructible=true;shot.solidCollision=true;shot.collidePlatforms=true; + // Eater-specific Vile Spit is an NPC attack and has no Weak debuff since Desktop 1.4.2. + // Its 7 px/tick motion corresponds to the Wiki's rounded 36 mph. + c.emit('vile_spit',s.x,s.y); + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre(),lookup={},self=this; + this.segments.forEach(function(s){lookup[s.id]=s;}); + this.chains.forEach(function(ch){ + var head=lookup[ch.ids[0]],material=self.inMaterial(c,head),distance=Math.hypot(head.x-b.x,head.y-b.y), + far=Math.abs(head.x-b.x)>62.5*TR.TILE||Math.abs(head.y-b.y)>62.5*TR.TILE; + ch.digTimer-=dt; + if(material&&distance<25&&ch.digTimer<=0){ + c.emit('burrow_dig',head.x,head.y);ch.digTimer=BB.clamp(.1+distance*.026,.1,.75); + } + ch.target={x:b.x,y:b.y}; + if(material)ch.forceFall=false; + // The source compares tile-snapped centres (16 px = TR.TILE). + var dirX=snap(b.x)-snap(head.x),dirY=snap(b.y)-snap(head.y); + if((material||far)&&!ch.forceFall){self.steerToward(ch,dirX,dirY);ch.st='burrow';} + // No artificial pause or telegraph: outside tiles a worm follows a ballistic fall. + else{self.fall(ch,dirX);ch.st='lunge';} + head.vx=ch.vx;head.vy=ch.vy;head.x+=ch.vx*dt;head.y+=ch.vy*dt; + // Finite benchmark world margins allow a long chain to turn underground off-screen. + if(head.x< -4){head.x=-4;ch.vx=Math.abs(ch.vx);}if(head.x>BB.ARENA.W+4){head.x=BB.ARENA.W+4;ch.vx=-Math.abs(ch.vx);} + if(head.y< -20){head.y=-20;ch.vy=Math.abs(ch.vy);}if(head.y>BB.ARENA.H+10){head.y=BB.ARENA.H+10;ch.vy=-Math.abs(ch.vy);} + for(var n=1;nself.spacing){ + s.x=prev.x-sx/dist*self.spacing;s.y=prev.y-sy/dist*self.spacing;s.visible=true; + }else if(s.visible&&dist>1e-9){s.x=prev.x-sx/dist*self.spacing;s.y=prev.y-sy/dist*self.spacing;} + s.vx=(s.x-ox)/dt;s.vy=(s.y-oy)/dt; + } + }); + var leader=this.chains[0]; + if(leader){var head=lookup[leader.ids[0]];this.x=head.x;this.y=head.y;this.vx=head.vx;this.vy=head.vy; + this.st=leader.st==='burrow'?'recover':'attack';this.timer=0;this.target=leader.target;} + if(this.expert)this.segments.forEach(function(s){ + if(!self.spitAllowed(c,s))return;s.shotAttempts++; + if(c.rng.chance(self.spitChance(s)))self.spit(c,s); + }); + }; + P.hazards=function(){ + return this.st==='dead'?[]:this.segments.filter(function(s){return s.hp>0&&s.y>-s.h/2;}).map(function(s){ + return {kind:'worm_'+s.type,box:TR.box(s),dmg:s.dmg,fromX:s.x}; + }).concat(TR.extraHazards(this)); + }; + BB.CASES['terraria/eater_of_worlds'] = TR.register('eater_of_worlds','Burrowing Great Worm',Eater,'corruption'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js b/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js new file mode 100644 index 0000000000000000000000000000000000000000..1e5bfa79114c85e7151db706e90a5d2c43f975fb --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/eye_of_cthulhu.js @@ -0,0 +1,125 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.eye_of_cthulhu; + function Eye(){} + var P=Eye.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,20,10,110/32,110/32); + this.expert=this.k.expert>=0.5;this.easyScale=1; + this.hp=this.max_hp=TR.paceHp(this,this.expert?3640:2800); + this.dmg=TR.paceDmg(this,this.expert?30:15);this.defense=12;this.phaseAt=this.expert?0.65:0.5; + this.k.hp=this.max_hp;this.k.dmg=this.dmg;this.k.phase_at=this.phaseAt; + this.k.def_factor=this.expert?0.75:0.5; + this.cycleIndex=0;this.dashesLeft=0;this.spawnTimer=0;this.servantsThisHover=0; + this.servantsPerHover=this.expert?5:4;this.pendingChain=false; + this.transformFrames=0;this.rotation=0;this.dashAge=0;this.dashFrames=0;this.dashFramesTotal=0;this.chainLevel=0; + this.recoverFrames=0;this.despawned=false;this.dawnDeparting=false; + this.startHover(c); + }; + P.startHover=function(c){ + this.move=null;this.dashesLeft=0;this.pendingChain=false; + this.servantsThisHover=0;this.spawnTimer=1.8/this.pace.aggr;this.hoverFrames=0; + this.go(c,'idle',this.hoverLimit()/60); + }; + // Tier aggression stretches hover and summon cadences and scales dash/hover speeds (tiers.js). + P.hoverLimit=function(){return Math.round((this.phase===1?600:this.expert?120:200)/this.pace.aggr);}; + P.spawnServant=function(c,angle){ + var b=c.body.centre(),dx=b.x-this.x,dy=b.y-this.y,l=Math.hypot(dx,dy)||1; + var vx=dx/l,vy=dy/l; + if(angle){var co=Math.cos(angle),si=Math.sin(angle),ox=vx;vx=ox*co-vy*si;vy=ox*si+vy*co;} + this.minions.push({id:++this.nextId,kind:'servant',x:this.x+vx*this.w/2,y:this.y+vy*this.h/2, + vx:vx*5*TR.PX*this.pace.speed,vy:vy*5*TR.PX*this.pace.speed,w:20/32,h:20/32,hp:this.expert?12:8,max_hp:this.expert?12:8, + dmg:TR.paceDmg(this,this.expert?24:12),defense:0,drop:'heart_star',floating:true,knockbackResist:this.expert?0.1:0}); + c.emit('servant_spawn',this.x,this.y); + }; + P.startDashes=function(c,chain){ + this.move=chain?'chain_dash':'dash';this.dashesLeft=chain?5:3; + this.chainLevel=this.expert&&this.phase===2?(this.hp/this.max_hp<0.04?2:this.hp/this.max_hp<0.12?1:0):0; + this.launch(c); + }; + P.launch=function(c){ + var b=c.body.centre(),chain=this.move==='chain_dash'; + if(chain)this.chainLevel=this.hp/this.max_hp<0.04?2:this.hp/this.max_hp<0.12?1:0; + // A charge commits to one vector. Only rapid charges lead the moving target. + var lead=chain?(this.chainLevel===2?0.25:0.12):0; + this.target={x:b.x+(c.body.vx||0)*lead,y:b.y+(c.body.vy||0)*lead}; + var dx=this.target.x-this.x,dy=this.target.y-this.y,l=Math.hypot(dx,dy)||1; + var speed=(chain?(this.chainLevel===2?20:16):this.phase===2?6.8:6)*TR.PX*this.pace.speed; + if(!chain&&this.expert)speed*=1.15; + this.vx=dx/l*speed;this.vy=dy/l*speed;this.dashAge=0;this.dashFrames=0; + this.dashFramesTotal=chain?(this.chainLevel===2?21:this.chainLevel===1?29:39):150; + this.go(c,'attack',this.dashFramesTotal/60,this.move); + c.emit(chain?'eye_chain_roar':'eye_roar',this.x,this.y); + }; + P.pauseCharges=function(c,frames){frames=Math.round(frames/this.pace.aggr);this.recoverFrames=frames;this.go(c,'recover',frames/60);}; + P.updateServants=function(c,b){ + this.minions=this.minions.filter(function(m){ + if(m.hp<=0){if(TR.dropMinion)TR.dropMinion(c,this,m);return false;} + TR.moveToward(m,b.x,b.y,(this.expert?7:6)*TR.PX*this.pace.speed,12);return true; + },this); + }; + P.updateArmor=function(){ + if(this.phase===1){this.defense=12;this.dmg=TR.paceDmg(this,this.expert?30:15);return;} + var frac=this.hp/this.max_hp; + this.defense=this.expert&&frac<0.04?-30:this.expert&&frac<0.12?-15:0; + this.dmg=TR.paceDmg(this,this.expert?(frac<0.04?40:36):23); + }; + P.onNailHit=function(c,base,dir,f,id){this.updateArmor();return TR.damageBoss(this,c,base,id);}; + P.update=function(c){ + if(this.st==='dead'||this.despawned)return;this.clock(c);var dt=BB.DT,b=c.body.centre(); + if(TR.isDaytime&&TR.isDaytime(c)&&!this.dawnDeparting){ + this.dawnDeparting=true;this.st='despawn';this.timer=1e9;this.stT=0;this.move=null; + this.vy=Math.max(4*TR.PX,this.vy);c.emit('eye_dawn_flee',this.x,this.y); + } + if(this.dawnDeparting){ + // Night-only bosses depart upward rather than vanishing in place when dawn arrives. + this.vx*=0.98;this.vy=Math.min(10*TR.PX,this.vy+0.2*TR.PG*dt); + this.x+=this.vx*dt;this.y+=this.vy*dt;this.updateServants(c,b); + if(this.y-this.h/2>BB.ARENA.H){this.despawned=true;this.minions=[];this.shots=[];c.emit('eye_dawn_despawn',this.x,this.y);} + return; + } + // Mode gates are discrete. At exactly the threshold the original first form remains active. + if(this.phase===1&&this.hp/this.max_hp=this.hoverLimit())this.startDashes(c,this.expert&&this.phase===2&&this.hp/this.max_hp<0.12); + }else if(this.st==='transform'){ + this.vx=this.vy=0;this.transformFrames++;this.rotation+=Math.max(0,100-Math.abs(100-this.transformFrames))*0.005; + // The original Eye remains vulnerable during the transformation. + if(this.transformFrames>=200)this.startDashes(c,false); + }else if(this.st==='attack'){ + this.dashFrames++;this.dashAge=this.dashFrames/60; + if(this.move==='dash'&&this.dashFrames>40){this.vx*=0.98;this.vy*=0.98;} + this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2); + this.y=BB.clamp(this.y+this.vy*dt,this.h/2,BB.ARENA.H-this.h/2); + if(this.dashFrames>=this.dashFramesTotal){ + this.dashesLeft--; + if(this.dashesLeft>0)this.pauseCharges(c,this.move==='chain_dash'?(this.chainLevel===2?1:this.chainLevel===1?5:12):1); + else if(this.expert&&this.phase===2){ + if(this.move==='dash'){this.pendingChain=true;this.pauseCharges(c,21);} + else if(this.hp/this.max_hp<0.12){this.pendingChain=true;this.pauseCharges(c,this.hp/this.max_hp<0.04?1:7);} + else this.startHover(c); + }else this.startHover(c); + } + }else if(this.st==='recover'){ + this.vx*=0.98;this.vy*=0.98; + this.recoverFrames--; + if(this.recoverFrames<=0){if(this.pendingChain){this.pendingChain=false;this.startDashes(c,true);}else this.launch(c);} + } + this.updateServants(c,b); + }; + P.hazards=function(){return this.st==='dead'||this.despawned?[]:[{kind:this.phase===2?'maw':'eye',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}].concat(TR.extraHazards(this));}; + BB.CASES['terraria/eye_of_cthulhu'] = TR.register('eye_of_cthulhu','Charging Giant Eye',Eye,'night'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/king_slime.js b/environments/games/web/games/terraria_remake/bosses/king_slime.js new file mode 100644 index 0000000000000000000000000000000000000000..57e6fe6aed13ef4e7d439ec910c783c6269e3b4e --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/king_slime.js @@ -0,0 +1,132 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.king_slime; + // Desktop 1.4.5.8, ordinary single-player Classic / Expert, without secret seeds. + // Units retain the common 32 source pixels per world unit and 60 simulation ticks per second. + var W=122.5/32,H=115/32,GRAVITY=0.3*TR.PG; + function KingSlime(){} + var P=KingSlime.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,21,H/2,W,H);this.expert=this.k.expert>=0.5; + this.hp=this.max_hp=TR.paceHp(this,this.expert?2800:2000);this.dmg=TR.paceDmg(this,this.expert?64:40);this.defense=10; + this.jumpIndex=0;this.floor=0;this.groundTicks=0;this.teleportWait=0; + this.spawnMark=this.max_hp;this.teleportScale=1;this.hidden=false;this.invulnerable=false; + this.go(c,'idle',1);this.sourceProfile=this.expert?'desktop-expert':'desktop-classic'; + }; + P.jumpCooldown=function(){ + var f=this.hp/this.max_hp,i=f>=.8?0:f>=.6?1:f>=.4?2:f>=.2?3:f>=.1?4:5; + // Tier aggression stretches the source cooldown frames (tiers.js); 1 at normal and above. + return Math.round((this.move==='high_jump'?[100,67,50,34,23,16]:[60,40,30,20,14,10])[i]/this.pace.aggr); + }; + P.resize=function(){ + var bottom=this.y-this.h/2,size=(.6+.4*this.hp/this.max_hp)*this.teleportScale; + this.w=W*size;this.h=H*size;this.y=bottom+this.h/2; + }; + P.slime=function(c,blueOnly){ + var spike=!blueOnly&&this.expert&&c.rng.chance(.25),kind=spike?'spiked_slime':'slime'; + // Sourced ordinary pre-Hardmode NPC statistics; volley timing remains provisional. + var m={id:++this.nextId,kind:kind,x:this.x+c.rng.uniform(-this.w*.35,this.w*.35), + y:Math.max(.3,this.y-this.h*.25),vx:c.rng.uniform(-2,2),vy:c.rng.uniform(3,5), + w:.75,h:.5,hp:spike?100:this.expert?50:25,max_hp:spike?100:this.expert?50:25, + defense:spike?5:2,dmg:TR.paceDmg(this,spike?28:this.expert?14:7),knockbackResist:spike||this.expert?.1:0, + aggressive:spike,face:c.rng.chance(.5)?1:-1,drop:'heart_star',timer:c.rng.uniform(.1,.6),spikeTimer:c.rng.uniform(.8,1.5)}; + this.minions.push(m);c.emit(spike?'spiked_slime_spawn':'slime_spawn',m.x,m.y); + }; + P.onNailHit=function(c,base,dir,f,part){ + if(this.invulnerable||this.hidden||this.st==='dead')return null; + var old=this.hp,result=TR.damageBoss(this,c,base,part); + if(this.hp===old)return result; + if(!this.hp){var deathCount=4+c.rng.int(4);for(var j=0;j125*TR.TILE)return {x:b.x,y:c.body.y}; + var surfaces=[[0,BB.ARENA.W,0]].concat(TR.platforms(c)); + function candidates(lo,hi){ + var result=[];surfaces.forEach(function(p){ + for(var x=Math.max(.5,p[0]);x<=Math.min(BB.ARENA.W-.5,p[1]);x+=TR.TILE){ + var d=Math.max(Math.abs(x-b.x),Math.abs(p[2]-b.y)); + if(d>=lo*TR.TILE&&d<=hi*TR.TILE&&los(x,p[2]+self.h/2)&& + (!TR.solidAt||!TR.solidAt(c,x,p[2]+TR.TILE,{platforms:true})))result.push({x:x,y:p[2]}); + } + });return result; + } + var spots=candidates(7,10);if(!spots.length)spots=candidates(2,6); + return spots.length?spots[c.rng.int(spots.length)]:{x:b.x,y:c.body.y}; + }; + P.startTeleport=function(c){ + this.target=this.teleportSpot(c);this.move='teleport';this.teleportWait=0;this.vx=this.vy=0; + this.go(c,'antic',1,'teleport');c.emit('teleport_disappear',this.x,this.y); + }; + P.jump=function(c){ + this.move=['jump','jump','low_jump','high_jump'][this.jumpIndex++%4]; + this.f=c.body.x>=this.x?1:-1;this.target=c.body.centre(); + this.vx=this.f*(this.move==='low_jump'?4.5:this.move==='high_jump'?3.5:4)*TR.PX; + this.vy=(this.move==='low_jump'?6:this.move==='high_jump'?13:8)*TR.PX; + this.go(c,'attack',0,this.move); + }; + P.updateMinions=function(c){ + var dt=BB.DT,b=c.body.centre(),self=this; + this.minions=this.minions.filter(function(m){ + if(m.hp<=0)return false;var oldFeet=m.y-m.h/2;m.timer-=dt;m.spikeTimer-=dt; + m.vy=Math.max(-10*TR.PX,m.vy-GRAVITY*dt);m.x=BB.clamp(m.x+m.vx*dt,m.w/2,BB.ARENA.W-m.w/2);m.y+=m.vy*dt; + var ground=0;TR.platforms(c).forEach(function(p){if(m.x>=p[0]&&m.x<=p[1]&&oldFeet>=p[2]&&m.y-m.h/2<=p[2]&&m.vy<=0&&c.body.y>=p[2])ground=Math.max(ground,p[2]);}); + if(m.y-m.h/2<=ground){ + m.y=ground+m.h/2;m.vy=0;m.vx*=.8; + if(m.kind==='spiked_slime'&&Math.hypot(b.x-m.x,b.y-m.y)<7&&m.spikeTimer<=0){ + for(var k=-1;k<=1;k++){var dx=b.x-m.x,dy=b.y-m.y,a=Math.atan2(dy,dx)+k*.22; + self.shots.push({id:++self.nextId,kind:'slime_spike',x:m.x,y:m.y,vx:Math.cos(a)*9,vy:Math.sin(a)*9, + r:.12,life:5,dmg:TR.paceDmg(self,36),gravity:9,solidCollision:true,collidePlatforms:false,sourceMinion:m.id});} + m.spikeTimer=1.5;c.emit('slime_spikes',m.x,m.y); + } + if(m.timer<=0){ + if(m.aggressive||m.hp=m.x?1:-1; + m.vy=6*TR.PX;m.vx=m.face*2*TR.PX;m.timer=1; + } + } + return true; + }); + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var dt=BB.DT; + var obstructed=TR.lineOfSight&&!TR.lineOfSight(c,this.x,this.y,c.body.x,c.body.y+.65); + var teleporting=this.move==='teleport'&&(this.st==='antic'||this.st==='recover'); + if(!teleporting&&(obstructed||Math.abs(c.body.y-(this.y+this.h/2))>10*TR.TILE))this.teleportWait+=dt; + // Timer pauses when reachable and is consumed only once King Slime is grounded. + if(teleporting){ + if(this.st==='antic'){ + this.teleportScale=Math.max(.02,Math.max(0,this.timer));this.resize(); + this.hidden=this.timer<=1e-9;this.invulnerable=this.hidden; + if(this.timer<=1e-9){this.x=this.target.x;this.floor=this.target.y;this.y=this.floor+this.h/2; + this.go(c,'recover',.5,'teleport');c.emit('teleport',this.x,this.floor);} + }else{ + this.hidden=false;this.invulnerable=false;this.teleportScale=BB.clamp(1-this.timer/.5,.02,1);this.resize(); + if(this.timer<=1e-9){this.teleportScale=1;this.resize();this.jumpIndex=0;this.groundTicks=0;this.move=null;this.go(c,'idle',1);} + } + }else if(this.st==='attack'){ + var feet=this.y-this.h/2;this.vy=Math.max(-10*TR.PX,this.vy-GRAVITY*dt); + this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2);this.y+=this.vy*dt; + var floor=0;TR.platforms(c).forEach(function(p){ + if(this.vy<=0&&this.x+this.w/2>p[0]&&this.x-this.w/2=p[2]&&this.y-this.h/2<=p[2]&&c.body.y>=p[2]-.1)floor=Math.max(floor,p[2]); + },this); + if(this.y-this.h/2<=floor){this.floor=floor;this.y=floor+this.h/2;this.vx=this.vy=0;this.groundTicks=0; + this.go(c,'recover',this.jumpCooldown()/60);c.emit('boss_land_hard',this.x,this.floor);} + }else{ + this.y=this.floor+this.h/2;this.groundTicks++;this.timer=Math.max(0,(this.jumpCooldown()-this.groundTicks)/60); + if(this.floor>0&&c.body.y=5/this.pace.aggr-1e-9)this.startTeleport(c);else if(!this.timer)this.jump(c); + } + this.updateMinions(c); + }; + P.hazards=function(){ + if(this.st==='dead')return []; + var contact=this.hidden?[]:[{kind:'king_slime',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}]; + return contact.concat(TR.extraHazards(this)); + }; + BB.CASES['terraria/king_slime'] = TR.register('king_slime','Bouncing Gel Giant',KingSlime,'forest'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/kit.js b/environments/games/web/games/terraria_remake/bosses/kit.js new file mode 100644 index 0000000000000000000000000000000000000000..334bee8f1fdce39bada8a2906ddf515749fd6f48 --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/kit.js @@ -0,0 +1,24 @@ +(function(g){ + var BB=g.BB,TR=BB.TR;BB.CASES=BB.CASES||{}; + TR.boss=function(P,spec){ + BB.bossKit(P,spec,{idle:'idle',antic:'telegraph',attack:'active',recover:'recovery',transform:'telegraph',dead:'recovery'}); + P.setup=function(c,x,y,w,h){ + this.k=BB.knobs(spec.difficulty,c.d>=.75?1:.5);this.pace=TR.pace(c,spec.id);this.hp=this.max_hp=Math.round(this.k.hp);this.dmg=Math.round(this.k.dmg);this.defense=this.k.defense||0; + this.x=x;this.y=y;this.w=w;this.h=h;this.vx=0;this.vy=0;this.f=-1; + this.st='idle';this.timer=0.8;this.stT=0;this.move=null;this.phase=1;this.hitFlash=0;this.track={};this.cycle={};this.stamp=0;this.lastActive=null; + this.minions=[];this.shots=[];this.pickups=[];this.nextId=0;this.target={x:x,y:y}; + var dawn=c.options&&c.options.dawn_in_seconds; + this.nightTicks=Number.isFinite(dawn)?32400-BB.clamp(dawn,0,540)*60:0; + }; + P.bodyBox=function(){return TR.box(this);}; + P.onNailHit=function(c,base,dir,f,part){return TR.damageBoss(this,c,base,part);}; + P.state=function(){var role=this.role();return TR.snapshot(this,{fsm:this.st,role:role,telegraph_left:role==='telegraph'?BB.r4(Math.max(0,this.timer)):0,hazards:this.hazards()});}; + P.begin=function(c,move,target){this.target=target||c.body.centre();this.move=move;this.go(c,'antic',this.k.telegraph,move);}; + P.recover=function(c,scale){this.vx=this.vy=0;this.go(c,'recover',this.k.recovery*(scale||1));}; + P.clock=function(c){this.flash(BB.DT);this.timer-=BB.DT;this.stT+=BB.DT;this.nightTicks++;TR.updateShots(this,c);}; + }; + TR.register=function(id,title,Boss,arena,platforms){ + BB.CASES=BB.CASES||{}; + return {title:title,Body:BB.Adventurer,Boss:Boss,arena:arena,platforms:platforms||[[2,25,2.4],[4,23,5.3]]}; + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/queen_bee.js b/environments/games/web/games/terraria_remake/bosses/queen_bee.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ebc9beecece4190cad3354f221368cef33aa18 --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/queen_bee.js @@ -0,0 +1,128 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.queen_bee; + // Desktop 1.4.5.8 ordinary single-player Classic / Expert Queen Bee (aiStyle 43). + // Published: life 3400/4760, contact 30/54, stinger 22/44, defense 8 (Expert 8-28 with lost health), knockback + // immune, 120 % scale, the opening attack is always the triple charge, 6/12/18 bees, Poisoned on stingers 1/3 10 s + // (Expert 100 % 2-20 s, contact 2-8 s). Unpublished (estimates): charge/stinger speeds, + // intervals, stinger count, hover offsets and the Expert speed-up curve. + var W=66/32*1.2,H=66/32*1.2; + function QueenBee(){} + var P=QueenBee.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,21,10,W,H);this.expert=this.k.expert>=.5; + this.hp=this.max_hp=TR.paceHp(this,this.expert?4760:3400);this.dmg=TR.paceDmg(this,this.expert?54:30); + this.stingerDmg=TR.paceDmg(this,this.expert?44:22);this.defense=8; + this.knockbackResist=1;this.sourceProfile=this.expert?'desktop-expert':'desktop-classic'; + this.chargesLeft=0;this.side=1;this.cycleIndex=0;this.volleyLeft=0;this.volleyTimer=0;this.beeBatch=0;this.beesLeft=0; + this.hoverT=0;this.lockY=null;this.charge=null;this.hold=0;this.align=0;this.spawnTimer=0; + // The source opening attack: always the horizontal charge first. + this.startCharges(c); + }; + // Expert grows faster and more relentless as health drops (published qualitatively; this 0..1 curve is ours). + P.rage=function(){return this.expert?BB.clamp(1-this.hp/this.max_hp,0,1):0;}; + P.updateArmor=function(){this.defense=this.expert?8+Math.round(20*this.rage()):8;}; + P.startCharges=function(c){ + var r=this.rage();this.chargesLeft=this.expert?(r>=.9?6:r>=.75?5:r>=.5?4:3):3; + this.side=c.body.x>=this.x?-1:1;this.move='charge';this.go(c,'antic',0,'charge');this.align=0; + }; + // Charge speed is fixed in Classic and increases as health falls in Expert. Hard scales cadence, damage, and health. + P.chargeSpeed=function(){return (18+9*this.rage())*TR.PX;}; + // How long she holds the lined-up pose before a charge (estimate; the source game shows a brief pause while she + // lines up). Expert shortens it as health drops; tier aggression shortens it, never below 0.15 s. + P.windup=function(){return Math.max(.15,(this.expert?.32-.14*this.rage():.32)/this.pace.aggr);}; + P.nextAttack=function(c){ + // After the opening charges the source cycles through its three patterns; ours: summon, stingers, charge. + var order=['summon','stingers','charge'],next=order[this.cycleIndex++%3]; + if(next==='charge')this.startCharges(c); + else if(next==='summon'){ + this.move='summon';this.beeBatch=[6,12,18][c.rng.int(3)];this.beesLeft=this.beeBatch;this.spawnTimer=.35/this.pace.aggr; + this.hoverT=0;this.go(c,'idle',0,'summon');c.emit('queen_bee_buzz',this.x,this.y); + }else{ + this.move='stingers';this.volleyLeft=this.expert?12:8;this.volleyTimer=.7/this.pace.aggr;this.hoverT=0; + this.go(c,'recover',0,'stingers'); + } + }; + P.spawnBee=function(c){ + var big=this.expert&&c.rng.chance(.3),hp=big?24:this.expert?12:10,dmg=TR.paceDmg(this,big?24:this.expert?18:15); + var a=c.rng.uniform(0,Math.PI*2); + this.minions.push({id:++this.nextId,kind:big?'big_bee':'bee',x:this.x,y:this.y-H*.3,vx:TR.cos(a)*3,vy:TR.sin(a)*3, + w:big?.6:.45,h:big?.6:.45,hp:hp,max_hp:hp,dmg:dmg,defense:big?5:2,knockbackResist:.5,floating:true,drop:'heart_star', + debuff:this.expert?'poisoned':null,debuffChance:1,debuffDuration:[2,6],life:12}); + c.emit('bee_spawn',this.x,this.y); + }; + P.fireStinger=function(c){ + var b=c.body.centre(),dx=b.x-this.x,dy=b.y-(this.y-H*.35),u=TR.dir(dx,dy,c.rng.uniform(-.06,.06)),speed=(this.expert?15:12)*TR.PX*this.pace.speed; + this.shots.push({id:++this.nextId,kind:'bee_stinger',x:this.x,y:this.y-H*.35,vx:u.x*speed,vy:u.y*speed,speed:speed, + r:.16,life:4,dmg:this.stingerDmg,solidCollision:true,collidePlatforms:false, + debuff:'poisoned',debuffChance:this.expert?1:1/3,debuffDuration:this.expert?[2,20]:[10,10]}); + c.emit('bee_stinger',this.x,this.y); + }; + P.updateBees=function(c,b){ + var dt=BB.DT,self=this; + this.minions=this.minions.filter(function(m){ + if(m.hp<=0){if(TR.dropMinion)TR.dropMinion(c,self,m);return false;} + m.life-=dt;if(m.life<=0)return false; + // Bees home in with a little wobble; they stay inside the arena. + var wob=TR.sin((c.t+m.id*17)*.15)*.8; + TR.moveToward(m,b.x+wob,b.y+.3,(m.kind==='big_bee'?6:7.5)*self.pace.speed,14);return true; + }); + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var dt=BB.DT,b=c.body.centre(),self=this; + this.updateArmor(); + if(this.move==='charge'){ + var sp=this.chargeSpeed(),edge=BB.ARENA.W-this.w/2; + if(this.st==='antic'){ + // Align with the player’s height, then lock the lane during the windup and horizontal dash. + var tx=BB.clamp(b.x+this.side*9,this.w/2,edge),ty=BB.clamp(b.y,this.h/2,BB.ARENA.H-this.h/2); + if(this.hold>0){ + this.vx*=.8;this.vy=0;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,edge);this.y=this.lockY;this.hold+=dt; + }else{ + TR.moveToward(this,tx,ty,(16+6*this.rage())*TR.PX*this.pace.speed,60*this.pace.aggr); + this.align+=dt; + if(Math.abs(this.y-ty)<.45&&Math.abs(this.x-tx)<2.2){this.hold=dt;this.lockY=this.y;this.vy=0;} + } + if(this.hold>=this.windup()||this.align>1.6/this.pace.aggr+this.windup()){ + this.hold=0;this.f=b.x>=this.x?1:-1;this.vx=this.f*sp;this.vy=0;this.lockY=this.y;this.go(c,'attack',0,'charge');c.emit('queen_bee_charge',this.x,this.y); + } + }else if(this.st==='attack'){ + this.x+=this.vx*dt;this.y=this.lockY; + // A charge ends past the player (or at the wall); she brakes and turns for the next one. + var past=this.f>0?this.x>b.x+6:this.x=edge){ + this.x=BB.clamp(this.x,this.w/2,edge);this.chargesLeft--;this.vx*=.3; + if(this.chargesLeft>0){this.side=this.f;this.go(c,'recover',(this.expert?.18:.3)/this.pace.aggr,'charge');} + else{this.go(c,'recover',.5/this.pace.aggr,'charge_end');} + } + }else if(this.st==='recover'){ + this.vx*=.85;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,edge); + if(this.timer<=0){if(this.move==='charge'){this.f=b.x>=this.x?1:-1;this.go(c,'antic',0,'charge');this.align=0;}} + } + }else if(this.move==='charge_end'){ + this.vx*=.85;this.x=BB.clamp(this.x+this.vx*dt,this.w/2,BB.ARENA.W-this.w/2); + if(this.timer<=0)this.nextAttack(c); + }else if(this.move==='summon'){ + // Hover above the player and release the batch over time. + TR.moveToward(this,b.x,Math.min(BB.ARENA.H-this.h/2,b.y+6),7*TR.PX*this.pace.speed,8); + this.hoverT+=dt;this.spawnTimer-=dt; + if(this.beesLeft>0&&this.spawnTimer<=0){this.spawnBee(c);this.beesLeft--;this.spawnTimer=(this.expert?.16:.22)/this.pace.aggr;} + if(this.beesLeft<=0&&this.hoverT>.6)this.nextAttack(c); + }else if(this.move==='stingers'){ + // Hornet-like: drift above and to the side of the player and fire stingers down at them. + this.hoverT+=dt;var sway=TR.sin(this.hoverT*1.4)*6; + TR.moveToward(this,BB.clamp(b.x+sway,this.w/2,BB.ARENA.W-this.w/2),Math.min(BB.ARENA.H-this.h/2,b.y+5.5),9*TR.PX*this.pace.speed,10); + this.volleyTimer-=dt; + if(this.volleyTimer<=0&&this.volleyLeft>0){this.fireStinger(c);this.volleyLeft--;this.volleyTimer=(this.expert?.32-.12*this.rage():.45)/this.pace.aggr;} + if(this.volleyLeft<=0&&this.volleyTimer<=-.4)this.nextAttack(c); + } + this.updateBees(c,b); + }; + P.onNailHit=function(c,base,dir,f,id){this.updateArmor();return TR.damageBoss(this,c,base,id);}; + P.hazards=function(){ + if(this.st==='dead')return []; + var body={kind:this.move==='charge'&&this.st==='attack'?'queen_bee_charge':'queen_bee',box:this.bodyBox(),dmg:this.dmg,fromX:this.x}; + if(this.expert){body.debuff='poisoned';body.debuffChance=1;body.debuffDuration=[2,8];} + return [body].concat(TR.extraHazards(this)); + }; + BB.CASES['terraria/queen_bee'] = TR.register('queen_bee','Charging Giant Bee',QueenBee,'hive'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/bosses/skeletron.js b/environments/games/web/games/terraria_remake/bosses/skeletron.js new file mode 100644 index 0000000000000000000000000000000000000000..e8724b06a2948ac71a77fd9e9b1e60d3f76d0680 --- /dev/null +++ b/environments/games/web/games/terraria_remake/bosses/skeletron.js @@ -0,0 +1,110 @@ +(function(g){ + var BB=g.BB,TR=BB.TR,S=BB.SPECS.skeletron; + function Skeletron(){} + var P=Skeletron.prototype;TR.boss(P,S); + P.reset=function(c){ + this.setup(c,18,10.5,80/32,102/32);this.expert=this.k.expert>=0.5;this.easyScale=1; + this.hp=this.max_hp=TR.paceHp(this,this.expert?8800:4400);this.dmg=TR.paceDmg(this,this.expert?70:32); + this.k.hp=this.max_hp;this.k.dmg=this.dmg;this.k.def_factor=this.expert?0.75:0.5; + this.k.hand_hp=TR.paceHp(this,this.expert?1560:600);this.skullTimer=80/60;this.skullFrames=0;this.headFrames=0; + this.handIndex=0;this.enraged=false;this.spinSpeed=0; + // Tier aggression stretches the hover / hand cadences and scales chase and hand speeds (tiers.js). + this.hoverFrames=Math.round(800/this.pace.aggr);this.handGap=Math.round((this.expert?200:300)/this.pace.aggr); + var offset=Math.round((this.expert?100:150)/this.pace.aggr); + this.hands=[-1,1].map(function(side,n){return {id:'hand'+n,side:side,x:18+side*3,y:7.8,vx:0,vy:0, + w:52/32,h:52/32,hp:this.k.hand_hp,max_hp:this.k.hand_hp,defense:14,st:'idle',timer:0, + wait:n*offset/60,waitFrames:n*offset,attackIndex:n,target:{x:0,y:0}};},this); + this.go(c,'idle',this.hoverFrames/60);this.defense=this.armor(); + }; + P.hitTargets=function(){return [{id:'head',box:this.bodyBox()}].concat(this.hands.filter(function(h){return h.hp>0;}) + .map(function(h){return {id:h.id,box:TR.box(h)};}));}; + P.armor=function(){return this.enraged?9999:(this.st==='attack'?0:10)+ + (this.expert?this.hands.filter(function(h){return h.hp>0;}).length*25:0);}; + P.onNailHit=function(c,base,dir,f,id){ + if(this.hp<=0)return null;var hand=this.hands.find(function(h){return h.id===id;}); + if(hand){ + if(hand.hp<=0)return null; + var hit=TR.rollDetails(c,base,14,0.5,0.04);hand.hp=Math.max(0,hand.hp-hit.damage);TR.emitHit(c,'boss_hit',hand.x,hand.y,hit.damage,hit.critical); + if(!hand.hp)c.emit('hand_destroyed',hand.x,hand.y);this.defense=this.armor();return 'flesh'; + } + this.defense=this.armor();return TR.damageBoss(this,c,base,id); + }; + P.chaseSpeed=function(b){ + var alive=this.hands.filter(function(h){return h.hp>0;}).length,speed=2*TR.PX*this.pace.speed; + if(this.expert){ + speed*=10/3;speed*=1+(2-alive)*0.05; + var tiles=Math.hypot(this.x-b.x,this.y-b.y)/TR.TILE; + if(tiles>=9.375)speed*=Math.min(2.6,Math.pow(1.1,Math.floor((tiles-9.375)/3.125)+1)); + }return speed; + }; + P.spawnSkull=function(c){ + TR.shoot(this,c,this.x,this.y,3*TR.PX,'homing_skull',true); + var p=this.shots[this.shots.length-1];p.dmg=TR.paceDmg(this,68);p.solidCollision=true;p.collidePlatforms=false;p.life=10; + }; + P.beginHand=function(c,h,b){ + h.attackIndex++;h.attackAxis=h.attackIndex%2?'vertical':'horizontal'; + h.target={x:b.x,y:b.y};h.st='antic';h.timer=0; + c.emit(h.attackAxis==='vertical'?'hand_vertical_antic':'hand_horizontal_antic',h.x,h.y); + }; + P.updateHand=function(c,h,b){ + if(h.hp<=0)return;var dt=BB.DT,speedMul=(this.expert?1.16:1)*this.pace.speed;h.timer-=dt; + if(this.st==='attack'){ + h.st='idle';TR.moveToward(h,this.x+h.side*3.2,this.y-2.8,(this.expert?8:5)*TR.PX*this.pace.speed,35);return; + } + if(h.st==='idle'){ + h.waitFrames++;h.wait=h.waitFrames/60;TR.moveToward(h,this.x+h.side*3.2,this.y-2.8,(this.expert?8:5)*TR.PX*this.pace.speed,25); + if(h.waitFrames>=this.handGap){h.wait=0;h.waitFrames=0;this.beginHand(c,h,b);} + }else if(h.st==='antic'){ + // Preparation is physical alignment, not an added stationary telegraph timer. + var ax=h.attackAxis==='vertical'?b.x:BB.clamp(this.x+h.side*6,h.w/2,BB.ARENA.W-h.w/2); + var ay=h.attackAxis==='vertical'?Math.min(BB.ARENA.H-h.h/2,this.y+2):b.y; + TR.moveToward(h,ax,ay,9*TR.PX*speedMul,40); + if(Math.hypot(ax-h.x,ay-h.y)<0.6){ + h.target={x:b.x,y:b.y};h.st='attack';h.timer=0.7; + if(h.attackAxis==='vertical'){ + h.vx=BB.clamp((b.x-h.x)/Math.max(0.15,Math.abs(b.y-h.y)/(15*TR.PX*speedMul)),-16*TR.PX*speedMul,16*TR.PX*speedMul); + h.vy=-15*TR.PX*speedMul; + }else{h.vx=(b.x=BB.ARENA.W-h.w/2))h.st='return'; + }else if(h.st==='return'){ + var rx=BB.clamp(this.x+h.side*3.2,h.w/2,BB.ARENA.W-h.w/2),ry=BB.clamp(this.y-2.8,h.h/2,BB.ARENA.H-h.h/2); + TR.moveToward(h,rx,ry,(this.expert?12:8)*TR.PX*this.pace.speed,40); + if(Math.hypot(h.x-rx,h.y-ry)<1)h.st='idle'; + } + }; + P.update=function(c){ + if(this.st==='dead')return;this.clock(c);var b=c.body.centre(),alive=this.hands.filter(function(h){return h.hp>0;}); + // Starting at 19:30, dawn is nine real-time minutes later. The finite benchmark may end first. + if((TR.isDaytime?TR.isDaytime(c):c.t>=9*60*60)&&!this.enraged){this.enraged=true;this.go(c,'attack',1e9,'spin');c.emit('skeletron_day_enrage',this.x,this.y);} + if(this.st==='idle'){ + this.headFrames++; + TR.moveToward(this,b.x,Math.min(BB.ARENA.H-this.h/2,b.y+250/32),(this.expert?4:2)*TR.PX*this.pace.speed,this.expert?15:6); + if(this.expert&&(alive.length<2||this.hp/this.max_hp<0.75)){ + this.skullFrames++;this.skullTimer=((alive.length===0?40:80)-this.skullFrames)/60; + if(this.skullFrames>=(alive.length===0?40:80)){this.spawnSkull(c);this.skullFrames=0;this.skullTimer=(alive.length===0?40:80)/60;} + } + if(this.headFrames>=this.hoverFrames){this.headFrames=0;this.go(c,'attack',400/60,'spin');c.emit('skeletron_roar',this.x,this.y);} + }else if(this.st==='attack'){ + this.headFrames++; + this.spinSpeed=this.enraged?20*TR.PX:this.chaseSpeed(b); + TR.moveToward(this,b.x,b.y,this.spinSpeed,this.enraged?100:60); + if(!this.enraged&&this.headFrames>=400){this.headFrames=0;this.go(c,'idle',this.hoverFrames/60);this.move=null;} + } + this.hands.forEach(function(h){this.updateHand(c,h,b);},this);this.defense=this.armor(); + }; + P.hazards=function(){ + if(this.st==='dead')return []; + var head={kind:this.st==='attack'?'skull_spin':'skull',box:this.bodyBox(),fromX:this.x, + dmg:this.enraged?9999:TR.paceDmg(this,this.expert?(this.st==='attack'?91:70):32)}; + if(this.expert){head.debuff='bleeding';head.debuffChance=1;head.debuffDuration=[12,20];} + return [head].concat(this.hands.filter(function(h){return h.hp>0;}).map(function(h){ + var hit={kind:'hand',box:TR.box(h),dmg:TR.paceDmg(this,this.expert?44:20),fromX:h.x}; + if(this.expert){hit.debuff='slow';hit.debuffChance=0.5;hit.debuffDuration=[1,2];}return hit; + },this),TR.extraHazards(this)); + }; + BB.CASES['terraria/skeletron'] = TR.register('skeletron','Twin-Handed Giant Skull',Skeletron,'dungeon'); +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/adventurer.js b/environments/games/web/games/terraria_remake/draw/adventurer.js new file mode 100644 index 0000000000000000000000000000000000000000..c5a70146be97f360b5c53da592cf8229117208ec --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/adventurer.js @@ -0,0 +1,133 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2; + // Original procedural adventurer: hair, tunic, belt, boots; legs follow the simulated run speed, the cape + // follows velocity, wings appear only while flying/gliding (the simulated state), the sword arc is the hitbox. + function limb(x,ax,ay,bx,by,w,col){x.lineCap='round';x.lineWidth=w;x.strokeStyle=col;x.beginPath();x.moveTo(ax,ay);x.lineTo(bx,by);x.stroke();} + function figure(x,b,V,t){ + var f=b.facing<0?-1:1,s=V.S,run=Math.abs(b.vx)/11.25,air=!b.grounded; + var cx=V.sx(b.x),fy=V.sy(b.y),H=1.3125*s,ph=b.x*2.2; + x.save();x.translate(cx,fy);x.scale(f,1); + var hip=-H*.42,sw=air?.5:Math.sin(ph)*Math.min(1,run*1.4)*.75; + // cape + x.fillStyle='#5a2f63';x.beginPath();x.moveTo(-s*.12,-H*.78);x.quadraticCurveTo(-s*.4-run*s*.2,-H*.5,-s*.32-run*s*.35,-H*.22+(air?-s*.1:0));x.lineTo(-s*.05,-H*.3);x.closePath();x.fill(); + // legs + limb(x,-s*.05,hip,-s*.05+Math.sin(sw)*s*.22,-s*.04,s*.15,'#3a4e66'); + limb(x,s*.06,hip,s*.06-Math.sin(sw)*s*.22,-s*.04,s*.15,'#455d79'); + x.fillStyle='#3a2a20';x.fillRect(-s*.05+Math.sin(sw)*s*.22-s*.08,-s*.08,s*.2,s*.08);x.fillRect(s*.06-Math.sin(sw)*s*.22-s*.08,-s*.08,s*.2,s*.08); + // torso + x.fillStyle='#b5482f';x.beginPath();x.moveTo(-s*.17,-H*.78);x.lineTo(s*.17,-H*.78);x.lineTo(s*.2,hip);x.lineTo(-s*.2,hip);x.closePath();x.fill(); + x.fillStyle='#e8c25e';x.fillRect(-s*.2,hip-s*.06,s*.4,s*.06); + x.strokeStyle='#4a1d12';x.lineWidth=1.2;x.strokeRect(-s*.17,-H*.78,s*.34,H*.36); + // head + x.fillStyle='#efc39b';x.beginPath();x.arc(s*.02,-H*.88,s*.17,0,TAU);x.fill(); + x.fillStyle='#5b3a24';x.beginPath();x.arc(-s*.02,-H*.93,s*.18,Math.PI*.9,Math.PI*2.05);x.fill();x.fillRect(-s*.2,-H*.93,s*.1,s*.16); + x.fillStyle='#1c2430';x.fillRect(s*.09,-H*.9,s*.05,s*.05); + x.restore(); + } + function wings(x,b,V,t){ + var cx=V.sx(b.x),cy=V.sy(b.y+.9),flap=b.flying?Math.sin(t*28)*.5:.25; + [-1,1].forEach(function(k){x.save();x.translate(cx,cy);x.scale(k,1);x.rotate(-.3-flap); + for(var i=0;i<4;i++){x.fillStyle=i%2?'#d9e6ee':'#b9cbd8';x.beginPath();x.ellipse(-12-i*5,-4+i*3,12-i*1.5,4,-.5+i*.18,0,TAU);x.fill();} + x.restore();}); + } + function weapon(x,b,V,center){ + var a=b.atkT>0?b.slashAngle:Math.atan2(b.aimY-center.y,b.aimX-center.x); + x.save();x.translate(V.sx(b.x),V.sy(center.y));x.rotate(-a); + if(b.atkT>0||b.weapon==='sword'){ + x.fillStyle='#8b6a3e';x.fillRect(2,-2,8,4);x.fillStyle='#e9c35a';x.fillRect(9,-7,4,14); + x.fillStyle='#d6ecf0';x.beginPath();x.moveTo(13,-3);x.lineTo(13+V.S*2.0,-2);x.lineTo(16+V.S*2.05,0);x.lineTo(13+V.S*2.0,2);x.lineTo(13,3);x.closePath();x.fill(); + x.strokeStyle='#5d7a86';x.lineWidth=1;x.stroke(); + }else{ + x.strokeStyle='#7b4f2c';x.lineWidth=3;x.beginPath();x.arc(4,0,13,-1.15,1.15);x.stroke(); + x.strokeStyle='#efe6cf';x.lineWidth=1;x.beginPath();x.moveTo(4+13*Math.cos(-1.15),13*Math.sin(-1.15));x.lineTo(4+13*Math.cos(1.15),13*Math.sin(1.15));x.stroke(); + } + x.restore(); + } + function crosshair(x,V,b){ + var ax=V.sx(b.aimX),ay=V.sy(b.aimY);x.save();x.strokeStyle='rgba(20,20,20,.6)';x.lineWidth=3; + x.beginPath();x.arc(ax,ay,6,0,TAU);x.stroke();x.strokeStyle='#fff0b8';x.lineWidth=1.5;x.beginPath();x.arc(ax,ay,6,0,TAU);x.moveTo(ax-11,ay);x.lineTo(ax-7,ay);x.moveTo(ax+7,ay);x.lineTo(ax+11,ay);x.moveTo(ax,ay-11);x.lineTo(ax,ay-7);x.moveTo(ax,ay+7);x.lineTo(ax,ay+11);x.stroke();x.restore(); + } + // Floating combat text from the case's own events (amounts are presentation-only payloads); stateless. + function combatText(x,c,V){ + var ev=c.events;x.save();x.textAlign='center';x.font='bold 13px "Segoe UI",sans-serif'; + for(var i=ev.length-1,n=0;i>=0&&n<24;i--){var e=ev[i];if(e.t=12; + return (h%12||12)+':'+(m<10?'0':'')+m+(pm?' PM':' AM'); + } + BB.BODY_DRAW.terraria_adventurer={ + draw:function(x,c,t,V){ + var b=c.body,center=b.centre(); + D.shadow(x,V,b.x,b.y,.7,c); + if(b.hp<=0){ // Terraria leaves a tombstone where the player died + var gx=V.sx(b.x),gy=V.sy(b.y);x.save();x.fillStyle='#8d949a';x.strokeStyle='#2c3036';x.lineWidth=2; + x.beginPath();x.moveTo(gx-11,gy);x.lineTo(gx-11,gy-22);x.arc(gx,gy-22,11,Math.PI,0);x.lineTo(gx+11,gy);x.closePath();x.fill();x.stroke(); + x.fillStyle='#3b4148';x.fillRect(gx-1.5,gy-26,3,14);x.fillRect(gx-6,gy-22,12,3);x.restore();combatText(x,c,V);return;} + x.save();if(b.invul>0&&Math.floor(t*18)%2)x.globalAlpha=0.45; + if(b.flying||b.gliding)wings(x,b,V,t); + figure(x,b,V,t);weapon(x,b,V,center);x.restore(); + b.arrows.forEach(function(p){ + x.save();x.translate(V.sx(p.x),V.sy(p.y));x.rotate(-Math.atan2(p.vy,p.vx));x.fillStyle='rgba(255,240,200,.25)';x.fillRect(-20,-1,12,2); + x.fillStyle='#d9c08a';x.fillRect(-9,-1,16,2);x.fillStyle='#e9f7ee';x.beginPath();x.moveTo(11,0);x.lineTo(6,-3);x.lineTo(6,3);x.fill();x.fillStyle='#c0644a';x.fillRect(-10,-3,4,2);x.fillRect(-10,1,4,2);x.restore(); + }); + var slash=b.slashBox(); + if(slash){x.save();x.globalCompositeOperation='lighter';x.fillStyle='rgba(255,226,150,.35)';x.beginPath(); + slash.pts.forEach(function(p,n){if(n)x.lineTo(V.sx(p[0]),V.sy(p[1]));else x.moveTo(V.sx(p[0]),V.sy(p[1]));});x.closePath();x.fill();x.restore();} + crosshair(x,V,b); + combatText(x,c,V); + }, + fullHud:function(x,c,V,extra){ + var b=c.body,w=c.boss,dr=BB.BOSS_DRAW[c.id]||{},W=V.W; + x.save();x.textBaseline='alphabetic'; + // player panel (top left) + panel(x,10,8,250,62); + x.font='bold 12px "Segoe UI",sans-serif';x.fillStyle='#ffd7cf';x.fillText('Health '+b.hp+' / '+b.max_hp,18,24); + bar(x,18,29,150,8,b.hp/b.max_hp,b.hp/b.max_hp<.3?'#ff4a4a':'#e2453b','#3b1518'); + x.fillStyle='#bfe6f5';x.font='11px "Segoe UI",sans-serif';x.fillText('Flight',18,52);bar(x,46,45,122,5,b.flight/1.5,'#7fd0ec','#173040'); + x.fillStyle='#c9c4ff';x.fillText('Mana '+b.mana,18,65);bar(x,66,59,102,4,b.mana/b.max_mana,'#6f7cff','#1c1c46'); + x.fillStyle='#f3e2b2';x.font='bold 12px "Segoe UI",sans-serif';x.fillText(b.weapon==='bow'?'Bow':'Sword',180,24); + x.font='10px "Segoe UI",sans-serif';x.fillStyle='#b8c6cc';x.fillText(b.flying?'Flying':b.gliding?'Gliding':b.grounded?'Grounded':'Airborne',180,38); + var st=[],NAMES={slow:'Slow',bleeding:'Bleeding',poisoned:'Poisoned',confused:'Confused',weak:'Weak',broken_armor:'Armor broken',cursed:'Cursed',darkness:'Darkness',silenced:'Silenced'}; + Object.keys(NAMES).forEach(function(k){if(b.status[k]>0)st.push(NAMES[k]+' '+b.status[k].toFixed(1)+'s');}); + if(st.length){x.fillStyle='#ffb36b';x.fillText(st.slice(0,2).join(' '),180,52);if(st.length>2)x.fillText(st.slice(2,4).join(' '),180,64);} + // boss panel (top right) + var bw=330,bx=W-bw-10;panel(x,bx,8,bw,48); + var title=String(c.def&&c.def.title||'Boss'),f=Math.max(0,w.hp/w.max_hp),col=dr.bar?dr.bar(w):'#d8c27a'; + x.font='bold 13px Georgia,"Microsoft YaHei",serif';x.fillStyle='#f6e7c4';x.textAlign='left';x.fillText(title,bx+8,24); + x.textAlign='right';x.font='bold 12px "Segoe UI",sans-serif';x.fillStyle='#fff';x.fillText(w.hp+' / '+w.max_hp,bx+bw-8,24); + bar(x,bx+8,29,bw-16,9,f,col,'#26161a','rgba(240,220,170,.8)'); + if(w.hands){var hx=bx+8;w.hands.forEach(function(h,i){bar(x,hx+i*((bw-16)/2+2),40,(bw-16)/2-2,3,h.hp/h.max_hp,'#cdbf9a','#2a2622');});} + x.textAlign='left';x.font='11px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle='#d9e4e8'; + x.fillText(dr.phase?dr.phase(w,!!BB.TR.showCues):'',bx+8,w.hands?54:52); + // centre column, between the two panels: public tier (or the source mode for a custom d) + timer, then the + // rules, native tick rate and in-game clock, then the label + var secs=c.t/BB.FPS,mm=Math.floor(secs/60),ss=Math.floor(secs%60),tier=w.pace&&w.pace.tier,cx=(260+bx)/2, + level=tier?BB.TR.TIER_NAMES[tier]:w.expert?'Expert Expert':'Custom d='+(+c.d).toFixed(2); + x.textAlign='center';x.font='bold 12px "Segoe UI","Microsoft YaHei",sans-serif'; + x.fillStyle=w.expert?'#ff9d6b':tier==='hard'?'#ffc46b':tier==='easy'?'#a8e6b0':'#bfe3c6'; + x.fillText(level+' · '+mm+':'+(ss<10?'0':'')+ss,cx,22); + x.font='11px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle=BB.TR.isDaytime(c)?'#ffe48a':'#a9c1e8'; + x.fillText((w.expert?'Expert rules':'Classic rules')+' · '+BB.FPS+' Hz · '+(BB.TR.isDaytime(c)?'Day ':'Night ')+clock(c),cx,37); + if(extra){x.font='bold 12px "Segoe UI","Microsoft YaHei",sans-serif';x.fillStyle='#ffe7a3';x.fillText(extra,cx,54);} + // The play page draws the final live frame once before its HTML result panel opens; that frame skips the + // banner so the two never overlap. Off-page renderers (RGB observations, harness video) keep it. + var onPage=!!(x.canvas&&x.canvas.id==='view'&&g.document&&g.document.getElementById('result')); + if(c.result&&!onPage){x.font='bold 30px Georgia,serif';x.fillStyle=c.result==='win'?'#ffe08a':'#ff8a7a';x.strokeStyle='rgba(0,0,0,.7)';x.lineWidth=4; + var word=c.result==='win'?'VICTORY':c.result==='loss'?'DEFEATED':'TIME UP';x.strokeText(word,W/2,V.H/2-40);x.fillText(word,W/2,V.H/2-40);} + x.restore(); + } + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js b/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js new file mode 100644 index 0000000000000000000000000000000000000000..b040ade5f283011f5db334f64e7e30d78c20de53 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/brain_of_cthulhu.js @@ -0,0 +1,64 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2; + // Original art: a pink, folded brain with a dangling brain stem and a single eye; translucent and invulnerable + // in phase 1, it reveals a beating heart in phase 2. Creepers are veiny eyeballs with flesh tendrils. + // Expert illusions are the same drawing at the illusion opacity; only the real brain flashes when hit. + function brain(x,V,w,cx,cy,t,alpha,flash,phase){ + var s=w.w*V.S,pulse=1+Math.sin(t*(phase===2?9:3))*.03; + x.save();x.globalAlpha=alpha;x.translate(cx,cy);x.scale(pulse,pulse); + // stem + x.strokeStyle='#8a3040';x.lineWidth=s*.08;x.beginPath();x.moveTo(0,s*.25);x.quadraticCurveTo(s*.08+Math.sin(t*2)*s*.05,s*.42,-s*.04,s*.55);x.stroke(); + // lobes + x.fillStyle=D.lit(flash,phase===2?'#e58c98':'#d98a9c');x.beginPath();x.ellipse(0,0,s*.5,s*.36,0,0,TAU);x.fill(); + x.strokeStyle='#6a1f2c';x.lineWidth=2;x.stroke(); + x.strokeStyle='rgba(120,30,50,.7)';x.lineWidth=1.6; + for(var k=0;k<6;k++){var yy=-s*.28+k*s*.11;x.beginPath();x.moveTo(-s*.45,yy); + for(var j=0;j<6;j++)x.quadraticCurveTo(-s*.4+j*s*.16,yy+((j+k)%2?-1:1)*s*.06,-s*.32+j*s*.16,yy);x.stroke();} + x.strokeStyle='#6a1f2c';x.lineWidth=2;x.beginPath();x.moveTo(0,-s*.35);x.quadraticCurveTo(s*.04,0,0,s*.3);x.stroke(); + if(phase===2){ + // the exposed heart + var hb=1+Math.max(0,Math.sin(t*9))*.18;x.save();x.translate(0,s*.12);x.scale(hb,hb); + x.fillStyle='#b8202e';x.beginPath();x.moveTo(0,s*.12);x.bezierCurveTo(-s*.2,-s*.02,-s*.1,-s*.18,0,-s*.07);x.bezierCurveTo(s*.1,-s*.18,s*.2,-s*.02,0,s*.12);x.fill(); + x.strokeStyle='#4a0810';x.lineWidth=1.5;x.stroke();x.restore(); + }else{ + x.fillStyle='#f2e4d6';x.beginPath();x.arc(s*.18,-s*.02,s*.11,0,TAU);x.fill(); + x.fillStyle='#7a1a2a';x.beginPath();x.arc(s*.21,-s*.02,s*.05,0,TAU);x.fill(); + } + x.restore(); + } + function creeper(x,V,m,t){ + var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,a=m.st==='charge'?Math.atan2(-m.vy,m.vx):Math.sin(t*2+m.id); + x.save();x.translate(cx,cy);x.rotate(a); + x.strokeStyle='#7a2232';x.lineWidth=2; + for(var k=-1;k<=1;k++){x.beginPath();x.moveTo(-r*.7,k*r*.3);x.quadraticCurveTo(-r*1.5,k*r*.6+Math.sin(t*12+k+m.id)*3,-r*2,k*r*.9);x.stroke();} + x.fillStyle=m.hitT>0?'#fff':'#c9505e';x.beginPath();x.arc(0,0,r,0,TAU);x.fill();x.strokeStyle='#4a1020';x.lineWidth=1.5;x.stroke(); + // health ring: a Creeper the player has hit shows how much is left (the source game draws per-NPC bars) + if(m.hp0)creeper(x,V,m,t);}); + (w.pickups||[]).length&&D.extras(x,{boss:{minions:[],shots:[],pickups:w.pickups}},t,V); + },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return; + // Expert illusions first (behind), the real brain on top. A fading (teleporting) brain is drawn at its fade. + if(w.phase===2&&w.illusions&&w.illusions.length){ + w.illusions.forEach(function(p){brain(x,V,w,V.sx(p.x),V.sy(p.y),t,w.illusionAlpha*w.fade,false,2);}); + } + var alpha=(w.phase===1?.55:1)*Math.max(.15,w.fade); + brain(x,V,w,V.sx(w.x),V.sy(w.y),t,alpha,w.hitFlash>0,w.phase); + },bar:function(w){return w.phase===2?'#d0454f':'#d98a9c';}, + phase:function(w){ + var alive=w.minions.filter(function(m){return m.kind==='creeper'&&m.hp>0;}); + if(w.phase===1){ + // The HUD bar is the brain + Creeper total; spell out where the remaining health sits. + var creepers=alive.reduce(function(a,m){return a+m.hp;},0); + return 'Phase 1 · core invulnerable · guard eyes '+alive.length+'/20 ('+creepers+')· core '+w.brainHp; + } + return 'Phase 2 · core '+w.brainHp+'/'+w.brainMax+(w.expert?' · clones':''); + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js b/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js new file mode 100644 index 0000000000000000000000000000000000000000..1803f53cdcf1b9b0e0a7447e5b30cc582e3bb48d --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/eater_of_worlds.js @@ -0,0 +1,47 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW; + var TAU=Math.PI*2; + // Original art: armoured corrupt segments, a head with mandibles and a spiked tail. Each segment faces the + // segment in front of it; coiled (not yet visible) and underground segments are not drawn. + function segment(x,s,len,flash,t){ + var r=len*.5; + if(s.type==='tail'){ + x.beginPath();x.moveTo(r*.9,-r*.75);x.quadraticCurveTo(-r*.2,-r*.7,-r*1.3,0);x.quadraticCurveTo(-r*.2,r*.7,r*.9,r*.75);x.closePath(); + x.fillStyle=D.lit(flash,'#6d4f7d');x.fill();x.lineWidth=2;x.strokeStyle='#22162b';x.stroke(); + x.strokeStyle='#a27fb3';x.lineWidth=1.5;x.beginPath();x.moveTo(r*.5,-r*.45);x.quadraticCurveTo(-r*.1,0,r*.5,r*.45);x.stroke();return; + } + x.beginPath();x.ellipse(0,0,r*1.02,r*.92,0,0,TAU);x.fillStyle=D.lit(flash,s.type==='head'?'#7a5a8c':'#6d4f7d');x.fill(); + x.lineWidth=2;x.strokeStyle='#22162b';x.stroke(); + x.fillStyle='rgba(190,160,205,.55)';x.beginPath();x.ellipse(0,-r*.35,r*.75,r*.3,0,0,TAU);x.fill(); + x.strokeStyle='#3a2647';x.lineWidth=1.5;x.beginPath();x.moveTo(-r*.25,-r*.88);x.quadraticCurveTo(-r*.45,0,-r*.25,r*.88);x.stroke(); + x.beginPath();x.moveTo(r*.3,-r*.86);x.quadraticCurveTo(r*.1,0,r*.3,r*.86);x.stroke(); + if(s.type==='head'){ + var bite=Math.sin(t*9)*.18; + [-1,1].forEach(function(k){ + x.save();x.translate(r*.75,k*r*.45);x.rotate(k*(.35+bite)); + x.beginPath();x.moveTo(0,-r*.16*k);x.quadraticCurveTo(r*.75,-r*.1*k,r*.95,r*.25*k);x.quadraticCurveTo(r*.55,r*.08*k,0,r*.18*k);x.closePath(); + x.fillStyle='#d9cc9b';x.fill();x.lineWidth=1.5;x.strokeStyle='#2a1f12';x.stroke();x.restore(); + }); + x.fillStyle='#f2e27a';[-1,1].forEach(function(k){x.beginPath();x.arc(r*.42,k*r*.42,r*.11,0,TAU);x.fill();}); + x.fillStyle='#2a1030';x.beginPath();x.ellipse(r*.86,0,r*.14,r*.22,0,0,TAU);x.fill(); + } + } + BB.BOSS_DRAW['terraria/eater_of_worlds']={hazards:D.extras,body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return; + var lookup={},fronts={};w.segments.forEach(function(s){lookup[s.id]=s;}); + w.chains.forEach(function(ch){for(var i=1;i0; + w.segments.slice().reverse().forEach(function(s){if(s.hp<=0||s.visible===false||s.y<=-s.h/2)return; + var front=fronts[s.id],dx=front?front.x-s.x:s.vx||0,dy=front?front.y-s.y:s.vy||0; + x.save();x.translate(V.sx(s.x),V.sy(s.y));x.rotate(-Math.atan2(dy,dx||1e-6)); + segment(x,s,s.w*V.S,flash,t);x.restore(); + }); + // dirt bursts where a head is digging just below the surface (presentation only) + w.chains.forEach(function(ch){var h=lookup[ch.ids[0]];if(!h||h.y>.4||h.y<-2.5)return; + x.fillStyle='rgba(98,71,53,.8)';for(var k=0;k<5;k++){var px=V.sx(h.x)+Math.sin(t*13+k*2.3)*14,py=V.sy(0)-Math.abs(Math.sin(t*9+k))*10;x.fillRect(px,py,3,3);}}); + },bar:function(){return '#b07fc4';}, + phase:function(w){ + var alive=w.segments.filter(function(s){return s.hp>0;}).length; + return w.chains.length+' worms · '+alive+' segments alive'; + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js b/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js new file mode 100644 index 0000000000000000000000000000000000000000..0b2d27e95aa12615958d93ca305531f61a3dd700 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/eye_of_cthulhu.js @@ -0,0 +1,52 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW; + var TAU=Math.PI*2; + // Original art: an eyeball with trailing nerve tendrils; the second form shows a toothed maw. + // Orientation follows the simulated charge velocity, the transform spin, or the player while hovering. + BB.BOSS_DRAW['terraria/eye_of_cthulhu']={hazards:function(x,c,t,V){ + var w=c.boss;if(w.st==='antic')D.cue(x,V,w,w.target,'#f39783');D.extras(x,c,t,V); + },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead'||w.despawned)return; + var b=c.body.centre(),a; + if(w.st==='transform')a=w.rotation; + else if(w.st==='attack'||w.dawnDeparting)a=Math.atan2(-(w.vy||0),w.vx||1e-6); + else a=Math.atan2(-(b.y-w.y),b.x-w.x); + var r=w.w*V.S*.5,flash=w.hitFlash>0,phase2=w.phase===2; + x.save();x.translate(V.sx(w.x),V.sy(w.y));x.rotate(a); + // tendrils trail behind the eye + var wig=w.st==='attack'?2:5; + for(var k=0;k<5;k++){ + var off=(k-2)*r*.22,len=r*(1.25+.18*(k%3)),ph=t*(w.st==='attack'?16:7)+k*1.7; + x.beginPath();x.moveTo(-r*.8,off*.8); + x.bezierCurveTo(-r-len*.35,off+Math.sin(ph)*wig,-r-len*.7,off*1.3-Math.sin(ph+1)*wig*1.5,-r-len,off*1.6+Math.sin(ph+2)*wig*2); + x.lineWidth=Math.max(2,r*.13)*(1-k%2*.3);x.strokeStyle='#7c1f2c';x.stroke(); + x.lineWidth=Math.max(1,r*.05);x.strokeStyle='#c4485a';x.stroke(); + } + // sclera + x.beginPath();x.arc(0,0,r,0,TAU);x.fillStyle=D.lit(flash,phase2?'#e2c3b2':'#efe3d3');x.fill(); + x.lineWidth=2.5;x.strokeStyle='#4a1a22';x.stroke(); + // veins + x.strokeStyle='rgba(184,40,58,.75)';x.lineWidth=1.3; + for(var v=0;v<7;v++){var va=Math.PI*.55+v*.27,vx=Math.cos(va)*r*.95,vy=Math.sin(va)*r*.95; + x.beginPath();x.moveTo(vx,vy);x.quadraticCurveTo(vx*.65+Math.sin(v*3.1)*4,vy*.65,vx*.42,vy*.42+Math.cos(v)*3);x.stroke();} + if(!phase2){ + x.beginPath();x.arc(r*.42,0,r*.46,0,TAU);x.fillStyle='#3b7f8a';x.fill();x.strokeStyle='#18363b';x.lineWidth=2;x.stroke(); + x.beginPath();x.arc(r*.5,0,r*.24,0,TAU);x.fillStyle='#0b0b10';x.fill(); + x.fillStyle='rgba(255,255,255,.75)';x.beginPath();x.arc(r*.36,-r*.16,r*.08,0,TAU);x.fill(); + }else{ + // maw: dark opening with two rows of teeth facing forward + x.beginPath();x.ellipse(r*.38,0,r*.5,r*.62,0,0,TAU);x.fillStyle='#3a0d16';x.fill();x.strokeStyle='#1b0408';x.lineWidth=2;x.stroke(); + x.fillStyle='#f2ead2'; + for(var i=0;i<6;i++){var ty=-r*.5+i*r*.2;x.beginPath();x.moveTo(r*.85,ty);x.lineTo(r*.55,ty+r*.07);x.lineTo(r*.85,ty+r*.14);x.fill(); + x.beginPath();x.moveTo(r*.0,ty+r*.02);x.lineTo(r*.22,ty+r*.09);x.lineTo(r*.0,ty+r*.16);x.fill();} + x.fillStyle='rgba(220,60,70,.6)';x.beginPath();x.ellipse(r*.38,0,r*.18,r*.3,0,0,TAU);x.fill(); + } + x.restore(); + },bar:function(w){return w.phase===2?'#d8545e':'#db927e';}, + phase:function(w,assist){ + if(w.dawnDeparting)return 'Dawn departure · Dawn'; + if(w.st==='transform')return 'Transforming · Transforming'; + var form=w.phase===1?'Phase 1':'Phase 2'; + if(w.st==='attack'||w.st==='recover')return form+' · '+(w.move==='chain_dash'?'Rapid charges':'Dash')+(assist?' remaining '+w.dashesLeft:''); + return form+' · Hovering'; + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/king_slime.js b/environments/games/web/games/terraria_remake/draw/king_slime.js new file mode 100644 index 0000000000000000000000000000000000000000..03e6ce6227bab67726896450888ade9310d22dd8 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/king_slime.js @@ -0,0 +1,51 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW,TR=BB.TR; + // Original art: a translucent gel dome with a crown and a dark core. Squash/stretch follows the simulated + // jump velocity and landing recovery; the teleport shrink is the simulated hitbox size itself. + BB.BOSS_DRAW['terraria/king_slime']={ + hazards:function(x,c,t,V){ + var w=c.boss; + if(w.st==='antic'&&w.move==='teleport')D.cue(x,V,{x:w.x,y:w.y},{x:w.target.x,y:w.target.y+0.2},'#88e9d4'); + if(w.st!=='dead'&&!w.hidden)D.shadow(x,V,w.x,w.y-w.h/2,w.w,c); + D.extras(x,c,t,V); + }, + body:function(x,c,t,V){var w=c.boss; + if(w.st==='dead'||w.hidden)return; + var sq=1; + if(w.st==='attack')sq=1+BB.clamp(w.vy/(13*TR.PX),-1,1)*.16; + else if(w.st==='recover'&&w.move!=='teleport')sq=1-.16*Math.max(0,1-w.stT/.22); + else sq=1+Math.sin(t*5)*.025; + var W=w.w*V.S/Math.sqrt(sq),H=w.h*V.S*sq,cx=V.sx(w.x),by=V.sy(w.y-w.h/2),flash=w.hitFlash>0; + var fade=w.move==='teleport'&&(w.st==='antic'||w.st==='recover')?.55:1; + x.save();x.translate(cx,by);x.globalAlpha=fade; + // gel dome + x.beginPath();x.moveTo(-W/2,0);x.bezierCurveTo(-W*.56,-H*.62,-W*.3,-H,0,-H);x.bezierCurveTo(W*.3,-H,W*.56,-H*.62,W/2,0);x.closePath(); + x.globalAlpha=fade*.86;x.fillStyle=D.lit(flash,'#3d86d6');x.fill();x.globalAlpha=fade; + x.lineWidth=2.5;x.strokeStyle='#123563';x.stroke(); + // darker inner core and lower gel + x.fillStyle='rgba(14,40,92,.45)';x.beginPath();x.ellipse(0,-H*.38,W*.2,H*.22,0,0,Math.PI*2);x.fill(); + x.fillStyle='rgba(20,60,120,.35)';x.beginPath();x.ellipse(0,-H*.08,W*.44,H*.1,0,0,Math.PI*2);x.fill(); + // highlights + x.fillStyle='rgba(255,255,255,.55)';x.beginPath();x.ellipse(-W*.25,-H*.72,W*.08,H*.14,-.6,0,Math.PI*2);x.fill(); + x.fillStyle='rgba(255,255,255,.3)';x.beginPath();x.ellipse(-W*.12,-H*.86,W*.05,H*.05,0,0,Math.PI*2);x.fill(); + // crown (dropped visually while vanishing) + if(!(w.move==='teleport'&&w.st==='antic')){ + var cw=W*.36,ch=H*.2,top=-H*1.0; + x.beginPath();x.moveTo(-cw/2,top+ch*.15);x.lineTo(-cw/2,top-ch*.55);x.lineTo(-cw/4,top-ch*.15);x.lineTo(0,top-ch*.75);x.lineTo(cw/4,top-ch*.15);x.lineTo(cw/2,top-ch*.55);x.lineTo(cw/2,top+ch*.15);x.closePath(); + x.fillStyle=D.lit(flash,'#f0c445');x.fill();x.lineWidth=1.5;x.strokeStyle='#6d4b0c';x.stroke(); + x.fillStyle='#d8324a';x.beginPath();x.arc(0,top-ch*.12,ch*.17,0,Math.PI*2);x.fill(); + x.fillStyle='#7fd4f0';x.fillRect(-cw/2+2,top-ch*.2,3,3);x.fillRect(cw/2-5,top-ch*.2,3,3); + } + x.restore(); + if(w.st==='antic'&&w.move!=='teleport')D.cue(x,V,{x:w.x,y:w.y},{x:w.target.x,y:0.2},'#f7d377'); + }, + bar:function(){return '#4f9de0';}, + // Only what the original shows on screen; hidden counters appear only with the explicit assist toggle. + phase:function(w,assist){ + if(w.move==='teleport'&&(w.st==='antic'||w.st==='recover'))return 'Teleport · Teleport'; + var text=w.st==='attack'?'Jump · Jump':'Landed · Landed'; + if(assist)text+=' · next jump '+['normal','normal','low','high'][w.jumpIndex%4]+(w.teleportWait>0?' · TeleportTimer '+(5-w.teleportWait).toFixed(1)+'s':''); + return text; + } + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/palette.js b/environments/games/web/games/terraria_remake/draw/palette.js new file mode 100644 index 0000000000000000000000000000000000000000..a5ae00f1467497da6d6db35d268ea2c190d03593 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/palette.js @@ -0,0 +1,80 @@ +(function(g){ + var BB=g.BB; + BB.VIEW.PAL={sky:'#83b9c6',forest:'#35694d',earth:'#624735',gold:'#efc96e',ink:'#e8eddd',dark:'#172b32'}; + var D=BB.TR.DRAW={}; + // Hand-authored original procedural art; no downloaded images, fonts or source-game sprites. + // Every function here only reads the case; noise comes from a hash of ids/time, never from the game RNG. + D.sprite=function(ctx,V,e,rows,pal,w,h,flip){ + var sx=V.sx(e.x),sy=V.sy(e.y),cw=w*V.S/rows[0].length,ch=h*V.S/rows.length; + ctx.save();ctx.translate(Math.round(sx),Math.round(sy));if(flip)ctx.scale(-1,1); + for(var y=0;y=p[0]&&ex<=p[1]&&ey>=p[2]-.05&&p[2]>floor)floor=p[2];}); + var gap=Math.max(0,ey-floor),k=Math.max(0,1-gap/8);if(k<=0)return; + BB.ART.shade(x,V.sx(ex),V.sy(floor)+2,width*V.S*.55*(0.6+0.4*k),5,0.35*k); + }; + function slime(x,V,m,t,spiked){ + var cx=V.sx(m.x),by=V.sy(m.y-m.h/2),w=m.w*V.S,h=m.h*V.S*(1+Math.sin(t*7+m.id)*.05),flash=m.hitT>0; + x.save();x.translate(cx,by); + if(spiked){x.fillStyle='#d9d3c4';for(var k=-2;k<=2;k++){x.beginPath();x.moveTo(k*w*.18-3,-h*.55);x.lineTo(k*w*.2,-h*1.15+Math.abs(k)*3);x.lineTo(k*w*.18+3,-h*.55);x.fill();}} + x.beginPath();x.moveTo(-w/2,0);x.quadraticCurveTo(-w/2,-h*1.05,0,-h*1.05);x.quadraticCurveTo(w/2,-h*1.05,w/2,0);x.closePath(); + x.globalAlpha=.88;x.fillStyle=D.lit(flash,spiked?'#4c78c9':'#3f8ee0');x.fill();x.globalAlpha=1; + x.lineWidth=1.5;x.strokeStyle='#14305a';x.stroke(); + x.fillStyle='rgba(255,255,255,.55)';x.beginPath();x.ellipse(-w*.2,-h*.72,w*.11,h*.12,-.5,0,Math.PI*2);x.fill(); + x.fillStyle='#0d1f38';var f=m.face||1;x.fillRect(f*w*.08-3,-h*.55,2,3);x.fillRect(f*w*.08+3,-h*.55,2,3); + x.restore(); + } + function servant(x,V,m,t){ + var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,a=Math.atan2(-(m.vy||0),m.vx||1); + x.save();x.translate(cx,cy);x.rotate(a); + x.strokeStyle='#8e2b3a';x.lineWidth=2; + for(var k=-1;k<=1;k++){x.beginPath();x.moveTo(-r*.6,k*r*.3);x.quadraticCurveTo(-r*1.5,k*r*.5+Math.sin(t*14+k+m.id)*3,-r*2.1,k*r*.7);x.stroke();} + x.fillStyle='#ece0d0';x.beginPath();x.arc(0,0,r,0,Math.PI*2);x.fill();x.strokeStyle='#4a1820';x.lineWidth=1.5;x.stroke(); + x.fillStyle='#a8343f';x.beginPath();x.arc(r*.35,0,r*.5,0,Math.PI*2);x.fill(); + x.fillStyle='#120608';x.beginPath();x.arc(r*.45,0,r*.22,0,Math.PI*2);x.fill(); + x.restore(); + } + function shot(x,V,p,t){ + var cx=V.sx(p.x),cy=V.sy(p.y),a=Math.atan2(-p.vy,p.vx),r=Math.max(4,p.r*V.S); + x.save();x.translate(cx,cy); + if(p.kind==='slime_spike'){x.rotate(a);x.fillStyle='#e7e1cf';x.beginPath();x.moveTo(r*1.6,0);x.lineTo(-r*1.2,-2.2);x.lineTo(-r*1.2,2.2);x.closePath();x.fill();x.strokeStyle='#5a5246';x.lineWidth=1;x.stroke();} + else if(p.kind==='vile_spit'){ + x.rotate(a);x.fillStyle='rgba(126,170,52,.45)';x.beginPath();x.ellipse(-r*.9,0,r*1.1,r*.55,0,0,Math.PI*2);x.fill(); + x.fillStyle='#a7c94a';x.beginPath();x.arc(0,0,r,0,Math.PI*2);x.fill();x.strokeStyle='#3d4f17';x.lineWidth=1.5;x.stroke(); + x.fillStyle='#e3f3a0';x.beginPath();x.arc(r*.3,-r*.3,r*.3,0,Math.PI*2);x.fill(); + }else{ // homing skull with a cold flame trail + x.save();x.rotate(a);x.fillStyle='rgba(110,170,255,.35)';x.beginPath();x.moveTo(-r*.4,-r*.7);x.quadraticCurveTo(-r*2.6,Math.sin(t*20+p.id)*3,-r*.4,r*.7);x.fill();x.restore(); + x.fillStyle='#ece3c9';x.beginPath();x.arc(0,-1,r*.85,0,Math.PI*2);x.fill();x.fillRect(-r*.5,r*.3,r,r*.5); + x.strokeStyle='#4d463c';x.lineWidth=1;x.stroke();x.fillStyle='#2a2430';x.fillRect(-r*.45,-r*.35,r*.35,r*.35);x.fillRect(r*.1,-r*.35,r*.35,r*.35); + } + x.restore(); + } + function pickup(x,V,p,t){ + var cx=V.sx(p.x),cy=V.sy(p.y)+Math.sin(t*5+p.x)*1.5;x.save();x.translate(cx,cy); + if(p.kind==='heart'){x.fillStyle='#e9465a';x.beginPath();x.moveTo(0,5);x.bezierCurveTo(-9,-1,-5,-8,0,-3);x.bezierCurveTo(5,-8,9,-1,0,5);x.fill();x.strokeStyle='#5c0f1c';x.lineWidth=1;x.stroke();} + else{BB.ART.glow(x,0,0,12,'150,190,255',.5);x.fillStyle='#ffe78a';x.beginPath();for(var i=0;i<10;i++){var rr=i%2?3:7,a=-Math.PI/2+i*Math.PI/5;x.lineTo(Math.cos(a)*rr,Math.sin(a)*rr);}x.closePath();x.fill();x.strokeStyle='#7a5a12';x.lineWidth=1;x.stroke();} + x.restore(); + } + D.extras=function(x,c,t,V){ + var boss=c.boss; + (boss.minions||[]).forEach(function(m){if(m.hp<=0)return; + if(m.kind==='slime'||m.kind==='spiked_slime'){D.shadow(x,V,m.x,m.y-m.h/2,m.w,c);slime(x,V,m,t,m.kind==='spiked_slime');}else servant(x,V,m,t); + }); + (boss.shots||[]).forEach(function(p){shot(x,V,p,t);}); + (boss.pickups||[]).forEach(function(p){pickup(x,V,p,t);}); + }; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/queen_bee.js b/environments/games/web/games/terraria_remake/draw/queen_bee.js new file mode 100644 index 0000000000000000000000000000000000000000..5cb4b3f0199cf6851f843aa51d35ec3e8ddff032 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/queen_bee.js @@ -0,0 +1,71 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW,TAU=Math.PI*2; + // Original art: a crowned queen bee with striped abdomen, stinger, translucent beating wings and a royal ruff. + // She faces her velocity while charging and the player otherwise; bees and stingers are drawn here too. + function bee(x,V,m,t){ + var cx=V.sx(m.x),cy=V.sy(m.y),r=m.w*V.S*.5,f=(m.vx||0)>=0?1:-1,flap=Math.sin(t*60+m.id)*.6; + x.save();x.translate(cx,cy);x.scale(f,1); + x.fillStyle='rgba(230,240,255,.65)';x.beginPath();x.ellipse(-r*.1,-r*.75,r*.55,r*.3*(1+flap*.4),-.5,0,TAU);x.fill(); + x.fillStyle='#f2c23a';x.beginPath();x.ellipse(0,0,r,r*.75,0,0,TAU);x.fill(); + x.fillStyle='#2a1c08';x.fillRect(-r*.35,-r*.72,r*.22,r*1.44);x.fillRect(r*.1,-r*.72,r*.2,r*1.44); + x.beginPath();x.moveTo(-r,0);x.lineTo(-r*1.45,r*.12);x.lineTo(-r,r*.25);x.fill(); + x.fillStyle='#1a1205';x.beginPath();x.arc(r*.72,-r*.15,r*.2,0,TAU);x.fill(); + if(m.kind==='big_bee'){x.strokeStyle='#8a5a12';x.lineWidth=1.5;x.beginPath();x.ellipse(0,0,r,r*.75,0,0,TAU);x.stroke();} + x.restore(); + } + function stinger(x,V,p){ + var a=Math.atan2(-p.vy,p.vx),r=Math.max(5,p.r*V.S*1.4);x.save();x.translate(V.sx(p.x),V.sy(p.y));x.rotate(a); + x.fillStyle='rgba(255,220,90,.35)';x.beginPath();x.ellipse(-r*1.2,0,r*1.3,r*.45,0,0,TAU);x.fill(); + x.fillStyle='#f6d34a';x.beginPath();x.moveTo(r*1.4,0);x.lineTo(-r,-r*.42);x.lineTo(-r*.6,0);x.lineTo(-r,r*.42);x.closePath();x.fill(); + x.strokeStyle='#6a4a08';x.lineWidth=1;x.stroke();x.restore(); + } + BB.BOSS_DRAW['terraria/queen_bee']={hazards:function(x,c,t,V){ + var w=c.boss; + // Readable windup: while she hangs at the charge height a faint (18 %) streak marks that lane. It is drawn only + // during the pause, the period the source shows her holding level with the player; the explicit target box + // stays behind the assist cues switch. + if(w.move==='charge'&&w.st==='antic'&&w.hold>0){ + var y=V.sy(w.y),k=Math.min(1,w.hold/w.windup());x.save();x.globalAlpha=.18*k;x.fillStyle='#ffe28a'; + x.fillRect(Math.min(V.sx(w.x),V.sx(c.body.x))-20,y-3,Math.abs(V.sx(c.body.x)-V.sx(w.x))+40,6);x.restore(); + } + if(w.move==='charge'&&w.st==='antic'&&BB.TR.showCues)D.cue(x,V,w,{x:c.body.centre().x,y:w.y},'#f5d26a'); + w.minions.forEach(function(m){if(m.hp>0)bee(x,V,m,t);}); + w.shots.forEach(function(p){stinger(x,V,p);}); + (w.pickups||[]).length&&D.extras(x,{boss:{minions:[],shots:[],pickups:w.pickups}},t,V); + },body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return; + var charging=w.move==='charge'&&w.st==='attack',b=c.body.centre(),f=charging?(w.vx>=0?1:-1):(b.x>=w.x?1:-1); + var s=w.w*V.S,flash=w.hitFlash>0,flap=Math.sin(t*(charging?70:48))*.5,tilt=charging?.12:Math.sin(t*3)*.05; + // the windup crouch: she pulls back slightly before the dash + var crouch=w.move==='charge'&&w.st==='antic'&&w.hold>0?Math.min(1,w.hold/w.windup()):0; + x.save();x.translate(V.sx(w.x)-f*crouch*6,V.sy(w.y));x.scale(f,1);x.rotate(-tilt+crouch*.18); + // speed lines while charging + if(charging){x.strokeStyle='rgba(255,240,190,.35)';x.lineWidth=2;for(var k=0;k<4;k++){x.beginPath();x.moveTo(-s*.6,-s*.25+k*s*.16);x.lineTo(-s*(1.1+k%2*.25),-s*.25+k*s*.16);x.stroke();}} + // back wings + x.fillStyle='rgba(210,230,255,.5)';x.beginPath();x.ellipse(-s*.05,-s*.42,s*.42,s*.2*(1+flap*.5),-.6,0,TAU);x.fill(); + // abdomen with stripes and stinger + x.fillStyle=D.lit(flash,'#f0b62e');x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.fill(); + x.save();x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.clip();x.fillStyle='#3a2508'; + for(k=0;k<3;k++)x.fillRect(-s*.42+k*s*.17,-s*.3,s*.07,s*.7);x.restore(); + x.strokeStyle='#4a2f08';x.lineWidth=2;x.beginPath();x.ellipse(-s*.18,s*.06,s*.36,s*.28,.15,0,TAU);x.stroke(); + x.fillStyle='#2a1a06';x.beginPath();x.moveTo(-s*.5,s*.1);x.lineTo(-s*.72,s*.2);x.lineTo(-s*.48,s*.22);x.fill(); + // thorax with royal ruff + x.fillStyle=D.lit(flash,'#7a4a12');x.beginPath();x.arc(s*.17,-s*.02,s*.2,0,TAU);x.fill(); + x.fillStyle='#f5e6c2';for(k=0;k<6;k++){var a=-1.2+k*.48;x.beginPath();x.arc(s*.17+Math.cos(a)*s*.2,-s*.02+Math.sin(a)*s*.2,s*.07,0,TAU);x.fill();} + // head, eyes, antennae and crown + x.fillStyle=D.lit(flash,'#e8a82a');x.beginPath();x.arc(s*.38,-s*.13,s*.15,0,TAU);x.fill();x.strokeStyle='#4a2f08';x.lineWidth=1.5;x.stroke(); + x.fillStyle='#2a1408';x.beginPath();x.ellipse(s*.45,-s*.15,s*.05,s*.075,0,0,TAU);x.fill(); + x.strokeStyle='#2a1408';x.lineWidth=1.5;x.beginPath();x.moveTo(s*.4,-s*.27);x.quadraticCurveTo(s*.47,-s*.42,s*.56,-s*.4);x.stroke(); + x.fillStyle='#f6cf46';x.beginPath();x.moveTo(s*.26,-s*.26);for(var p=0;p<5;p++){x.lineTo(s*.28+p*s*.045,-s*(p%2?.32:.4));}x.lineTo(s*.48,-s*.26);x.closePath();x.fill(); + x.fillStyle='#e24a5a';x.beginPath();x.arc(s*.37,-s*.33,s*.022,0,TAU);x.fill(); + // front wings + x.fillStyle='rgba(235,245,255,.6)';x.beginPath();x.ellipse(s*.02,-s*.4,s*.38,s*.17*(1-flap*.5),-.85,0,TAU);x.fill(); + x.strokeStyle='rgba(120,150,190,.6)';x.lineWidth=1;x.stroke(); + x.restore(); + },bar:function(){return '#e6b23a';}, + phase:function(w,assist){ + if(w.move==='charge'||w.move==='charge_end')return 'Lane charge'+(assist?' remaining '+w.chargesLeft:''); + if(w.move==='summon')return 'Summon bees'+(assist?' remaining '+w.beesLeft:''); + if(w.move==='stingers')return 'Stinger volley'+(assist?' remaining '+w.volleyLeft:''); + return ''; + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/draw/skeletron.js b/environments/games/web/games/terraria_remake/draw/skeletron.js new file mode 100644 index 0000000000000000000000000000000000000000..aca054ed323b0506450c8472ede5691f65650427 --- /dev/null +++ b/environments/games/web/games/terraria_remake/draw/skeletron.js @@ -0,0 +1,58 @@ +(function(g){ + var BB=g.BB,D=BB.TR.DRAW; + var TAU=Math.PI*2; + function bone(x,ax,ay,bx,by,wd){ + x.lineCap='round';x.lineWidth=wd+3;x.strokeStyle='#3d362f';x.beginPath();x.moveTo(ax,ay);x.lineTo(bx,by);x.stroke(); + x.lineWidth=wd;x.strokeStyle='#ddd1b3';x.stroke(); + x.fillStyle='#e9dfc4';[[ax,ay],[bx,by]].forEach(function(p){x.beginPath();x.arc(p[0],p[1],wd*.75,0,TAU);x.fill();}); + } + function hand(x,V,h,flash,t){ + var cx=V.sx(h.x),cy=V.sy(h.y),s=h.w*V.S*.5,a=h.st==='attack'?Math.atan2(-h.vy,h.vx):Math.PI/2*(h.side<0?1:1)+.0; + if(h.st!=='attack')a=-Math.PI/2+h.side*.35; + x.save();x.translate(cx,cy);x.rotate(a); + x.fillStyle=D.lit(flash,'#e2d6b8');x.strokeStyle='#3d362f';x.lineWidth=2; + x.beginPath();x.ellipse(0,0,s*.62,s*.55,0,0,TAU);x.fill();x.stroke(); + for(var f=-1.5;f<=1.5;f++){ + var fy=f*s*.28;x.beginPath();x.moveTo(s*.4,fy);x.lineTo(s*1.05,fy*1.15);x.lineWidth=s*.22+2;x.strokeStyle='#3d362f';x.stroke(); + x.lineWidth=s*.22;x.strokeStyle=D.lit(flash,'#e2d6b8');x.stroke(); + x.fillStyle='#3d362f';x.beginPath();x.arc(s*1.08,fy*1.15,s*.1,0,TAU);x.fill(); + } + x.beginPath();x.moveTo(-s*.1,-s*.55);x.lineTo(-s*.55,-s*1.0);x.lineWidth=s*.22+2;x.strokeStyle='#3d362f';x.stroke();x.lineWidth=s*.22;x.strokeStyle=D.lit(flash,'#e2d6b8');x.stroke(); + x.restore(); + } + function skull(x,w,W,H,flash,glow){ + // cranium + cheek + jaw, original silhouette + x.beginPath();x.moveTo(-W*.48,-H*.05);x.bezierCurveTo(-W*.55,-H*.6,-W*.3,-H*.52,0,-H*.52);x.bezierCurveTo(W*.3,-H*.52,W*.55,-H*.6,W*.48,-H*.05); + x.bezierCurveTo(W*.46,H*.16,W*.3,H*.22,W*.26,H*.28);x.lineTo(-W*.26,H*.28);x.bezierCurveTo(-W*.3,H*.22,-W*.46,H*.16,-W*.48,-H*.05);x.closePath(); + x.fillStyle=D.lit(flash,'#e6dbc0');x.fill();x.lineWidth=2.5;x.strokeStyle='#3d362f';x.stroke(); + x.beginPath();x.rect(-W*.22,H*.28,W*.44,H*.17);x.fillStyle=D.lit(flash,'#d8ccae');x.fill();x.stroke(); + x.strokeStyle='#3d362f';x.lineWidth=1.5;for(var i=-2;i<=2;i++){x.beginPath();x.moveTo(i*W*.085,H*.28);x.lineTo(i*W*.085,H*.42);x.stroke();} + [-1,1].forEach(function(s){x.beginPath();x.ellipse(s*W*.2,-H*.04,W*.14,H*.13,s*.2,0,TAU);x.fillStyle='#15121a';x.fill(); + if(glow){BB.ART.glow(x,s*W*.2,-H*.04,W*.2,'255,70,60',.8);x.fillStyle='#ff6a4d';x.beginPath();x.arc(s*W*.2,-H*.04,W*.04,0,TAU);x.fill();}}); + x.beginPath();x.moveTo(0,H*.1);x.lineTo(-W*.06,H*.2);x.lineTo(W*.06,H*.2);x.closePath();x.fillStyle='#15121a';x.fill(); + x.strokeStyle='rgba(61,54,47,.6)';x.lineWidth=1.2;x.beginPath();x.moveTo(W*.1,-H*.5);x.lineTo(W*.16,-H*.36);x.lineTo(W*.1,-H*.28);x.stroke(); + } + BB.BOSS_DRAW['terraria/skeletron']={hazards:D.extras,body:function(x,c,t,V){var w=c.boss;if(w.st==='dead')return; + var flash=w.hitFlash>0,hx=V.sx(w.x),hy=V.sy(w.y); + w.hands.forEach(function(h){if(h.hp<=0)return; + var sx=V.sx(w.x+h.side*.85),sy=V.sy(w.y-.75),ex=V.sx(h.x),ey=V.sy(h.y),mx=(sx+ex)/2,my=(sy+ey)/2,dx=ex-sx,dy=ey-sy,l=Math.hypot(dx,dy)||1; + var bend=Math.max(0,95-l)*.55+12,elx=mx+(-dy/l)*bend*h.side*-1,ely=my+(dx/l)*bend*h.side*-1; + if(ely0;}).length; + if(w.enraged)return 'Daytime enraged · Enraged'; + return (w.st==='attack'?'Spinning pursuit · Spin':'Hovering hand strikes · Hands')+' · hands '+hands+'/2'+(assist?' · Armor '+w.defense:''); + }}; +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/game.js b/environments/games/web/games/terraria_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..93b5e9ebb8d3a2335b3f646e8b21f886dfdb22b0 --- /dev/null +++ b/environments/games/web/games/terraria_remake/game.js @@ -0,0 +1,14 @@ +(function(g){ + g.BB.GAME={id:'terraria_remake',title:'Terraria · Arena Trials',rules:'terraria-1458-arena-r7',defaultCase:'terraria/king_slime',roster:[ + {id:'terraria/king_slime',name:'Bouncing Gel Giant',arch:'Jumps, teleports, and slime minions'}, + {id:'terraria/eye_of_cthulhu',name:'Charging Giant Eye',arch:'Read the charge lane and adapt to phase-two rapid charges'}, + {id:'terraria/skeletron',name:'Twin-Handed Giant Skull',arch:'Independent hands, spinning pursuit, and armor windows'}, + {id:'terraria/eater_of_worlds',name:'Burrowing Great Worm',arch:'Burrowing, segmented targets, and real splitting'}, + {id:'terraria/queen_bee',name:'Charging Giant Bee',arch:'Align with lane charges, bee summons, and stinger volleys'}, + {id:'terraria/brain_of_cthulhu',name:'Teleporting Flesh Brain',arch:'Clear the guard eyes, then chase the teleporting core'} + ]}; + // Public three tiers (tiers.js): the shared page builds its difficulty buttons from this declaration. + g.BB.GAME.tiers=g.BB.TR.TIER_D; + g.BB.GAME.resetOptions=function(){var el=g.document&&g.document.getElementById('world-start');return {dawn_in_seconds:el?+el.value:540};}; + if(g.document){var cue=g.document.getElementById('show-cues');if(cue)cue.addEventListener('change',function(){g.BB.TR.showCues=cue.checked;});} +})(typeof window!=='undefined'?window:globalThis); diff --git a/environments/games/web/games/terraria_remake/index.html b/environments/games/web/games/terraria_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..711296b1af576cd59ba3dae9b7e17c15906a3a23 --- /dev/null +++ b/environments/games/web/games/terraria_remake/index.html @@ -0,0 +1,68 @@ + + + + +Terraria · Arena Trials | BossBench + + +
            +

            Terraria ARENA TRIALS

            One loadout, six challenges. Read attacks and master your positioning.

            ← BOSSBENCH
            +
            + +

            Choose your challenge

            +
            Difficulty + + +
            +
            + + + +
            + +

            Adventurer: Fixed Equipment

              +
            • A/D Move; hold Space to jump higher and continue flying; S drops through platforms.
            • +
            • Move the mouse to aim; J/left mouse button uses the current weapon; Q switches between sword and bow.
            • +
            • E equips the bow; right mouse button equips the sword. Bow is the default with unlimited standard arrows.
            • +
            • The blue bar shows remaining flight time and refills on landing; hold Space to glide after it runs out. The sword sweeps an arc in the facing direction and can hit several worm segments at once.
            • +
            • The charging giant eye leaves at dawn; the twin-handed skull enrages by day. Target lines are off by default because the original game has none; enable assist cues if needed.
            • +
            • All three difficulty tiers use Classic rules: Easy lasts about 25 seconds, Normal about one minute, and Hard about three minutes. Boss health, attack frequency, and damage increase by tier.
            +

            Move list

              +

              Recording and Replay

              +
              +After a match, save its seed, difficulty, and complete keyboard and mouse input.
              +
              All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
              +
              + + + + + + + + + + diff --git a/environments/games/web/games/terraria_remake/presentation.js b/environments/games/web/games/terraria_remake/presentation.js new file mode 100644 index 0000000000000000000000000000000000000000..737e8a33c65a78c7a67227def0de22f664a66dc7 --- /dev/null +++ b/environments/games/web/games/terraria_remake/presentation.js @@ -0,0 +1,32 @@ +// Original synthesized cues; presentation never changes the simulation or its RNG. +(function(g){ + var BB=g.BB,ctx=null; + function unlock(){ + var Audio=g.AudioContext||g.webkitAudioContext;if(!Audio)return; + if(!ctx)ctx=new Audio();if(ctx.state==='suspended')ctx.resume().catch(function(){}); + } + if(g.document){g.document.addEventListener('pointerdown',unlock,{once:true});g.document.addEventListener('keydown',unlock,{once:true});} + function tone(hz,duration,volume,type,end){ + if(!ctx||ctx.state!=='running')return; + var o=ctx.createOscillator(),a=ctx.createGain(),t=ctx.currentTime; + o.type=type||'triangle';o.frequency.setValueAtTime(hz,t);if(end)o.frequency.exponentialRampToValueAtTime(end,t+duration); + a.gain.setValueAtTime(volume,t);a.gain.exponentialRampToValueAtTime(.0001,t+duration); + o.connect(a);a.connect(ctx.destination);o.start(t);o.stop(t+duration); + } + var consume=BB.Juice.prototype.consume; + BB.Juice.prototype.consume=function(c,R){ + var start=this.caseRef===c&&c.events.length>=this.seen?this.seen:c.events.length; + consume.call(this,c,R); + if(!c.id.startsWith('terraria/'))return; + // Terraria has no artificial hit-stop. Keep the shared visual particles. + this.hitstop=0; + if(!R.canvas||R.canvas.id!=='view'||!g.document.getElementById('select').classList.contains('hidden'))return; + var count=0; + for(var i=start;i one legal 200 ms packet. +// It reads the live BB.Case (privileged state) and evaluates candidate key sets on isolated deep copies +// (their own RNG copy, no shared objects except the immutable case definition), so the live simulation and +// its RNG are never touched. Deterministic: no Math.random, no clock, no memory between calls. +// It is a reference/demo controller, never shown to a policy; its wins are not model or human results. +(function (g) { + var BB = g.BB, SC = BB.TR.SCRIPTED = {}; + function copy(v) { + if (!v || typeof v !== 'object') return v; + if (Array.isArray(v)) return v.map(copy); + var o = Object.create(Object.getPrototypeOf(v)); + Object.keys(v).forEach(function (k) { o[k] = k === 'def' ? v[k] : k === 'events' ? [] : copy(v[k]); }); + return o; + } + function dist(a, b) { return Math.hypot(a.x - b.x, a.y - b.y); } + // Aim point: the nearest live target part (Eater segments above ground, Expert Skeletron hands first, + // close minions), led by its velocity over the arrow flight time. + function aimTarget(c) { + var w = c.boss, b = c.body.centre(), parts = []; + if (w.segments) parts = w.segments.filter(function (s) { return s.hp > 0 && s.y > 0.1; }); + else if (w.hands && w.k.expert >= .5) parts = w.hands.filter(function (h) { return h.hp > 0; }); + if (!parts.length) parts = [w]; + parts = parts.concat((w.minions || []).filter(function (m) { return m.hp > 0 && dist(m, b) < 4; })); + parts.sort(function (a, z) { return dist(a, b) - dist(z, b); }); + var p = parts[0], flight = dist(p, b) / 31; + var lead = (w.st === 'antic' || w.st === 'recover') ? 0 : Math.min(.35, flight); + return { x: BB.clamp(p.x + (p.vx || 0) * lead, .1, 26.9), y: BB.clamp(p.y + (p.vy || 0) * lead + 1.5 * flight * flight, .1, 14.9) }; + } + // Same keys held for all six sub-steps; Space is released for one packet when a fresh press is needed. + function packet(c, keys) { + var t = aimTarget(c); keys = Object.assign({}, keys); + if (keys.Space && c.body.grounded && c.body.prev.jump) delete keys.Space; + var held = []; for (var i = 0; i < BB.SUBSTEPS; i++) held.push(keys); + return BB.formatPacket(held, [BB.clamp(Math.round((t.x - c.body.aimX) * 30), -1000, 1000), BB.clamp(Math.round((c.body.aimY - t.y) * 30), -1000, 1000), 0]); + } + function runPacket(s, text) { + var p = BB.parsePacket(text), m = p.mouse.map(function (v) { return v / 12; }); + for (var j = 0; j < 12 && !s.result; j++) s.tick(p.subs[Math.floor(j / 2)], m); + } + function bossHealth(w) { return w.hp + (w.hands ? w.hands.reduce(function (a, h) { return a + h.hp; }, 0) : 0); } + function candidates(c, expertEye) { + var a = [{ E: true }, { E: true, A: true }, { E: true, D: true }, { E: true, Space: true }, { E: true, A: true, Space: true }, + { E: true, D: true, Space: true }, { E: true, S: true }, { E: true, A: true, S: true }, { E: true, D: true, S: true }]; + // Consider sword arcs against clustered enemies or a boss at close range. + if (c.boss.segments || expertEye || c.id === 'terraria/queen_bee' || c.id === 'terraria/brain_of_cthulhu') a = a.concat([{ RMB: true }, { RMB: true, A: true }, { RMB: true, D: true }, { RMB: true, Space: true }, + { RMB: true, A: true, Space: true }, { RMB: true, D: true, Space: true }]); + return a; + } + // Score look-ahead copies by health, boss damage, hazard distance, wing time, and wall position. Expert Eye candidates can change direction in a follow-up. + var CONTINUATIONS = [null, { E: true }, { E: true, A: true }, { E: true, D: true }]; + function evaluate(c, keys, horizon, expertEye, cont) { + var s = copy(c), initial = s.body.hp, before = bossHealth(s.boss); + for (var n = 0; n < horizon && !s.result; n++) runPacket(s, packet(s, n === 0 || !cont ? keys : cont)); + return score(s, initial, before, expertEye); + } + function score(s, initial, before, expertEye) { + var b = s.body.centre(), near = 0; + s.boss.hazards().forEach(function (h) { + var q = h.box || { x: h.circle[0], y: h.circle[1] }; near += Math.max(0, 3 - Math.hypot(q.x - b.x, q.y - b.y)); + }); + // Weight health more heavily against the Eater of Worlds because its chain can hit the player repeatedly. + var score = (s.body.hp - initial) * (expertEye ? 16 : s.boss.segments ? 26 : 14) + (before - bossHealth(s.boss)) * (expertEye ? 1.6 : .6) - near * 8 + s.body.flight * 2; + if (s.result === 'loss') score -= 10000; if (s.result === 'win') score += 10000; + return score - Math.max(0, 2 - s.body.x) - Math.max(0, s.body.x - 25); + } + // Use a follow-up input in hard Skeletron to allow dodging a swipe before aiming the next shot. + function twoPly(c, horizon) { + var initial = c.body.hp, before = bossHealth(c.boss), list = candidates(c, false), best = null, bestScore = -Infinity; + list.forEach(function (k1) { + var s1 = copy(c); runPacket(s1, packet(s1, k1)); var top = -Infinity; + list.forEach(function (k2) { + var s2 = copy(s1); for (var n = 1; n < horizon && !s2.result; n++) runPacket(s2, packet(s2, k2)); + top = Math.max(top, score(s2, initial, before, false)); + }); + if (top > bestScore) { bestScore = top; best = k1; } + }); + return packet(c, best); + } + function decide(c) { + var expertEye = c.id === 'terraria/eye_of_cthulhu' && !!c.boss.expert; + if (c.boss.hands && !c.boss.expert && c.boss.pace.aggr > 1) return twoPly(c, 9); + // Skeletron's spin chases for 6.7 s: Expert needs a 2.4 s look-ahead to plan the escape past the head. + var horizon = expertEye ? 10 : c.id === 'terraria/brain_of_cthulhu' ? 9 : c.boss.hands && c.boss.expert ? 12 : 6, best = null, bestScore = -Infinity; + candidates(c, expertEye).forEach(function (keys) { + var score = -Infinity; + (expertEye ? CONTINUATIONS : [null]).forEach(function (cont) { score = Math.max(score, evaluate(c, keys, horizon, expertEye, cont)); }); + if (score > bestScore) { bestScore = score; best = keys; } + }); + return packet(c, best); + } + SC.copy = copy; SC.packet = packet; SC.decide = decide; SC.aimTarget = aimTarget; + BB.GAME.scripted = function (c) { return decide(c); }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13ef4b83bfd63fbbe6e09c5b6c36021e8017f4b7 --- /dev/null +++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/__init__.py @@ -0,0 +1,4 @@ +from .env import SemanticEnv, make_semantic_env +from .actions import to_named, to_indices + +__all__ = ['SemanticEnv', 'make_semantic_env', 'to_named', 'to_indices'] diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..1282a25b9ae72f963936af73dfbed579e4897440 --- /dev/null +++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/actions.py @@ -0,0 +1,42 @@ +"""The named action vocabulary shown to an LLM; integer IDs stay inside PPO.""" +from numbers import Integral +import gymnasium as gym +import numpy as np + +FIELDS = ('move', 'vert', 'attack') +LABELS = (('none', 'left', 'right'), ('none', 'jump', 'drop'), + ('none',) + tuple(f'shoot {i*22.5:g}' for i in range(16)) + ('slash left', 'slash right')) + + +def to_named(indices): + if len(indices) != 3 or any(isinstance(v, (bool, np.bool_)) or not isinstance(v, Integral) + or not 0 <= v < len(labels) for v, labels in zip(indices, LABELS)): + raise ValueError('expected three categorical integer IDs in [3,3,19]') + return {field: labels[int(i)] for field, labels, i in zip(FIELDS, LABELS, indices)} + + +def to_indices(action): + """Decode canonical named fields; the environment additionally accepts text envelopes.""" + if not isinstance(action, dict) or set(action) != set(FIELDS): + raise ValueError('expected move, vert, attack fields') + return tuple(labels.index(action[field]) for field, labels in zip(FIELDS, LABELS)) + + +class NamedActions(gym.Space): + def __init__(self, seed=None): + super().__init__(None, None, seed) + + def sample(self, mask=None, probability=None): + if mask is not None or probability is not None: + raise ValueError('named action masking is not supported') + return to_named([int(self.np_random.integers(len(labels))) for labels in LABELS]) + + def contains(self, action): + try: + to_indices(action) + return True + except (TypeError, ValueError, KeyError): + return False + + def __repr__(self): + return 'NamedActions(move=3, vert=3, attack=19)' diff --git a/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py b/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py new file mode 100644 index 0000000000000000000000000000000000000000..c078cff28f09729e2724c0524e6c0c83d8fb52f4 --- /dev/null +++ b/environments/games/web/games/terraria_remake/semantic_ppo_v1/env.py @@ -0,0 +1,250 @@ +"""Experimental RGB / 100 ms semantic Gym environment, independent of policy-gym@2.""" +from __future__ import annotations + +import base64 +import copy +import hashlib +import json +import math +from numbers import Integral +from pathlib import Path +import re +import shutil +import subprocess + +import gymnasium as gym +import numpy as np + +from bossbench.unified import _finite_number, _plain, _reset_options +from bossbench.tiers import resolve_options +from bossbench.webenv import BrowserTransport +from .actions import NamedActions, FIELDS, LABELS + +HERE = Path(__file__).resolve().parent +GAME = HERE.parent +ROOT = HERE.parents[3] +PROTOCOL = ('Output a JSON object with explicit action meanings, for example ' + '{"move":"left","vert":"jump","attack":"shoot 135"}. ' + 'All three fields execute concurrently in one 100 ms window; use "none" for no action. ' + '0 degrees points right, 90 up. The 16 shoot directions are multiples of 22.5 degrees. ' + 'Text envelopes such as <|semantic_start|> left ; jump ; shoot 135 <|semantic_end|> are also accepted. ' + 'Invalid input executes a no-op; never output categorical integer IDs in the LLM response.') + + +def source_manifest(): + """Fingerprint precisely the frozen page plus the experimental adapter.""" + page = (GAME / 'index.html').read_text(encoding='utf-8') + frozen = hashlib.sha256() + for name in re.findall(r' diff --git a/environments/games/web/games/tombraider_remake/lizard.js b/environments/games/web/games/tombraider_remake/lizard.js new file mode 100644 index 0000000000000000000000000000000000000000..de5c6baa44cea030154282737b5d7f5052c48cfe --- /dev/null +++ b/environments/games/web/games/tombraider_remake/lizard.js @@ -0,0 +1,72 @@ +/* Tomb Raider (1996) boss arenas - the T-Rex of Lost Valley. State logic and thresholds from TRX objects/creatures/trex.c (TR1 branch): + see section A. Approximation: ANIM lengths, speeds, body spheres and the bite's head path (animation/mesh data). */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { deg } = T; + const HP = [120, 280, 700], TOUCH = 1, TRAMPLE = 10, BITE = 10000, PIVOT = 2000, RADIUS = 341; + const RUN_RANGE = Math.pow(5 * T.WALL_L, 2), ATTACK_RANGE = Math.pow(4 * T.WALL_L, 2), BITE_RANGE = 1500 * 1500, ROAR_CHANCE = 512; + const WALK_TURN = T.v(deg(2)), RUN_TURN = T.v(deg(4)); + // Approximation: original ticks per cycle, units per original tick; converted to 60 Hz by T.anim. + const ANIM = T.REX_ANIM = T.anim({ stop: { len: 8, speed: 0 }, walk: { len: 20, speed: 36 }, run: { len: 16, speed: 80 }, bite: { len: 42, speed: 0 }, roar: { len: 48, speed: 0 } }); + const BITE_FROM = T.n(16), BITE_TO = T.n(30); // ticks of the bite where the head sweeps forward: the telegraph is the first 16 + const BODY = [[-2300, 800, 240], [-1500, 1000, 340], [-500, 1200, 620], [400, 1300, 640], [120, 340, 380, 320], [120, 340, 380, -320]]; + const headAt = b => { + if (b.state !== 'bite') return [1800, 1900, 420]; + if (b.stateT < BITE_FROM) return [1800 - 500 * (b.stateT / BITE_FROM), 2050, 420]; + const f = T.clamp((b.stateT - BITE_FROM) / (BITE_TO - BITE_FROM), 0, 1); + return [1300 + 1500 * f, 2050 - 1600 * f, 460]; + }; + T.CREATURES.lizard = { + label: 'Giant-Fanged Lizard Beast', pivot: PIVOT, radius: RADIUS, hpTable: HP, states: { stop: 'Idle', walk: 'Walking slowly', run: 'Charge', bite: 'Gaping bite', roar: 'Roar' }, + spawn(g, x, z, rot) { + const k = g.tierScale, hp = Math.round(T.tierValue(g.d, g.tiers, HP)); + return { kind: 'lizard', x, y: 0, z, rot, hp, maxHp: hp, state: 'stop', goal: 'stop', req: '', stateT: 0, flag: false, turn: 0, bites: 0, roars: 0, attacks: 0, + touchDmg: T.v(TOUCH * k.damage), trampleDmg: T.v(TRAMPLE * k.damage), roarChance: T.chance(ROAR_CHANCE * k.chatter), stopLen: Math.round(ANIM.stop.len * k.pause) }; + }, + aimPoint: b => ({ x: b.x + T.sin(b.rot) * 200, y: b.y + 1250, z: b.z + T.cos(b.rot) * 200 }), + // Telegraphs (tr1-arena@3): which damaging move is winding up or live, for the renderer, the HUD and the measurement scripts. A pure function + // of the boss state; nothing in the simulation reads it. windup = ticks between the move's start and its first damaging tick (the source's). + moves: { bite: { label: 'Gaping bite (instant kill)', windup: BITE_FROM, form: 'Draws head back and opens mouth' }, trample: { label: 'Charging trample', windup: 0, form: 'Charge posture (no original wind-up)' } }, + tele: b => b.state === 'bite' ? (b.stateT < BITE_FROM ? { move: 'bite', phase: 'windup', k: b.stateT / BITE_FROM } : b.stateT <= BITE_TO ? { move: 'bite', phase: 'active', k: 1 } : null) + : b.state === 'run' ? { move: 'trample', phase: 'active', k: 1 } : null, + headLocal: headAt, shadow: 700, + spheres(b) { return T.bodySpheres(b, BODY.concat([headAt(b)])); }, + headSphere(b) { return T.bodySpheres(b, [headAt(b)])[0]; }, + tick(g, b) { + const L = g.lara, i = T.aiInfo(g, b, PIVOT), a = ANIM[b.state]; + b.turn = T.creatureMove(g, b, a.speed, b.state === 'run' ? RUN_TURN : WALK_TURN, RADIUS); + if (T.pushLara(g, this.spheres(b))) T.laraDamage(g, b.state === 'run' ? b.trampleDmg : b.touchDmg, 'lizard_touch'); + b.flag = !i.ahead && i.facing > -T.DEG90 && i.facing < T.DEG90; + if (!b.flag && i.distance > BITE_RANGE && i.distance < ATTACK_RANGE && i.bite) b.flag = true; + switch (b.state) { + case 'stop': + if (b.req) b.goal = b.req; + else if (i.distance < BITE_RANGE && i.bite) b.goal = 'bite'; + else b.goal = b.flag ? 'walk' : 'run'; + break; + case 'walk': // TRX: any mood but BORED leaves the walk at once, so an attacking rex steps and stops + b.goal = 'stop'; + break; + case 'run': + if (i.distance < RUN_RANGE && i.bite) b.goal = 'stop'; + else if (b.flag) b.goal = 'stop'; + else if (i.ahead && T.rand(g) < b.roarChance) { b.req = 'roar'; b.goal = 'stop'; } + break; + case 'bite': { + if (b.stateT === 0) { b.attacks++; T.event(g, 'lizard_bite_start'); } + const h = this.headSphere(b); + if (b.stateT >= BITE_FROM && b.stateT <= BITE_TO && T.touchesLara(L, null, h[0], h[1], h[2], h[3])) { b.bites++; T.laraDamage(g, BITE, 'lizard_bite'); } + b.req = 'walk'; b.goal = 'stop'; + break; + } + case 'roar': + if (b.stateT === 0) { b.roars++; T.event(g, 'lizard_roar'); } + b.goal = 'stop'; + break; + } + const len = b.state === 'stop' ? b.stopLen : a.len; + b.stateT++; + if (b.stateT >= len && b.goal !== b.state) { b.state = b.goal; b.stateT = 0; if (b.state === b.req) b.req = ''; } + }, + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/manifest.json b/environments/games/web/games/tombraider_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..38e797e79708c3b0b21033d42a48406b791c9f68 --- /dev/null +++ b/environments/games/web/games/tombraider_remake/manifest.json @@ -0,0 +1,50 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "tombraider_remake", + "module": "TombRaiderGame", + "title": "Tomb Raider 1: Ruins Bosses", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-tombraider", + "rules": "tr1-arena@3", + "cases": [ + "tombraider/giant_lizard", + "tombraider/lone_gunman", + "tombraider/cannon_quadruped", + "tombraider/twin_pistols", + "tombraider/legless_giant", + "tombraider/winged_matriarch" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "tombraider_remake/tr1core.js", + "tombraider_remake/tr1player.js", + "tombraider_remake/tr1camera.js", + "tombraider_remake/tr1creature.js", + "tombraider_remake/lizard.js", + "tombraider_remake/human.js", + "tombraider_remake/fleshkin.js", + "tombraider_remake/game.js", + "tombraider_remake/scripted.js", + "tombraider_remake/renderer3d.js", + "tombraider_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "tombraider_remake/tr1core.js", + "tombraider_remake/tr1player.js", + "tombraider_remake/tr1camera.js", + "tombraider_remake/tr1creature.js", + "tombraider_remake/lizard.js", + "tombraider_remake/human.js", + "tombraider_remake/fleshkin.js", + "tombraider_remake/game.js", + "tombraider_remake/scripted.js" + ], + "play_page": "web/games/tombraider_remake/index.html", + "scripted_controller": "TombRaiderGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]}; privileged state, look-ahead on copies whose RNG is reseeded per tick by a multiply mix", + "source": "https://github.com/LostArtefacts/TRX/tree/4b9b64f5a717330d148d5d0e0eef220ff389b480 (GPL-3, read only) and https://github.com/XProger/OpenLara/tree/3b268ca4bf986c380f44a26ffd9218bf6d376249 (BSD-2, read only)" +} diff --git a/environments/games/web/games/tombraider_remake/renderer3d.js b/environments/games/web/games/tombraider_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..08ab727542543af90e18c81f7918d919082fcbaa --- /dev/null +++ b/environments/games/web/games/tombraider_remake/renderer3d.js @@ -0,0 +1,454 @@ +/* Tomb Raider (1996) boss arenas - original procedural 3D art on Three.js r160 (MIT, shared read-only vendor copy in web/games/_boss3d/vendor). + Third-person chase camera behind Lara. Low-poly, vertex-shaded and nearest-filtered as a nod to the 1996 look, but every mesh, texture and + colour here is generated by this file; no Tomb Raider model, texture or level geometry is used. Rendering is a pure function of the game + state: it never writes the simulation and never draws gameplay RNG, and animation time comes from the state's tick counter. + Axes: game (x, y up, z) with rot 0 = +z, turning right; three.js (x, y, -z), rotation.y = -rot. */ +(function (root) { + 'use strict'; + const TH = root.THREE, M = root.TombRaiderGame, T = M && M.T; + if (!TH) throw Error('Three.js is missing (web/games/_boss3d/vendor/three.min.js)'); + const R = M.R3 = {}, S = 1 / 256, A2R = Math.PI * 2 / 65536, byCanvas = new WeakMap(); + const vec = (x, y, z, out) => (out || new TH.Vector3()).set(x * S, y * S, -z * S); + function hash(x, y, s) { let n = Math.imul(x + 374761393 * s, 668265263) ^ Math.imul(y + s, 2246822519); n = Math.imul(n ^ (n >>> 13), 1274126177); return ((n ^ (n >>> 16)) >>> 0) / 4294967295; } + + // ---------------- procedural textures ---------------- + function tex(paint, size) { + const c = document.createElement('canvas'); c.width = c.height = size || 128; paint(c.getContext('2d'), c.width); + const t = new TH.CanvasTexture(c); t.colorSpace = TH.SRGBColorSpace; t.wrapS = t.wrapT = TH.RepeatWrapping; t.magFilter = TH.NearestFilter; t.minFilter = TH.NearestMipmapLinearFilter; return t; + } + const speckle = (q, n, base, amp, seed, grain) => { const im = q.createImageData(n, n); for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) { const v = (hash(x >> (grain || 0), y >> (grain || 0), seed) - .5) * amp + (hash(x >> 3, y >> 3, seed + 3) - .5) * amp, i = (y * n + x) * 4; im.data[i] = base[0] + v; im.data[i + 1] = base[1] + v * .95; im.data[i + 2] = base[2] + v * .85; im.data[i + 3] = 255; } q.putImageData(im, 0, 0); }; + const blocks = (q, n, rows, col, seed) => { q.strokeStyle = col; q.lineWidth = 2; const h = n / rows; for (let r = 0; r < rows; r++) { q.beginPath(); q.moveTo(0, r * h); q.lineTo(n, r * h); q.stroke(); const off = r % 2 ? n / 4 : 0; for (let k = 0; k < 2; k++) { const x = off + k * n / 2 + (hash(r, k, seed) - .5) * 8; q.beginPath(); q.moveTo(x, r * h); q.lineTo(x, r * h + h); q.stroke(); } } }; + const PAINT = { + grass(q, n) { speckle(q, n, [78, 98, 46], 44, 5, 1); for (let k = 0; k < 90; k++) { q.fillStyle = k % 3 ? 'rgba(40,62,24,.7)' : 'rgba(136,146,70,.6)'; q.fillRect(hash(k, 1, 7) * n, hash(k, 2, 7) * n, 2, 5); } }, + cliff(q, n) { speckle(q, n, [104, 92, 76], 54, 9); q.strokeStyle = 'rgba(40,32,26,.75)'; q.lineWidth = 3; for (let k = 0; k < 7; k++) { let x = hash(k, 0, 3) * n, y = 0; q.beginPath(); q.moveTo(x, y); while (y < n) { y += 12 + hash(k, y, 4) * 16; x += (hash(k, y, 5) - .5) * 34; q.lineTo(x, y); } q.stroke(); } }, + sand(q, n) { speckle(q, n, [168, 138, 92], 34, 12, 1); blocks(q, n, 2, 'rgba(86,62,34,.8)', 2); }, + sandwall(q, n) { speckle(q, n, [150, 120, 80], 38, 14); blocks(q, n, 4, 'rgba(66,46,26,.85)', 3); q.fillStyle = 'rgba(190,150,70,.35)'; for (let k = 0; k < 6; k++) q.fillRect(14 + k * 19, 34, 9, 9); }, + dark(q, n) { speckle(q, n, [70, 70, 78], 30, 16, 1); blocks(q, n, 2, 'rgba(24,24,30,.9)', 4); }, + darkwall(q, n) { speckle(q, n, [78, 76, 88], 34, 18); blocks(q, n, 3, 'rgba(24,22,30,.85)', 5); q.strokeStyle = 'rgba(96,170,160,.45)'; q.lineWidth = 2; q.strokeRect(n * .3, n * .36, n * .4, n * .26); }, + flesh(q, n) { speckle(q, n, [120, 52, 48], 46, 21); q.strokeStyle = 'rgba(60,14,20,.8)'; q.lineWidth = 3; for (let k = 0; k < 9; k++) { q.beginPath(); q.moveTo(hash(k, 3, 1) * n, 0); q.bezierCurveTo(hash(k, 4, 1) * n, n / 3, hash(k, 5, 1) * n, n * .6, hash(k, 6, 1) * n, n); q.stroke(); } }, + gold(q, n) { speckle(q, n, [150, 114, 46], 40, 25); blocks(q, n, 2, 'rgba(70,46,12,.85)', 6); }, + scale(q, n) { speckle(q, n, [78, 92, 54], 40, 28); q.strokeStyle = 'rgba(30,42,20,.8)'; for (let y = 0; y < n; y += 10) for (let x = (y / 10) % 2 * 6; x < n; x += 12) { q.beginPath(); q.arc(x, y, 6, 0, Math.PI); q.stroke(); } q.fillStyle = 'rgba(160,140,70,.25)'; q.fillRect(0, n * .75, n, n * .25); }, + mutant(q, n) { speckle(q, n, [150, 96, 88], 46, 31); q.fillStyle = 'rgba(90,20,34,.55)'; for (let k = 0; k < 14; k++) { q.beginPath(); q.arc(hash(k, 1, 9) * n, hash(k, 2, 9) * n, 4 + hash(k, 3, 9) * 8, 0, 7); q.fill(); } }, + }; + const THEME = { + valley: { floor: 'grass', wall: 'cliff', wallH: 6, natural: true, fog: [0xa8b8a4, 9000, 30000], sky: ['#5f8fb0', '#b8cdb4', '#d8d2b0'], hemi: [0xe8f0ff, 0x4a5a30, 2.4], sun: [0xfff0d0, 2.2] }, + hall: { floor: 'sand', wall: 'sandwall', wallH: 4, ceil: true, fog: [0x2a1f14, 3000, 13000], hemi: [0xffe0b0, 0x40301c, 2.2], sun: [0xffc080, .9], torch: true }, + crypt: { floor: 'dark', wall: 'darkwall', wallH: 4, ceil: true, fog: [0x151a22, 3000, 14000], hemi: [0xc8d8ff, 0x2a2a38, 2.4], sun: [0xa0c0ff, .9], torch: true }, + pit: { floor: 'flesh', wall: 'flesh', wallH: 5, ceil: true, natural: true, fog: [0x2a0c0e, 2500, 14000], hemi: [0xffc0a8, 0x401018, 2.6], sun: [0xff9060, 1], torch: false }, + gold: { floor: 'gold', wall: 'gold', wallH: 6, ceil: true, fog: [0x241204, 3000, 16000], hemi: [0xffd8a0, 0x402810, 2.4], sun: [0xffa850, 1.2], torch: true }, + }; + const SIDES = [[1, 0, 1, 0, 1, 1], [-1, 0, 0, 1, 0, 0], [0, 1, 1, 1, 0, 1], [0, -1, 0, 0, 1, 0]]; + function arenaGeometry(m, th) { + const fp = [], fu = [], fc = [], fi = [], wp = [], wu = [], wc = [], wi = [], W = T.WALL_L, top = th.wallH * W; + const h = (i, j) => (i < 0 || j < 0 || i >= m.w || j >= m.h ? T.WALL : m.cells[j * m.w + i]); + const jig = () => 0; // a jittered rock face left slivers of sky at the corners; the texture carries the rock look instead + const shade = (i, j) => 1 - .1 * [[0, 0], [-1, 0], [0, -1], [-1, -1]].filter(([a, b]) => h(i + a, j + b) === T.WALL).length; + const quad = (p, u, c, ix, q, uv, cs) => { const n = p.length / 3; for (let k = 0; k < 4; k++) { p.push(q[k][0] * S, q[k][1] * S, -q[k][2] * S); u.push(uv[k][0], uv[k][1]); c.push(cs[k], cs[k], cs[k] * .98); } ix.push(n, n + 1, n + 2, n, n + 2, n + 3); }; + for (let j = 0; j < m.h; j++) for (let i = 0; i < m.w; i++) { + const f = h(i, j); if (f === T.WALL) continue; + const n = hash(i, j, 11) * .1 + .9; + quad(fp, fu, fc, fi, [[i * W, f, j * W], [(i + 1) * W, f, j * W], [(i + 1) * W, f, (j + 1) * W], [i * W, f, (j + 1) * W]], [[0, 0], [1, 0], [1, 1], [0, 1]], + [shade(i, j) * n, shade(i + 1, j) * n, shade(i + 1, j + 1) * n, shade(i, j + 1) * n]); + for (const [di, dj, ax, az, bx, bz] of SIDES) { + const o = h(i + di, j + dj); if (o <= f) continue; + const roof = o === T.WALL ? top : o, tiers = Math.max(1, Math.round((roof - f) / W)); + for (let k = 0; k < tiers; k++) { + const y0 = f + (roof - f) * k / tiers, y1 = f + (roof - f) * (k + 1) / tiers, a = [(i + ax) * W, (j + az) * W], b = [(i + bx) * W, (j + bz) * W]; + const j00 = jig(Math.round(a[0] / W), Math.round(a[1] / W), k, 1), j10 = jig(Math.round(b[0] / W), Math.round(b[1] / W), k, 1), j01 = jig(Math.round(a[0] / W), Math.round(a[1] / W), k + 1, 1), j11 = jig(Math.round(b[0] / W), Math.round(b[1] / W), k + 1, 1); + const light = (dj ? .86 : 1) * (.72 + .28 * (k + .5) / tiers), lo = k === 0 ? light * .72 : light; + quad(wp, wu, wc, wi, [[a[0] + di * j00, y0, a[1] + dj * j00], [b[0] + di * j10, y0, b[1] + dj * j10], [b[0] + di * j11, y1, b[1] + dj * j11], [a[0] + di * j01, y1, a[1] + dj * j01]], [[0, k + 1], [1, k + 1], [1, k], [0, k]], [lo, lo, light, light]); + } + } + if (th.ceil) quad(wp, wu, wc, wi, [[i * W, top, j * W], [i * W, top, (j + 1) * W], [(i + 1) * W, top, (j + 1) * W], [(i + 1) * W, top, j * W]], [[0, 0], [0, 1], [1, 1], [1, 0]], [.34, .34, .34, .34]); + } + const make = (p, u, c, ix) => { const g = new TH.BufferGeometry(); g.setAttribute('position', new TH.Float32BufferAttribute(p, 3)); g.setAttribute('uv', new TH.Float32BufferAttribute(u, 2)); g.setAttribute('color', new TH.Float32BufferAttribute(c, 3)); g.setIndex(ix); return g; }; + return { floor: make(fp, fu, fc, fi), wall: make(wp, wu, wc, wi) }; + } + + // ---------------- model helpers: origin at the feet, forward = -z ---------------- + class Kit { + constructor(scene) { this.mats = new Map(); this.scene = scene; } + mat(color, opts) { const k = color + JSON.stringify(opts ? Object.keys(opts) : 0) + (opts && opts.map ? opts.map.uuid : ''); if (!this.mats.has(k)) { const m = new TH.MeshLambertMaterial(Object.assign({ color, flatShading: true }, opts || {})); this.mats.set(k, m); this.scene.keep(m); } return this.mats.get(k); } + add(parent, geo, mat, x, y, z) { const m = new TH.Mesh(geo, mat); this.scene.keep(geo); m.position.set((x || 0) * S, (y || 0) * S, -(z || 0) * S); parent.add(m); return m; } + box(p, w, h, d, c, x, y, z) { return this.add(p, new TH.BoxGeometry(w * S, h * S, d * S), this.mat(c), x, y, z); } + cyl(p, rt, rb, h, c, x, y, z, seg) { return this.add(p, new TH.CylinderGeometry(rt * S, rb * S, h * S, seg || 7), this.mat(c), x, y, z); } + ball(p, r, c, x, y, z, map) { return this.add(p, new TH.IcosahedronGeometry(r * S, 1), map ? this.mat(0xffffff, { map }) : this.mat(c), x, y, z); } + group(p, x, y, z) { const g = new TH.Group(); g.position.set((x || 0) * S, (y || 0) * S, -(z || 0) * S); p.add(g); return g; } + limb(p, x, y, z, r1, r2, len, c) { const g = this.group(p, x, y, z); this.cyl(g, r1, r2, len, c, 0, -len / 2, 0); return g; } + } + function human(k, o) { // a generic low-poly person: o = { skin, top, legs, boots, hair, scale }; hips at y 400 + const root = new TH.Group(), s = o.scale || 1, hips = k.group(root, 0, 400 * s, 0), L = {}; + root.scale.set(1, 1, 1); + k.cyl(hips, 86 * s, 96 * s, 110 * s, o.legs, 0, 10, 0); + k.cyl(hips, 99 * s, 99 * s, 28 * s, o.belt || 0x3a2a1c, 0, 58 * s, 0, 8); + if (o.coat) k.cyl(hips, 104 * s, 150 * s, 300 * s, o.coat, 0, -130 * s, 0, 8); + const torso = L.torso = k.group(hips, 0, 60 * s, 0); + k.cyl(torso, 96 * s, 74 * s, 220 * s, o.top, 0, 110 * s, 0); + k.ball(torso, 44 * s, o.top, -104 * s, 205 * s, 0); k.ball(torso, 44 * s, o.top, 104 * s, 205 * s, 0); + k.cyl(torso, 32 * s, 36 * s, 50 * s, o.skin, 0, 238 * s, 0, 6); + if (o.pack) k.box(torso, 150 * s, 170 * s, 80 * s, o.pack, 0, 120 * s, -96 * s); + L.head = k.group(torso, 0, 250 * s, 0); k.ball(L.head, 62 * s, o.skin, 0, 40 * s, 0); + k.ball(L.head, 9 * s, 0x141414, -22 * s, 52 * s, 56 * s); k.ball(L.head, 9 * s, 0x141414, 22 * s, 52 * s, 56 * s); + if (o.hair) k.ball(L.head, 64 * s, o.hair, 0, 58 * s, -12 * s); + if (o.cap) { k.cyl(L.head, 64 * s, 66 * s, 44 * s, o.cap, 0, 98 * s, 0, 8); k.box(L.head, 90 * s, 12 * s, 70 * s, o.cap, 0, 80 * s, 66 * s); } + L.armL = k.limb(torso, -118 * s, 205 * s, 0, 34 * s, 26 * s, 250 * s, o.skin); L.armR = k.limb(torso, 118 * s, 205 * s, 0, 34 * s, 26 * s, 250 * s, o.skin); + L.legL = k.limb(hips, -52 * s, -30 * s, 0, 50 * s, 34 * s, 370 * s, o.skinLeg || o.legs); L.legR = k.limb(hips, 52 * s, -30 * s, 0, 50 * s, 34 * s, 370 * s, o.skinLeg || o.legs); + k.box(L.legL, 62 * s, 44 * s, 130 * s, o.boots, 0, -380 * s, 18 * s); k.box(L.legR, 62 * s, 44 * s, 130 * s, o.boots, 0, -380 * s, 18 * s); + if (o.holster) { k.box(L.legL, 44 * s, 110 * s, 64 * s, o.holster, -44 * s, -100 * s, 0); k.box(L.legR, 44 * s, 110 * s, 64 * s, o.holster, 44 * s, -100 * s, 0); } + for (const a of [L.armL, L.armR]) { k.ball(a, 30 * s, o.skin, 0, -238 * s, 0); a.gun = k.box(a, 28 * s, 34 * s, 96 * s, o.gun || 0x24262c, 0, -256 * s, 26 * s); a.flash = k.ball(a, 56 * s, 0xffffff, 0, -280 * s, 90 * s); a.flash.material = k.flashMat; a.flash.visible = false; } + Object.assign(root, { parts: L, hips }); + return root; + } + const pose = (m, st, t) => { + const P = m.parts, w = st.run ? Math.sin(t * .42) * .85 : st.walk ? Math.sin(t * .3) * .45 : 0; + P.legL.rotation.x = w; P.legR.rotation.x = -w; + P.armL.rotation.set(-w * .6, 0, -.12); P.armR.rotation.set(w * .6, 0, .12); + m.hips.position.y = (st.crouch ? 300 : 400) * S + (st.run ? Math.abs(Math.sin(t * .42)) * 16 * S : 0); + P.torso.rotation.set(0, 0, 0); + }; + const aimArm = (a, yaw, pitch) => { a.rotation.order = 'YXZ'; a.rotation.set(Math.PI / 2 + pitch, yaw, 0); }; // the limb hangs along -y: +90 degrees about x swings it to the model's forward (-z) + const flash = (a, f) => { if (a.flash) a.flash.visible = f; }; + + const BUILD = { + lara(k) { + const m = human(k, { skin: 0xd8a080, top: 0x6f6a3c, legs: 0x4c4436, boots: 0x2c2620, hair: 0x2a2a2e, pack: 0x5a4a30, holster: 0x3a2a1c }); + const braid = m.parts.braid = k.group(m.parts.head, 0, 60, -56); k.cyl(braid, 24, 16, 80, 0x2a2a2e, 0, -24, 0, 5); + return m; + }, + lizard(k, s) { + const r = new TH.Group(), skin = k.mat(0xffffff, { map: s.tex.scale }), g = new TH.BoxGeometry(1, 1, 1); + const ell = (p, rx, ry, rz, x, y, z) => { const m = k.ball(p, 1, 0, x, y, z); m.material = skin; m.scale.set(rx, ry, rz); return m; }; + const body = k.group(r, 0, 0, 0); ell(body, 430, 520, 1150, 0, 1230, -300); + const P = r.parts = { tail: [], body }; + let parent = k.group(body, 0, 1160, -1250); for (let i = 0; i < 5; i++) { ell(parent, 280 - i * 50, 280 - i * 50, 360, 0, 0, -300); P.tail.push(parent); parent = k.group(parent, 0, -30, -520); } + P.neck = k.group(body, 0, 1500, 700); ell(P.neck, 300, 320, 520, 0, 150, 260); + P.head = k.group(P.neck, 0, 330, 660); ell(P.head, 310, 240, 460, 0, 40, 260); + P.jaw = k.group(P.head, 0, -80, 60); ell(P.jaw, 250, 90, 400, 0, -40, 240); + for (let i = 0; i < 5; i++) { k.cyl(P.head, 0, 26, 110, 0xe8e0c0, -170 + i * 85, -150, 560, 4); k.cyl(P.jaw, 26, 0, 90, 0xe8e0c0, -130 + i * 65, 50, 440, 4); } + k.ball(P.head, 44, 0xd0a020, -220, 150, 400); k.ball(P.head, 44, 0xd0a020, 220, 150, 400); + P.legL = k.group(body, -340, 900, -100); P.legR = k.group(body, 340, 900, -100); + for (const L of [P.legL, P.legR]) { ell(L, 200, 460, 300, 0, -230, 0); ell(L, 110, 320, 130, 0, -640, -80); const f = k.box(L, 240, 80, 460, 0x3a4228, 0, -860, 110); f.castShadow = false; } + k.limb(P.neck, -230, -120, 300, 44, 30, 240, 0x4a5a36); k.limb(P.neck, 230, -120, 300, 44, 30, 240, 0x4a5a36); + return r; + }, + gunman(k) { return human(k, { skin: 0xd0a080, top: 0x6c5a3c, legs: 0x3e3a34, boots: 0x20201c, hair: 0x6a4a28, scale: 1.1, cap: 0x4a4030, belt: 0x201810 }); }, + duelist(k) { return human(k, { skin: 0xd8a888, top: 0x28303c, legs: 0x20242c, boots: 0x101014, hair: 0x101014, scale: 1.05, coat: 0x1c2230, belt: 0x6a5020 }); }, + quadruped(k, s) { + const r = new TH.Group(), skin = k.mat(0xffffff, { map: s.tex.mutant }), P = r.parts = { legs: [] }; + const ell = (p, rx, ry, rz, x, y, z) => { const m = k.ball(p, 1, 0, x, y, z); m.material = skin; m.scale.set(rx, ry, rz); return m; }; + ell(r, 300, 300, 640, 0, 760, -120); + for (const [x, z] of [[-200, 340], [200, 340], [-200, -520], [200, -520]]) { const L = k.group(r, x, 660, z); ell(L, 90, 340, 110, 0, -320, 0); k.box(L, 120, 60, 170, 0x4a3030, 0, -640, 20); P.legs.push(L); } + P.torso = k.group(r, 0, 930, 380); ell(P.torso, 240, 380, 200, 0, 320, 0); + P.head = k.group(P.torso, 0, 740, 40); ell(P.head, 130, 150, 150, 0, 40, 30); k.cyl(P.head, 0, 42, 240, 0xd8d0b0, -100, 190, 20, 4); k.cyl(P.head, 0, 42, 240, 0xd8d0b0, 100, 190, 20, 4); + P.armL = k.limb(P.torso, -300, 560, 0, 84, 60, 560, 0xa06a60); P.armR = k.limb(P.torso, 300, 560, 0, 84, 60, 560, 0xa06a60); + P.cannon = k.cyl(P.armR, 60, 90, 260, 0x60504a, 0, -640, 0, 6); P.glow = k.ball(P.armR, 86, 0xffffff, 0, -790, 0); P.glow.material = k.flashMat; P.glow.visible = false; + return r; + }, + fleshgiant(k, s) { + const r = new TH.Group(), skin = k.mat(0xffffff, { map: s.tex.flesh }), P = r.parts = {}; + const ell = (p, rx, ry, rz, x, y, z) => { const m = k.ball(p, 1, 0, x, y, z); m.material = skin; m.scale.set(rx, ry, rz); return m; }; + ell(r, 900, 800, 800, 0, 900, 0); ell(r, 560, 420, 520, 0, 1820, 180); + P.head = k.group(r, 0, 2000, 460); ell(P.head, 230, 240, 240, 0, 40, 60); k.ball(P.head, 40, 0xf0e040, -110, 90, 260); k.ball(P.head, 40, 0xf0e040, 110, 90, 260); + P.armL = k.group(r, -980, 1700, 100); P.armR = k.group(r, 980, 1700, 100); + for (const a of [P.armL, P.armR]) { ell(a, 300, 700, 300, 0, -620, 0); const f = k.group(a, 0, -1260, 0); ell(f, 230, 620, 230, 0, -480, 0); for (let i = -1; i <= 1; i++) k.cyl(f, 46, 0, 300, 0xd8c8a0, i * 120, -1120, 0, 4); a.fore = f; } + return r; + }, + winged(k, s) { + const r = human(k, { skin: 0xc8a8a8, top: 0x7a2030, legs: 0x4a1420, boots: 0x20080c, hair: 0x2a1a30, scale: 1.1 }); + const mat = new TH.MeshLambertMaterial({ color: 0x8a2a38, side: TH.DoubleSide, flatShading: true }); s.keep(mat); + const wing = sign => { const pts = new Float32Array([0, 0, 0, sign * 1000, 260, -160, sign * 760, -180, -120, 0, 0, 0, sign * 760, -180, -120, sign * 420, -620, -80]).map(v => v * S), g = new TH.BufferGeometry(); g.setAttribute('position', new TH.BufferAttribute(pts, 3)); g.computeVertexNormals(); s.keep(g); const m = new TH.Mesh(g, mat); m.position.set(0, 180 * S, 80 * S); r.parts.torso.add(m); return m; }; + r.parts.wingL = wing(-1); r.parts.wingR = wing(1); + return r; + }, + }; + const ANIMATE = { + lara(m, L, t, g) { + const st = { run: L.state === 'run' || L.state === 'backHop', walk: ['walk', 'walkBack', 'stepL', 'stepR'].includes(L.state), crouch: L.state === 'compress' || L.state === 'land' }; + pose(m, st, t); + const P = m.parts; + m.rotation.x = L.state === 'roll' ? (L.stateT / T.n(15)) * Math.PI * 2 : 0; + if (L.state === 'jump') { P.legL.rotation.x = -.5; P.legR.rotation.x = .25; } + P.braid.rotation.x = st.run ? .5 + Math.sin(t * .42) * .2 : L.airborne ? -.6 : .1; + if (L.gun === 'ready') { + const rec = a => a.frame >= 24 ? (33 - a.frame) * .02 : 0, yaw = a => -a.ry * A2R, pit = a => a.rx * A2R; + P.torso.rotation.y = -L.torso * A2R; + aimArm(P.armL, yaw(L.armL) + L.torso * A2R, pit(L.armL) + rec(L.armL)); aimArm(P.armR, yaw(L.armR) + L.torso * A2R, pit(L.armR) + rec(L.armR)); + flash(P.armL, L.armL.flash > 0); flash(P.armR, L.armR.flash > 0); + } else { flash(P.armL, false); flash(P.armR, false); } + if (L.hitFlash > 0) { const f = Math.min(1, L.hitFlash / T.n(12)); P.torso.rotation.x -= .32 * f; P.head.rotation.x = -.25 * f; } else P.head.rotation.x = 0; + }, + lizard(m, b, t) { + const P = m.parts, w = b.state === 'run' ? Math.sin(t * .4) * .7 : b.state === 'walk' ? Math.sin(t * .3) * .34 : 0, c = T.CREATURES.lizard, h = c.headLocal(b); + P.legL.rotation.x = w; P.legR.rotation.x = -w; P.body.rotation.z = Math.sin(t * .2) * (b.state === 'run' ? .03 : .01); + P.tail.forEach((s, i) => { s.rotation.y = Math.sin(t * .14 - i * .7) * (.1 + i * .02); s.rotation.x = .04 * i; }); + // The head follows the same path the bite's sphere uses (rex.js headAt), so the lunge on screen is the hit test. + const f = T.clamp((h[0] - 1300) / 1500, -.4, 1), roar = b.state === 'roar' ? Math.min(1, b.stateT / T.n(10)) : 0; + P.neck.rotation.x = b.state === 'bite' ? f * .62 + .0 : -roar * .5 + (b.state === 'bite' ? 0 : 0); + P.neck.position.z = -(700 + Math.max(0, f) * 600) * S; + P.jaw.rotation.x = b.state === 'bite' ? (b.stateT < T.n(26) ? .7 : .1) : roar * .9; + }, + gunman(m, b, t) { const shoot = b.state === 'aim' || b.state === 'shoot'; pose(m, { run: b.state === 'run', walk: b.state === 'walk' }, t); if (shoot) { aimArm(m.parts.armR, 0, 0); if (b.state === 'aim') aimArm(m.parts.armL, 0, -.3); } flash(m.parts.armR, b.flash > 0); flash(m.parts.armL, false); }, + duelist(m, b, t) { const shoot = b.state === 'aim' || b.state === 'shoot'; pose(m, { run: b.state === 'run', walk: b.state === 'walk' }, t); if (shoot) { aimArm(m.parts.armR, 0, 0); aimArm(m.parts.armL, 0, 0); } flash(m.parts.armR, b.flash > 0); flash(m.parts.armL, b.flash > 0); }, + quadruped(m, b, t) { + const P = m.parts, w = b.state === 'run' ? Math.sin(t * .5) * .7 : 0; P.legs.forEach((L, i) => { L.rotation.x = i % 3 ? w : -w; }); + const rear = b.state === 'rear' ? Math.sin(Math.min(1, b.stateT / T.n(30)) * Math.PI) : 0; m.rotation.x = rear * .5; + const aim = b.state === 'aim' || b.state === 'shoot' ? 1 : 0; P.armR.rotation.x = aim * 1.4; P.glow.visible = b.state === 'aim' && (b.stateT >> 1) % 4 < 2; P.armL.rotation.x = Math.sin(t * .2) * .1 + rear; + }, + fleshgiant(m, b, t) { + const P = m.parts, swing = (a, on, f) => { a.rotation.x = on ? -2.2 + f * 2.4 : Math.sin(t * .06) * .1; if (a.fore) a.fore.rotation.x = on ? .9 - f * .8 : -.2; }; + const f = T.clamp(b.stateT / T.n(24), 0, 1); + swing(P.armL, b.state === 'attackL' || b.state === 'attackB', f); swing(P.armR, b.state === 'attackR' || b.state === 'attackB' || b.state === 'grab', f); + m.rotation.z = b.state === 'turnL' ? Math.sin(t * .2) * .05 : b.state === 'turnR' ? -Math.sin(t * .2) * .05 : 0; + m.position.y += b.state === 'forward' ? Math.abs(Math.sin(t * .2)) * 40 * S : 0; + }, + winged(m, b, t) { + const P = m.parts, fly = b.state === 'fly', down = b.state === 'faint'; + pose(m, { run: b.state === 'run', walk: b.state === 'walk' }, t); + const beat = Math.sin(t * .5) * (fly ? .7 : .1); P.wingL.rotation.y = beat; P.wingR.rotation.y = -beat; P.wingL.visible = P.wingR.visible = !down; + m.rotation.x = down ? -Math.PI / 2 * Math.min(1, b.stateT / T.n(15)) : 0; + if (b.state === 'shoot' || b.state === 'aim') { aimArm(P.armR, 0, 0); aimArm(P.armL, 0, 0); } + flash(P.armL, false); flash(P.armR, false); + }, + }; + + // Scenery props, built once per arena from the map: rocks along the walls, plinths and capitals on the pillars. Original procedural shapes. + function decorate(sc, m, th, theme) { + const W = T.WALL_L, k = sc.kit, h = (i, j) => (i < 0 || j < 0 || i >= m.w || j >= m.h ? T.WALL : m.cells[j * m.w + i]); + const rockCol = { valley: 0x7a6e5c, hall: 0x9a8058, crypt: 0x5a5a64, pit: 0x7a302a, gold: 0x8a6a2a }[theme] || 0x777777; + const trim = { hall: 0x8a6a40, crypt: 0x44444e, gold: 0xa07a30, pit: 0x5a1c1c, valley: 0x6a604e }[theme]; + const rock = sc.keep(new TH.IcosahedronGeometry(S, 0)), mat = k.mat(rockCol), group = new TH.Group(); sc.world.add(group); + for (let j = 1; j < m.h - 1; j++) for (let i = 1; i < m.w - 1; i++) { + if (h(i, j) === T.WALL) continue; + for (const [a, c] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { + if (h(i + a, j + c) !== T.WALL || hash(i * 4 + a + 2, j * 4 + c + 2, 41) > (th.natural ? .5 : .28)) continue; + const cnt = 1 + Math.floor(hash(i, j, 42 + a + 2 * c) * 3); + for (let q = 0; q < cnt; q++) { + const r = 45 + hash(i, j, 43 + q + a) * 90, along = (.15 + .7 * hash(i, j, 50 + q + c)) * W, off = 40 + r * .8; + const x = a ? (i + (a > 0 ? 1 : 0)) * W - a * off : i * W + along, z = c ? (j + (c > 0 ? 1 : 0)) * W - c * off : j * W + along; + const mesh = new TH.Mesh(rock, mat); vec(x, r * .3, z, mesh.position); mesh.scale.set(r, r * .65, r * (.8 + .4 * hash(i, j, 61 + q))); mesh.rotation.set(hash(i, j, 70 + q) * 3, hash(i, j, 80 + q) * 3, 0); group.add(mesh); + } + } + } + if (!th.natural) for (let j = 1; j < m.h - 1; j++) for (let i = 1; i < m.w - 1; i++) { + if (h(i, j) !== T.WALL || ![[1, 0], [-1, 0], [0, 1], [0, -1]].some(([a, c]) => h(i + a, j + c) !== T.WALL)) continue; + k.box(group, W + 90, 150, W + 90, trim, (i + .5) * W, 75, (j + .5) * W); k.box(group, W + 50, 60, W + 50, trim, (i + .5) * W, 180, (j + .5) * W); + k.box(group, W + 70, 110, W + 70, trim, (i + .5) * W, th.wallH * W - 160, (j + .5) * W); + } + } + class Scene { + constructor(key, canvas, boss) { + this.key = key; this.resources = []; this.ready = false; this.error = null; this.closed = false; this.times = []; + const view = this.view = document.createElement('canvas'); view.width = 854; view.height = 480; + const r = this.renderer = new TH.WebGLRenderer({ canvas: view, antialias: true, stencil: true, preserveDrawingBuffer: true, powerPreference: 'low-power' }); + r.setPixelRatio(1); r.setSize(854, 480, false); r.outputColorSpace = TH.SRGBColorSpace; + view.addEventListener('webglcontextlost', e => { e.preventDefault(); this.ready = false; this.error = 'WebGL context lost'; }); + const arena = M.arenas[key], th = THEME[arena.theme]; this.ceilY = th.ceil ? th.wallH * T.WALL_L : 1e9; + this.world = new TH.Scene(); this.world.fog = new TH.Fog(th.fog[0], th.fog[1] * S, th.fog[2] * S); + this.camera = new TH.PerspectiveCamera(58, 854 / 480, 40 * S, 60000 * S); + if (th.sky) { const t = this.keep(tex((q, n) => { const g = q.createLinearGradient(0, 0, 0, n); g.addColorStop(0, th.sky[0]); g.addColorStop(.6, th.sky[1]); g.addColorStop(1, th.sky[2]); q.fillStyle = g; q.fillRect(0, 0, n, n); }, 64)); this.world.background = t; } + else this.world.background = new TH.Color(th.fog[0]); + this.world.add(new TH.HemisphereLight(th.hemi[0], th.hemi[1], th.hemi[2])); + const sun = new TH.DirectionalLight(th.sun[0], th.sun[1]); sun.position.set(4, 8, 3); this.world.add(sun); + this.tex = {}; for (const k of Object.keys(PAINT)) this.tex[k] = this.keep(tex(PAINT[k])); + const geo = arenaGeometry(arena.map, th), base = o => this.keep(new TH.MeshBasicMaterial(Object.assign({ vertexColors: true, side: TH.DoubleSide }, o))); + this.keep(geo.floor); this.keep(geo.wall); + const floorMesh = new TH.Mesh(geo.floor, base({ map: this.tex[th.floor] })), wallMesh = new TH.Mesh(geo.wall, base({ map: this.tex[th.wall] })); + floorMesh.renderOrder = wallMesh.renderOrder = -2; floorMesh.userData.occluder = wallMesh.userData.occluder = true; this.world.add(floorMesh, wallMesh); + this.kit = new Kit(this); this.kit.flashMat = this.keep(new TH.MeshBasicMaterial({ color: 0xffd080, transparent: true, opacity: .9, blending: TH.AdditiveBlending, depthWrite: false })); + this.lara = BUILD.lara(this.kit, this); this.world.add(this.lara); this.lara.traverse(o => { o.renderOrder = -1; }); + // The boss has its own materials: they mark its visible pixels in the stencil buffer, so the x-ray pass draws only the parts a wall (or + // Lara) hides, never its own back behind its front. + this.bkit = new Kit(this); this.bkit.flashMat = this.kit.flashMat; + this.boss = BUILD[boss](this.bkit, this); this.world.add(this.boss); + this.boss.traverse(o => { if (o.isMesh && !o.material.transparent) Object.assign(o.material, { stencilWrite: true, stencilRef: 1, stencilFunc: TH.AlwaysStencilFunc, stencilZPass: TH.ReplaceStencilOp }); }); + this.xray = this.keep(new TH.MeshBasicMaterial({ color: 0xff7a40, transparent: true, opacity: .42, depthWrite: false, depthFunc: TH.GreaterDepth, fog: false, side: TH.DoubleSide, + stencilWrite: true, stencilRef: 0, stencilFunc: TH.EqualStencilFunc, stencilZPass: TH.IncrementStencilOp })); + this.xworld = new TH.Scene(); + this.shadow = this.blob(); this.bshadow = this.blob(); + this.pool = []; this.fxTex = this.keep(tex((q, n) => { const g = q.createRadialGradient(n / 2, n / 2, 0, n / 2, n / 2, n / 2); g.addColorStop(0, '#fff'); g.addColorStop(.5, 'rgba(255,255,255,.5)'); g.addColorStop(1, 'rgba(255,255,255,0)'); q.fillStyle = g; q.fillRect(0, 0, n, n); }, 32)); + for (let i = 0; i < 170; i++) { const sp = new TH.Sprite(this.keep(new TH.SpriteMaterial({ map: this.fxTex, blending: TH.AdditiveBlending, depthWrite: false, transparent: true }))); sp.visible = false; this.world.add(sp); this.pool.push(sp); } + // floor decals (danger zones, impact rings, light pools) and hitscan tracers: pooled, set per frame from the state + this.ringTex = this.keep(tex((q, n) => { const g = q.createRadialGradient(n / 2, n / 2, 0, n / 2, n / 2, n / 2); g.addColorStop(0, 'rgba(255,255,255,.34)'); g.addColorStop(.8, 'rgba(255,255,255,.5)'); g.addColorStop(.88, '#fff'); g.addColorStop(.97, '#fff'); g.addColorStop(1, 'rgba(255,255,255,0)'); q.fillStyle = g; q.fillRect(0, 0, n, n); }, 128)); + this.ringTex.magFilter = TH.LinearFilter; + const D = Math.PI / 180, plane = this.keep(new TH.PlaneGeometry(2, 2)); + this.shapes = { disc: plane, ring: plane, fanR: new TH.CircleGeometry(1, 24, 12 * D, 90 * D), fanL: new TH.CircleGeometry(1, 24, 78 * D, 90 * D), fanB: new TH.CircleGeometry(1, 36, 12 * D, 156 * D), + semi: new TH.CircleGeometry(1, 24, 0, 180 * D), wedge: new TH.RingGeometry(.3, 1, 16, 1, 74 * D, 32 * D), lane: new TH.RingGeometry(.12, 1, 6, 1, 83 * D, 14 * D) }; + for (const k of Object.keys(this.shapes)) this.keep(this.shapes[k]); + this.decals = []; + for (let i = 0; i < 28; i++) { const d = new TH.Mesh(plane, this.keep(new TH.MeshBasicMaterial({ map: this.fxTex, transparent: true, depthWrite: false, side: TH.DoubleSide, fog: false }))); d.visible = false; d.renderOrder = 1; this.world.add(d); this.decals.push(d); } + const tube = this.keep(new TH.CylinderGeometry(1, 1, 1, 6, 1, true)); + this.tracers = []; + for (let i = 0; i < 12; i++) { const m = new TH.Mesh(tube, this.keep(new TH.MeshBasicMaterial({ color: 0xffffff, transparent: true, depthWrite: false, blending: TH.AdditiveBlending, fog: false }))); m.visible = false; this.world.add(m); this.tracers.push(m); } + this.bossMats = []; this.boss.traverse(o => { if (o.isMesh && o.material.emissive && !this.bossMats.includes(o.material)) this.bossMats.push(o.material); }); + const fill = new TH.DirectionalLight(th.hemi[0], .55); fill.position.set(-5, 3, -4); this.world.add(fill); + decorate(this, arena.map, th, arena.theme); + this.torches = []; + if (th.torch) { + const m = arena.map, W = T.WALL_L, spots = []; for (let j = 2; j < m.h - 2; j += 4) for (let i = 2; i < m.w - 2; i += 4) if (m.cells[j * m.w + i] !== T.WALL) for (const [a, b] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) if (m.cells[(j + b) * m.w + i + a] === T.WALL) spots.push([(i + .5 + a * .42) * W, (j + .5 + b * .42) * W]); + for (const [x, z] of spots.slice(0, 14)) { + const sp = new TH.Sprite(this.keep(new TH.SpriteMaterial({ map: this.fxTex, color: 0xff9030, blending: TH.AdditiveBlending, depthWrite: false, transparent: true }))); vec(x, 1100, z, sp.position); sp.scale.set(1.8, 2.6, 1); this.world.add(sp); this.torches.push(sp); + this.kit.box(this.world, 70, 170, 70, 0x2a2420, x, 960, z); this.kit.cyl(this.world, 50, 30, 60, 0x4a3a2a, x, 1060, z, 6); + const pool = new TH.Mesh(plane, this.keep(new TH.MeshBasicMaterial({ map: this.fxTex, color: 0xff9a40, transparent: true, opacity: .22, depthWrite: false, blending: TH.AdditiveBlending, fog: false }))); + pool.rotation.x = -Math.PI / 2; vec(x, 3, z, pool.position); pool.scale.set(700 * S, 700 * S, 1); this.world.add(pool); + } + } + } + keep(x) { this.resources.push(x); return x; } + blob() { const m = new TH.Mesh(this.keep(new TH.CircleGeometry(1, 16)), this.keep(new TH.MeshBasicMaterial({ color: 0, transparent: true, opacity: .34, depthWrite: false }))); m.rotation.x = -Math.PI / 2; this.world.add(m); return m; } + // The view, from the camera rig in the state (tr1camera.js): lens on the boom, then a look direction that starts from the chase view + // (ahead of her) and turns toward her and the boss as the rig's framing weight rises; the boss (while framed) and she are then kept + // inside the frame, the boss first. A pure function of the state. + frame(g) { + const L = g.lara, b = g.boss, c = L.cam, C = T.CAM, cam = this.camera, P = Math.PI, D = P / 180; + const len = C.CHASE + (C.COMBAT - C.CHASE) * c.lock, yaw = T.wrap(L.camYaw + C.SHOULDER * c.lock), up = C.UP + L.lookPitch * 18; + const r = Math.min(c.dist, T.camBoom(g, yaw, len, up)), head = L.y + C.HEAD; + const lift = Math.max(0, Math.min(c.lift, C.ceilOf(g) - 260 - head - up * r / len)); + const ex = L.x - T.sin(yaw) * r, ey = head + up * r / len + lift, ez = L.z - T.cos(yaw) * r; + vec(ex, ey, ez, cam.position); + const fov = 58 + 38 * Math.min(1, lift / 1600); + if (cam.fov !== fov) { cam.fov = fov; cam.updateProjectionMatrix(); } + const halfV = fov / 2 * D, halfH = Math.atan(Math.tan(halfV) * 854 / 480), wr = a => a - 2 * P * Math.round(a / (2 * P)); + const aim = (x, y, z) => { const dx = x - ex, dz = z - ez, h = Math.hypot(dx, dz); return { yaw: Math.atan2(dx, dz), pitch: Math.atan2(y - ey, h), h }; }; + const lk = c.look * A2R, A = aim(L.x + Math.sin(lk) * 1600, head - 60 - L.lookPitch * 14, L.z + Math.cos(lk) * 1600), her = aim(L.x, L.y + 430, L.z); + const shown = b.hp > 0 || b.state === 'faint', ap = T.CREATURES[b.kind].aimPoint(b), B = aim(ap.x, ap.y, ap.z), fr = shown ? c.fr : 0; + if (her.h < 250) her.yaw = shown ? B.yaw : A.yaw; // lens straight above her (corner lift): her bearing means nothing + const wy = A.yaw + wr(wr(her.yaw + wr(B.yaw - her.yaw) * .55) - A.yaw) * fr, wp = A.pitch + ((her.pitch + B.pitch) / 2 - A.pitch) * fr; + // Intervals of allowed offsets from the wanted direction, intersected in priority order; one that would empty the set is skipped. + const fit = (want, cons) => { let lo = -9, hi = 9; for (const [d, m] of cons) { const l = Math.max(lo, d - m), h = Math.min(hi, d + m); if (l <= h) { lo = l; hi = h; } } return want + Math.min(Math.max(0, lo), hi); }; + const boss1 = fr > .5; + const yy = fit(wy, boss1 ? [[wr(B.yaw - wy), halfH - 7 * D], [wr(her.yaw - wy), halfH - 5 * D]] : [[wr(her.yaw - wy), halfH - 5 * D]]); + const pp = T.clamp(fit(wp, boss1 ? [[B.pitch - wp, halfV - 6 * D], [her.pitch - wp, halfV - 8 * D]] : [[her.pitch - wp, halfV - 8 * D]]), -80 * D, 60 * D); + cam.lookAt(vec(ex + Math.sin(yy) * Math.cos(pp) * 1000, ey + Math.sin(pp) * 1000, ez + Math.cos(yy) * Math.cos(pp) * 1000)); + } + // Effects and telegraphs, all pure functions of the state (fx list, missiles, the boss's tele()). Player shots are pale yellow, the boss's red, + // orange or cyan. A telegraph is a floor zone where the move will land and a glow on the boss (or at its gun / hand) that grows over the wind-up. + effects(g, t) { + const L = g.lara, b = g.boss, cre = T.CREATURES[b.kind], sc = this, Wv = new TH.Vector3(), Wv2 = new TH.Vector3(), UP = new TH.Vector3(0, 1, 0); + let n = 0, nd = 0, nt = 0; + const put = (x, y, z, size, color, op) => { if (n >= sc.pool.length || op <= .01) return; const sp = sc.pool[n++]; vec(x, y, z, sp.position); sp.scale.setScalar(size * S); sp.material.color.setHex(color); sp.material.opacity = Math.min(1, op); sp.visible = true; }; + const putW = (w, size, color, op) => { if (n >= sc.pool.length || op <= .01) return; const sp = sc.pool[n++]; sp.position.copy(w); sp.scale.setScalar(size * S); sp.material.color.setHex(color); sp.material.opacity = Math.min(1, op); sp.visible = true; }; + const decal = (shape, x, z, radius, rot, color, op, add) => { + if (nd >= sc.decals.length || op <= .01) return; const d = sc.decals[nd++], f = T.floorAt(g.map, x, z); + // zones (every shape but 'disc') use the ring texture: a faint fill and a bright rim at the reach of the move + d.geometry = sc.shapes[shape]; d.material.map = shape === 'disc' ? sc.fxTex : sc.ringTex; d.material.color.setHex(color); d.material.opacity = Math.min(1, op); + d.material.blending = add ? TH.AdditiveBlending : TH.NormalBlending; vec(x, (f >= T.WALL ? 0 : f) + 8 + nd * .6, z, d.position); d.rotation.set(-Math.PI / 2, 0, -rot * A2R); + const k = shape === 'disc' || shape === 'ring' ? radius / 2 : radius; d.scale.set(k * S, k * S, 1); d.visible = true; + }; + const tracer = (from, x, y, z, color, op, width) => { if (nt >= sc.tracers.length) return; const m = sc.tracers[nt++]; vec(x, y, z, Wv2); const dir = Wv2.clone().sub(from), len = dir.length(); if (len < 1e-3) { m.visible = false; return; } m.position.copy(from).addScaledVector(dir, .5); m.quaternion.setFromUnitVectors(UP, dir.normalize()); m.scale.set(width * S, len, width * S); m.material.color.setHex(color); m.material.opacity = op; m.visible = true; }; + let flinch = 0; + // impacts, sparks, blasts, tracers + for (const f of g.fx) { + const age = g.t - f.t0, k = age / f.life; if (k >= 1) continue; + if (f.kind === 'ricochet') { + for (let i = 0; i < 6; i++) { const a = hash(f.id, i, 3) * 6.283, up = .3 + .7 * hash(f.id, i, 4), r = 40 + 260 * k; put(f.x + Math.cos(a) * r, f.y + up * r - 260 * k * k, f.z + Math.sin(a) * r, 34 * (1 - k) + 8, f.src === 'shard' ? 0x80e8ff : 0xffe080, 1 - k); } + put(f.x, f.y, f.z, 110 * (1 - k), 0xfff4c0, 1 - k); + } else if (f.kind === 'blood') { + for (let i = 0; i < 4; i++) { const a = hash(f.id, i, 5) * 6.283, r = 30 + 180 * k; put(f.x + Math.cos(a) * r, f.y + 60 * hash(f.id, i, 6) - 200 * k * k, f.z + Math.sin(a) * r, 46 * (1 - k) + 10, 0xb01810, 1 - k); } + put(f.x, f.y, f.z, 150 * (1 + k), 0x901410, (1 - k) * .8); + if (f.src === 'lara') flinch = Math.max(flinch, 1 - age / T.n(4)); + } else if (f.kind === 'blast') { + put(f.x, f.y + 200 * k, f.z, 1100 * (.55 + .9 * k), k < .3 ? 0xffe090 : 0xff6a20, (1 - k) * 1.1); + put(f.x, f.y + 120, f.z, 520 * (1 - k * .5), 0xfff6d8, 1 - k * 1.6); + for (let i = 0; i < 5; i++) { const a = hash(f.id, i, 7) * 6.283, r = 300 + 500 * k; put(f.x + Math.cos(a) * r, f.y + 200 + 700 * k * hash(f.id, i, 8), f.z + Math.sin(a) * r, 420 + 600 * k, 0x6a5040, .45 * (1 - k)); } + decal('ring', f.x, f.z, 400 + 1500 * k, 0, 0xff8a30, (1 - k) * .9, true); decal('disc', f.x, f.z, 1700, 0, 0xffa050, (1 - k) * .55, true); + } + if ((f.kind === 'ricochet' || f.kind === 'blood') && age < T.n(2) && (f.src === 'lara' || f.src === 'gunman' || f.src === 'duelist')) { + const own = f.src === 'lara', mdl = own ? sc.lara : sc.boss, arm = own ? (f.side === 'L' ? mdl.parts.armL : mdl.parts.armR) : (f.gun ? mdl.parts.armL : mdl.parts.armR); + if (arm && arm.gun) { arm.gun.getWorldPosition(Wv); tracer(Wv, f.x, f.y, f.z, own ? 0xfff0a0 : 0xff3420, 1 - age / T.n(2), own ? 9 : 12); } + } + } + // muzzle light on the floor + if (L.gun === 'ready' && (L.armL.flash > 0 || L.armR.flash > 0)) decal('disc', L.x, L.z, 900, 0, 0xffd080, .4, true); + if (b.flash > 0) decal('disc', b.x, b.z, 900, 0, 0xff8050, .4, true); + // missiles: hot core, coloured halo, a fading trail, and a ring where the straight flight meets the floor (bombs: the 1024 blast radius) + for (const q of g.missiles) { + const bomb = q.kind === 'bomb', col = bomb ? 0xff5a1e : 0x30d8ff, core = bomb ? 0xfff0c0 : 0xe8ffff, big = bomb ? 190 : 120; + put(q.x, q.y, q.z, big * 2.8, col, .55); put(q.x, q.y, q.z, big, core, 1); + for (let i = 1; i <= 6; i++) put(q.x - q.vx * i * 1.3, q.y - q.vy * i * 1.3, q.z - q.vz * i * 1.3, big * (1.6 - i * .18), col, .55 - i * .075); + let x = q.x, y = q.y, z = q.z, hit = null; + for (let i = 0, lim = Math.max(0, T.n(240) - q.age); i < lim; i++) { x += q.vx; y += q.vy; z += q.vz; const f = T.floorAt(g.map, x, z); if (y <= f || f >= T.WALL || y >= T.CEILING) { hit = [x - q.vx * .5, z - q.vz * .5, i]; break; } } + if (hit) { const soon = 1 - Math.min(1, hit[2] / T.n(30)); decal('ring', hit[0], hit[1], bomb ? 2048 : 420, 0, col, .35 + .5 * soon, true); if (bomb) decal('disc', hit[0], hit[1], 2048, 0, col, .12 + .25 * soon, true); } + } + // telegraph of the current move (cre.tele: windup / active): on the floor, on the boss and at its weapon + const tl = sc.boss.visible && cre.tele ? cre.tele(b) : null, red = 0xff2418; + let glow = 0; + if (tl) { + const w = tl.phase === 'windup' ? .25 + .6 * tl.k : 1, pulse = .78 + .22 * Math.sin(g.t * .8); + const P = sc.boss.parts, at = (part, size, color, op) => { if (part) { part.getWorldPosition(Wv); putW(Wv, size, color, op); } }; + switch (b.kind) { + case 'lizard': if (tl.move === 'bite') decal('wedge', b.x, b.z, 3000, b.rot, red, .75 * w * pulse); else decal('lane', b.x, b.z, 2600, b.rot, 0xff6a20, .35); break; + case 'quadruped': + if (tl.move === 'rear') decal('semi', b.x, b.z, 1150, b.rot, red, .7 * w * pulse); + else { at(P.glow, 160 + 320 * w, 0xff7a30, .9); if (tl.phase !== 'active') decal('ring', L.x, L.z, 2048, 0, red, .7 * w * pulse, true); } + break; + case 'fleshgiant': decal(tl.move === 'attackB' ? 'fanB' : 'fanR', b.x, b.z, 2800, b.rot, tl.move === 'grab' ? 0xc030ff : red, .6 * w * pulse); break; + case 'gunman': case 'duelist': if (tl.phase === 'windup') { at(P.armR.gun, 80 + 170 * w, 0xff4030, w); if (b.kind === 'duelist') at(P.armL.gun, 80 + 170 * w, 0xff4030, w); } break; + case 'winged': { + at(P.armR.gun, 120 + 260 * w, 0xff6a20, w); at(P.armL.gun, 120 + 260 * w, 0xff6a20, w); + if (tl.move === 'volley' && tl.phase === 'windup') decal('ring', L.x, L.z, 2048, 0, red, .6 * w * pulse, true); + break; + } + } + glow = w; + } + // dust under running feet + if (b.state === 'run' && (b.kind === 'lizard' || b.kind === 'quadruped')) for (let i = 0; i < 3; i++) { const ph = ((g.t + i * 7) % 21) / 21, back = -300 - 700 * ph; put(b.x + T.sin(b.rot) * back + (i - 1) * 260, 80 + 200 * ph, b.z + T.cos(b.rot) * back, 300 + 400 * ph, 0x8a7a5a, .35 * (1 - ph)); } + if (L.state === 'run') { const ph = (g.t % 14) / 14; put(L.x - T.sin(L.rot) * (120 + 200 * ph), 40 + 60 * ph, L.z - T.cos(L.rot) * (120 + 200 * ph), 120 + 160 * ph, 0x8a7a5a, .25 * (1 - ph)); } + while (n < sc.pool.length) sc.pool[n++].visible = false; + while (nd < sc.decals.length) sc.decals[nd++].visible = false; + while (nt < sc.tracers.length) sc.tracers[nt++].visible = false; + // the boss glows red over a wind-up and flashes white when a pistol round lands + const fk = sc.boss.visible ? flinch : 0, er = Math.max(glow * .6, fk * .75), eg = fk * .6 + glow * .06, eb = fk * .55; + for (const m of sc.bossMats) m.emissive.setRGB(er, eg, eb); + if (fk > 0) sc.boss.rotation.z += Math.sin(g.t * 1.9) * .05 * fk; + } + // X-ray: the boss's hidden parts (behind a wall, a pillar or Lara) drawn again as a flat translucent silhouette. depthFunc Greater draws only + // where something nearer is in front; the stencil (1 where the boss itself is visible) keeps its own back and front from stacking. + xrayPass() { + const r = this.renderer, ac = r.autoClear; + this.xworld.add(this.boss); this.xworld.overrideMaterial = this.xray; r.autoClear = false; + try { r.render(this.xworld, this.camera); } finally { r.autoClear = ac; this.xworld.overrideMaterial = null; this.world.add(this.boss); } + } + render(g, ctx) { + const t0 = performance.now(); + try { + const L = g.lara, b = g.boss, t = g.t / T.TS; // animation phase in original (30 Hz) ticks, so the look is the same at any clock + vec(L.x, L.y, L.z, this.lara.position); this.lara.rotation.y = -L.rot * A2R; ANIMATE.lara(this.lara, L, t, g); + vec(b.x, b.y || 0, b.z, this.boss.position); this.boss.rotation.set(0, -b.rot * A2R, 0); this.boss.visible = b.hp > 0 || b.state === 'faint'; ANIMATE[b.kind](this.boss, b, t, g); + vec(L.x, T.floorAt(g.map, L.x, L.z) + 4, L.z, this.shadow.position); this.shadow.scale.setScalar(120 * S); + vec(b.x, T.floorAt(g.map, b.x, b.z) + 5, b.z, this.bshadow.position); this.bshadow.scale.setScalar((T.CREATURES[b.kind].shadow || 300) * S); + this.effects(g, t); + for (let i = 0; i < this.torches.length; i++) this.torches[i].material.opacity = .62 + .3 * Math.sin(t * .3 + i * 2); + this.frame(g); + this.renderer.render(this.world, this.camera); + if (this.boss.visible) this.xrayPass(); + ctx.drawImage(this.view, 0, 0, 854, 480); + this.times.push(performance.now() - t0); if (this.times.length > 120) this.times.shift(); + this.ready = true; this.error = null; + } catch (e) { this.ready = false; this.error = String(e && e.stack || e); throw e; } + } + close() { if (this.closed) return; this.closed = true; this.ready = false; for (const r of this.resources) r.dispose && r.dispose(); this.renderer.dispose(); this.renderer.forceContextLoss(); this.resources = []; } + } + R.render = (g, ctx) => { + let m = byCanvas.get(ctx.canvas); if (!m) { m = new Map(); byCanvas.set(ctx.canvas, m); } + let s = m.get(g.key); if (!s || s.closed) { s = new Scene(g.key, ctx.canvas, g.boss.kind); m.set(g.key, s); } + s.render(g, ctx); m.last = s; return s; + }; + const PV = new TH.Vector3(); + // Screen position of a game-space point in the last rendered view (for the HUD's lock reticle and edge arrow). + R.project = (ctx, x, y, z) => { + const m = ctx && byCanvas.get(ctx.canvas), s = m && m.last; if (!s || s.closed) return null; + const cam = s.camera; PV.set(x * S, y * S, -z * S).applyMatrix4(cam.matrixWorldInverse); + const front = PV.z < -cam.near, cx = PV.x, cy = PV.y; PV.set(x * S, y * S, -z * S).project(cam); + return { x: (PV.x + 1) * 427, y: (1 - PV.y) * 240, front, cx, cy }; + }; + // The lens position of the last rendered view, in game units (for the HUD's line-of-sight test). + R.eye = ctx => { const m = ctx && byCanvas.get(ctx.canvas), s = m && m.last; if (!s || s.closed) return null; const p = s.camera.position; return { x: p.x / S, y: p.y / S, z: -p.z / S }; }; + R.status = ctx => { + const m = ctx && byCanvas.get(ctx.canvas); let ready = false, error = null; + if (m) for (const s of m.values()) { if (!s.closed && s.renderer.getContext().isContextLost()) { s.ready = false; s.error = 'WebGL context lost'; } ready = ready || (s.ready && !s.closed); error = error || s.error; } + return { renderer: 'webgl-tombraider', kind: 'perspective', ready, error }; + }; + R.metrics = ctx => { const m = ctx && byCanvas.get(ctx.canvas); if (!m || !m.last || m.last.closed) return null; const a = m.last.times; return { frames: a.length, avg_ms: a.reduce((x, y) => x + y, 0) / (a.length || 1), max_ms: Math.max(0, ...a) }; }; + R.close = ctx => { const m = ctx && byCanvas.get(ctx.canvas); if (!m) return; for (const s of m.values()) s.close(); byCanvas.delete(ctx.canvas); }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/scripted.js b/environments/games/web/games/tombraider_remake/scripted.js new file mode 100644 index 0000000000000000000000000000000000000000..3930ca67263b701a4de3b6e68503820f5c29734f --- /dev/null +++ b/environments/games/web/games/tombraider_remake/scripted.js @@ -0,0 +1,134 @@ +/* Tomb Raider (1996) boss arenas - the standard scripted controller. Privileged state, legal keys only, look-ahead on copies of the game. + Blinding: the copies never carry the live RNG. Before every simulated tick the copy is + reseeded from a multiply mix of (tick, sample), so a look-ahead can only learn what is already decided (states, timers, missiles), never a + coin flip that has not happened yet. Each candidate is scored over three sampled futures: half worst case, half mean. + 60 Hz (tr1-arena@2): the horizon is 2 s = 120 ticks; a decision is taken every 2 ticks and held for both, exactly as a packet's six hold + sets are applied by the runtime, so the simulated future is the one the packet will produce. */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { wrap, deg, atan } = T; + const ZERO = [0, 0, 0], HZ = T.HZ, SUB = HZ / 30, HORIZON = 2 * HZ, SAMPLES = 3, LIFE = { winged: 40 }; // per-boss price of one point of the player's health (default 16) + const mix = (t, k) => { let h = Math.imul(t + 40503, 0x85EBCA6B) ^ Math.imul(k + 7919, 0xC2B2AE35); h = Math.imul(h ^ (h >>> 15), 0x2C1B3C6D); h = Math.imul(h ^ (h >>> 13), 0xC2B2AE35); return ((h ^ (h >>> 16)) >>> 0) || 1; }; + M.lookaheadSeed = mix; + const bearing = (L, b) => atan(b.x - L.x, b.z - L.z); + const turnKey = (err, slack) => Math.abs(err) <= slack ? null : err < 0 ? 'A' : 'D'; + // One action = a small closed-loop rule re-evaluated every simulated tick; its first six ticks are the packet. + function keysFor(c, act) { + const L = c.lara, b = c.boss, to = bearing(L, b), keys = ['J']; + if (L.gun !== 'ready') { keys[0] = 'K'; return keys; } + if (act.m === 'stand') { + const k = turnKey(wrap(to - L.rot), deg(10)); if (k && L.state === 'stop') keys.push(k); + } else if (act.m === 'run') { + keys.push('W'); const k = turnKey(wrap(to + act.a - L.rot), deg(4)); if (k) keys.push(k); + } else if (act.m === 'jump') { + // Keep facing the boss between hops: the rex only breaks into its run while Lara has her back to it (flags, enemy_facing). + const k = turnKey(wrap(to - L.rot), deg(14)); + if (L.state === 'stop' && k) keys.push(k); + else if (L.state === 'stop' || L.state === 'compress') keys.push('Space', act.k); + else if (L.state === 'jump' && k) keys.push(k); + } else if (act.m === 'hop') keys.push('S'); + else if (act.m === 'step') keys.push(act.k); + else if (act.m === 'leap') { // a running jump across her line: 2790 per second in the air, twice the run, the fastest way out of a blast + const k = turnKey(wrap(to + act.a - L.rot), deg(8)); + if (L.state === 'run' && !k) keys.push('W', 'Space'); else { keys.push('W'); if (k) keys.push(k); } + } + else if (act.m === 'cover') { // run to the side of a pillar away from the boss, then hold there facing it + const p = coverPoint(c, act.cell), dx = p.x - L.x, dz = p.z - L.z; + if (Math.hypot(dx, dz) > 220) { keys.push('W'); const k = turnKey(wrap(atan(dx, dz) - L.rot), deg(6)); if (k) keys.push(k); } + else { const k = turnKey(wrap(to - L.rot), deg(10)); if (k && L.state === 'stop') keys.push(k); } + } + return keys; + } + // Interior solid cells (pillars) of the arena: a pure function of the map, cached by map identity. + const pillarCache = new WeakMap(); + function pillars(m) { + if (pillarCache.has(m)) return pillarCache.get(m); + const out = []; for (let j = 1; j < m.h - 1; j++) for (let i = 1; i < m.w - 1; i++) if (m.cells[j * m.w + i] === T.WALL && [[1, 0], [-1, 0], [0, 1], [0, -1]].some(([a, b]) => m.cells[(j + b) * m.w + i + a] !== T.WALL)) out.push(j * m.w + i); + pillarCache.set(m, out); return out; + } + function coverPoint(c, cell) { + const m = c.map, i = cell % m.w, j = (cell - i) / m.w, W = T.WALL_L, cx = (i + .5) * W, cz = (j + .5) * W, b = c.boss; + const dx = cx - b.x, dz = cz - b.z, d = Math.hypot(dx, dz) || 1, r = W * 0.5 + T.LARA_RADIUS + 140; + return { x: T.clamp(cx + dx / d * r, W + 120, (m.w - 1) * W - 120), z: T.clamp(cz + dz / d * r, W + 120, (m.h - 1) * W - 120) }; + } + function rollout(g0, act, sample, H, rec) { + const c = M.copyGame(g0); c.noCamera = true; // the camera rig is cosmetic: nothing below reads it + const start = { lara: c.lara.hp, boss: T.CREATURES[c.boss.kind].bossHp ? T.CREATURES[c.boss.kind].bossHp(c.boss) : c.boss.hp }; + let prev = new Set(c.heldKeys || []), died = -1, keys = null; + for (let i = 0; i < H && !c.outcome; i++) { + if (i % SUB === 0) { keys = keysFor(c, act); if (rec) rec.push(keys); } // one decision per hold set (two ticks at 60 Hz) + const set = new Set(keys), pressed = new Set(keys.filter(k => !prev.has(k))); + c.rng = mix(c.t, sample); c.events = []; + c.update(set, pressed, ZERO); c.t++; prev = set; + if (c.lara.hp <= 0 && died < 0) died = Math.floor(i / SUB); + } + return { c, start, died }; + } + const wallCost = (c, reach, k) => { const L = c.lara, e = Math.min(L.x, L.z, c.map.w * T.WALL_L - L.x, c.map.h * T.WALL_L - L.z); return e < reach ? -(reach - e) * k : 0; }; + const SAFETY = { + lizard(c) { + const L = c.lara, b = c.boss, i = T.aiInfo(c, b, T.CREATURES.lizard.pivot); + let s = 0; + if (i.bite && i.distance < Math.pow(2100, 2)) s -= 400; // inside the zone the next stop turns into a bite + if (b.state === 'bite' && i.distance < Math.pow(2400, 2)) s -= 300; + const near = Math.hypot(b.x - L.x, b.z - L.z); // trample: the run state hurts every tick of contact + if (near < 2600) s -= (2600 - near) * (b.state === 'run' ? 0.12 : 0.03); + const edge = Math.min(L.x, L.z, c.map.w * T.WALL_L - L.x, c.map.h * T.WALL_L - L.z); + if (edge < 2200) s -= (2200 - edge) * 0.2; + return s; + }, + gunman: c => SAFETY.human(c), duelist: c => SAFETY.human(c), + // Missiles are dodged by the simulated futures themselves; what the score adds is where to stand. Centaur: outside its kick. Torso: outside its arms, and + // far outside once Lara is low enough to be grabbed. Natla: in the open, off the walls, so a bomb's blast has room to miss. + quadruped(c) { const L = c.lara, b = c.boss, d = Math.hypot(b.x - L.x, b.z - L.z); let s = 0; if (d < 2600) s -= (2600 - d) * 0.12; return s + wallCost(c, 1500, 0.1); }, + fleshgiant(c) { const L = c.lara, b = c.boss, d = Math.hypot(b.x - L.x, b.z - L.z), keep = L.hp > 500 ? 3200 : 3800; let s = 0; if (d < keep) s -= (keep - d) * 0.5; return s + wallCost(c, 1400, 0.1); }, + // A bomb dropped from overhead lands inside its blast whatever she aims at, so keep her at a slant: far enough that the bomb's flight can be stepped out of. + winged(c) { const L = c.lara, b = c.boss, d = Math.hypot(b.x - L.x, b.z - L.z); let s = wallCost(c, 1700, 0.08); if (b.flyMode && d < 4500) s -= (4500 - d) * 0.3; // airborne (or taking off): a bomb from overhead lands inside its own 1024 blast before she can be outrun; distance buys flight time + if (b.stage === 1 && b.y <= 300 && d < 4200) s -= (4200 - d) * 0.06 * (c.tierScale.damage); // on foot her volley of three is aimed at a spot; the farther away, the longer the flight to step out of + // Stage 2: a shard every 20 ticks, aimed where she stands looking. A shard at 250/tick crosses 3 sectors in 12 ticks, so distance buys time to sidestep. + if (b.stage === 2 && d < 5000) s -= (5000 - d) * 0.03 * c.tierScale.damage; + return s; }, + // Gunmen: what matters is his line of fire. Breaking it (a pillar between) or standing beyond the zero-hit distance is safe; + // standing in his open sight close in is what costs. Shown for the score only; the hit roll itself stays in the simulated futures. + human(c) { + const L = c.lara, b = c.boss, d = Math.hypot(b.x - L.x, b.z - L.z), sight = T.los(c.map, b.x, b.y + 768, b.z, L.x, L.y + 768, L.z); + // While he escapes he runs and never stops to aim (his run state ignores targets in that mood), so his sight costs little and closing in + // buys accuracy (the 8 degree spread misses half the shots beyond 4 sectors): chase him then, keep the old caution otherwise. + const esc = b.mood === 'escape'; + let s = 0; if (sight) s -= Math.max(0, 6200 - d) * 0.025 * Math.min(1, b.damage / 75) * (esc ? 0.25 : 1); + if (esc && d > 1600) s -= (d - 1600) * 0.1; + // A fight against a man who hides behind pillars is also lost to time: when he is not escaping and the pillars break every line, the + // look-ahead sees no damage either way and stands still. A small price on a broken line makes it step round to find one. + if (!esc && !sight) s -= 300; + const edge = Math.min(L.x, L.z, c.map.w * T.WALL_L - L.x, c.map.h * T.WALL_L - L.z); if (edge < 1300) s -= (1300 - edge) * 0.1; + return s; + }, + }; + function score(g0, r, kind) { + const c = r.c, cre = T.CREATURES[kind], hp = cre.bossHp ? cre.bossHp(c.boss) : c.boss.hp; + let s = (r.start.boss - hp) * 30 - (r.start.lara - c.lara.hp) * (LIFE[kind] || 16); // 1 boss hp may cost about 2 of the player's (the hard budget); the shard boss gets a dearer price: standing to trade shots loses there + if (r.died >= 0) s -= 200000 - r.died * 1000; // died counts hold sets (1/30 s), as at 30 Hz + if (c.outcome === 'win') s += 5000; + return s + SAFETY[kind](c); + } + const ACTIONS = [{ m: 'stand' }, { m: 'hop' }, { m: 'step', k: 'Q' }, { m: 'step', k: 'E' }, { m: 'jump', k: 'A' }, { m: 'jump', k: 'D' }, { m: 'jump', k: 'S' }]; + for (const a of [0, 45, 90, 135, 180, -45, -90, -135]) ACTIONS.push({ m: 'run', a: deg(a) }); + const LEAPS = [90, -90, 135, -135, 180].map(a => ({ m: 'leap', a: deg(a) })); + M.scripted = function (g) { + const L = g.lara, kind = g.boss.kind; + const acts = T.CREATURES[kind].gunman ? ACTIONS.concat(pillars(g.map).map(cell => ({ m: 'cover', cell }))) : kind === 'winged' ? ACTIONS.concat(LEAPS) : ACTIONS; + // Every action gets one future; only the five best get the other two, so the three-sample rule costs 25 rollouts rather than 45. + const first = acts.map(act => ({ act, s: score(g, rollout(g, act, 0, HORIZON), kind) })).sort((x, y) => y.s - x.s).slice(0, 5); + let best = null, bestS = -Infinity; + for (const f of first) { + let worst = f.s, sum = f.s; + for (let k = 1; k < SAMPLES; k++) { const s = score(g, rollout(g, f.act, k, HORIZON), kind); worst = Math.min(worst, s); sum += s; } + const s = 0.5 * worst + 0.5 * sum / SAMPLES; + if (s > bestS) { bestS = s; best = f.act; } + } + const rec = []; rollout(g, best, 0, 6 * SUB, rec); + while (rec.length < 6) rec.push([]); + if (L.hp <= 500 && L.medi > 0 && !(g.heldKeys || []).includes('R')) { rec[0] = rec[0].slice(0, 3); rec[0].push('R'); } + return { holds: rec, mouse: [0, 0, 0] }; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/tr1camera.js b/environments/games/web/games/tombraider_remake/tr1camera.js new file mode 100644 index 0000000000000000000000000000000000000000..be486a18348caf3bd9558d95c8aa25275f9d75e0 --- /dev/null +++ b/environments/games/web/games/tombraider_remake/tr1camera.js @@ -0,0 +1,69 @@ +/* Tomb Raider (1996) boss arenas - the camera rig, tr1-arena@3 (2026-11-08). + Cosmetic: nothing in the simulation or the scripted controller reads it, it never draws from the RNG, and the controller's look-ahead copies skip + it (g.noCamera). It lives in the state (as camYaw always did) so that a frame stays a pure function of the state while the view moves smoothly. + TRX camera/box_camera.c: the chase camera trails her facing; M_Combat (a target held) swings the boom behind her along the target's bearing + (target_angles[0] + rot.y), 2560 out - here 2200, these rooms are 7 to 18 sectors wide. + BossBench additions, for an agent that sees only the frame ( B): + - with no target held, a boss within 100 degrees of her facing pulls the view up to 35 degrees toward it; + - ten times a second the boom picks, among nine directions within 90 degrees of the wanted one, the one with her and the boss in clear view + (a pillar between the lens and the boss is why the old view so often showed a wall), preferring small swings and the current choice; + - in combat the boom swings 12 degrees off her back (the lens over her right shoulder, she stands left of centre), so a boss straight ahead + is not hidden behind her own body. */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { wrap, sin, cos, atan, deg, clamp } = T; + const C = T.CAM = { HEAD: 620, CHASE: 1700, COMBAT: 2200, UP: 820, PAD: 150, SHOULDER: -deg(12), LIFT_MAX: 2600, + CEIL: { valley: 1e9, hall: 4 * 1024, crypt: 4 * 1024, pit: 5 * 1024, gold: 6 * 1024 } }; // = the renderer's wall heights of the roofed themes + const YAW_BLEND = T.blend(0.12), LOCK_BLEND = T.blend(0.2), DIST_BLEND = T.blend(0.15), LIFT_BLEND = T.blend(0.35); + const OFFS = [0, 1, -1, 2, -2, 3, -3, 4, -4].map(k => k * deg(22.5)); + T.camRig = rot => ({ off: 0, dist: C.CHASE, lift: 0, lock: 0, fr: 0, look: rot || 0 }); + const ceilOf = g => C.CEIL[M.arenas[g.key].theme] || 1e9; + C.ceilOf = ceilOf; + // The boom from her head out along yaw, cut where the lens (with a pad for the near plane that grows with the boom: at her own position she is + // legitimately close to a wall, the lens is not) would enter a wall or come within 200 of the ceiling. + T.camBoom = (g, yaw, len, up) => { + const L = g.lara, m = g.map, head = L.y + C.HEAD, sy = sin(yaw), cy = cos(yaw), top = ceilOf(g) - 200; + for (let d = 64; d <= len; d += 32) { + const x = L.x - sy * d, y = head + up * d / len, z = L.z - cy * d, p = Math.min(C.PAD, d * 0.4); + if (y > top || T.floorAt(m, x, z) >= y - 40 || T.floorAt(m, x + p, z) >= y - 40 || T.floorAt(m, x - p, z) >= y - 40 || T.floorAt(m, x, z + p) >= y - 40 || T.floorAt(m, x, z - p) >= y - 40) return Math.max(0, d - 64); + } + return len; + }; + // In a corner every boom is short: the lens rises above her instead (up to 2600, never into the ceiling); the renderer widens and tilts the view. + T.camLift = (g, r, len) => r < 900 ? Math.max(0, Math.min((900 - r) * 3, C.LIFT_MAX, ceilOf(g) - 260 - (g.lara.y + C.HEAD) - C.UP * r / len)) : 0; + // The boss points the lens should see: its aim point (where the pistols' auto-aim shoots) and its hit-sphere centres. + T.camBossPoints = b => { const c = T.CREATURES[b.kind], a = c.aimPoint(b); return [[a.x, a.y, a.z]].concat(c.spheres(b).map(s => [s[0], s[1], s[2]])); }; + const bossShown = b => b.hp > 0 || b.state === 'faint'; + function lens(g, yaw, len) { + const L = g.lara, up = C.UP + L.lookPitch * 18, r = T.camBoom(g, yaw, len, up); + return { r, x: L.x - sin(yaw) * r, y: L.y + C.HEAD + up * r / len + T.camLift(g, r, len), z: L.z - cos(yaw) * r }; + } + function pickOffset(g, base, len, shoulder) { + const L = g.lara, m = g.map, pts = bossShown(g.boss) ? T.camBossPoints(g.boss) : []; + let best = 0, bestS = -Infinity; + for (const k of OFFS) { + const p = lens(g, wrap(base + k + shoulder), len); + const her = (T.los(m, p.x, p.y, p.z, L.x, L.y + 450, L.z) ? 2 : 0) + (T.los(m, p.x, p.y, p.z, L.x, L.y + 700, L.z) ? 2 : 0); + const seen = pts.length ? pts.filter(q => T.los(m, p.x, p.y, p.z, q[0], q[1], q[2])).length / pts.length : 0; + const s = her + 3 * seen + 1.5 * Math.min(1, p.r / 900) - 1.2 * Math.abs(k) / deg(90) - (k === L.cam.off ? 0 : 0.4); + if (s > bestS) { bestS = s; best = k; } + } + return best; + } + T.camTick = g => { + if (g.noCamera) return; + const L = g.lara, b = g.boss, c = L.cam; + c.lock += ((L.target ? 1 : 0) - c.lock) * LOCK_BLEND; + let base = L.rot, frame = 0; + if (L.target) { base = wrap(L.rot + L.targetYaw); frame = 1; } + else if (bossShown(b)) { const rel = wrap(atan(b.x - L.x, b.z - L.z) - L.rot); if (Math.abs(rel) < deg(100)) { base = wrap(L.rot + clamp(rel, -deg(35), deg(35))); frame = 1; } } + c.fr += (frame - c.fr) * LOCK_BLEND; + c.look = wrap(c.look + wrap(base - c.look) * YAW_BLEND); + const len = C.CHASE + (C.COMBAT - C.CHASE) * c.lock, shoulder = C.SHOULDER * c.lock; + if (g.t % 6 === 0) c.off = pickOffset(g, base, len, shoulder); + L.camYaw = wrap(L.camYaw + wrap(wrap(base + c.off) - L.camYaw) * YAW_BLEND); + const r = T.camBoom(g, wrap(L.camYaw + shoulder), len, C.UP + L.lookPitch * 18); + c.dist = r < c.dist ? r : c.dist + (r - c.dist) * DIST_BLEND; + c.lift += (T.camLift(g, c.dist, len) - c.lift) * LIFT_BLEND; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/tr1core.js b/environments/games/web/games/tombraider_remake/tr1core.js new file mode 100644 index 0000000000000000000000000000000000000000..98dbffb6112c0e951fc8f54bc70a2753d5da1c3e --- /dev/null +++ b/environments/games/web/games/tombraider_remake/tr1core.js @@ -0,0 +1,120 @@ +/* Tomb Raider (1996) boss arenas, rules tr1-arena@2 - core: units, RNG, sector map, collision, line of sight, pathing. + Independent reimplementation; constants are read from TRX 4b9b64f and OpenLara 3b268ca, no code is + copied and no original data (levels, animations, models, textures, audio) is used. + Conventions follow the original: world units (1 sector = 1024, 1 click = 256), binary angles (65536 = 360 degrees, + 0 = +z, positive = turn right). One difference: y grows upward here (the original's y grows down). + Clock (tr1-arena@2, 2026-11-06): the original runs 30 ticks per second; this reimplementation runs 60. Every constant below and in the other + files is still written in the original's 30 Hz units and converted where it is defined, with the helpers here: + per-tick velocities T.v, per-tick accelerations T.acc, durations T.n, per-tick chances T.chance, per-tick blend factors T.blend. */ +(function (root) { + 'use strict'; + const N = root.NativeBench, M = root.TombRaiderGame = {}, T = M.T = {}; + T.HZ = 60; const TS = T.TS = T.HZ / 30; // new ticks per original tick + T.v = x => x / TS; // units (or angle) per original tick -> per new tick + T.acc = x => x / (TS * TS); // per original tick, per original tick -> per new tick squared + T.n = x => Math.round(x * TS); // a duration of x original ticks -> new ticks (exact for 30 -> 60) + T.chance = c => 32768 * (1 - Math.pow(1 - c / 32768, 1 / TS)); // a 0..32767 threshold rolled every original tick -> rolled every new tick, same rate per second + T.blend = k => 1 - Math.pow(1 - k, 1 / TS); // x += (target - x) * k every original tick + T.anim = tab => Object.fromEntries(Object.entries(tab).map(([k, a]) => [k, Object.assign({}, a, { len: T.n(a.len), speed: T.v(a.speed) }, a.rot ? { rot: T.v(a.rot) } : {})])); // 30 Hz ANIM table -> 60 Hz + Object.assign(T, { WALL_L: 1024, STEP_L: 256, GRAVITY: T.acc(6), FAST_FALL: T.v(128), FALL_TAIL: T.acc(1), STEPUP: 384 }); + const TAU = Math.PI * 2; + T.deg = d => Math.round(d * 65536 / 360); + T.DEG90 = 16384; T.DEG180 = 32768; + T.wrap = a => ((Math.round(a) + 32768) & 65535) - 32768; // int16 wrap-around, as the original's angle arithmetic + T.sin = a => Math.sin(a * TAU / 65536); + T.cos = a => Math.cos(a * TAU / 65536); + T.atan = (dx, dz) => Math.round(Math.atan2(dx, dz) * 65536 / TAU); // Math_Atan(z, x) + T.rand = g => Math.floor(N.rand(g) * 32768); // Random_GetControl: 0..32767 + T.clamp = N.clamp; + T.event = (g, type, data) => { g.events.push(Object.assign({ type, t: g.t }, data || {})); }; + T.fx = (g, kind, x, y, z, life, extra) => { // cosmetic, read by the renderer only; never touches the RNG. life in original ticks + g.fx.push(Object.assign({ kind, x, y, z, t0: g.t, life: T.n(life), id: g.fxSeq++ }, extra || {})); + if (g.fx.length > 80) g.fx.splice(0, g.fx.length - 80); + }; + + // ---------------- sector map: rows of characters, one per sector. '#' = solid to the ceiling, digits = floor height in clicks ---------------- + const WALL = T.WALL = 1e9; + T.parseMap = rows => { + const h = rows.length, w = rows[0].length, cells = []; + for (const r of rows) { if (r.length !== w) throw Error('uneven map'); for (const c of r) cells.push(c === '#' ? WALL : c === '.' ? 0 : Number(c) * T.STEP_L); } + return { w, h, cells: Object.freeze(cells), rows }; + }; + T.floorAt = (m, x, z) => { + const i = Math.floor(x / T.WALL_L), j = Math.floor(z / T.WALL_L); + if (i < 0 || j < 0 || i >= m.w || j >= m.h) return WALL; + return m.cells[j * m.w + i]; + }; + // Highest floor under a square of half-width r: the footprint test a sector grid allows. + const floorUnder = T.floorUnder = (m, x, z, r) => Math.max(T.floorAt(m, x - r, z - r), T.floorAt(m, x + r, z - r), T.floorAt(m, x - r, z + r), T.floorAt(m, x + r, z + r)); + // Axis-separated slide against sectors a body at height y cannot step onto. Returns what blocked it. + T.slide = (m, e, dx, dz, r, climb) => { + let hitX = false, hitZ = false; + if (dx && floorUnder(m, e.x + dx, e.z, r) - e.y <= climb) e.x += dx; else if (dx) hitX = true; + if (dz && floorUnder(m, e.x, e.z + dz, r) - e.y <= climb) e.z += dz; else if (dz) hitZ = true; + return { hitX, hitZ }; + }; + // LOS_Check on a sector grid: 64-unit march, blocked by any floor rising above the ray. + T.los = (m, ax, ay, az, bx, by, bz) => { + const d = Math.hypot(bx - ax, bz - az), n = Math.max(1, Math.ceil(d / 64)); + for (let i = 1; i < n; i++) { const f = i / n; if (T.floorAt(m, ax + (bx - ax) * f, az + (bz - az) * f) > ay + (by - ay) * f) return false; } + return true; + }; + const corridor = (m, ax, az, bx, bz, r, y) => { // a body of half-width r can walk straight from a to b + const d = Math.hypot(bx - ax, bz - az), n = Math.max(1, Math.ceil(d / 128)); + for (let i = 0; i <= n; i++) { const f = i / n; if (floorUnder(m, ax + (bx - ax) * f, az + (bz - az) * f, r) > y + T.STEPUP) return false; } + return true; + }; + // ---------------- pathing: the original's AI boxes reduced to sectors. A breadth-first flow field from the target's sector; + // the creature aims at the farthest sector centre along it that it can reach in a straight line (Box_CalculateTarget's role). + // The cache is a pure function of (map, sector), so it holds no simulation state. + const flows = new WeakMap(); + function flow(m, ti, tj) { + let byT = flows.get(m); if (!byT) { byT = new Map(); flows.set(m, byT); } + const key = tj * m.w + ti; let dist = byT.get(key); + if (dist) return dist; + dist = new Int16Array(m.w * m.h).fill(-1); + const q = [key]; dist[key] = 0; + for (let k = 0; k < q.length; k++) { + const c = q[k], i = c % m.w, j = (c - i) / m.w; + for (const [a, b] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { + const u = i + a, v = j + b; if (u < 0 || v < 0 || u >= m.w || v >= m.h) continue; + const n = v * m.w + u; if (dist[n] >= 0 || m.cells[n] === WALL) continue; + dist[n] = dist[c] + 1; q.push(n); + } + } + byT.set(key, dist); + return dist; + } + T.pathTarget = (m, e, r, tx, tz) => { + if (corridor(m, e.x, e.z, tx, tz, r, e.y)) return { x: tx, z: tz }; + const ti = T.clamp(Math.floor(tx / T.WALL_L), 0, m.w - 1), tj = T.clamp(Math.floor(tz / T.WALL_L), 0, m.h - 1), dist = flow(m, ti, tj); + let i = T.clamp(Math.floor(e.x / T.WALL_L), 0, m.w - 1), j = T.clamp(Math.floor(e.z / T.WALL_L), 0, m.h - 1); + let best = { x: tx, z: tz }, found = false; + for (let guard = 0; guard < 64; guard++) { + const here = dist[j * m.w + i]; if (here <= 0) break; + let nx = -1, ny = -1, low = here; + for (const [a, b] of [[0, -1], [1, 0], [0, 1], [-1, 0]]) { + const u = i + a, v = j + b; if (u < 0 || v < 0 || u >= m.w || v >= m.h) continue; + const dn = dist[v * m.w + u]; if (dn >= 0 && dn < low) { low = dn; nx = u; ny = v; } + } + if (nx < 0) break; + i = nx; j = ny; + const cx = (i + 0.5) * T.WALL_L, cz = (j + 0.5) * T.WALL_L; + if (corridor(m, e.x, e.z, cx, cz, r, e.y) || !found) { best = { x: cx, z: cz }; found = true; } else break; + } + return best; + }; + // Lara's body as the vertical segment her spheres cover, against a sphere: Collide_TestCollision reduced to one capsule. + T.touchesLara = (L, s, x, y, z, r) => { + const lo = L.y + T.LARA_RADIUS, hi = L.y + T.LARA_HEIGHT - T.LARA_RADIUS, cy = T.clamp(y, lo, hi), R = r + T.LARA_RADIUS; + const dx = x - L.x, dz = z - L.z, dy = y - cy; + return dx * dx + dy * dy + dz * dz < R * R; + }; + // Ray (unit direction) against a sphere, front side only: the test in Gun_FireWeapon, in world space. + T.rayHitsSphere = (ox, oy, oz, dx, dy, dz, sx, sy, sz, r) => { + const px = sx - ox, py = sy - oy, pz = sz - oz, along = px * dx + py * dy + pz * dz; + if (along <= r) return null; + const qx = px - along * dx, qy = py - along * dy, qz = pz - along * dz; + return qx * qx + qy * qy + qz * qz <= r * r ? along - r : null; + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/tr1creature.js b/environments/games/web/games/tombraider_remake/tr1creature.js new file mode 100644 index 0000000000000000000000000000000000000000..7289b773b1894f979a4807a95a1e57fb29dd27a2 --- /dev/null +++ b/environments/games/web/games/tombraider_remake/tr1creature.js @@ -0,0 +1,59 @@ +/* Tomb Raider (1996) boss arenas - the shared creature layer: AI_INFO, turning, moving, contact, generic body tests. + Documented (TRX creature/common.c, creature/shooting.c, creature/const.h): Creature_AIInfo, Creature_Turn, the shot roll. + Approximation: the original changes state only where the animation data allows it; here each state has one tick + length (per boss, in its ANIM table), and a pending goal is taken when that length is up. See */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { wrap, sin, cos, atan, clamp } = T; + T.CREATURES = {}; + const FRONT_ARC = T.DEG90; + Object.assign(T, { BITE_HEIGHT: 256, SHOOT_RANGE: 7 * T.WALL_L, MISS_CHANCE: 0x2000 }); + // Creature_AIInfo. `distance` is squared, as in the original; pivot is the object's pivot_length. + T.aiInfo = (g, b, pivot) => { + const L = g.lara, x = L.x - sin(b.rot) * (pivot || 0) - b.x, z = L.z - cos(b.rot) * (pivot || 0) - b.z; + const angle = atan(x, z), rel = wrap(angle - b.rot), facing = wrap(angle - L.rot + T.DEG180); + const ahead = rel > -FRONT_ARC && rel < FRONT_ARC; + return { distance: x * x + z * z, angle: rel, facing, ahead, bite: ahead && Math.abs(L.y - b.y) <= T.BITE_HEIGHT }; + }; + // Creature_Turn, then the forward move the animation would have made. speed 0 does not turn (TR1 branch). + T.creatureMove = (g, b, speed, maxTurn, radius) => { + let turned = 0; + if (speed > 0 && maxTurn > 0) { + const t = T.pathTarget(g.map, b, radius, g.lara.x, g.lara.z), dx = t.x - b.x, dz = t.z - b.z; + const angle = wrap(atan(dx, dz) - b.rot); + let cap = maxTurn; + if (angle > FRONT_ARC || angle < -FRONT_ARC) { + const range = speed * 16384 / maxTurn; + if (dx * dx + dz * dz < range * range) cap = maxTurn / 2; + } + turned = clamp(angle, -cap, cap); + b.rot = wrap(b.rot + turned); + T.slide(g.map, b, sin(b.rot) * speed, cos(b.rot) * speed, radius, T.STEPUP); + b.y = T.floorUnder(g.map, b.x, b.z, radius); + } + return turned; + }; + T.bodySpheres = (b, list) => { + const s = sin(b.rot), c = cos(b.rot); + return list.map(([f, h, r, side]) => [b.x + s * f + c * (side || 0), b.y + h, b.z + c * f - s * (side || 0), r]); + }; + const PUSH = T.v(40); // push-out per tick, 40 per original tick + // Creature_Collision + Lara_Push reduced to spheres: pushes Lara out sideways and reports touch_bits != 0. + T.pushLara = (g, spheres) => { + const L = g.lara; let touch = false; + for (const [x, y, z, r] of spheres) { + if (!T.touchesLara(L, null, x, y, z, r)) continue; + touch = true; + const dx = L.x - x, dz = L.z - z, d = Math.hypot(dx, dz) || 1, R = r + T.LARA_RADIUS; + if (d < R) T.slide(g.map, L, dx / d * Math.min(R - d, PUSH), dz / d * Math.min(R - d, PUSH), T.LARA_RADIUS, T.STEPUP); + } + return touch; + }; + // Linear between the three tier anchors, held outside them. Purely a function of d. + T.tierValue = (d, tiers, a) => { + if (d <= tiers.easy) return a[0]; + if (d >= tiers.hard) return a[2]; + const lo = d <= tiers.normal, x0 = lo ? tiers.easy : tiers.normal, x1 = lo ? tiers.normal : tiers.hard, y0 = lo ? a[0] : a[1], y1 = lo ? a[1] : a[2]; + return y0 + (y1 - y0) * (d - x0) / (x1 - x0); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/tombraider_remake/tr1player.js b/environments/games/web/games/tombraider_remake/tr1player.js new file mode 100644 index 0000000000000000000000000000000000000000..5efaecff1be3d87265c4a15e076401978b21a6bf --- /dev/null +++ b/environments/games/web/games/tombraider_remake/tr1player.js @@ -0,0 +1,252 @@ +/* Tomb Raider (1996) boss arenas - Lara: state machine, turning, jumps, pistols. See sections B-D. + Documented (TRX gun/pistols.c, gun/misc.c, gun/control.c, lara/const.h, lara/state/*.c, lara/control.c): the turn rates and their order + of application, gravity, the pistol arm-frame counter (10 ticks per shot, both hands), spread, lock cone, arm arcs, aim speed. + Approximation (the original keeps these in its animation data, which is copyrighted and not used): every speed and duration in APPROX. */ +(function (root) { + 'use strict'; + const M = root.TombRaiderGame, T = M.T, { wrap, sin, cos, atan, deg, clamp } = T; + Object.assign(T, { LARA_MAX_HP: 1000, LARA_RADIUS: 100, LARA_HEIGHT: 762, GUN_HEIGHT: 650 }); + // lara/const.h at 30 Hz: +409 per tick while a turn key is held, then -364 undo every tick, caps 728 / 1092 / 1456 / 546. The 30 Hz net + // behaviour is a ramp of 45 per tick per tick up to (cap - 364) per tick, and a 364 per tick per tick decay on release. At 60 Hz the undo is + // an acceleration (/4), the ramp too, and each cap is chosen so cap - undo is the original top rate per second (/2). + const TURN_UNDO = T.acc(364), TURN_RATE = T.acc(409 - 364) + TURN_UNDO, capOf = x => T.v(x - 364) + TURN_UNDO; + const SLOW = capOf(728), MED = capOf(1092), FAST = capOf(1456), JUMP_TURN = capOf(546); + // Approximations, written in 30 Hz units (units per original tick, original ticks) and converted; jump numbers give the usual 1 sector standing, + // 2 sectors running over 0.7 s in the air. + const A30 = T.LARA_APPROX30 = { run: 44, walk: 20, back: 30, walkBack: 16, step: 20, accel: 8, compress: 3, jumpUp: 66, jumpStand: 46.5, jumpRun: 93, land: 3, roll: 15, rollSpeed: 16, backHop: 14 }; + const APPROX = T.LARA_APPROX = { run: T.v(A30.run), walk: T.v(A30.walk), back: T.v(A30.back), walkBack: T.v(A30.walkBack), step: T.v(A30.step), accel: T.acc(A30.accel), + compress: T.n(A30.compress), jumpUp: T.v(A30.jumpUp), jumpStand: T.v(A30.jumpStand), jumpRun: T.v(A30.jumpRun), land: T.n(A30.land), roll: T.n(A30.roll), rollSpeed: T.v(A30.rollSpeed), backHop: T.n(A30.backHop) }; + // Arm frames, gun/pistols.c with lara/enum.h. The arm animation advances one frame per original (30 Hz) tick: armTick steps it every TS ticks. + const AIM_START = 0, AIM_BEND = 1, AIM_EXTEND = 3, AIM_END = 4, RECOIL_START = 24, RECOIL_END = 32, RECOIL_FRAME = 9; + // weapons.json5, pistols + const PISTOL = T.PISTOL = { damage: 1, range: 8 * T.WALL_L, aimSpeed: T.v(deg(10)), spread: deg(8), lock: deg(60), armOut: deg(170), armIn: deg(60), drawTicks: T.n(19) }; + const MEDI_SMALL = 500, HOP_MOVE = T.n(A30.backHop - 1), HOP_END = T.n(A30.backHop) + T.TS - 1; + const arm = () => ({ frame: AIM_START, lock: false, ry: 0, rx: 0, flash: 0, sub: 0 }); + + T.spawnLara = (x, z, rot, y) => ({ + x, y: y || 0, z, rot, turnRate: 0, state: 'stop', stateT: 0, speed: 0, moveAngle: rot, fall: 0, airborne: false, hp: T.LARA_MAX_HP, + medi: 2, gun: 'ready', gunT: 0, target: false, targetYaw: 0, targetPitch: 0, armL: arm(), armR: arm(), torso: 0, + mouseFrac: 0, lookPitch: 0, camYaw: rot, cam: T.camRig(rot), hitFlash: 0, shots: 0, hits: 0, damageTaken: 0, bitten: false, + }); + T.laraDamage = (g, n, kind) => { + const L = g.lara; if (L.hp <= 0) return; + L.hp -= n; L.damageTaken += n; + if (L.hp <= 0 && g.oneHpFixture) { g.fixtureSaves = (g.fixtureSaves || 0) + 1; L.hp = 1; L.bitten = false; } + L.hp = Math.max(0, L.hp); L.hitFlash = Math.max(L.hitFlash, T.n(Math.min(12, 3 + n))); + if (n >= 10) T.event(g, 'player_hit', { damage: n, kind }); + }; + const setState = (L, s) => { if (L.state !== s) { L.state = s; L.stateT = 0; } }; + const turnBy = (L, sign, cap) => { L.turnRate = clamp(L.turnRate + sign * TURN_RATE, -cap, cap); }; + function approach(L, to) { L.speed = L.speed < to ? Math.min(to, L.speed + APPROX.accel) : Math.max(to, L.speed - APPROX.accel); } + // Gravity at 60 Hz: the 30 Hz rule is v += 6 then y -= v once per original tick. With a = 6/4 per new tick and a start offset of a(TS-1)/2 the + // new-tick sum over each original tick equals the original step exactly, so heights and air time match the original at every 1/30 s. + const FALL0 = T.GRAVITY * (T.TS - 1) / 2; + function startJump(L, angle, h) { setState(L, 'jump'); L.airborne = true; L.fall = -APPROX.jumpUp + FALL0; L.moveAngle = angle; L.speed = h; } + + function stateTick(g, L, keys, pressed) { + const W = keys.has('W'), S = keys.has('S'), A = keys.has('A'), D = keys.has('D'), slow = keys.has('Shift'), jump = keys.has('Space'); + const Q = keys.has('Q'), E = keys.has('E'), roll = pressed.has('L'), side = A ? -1 : D ? 1 : 0; + L.stateT++; + switch (L.state) { + case 'stop': { + approach(L, 0); L.moveAngle = L.rot; + if (roll) { setState(L, 'roll'); L.moveAngle = L.rot; L.speed = APPROX.rollSpeed; break; } + if (jump) { setState(L, 'compress'); break; } + if (W) { setState(L, slow ? 'walk' : 'run'); break; } + if (S) { setState(L, slow ? 'walkBack' : 'backHop'); break; } + if (Q || E) { setState(L, Q ? 'stepL' : 'stepR'); break; } + if (side) { + // M_TurnLeft/Right + M_FastTurn: with the guns ready Lara goes straight to the fast turn; otherwise once past the slow rate. + if (L.gun === 'ready' || Math.abs(L.turnRate) > SLOW) L.turnRate = side * FAST; + else turnBy(L, side, FAST); + } + break; + } + case 'run': + if (roll) { setState(L, 'roll'); L.moveAngle = L.rot; L.speed = APPROX.rollSpeed; break; } + if (side) turnBy(L, side, FAST); + L.moveAngle = L.rot; + if (jump) { startJump(L, L.rot, APPROX.jumpRun); break; } + if (!W) { setState(L, 'stop'); break; } + if (slow) { setState(L, 'walk'); break; } + approach(L, APPROX.run); + break; + case 'walk': + if (side) turnBy(L, side, SLOW); + L.moveAngle = L.rot; + if (!W) { setState(L, 'stop'); break; } + if (!slow) { setState(L, 'run'); break; } + approach(L, APPROX.walk); + break; + case 'backHop': // LS_FAST_BACK: one committed hop, repeated while S is held + // At 30 Hz a hop cycle is 15 ticks: 1 in stop, 13 moving, 1 ending. The new clock keeps that per second: the hop runs TS - 1 ticks longer + // (the stop tick between hops is one new tick, not one original tick) and moves only over the original's 13 moving ticks. + if (side) turnBy(L, side, MED); + L.moveAngle = wrap(L.rot + T.DEG180); L.speed = L.stateT <= HOP_MOVE ? APPROX.back : 0; + if (L.stateT >= HOP_END) { L.speed = 0; setState(L, 'stop'); } + break; + case 'walkBack': + if (side) turnBy(L, side, SLOW); + L.moveAngle = wrap(L.rot + T.DEG180); L.speed = APPROX.walkBack; + if (!S || !slow) { L.speed = 0; setState(L, 'stop'); } + break; + case 'stepL': case 'stepR': { + const held = L.state === 'stepL' ? Q : E; + L.moveAngle = wrap(L.rot + (L.state === 'stepL' ? -T.DEG90 : T.DEG90)); L.speed = APPROX.step; + if (!held) { L.speed = 0; setState(L, 'stop'); } + break; + } + case 'compress': // M_Compress: the direction read at the end of the crouch picks the jump + approach(L, 0); + if (L.stateT >= APPROX.compress) { + if (W) startJump(L, L.rot, APPROX.jumpStand); + else if (A) startJump(L, wrap(L.rot - T.DEG90), APPROX.jumpStand); + else if (D) startJump(L, wrap(L.rot + T.DEG90), APPROX.jumpStand); + else if (S) startJump(L, wrap(L.rot + T.DEG180), APPROX.jumpStand); + else startJump(L, L.rot, 0); + } + break; + case 'jump': + if (side) turnBy(L, side, JUMP_TURN); + break; + case 'land': // at 30 Hz the last tick of a committed state stands still: here its whole last original tick (TS new ticks) does + approach(L, 0); if (L.stateT > T.n(A30.land - 1)) L.speed = 0; + if (L.stateT >= APPROX.land) { L.speed = 0; setState(L, 'stop'); } + break; + case 'roll': + if (L.stateT >= APPROX.roll) { L.rot = wrap(L.rot + T.DEG180); L.camYaw = wrap(L.camYaw + T.DEG180); L.speed = 0; setState(L, 'stop'); } + break; + } + } + // The turn cap of the current state; the mouse may never turn Lara faster than the keys do. + function turnCap(L) { + switch (L.state) { + case 'stop': case 'run': return FAST - TURN_UNDO; + case 'backHop': return MED - TURN_UNDO; + case 'jump': return JUMP_TURN - TURN_UNDO; + case 'walk': case 'walkBack': return SLOW - TURN_UNDO; + default: return 0; + } + } + T.laraTick = function (g, keys, pressed, mouse) { + const L = g.lara, m = g.map; + if (L.hp <= 0) return; + if (L.hitFlash > 0) L.hitFlash--; + if (pressed.has('R') && L.medi > 0 && L.hp < T.LARA_MAX_HP) { L.medi--; L.hp = Math.min(T.LARA_MAX_HP, L.hp + MEDI_SMALL); T.event(g, 'medipack', { hp: L.hp }); } + stateTick(g, L, keys, pressed); + // lara/control.c: undo first, then apply. Keyboard turning alone never exceeds the cap; the mouse fills up to it, one count = 0.1 degrees. + L.turnRate = L.turnRate > 0 ? Math.max(0, L.turnRate - TURN_UNDO) : Math.min(0, L.turnRate + TURN_UNDO); + const cap = turnCap(L), wanted = mouse[0] * 18.2 + L.mouseFrac; + const total = clamp(L.turnRate + wanted, -Math.max(cap, Math.abs(L.turnRate)), Math.max(cap, Math.abs(L.turnRate))); + const whole = Math.round(total); + L.mouseFrac = cap ? clamp(total - whole, -1, 1) : 0; + L.rot = wrap(L.rot + whole); + L.lookPitch = clamp(L.lookPitch - mouse[1] * 0.1, -60, 60); + // movement + const dx = sin(L.moveAngle) * L.speed, dz = cos(L.moveAngle) * L.speed; + const hit = T.slide(m, L, dx, dz, T.LARA_RADIUS, L.airborne ? 0 : T.STEPUP); + if (L.airborne && (hit.hitX || hit.hitZ)) L.speed = 0; // Lara_Col_Jumper: a wall kills the horizontal speed + const floor = T.floorUnder(m, L.x, L.z, T.LARA_RADIUS); + if (L.airborne) { + L.fall += L.fall < T.FAST_FALL ? T.GRAVITY : T.FALL_TAIL; // lara/common.c + L.y -= L.fall; + if (L.y <= floor && L.fall >= 0) { L.y = floor; L.airborne = false; L.fall = 0; setState(L, 'land'); } + } else if (floor < L.y) { + L.airborne = true; L.fall = FALL0; setState(L, 'jump'); // walked off an edge + } else L.y = floor; + // The camera (camYaw, cam) is updated after the guns by T.camTick (tr1camera.js), from Game.update. + }; + + // ---------------- pistols ---------------- + function targetFrom(g) { + const L = g.lara, b = g.boss, c = T.CREATURES[b.kind], p = c.aimPoint(b); + const gx = L.x, gy = L.y + T.GUN_HEIGHT, gz = L.z; + const dx = p.x - gx, dy = p.y - gy, dz = p.z - gz; + return { p, gx, gy, gz, yaw: atan(dx, dz), pitch: Math.round(Math.atan2(dy, Math.hypot(dx, dz)) * 65536 / (Math.PI * 2)), los: T.los(g.map, gx, gy, gz, p.x, p.y, p.z) }; + } + function considerTarget(g, t) { // M_ConsiderTarget + const L = g.lara, b = g.boss; + if (b.hp <= 0 || (T.CREATURES[b.kind].untargetable && T.CREATURES[b.kind].untargetable(b))) return false; + if (Math.hypot(b.x - L.x, b.y - (L.y + T.GUN_HEIGHT), b.z - L.z) >= PISTOL.range || !t.los) return false; + const ay = wrap(t.yaw - (L.torso + L.rot)), ax = t.pitch; + return Math.abs(ay) <= PISTOL.lock && Math.abs(ax) <= PISTOL.lock; + } + function targetInfo(g, t) { // Gun_TargetInfo + const L = g.lara; + if (!L.target) { L.armL.lock = false; L.armR.lock = false; L.targetYaw = 0; L.targetPitch = 0; return; } + const ay = wrap(t.yaw - L.rot), ax = t.pitch; + if (!t.los) { L.armL.lock = false; L.armR.lock = false; } + else if (Math.abs(ay) <= PISTOL.lock && Math.abs(ax) <= PISTOL.lock) { L.armL.lock = true; L.armR.lock = true; } + else { + if (L.armL.lock && (ay < -PISTOL.armOut || ay > PISTOL.armIn || Math.abs(ax) > deg(80))) L.armL.lock = false; + if (L.armR.lock && (ay < -PISTOL.armIn || ay > PISTOL.armOut || Math.abs(ax) > deg(80))) L.armR.lock = false; + } + L.targetYaw = ay; L.targetPitch = ax; + } + function aimArm(L, a) { // Gun_AimWeapon + const s = PISTOL.aimSpeed, dy = a.lock ? L.targetYaw : 0, dx = a.lock ? L.targetPitch : 0; + a.ry = a.ry >= dy - s && a.ry <= dy + s ? dy : a.ry < dy ? a.ry + s : a.ry - s; + a.rx = a.rx >= dx - s && a.rx <= dx + s ? dx : a.rx < dx ? a.rx + s : a.rx - s; + } + function fire(g, a, side) { // Gun_FireWeapon + const L = g.lara, b = g.boss, c = T.CREATURES[b.kind]; + const yaw = wrap(a.ry + L.rot + PISTOL.spread * (T.rand(g) - T.DEG90) / 65536), pitch = a.rx + PISTOL.spread * (T.rand(g) - T.DEG90) / 65536; + const cp = cos(pitch), dx = sin(yaw) * cp, dy = sin(pitch), dz = cos(yaw) * cp; + const ox = L.x, oy = L.y + T.GUN_HEIGHT, oz = L.z; + L.shots++; a.flash = T.n(3); + let best = null; + if (L.target && b.hp > 0) for (const s of c.spheres(b)) { + const hit = T.rayHitsSphere(ox, oy, oz, dx, dy, dz, s[0], s[1], s[2], s[3]); + if (hit !== null && (best === null || hit < best)) best = hit; + } + if (best === null) { + let d = 64, reach = PISTOL.range; + while (d < reach && T.floorAt(g.map, ox + dx * d, oz + dz * d) <= oy + dy * d) d += 64; + T.fx(g, 'ricochet', ox + dx * d, oy + dy * d, oz + dz * d, 6, { side, src: 'lara' }); + return; + } + L.hits++; + const was = b.hp; b.hp = Math.max(c.hpFloor ? c.hpFloor(b) : 0, b.hp - PISTOL.damage); + T.fx(g, 'blood', ox + dx * best, oy + dy * best, oz + dz * best, 10, { side, src: 'lara' }); + c.onHit && c.onHit(g, b, PISTOL.damage); + if (was > 0 && b.hp <= 0) T.event(g, 'boss_dead', { kind: b.kind }); + } + function armTick(g, L, a, action, side) { // M_Animate, one hand: one frame per original tick + if (a.flash > 0) a.flash--; + if (++a.sub < T.TS) return; + a.sub = 0; + let f = a.frame; + if (!a.lock && (!action || L.target)) { + if (f >= RECOIL_START && f <= RECOIL_END) f = AIM_END; + else if (f >= AIM_BEND && f <= AIM_END) f--; + } else if (f >= AIM_START && f <= AIM_EXTEND) f++; + else if (f === AIM_END) { if (action) { fire(g, a, side); f = RECOIL_START; } } + else if (f >= RECOIL_START && f <= RECOIL_END) { f++; if (f === RECOIL_START + RECOIL_FRAME) f = AIM_END; } + a.frame = f; + } + T.gunTick = function (g, keys, pressed) { + const L = g.lara; + if (L.hp <= 0) return; + const action = keys.has('J') || keys.has('LMB'); + if (pressed.has('K') || pressed.has('RMB')) { // Gun_Control: the draw key flips between drawn and holstered + if (L.gun === 'ready') { L.gun = 'undraw'; L.gunT = PISTOL.drawTicks; L.target = false; L.armL.lock = L.armR.lock = false; } + else if (L.gun === 'armless') { L.gun = 'draw'; L.gunT = PISTOL.drawTicks; } + } + if (L.gun === 'draw' || L.gun === 'undraw') { + L.armL.ry = L.armR.ry = L.armL.rx = L.armR.rx = 0; + if (--L.gunT <= 0) { L.gun = L.gun === 'draw' ? 'ready' : 'armless'; L.armL.frame = L.armR.frame = AIM_START; } + return; + } + if (L.gun !== 'ready') { L.torso = 0; return; } + const cre = T.CREATURES[g.boss.kind]; + if (cre.untargetable && cre.untargetable(g.boss)) { L.target = false; L.armL.lock = L.armR.lock = false; } // M_IsTargetable: the lock drops at once + const t = targetFrom(g), held = L.target && action; // Gun_GetNewTarget: a target is kept while the trigger stays down + if (!held) L.target = considerTarget(g, t); + targetInfo(g, t); + aimArm(L, L.armL); aimArm(L, L.armR); + // Gun_Pistols_Control: the torso follows the locked arms + L.torso = L.armL.lock && L.armR.lock ? (L.armL.ry + L.armR.ry) / 4 : L.armL.lock ? L.armL.ry / 2 : L.armR.lock ? L.armR.ry / 2 : 0; + armTick(g, L, L.armR, action, 'R'); + armTick(g, L, L.armL, action, 'L'); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/touhou_remake/compact_actions.json b/environments/games/web/games/touhou_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..ef6ea8595c7b183194227d13362c4d92ed68bd83 --- /dev/null +++ b/environments/games/web/games/touhou_remake/compact_actions.json @@ -0,0 +1,148 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "touhou_remake", + "version": "touhou-compact@1", + "heads": [ + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "up", + "keys": [ + "W" + ] + }, + { + "label": "down", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "up_left", + "keys": [ + "W", + "A" + ] + }, + { + "label": "up_right", + "keys": [ + "W", + "D" + ] + }, + { + "label": "down_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "down_right", + "keys": [ + "S", + "D" + ] + } + ] + }, + { + "name": "action", + "options": [ + { + "label": "none" + }, + { + "label": "bomb_focus", + "subs": [ + [ + "K", + "J" + ], + [ + "J", + "Shift" + ], + [ + "J", + "Shift" + ], + [ + "J", + "Shift" + ], + [ + "J", + "Shift" + ], + [ + "J", + "Shift" + ] + ] + }, + { + "label": "bomb_fast", + "subs": [ + [ + "K", + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ], + [ + "J" + ] + ] + }, + { + "label": "bomb_hold", + "keys": [ + "K", + "J" + ] + }, + { + "label": "fire_fast", + "keys": [ + "J" + ] + }, + { + "label": "fire_focus", + "keys": [ + "J", + "Shift" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/touhou_remake/draw.js b/environments/games/web/games/touhou_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..8a49bab5efd243522f346ab8bd7ae487249ccff7 --- /dev/null +++ b/environments/games/web/games/touhou_remake/draw.js @@ -0,0 +1,671 @@ +/* Read-only renderer for touhou_remake (scarlet-practice@8). The whole 854x480 frame is the playfield: no side panel and no + * frame; the HUD is drawn over the field in the corners. Never writes game state and never touches the game RNG. + * All art is original procedural Canvas drawing; sprites and tiles are cached in module-level canvases. */ +(function (root) { + 'use strict'; + const M = root.TouhouGame, TAU = Math.PI * 2, PI = Math.PI, W = M.W, H = M.H, CX = M.CX; + const SANS = '"Yu Gothic UI","Yu Gothic","Microsoft YaHei","Meiryo",sans-serif', SERIF = 'Georgia,"Yu Mincho","SimSun",serif'; + const COL = ['#ff3048', '#ff5ec8', '#3a6bff', '#3fd2ff', '#45e06a', '#ffe14a', '#ff9a2a', '#eef2ff', '#a85cff']; + const DIFF_COL = ['#7fe08a', '#7fb4ff', '#ffb35c', '#d78cff']; + const THEME = {rumia: {acc: '255,70,90', bar: ['#ff9ec0', '#ff4f86']}, cirno: {acc: '150,220,255', bar: ['#bff0ff', '#58b8ff']}, sakuya: {acc: '190,200,255', bar: ['#e6e9ff', '#8f9cff']}, meiling: {acc: '120,230,150', bar: ['#c8ffd4', '#3fc06a']}, patchouli: {acc: '200,150,255', bar: ['#ecd8ff', '#9a5cff']}, remilia: {acc: '255,60,80', bar: ['#ffc2c8', '#e0203a']}}; + const TILE_H = 960, cache = {}; + const hash = n => { n = (n ^ 61) ^ (n >>> 16); n = n + (n << 3); n ^= n >>> 4; n = Math.imul(n, 0x27d4eb2d); n ^= n >>> 15; return (n >>> 0) / 4294967296; }; + function canvas(w, h) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; } + function rgba(hex, a) { const n = parseInt(hex.slice(1), 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; } + function text(c, s, x, y, size, color, font, align) { c.font = size + 'px ' + (font || SANS); c.textAlign = align || 'left'; c.fillStyle = color; c.fillText(s, x, y); } + function outlined(c, s, x, y, size, color, font, align, edge) { c.font = size + 'px ' + (font || SANS); c.textAlign = align || 'left'; c.lineJoin = 'round'; c.lineWidth = 3; c.strokeStyle = edge || 'rgba(10,6,20,.85)'; c.strokeText(s, x, y); c.fillStyle = color; c.fillText(s, x, y); } + function star(c, cx, cy, r1, r2, fill) { c.fillStyle = fill; c.beginPath(); for (let k = 0; k < 10; k++) { const r = k % 2 ? r2 : r1, a = -PI / 2 + k * PI / 5; c.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); } c.fill(); } + + // ---------- sprites ---------- + function bulletSprite(k, ci) { + const key = 'b' + k + '_' + ci; if (cache[key]) return cache[key]; + const col = COL[ci] || COL[7], size = [14, 18, 18, 18, 18, 18, 34, 28, 28, 52][k], cv = canvas(size, size), c = cv.getContext('2d'), m = size / 2; + const glow = c.createRadialGradient(m, m, 0, m, m, m); + glow.addColorStop(0, rgba(col, 0.55)); glow.addColorStop(1, rgba(col, 0)); c.fillStyle = glow; c.fillRect(0, 0, size, size); + c.translate(m, m); + const disc = (r, fill) => { c.fillStyle = fill; c.beginPath(); c.arc(0, 0, r, 0, TAU); c.fill(); }; + if (k === 0) { disc(3.2, col); disc(1.6, '#fff'); } + else if (k === 1) { disc(5.2, col); disc(3.4, '#fff'); c.strokeStyle = rgba(col, 0.9); c.lineWidth = 1; c.beginPath(); c.arc(0, 0, 2.2, 0, TAU); c.stroke(); } + else if (k === 3) { disc(5.4, col); disc(3.6, rgba('#ffffff', 0.95)); } + else if (k === 6) { disc(11, col); disc(8, '#fff'); } + else if (k === 7) { disc(9, col); disc(5, '#fff6d8'); } + else if (k === 9) { c.strokeStyle = rgba(col, 0.9); c.lineWidth = 3; c.beginPath(); c.arc(0, 0, 18, 0, TAU); c.stroke(); disc(14, rgba(col, 0.25)); disc(6, rgba('#ffffff', 0.5)); } + else if (k === 8) { // knife: steel blade pointing to +x, coloured guard and glow (blue / red / green read at a glance) + c.fillStyle = rgba(col, 0.9); c.beginPath(); c.moveTo(-6, -4.2); c.lineTo(-4, -4.2); c.lineTo(-4, 4.2); c.lineTo(-6, 4.2); c.closePath(); c.fill(); + c.fillStyle = col; c.fillRect(-11, -1.6, 6, 3.2); + c.fillStyle = '#f4f7ff'; c.beginPath(); c.moveTo(12, 0); c.lineTo(-3, -3); c.lineTo(-4, 0); c.lineTo(-3, 3); c.closePath(); c.fill(); + c.strokeStyle = rgba(col, 0.95); c.lineWidth = 1; c.beginPath(); c.moveTo(11, 0); c.lineTo(-3, 0); c.stroke(); + } else { // oriented shapes pointing to +x + c.fillStyle = col; c.beginPath(); + if (k === 2) c.ellipse(0, 0, 7, 3.4, 0, 0, TAU); + else if (k === 4) { c.moveTo(8, 0); c.lineTo(-2, -4); c.lineTo(-7, -1.5); c.lineTo(-7, 1.5); c.lineTo(-2, 4); } + else { c.moveTo(8.5, 0); c.lineTo(0, -3.2); c.lineTo(-8, 0); c.lineTo(0, 3.2); } + c.closePath(); c.fill(); + c.fillStyle = 'rgba(255,255,255,.92)'; c.beginPath(); + if (k === 2) c.ellipse(0.5, 0, 4, 1.6, 0, 0, TAU); else { c.moveTo(5, 0); c.lineTo(-1, -1.4); c.lineTo(-4, 0); c.lineTo(-1, 1.4); c.closePath(); } + c.fill(); + } + return (cache[key] = cv); + } + function itemSprite(k) { + const key = 'i' + k; if (cache[key]) return cache[key]; + const cv = canvas(22, 22), c = cv.getContext('2d'); + if (k === 6) { + c.translate(11, 11); c.fillStyle = 'rgba(255,240,140,.35)'; c.beginPath(); c.arc(0, 0, 9, 0, TAU); c.fill(); + star(c, 0, 0, 6, 2.4, '#ffe860'); return (cache[key] = cv); + } + const big = k === 2 || k === 4, s = big ? 16 : 12, o = (22 - s) / 2; + const fill = ['#e8333f', '#3a6cf0', '#e8333f', '#3cb84a', '#f0c030', '#ff6fb0'][k], label = ['P', 'Point', 'P', 'B', 'F', '1UP'][k]; + c.fillStyle = 'rgba(0,0,0,.35)'; c.fillRect(o + 1, o + 1, s, s); c.fillStyle = fill; c.fillRect(o, o, s, s); + c.strokeStyle = 'rgba(255,255,255,.85)'; c.lineWidth = 1; c.strokeRect(o + 0.5, o + 0.5, s - 1, s - 1); + c.fillStyle = '#fff'; c.font = 'bold ' + (big ? 12 : 9) + 'px ' + SANS; c.textAlign = 'center'; c.textBaseline = 'middle'; c.fillText(label, 11, 11.5); + return (cache[key] = cv); + } + function shotSprite(k) { + const key = 's' + k; if (cache[key]) return cache[key]; + const cv = canvas(16, 44), c = cv.getContext('2d'); + if (k === 2) { const g = c.createLinearGradient(0, 0, 0, 44); g.addColorStop(0, 'rgba(255,255,255,.95)'); g.addColorStop(1, 'rgba(255,200,120,.1)'); c.fillStyle = g; c.fillRect(6, 2, 4, 40); } + else { + const red = k === 0; c.globalAlpha = 0.5; c.fillStyle = red ? '#ffffff' : '#c9b7ff'; c.fillRect(4, 16, 8, 13); + c.fillStyle = red ? '#ff5470' : '#8a62ff'; c.fillRect(5, 18, 6, 2); c.fillRect(5, 25, 6, 2); + c.globalAlpha = 0.14; c.fillStyle = red ? '#ff8aa0' : '#a080ff'; c.fillRect(2, 14, 12, 17); + } + return (cache[key] = cv); + } + // ---------- stage and spell backgrounds (cached, full width) ---------- + function stageTile(kind) { + const key = 'st' + kind; if (cache[key]) return cache[key]; + const cv = canvas(W, TILE_H), c = cv.getContext('2d'), T = TILE_H; + if (kind === 'rumia') { // dusk forest seen from above, a pale path winding down the middle + const g = c.createLinearGradient(0, 0, W, 0); g.addColorStop(0, '#0f1428'); g.addColorStop(0.5, '#1c2343'); g.addColorStop(1, '#0f1428'); c.fillStyle = g; c.fillRect(0, 0, W, T); + c.strokeStyle = 'rgba(130,108,150,.17)'; c.lineWidth = 140; c.lineCap = 'round'; c.beginPath(); + for (let y = -40; y <= T + 40; y += 6) { const x = CX + Math.sin(y / T * TAU * 2) * 70; if (y === -40) c.moveTo(x, y); else c.lineTo(x, y); } + c.stroke(); + for (let i = 0; i < 330; i++) { + const y = hash(i * 31 + 7) * T, side = i % 2 ? 1 : -1, x = CX + side * (110 + hash(i * 17 + 3) * 330), r = 20 + hash(i * 11) * 30; + for (const yy of [y, y - T, y + T]) { + const gr = c.createRadialGradient(x - r * 0.3, yy - r * 0.3, r * 0.1, x, yy, r); + gr.addColorStop(0, i % 3 ? '#2b3f4a' : '#36405c'); gr.addColorStop(1, 'rgba(10,14,28,0.0)'); c.fillStyle = gr; c.beginPath(); c.arc(x, yy, r, 0, TAU); c.fill(); + } + } + } else if (kind === 'cirno') { // misty lake: deep water with ripple bands + const g = c.createLinearGradient(0, 0, W, 0); g.addColorStop(0, '#0d3247'); g.addColorStop(0.5, '#17546e'); g.addColorStop(1, '#0d3247'); c.fillStyle = g; c.fillRect(0, 0, W, T); + for (let i = 0; i < 260; i++) { + const y = hash(i * 19 + 2) * T, x = hash(i * 23 + 9) * W, rw = 20 + hash(i * 5) * 70; + for (const yy of [y, y - T, y + T]) { c.strokeStyle = 'rgba(190,235,255,' + (0.07 + hash(i) * 0.12).toFixed(3) + ')'; c.lineWidth = 1.2; c.beginPath(); c.ellipse(x, yy, rw, rw * 0.18, 0, 0, TAU); c.stroke(); } + } + } else if (kind === 'meiling') { // the mansion gate: a stone path through the front garden, flower beds and hedges either side + const g = c.createLinearGradient(0, 0, W, 0); g.addColorStop(0, '#13291b'); g.addColorStop(0.5, '#1d3d27'); g.addColorStop(1, '#13291b'); c.fillStyle = g; c.fillRect(0, 0, W, T); + const pw = 210; c.fillStyle = '#3a3533'; c.fillRect(CX - pw / 2, 0, pw, T); + for (let y = 0; y < T; y += 30) for (let x = CX - pw / 2; x < CX + pw / 2; x += 42) { // flagstones + const ox = (y / 30) % 2 ? 21 : 0; c.fillStyle = (((x + ox) / 42 + y / 30) % 3) ? '#4a4440' : '#555049'; c.fillRect(x + ox - 20 + 2, y + 2, 38, 26); + } + c.fillStyle = '#9a2a2a'; c.fillRect(CX - pw / 2 - 6, 0, 6, T); c.fillRect(CX + pw / 2, 0, 6, T); // red brick kerbs + for (let i = 0; i < 300; i++) { // flowers in the beds + const y = hash(i * 29 + 5) * T, side = i % 2 ? 1 : -1, x = CX + side * (pw / 2 + 24 + hash(i * 13 + 1) * 280), col = ['#ff8fb8', '#ffe066', '#ff6a5c', '#ffffff', '#c38bff'][i % 5]; + for (const yy of [y, y - T, y + T]) { c.fillStyle = col; c.globalAlpha = 0.55; c.beginPath(); c.arc(x, yy, 2.5 + hash(i) * 2, 0, TAU); c.fill(); c.globalAlpha = 1; } + } + for (let y = 0; y < T; y += 120) for (const s of [-1, 1]) { // trimmed hedges + const x = CX + s * 380, gr = c.createRadialGradient(x - 8, y - 8, 4, x, y, 34); gr.addColorStop(0, '#3f7a3c'); gr.addColorStop(1, '#173018'); + c.fillStyle = gr; c.beginPath(); c.arc(x, y, 32, 0, TAU); c.fill(); + } + } else if (kind === 'remilia') { // the clock-tower terrace at night: dark slates, a red runner, stone balustrades either side + c.fillStyle = '#100a14'; c.fillRect(0, 0, W, T); + for (let y = 0; y < T; y += 40) for (let x = (y / 40) % 2 ? -30 : 0; x < W; x += 60) { c.fillStyle = hash(x * 11 + y * 3) < 0.5 ? '#1a1220' : '#201626'; c.fillRect(x, y, 58, 38); } + c.fillStyle = '#4a0c18'; c.fillRect(CX - 70, 0, 140, T); c.fillStyle = '#7a1626'; c.fillRect(CX - 70, 0, 6, T); c.fillRect(CX + 64, 0, 6, T); + for (let y = 0; y < T; y += 80) for (const sd of [-1, 1]) { const x = sd < 0 ? 26 : W - 26; c.fillStyle = '#2c2430'; c.fillRect(x - 14, y, 28, 66); c.fillStyle = '#3c3240'; c.fillRect(x - 18, y, 36, 8); c.fillRect(x - 18, y + 58, 36, 8); } + c.fillStyle = 'rgba(255,60,70,.05)'; c.fillRect(0, 0, W, T); + } else if (kind === 'patchouli') { // the Voile library: tall bookshelves either side of a dim aisle, reading desks under lamps + c.fillStyle = '#120c1c'; c.fillRect(0, 0, W, T); + const aisle = 260; c.fillStyle = '#1d1430'; c.fillRect(CX - aisle / 2, 0, aisle, T); + for (let y = 0; y < T; y += 48) for (const sd of [-1, 1]) { + const x0 = sd < 0 ? 0 : CX + aisle / 2, x1 = sd < 0 ? CX - aisle / 2 : W; + c.fillStyle = '#2b1a14'; c.fillRect(x0, y, x1 - x0, 48); c.fillStyle = '#3d2618'; c.fillRect(x0, y + 42, x1 - x0, 6); // shelf board + for (let x = x0 + 4; x < x1 - 6;) { // book spines + const bw = 6 + Math.floor(hash(x * 7 + y * 13) * 9), bh = 26 + Math.floor(hash(x * 3 + y) * 14); + c.fillStyle = ['#5a2a3a', '#2f3f6a', '#3a5a3a', '#6a5a2a', '#4a2f6a', '#6a3a2a'][Math.floor(hash(x + y * 5) * 6)]; c.fillRect(x, y + 42 - bh, bw, bh); + c.fillStyle = 'rgba(230,200,120,.35)'; c.fillRect(x, y + 42 - bh + 4, bw, 1.5); x += bw + 1; + } + } + c.fillStyle = 'rgba(0,0,0,.35)'; c.fillRect(CX - aisle / 2 - 10, 0, 10, T); c.fillRect(CX + aisle / 2, 0, 10, T); + for (let y = 60; y < T; y += 240) { c.fillStyle = '#3b2a1c'; c.fillRect(CX - 60, y, 120, 50); c.fillStyle = 'rgba(255,220,140,.25)'; c.beginPath(); c.arc(CX, y + 25, 46, 0, TAU); c.fill(); } + } else { // Scarlet Devil Mansion corridor: red carpet, checker floor, pillars and moonlit windows + c.fillStyle = '#170b10'; c.fillRect(0, 0, W, T); + for (let y = 0; y < T; y += 40) for (let x = 0; x < W; x += 40) { c.fillStyle = ((x + y) / 40) % 2 ? '#24121a' : '#1b0d13'; c.fillRect(x, y, 40, 40); } + for (let y = 0; y < T; y += 240) for (const s of [-1, 1]) { // moonlight falling through the windows + const x = CX + s * 330, gr = c.createLinearGradient(x, y, x + s * 60, y + 120); gr.addColorStop(0, 'rgba(170,190,255,.16)'); gr.addColorStop(1, 'rgba(170,190,255,0)'); + c.fillStyle = gr; c.beginPath(); c.moveTo(x - 40, y); c.lineTo(x + 40, y); c.lineTo(x + 40 + s * 80, y + 160); c.lineTo(x - 40 + s * 80, y + 160); c.closePath(); c.fill(); + } + const cw = 230; c.fillStyle = '#5c0f1c'; c.fillRect(CX - cw / 2, 0, cw, T); + c.fillStyle = '#7a1626'; c.fillRect(CX - cw / 2 + 14, 0, cw - 28, T); + c.fillStyle = '#c9a24a'; c.fillRect(CX - cw / 2 + 6, 0, 3, T); c.fillRect(CX + cw / 2 - 9, 0, 3, T); + c.strokeStyle = 'rgba(230,190,110,.35)'; c.lineWidth = 1.5; + for (let y = 0; y < T; y += 60) { c.beginPath(); c.moveTo(CX, y + 8); c.lineTo(CX + 26, y + 30); c.lineTo(CX, y + 52); c.lineTo(CX - 26, y + 30); c.closePath(); c.stroke(); } + for (let y = 40; y < T; y += 160) for (const s of [-1, 1]) { + const x = CX + s * 190, gr = c.createRadialGradient(x - 6, y - 6, 2, x, y, 26); gr.addColorStop(0, '#7b5a52'); gr.addColorStop(1, '#2a1517'); + c.fillStyle = 'rgba(0,0,0,.35)'; c.beginPath(); c.arc(x + 5, y + 6, 27, 0, TAU); c.fill(); + c.fillStyle = gr; c.beginPath(); c.arc(x, y, 24, 0, TAU); c.fill(); c.strokeStyle = 'rgba(220,180,120,.5)'; c.lineWidth = 2; c.beginPath(); c.arc(x, y, 24, 0, TAU); c.stroke(); + } + } + return (cache[key] = cv); + } + function spellTile(kind) { + const key = 'sp' + kind; if (cache[key]) return cache[key]; + const cv = canvas(W, H), c = cv.getContext('2d'), R = Math.hypot(CX, H / 2); + if (kind === 'rumia') { + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#3a0710'); g.addColorStop(0.55, '#12030a'); g.addColorStop(1, '#050106'); c.fillStyle = g; c.fillRect(0, 0, W, H); + c.translate(CX, H / 2); + for (let r = 40; r < R; r += 34) { c.strokeStyle = 'rgba(255,60,80,' + (0.22 - r / R * 0.16).toFixed(3) + ')'; c.lineWidth = 2; c.beginPath(); c.arc(0, 0, r, 0, TAU); c.stroke(); } + c.strokeStyle = 'rgba(255,90,110,.14)'; c.lineWidth = 1.5; + for (let i = 0; i < 32; i++) { const a = i * TAU / 32; c.beginPath(); c.moveTo(Math.cos(a) * 30, Math.sin(a) * 30); c.lineTo(Math.cos(a + 0.6) * R, Math.sin(a + 0.6) * R); c.stroke(); } + } else if (kind === 'cirno') { + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#24607f'); g.addColorStop(0.4, '#143958'); g.addColorStop(1, '#06162a'); c.fillStyle = g; c.fillRect(0, 0, W, H); + c.strokeStyle = 'rgba(170,225,255,.10)'; c.lineWidth = 1.5; + for (let y = -40; y < H + 40; y += 70) for (let x = -40; x < W + 40; x += 80) { + const ox = x + ((y / 70) % 2 ? 40 : 0); c.beginPath(); for (let i = 0; i <= 6; i++) { const a = i * TAU / 6; c.lineTo(ox + Math.cos(a) * 30, y + Math.sin(a) * 30); } c.stroke(); + } + } else if (kind === 'meiling') { // rainbow rays fanning from the centre over deep green, a taiji ring + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#1e5a35'); g.addColorStop(0.5, '#0f2e1d'); g.addColorStop(1, '#06140c'); c.fillStyle = g; c.fillRect(0, 0, W, H); + c.translate(CX, H / 2); + const RB = ['255,70,70', '255,160,60', '255,230,80', '90,220,110', '80,200,255', '90,110,255', '190,110,255']; + for (let i = 0; i < 28; i++) { const a = i * TAU / 28; c.fillStyle = `rgba(${RB[i % 7]},.07)`; c.beginPath(); c.moveTo(0, 0); c.lineTo(Math.cos(a - 0.07) * R, Math.sin(a - 0.07) * R); c.lineTo(Math.cos(a + 0.07) * R, Math.sin(a + 0.07) * R); c.closePath(); c.fill(); } + c.strokeStyle = 'rgba(170,255,190,.20)'; c.lineWidth = 2; c.beginPath(); c.arc(0, 0, 150, 0, TAU); c.stroke(); + c.fillStyle = 'rgba(170,255,190,.08)'; c.beginPath(); c.arc(0, 0, 150, -PI / 2, PI / 2); c.arc(0, 75, 75, PI / 2, -PI / 2, true); c.arc(0, -75, 75, PI / 2, -PI / 2); c.fill(); + } else if (kind === 'remilia') { // a blood-red full moon, thin clouds and a ring of bats' wings + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#5a0a1c'); g.addColorStop(0.55, '#230512'); g.addColorStop(1, '#090208'); c.fillStyle = g; c.fillRect(0, 0, W, H); + const m = c.createRadialGradient(CX, H / 2, 40, CX, H / 2, 170); m.addColorStop(0, 'rgba(255,70,80,.55)'); m.addColorStop(0.75, 'rgba(210,20,50,.35)'); m.addColorStop(1, 'rgba(210,20,50,0)'); c.fillStyle = m; c.beginPath(); c.arc(CX, H / 2, 170, 0, TAU); c.fill(); + c.translate(CX, H / 2); c.fillStyle = 'rgba(0,0,0,.34)'; + for (let i = 0; i < 12; i++) { const a = i * TAU / 12; c.save(); c.rotate(a); c.translate(205, 0); c.beginPath(); c.moveTo(-24, 0); c.quadraticCurveTo(-12, -14, 0, -3); c.quadraticCurveTo(12, -14, 24, 0); c.quadraticCurveTo(10, -2, 0, 7); c.quadraticCurveTo(-10, -2, -24, 0); c.fill(); c.restore(); } + } else if (kind === 'patchouli') { // seven-element magic circle (fire, water, wood, metal, earth, sun, moon) on violet + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#3a2160'); g.addColorStop(0.5, '#1a0f33'); g.addColorStop(1, '#08051a'); c.fillStyle = g; c.fillRect(0, 0, W, H); + c.translate(CX, H / 2); c.strokeStyle = 'rgba(220,190,255,.22)'; c.lineWidth = 2; + for (const r of [200, 186, 120]) { c.beginPath(); c.arc(0, 0, r, 0, TAU); c.stroke(); } + c.beginPath(); for (let i = 0; i <= 7; i++) { const a = -PI / 2 + i * TAU * 3 / 7; c.lineTo(Math.cos(a) * 186, Math.sin(a) * 186); } c.stroke(); // heptagram + const EL = ['Fire', 'Water', 'Wood', 'Metal', 'Earth', 'Sun', 'Moon'], ECOL = ['255,110,90', '110,170,255', '110,220,120', '230,230,240', '220,180,90', '255,220,90', '200,200,255']; + c.font = '22px ' + SERIF; c.textAlign = 'center'; c.textBaseline = 'middle'; + for (let i = 0; i < 7; i++) { const a = -PI / 2 + i * TAU / 7; c.fillStyle = 'rgba(' + ECOL[i] + ',.40)'; c.beginPath(); c.arc(Math.cos(a) * 186, Math.sin(a) * 186, 18, 0, TAU); c.fill(); c.fillStyle = 'rgba(255,255,255,.55)'; c.fillText(EL[i], Math.cos(a) * 186, Math.sin(a) * 186); } + } else { // Sakuya: indigo night and a great clock face with gears + const g = c.createRadialGradient(CX, H / 2, 10, CX, H / 2, R); g.addColorStop(0, '#2b2a6a'); g.addColorStop(0.5, '#141537'); g.addColorStop(1, '#07061a'); c.fillStyle = g; c.fillRect(0, 0, W, H); + const gear = (x, y, r, n) => { + c.save(); c.translate(x, y); c.strokeStyle = 'rgba(200,190,255,.14)'; c.lineWidth = 3; c.beginPath(); + for (let i = 0; i < n * 2; i++) { const a = i * PI / n, rr = i % 2 ? r : r + 9; c.lineTo(Math.cos(a) * rr, Math.sin(a) * rr); } c.closePath(); c.stroke(); + c.beginPath(); c.arc(0, 0, r * 0.45, 0, TAU); c.stroke(); c.restore(); + }; + gear(90, 70, 60, 14); gear(W - 110, 400, 80, 18); gear(W - 70, 60, 36, 10); gear(120, 420, 44, 12); + c.translate(CX, H / 2); + c.strokeStyle = 'rgba(210,205,255,.28)'; c.lineWidth = 3; c.beginPath(); c.arc(0, 0, 214, 0, TAU); c.stroke(); + c.lineWidth = 1; c.beginPath(); c.arc(0, 0, 200, 0, TAU); c.stroke(); c.beginPath(); c.arc(0, 0, 150, 0, TAU); c.stroke(); + for (let i = 0; i < 60; i++) { const a = i * TAU / 60, r0 = i % 5 ? 192 : 182; c.lineWidth = i % 5 ? 1 : 3; c.beginPath(); c.moveTo(Math.cos(a) * r0, Math.sin(a) * r0); c.lineTo(Math.cos(a) * 200, Math.sin(a) * 200); c.stroke(); } + const NUM = ['XII', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI']; + c.fillStyle = 'rgba(220,214,255,.30)'; c.font = '22px ' + SERIF; c.textAlign = 'center'; c.textBaseline = 'middle'; + for (let i = 0; i < 12; i++) { const a = -PI / 2 + i * TAU / 12; c.fillText(NUM[i], Math.cos(a) * 166, Math.sin(a) * 166); } + } + return (cache[key] = cv); + } + + // ---------- characters ---------- + function reimu(c, x, y, lean, t) { + c.save(); c.translate(x, y); c.rotate(lean * 0.12); + c.fillStyle = 'rgba(0,0,0,.25)'; c.beginPath(); c.ellipse(0, 18, 11, 3, 0, 0, TAU); c.fill(); + c.fillStyle = '#c81f35'; c.beginPath(); c.moveTo(-7, 2); c.lineTo(-11, 17); c.lineTo(11, 17); c.lineTo(7, 2); c.closePath(); c.fill(); // skirt + c.fillStyle = '#e8e2e6'; c.fillRect(-3, 12, 6, 5); + c.fillStyle = '#d7263d'; c.fillRect(-6, -4, 12, 8); // vest + c.fillStyle = '#ffd34a'; c.fillRect(-2, -3, 4, 3); // ascot + const sw = Math.sin(t * 0.2) * 1.2; + c.fillStyle = '#f4f2f6'; c.beginPath(); c.moveTo(-6, -3); c.lineTo(-15, 6 + sw); c.lineTo(-10, 10 + sw); c.lineTo(-5, 3); c.fill(); + c.beginPath(); c.moveTo(6, -3); c.lineTo(15, 6 - sw); c.lineTo(10, 10 - sw); c.lineTo(5, 3); c.fill(); // detached sleeves + c.fillStyle = '#2a1b1f'; c.beginPath(); c.arc(0, -10, 7, 0, TAU); c.fill(); c.fillRect(-7, -10, 3, 10); c.fillRect(4, -10, 3, 10); // hair + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -9, 4.6, 0, PI); c.fill(); + c.fillStyle = '#e0283f'; c.beginPath(); c.moveTo(0, -17); c.lineTo(-11, -23); c.lineTo(-9, -13); c.closePath(); c.fill(); c.beginPath(); c.moveTo(0, -17); c.lineTo(11, -23); c.lineTo(9, -13); c.closePath(); c.fill(); // bow + c.fillStyle = '#fff'; c.fillRect(-8, -21, 2, 5); c.fillRect(6, -21, 2, 5); + c.restore(); + } + function yinyang(c, x, y, a, blue) { + c.save(); c.translate(x, y); c.rotate(a); + c.fillStyle = blue ? 'rgba(150,140,255,.28)' : 'rgba(255,120,150,.25)'; c.beginPath(); c.arc(0, 0, 8.5, 0, TAU); c.fill(); + c.fillStyle = '#f8f4f4'; c.beginPath(); c.arc(0, 0, 6, 0, TAU); c.fill(); + c.fillStyle = blue ? '#5a4fd0' : '#c81f35'; c.beginPath(); c.arc(0, 0, 6, -PI / 2, PI / 2); c.arc(0, 3, 3, PI / 2, -PI / 2, true); c.arc(0, -3, 3, PI / 2, -PI / 2); c.fill(); + c.fillStyle = '#f8f4f4'; c.beginPath(); c.arc(0, 3, 1.2, 0, TAU); c.fill(); c.fillStyle = blue ? '#5a4fd0' : '#c81f35'; c.beginPath(); c.arc(0, -3, 1.2, 0, TAU); c.fill(); + c.restore(); + } + function rumia(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.05) * 2); + c.fillStyle = '#16131c'; c.beginPath(); c.moveTo(-8, 0); c.lineTo(-13, 22); c.lineTo(13, 22); c.lineTo(8, 0); c.closePath(); c.fill(); // black skirt + c.fillStyle = '#f0ece6'; c.fillRect(-6, -6, 12, 9); + c.fillStyle = '#1b1820'; c.beginPath(); c.moveTo(-7, -6); c.lineTo(-3, 4); c.lineTo(-7, 4); c.closePath(); c.fill(); c.beginPath(); c.moveTo(7, -6); c.lineTo(3, 4); c.lineTo(7, 4); c.closePath(); c.fill(); + c.fillStyle = '#c4253a'; c.beginPath(); c.moveTo(0, -5); c.lineTo(-3, 1); c.lineTo(3, 1); c.closePath(); c.fill(); // necktie + c.strokeStyle = '#f0ece6'; c.lineWidth = 4; c.lineCap = 'round'; c.beginPath(); c.moveTo(-6, -4); c.lineTo(-22, -7); c.moveTo(6, -4); c.lineTo(22, -7); c.stroke(); // outstretched arms + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(-23, -7, 2.2, 0, TAU); c.arc(23, -7, 2.2, 0, TAU); c.fill(); + c.fillStyle = '#f2d15a'; c.beginPath(); c.arc(0, -15, 8.5, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 7); // blonde bob + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#c0182c'; c.fillRect(-11, -22, 6, 5); // red hair ribbon (ofuda) + c.fillStyle = '#d42a3c'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function cirno(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.06) * 2); + for (const s of [-1, 1]) for (let j = 0; j < 3; j++) { // six ice wings + c.save(); c.translate(s * 7, -4 + j * 7); c.rotate(s * (-0.6 + j * 0.5)); const g = c.createLinearGradient(0, 0, s * 18, 0); + g.addColorStop(0, 'rgba(210,245,255,.95)'); g.addColorStop(1, 'rgba(120,200,255,.55)'); c.fillStyle = g; + c.beginPath(); c.moveTo(0, 0); c.lineTo(s * 9, -4); c.lineTo(s * 19, 0); c.lineTo(s * 9, 4); c.closePath(); c.fill(); c.restore(); + } + c.fillStyle = '#2f6fd8'; c.beginPath(); c.moveTo(-8, -1); c.lineTo(-13, 21); c.lineTo(13, 21); c.lineTo(8, -1); c.closePath(); c.fill(); // blue dress + c.fillStyle = '#f2f6ff'; c.fillRect(-6, -7, 12, 7); + c.fillStyle = '#e0283f'; c.fillRect(-3, -6, 6, 3); + c.fillStyle = '#7cc6ff'; c.beginPath(); c.arc(0, -15, 8.5, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 8); // blue hair + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#3a7fe8'; c.beginPath(); c.moveTo(0, -23); c.lineTo(-10, -30); c.lineTo(-9, -20); c.closePath(); c.fill(); c.beginPath(); c.moveTo(0, -23); c.lineTo(10, -30); c.lineTo(9, -20); c.closePath(); c.fill(); // big bow + c.fillStyle = '#244a9a'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function sakuya(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.05) * 1.6); + c.fillStyle = '#25317f'; c.beginPath(); c.moveTo(-8, 0); c.lineTo(-14, 22); c.lineTo(14, 22); c.lineTo(8, 0); c.closePath(); c.fill(); // navy dress + c.fillStyle = '#f2f3fb'; c.beginPath(); c.moveTo(-5, 1); c.lineTo(-8, 20); c.lineTo(8, 20); c.lineTo(5, 1); c.closePath(); c.fill(); // apron + c.fillStyle = '#2d3a96'; c.fillRect(-6, -7, 12, 9); + c.fillStyle = '#f2f3fb'; c.beginPath(); c.moveTo(-6, -7); c.lineTo(0, -2); c.lineTo(6, -7); c.closePath(); c.fill(); + c.fillStyle = '#3fb06a'; c.fillRect(-2, -5, 4, 3); // green bow + c.strokeStyle = '#2d3a96'; c.lineWidth = 3.5; c.lineCap = 'round'; c.beginPath(); c.moveTo(-6, -4); c.lineTo(-16, 3); c.moveTo(6, -4); c.lineTo(16, 3); c.stroke(); + for (const s of [-1, 1]) { // a knife fanned in each hand + c.save(); c.translate(s * 17, 4); c.rotate(s * 0.9 - PI / 2 * s); + for (let i = -1; i <= 1; i++) { c.save(); c.rotate(i * 0.25); c.fillStyle = '#e8ecff'; c.beginPath(); c.moveTo(0, -12); c.lineTo(-1.6, 0); c.lineTo(1.6, 0); c.closePath(); c.fill(); c.restore(); } + c.restore(); + } + const hg = c.createLinearGradient(0, -26, 0, -6); hg.addColorStop(0, '#ffffff'); hg.addColorStop(1, '#a9b2cc'); c.fillStyle = hg; + c.beginPath(); c.arc(0, -15, 8.6, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 7); // silver hair + c.fillRect(-10, -12, 3, 11); c.fillRect(7, -12, 3, 11); // braids + c.fillStyle = '#3fb06a'; c.fillRect(-10, -2, 3, 3); c.fillRect(7, -2, 3, 3); + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#ffffff'; c.beginPath(); c.moveTo(-8, -21); c.quadraticCurveTo(0, -27, 8, -21); c.lineTo(7, -19); c.quadraticCurveTo(0, -24, -7, -19); c.closePath(); c.fill(); // maid headdress + c.fillStyle = '#2f55c8'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function meiling(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.05) * 1.8); + c.fillStyle = '#2f9a52'; c.beginPath(); c.moveTo(-8, -1); c.lineTo(-13, 22); c.lineTo(-2, 22); c.lineTo(0, 8); c.lineTo(2, 22); c.lineTo(13, 22); c.lineTo(8, -1); c.closePath(); c.fill(); // green dress with side slits + c.fillStyle = '#f4f2ea'; c.fillRect(-3, 8, 6, 14); // white trousers in the slit + c.fillStyle = '#38ad5e'; c.fillRect(-7, -7, 14, 9); + c.fillStyle = '#f0d36a'; c.fillRect(-1, -7, 2, 9); // frog buttons + c.strokeStyle = '#38ad5e'; c.lineWidth = 3.5; c.lineCap = 'round'; c.beginPath(); c.moveTo(-6, -4); c.lineTo(-15, -12); c.moveTo(6, -4); c.lineTo(16, 2); c.stroke(); // martial-arts stance + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(-16, -13, 2.4, 0, TAU); c.arc(17, 3, 2.4, 0, TAU); c.fill(); + const hg = c.createLinearGradient(0, -26, 0, 8); hg.addColorStop(0, '#ff5a4a'); hg.addColorStop(1, '#c22a2a'); c.fillStyle = hg; + c.beginPath(); c.arc(0, -15, 8.6, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 8); c.fillRect(-10, -12, 4, 20); c.fillRect(6, -12, 4, 20); // long red hair + c.fillStyle = '#2a7a45'; c.beginPath(); c.moveTo(-9, -20); c.lineTo(9, -20); c.lineTo(6, -27); c.lineTo(-6, -27); c.closePath(); c.fill(); // beret + c.fillStyle = '#f0d36a'; c.beginPath(); c.arc(0, -25, 2.2, 0, TAU); c.fill(); // star badge + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#2f7a4a'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function patchouli(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.04) * 1.5); + c.fillStyle = '#c9a4e0'; c.beginPath(); c.moveTo(-9, -2); c.lineTo(-14, 22); c.lineTo(14, 22); c.lineTo(9, -2); c.closePath(); c.fill(); // striped pale-purple gown + c.strokeStyle = 'rgba(120,80,160,.6)'; c.lineWidth = 1; for (let i = -2; i <= 2; i++) { c.beginPath(); c.moveTo(i * 3, 0); c.lineTo(i * 5, 22); c.stroke(); } + c.fillStyle = '#d9bdf0'; c.fillRect(-7, -7, 14, 8); + c.fillStyle = '#7a4a2a'; c.fillRect(6, -2, 10, 12); c.fillStyle = '#e8d6a0'; c.fillRect(7, -1, 8, 10); // the book she holds + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(-8, 2, 2.2, 0, TAU); c.fill(); + const hg = c.createLinearGradient(0, -26, 0, 12); hg.addColorStop(0, '#b07ad8'); hg.addColorStop(1, '#6e3ea0'); c.fillStyle = hg; + c.beginPath(); c.arc(0, -15, 8.8, 0, TAU); c.fill(); c.fillRect(-10, -15, 20, 8); c.fillRect(-11, -12, 4, 22); c.fillRect(7, -12, 4, 22); // long purple hair + c.fillStyle = '#f2e6f6'; c.beginPath(); c.moveTo(-11, -19); c.quadraticCurveTo(0, -34, 11, -19); c.quadraticCurveTo(0, -23, -11, -19); c.fill(); // mob cap + c.fillStyle = '#f0d36a'; c.beginPath(); c.moveTo(4, -27); c.lineTo(8, -23); c.lineTo(4, -21); c.lineTo(0, -23); c.closePath(); c.fill(); // crescent pin + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#7a3ea8'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + function remilia(c, x, y, t) { + c.save(); c.translate(x, y + Math.sin(t * 0.05) * 1.5); + const fl = Math.sin(t * 0.2) * 0.12; + c.fillStyle = '#2a1830'; for (const sd of [-1, 1]) { c.save(); c.scale(sd, 1); c.rotate(fl); c.beginPath(); c.moveTo(4, -6); c.quadraticCurveTo(16, -22, 32, -14); c.quadraticCurveTo(26, -8, 27, -1); c.quadraticCurveTo(20, -5, 18, 2); c.quadraticCurveTo(12, -3, 5, 3); c.closePath(); c.fill(); c.restore(); } // bat wings + c.fillStyle = '#f4e6f0'; c.beginPath(); c.moveTo(-7, -2); c.lineTo(-13, 20); c.lineTo(13, 20); c.lineTo(7, -2); c.closePath(); c.fill(); // pale pink dress + c.fillStyle = '#d0304a'; c.fillRect(-13, 16, 26, 3); c.fillRect(-2, -3, 4, 6); + c.fillStyle = '#f4e6f0'; c.fillRect(-7, -7, 14, 8); + const hg = c.createLinearGradient(0, -24, 0, -6); hg.addColorStop(0, '#a8b4e8'); hg.addColorStop(1, '#6c78c0'); c.fillStyle = hg; + c.beginPath(); c.arc(0, -15, 8.2, 0, TAU); c.fill(); c.fillRect(-9, -15, 18, 7); // short lavender hair + c.fillStyle = '#f7ecf2'; c.beginPath(); c.ellipse(0, -22, 11, 6.5, 0, 0, TAU); c.fill(); c.fillStyle = '#d0304a'; c.fillRect(-10, -20, 20, 2); // mob cap with a red band + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -13, 5.2, 0, PI); c.fill(); + c.fillStyle = '#c8102e'; c.fillRect(-3, -12, 2, 2); c.fillRect(1, -12, 2, 2); + c.restore(); + } + // Ordinary enemy (fairy): small body with translucent wings; fades in, flickers when hit. + function fairy(c, f, t) { + const col = f.c === M.C.CYAN ? '120,230,255' : '110,140,255'; + c.save(); c.translate(f.x, f.y); + const fl = Math.sin(t * 0.5 + f.fire) * 0.3; + c.fillStyle = `rgba(${col},.45)`; for (const s of [-1, 1]) { c.beginPath(); c.ellipse(s * 7, -3, 7, 4 + fl * 4, s * 0.5, 0, TAU); c.fill(); } + c.fillStyle = '#2f5fc8'; c.beginPath(); c.moveTo(-4, -1); c.lineTo(-6, 9); c.lineTo(6, 9); c.lineTo(4, -1); c.closePath(); c.fill(); + c.fillStyle = '#f6e7a0'; c.beginPath(); c.arc(0, -5, 4.2, 0, TAU); c.fill(); + c.fillStyle = '#f6d9c8'; c.beginPath(); c.arc(0, -4, 2.6, 0, PI); c.fill(); + c.restore(); + } + // Spell cut-in bust: drawn once per boss into a cached 220x260 canvas. + function bustTile(kind) { + const key = 'bust' + kind; if (cache[key]) return cache[key]; + const cv = canvas(220, 260), c = cv.getContext('2d'), R = kind === 'rumia', S = kind === 'sakuya', Mei = kind === 'meiling', Pa = kind === 'patchouli', Re = kind === 'remilia'; + const hair = R ? ['#fff3b0', '#f2cf55', '#c99a2a'] : S ? ['#ffffff', '#d5dbea', '#8f99b8'] : Mei ? ['#ff8a70', '#e23a32', '#9a1c22'] : Pa ? ['#d6b0f0', '#9a62c8', '#5e2e8a'] : Re ? ['#c4ccf2', '#8a96d8', '#525ea8'] : ['#d6f0ff', '#7cc6ff', '#3d82d6'], eye = R ? '#c8102e' : S ? '#3352c8' : Mei ? '#2f8a50' : Pa ? '#8a3ac8' : '#2d6fe0'; + c.translate(110, 0); + if (R) { const a = c.createRadialGradient(0, 120, 20, 0, 120, 130); a.addColorStop(0, 'rgba(20,0,20,.75)'); a.addColorStop(1, 'rgba(20,0,20,0)'); c.fillStyle = a; c.fillRect(-110, 0, 220, 260); } + else if (Re) { // a blood moon and spread bat wings behind her + const gl = c.createRadialGradient(0, 110, 30, 0, 110, 120); gl.addColorStop(0, 'rgba(255,60,70,.75)'); gl.addColorStop(1, 'rgba(255,60,70,0)'); c.fillStyle = gl; c.fillRect(-110, 0, 220, 240); + c.fillStyle = '#231228'; for (const sd of [-1, 1]) { c.save(); c.scale(sd, 1); c.beginPath(); c.moveTo(26, 170); c.quadraticCurveTo(60, 70, 108, 96); c.quadraticCurveTo(94, 116, 98, 142); c.quadraticCurveTo(80, 128, 72, 156); c.quadraticCurveTo(58, 142, 46, 186); c.closePath(); c.fill(); c.restore(); } + } else if (Pa) { // an open grimoire glowing behind her + const gl = c.createRadialGradient(0, 200, 10, 0, 200, 120); gl.addColorStop(0, 'rgba(220,180,255,.7)'); gl.addColorStop(1, 'rgba(220,180,255,0)'); c.fillStyle = gl; c.fillRect(-110, 80, 220, 180); + c.fillStyle = 'rgba(240,225,190,.9)'; c.beginPath(); c.moveTo(-90, 230); c.lineTo(0, 210); c.lineTo(90, 230); c.lineTo(90, 250); c.lineTo(0, 232); c.lineTo(-90, 250); c.closePath(); c.fill(); + } else if (Mei) { // rainbow rays behind her + const RB = ['255,70,70', '255,160,60', '255,230,80', '90,220,110', '80,200,255', '90,110,255', '190,110,255']; + for (let i = 0; i < 7; i++) { c.save(); c.translate(0, 200); c.rotate(-1.05 + i * 0.35); c.fillStyle = `rgba(${RB[i]},.55)`; c.beginPath(); c.moveTo(-5, 0); c.lineTo(-16, -190); c.lineTo(16, -190); c.lineTo(5, 0); c.closePath(); c.fill(); c.restore(); } + } else if (S) { // knives fanned behind her + for (let i = 0; i < 9; i++) { + c.save(); c.translate(0, 190); c.rotate(-1.2 + i * 0.3); c.fillStyle = 'rgba(225,232,255,.85)'; + c.beginPath(); c.moveTo(0, -150); c.lineTo(-6, -96); c.lineTo(6, -96); c.closePath(); c.fill(); c.fillStyle = 'rgba(80,110,220,.8)'; c.fillRect(-7, -96, 14, 5); c.restore(); + } + } else for (const s of [-1, 1]) for (let j = 0; j < 3; j++) { // ice wings behind + c.save(); c.translate(s * 34, 130 + j * 26); c.rotate(s * (-0.5 + j * 0.42)); const g = c.createLinearGradient(0, 0, s * 70, 0); + g.addColorStop(0, 'rgba(225,248,255,.95)'); g.addColorStop(1, 'rgba(120,200,255,.35)'); c.fillStyle = g; + c.beginPath(); c.moveTo(0, 0); c.lineTo(s * 34, -13); c.lineTo(s * 74, 0); c.lineTo(s * 34, 13); c.closePath(); c.fill(); c.restore(); + } + // shoulders and clothes + c.fillStyle = R ? '#16131c' : S ? '#26338a' : Mei ? '#2f9a52' : Pa ? '#c9a4e0' : Re ? '#f2e2ec' : '#2f6fd8'; c.beginPath(); c.moveTo(-78, 260); c.bezierCurveTo(-74, 196, -46, 172, 0, 170); c.bezierCurveTo(46, 172, 74, 196, 78, 260); c.closePath(); c.fill(); + c.fillStyle = '#f4f2f6'; c.beginPath(); c.moveTo(-30, 176); c.lineTo(0, 236); c.lineTo(30, 176); c.closePath(); c.fill(); + c.fillStyle = R ? '#c4253a' : S ? '#3fb06a' : Mei ? '#f0d36a' : Pa ? '#e0507a' : Re ? '#c8102e' : '#e0283f'; c.beginPath(); c.moveTo(-10, 182); c.lineTo(0, 214); c.lineTo(10, 182); c.closePath(); c.fill(); + // neck and face + c.fillStyle = '#f2d0bd'; c.fillRect(-11, 146, 22, 30); + const fg = c.createRadialGradient(-10, 104, 8, 0, 112, 52); fg.addColorStop(0, '#fff1e6'); fg.addColorStop(1, '#f0c9b2'); c.fillStyle = fg; + c.beginPath(); c.ellipse(0, 112, 40, 46, 0, 0, TAU); c.fill(); + // hair: back volume, bangs, side locks + const hg = c.createLinearGradient(0, 40, 0, 170); hg.addColorStop(0, hair[0]); hg.addColorStop(0.45, hair[1]); hg.addColorStop(1, hair[2]); c.fillStyle = hg; + c.beginPath(); c.moveTo(-52, 150); c.bezierCurveTo(-64, 80, -40, 44, 0, 42); c.bezierCurveTo(40, 44, 64, 80, 52, 150); c.bezierCurveTo(44, 120, 40, 100, 34, 92); + c.lineTo(22, 104); c.lineTo(14, 88); c.lineTo(2, 104); c.lineTo(-8, 88); c.lineTo(-20, 104); c.lineTo(-30, 90); c.bezierCurveTo(-40, 104, -44, 124, -52, 150); c.closePath(); c.fill(); + if (S) { // braids with green ribbons, maid headdress + for (const s of [-1, 1]) { + c.fillStyle = hg; c.beginPath(); c.ellipse(s * 46, 160, 9, 34, s * 0.12, 0, TAU); c.fill(); + c.strokeStyle = 'rgba(120,130,170,.6)'; c.lineWidth = 1.2; for (let k = 0; k < 4; k++) { c.beginPath(); c.arc(s * 46, 136 + k * 14, 8, 0.2 * PI, 0.8 * PI); c.stroke(); } + c.fillStyle = '#3fb06a'; c.beginPath(); c.moveTo(s * 46, 190); c.lineTo(s * 34, 200); c.lineTo(s * 36, 186); c.closePath(); c.fill(); c.beginPath(); c.moveTo(s * 46, 190); c.lineTo(s * 58, 200); c.lineTo(s * 56, 186); c.closePath(); c.fill(); + } + c.fillStyle = '#ffffff'; c.beginPath(); c.moveTo(-46, 58); c.quadraticCurveTo(0, 22, 46, 58); c.lineTo(40, 66); c.quadraticCurveTo(0, 36, -40, 66); c.closePath(); c.fill(); + c.strokeStyle = 'rgba(160,170,210,.7)'; c.lineWidth = 1; for (let k = -4; k <= 4; k++) { c.beginPath(); c.arc(k * 10, 44 + Math.abs(k) * 2.4, 4, PI, TAU); c.stroke(); } + } + // eyes + for (const s of [-1, 1]) { + c.fillStyle = '#ffffff'; c.beginPath(); c.ellipse(s * 16, 120, 9, 11, 0, 0, TAU); c.fill(); + const eg = c.createLinearGradient(0, 110, 0, 132); eg.addColorStop(0, '#1a0f14'); eg.addColorStop(0.35, eye); eg.addColorStop(1, '#ffd8e0'); c.fillStyle = eg; + c.beginPath(); c.ellipse(s * 16, 121, 6.5, 9, 0, 0, TAU); c.fill(); + c.fillStyle = '#fff'; c.beginPath(); c.arc(s * 16 - 2, 116, 2.4, 0, TAU); c.fill(); + c.strokeStyle = '#3a2228'; c.lineWidth = 2.2; c.beginPath(); c.arc(s * 16, 120, 10, PI * 1.15, PI * 1.85); c.stroke(); + } + c.strokeStyle = '#b06a6a'; c.lineWidth = 1.6; c.beginPath(); c.arc(0, 140, 6, 0.2 * PI, 0.8 * PI); c.stroke(); + c.fillStyle = 'rgba(255,120,140,.25)'; c.beginPath(); c.ellipse(-24, 136, 7, 4, 0, 0, TAU); c.ellipse(24, 136, 7, 4, 0, 0, TAU); c.fill(); + if (R) { c.fillStyle = '#c0182c'; c.beginPath(); c.moveTo(34, 64); c.lineTo(56, 52); c.lineTo(58, 78); c.closePath(); c.fill(); c.fillStyle = '#fff'; c.fillRect(44, 60, 3, 10); } + else if (Mei) { // long side locks with braids, green beret with a gold star + for (const s2 of [-1, 1]) { c.fillStyle = hg; c.beginPath(); c.ellipse(s2 * 50, 180, 10, 56, s2 * 0.08, 0, TAU); c.fill(); c.fillStyle = '#2f9a52'; c.fillRect(s2 * 50 - 6, 222, 12, 6); } + c.fillStyle = '#2a7a45'; c.beginPath(); c.moveTo(-50, 62); c.quadraticCurveTo(0, 6, 50, 62); c.quadraticCurveTo(0, 46, -50, 62); c.fill(); + star(c, 0, 40, 11, 4.6, '#f0d36a'); + } else if (Re) { // mob cap with a red band, two small fangs + c.fillStyle = '#f7ecf2'; c.beginPath(); c.moveTo(-58, 64); c.quadraticCurveTo(0, -6, 58, 64); c.quadraticCurveTo(0, 42, -58, 64); c.fill(); + c.strokeStyle = '#c8102e'; c.lineWidth = 5; c.beginPath(); c.moveTo(-50, 58); c.quadraticCurveTo(0, 32, 50, 58); c.stroke(); + c.fillStyle = '#ffffff'; for (const s2 of [-4, 4]) { c.beginPath(); c.moveTo(s2 - 2, 142); c.lineTo(s2, 149); c.lineTo(s2 + 2, 142); c.closePath(); c.fill(); } + } else if (Pa) { // long locks with red / blue ribbons, mob cap with a crescent + for (const s2 of [-1, 1]) { c.fillStyle = hg; c.beginPath(); c.ellipse(s2 * 50, 184, 10, 60, s2 * 0.06, 0, TAU); c.fill(); c.fillStyle = s2 < 0 ? '#e0507a' : '#5a7ae0'; c.fillRect(s2 * 50 - 6, 224, 12, 6); } + c.fillStyle = '#f2e6f6'; c.beginPath(); c.moveTo(-58, 66); c.quadraticCurveTo(0, -4, 58, 66); c.quadraticCurveTo(0, 44, -58, 66); c.fill(); + c.fillStyle = '#f0d36a'; c.beginPath(); c.arc(22, 30, 9, 0.4 * PI, 1.6 * PI); c.arc(26, 30, 7, 1.6 * PI, 0.4 * PI, true); c.fill(); + } else if (!S) { // big ribbon + c.fillStyle = '#3a7fe8'; for (const s of [-1, 1]) { c.beginPath(); c.moveTo(0, 46); c.bezierCurveTo(s * 20, 20, s * 54, 18, s * 50, 46); c.bezierCurveTo(s * 46, 60, s * 18, 58, 0, 46); c.fill(); } + c.fillStyle = '#2a5fc0'; c.beginPath(); c.arc(0, 46, 7, 0, TAU); c.fill(); + } + return (cache[key] = cv); + } + function portrait(c, kind, x, y, alpha) { c.save(); c.globalAlpha = alpha; c.drawImage(bustTile(kind), x - 110, y - 150); c.restore(); } + + // ---------- scene ---------- + function drawBackground(c, g) { + const tile = stageTile(g.kind), off = (g.t * (g.kind === 'rumia' ? 0.7 : g.kind === 'cirno' || g.kind === 'meiling' ? 0.9 : g.kind === 'patchouli' ? 0.5 : g.kind === 'remilia' ? 0.4 : 0.6)) % TILE_H; + c.drawImage(tile, 0, off - TILE_H); c.drawImage(tile, 0, off); + if (g.kind === 'cirno') { // drifting fog + for (let i = 0; i < 7; i++) { + const x = ((hash(i * 9) * W + g.t * (0.25 + i * 0.07)) % (W + 260)) - 130, y = 50 + i * 64 + Math.sin(g.t * 0.01 + i) * 20; + const fg = c.createRadialGradient(x, y, 10, x, y, 140); fg.addColorStop(0, 'rgba(225,245,255,.18)'); fg.addColorStop(1, 'rgba(225,245,255,0)'); c.fillStyle = fg; c.fillRect(x - 140, y - 140, 280, 280); + } + } else if (g.kind === 'rumia') { + const v = c.createRadialGradient(CX, H / 2, 160, CX, H / 2, 520); v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(4,2,12,.6)'); c.fillStyle = v; c.fillRect(0, 0, W, H); + for (let i = 0; i < 22; i++) { const x = hash(i * 41) * W, y = (hash(i * 43) * H + g.t * 0.4 * (1 + i % 3)) % H, a = 0.3 + 0.3 * Math.sin(g.t * 0.07 + i); c.fillStyle = 'rgba(200,255,170,' + a.toFixed(2) + ')'; c.fillRect(x, y, 2, 2); } + } else { + const v = c.createRadialGradient(CX, H / 2, 180, CX, H / 2, 560); v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(8,0,6,.55)'); c.fillStyle = v; c.fillRect(0, 0, W, H); + } + if (g.spell && g.phaseId) { + const a = Math.min(1, g.phaseT / 50), th = THEME[g.kind].acc; + c.save(); c.globalAlpha = a * 0.9; c.drawImage(spellTile(g.kind), 0, 0); c.restore(); + c.save(); c.globalAlpha = a; c.translate(CX, H / 2); + if (g.kind === 'sakuya') { // clock hands follow the spell clock, which stands still while time is stopped + const sec = g.clock / 60; + c.strokeStyle = `rgba(${th},.55)`; c.lineCap = 'round'; + c.lineWidth = 6; c.beginPath(); c.moveTo(0, 0); const ah = -PI / 2 + sec * TAU / 120; c.lineTo(Math.cos(ah) * 110, Math.sin(ah) * 110); c.stroke(); + c.lineWidth = 3; c.beginPath(); c.moveTo(0, 0); const am = -PI / 2 + sec * TAU / 10; c.lineTo(Math.cos(am) * 170, Math.sin(am) * 170); c.stroke(); + c.fillStyle = `rgba(${th},.7)`; c.beginPath(); c.arc(0, 0, 8, 0, TAU); c.fill(); + } else { + c.rotate(g.phaseT * (g.kind === 'rumia' ? 0.004 : -0.003)); c.strokeStyle = `rgba(${th},.16)`; c.lineWidth = 2; + const n = g.kind === 'rumia' ? 8 : 6; + for (let i = 0; i < n; i++) { const a = i * TAU / n, b = a + TAU * (n === 8 ? 3 : 2) / n; c.beginPath(); c.moveTo(Math.cos(a) * 200, Math.sin(a) * 200); c.lineTo(Math.cos(b) * 200, Math.sin(b) * 200); c.stroke(); } + c.beginPath(); c.arc(0, 0, 200, 0, TAU); c.stroke(); c.beginPath(); c.arc(0, 0, 224, 0, TAU); c.stroke(); + } + c.restore(); + } + if (g.stop > 0) { // time stop: the world loses its colour; bullets and characters are drawn after this, still in colour + const el = (g.stopLen || g.stop) - g.stop, a = Math.min(1, el / 6, g.stop / 8); + c.save(); c.globalAlpha = 0.85 * a; c.globalCompositeOperation = 'saturation'; c.fillStyle = '#808080'; c.fillRect(0, 0, W, H); + c.globalCompositeOperation = 'source-over'; c.globalAlpha = 0.22 * a; c.fillStyle = '#1b1640'; c.fillRect(0, 0, W, H); c.restore(); + } + } + function drawFamiliars(c, g) { + for (const f of g.fams) { + if (f.hp !== undefined) { if (f.t >= 0) fairy(c, f, g.t); continue; } + const col = f.c === M.C.RED ? '255,90,110' : '120,150,255', u = Math.min(1, f.t / 40); + c.save(); c.translate(f.x, f.y); c.globalAlpha = u; + const gr = c.createRadialGradient(0, 0, 2, 0, 0, 22); gr.addColorStop(0, `rgba(${col},.55)`); gr.addColorStop(1, `rgba(${col},0)`); c.fillStyle = gr; c.beginPath(); c.arc(0, 0, 22, 0, TAU); c.fill(); + c.rotate(f.t * (f.c === M.C.RED ? 0.05 : -0.05)); c.strokeStyle = `rgba(${col},.9)`; c.lineWidth = 1.5; + c.beginPath(); c.arc(0, 0, 14, 0, TAU); c.stroke(); + for (let k = 0; k < 2; k++) { c.beginPath(); for (let i = 0; i <= 3; i++) { const a = k * PI / 3 + i * TAU / 3; c.lineTo(Math.cos(a) * 13, Math.sin(a) * 13); } c.stroke(); } + c.restore(); + } + } + function drawBoss(c, g) { + const b = g.boss; if (b.y < -60) return; + const spellOn = g.spell && g.phaseId, th = THEME[g.kind].acc; + if (g.kind === 'rumia') { // darkness aura + const r = 46 + Math.sin(g.t * 0.05) * 4, a = c.createRadialGradient(b.x, b.y, 4, b.x, b.y, r); a.addColorStop(0, 'rgba(10,0,10,.55)'); a.addColorStop(1, 'rgba(10,0,10,0)'); c.fillStyle = a; c.beginPath(); c.arc(b.x, b.y, r, 0, TAU); c.fill(); + } else { const a = c.createRadialGradient(b.x, b.y, 4, b.x, b.y, 44); a.addColorStop(0, `rgba(${th},.35)`); a.addColorStop(1, `rgba(${th},0)`); c.fillStyle = a; c.beginPath(); c.arc(b.x, b.y, 44, 0, TAU); c.fill(); } + if (spellOn) { // spell circle shrinking with the remaining time + const left = Math.max(0, 1 - g.clock / g.timer), r = 28 + 52 * left; + c.save(); c.translate(b.x, b.y); c.rotate(g.t * 0.03); c.strokeStyle = `rgba(${th},.75)`; c.lineWidth = 2; c.beginPath(); c.arc(0, 0, r, 0, TAU); c.stroke(); + c.lineWidth = 1; c.beginPath(); c.arc(0, 0, r - 6, 0, TAU); c.stroke(); + for (let i = 0; i < 16; i++) { c.rotate(TAU / 16); c.fillStyle = `rgba(${th},.85)`; c.fillRect(r - 4.5, -1.5, 3, 3); } + c.restore(); + } + if (g.trans > 0 || (g.phaseId && g.phaseT < 40 && g.spell)) { // charge particles converging on the boss + for (let i = 0; i < 12; i++) { const a = i * TAU / 12 + g.t * 0.05, d = 70 - ((g.t * 2 + i * 9) % 70); c.fillStyle = `rgba(${th},.85)`; c.fillRect(b.x + Math.cos(a) * d - 1.5, b.y + Math.sin(a) * d - 1.5, 3, 3); } + } + if (g.defeat > 0) { + const u = 1 - g.defeat / 100; + for (let i = 0; i < 3; i++) { c.strokeStyle = `rgba(255,255,255,${(0.8 - u * 0.7).toFixed(2)})`; c.lineWidth = 3; c.beginPath(); c.arc(b.x, b.y, 10 + u * (220 + i * 80), 0, TAU); c.stroke(); } + if (u > 0.35) return; + } + if (g.kind === 'rumia') rumia(c, b.x, b.y, g.t); else if (g.kind === 'cirno') cirno(c, b.x, b.y, g.t); else if (g.kind === 'meiling') meiling(c, b.x, b.y, g.t); else if (g.kind === 'patchouli') patchouli(c, b.x, b.y, g.t); else if (g.kind === 'remilia') { + const iv = g.sub.inv || g.sub.bat > 0; // untouchable (C47): faded, inside a dark ring + if (iv) { c.strokeStyle = 'rgba(40,10,50,.85)'; c.lineWidth = 3; c.beginPath(); c.arc(b.x, b.y, 26, 0, TAU); c.stroke(); c.globalAlpha = 0.45; } + remilia(c, b.x, b.y, g.t); c.globalAlpha = 1; + } else sakuya(c, b.x, b.y, g.t); + } + function drawBullets(c, g, ox, oy) { + for (const q of g.bullets) { + const img = bulletSprite(q.k, q.c), oriented = q.k === 2 || q.k === 4 || q.k === 5 || q.k === 8, hw = img.width / 2; + if (oriented) { + const a = (q.vx * q.vx + q.vy * q.vy) > 1e-6 ? Math.atan2(q.vy, q.vx) : (q.a !== undefined ? q.a : PI / 2); + const cs = Math.cos(a), sn = Math.sin(a); c.setTransform(cs, sn, -sn, cs, q.x + ox, q.y + oy); c.drawImage(img, -hw, -hw); + } else { c.setTransform(1, 0, 0, 1, q.x + ox, q.y + oy); c.drawImage(img, -hw, -hw); } + } + c.setTransform(1, 0, 0, 1, ox, oy); + } + function drawLasers(c, g) { + for (const l of g.lasers) { + const warn = l.t <= l.wn, fade = l.t > l.wn + l.on, w = warn ? 1.5 : fade ? l.w * Math.max(0, 1 - (l.t - l.wn - l.on) / 16) : l.w * Math.min(1, (l.t - l.wn) / 6); + c.save(); c.translate(l.x, l.y); c.rotate(l.a); + const lc = l.col === undefined ? null : rgba(COL[l.col], 0.55), le = l.col === undefined ? 'rgba(60,220,110,0)' : rgba(COL[l.col], 0); + if (warn) { c.fillStyle = lc || 'rgba(160,255,190,.55)'; c.fillRect(0, -0.75, l.l, 1.5); } + else { const gr = c.createLinearGradient(0, -w, 0, w); gr.addColorStop(0, le); gr.addColorStop(0.5, 'rgba(220,255,230,.95)'); gr.addColorStop(1, le); c.fillStyle = gr; c.fillRect(0, -w, l.l, w * 2); } + c.restore(); + } + } + function drawPlayer(c, g) { + const p = g.player, B = g.bomb; + if (B && B.k === 'A') for (const o of B.orbs) { + const col = COL[[0, 5, 4, 3, 2, 8, 1][o.c % 7]]; + if (o.st === 0) { const gr = c.createRadialGradient(o.x, o.y, 2, o.x, o.y, 26); gr.addColorStop(0, '#ffffff'); gr.addColorStop(0.35, rgba(col, 0.9)); gr.addColorStop(1, rgba(col, 0)); c.fillStyle = gr; c.beginPath(); c.arc(o.x, o.y, 26, 0, TAU); c.fill(); } + else { const u = o.st / 30, gr = c.createRadialGradient(o.x, o.y, 4, o.x, o.y, 40 + u * 110); gr.addColorStop(0, rgba('#ffffff', 0.8 * (1 - u))); gr.addColorStop(1, rgba(col, 0)); c.fillStyle = gr; c.beginPath(); c.arc(o.x, o.y, 40 + u * 110, 0, TAU); c.fill(); } + } + if (B && B.k === 'B') { + const a = Math.min(1, B.t / 10) * Math.min(1, (B.dur - B.t) / 20); + c.fillStyle = `rgba(255,90,120,${(0.35 * a).toFixed(3)})`; c.fillRect(B.x - 31, 0, 62, H); c.fillRect(0, B.y - 31, W, 62); + c.strokeStyle = `rgba(255,230,240,${(0.8 * a).toFixed(3)})`; c.lineWidth = 2; c.strokeRect(B.x - 31, -2, 62, H + 4); c.strokeRect(-2, B.y - 31, W + 4, 62); + } + if (p.state === 'dead') { + const u = Math.min(1, p.deadT / 30); + for (let i = 0; i < 2; i++) { c.strokeStyle = `rgba(255,${i ? 120 : 255},${i ? 160 : 255},${(1 - u).toFixed(2)})`; c.lineWidth = 3 - i; c.beginPath(); c.arc(p.x, p.y, 6 + u * (60 + i * 40), 0, TAU); c.stroke(); } + return; + } + let alpha = 1; + if (p.state === 'spawning') alpha = 1 - p.spawnT / 30; else if (p.inv > 0 && p.inv % 8 < 2) alpha = 0.45; + c.save(); c.globalAlpha = alpha; + if (p.power >= 8) for (const o of g.orbs()) yinyang(c, o.x, o.y, g.t * 0.12, g.shotType === 'B'); + reimu(c, p.x, p.y, p.mx, g.t); c.restore(); + } + function drawHitbox(c, g) { + const p = g.player; if (p.state === 'dead' || !p.foc) return; + c.save(); c.translate(p.x, p.y); c.rotate(g.t * 0.04); c.strokeStyle = 'rgba(255,255,255,.55)'; c.lineWidth = 1; c.beginPath(); c.arc(0, 0, 14, 0, TAU * 0.8); c.stroke(); c.restore(); + c.fillStyle = '#ff2a4a'; c.beginPath(); c.arc(p.x, p.y, 3.4, 0, TAU); c.fill(); c.fillStyle = '#fff'; c.beginPath(); c.arc(p.x, p.y, 2, 0, TAU); c.fill(); + } + function fmt(n) { return String(Math.floor(n)).padStart(9, '0').replace(/(\d)(?=(\d{3})+$)/g, '$1,'); } + function drawOverlays(c, g) { + const p = g.player; + for (const q of g.pops) outlined(c, String(q.v), q.x, q.y - q.t * 0.4, 9, q.g ? '#ffe35c' : '#f2f2ff', SANS, 'center'); + if (g.cutin > 0) { + const u = g.cutin / 110, x = W - 150 + Math.max(0, u - 0.75) * 4 * 300, a = Math.min(1, u * 3) * 0.85; + c.fillStyle = `rgba(0,0,0,${(0.22 * a).toFixed(3)})`; c.fillRect(0, 130, W, 230); + portrait(c, g.kind, x, 260, a); + } + if (g.msg) { + const m = g.msg, a = Math.min(1, m.t / 20); + c.save(); c.globalAlpha = a; + if (m.k === 'capture') { outlined(c, 'Get Spell Card Bonus!!', CX, 150, 22, '#ffe066', SERIF, 'center'); outlined(c, m.v.toLocaleString('en-US'), CX, 178, 19, '#ffffff', SERIF, 'center'); } + else if (m.k === 'failed') outlined(c, 'Bonus Failed...', CX, 150, 19, '#b8c0d8', SERIF, 'center'); + else if (m.k === 'fullpower') outlined(c, 'Full Power Mode!!', CX, 230, 18, '#ff9ab6', SERIF, 'center'); + else if (m.k === 'extend') outlined(c, 'Extend!!', CX, 262, 20, '#9affc0', SERIF, 'center'); + c.restore(); + } + if (g.intro > 0) { + const boss = M.BOSS[g.kind], a = Math.min(1, g.intro / 20); + c.save(); c.globalAlpha = a; + outlined(c, boss.title, CX, 186, 15, '#e8d8ff', SERIF, 'center'); outlined(c, boss.name + ' ' + boss.en, CX, 218, 27, '#ffffff', SERIF, 'center'); + outlined(c, M.DIFFS[g.D] + ' · ' + M.hz + 'Hz', CX, 246, 15, DIFF_COL[g.D], SERIF, 'center'); + const sel = g.shotType; + outlined(c, (sel === 'A' ? '▶ ' : ' ') + 'Type A: Homing shots · Homing orbs', CX, 298, 13, sel === 'A' ? '#ffd7e0' : '#8a8fa8', SANS, 'center'); + outlined(c, (sel === 'B' ? '▶ ' : ' ') + 'Type B: Straight needles · Cross beam', CX, 318, 13, sel === 'B' ? '#ffd7e0' : '#8a8fa8', SANS, 'center'); + outlined(c, 'Q / E: Switch type at any time', CX, 340, 11, '#c6c8d8', SANS, 'center'); + c.restore(); + } + if (g.swapT > 0 && g.intro === 0) { c.save(); c.globalAlpha = Math.min(1, g.swapT / 15); outlined(c, g.shotType === 'A' ? 'Type A: Homing shots' : 'Type B: Straight needles', p.x, p.y - 34, 12, '#ffe2ea', SANS, 'center'); c.restore(); } + if (g.defeat > 0 || g.outcome === 'win') { outlined(c, 'Defeated!', CX, 232, 28, '#fff2a8', SERIF, 'center'); outlined(c, M.BOSS[g.kind].name + ' · ' + g.captures + ' / ' + g.declared + ' Spell Card · ' + (g.t / 60).toFixed(1) + ' s', CX, 260, 14, '#ffe9f0', SANS, 'center'); } + if (g.outcome === 'loss') { c.fillStyle = 'rgba(10,0,10,.5)'; c.fillRect(0, 0, W, H); outlined(c, 'GAME OVER', CX, 220, 32, '#ff8a9a', SERIF, 'center'); } + if (g.outcome === 'timeout') outlined(c, 'TIME UP', CX, 220, 30, '#ffd08a', SERIF, 'center'); + if (g.phaseId === 'c_freeze' && g.phaseT >= 40) { const lt = (g.phaseT - 40) % 330; if (lt >= 130 && lt < 146) { c.fillStyle = 'rgba(210,240,255,' + ((146 - lt) / 40).toFixed(3) + ')'; c.fillRect(0, 0, W, H); } } + if (g.stop > 0 && g.stopLen) { // time stop: a ripple from Sakuya when it starts, a cold vignette while it lasts + const el = g.stopLen - g.stop, a = Math.min(1, el / 8, g.stop / 10); + if (el < 28) { c.strokeStyle = `rgba(230,225,255,${(0.8 * (1 - el / 28)).toFixed(3)})`; c.lineWidth = 3; c.beginPath(); c.arc(g.boss.x, g.boss.y, 20 + el * 34, 0, TAU); c.stroke(); } + const v = c.createRadialGradient(CX, H / 2, 200, CX, H / 2, 520); v.addColorStop(0, 'rgba(150,140,255,0)'); v.addColorStop(1, `rgba(150,140,255,${(0.32 * a).toFixed(3)})`); + c.fillStyle = v; c.fillRect(0, 0, W, H); + } + if (g.bomb) { const B = g.bomb, a = Math.min(1, B.t / 12, (B.dur - B.t) / 30); c.save(); c.globalAlpha = Math.max(0, a); c.fillStyle = 'rgba(60,0,20,.5)'; c.fillRect(0, H - 70, 260, 22); outlined(c, B.k === 'A' ? 'Homing orbs' : 'Cross beam', 10, H - 54, 14, '#ffd6e2', SANS); c.restore(); } + if (g.flash > 0) { c.fillStyle = `rgba(255,255,255,${(g.flash / 40).toFixed(3)})`; c.fillRect(0, 0, W, H); } + if (g.hitFx > 0) { c.fillStyle = `rgba(255,40,70,${(g.hitFx / 110).toFixed(3)})`; c.fillRect(0, 0, W, H); } + if (p.state === 'alive' && p.power >= 128 && p.y < 128 && g.t % 40 < 30) outlined(c, '— Point of Collection —', p.x, 126, 9, 'rgba(255,240,200,.8)', SANS, 'center'); + } + // HUD over the field: boss line on top, player resources bottom-left, score / difficulty / native Hz bottom-right. + function drawHud(c, g) { + const ph = g.phaseId ? M.PHASES[g.phaseId] : null, boss = M.BOSS[g.kind], p = g.player, theme = THEME[g.kind]; + const top = c.createLinearGradient(0, 0, 0, 40); top.addColorStop(0, 'rgba(6,4,14,.55)'); top.addColorStop(1, 'rgba(6,4,14,0)'); c.fillStyle = top; c.fillRect(0, 0, W, 40); + const bot = c.createLinearGradient(0, H - 34, 0, H); bot.addColorStop(0, 'rgba(6,4,14,0)'); bot.addColorStop(1, 'rgba(6,4,14,.55)'); c.fillStyle = bot; c.fillRect(0, H - 34, W, 34); + if (g.intro === 0 && !g.defeat && !g.outcome) { + outlined(c, 'Enemy', 10, 14, 11, '#ffd0d8'); outlined(c, boss.name, 52, 14, 12, '#ffffff', SANS); + const left = g.remainingAttacks(), sx = 60 + c.measureText(boss.name).width; + for (let i = 0; i < Math.min(9, left); i++) star(c, sx + 6 + i * 11, 10, 4.6, 2, '#ffd56a'); + const pi = Math.min(g.phase + 1, g.phases.length) + ' / ' + g.phases.length; + outlined(c, pi, W - 52, 14, 11, '#e6dcf2', SANS, 'right'); + if (ph) { + const frac = Math.max(0, g.phaseHp / g.phaseMax), bx = 10, bw = W - 64; + c.fillStyle = 'rgba(0,0,0,.45)'; c.fillRect(bx, 19, bw, 5); + const gr = c.createLinearGradient(bx, 0, bx + bw, 0); gr.addColorStop(0, ph.spell ? theme.bar[0] : '#fff2f5'); gr.addColorStop(1, ph.spell ? theme.bar[1] : '#ffd0dc'); c.fillStyle = gr; c.fillRect(bx, 19, bw * frac, 5); + const secs = Math.max(0, Math.ceil((g.timer - g.clock) / 60)); + outlined(c, String(Math.min(99, secs)).padStart(2, '0'), W - 8, 30, 24, g.stop > 0 ? '#b8b0ff' : secs <= 10 ? '#ff6a6a' : '#ffffff', SERIF, 'right'); + if (ph.spell && !g.trans) { + const decl = Math.max(0, g.cutin) / 110, y = 50 + decl * decl * 360; + c.fillStyle = 'rgba(20,6,18,.5)'; c.fillRect(W - 330, y - 13, 322, 30); + outlined(c, ph.name, W - 12, y + 1, 14, '#ffffff', SANS, 'right'); + const base = boss.base, bonus = g.capture ? base + Math.floor(base * Math.floor((g.timer - g.clock) / 60) / 10) : 0; + outlined(c, g.capture ? 'Bonus ' + bonus.toLocaleString('en-US') : 'Bonus Failed', W - 12, y + 14, 10, g.capture ? '#ffe58a' : '#9aa3b8', SANS, 'right'); + } else outlined(c, ph.name + ' · ' + ph.en, 10, 40, 11, '#e9e2f2'); + } + const b = g.boss; // boss x indicator on the bottom edge + c.fillStyle = 'rgba(255,80,110,.8)'; c.fillRect(b.x - 16, H - 9, 32, 9); text(c, 'ENEMY', b.x, H - 1.5, 8, '#fff', SANS, 'center'); + } + // bottom-left: spare lives, bombs, power, shot type + const y0 = H - 12; + outlined(c, 'Player', 10, y0, 12, '#f2c4d0', SERIF); + for (let i = 0; i < Math.max(0, Math.min(8, p.lives - 1)); i++) star(c, 58 + i * 14, y0 - 4, 5.6, 2.4, '#ff7aa0'); + const bx = 58 + Math.max(1, Math.min(8, p.lives - 1)) * 14 + 8; + outlined(c, 'Bomb', bx, y0, 12, '#f2c4d0', SERIF); + for (let i = 0; i < Math.min(8, p.bombs); i++) star(c, bx + 42 + i * 14, y0 - 4, 5.6, 2.4, '#9be37a'); + const px = bx + 42 + Math.max(1, Math.min(8, p.bombs)) * 14 + 8, pw = Math.min(128, p.power); + outlined(c, 'Power', px, y0, 12, '#f2c4d0', SERIF); + c.fillStyle = 'rgba(0,0,0,.45)'; c.fillRect(px + 44, y0 - 9, 60, 8); c.fillStyle = pw >= 128 ? '#ffd35a' : '#ff5a72'; c.fillRect(px + 44, y0 - 9, 60 * pw / 128, 8); + outlined(c, pw >= 128 ? 'MAX' : String(pw), px + 110, y0, 12, pw >= 128 ? '#ffd35a' : '#ffffff', SERIF); + outlined(c, g.shotType === 'A' ? 'Type A' : 'Type B', px + 146, y0, 11, '#f0dce2', SANS); + // bottom-right: score, graze, spell count, difficulty, native Hz + const right = W - 8; + outlined(c, M.hz + 'Hz', right, y0, 12, '#9fe0ff', SERIF, 'right'); + outlined(c, M.DIFFS[g.D], right - 46, y0, 13, DIFF_COL[g.D], SERIF, 'right'); + outlined(c, 'Spell ' + g.captures + '/' + g.declared, right - 116, y0, 11, '#e2cfd8', SANS, 'right'); + outlined(c, 'Graze ' + p.graze, right - 186, y0, 11, '#e2cfd8', SANS, 'right'); + outlined(c, fmt(p.score), right - 262, y0, 13, '#ffffff', SERIF, 'right'); + outlined(c, 'Score', right - 352, y0, 11, '#f2c4d0', SERIF, 'right'); + } + // Build every cached sprite/tile once, before the first frame, so no gameplay frame pays for canvas creation. + function warm() { + if (cache.warm) return; + for (let k = 0; k < 10; k++) for (let ci = 0; ci < COL.length; ci++) bulletSprite(k, ci); + for (let k = 0; k < 7; k++) itemSprite(k); + for (let k = 0; k < 3; k++) shotSprite(k); + for (const kind of ['rumia', 'cirno', 'sakuya', 'meiling', 'patchouli', 'remilia']) { stageTile(kind); spellTile(kind); bustTile(kind); } + // first use of a CJK string triggers font fallback and glyph rasterisation; do it once here instead of at a spell declaration + const sc = canvas(64, 32).getContext('2d'), strings = ['Defeated! Get Spell Card Bonus!! Bonus Failed... Full Power Mode!! Extend!! GAME OVER TIME UP ENEMY Enemy Point of Collection 60Hz', + 'Homing orbs Cross beam A Type B Homing shots Straight needles Q / E: Switch type at any time ▶ Player Bomb Power MAX Score Graze Spell 0123456789,/ ·']; + for (const id in M.PHASES) strings.push(M.PHASES[id].name + ' · ' + M.PHASES[id].en); + for (const k in M.BOSS) strings.push(M.BOSS[k].name + M.BOSS[k].en + M.BOSS[k].title); + for (const str of strings) for (const size of [8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 22, 24, 27, 28, 30, 32]) for (const font of [SANS, SERIF]) { sc.font = size + 'px ' + font; sc.fillText(str, 0, 20); sc.strokeText(str, 0, 20); } + // draw every cached canvas once so its pixels are uploaded before the first gameplay frame that needs it + const up = canvas(16, 16).getContext('2d'); for (const k in cache) if (cache[k] && cache[k].width) up.drawImage(cache[k], 0, 0, 16, 16); + up.getImageData(0, 0, 1, 1); + cache.warm = true; + } + M.warmRenderer = warm; + M.draw = function (g, c) { + warm(); + c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = 'source-over'; c.textBaseline = 'alphabetic'; + const sh = g.shake > 0 ? Math.min(4, g.shake / 4) : 0, ox = sh ? Math.sin(g.t * 1.7) * sh : 0, oy = sh ? Math.cos(g.t * 2.3) * sh : 0; + if (sh) { c.fillStyle = '#05030a'; c.fillRect(0, 0, W, H); } + c.setTransform(1, 0, 0, 1, ox, oy); + drawBackground(c, g); + for (const it of g.items) c.drawImage(itemSprite(it.k), it.x - 11, it.y - 11); + for (const s of g.shots) { const img = shotSprite(s.k); if (s.k === 1) { c.save(); c.translate(s.x, s.y); c.rotate(Math.atan2(s.vy, s.vx) + PI / 2); c.drawImage(img, -8, -22); c.restore(); } else c.drawImage(img, s.x - 8, s.y - 22); } + drawFamiliars(c, g); drawBoss(c, g); drawLasers(c, g); drawPlayer(c, g); + drawBullets(c, g, ox, oy); + drawHitbox(c, g); drawOverlays(c, g); + c.setTransform(1, 0, 0, 1, 0, 0); + drawHud(c, g); + }; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/touhou_remake/game.js b/environments/games/web/games/touhou_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..46b7fef39dd684fd17e883c5592d91c4aa444d07 --- /dev/null +++ b/environments/games/web/games/touhou_remake/game.js @@ -0,0 +1,1509 @@ +/* Touhou 6 (EoSD) boss practice: Rumia (stage 1), Cirno (stage 2), Hong Meiling (stage 3), Patchouli Knowledge (stage 4), Sakuya + * (stage 5) and Remilia Scarlet (stage 6), rules scarlet-practice@8. + * Player/bomb/item/rank/spell-card/time-stop rules follow the CC0 GensokyoClub/th06 decompilation (v1.02h); spell geometry is + * authored from community descriptions. + * The arena uses the full frame. Movement, projectiles, and collisions use the original pixel units. */ +(function (root) { + 'use strict'; + // Local bindings of the builtins: under Node's vm loader every global lookup goes through the sandbox interceptor (30x slower + // in the hot loops); in a browser this changes nothing. Same functions, same results. + const Math = root.Math, Number = root.Number, Object = root.Object, Array = root.Array, Set = root.Set, Error = root.Error; + const N = root.NativeBench, TAU = Math.PI * 2, PI = Math.PI; + const W = 854, H = 480, CX = W / 2; // full-frame arena (C18B; original lane 384x448, C18) + const AREA = {x0: 8, y0: 16, x1: W - 8, y1: H - 16}; // movement-area insets 8/16 (S11) + const SPAWN = {x: CX, y: H - 64}; // 64 px above the bottom edge, as (192, 384) in 448 (S08) + const DIFFS = ['Easy', 'Normal', 'Hard', 'Lunatic']; + const diffIndex = d => d < 0.3 ? 0 : d < 0.6 ? 1 : d < 0.85 ? 2 : 3; // C15 (engineering mapping) + const TIERS = {easy: 0.2, normal: 0.5, hard: 0.8}; // public tiers = original Easy / Normal / Hard (C24) + // Tier calibration (C24, approximation): one life multiplier per boss and tier on the C16 per-attack life, non-decreasing from + // easy to hard, and one attack-timer multiplier per tier; linear in d between the tier anchors, flat outside them (Lunatic uses + // the hard values). Calibrated with the reference controller against the tier time windows (easy 20-30 s, normal 45-90 s, + // hard 150-240 s); a boss with more attacks gets a smaller multiplier for the same window. + const LIFE_CAL = {rumia: [0.40, 0.52, 1.6], cirno: [0.40, 0.415, 1.0], sakuya: [0.45, 0.45, 0.9], meiling: [0.40, 0.45, 0.9], patchouli: [0.40, 0.42, 0.8], remilia: [0.45, 0.45, 0.74]}; + const TIME_CAL = [1, 1, 2]; + const calAt = (v, d) => { + const a = [TIERS.easy, TIERS.normal, TIERS.hard]; + if (d <= a[0]) return v[0]; + if (d >= a[2]) return v[2]; + const i = d <= a[1] ? 0 : 1; + return v[i] + (v[i + 1] - v[i]) * (d - a[i]) / (a[i + 1] - a[i]); + }; + // Enemy bullet sprite boxes (edge length, px), BulletManager templates (S15). + const K = {PELLET: 0, RING: 1, RICE: 2, BALL: 3, KUNAI: 4, SHARD: 5, BIG: 6, FIRE: 7, KNIFE: 8, BUBBLE: 9}; + const BSIZE = [4, 6, 4, 6, 5, 4, 16, 11, 9, 32]; + const C = {RED: 0, PINK: 1, BLUE: 2, CYAN: 3, GREEN: 4, YELLOW: 5, ORANGE: 6, WHITE: 7, PURPLE: 8}; + const RAINBOW = [0, 6, 5, 4, 3, 2, 8]; + const PLAYER_HALF = 1.25, GRAZE_PAD = 20, BOSS_HALF = 16; // C02, C04; boss box is an approximation (C23) + // Shot rows: [wait, start, dx, dy, w, h, angleDeg, speed, damage, spawn(0 body,1 left orb,2 right orb), kind(0 main,1 homing,2 needle)] + const MAIN = (dx, a, d) => [5, 0, dx, 0, 12, 12, a, 12, d, 0, 0]; + const AM = (w, s, a1, a2, d) => [[w, s, 0, 0, 12, 12, a1, 10, d, 1, 1], [w, s, 0, 0, 12, 12, a2, 10, d, 2, 1]]; + const ND = (w, dx, d) => [[w, 0, dx, -16, 12, 40, -90, 22, d, 1, 2], [w, 0, dx, -16, 12, 40, -90, 22, d, 2, 2]]; + const A7 = [MAIN(0, -97, 24), MAIN(0, -90, 28), MAIN(0, -83, 24)], B8 = [MAIN(0, -106, 9), MAIN(0, -98, 17), MAIN(0, -90, 20), MAIN(0, -82, 17), MAIN(0, -74, 9)]; + const SHOT = { // g_CharacterPowerDataReimuA / ReimuB (S09); the first tier whose cut-off exceeds power is used + A: [[8, [MAIN(0, -90, 48)]], [16, [MAIN(0, -90, 48), ...AM(30, 0, -120, -60, 14)]], + [32, [MAIN(-4, -91, 30), MAIN(4, -89, 30), ...AM(30, 0, -120, -60, 14)]], + [48, [MAIN(0, -96, 24), MAIN(0, -90, 30), MAIN(0, -84, 24), ...AM(30, 0, -120, -60, 14)]], + [64, [MAIN(0, -97, 24), MAIN(0, -90, 30), MAIN(0, -83, 24), ...AM(15, 0, -120, -60, 12)]], + [80, [MAIN(0, -97, 24), MAIN(0, -90, 29), MAIN(0, -83, 24), ...AM(15, 0, -120, -60, 9), ...AM(30, 0, -150, -30, 12)]], + [96, [...A7, ...AM(30, 0, -110, -70, 10), ...AM(30, 10, -130, -50, 9), ...AM(30, 20, -150, -30, 11)]], + [127, [...A7, ...AM(15, 0, -110, -70, 8), ...AM(15, 5, -130, -50, 8), ...AM(15, 10, -150, -30, 8)]], + [999, [MAIN(-8, -97, 23), MAIN(-8, -90, 24), MAIN(8, -90, 24), MAIN(8, -83, 23), ...AM(16, 0, -110, -70, 10), ...AM(16, 4, -130, -50, 8), ...AM(16, 8, -150, -30, 7), ...AM(16, 12, -170, -10, 10)]]], + B: [[8, [MAIN(0, -90, 48)]], [16, [MAIN(0, -90, 48), ...ND(15, 0, 12)]], + [32, [MAIN(-4, -91, 32), MAIN(4, -89, 32), ...ND(10, 0, 12)]], + [48, [MAIN(-4, -91, 30), MAIN(4, -89, 30), ...ND(8, 0, 12)]], + [64, [MAIN(0, -97, 20), MAIN(0, -90, 28), MAIN(0, -83, 20), ...ND(8, 0, 12)]], + [80, [MAIN(0, -97, 16), MAIN(0, -90, 27), MAIN(0, -83, 16), ...ND(5, 8, 12), ...ND(8, -8, 10)]], + [96, [MAIN(0, -98, 16), MAIN(0, -90, 22), MAIN(0, -82, 16), ...ND(3, 8, 10), ...ND(5, -8, 10)]], + [127, [...B8, ...ND(3, 12, 10), ...ND(5, -12, 10), ...ND(10, 0, 10)]], + [999, [...B8, ...ND(3, 12, 10), ...ND(3, -12, 10), ...ND(5, 0, 10)]]] + }; + const POWER_SCORE = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 51200]; + const POINT_VALUE = [[100000, 60000, 100], [100000, 60000, 100], [150000, 100000, 180], [200000, 150000, 270]]; // (S10) + const RANK = [[16, 12, 20], [16, 10, 32], [16, 10, 32], [16, 10, 32]]; // rank, min, max (S11) + const EXTENDS = [10000000, 20000000, 40000000, 60000000]; + const ITEM = {POWER: 0, POINT: 1, BIG: 2, BOMB: 3, FULL: 4, LIFE: 5, STAR: 6}; + // Base HP and duration before tier scaling. The labels identify the attacks in this environment. + const PHASES = { + r_non1: {spell: false, hp: 9000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + r_bird: {spell: true, hp: 2600, time: 40, name: 'Alternating Sweep', en: 'Alternating Sweep', easyTimeoutOnly: true}, + r_non2: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + r_demarc: {spell: true, hp: 3200, time: 45, name: 'Counter Rings', en: 'Counter Rings'}, + c_non1: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + c_icicle: {spell: true, hp: 2800, time: 40, name: 'Side Arcs', en: 'Side Arcs', diffs: [0, 1]}, + c_hail: {spell: true, hp: 3000, time: 40, name: 'Hanging Shard Rings', en: 'Hanging Shard Rings', diffs: [2, 3]}, + c_non2: {spell: false, hp: 11000, time: 30, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + c_freeze: {spell: true, hp: 3600, time: 50, name: 'Stall and Scatter', en: 'Stall and Scatter'}, + c_blizzard: {spell: true, hp: 2600, time: 45, name: 'Drifting Shard Bursts', en: 'Drifting Shard Bursts', diffs: [1, 2, 3]}, + // Sakuya: the time stops freeze the player's shots, so for the same C16 capture time her cards carry less life (C16B) + s_non1: {spell: false, hp: 7000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + s_corpse: {spell: true, hp: 2200, time: 40, name: 'Stop and Lay Knives', en: 'Stop and Lay Knives', diffs: [0, 1]}, + s_jack: {spell: true, hp: 2300, time: 40, name: 'Trail Knives', en: 'Trail Knives', diffs: [2, 3]}, + s_non2: {spell: false, hp: 11000, time: 35, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + s_luna: {spell: true, hp: 2300, time: 45, name: 'Knife Lanes', en: 'Knife Lanes', diffs: [0, 1]}, + s_world: {spell: true, hp: 2400, time: 45, name: 'Surround Knives', en: 'Surround Knives', diffs: [2, 3]}, + s_non3: {spell: false, hp: 11000, time: 30, name: 'Non-spell pattern 3', en: 'Non-spell 3'}, + s_doll: {spell: true, hp: 2300, time: 50, name: 'Turning Ricochet Knives', en: 'Turning Ricochet Knives', diffs: [0, 1]}, + s_killing: {spell: true, hp: 2400, time: 50, name: 'Rest and Aim Rings', en: 'Rest and Aim Rings', diffs: [2, 3]}, + // Hong Meiling (stage 3, C35): Easy 5 / Normal 6 / Hard+ 7 attacks; hp/time are C16-style starting values, calibrated per tier + m_non1: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + m_chime: {spell: true, hp: 2800, time: 40, name: 'Fixed Angle Streams', en: 'Fixed Angle Streams'}, + m_non2: {spell: false, hp: 11000, time: 35, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + m_vine: {spell: true, hp: 2800, time: 40, name: 'Drifting Scatter', en: 'Drifting Scatter', diffs: [2, 3]}, + m_non3: {spell: false, hp: 11000, time: 30, name: 'Non-spell pattern 3', en: 'Non-spell 3'}, + m_rain: {spell: true, hp: 3000, time: 45, name: 'Side Accel Shards', en: 'Side Accel Shards', diffs: [0, 1]}, + m_dance: {spell: true, hp: 3000, time: 45, name: 'Burst and Curve', en: 'Burst and Curve', diffs: [2, 3]}, + m_typhoon: {spell: true, hp: 3200, time: 50, name: 'Crossing Spirals', en: 'Crossing Spirals', diffs: [1, 2, 3]}, + // Patchouli Knowledge (stage 4, C40), Reimu A list: Easy 4 / Normal 6 / Hard+ 7 attacks + p_non1: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + p_agni: {spell: true, hp: 2800, time: 40, name: 'Wavering Fall', en: 'Wavering Fall', diffs: [0, 1]}, + p_agni_hl: {spell: true, hp: 3000, time: 40, name: 'Wavering Fall Dense', en: 'Wavering Fall Dense', diffs: [2, 3]}, + p_non2: {spell: false, hp: 11000, time: 30, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + p_trilithon_hl: {spell: true, hp: 2800, time: 40, name: 'Stall and Turn', en: 'Stall and Turn', diffs: [1]}, + p_shake: {spell: true, hp: 3000, time: 40, name: 'Stall Turn and Heavy Shots', en: 'Stall Turn and Heavy Shots', diffs: [2, 3]}, + p_lava: {spell: true, hp: 3000, time: 45, name: 'Rings and Stalls', en: 'Rings and Stalls'}, + p_mercury: {spell: true, hp: 3000, time: 45, name: 'Twin Curving Streams', en: 'Twin Curving Streams', diffs: [1, 2, 3]}, + p_forest: {spell: true, hp: 3200, time: 50, name: 'Corner Stream and Sparks', en: 'Corner Stream and Sparks', diffs: [2, 3]}, + // Remilia Scarlet (stage 6, C45): Normal and Hard+ each 4 non-spells + 5 cards; the original Easy has no stage 6. `base` = the + // card's own g_SpellcardScore where it differs from BOSS.base (C46); `bat` = the bomb rule of the final card (C47). + r6_non1: {spell: false, hp: 10000, time: 30, name: 'Non-spell pattern 1', en: 'Non-spell 1'}, + r6_david: {spell: true, hp: 1100, time: 40, name: 'Beam Web', en: 'Beam Web', diffs: [0, 1]}, + r6_demon: {spell: true, hp: 2600, time: 40, name: 'Static Web Shells', en: 'Static Web Shells', diffs: [2, 3], base: 600000}, + r6_non2: {spell: false, hp: 8000, time: 30, name: 'Non-spell pattern 2', en: 'Non-spell 2'}, + r6_nether: {spell: true, hp: 1100, time: 40, name: 'Falling Slivers', en: 'Falling Slivers', diffs: [0, 1]}, + r6_needles: {spell: true, hp: 2600, time: 40, name: 'Bouncing Slivers', en: 'Bouncing Slivers', diffs: [2, 3], base: 600000}, + r6_non3: {spell: false, hp: 7000, time: 30, name: 'Non-spell pattern 3', en: 'Non-spell 3'}, + r6_tepes: {spell: true, hp: 1200, time: 45, name: 'Spiral Blades', en: 'Spiral Blades', diffs: [0, 1]}, + r6_fantasy: {spell: true, hp: 2800, time: 45, name: 'Even Way Shells', en: 'Even Way Shells', diffs: [2, 3], base: 600000}, + r6_non4: {spell: false, hp: 6000, time: 35, name: 'Non-spell pattern 4', en: 'Non-spell 4'}, + r6_shoot: {spell: true, hp: 1000, time: 40, name: 'Fast Aimed Shells', en: 'Fast Aimed Shells', diffs: [0, 1]}, + r6_meister: {spell: true, hp: 1900, time: 40, name: 'Led Volleys', en: 'Led Volleys', diffs: [2, 3], base: 600000}, + r6_magic: {spell: true, hp: 2800, time: 50, name: 'Bouncing Trail Shells', en: 'Bouncing Trail Shells', diffs: [0, 1], bat: true}, + r6_gensokyo: {spell: true, hp: 2600, time: 50, name: 'Trail Shells and Ring', en: 'Trail Shells and Ring', diffs: [2, 3], base: 600000, bat: true} + }; + const ORDER = { + rumia: ['r_non1', 'r_bird', 'r_non2', 'r_demarc'], + cirno: ['c_non1', 'c_icicle', 'c_hail', 'c_non2', 'c_freeze', 'c_blizzard'], + sakuya: ['s_non1', 's_corpse', 's_jack', 's_non2', 's_luna', 's_world', 's_non3', 's_doll', 's_killing'], + meiling: ['m_non1', 'm_chime', 'm_non2', 'm_vine', 'm_non3', 'm_rain', 'm_dance', 'm_typhoon'], + // the Reimu A card list (C40): the shot type at reset fixes it; only Reimu A is implemented + patchouli: ['p_non1', 'p_agni', 'p_agni_hl', 'p_non2', 'p_trilithon_hl', 'p_shake', 'p_lava', 'p_mercury', 'p_forest'], + remilia: ['r6_non1', 'r6_david', 'r6_demon', 'r6_non2', 'r6_nether', 'r6_needles', 'r6_non3', 'r6_tepes', 'r6_fantasy', 'r6_non4', 'r6_shoot', 'r6_meister', 'r6_magic', 'r6_gensokyo'] + }; + // BossBench easy (d < 0.30) keeps the opening non-spell and the boss's final Easy card (C24, deviation from the original Easy). + const EASY_ORDER = {rumia: ['r_non1', 'r_bird', 'r_demarc'], cirno: ['c_non1', 'c_freeze'], sakuya: ['s_non1', 's_doll'], meiling: ['m_non1', 'm_rain'], patchouli: ['p_non1', 'p_lava'], remilia: ['r6_non1', 'r6_magic']}; + const BOSS = { + rumia: {name: 'Fan Caster', en: 'FAN CASTER', title: 'Spread arms and fire sweeping loops', stage: 'Stage 1', base: 200000}, + cirno: {name: 'Shard Sprayer', en: 'SHARD SPRAYER', title: 'Crystal shards fill the sky, then suddenly freeze', stage: 'Stage 2', base: 200000}, + meiling: {name: 'Spiral Weaver', en: 'SPIRAL WEAVER', title: 'Stationary crossed streams', stage: 'Stage 3', base: 250000}, // g_SpellcardScore stage 3 (C36) + patchouli: {name: 'Beam Elementalist', en: 'BEAM ELEMENTALIST', title: 'Rotating beams and rapid elemental shots', stage: 'Stage 4', base: 300000}, // g_SpellcardScore stage 4 (C41) + sakuya: {name: 'Stoptime Knifer', en: 'STOPTIME KNIFER', title: 'Time stops and knives are already in place', stage: 'Stage 5', base: 400000}, // g_SpellcardScore (S13) + remilia: {name: 'Web Bombardier', en: 'WEB BOMBARDIER', title: 'Beam webs and trailing giant bullets', stage: 'Stage 6', base: 500000} // Normal cards; Hard+ cards carry their own 600,000 (S13) + }; + const INTRO = 120, TRANSITION = 80, DEFEAT = 100, START_POWER = 128; + + const M = root.TouhouGame = { + id: 'touhou_remake', version: 'scarlet-practice@8', hz: 60, maxSeconds: 600, dimension: '2d', renderer: 'canvas-native', + title: 'Touhou Koumakyou: Boss Practice', tiers: TIERS, + cases: [{id: 'touhou/rumia', name: 'Fan Caster · Stage 1 Boss'}, {id: 'touhou/cirno', name: 'Shard Sprayer · Stage 2 Boss'}, {id: 'touhou/sakuya', name: 'Stoptime Knifer · Stage 5 Boss'}, {id: 'touhou/meiling', name: 'Spiral Weaver · Stage 3 Boss'}, {id: 'touhou/patchouli', name: 'Beam Elementalist · Stage 4 Boss'}, {id: 'touhou/remilia', name: 'Web Bombardier · Stage 6 Boss'}], + controls: { + 'W A S D / arrow keys': 'Move in eight directions at 4.0 px/frame; diagonal movement is normalized by √2', + 'Shift': 'Slow movement at 2.0 px/frame, showing the 2.5×2.5 px hitbox; options cluster inward', + 'J / LMB': 'Hold to shoot: Type A homing shots / Type B straight needles (one cycle per 30 frames)', + 'K / RMB': 'Spell card: Type A homing orbs / Type B cross beam; deathbomb within 6 frames after being hit', + 'Q / E': 'Switch between Type A and Type B at any time except during a spell card or time stop', + 'Esc': 'Pause (automatic on focus loss)' + }, + W, H, CX, AREA, SPAWN, K, C, BSIZE, PHASES, ORDER, EASY_ORDER, BOSS, DIFFS, diffIndex, LIFE_CAL, TIME_CAL, calAt, ITEM, SHOT + }; + + // Fairies (C33): ordinary enemies with a 12x12 hitbox (contact box 8x8); only in-bounds fairies interact. + const FAIRY_HALF = 6, EMPTY_A = []; + const fairyIn = f => f.x >= 0 && f.x <= W && f.y >= 0 && f.y <= H; + const clone = v => { + if (v === null || typeof v !== 'object') return v; + if (Array.isArray(v)) { const a = new Array(v.length); for (let i = 0; i < v.length; i++) a[i] = clone(v[i]); return a; } + const o = {}; for (const k in v) o[k] = clone(v[k]); return o; + }; + const angDiff = (a, b) => Math.atan2(Math.sin(a - b), Math.cos(a - b)); + + class Game { + constructor(id, seed, d) { + this.id = id; this.kind = id.split('/')[1]; this.d = d; this.D = diffIndex(d); + if (!ORDER[this.kind]) throw Error('Unknown touhou case ' + id); + this.rng = (seed >>> 0) || 0x9e3779b9; this.t = 0; this.outcome = null; this.events = []; + this.shotType = 'A'; + const r = RANK[this.D]; this.rank = r[0]; this.rankMin = r[1]; this.rankMax = r[2]; this.subrank = 0; + // lifeCount 4 on easy, the default 2 otherwise: both inside the original option range 0..4 (S22), the tier's "damage" axis (C24) + const lives = this.D === 0 ? 5 : 3; this.lifeMax = lives; + this.player = {x: SPAWN.x, y: SPAWN.y, state: 'alive', inv: 120, deadT: 0, window: 0, spawnT: 0, focus: 0, foc: 0, mx: 0, + fireT: -1, lives, bombs: 3, power: START_POWER, graze: 0, grazeStage: 0, score: 0, points: 0, pc: 0, grace: 0, + misses: 0, bombsUsed: 0, extendsEarned: 0, hits: 0}; + const lm = calAt(LIFE_CAL[this.kind], d), tm = calAt(TIME_CAL, d); + this.phases = (this.D === 0 ? EASY_ORDER : ORDER)[this.kind].filter(id => !PHASES[id].diffs || PHASES[id].diffs.includes(this.D)); + this.lifeOf = this.phases.map(id => Math.max(100, Math.round(PHASES[id].hp * lm / 10) * 10)); + this.timeOf = this.phases.map(id => Math.round(PHASES[id].time * tm) * 60); + this.bossMax = this.lifeOf.reduce((v, x) => v + x, 0); this.cleared = 0; + this.boss = {x: CX, y: -40, fx: CX, fy: -40, tx: CX, ty: 112, mt: 0, md: 90, lin: 0}; + this.phase = -1; this.phaseId = null; this.phaseT = 0; this.clock = 0; this.timer = 0; this.phaseHp = 0; this.phaseMax = 1; + this.spell = false; this.capture = false; this.usedBomb = false; this.timedOut = []; this.sub = {}; + this.intro = INTRO; this.trans = 0; this.defeat = 0; this.captures = 0; this.declared = 0; this.stop = 0; this.stopLen = 0; + this.bullets = []; this.lasers = []; this.shots = []; this.items = []; this.fams = []; this.bomb = null; + this.pops = []; this.msg = null; this.cutin = 0; this.shake = 0; this.flash = 0; this.hitFx = 0; this.swapT = 0; + } + // ---------- helpers ---------- + ev(name) { this.events.push(name); } + rnd() { return N.rand(this); } + rankLerp(lo, hi) { return this.rank * (hi - lo) / 32 + lo; } + sp(s) { return s * (1 + this.rankLerp(-0.08, 0.08)); } // approximated rank speed range + cnt(n) { return Math.max(1, n + Math.trunc(this.rankLerp(1, -1))); } // low rank denser, high rank sparser (S19) + iv(n) { return Math.max(1, n + Math.trunc(this.rankLerp(n / 5, -n / 5))); } // +-20 % interval (S13) + addSubrank(n) { this.subrank += n; while (this.subrank >= 100) { this.rank++; this.subrank -= 100; } if (this.rank > this.rankMax) this.rank = this.rankMax; } + subSubrank(n) { this.subrank -= n; while (this.subrank < 0) { this.rank--; this.subrank += 100; } if (this.rank < this.rankMin) this.rank = this.rankMin; } + aim(x, y) { const p = this.player; return Math.atan2(p.y - y, p.x - x); } + // Every enemy bullet is created with the same fields in the same order (unused ones undefined, which JSON and the state hash + // omit), so the per-tick loops stay monomorphic. + shoot(x, y, a, s, k, c, ex) { + const q = {x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, k, c, t: 0, g: 0, a: undefined, s: undefined, st: undefined, gt: undefined, gm: undefined, + ga: undefined, gs: undefined, w: undefined, wt: undefined, ta: undefined, tw: undefined, ax: undefined, ay: undefined, am: undefined, bn: undefined, bm: undefined}; + if (ex) { for (const key in ex) { if (!(key in q)) throw Error('unknown bullet field ' + key); q[key] = ex[key]; } if (q.st) q.a = a; } + this.bullets.push(q); return q; + } + knife(x, y, a, s, c, ex) { return this.shoot(x, y, a, s, K.KNIFE, c, ex ? Object.assign({s, a}, ex) : {s, a}); } + ring(x, y, n, a0, s, k, c, ex) { for (let i = 0; i < n; i++) this.shoot(x, y, a0 + TAU * i / n, s, k, c, ex); } + fan(x, y, n, a, gap, s, k, c, ex) { for (let i = 0; i < n; i++) this.shoot(x, y, a + (i - (n - 1) / 2) * gap, s, k, c, ex); } + laser(x, y, a, l, w, warn, on) { this.lasers.push({x, y, a, l, w, t: 0, wn: warn, on, gz: 0}); } + // ExInsStage4Func12 (C42): for every live laser (at most 8), fire(x, y, angle) at 64 px from the boss along the laser. + fromLasers(b, fire) { + let n = 0; + for (const l of this.lasers) { + if (n >= 8) break; + if (l.t > l.wn + l.on) continue; + n++; fire(b.x + Math.cos(l.a) * 64, b.y + Math.sin(l.a) * 64, l.a); + } + return n; + } + moveBoss(x, y, frames, linear) { const b = this.boss; b.fx = b.x; b.fy = b.y; b.tx = N.clamp(x, 40, W - 40); b.ty = N.clamp(y, 48, 200); b.mt = 0; b.md = frames; b.lin = linear ? 1 : 0; } + timeStop(frames) { this.stop = this.stopLen = frames; this.ev('time_stop'); } // ExInsStage56Func4 arg 1 / 0 (S14) + addScore(v) { + const p = this.player; p.score += v; + if (p.extendsEarned < EXTENDS.length && p.score >= EXTENDS[p.extendsEarned]) { + p.extendsEarned++; if (p.lives < 9) p.lives++; this.addSubrank(200); this.ev('extend'); this.msg = {k: 'extend', t: 120, v: 0}; + } + } + pop(x, y, v, gold) { this.pops.push({x, y, v, t: 0, g: gold ? 1 : 0}); if (this.pops.length > 24) this.pops.shift(); } + spawnItem(type, x, y, magnet) { this.items.push({x, y, vy: -2.2, k: type, m: magnet ? 1 : 0}); } + starItems(awardScore) { // TurnAllBulletsIntoPoints / DespawnBullets (S15) + let s = 2000, total = 0; + for (const q of this.bullets) { this.spawnItem(ITEM.STAR, q.x, q.y, true); if (awardScore) { total += s; s = Math.min(12800, s + 10); } } + this.bullets = []; this.lasers = []; + if (total) this.addScore(total); + return total; + } + // ExInsStage56Func4 with arg >= 2 (S14): medium-or-larger bullets that are not green yet turn green with probability 1/4 and take + // a new heading at their own speed, oldest first, at most 14 (Easy/Normal) or 52 (Hard/Lunatic). Further than 128 px from the + // player the heading is random in [pi/4, pi] on Easy/Normal and anywhere on Hard/Lunatic; closer, effectively random. + redirect(extra) { + let left = this.D <= 1 ? 14 : 52, n = 0; + const p = this.player; + for (const q of this.bullets) { + if (left <= 0) break; + if (BSIZE[q.k] < 5 || q.c === C.GREEN) continue; + if (Math.floor(this.rnd() * 4) !== 0) continue; + const far = Math.hypot(q.x - p.x, q.y - p.y) > 128; + const a = far ? (this.D <= 1 ? this.rnd() * (3 * PI / 4) + PI / 4 : this.rnd() * TAU) : Math.atan2(q.y - p.y, q.x - p.x) + PI / 2 + this.rnd() * TAU; + const s = q.s || Math.hypot(q.vx, q.vy) || 2; + q.c = C.GREEN; q.vx = Math.cos(a) * s; q.vy = Math.sin(a) * s; q.a = a; + q.st = undefined; q.gt = undefined; q.gm = undefined; q.ga = undefined; q.gs = undefined; q.ta = undefined; q.tw = undefined; q.am = undefined; q.ax = undefined; q.ay = undefined; + if (extra) Object.assign(q, extra); + left--; n++; + } + this.ev('redirect'); + return n; + } + // ---------- player ---------- + hitPlayer() { // Player::Die + const p = this.player; + p.state = 'dead'; p.deadT = 0; p.window = 6; p.fireT = -1; p.hits++; + this.capture = false; this.hitFx = 32; this.ev('hit'); + for (const l of this.lasers) if (l.t < l.wn + l.on) l.t = l.wn + l.on; + } + finalizeMiss() { + const p = this.player; p.misses++; p.pc = 0; this.subSubrank(1600); this.ev('miss'); + const drops = p.lives > 1 ? [ITEM.BIG, ITEM.POWER, ITEM.POWER, ITEM.POWER, ITEM.POWER, ITEM.POWER] : [ITEM.FULL, ITEM.FULL, ITEM.FULL, ITEM.FULL, ITEM.FULL]; + // items glide to random points of the upper field; within +-144 px of the player in the wide arena (C18B) + for (const k of drops) this.items.push({x: p.x, y: p.y, vy: 0, k, m: 0, np: 1, gx: p.x, gy: p.y, tx: N.clamp(p.x + (this.rnd() - 0.5) * 288, 48, W - 48), ty: this.rnd() * 192 - 64, gt: 0}); + p.power = p.lives > 1 ? Math.max(0, p.power - 16) : 0; + } + startBomb() { + const p = this.player, type = this.shotType; + p.bombs--; p.bombsUsed++; this.subSubrank(200); this.capture = false; + if (this.spell) this.usedBomb = true; + p.inv = type === 'A' ? 360 : 200; + this.bomb = {k: type, t: 0, dur: type === 'A' ? 300 : 140, x: p.x, y: p.y, orbs: []}; + for (const it of this.items) it.m = 1; // MagnetAllItems + this.shake = type === 'B' ? 60 : 0; this.flash = 12; this.ev('bomb'); + } + updatePlayer(keys, pressed) { + const p = this.player, bombKey = pressed.has('K') || pressed.has('RMB'); + if (p.state === 'dead') { + if (bombKey && p.window > 0 && p.bombs > 0 && !this.bomb) { p.state = 'alive'; p.window = 0; this.startBomb(); this.ev('deathbomb'); } + else { + p.deadT++; + if (p.window > 0 && --p.window === 0) this.finalizeMiss(); + if (p.deadT >= 30) { + p.lives--; + if (p.lives <= 0) { p.lives = 0; this.outcome = 'loss'; this.ev('game_over'); return; } + p.state = 'spawning'; p.spawnT = 30; p.x = SPAWN.x; p.y = SPAWN.y; p.bombs = 3; p.grace = 90; p.fireT = -1; + } + return; + } + } else if (bombKey && p.state === 'alive' && p.bombs > 0 && !this.bomb) this.startBomb(); + if (p.state === 'spawning' && --p.spawnT <= 0) { p.state = 'alive'; p.inv = 240; } + else if (p.state === 'alive' && p.inv > 0) p.inv--; + // movement (Player.cpp: up before down, right overrides left, diagonal speed/sqrt2 per axis) + const focus = keys.has('Shift'); + let dx = 0, dy = 0; + if (keys.has('W')) dy = -1; else if (keys.has('S')) dy = 1; + if (keys.has('A')) dx = -1; + if (keys.has('D')) dx = 1; + const speed = focus ? 2 : 4, s = dx && dy ? speed / Math.SQRT2 : speed; + p.x = N.clamp(p.x + dx * s, AREA.x0, AREA.x1); p.y = N.clamp(p.y + dy * s, AREA.y0, AREA.y1); + p.mx = dx; p.foc = focus ? 1 : 0; p.focus = focus ? Math.min(8, p.focus + 1) : Math.max(0, p.focus - 1); + // shot volley timer (30-frame cycle that finishes after release) + const shooting = keys.has('J') || keys.has('LMB'); + if (p.fireT < 0 && shooting) p.fireT = 0; + if (p.fireT >= 0) { this.fire(p.fireT); if (++p.fireT >= 30) p.fireT = -1; } + } + orbs() { + const p = this.player, f = p.focus / 8, ox = 24 - 16 * f, oy = -32 * f; + return [{x: p.x - ox, y: p.y + oy}, {x: p.x + ox, y: p.y + oy}]; + } + fire(timer) { + const p = this.player, table = SHOT[this.shotType]; + let tier = 0; while (tier < table.length - 1 && p.power >= table[tier][0]) tier++; + const rows = table[tier][1], orbs = this.orbs(); + for (const r of rows) { + if (timer % r[0] !== r[1]) continue; + const o = r[9] === 0 ? p : orbs[r[9] - 1], a = r[6] * PI / 180; + this.shots.push({x: o.x + r[2], y: o.y + r[3], vx: Math.cos(a) * r[7], vy: Math.sin(a) * r[7], s: r[7], k: r[10], w: r[4], h: r[5], d: r[8], t: 0}); + } + } + graze(x, y) { // CheckGraze (S08): score always, counters skipped during bombs + const p = this.player; this.addScore(500); this.addSubrank(6); this.ev('graze'); + if (!this.bomb) { if (p.graze < 999999) p.graze++; if (p.grazeStage < 9999) p.grazeStage++; } + } + // ---------- boss ---------- + // sub.bat (C47): not interactable at all; sub.inv (C47): the attack segments of Remilia's non-spell 4 take no damage. Both stay undefined outside those attacks. + targetable() { return this.intro === 0 && !this.defeat && this.boss.y > -16 && !(this.sub.bat > 0); } + damageable() { return this.phase >= 0 && !this.trans && !this.intro && !this.defeat && !this.sub.inv && !(this.sub.bat > 0); } + // positionOfLastEnemyHit (C34): starting from "no target", the boss (when targetable) and then every interactable fairy in spawn + // order replace the target if it is strictly higher on screen, so the lowest enemy wins. Returns the enemy object itself (or null): + // with no fairy on the field this is this.boss, exactly the @5 target. + homingTarget() { + let t = this.targetable() ? this.boss : null; + for (const f of this.fams) if (f.hp !== undefined && fairyIn(f) && (!t || t.y < f.y)) t = f; + return t; + } + startPhase(i) { + while (i < this.phases.length) { + const id = this.phases[i]; + if (PHASES[id].easyTimeoutOnly && this.D === 0 && !this.timedOut.includes(this.phases[i - 1])) { this.cleared += this.lifeOf[i]; i++; continue; } + break; + } + if (i >= this.phases.length) return this.bossDefeated(); + const id = this.phases[i], ph = PHASES[id]; + this.phase = i; this.phaseId = id; this.phaseT = 0; this.clock = 0; this.timer = this.timeOf[i]; this.phaseHp = this.phaseMax = this.lifeOf[i]; + this.spell = ph.spell; this.capture = ph.spell; this.usedBomb = false; this.sub = {}; this.fams = []; this.stop = 0; + if (ph.spell) { this.starItems(false); this.declared++; this.cutin = 110; this.ev('spell_start'); } + else this.ev('phase_start'); + } + endPhase(timeout) { + const ph = PHASES[this.phaseId], b = this.boss; + this.stop = 0; this.fams = []; + if (timeout) this.timedOut.push(this.phaseId); + if (timeout) { this.capture = false; this.bullets = []; this.lasers = []; } // RemoveAllBullets(0): no items, no score (S16) + if (ph.spell) { + this.starItems(true); + if (this.capture && !timeout) { + const base = ph.base || BOSS[this.kind].base, secs = Math.floor((this.timer - this.clock) / 60), bonus = base + Math.floor(base * secs / 10); + this.addScore(bonus); this.captures++; this.msg = {k: 'capture', t: 150, v: bonus}; this.ev('spell_capture'); + } else { this.msg = {k: 'failed', t: 110, v: 0}; this.ev(timeout ? 'spell_timeout' : 'spell_failed'); } + } else { if (!timeout) this.starItems(false); else this.ev('phase_timeout'); } + this.cleared += this.phaseMax; this.spell = false; this.capture = false; this.ev('phase_end'); + const drops = ph.spell ? [1, 1, 1, 1, 1, 1, 0, 0, 0, 0] : [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]; // approximated drop table + for (const k of drops) this.spawnItem(k, b.x + (this.rnd() - 0.5) * 96, b.y + (this.rnd() - 0.6) * 48, false); + if (this.phase + 1 >= this.phases.length) return this.bossDefeated(); + this.trans = TRANSITION; this.moveBoss(CX, 112, 60); + } + bossDefeated() { + this.phase = this.phases.length; this.phaseId = null; this.defeat = DEFEAT; this.bullets = []; this.lasers = []; this.fams = []; this.stop = 0; + this.cleared = this.bossMax; this.flash = 30; this.shake = 30; + for (const it of this.items) it.m = 1; + this.ev('boss_defeated'); + } + damageBoss(raw, byBomb) { // EnemyManager damage block (S16) + if (!raw || !this.damageable()) return; + let d = Math.min(70, raw); + this.addScore(Math.floor(d / 5) * 10); + if (this.spell) { + if (!byBomb) d = d > 7 ? Math.floor(d / 7) : 1; + else if (this.usedBomb) d = d > 3 ? Math.floor(d / 3) : 1; + else d = 0; + } + this.phaseHp = Math.max(0, this.phaseHp - d); + } + updateBoss(frozen) { + const b = this.boss; + if (b.mt < b.md) { b.mt++; const u = b.mt / b.md, e = b.lin ? u : u * u * (3 - 2 * u); b.x = b.fx + (b.tx - b.fx) * e; b.y = b.fy + (b.ty - b.fy) * e; } + if (this.intro > 0) { if (--this.intro === 0) this.startPhase(0); return; } + if (this.defeat > 0) { if (--this.defeat === 0) { this.outcome = 'win'; this.ev('win'); } return; } + if (this.trans > 0) { if (--this.trans === 0) this.startPhase(this.phase + 1); return; } + if (this.phaseId) { + // ExInsHandleBatTransformation's shape (C47): uninteractable with a bomb on the field and for 60 frames after it + if (PHASES[this.phaseId].bat) { if (this.bomb) this.sub.bat = 60; else if (this.sub.bat > 0) this.sub.bat--; } + const start = this.spell ? 40 : 16, lt = this.phaseT - start; + if (lt >= 0) PATTERN[this.phaseId].call(this, lt, this.sub, b, this.D); + this.phaseT++; + if (!frozen) this.clock++; // the spell clock (phaseTimer) stands still while time is stopped (S16) + } + } + // ---------- bomb ---------- + updateBomb() { + const B = this.bomb, p = this.player; if (!B) return 0; + const boxes = []; + let dmg = 0; + const tgt = this.homingTarget() || p, fairies = this.fams.length ? this.fams.filter(f => f.hp > 0 && fairyIn(f)) : EMPTY_A; + // bomb regions damage every fairy they overlap too (C33); the damage is applied with the fairy's shot damage in updateFairies + const hitF = (x, y, hw, hh, v) => { let n = 0; for (const f of fairies) if (Math.abs(f.x - x) < hw + FAIRY_HALF && Math.abs(f.y - y) < hh + FAIRY_HALF) { f.bd += v; n += v; } return n; }; + if (B.k === 'A') { // BombReimuACalc (S12) + if (B.t === 0) boxes.push([p.x, p.y, 128]); + if (B.t >= 60 && B.t < 180 && B.t % 16 === 0) { + const i = Math.floor((B.t - 60) / 16); + if (i !== 0) { const a = this.rnd() * TAU - PI; B.orbs.push({x: p.x, y: p.y, vx: Math.cos(a) * 4, vy: Math.sin(a) * 4, s: 4, st: 0, tot: 0, c: i - 1}); } + } + for (const o of B.orbs) { + if (o.st === 0) { + let vx = tgt.x - o.x, vy = tgt.y - o.y, len = Math.hypot(vx, vy) / (o.s / 8); + if (len < 1) len = 1; + vx = vx / len + o.vx; vy = vy / len + o.vy; + const l = Math.hypot(vx, vy) || 1; o.s = N.clamp(l, 1, 10); o.vx = vx / l * o.s; o.vy = vy / l * o.s; + o.x += o.vx; o.y += o.vy; + boxes.push([o.x, o.y, 24]); + if (this.damageable() && Math.abs(o.x - this.boss.x) < 24 + BOSS_HALF && Math.abs(o.y - this.boss.y) < 24 + BOSS_HALF) { dmg += 8; o.tot += 8; } + if (fairies.length) o.tot += hitF(o.x, o.y, 24, 24, 8); + if (o.tot >= 100 || B.t >= B.dur - 30) { + o.st = 1; boxes.push([o.x, o.y, 128]); this.shake = Math.max(this.shake, 16); this.ev('bomb_burst'); + if (this.damageable() && Math.abs(o.x - this.boss.x) < 128 + BOSS_HALF && Math.abs(o.y - this.boss.y) < 128 + BOSS_HALF) dmg += 200; + if (fairies.length) hitF(o.x, o.y, 128, 128, 200); + } + } else { o.st++; o.x += o.vx; o.y += o.vy; if (o.st < 30) boxes.push([o.x, o.y, 64]); } + } + B.orbs = B.orbs.filter(o => o.st < 30); + } else { // BombReimuBCalc: two vertical and two horizontal 62 px bars through the bombing point + boxes.push([B.x, H / 2, 31, H / 2], [W / 2, B.y, W / 2, 31]); + if (B.t % 2 === 1 && this.damageable()) { + const b = this.boss; + if (Math.abs(b.x - B.x) < 31 + BOSS_HALF) dmg += 16; // two stacked vertical bars x 8 + if (Math.abs(b.y - B.y) < 31 + BOSS_HALF) dmg += 16; + } + if (B.t % 2 === 1 && fairies.length) { hitF(B.x, H / 2, 31, H / 2, 16); hitF(W / 2, B.y, W / 2, 31, 16); } + if (B.t === 60) this.shake = 80; + } + // a fairy whose contact box overlaps a bomb region this frame grazes instead of colliding (CheckCollision GRAZE, C33) + for (const f of fairies) for (const bx of boxes) { const hh = bx.length > 3 ? bx[3] : bx[2]; if (Math.abs(f.x - bx[0]) < bx[2] + FAIRY_HALF / 1.5 && Math.abs(f.y - bx[1]) < hh + FAIRY_HALF / 1.5) { f.gz = 1; break; } } + if (boxes.length && this.bullets.length) { + const keep = []; + for (const q of this.bullets) { + let hit = false; + for (const bx of boxes) { const hw = bx[2], hh = bx.length > 3 ? bx[3] : bx[2]; if (Math.abs(q.x - bx[0]) < hw && Math.abs(q.y - bx[1]) < hh) { hit = true; break; } } + if (hit) this.spawnItem(ITEM.STAR, q.x, q.y, true); else keep.push(q); + } + this.bullets = keep; + if (this.lasers.length) this.lasers = this.lasers.filter(l => !boxes.some(bx => Math.hypot(l.x - bx[0], l.y - bx[1]) < bx[2])); + } + if (++B.t >= B.dur) { this.bomb = null; this.ev('bomb_end'); } + return dmg; + } + // ---------- per-tick ---------- + // Time stop (S08 S15 S16): while stopped the player, its shots and bomb, enemy bullets, lasers, items and the spell clock do + // not update; the boss, its script and familiars keep running, and frozen shots that touch the boss still damage it. + update(keys, pressed) { + if (this.outcome) return; + const frozen = this.stop > 0; + if (frozen) this.stop--; + const p = this.player; + if (!frozen) { + // Q/E: shot type at any time except during a bomb + if ((pressed.has('Q') || pressed.has('E')) && !this.bomb && p.state !== 'dead') { this.shotType = this.shotType === 'A' ? 'B' : 'A'; this.swapT = 70; this.ev('shot_type'); } + this.updatePlayer(keys, pressed); + if (this.outcome) return; + } + this.updateBoss(frozen); + // player shots vs boss (box overlap, one hit per shot, damage /3 during a bomb) + let shotDmg = 0; + const b = this.boss, tgt = this.targetable(), live = [], ht = this.homingTarget(), fams = this.fams; + for (const s of this.shots) { + if (!frozen) { + if (s.k === 1) { // homing amulet (Player.cpp), toward positionOfLastEnemyHit (C34) + if (ht && s.t < 40) { + let vx = ht.x - s.x, vy = ht.y - s.y, len = Math.hypot(vx, vy) / (s.s / 4); + if (len < 1) len = 1; + vx = vx / len + s.vx; vy = vy / len + s.vy; + const l = Math.hypot(vx, vy) || 1; s.s = N.clamp(l, 1, 10); s.vx = vx / l * s.s; s.vy = vy / l * s.s; + } else if (s.s < 10) { const l = s.s || 1; s.s = Math.min(10, s.s + 1 / 3); s.vx = s.vx / l * s.s; s.vy = s.vy / l * s.s; } + } + s.x += s.vx; s.y += s.vy; s.t++; + } + if (tgt && Math.abs(s.x - b.x) < s.w / 2 + BOSS_HALF && Math.abs(s.y - b.y) < s.h / 2 + BOSS_HALF) { + if (this.damageable()) { const dd = this.bomb ? Math.max(1, Math.floor(s.d / 3)) : s.d; shotDmg += dd; } + continue; + } + // a shot that hits is consumed by the first enemy processed: the boss, then the fairies in spawn order (C33) + let used = false; + for (const f of fams) { + if (f.hp === undefined || f.hp <= 0 || !fairyIn(f) || Math.abs(s.x - f.x) >= s.w / 2 + FAIRY_HALF || Math.abs(s.y - f.y) >= s.h / 2 + FAIRY_HALF) continue; + f.sd += this.bomb ? Math.max(1, Math.floor(s.d / 3)) : s.d; used = true; break; + } + if (used) continue; + if (s.y > -24 && s.y < H + 24 && s.x > -24 && s.x < W + 24) live.push(s); + } + this.shots = live; + const bombDmg = frozen ? 0 : this.updateBomb(); + this.damageBoss(shotDmg + bombDmg, bombDmg > 0); + this.bodyContact(); + if (fams.length) this.updateFairies(); + if (!frozen) { this.updateBullets(); this.updateLasers(); this.updateItems(); } + // phase end: life depleted or timer expired + if (this.phaseId && !this.trans && !this.defeat) { + if (this.phaseHp <= 0) this.endPhase(false); + else if (this.clock >= this.timer) this.endPhase(true); + } + if (this.cutin > 0) this.cutin--; if (this.shake > 0) this.shake--; if (this.flash > 0) this.flash--; if (this.hitFx > 0) this.hitFx--; if (this.swapT > 0) this.swapT--; + if (this.msg && --this.msg.t <= 0) this.msg = null; + for (const q of this.pops) q.t++; + if (this.pops.length && this.pops[0].t > 50) this.pops = this.pops.filter(q => q.t <= 50); + } + // Body contact (C17, S16 EnemyManager_OnUpdate + S08 Player::CheckCollision): every collidable, interactable enemy tests the + // player against its hitbox / 1.5. CheckCollision kills only a player in the ALIVE state (invulnerability after a respawn or + // during a bomb is its own state there, so it is spared), and the `!isBoss` term only exempts a boss from the enemy's own + // -10 life, so a boss kills on contact too. Checked after the damage step, as there, and also during a time stop (the enemy + // update is not frozen). Boss box 32x32 (C23 approximation) -> contact half-size 10.67 px; no graze for bodies. + bodyContact() { + const p = this.player, b = this.boss; + if (p.state !== 'alive' || p.inv > 0 || !this.targetable()) return; + const r = BOSS_HALF / 1.5 + PLAYER_HALF; + if (Math.abs(p.x - b.x) < r && Math.abs(p.y - b.y) < r) { this.hitPlayer(); this.ev('contact'); } + } + // Fairies after the boss (C33, EnemyManager_OnUpdate block order): body contact, then this frame's shot and bomb damage, then + // death. Contact box = hitbox / 1.5; an overlap costs the fairy 10 life whatever the player's state (it only kills an ALIVE, + // non-invulnerable player) unless the fairy touches a bomb region this frame (GRAZE). Damage: cap 70, score (d/5)*10, the + // spell-card divisors as for the boss. Death: 100 points and one point item (itemDrop unread, engineering choice). + updateFairies() { + const p = this.player, r = FAIRY_HALF / 1.5 + PLAYER_HALF, keep = []; + for (const f of this.fams) { + if (f.hp === undefined) { keep.push(f); continue; } + if (fairyIn(f)) { + if (!f.gz && Math.abs(p.x - f.x) < r && Math.abs(p.y - f.y) < r) { + if (p.state === 'alive' && p.inv === 0) { this.hitPlayer(); this.ev('contact'); } + f.hp -= 10; + } + const raw = f.sd + f.bd; + if (raw) { + let d = Math.min(70, raw); + this.addScore(Math.floor(d / 5) * 10); + if (this.spell) { + if (!f.bd) d = d > 7 ? Math.floor(d / 7) : 1; + else if (this.usedBomb) d = d > 3 ? Math.floor(d / 3) : 1; + else d = 0; + } + f.hp -= d; + } + } + f.sd = 0; f.bd = 0; f.gz = 0; + if (f.hp <= 0) { this.addScore(100); this.spawnItem(ITEM.POINT, f.x, f.y, false); this.ev('fairy_down'); continue; } + if (f.t > 60 && (f.x < -32 || f.x > W + 32 || f.y < -48 || f.y > H + 32)) continue; // flew off the field + keep.push(f); + } + this.fams = keep; + } + // EX_BOUNCE_TLR (bm 1) / TBLR (bm 2) (S15): checked before the move; side walls reflect the angle (-a - pi), the top (and for + // TBLR the floor) negate it; the speed is kept, every bounce counts down and the flag clears at the limit. + bounce(q) { + const ox = (q.x < 0 && q.vx < 0) || (q.x > W && q.vx > 0), ot = q.y < 0 && q.vy < 0, ob = q.bm === 2 && q.y > H && q.vy > 0; + if (!ox && !ot && !ob) return; + let a = Math.atan2(q.vy, q.vx); + if (ox) a = -a - PI; + if (ot || ob) a = -a; + const s = Math.hypot(q.vx, q.vy); + q.vx = Math.cos(a) * s; q.vy = Math.sin(a) * s; q.a = a; + if (--q.bn <= 0) { q.bn = undefined; q.bm = undefined; } + } + updateBullets() { + const p = this.player; + if (p.grace > 0) { p.grace--; this.bullets = []; this.lasers = []; return; } + const canGraze = p.state === 'alive', hitOk = canGraze && p.inv === 0, keep = []; + for (const q of this.bullets) { + if (q.ta !== undefined) { // turn toward a target heading + const a = Math.atan2(q.vy, q.vx), d = angDiff(q.ta, a), s = Math.hypot(q.vx, q.vy); + const na = Math.abs(d) <= q.tw ? q.ta : a + Math.sign(d) * q.tw; + q.vx = Math.cos(na) * s; q.vy = Math.sin(na) * s; + if (na === q.ta) { q.ta = undefined; q.tw = undefined; } + } + if (q.w) { + if (q.wt > 0) { const c = Math.cos(q.w), s = Math.sin(q.w), vx = q.vx * c - q.vy * s; q.vy = q.vx * s + q.vy * c; q.vx = vx; q.wt--; } + else { q.w = undefined; q.wt = undefined; } + } + if (q.st) { // decelerate linearly to rest at st, relaunch at gt + if (q.t < q.st) { const f = (q.st - q.t - 1) / (q.st - q.t); q.vx *= f; q.vy *= f; } + else if (q.t >= q.gt) { + const a = q.gm === 1 ? this.aim(q.x, q.y) + (q.ga || 0) : q.gm === 2 ? q.a + (q.ga || 0) : q.ga; + q.vx = Math.cos(a) * q.gs; q.vy = Math.sin(a) * q.gs; q.a = a; + q.st = undefined; q.gt = undefined; q.gm = undefined; q.ga = undefined; q.gs = undefined; + } + } + if (q.am) { q.vx += q.ax; q.vy += q.ay; if (--q.am <= 0) { q.ax = undefined; q.ay = undefined; q.am = undefined; } } + if (q.bn) this.bounce(q); + q.x += q.vx; q.y += q.vy; q.t++; + const hs = BSIZE[q.k] / 2; + if (q.x < -hs - 8 || q.x > W + hs + 8 || q.y < -hs - 8 || q.y > H + hs + 8) continue; + if (canGraze) { + const dx = Math.abs(q.x - p.x), dy = Math.abs(q.y - p.y), hb = hs + PLAYER_HALF; + if (!q.g && dx < hb + GRAZE_PAD && dy < hb + GRAZE_PAD) { q.g = 1; this.graze(q.x, q.y); } + if (hitOk && p.state === 'alive' && dx < hb && dy < hb) { this.hitPlayer(); continue; } + } + keep.push(q); + } + this.bullets = keep; + } + updateLasers() { + if (!this.lasers.length) return; + const p = this.player, keep = []; + for (const l of this.lasers) { + l.t++; + if (l.t >= l.wn + l.on + 16) continue; + if (l.va !== undefined && l.t > l.wn && l.t <= l.wn + l.on) l.a += l.va; // optional sweep (@7, Patchouli); lasers without va never turn + if (l.t > l.wn && l.t <= l.wn + l.on && p.state === 'alive') { + const c = Math.cos(l.a), s = Math.sin(l.a), rx = p.x - l.x, ry = p.y - l.y, along = rx * c + ry * s, perp = Math.abs(-rx * s + ry * c); + if (along > -PLAYER_HALF && along < l.l + PLAYER_HALF) { + if (perp < l.w / 2 + 48 + PLAYER_HALF && l.t % 12 === 0) this.graze(p.x, p.y); + if (p.inv === 0 && perp < l.w / 2 + PLAYER_HALF) this.hitPlayer(); + } + } + keep.push(l); + } + this.lasers = keep; + } + collect(it) { + const p = this.player; + switch (it.k) { + case ITEM.POWER: case ITEM.BIG: { + const add = it.k === ITEM.BIG ? 8 : 1; + if (p.power < 128) { + const before = p.power; p.power = Math.min(128, p.power + add); this.addScore(10); + if (it.k === ITEM.POWER) p.pc = 0; + if (p.power >= 128) { this.starItems(false); this.msg = {k: 'fullpower', t: 120, v: 0}; this.ev('full_power'); } + else if ([8, 16, 32, 48, 64, 80, 96].some(v => before < v && p.power >= v)) this.ev('power_up'); + } else { p.pc = Math.min(POWER_SCORE.length - 1, p.pc + add); const v = POWER_SCORE[p.pc]; this.addScore(v); this.pop(it.x, it.y, v, v >= 12800); } + if (it.k === ITEM.POWER) this.addSubrank(1); + break; + } + case ITEM.FULL: this.addScore(1000); if (p.power < 128) { p.power = 128; this.starItems(false); this.msg = {k: 'fullpower', t: 120, v: 0}; this.ev('full_power'); } break; + case ITEM.POINT: { + const pv = POINT_VALUE[this.D], v = it.y < 128 ? pv[0] : Math.max(0, Math.floor(pv[1] - (Math.floor(it.y) - 128) * pv[2])); + this.addScore(v); p.points++; this.addSubrank(it.y < 128 ? 30 : 3); this.pop(it.x, it.y, v, it.y < 128); break; + } + case ITEM.BOMB: if (p.bombs < 8) p.bombs++; this.addSubrank(5); break; + case ITEM.LIFE: if (p.lives < 9) p.lives++; this.addSubrank(200); break; + case ITEM.STAR: this.addScore(this.bomb ? 100 : 500 + 10 * Math.floor(p.grazeStage / 3)); break; + } + this.ev('item'); + } + updateItems() { + if (!this.items.length) return; + const p = this.player, poc = p.power >= 128 && p.y < 128 && p.state === 'alive', canGet = p.state !== 'dead', keep = []; + for (const it of this.items) { + if (it.gt !== undefined) { // death drop glides to its target over 60 frames + it.gt++; const u = it.gt / 60; it.x = it.gx + (it.tx - it.gx) * u; it.y = it.gy + (it.ty - it.gy) * u; + if (it.gt >= 60) { it.gt = undefined; it.gx = undefined; it.gy = undefined; it.tx = undefined; it.ty = undefined; it.vy = 0; } + } else if (it.m || (poc && !it.np)) { + it.m = 1; const a = Math.atan2(p.y - it.y, p.x - it.x); it.x += Math.cos(a) * 8; it.y += Math.sin(a) * 8; + } else { it.vy = Math.min(3, it.vy + 0.03); it.y += it.vy; } + if (canGet && Math.abs(it.x - p.x) < 20 && Math.abs(it.y - p.y) < 20) { this.collect(it); continue; } + if (it.y >= H + 16) { this.subSubrank(3); continue; } + keep.push(it); + } + this.items = keep; + } + // Reported boss life (C44, @7): endPhase has already added the finished attack to `cleared`, and during the following + // transition (trans > 0) phaseId still names that attack, so its progress must not be counted a second time (@1-@6 did, + // which dipped boss_hp by one attack for 80 frames). Reporting only; the simulation never reads this. + health() { + const done = this.cleared + (this.phaseId && !this.trans ? this.phaseMax - this.phaseHp : 0); + return [this.player.lives, Math.max(this.lifeMax, this.player.lives), Math.max(0, this.bossMax - done), this.bossMax]; + } + remainingAttacks() { return this.phaseId ? this.phases.length - this.phase - 1 : Math.max(0, this.phases.length - this.phase - 1); } + // ExInsStage6Func7 geometry (C48): two webs of 8 arms 45 deg apart (the second 22.5 deg on and turning the other way), starting 32 px + // out; 3 segments each, every segment starting 112 / 112 / 480 px on from the last and turning 45 deg. + webEach(b, r, fn) { + for (let net = 0; net < 2; net++) for (let arm = 0; arm < 8; arm++) { + let a = (net ? -7 * PI / 8 : -PI) + r + arm * PI / 4, x = b.x + Math.cos(a) * 32, y = b.y + Math.sin(a) * 32; + for (let n = 0; n < 3; n++) { + const len = n < 2 ? 112 : 480; + fn(x, y, a, n, len, net); + x += Math.cos(a) * len; y += Math.sin(a) * len; a += net ? -PI / 4 : PI / 4; + } + } + } + // Func7's beams on the shared laser model (C48): warning 60+16n, then 90-16n on, 16 fading, so all three segments end together; red, width 28, as long as the step up to Normal; cyan, width 20, 440 long above. + webLasers(b, r) { + const w = this.D >= 2 ? 20 : 28, col = this.D >= 2 ? C.CYAN : C.RED; + this.webEach(b, r, (x, y, a, n, len) => { this.laser(x, y, a, this.D >= 2 ? 440 : len, w, 60 + 16 * n, 90 - 16 * n); this.lasers[this.lasers.length - 1].col = col; }); + } + // ExInsStage6Func8 (C48): a still dark-red ball at every live bullet of kind k and colour c. The original's 640-bullet ceiling applies (S44). + dropStill(k, c) { + const n = this.bullets.length; + for (let i = 0; i < n && this.bullets.length < 640; i++) { const q = this.bullets[i]; if (q.k === k && q.c === c && q.x >= 0 && q.x <= W && q.y >= 0 && q.y <= H) this.shoot(q.x, q.y, 0, 0, K.BALL, C.RED); } + } + // ExInsStage6Func9 / Func11 (C48): every still bullet below the large size accelerates at 0.01 for 120 frames, in a swirl (distance to her x pi/256 + one shared angle) or each its own random way. + releaseStill(b, swirl) { + const r = this.rnd() * TAU; + for (const q of this.bullets) { + if (BSIZE[q.k] >= 16 || q.vx !== 0 || q.vy !== 0 || q.am) continue; + const a = swirl ? Math.hypot(q.x - b.x, q.y - b.y) * PI / 256 + r : this.rnd() * TAU; + q.ax = Math.cos(a) * 0.01; q.ay = Math.sin(a) * 0.01; q.am = 120; + } + this.ev('still_release'); + } + hasBullet(k, c) { for (const q of this.bullets) if (q.k === k && q.c === c) return true; return false; } + // ExInsStage5Func5 (S14): one wave of nine daggers 10 deg apart on a 256 px arc laid across the boss->player line; the reference + // point starts halfway to the player and slides back 1/18 per wave, the arc bows to alternate sides; each dagger is an aimed fan + // (1 on Easy/Normal, 3 at pi/6 above) at speed 2, odd waves on Easy/Normal spread -45..+35 deg instead of aiming. + daggerArc(wave, b) { + const p = this.player, dx = p.x - b.x, dy = p.y - b.y, len = Math.hypot(dx, dy) || 1, ux = dx / len, uy = dy / len; + const f = 0.5 - wave * 0.5 / 9, rx = b.x + dx * f, ry = b.y + dy * f, side = wave % 2 ? -1 : 1; + const cx = rx + side * 256 * ux, cy = ry + side * 256 * uy; + let ang = Math.atan2(ry - cy, rx - cx) + PI / 4; + const per = this.D <= 1 ? 1 : 3, spread = wave % 2 === 1 && this.D <= 1; + for (let i = 0; i < 9; i++) { + ang -= PI / 18; + const x = cx + Math.cos(ang) * 256, y = cy + Math.sin(ang) * 256; + if (x < -8 || x > W + 8 || y < -8 || y > H + 8) continue; + const a = this.aim(x, y) + (spread ? (-45 + 10 * i) * PI / 180 : 0); + for (let j = 0; j < per; j++) this.knife(x, y, a + (j - (per - 1) / 2) * PI / 6, 2, C.BLUE); + } + } + } + + // ---------- attack patterns: (t from attack start, sub-state, boss, difficulty 0..3) ---------- + // Geometry is reconstructed (C14/C26). In the 854 px arena, boss relocation spans are 1.75x the 384 px originals (C18B). + const PATTERN = { + r_non1(t, s, b, D) { // aimed sub-patterns, always red first, never repeated back-to-back (S17) + if (s.k === undefined) { s.k = 0; s.t0 = 0; } + const lt = t - s.t0, dur = [96, 72, 112, 84][s.k]; + if (lt < dur) { + if (s.k === 0 && lt % 32 === 0) { + const a = this.aim(b.x, b.y), n = 3 + 2 * D; + for (let i = 0; i < n; i++) for (let j = 0; j < 4 + D; j++) this.shoot(b.x, b.y, a + (i - (n - 1) / 2) * 0.3, this.sp(1.7 + 0.45 * j), K.RICE, C.RED); + } else if (s.k === 1 && lt % 18 === 0) { + const n = 7 + 2 * D, gap = 1.25 / (n - 1), w = lt / 18; + this.fan(b.x, b.y, n, this.aim(b.x, b.y) + (w % 2 ? gap / 2 : -gap / 2), gap, this.sp(2.3 + 0.15 * D), K.BALL, C.GREEN); + } else if (s.k === 2 && lt % 38 === 0) { + const a = this.aim(b.x, b.y); + this.fan(b.x, b.y, 5, a, 0.17, this.sp(3.0), K.BALL, C.RED); + this.ring(b.x, b.y, this.cnt(12 + 6 * D), a, this.sp(1.7), K.RING, C.BLUE); + } else if (s.k === 3 && lt % 21 === 0) { + const n = this.cnt(14 + 6 * D), w = lt / 21; + this.ring(b.x, b.y, n, this.aim(b.x, b.y) + (w % 2 ? PI / n : 0), this.sp(2.0 + 0.15 * D), K.BALL, C.BLUE); + } + } else if (lt === dur) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 88 + this.rnd() * 40, 50); + else if (lt >= dur + 50) { s.k = (s.k + 1 + Math.floor(this.rnd() * 3)) % 4; s.t0 = t; } + }, + r_bird(t, s, b, D) { // alternating aimed wing sweeps of light-blue/blue bullets; relocate between volleys + if (s.t0 === undefined) { s.t0 = 0; s.side = 1; } + const lt = t - s.t0, flaps = 3 + D, fl = 20, n = D ? 14 : 11; + if (lt < flaps * fl) { + const f = Math.floor(lt / fl), ft = lt % fl, side = (f % 2 ? -1 : 1) * s.side; + if (ft === 0) s.a = this.aim(b.x, b.y); + if (ft < n) { + const u = ft / (n - 1), ang = s.a + side * (1.3 - 2.6 * u), v = this.sp(1.8 + 1.5 * Math.sin(PI * u)), col = f % 2 ? C.BLUE : C.CYAN; + this.shoot(b.x, b.y, ang, v, K.RING, col); + if (D >= 2) this.shoot(b.x, b.y, ang, v * 0.72, K.RING, col); + } + } else if (lt === flaps * fl) this.moveBoss(CX + (this.rnd() - 0.5) * 390, 80 + this.rnd() * 60, 56); + else if (lt >= flaps * fl + 60) { s.t0 = t; s.side = -s.side; } + }, + r_non2(t, s, b, D) { // laser+fan first, then yellow two-way rings, green aimed rings, anti-aimed layered fan (S17) + if (s.k === undefined) { s.k = 0; s.t0 = 0; } + const lt = t - s.t0, dur = [112, 84, 72, 80][s.k]; + if (lt < dur) { + if (s.k === 0) { + if (lt === 0) { const a = this.aim(b.x, b.y), n = 2 + D; for (let i = 0; i < n; i++) this.laser(b.x, b.y, a + (i - (n - 1) / 2) * 0.42, 600, 12, 48, 36); } + if (lt === 16 || lt === 40 || lt === 64) this.fan(b.x, b.y, 5 + 2 * D, this.aim(b.x, b.y), 0.15, this.sp(2.6), K.BALL, C.GREEN); + } else if (s.k === 1 && lt % 28 === 0) { + const n = this.cnt(16 + 4 * D), a = this.aim(b.x, b.y); + this.ring(b.x, b.y, n, a, this.sp(2.2), K.RICE, C.YELLOW, {w: 0.004, wt: 120}); + this.ring(b.x, b.y, n, a + PI / n, this.sp(1.6), K.RICE, C.YELLOW, {w: -0.004, wt: 120}); + } else if (s.k === 2 && lt % 16 === 0) { + this.ring(b.x, b.y, this.cnt(18 + 6 * D), this.aim(b.x, b.y), this.sp(2.5), K.BALL, C.GREEN); + } else if (s.k === 3 && lt % 26 === 0) { + const m = 6 + 2 * D, a = this.aim(b.x, b.y), layers = D ? [1.7, 2.3, 2.9] : [1.8, 2.5]; + for (const v of layers) this.fan(b.x, b.y, m, a, 0.2, this.sp(v), K.RICE, C.GREEN); + } + } else if (lt === dur) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 88 + this.rnd() * 40, 50); + else if (lt >= dur + 46) { s.k = (s.k + 1 + Math.floor(this.rnd() * 3)) % 4; s.t0 = t; } + }, + r_demarc(t, s, b, D) { // 3 waves of counter-rotating rings, pause, 3 aimed volleys growing with time + const cyc = D ? 260 : 290, lt = t % cyc; + if (lt === 0 || lt === 30 || lt === 60) { + const n = this.cnt(16 + 8 * D), a0 = this.rnd() * TAU, v = this.sp(1.2 + 0.1 * D); + for (let i = 0; i < n; i++) { + this.shoot(b.x, b.y, a0 + TAU * i / n, v, K.BALL, C.BLUE, {w: 0.0065, wt: 170}); + this.shoot(b.x, b.y, a0 + TAU * (i + 0.5) / n, v, K.BALL, C.RED, {w: -0.0065, wt: 170}); + } + } + if (lt === 130 || lt === 148 || lt === 166) { + const m = (D >= 2 ? 5 : 3) + 2 * Math.min(4, Math.floor(t / 540)); + this.fan(b.x, b.y, m, this.aim(b.x, b.y), 0.14, this.sp(3.2), K.RICE, C.PURPLE); + } + if (lt === 200) this.moveBoss(N.clamp(b.x + (this.rnd() - 0.5) * 160, CX - 126, CX + 126), 96 + this.rnd() * 24, 40); + }, + c_non1(t, s, b, D) { // A: three aimed icicle triangles + aimed rings; B: moving icicle rings redirected at the player (S18) + if (s.k === undefined) { s.k = 0; s.t0 = 0; s.dir = 1; } + const lt = t - s.t0; + if (s.k === 0) { + if (lt === 0 || lt === 28 || lt === 56) { + const w = lt / 28, a = this.aim(b.x, b.y), rows = 5 + D - w, gap = [0.06, 0.1, 0.15][w]; + for (let r = 0; r < rows; r++) for (let i = 0; i <= r; i++) this.shoot(b.x, b.y, a + (i - r / 2) * gap, this.sp(4.0 - r * 0.32), K.KUNAI, C.CYAN); + this.ring(b.x, b.y, this.cnt(10 + 4 * D), a, this.sp(1.6), K.PELLET, C.BLUE); + } + if (lt >= 110) { s.k = 1; s.t0 = t; s.dir = -s.dir; this.moveBoss(CX + s.dir * 168, 104, 90); } + } else { + if (lt < 90 && lt % 18 === 0) { + const n = this.cnt(12 + 4 * D), a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) this.shoot(b.x, b.y, a0 + TAU * i / n, 2.2, K.SHARD, C.CYAN, {st: 28, gt: 44, gm: 1, gs: this.sp(2.4 + 0.25 * D)}); + if (lt % 36 === 0) this.ring(b.x, b.y, this.cnt(10 + 4 * D), this.aim(b.x, b.y), this.sp(1.8), K.PELLET, C.BLUE); + } + if (lt === 120) this.moveBoss(CX, 104, 60); + if (lt >= 190) { s.k = 0; s.t0 = t; } + } + }, + c_icicle(t, s, b, D) { // side lines of shards that curve down into falling arcs; Normal adds aimed yellow 5-way + if (s.iv === undefined || t % 120 === 0) s.iv = this.iv(D ? 7 : 10); + if (t % s.iv === 0) { + const kn = D ? 4 : 3; + for (const side of [-1, 1]) for (let k = 0; k < kn; k++) { + const th = 0.12 + 0.2 * k, a = side > 0 ? -th : PI + th; + // turn rate 0.010 rad/frame (0.022 in the 384 px lane) so the arcs still reach ~0.7 of the half-width (C18B) + this.shoot(b.x + side * 8, b.y, a, this.sp(1.6 + 0.4 * k), K.SHARD, C.CYAN, {ta: PI / 2, tw: 0.010}); + } + } + if (D >= 1 && t % 56 === 20) this.fan(b.x, b.y, 5, this.aim(b.x, b.y), 0.22, this.sp(2.8), K.BALL, C.YELLOW); + if (t % 180 === 90) this.moveBoss(CX + (this.rnd() - 0.5) * 105, 100 + this.rnd() * 16, 90); + }, + c_hail(t, s, b, D) { // circles of shards stop around Cirno, then each circle leaves along an ordered arc below her + const per = s.per || (s.per = this.iv(D === 3 ? 56 : 70)); + if (t % per === 0) { + s.per = this.iv(D === 3 ? 56 : 70); + const G = D === 3 ? 8 : 6, r0 = this.rnd() * TAU, m = 6; + for (let g = 0; g < G; g++) { + const th = r0 + TAU * g / G, cx = 50 * Math.cos(th), cy = 50 * Math.sin(th), dir = PI / 2 + (g / (G - 1) - 0.5) * 1.7; + for (let j = 0; j < m; j++) { + const ph = TAU * j / m, tx = cx + 14 * Math.cos(ph), ty = cy + 14 * Math.sin(ph), dist = Math.hypot(tx, ty); + this.shoot(b.x, b.y, Math.atan2(ty, tx), 2 * dist / 24, K.SHARD, C.CYAN, {st: 24, gt: 40, gm: 0, ga: dir, gs: this.sp(2.0 + 0.3 * (D - 2))}); + } + } + } + if (t % 240 === 120) this.moveBoss(CX + (this.rnd() - 0.5) * 210, 96 + this.rnd() * 30, 60); + }, + c_non2(t, s, b, D) { // authored (no readable description): rotating kunai arms, then aimed shard bursts + if (s.k === undefined) { s.k = 0; s.t0 = 0; s.rot = this.rnd() * TAU; s.dir = 1; s.iv = this.iv(5); } + const lt = t - s.t0; + if (s.k === 0) { + if (lt < 120 && lt % s.iv === 0) { const A = 3 + D; for (let i = 0; i < A; i++) this.shoot(b.x, b.y, s.rot + TAU * i / A, this.sp(2.1), K.KUNAI, C.CYAN); s.rot += 0.21 * s.dir; } + if (lt === 120) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 92 + this.rnd() * 30, 44); + if (lt >= 160) { s.k = 1; s.t0 = t; } + } else { + if (lt < 80 && lt % 20 === 0) { const a = this.aim(b.x, b.y), n = 8 + 3 * D; for (let i = 0; i < n; i++) this.shoot(b.x, b.y, a + (this.rnd() - 0.5) * 0.9, this.sp(2.0 + this.rnd() * 1.6), K.SHARD, C.BLUE); } + if (lt === 90) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 92 + this.rnd() * 30, 44); + if (lt >= 130) { s.k = 0; s.t0 = t; s.dir = -s.dir; s.iv = this.iv(5); } + } + }, + c_freeze(t, s, b, D) { // random rainbow spray -> freeze white -> aimed blue -> random release (S14) + const cyc = 330, lt = t % cyc; + if (lt === 0) s.iv = this.iv([4, 3, 2, 2][D]); + if (lt < 120 && lt % s.iv === 0) { + const m = D >= 2 ? 3 : 2; + for (let i = 0; i < m; i++) this.shoot(b.x, b.y, this.rnd() * TAU, this.sp(1.2 + this.rnd() * 2.4), K.BALL, RAINBOW[Math.floor(this.rnd() * 7)]); + } + if (lt === 130) { // ExInsCirnoRainbowBallJank mode 0 + for (const q of this.bullets) { q.vx = 0; q.vy = 0; q.c = C.WHITE; q.w = undefined; q.ta = undefined; q.am = undefined; q.st = undefined; } + this.ev('freeze'); + } + if (lt === 150 || lt === 194 || (D >= 1 && lt === 172)) this.fan(b.x, b.y, this.rank >= 20 ? 6 : 5, this.aim(b.x, b.y), 0.2, this.sp(3.0), K.RICE, C.BLUE); + if (lt === 236) { // mode 1: every bullet white, random direction, acceleration 0.01 for 220 frames + for (const q of this.bullets) { const a = this.rnd() * TAU - PI; q.c = C.WHITE; q.ax = Math.cos(a) * 0.01; q.ay = Math.sin(a) * 0.01; q.am = 220; } + this.ev('thaw'); + } + if (lt === 262) this.moveBoss(CX + (this.rnd() - 0.5) * 252, 90 + this.rnd() * 30, 50); + }, + c_blizzard(t, s, b, D) { // shard explosions around an erratically moving Cirno + if (t % 40 === 0) this.moveBoss(CX + (this.rnd() - 0.5) * 448, 64 + this.rnd() * 96, 40); + if (s.iv === undefined || t % 120 === 0) s.iv = this.iv([5, 4, 3, 2][D]); + if (t >= 20 && t % s.iv === 0) { + const r = this.rnd() * 64, th = this.rnd() * TAU, x = b.x + Math.cos(th) * r, y = b.y + Math.sin(th) * r * 0.8, k = 4 + D; + for (let i = 0; i < k; i++) this.shoot(x, y, this.rnd() * TAU, this.sp(1.0 + this.rnd() * 2.0), K.SHARD, [C.CYAN, C.WHITE, C.BLUE][Math.floor(this.rnd() * 3)]); + } + }, + // ---------- Sakuya Izayoi (stage 5) ---------- + s_non1(t, s, b, D) { // wild spray of small bullets + knives, alternating with dagger arcs (S24 NC; arcs = ExInsStage5Func5, S14) + const cyc = 236, lt = t % cyc; + if (lt < 84 && lt % 4 === 0) { + for (let i = 0; i < (D >= 2 ? 3 : 2); i++) this.shoot(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.6, this.sp(1.5 + this.rnd() * 1.8), K.PELLET, i % 2 ? C.RED : C.BLUE); + if (lt % 8 === 0) this.knife(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.2, this.sp(2.1 + this.rnd()), C.BLUE); + } + if (lt === 92) this.moveBoss(CX + (this.rnd() - 0.5) * 300, 92 + this.rnd() * 30, 40); + if (lt >= 140 && lt < 194 && (lt - 140) % 9 === 0) this.daggerArc((lt - 140) / 9, b); + }, + s_corpse(t, s, b, D) { // rice scatter -> time stop: Sakuya moves and lays aimed + parabolic blue knives -> time resumes (S25 S27) + const cyc = 300, lt = t % cyc; + if (lt < 40 && lt % 5 === 0) this.ring(b.x, b.y, this.cnt(D ? 14 : 10), this.rnd() * TAU, this.sp(1.5 + this.rnd() * 0.8), K.RICE, C.RED); + if (lt === 60) { this.timeStop(72); const s2 = b.x < CX ? 1 : -1; this.moveBoss(b.x + s2 * (200 + this.rnd() * 160), 80 + this.rnd() * 70, 68, true); } // she crosses the field at an even pace, laying the curtain + if (lt > 60 && lt <= 128 && lt % (D ? 6 : 8) === 0) { + const a = this.aim(b.x, b.y); + this.knife(b.x, b.y, a, this.sp(2.6), C.BLUE); + for (const side of [-1, 1]) this.knife(b.x, b.y, a + side * 0.55, this.sp(2.1), C.BLUE, {ax: 0, ay: 0.022, am: 150}); + } + }, + s_jack(t, s, b, D) { // downward bubble burst -> time stop: Sakuya travels leaving knives aimed at and around the player (S23) + const cyc = 270, lt = t % cyc, p = this.player; + if (lt === 0) for (let i = 0; i < (D === 3 ? 12 : 9); i++) this.shoot(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.0, this.sp(1.1 + this.rnd() * 1.4), K.BUBBLE, [C.BLUE, C.PURPLE, C.CYAN][i % 3]); + if (lt === 40) { this.timeStop(82); const s2 = b.x < CX ? 1 : -1; this.moveBoss(b.x + s2 * (240 + this.rnd() * 200), 70 + this.rnd() * 90, 78, true); } + if (lt > 40 && lt <= 118 && lt % 4 === 0) { + const k = (lt / 4) % 3, off = [0, -40, 40][k]; + this.knife(b.x, b.y, Math.atan2(p.y - b.y, p.x + off - b.x), this.sp(3.0), k ? C.RED : C.BLUE); + } + }, + s_non2(t, s, b, D) { // four moving magic circles: the blue pair sweeps CCW, the red pair CW; their kunai ricochet twice off + // the top/side walls before leaving through the floor (EX_BOUNCE_TLR, S15); Sakuya adds aimed knife rings (S23 S24) + if (!this.fams.length) for (let i = 0; i < 4; i++) { + const blue = i < 2, side = i % 2 ? 1 : -1, a0 = -PI / 2 + side * (blue ? 0.35 : 0.85); + this.fams.push({x: b.x, y: b.y, ox: side * (blue ? 290 : 140), oy: blue ? 96 : 30, t: 0, c: blue ? C.BLUE : C.RED, a0, a: a0, w: blue ? -0.045 : 0.045}); + } + const pair = Math.floor(t / 96) % 2, lt = t % 96; // blue pair, then red pair, 96 frames each + for (let i = 0; i < 4; i++) { + const f = this.fams[i], u = Math.min(1, f.t / 50), e = u * u * (3 - 2 * u), k = f.t + i * 40; + f.x = b.x + (f.ox + Math.sin(k * 0.02) * 26) * e; f.y = b.y + (f.oy + Math.cos(k * 0.025) * 16) * e; f.t++; + if ((i < 2 ? 0 : 1) !== pair || f.t <= 40) continue; + if (lt === 0) f.a = f.a0; + // a circle that has drifted off the playfield cannot fire (S23) + if (lt < 72 && lt % (D >= 2 ? 4 : 6) === 0 && f.x > 0 && f.x < W && f.y > 0 && f.y < H) { + this.shoot(f.x, f.y, f.a, this.sp(2.3 + 0.2 * D), K.KUNAI, f.c, {bn: 2, bm: 1}); f.a += f.w; + } + } + if (t % 70 === 50) this.ring(b.x, b.y, this.cnt(12 + 4 * D), this.aim(b.x, b.y), this.sp(2.2), K.KNIFE, C.BLUE, {s: 2.2}); + if (t % 300 === 280) this.moveBoss(CX + (this.rnd() - 0.5) * 200, 96 + this.rnd() * 24, 50); + }, + s_luna(t, s, b, D) { // fixed rice ripples -> time stop: lanes of blue knives toward the player, some turn green (ExInsStage56Func4) -> resume (S25 S26) + const cyc = 320, lt = t % cyc, p = this.player; + if (lt === 0 || lt === 12 || (D && lt === 24)) { const n = D ? 20 : 16; this.ring(b.x, b.y, n, PI / 2 + (lt / 12) * PI / n, this.sp(1.3 + lt / 40), K.RICE, C.YELLOW); } + if (lt === 50) { this.timeStop(96); s.a = this.aim(b.x, b.y); s.dist = Math.hypot(p.x - b.x, p.y - b.y); } + if (lt > 50 && lt <= 100 && lt % 5 === 0) { + const k = (lt - 55) / 5, lanes = D ? [-0.5, -0.25, 0, 0.25, 0.5] : [-0.34, 0, 0.34], r = 50 + k * Math.max(10, s.dist - 120) / 9; + for (const o of lanes) { const x = b.x + Math.cos(s.a + o) * r, y = b.y + Math.sin(s.a + o) * r; this.knife(x, y, this.aim(x, y), this.sp(2.2), C.BLUE); } + } + if (lt === 112) this.redirect(); + if (lt === 118) this.moveBoss(CX + (this.rnd() - 0.5) * 360, 80 + this.rnd() * 60, 40); + }, + s_world(t, s, b, D) { // rice rings -> time stop: daggers appear around the player (further away the closer she is to Sakuya), many turn green -> resume (S25 S26) + const cyc = 300, lt = t % cyc, p = this.player; + if (lt === 0 || lt === 10 || lt === 20) this.ring(b.x, b.y, this.cnt(24), this.rnd() * TAU, this.sp(1.6 + lt / 20), K.RICE, C.YELLOW); + if (lt === 40) this.timeStop(96); + if (lt > 40 && lt <= 110 && lt % 2 === 0) { + const dist = Math.hypot(p.x - b.x, p.y - b.y), r = 64 + Math.max(0, 300 - dist) * 0.4 + this.rnd() * 40, a = this.rnd() * TAU; + const x = p.x + Math.cos(a) * r, y = p.y + Math.sin(a) * r; + if (x > 0 && x < W && y > 0 && y < H) this.knife(x, y, this.aim(x, y), this.sp(2.3), C.BLUE); + } + if (lt === 120) this.redirect(); + if (lt === 124) this.moveBoss(CX + (this.rnd() - 0.5) * 420, 80 + this.rnd() * 60, 40); + }, + s_non3(t, s, b, D) { // blue knives from above alternate with red knives from the diagonals; nothing is aimed (S24 NC) + const cyc = 120, lt = t % cyc, wave = Math.floor(t / cyc); + if (lt < 36 && lt % 6 === 0) { + if (wave % 2 === 0) { + const n = this.cnt(D >= 2 ? 11 : D ? 9 : 7); + for (let i = 0; i < n; i++) { const x = (i + 0.5 + (this.rnd() - 0.5) * 0.6) * W / n; this.knife(x, -6, PI / 2 + (this.rnd() - 0.5) * 0.3, this.sp(2.0 + this.rnd() * 0.8), C.BLUE); } + } else { + for (const side of [-1, 1]) for (let i = 0; i < (D >= 2 ? 5 : D ? 4 : 3); i++) { + const x = side < 0 ? -6 : W + 6, y = 20 + this.rnd() * 140, a = side < 0 ? 0.45 + this.rnd() * 0.5 : PI - 0.45 - this.rnd() * 0.5; + this.knife(x, y, a, this.sp(2.4 + this.rnd() * 0.6), C.RED); + } + } + } + if (lt === 80) this.moveBoss(CX + (this.rnd() - 0.5) * 300, 90 + this.rnd() * 30, 40); + }, + s_doll(t, s, b, D) { // slow aimed 4-way blue then red knives -> time stop -> some turn into scattered green knives that ricochet once (S24 S26) + const cyc = 240, lt = t % cyc, vol = D ? 3 : 2; + if (lt < vol * 10 && lt % 10 === 0) this.fan(b.x, b.y, 4, this.aim(b.x, b.y), D ? 0.22 : 0.3, this.sp(1.6 + lt / 60), K.KNIFE, C.BLUE, {s: 2}); + if (lt >= 30 && lt < 30 + vol * 10 && lt % 10 === 0) this.fan(b.x, b.y, 4, this.aim(b.x, b.y) + 0.11, D ? 0.22 : 0.3, this.sp(1.8 + (lt - 30) / 60), K.KNIFE, C.RED, {s: 2.2}); + if (lt === 76) this.timeStop(60); + if (lt === 100) this.redirect({bn: 1, bm: 1}); + if (lt === 108) this.moveBoss(CX + (this.rnd() - 0.5) * 360, 84 + this.rnd() * 50, 36); + }, + s_killing(t, s, b, D) { // knife rings around Sakuya: blue come to rest, red stop and re-aim; in the stop she moves and some turn green (S23) + const cyc = 260, lt = t % cyc; + if (lt < 40 && lt % 8 === 0) { + const n = this.cnt(D === 3 ? 24 : 18), red = lt >= 24, a0 = this.rnd() * TAU, v = this.sp(red ? 3.0 : 2.4); + for (let i = 0; i < n; i++) this.knife(b.x, b.y, a0 + TAU * i / n, v, red ? C.RED : C.BLUE, red ? {st: 30, gt: 44, gm: 1, gs: v} : {st: 34, gt: 214, gm: 2, ga: 0, gs: 1.6}); + } + if (lt === 56) { this.timeStop(70); this.moveBoss(CX + (this.rnd() - 0.5) * 460, 80 + this.rnd() * 80, 60); } + if (lt === 100) this.redirect({bn: 1, bm: 2}); + }, + // ---------- Hong Meiling (stage 3) ---------- + // Geometry from community text only (C37, approximation); the only source numbers are the starting ways of non-spell 1 + // (4/5/7/10) and the ways of non-spell 3 (16/24/35/42). Fairies are ordinary enemies (C33/C38). + m_non1(t, s, b, D) { // red player-dependent rotating rings: every shot re-aims at the player, the ring turns, ways grow per wave + const cyc = 96, lt = t % cyc, wave = Math.floor(t / cyc); + if (lt === 0) s.dir = wave % 2 ? -1 : 1; + if (lt < 30 && lt % 3 === 0) { + const n = [4, 5, 7, 10][D] + Math.min(6, wave), rot = s.dir * (lt / 3) * 0.11; + this.ring(b.x, b.y, n, this.aim(b.x, b.y) + rot, this.sp(2.0 + 0.1 * D), K.RICE, C.RED); + } + if (lt === 40 && D >= 1) this.fan(b.x, b.y, 3 + D, this.aim(b.x, b.y), 0.16, this.sp(2.8), K.BALL, C.PINK); + if (lt === 60 && wave % 2 === 1) this.moveBoss(CX + (this.rnd() - 0.5) * 280, 96 + this.rnd() * 30, 36); + }, + m_chime(t, s, b, D) { // fixed-angle rainbow bullets, nothing aimed or random; she sinks slowly, the gap right below her is the safe spot + const cyc = 540, lt = t % cyc; + if (lt === 0) this.moveBoss(CX, 70, 50); + if (lt === 60) this.moveBoss(CX, 196, 440, true); + const iv = [9, 7, 6, 5][D], sh = (this.rank - 16) * 0.004; // rank shifts the angles slightly (C37) + if (lt >= 40 && lt % iv === 0) { + const k = Math.floor(lt / iv) % 7, v = this.sp(1.5 + 0.12 * k); + for (const side of [-1, 1]) { + // purple/blue rows lean to one side, orange/red to the other, so the colours ask for a nudge (C37) + const a = PI / 2 + side * (0.30 + 0.16 * k + 0.10 * Math.sin(lt * 0.035 + k)) + (k - 3) * 0.02 + sh; + this.shoot(b.x, b.y, a, v, K.BALL, RAINBOW[k]); + if (D >= 2) this.shoot(b.x, b.y, a + side * 0.07, v * 0.85, K.BALL, RAINBOW[k]); + } + } + }, + m_non2(t, s, b, D) { // three random blue sub-patterns (around her / above her / a line) + fairy squads with aimed kunai lines (C37 C38) + if (s.k === undefined) { s.k = Math.floor(this.rnd() * 3); s.t0 = 0; s.sq = 0; } + const lt = t - s.t0; + if (lt < 90) { + if (s.k === 0 && lt % 18 === 0) { + const n = this.cnt(14 + 4 * D), a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) { const a = a0 + TAU * i / n; this.shoot(b.x + Math.cos(a) * 36, b.y + Math.sin(a) * 36, a, this.sp(1.7), K.BALL, C.BLUE); } + } else if (s.k === 1 && lt % 5 === 0) { + for (let i = 0; i < 1 + (D >= 2 ? 1 : 0); i++) this.shoot(b.x + (this.rnd() - 0.5) * 320, b.y - 40 - this.rnd() * 30, PI / 2 + (this.rnd() - 0.5) * 0.7, this.sp(1.4 + this.rnd() * 1.2), K.RICE, C.BLUE); + } else if (s.k === 2 && lt % 30 === 0) { + const m = 5 + D; + for (let i = -m; i <= m; i++) { const x = b.x + i * 34; if (x > 8 && x < W - 8) this.shoot(x, b.y, this.aim(x, b.y), this.sp(1.9), K.PELLET, C.CYAN); } + } + } else if (lt === 90) this.moveBoss(CX + (this.rnd() - 0.5) * 240, 92 + this.rnd() * 30, 40); + else if (lt >= 130) { s.k = (s.k + 1 + Math.floor(this.rnd() * 2)) % 3; s.t0 = t; } + // fairy squad every 260 frames from alternating sides: they cross the field sinking slowly (so they pass below her) and each + // fires a line of kunai aimed at the player (several kunai on one line with rising speeds = the laser-like kunai) + if (t % 260 === 20) { + const side = s.sq % 2 ? 1 : -1, n = 3 + Math.min(D, 2); + s.sq++; + for (let i = 0; i < n; i++) this.fams.push({x: side < 0 ? -12 : W + 12, y: 56 + i * 22, vx: -side * 2.2, vy: 0.28, t: -i * 24, c: i % 2 ? C.CYAN : C.BLUE, hp: 120, sd: 0, bd: 0, gz: 0, fire: 50 + i * 10}); + } + for (const f of this.fams) { + if (f.hp === undefined) continue; + if (f.t++ < 0) continue; + f.x += f.vx; f.y += f.vy; + if (f.t === f.fire || (f.t > f.fire && (f.t - f.fire) % 110 === 0)) { + if (fairyIn(f)) { const a = this.aim(f.x, f.y); for (let j = 0; j < 4 + D; j++) this.shoot(f.x, f.y, a, this.sp(1.8 + 0.45 * j), K.KUNAI, C.CYAN); } + } + } + }, + m_vine(t, s, b, D) { // Hard/Lunatic: scatter whose density drifts in patches (Hard slower and denser, Lunatic faster and sparser) + if (t % 3 === 0) { + const tries = D === 3 ? 3 : 4, ph = t * 0.013; + for (let i = 0; i < tries; i++) { + const a = PI / 2 + (this.rnd() - 0.5) * 3.0, keep = this.rnd(); + if (keep > 0.25 + 0.75 * (0.5 + 0.5 * Math.sin(5 * a + ph * 4))) continue; + const v = D === 3 ? this.sp(2.0 + this.rnd()) : this.sp(1.3 + this.rnd() * 0.9); + this.shoot(b.x, b.y, a, v, K.RICE, [C.PINK, C.PURPLE, C.GREEN][i % 3]); + } + } + if (t % 200 === 150) this.moveBoss(CX + (this.rnd() - 0.5) * 260, 90 + this.rnd() * 30, 50); + }, + m_non3(t, s, b, D) { // all-round kunai rows: blue (slow) then red (fast) circle her before flying out with a gap to her + // left (blue) / right (red), then a short random scatter (C37) + const cyc = 250, lt = t % cyc, n = [16, 24, 35, 42][D]; + for (const [at, red] of [[0, false], [70, true]]) { + if (lt !== at && lt !== at + 8) continue; + const gap = PI / 2 + (red ? -0.5 : 0.5), w = red ? -0.035 : 0.035, wt = 40, a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) { + const a = a0 + TAU * i / n, fin = a + w * wt; + if (Math.abs(angDiff(fin, gap)) < 0.33) continue; // the lane stays open after the turn + this.shoot(b.x, b.y, a, this.sp(red ? 2.4 : 1.5), K.KUNAI, red ? C.RED : C.BLUE, {w, wt}); + } + } + if (lt >= 140 && lt < 180 && lt % 5 === 0) for (let i = 0; i < 2 + (D >> 1); i++) this.shoot(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.4, this.sp(1.6 + this.rnd() * 1.4), K.PELLET, C.YELLOW); + if (lt === 200) this.moveBoss(CX + (this.rnd() - 0.5) * 260, 96 + this.rnd() * 26, 40); + }, + m_rain(t, s, b, D) { // Easy/Normal: colourful shards cross from both sides of her, accelerating; then curves in from both sides + const cyc = 260, lt = t % cyc; + if (lt < 110 && lt % (D ? 4 : 5) === 0) { + for (const side of [-1, 1]) { + const x = b.x + side * 130, a = PI / 2 - side * (0.55 + this.rnd() * 0.45), v = this.sp(0.6), acc = 0.018 + 0.004 * D; + this.shoot(x, b.y - 10, a, v, K.SHARD, RAINBOW[Math.floor(this.rnd() * 7)], {ax: Math.cos(a) * acc, ay: Math.sin(a) * acc, am: 90}); + } + } + if (lt >= 130 && lt < 200 && lt % 10 === 0) { + for (const side of [-1, 1]) for (let j = 0; j < 2 + D; j++) { + const a = side > 0 ? -0.25 - j * 0.12 : PI + 0.25 + j * 0.12; + this.shoot(b.x, b.y, a, this.sp(1.4 + 0.2 * j), K.BALL, side > 0 ? C.ORANGE : C.GREEN, {ta: PI / 2, tw: 0.016}); + } + } + if (lt === 110 || lt === 235) this.moveBoss(CX + (this.rnd() - 0.5) * 300, 88 + this.rnd() * 36, 40); + }, + m_dance(t, s, b, D) { // Hard/Lunatic: accelerating radial bursts alternate with curves (red inner, yellow outer) mostly from the upper right + const cyc = 220, lt = t % cyc; + if (lt === 0 || lt === 12 || lt === 24) { + const n = this.cnt(18 + 4 * D), a0 = this.rnd() * TAU, acc = 0.012; + for (let i = 0; i < n; i++) { const a = a0 + TAU * i / n; this.shoot(b.x, b.y, a, this.sp(0.8), K.SHARD, RAINBOW[i % 7], {ax: Math.cos(a) * acc, ay: Math.sin(a) * acc, am: 100}); } + } + if (lt >= 80 && lt < 160 && lt % 6 === 0) { + const ox = this.rnd() < 0.75 ? 1 : -1, x = b.x + ox * 160, y = b.y - 40; + for (const [r, col] of [[0, C.RED], [1, C.YELLOW]]) { + const a = PI / 2 + ox * (0.35 + 0.35 * r); + this.shoot(x, y, a, this.sp(1.2 + 0.5 * r), K.BALL, col, {w: -ox * 0.008 * (r ? 0.6 : 1), wt: 90, ax: Math.cos(a) * 0.01, ay: Math.sin(a) * 0.01, am: 80}); + } + } + if (lt === 180) this.moveBoss(CX + (this.rnd() - 0.5) * 260, 92 + this.rnd() * 30, 36); + }, + m_typhoon(t, s, b, D) { // Meiling stays put and fires nonstop: two counter-turning spiral streams cross, colours random + if (t === 0) { this.moveBoss(CX, 120, 40); s.a = 0; } + const iv = [5, 4, 3, 3][D]; + if (t >= 40 && t % iv === 0) { + s.a += 0.21; + for (const side of [-1, 1]) { + const a = PI / 2 + side * s.a; + this.shoot(b.x, b.y, a, this.sp(1.7 + 0.2 * D), K.SHARD, RAINBOW[Math.floor(this.rnd() * 7)], {w: -side * 0.006, wt: 120}); + } + if (D >= 3 && t % 6 === 0) this.shoot(b.x, b.y, this.rnd() * TAU, this.sp(1.4), K.BALL, C.RED); + } + }, + // ---------- Patchouli Knowledge (stage 4), Reimu A card list ---------- + // Geometry from guide text (C42, C43, approximation); documented: lasers fire from 64 px along each laser (C42), the + // Lava Cromlech ways 8/12/16/20 and the Mercury Poison ways 15/20/28 with +1 way per set. + p_non1(t, s, b, D) { PATTERN.p_nonspell.call(this, t, s, b, D, false); }, + p_non2(t, s, b, D) { PATTERN.p_nonspell.call(this, t, s, b, D, true); }, + // Rotating lasers from one side sweep down toward her (Easy stops short of straight down, Normal reaches it, Hard+ goes a + // little past), alternating left / right; from the 2nd wave (non-spell 2: every wave) aimed bullets come from the lasers; + // then she moves and fires aimed all-round rings (non-spell 2: faster, turning like a winder). + p_nonspell(t, s, b, D, two) { + const cyc = 300, lt = t % cyc, wave = Math.floor(t / cyc), side = wave % 2 ? 1 : -1; + if (lt === 0) { + const n = [3, 4, 5, 5][D], sweep = PI / 2 + [-0.25, 0, 0.2, 0.2][D], frames = 100, gap = 0.22; + for (let i = 0; i < n; i++) { + const a0 = side < 0 ? PI + i * gap : -i * gap; // fanned away from straight down, the lead laser first + this.laser(b.x, b.y, a0, 600, 14, 40, frames); + this.lasers[this.lasers.length - 1].va = side * sweep / frames; // canvas y is down: left lasers turn from pi toward pi/2 + } + } + if (lt > 40 && lt <= 140 && lt % 20 === 0 && (two || wave >= 1)) { + const v = this.sp(2.0 + 0.15 * D); + this.fromLasers(b, (x, y) => this.fan(x, y, 3, this.aim(x, y), 0.18, v, K.PELLET, C.PURPLE)); + } + if (lt === 160) this.moveBoss(CX + (this.rnd() - 0.5) * 260, 92 + this.rnd() * 30, 40); + const shots = two ? 6 : 3, step = two ? 7 : 14; + if (lt >= 210 && lt < 210 + shots * step && (lt - 210) % step === 0) { + const k = (lt - 210) / step, n = this.cnt([12, 16, 20, 24][D]); + this.ring(b.x, b.y, n, this.aim(b.x, b.y) + (two ? side * 0.06 * k : 0), this.sp(two ? 2.4 : 2.0), K.BALL, C.BLUE); + } + }, + p_agni(t, s, b, D) { PATTERN.p_fire.call(this, t, s, b, D, false); }, + p_agni_hl(t, s, b, D) { PATTERN.p_fire.call(this, t, s, b, D, true); }, + // Agni Shine: waves of wavering fire bullets falling from above her and from her body; the outer ones leave the + // screen before the bottom, thinning the lower right (High Level: both lower corners, denser waves) + p_fire(t, s, b, D, hl) { + const per = hl ? 56 : 72, lt = t % per; + if (lt === 0) s.k = (s.k || 0) + 1; + if (lt < 24 && lt % 4 === 0) { + const lanes = hl ? [-1, 0, 1] : [-1, 0]; + for (const o of lanes) { + const x = o ? b.x + o * 210 : b.x, y = o ? 24 : b.y, base = PI / 2 + (o ? -o * 0.35 : 0); + for (let j = 0; j < 2 + (D >> 1); j++) { + const a = base + (this.rnd() - 0.5) * 1.2; + this.shoot(x, y, a, this.sp(1.5 + this.rnd()), K.FIRE, j % 2 ? C.ORANGE : C.RED, {w: (j % 2 ? 1 : -1) * 0.006, wt: 160}); + } + } + } + if (t % 300 === 260) this.moveBoss(CX + (this.rnd() - 0.5) * 200, 96 + this.rnd() * 26, 40); + }, + p_trilithon_hl(t, s, b, D) { PATTERN.p_earth.call(this, t, s, b, D, false); }, + p_shake(t, s, b, D) { PATTERN.p_earth.call(this, t, s, b, D, true); }, + // Earth: yellow bullets stop near her, turn to a random heading and go again (High Level: a short stop close to her); + // being above her draws aimed penalty shots; Trilithon Shake adds periodic aimed large bullets. She does not move. + p_earth(t, s, b, D, shake) { + if (t % 24 === 0) { + const n = this.cnt(8 + 2 * D), a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) this.shoot(b.x, b.y, a0 + TAU * i / n, 2.2, K.BALL, C.YELLOW, {st: 18, gt: 30, gm: 0, ga: PI / 2 + (this.rnd() - 0.5) * 2.6, gs: this.sp(1.5 + this.rnd() * 0.8)}); + } + if (this.player.y < b.y && t % 10 === 0) this.fan(b.x, b.y, 3, this.aim(b.x, b.y), 0.12, this.sp(3.4), K.RICE, C.YELLOW); + if (shake && t % 90 === 45) this.shoot(b.x, b.y, this.aim(b.x, b.y), this.sp(2.4), K.BIG, C.ORANGE); + }, + // Lava Cromlech: 16 sets alternating straight all-round fire (8/12/16/20-way, two speeds) and Earth-type yellow bullets + p_lava(t, s, b, D) { + const set = Math.floor(t / 40) % 16, lt = t % 40; + if (lt === 0) { + if (set % 2 === 0) { + const n = [8, 12, 16, 20][D], a0 = this.rnd() * TAU; + this.ring(b.x, b.y, n, a0, this.sp(1.8), K.FIRE, C.RED); + this.ring(b.x, b.y, n, a0 + PI / n, this.sp(2.6), K.FIRE, C.ORANGE); + } else { + const n = this.cnt(10 + 2 * D), a0 = this.rnd() * TAU; + for (let i = 0; i < n; i++) this.shoot(b.x, b.y, a0 + TAU * i / n, 2.0, K.BALL, C.YELLOW, {st: 22, gt: 34, gm: 0, ga: PI / 2 + (this.rnd() - 0.5) * 2.4, gs: this.sp(1.3 + this.rnd() * 0.7)}); + } + } + if (t % 640 === 600) this.moveBoss(CX + (this.rnd() - 0.5) * 180, 100 + this.rnd() * 20, 40); + }, + // Mercury Poison: from two points beside her, yellow streams curving clockwise and light-blue counter-clockwise, 8 + 8 + // alternate shots a set, 15/20/28 ways (Normal/Hard/Lunatic; not on Easy) and one more way every set + p_mercury(t, s, b, D) { + const step = 20, k = Math.floor(t / step), set = Math.floor(k / 16), n = [15, 15, 20, 28][D] + set; + if (t % step === 0) { + const yellow = k % 2 === 0, x = b.x + (yellow ? -60 : 60), a0 = PI / 2 + (k % 16) * 0.04 * (yellow ? 1 : -1); + this.ring(x, b.y, n, a0, this.sp(2.1), K.BALL, yellow ? C.YELLOW : C.CYAN, {w: yellow ? 0.004 : -0.004, wt: 200}); + } + }, + // Forest Blaze: green bullets stream in from off-screen top right toward the lower left, her body scatters fire bullets + p_forest(t, s, b, D) { + if (t % 6 === 0) for (let i = 0; i < 1 + (D >> 1); i++) { + const x = W * 0.45 + this.rnd() * (W * 0.6), a = PI / 2 + 0.2 + this.rnd() * 0.5; + this.shoot(x, -8, a, this.sp(1.8 + this.rnd() * 0.9), K.RICE, C.GREEN); + } + if (t % 40 === 20) for (let i = 0; i < 6; i++) this.shoot(b.x, b.y, PI / 2 + (this.rnd() - 0.5) * 2.4, this.sp(1.6 + this.rnd()), K.FIRE, C.RED); + if (t % 240 === 200) this.moveBoss(CX + (this.rnd() - 0.5) * 220, 90 + this.rnd() * 30, 50); + }, + // ---------- Remilia (stage 6, C45-C48). Order and rules are documented; counts and speeds are approximations unless a comment says otherwise ---------- + // Non-spell 1: "enemy-dependent all-round": one emission point; red large, blue medium at random angles and aimed blue pellets, then a move + r6_non1(t, s, b, D) { + const cyc = 170, lt = t % cyc; + if (lt === 0) this.ring(b.x, b.y, [6, 10, 14, 18][D], this.aim(b.x, b.y), this.sp(1.7), K.BIG, C.RED); + if (lt < 48 && lt % 12 === 0) { + this.ring(b.x, b.y, this.cnt([10, 14, 18, 24][D]), this.rnd() * TAU, this.sp(2.2), K.BALL, C.BLUE); + this.ring(b.x, b.y, this.cnt([12, 20, 26, 32][D]), this.aim(b.x, b.y), this.sp(2.9), K.PELLET, C.BLUE); + } + if (lt === 90) this.moveBoss(CX + (this.rnd() - 0.5) * 300, 88 + this.rnd() * 56, 50); + }, + // Non-spell 2: fixed order "aimed, move, right to left, move, left to right, aimed, move"; large with scattered medium and small; 8 shots a sweep (S45), the top row is out of reach + r6_non2(t, s, b, D) { + const lt = t % 500, volley = a => { + this.shoot(b.x, b.y, a, this.sp(2.6), K.BIG, C.RED); + for (let i = 0; i < 3 + D; i++) this.shoot(b.x, b.y, a + (this.rnd() - 0.5) * 0.5, this.sp(1.9 + this.rnd() * 1.1), i % 2 ? K.BALL : K.PELLET, C.BLUE); + }; + if (lt < 70 && lt % 14 === 0) { const a = this.aim(b.x, b.y); for (const o of [-0.3, 0, 0.3]) volley(a + o); } + if (lt === 80) this.moveBoss(CX + 200, 110, 40); + if (lt >= 130 && lt < 130 + 8 * 13 && (lt - 130) % 13 === 0) { const a = (lt - 130) / 13 * PI / 7; for (let i = 0; i < 2 + (D >> 1); i++) volley(a + i * 0.16); } + if (lt === 240) this.moveBoss(CX - 200, 110, 40); + if (lt >= 290 && lt < 290 + 8 * 13 && (lt - 290) % 13 === 0) { const a = PI - (lt - 290) / 13 * PI / 7; for (let i = 0; i < 2 + (D >> 1); i++) volley(a - i * 0.16); } + if (lt === 400) this.moveBoss(CX, 100, 40); + }, + // Non-spell 3: fixed all-round knives; each set's rounds share one angle, so they fly the same paths and the gap in the first row + // stays safe; clockwise first, then the same counter-clockwise, random starting point (S46) + r6_non3(t, s, b, D) { + const lt = t % 170; + if (lt === 0) { s.k = (s.k || 0) + 1; if (s.k % 2) s.a0 = this.aim(b.x, b.y) + (this.rnd() - 0.5) * 0.5; } + if (lt < 66 && lt % 11 === 0) { + const n = [14, 18, 22, 26][D], dir = s.k % 2 ? 1 : -1, v = 2.2 + 0.2 * D; + for (let i = 0; i < n; i++) this.knife(b.x, b.y, s.a0 + TAU * i / n, v, C.BLUE, {w: dir * 0.0065, wt: 150}); + } + }, + // Non-spell 4: fixed three segments, invulnerable while attacking (documented, hit her between them): 1 scattered accelerating falling + // rice, 2 aimed odd-way large, 3 aimed odd-way fire much slower than 2; she moves at random between them. Segment lengths are approximations. + r6_non4(t, s, b, D) { + const lt = t % 600, seg = lt < 120 ? 1 : lt < 200 ? 0 : lt < 280 ? 2 : lt < 360 ? 0 : lt < 480 ? 3 : 0; + s.inv = seg > 0 ? 1 : 0; + if (seg === 1 && lt % 5 === 0) for (let i = 0; i < 2 + D; i++) { + const a = PI / 2 + (this.rnd() - 0.5) * 2.8; + this.shoot(b.x, b.y, a, this.sp(0.5), K.RICE, this.rnd() < 0.5 ? C.RED : C.PINK, {ax: Math.cos(a) * 0.012, ay: 0.02 + Math.sin(a) * 0.012, am: 110}); + } + if (seg === 2 && (lt - 200) % 16 === 0) this.fan(b.x, b.y, 3 + 2 * (D >> 1), this.aim(b.x, b.y), 0.22, this.sp(2.4 + 0.4 * D), K.BIG, C.RED); + if (seg === 3 && (lt - 360) % 14 === 0) this.fan(b.x, b.y, 5 + 2 * (D >> 1), this.aim(b.x, b.y), 0.2, this.sp(1.4 + 0.2 * D), K.FIRE, C.ORANGE); + if (lt === 120 || lt === 280 || lt === 480) this.moveBoss(CX + (this.rnd() - 0.5) * 340, 88 + this.rnd() * 52, 50); + }, + // Star of David: the web, and from the 16x3 points of a second Func7 call with its own rotation (S45 S47) blue medium bullets: the first web's points all-round 5-way at one common angle + // (reads as rings from her), the second's 3 shots in one common direction, slightly random, mostly right or down (lower left is often safe). + r6_david(t, s, b, D) { + const lt = t % 240; + if (lt === 0) { s.a0 = this.rnd() * TAU; s.a1 = (this.rnd() < 0.5 ? 0 : PI / 2) + (this.rnd() - 0.5) * 0.5; this.webLasers(b, this.rnd() * TAU); } + if (lt === 20) this.webEach(b, this.rnd() * TAU, (x, y, a, n, len, net) => { + if (x < 0 || x > W || y < 0 || y > H) return; + if (net === 0) this.ring(x, y, 5, s.a0, this.sp(1.5), K.BALL, C.BLUE); + else for (let i = 0; i < 3; i++) this.shoot(x, y, s.a1 + (this.rnd() - 0.5) * 0.4, this.sp(1.5 + this.rnd() * 0.6), K.BALL, C.BLUE); + }); + }, + // Young Demon Lord: the same web (inferred, C48), a static random rotation each wave, large and medium bullets from the points + r6_demon(t, s, b, D) { + const lt = t % 240; + if (lt === 0) { s.a0 = this.rnd() * TAU; this.webLasers(b, this.rnd() * TAU); } + if (lt === 20) this.webEach(b, this.rnd() * TAU, (x, y, a, n, len, net) => { + if (x < 0 || x > W || y < 0 || y > H) return; + if (net === 0) this.shoot(x, y, a, this.sp(1.8), K.BIG, C.CYAN); + else this.ring(x, y, 4 + D, s.a0, this.sp(1.7), K.BALL, C.BLUE); + }); + }, + // From the second card on rank no longer changes her cards (S44), so these take plain speeds, not sp(). + // Scarlet Netherworld: 16-way falling needles (gravity on Normal, S45) + 24-way crossing bullets; the first wave's angle is random and + // every later wave repeats it, so the rows are orderly and a spot that survives one wave survives the next. + r6_nether(t, s, b, D) { + if (t === 0) s.a0 = this.rnd() * TAU; + if (t % 90 !== 0) return; + this.ring(b.x, b.y, 16, s.a0, 1.8, K.RICE, C.RED, {ax: 0, ay: 0.012, am: 200}); + for (let i = 0; i < 24; i++) { const a = s.a0 + TAU * i / 24; this.shoot(b.x, b.y, a, 2.0, K.BALL, C.PINK, {w: (i % 2 ? 1 : -1) * 0.006, wt: 160}); } + }, + // Thousand Needles: the crossing bullets become 16-way knives; needles without gravity reflect off the top and side walls, 12-way on Hard, 32-way on Lunatic (S44) + r6_needles(t, s, b, D) { + if (t === 0) s.a0 = this.rnd() * TAU; + if (t % 80 !== 0) return; + this.ring(b.x, b.y, D >= 3 ? 32 : 12, s.a0, 2.2, K.RICE, C.RED, {bn: 2, bm: 1}); + for (let i = 0; i < 16; i++) this.knife(b.x, b.y, s.a0 + TAU * i / 16, 2.3, C.BLUE, {w: (i % 2 ? 1 : -1) * 0.006, wt: 160}); + }, + // Curse of Vlad Tepes: spiral all-round blue knives, 13 growing to 18 ways, strongly curving; red bullets spread along their tracks; a new + // round only when no blue knife is on screen (documented, S44 S45) + r6_tepes(t, s, b, D) { + if (s.next === undefined) { s.next = 0; s.k = 0; } + if (t >= s.next && !this.hasBullet(K.KNIFE, C.BLUE)) { + const n = Math.min(18, 13 + s.k), a0 = this.rnd() * TAU, dir = s.k % 2 ? 1 : -1; + for (let i = 0; i < n; i++) this.knife(b.x, b.y, a0 + TAU * i / n, 2.6, C.BLUE, {w: dir * 0.011, wt: 130}); + s.k++; s.next = t + 40; + } + if (t % 16 === 8 && this.bullets.length < 640) { + const m = this.bullets.length; + for (let i = 0; i < m; i++) { + const q = this.bullets[i]; + if (q.k === K.KNIFE && q.c === C.BLUE && q.x >= 0 && q.x <= W && q.y >= 0 && q.y <= H) this.shoot(q.x, q.y, this.rnd() * TAU, 0.5 + this.rnd() * 0.5, K.PELLET, C.RED); + } + } + }, + // Vampire Illusion: aimed even-way large bullets (only a big move runs into them) leave still bullets on their tracks that slowly spread; a + // new round only when no blue large bullet is on screen (S44) + r6_fantasy(t, s, b, D) { + if (s.next === undefined) s.next = 0; + if (t >= s.next && !this.hasBullet(K.BIG, C.BLUE)) { + this.fan(b.x, b.y, D >= 3 ? 8 : 6, this.aim(b.x, b.y), 0.3, 2.4, K.BIG, C.BLUE); + s.next = t + 30; + } + if (t % 12 === 6) this.dropStill(K.BIG, C.BLUE); + if (t % 60 === 30) this.releaseStill(b, false); + }, + // Scarlet Shoot: aimed large bullets with scattered medium and small from one point: 5-way x 2 (180 deg across), a narrow 3-way, a pause, + // 5-way x 2, a gap (S44 S45); fast + r6_shoot(t, s, b, D) { + const lt = t % 320, volley = (n, gap) => { + const a0 = this.aim(b.x, b.y); + for (let i = 0; i < n; i++) { + const a = a0 + (i - (n - 1) / 2) * gap; + this.shoot(b.x, b.y, a, 3.4, K.BIG, C.RED); + for (let j = 0; j < 4; j++) this.shoot(b.x, b.y, a + (this.rnd() - 0.5) * 0.3, 2.2 + this.rnd() * 1.2, j % 2 ? K.BALL : K.PELLET, C.RED); + } + }; + if (lt === 0 || lt === 26 || lt === 160 || lt === 186) volley(5, PI / 4); + else if (lt === 70) volley(3, 0.2); + if (lt === 250) this.moveBoss(CX + (this.rnd() - 0.5) * 240, 92 + this.rnd() * 40, 40); + }, + // Scarlet Meister: circular volleys led by large bullets; each wave a long aimed row of 5 turning clockwise, she moves a fixed distance, a + // short row of 3 turning counter-clockwise, a long pause (S44 S46) + r6_meister(t, s, b, D) { + const lt = t % 340, n = D >= 3 ? 26 : 20, row = (k, dir) => { + const a = (k === 0 ? (s.a0 = this.aim(b.x, b.y)) : s.a0) + dir * k * 0.09, v = 2.7; + this.ring(b.x, b.y, n, a, v, K.BIG, C.RED); this.ring(b.x, b.y, n, a, v * 0.82, K.BALL, C.RED); this.ring(b.x, b.y, n, a, v * 0.66, K.PELLET, C.RED); + }; + if (lt < 50 && lt % 10 === 0) row(lt / 10, 1); + if (lt === 70) { const sd = this.rnd() < 0.5 ? -1 : 1, x = b.x + sd * 180; this.moveBoss(x < 60 || x > W - 60 ? b.x - sd * 180 : x, 92 + this.rnd() * 40, 40); } + if (lt >= 120 && lt < 150 && (lt - 120) % 10 === 0) row((lt - 120) / 10, -1); + }, + // Red Magic (C47 C48): all-round large bullets leaving still bullets on their tracks, 10-way x 5 at one random angle (S45; Easy's sparser + // 6-way x 3 with still bullets every 30 frames is our own, the original has no Easy stage 6), reflecting off the top and sides but not the floor; on her signal the pellets + // scatter (Func11 random / Func9 swirl in turn); the next round only when no large bullet is left. + r6_magic(t, s, b, D) { PATTERN.r6_final.call(this, t, s, b, D, D === 0 ? 6 : 10, D === 0 ? 3 : 5, true, 0); }, + // Scarlet Gensokyo: the same without the reflection, with the 56-way ring (S44) + r6_gensokyo(t, s, b, D) { PATTERN.r6_final.call(this, t, s, b, D, 12, 5, false, 56); }, + r6_final(t, s, b, D, ways, sets, reflect, ring) { + if (s.left === undefined) { s.left = 0; s.k = 0; } + if (s.left > 0 && t >= s.fire) { + this.ring(b.x, b.y, ways, s.a0, 2.1, K.BIG, C.RED, reflect ? {bn: 1, bm: 1} : undefined); + s.left--; s.fire = t + 14; + if (ring && s.left === sets - 1) this.ring(b.x, b.y, ring, s.a0, 1.5, K.BALL, C.PINK); + } else if (s.left === 0 && !this.hasBullet(K.BIG, C.RED)) { s.a0 = this.rnd() * TAU; s.left = sets; s.fire = t; s.k++; } + if (t % (D === 0 ? 30 : 20) === 10) this.dropStill(K.BIG, C.RED); + if (t % 100 === 60) this.releaseStill(b, s.k % 2 === 0); + } + }; + M.Game = Game; M.PATTERN = PATTERN; + + // ---------- standard scripted controller (trusted reference; reads privileged state, never mutates it) ---------- + const DIRS = [[0, 0], [-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]]; + const keysFor = (dx, dy, focus, extra) => { + const k = ['J']; if (focus) k.push('Shift'); + if (dx < 0) k.push('A'); else if (dx > 0) k.push('D'); + if (dy < 0) k.push('W'); else if (dy > 0) k.push('S'); + if (extra && k.length < 4) k.push(extra); + return k; + }; + // Private copy for lookahead. Spread copies keep the source objects' fast shapes; copying key by key (o[k] = v) would turn the + // ~60-field game and the 26-field bullets into slow dictionary-mode objects. Arrays fixed at construction are shared. + const SHARED = new Set(['phases', 'lifeOf', 'timeOf']), OWN = new Set(['player', 'boss', 'sub', 'bullets', 'shots', 'items', 'lasers', 'fams', 'bomb', 'events', 'pops', 'msg']); + const spreadAll = a => { const out = new Array(a.length); for (let i = 0; i < a.length; i++) out[i] = {...a[i]}; return out; }; + function cloneGame(g) { + const c = Object.setPrototypeOf({...g}, Game.prototype); + for (const k in c) { const v = c[k]; if (v !== null && typeof v === 'object' && !SHARED.has(k) && !OWN.has(k)) c[k] = clone(v); } + c.player = {...g.player}; c.boss = {...g.boss}; c.sub = {...g.sub}; + c.bullets = spreadAll(g.bullets); c.shots = spreadAll(g.shots); c.items = spreadAll(g.items); c.lasers = spreadAll(g.lasers); c.fams = spreadAll(g.fams); + if (g.bomb) { c.bomb = {...g.bomb}; c.bomb.orbs = spreadAll(g.bomb.orbs); } + c.events = []; c.pops = []; c.msg = null; + return c; + } + // Same rounding as NativeBench.quantize, restricted to the containers that can hold fractional numbers. + function qo(o) { for (const k in o) { const v = o[k]; if (typeof v === 'number') { if (!Number.isInteger(v)) o[k] = Math.round(v * 1e6) / 1e6; } else if (v !== null && typeof v === 'object') qo(v); } } + function qa(a) { for (let i = 0; i < a.length; i++) qo(a[i]); } + const r6 = v => Number.isInteger(v) ? v : Math.round(v * 1e6) / 1e6; + function qb(a) { + for (let i = 0; i < a.length; i++) { + const q = a[i]; q.x = r6(q.x); q.y = r6(q.y); q.vx = r6(q.vx); q.vy = r6(q.vy); + if (q.a !== undefined) q.a = r6(q.a); if (q.ax !== undefined) { q.ax = r6(q.ax); q.ay = r6(q.ay); } + if (q.w !== undefined) q.w = r6(q.w); if (q.ta !== undefined) q.ta = r6(q.ta); if (q.ga !== undefined) q.ga = r6(q.ga); if (q.gs !== undefined) q.gs = r6(q.gs); + if (q.s !== undefined) q.s = r6(q.s); if (q.tw !== undefined) q.tw = r6(q.tw); + } + } + function quantizeGame(g) { qo(g.player); qo(g.boss); qb(g.bullets); qa(g.shots); qa(g.items); qa(g.lasers); qa(g.fams); if (g.bomb) qo(g.bomb); qo(g.sub); if (g.msg) qo(g.msg); } + M.quantizeGame = quantizeGame; + const EMPTY = new Set(); + // Advance a private copy n ticks with constant held keys (candidates never press K/Q/E, so pressed is empty), + // quantized exactly like NativeBench.Session so the prediction matches the live packet. + function advance(g, keys, n, acc) { + const p = g.player, hits0 = p.hits; + for (let i = 0; i < n; i++) { + g.events = []; g.update(keys, EMPTY, null); quantizeGame(g); g.t++; + if (g.outcome === 'win') { acc.win = 1; return true; } + if (p.hits !== hits0 || g.outcome === 'loss') { acc.dead = acc.tick + i; return false; } + if (p.state === 'alive' && p.inv === 0 && !g.stop) { + const w = 1 / (1 + (acc.tick + i) * 0.12); + for (const q of g.bullets) { + const dx = Math.abs(q.x - p.x), dy = Math.abs(q.y - p.y); + if (dx > 40 || dy > 40) continue; + const d = Math.max(dx, dy) - BSIZE[q.k] / 2 - PLAYER_HALF; + if (d < acc.margin) acc.margin = d; + if (d < 24) acc.danger += (24 - d) * (24 - d) * w; + } + for (const l of g.lasers) { + if (l.t > l.wn + l.on) continue; + const c = Math.cos(l.a), s = Math.sin(l.a), rx = p.x - l.x, ry = p.y - l.y, along = rx * c + ry * s; + if (along < 0 || along > l.l) continue; + const d = Math.abs(-rx * s + ry * c) - l.w / 2 - PLAYER_HALF; + if (d < acc.margin) acc.margin = d; + if (d < 30) acc.danger += (30 - d) * (30 - d) * 2 * w; + } + } + } + acc.tick += n; return true; + } + const T = M.tune = {danger: 0.6, margin: 4, ax: 1.6, ay: 0.35, wantY: 400}; // controller weights (fixed constants of the reference controller) + M.scripted = function (game) { + const p = game.player, holds = k => ({holds: Array.from({length: 6}, () => k), mouse: [0, 0, 0]}); + if (game.outcome) return holds([]); + // Hit inside the previous packet: deathbomb while the 6-frame window is still open. The window (like everything of the + // player's) stands still in a time stop, so the press goes into the first hold set whose first tick is not frozen. + if (p.state === 'dead') { + const j0 = Math.ceil(Math.min(12, game.stop) / 2); + if (p.window > 0 && p.bombs > 0 && !game.bomb && j0 <= 5) return {holds: Array.from({length: 6}, (_, j) => j >= j0 ? ['K', 'J'] : ['J']), mouse: [0, 0, 0]}; + return holds(['J']); + } + // The whole packet is inside a time stop: input is ignored, nothing to decide. + if (game.stop > 12) return holds(keysFor(0, 0, true)); + // Line up under where the boss will be when the 12 px/frame amulets arrive (~20 frames), not where it is now. + const b = game.boss, lead = Math.min(1, (b.mt + 20) / (b.md || 1)), ease = lead * lead * (3 - 2 * lead); + const wantX = b.mt < b.md ? b.fx + (b.tx - b.fx) * ease : b.x, wantY = T.wantY, stay = new Set(keysFor(0, 0, true)); + const stage1 = []; + for (const [dx, dy] of DIRS) for (const focus of [true, false]) { + if (!focus && dx === 0 && dy === 0) continue; + const k = keysFor(dx, dy, focus), ks = new Set(k), g1 = cloneGame(game), acc = {tick: 0, dead: -1, danger: 0, margin: 99, win: 0}; + const ok = advance(g1, ks, 12, acc), gp = g1.player; + // cheap first-stage estimate, used only to choose which candidates get the expensive second stage + const pre = !ok ? -1e7 + acc.dead * 1e4 : acc.win ? 1e6 : -acc.danger * T.danger + Math.min(acc.margin, 30) * T.margin - Math.abs(gp.x - wantX) * T.ax - Math.abs(gp.y - wantY) * T.ay; + stage1.push({k, ks, g1, acc, ok, pre}); + } + stage1.sort((a, b2) => b2.pre - a.pre); + let best = null; + for (let i = 0; i < stage1.length; i++) { + const c = stage1[i], {k, ks, g1, acc} = c; + let score; + if (!c.ok) score = -1e7 + acc.dead * 1e4; + else if (acc.win) score = 1e6; + else if (i >= 7) score = c.pre - 1e5; // not expanded: ranked below every expanded survivor + else { + let cont = null; + for (const k2 of [ks, stay]) { + const g2 = cloneGame(g1), a2 = {tick: acc.tick, dead: -1, danger: acc.danger, margin: acc.margin, win: 0}; + const ok = advance(g2, k2, 12, a2), gp = g2.player; + let v; + if (!ok) v = -1e6 + a2.dead * 1e4; + else { + v = -a2.danger * T.danger + Math.min(a2.margin, 30) * T.margin - Math.abs(gp.x - wantX) * T.ax - Math.abs(gp.y - wantY) * T.ay; + if (gp.x < 28 || gp.x > W - 28) v -= 60; + if (gp.y > H - 24) v -= 40; + } + if (cont === null || v > cont) cont = v; + } + score = cont; + } + if (!best || score > best.score) best = {k, score, dead: acc.dead}; + } + // Every candidate is hit inside this packet: bomb (any bomb voids the capture anyway). The press must land on a tick + // outside a time stop, so it goes into the first hold set whose first tick is no longer frozen. + if (best.dead >= 0 && p.bombs > 0 && !game.bomb && p.state === 'alive') { + const j0 = Math.ceil(Math.min(12, game.stop) / 2); + if (j0 <= 5) { + const k = best.k.slice(0, 3); k.push('K'); + return {holds: Array.from({length: 6}, (_, j) => j === j0 ? k : best.k), mouse: [0, 0, 0]}; + } + } + return holds(best.k); + }; + M.oracle = M.scripted; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/environments/games/web/games/touhou_remake/index.html b/environments/games/web/games/touhou_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..3d4a87b07209ec076eea03cbc1887bc845192384 --- /dev/null +++ b/environments/games/web/games/touhou_remake/index.html @@ -0,0 +1,32 @@ + +Touhou Koumakyou: Boss Practice + +
              +
              + +
              Select a boss to start
              + +

              + +
              +
              + +

              All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.

              +
              + diff --git a/environments/games/web/games/touhou_remake/manifest.json b/environments/games/web/games/touhou_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8691e96a8ca74438478af0fb0c1ea73e64e449ae --- /dev/null +++ b/environments/games/web/games/touhou_remake/manifest.json @@ -0,0 +1,31 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "touhou_remake", + "module": "TouhouGame", + "title": "Touhou Koumakyou: Boss Practice", + "dimension": "2d", + "native_hz": 60, + "max_seconds": 600, + "renderer": "canvas-native", + "rules": "scarlet-practice@8", + "cases": [ + "touhou/rumia", + "touhou/cirno", + "touhou/sakuya", + "touhou/meiling", + "touhou/patchouli", + "touhou/remilia" + ], + "scripts": [ + "_native/runtime.js", + "touhou_remake/game.js", + "touhou_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "touhou_remake/game.js" + ], + "play_page": "web/games/touhou_remake/index.html", + "scripted_controller": "TouhouGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]}: exact 24-tick lookahead on a private copy, deathbomb/bomb on unavoidable hits (bomb press placed outside time stops)" +} diff --git a/environments/games/web/games/touhou_remake/page.css b/environments/games/web/games/touhou_remake/page.css new file mode 100644 index 0000000000000000000000000000000000000000..76cccd740aedafe77d6224f787dabc111ae4acec --- /dev/null +++ b/environments/games/web/games/touhou_remake/page.css @@ -0,0 +1,49 @@ +/* touhou_remake play page (scarlet-practice@4): the window is the game. No page chrome, no borders. */ +:root{color-scheme:dark;--ink:#f3eaf0;--muted:#b9a9b6;--accent:#f0b6d0;--glass:rgba(14,8,22,.72);--edge:rgba(255,200,225,.22)} +*{box-sizing:border-box} +html,body{margin:0;height:100%;background:#05030a;color:var(--ink);font:14px/1.5 "Yu Gothic UI","Microsoft YaHei","Segoe UI",sans-serif;overflow:hidden} +a{color:var(--accent)} +.stage{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;overflow:hidden} +#ambient{position:fixed;inset:-6%;z-index:-1;background:#05030a center/cover no-repeat;filter:blur(26px) brightness(.5) saturate(1.25);pointer-events:none} +.frame{position:relative;width:min(100vw,calc(100vh * 854 / 480));aspect-ratio:854/480;box-shadow:0 0 60px rgba(0,0,0,.6)} +.frame>canvas{display:block;width:100%;height:100%;touch-action:none;outline:none} +.frame>canvas:focus-visible{box-shadow:inset 0 0 0 2px var(--accent)} +#overlay{pointer-events:none;position:absolute;inset:0;background:radial-gradient(ellipse at center,rgba(8,4,16,.12),rgba(8,4,16,.45))} +#overlay[hidden]{display:none} +#overlay div{position:absolute;top:11.5%;left:1.2%;white-space:nowrap;padding:4px 16px;background:var(--glass);border:1px solid var(--edge);border-radius:4px;font:16px/1.4 Georgia,"Yu Mincho","SimSun",serif;letter-spacing:.06em;text-align:left} +.bar{position:absolute;left:0;right:0;top:0;display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;padding:6px 10px;background:linear-gradient(rgba(10,6,18,.88),rgba(10,6,18,.62));border-bottom:1px solid var(--edge);transition:opacity .35s ease;z-index:2} +.bar.idle{opacity:0} +.bar.idle.locked{pointer-events:none} +.bar h1{margin:0 6px 0 0;font:600 15px/1.2 Georgia,"Yu Mincho","Microsoft YaHei",serif;letter-spacing:.04em;white-space:nowrap} +.bar label{display:flex;align-items:center;gap:5px;color:var(--muted);font-size:12px;white-space:nowrap} +.bar .group{display:flex;gap:5px} +.bar .lobby{font-size:12px;align-self:center;margin-left:2px} +button,select,input{font:inherit;font-size:12.5px;color:var(--ink);background:rgba(40,24,52,.85);border:1px solid var(--edge);border-radius:3px;padding:4px 9px} +button{cursor:pointer}button:hover{border-color:var(--accent)} +button.primary{background:#e9a6c4;color:#1c0d18;font-weight:600;border-color:#f7c9dc} +input[type=number]{width:96px} +select{max-width:190px} +#file{display:none} +:focus-visible{outline:2px solid var(--accent);outline-offset:1px} +#status{position:absolute;left:50%;bottom:44px;transform:translateX(-50%);margin:0;max-width:80%;padding:4px 14px;background:var(--glass);border:1px solid var(--edge);border-radius:3px;font-size:12.5px;color:var(--accent);text-align:center;pointer-events:none;transition:opacity .6s ease;overflow-wrap:anywhere} +#status:empty,#status.faded{opacity:0} +.help{position:absolute;right:10px;top:52px;width:min(360px,46%);max-height:calc(100% - 64px);overflow:auto;padding:12px 16px;background:var(--glass);border:1px solid var(--edge);border-radius:4px;z-index:3} +.help[hidden]{display:none} +.help h2{margin:0 0 8px;font:600 15px Georgia,"Microsoft YaHei",serif} +.help dl{margin:0}.help dt{color:var(--accent);font:12px Consolas,monospace}.help dd{margin:0 0 7px;font-size:12.5px;color:var(--muted)} +.help .note{font-size:12px;color:var(--muted);margin:8px 0}.help .links{display:flex;gap:14px;font-size:12px;margin:6px 0 0} +.mobile{display:none} +@media (max-width:900px),(orientation:portrait){ + html,body{overflow:auto} + .stage{position:static;display:block;min-height:100%} + .frame{width:100vw;box-shadow:none} + .bar{position:static;background:rgba(10,6,18,.9)} + .bar.idle,.bar.idle.locked{opacity:1;pointer-events:auto} + #overlay div{font-size:14px;padding:3px 14px} + #status{position:static;transform:none;max-width:none;margin:6px 10px} + .help{position:static;width:auto;max-height:none;margin:8px 10px} + .mobile{display:flex;flex-wrap:wrap;gap:8px;padding:10px} + .mobile button{min-width:52px;min-height:44px;font-size:15px;touch-action:none} + #ambient{display:none} +} +@media (prefers-reduced-motion:reduce){.bar,#status{transition:none}} diff --git a/environments/games/web/games/touhou_remake/page.js b/environments/games/web/games/touhou_remake/page.js new file mode 100644 index 0000000000000000000000000000000000000000..ae734a241e7a29da018e1723b9403148d738d9f4 --- /dev/null +++ b/environments/games/web/games/touhou_remake/page.js @@ -0,0 +1,56 @@ +/* touhou_remake play page helpers (scarlet-practice@8). Runs after the shared _native/shell.js and only uses its public + * surface (window.nativeAPI and the page's controls); it never touches the simulation. */ +(function () { + 'use strict'; + const $ = s => document.querySelector(s), game = $('canvas'), bar = $('#bar'), overlay = $('#overlay'), frame = $('#frame'); + const ambient = $('#ambient'), status = $('#status'), help = $('#help'); + const mini = document.createElement('canvas'); mini.width = 96; mini.height = 54; const mctx = mini.getContext('2d'); // off-DOM: the page keeps one canvas + const playing = () => overlay.hidden; // shell.js hides the overlay exactly while a fight is running + const formField = () => ['INPUT', 'SELECT', 'TEXTAREA'].includes(document.activeElement && document.activeElement.tagName); + // ---- menu strip: always shown outside a fight; during a fight it fades 2 s after the pointer last moved over the top edge. + // While the player is steering with the keyboard the faded strip also stops taking clicks (no accidental restart); a scripted + // demo or replay keeps it clickable. ---- + const GAME_KEYS = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'KeyJ', 'KeyK', 'KeyQ', 'KeyE', 'ShiftLeft', 'ShiftRight']); + let shownAt = performance.now(), keyPlay = false; + const show = () => { shownAt = performance.now(); keyPlay = false; bar.classList.remove('idle', 'locked'); }; + function updateBar() { + if (!playing()) keyPlay = false; + const idle = playing() && performance.now() - shownAt > 2000 && !bar.contains(document.activeElement) && help.hidden; + bar.classList.toggle('idle', idle); bar.classList.toggle('locked', idle && keyPlay); + } + window.addEventListener('keydown', e => { if (GAME_KEYS.has(e.code) && playing() && !formField()) keyPlay = true; }, true); + frame.addEventListener('pointermove', e => { const r = frame.getBoundingClientRect(); if (e.clientY - r.top < Math.max(48, r.height * 0.12)) show(); }); + bar.addEventListener('focusin', show); + // ---- Up / Down choose the boss before a fight. Only on a fresh or finished + // session, so a paused fight is never thrown away by a movement key. ---- + window.addEventListener('keydown', e => { + if ((e.code !== 'ArrowUp' && e.code !== 'ArrowDown') || playing() || formField() || !window.nativeAPI) return; + const st = nativeAPI.state(); if (st.ticks > 0 && !st.outcome) return; + const sel = $('#case'), n = sel.options.length; sel.selectedIndex = (sel.selectedIndex + (e.code === 'ArrowDown' ? 1 : n - 1)) % n; preview(); + }, true); + // ---- keep keyboard focus on the game after a menu button (the shell ignores keys while a button has focus) ---- + bar.addEventListener('click', e => { const b = e.target.closest('button'); if (b && !['import', 'help-toggle', 'fullscreen'].includes(b.id)) setTimeout(() => { game.focus({preventScroll: true}); shownAt = performance.now(); }, 0); }); + // ---- choosing a boss or a tier before a fight shows that fight's opening frame ---- + function preview() { + if (playing() || !window.nativeAPI) return; + const seed = Number($('#seed').value), d = Number($('#difficulty').value); + if (!Number.isInteger(seed) || seed < 0) return; + try { nativeAPI.reset($('#case').value, seed, d); status.textContent = $('#case').selectedOptions[0].textContent + ' · ' + $('#difficulty').selectedOptions[0].textContent + ' (↑ / ↓ switch bosses)'; } catch (err) { status.textContent = err.message; } + } + $('#case').addEventListener('change', preview); $('#difficulty').addEventListener('change', preview); + // ---- help panel and full screen ---- + $('#help-toggle').addEventListener('click', () => { help.hidden = !help.hidden; $('#help-toggle').setAttribute('aria-expanded', String(!help.hidden)); }); + $('#fullscreen').addEventListener('click', () => { if (document.fullscreenElement) document.exitFullscreen(); else if (document.documentElement.requestFullscreen) document.documentElement.requestFullscreen(); }); + document.addEventListener('fullscreenchange', () => { $('#fullscreen').textContent = document.fullscreenElement ? 'Exit Fullscreen' : 'Fullscreen'; }); + game.addEventListener('dblclick', () => { if (!document.fullscreenElement && document.documentElement.requestFullscreen) document.documentElement.requestFullscreen(); }); + // ---- status line fades a few seconds after each message ---- + let fadeTimer = 0; + new MutationObserver(() => { status.classList.remove('faded'); clearTimeout(fadeTimer); fadeTimer = setTimeout(() => status.classList.add('faded'), 5000); }).observe(status, {childList: true, characterData: true, subtree: true}); + // ---- letterbox fill (window not 16:9): a tiny, blurred live copy of the frame instead of bars ---- + let n = 0; + (function loop() { + if ((n & 3) === 0) updateBar(); + if (n % 12 === 0 && ambient.offsetParent !== null) { mctx.drawImage(game, 0, 0, 96, 54); ambient.style.backgroundImage = 'url(' + mini.toDataURL('image/jpeg', 0.7) + ')'; } + n++; requestAnimationFrame(loop); + })(); +})(); diff --git a/environments/games/web/games/zelda_oot_remake/app3d.js b/environments/games/web/games/zelda_oot_remake/app3d.js new file mode 100644 index 0000000000000000000000000000000000000000..0e35363ebfc08836343c42112f3c008178973f81 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/app3d.js @@ -0,0 +1,67 @@ +/* Human play and exact native-input recording. Game state is owned by each module. */ +(function () { + 'use strict'; + const N=NativeBench, M=window.GAME_MODULE, $=s=>document.querySelector(s), canvas=$('canvas'), context=canvas.getContext('2d'); + let session=new N.Session(M,M.cases[0].id,1,.5),running=false,last=0,accumulator=0; + // A key pressed and released between two ticks stays held until one tick has sampled it (same latch as _native/shell.js), + // so fast taps (jump, ground pound, camera steps) are never lost. + const held=new Set(),pending=new Set(),releaseAfter=new Set(),pointerHeld=new Map(),touchHeld=new Map(); let mouse=[0,0,0],replay=null,replayIndex=0,automatic=false,script=null,scriptTick=0; + const keys={KeyW:'W',KeyA:'A',KeyS:'S',KeyD:'D',Space:'Space',ShiftLeft:'Shift',ShiftRight:'Shift',KeyJ:'J',KeyK:'K',KeyL:'L',KeyQ:'Q',KeyE:'E',KeyR:'R',ArrowUp:'W',ArrowDown:'S',ArrowLeft:'A',ArrowRight:'D'}; + document.body.dataset.game=M.id; + // Public difficulty = three tiers (2026-11-02): rebuilt from Module.tiers when the game declares it. + if(M.tiers&&$('#difficulty')){const sel=$('#difficulty'),names={easy:'Easy',normal:'Normal',hard:'Hard'};sel.textContent=''; + for(const t of ['easy','normal','hard']){const op=document.createElement('option');op.value=String(M.tiers[t]);op.textContent=names[t]+' (d='+M.tiers[t]+')';if(t==='normal')op.selected=true;sel.append(op);}} + for(const def of M.cases){const option=document.createElement('option');option.value=def.id;option.textContent=def.name;$('#case').append(option);} + const controls=Array.isArray(M.controls)?M.controls.map(value=>['',value]):Object.entries(M.controls); + for(const [key,value]of controls){const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=key;dd.textContent=value;$('dl').append(dt,dd);} + function status(value){$('#status').textContent=value;} + function clear(){held.clear();pending.clear();releaseAfter.clear();pointerHeld.clear();touchHeld.clear();mouse=[0,0,0];accumulator=0;} + function inputKeys(){return [...new Set([...held,...[...pointerHeld.values()].flatMap(keys=>[...keys]),...touchHeld.values()])].filter(key=>N.keys.includes(key)).slice(0,4);} + function draw(){ + M.draw(session.game,context); + $('#pause').textContent=running?'Pause':'Resume'; + $('#overlay').hidden=running&&!session.game.outcome; + $('#overlay strong').textContent=session.game.outcome?{win:'Challenge Complete',loss:'Challenge Failed',timeout:'Time up'}[session.game.outcome]:replay?'ReplayReplay · Paused':session.game.t?'Paused':'Are You Ready?'; + $('#overlay span').textContent=session.game.outcome?'Restart the challenge or export this replay':session.game.t?'Click Resume to return to battle':'Click Start Challenge, then click the screen to use keyboard and mouse controls.'; + } + function reset(id,seed,difficulty){running=false;automatic=false;replay=null;script=null;scriptTick=0;clear();session=new N.Session(M,id,seed,difficulty);draw();return session.snapshot();} + window.nativeAPI={reset,packet(packet){if(running)throw Error('Pause before a scripted packet');const value=session.packet(packet);draw();return value;}, + state(){return session.snapshot();},recording(){return session.export();}, + render(){draw();return canvas.toDataURL('image/png');}, + renderMetrics(){return M.renderMetrics?M.renderMetrics(context):{};}, + module(){return {id:M.id,hz:M.hz,version:M.version,cases:M.cases};}}; + function start(useScript){try{reset($('#case').value,Number($('#seed').value),Number($('#difficulty').value));automatic=useScript;running=true;status(useScript?'Script verification running':'Battle started; recording this match.');canvas.focus();draw();}catch(error){status(error.message);}} + $('#start').onclick=()=>start(false);$('#demo').onclick=()=>start(true); + $('#pause').onclick=()=>{if(session.game.outcome)return;running=!running;clear();if(running)canvas.focus();draw();}; + $('#step').onclick=()=>{running=false;if(replay)replayTick();else session.tick();draw();}; + function openReplay(data){N.Session.import(M,data);reset(data.case,data.seed,data.difficulty);replay=data;replayIndex=0;running=true;$('#case').value=data.case;status('Replay verified; starting playback.');draw();} + function replayTick(){if(replayIndex{const data=session.export(),url=URL.createObjectURL(new Blob([JSON.stringify(data)],{type:'application/json'}));const link=document.createElement('a');link.href=url;link.download=M.id+'-'+session.seed+'.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status('Current replay exported');}; + $('#import').onclick=()=>$('#file').click();$('#file').onchange=async event=>{const file=event.target.files[0];if(!file)return;try{if(file.size>12e6)throw Error('Replay file is too large');openReplay(JSON.parse(await file.text()));}catch(error){status('Import failed: '+error.message);}event.target.value='';}; + function release(){clear();if(running){running=false;status('Window lost focus; battle paused.');}draw();} + window.addEventListener('blur',release);document.addEventListener('visibilitychange',()=>{if(document.hidden)release();}); + window.addEventListener('keydown',event=>{if(['INPUT','SELECT','BUTTON'].includes(document.activeElement.tagName))return;if(keys[event.code]){event.preventDefault();held.add(keys[event.code]);pending.add(keys[event.code]);releaseAfter.delete(keys[event.code]);}if(event.code==='Escape'){running=false;clear();draw();}}); + window.addEventListener('keyup',event=>{const key=keys[event.code];if(key){event.preventDefault();if(pending.has(key))releaseAfter.add(key);else held.delete(key);}}); + canvas.oncontextmenu=event=>event.preventDefault();canvas.onpointerdown=event=>{if(event.button!==0&&event.button!==2)return;canvas.focus();const keys=pointerHeld.get(event.pointerId)||new Set();keys.add(event.button===2?'RMB':'LMB');pointerHeld.set(event.pointerId,keys);}; + // Pointer Events emits pointerup only after the final mouse button is released. + // pointermove carries changes to the button mask for chorded mouse presses. + function syncMouse(event){if(event.pointerType==='mouse'&&pointerHeld.has(event.pointerId)){const keys=new Set();if(event.buttons&1)keys.add('LMB');if(event.buttons&2)keys.add('RMB');if(keys.size)pointerHeld.set(event.pointerId,keys);else pointerHeld.delete(event.pointerId);}} + window.addEventListener('pointermove',syncMouse); + window.addEventListener('pointerup',event=>{if(event.pointerType==='mouse')syncMouse(event);else pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + window.addEventListener('pointercancel',event=>{pointerHeld.delete(event.pointerId);touchHeld.delete(event.pointerId);}); + canvas.onpointermove=event=>{if(event.buttons||document.pointerLockElement===canvas){mouse[0]+=event.movementX;mouse[1]+=event.movementY;}}; + canvas.onwheel=event=>{event.preventDefault();mouse[2]+=Math.sign(event.deltaY);}; + canvas.ondblclick=()=>canvas.requestPointerLock?.(); + document.querySelectorAll('[data-key]').forEach(button=>{button.onpointerdown=event=>{event.preventDefault();button.setPointerCapture(event.pointerId);touchHeld.set(event.pointerId,button.dataset.key);};button.onpointerup=button.onpointercancel=event=>touchHeld.delete(event.pointerId);}); + function frame(now){const delta=Math.min(.1,(now-last)/1000||0);last=now;const beforeTick=session.game.t,wasRunning=running;try{ + if(running&&!session.game.outcome){accumulator+=delta;while(accumulator>=1/M.hz&&running&&!session.game.outcome){accumulator-=1/M.hz; + if(replay)replayTick();else if(automatic){const count=M.hz/5;if(scriptTick===0)script=(M.scripted||M.oracle).call(M,session.game);const sub=Math.ceil((scriptTick+1)*6/count)-1;session.tick(script.holds[sub],script.mouse.map(value=>value/count));scriptTick=(scriptTick+1)%count;} + else{session.tick(inputKeys(),mouse.map((value,index)=>N.clamp(value,index===2?-5:-1000,index===2?5:1000)));mouse=[0,0,0];pending.clear();for(const key of releaseAfter)held.delete(key);releaseAfter.clear();}} + if(session.game.outcome){running=false;status({win:'Challenge Complete',loss:'Challenge Failed',timeout:'Challenge Timed Out'}[session.game.outcome]+' · you can export or replay this match');}} + if(session.game.t!==beforeTick||running!==wasRunning)draw(); + }catch(error){running=false;clear();status('Runtime error: '+error.message);$('#overlay').hidden=false;$('#overlay strong').textContent='Unable to continue right now';$('#overlay span').textContent=error.message;} + requestAnimationFrame(frame); + } + window.addEventListener('pagehide',()=>M.closeRenderer?.(context)); + draw();requestAnimationFrame(frame); +})(); diff --git a/environments/games/web/games/zelda_oot_remake/art/dodongo.js b/environments/games/web/games/zelda_oot_remake/art/dodongo.js new file mode 100644 index 0000000000000000000000000000000000000000..d7f92b53fa8fa8e23d03c5361b61d41ebdf16943 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/art/dodongo.js @@ -0,0 +1,79 @@ +/* Original procedural look for the fire-breathing cave lizard king: a squat armoured lizard with a ridge of horn plates, curling into a rolling ball. Lava cavern. No original model or texture is traced. + * Telegraphs (read from the state): inhaling, the mouth glows brighter and a fire lane lights up on the floor ahead (inhale 100 + 18 frames before the first flame); + * winding up a roll (27 frames) he curls and the lane to the corner he will roll to lights up; a bomb about to go off shows its blast radius. */ +(function(root){ + 'use strict'; + const R=root.ZeldaOot3D,PI=Math.PI,{canvasTex,noise}=R.tex; + const CORNERS=[[-500,-500],[-500,500],[500,500],[500,-500]],FIRE_LEN=585,FIRE_W=84,BLAST=110; + R.art.dodongo={camY:150,lookBias:.3,focusUp:40,focusR:110,lockR:70, + hits(g){const b=g.boss;if(b.act!=='damaged')return [];const y=['lay','vuln'].includes(b.act)?30:60;return [{x:b.x+Math.sin(b.yaw)*96,y:y+30,z:b.z+Math.cos(b.yaw)*96,k:b.timer/12}];}, + marker(g){const b=g.boss;return {x:b.x,y:60,z:b.z};}, + dangers(g){const b=g.boss,out=[];if(b.act==='inhale'||(b.act==='fire'&&b.af<34))out.push({x:b.x+Math.sin(b.yaw)*112,y:60,z:b.z+Math.cos(b.yaw)*112,label:'Fire breath'}); + if(b.act==='roll')out.push({x:b.x,y:60,z:b.z,label:'Roll'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(512,512,(q,w,h)=>{q.fillStyle='#4a3a30';q.fillRect(0,0,w,h);noise(q,w,h,6000,31,'rgba(20,12,8,.4)','rgba(150,110,80,.14)',6); + q.strokeStyle='rgba(30,18,10,.6)';q.lineWidth=3;for(let i=0;i<=8;i++){q.beginPath();q.moveTo(i*64,0);q.lineTo(i*64,h);q.stroke();q.beginPath();q.moveTo(0,i*64);q.lineTo(w,i*64);q.stroke();} + q.strokeStyle='rgba(255,110,40,.16)';q.lineWidth=1.5;for(let i=0;i<24;i++){let x=(i*131)%w,y=(i*71)%h;q.beginPath();q.moveTo(x,y);for(let k=0;k<4;k++){x+=((i*k*29)%40)-20;y+=((i*k*43)%40)-20;q.lineTo(x,y);}q.stroke();}},6,6); + const wallTex=canvasTex(512,256,(q,w,h)=>{q.fillStyle='#3b2a22';q.fillRect(0,0,w,h);noise(q,w,h,4000,41,'rgba(10,6,4,.45)','rgba(160,90,60,.12)',8); + for(let i=0;i<9;i++){const x=i*58+10,G=q.createLinearGradient(0,h,0,h*.4);G.addColorStop(0,'rgba(255,120,40,.5)');G.addColorStop(1,'rgba(255,120,40,0)');q.fillStyle=G;q.fillRect(x,h*.4,6+i%3*4,h*.6);}},4,1); + const lavaTex=canvasTex(256,256,(q,w,h)=>{const g=q.createRadialGradient(128,128,10,128,128,128);g.addColorStop(0,'#ffe08a');g.addColorStop(.5,'#ff7a1a');g.addColorStop(1,'#a8240c');q.fillStyle=g;q.fillRect(0,0,w,h);noise(q,w,h,900,7,'rgba(140,20,0,.35)','rgba(255,240,160,.35)',6);}); + const m=new T.MeshLambertMaterial({map:floorTex}),floor=new T.Mesh(new T.PlaneGeometry(1200,1200),m);floor.rotation.x=-PI/2;group.add(floor); + const wm=new T.MeshLambertMaterial({map:wallTex});for(let i=0;i<4;i++){const wall=new T.Mesh(new T.PlaneGeometry(1200,520),wm);const a=i*PI/2;wall.position.set(Math.sin(a)*600,260,Math.cos(a)*600);wall.rotation.y=a+PI;group.add(wall);} + const lava=new T.Mesh(new T.CircleGeometry(210,40),new T.MeshBasicMaterial({map:lavaTex}));lava.rotation.x=-PI/2;lava.position.y=1.2;group.add(lava); + const rim=new T.Mesh(new T.RingGeometry(206,232,40),new T.MeshLambertMaterial({color:0x2a1a12}));rim.rotation.x=-PI/2;rim.position.y=1.5;group.add(rim); + const rock=new T.MeshLambertMaterial({color:0x3a2a20,flatShading:true});for(let i=0;i<16;i++){const a=i*PI/8+.1,r=219,s=new T.Mesh(new T.DodecahedronGeometry(12+i%4*4,0),rock);s.position.set(Math.sin(a)*r,4,Math.cos(a)*r);s.rotation.set(i,i*2,0);group.add(s);} + // Corner pillars (outside his lap) and a dark ceiling. + for(const [x,z] of CORNERS){const p=new T.Mesh(new T.CylinderGeometry(26,34,520,8),rock);p.position.set(x*1.12,260,z*1.12);group.add(p);} + const ceil=new T.Mesh(new T.PlaneGeometry(1200,1200),new T.MeshLambertMaterial({color:0x22160f}));ceil.rotation.x=PI/2;ceil.position.y=520;group.add(ceil); + S.hemi.color.set(0xffd2b0);S.hemi.groundColor.set(0x40261a);S.hemi.intensity=2.2;S.sun.intensity=1.8;S.sun.color.set(0xffe2c0);S.glow.color.set(0xff7a2a);S.glow.intensity=2.4;S.glow.position.set(0,80,0);S.world.background=new T.Color(0x140c08);S.world.fog=new T.Fog(0x140c08,900,1900);}, + focus(g){return g.lockTarget()||g.boss;}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60,h=g.hero; + const flash=b.inv>0&&(g.t>>1)%2===0,skin=S.mat(flash?0xffffff:0x5d6b3a),skin2=S.mat(flash?0xffffff:0x46522c),belly=S.mat(flash?0xffffff:0xb8a070),horn=S.mat(0xe8dcc0),dark=S.mat(0x2a2a1a),claw=S.mat(0xf0e6cc); + // Lava pit: heat shimmer and embers rising. + for(let i=0;i<6;i++){const u=(t*.4+i/6)%1,a=i*1.7+Math.floor(t*.4+i/6)*2.3;S.flare(Math.sin(a)*150*(.3+.7*((i*37)%10)/10),10+u*160,Math.cos(a)*150*(.3+.7*((i*53)%10)/10),14*(1-u)+4,0xff8a2a,.7*(1-u));} + S.flare(0,30,0,380,0xff6a1a,.18); + S.shadow(x,0,z,b.act==='roll'?90:110); + const down=b.act==='lay'||b.act==='vuln',inh=b.act==='inhale',blow=b.act==='fire',open=inh?.3+.25*Math.sin(t*14)+.3*Math.min(1,b.af/100):blow?.8:down?.5:.1,heat=inh?Math.min(1,b.af/100):blow?1:0; + // Fire lane: faint through the inhale, bright in its last second and while the flames run. + if(inh||blow&&b.af<=34){const k=blow?1:Math.min(1,b.af/100),late=blow||b.af>80,mx=x+Math.sin(b.yaw)*112,mz=z+Math.cos(b.yaw)*112; + S.decal('strip',mx,mz,FIRE_LEN,FIRE_W,0xff3a1a,late?.42:.1+.15*k,b.yaw);S.decal('strip',mx,mz,FIRE_LEN*k,FIRE_W*.35,0xff8a3a,late?.5:.2,b.yaw);} + // Roll lane: from his position to the corner he heads for, lit while he winds up and rolls. + if(b.act==='roll'){const c=CORNERS[b.corner],dx=c[0]-x,dz=c[1]-z,L=Math.hypot(dx,dz),wind=b.timer>0,yw=Math.atan2(dx,dz); + if(L>1)S.decal('strip',x,z,L,192,0xff3a1a,wind?.18+.25*(1-b.timer/27):.3,yw);S.decal('thin',x,z,100+(wind?Math.sin(t*30)*6:0),0,0xff3a1a,.8);} + if(b.act==='roll'){const sp=b.spin,wind=b.timer>0?1-b.timer/27:1;S.push(x,y+82,z,b.yaw,sp,0);S.part('ball',skin,0,0,0,82); + for(let i=0;i<10;i++){const a=i*PI/5;S.part('cone',horn,0,Math.cos(a)*80,Math.sin(a)*80,12,30,12,0,a);} + for(const sd of [-1,1])S.part('ball',belly,sd*44,0,0,40,70,70);S.pop();if(b.timer>0)S.flare(x,y+82,z,200*wind,0xff6a2a,.35*wind); + if(b.timer===0)for(let i=0;i<3;i++)S.flare(x-Math.sin(b.yaw)*(60+i*40),20,z-Math.cos(b.yaw)*(60+i*40),60-i*14,0xb08a6a,.35-i*.1);} + else{const dead=b.act==='dead',sink=down?-30:0,tilt=down?.25:0,breathe=inh?Math.sin(t*16)*3:Math.sin(t*2)*1.5; + S.push(x,y,z,b.yaw,0,tilt); + // Body: armoured back plates over a pale belly, a heavy tail and four clawed legs. + S.part('ball',skin,0,70+sink+breathe,-10,78,62+breathe,96);S.part('ball',belly,0,48+sink,6,60,36,80); + for(let i=0;i<5;i++)S.part('ball',skin2,0,118+sink-i*3+breathe,-56+i*26,40-i*2,10,20); + for(let i=0;i<6;i++){const zz=-70+i*26;S.part('cone',horn,0,128+sink-i*2,zz,10,34-i*2,14,0,-.25);} + const sw=Math.sin(t*2.4)*.25;S.push(0,48+sink,-100,sw,0,0);S.part('ball',skin,0,0,-12,34,26,50);S.part('ball',skin2,0,-8,-56,22,16,30);S.part('cone',skin2,0,-12,-92,12,40,12,0,-PI/2-.1); + for(let i=0;i<3;i++)S.part('cone',horn,0,22-i*5,-10-i*26,6,16,8,0,-.3);S.pop(); + const gait=b.act==='walk'?Math.sin(t*5):0;for(const sd of [-1,1])for(const fz of [-1,1]){const ph=gait*sd*fz;S.part('cyl',skin,sd*62,26+sink,fz*44+ph*8,16,52,18,0,ph*.3,0);S.part('box',dark,sd*62,4,fz*44+ph*10+8,22,8,30); + for(let c=-1;c<2;c++)S.part('cone',claw,sd*62+c*7,4,fz*44+ph*10+26,3,10,3,0,PI/2);} + // Head with the mouth that eats bombs: the inside glows hotter through the inhale. + S.push(0,92+sink,90,0,down?.35:-.1,0);S.part('ball',skin,0,0,8,44,36,50);S.part('box',belly,0,-18-open*14,30,40,10,46,0,open*.6); + S.part('box',skin,0,6+open*8,38,46,12,46,0,-open*.4);for(const c of [-1,1])for(let i=0;i<4;i++)S.part('cone',claw,c*(6+i*9),-4-open*6,52,2.4,7,2.4,0,PI); + const eyeCol=inh||blow?0xff5a2a:0xffe08a;for(const sd of [-1,1]){S.part('ball',S.mat(eyeCol,{em:0xaa4400}),sd*24,22,22,9);S.part('cone',horn,sd*28,30,-4,8,36,8,0,-.8,-sd*.5);} + if(heat>0)S.part('ball',S.mat(0xffb040,{basic:true,op:.5+.5*heat,add:true}),0,-6,40,16*heat+6,10*heat+4,10); + S.pop(); + if(down&&!dead)for(let i=0;i<3;i++){const a=t*4+i*2.1;S.flare(x+Math.sin(a+b.yaw)*30+Math.sin(b.yaw)*90,150+sink,z+Math.cos(a+b.yaw)*30+Math.cos(b.yaw)*90,16,0xfff0a0,.9);} + S.pop(); + const hx=x+Math.sin(b.yaw)*112,hz=z+Math.cos(b.yaw)*112; + if(heat>0)S.flare(hx,66+sink,hz,60+80*heat,0xff7a2a,.25+.45*heat); + if(inh)for(let i=0;i<6;i++){const k=((t*2+i/6)%1),r=60+(1-k)*200,a=b.yaw+(i-2.5)*.18;S.flare(hx+Math.sin(a)*r,60+Math.sin(i*2.3)*20,hz+Math.cos(a)*r,10+(1-k)*8,0xfff2d0,.5*k);}} + // Flames: hot core, orange halo, smoke tail, scorch under each. + for(const q of b.flames){const k=q.life/26,fx=q.ox+(q.x-q.ox)*f,fz=q.oz+(q.z-q.oz)*f,fy=24+Math.sin(q.idx+t*20)*6,r=18+(1-k)*20; + S.flare(fx,fy,fz,r*3.2,k>.5?0xff9a2a:0xff4a1a,.75*k+.2);S.flare(fx,fy,fz,r*1.4,0xffe8a0,.9*k);S.flare(fx-q.vx*.5,fy+10,fz-q.vz*.5,r*2,0x6a4030,.3*(1-k));S.decal('disc',fx,fz,r*1.2,0,0xff5a1a,.25*k);} + // Bombs: dark shell, sparking fuse, and the blast radius once the fuse is short. + for(const q of b.bombs){const bx=q.ox+(q.x-q.ox)*f,by=q.oy+(q.y-q.oy)*f,bz=q.oz+(q.z-q.oz)*f,blink=q.fuse<20&&(g.t>>2)%2===0;S.shadow(bx,0,bz,12); + S.part('ball',S.mat(blink?0xff4030:0x22263a),bx,by+12,bz,12);S.part('cyl',S.mat(0x8a7a5a),bx,by+26,bz,2,6,2);S.flare(bx,by+30,bz,14+Math.sin(t*40)*4,0xffd060,1); + if(q.fuse<24)S.decal('thin',bx,bz,BLAST,0,0xff4a2a,blink?.8:.45);} + if(h.holding){const hx=h.ox+(h.x-h.ox)*f,hz=h.oz+(h.z-h.oz)*f,blink=h.bombT<20&&(g.t>>2)%2===0;S.part('ball',S.mat(blink?0xff4030:0x22263a),hx,h.y+66,hz,11);S.flare(hx,h.y+80,hz,14+Math.sin(t*40)*4,0xffd060,1); + if(h.bombT<24)S.decal('thin',hx,hz,BLAST,0,0xff4a2a,blink?.8:.45);} + } + }; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/art/ganondrof.js b/environments/games/web/games/zelda_oot_remake/art/ganondrof.js new file mode 100644 index 0000000000000000000000000000000000000000..78c4f16874a022aefd9b809a4553138241f6d3aa --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/art/ganondrof.js @@ -0,0 +1,63 @@ +/* Original procedural look for the phantom sorcerer: a floating cloaked rider-less spectre with a crescent-bladed trident, in a round gallery of blank picture frames. No original model or texture is traced. + * Telegraphs (read from the state): before a throw the trident is raised and an energy orb grows on its tip for 25 frames (21 for the slow ball), with a green flare; + * before a charge (20 frames) he rears back, his eyes and cloak flare red and a red lane points at the hero. The ball is green while it flies at the hero + * and turns pale blue once the hero sends it back, so it is always clear whose turn it is. */ +(function(root){ + 'use strict'; + const R=root.ZeldaOot3D,PI=Math.PI,{canvasTex,noise}=R.tex; + R.art.ganondrof={camY:120,lookBias:.45,focusUp:0,focusR:70,lockR:(g,L)=>g.boss.act==='throw'?100:60, + hits(g){const b=g.boss;return b.inv>0&&b.act==='stunned'&&b.ground?[{x:b.x,y:b.y+50,z:b.z,k:b.inv/10,c:0xd8ffd8}]:[];}, + marker(g){const b=g.boss;return {x:b.x,y:b.y+50,z:b.z};}, + dangers(g){const b=g.boss,out=[];if(b.ball&&b.ball.mode==='green')out.push({x:b.ball.x,y:b.ball.y,z:b.ball.z,label:'Light orbs'});if(b.act==='charge')out.push({x:b.x,y:b.y+40,z:b.z,label:'Charge'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(512,512,(q,w,h)=>{q.fillStyle='#2c3330';q.fillRect(0,0,w,h);noise(q,w,h,5000,51,'rgba(0,0,0,.35)','rgba(140,170,150,.1)',4); + q.strokeStyle='rgba(150,190,170,.25)';q.lineWidth=3;for(let r=40;r<256;r+=48){q.beginPath();q.arc(256,256,r,0,PI*2);q.stroke();} + for(let i=0;i<12;i++){q.beginPath();q.moveTo(256,256);q.lineTo(256+Math.cos(i*PI/6)*256,256+Math.sin(i*PI/6)*256);q.stroke();} + q.strokeStyle='rgba(160,255,190,.18)';q.lineWidth=6;q.beginPath();q.arc(256,256,232,0,PI*2);q.stroke();}); + const wallTex=canvasTex(512,256,(q,w,h)=>{q.fillStyle='#232a2a';q.fillRect(0,0,w,h);noise(q,w,h,2500,61,'rgba(0,0,0,.35)','rgba(120,150,140,.1)',5); + for(let i=0;i<4;i++){const x=24+i*128;q.fillStyle='#5a4426';q.fillRect(x,46,80,128);q.fillStyle='#8a6a32';q.fillRect(x+4,50,72,120);q.fillStyle='#10161a';q.fillRect(x+10,56,60,108); + const G=q.createLinearGradient(0,56,0,164);G.addColorStop(0,'rgba(80,140,110,.25)');G.addColorStop(1,'rgba(10,20,20,0)');q.fillStyle=G;q.fillRect(x+10,56,60,108);}},4,1); + S.addChamber(group,{r:330,h:520,floorTex,wallTex}); + // Columns between the frames and green torches above them (scenery, outside the floor radius). + const stone=new T.MeshLambertMaterial({color:0x3a4440,flatShading:true}),fire=new T.MeshBasicMaterial({color:0x9fff9f}); + for(let i=0;i<8;i++){const a=i*PI/4+PI/8,c=new T.Mesh(new T.CylinderGeometry(14,18,520,8),stone);c.position.set(Math.sin(a)*322,260,Math.cos(a)*322);group.add(c); + const fl=new T.Mesh(new T.SphereGeometry(7,8,6),fire);fl.position.set(Math.sin(a)*312,230,Math.cos(a)*312);group.add(fl);} + S.hemi.color.set(0xc8e8d8);S.hemi.groundColor.set(0x202826);S.hemi.intensity=2.0;S.sun.intensity=1.4;S.sun.color.set(0xd8f0e0);S.glow.color.set(0x9cff9c);S.glow.intensity=0;S.world.background=new T.Color(0x0b0f0e);S.world.fog=new T.Fog(0x0b0f0e,500,1200);}, + focus(g){const b=g.boss;return b.ball?{x:(b.x+b.ball.x)/2,y:(b.y+b.ball.y)/2,z:(b.z+b.ball.z)/2}:b;}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60; + for(let i=0;i<8;i++){const a=i*PI/4+PI/8;S.flare(Math.sin(a)*312,232+Math.sin(t*9+i)*3,Math.cos(a)*312,34,0x7aff8a,.6);} + const flash=b.inv>0&&(g.t>>1)%2===0,shock=b.act==='stunned'&&!b.ground,charging=b.act==='charge',wind=charging&&b.sub==='wind'; + const cloak=S.mat(flash||shock&&(g.t>>2)%2?0xffffff:charging?0x40243a:0x2a2440,{em:charging?0x300810:0x0a0618}),trim=S.mat(0xb08a3a,{em:0x201400}),mask=S.mat(0xd8d0c0),eyeCol=charging?0xff2a1a:0xff7a3a; + S.shadow(x,0,z,40); + // Charge lane: from him toward the hero through the wind-up. + if(wind){const h=g.hero,dx=h.x-x,dz=h.z-z,L=Math.hypot(dx,dz);S.decal('strip',x,z,Math.min(L+60,560),70,0xff3a2a,.18+.3*(1-b.t0/20),Math.atan2(dx,dz));} + const down=b.act==='stunned'&&b.ground,lean=charging?(wind?-.35:.7):down?1.1:0,throwArm=b.act==='throw'?Math.min(1,b.af/b.throwFrame):b.act==='return'?1:0,bob=Math.sin(t*3)*3; + S.push(x,y+bob,z,b.yaw,lean,0); + // Robe: layered tattered skirt, cape, shoulder plates; the hem streams in tatters that sway. + S.part('cone',cloak,0,30,0,34,80,30,0,PI);S.part('cone',cloak,0,40,-10,38,70,26,0,PI+.12);S.part('ball',cloak,0,70,0,24,26,22);S.part('cyl',trim,0,52,0,26,6,24); + for(const sd of [-1,1]){S.part('ball',trim,sd*24,82,0,12,8,12);S.part('cone',trim,sd*30,88,0,4,14,4,0,0,-sd*.8);} + for(let i=0;i<7;i++){const a=t*3+i;S.part('cone',cloak,Math.sin(i*.9)*22,-14-Math.sin(a)*6,Math.cos(i*.9)*16,7,32,7,0,PI+Math.sin(a)*.15);} + // Masked head with horns, eyes that burn hotter before a charge. + S.push(0,96,6,0,0,0);S.part('ball',mask,0,0,4,15,17,13);S.part('box',S.mat(0x1a1420),0,-4,14,10,3,2);S.part('ball',S.mat(eyeCol,{em:0xaa2010}),-5,3,14,3);S.part('ball',S.mat(eyeCol,{em:0xaa2010}),5,3,14,3); + for(const sd of [-1,1])S.part('cone',trim,sd*12,14,-2,4,24,4,0,-.3,-sd*.6);S.part('cone',cloak,0,10,-8,18,28,18,0,-.4);S.pop(); + // Trident arm: raised to throw, swung to return the ball; the orb grows on its tip until the throw frame. + S.push(-26,66,4,0,-.6-throwArm*1.4,0);S.part('cyl',cloak,0,10,0,6,26,6);S.part('cyl',trim,0,30,0,2.2,70,2.2);S.part('cone',S.mat(0xd8e0e8,{em:0x203040}),0,70,0,7,16,2); + for(const sd of [-1,1])S.part('cone',S.mat(0xd8e0e8,{em:0x203040}),sd*8,64,0,3,12,2,0,0,-sd*.5); + S.pop(); + S.pop(); + // World-space glows (outside push/pop so sprites sit in the room's frame). + const eyeY=y+bob+99,fx=Math.sin(b.yaw),fz=Math.cos(b.yaw);for(const sd of [-1,1])S.flare(x+fx*20+fz*sd*5,eyeY,z+fz*20-fx*sd*5,charging?26:14,eyeCol,charging?.9:.6); + if(b.act==='throw'&&b.afo===undefined?a:o+(a-o)*f,x=ip(b.x,b.ox),y=ip(b.y,b.oy),z=ip(b.z,b.oz),fw=b.y>100?0:34; + return {x:x+Math.sin(b.yaw)*fw,y:y>100?y-28:y+50,z:z+Math.cos(b.yaw)*fw};}, + focusR:62,lockR:(g,L)=>L.id==='eye'?(g.boss.y>100?70:56):26, + threat(g){const b=g.boss,L=g.lockTarget();if(b.y>100&&L&&L.id!=='eye')return {x:b.x,y:b.y-20,z:b.z,r:70};return null;}, + hits(g){const b=g.boss,out=[],e={x:b.x+Math.sin(b.yaw)*(b.y>100?0:34),y:b.y>100?b.y-50:b.y+(b.act==='stunned'||b.act==='damaged'?34:62),z:b.z+Math.cos(b.yaw)*(b.y>100?0:34)}; + if(b.act==='damaged')out.push({...e,k:1-b.af/16});else if(b.inv>0)out.push({...e,k:b.inv/10,c:0xd8ff8a}); + for(const k of b.kids)if(k.inv>0&&k.act==='hurt')out.push({x:k.x,y:k.y+14,z:k.z,k:k.inv/10*.6});return out;}, + marker(g){const b=g.boss;return {x:b.x,y:b.y>100?b.y-20:b.y+40,z:b.z};}, + dangers(g){const b=g.boss,out=[];if(b.act==='posture'||(b.act==='attack'&&b.sub===0))out.push({x:b.x,y:40,z:b.z,label:'Leg strike'}); + for(const k of b.kids){if(k.act==='prep'||k.act==='jump')out.push({x:k.x,y:k.y+12,z:k.z,label:'Pounce'});} + if(b.act==='fallJump'||b.act==='fallStruck')out.push({x:b.x,y:0,z:b.z,label:'Landing'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(512,512,(q,w,h)=>{q.fillStyle='#3a3a2a';q.fillRect(0,0,w,h);noise(q,w,h,5000,11,'rgba(20,24,12,.34)','rgba(120,120,80,.13)',5); + q.strokeStyle='rgba(16,20,10,.55)';for(let i=0;i<46;i++){q.lineWidth=2+i%3;q.beginPath();let x=(i*97)%w,y=(i*211)%h;q.moveTo(x,y);for(let k=0;k<5;k++){x+=((i*k*37)%90)-45;y+=((i*k*53)%90)-45;q.lineTo(x,y);}q.stroke();} + for(let i=0;i<30;i++){const x=(i*173)%w,y=(i*89)%h,G=q.createRadialGradient(x,y,1,x,y,10+i%7*3);G.addColorStop(0,'rgba(140,200,120,.22)');G.addColorStop(1,'rgba(140,200,120,0)');q.fillStyle=G;q.fillRect(x-30,y-30,60,60);}},4,4); + const wallTex=canvasTex(512,256,(q,w,h)=>{q.fillStyle='#2e2c22';q.fillRect(0,0,w,h);noise(q,w,h,3000,23,'rgba(10,12,8,.4)','rgba(110,110,70,.12)',6); + q.strokeStyle='rgba(70,84,40,.75)';q.lineCap='round';for(let i=0;i<26;i++){q.lineWidth=3+i%6;q.beginPath();let x=(i*71)%w,y=0;q.moveTo(x,y);while(y{q.fillStyle='#22221a';q.fillRect(0,0,w,h);noise(q,w,h,1600,5,'rgba(0,0,0,.3)','rgba(90,90,60,.13)',7); + q.strokeStyle='rgba(60,70,36,.6)';q.lineWidth=5;for(let i=0;i<12;i++){q.beginPath();q.moveTo(128,128);q.quadraticCurveTo(128+Math.cos(i)*90,128+Math.sin(i*1.3)*90,128+Math.cos(i*.52)*128,128+Math.sin(i*.52)*128);q.stroke();}},3,3); + S.addChamber(group,{r:430,h:360,floorTex,wallTex,ceilTex}); + // Hanging roots and glowing fungus clumps round the wall (scenery only, outside the play radius). + const root_=new T.MeshLambertMaterial({color:0x3e4a26,flatShading:true}),fungus=new T.MeshLambertMaterial({color:0x3a5a3a,emissive:0x1a3a24}); + for(let i=0;i<18;i++){const a=i*PI/9+.2,r=418,len=80+(i*37)%120,m=new T.Mesh(new T.ConeGeometry(4+i%3*2,len,5),root_);m.position.set(Math.sin(a)*r,360-len/2,Math.cos(a)*r);m.rotation.z=PI;group.add(m); + if(i%2===0){const c=new T.Mesh(new T.SphereGeometry(5+i%4,8,6),fungus);c.position.set(Math.sin(a+.1)*(r-4),20+(i*13)%60,Math.cos(a+.1)*(r-4));group.add(c);}} + S.hemi.color.set(0xb7d6a8);S.hemi.groundColor.set(0x3b3424);S.hemi.intensity=2.6;S.sun.intensity=2.2;S.sun.color.set(0xe8f2c8);S.glow.intensity=0;S.world.background=new T.Color(0x0d0f09);S.world.fog=new T.Fog(0x0d0f09,700,1500);}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60,dead=b.act==='dead',red=['posture','attack','prepEggs'].includes(b.act),stun=b.act==='stunned'||b.act==='damaged'; + const hitFlash=b.inv>0&&(g.t>>1)%2===0; + const shell=S.mat(hitFlash?0xffffff:0x4a5e46,{em:red?0x3a1008:0x0a1208}),plate=S.mat(hitFlash?0xffffff:0xa8a47e),plate2=S.mat(hitFlash?0xffffff:0xd0c89e),limb=S.mat(0x2a3324),joint=S.mat(0x6d6a50),claw=S.mat(0xd8d0b0); + const eyeCol=red?0xff3a1a:stun?0xfff2a0:0x66ffcc,glow=S.mat(eyeCol,{em:red?0xaa2200:stun?0x887a22:0x118866}); + S.shadow(x,0,z,70); + const onCeil=y>100,flip=onCeil?PI:0,climb=b.act==='climb'?-PI/2:0,base=onCeil?y-32:y+44,legK=onCeil?1.75:1.2; + // Leg-strike telegraph: a red sector of the strike's reach in front of her, filling as the rear-up runs (posture 33 frames), solid on the hit frames. + if(b.act==='posture'||(b.act==='attack'&&b.sub===0&&b.af<=13)){const k=b.act==='posture'?Math.min(1,b.af/33):1,hot=b.act==='attack'&&b.af>=7; + S.decal('sector',x,z,LEG_REACH,.8,0xff3a1a,hot?.55:.18+.22*k,b.yaw);S.decal('sector',x,z,LEG_REACH*k,.8,0xff6a3a,hot?.4:.3,b.yaw);S.decal('thin',x,z,LEG_REACH,0,0xff5a3a,.6);} + S.push(x,base,z,b.yaw,climb,flip); + const attack=b.act==='attack'&&b.sub===0?Math.sin(Math.min(1,b.af/12)*PI):0,rear=b.act==='posture'?Math.min(1,b.af/20):0,breathe=Math.sin(t*3)*1.5; + if(dead){const k=Math.max(0,b.timer/30);S.push(0,-10*(1-k),0,0,(1-k)*.4,0,.6+.4*k);} + // Abdomen: banded shell plates over a soft underbelly; the egg sac swells and glows red before eggs. + const sac=b.act==='prepEggs'?.5+.5*Math.sin(t*14):b.act==='spawnEggs'?1:0; + S.part('ball',shell,0,4+rear*5+breathe,-20,38,28,48);for(let i=0;i<3;i++)S.part('ball',plate,0,18+rear*7-i*2+breathe,-6-i*16,30-i*3,8,14); + for(let i=0;i<4;i++){const swell=b.act==='spawnEggs'&&((b.spawnT-24)>>3)===i?1.5:1,r=(22-i*4)*swell;S.part('ball',shell,0,6-i*3,-62-i*20,r,r*.86,r);S.part('ball',plate2,0,12-i*3,-62-i*20,r*.7,r*.3,r*.76);} + if(sac>0)S.flare(0,4,-90,90*sac,0xff4a2a,.5*sac); + // Head: crest horns, mandibles that open on the strike, and the single eye under a lid. + S.push(0,18+rear*18,26,0,-rear*.5-attack*.1); + S.part('ball',shell,0,0,4,28,24,26);S.part('cone',plate2,0,22,-2,7,18,7,0,-.3);S.part('cone',plate,-14,16,4,5,14,5,0,0,.5);S.part('cone',plate,14,16,4,5,14,5,0,0,-.5); + const jaw=.2+rear*.5+attack*.4;for(const sd of [-1,1])S.part('cone',claw,sd*10,-14,26,3.5,20,3.5,sd*jaw,PI/2-.4,0); + const lid=b.eyeLid||0,ey=stun?-28:0;S.part('ball',glow,0,ey,24,16);S.part('ball',S.mat(0x0a0a0a),0,ey,36,6,9,4); + S.part('hemi',S.mat(0x4a5a42),0,ey,24,17.5,17.5*Math.max(.05,lid),17.5,0,0,0);S.part('hemi',S.mat(0x4a5a42),0,ey,24,17.5,17.5*Math.max(.05,lid),17.5,0,PI,0); + if(lid<.6)S.flare(0,ey,32,(red?70:stun?54:40)*(1-lid),eyeCol,red?.8:.5); + S.pop(); + // Six jointed legs; the front pair rise and slam. + const walk=b.act==='main'||b.act==='ceilMove'?t*7:0; + for(let i=0;i<3;i++)for(const sd of [-1,1]){const ph=walk+i*2.1+(sd>0?PI:0),lift=Math.max(0,Math.sin(ph))*12; + const front=i===2,up=front?(rear*40-attack*48):0; + S.push(sd*18,6,(i-1)*18-4,PI/2*sd-(i-1)*.6*sd,0,0); + S.part('box',limb,0,8+lift*.5+up*.4,20,7,7,44,0,-.5-up*.012);S.part('ball',joint,0,22+lift+up*.8,40,6.5);const L=62*legK,ca=PI-.5+up*.012,dy=Math.cos(ca),dz=Math.sin(ca);S.part('cone',limb,0,21+lift+up*.9+dy*L/2,43+dz*L/2,5.5,L,5.5,0,ca); + S.part('cone',claw,0,21+lift+up*.9+dy*(L+5),43+dz*(L+5),3,12,3,0,ca);S.pop();} + if(dead)S.pop(); + S.pop(); + if(stun){for(let i=0;i<3;i++){const a=t*4+i*2.1;S.flare(x+Math.sin(a)*30,y+92,z+Math.cos(a)*30,16,0xfff0a0,.9);}} + // Eggs: the landing spot is marked while one falls; an egg about to hatch throbs. Larvae crouch and flash red before a pounce. + for(const k of b.kids){const kx=k.ox+(k.x-k.ox)*f,ky=k.oy+(k.y-k.oy)*f,kz=k.oz+(k.z-k.oz)*f;S.shadow(kx,0,kz,20); + if(k.act==='fall'){S.decal('thin',kx,kz,22+Math.min(30,ky*.1),0,0xffd04a,.7);S.decal('disc',kx,kz,16,0,0xffd04a,.25);} + if(k.act==='fall'||k.act==='egg'){const late=k.act==='egg'?(80-k.timer)/80:0,pulse=1+Math.sin(g.t*(.25+late*.5))*.05*(1+late*3); + S.part('ball',S.mat(0xbcc48a,{em:late>.7?0x332200:0x223300}),kx,ky+15,kz,14*pulse,18*pulse,14*pulse);S.part('ball',S.mat(0x7c8a50),kx,ky+24,kz,6,6,6);if(late>.6)S.flare(kx,ky+16,kz,36*late,0xd8ff6a,.4);} + else{const prep=k.act==='prep',jump=k.act==='jump',sq=prep?.7:1,warn=prep&&(g.t>>2)%2===0; + S.push(kx,ky+12*sq,kz,k.yaw);S.part('ball',S.mat(k.inv>0?0xffffff:warn?0xc8402a:0x46563a),0,0,0,15,12*sq,15);S.part('ball',S.mat(prep||jump?0xff5a3a:0x88ffcc,{em:prep||jump?0x882010:0x116644}),0,4,12,6); + for(let i=0;i<3;i++)for(const sd of [-1,1]){const w=Math.sin(g.t*.5+i)*.3;S.part('box',S.mat(0x2a3324),sd*14,-4+w*3,-7+i*7,16,3,3,sd*(i-1)*.4);}S.pop(); + if(prep||jump){S.flare(kx,ky+18,kz+0,30,0xff5a3a,.6);S.decal('strip',kx,kz,150,26,0xff4a2a,.28,k.yaw);}}} + } + }; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/art/morpha.js b/environments/games/web/games/zelda_oot_remake/art/morpha.js new file mode 100644 index 0000000000000000000000000000000000000000..7c6e1a7c368e867e8dfdc6669016515e29bf9485 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/art/morpha.js @@ -0,0 +1,58 @@ +/* Original procedural look for the water nucleus: a glassy red nucleus in a square pool, raising a translucent column of water that lashes out. No original model or texture is traced. + * Telegraphs (read from the state): a tentacle about to rise shows a rippling ring at its root (70-frame rise); while it sways (40-62 frames) a lane on the floor shows where the lash + * will land, filling as the sway runs out; once it curls a ring marks the grab. The nucleus glows through the water so it can be followed while it hides. */ +(function(root){ + 'use strict'; + const R=root.ZeldaOot3D,PI=Math.PI,{canvasTex,noise}=R.tex,POOL=380,A=520,REACH=360; + R.art.morpha={camY:160,lookBias:.4,focusUp:0,focusR:70,lockR:40, + hits(g){const c=g.boss.core;return c.flash>0&&c.y>-10?[{x:c.x,y:c.y+12,z:c.z,k:c.flash/15,c:0xc8f0ff}]:[];}, + marker(g){const c=g.boss.core;return c.y>-10?{x:c.x,y:c.y+12,z:c.z}:null;}, + dangers(g){const out=[];for(const t of g.boss.tents){if(t.st==='spawn'||t.st==='swing'||t.st==='attack'||t.st==='curl')out.push({x:t.x,y:20,z:t.z,label:t.st==='spawn'?'Tentacles':t.st==='curl'?'Grab':'Whip'});}return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(1024,1024,(q,w,h)=>{q.fillStyle='#3b4a52';q.fillRect(0,0,w,h);noise(q,w,h,9000,91,'rgba(0,0,0,.3)','rgba(160,200,220,.1)',5); + q.strokeStyle='rgba(20,30,36,.5)';q.lineWidth=3;for(let i=0;i<=16;i++){const p=i*w/16;q.beginPath();q.moveTo(p,0);q.lineTo(p,h);q.stroke();q.beginPath();q.moveTo(0,p);q.lineTo(w,p);q.stroke();} + const m=(A-POOL)/(2*A)*w,G=q.createLinearGradient(0,m,0,h-m);G.addColorStop(0,'#1f5e78');G.addColorStop(.5,'#2a7896');G.addColorStop(1,'#1f5e78');q.fillStyle=G;q.fillRect(m,m,w-2*m,h-2*m); + q.strokeStyle='rgba(200,240,255,.35)';q.lineWidth=2;let s=5;const r=()=>(s=(s*16807)%2147483647)/2147483647;for(let i=0;i<70;i++){const x=m+r()*(w-2*m),y=m+r()*(h-2*m),l=20+r()*50;q.beginPath();q.moveTo(x,y);q.quadraticCurveTo(x+l/2,y-6,x+l,y);q.stroke();} + q.strokeStyle='#8fa6ae';q.lineWidth=8;q.strokeRect(m,m,w-2*m,h-2*m);}); + const wallTex=canvasTex(1024,512,(q,w,h)=>{q.fillStyle='#2a383f';q.fillRect(0,0,w,h);noise(q,w,h,6000,93,'rgba(0,0,0,.3)','rgba(140,190,210,.1)',6); + q.strokeStyle='rgba(140,190,210,.25)';q.lineWidth=3;for(let i=0;i<8;i++){q.strokeRect(20+i*126,60,96,h-120);}},4,1); + const fl=new T.Mesh(new T.PlaneGeometry(2*A,2*A),new T.MeshLambertMaterial({map:floorTex}));fl.rotation.x=-PI/2;group.add(fl); + for(let i=0;i<4;i++){const wl=new T.Mesh(new T.PlaneGeometry(2*A,600),new T.MeshLambertMaterial({map:wallTex}));const a=i*PI/2;wl.position.set(Math.sin(a)*A,300,Math.cos(a)*A);wl.rotation.y=a+PI;group.add(wl);} + // A raised kerb round the pool and blue lamps in the corners (scenery only). + const kerb=new T.MeshLambertMaterial({color:0x6a828a,flatShading:true});for(let i=0;i<4;i++){const a=i*PI/2,k=new T.Mesh(new T.BoxGeometry(2*POOL+16,6,8),kerb);k.position.set(Math.sin(a)*(POOL+4),3,Math.cos(a)*(POOL+4));k.rotation.y=a;group.add(k);} + const lamp=new T.MeshBasicMaterial({color:0x9fe8ff});for(let i=0;i<8;i++){const a=i*PI/4,l=new T.Mesh(new T.SphereGeometry(10,10,8),lamp),r=i%2?A*1.38:A-2;l.position.set(Math.sin(a)*r,230,Math.cos(a)*r);if(i%2===0)group.add(l);} + S.hemi.color.set(0xd0f0ff);S.hemi.groundColor.set(0x203038);S.hemi.intensity=2.1;S.sun.intensity=1.5;S.sun.color.set(0xe8f6ff);S.glow.color.set(0xff6a5a);S.glow.intensity=0;S.world.background=new T.Color(0x0c1418);S.world.fog=new T.Fog(0x0c1418,900,2000);}, + threat(g){const b=g.boss,c=b.core;let best=null,bd=1e9;for(const t of b.tents){if(!['spawn','swing','attack','curl'].includes(t.st))continue;if((c.act==='ride'||c.act==='back')&&t.i===0)continue; + const d=Math.hypot(t.x-g.hero.x,t.z-g.hero.z);if(d-10?{x:c.x,y:c.y+12,z:c.z}:{x:t.x,y:Math.max(40,140*t.grow),z:t.z};}, + draw(S,g,f){const b=g.boss,c=b.core,t0=g.t/60,h=g.hero; + for(let i=0;i<4;i++){const a=i*PI/2;S.flare(Math.sin(a)*(A-8),230,Math.cos(a)*(A-8),90,0x9fe8ff,.5);} + // Surface shimmer over the pool. + for(let i=0;i<10;i++){const u=(t0*.3+i*.1)%1,x=Math.sin(i*2.7)*POOL*.85,z=Math.cos(i*1.9)*POOL*.85;S.decal('thin',x,z,10+u*50,0,0xd8f6ff,.35*(1-u));} + for(const t of b.tents){ + const swing=t.st==='swing',lash=t.st==='attack',curl=t.st==='curl'||t.st==='grab'||t.st==='shake'; + if(t.st==='wait'&&t.i===1&&t.t0<20||t.st==='spawn'){const k=.7+Math.sin(t0*12)*.3;S.decal('ring',t.x,t.z,50*k+20,0,0xd8f6ff,.5);S.decal('thin',t.x,t.z,90,0,0xff7a5a,.6);} + if(t.grow<=0.02&&t.st!=='spawn')continue; + // Lash lane: from the root toward where it will strike, filling as the sway runs down; bright while it lashes. + if(swing||lash&&t.ext<.6){const k=swing?Math.max(0,1-t.t0/50):1;S.decal('strip',t.x,t.z,REACH+40,84,0xff3a2a,swing?.12+.3*k:.45,t.yaw);S.decal('strip',t.x,t.z,(REACH+40)*k,30,0xff8a6a,.35,t.yaw);} + if(t.st==='curl')S.decal('thin',t.x+Math.sin(t.yaw)*REACH*.55,t.z+Math.cos(t.yaw)*REACH*.55,90,0,0xff3a2a,.8); + const water=S.mat(swing?0xc8f0ff:0x9fe2ff,{em:swing||lash?0x3a2a40:0x1a4a60,op:.62}); + const pt=fr=>{const s=Math.sin(t.sway+fr*2.2)*fr*fr*36*(1-t.ext),H=280*t.grow,dx=Math.sin(t.yaw),dz=Math.cos(t.yaw),ux=t.x+Math.cos(t.yaw)*s,uz=t.z-Math.sin(t.yaw)*s,uy=fr*H,sx=t.x+dx*fr*360,sz=t.z+dz*fr*360,sy=24+(1-fr)*(1-fr)*H*.55; + return {x:ux+(sx-ux)*t.ext,y:uy+(sy-uy)*t.ext,z:uz+(sz-uz)*t.ext};}; + const n=18;for(let i=0;i<=n;i++){const fr=i/n,p=pt(fr),r=(30-fr*16)*(.4+.6*t.grow)*(t.st==='cut'?Math.max(.2,1-fr):1);S.part('ball',water,p.x,p.y,p.z,r,r*1.15,r);if(i%3===0)S.flare(p.x,p.y,p.z,r*2.2,swing?0xffb0a0:0x9fe8ff,.22);} + const tip=pt(1);S.part('ico',S.mat(0xe8fbff,{basic:true,op:.5}),tip.x,tip.y,tip.z,14,14,14,t0*4,t0*3);S.flare(tip.x,tip.y,tip.z,swing?60:40,swing?0xff8a6a:0xc8f4ff,.6); + if(lash)for(let i=0;i<5;i++){const u=(t0*3+i/5)%1,p=pt(.4+u*.6);S.flare(p.x,p.y+10,p.z,20,0xffffff,.4*(1-u));} + S.decal('ring',t.x,t.z,46,0,0xd8f6ff,.45);for(let i=0;i<3;i++){const u=(t0*1.2+i/3)%1;S.decal('thin',t.x,t.z,46+u*60,0,0xd8f6ff,.4*(1-u));}} + // The nucleus: a red core with a glassy shell, a glow that shows through the water, and a trail while it rides the tentacle. + if(c.y>-60){const x=c.ox+(c.x-c.ox)*f,y=c.oy+(c.y-c.oy)*f,z=c.oz+(c.z-c.oz)*f,hit=c.flash>0&&(g.t>>1)%2===0,under=y<-10,stunned=c.act==='stunned'; + S.part('ball',S.mat(hit?0xffffff:0xd8323a,{em:0x6a0a10}),x,y+12,z,18,18,18);S.part('ball',S.mat(0xffffff,{basic:true,op:.35}),x,y+12,z,26,24,26); + S.part('ball',S.mat(0xffd0c8,{basic:true}),x+5,y+18,z+6,4);S.flare(x,y+12,z,under?70:90,0xff4a3a,under?.35:.55); + if(!under)S.shadow(x,0,z,20);else S.decal('disc',x,z,30,0,0xff4a3a,.3); + if(stunned&&!under)for(let i=0;i<3;i++){const a=t0*4+i*2.1;S.flare(x+Math.sin(a)*24,y+44,z+Math.cos(a)*24,14,0xfff0a0,.9);} + S.glow.position.set(x,y+20,z);S.glow.intensity=y>-10?2:.8;} + // Held by a tentacle: the squeeze shows as rings closing round the hero. + if(h.grabbed)for(let i=0;i<3;i++){const u=(t0*2+i/3)%1;S.part('ring',S.mat(0xc8f0ff,{basic:true,op:.6*(1-u),add:true}),h.x,h.y+30,h.z,40-u*20,40-u*20,40-u*20,0,-PI/2);} + } + }; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/art/twinrova.js b/environments/games/web/games/zelda_oot_remake/art/twinrova.js new file mode 100644 index 0000000000000000000000000000000000000000..de62b5d442e8ed131c5e675362e465f436903eb1 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/art/twinrova.js @@ -0,0 +1,57 @@ +/* Original procedural look for the twin-element witch: a hovering sorceress in split red-and-pale-blue robes over a sandstone disc. No original model or texture is traced. + * Her four perches are floating rune circles, not towers, so she can be followed all the way down when knocked out of the air (the rules have no tower bodies). + * Telegraphs (read from the state): arriving at a perch (25 frames) and winding up (30 frames) the sceptre of the coming element glows and a coloured line runs to the hero; + * the blast leaves on frame 12 of the throw. Blasts are fire-orange or ice-blue with trails; the hero's reflected charge is a white-gold beam, so who fired what is always clear. */ +(function(root){ + 'use strict'; + const R=root.ZeldaOot3D,PI=Math.PI,{canvasTex,noise}=R.tex,A=640,PERCH=[[580,0],[0,580],[-580,0],[0,-580]],FIRE=0xff6a1a,ICE=0x7ad8ff; + R.art.twinrova={camY:170,lookBias:.45,focusUp:0,focusR:70,lockR:70, + hits(g){const b=g.boss;return b.inv>0?[{x:b.x,y:b.y+40,z:b.z,k:b.inv/20}]:[];}, + marker(g){const b=g.boss;return {x:b.x,y:b.y+40,z:b.z};}, + dangers(g){const out=[];for(const q of g.boss.blasts)out.push({x:q.x,y:q.y,z:q.z,label:q.el?'fire':'ice'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(1024,1024,(q,w,h)=>{q.fillStyle='#6b5038';q.fillRect(0,0,w,h);noise(q,w,h,12000,101,'rgba(0,0,0,.3)','rgba(230,190,140,.12)',5); + q.strokeStyle='rgba(40,24,14,.45)';q.lineWidth=3;for(let r=60;r<512;r+=70){q.beginPath();q.arc(512,512,r,0,PI*2);q.stroke();} + const G=q.createLinearGradient(0,0,w,0);G.addColorStop(0,'rgba(255,90,40,.28)');G.addColorStop(.5,'rgba(0,0,0,0)');G.addColorStop(1,'rgba(120,200,255,.28)');q.fillStyle=G;q.fillRect(0,0,w,h); + q.strokeStyle='rgba(255,220,160,.25)';q.lineWidth=4;for(let i=0;i<8;i++){q.beginPath();q.moveTo(512,512);q.lineTo(512+Math.cos(i*PI/4)*500,512+Math.sin(i*PI/4)*500);q.stroke();}}); + const wallTex=canvasTex(1024,512,(q,w,h)=>{q.fillStyle='#2b1d18';q.fillRect(0,0,w,h);noise(q,w,h,6000,103,'rgba(0,0,0,.35)','rgba(200,150,110,.1)',6); + for(let i=0;i<12;i++){const x=i*86+20,G=q.createLinearGradient(0,h,0,0);G.addColorStop(0,i%2?'rgba(255,110,50,.35)':'rgba(110,200,255,.35)');G.addColorStop(1,'rgba(0,0,0,0)');q.fillStyle=G;q.fillRect(x,0,8,h);}},4,1); + S.addChamber(group,{r:A,h:900,floorTex,wallTex}); + S.hemi.color.set(0xffe2c8);S.hemi.groundColor.set(0x3a2418);S.hemi.intensity=2.2;S.sun.intensity=1.6;S.sun.color.set(0xfff0e0);S.glow.intensity=0;S.world.background=new T.Color(0x140c0a);S.world.fog=new T.Fog(0x140c0a,1100,2400);}, + focus(g){return g.boss;}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60,flash=b.inv>0&&(g.t>>1)%2===0,down=b.act==='stun'||b.act==='dead',h=g.hero; + // Perches: floating rune circles at her landing height, the one she is heading for lit. + PERCH.forEach(([px,pz],i)=>{const on=b.perch===i&&b.act!=='stun'&&b.act!=='dead',col=i%2?ICE:FIRE; + S.part('ring',S.mat(col,{basic:true,op:on?.85:.4,add:true}),px,372,pz,70,70,70,t*(i%2?-.6:.6),-PI/2);S.part('ring',S.mat(0xfff0d0,{basic:true,op:on?.6:.25,add:true}),px,372,pz,46,46,46,-t*.9,-PI/2); + S.flare(px,372,pz,on?160:90,col,on?.45:.2);}); + const fire=S.mat(flash?0xffffff:0xc8402a),ice=S.mat(flash?0xffffff:0x9fd6ff),skin=S.mat(0xd8c8b0),hair=S.mat(0xf2f0ea),gold=S.mat(0xe0b040,{em:0x402a00}); + S.shadow(x,0,z,50*(1+Math.max(0,400-y)/400)); + // Wind-up: the coming element is decided only at the end of the wind-up (W4), so the wind-up shows both sceptres; the throw shows the chosen one. + const arrive=b.act==='arrive',wind=b.act==='windup',thr=b.act==='throw'&&b.af<12,el=b.act==='throw'?b.element:-1,ch=arrive?1-b.t0/25:wind?1:thr?1:0; + if(ch>0){const dx=h.x-x,dz=h.z-z,L=Math.hypot(dx,dz),col=el===1?FIRE:el===0?ICE:0xffe0a0;S.decal('strip',x,z,L,40,col,(wind||thr)?.3:.12,Math.atan2(dx,dz));S.decal('thin',h.x,h.z,40,0,col,(wind||thr)?.8:.4);} + S.push(x,y,z,b.yaw,down?1.2:0,0); + S.part('cone',fire,-12,10,0,26,70,30,0,PI,.15);S.part('cone',ice,12,10,0,26,70,30,0,PI,-.15); + for(let i=0;i<5;i++){const a=t*3+i;S.part('cone',i%2?ice:fire,-16+i*8,-24-Math.sin(a)*5,Math.cos(i)*8,6,26,6,0,PI+Math.sin(a)*.2);} + S.part('ball',fire,-9,48,0,15,20,15);S.part('ball',ice,9,48,0,15,20,15);S.part('ball',skin,0,74,4,13); + for(const sd of [-1,1]){S.part('cone',hair,sd*10,88,-4,8,30,8,0,-.2,sd*.6);S.part('ball',S.mat(sd<0?0xff5a2a:0x6ac8ff,{basic:true}),sd*5,78,15,2.5);} + S.part('torus',gold,0,96,0,10,10,10,0,PI/2);S.part('cone',gold,0,104,0,6,14,6); + for(const sd of [-1,1]){S.push(sd*34,50,6,0,-.3-(ch>0?.6:0),sd*.4);S.part('cyl',gold,0,0,0,2.4,70,2.4);S.part('ico',S.mat(sd<0?0xff7a2a:0x9fe2ff,{basic:true,op:.9}),0,40,0,7+(ch>0&&(el<0||(el===1)===(sd<0))?6*ch:0));S.pop();} + S.pop(); + // World-space glows at the two sceptre heads. + const c=Math.cos(b.yaw),s=Math.sin(b.yaw);for(const sd of [-1,1]){const lit=ch>0&&(el<0||(el===1)===(sd<0)),px=x+c*sd*34+s*20,pz=z-s*sd*34+c*20,py=y+(down?30:92); + S.flare(px,py,pz,lit?40+80*ch:26,sd<0?FIRE:ICE,lit?.9:.45);} + if(ch>0){S.glow.position.set(x,y+40,z);S.glow.color.set(el===1?FIRE:el===0?ICE:0xffd0a0);S.glow.intensity=1+2*ch;}else S.glow.intensity=0; + if(down)for(let i=0;i<3;i++){const a=t*4+i*2.1;S.flare(x+Math.sin(a)*30,y+70,z+Math.cos(a)*30,16,0xfff0a0,.9);} + // Blasts: element-coloured cores with a long trail and a marker under them. + for(const q of b.blasts){const bx=q.ox+(q.x-q.ox)*f,by=q.oy+(q.y-q.oy)*f,bz=q.oz+(q.z-q.oz)*f,col=q.el?FIRE:ICE; + S.part('ico',S.mat(q.el?0xffd0a0:0xe8faff,{basic:true}),bx,by,bz,12,12,12,t*6,t*5);S.bolt(bx,by,bz,q.ox,q.oy,q.oz,14,q.el?0xffe0b0:0xf0fcff,col,6); + for(let k=0;k<3;k++){const a=t*20+k*2.1;S.flare(bx+Math.sin(a)*16,by+Math.cos(a)*16,bz+Math.cos(a*1.3)*16,10,col,.6);}S.shadow(bx,0,bz,14);S.decal('thin',bx,bz,22,0,col,.6);} + // The hero's reflected charge: a white-gold beam with the soaked element's rim. + for(const sh of b.shots){const sx=sh.ox+(sh.x-sh.ox)*f,sy=sh.oy+(sh.y-sh.oy)*f,sz=sh.oz+(sh.z-sh.oz)*f;S.beam(sh.ox,sh.oy,sh.oz,sx,sy,sz,14,0xfff0b0,.9,4);S.bolt(sx,sy,sz,sh.ox,sh.oy,sh.oz,16,0xffffff,sh.el?FIRE:ICE,4);} + // Charge stored on the mirror shield: stacked rings round the hero in the soaked element. + if(b.charge>0){for(let k=0;k.2)S.part('ball',S.mat(0xffc15a,{basic:true,op:.85,add:true}),0,-7,36,8+Math.sin(t*40)*1.5);} + // Breath: a cone of fire from the jaws, hot core and orange halo glows along it. + function flame(S,x,y,z,a,pitch,len,t){const dx=Math.sin(a)*Math.cos(pitch),dy=-Math.sin(pitch),dz=Math.cos(a)*Math.cos(pitch); + for(let i=0;i<10;i++){const k=(i+((t*12)%1))/10,w=18+k*90,j=Math.sin(t*40+i*1.7)*6;S.flare(x+dx*len*k+j,y+dy*len*k,z+dz*len*k-j,w*1.4,i<3?0xffe08a:0xff6a1a,.85-k*.4);S.flare(x+dx*len*k,y+dy*len*k,z+dz*len*k,w*.6,0xfff4c0,.8-k*.6);}} + R.art.volvagia={camY:150,lookBias:.42,focusUp:0,focusR:70,lockR:60, + focus(g,f){const b=g.boss;if(b.act==='under'||b.act==='burrow'||b.act==='peek')return {x:b.x,y:30,z:b.z};if(b.act==='fly'){const h=g.hero;return {x:b.mode==='rocks'?b.x:h.x,y:0,z:b.mode==='rocks'?b.z:h.z};} + const down=b.act==='vuln'||b.act==='dead';return {x:b.x+Math.sin(b.yaw)*46,y:118*(down?.35:1),z:b.z+Math.cos(b.yaw)*46};}, + threat(g){const b=g.boss;if(b.act!=='fly')return null;return {x:b.x,y:Math.min(b.y,b.mode==='rocks'?600:420),z:b.z,r:70};}, + hits(g){const b=g.boss;if(!(b.inv>0)||b.act==='fly'||b.act==='under')return [];const down=b.act==='vuln'||b.act==='dead'; + return [{x:b.x+Math.sin(b.yaw)*46,y:b.y+118*(down?.35:1),z:b.z+Math.cos(b.yaw)*46,k:Math.min(1,b.inv/(b.exposed&&b.inv<=6?6:30)),c:0xffd8a0}];}, + marker(g){const b=g.boss;return b.act==='under'||b.act==='burrow'?null:{x:b.x,y:b.act==='fly'?b.y:90,z:b.z};}, + dangers(g){const b=g.boss,out=[];if(b.act==='under'||b.act==='peek')out.push({x:b.x,y:10,z:b.z,label:'Hole'});if(b.act==='fly')out.push({x:b.x,y:b.y,z:b.z,label:'Flying'}); + for(const q of b.rocks)out.push({x:q.x,y:2,z:q.z,label:'Rockfall'});return out;}, + room(S,group){const T=root.THREE; + const floorTex=canvasTex(1024,1024,(q,w,h)=>{q.fillStyle='#3a2a24';q.fillRect(0,0,w,h);noise(q,w,h,14000,71,'rgba(0,0,0,.35)','rgba(190,120,80,.1)',6); + q.strokeStyle='rgba(255,120,40,.3)';q.lineWidth=2;let s=9;const r=()=>(s=(s*16807)%2147483647)/2147483647;for(let i=0;i<46;i++){let x=r()*w,y=r()*h;q.beginPath();q.moveTo(x,y);for(let j=0;j<6;j++){x+=(r()-.5)*70;y+=(r()-.5)*70;q.lineTo(x,y);}q.stroke();} + for(const a of [-H,0,H])for(const c of [-H,0,H]){const x=512+a/526*512,y=512+c/526*512,G=q.createRadialGradient(x,y,6,x,y,74);G.addColorStop(0,'#ff9a3a');G.addColorStop(.3,'#a8381a');G.addColorStop(.52,'#160c0a');G.addColorStop(.78,'#2a1a14');G.addColorStop(1,'rgba(42,26,20,0)');q.fillStyle=G;q.beginPath();q.arc(x,y,74,0,PI*2);q.fill();}}); + const wallTex=canvasTex(1024,512,(q,w,h)=>{q.fillStyle='#21140f';q.fillRect(0,0,w,h);noise(q,w,h,9000,73,'rgba(0,0,0,.4)','rgba(150,90,60,.1)',7); + for(let i=0;i<9;i++){const x=40+i*114,G=q.createLinearGradient(0,h,0,h*.3);G.addColorStop(0,'rgba(255,120,40,.65)');G.addColorStop(1,'rgba(255,90,20,0)');q.fillStyle=G;q.fillRect(x,h*.3,10+i%3*7,h*.7);}},3,1); + const ceilTex=canvasTex(256,256,(q,w,h)=>{q.fillStyle='#1a100c';q.fillRect(0,0,w,h);noise(q,w,h,3000,79,'rgba(0,0,0,.4)','rgba(150,90,60,.14)',6);}); + S.addChamber(group,{r:520,h:820,floorTex,wallTex,ceilTex}); + // Rim rocks round each vent and stalactites over the room (scenery; the vents stay flat, as the rules have no lip). + const rock=new T.MeshLambertMaterial({color:0x2e201a,flatShading:true}); + for(const a of [-H,0,H])for(const c of [-H,0,H])for(let i=0;i<6;i++){const u=i*PI/3+a*.01,m=new T.Mesh(new T.DodecahedronGeometry(7+i%3*3,0),rock);m.position.set(a+Math.sin(u)*64,3,c+Math.cos(u)*64);m.rotation.set(i,i*2,0);group.add(m);} + for(let i=0;i<14;i++){const a=i*PI/7,r=200+(i*67)%280,len=60+(i*41)%110,m=new T.Mesh(new T.ConeGeometry(10+i%4*4,len,6),rock);m.position.set(Math.sin(a)*r,820-len/2,Math.cos(a)*r);m.rotation.z=PI;group.add(m);} + S.hemi.color.set(0xffd8b8);S.hemi.groundColor.set(0x6a2a14);S.hemi.intensity=2.2;S.sun.intensity=1.5;S.sun.color.set(0xffe0c0);S.glow.color.set(0xff7a2a);S.glow.intensity=0;S.world.background=new T.Color(0x120806);S.world.fog=new T.Fog(0x120806,900,2000);}, + draw(S,g,f){const b=g.boss,x=b.ox+(b.x-b.ox)*f,y=b.oy+(b.y-b.oy)*f,z=b.oz+(b.z-b.oz)*f,t=g.t/60,flash=b.inv>0&&(g.t>>1)%2===0,h=g.hero; + // Vent embers everywhere; the vent he is under glows, smokes and rings, brighter on the true emergence. + for(const a of [-H,0,H])for(const c of [-H,0,H]){const u=(t*.6+(a+c)*.001)%1;S.flare(a,8+u*60,c,18*(1-u)+6,0xff7a2a,.35*(1-u));} + if(b.act==='under'||b.act==='peek'){const k=.7+Math.sin(t*14)*.3,real=b.act==='peek'&&b.fakes===0;S.decal('ring',b.x,b.z,70*k,0,0xffa040,.6);S.decal('thin',b.x,b.z,real?120:80,0,real?0xff3a1a:0xffa040,real?.8:.5); + S.flare(b.x,30,b.z,140,0xff7a2a,.5);for(let i=0;i<4;i++){const u=(t*.8+i/4)%1;S.flare(b.x+Math.sin(i*2.1)*12,10+u*130,b.z+Math.cos(i*2.1)*12,30+u*50,0x6a5a50,.35*(1-u));}} + if(b.act==='burrow'&&y<-40)S.flare(b.x,20,b.z,120,0xff7a2a,.4); + S.glow.intensity=0; + if(b.act==='fly'){const body=[{x,y,z},...b.trail]; + for(let i=1;i3)for(const sd of [-1,1]){const s=body[3];S.part('cone',S.mat(0x3a2a24),s.x+Math.cos(b.yaw)*sd*40,s.y+10+Math.sin(t*8)*10,s.z-Math.sin(b.yaw)*sd*40,8,70,30,b.yaw,0,sd*(1.2+Math.sin(t*8)*.3));} + S.push(x,y,z,b.yaw,.2,0);head(S,g,b,{flash,exposed:false,open:b.breathT>0?1:.15});S.pop();S.flare(x,y,z,150,0xff7a2a,.4);S.glow.position.set(x,y,z);S.glow.color.set(0xff7a2a);S.glow.intensity=2; + if(b.breathT>0){const off=Math.atan2(y-h.y,Math.max(40,Math.hypot(h.x-x,h.z-z)));flame(S,x+Math.sin(b.yaw)*50,y-8,z+Math.cos(b.yaw)*50,b.yaw,off,FIRE,t);S.glow.position.set(x,y,z);S.glow.intensity=3; + S.decal('sector',x,z,FIRE,.35,0xff3a1a,.35,b.yaw);} + S.shadow(x,0,z,50);} + else if(b.act!=='under'){const down=b.act==='vuln'||b.act==='dead',hy=118*(down?.35:1),n=7,fwd=46; + for(let i=0;i0)S.flare(sx,sy,sz,r*2.2,0xff5a1a,.3);} + const fireAnim=b.act==='fire',pre=fireAnim&&b.af<25,open=fireAnim?Math.min(1,b.af/20):b.act==='swipe'?.5:b.act==='dead'?.8:.1,hx=x+Math.sin(b.yaw)*fwd,hz=z+Math.cos(b.yaw)*fwd,hh=y+hy; + S.push(hx,hh,hz,b.yaw,down?.5:0,down?.3:0);head(S,g,b,{flash,exposed:b.exposed,open});S.pop(); + if(b.exposed)S.flare(hx,hh+10,hz,60,0xff6a3a,.4+.2*Math.sin(t*10)); + if(down)for(let i=0;i<3;i++){const a=t*4+i*2.1;S.flare(hx+Math.sin(a)*30,hh+38,hz+Math.cos(a)*30,16,0xfff0a0,.9);} + // Breath wind-up: the jaws fill with fire and the cone it will sweep (head turn up to 0x1F40 either way) shows on the floor. + if(pre){const k=b.af/25;S.flare(hx+Math.sin(b.yaw)*34,hh-6,hz+Math.cos(b.yaw)*34,30+70*k,0xff8a2a,.5+.4*k);S.decal('sector',x,z,FIRE+fwd,ARC+.24,0xff3a1a,.12+.25*k,b.yaw);} + // Claws on the rim; within reach they rise and the swipe arc shows. + const near=b.act==='idle'&&Math.hypot(h.x-b.x,h.z-b.z)=8?.5:.22,b.yaw); + for(const sd of [-1,1]){S.push(x,y,z,b.yaw,0,0);S.part('box',S.mat(0x6a4a3a,{em:0x2a0a00}),sd*(44+sw*30),22+sw*30,16+sw*70,16,14,46,sd*sw*.5,-sw*.5);for(let i=-1;i<2;i++)S.part('cone',S.mat(0xe0d4b8),sd*(44+sw*30)+i*7,16+sw*30,42+sw*90,3,16,3,0,PI/2);S.pop();} + S.shadow(x,0,z,64); + if(fireAnim&&b.af>=25&&b.af<70){const a=b.yaw+(b.breath||0);flame(S,hx+Math.sin(a)*34,hh-6,hz+Math.cos(a)*34,a,Math.atan2(hh,FIRE),FIRE,t);S.glow.position.set(hx,hh,hz);S.glow.intensity=4;S.decal('sector',x,z,FIRE+fwd,.24,0xff4a1a,.4,a);}} + // Rocks: a molten core, a smoke tail, and the landing circle sized to the hit radius. + for(const q of b.rocks){const ry=q.oy+(q.y-q.oy)*f,k=Math.max(0,Math.min(1,1-ry/600));S.part('ico',S.mat(0x5a4438,{em:0x601a08}),q.x,ry,q.z,q.r,q.r*.8,q.r,t*3,t*2);S.flare(q.x,ry,q.z,q.r*3,0xff6a1a,.5);S.flare(q.x,ry+40,q.z,q.r*2.4,0x5a4a40,.35); + S.decal('ring',q.x,q.z,q.r+14,0,0xff3a1a,.25+.45*k);S.decal('thin',q.x,q.z,(q.r+14)*(2-k),0,0xff7a2a,.7*k);S.shadow(q.x,0,q.z,q.r+6);} + } + }; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/dodongo.js b/environments/games/web/games/zelda_oot_remake/bosses/dodongo.js new file mode 100644 index 0000000000000000000000000000000000000000..b8b5276f727a775df651ce29d8a19a8097247b6e --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/dodongo.js @@ -0,0 +1,130 @@ +/* King Dodongo (z_boss_dodongo.c, z_en_bom.c). Original mechanics, own code. Frame counts are 20 Hz logic frames. + * The room is a square lap: he walks and rolls along the four corners of a 1000-unit square around a central lava pit, as in the source. Coordinates are centred on that square. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,MOVE}=M.helpers,PI=Math.PI; + const HALF=500,CORNERS=[{x:-HALF,z:-HALF},{x:-HALF,z:HALF},{x:HALF,z:HALF},{x:HALF,z:-HALF}]; // source order (D2), recentred + // A*: approximations for data found only in the assets. Everything else is a source value. + const D={inhaleFrames:100,eatFrom:21,eatTo:81,mouthBox:40,explode:35,vulnerable:100,rollWind:27,rollJump:15,rollEndJump:20,fire:50,fireFrom:18,fireTo:34,breakWalk:50,invHit:5,inhaleRange:500,cornerNear:200,yawRange:0x38e3, + walkScale:.7,rollScale:3,bombFuse:70,bombGravity:4,bombHold:44, + layFrames:12,getUpFrames:18,damagedFrames:12,bodyR:88,rollR:96,mouthFwd:112,mouthY:64,headFwd:96,headR:44,standOff:70,fireStep:15,fireLife:26,fireR:30,blastR:110,throwSpeed:9,throwVy:7,pickupCd:18,pitR:210,roomHalf:600}; // A: his body (88) covers the strip between his lap (500) and the wall, so the only lane he cannot reach is the inner one by the pit + const TUNE={ + hp:[8,8,20,48], // BossBench: scaled to the tier windows (T1). Source 12; the d = 0 anchor is easy's 8 so health never falls as d rises (dsweep found 12 > 10 > 8 below easy) + bombDmg:[2,2,2,2], // source (D1), kept in every tier: only his vulnerable window grows the fight + touch:[8,8,12,16], // contact and rolling + fireDmg:[8,8,12,16], + rollCap:[1,1,1.08,1.16], // speed factor on the source roll + vuln:[100,100,90,80] // frames down after a bomb + }; + const setAct=(b,a,t)=>{b.act=a;b.timer=t===undefined?0:t;b.af=0;}; + function setupWalk(b){setAct(b,'walk',0);b.walkAnim=0;} + function setupRoll(b){setAct(b,'roll',D.rollWind);b.walls=0;} + const mouth=b=>({x:b.x+Math.sin(b.yaw)*D.mouthFwd,y:b.y+D.mouthY,z:b.z+Math.cos(b.yaw)*D.mouthFwd}); + const head=b=>({x:b.x+Math.sin(b.yaw)*D.headFwd,y:b.y+(['lay','vuln'].includes(b.act)?30:60),z:b.z+Math.cos(b.yaw)*D.headFwd}); + // Source: smooth step with a capped increment (scale s on the remaining distance, then at most `step`), written directly to the coordinate, so no x 1.5 here. + const smooth=(v,t,s,step)=>{const d=(t-v)*s;return v+N.clamp(d,-step,step);}; + function lane(b,h,turn){const a=b.yaw+turn,dx=h.x-b.x,dz=h.z-b.z,side=Math.cos(a)*dx-Math.sin(a)*dz,ahead=Math.sin(a)*dx+Math.cos(a)*dz;return Math.abs(side)<150&&ahead>=100&&ahead<=2000?1:0;} + function arriveNext(b){b.corner=(b.corner+(b.dir?3:1))%4;} + function move(g,b,scale,cap,accel,near,fine){const c=CORNERS[b.corner];b.spd=Math.min(cap,b.spd+accel);b.x=smooth(b.x,c.x,fine,b.spd);b.z=smooth(b.z,c.z,fine,b.spd); + const dx=c.x-b.x,dz=c.z-b.z;if(Math.abs(dx)>1e-3||Math.abs(dz)>1e-3)b.yaw=wrap(b.yaw+N.clamp(wrap(Math.atan2(dx,dz)-b.yaw)/5,-(scale*b.turn)*M.helpers.BIN,(scale*b.turn)*M.helpers.BIN)); + return Math.abs(dx)<=near&&Math.abs(dz)<=near;} + function hitBoss(g,b,dmg){b.hp-=dmg;b.inv=D.invHit;g.ev('dodongo_hit');if(b.hp>0)setAct(b,'damaged',D.damagedFrames);else killCheck(g,b);} + function killCheck(g,b){if(b.hp<=0&&b.act!=='dead'){b.hp=0;setAct(b,'dead',45);g.ev('boss_dead');g.fxAdd('burst',b.x,70,b.z,16,{r:90,color:0xff8a3a});}} + function explodeBomb(g,q){g.ev('bomb_blast');g.fxAdd('burst',q.x,q.y+10,q.z,12,{r:D.blastR*.8,color:0xffb04a});g.fxAdd('ring',q.x,3,q.z,10,{r:D.blastR}); + const h=g.hero;if(Math.hypot(q.x-h.x,q.z-h.z){q.ox=q.x;q.oy=q.y;q.oz=q.z;q.fuse--; + if(q.state==='air'){q.vy-=D.bombGravity*.25;q.x+=q.vx*MOVE;q.z+=q.vz*MOVE;q.y+=q.vy*MOVE; + if(q.y<=0){q.y=0;q.state='ground';q.vx=q.vz=q.vy=0;g.ev('bomb_land');}} + if(b.act==='inhale'&&b.af>D.eatFrom&&b.af0)b.next--;b.turn=2000;if(move(g,b,D.walkScale,D.walkScale*4,D.walkScale*.25,5,.3)){b.spd=0;arriveNext(b);} + if(b.next===0){const near=hd(b,h)Math.abs(b.x-p.x)=D.fireFrom&&b.af<=D.fireTo){const m=mouth(b),idx=b.af-D.fireFrom;b.flames.push({x:m.x,y:m.y-12,z:m.z,ox:m.x,oy:m.y-12,oz:m.z,vx:Math.sin(b.yaw)*D.fireStep,vz:Math.cos(b.yaw)*D.fireStep,life:D.fireLife,idx});} + if(b.timer===0){setupRoll(b);g.ev('dodongo_roll');}}, + roll(g,b,h){b.turn=2000;const t=b.timer;if(t===10)b.vy=D.rollJump; + if(t===0){b.turn=3000;if(move(g,b,D.rollScale,D.rollScale*5*g.T.rollCap,D.rollScale*.25,15,1)){b.walls++; + if(b.walls>=2){if(b.switchDir)b.dir=b.dir?0:1;b.spd=0;setupWalk(b);b.next=0;b.vy=D.rollEndJump;g.ev('dodongo_roll_end');g.fxAdd('ring',b.x,3,b.z,12,{r:140});}else b.vy=D.rollJump; + arriveNext(b);}}}, + explode(g,b){b.af++;if(b.timer===0){setAct(b,'lay',0);g.ev('dodongo_blast');g.fxAdd('burst',b.x,80,b.z,12,{r:66,color:0xffb04a});b.hp-=D.bomb||g.T.bombDmg;if(b.hp<=0)b.hp=1;}}, // the source's bomb can never kill: it leaves 1 (D1) + lay(g,b){b.af++;if(b.af>=D.layFrames)setAct(b,'vuln',Math.round(g.T.vuln));}, + vuln(g,b){if(b.timer===0)setAct(b,'getup',D.getUpFrames);}, + getup(g,b){if(b.timer===0){setupRoll(b);g.ev('dodongo_roll');}}, + damaged(g,b){if(b.timer===0){setupRoll(b);g.ev('dodongo_roll');}}, + dead(g,b){if(b.timer===0)g.outcome='win';} + }; + M.register('dodongo',{ + cases:[{id:'zelda/lava_lizard_king',name:'Lava-Cave Fire Lizard King (Young Swordsman · Bomb Fruit)'}], + arena:{r:900,square:600,ceil:520,start:[0,-300]},hearts:6,age:'child',camDist:330,tune:TUNE,art:'dodongo', + item:{kind:'bomb',name:'Bomb Fruit: pick up / throw'},threats:{dodongo_inhale:1,dodongo_roll:1,dodongo_fire:1,hero_hurt:1}, + init(g){const b=g.boss,k=Math.floor(g.rand()*4),dir=g.rand()<.5?0:1,p=CORNERS[k],nx=(k+(dir?3:1))%4;Object.assign(b,{x:p.x,y:0,z:p.z,ox:p.x,oy:0,oz:p.z,vy:0,yaw:Math.atan2(CORNERS[nx].x-p.x,CORNERS[nx].z-p.z),spd:0,turn:2000,corner:nx,dir,walls:0,next:0,timer:0,af:0,walkAnim:0,inv:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp), + playerNear:0,switchDir:0,bombs:[],flames:[],lastSlash:-1,stock:0,fired:0,spin:0});setupWalk(b); + const h=g.hero;h.holding=false;h.bombT=0;h.x=-p.x*.55;h.z=-p.z*.55;h.ox=h.x;h.oz=h.z;h.yaw=h.face=Math.atan2(-h.x,-h.z);}, + // The item key takes a fresh bomb flower and, while one is held, throws it forward. Held too long it goes off in hand (fuse 70). + useItem(g){const h=g.hero,b=g.boss; + if(!h.holding){h.holding=true;h.bombT=D.bombFuse;h.itemCd=D.pickupCd;g.ev('bomb_pick');return;} + const y0=h.y+34;b.bombs.push({state:'air',x:h.x+Math.sin(h.face)*16,y:y0,z:h.z+Math.cos(h.face)*16,ox:h.x,oy:y0,oz:h.z,vx:Math.sin(h.face)*D.throwSpeed,vy:D.throwVy,vz:Math.cos(h.face)*D.throwSpeed,fuse:h.bombT}); + h.holding=false;h.bombT=0;h.itemCd=D.pickupCd;g.ev('bomb_throw');}, + update(g){const b=g.boss,h=g.hero;if(b.inv>0)b.inv--;if(b.timer>0)b.timer--; + if(h.holding&&!g.events.includes('bomb_pick')&&--h.bombT<=0){h.holding=false;explodeBomb(g,{x:h.x,y:h.y,z:h.z});} + // The walk's two sensors (D5): the player straight ahead (within 150 to the side, 100-2000 in front) lets him inhale; straight behind makes the next roll turn back. + b.playerNear=lane(b,h,0);b.switchDir=lane(b,h,PI); + ACT[b.act](g,b,h);if(g.outcome)return; + b.vy-=2;b.y=Math.max(0,b.y+b.vy*MOVE);if(b.y===0&&b.vy<0)b.vy=0; + if(Math.hypot(h.x,h.z){q.ox=q.x;q.oy=q.y;q.oz=q.z;q.x+=q.vx*MOVE;q.z+=q.vz*MOVE;q.life--;if(Math.hypot(q.x-h.x,q.z-h.z)0;}); + if(b.act==='roll'&&b.timer===0)b.spin+=2000*M.helpers.BIN; + const s=g.strike(); + if(s&&s.id!==b.lastSlash&&(b.act==='vuln'||b.act==='lay')&&b.inv===0){const q=head(b);if(g.swordReach(q.x,q.y,q.z,D.headR)){b.lastSlash=s.id;hitBoss(g,b,s.dmg);}} + const R=b.act==='roll'?D.rollR:D.bodyR; + if(!['lay','vuln','dead','explode'].includes(b.act)&&Math.hypot(b.x-h.x,b.z-h.z)h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + // A trial for the next half second: is this stick direction hit, and how close does it pass? + const trial=(keys,n=30)=>{const s=cloneGame(h);let hurt=0;for(let i=0;i{let best=[],bs=-1e9;for(const o of [0,.5,-.5,1,-1,1.6,-1.6,2.4,-2.4,PI]){const a=wrap(yaw+o),k=stickTo(h,a),r=trial([...base,...k]),sc=(r.hurt?-1e4:0)-Math.abs(o)*10+Math.min(hd(r.s.hero,r.s.boss),220)*.3;if(sc>bs){bs=sc;best=k;}}return best;}; + // Stay on the inside of his lap, where the roll cannot reach: the pit edge between centre and the side he is on is the safe track (D3). + const dangerous=b.act==='roll'||b.act==='getup'||b.act==='damaged'; + if(b.act==='vuln'||b.act==='lay'){const q=head(b),d=Math.hypot(q.x-H.x,q.z-H.z),reach=M.constants.reach[H.age]+D.headR-8,keys=['Shift']; + const jump=reach+70,lock=H.lock==='head'; + if(lock&&free&&b.inv===0&&d>reach-25&&d12))return ['Shift',...tap('Space')]; + if(d>reach&&free)keys.push(...stickTo(h,yawTo(H,q)));else if(b.inv===0)keys.push(...tap('J'));return keys;} + if(dangerous&&b.timer>0&&b.act!=='roll'){const c={x:0,z:0},back=hd(H,b);if(back<300&&free)return steer(yawTo(b,H),[]);return [];} + if(b.act==='roll'||(b.act==='walk'&&b.timer===0&&hd(H,b)<260)){if(!free)return [];let best=[],bs=-1e9; + for(const o of [0,.6,-.6,1.2,-1.2,1.9,-1.9,2.6,-2.6,PI]){const a=wrap(Math.atan2(-H.x,-H.z)+o),k=stickTo(h,a);for(const roll of [false,true]){const s=cloneGame(h);let hurt=0,minD=1e9; + for(let i=0;i<48&&!s.outcome;i++){simTick(s,roll&&i<3?[...k,'Space']:k);minD=Math.min(minD,hd(s.hero,s.boss));if(s.events.includes('hero_hurt')){hurt=1;break;}} + const r=Math.hypot(s.hero.x,s.hero.z),sc=(hurt?-1e4:0)+Math.min(minD,260)-Math.abs(r-(D.pitR+70))*.4-(roll?25:0)-Math.abs(o)*3;if(sc>bs){bs=sc;best=roll?[...k,'Space']:k;}}} + return best.includes('Space')&&h.lastKeys.includes('Space')?best.filter(x=>x!=='Space'):best;} + if(b.act==='explode'){const q=head(b),spot={x:q.x+Math.sin(b.yaw)*95,z:q.z+Math.cos(b.yaw)*95};if(hd(H,spot)>12&&free)return ['Shift',...stickTo(h,yawTo(H,spot))];return ['Shift'];} + if(b.act==='fire'){const fwd=Math.abs(wrap(yawTo(b,H)-b.yaw));if(fwd<.9&&hd(H,b)<520&&free)return steer(wrap(yawTo(b,H)+(wrap(yawTo(b,H)-b.yaw)>=0?1.3:-1.3)),[]);return [];} + // Inhale: he stands still, so walk to a point in line with the mouth and let a copy say when a throw now lands in the mouth inside the eating frames. + const m=mouth(b),want={x:m.x+Math.sin(b.yaw)*170,z:m.z+Math.cos(b.yaw)*170}; + if(b.act==='inhale'){if(H.holding){const try1=cloneGame(h);let ate=false;for(let i=0;i<70&&!try1.outcome;i++){simTick(try1,i===0?['Shift','L']:['Shift']);if(try1.events.includes('dodongo_ate_bomb')){ate=true;break;}if(try1.boss.act!=='inhale')break;} + if(ate&&free&&H.itemCd===0)return ['Shift',...tap('L')];} + else if(free&&H.itemCd===0&&b.timer>18)return ['Shift',...tap('L')]; + if(hd(H,want)>10&&free)return ['Shift',...stickTo(h,yawTo(H,want))];return ['Shift'];} + // Walking: keep a bomb out of the fuse's way and stand ahead of him, within the range that triggers his inhale, away from the corners. + // His inhale needs the hero on his walking line (D5): wait on that line between him and the next corner, at least 200 short of the corner (no inhale near one). + const c=CORNERS[b.corner],len=hd(b,c),ux=(c.x-b.x)/(len||1),uz=(c.z-b.z)/(len||1),ahead=Math.min(len-220,Math.max(260,len*.5)),spot={x:b.x+ux*ahead,z:b.z+uz*ahead}; + if(b.act==='walk'&&len>480&&hd(spot,{x:0,z:0})>D.pitR+20){if(hd(H,spot)>16&&free)return steer(yawTo(H,spot),[]);return ['Shift'];} + // Otherwise wait by the pit on the side he is heading for, clear of his body. + const nxt=CORNERS[(b.corner+(b.dir?3:1))%4],mid={x:(c.x+nxt.x)/2*.5,z:(c.z+nxt.z)/2*.5}; + if(hd(H,b)<170&&free)return steer(yawTo(b,H),[]); + if(hd(H,mid)>30&&free)return steer(yawTo(H,mid),[]); + return [];} + }); +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/ganondrof.js b/environments/games/web/games/zelda_oot_remake/bosses/ganondrof.js new file mode 100644 index 0000000000000000000000000000000000000000..5c2da2328f12c5cf91be0bd3c9fc3c988d13e036 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/ganondrof.js @@ -0,0 +1,113 @@ +/* Phantom Ganon, second phase (z_boss_ganondrof.c, z_en_fhg_fire.c). Original mechanics, own code. The painting phase on horseback is not built: + * the fight starts as he leaves the paintings and floats free. Frame counts are 20 Hz logic frames. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,approachF,approachS,MOVE}=M.helpers,PI=Math.PI; + const F={roomR:280,lead:180,var:100,heightN:100,heightV:200,heightC:150,volleyZ:265,chargeZ:215,throwFrame:25,throwEnd:34, + ballSpeed:8,ballSlow:3,ballR:25,reflectNeutral:15,reflectSpin:20,returnNear:150,returnPer:8,reflectFrames:8,bossBox:[30,45], + stunAir:50,stunLong:120,invHit:10,chargeWind:20,chargeStart:10,chargeCap:10,chargeAccel:.5,chargeEnd:20,chargeNear:100, + blockFrames:10,bodyR:36,floorY:5,ballLife:200}; + const TUNE={ + hp:[18,18,50,170], // BossBench: tier windows (T1). Source 30; the d = 0 anchor is easy's 18 so health never falls as d rises (dsweep found 30 > 24 > 18 below easy) + dmg:[16,16,20,24], // energy ball (source 0x10 = one heart) + charge:[16,16,20,24], + pick:[64,64,52,40], // random part of his neutral wait (source 30 + 0..63) + speedUp:[1,1,1.5,2], // ball speed added per return + stun:[50,50,50,50] // frames he stays down after his own ball hits him (source 50); longer on the easier tiers, T3 + }; + const setAct=(b,a)=>{b.act=a;b.af=0;}; + function setupNeutral(g,b){setAct(b,'neutral');b.floatSpeed=0;b.t0=30+Math.floor(g.rand()*g.T.pick);} + function setupThrow(g,b){setAct(b,'throw');b.slow=g.rand()<=.1&&b.throws>=10&&b.fly==='neutral';b.throwFrame=b.slow?21:F.throwFrame;b.throws++;g.ev('ganon_windup');} + function newBall(g,b){const s=spearTip(b),h=g.hero,dx=h.x-s.x,dy=h.y+30-s.y,dz=h.z-s.z,dxz=Math.hypot(dx,dz)||1,sp=b.slow?F.ballSlow:F.ballSpeed; + b.ball={mode:'green',x:s.x,y:s.y,z:s.z,ox:s.x,oy:s.y,oz:s.z,yaw:Math.atan2(dx,dz),pitch:Math.atan2(dy,dxz),speed:sp,returns:0,timer:0,life:F.ballLife};g.ev('ganon_ball');} + const spearTip=b=>({x:b.x+Math.sin(b.yaw)*40,y:b.y+70,z:b.z+Math.cos(b.yaw)*40}); + function stun(g,b,returns){if(b.act==='stunned'){setAct(b,'stunned');return;}setAct(b,'stunned');b.t0=returns>=2?F.stunLong:Math.round(g.T.stun);b.ground=false;b.vy=0;b.inv=F.invHit;g.ev('ganon_stunned');} + function ballUpdate(g,b){const q=b.ball;if(!q)return;const h=g.hero;q.ox=q.x;q.oy=q.y;q.oz=q.z;q.life--;if(q.timer>0)q.timer--; + const c=Math.cos(q.pitch);q.x+=Math.sin(q.yaw)*c*q.speed*MOVE;q.y+=Math.sin(q.pitch)*q.speed*MOVE;q.z+=Math.cos(q.yaw)*c*q.speed*MOVE; + const toL={x:h.x-q.x,y:h.y+40-q.y,z:h.z-q.z},dL=Math.hypot(toL.x,toL.y,toL.z),T=b.target,toB={x:T.x-q.x,y:T.y-q.y,z:T.z-q.z}; + if(q.mode==='green'){ + const s=g.strike(); + if(s&&s.id!==q.lastSlash&&g.swordReach(q.x,q.y,q.z,F.ballR)){q.lastSlash=s.id; + // The sword sends it back at him: aimed exactly in a rally (F7), with some scatter while he floats freely; the spin attack sends it fast. + if(b.fly==='neutral'){q.yaw=Math.atan2(toB.x,toB.z)+(g.rand()-.5)*.39;q.pitch=Math.atan2(toB.y,Math.hypot(toB.x,toB.z))+(g.rand()-.5)*.39;q.speed=F.reflectNeutral;} + else{q.returns++;if(q.returns>3&&g.rand()<.5)q.returns=100; + if(s.kind==='spin'){q.speed=F.reflectSpin;q.returns=4;}else q.speed+=g.T.speedUp; + q.yaw=Math.atan2(toB.x,toB.z);q.pitch=Math.atan2(toB.y,Math.hypot(toB.x,toB.z));} + q.mode='blue';g.ev('ball_reflect');g.fxAdd('spark',q.x,q.y,q.z,8,{r:20,color:0xbfe9ff});return;} + if(dL<=F.ballR){const r=g.hurt(g.T.dmg,q.yaw,{kb:6,vy:6});if(r==='block'){q.mode='dead';}else{g.fxAdd('burst',q.x,q.y,q.z,10,{r:30,color:0xb8ff7a});q.mode='dead';} + b.fly='neutral';return;}} + else if(q.mode==='blue'){ + if(b.fly==='return'&&q.returns<100){q.yaw=Math.atan2(toB.x,toB.z);if(Math.hypot(toB.x,toB.z)=100){if(Math.hypot(toB.x,toB.y,toB.z)<100)b.returnSuccess=true;q.yaw=Math.atan2(toB.x,toB.z);q.pitch=Math.atan2(toB.y,Math.hypot(toB.x,toB.z));} + if(Math.abs(toB.x)g.arena.ceil||Math.hypot(q.x,q.z)>g.arena.r+30||q.life<=0)){q.mode='dead';b.fly='neutral';g.fxAdd('burst',q.x,Math.max(4,q.y),q.z,10,{r:26,color:0xb8ff7a});} + if(q.mode==='dead')b.ball=null;} + function hitCheck(g,b){const h=g.hero;if(b.inv>0){b.inv--;b.returnCount=0;return;} + if(b.returnCount){const n=b.returnCount;b.returnCount=0;if(b.act==='charge')return;stun(g,b,n);if(n>=2)b.t0=F.stunLong;return;} + const s=g.strike();if(!s||s.id===b.lastSlash)return; + if(b.act==='stunned'&&b.ground&&g.swordReach(b.x,b.y+50,b.z,F.bodyR)){b.lastSlash=s.id;b.hp-=s.dmg;b.inv=F.invHit;g.ev('ganon_hit'); + if(b.hp<=0){b.hp=0;setAct(b,'dead');b.t0=40;g.ev('boss_dead');}else setAct(b,'stunned');}} + const ACT={ + neutral(g,b,h){if(b.t0>0)b.t0--;let tx,ty,tz;const v=b.vt; + if(b.fly==='neutral'){if(b.t0===0){b.t0=30+Math.floor(g.rand()*g.T.pick);const r=g.rand(); + if(b.hp=.8){b.fly='charge';b.t0=60;b.floatSpeed=0;}else{b.fly='volley';b.t0=60;b.floatSpeed=0;}} + else if(r<.5||b.throws<5)return setupThrow(g,b);else{b.fly='volley';b.t0=60;b.floatSpeed=0;}} + if(b.t1>0){tx=0;tz=0;}else{tx=h.x+F.lead*Math.sin(h.face);tz=h.z+F.lead*Math.cos(h.face);if(Math.hypot(tx,tz)>F.roomR){b.t1=50;b.floatSpeed=0;}} + ty=h.y+F.heightN;tx+=Math.sin(v*0x500*M.helpers.BIN)*F.var;tz+=Math.cos(v*0x700*M.helpers.BIN)*F.var;} + else if(b.fly==='volley'){tx=-14;tz=F.volleyZ;ty=h.y+F.heightV;tx+=Math.sin(v*0x500*M.helpers.BIN)*F.var;tz+=Math.cos(v*0x700*M.helpers.BIN)*F.var; + if(b.t0===0){b.fly='return';b.returnSuccess=false;setupThrow(g,b);b.t0=80;return;}} + else if(b.fly==='return'){tx=-14;tz=F.volleyZ;ty=h.y+F.heightV;tx+=Math.sin(v*0x500*M.helpers.BIN)*50;tz+=Math.cos(v*0x700*M.helpers.BIN)*50; + if(b.returnSuccess){b.returnSuccess=false;setAct(b,'return');b.t0=80;return;}if(b.t0===0)b.fly='neutral';} + else{tx=-14;tz=F.chargeZ;ty=h.y+F.heightC;tx+=Math.sin(v*0x500*M.helpers.BIN)*F.var;tz+=Math.cos(v*0x700*M.helpers.BIN)*F.var;if(b.t0===0){setAct(b,'charge');b.sub='wind';b.t0=F.chargeWind;g.ev('ganon_charge');return;}} + b.x=approachF(b.x,tx,.05,b.floatSpeed);b.y=approachF(b.y,ty,.05,10);b.z=approachF(b.z,tz,.05,b.floatSpeed);b.floatSpeed=approachF(b.floatSpeed,50,1,.5); + b.y+=2*Math.sin(v*1500*M.helpers.BIN);b.yaw=approachS(b.yaw,yawTo(b,h),5,0xbb8);}, + throw(g,b,h){b.af++;if(b.af===b.throwFrame)newBall(g,b);if(b.af>=F.throwEnd)setupNeutral(g,b);b.yaw=approachS(b.yaw,yawTo(b,h),5,0x7d0);b.y+=2*Math.sin(b.vt*1500*M.helpers.BIN);}, + return(g,b){b.af++;if(b.returnSuccess){b.returnSuccess=false;setAct(b,'return');b.t0=80;}if(b.af>=14&&!b.returnSuccess){setupNeutral(g,b);b.fly='return';b.t0=Math.max(1,b.t0);}b.y+=2*Math.sin(b.vt*1500*M.helpers.BIN);}, + stunned(g,b){if(b.t0>0)b.t0--;if(!b.ground){b.vy-=.2;b.y+=b.vy*MOVE;if(b.y<=F.floorY){b.y=F.floorY;b.vy=0;b.ground=true;g.ev('ganon_fall');}} + if(b.t0===0){setupNeutral(g,b);b.t0=30;b.t2=30;b.fly='neutral';b.ground=false;}}, + charge(g,b,h){if(b.t0>0)b.t0--; + if(b.sub==='wind'){b.yaw=approachS(b.yaw,yawTo(b,h),5,0x7d0);if(b.t0===0){b.sub='attack';b.t0=F.chargeStart;b.cspeed=0;}} + else if(b.sub==='attack'){if(b.t0>0){b.yaw=approachS(b.yaw,yawTo(b,h),5,0x7d0);b.pitch=Math.atan2(h.y+40-b.y,Math.hypot(h.x-b.x,h.z-b.z));} + b.cspeed=approachF(b.cspeed,F.chargeCap,1,F.chargeAccel);const c=Math.cos(b.pitch);b.x+=Math.sin(b.yaw)*c*b.cspeed*MOVE;b.y+=Math.sin(b.pitch)*b.cspeed*MOVE;b.z+=Math.cos(b.yaw)*c*b.cspeed*MOVE; + if(Math.hypot(b.x,b.z)>F.roomR||Math.hypot(b.x-h.x,b.y-h.y-40,b.z-h.z)F.roomR)b.t0=0; + if(b.t0===0&&b.cspeed<=.5){setupNeutral(g,b);b.t0=30;b.fly='neutral';}}}, + dead(g,b){if(--b.t0<=0)g.outcome='win';} + }; + M.register('ganondrof',{ + cases:[{id:'zelda/specter_rider',name:'Gallery Specter Rider (Young Swordsman · Longsword)'}], + arena:{r:330,ceil:520,start:[0,-220]},hearts:8,age:'adult',camDist:300,tune:TUNE,art:'ganondrof', + threats:{ganon_ball:1,ganon_return:1,hero_hurt:1,ganon_charge:1}, + init(g){const b=g.boss;Object.assign(b,{x:0,y:F.heightN,z:120,ox:0,oy:F.heightN,oz:120,vy:0,yaw:PI,pitch:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp),fly:'neutral', + t0:0,t1:0,t2:0,af:0,throws:0,slow:false,throwFrame:F.throwFrame,floatSpeed:0,vt:0,ball:null,returnSuccess:false,returnCount:0,inv:0,ground:false,lastSlash:-1,sub:'',cspeed:0,target:{x:0,y:0,z:0}}); + setupNeutral(g,b);b.t0=90;g.hero.face=g.hero.yaw=0;}, // A: he hovers 90 frames before the first throw (the cutscene before it is not built) + update(g){const b=g.boss,h=g.hero;b.vt++;if(b.t1>0)b.t1--;if(b.t2>0)b.t2--;b.target={x:b.x,y:b.y+50,z:b.z}; + if(b.act==='dead'){ACT.dead(g,b);return;} + ACT[b.act](g,b,h);if(g.outcome||b.act==='dead')return;g.confine(b,10); + ballUpdate(g,b);hitCheck(g,b);}, + targets(g){const b=g.boss;if(b.act==='dead')return [];const out=[{id:'ganon',x:b.x,y:b.y+50,z:b.z,range:900}];return out;}, + focus(g){return g.boss.ball&&g.boss.ball.mode!=='dead'?{x:(g.boss.x+g.boss.ball.x)/2,y:g.boss.y,z:(g.boss.z+g.boss.ball.z)/2}:g.boss;}, + hud(g){const b=g.boss,q=b.ball;if(b.act==='stunned')return b.ground?'He is down! Approach and strike with J.':'He was shocked and is falling.'; + if(q&&q.mode==='green')return 'An orb is incoming: swing your sword with J to return it.';if(q&&q.mode!=='green')return 'During the exchange, wait for him to return it before swinging again.'; + if(b.act==='charge')return 'He is charging! Roll aside.';return '';}, + plan(h){const {stickTo,cloneGame,simTick}=M.ctl,H=h.hero,b=h.boss,q=b.ball,tap=k=>h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + // A grounded, stunned Ganon: walk in and cut; a jump slash from just outside reach. + if(b.act==='stunned'&&b.ground){const d=Math.hypot(b.x-H.x,b.z-H.z),reach=M.constants.reach.adult+F.bodyR-8; + if(H.lock==='ganon'&&free&&d>reach-20&&d14)return ['Shift',...tap('Space')]; + if(d>reach&&free)return ['Shift',...stickTo(h,yawTo(H,b))];return b.inv===0?['Shift',...tap('J')]:['Shift'];} + if(b.act==='stunned'){const d=Math.hypot(b.x-H.x,b.z-H.z);return d>70&&free?['Shift',...stickTo(h,yawTo(H,b))]:['Shift'];} + // An incoming green ball: let a copy find the slash timing that sends it back; never turn the back on it. + if(q&&q.mode==='green'){const keysFor=k=>['Shift',...k]; + if(free){for(const k of [['J']]){const s=cloneGame(h);let ok=false;for(let i=0;i<9&&!s.outcome;i++){simTick(s,i<2?keysFor(k):['Shift']);if(s.events.includes('ball_reflect')){ok=true;break;}if(s.events.includes('hero_hurt'))break;}if(ok)return keysFor(tap('J'));}} + return ['Shift'];} + if(b.act==='charge'){if(!free)return [];const s0=cloneGame(h);let hit=false;for(let i=0;i<24&&!s0.outcome;i++){simTick(s0,['Shift']);if(s0.events.includes('hero_hurt')){hit=true;break;}} + if(hit){for(const o of [PI/2,-PI/2,PI]){const k=stickTo(h,wrap(yawTo(H,b)+o)),s=cloneGame(h);let hurt=false;for(let i=0;i<24&&!s.outcome;i++){simTick(s,i<2?[...k,'Space']:k);if(s.events.includes('hero_hurt')){hurt=true;break;}}if(!hurt)return [...k,'Space'];}} + return ['Shift'];} + // Otherwise keep the middle of the room and face him. + if(Math.hypot(H.x,H.z)>120&&free)return ['Shift',...stickTo(h,yawTo(H,{x:0,z:0}))]; + return ['Shift'];} + }); +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/goma.js b/environments/games/web/games/zelda_oot_remake/bosses/goma.js new file mode 100644 index 0000000000000000000000000000000000000000..ae868e6a9d251e66c6dc0dc07491a8e3e3c7f6a2 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/goma.js @@ -0,0 +1,161 @@ +/* Queen Gohma (z_boss_goma.c, z_en_goma.c). Original mechanics, own code. Frame counts are 20 Hz logic frames. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,approachF,approachS,MOVE}=M.helpers,PI=Math.PI; + // Source values, except A* (approximations for data only found in the assets: room size, animation lengths, limb positions). + const G={roof:320,wallMargin:62,eyeFwd:34,eyeY:{floor:62,stunned:34,ceil:-50},eyeR:26,bodyR:62,legReach:178, + stunSeed:90,stunFall:150,inv:10,idleBase:20,idleRange:30,mainBase:70,mainRange:40,ceilBase:30,ceilRange:60,walk:10/3,walkAway:20/3,walkBack:-10,prep:70, + postureFrames:33,postureTurnFrom:19,postureTurnTo:30,attackRange:150,attackConfirm:250,attackFrames:20,attackHit:[7,13],restBase:30,restRange:30,recover:15,damagedFrames:16,landFrames:25,crashFrames:20, + eggGravity:1.3,eggSpeed:1.5,hatch:80,kidHp:2,kidStandBase:10,kidStandRange:30,kidChaseBase:70,kidChaseRange:40,kidWalk:10/3,kidJumpRange:150,kidPrep:30,kidJumpVy:8,kidJumpSpeed:10,kidLand:10,kidR:20,kidDmg:8,kidInv:10,kidDead:5}; + const TUNE={ + hp:[10,10,15,42], // BossBench: scaled to the tier windows (T1) + dmg:[8,8,12,16], // contact and leg strike + patience:[200,200,240,280], + walk:[1,1,1.12,1.25], + stunSeed:[90,90,84,78], + // BossBench (T2): frames the eye stays shut after she reaches the ceiling / lands, so that a player who always hits still meets the eggs and the leg strike. 0 at d = 0 (source). + ceilGuard:[0,40,240,280], + floorGuard:[0,105,130,170] + }; + const ceilingActs=new Set(['ceilMove','ceilIdle','prepEggs']); + const eyeOf=b=>{const c=b.y>100,fy=c?G.eyeY.ceil:(b.act==='stunned'||b.act==='damaged'?G.eyeY.stunned:G.eyeY.floor);return {x:b.x+Math.sin(b.yaw)*G.eyeFwd,y:b.y+fy,z:b.z+Math.cos(b.yaw)*G.eyeFwd};}; + function setAct(b,a){b.act=a;b.af=0;} + function setupMain(g,b){setAct(b,'main');b.next=g.randS(G.mainBase,G.mainRange);b.walkAnim=0;} + function setupIdle(g,b){setAct(b,'idle');b.next=g.randS(G.idleBase,G.idleRange);} + function setupStunned(b){setAct(b,'stunned');} + function kidAlive(b){return b.kids.some(k=>k.state>0);} + function spawnEgg(g,b,i){const tail={x:b.x-Math.sin(b.yaw)*60,y:b.y-60,z:b.z-Math.cos(b.yaw)*60}; + b.kids.push({i,state:1,act:'fall',x:tail.x,y:tail.y,z:tail.z,ox:tail.x,oy:tail.y,oz:tail.z,vy:0,speed:G.eggSpeed,yaw:b.yaw,hp:G.kidHp,timer:0,inv:10});b.kidState[i]=1;g.ev('egg_spawn');} + function updateKids(g,b){const h=g.hero; + for(const k of b.kids){if(k.state<=0)continue;k.ox=k.x;k.oy=k.y;k.oz=k.z;if(k.inv>0)k.inv--;if(k.timer>0)k.timer--; + const d=hd(k,h),aim=yawTo(k,h); + if(k.act==='fall'){k.vy=Math.max(-20,k.vy-G.eggGravity);if(k.y<=0&&k.vy<0){k.y=0;k.vy=0;k.speed=0;k.act='egg';k.timer=G.hatch;}} + else if(k.act==='egg'){if(k.timer===0){k.act='stand';k.timer=g.randS(G.kidStandBase,G.kidStandRange);g.ev('egg_hatch');}} + else if(k.act==='stand'){k.speed=approachF(k.speed,0,.5,2);k.yaw=approachS(k.yaw,aim,3,2000);if(k.timer===0){k.act='chase';k.timer=g.randS(G.kidChaseBase,G.kidChaseRange);}} + else if(k.act==='chase'){k.speed=approachF(k.speed,G.kidWalk,.5,2);k.yaw=approachS(k.yaw,aim,3,2000); + if(d<=G.kidJumpRange){k.act='prep';k.timer=G.kidPrep;}else if(k.timer===0){k.act='stand';k.timer=g.randS(G.kidStandBase,G.kidStandRange);}} + else if(k.act==='prep'){k.speed=approachF(k.speed,0,.5,2);k.yaw=approachS(k.yaw,aim,3,2000);if(k.timer===0){k.act='jump';k.vy=G.kidJumpVy;g.ev('kid_jump');}} + else if(k.act==='jump'){k.vy-=G.eggGravity;k.speed=approachF(k.speed,G.kidJumpSpeed,.5,5);if(k.y<=0&&k.vy<0){k.y=0;k.vy=0;k.act='land';k.timer=G.kidLand;}} + else if(k.act==='land'){k.speed=approachF(k.speed,0,1,2);if(k.timer===0){k.act='stand';k.timer=g.randS(G.kidStandBase,G.kidStandRange);}} + else if(k.act==='hurt'){k.speed=approachF(k.speed,0,1,2);if(k.timer===0){if(k.hp<=0)killKid(g,b,k);else{k.act='stand';k.timer=g.randS(G.kidStandBase,G.kidStandRange);}}} + if(k.state<=0)continue; + k.x+=Math.sin(k.yaw)*k.speed*MOVE;k.z+=Math.cos(k.yaw)*k.speed*MOVE;k.y=Math.max(0,k.y+k.vy*MOVE);g.confine(k,G.kidR); + if(k.act!=='fall'&&k.act!=='egg'&&k.act!=='hurt'&&Math.hypot(k.x-h.x,k.z-h.z)k.state>0);} + function killKid(g,b,k){k.state=-1;b.kidState[k.i]=-1;g.ev('kid_dead');g.fxAdd('burst',k.x,k.y+14,k.z,10);} + function hitKid(g,b,k,dmg){if(k.inv>0)return; + if(k.act==='fall'||k.act==='egg'){killKid(g,b,k);return;} + k.hp-=dmg;k.inv=G.kidInv;k.act='hurt';k.timer=k.hp<=0?G.kidDead:10;k.speed=20;k.yaw=yawTo(g.hero,k);k.vy=0;g.ev('kid_hurt');} + function struckEye(g,b,kind,dmg){ // kind 'seed' or 'sword' + if(b.inv>0||b.eyeClosed>0||b.act==='spawnEggs'||b.act==='dead')return false; + if(ceilingActs.has(b.act)){setAct(b,'fallStruck');b.speed=0;b.vy=0;b.grav=-2;g.ev('gohma_struck_down');return true;} + if(b.act==='stunned'&&kind==='sword'){b.hp-=dmg;b.inv=G.inv;g.ev('gohma_hit'); + if(b.hp>0){setAct(b,'damaged');}else{b.hp=0;setAct(b,'dead');b.timer=30;g.ev('boss_dead');}return true;} + if(b.act!=='stunned'&&b.patience>0&&kind==='seed'&&b.y<5&&b.act!=='climb'){b.inv=G.inv;setupStunned(b);b.next=Math.round(g.T.stunSeed);b.timer=4;g.ev('gohma_stunned');return true;} + return false;} + const ACT={ + main(g,b,h){b.walkAnim=(b.walkAnim+(b.playSpeed||1))%31;const f=Math.floor(b.walkAnim);if(f===1||f===15||f===16||f===30)b.noMove=true;b.playSpeed=1; + if(!b.noMove){const rot=yawTo(b,h),d=hd(b,h); + if(b.patience>0){b.patience--;if(d0){b.speed=approachF(b.speed,G.walkBack,.5,2);b.playSpeed=3;if(b.timer===1)b.speed=0;b.yaw=approachS(b.yaw,rot,3,0x9c4);} + else{b.speed=approachF(b.speed,G.walkAway*g.T.walk,.5,2);b.playSpeed=2;b.yaw=approachS(b.yaw,wrap(rot+PI),3,0x9c4);}} + if(hd(b,{x:0,z:0})>=g.arena.r-G.wallMargin&&b.y<=0){setAct(b,'climb');b.speed=0;b.vy=0;b.grav=0;b.wallYaw=yawTo({x:0,z:0},b);g.ev('gohma_climb');return;} + if(b.next===0&&b.patience>0)setupIdle(g,b);}, + idle(g,b){b.speed=approachF(b.speed,0,.5,2);if(b.next===0)setupMain(g,b);}, + posture(g,b,h){b.af++;b.speed=approachF(b.speed,0,.5,2);if(b.af>=G.postureTurnFrom&&b.af<=G.postureTurnTo)b.yaw=approachS(b.yaw,yawTo(b,h),3,0xbb8); + if(b.af>=G.postureFrames){if(hd(b,h)=G.attackHit[0]&&b.af<=G.attackHit[1]&&!b.struck){const d=hd(b,h),off=Math.abs(wrap(yawTo(b,h)-b.yaw));if(d=G.attackFrames){b.sub=1;if(!b.struck)b.timer=g.randS(G.restBase,G.restRange);}} + else if(b.sub===1){if(b.timer===0){b.sub=2;b.af=0;}} + else if(b.af>=G.recover)setupIdle(g,b);}, + stunned(g,b,h){b.speed=approachF(b.speed,0,.5,1);if(b.next===0){setupMain(g,b);if(b.patience===0&&hd(b,h)<130)b.timer=20;}}, + damaged(g,b){b.af++;if(b.af>=G.damagedFrames){setupStunned(b);b.patience=0;}}, + climb(g,b){b.vy=approachF(b.vy,5,.5,2);b.yaw=approachS(b.yaw,wrap(b.wallYaw+PI),2,0x5dc); + if(b.y>G.roof){setAct(b,'ceilMove');b.guard=Math.round(g.T.ceilGuard);b.speed=0;b.vy=0;b.grav=0;b.y=G.roof;b.next=g.randS(G.ceilBase,G.ceilRange);b.kidState=[0,0,0];b.kids=[];}}, + ceilMove(g,b){b.yaw=approachS(b.yaw,wrap(yawTo(b,{x:0,z:0})+PI),2,0x3e8);b.speed=approachF(b.speed,-5,.5,2);b.y=G.roof; + if(b.next===0&&Math.abs(b.x)<100&&Math.abs(b.z)<100){setAct(b,'ceilIdle');b.next=g.randS(G.idleBase,G.idleRange);}}, + ceilIdle(g,b){b.speed=approachF(b.speed,0,.5,2); + if(b.next===0){const s=b.kidState; + if(s[0]===0&&s[1]===0&&s[2]===0){setAct(b,'prepEggs');b.next=G.prep;g.ev('gohma_prep_eggs');} + else if(s[0]<0&&s[1]<0&&s[2]<0){setAct(b,'fallJump');b.speed=0;b.vy=0;b.grav=-2;g.ev('gohma_jump_down');} + else{setAct(b,'ceilMove');b.next=g.randS(G.ceilBase,G.ceilRange);}}}, + prepEggs(g,b){if(b.next===0){setAct(b,'spawnEggs');b.spawnT=0;}}, + spawnEggs(g,b){b.speed=approachF(b.speed,0,.5,2);b.spawnT++; + // The tail swells limb by limb from frame 24 of each cycle and the egg leaves on frame 56 (limb timer 10 reaching 2, source sequence). + if(b.spawnT===56){const i=b.kidState.indexOf(0);if(i>=0)spawnEgg(g,b,i);if(b.kidState.includes(0))b.spawnT=23;} + if(b.spawnT>=64){setAct(b,'ceilIdle');b.next=g.randS(G.idleBase,G.idleRange);}}, + fallJump(g,b,h){b.yaw=approachS(b.yaw,yawTo(b,h),2,0x7d0);if(b.y<=0){setAct(b,'land');b.vy=0;b.y=0;g.ev('gohma_land');g.fxAdd('ring',b.x,2,b.z,12);}}, + fallStruck(g,b,h){b.yaw=approachS(b.yaw,yawTo(b,h),3,0x7d0);if(b.y<=0){setAct(b,'landStruck');b.vy=0;b.y=0;g.ev('gohma_land');g.fxAdd('ring',b.x,2,b.z,12);}}, + land(g,b){b.af++;if(b.af>=G.landFrames){setupIdle(g,b);b.patience=Math.round(g.T.patience);b.guard=Math.round(g.T.floorGuard);}}, + landStruck(g,b){b.af++;if(b.af>=G.crashFrames){setupStunned(b);b.patience=0;b.next=G.stunFall;}}, + dead(g,b){if(b.timer===0)g.outcome='win';} + }; + M.register('goma',{ + cases:[{id:'zelda/armored_spider_queen',name:'One-Eyed Armored Spider Queen (Young Swordsman · Slingshot)'}], + arena:{r:430,ceil:360,start:[0,300]},hearts:5,age:'child',camDist:300,tune:TUNE,item:{kind:'seed',cd:14,name:'Slingshot'},art:'goma',threats:{gohma_attack:1,egg_spawn:1,kid_jump:1}, + init(g){const b=g.boss;Object.assign(b,{x:0,y:0,z:-130,ox:0,oy:0,oz:-130,vy:0,speed:0,yaw:0,grav:-2,next:0,timer:0,af:0,sub:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp), + inv:0,patience:Math.round(g.T.patience),eyeClosed:0,eyeLid:0,guard:Math.round(g.T.floorGuard),noMove:false,playSpeed:1,walkAnim:0,struck:false,spawnT:0,wallYaw:0,kidState:[0,0,0],kids:[],frameCount:0}); + setupMain(g,b);g.hero.face=g.hero.yaw=PI;}, + update(g){const b=g.boss,h=g.hero;b.frameCount++;if(b.next>0)b.next--;if(b.timer>0)b.timer--; + if(b.act==='dead'){ACT.dead(g,b);return;} + const eyeDefault=!['posture','attack','stunned','damaged','prepEggs','spawnEggs'].includes(b.act); + ACT[b.act](g,b,h);if(g.outcome)return; + if(!b.noMove){b.x+=Math.sin(b.yaw)*b.speed*MOVE;b.z+=Math.cos(b.yaw)*b.speed*MOVE;b.vy=Math.max(-20,b.vy+b.grav);b.y+=b.vy*MOVE;if(b.y<=0){b.y=0;if(b.vy<0)b.vy=0;}}else b.noMove=false; + g.confine(b,G.wallMargin-2); + // Eye: a quiet boss may blink (30% every 16 frames, shut for 7); while a child lives it stays shut. Lids take a few frames to move. + if(eyeDefault&&b.frameCount%16===0&&g.rand()<.3)b.eyeClosed=7; + if(kidAlive(b))b.eyeClosed=7; + if(b.guard>0){b.guard--;b.eyeClosed=Math.max(b.eyeClosed,2);} + if(b.eyeClosed>0){b.eyeClosed--;b.eyeLid=Math.min(1,b.eyeLid+.34);}else b.eyeLid=Math.max(0,b.eyeLid-.34); + if(b.inv>0)b.inv--; + updateKids(g,b); + const s=g.strike(); + if(s){if(s.id!==b.lastSlash){const e=eyeOf(b);if(b.act!=='spawnEggs'&&g.swordReach(e.x,e.y,e.z,G.eyeR)){if(struckEye(g,b,'sword',s.dmg))b.lastSlash=s.id;}} + for(const k of b.kids)if(k.state>0&&k.lastSlash!==s.id&&g.swordReach(k.x,k.y+12,k.z,G.kidR)){k.lastSlash=s.id;hitKid(g,b,k,s.dmg);} + b.kids=b.kids.filter(k=>k.state>0);if(b.act==='dead')return;} + // Body contact: on except while stunned or hurt and while backing away (source condition). + if(b.act!=='stunned'&&b.act!=='damaged'&&(b.act!=='main'||b.timer===0)&&b.y<70&&hd(b,h)0&&Math.hypot(s.x-k.x,s.y-k.y-12,s.z-k.z)q.state>0);return true;} + const e=eyeOf(b);if(Math.hypot(s.x-e.x,s.y-e.y,s.z-e.z)100||Math.abs(wrap(Math.atan2(-s.vx,-s.vz)-b.yaw))<1.9){struckEye(g,b,'seed',0);return true;}}return false;}, + targets(g){const b=g.boss,e=eyeOf(b),out=[];for(const k of b.kids)if(k.state>0)out.push({id:'kid'+k.i,x:k.x,y:k.y+12,z:k.z,range:520});if(b.act!=='dead'&&!b.kids.length)out.push({id:'eye',x:e.x,y:e.y,z:e.z,range:900});return out;}, + focus(g){return g.lockTarget()||g.boss;}, + hud(g){const b=g.boss,e=b.eyeClosed>0||b.eyeLid>.5; + if(b.act==='stunned'||b.act==='damaged')return 'She is stunned! Approach and strike the eye with J.'; + if(b.kids.length)return `Defeat the hatchlings first (slingshot or sword); ${b.kids.length} remain`; + if(ceilingActs.has(b.act))return e?'Her eye is closed':'Shoot her eye with the slingshot to knock her from the ceiling (Shift lock, L shoot).'; + if(b.patience>0&&!e&&b.act!=='climb')return 'Shoot her open eye with the slingshot (Shift lock, L shoot).';return '';}, + plan(h){const {stickTo}=M.ctl,H=h.hero,b=h.boss; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + const tap=k=>h.lastKeys.includes(k)?[]:[k],d=hd(H,b),free=H.act==='idle'; + // Larvae first: a seed bursts an egg and hurts a larva. Keep moving away from a larva that is about to pounce. + if(b.kids.length){const k=[...b.kids].sort((p,q)=>hd(H,p)-hd(H,q))[0],dk=hd(H,k),keys=['Shift']; + const up=['prep','jump'].includes(k.act); + if(dk<(up?170:90)&&k.act!=='egg'&&k.act!=='fall'&&k.act!=='hurt'){keys.push(...safeStep(h,wrap(yawTo(k,H)),['Shift']));if(free&&H.itemCd===0)keys.push(...tap('L'));return keys;} + if(free&&H.itemCd===0&&H.lock!==null)keys.push(...tap('L'));return keys;} + // Stunned: run to the eye and cut. Stay on the near side; the third combo cut lands harder only in reach, so tap steadily. + if(b.act==='stunned'||b.act==='damaged'){const e=eyeOf(b),de=Math.hypot(e.x-H.x,e.z-H.z),keys=['Shift']; + if(de>M.constants.reach[H.age]+G.eyeR-6&&free)keys.push(...stickTo(h,yawTo(H,e))); + else if(b.act==='stunned'&&!(b.inv>4))keys.push(...tap('J')); + return keys;} + if(ceilingActs.has(b.act)){const keys=['Shift'];if(b.eyeLid<.2&&free&&H.itemCd===0&&H.lock==='eye')keys.push(...tap('L'));else if(hd(H,{x:0,z:0})>170&&free)keys.push(...stickTo(h,yawTo(H,{x:0,z:0})));return keys;} + if(b.act==='climb'||b.act==='spawnEggs'||b.act==='fallJump'||b.act==='fallStruck'||b.act==='land'||b.act==='landStruck'){const keys=[];if(hd(H,{x:0,z:0})>170&&free)keys.push(...stickTo(h,yawTo(H,{x:0,z:0})));return keys;} + // Floor: stay out of leg reach and shoot the open eye from the front while she still has patience; once it has run out, seeds do nothing, so only keep clear. + const keys=['Shift'],close=b.act==='posture'||b.act==='attack'?205:105; + if(d0&&b.eyeLid<.2&&free&&H.itemCd===0&&H.lock==='eye'&&Math.abs(wrap(yawTo(b,H)-b.yaw))<1.6)keys.push(...tap('L'));return keys;} + if(b.patience>0&&b.eyeLid<.2&&free&&H.itemCd===0&&H.lock==='eye'&&Math.abs(wrap(yawTo(b,H)-b.yaw))<1.6)keys.push(...tap('L')); + return keys;} + }); + // Run in the given direction, turning along the wall or toward the centre when a copy says that step is hit or walled in. + function safeStep(h,yaw,base){const {cloneGame,simTick,stickTo}=M.ctl;let best=[],bestS=-1e9; + for(const o of [0,.6,-.6,1.2,-1.2,1.9,-1.9]){const a=wrap(yaw+o),keys=stickTo(h,a),s=cloneGame(h);let hit=0; + for(let i=0;i<30&&!s.outcome;i++){simTick(s,[...base,...keys]);if(s.events.includes('hero_hurt')){hit=1;break;}} + const R=hd(s.hero,{x:0,z:0}),score=(hit?-1000:0)-Math.max(0,R-(h.arena.r-70))*4-Math.abs(o)*2+hd(s.hero,s.boss)*.05; + if(score>bestS){bestS=score;best=keys;}} + return best;} +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/morpha.js b/environments/games/web/games/zelda_oot_remake/bosses/morpha.js new file mode 100644 index 0000000000000000000000000000000000000000..598ca742c0d761c0ef67ed7f4c98fa797b2ff5f0 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/morpha.js @@ -0,0 +1,146 @@ +/* Morpha (z_boss_mo.c). Original mechanics, own code. Frame counts are 20 Hz logic frames. + * A water nucleus hides in a square pool and grows a water tentacle near the hero. The tentacle sways, then lashes out and the nucleus rides up inside it; + * a tentacle that reaches the hero curls round, lifts and squeezes him. The hookshot tears the nucleus out of the tentacle and drags it ashore, where the sword hurts it. + * After three sword hits a second tentacle joins. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,approachF,MOVE}=M.helpers,PI=Math.PI; + const SPAWNS=[[-360,-360],[-180,-360],[0,-360],[180,-360],[360,-360],[-360,-180],[0,-180],[360,-180],[-360,0],[-180,0],[0,0],[180,0],[360,0],[-360,180],[0,180],[360,180],[-360,360],[-180,360],[0,360],[180,360],[360,360]]; // M3, source order + const ORDER=[0,1,2,3,4,15,19,5,14,16,17,18,6,13,20,7,12,11,10,9,8]; + const V={pool:380,spawn:70,ready:60,attack1:175,attack2:55,curl:40,shake:150,retreat:75,shakeEvery:8,mash:40,releaseInv:50,near:320,far:300, + hookStun:30,swordStun:25,coreInv:10,knock:15,knockDecay:0,coreR:24,height:280,reach:360,tentR:40,grabR:120,curlGrab:90,hookRange:520,hookR:34,landY:10,poolY:-60, + climb:[15,10],segs:40,swingJitter:12,arena:520}; + const TUNE={ + hp:[20,26,120,400], + dmg:[16,16,16,16], // tentacle and nucleus contact, source 0x10 = one heart in every tier: hard 400 with 20 lost 3 of 16 to the second tentacle's lashes + squeeze:[1,1,1,2], // per 8 frames while held (source 1) + swing:[50,50,45,40] // sway before the lash (source 50) + }; + const inPool=(x,z)=>Math.abs(x)h.y-30)return true;}return false;} + function tentReset(t,st,t0){t.st=st;t.t0=t0;} + function holding(b,t){return b.tents.some(o=>o!==t&&o.held);} + function relocate(g,b,t){const h=g.hero;for(let n=0;n<40;n++){const k=ORDER[Math.floor(g.rand()*20.9)],[x,z]=SPAWNS[k]; + if(Math.abs(h.x-x)>V.near||Math.abs(h.z-z)>V.near||b.tents.some(o=>o!==t&&o.spawn===k))continue;t.spawn=k;t.x=x;t.z=z;break;} + if(t.spawn<0){t.spawn=10;t.x=0;t.z=0;}} + function release(g,b,t,shaken){const h=g.hero;if(!t.held)return;t.held=false;h.grabbed=false;h.y=0; + if(shaken){h.act='kb';h.timer=18;h.yaw=wrap(t.yaw);h.speed=8;h.vy=6;h.face=wrap(t.yaw+PI);}else{h.act='idle';h.timer=0;h.speed=0;} + g.ev('tentacle_release');} + const TENT={ + wait(g,b,t){if(t.i===1&&t.t0===0){tentReset(t,'spawn',V.spawn);t.yaw=yawTo(t,g.hero);g.ev('tentacle_rise');}}, + spawn(g,b,t){t.grow=Math.min(1,t.grow+1/50);if(t.t0<20&&t.grow>=1){tentReset(t,'ready',60);}}, + ready(g,b,t){if(t.t0===0&&!holding(b,t)){tentReset(t,'swing',Math.round(g.T.swing)+Math.floor(g.rand()*V.swingJitter));t.mod=(g.rand()-.5)*0x1000*M.helpers.BIN;}}, + swing(g,b,t,h){t.yaw=M.helpers.approachS(t.yaw,wrap(yawTo(t,h)+t.mod),3,0x1f4);if(t.t0===0){tentReset(t,'attack',t.i===0?V.attack1:V.attack2);t.lash=0;g.ev('tentacle_lash');}}, + attack(g,b,t,h){t.ext=Math.min(1,t.ext+.15);if(t.ext>.5&&!h.grabbed&&touching(t,h,V.tentR)){const r=g.hurt(g.T.dmg,t.yaw,{kb:6});if(r)t.lash=5;} + if(t.lash>0)t.lash--; + if(t.t0===0||t.lash===4){const p=tentPoint(t,.55); + if(Math.hypot(p.x-h.x,p.z-h.z)V.far||Math.abs(h.z-t.z)>V.far||holding(b,t))tentReset(t,'retreat',V.retreat);}}}, + curl(g,b,t,h){t.ext=Math.max(.5,t.ext-.04);if(t.t0>=30)t.yaw=M.helpers.approachS(t.yaw,yawTo(t,h),5,0xc8); + const p=tentPoint(t,.55);if(t.t0>=5&&!h.grabbed&&h.act!=='dead'&&Math.hypot(p.x-h.x,p.z-h.z)=V.mash||t.t0===0){release(g,b,t,t.t0===0);t.inv=V.releaseInv;tentReset(t,'retreat',V.retreat);}}, + cut(g,b,t){release(g,b,t,false);t.grow=Math.max(0,t.grow-.06);t.ext=Math.max(0,t.ext-.06);if(t.t0===0||t.grow<=0)tentReset(t,'retreat',V.retreat);}, + retreat(g,b,t){t.ext=Math.max(0,t.ext-.05);if(t.t0===0){t.grow=Math.max(0,t.grow-.05);if(t.grow<=0){relocate(g,b,t);tentReset(t,'despawn',30+Math.floor(g.rand()*20)); + if(t.i===0&&b.hitCount>=3&&b.tents.length<2){const u=newTent(1);u.spawn=t.spawn>10?t.spawn-1:t.spawn+1;[u.x,u.z]=SPAWNS[u.spawn];b.tents.push(u);g.ev('second_tentacle');}}}}, + despawn(g,b,t){if(t.t0===0){tentReset(t,'wait',10+Math.floor(g.rand()*20));}} + }; + function tentUpdate(g,b,t){const h=g.hero;if(t.inv>0)t.inv--;t.sway+=.3;if(t.st!=='attack'&&t.st!=='curl'&&t.st!=='cut')t.ext=Math.max(0,t.ext-.1);TENT[t.st](g,b,t,h); + // Swaying column: the base of the tentacle hurts on contact. + if((t.st==='ready'||t.st==='swing')&&t.grow>.5&&!h.grabbed&&t.inv===0&&Math.hypot(h.x-t.x,h.z-t.z)0)c.inv--;if(c.flash>0)c.flash--;c.vt++; + if(c.act==='move'){if(c.t0===0&&(t.st==='wait'||t.st==='ready')&&c.y<0&&inPool(c.x,c.z)){c.act='make';c.speed=0;if(t.st==='wait'){tentReset(t,'spawn',V.spawn);t.yaw=yawTo(t,h);g.ev('tentacle_rise');}}} + else if(c.act==='make'){if(t.st==='despawn'||t.st==='wait'){c.act='move';c.t0=70;}if(t.st==='attack'||t.st==='cut'){c.act='ride';c.pos=0;c.speed=0;}} + else if(c.act==='stunned'){if(c.t0===0){c.act='move';c.t0=30;}if(c.y<0&&inPool(c.x,c.z)){c.act='make';c.t0=50;c.speed=0;}} + if(c.act==='ride'){c.pos++;const cap=Math.round(Math.sin(c.vt*0x300*M.helpers.BIN)*V.climb[1])+V.climb[0];if(t.st==='attack'&&c.pos>cap)c.pos=cap;if(t.st!=='attack'&&t.st!=='cut')c.act='back';} + else if(c.act==='back'){c.pos--;if(c.pos<=0){c.pos=0;c.act='make';c.t0=100;}} + if(c.act==='ride'||c.act==='back'){const p=tentPoint(t,Math.min(V.segs,c.pos)/V.segs);c.x=approachF(c.x,p.x,.5,30);c.y=approachF(c.y,p.y-(c.pos<=1?20:0),.5,30);c.z=approachF(c.z,p.z,.5,30);c.vy=0;} + else{const floor=inPool(c.x,c.z)?V.poolY:V.landY; + if(c.act==='move'){const a=c.vt*0x800*M.helpers.BIN;c.speed=Math.min(10,c.speed+.5);c.x=approachF(c.x,t.x+Math.sin(a)*100,.05,c.speed);c.z=approachF(c.z,t.z+Math.cos(a)*100,.05,c.speed);} + else if(c.act==='make'){c.speed=Math.min(10,c.speed+.5);c.x=approachF(c.x,t.x,.1,c.speed);c.z=approachF(c.z,t.z,.1,c.speed);c.y=approachF(c.y,-40,.1,c.speed);} + else if(c.act==='stunned'){c.x+=Math.sin(c.yaw)*c.speed;c.z+=Math.cos(c.yaw)*c.speed;c.speed=Math.max(0,c.speed-V.knockDecay);} + if(c.act==='move'||c.act==='stunned'){c.y+=c.vy*MOVE;c.vy-=1; + if(!inPool(c.x,c.z)){if(c.y<=V.landY){c.y=V.landY;c.vy=c.act==='move'&&c.vt%3===0?6:0;}} + // In the pool it stays under (A: the source's 18-unit hop above the surface is left out, so the hookshot waits for the tentacle). + else if(c.act==='move'&&c.y<-30){c.y=-30;c.vy=0;} + if(c.y-10&&!h.grabbed&&Math.hypot(c.x-h.x,c.z-h.z)0||c.y<0||!['move','make','stunned'].includes(c.act))return;const s=g.strike();if(!s||s.id===b.lastSlash)return; + if(!g.swordReach(c.x,c.y+12,c.z,V.coreR))return;b.lastSlash=s.id; + c.act='stunned';c.t0=V.swordStun;c.speed=V.knock;c.yaw=yawTo(h,c);c.vy=3;c.flash=15;c.inv=V.coreInv;b.hp-=s.dmg;b.hitCount++;g.ev('core_hit');g.fxAdd('burst',c.x,c.y+12,c.z,10,{r:26,color:0xc8f0ff}); + if(b.hp<=0){if(b.tents.some(t=>t.held))b.hp=1;else{b.hp=0;b.act='dead';b.t0=50;g.ev('boss_dead');}}} + M.register('morpha',{ + cases:[{id:'zelda/water_core_amoeba',name:'Water-Core Amoeba (Young Swordsman · Hookshot)'}], + arena:{r:V.arena,square:V.arena,ceil:600,start:[0,-460]},hearts:10,age:'adult',camDist:340,tune:TUNE,art:'morpha', + item:{kind:'hook',name:'Hookshot: fire with L (auto-aim at the core while locked)'},threats:{tentacle_lash:1,tentacle_grab:1,second_tentacle:1,core_hit:1,hero_hurt:1}, + // The hookshot: a straight reach of 520; a nucleus above the water is torn out of its tentacle and dragged to the hero (M8). + useItem(g){const h=g.hero,b=g.boss,c=b.core,T=g.lockTarget();if(h.itemCd>0)return;h.itemCd=16;const yaw=T?Math.atan2(T.x-h.x,T.z-h.z):h.face;h.face=yaw;g.ev('hook_fire'); + const dx=c.x-h.x,dz=c.z-h.z,along=dx*Math.sin(yaw)+dz*Math.cos(yaw),side=Math.abs(dx*Math.cos(yaw)-dz*Math.sin(yaw)); + for(let k=1;k<=6;k++){const f=Math.min(along>0?along:V.hookRange,V.hookRange)*k/6;g.fxAdd('spark',h.x+Math.sin(yaw)*f,h.y+44,h.z+Math.cos(yaw)*f,6,{r:5,color:0xd0d8e0});} + if(b.act==='dead'||c.y<-10||along<0||along>V.hookRange||side>V.hookR||c.inv>0)return; + if(c.act==='ride'||c.act==='back'){const t=b.tents[0];release(g,b,t,false);tentReset(t,'cut',40);g.ev('tentacle_cut');} + c.act='stunned';c.t0=V.hookStun;c.speed=0;c.inv=V.coreInv;c.x=h.x+Math.sin(yaw)*50;c.z=h.z+Math.cos(yaw)*50; + // Dragged all the way to the hero (source pulls the actor to the hookshot). Where it lands beside him is not in the code we can read (T19): here, on his wall side, so it never lands back in the pool. + const ox=Math.abs(h.x)>=Math.abs(h.z)?Math.sign(h.x||1):0,oz=ox?0:Math.sign(h.z||1),m=V.arena-30;c.x=N.clamp(h.x+ox*45,-m,m);c.z=N.clamp(h.z+oz*45,-m,m); + if(Math.hypot(c.x-h.x,c.z-h.z)<30){c.x=N.clamp(h.x+oz*45,-m,m);c.z=N.clamp(h.z+ox*45,-m,m);} + c.y=Math.max(c.y,30);c.vy=2;g.ev('core_hooked');}, + init(g){const b=g.boss;Object.assign(b,{hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp),act:'fight',t0:0,hitCount:0,lastSlash:-1,tents:[newTent(0)], + core:{x:200,y:-40,z:0,ox:200,oy:-40,oz:0,vy:0,speed:0,yaw:0,act:'move',t0:50,pos:0,inv:0,flash:0,vt:0}}); + const t=b.tents[0];relocate(g,b,t);}, + update(g){const b=g.boss,h=g.hero,c=b.core;c.ox=c.x;c.oy=c.y;c.oz=c.z;if(b.t0>0)b.t0--; + if(b.act==='dead'){if(b.t0===0)g.outcome='win';return;} + for(const t of b.tents){if(t.t0>0)t.t0--;}if(c.t0>0)c.t0--; + for(const t of b.tents)tentUpdate(g,b,t);if(g.outcome)return;coreUpdate(g,b);swordCheck(g,b); + // Deep water: the hero keeps to the walkway round the pool (T18). + if(!h.grabbed&&inPool(h.x,h.z)){const ex=V.pool+12-Math.abs(h.x),ez=V.pool+12-Math.abs(h.z);if(ex-10?{x:c.x,y:c.y,z:c.z}:{x:t.x,y:60,z:t.z};}, + hud(g){const b=g.boss,c=b.core,h=g.hero;if(h.grabbed)return 'Grabbed! Press J repeatedly to break free.'; + if(c.act==='stunned'||(c.act==='move'&&c.y>-10&&!inPool(c.x,c.z)))return 'Core on shore! Strike it with J.'; + if(c.act==='ride')return 'Core in a tentacle: lock with Shift, then pull it out with the hookshot (L).'; + return 'The core is hiding in water; wait for a tentacle to emerge.';}, + plan(h){return M.plans.__morpha(h);} + }); + M.plans.__morpha=function(h){const {stickTo,cloneGame,simTick}=M.ctl,H=h.hero,b=h.boss,c=b.core,t=b.tents[0],tap=k=>h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead')return []; + if(H.grabbed){const k=Math.floor(h.t/2)%3;return k===0?['J']:k===1?['Space']:[];} + if(H.act==='kb')return []; + const safe=(keys,n)=>{const s=cloneGame(h);for(let i=0;i{for(const o of [0,.7,-.7,1.4,-1.4,2.2,-2.2,PI]){const k=stickTo(h,wrap(yaw+o));if(safe(k,16))return k;}for(const o of [0,PI/2,-PI/2,PI]){const k=[...stickTo(h,wrap(yaw+o)),'Space'];if(safe(k,14))return k;}return stickTo(h,yaw);}; + // The tentacle to keep away from: the nearest one that is up (a second one joins after three cuts, M10). + const live=b.tents.filter(q=>q.grow>.3||q.st==='spawn'),near=(live.length?live:b.tents).reduce((p,q)=>Math.hypot(q.x-H.x,q.z-H.z)-10&&!inPool(c.x,c.z)&&['move','stunned'].includes(c.act); + // Ashore: come at it from the pool side so each cut knocks it outwards against the wall (its knock-back is 15 a frame for 25 frames, M7), not back into the water. + if(ashore){const keys=['Shift'];if(!free)return keys;const ox=Math.abs(c.x)>=Math.abs(c.z)?Math.sign(c.x||1):0,oz=ox?0:Math.sign(c.z||1),side=(H.x-c.x)*ox+(H.z-c.z)*oz; + const spot={x:c.x-ox*40,z:c.z-oz*40},ds=Math.hypot(spot.x-H.x,spot.z-H.z); + // A cut roots the hero for its swing (10 frames): only start one the other tentacle cannot reach before it ends. + const lashing=b.tents.some(q=>q!==t&&(q.st==='swing'&&q.t0<12||q.st==='attack')&&Math.hypot(q.x-H.x,q.z-H.z)16){const k=stickTo(h,yawTo(H,side>10&&d<70?{x:c.x-ox*80+(H.x-c.x)*.3,z:c.z-oz*80+(H.z-c.z)*.3}:spot));keys.push(...(safe([...keys,...k],8)?k:dodge(yawTo(near,H))));} + return keys;} + // Above the water and within the hookshot's reach: pull it out. + if(c.y>-10&&dq.st==='swing'||q.st==='attack'||q.st==='curl'); + if(!safe([],busy?24:12))return dodge(yawTo(near,H)); + if(dw>30){const k=stickTo(h,yawTo(H,want));return safe(k,busy?24:12)?k:dodge(yawTo(near,H));}return [];}; + // The walkway point nearest the hero on a ring of radius 420 round the first root (past the lash, 360 + 40, and inside the hookshot reach of the riding nucleus), also 420 from any other root. + function standOff(ts,H){const t=ts[0];let best=null,bd=1e9;for(let i=0;i<32;i++){const a=i*PI/16,x=t.x+Math.sin(a)*420,z=t.z+Math.cos(a)*420; + if(inPool(x,z)&&Math.max(Math.abs(x),Math.abs(z))V.arena-24||Math.abs(z)>V.arena-24||ts.some(q=>q!==t&&Math.hypot(q.x-x,q.z-z)<400))continue;const d=Math.hypot(x-H.x,z-H.z);if(d 61-143 s (a run of fire blasts below 10/24 stalls the charge), 18 -> 63-67 s: two knock-downs finish her before the random phase. Source 24 (W1) is above normal; the d = 0 anchor is easy's 6 so health never falls as d rises + blast:[48,48,48,48], // blast damage, source 0x30 = three hearts (W5) + speed:[1,1,1.1,1.2], // blast speed factor (source 20) + rest:[60,30,50,45] // frames after a throw (source 60); easy 30: three soaked blasts are the shortest fight, and with 60 they alone take 31 s (T23) + }; + const setAct=(b,a,t)=>{b.act=a;b.t0=t===undefined?0:t;b.af=0;}; + function pickPerch(g,b){const h=g.hero;for(let n=0;n<20;n++){b.perch=(b.perch+1+Math.floor(g.rand()*2.99))%4;const [x,z]=PERCH[b.perch];if(Math.hypot(x-h.x,z-h.z)>W.away)break;} + const [x,z]=PERCH[b.perch];b.tx=x;b.tz=z;b.ty=W.flyY;} + function nextElement(g,b){if(b.hp=W.seqLen+1){b.seq=1;b.fixed=1-b.fixed;}return b.fixed;} // W4, threshold read at source health 10 of 24 + const ACT={ + fly(g,b){const sp=W.flySpeed*MOVE*.5;b.speed=Math.min(sp,b.speed+2);const dx=b.tx-b.x,dz=b.tz-b.z,d=Math.hypot(dx,dz)||1;b.x+=dx/d*Math.min(b.speed,d);b.z+=dz/d*Math.min(b.speed,d); + b.ty=Math.max(W.perchY,b.ty-2);b.y=approachF(b.y,b.ty,.1,6);b.yaw=Math.atan2(dx,dz);if(d{q.ox=q.x;q.oy=q.y;q.oz=q.z;q.life--; + const steps=3;for(let i=0;ih.y-10){ + if(shieldFaces(h,q)){absorb(g,b,q);return false;}g.hurt(g.T.blast,Math.atan2(q.vx,q.vz),{unblockable:true,kb:6});g.ev(q.el?'burned':'frozen');return false;} + if(q.y<=0||Math.hypot(q.x,q.z)>W.arena){g.fxAdd('burst',q.x,Math.max(4,q.y),q.z,12,{r:40,color:q.el?0xff7a2a:0x9fe2ff});return false;}} + return q.life>0;});} + // Soak: the same element adds a charge, the other element cancels the charge; three charges fire back along the shield (W7). + function absorb(g,b,q){const h=g.hero;g.ev('shield_absorb');if(b.charge>0&&b.chargeEl!==q.el){b.charge=0;g.ev('charge_cancel');return;} + b.chargeEl=q.el;b.charge++;if(b.charge>=3){b.charge=0;const T=g.lockTarget(),yaw=T?Math.atan2(T.x-h.x,T.z-h.z):h.face,pitch=T?Math.atan2(T.y-(h.y+40),Math.hypot(T.x-h.x,T.z-h.z)):.6; + b.shots.push({el:q.el,x:h.x,y:h.y+40,z:h.z,ox:h.x,oy:h.y+40,oz:h.z,vx:Math.sin(yaw)*Math.cos(pitch)*W.chargeSpeed,vy:Math.sin(pitch)*W.chargeSpeed,vz:Math.cos(yaw)*Math.cos(pitch)*W.chargeSpeed,life:W.chargeLife});g.ev('charge_release');}} + function chargeShots(g,b){b.shots=b.shots.filter(s=>{s.ox=s.x;s.oy=s.y;s.oz=s.z;s.life--;for(let i=0;i<4;i++){s.x+=s.vx*MOVE/4;s.y+=s.vy*MOVE/4;s.z+=s.vz*MOVE/4; + if(b.act!=='stun'&&b.act!=='dead'&&b.act!=='getup'&&Math.hypot(s.x-b.x,s.y-b.y,s.z-b.z)0&&Math.hypot(s.x,s.z)0||b.y>60)return;const s=g.strike();if(!s||s.id===b.lastSlash)return;if(!g.swordReach(b.x,b.y+30,b.z,W.bodyR))return;b.lastSlash=s.id; + b.hp-=s.dmg;b.inv=W.swordInv;g.ev('witch_hit');g.fxAdd('burst',b.x,b.y+40,b.z,8,{r:24,color:0xffffff});if(b.hp<=0){b.hp=0;setAct(b,'dead',50);g.ev('boss_dead');}} + M.register('twinrova',{ + cases:[{id:'zelda/twin_flame_frost_witches',name:'Twin Flame and Frost Witches (Young Swordsman · Mirror Shield)'}], + arena:{r:W.arena,ceil:900,start:[0,0]},hearts:12,age:'adult',camDist:360,tune:TUNE,art:'twinrova', + // No C item: the mirror shield (K) is the tool here (W6, W7), so L does nothing.threats:{fire_blast:1,ice_blast:1,charge_release:1,witch_stunned:1,hero_hurt:1}, + init(g){const b=g.boss;Object.assign(b,{x:PERCH[0][0],y:W.flyY,z:PERCH[0][1],ox:PERCH[0][0],oy:W.flyY,oz:PERCH[0][1],yaw:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp),t0:0,af:0, + perch:0,tx:PERCH[0][0],ty:W.flyY,tz:PERCH[0][1],speed:0,vy:0,inv:0,lastSlash:-1,seq:0,fixed:0,element:0,blasts:[],shots:[],charge:0,chargeEl:0}); + pickPerch(g,b);setAct(b,'fly');}, + update(g){const b=g.boss,h=g.hero;if(b.t0>0)b.t0--;if(b.inv>0)b.inv--; + ACT[b.act](g,b,h);if(g.outcome)return;blasts(g,b);chargeShots(g,b);swordCheck(g,b); + if(b.act!=='stun'&&b.act!=='dead'&&b.y0)return `Shield holds ${c} charges of ${el}: absorb another of the same element (hold K to raise the shield); opposite elements cancel.`; + return 'Lock onto her with Shift and raise the shield with K to absorb shockwaves. Three of the same element reflect automatically.';}, + plan(h){return M.plans.__twinrova(h);} + }); + M.plans.__twinrova=function(h){const {stickTo,cloneGame,simTick}=M.ctl,H=h.hero,b=h.boss,tap=k=>h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + // Knocked down: run to where she falls (straight down) and cut once she is low enough. + if(b.act==='stun'){const keys=['Shift'],d=hd(b,H),reach=M.constants.reach.adult+W.bodyR-6;if(!free)return keys;if(d>reach)keys.push(...stickTo(h,yawTo(H,b)));else if(b.inv===0&&b.y<60)keys.push(...tap('J'));return keys;} + // A blast on the way: face it with the shield if it is the element we are charging (or the shield is empty); otherwise roll out of its line. + const incoming=b.blasts.filter(q=>{const t=((H.x-q.x)*q.vx+(H.z-q.z)*q.vz)/(q.vx*q.vx+q.vz*q.vz||1);return t>0&&t<40;}); + if(incoming.length){const q=incoming[0],want=b.charge===0||q.el===b.chargeEl; + if(want){const keys=['Shift','K'];return keys;} + if(!free)return [];const side=wrap(Math.atan2(q.vx,q.vz)+PI/2);for(const o of [0,PI]){const k=[...stickTo(h,wrap(side+o)),'Space'];const s=cloneGame(h);let ok=true;for(let i=0;i<12&&!s.outcome;i++){simTick(s,k);if(s.events.includes('hero_hurt')){ok=false;break;}}if(ok)return k;} + return ['Shift','K'];} + // Otherwise stay near the middle, locked on, shield down. + const keys=['Shift'];if(free&&Math.hypot(H.x,H.z)>120)keys.push(...stickTo(h,yawTo(H,{x:0,z:0})));return keys;}; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/bosses/volvagia.js b/environments/games/web/games/zelda_oot_remake/bosses/volvagia.js new file mode 100644 index 0000000000000000000000000000000000000000..0665e4dd7751c4a237f65431437481ff7cb7c9c7 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/bosses/volvagia.js @@ -0,0 +1,102 @@ +/* Volvagia (z_boss_fd2.c hole phase, z_boss_fd.c flying phase). Original mechanics, own code. Frame counts are 20 Hz logic frames. + * Hole phase: he rises from one of nine holes, faking out more often as he weakens; a hammer blow on the head knocks him flat and exposes the face to the sword. + * Flying phase after three holes: alternately chases the hero breathing fire, or rams the ceiling to rain rocks, then dives into a new hole. */ +(function(root){ + 'use strict'; + const M=root.ZeldaOotGame,N=root.NativeBench,{wrap,hd,yawTo,approachS,MOVE}=M.helpers,PI=Math.PI; + const HOLES=[];for(const x of [-243,0,243])for(const z of [-243,0,243])HOLES.push({x,z}); // V2, source order + const V={wait:10,rise:15,sink:25,invHammer:30,vulnAnim:22,vuln:60,swipeR:200,swipe:24,swipeHit:[8,14],fireAnim:76,fireFrom:25,fireTo:70,fireLen:300,fireArc:0x1f40,headR:42,headY:118,headFwd:46,bodyR:58, + emergeKnock:120,flyChase:300,flyCeil:150,ceilY:700,rockEvery:16,rockFor:300,rockR:[130,50],rockFall:16,flySpeed:5,chaseFloor:50,chaseHigh:300,breathEvery:64,breathFor:20,bodySeg:16,roomR:520}; + const holeTime=(hp,mx)=>{const k=hp/mx*24;return k>=24?30:k>=18?25:k>=12?20:k>=6?10:5;}; // V3, read at the source's health thresholds of 24 + const idleTime=(hp,mx)=>{const k=hp/mx*24;return k>=24?50:k>=18?40:k>=12?40:k>=6?30:20;}; + const fakes=(hp,mx)=>{const k=hp/mx*24;return k>=18?0:k>=12?1:k>=6?2:3;}; + const TUNE={ + hp:[24,32,64,190], + hammer:[2,2,2,2], // source (V4) + touch:[32,32,36,40], // hole-phase body and claw (source 0x20) + fly:[16,16,20,24], // flying body and breath (source 0x10) + rock:[16,16,20,24], + chase:[1,1,1.12,1.25] // flying speed factor + }; + const setAct=(b,a,t)=>{b.act=a;b.t0=t===undefined?0:t;b.af=0;}; + const headOf=b=>({x:b.x+Math.sin(b.yaw)*V.headFwd,y:b.y+V.headY*(b.act==='vuln'?.35:1),z:b.z+Math.cos(b.yaw)*V.headFwd}); + function pickHole(g,b){let i;do{i=Math.floor(g.rand()*8.9);}while(i===b.hole&&b.holesTried++<6);b.hole=i;const H=HOLES[i];b.x=H.x;b.z=H.z;} + function setupEmerge(g,b){setAct(b,'under',V.wait);pickHole(g,b);b.y=-200;b.fakes=fakes(b.hp,b.maxHp);b.exposed=false;g.ev('volvagia_rumble');} + function hurtHero(g,b,dmg,from,opt){return g.hurt(dmg,from,opt);} + const ACT={ + under(g,b){if(b.t0===0){setAct(b,'peek',holeTime(b.hp,b.maxHp));b.y=-60;g.ev('volvagia_peek');}}, + peek(g,b,h){if(b.t0===0){if(b.fakes>0){b.fakes--;setAct(b,'under',V.wait);pickHole(g,b);b.y=-200;return;} // a fake-out moves to another hole without resetting the count (V3) + setAct(b,'rise',V.rise);b.y=0;b.yaw=yawTo(b,h);b.holeCount++;g.ev('volvagia_emerge');g.fxAdd('ring',b.x,3,b.z,12,{r:150,color:0xff8a3a});}}, + rise(g,b,h){b.yaw=approachS(b.yaw,yawTo(b,h),3,0x7d0);if(b.t0===1&&hd(b,h)=V.swipeHit[0]&&b.af<=V.swipeHit[1]&&hd(b,h)=V.fireFrom&&b.af=3&&b.hpV.vulnAnim&&b.t0===0){b.exposed=false;setAct(b,'burrow',V.sink);}}, + damaged(g,b){if(b.t0===0){b.exposed=false;setAct(b,'burrow',V.sink);}}, + fly(g,b,h){b.af++;const T=b.flyTarget,dx=T.x-b.x,dy=T.y-b.y,dz=T.z-b.z,dist=Math.hypot(dx,dy,dz); + b.yaw=wrap(b.yaw+N.clamp(wrap(Math.atan2(dx,dz)-b.yaw),-b.turn*M.helpers.BIN,b.turn*M.helpers.BIN));const sp=V.flySpeed*b.speedK*MOVE; + const c=Math.min(1,dist/Math.max(1,sp));b.x+=Math.sin(b.yaw)*Math.min(sp,Math.hypot(dx,dz));b.z+=Math.cos(b.yaw)*Math.min(sp,Math.hypot(dx,dz));b.y+=N.clamp(dy,-sp,sp); + b.trail.unshift({x:b.x,y:b.y,z:b.z});if(b.trail.length>V.bodySeg)b.trail.pop(); + if(b.mode==='chase'){b.chaseY=Math.max(V.chaseFloor,b.chaseY-1);b.flyTarget={x:h.x,y:h.y+30+b.chaseY+Math.sin(b.af*2396*M.helpers.BIN)*30,z:h.z}; + if(b.t0%V.breathEvery===0&&b.t0<450&&Math.abs(wrap(yawTo(b,h)-b.yaw))<.6){b.breathT=V.breathFor;g.ev('volvagia_breath');} + if(b.t0===0||b.hitFly){b.hitFly=false;toHole(g,b);}} + else if(b.mode==='ceiling'){b.flyTarget={x:0,y:V.ceilY+60,z:-300};if(b.y>V.ceilY){b.mode='rocks';b.t0=V.flyCeil;b.rocksT=V.rockFor;g.ev('volvagia_ceiling');}} + else if(b.mode==='rocks'){b.flyTarget={x:b.ceilTargets[Math.floor(b.af/25)%6].x,y:V.ceilY+60,z:b.ceilTargets[Math.floor(b.af/25)%6].z};if(b.t0===0)toHole(g,b);} + else if(b.mode==='toHole'){if(dist<100){setAct(b,'burrow',V.sink*2);b.y=0;b.trail=[];g.ev('volvagia_dive');}} + if(b.breathT>0){b.breathT--;const d=hd(b,h),off=Math.abs(wrap(yawTo(b,h)-b.yaw));if(di%3===0))if(Math.hypot(s.x-h.x,s.z-h.z)0){b.rocksT--;if(b.rocksT%V.rockEvery===0){const r=V.rockR[0]+Math.floor(g.rand()*V.rockR[1]);b.rocks.push({x:b.x+(g.rand()-.5)*80,y:600,z:b.z+(g.rand()-.5)*80,oy:600,r:r*.3,vy:0});g.ev('rock_fall');}} + const h=g.hero;b.rocks=b.rocks.filter(q=>{q.oy=q.y;q.vy-=1.6;q.y+=q.vy*MOVE;if(q.y<=q.r){g.fxAdd('burst',q.x,8,q.z,10,{r:q.r*1.4,color:0xb06a3a});if(Math.hypot(q.x-h.x,q.z-h.z)0){b.inv--;return;}const s=g.strike();if(!s||s.id===b.lastSlash)return; + const q=headOf(b);if(!['peek','rise','idle','swipe','fire','vuln'].includes(b.act)||b.y<-10&&b.act!=='vuln')return; + if(!g.swordReach(q.x,q.y-(h.weapon==='hammer'?40:0),q.z,V.headR+(h.weapon==='hammer'?20:0)))return;b.lastSlash=s.id; + if(!b.exposed){if(h.weapon!=='hammer')return;b.hp-=g.T.hammer;if(b.hp<=2)b.hp=1;b.exposed=true;setAct(b,'vuln',0);b.inv=V.invHammer;g.ev('volvagia_hammered');g.fxAdd('burst',q.x,q.y,q.z,10,{r:30,color:0xffe0a0});return;} + if(h.weapon==='hammer'){if(b.hp>2){b.hp-=2;}}else b.hp-=s.dmg;g.ev('volvagia_hit');b.inv=6; + if(b.hp<=0){b.hp=0;setAct(b,'dead',50);g.ev('boss_dead');}} + M.register('volvagia',{ + cases:[{id:'zelda/burrowing_fire_dragon',name:'Burrowing Fire Dragon (Young Swordsman · Heavy Hammer)'}], + arena:{r:V.roomR,ceil:820,start:[0,-380]},hearts:10,age:'adult',camDist:340,tune:TUNE,art:'volvagia', + item:{kind:'hammer',name:'Heavy Hammer: L switches hammer / sword'},threats:{volvagia_emerge:1,volvagia_fire:1,volvagia_swipe:1,volvagia_fly:1,rock_fall:1,hero_hurt:1}, + // The C item swaps the hammer in for the sword: J then swings the hammer (slower, the only thing that dents his skull plate, V4). + useItem(g){const h=g.hero;h.weapon=h.weapon==='hammer'?'sword':'hammer';h.itemCd=8;g.ev('weapon_swap');}, + init(g){const b=g.boss;Object.assign(b,{x:0,y:-200,z:0,ox:0,oy:-200,oz:0,yaw:0,hp:Math.round(g.T.hp),maxHp:Math.round(g.T.hp),t0:0,af:0,hole:-1,holesTried:0,holeCount:0,fakes:0,exposed:false,inv:0,lastSlash:-1, + breath:0,flyCount:0,mode:'',trail:[],chaseY:0,turn:1000,speedK:1,flyTarget:{x:0,y:0,z:0},ceilTargets:[],breathT:0,rocksT:0,rocks:[],hitFly:false});setupEmerge(g,b);g.hero.weapon='sword';}, + update(g){const b=g.boss,h=g.hero;if(b.t0>0)b.t0--; + if(b.act==='dead'){if(b.t0===0)g.outcome='win';return;} + ACT[b.act](g,b,h);if(g.outcome)return;rocks(g,b);hitCheck(g,b); + if(['rise','idle','swipe','fire'].includes(b.act)&&hd(b,h)h.lastKeys.includes(k)?[]:[k],free=H.act==='idle'; + if(b.act==='dead'||H.act==='dead'||H.act==='kb')return []; + const want=b.exposed?'sword':'hammer';if(free&&H.weapon!==want&&H.itemCd===0&&['peek','rise','idle','swipe','fire','vuln','under'].includes(b.act))return tap('L'); + const safe=(keys,n)=>{const s=cloneGame(h);for(let i=0;i{for(const o of [0,.7,-.7,1.4,-1.4,2.2,-2.2,PI]){const k=stickTo(h,wrap(yaw+o));if(safe(k,24))return k;}for(const o of [0,PI/2,-PI/2,PI]){const k=[...stickTo(h,wrap(yaw+o)),'Space'];if(safe(k,18))return k;}return stickTo(h,yaw);}; + // Flying: keep moving away from him and from falling rocks; nothing to hit. + if(b.act==='fly'){if(!free)return [];if(safe([],24))return [];return dodge(yawTo(b,H));} + // Up out of a hole: walk to the head and strike while he is idle; leave his breath cone and claw. + if(['rise','idle','swipe','fire','vuln','peek'].includes(b.act)){const q=headOf(b),d=Math.hypot(q.x-H.x,q.z-H.z),reach=M.constants.reach.adult+V.headR-6; + if(!free)return ['Shift']; + const keys=['Shift'];if(b.act==='peek'){if(d>140)keys.push(...stickTo(h,yawTo(H,q)));return keys;} + if(d>reach){const k=stickTo(h,yawTo(H,q));if(safe([...keys,...k],12))keys.push(...k);else keys.push(...dodge(yawTo(b,H)));return keys;} + if(b.inv===0&&safe([...keys,'J'],6)||b.act==='vuln')keys.push(...tap('J'));else keys.push(...dodge(yawTo(b,H)));return keys;} + // Underground: wait near the middle. + if(Math.hypot(H.x,H.z)>140&&free)return stickTo(h,yawTo(H,{x:0,z:0}));return [];}; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/compact_actions.json b/environments/games/web/games/zelda_oot_remake/compact_actions.json new file mode 100644 index 0000000000000000000000000000000000000000..9b1e0338f5ce7e5671cd2f650653af146be14a27 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/compact_actions.json @@ -0,0 +1,582 @@ +{ + "schema": "bossbench/compact-actions@1", + "game": "zelda_oot_remake", + "version": "zelda_oot_remake-compact@3", + "note": "A 200 ms packet spans four logic frames. Brief movement and press-triggered actions can target individual frames. Movement is camera-relative. Hold the lock-on key to face the target. Q and E orbit the camera by 45 degrees. R resets the camera offset.", + "heads": [ + { + "name": "lock", + "options": [ + { + "label": "none" + }, + { + "label": "hold", + "keys": [ + "Shift" + ] + } + ] + }, + { + "name": "move", + "options": [ + { + "label": "none" + }, + { + "label": "forward", + "keys": [ + "W" + ] + }, + { + "label": "back", + "keys": [ + "S" + ] + }, + { + "label": "left", + "keys": [ + "A" + ] + }, + { + "label": "right", + "keys": [ + "D" + ] + }, + { + "label": "forward_left", + "keys": [ + "W", + "A" + ] + }, + { + "label": "forward_right", + "keys": [ + "W", + "D" + ] + }, + { + "label": "back_left", + "keys": [ + "S", + "A" + ] + }, + { + "label": "back_right", + "keys": [ + "S", + "D" + ] + }, + { + "label": "forward_step", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [ + "W" + ], + [], + [], + [] + ] + }, + { + "label": "back_step", + "subs": [ + [ + "S" + ], + [ + "S" + ], + [ + "S" + ], + [], + [], + [] + ] + }, + { + "label": "left_step", + "subs": [ + [ + "A" + ], + [ + "A" + ], + [ + "A" + ], + [], + [], + [] + ] + }, + { + "label": "right_step", + "subs": [ + [ + "D" + ], + [ + "D" + ], + [ + "D" + ], + [], + [], + [] + ] + }, + { + "label": "forward_left_step", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [], + [] + ] + }, + { + "label": "forward_right_step", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [], + [] + ] + }, + { + "label": "back_left_step", + "subs": [ + [ + "S", + "A" + ], + [ + "S", + "A" + ], + [ + "S", + "A" + ], + [], + [], + [] + ] + }, + { + "label": "back_right_step", + "subs": [ + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [ + "S", + "D" + ], + [], + [], + [] + ] + }, + { + "label": "forward_f1", + "subs": [ + [ + "W" + ], + [ + "W" + ], + [], + [], + [], + [] + ] + }, + { + "label": "forward_left_f1", + "subs": [ + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [], + [], + [], + [] + ] + }, + { + "label": "forward_right_f1", + "subs": [ + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [], + [], + [], + [] + ] + }, + { + "label": "forward_f3", + "subs": [ + [], + [], + [], + [ + "W" + ], + [ + "W" + ], + [] + ] + }, + { + "label": "forward_left_f3", + "subs": [ + [], + [], + [], + [ + "W", + "A" + ], + [ + "W", + "A" + ], + [] + ] + }, + { + "label": "forward_right_f3", + "subs": [ + [], + [], + [], + [ + "W", + "D" + ], + [ + "W", + "D" + ], + [] + ] + }, + { + "label": "forward_f4", + "subs": [ + [], + [], + [], + [], + [], + [ + "W" + ] + ] + } + ] + }, + { + "name": "act", + "options": [ + { + "label": "none" + }, + { + "label": "slash_f1", + "subs": [ + [ + "J" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "slash_f2", + "subs": [ + [], + [], + [ + "J" + ], + [], + [], + [] + ] + }, + { + "label": "slash_f3", + "subs": [ + [], + [], + [], + [ + "J" + ], + [], + [] + ] + }, + { + "label": "slash_f4", + "subs": [ + [], + [], + [], + [], + [], + [ + "J" + ] + ] + }, + { + "label": "shield", + "keys": [ + "K" + ] + }, + { + "label": "shield_late", + "subs": [ + [], + [], + [], + [ + "K" + ], + [ + "K" + ], + [ + "K" + ] + ] + }, + { + "label": "shield_early", + "subs": [ + [ + "K" + ], + [ + "K" + ], + [ + "K" + ], + [], + [], + [] + ] + }, + { + "label": "jump_f1", + "subs": [ + [], + [ + "Space" + ], + [], + [], + [], + [] + ] + }, + { + "label": "jump_f2", + "subs": [ + [], + [], + [ + "Space" + ], + [], + [], + [] + ] + }, + { + "label": "jump_f3", + "subs": [ + [], + [], + [], + [ + "Space" + ], + [], + [] + ] + }, + { + "label": "jump_f4", + "subs": [ + [], + [], + [], + [], + [], + [ + "Space" + ] + ] + }, + { + "label": "item_f1", + "subs": [ + [ + "L" + ], + [], + [], + [], + [], + [] + ] + }, + { + "label": "item_f2", + "subs": [ + [], + [], + [ + "L" + ], + [], + [], + [] + ] + }, + { + "label": "item_f3", + "subs": [ + [], + [], + [], + [ + "L" + ], + [], + [] + ] + }, + { + "label": "item_f4", + "subs": [ + [], + [], + [], + [], + [], + [ + "L" + ] + ] + }, + { + "label": "struggle", + "subs": [ + [ + "J" + ], + [ + "Space" + ], + [], + [ + "J" + ], + [ + "Space" + ], + [] + ] + }, + { + "label": "cam_left", + "tap": [ + "Q" + ] + }, + { + "label": "cam_right", + "tap": [ + "E" + ] + }, + { + "label": "cam_reset", + "tap": [ + "R" + ] + } + ] + } + ] +} diff --git a/environments/games/web/games/zelda_oot_remake/draw.js b/environments/games/web/games/zelda_oot_remake/draw.js new file mode 100644 index 0000000000000000000000000000000000000000..51851dffd4a9519aec927a1ab4242801f408c4fb --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/draw.js @@ -0,0 +1,39 @@ +/* HUD drawn over the WebGL frame: hearts, boss bar, timer, native Hz, tier, item, per-boss hint. Reads state only. */ +(function(root){ + 'use strict';const M=root.ZeldaOotGame,R=root.ZeldaOot3D; + const NAMES={goma:['One-Eyed Carapace Queen','ONE-EYED CARAPACE QUEEN'],dodongo:['Magma Cave Lizard King','MAGMA CAVE LIZARD KING'],ganondrof:['Gallery Specter','GALLERY SPECTER'],volvagia:['Burrowing Fire Dragon','BURROWING FIRE DRAGON'],morpha:['Water-Core Amoeba','WATER CORE AMOEBA'],twinrova:['Twin Flame-Frost Witches','TWIN FLAME FROST WITCHES']}; + const ACT={idle:'',slash:'Sword slash',spin:'Spin attack',jumpslash:'Jump slash',roll:'Roll',hop:'Side hop',land:'Landing',kb:'Knocked back',dead:'Down'}; + function text(c,s,x,y,size,color,align='left',weight='bold'){c.font=`${weight} ${size}px "Segoe UI","Microsoft YaHei",sans-serif`;c.textAlign=align;c.lineJoin='round';c.lineWidth=Math.max(3,size/4.5);c.strokeStyle='rgba(10,12,24,.88)';c.strokeText(s,x,y);c.fillStyle=color;c.fillText(s,x,y);} + function heart(c,x,y,r,k){c.save();c.translate(x,y);const path=()=>{c.beginPath();c.moveTo(0,r*.9);c.bezierCurveTo(-r*1.3,-r*.1,-r*.7,-r,0,-r*.35);c.bezierCurveTo(r*.7,-r,r*1.3,-r*.1,0,r*.9);c.closePath();}; + path();c.fillStyle='rgba(30,16,22,.82)';c.fill();if(k>0){c.save();path();c.clip();c.fillStyle='#ef4a56';c.fillRect(-r*1.4,-r*1.2,r*2.8*k,r*2.4);c.restore();}path();c.lineWidth=1.6;c.strokeStyle='#f8eede';c.stroke();c.restore();} + function tierName(d){for(const [k,v] of Object.entries(M.tiers))if(Math.abs(v-d)<1e-9)return k;return 'd='+(+d).toFixed(2);} + // Aim aids drawn in 2D over the frame, so walls never hide them: a lock reticle on the locked target, a small marker on lockable targets, + // and at the frame edge an arrow toward the boss or an active threat that is out of view. Everything comes from the state through the view's own camera. + function reticle(c,x,y,r,a,col,ring){c.save();c.translate(x,y);c.lineWidth=4;c.strokeStyle='rgba(10,12,24,.9)';c.beginPath();c.arc(0,0,r,0,PI2);c.stroke();c.lineWidth=2.5;c.strokeStyle=ring||col;c.beginPath();c.arc(0,0,r,0,PI2);c.stroke(); + for(let i=0;i<4;i++){const o=a+i*PI2/4;c.save();c.rotate(o);c.beginPath();c.moveTo(0,-r-3);c.lineTo(-7,-r-15);c.lineTo(7,-r-15);c.closePath();c.fillStyle=col;c.fill();c.lineWidth=1.5;c.strokeStyle='rgba(10,12,24,.9)';c.stroke();c.restore();} + c.fillStyle=col;c.beginPath();c.arc(0,0,2.5,0,PI2);c.fill();c.restore();} + function edgeArrow(c,p,col,label){const m=34,ax=p.dx,ay=p.dy,k=Math.min((427-m)/Math.max(1e-6,Math.abs(ax)),(240-m)/Math.max(1e-6,Math.abs(ay))),x=427+ax*k,y=240+ay*k,a=Math.atan2(ay,ax); + c.save();c.translate(x,y);c.rotate(a);c.beginPath();c.moveTo(18,0);c.lineTo(-10,-13);c.lineTo(-4,0);c.lineTo(-10,13);c.closePath();c.fillStyle=col;c.fill();c.lineWidth=2.5;c.strokeStyle='rgba(10,12,24,.92)';c.stroke();c.restore(); + if(label)text(c,label,x-Math.cos(a)*30,y-Math.sin(a)*30+5,12,col,'center');} + const PI2=Math.PI*2; + function aimAids(g,c,def){const P=(x,y,z)=>R.project(c,x,y,z);if(!R.project)return;const lock=g.lockTarget(),ts=g.targets(); + for(const q of ts){if(lock&&q.id===lock.id)continue;const p=P(q.x,q.y,q.z);if(p&&p.on){c.beginPath();c.moveTo(p.x,p.y-26);c.lineTo(p.x-7,p.y-38);c.lineTo(p.x+7,p.y-38);c.closePath();c.fillStyle='rgba(255,236,160,.9)';c.fill();c.lineWidth=1.5;c.strokeStyle='rgba(10,12,24,.9)';c.stroke();}} + if(lock){const p=P(lock.x,lock.y,lock.z),h=g.hero,d=Math.hypot(lock.x-h.x,lock.z-h.z),reach=M.constants.reach[h.age]+24,inReach=d<=reach&&lock.y-24<=h.y+96; + // The reticle closes in as the hero does (ring radius from the hero-target distance: a range finder in the picture) and its ring turns orange once the target is within a sword's reach. + if(p&&p.on)reticle(c,p.x,p.y,14+18*Math.max(0,Math.min(1,(d-reach)/360)),g.t*(inReach?.2:.09),'#ffd34a',inReach?'#ff7a2a':null);else if(p)edgeArrow(c,p,'#ffd34a','Lock');} + // The boss gets its own arrow whenever it is off screen and the lock is on something else (a larva, an egg) or on nothing. + const b=def.marker?def.marker(g):null;if(b&&(!lock||Math.hypot(lock.x-b.x,lock.y-b.y,lock.z-b.z)>90)){const p=P(b.x,b.y,b.z);if(p&&!p.on)edgeArrow(c,p,'#ffb07a','Boss');} + for(const w of def.dangers?def.dangers(g):[]){const p=P(w.x,w.y,w.z);if(p&&!p.on)edgeArrow(c,p,'#ff4a3a',w.label||'Danger');}} + M.draw=function(g,c){R.render(g,c);const h=g.hero,def=g.def(),[hp,maxHp,bh,bm]=g.health(),n=Math.ceil(maxHp/16);aimAids(g,c,R.art[g.kind]||{}); + for(let i=0;iq.id===g.id)||{}).name||'').split(' (')[0],''];text(c,`${cn} ${en}`,427,28,18,'#fff4d6','center'); + const w=300;c.fillStyle='rgba(16,16,34,.82)';c.fillRect(427-w/2,36,w,12);c.fillStyle='#ffbf4a';c.fillRect(427-w/2+2,38,(w-4)*(bm?bh/bm:0),8);c.strokeStyle='#f6f2e6';c.lineWidth=1.4;c.strokeRect(427-w/2,36,w,12);text(c,`${bh} / ${bm}`,427,64,12,'#fff','center'); + const s=g.t/M.hz,mm=Math.floor(s/60),ss=(s%60).toFixed(1).padStart(4,'0');text(c,`${mm}:${ss}`,830,30,20,'#fff','right');text(c,`${M.hz}Hz`,830,52,14,'#9fe7ff','right');text(c,tierName(g.d).toUpperCase(),830,72,13,'#ffd23a','right'); + if(def.item)text(c,`C Item: ${def.item.name} (L)`,22,78,13,'#ffe9a8');if(ACT[h.act])text(c,ACT[h.act],22,98,14,'#fff'); + if(h.charge>0){c.fillStyle='rgba(16,16,34,.82)';c.fillRect(22,108,110,8);c.fillStyle=h.charge>=.85?'#9fe7ff':'#6a7fb0';c.fillRect(23,109,108*h.charge,6);} + if(h.lock!==null)text(c,'Lockin',22,130,13,'#ffd34a'); + const tip=def.hud?def.hud(g):'';if(tip)text(c,tip,427,430,16,'#fff3c4','center','600'); + if(g.outcome==='win')text(c,'★ Boss defeated',427,226,40,'#ffe24a','center');if(g.outcome==='loss')text(c,'You fell',427,226,40,'#ff6b5b','center');if(g.outcome==='timeout')text(c,'Time up',427,226,40,'#ffd0c0','center'); + text(c,'WASD run · Space roll/dodge · Shift lock · J sword · K shield · L item · Q/E camera',832,466,12,'#d8e8ff','right','600');}; + M.renderStatus=ctx=>R.status(ctx);M.renderMetrics=ctx=>R.metrics(ctx);M.closeRenderer=ctx=>R.close(ctx); +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/game.js b/environments/games/web/games/zelda_oot_remake/game.js new file mode 100644 index 0000000000000000000000000000000000000000..e7c9de64edb1ecb4aadd4c1e9c6b999d7836f194 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/game.js @@ -0,0 +1,154 @@ +/* The Legend of Zelda: Ocarina of Time (N64, 1998): boss trials as an independent deterministic simulation (rules: M.version). + * Rules and numbers are facts read from the zeldaret/oot decompilation at commit 14759abf (no code, comments or assets + * copied). The original's game logic runs at 20 Hz (R_UPDATE_RATE = 3 on a 60 Hz VI); + * the shell runs 60 Hz and every third tick runs one logic frame, so constants keep their per-frame source values. + * Positions move by velocity x 1.5 per logic frame, as the original's position update does at that rate. */ +(function(root){ + 'use strict'; + const N=root.NativeBench,PI=Math.PI,BIN=PI*2/65536,MOVE=1.5,K=3; + const wrap=a=>N.angle(a),hd=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z),yawTo=(a,b)=>Math.atan2(b.x-a.x,b.z-a.z); + // Same behaviour as the source's approach helpers, in radians where the original uses binary angles. + const approachF=(v,t,scale,step)=>v+N.clamp((t-v)*scale,-step,step); + const approachS=(c,t,scale,step)=>wrap(c+N.clamp(wrap(t-c)/scale,-step*BIN,step*BIN)); + const stepF=(v,t,s)=>vvwrap(c+N.clamp(wrap(t-c),-s*BIN*MOVE,s*BIN*MOVE)); + // Reference player constants with approximate action lengths. + const P={heart:16,runCap:6,accel:2,decel:1.5,stop:8,turn:2000,gravity:1,rollFrames:16,rollInvFrom:6,rollInv:10,rollMin:3,rollMul:1.5, + hopBackVy:5.8,hopSideVy:3.5,hopBack:6,hopSide:8.5,jumpVy:5,jumpFwd:5,hurtInv:20,kbSpeed:4,kbVy:5,kbRecover:18,chargeStep:.02,chargeNeed:.85, + radius:12,height:60,seedSpeed:80,arrowSpeed:150, + slashFrames:[10,10,14],slashActive:[[1,4],[1,4],[0,5]],comboFrom:5,reach:{child:48,adult:62},itemCd:12,spinFrames:14,spinReach:1.3,shieldArc:1.2,deadFrames:30}; + const SWORD={child:{slash:1,jump:2,spin:1},adult:{slash:2,jump:4,spin:2}}; + const TIERS={easy:.2,normal:.5,hard:.8}; + // Each tuning row is [source value, easy, normal, hard] at d = 0 / .2 / .5 / .8, piecewise linear; past hard the last slope continues. + const lerpTune=(r,d)=>{const X=[0,.2,.5,.8];let i=0;while(i<2&&d>X[i+1])i++;return r[i]+(r[i+1]-r[i])*(d-X[i])/(X[i+1]-X[i]);}; + const M=root.ZeldaOotGame={id:'zelda_oot_remake',version:'oot-arena@5',hz:60,maxSeconds:300,dimension:'3d',renderer:'webgl-zelda-oot', + title:'Ancient Sword Legend: Boss Trials',tiers:TIERS,cases:[],bosses:{},plans:{},constants:P, + controls:{'W A S D':'Run relative to camera direction (full analog-stick deflection)','Space':'A: roll while unlocked (invulnerable frames); while locked, forward = jump slash, back = back hop, left/right = side hop.', + 'Shift':'Z: hold to lock onto the nearest target; press again to switch. Face the target while locked.','J / LMB':'B: swing sword; press repeatedly for a three-hit combo. Hold to charge, release for a spin attack.','K / RMB':'R: hold shield to block attacks from the front.', + 'L':'C: use the item for this fight (auto-aim while locked; otherwise aim forward).','Q / E':'Turn camera left/right by 45°','R':'reset the camera','MouseMove':'Rotate camera; vertical movement changes unlocked aim pitch.'}, + helpers:{wrap,hd,yawTo,approachF,approachS,stepF,stepAsym,stepYaw,BIN,MOVE,lerpTune}}; + M.register=(key,def)=>{M.bosses[key]=def;M.plans[key]=def.plan;for(const c of def.cases)M.cases.push({id:c.id,name:c.name,boss:key});}; + M.difficultyBand=d=>d===0?'source':d<=.2?'source-easy':d<=.5?'easy-normal':d<=.8?'normal-hard':'beyond-hard'; + // Planning copies draw from this instead of the live generator: a multiplicative mix of tick, draw count and salt, so nothing not yet drawn can reach a plan. + const planMix=(t,n,s)=>{let x=Math.imul(t+1,0x9e3779b1)^Math.imul(n+1,0x85ebca6b)^Math.imul(s+1,0xc2b2ae35);x=Math.imul(x^(x>>>15),0x2c1b3c6d);x=Math.imul(x^(x>>>12),0x297a2d39);return ((x^(x>>>15))>>>0)/4294967296;}; + class Game{ + constructor(id,seed,d){ + const c=M.cases.find(q=>q.id===id);if(!c)throw Error('Unknown case '+id); + this.id=id;this.seed=seed;this.d=d;this.t=0;this.outcome=null;this.events=[];this.sub=0;this.frame=0;this.draws=0; + this.rng=(Math.imul((seed^0x6f6f7421)>>>0,0x9e3779b1)>>>0)||1; + this.inp={press:[],mouse:[0,0]};this.shots=[];this.fx=[];this.lastKeys=[]; + const def=M.bosses[c.boss];this.kind=c.boss;this.T={};for(const k of Object.keys(def.tune))this.T[k]=lerpTune(def.tune[k],d); + const a=def.arena;this.arena={r:a.r,ceil:a.ceil,square:a.square||0}; + this.hero={x:a.start[0],y:0,z:a.start[1],ox:a.start[0],oy:0,oz:a.start[1],vy:0,speed:0,yaw:PI,face:PI,act:'idle',timer:0, + hp:def.hearts*P.heart,maxHp:def.hearts*P.heart,inv:0,lock:null,combo:0,slashId:0,charge:0,itemCd:0,shield:false,age:def.age,airSlash:false,flash:0,grabbed:false,mode:0}; + this.cam={yaw:PI,offset:0,dist:def.camDist||360,oyaw:PI,pitchAim:0}; + this.boss={kind:c.boss,hp:1,maxHp:1,act:'init',timer:0};def.init(this); + this.cam.yaw=this.cam.oyaw=this.hero.face; + } + rand(){if(this.blind!==undefined)return planMix(this.t,this.draws++,this.blind);this.draws++;return N.rand(this);} + randS(base,range){return base+Math.floor(this.rand()*range);} + ev(name){this.events.push(name);} + fxAdd(kind,x,y,z,life,extra){if(this.fx.length<48)this.fx.push(Object.assign({kind,x,y,z,life,max:life},extra||{}));} + def(){return M.bosses[this.kind];} + // fromYaw is the direction of the push, so the attacker stands at fromYaw + PI from the hero. Returns true (hurt), 'block', or false (no effect). + hurt(dmg,fromYaw,opt){const h=this.hero,o=opt||{};if(this.outcome||h.act==='dead'||h.inv!==0||(h.grabbed&&!o.grab))return false; + if(!o.unblockable&&h.shield&&Math.abs(wrap(fromYaw+PI-h.face))reach)return false; + if(!spin&&d>r&&Math.abs(wrap(Math.atan2(tx-h.x,tz-h.z)-h.face))>1.1)return false; + return ty+r>=h.y-10&&ty-r<=h.y+P.height+36;} + strike(){const h=this.hero; + if(h.act==='slash'){const [a,b]=P.slashActive[h.combo];return h.timer>=a&&h.timer<=b?{id:h.slashId,dmg:SWORD[h.age][h.airSlash?'jump':'slash'],kind:h.airSlash?'jump':'slash'}:null;} + if(h.act==='jumpslash')return h.vy<0?{id:h.slashId,dmg:SWORD[h.age].jump,kind:'jump'}:null; + if(h.act==='spin')return h.timer<=P.spinFrames-2?{id:h.slashId,dmg:SWORD[h.age].spin,kind:'spin'}:null; + return null;} + targets(){return this.def().targets(this);} + lockTarget(){const h=this.hero;return h.lock===null?null:this.targets().find(q=>q.id===h.lock)||null;} + confine(e,rad){const A=this.arena;if(A.square){const m=A.square-rad;e.x=N.clamp(e.x,-m,m);e.z=N.clamp(e.z,-m,m);return;} + const d=Math.hypot(e.x,e.z),m=A.r-rad;if(d>m){e.x*=m/d;e.z*=m/d;}} + stickFrom(held){const f=(held.has('W')?1:0)-(held.has('S')?1:0),s=(held.has('A')?1:0)-(held.has('D')?1:0);return !f&&!s?null:wrap(this.cam.yaw+this.cam.offset+Math.atan2(s,f));} + updateLock(held,press){const h=this.hero;if(!held.has('Shift')){h.lock=null;return;} + const ts=this.targets(),here=ts.some(q=>q.id===h.lock);if(!press.has('Shift')&&here)return; + let best=null,bd=1e9;for(const q of ts){const d=Math.hypot(q.x-h.x,q.z-h.z);if(d0)return; + if(it.kind==='seed'||it.kind==='arrow'){const t=this.lockTarget(),sp=it.kind==='seed'?P.seedSpeed:P.arrowSpeed,y0=h.y+(h.age==='child'?30:44);let yaw=h.face,pitch=this.cam.pitchAim; + if(t){yaw=Math.atan2(t.x-h.x,t.z-h.z);pitch=Math.atan2(t.y-y0,Math.hypot(t.x-h.x,t.z-h.z));h.face=yaw;} + const x=h.x+Math.sin(yaw)*14,z=h.z+Math.cos(yaw)*14; + this.shots.push({kind:it.kind,x,y:y0,z,ox:x,oy:y0,oz:z,vx:Math.sin(yaw)*Math.cos(pitch)*sp,vy:Math.sin(pitch)*sp,vz:Math.cos(yaw)*Math.cos(pitch)*sp,life:18}); + h.itemCd=it.cd||P.itemCd;this.ev('item_fire');} + else if(def.useItem)def.useItem(this);} + updateHero(held,press){const h=this.hero,def=this.def(); + if(h.inv>0)h.inv--;else if(h.inv<0)h.inv++;if(h.itemCd>0)h.itemCd--;if(h.flash>0)h.flash--; + if(h.grabbed){h.lock=null;return;} + const yawS=this.stickFrom(held);this.updateLock(held,press);const T=this.lockTarget(),J=held.has('J')||held.has('LMB'),jp=press.has('J')||press.has('LMB'); + h.mode=T?1:0;h.shield=false; + if(h.act==='idle'){ + if(held.has('K')||held.has('RMB'))h.shield=true; + if(press.has('Space')){ + if(T){const dir=yawS===null?0:wrap(yawS-h.face),ab=Math.abs(dir); + if(ab>2.36){h.act='hop';h.timer=0;h.yaw=wrap(h.face+PI);h.speed=P.hopBack;h.vy=P.hopBackVy;this.ev('backhop');} + else if(ab>.79){h.act='hop';h.timer=0;h.yaw=wrap(h.face+(dir>0?PI/2:-PI/2));h.speed=P.hopSide;h.vy=P.hopSideVy;this.ev('sidehop');} + else{h.act='jumpslash';h.timer=0;h.yaw=h.face;h.speed=P.jumpFwd;h.vy=P.jumpVy;h.airSlash=true;h.slashId++;h.shield=false;this.ev('jumpslash');}} + else if(yawS!==null){h.act='roll';h.timer=0;h.face=yawS;h.yaw=yawS;h.shield=false;this.ev('roll');}} + if(h.act==='idle'&&jp&&!h.shield){h.act='slash';h.timer=0;h.combo=0;h.airSlash=false;h.slashId++;h.charge=0;this.ev('slash');} + if(h.act==='idle'&&press.has('L')&&!h.shield)this.fireItem(); + if(h.act==='idle'&&J&&!h.shield&&!jp)h.charge=Math.min(1,h.charge+P.chargeStep); + if(h.act==='idle'&&!J){if(h.charge>=P.chargeNeed){h.act='spin';h.timer=0;h.slashId++;h.speed=0;this.ev('spin');}h.charge=0;} + } + if(h.act==='idle'){ + if(h.shield){h.speed=stepF(h.speed,0,P.stop);if(T)h.face=stepYaw(h.face,Math.atan2(T.x-h.x,T.z-h.z),P.turn*2);} + else{const target=yawS===null?0:P.runCap*(h.charge>0?.5:1); + if(yawS!==null){if(T)h.yaw=yawS;else if(Math.abs(wrap(yawS-h.yaw))>2.6&&h.speed>2)h.speed=stepF(h.speed,0,P.stop);else h.yaw=stepYaw(h.yaw,yawS,P.turn*2);} + h.speed=stepAsym(h.speed,target,P.accel,P.decel); + if(T)h.face=stepYaw(h.face,Math.atan2(T.x-h.x,T.z-h.z),P.turn*2);else if(yawS!==null)h.face=h.yaw;} + }else if(h.act==='slash'){h.timer++;h.speed=stepF(h.speed,0,P.decel);if(T)h.face=stepYaw(h.face,Math.atan2(T.x-h.x,T.z-h.z),P.turn);h.yaw=h.face; + if(jp&&h.timer>=P.comboFrom&&h.combo<2){h.combo++;h.timer=0;h.airSlash=false;h.slashId++;this.ev('slash');} + else if(h.timer>=P.slashFrames[h.combo]){h.act='idle';h.combo=0;h.timer=0;h.airSlash=false;} + }else if(h.act==='spin'){h.timer++;h.face=wrap(h.face+PI*2/P.spinFrames);if(h.timer>=P.spinFrames){h.act='idle';h.timer=0;} + }else if(h.act==='roll'){h.timer++;if(h.timer===P.rollInvFrom&&h.inv>=0)h.inv=-P.rollInv; + h.speed=stepAsym(h.speed,yawS!==null?Math.max(P.rollMin,P.runCap*P.rollMul):P.rollMin,P.accel,P.decel); + if(h.timer>=P.rollFrames){h.act='idle';h.timer=0;} + }else if(h.act==='hop'||h.act==='jumpslash'){h.vy-=P.gravity;h.y+=h.vy*MOVE;h.timer++; + if(h.y<=0&&h.vy<0){h.y=0;h.vy=0; + if(h.act==='jumpslash'){h.act='slash';h.combo=0;h.timer=1;h.speed=0;}else{h.act='land';h.timer=3;h.speed=0;}} + }else if(h.act==='land'){if(--h.timer<=0){h.act='idle';h.timer=0;} + }else if(h.act==='kb'){h.vy-=P.gravity;h.y+=h.vy*MOVE;if(h.y<=0){h.y=0;h.vy=0;h.speed=stepF(h.speed,0,1);if(--h.timer<=0){h.act='idle';h.timer=0;h.speed=0;}} + }else if(h.act==='dead'){if(--h.timer<=0)this.outcome='loss';return; + }else if(def.heroAct)def.heroAct(this,held,press,yawS); + h.x+=Math.sin(h.yaw)*h.speed*MOVE;h.z+=Math.cos(h.yaw)*h.speed*MOVE;this.confine(h,P.radius); + } + updateShots(){const def=this.def();this.shots=this.shots.filter(s=>{s.ox=s.x;s.oy=s.y;s.oz=s.z;s.life--; + const steps=Math.ceil(Math.hypot(s.vx,s.vy,s.vz)*MOVE/15)||1; + for(let i=0;ithis.arena.ceil||Math.hypot(s.x,s.z)>this.arena.r+40)return false;} + return s.life>0;});} + updateCam(mouse,press){const c=this.cam,h=this.hero,f=this.def().focus(this);c.oyaw=c.yaw; + if(press.has('Q'))c.offset=wrap(c.offset+PI/4);if(press.has('E'))c.offset=wrap(c.offset-PI/4);if(press.has('R'))c.offset=0; + c.offset=wrap(c.offset-mouse[0]*.0035);c.pitchAim=N.clamp(c.pitchAim-mouse[1]*.003,-.4,1.2); + if(Math.hypot(f.x-h.x,f.z-h.z)>40)c.yaw=wrap(c.yaw+N.clamp(wrap(Math.atan2(f.x-h.x,f.z-h.z)-c.yaw),-.14,.14));} + logic(held,press,mouse){this.frame++;const h=this.hero,b=this.boss;h.ox=h.x;h.oy=h.y;h.oz=h.z;if(b.x!==undefined){b.ox=b.x;b.oy=b.y;b.oz=b.z;} + this.updateCam(mouse,press);this.updateHero(held,press);if(this.outcome)return; + this.updateShots();this.def().update(this); + this.fx=this.fx.filter(q=>{q.life--;q.x+=q.vx||0;q.y+=q.vy||0;q.z+=q.vz||0;return q.life>0;});} + update(held,pressed,mouse){const I=this.inp;for(const k of pressed)if(!I.press.includes(k))I.press.push(k);I.mouse[0]+=mouse[0];I.mouse[1]+=mouse[1]; + this.lastKeys=[...held].sort();this.sub=(this.sub+1)%K;if(this.sub!==0)return; + const press=new Set(I.press),ms=I.mouse;this.inp={press:[],mouse:[0,0]};this.logic(held,press,ms);} + health(){const h=this.hero,b=this.boss;return [Math.max(0,h.hp),h.maxHp,this.outcome==='win'?0:Math.max(0,Math.min(b.hp,b.maxHp)),b.maxHp];} + } + M.Game=Game; + /* Scripted reference controller: plans on deep copies with blinded futures (planMix above) and returns legal holds only. */ + function cloneGame(g,salt){const c=Object.assign(Object.create(Game.prototype),N.copy(g));c.events=[];c.blind=salt===undefined?(g.blind===undefined?0:g.blind):salt;return c;} + function simTick(h,keys){const prev=new Set(h.lastKeys);h.events=[];h.update(new Set(keys),new Set(keys.filter(k=>!prev.has(k))),[0,0,0]);N.quantize(h);h.t++;if(h.t>=M.hz*M.maxSeconds&&!h.outcome)h.outcome='timeout';} + const STICK=[['W'],['W','A'],['A'],['S','A'],['S'],['S','D'],['D'],['W','D']]; + function stickTo(h,yaw){const r=wrap(yaw-h.cam.yaw-h.cam.offset),i=((Math.round(r/(PI/4))%8)+8)%8;return STICK[i];} + M.ctl={cloneGame,simTick,stickTo,STICK}; + M.scripted=function(game){const h=cloneGame(game,0),holds=[]; + for(let j=0;j<6;j++){const keys=h.outcome?[]:M.plans[h.kind](h).slice(0,4);holds.push(keys);for(let n=0;n<2&&!h.outcome;n++)simTick(h,keys);} + return {holds,mouse:[0,0,0]};}; + M.oracle=M.scripted; +})(typeof window==='undefined'?globalThis:window); diff --git a/environments/games/web/games/zelda_oot_remake/index.html b/environments/games/web/games/zelda_oot_remake/index.html new file mode 100644 index 0000000000000000000000000000000000000000..df90953e30101dc2ea08bf9936424137baa1630d --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/index.html @@ -0,0 +1,7 @@ +Ancient Sword Legend: Boss Trials
              +
              N64 · 1998 · Boss Trials

              Ancient Sword Legend: Boss Trials

              Third-person view, Z targeting, shield, and sword: each fight starts with one item. Mechanics were inferred from a public decompilation as read-only facts; characters, bosses, and arenas use original procedural art.

              Back to Game Lobby ↗
              +
              Are You Ready?ClickStart Challenge
              +

              The scripted demo reads internal state only to verify that each fight can be completed. Replays save actual inputs for deterministic full-battle and final-state verification.

              +
              +
              All rights in the original game, including its title, characters, artwork, audio, and trademarks, remain exclusively with its original game companies and rights holders. GameDojo is an independent reconstruction for non-commercial scientific research.
              + diff --git a/environments/games/web/games/zelda_oot_remake/manifest.json b/environments/games/web/games/zelda_oot_remake/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..5d300aba3d321a4d4f57f2482cd0bd6fec866ea4 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/manifest.json @@ -0,0 +1,52 @@ +{ + "schema": "bossbench/game-manifest@1", + "engine": "independent", + "game": "zelda_oot_remake", + "module": "ZeldaOotGame", + "title": "Ancient Sword Legend: Boss Trials", + "dimension": "3d", + "native_hz": 60, + "max_seconds": 300, + "renderer": "webgl-zelda-oot", + "rules": "oot-arena@5", + "cases": [ + "zelda/armored_spider_queen", + "zelda/lava_lizard_king", + "zelda/specter_rider", + "zelda/burrowing_fire_dragon", + "zelda/water_core_amoeba", + "zelda/twin_flame_frost_witches" + ], + "scripts": [ + "_native/runtime.js", + "_boss3d/vendor/three.min.js", + "zelda_oot_remake/renderer3d.js", + "zelda_oot_remake/art/goma.js", + "zelda_oot_remake/art/dodongo.js", + "zelda_oot_remake/art/ganondrof.js", + "zelda_oot_remake/art/volvagia.js", + "zelda_oot_remake/art/morpha.js", + "zelda_oot_remake/art/twinrova.js", + "zelda_oot_remake/game.js", + "zelda_oot_remake/bosses/goma.js", + "zelda_oot_remake/bosses/dodongo.js", + "zelda_oot_remake/bosses/ganondrof.js", + "zelda_oot_remake/bosses/volvagia.js", + "zelda_oot_remake/bosses/morpha.js", + "zelda_oot_remake/bosses/twinrova.js", + "zelda_oot_remake/draw.js" + ], + "sim_scripts": [ + "_native/runtime.js", + "zelda_oot_remake/game.js", + "zelda_oot_remake/bosses/goma.js", + "zelda_oot_remake/bosses/dodongo.js", + "zelda_oot_remake/bosses/ganondrof.js", + "zelda_oot_remake/bosses/volvagia.js", + "zelda_oot_remake/bosses/morpha.js", + "zelda_oot_remake/bosses/twinrova.js" + ], + "play_page": "web/games/zelda_oot_remake/index.html", + "original_clock": "Original game logic runs at 20 Hz (decompilation src/code/game.c R_UPDATE_RATE = 3 on a 60 Hz VI); this port runs 60 Hz, three ticks per original frame, logic on every third tick", + "scripted_controller": "ZeldaOotGame.scripted(game) -> {holds:[6 key arrays], mouse:[0,0,0]} (plans on deep copies with blinded futures)" +} diff --git a/environments/games/web/games/zelda_oot_remake/renderer3d.js b/environments/games/web/games/zelda_oot_remake/renderer3d.js new file mode 100644 index 0000000000000000000000000000000000000000..84ea19352846e77d12130f8ea0a1918f99a7ac3d --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/renderer3d.js @@ -0,0 +1,169 @@ +/* WebGL view for the Ocarina of Time boss trials. Reads the simulation only and never writes to it. All geometry and textures are made here in code: + * an immediate-mode pool of primitives, so each boss's art file is a short list of parts per frame. */ +(function(root){ + 'use strict'; + const T=root.THREE,PI=Math.PI,byCanvas=new WeakMap(),R=root.ZeldaOot3D={art:{}}; + const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)); + function canvasTex(w,h,paint,rx=1,ry=1){const c=document.createElement('canvas');c.width=w;c.height=h;paint(c.getContext('2d'),w,h);const t=new T.CanvasTexture(c);t.colorSpace=T.SRGBColorSpace;t.wrapS=t.wrapT=T.RepeatWrapping;t.repeat.set(rx,ry);return t;} + function noise(q,w,h,n,seed,dark,light,size=3){let s=seed>>>0||1;const r=()=>{s=Math.imul(s^(s>>>15),0x2c1b3c6d)+0x9e37|0;return (s>>>0)/4294967296;};for(let i=0;i{e.preventDefault();this.ready=false;this.error='WebGL context lost';}); + this.world=new T.Scene();this.camera=new T.PerspectiveCamera(54,854/480,4,4200); + this.hemi=new T.HemisphereLight(0xcfe4ff,0x4a4034,1.7);this.world.add(this.hemi);this.sun=new T.DirectionalLight(0xfff0d8,2.2);this.sun.position.set(-300,700,260);this.world.add(this.sun); + this.glow=new T.PointLight(0xffffff,0,1200,1.6);this.world.add(this.glow); + this.geo={box:this.keep(new T.BoxGeometry(1,1,1)),ball:this.keep(new T.SphereGeometry(1,14,10)),hemi:this.keep(new T.SphereGeometry(1,14,6,0,PI*2,0,PI/2)),cyl:this.keep(new T.CylinderGeometry(1,1,1,12)),cone:this.keep(new T.ConeGeometry(1,1,10)), + disc:this.keep(new T.CircleGeometry(1,28)),ring:this.keep(new T.RingGeometry(.8,1,32)),ico:this.keep(new T.IcosahedronGeometry(1,0)),oct:this.keep(new T.OctahedronGeometry(1,0)),torus:this.keep(new T.TorusGeometry(1,.16,6,18)),blade:this.keep(new T.ConeGeometry(.5,1,4))}; + this.mats=new Map();this.pool=new Map();this.stack=[new T.Matrix4()];this.tmp=new T.Matrix4();this.e=new T.Euler(0,0,0,'YXZ');this.v=new T.Vector3();this.s=new T.Vector3();this.q=new T.Quaternion(); + this.blob=this.keep(new T.MeshBasicMaterial({map:this.keep(canvasTex(64,64,(q,w,h)=>{const g=q.createRadialGradient(32,32,2,32,32,31);g.addColorStop(0,'rgba(0,0,0,.6)');g.addColorStop(.7,'rgba(0,0,0,.36)');g.addColorStop(1,'rgba(0,0,0,0)');q.fillStyle=g;q.fillRect(0,0,w,h);})),transparent:true,depthWrite:false})); + // Soft additive glow for projectiles, flames, sparks and charge-ups: camera-facing sprites from one radial texture. + this.glowTex=this.keep(canvasTex(64,64,(q,w,h)=>{const g=q.createRadialGradient(32,32,0,32,32,32);g.addColorStop(0,'rgba(255,255,255,1)');g.addColorStop(.22,'rgba(255,255,255,.8)');g.addColorStop(.55,'rgba(255,255,255,.22)');g.addColorStop(1,'rgba(255,255,255,0)');q.fillStyle=g;q.fillRect(0,0,w,h);})); + this.glowTex.wrapS=this.glowTex.wrapT=T.ClampToEdgeWrapping;this.glowTex.repeat.set(1,1); + this.sprites={items:[],n:0};this.smats=new Map();this.sectors=new Map(); + this.geo.plane=this.keep(new T.PlaneGeometry(1,1));this.geo.thin=this.keep(new T.RingGeometry(.9,1,48));this.geo.capsule=this.keep(new T.CapsuleGeometry(.5,1,4,10)); + } + keep(r){this.resources.add(r);return r;} + // Lambert by colour; `emissive` for things that must read in a dark room; `flat` faceted by default; `add` = additive glow. Opacity is quantised so the cache stays small. + mat(color,o={}){const op=o.op===undefined?undefined:Math.round(clamp(o.op,0,1)*32)/32,key=color+'|'+(o.em||0)+'|'+op+'|'+(o.basic?1:0)+'|'+(o.smooth?1:0)+'|'+(o.ei||0)+'|'+(o.add?1:0);let m=this.mats.get(key);if(m)return m; + if(o.basic)m=new T.MeshBasicMaterial({color,transparent:op!==undefined||!!o.add,opacity:op??1,depthWrite:op===undefined&&!o.add,side:T.DoubleSide,blending:o.add?T.AdditiveBlending:T.NormalBlending,toneMapped:!o.add,fog:!o.add}); + else m=new T.MeshLambertMaterial({color,flatShading:!o.smooth,emissive:o.em||0,emissiveIntensity:o.ei??1,transparent:op!==undefined,opacity:op??1}); + this.keep(m);this.mats.set(key,m);return m;} + // A camera-facing glow in world coordinates (not under push/pop). + flare(x,y,z,s,color,op=1){const q=Math.round(clamp(op,0,1)*32)/32;if(q<=0||s<=0)return null;const key=color+'|'+q;let m=this.smats.get(key); + if(!m){m=this.keep(new T.SpriteMaterial({map:this.glowTex,color,transparent:true,opacity:q,blending:T.AdditiveBlending,depthWrite:false,toneMapped:false,fog:false}));this.smats.set(key,m);} + const P=this.sprites;let sp=P.items[P.n];if(!sp){sp=new T.Sprite(m);sp.frustumCulled=false;sp.renderOrder=6;P.items.push(sp);this.world.add(sp);}P.n++; + sp.material=m;sp.visible=true;sp.position.set(x,y,z);sp.scale.set(s,s,1);return sp;} + // A projectile: bright core, coloured halo, and a tail of fading glows back along its last move. + bolt(x,y,z,px,py,pz,r,core,halo,tail=4){this.flare(x,y,z,r*4.2,halo,.55);this.flare(x,y,z,r*2,core,.95); + for(let i=1;i<=tail;i++){const k=i/(tail+1),u=1-k;this.flare(x+(px-x)*k*1.6,y+(py-y)*k*1.6,z+(pz-z)*k*1.6,r*2.6*u,halo,.5*u);}} + // Hit feedback: a white-hot flash with short rays, strength k (1 on the hit frame, fading with the target's invulnerability counter). + hitBurst(x,y,z,k,col=0xfff0c0){if(k<=0)return;this.flare(x,y,z,90*k+20,col,.8*k);this.flare(x,y,z,40*k+10,0xffffff,k); + for(let i=0;i<6;i++){const a=i*PI/3+.3,e=i%2?.6:1,L=(30+50*(1-k))*e;this.beam(x+Math.sin(a)*10,y+Math.cos(a)*10,z,x+Math.sin(a)*L,y+Math.cos(a)*L*.8,z+Math.cos(a+1)*L*.4,3*k+1,col,.8*k,1);}} + // A segment of glow (beams, sword arcs): a thin additive cylinder plus glows along it. + beam(x0,y0,z0,x1,y1,z1,w,color,op=.8,n=4){const dx=x1-x0,dy=y1-y0,dz=z1-z0,L=Math.hypot(dx,dy,dz);if(L<1e-3)return; + this.part('cyl',this.mat(color,{basic:true,op,add:true}),(x0+x1)/2,(y0+y1)/2,(z0+z1)/2,w*.35,L,w*.35,Math.atan2(dx,dz),Math.atan2(Math.hypot(dx,dz),dy)); + for(let i=0;i<=n;i++){const k=i/n;this.flare(x0+dx*k,y0+dy*k,z0+dz*k,w*2.2,color,op*.5);}} + // Flat marks on the floor, over it (no depth write): ring / thin ring / disc / sector (half-angle b round yaw) / strip (from x,z along yaw, length a, width b). + decal(kind,x,z,a,b,color,op,yaw=0,y=1.4){const m=this.mat(color,{basic:true,op,add:true});let mesh; + if(kind==='ring'||kind==='thin'||kind==='disc')mesh=this.part(kind,m,x,y,z,a,a,a,0,-PI/2); + else if(kind==='sector'){const k=Math.max(1,Math.min(62,Math.round(b*20))),name='sec'+k;if(!this.geo[name])this.geo[name]=this.keep(new T.CircleGeometry(1,Math.max(6,k),-PI/2-k/20,k/10));mesh=this.part(name,m,x,y,z,a,a,a,yaw,-PI/2);} + else mesh=this.part('plane',m,x+Math.sin(yaw)*a/2,y,z+Math.cos(yaw)*a/2,b,a,1,yaw,-PI/2); + mesh.renderOrder=3;return mesh;} + push(x,y,z,yaw=0,pitch=0,roll=0,s=1){this.e.set(pitch,yaw,roll);this.q.setFromEuler(this.e);this.v.set(x,y,z);this.s.set(s,s,s);this.stack.push(new T.Matrix4().multiplyMatrices(this.stack[this.stack.length-1],this.tmp.compose(this.v,this.q,this.s)));} + pop(){this.stack.pop();} + // One part: geometry name, material, position, scale, rotation. + part(g,m,x,y,z,sx,sy=sx,sz=sx,yaw=0,pitch=0,roll=0){let list=this.pool.get(g);if(!list){list={items:[],n:0};this.pool.set(g,list);} + let mesh=list.items[list.n];if(!mesh){mesh=new T.Mesh(this.geo[g],m);mesh.matrixAutoUpdate=false;mesh.frustumCulled=false;list.items.push(mesh);this.world.add(mesh);} + list.n++;mesh.material=m;mesh.visible=true;this.e.set(pitch,yaw,roll);this.q.setFromEuler(this.e);this.v.set(x,y,z);this.s.set(sx,sy,sz);mesh.matrix.multiplyMatrices(this.stack[this.stack.length-1],this.tmp.compose(this.v,this.q,this.s));return mesh;} + shadow(x,y,z,r){const m=this.part('disc',this.blob,x,y+.6,z,r,r,r,0,-PI/2);m.renderOrder=2;} + buildRoom(kind,art){if(this.room){this.world.remove(this.room);this.room.traverse(o=>{if(o.geometry)o.geometry.dispose();if(o.material){if(o.material.map)o.material.map.dispose();o.material.dispose();}});this.room=null;} + this.room=new T.Group();this.world.add(this.room);this.kind=kind;art.room(this,this.room);} + // A round chamber (or square hall) with procedural floor and wall textures. + addChamber(group,o){const r=o.r,h=o.h,floor=new T.CircleGeometry(r+6,64),fm=new T.MeshLambertMaterial({map:o.floorTex}),fl=new T.Mesh(floor,fm);fl.rotation.x=-PI/2;group.add(fl); + const wall=new T.CylinderGeometry(r+6,r+6,h,64,1,true),wm=new T.MeshLambertMaterial({map:o.wallTex,side:T.BackSide}),wl=new T.Mesh(wall,wm);wl.position.y=h/2;group.add(wl); + if(o.ceilTex){const cm=new T.MeshLambertMaterial({map:o.ceilTex}),c=new T.Mesh(new T.CircleGeometry(r+6,64),cm);c.rotation.x=PI/2;c.position.y=h;group.add(c);}} + drawHero(g,f){const h=g.hero,x=h.ox+(h.x-h.ox)*f,y=h.oy+(h.y-h.oy)*f,z=h.oz+(h.z-h.oz)*f,child=h.age==='child',s=child?.72:1,t=g.t/60,act=h.act; + // Hurt feedback: a red-white flash for the source's 10 flash frames, then a soft blink through the rest of the invulnerability. + const white=h.flash>0&&(g.t>>1)%2===0,blink=!white&&h.inv>0&&h.flash===0&&(g.t>>2)%2===0,cl=c=>white?0xffd8d0:c; + const tunic=this.mat(cl(0xc48a3a)),tunic2=this.mat(cl(0xa8702c)),belt=this.mat(cl(0x5a3a1e)),gold=this.mat(cl(0xd8b048),{em:0x302000}),skin=this.mat(cl(0xf0c7a0)),hood=this.mat(cl(0x5e3f28)),scarf=this.mat(cl(0x2f6fb0)),boot=this.mat(cl(0x4a2e1a)); + const steel=this.mat(0xe6edf6,{em:0x405468}),hilt=this.mat(0x2a4a8a),shf=this.mat(cl(0x8a96a6)),shRim=this.mat(cl(0xc8ccd4)),shEm=this.mat(cl(0x2f6fb0)); + this.shadow(x,0,z,18*(1+y/200));if(blink)return; + const roll=act==='roll'?h.timer/16*PI*2:0,run=act==='idle'&&Math.abs(h.speed)>.5?Math.sin(t*16):0,bob=Math.abs(run)*2,lean=act==='idle'?Math.min(.25,Math.abs(h.speed)*.04):0,kb=act==='kb'?.5:0,dead=act==='dead'?Math.min(1,1-h.timer/30):0; + this.push(x,y,z,h.face,0,0,s);this.push(0,dead?6:30,0,0,roll+lean-kb,dead*1.4); + // Body (original design: ochre coat, blue scarf, brown hood): coat skirt, torso, belt with buckle, scarf tail flying with the run. + this.part('cone',tunic,0,-8+bob,0,12,22,10,0,0);this.part('cyl',tunic2,0,4+bob,0,9.5,16,7.5);this.part('box',belt,0,-2+bob,0,11,3,8.4);this.part('box',gold,0,-2+bob,4.4,3,2.6,.8); + this.part('ball',skin,0,20+bob,0,8.4,9,8.2);this.part('hemi',hood,0,21+bob,-.5,10.2,10,10.2);this.part('box',hood,0,17+bob,-7,12,9,4); + this.part('box',this.mat(0x1c1410),-3,20+bob,7.6,1.6,2.4,.8);this.part('box',this.mat(0x1c1410),3,20+bob,7.6,1.6,2.4,.8); + this.part('torus',scarf,0,12+bob,0,8.5,8.5,14,0,PI/2);this.part('box',scarf,0,8+bob,-9,5,14,1.6,0,.35+Math.abs(run)*.5+Math.abs(h.speed)*.05);this.part('box',scarf,3,4+bob,-12-Math.abs(run)*3,4,10,1.4,.3,.6+Math.abs(run)*.6); + // Legs stride with the run; a roll tucks them. + const st=act==='roll'?0:run*5;for(const sd of [-1,1]){this.part('box',this.mat(cl(0xe8e0c8)),sd*4,-21,sd*st,3.6,14,4);this.part('box',boot,sd*4,-29,sd*st+1,4.6,5,7);} + // Sword arm: windup and follow-through by combo stage, a raised blade while charging, overhead on a jump slash. + const sl=act==='slash'?Math.min(1,h.timer/([10,10,14][h.combo]||10)):0,dir=h.combo===1?-1:1; + let arm=act==='slash'?(sl<.25?-1.6*dir:-1.6*dir+(sl-.25)/.75*3.4*dir):act==='spin'?0:act==='jumpslash'?(h.vy>0?-1.5:1.2):h.charge>0?-1.2:-.3,pitch=act==='jumpslash'?(h.vy>0?-1.2:.3):act==='slash'&&h.combo===2?-.2-sl*.8:-.6; + this.push(-11,7+bob,1,arm,pitch,0);this.part('box',skin,0,-3,3,3.4,3.4,9);this.part('box',hilt,0,-3,9,7,2.2,2.4);this.part('ball',gold,0,-3,7,1.8); + if(h.weapon==='hammer'){this.part('cyl',belt,0,-3,26,2.4,36,2.4,0,PI/2);this.part('cyl',this.mat(0x6a6f78,{em:0x202428}),0,-3,46,11,24,11,0,0,PI/2);this.part('cyl',gold,0,-3,46,11.5,3,11.5,0,0,PI/2);} + else{const L=(child?48:62)*.82;this.part('blade',steel,0,-3,10+L/2,3.2,L,1.4,0,PI/2);} + this.pop(); + // Shield arm: held across the body, raised to the front while blocking. + const up=h.shield;this.push(up?1:12,up?6+bob:4+bob,up?12:1,up?0:.5,0,0);this.part('cyl',shf,0,0,0,up?13:10,2.2,up?15:12,0,PI/2);this.part('torus',shRim,0,0,1.2,up?13:10,up?13:10,6,0,0); + this.part('oct',shEm,0,1,1.8,3.4,5,1.2);this.pop(); + this.pop();this.pop(); + // Sword trail: an additive arc swept across the slash's active frames; the spin draws a full ring. + if(act==='slash'||act==='jumpslash'||act==='spin'){const reach=(child?48:62)*s,hy=y+26*s,col=0xcfeaff; + if(act==='spin')for(let i=0;i<14;i++){const a=h.face+i/14*PI*2,k=i/14;this.flare(x+Math.sin(a)*reach,hy,z+Math.cos(a)*reach,26*s*(.4+.6*k),col,.55*k);} + else{const n=7,from=act==='jumpslash'?-1.1:-1.1*dir,to=act==='jumpslash'?1.1:1.1*dir,k0=act==='slash'?Math.max(0,(sl-.15)/.85):1; + for(let i=0;ik0)break;const a=h.face+from+(to-from)*u,yy=act==='jumpslash'?hy+30-u*40:hy+(h.combo===2?20-u*20:0);this.flare(x+Math.sin(a)*reach*.85,yy,z+Math.cos(a)*reach*.85,24*s,col,.55*(.4+.6*u));}}} + // Charge glow at the blade and a ring on the floor once a spin is ready. + if(h.charge>0){const k=Math.min(1,h.charge/.85),hx2=x+Math.sin(h.face-.6)*30*s,hz2=z+Math.cos(h.face-.6)*30*s;this.flare(hx2,y+48*s,hz2,(10+18*k)*s,h.charge>=.85?0xbfe9ff:0x6a8fd0,.5+.4*k); + if(h.charge>=.85){const a=t*12;this.decal('thin',x,z,46+Math.sin(t*20)*3,0,0x9fe2ff,.75);this.part('ring',this.mat(0xbfe9ff,{basic:true,op:.5,add:true}),x,4,z,40,40,40,a,-PI/2);}} + if(white)this.flare(x,y+34*s,z,70*s,0xff6a5a,.45); + } + render(g,ctx){const start=performance.now(); + try{const kind=g.kind,art=R.art[kind];if(!art)throw Error('no art for '+kind);if(this.kind!==kind)this.buildRoom(kind,art); + for(const l of this.pool.values()){for(let i=0;i120)this.times.shift();this.ready=true;this.error=null; + }catch(e){this.ready=false;this.error=String(e);throw e;} + } + metrics(){const info=this.renderer.info,sorted=[...this.times].sort((a,b)=>a-b); + return {renderer:'webgl-zelda-oot',webglVersion:this.renderer.capabilities.isWebGL2?2:1,drawCalls:info.render.calls,triangles:info.render.triangles,geometries:info.memory.geometries,textures:info.memory.textures,canvasBytes:854*480*4, + renderSamples:sorted.length,cpuRenderMsP50:sorted.length?sorted[Math.floor((sorted.length-1)*.5)]:null,cpuRenderMsP95:sorted.length?sorted[Math.floor((sorted.length-1)*.95)]:null,shadows:'blob shadows, no shadow maps',postprocess:false};} + close(){if(this.closed)return;this.closed=true;this.ready=false;if(this.room)this.room.traverse(o=>{if(o.geometry)o.geometry.dispose();if(o.material){if(o.material.map)o.material.map.dispose();o.material.dispose();}});this.resources.forEach(r=>{if(r.map)r.map.dispose?.();r.dispose?.();});this.renderer.dispose();this.renderer.forceContextLoss();this.resources.clear();} + } + const P={reach:62}; + const wrapDiff=a=>Math.atan2(Math.sin(a),Math.cos(a)); + // Usable half-angles of the 54-degree 854 x 480 view, with a margin so a framed point stays clear of the edge. + // Vertical fit keeps clear of the HUD: the title and boss bar take the top ~72 px, the hint and key line the bottom ~45 px. + const HALF_V=27*PI/180,HALF_H=Math.atan(Math.tan(HALF_V)*854/480),FIT_TOP=Math.atan(Math.tan(HALF_V)*162/240),FIT_BOT=Math.atan(Math.tan(HALF_V)*190/240),FIT_H=HALF_H*.84; + // Composed third-person camera. The simulation owns the camera yaw (it maps the stick, game.js updateCam); the view stands behind the hero along it, + // a little over the right shoulder so the hero does not hide the boss, and solves pitch and distance so hero and focus (lock target, else boss) both fit. + // A pure function of the state: the same tick always gives the same view, whoever renders it. + Scene.prototype.focusOf=function(g,f,art){const F=this.focusOf0(g,f,art),w=art.threat?art.threat(g,f):null;if(!w)return F; + const mx=(F.x+w.x)/2,my=(F.y+w.y)/2,mz=(F.z+w.z)/2,dy=Math.abs(F.y-w.y)/2;return {x:mx,y:my,z:mz,r:Math.max(F.r,w.r||40)+dy,pts:[F,w]};}; + Scene.prototype.focusOf0=function(g,f,art){const L=g.lockTarget();if(L)return {x:L.x,y:L.y,z:L.z,r:typeof art.lockR==='function'?art.lockR(g,L):art.lockR||28}; + const p=art.focus?art.focus(g,f):g.def().focus(g),ip=(a,o)=>o===undefined?a:o+(a-o)*f; + return {x:ip(p.x,p.ox),y:ip(p.y||0,p.oy)+(art.focusUp??40),z:ip(p.z,p.oz),r:art.focusR||50};}; + Scene.prototype.frame=function(g,f,art,hx,hy,hz){const c=g.cam,A=g.arena,yaw=c.oyaw+wrapDiff(c.yaw-c.oyaw)*f+c.offset,fo=this.focusOf(g,f,art),base=c.dist*(art.distK||1),camY=art.camY||118,lb=art.lookBias||.38; + const sx=Math.sin(yaw),sz=Math.cos(yaw);let dist=base,px=0,py=0,pz=0,vx=sx,vz=sz,lo=0,hi=0,pref=0; + for(let it=0;it<4;it++){const sh=dist*(art.shoulder??.13);px=hx-sx*dist-sz*sh;pz=hz-sz*dist+sx*sh;py=hy+camY; + if(A.square){const m=A.square-14;px=clamp(px,-m,m);pz=clamp(pz,-m,m);}else{const d=Math.hypot(px,pz),m=A.r-16;if(d>m){px*=m/d;pz*=m/d;}} + py=clamp(py,12,A.ceil-14); + const lb2=fo.pts?Math.max(lb,.5):lb,lx=hx+(fo.x-hx)*lb2,lz=hz+(fo.z-hz)*lb2,dl=Math.hypot(lx-px,lz-pz)||1;vx=(lx-px)/dl;vz=(lz-pz)/dl; + const va=Math.atan2(vx,vz),angs=(fo.pts||[fo]).map(p=>wrapDiff(Math.atan2(p.x-px,p.z-pz)-va)),amin=Math.min(...angs),amax=Math.max(...angs); + let shift=0;if(amax-amin<=2*FIT_H){if(amax>FIT_H)shift=amax-FIT_H;else if(amin<-FIT_H)shift=amin+FIT_H;}else{const fa=angs[0];if(Math.abs(fa)>FIT_H)shift=fa-Math.sign(fa)*FIT_H;} + if(shift){const t=va+clamp(shift,-.6,.6);vx=Math.sin(t);vz=Math.cos(t);} + const el=(x,y,z)=>Math.atan2(y-py,Math.max(30,(x-px)*vx+(z-pz)*vz)); + const P2=fo.pts||[fo],ft=Math.max(...P2.map(p=>el(p.x,p.y+(p.r||fo.r),p.z))),fb=Math.min(...P2.map(p=>el(p.x,p.y-(p.r||fo.r)*.6,p.z))),ht=el(hx,hy+70,hz),hb=el(hx,hy-4,hz),top=Math.max(ht,ft),bot=Math.min(hb,fb); + // Pitch window that keeps the focus in view; the hero is fitted inside it when both fit, else the focus wins and the hero is kept as close as it allows. + lo=ft-FIT_TOP;hi=fb+FIT_BOT;pref=el(lx,hy+34+(fo.y-hy-34)*lb*.9,lz);const both=top-bot<=FIT_TOP+FIT_BOT;if(both){lo=top-FIT_TOP;hi=bot+FIT_BOT;}else pref=(ht+hb)/2; + if(both||dist>=base*1.6)break;dist=Math.min(base*1.6,dist*(top-bot)/(FIT_TOP+FIT_BOT));} + const th=clamp(pref,Math.min(lo,hi),Math.max(lo,hi));this.camera.position.set(px,py,pz);this.camera.lookAt(px+vx*Math.cos(th)*100,py+Math.sin(th)*100,pz+vz*Math.cos(th)*100);this.camera.updateMatrixWorld();}; + // Screen position of a world point for the HUD: on-screen flag, pixel position, depth, and a screen direction that stays meaningful behind the camera. + Scene.prototype.project=function(x,y,z){const v=new T.Vector3(x,y,z).applyMatrix4(this.camera.matrixWorldInverse),depth=-v.z,cx=v.x,cy=v.y; + if(depth>1){v.applyMatrix4(this.camera.projectionMatrix);const sx=(v.x+1)*427,sy=(1-v.y)*240;return {front:true,on:sx>=0&&sx<=854&&sy>=0&&sy<=480,x:sx,y:sy,depth,dx:sx-427,dy:sy-240};} + return {front:false,on:false,x:NaN,y:NaN,depth,dx:cx,dy:-cy+Math.abs(depth)*.5+1};}; + R.render=function(g,ctx){let s=byCanvas.get(ctx.canvas);if(!s||s.closed){s=new Scene(ctx.canvas);byCanvas.set(ctx.canvas,s);}s.render(g,ctx);return s;}; + R.status=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);if(s&&!s.closed&&s.renderer.getContext().isContextLost()){s.ready=false;s.error='WebGL context lost';} + return {renderer:'webgl-zelda-oot',kind:'perspective',ready:!!s?.ready&&!s.closed,error:s?.error||null};}; + R.metrics=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);return s?s.metrics():null;}; + R.project=function(ctx,x,y,z){const s=ctx&&byCanvas.get(ctx.canvas);return s&&!s.closed?s.project(x,y,z):null;}; + R.close=function(ctx){const s=ctx&&byCanvas.get(ctx.canvas);if(s){s.close();byCanvas.delete(ctx.canvas);}}; +})(window); diff --git a/environments/games/web/games/zelda_oot_remake/style3d.css b/environments/games/web/games/zelda_oot_remake/style3d.css new file mode 100644 index 0000000000000000000000000000000000000000..ec39215c7a394dd8d0d0758490acf67ca7ec50f9 --- /dev/null +++ b/environments/games/web/games/zelda_oot_remake/style3d.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#14191a;--panel:#1d2425;--edge:#354141;--text:#ebe7dc;--muted:#a5b2ad;--accent:#dfb676}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top,#29312b,transparent 60%),var(--bg);color:var(--text);font:14px/1.7 'Segoe UI','Microsoft YaHei',sans-serif}body[data-game=genshin_remake]{--bg:#101822;--panel:#1b2530;--edge:#374754;--accent:#baacff;background:radial-gradient(ellipse at top,#2b2942,transparent 60%),var(--bg)}body[data-game=mario64_remake]{--bg:#0f1530;--panel:#18214a;--edge:#34407a;--text:#f3f1ea;--muted:#aeb7dd;--accent:#ffd23a;background:radial-gradient(ellipse at top,#2b3a8a,transparent 62%),radial-gradient(ellipse at bottom right,#5a1616,transparent 55%),var(--bg)}body[data-game=mario64_remake] h1{font-family:"Segoe UI","Microsoft YaHei",sans-serif;font-weight:800;letter-spacing:.5px;text-shadow:0 3px 0 #b81d22,0 6px 14px #0008}body[data-game=mario64_remake] button.primary{background:#e52521;color:#fff}body[data-game=mario64_remake] .stage{border-color:#ffd23a55}main{max-width:1220px;margin:auto;padding:28px 24px 40px}header{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px;gap:20px}.eyebrow{color:var(--accent);font-size:11px;letter-spacing:2.5px;text-transform:uppercase}h1{font:500 32px/1.35 Georgia,'Microsoft YaHei',serif;letter-spacing:1px;margin:6px 0}header p{color:var(--muted);margin:0;font-size:13px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.layout{display:grid;grid-template-columns:minmax(0,854px) 245px;gap:24px;align-items:start}.stage{position:relative;border:1px solid var(--edge);box-shadow:0 22px 55px #0005;background:#111b1c}canvas{display:block;width:100%;aspect-ratio:854/480;touch-action:none;outline:none}canvas:focus-visible{outline:2px solid var(--accent);outline-offset:3px}#overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#10171b30;pointer-events:none}#overlay[hidden]{display:none}#overlay div{background:#111b23de;padding:19px 32px;border:1px solid #9ba6a655;max-width:80%;text-align:center}#overlay strong{font:500 24px Georgia,'Microsoft YaHei',serif;display:block}#overlay span{display:block;color:var(--muted);font-size:12px;margin-top:7px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;padding:12px;background:var(--panel);border-top:1px solid var(--edge)}button,select,input{font:inherit;background:var(--panel);color:var(--text);border:1px solid var(--edge);border-radius:4px;padding:7px 11px}button{cursor:pointer}button:hover{border-color:var(--accent);background:#ffffff09}button.primary{background:var(--accent);color:var(--bg);font-weight:600}button:focus-visible,select:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}aside{padding:19px;border:1px solid var(--edge);background:var(--panel)}h2{font-size:16px;margin:0 0 8px}label{display:block;font-size:12px;color:var(--muted);margin:12px 0 5px}select,input{width:100%}dl{border-top:1px solid var(--edge);padding-top:16px;margin:18px 0 0}dt{color:var(--accent);font:12px/1.8 Consolas,monospace}dd{color:var(--muted);font-size:12px;margin:0 0 10px}.note{color:var(--muted);font-size:12px}#status{min-height:25px;margin:10px 0;color:var(--accent);overflow-wrap:anywhere}.record-toolbar{border:1px solid var(--edge);padding:10px;background:transparent}.record-toolbar button{font-size:12px}#file{display:none}.mobile{display:none}footer{display:flex;flex-wrap:wrap;gap:22px;border-top:1px solid var(--edge);margin-top:28px;padding-top:15px;font-size:12px}@media(max-width:950px){main{padding:14px}.layout{grid-template-columns:1fr}aside{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}aside dl,aside .note{grid-column:1/-1}dl{columns:2}.mobile{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.mobile button{min-width:45px;touch-action:none}header{align-items:start}h1{font-size:26px}}@media(max-width:500px){header{display:block}header a{font-size:12px}aside{padding:14px}#overlay div{padding:14px 20px}#overlay strong{font-size:19px}.toolbar{gap:6px;padding:8px}button{font-size:12px}h1{font-size:25px}} diff --git a/environments/games/web/index.html b/environments/games/web/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c55f5f3a0dd2e68b3d50e35c010e3603f4ca4c64 --- /dev/null +++ b/environments/games/web/index.html @@ -0,0 +1,2 @@ +GameDojo Games

              GameDojo: 20 games / 120 scenes

              Minecraft requires the local Python play server on port 8765.

              + diff --git a/environments/games/web/tools/gym_server.js b/environments/games/web/tools/gym_server.js new file mode 100644 index 0000000000000000000000000000000000000000..3b46f4e8ed7a374fad6e5aca05d3dad246d0e4f2 --- /dev/null +++ b/environments/games/web/tools/gym_server.js @@ -0,0 +1,14 @@ +// Node transport for the Python gymnasium binding: one env per process, one JSON command per stdin line, +// one JSON reply per stdout line ({error} on failure). Symbolic only; pixels go through the browser transport. +// usage: node tools/gym_server.js [game = hollowknight_remake] (a name under web/games/ or a path to a game folder) +// One game per process (games share the BB global); prototype/bossbench/webenv.py starts one per game. +var path = require('path'), fs = require('fs'); +var arg = process.argv[2] || 'hollowknight_remake', dir = fs.existsSync(path.join(__dirname, '..', 'games', arg)) ? path.join(__dirname, '..', 'games', arg) : path.resolve(arg); +var BB = require('../engine/load.js')(dir); +require('../engine/bridge.js'); +var rl = require('readline').createInterface({ input: process.stdin, terminal: false }); +rl.on('line', function (line) { + var res; + try { res = BB.bridge(JSON.parse(line)); } catch (e) { res = { error: String(e && e.stack || e) }; } + process.stdout.write(JSON.stringify(res) + '\n'); +}); diff --git a/environments/requirements-games.txt b/environments/requirements-games.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a257ce8773f18b1cf54034fc74d27cbbd494011 --- /dev/null +++ b/environments/requirements-games.txt @@ -0,0 +1,6 @@ +gymnasium==1.4.0 +numpy==2.5.4 +pillow==13.0.0 +playwright==1.65.0 +moderngl==5.13.0 +glcontext==3.1.0 diff --git a/environments/run_model.py b/environments/run_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a93b607acab041f5ce816a54d2f4475c09ad45 --- /dev/null +++ b/environments/run_model.py @@ -0,0 +1,6 @@ +import json, sys +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parent/'games/prototype')) +from bossbench_llm.run import main +defaults=['--policy','chat','--format','lumine','--lang','en','--base-url','http://127.0.0.1:8000/v1','--model','gamedojo-4b','--history','2','--image-size','854x480','--seeds','1','--policy-seed','1','--temperature','1','--top-p','1','--max-tokens','256','--extra-body',json.dumps({'skip_special_tokens':False,'chat_template_kwargs':{'enable_thinking':False}})] +sys.exit(main(defaults+sys.argv[1:]))