diff --git a/CLAUDE.md b/CLAUDE.md index 70444d2..f801802 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,8 +31,8 @@ npm run capture -- --seed 1979 # 8 standard screenshots into captures/seed-197 - **Randomness:** never call `Math.random()`. Use `random()` from `src/core/rng.ts` (or `createRng(seed)` for an independent stream) so games replay from `?seed=`. - **Debug hook:** `?debug=1` exposes `window.__sr` (`src/core/debug.ts`): `seed`, `state`, `start`, - `galaxy`, `teleport`, `spawn`, `setView`, `step`, `resume`, `hyperwarp`, `dock`. Extend it when a - phase needs a new way to reach a game state. + `galaxy`, `teleport`, `spawn`, `setView`, `step`, `resume`, `hyperwarp`, `dock`, `zylons`, `meteor` and + more (see the file). Extend it when a phase needs a new way to reach a game state. - **Screenshots:** reuse `scripts/capture.mjs` for evidence; add shots to its `SHOTS` list instead of writing a new harness. It freezes the page clock and advances the game only with `__sr.step()`, so keep new game logic driven by the update `deltaTime`, not wall-clock time. diff --git a/scripts/capture.mjs b/scripts/capture.mjs index 6084797..443fa6f 100644 --- a/scripts/capture.mjs +++ b/scripts/capture.mjs @@ -16,7 +16,9 @@ * 01-title 02-front 02a-front-crosshair 02b-shields 02c-red-alert 03-aft 04-galactic-chart 04a-chart-surrounded * 04b-chart-surround-holding 04c-chart-starbase-destroyed 04d-chart-damage * 05-long-range-scan 06-attack-computer 07-hyperwarp 08-docking 10-panel-hud 10a-panel-tracking-c - * 10b-panel-low-energy 10c-panel-shields-out 10d-panel-hyperspace 09-zero-energy (last: mission end) + * 10b-panel-low-energy 10c-panel-shields-out 10d-panel-hyperspace 11-fighter-approach 11a-fighter-hit + * 11b-explosion 12-meteor 12a-meteor-shot 13-fighter 13a-cruiser 13b-basestar + * 09-zero-energy (last: mission end) * * plus manifest.json with each file's SHA-256. Later phases reuse this script; add new * shots to SHOTS below rather than writing another harness. @@ -124,7 +126,7 @@ const SHOTS = [ run: async (sr) => sr(() => { window.__sr.setView('FRONT'); - window.__sr.spawn('fighter', 40); + window.__sr.spawn('fighter', 2000); // KM ahead window.__sr.step(20); }), }, @@ -155,7 +157,7 @@ const SHOTS = [ window.__sr.setView('FRONT'); window.__sr.killSector(); window.__sr.setSpeed(6); - window.__sr.spawn('fighter', 370, 400, -250); // ahead, right and below: θ, Φ, R all non-zero + window.__sr.spawn('fighter', 2400, 2560, -1600); // KM ahead, right and below: θ, Φ, R all non-zero window.__sr.setKills(18); window.__sr.setEnergy(8260); window.__sr.step(40); // V reaches 12 @@ -197,12 +199,80 @@ const SHOTS = [ window.__sr.step(160); // past the placeholder warp's midpoint: V ∞, HYPERSPACE }), }, + // Phase 5 (MANUAL_SPEC §16, §17.7, §17.8, §18.3): a fighter's H approaches, is shot and explodes; + // a meteor is shot down; the three Zylon sprites at their largest cell. All in an empty sector. + { + name: '11-fighter-approach', + run: async (sr) => + sr(() => { + window.__sr.step(200); // let the hyperwarp finish + const s = window.__sr.state; + const empty = window.__sr.galaxy().find((g) => !g.zylons && !g.starbase && (g.x !== s.sectorX || g.y !== s.sectorY)); + window.__sr.teleport(empty); + window.__sr.setView('FRONT'); + window.__sr.setSpeed(6); + if (!window.__sr.state.attackComputerOn) window.__sr.press('COMPUTER'); + // The manual's NOVICE drill: shields up (S) and computer on (C). A Zylon torpedo that gets + // through with the shields down destroys the ship (§5.9). + if (!window.__sr.state.shieldsActive) window.__sr.press('SHIELDS'); + // In line with the right barrel (photons leave 256 KM right/left and 256 KM below). + window.__sr.spawn('fighter', 4000, 256, -256); + window.__sr.step(24); + window.__sr.press('FIRE'); // left barrel + window.__sr.press('FIRE'); // right barrel + window.__sr.step(3); + }), + }, + { + name: '11a-fighter-hit', + run: async (sr) => + sr(() => { + for (let i = 0; i < 60 && window.__sr.zylons().ships.some((z) => z.alive); i++) window.__sr.step(1); + window.__sr.step(2); + }), + }, + { name: '11b-explosion', run: async (sr) => sr(() => window.__sr.step(30)) }, + { + name: '12-meteor', + run: async (sr) => + sr(() => { + window.__sr.step(100); + window.__sr.meteor(256, -256, 2400); // a green meteor coming straight at us + window.__sr.step(2); + window.__sr.press('FIRE'); + window.__sr.press('FIRE'); + window.__sr.step(4); + }), + }, + { + name: '12a-meteor-shot', + run: async (sr) => + sr(() => { + for (let i = 0; i < 60 && window.__sr.zylons().pl2.life > 0; i++) window.__sr.step(1); + window.__sr.step(3); + }), + }, + ...['fighter', 'cruiser', 'basestar'].map((type, i) => ({ + name: ['13-fighter', '13a-cruiser', '13b-basestar'][i], + run: async (sr) => + sr((t) => { + window.__sr.setSpeed(0); + if (window.__sr.state.attackComputerOn) window.__sr.press('COMPUTER'); // no cross hairs over it + window.__sr.step(40); + const s = window.__sr.state; + window.__sr.teleport(s.sectorX, s.sectorY); // an empty sector, nothing else in play + window.__sr.spawn(t, 480, 0, 0); // largest shape cell, centred + window.__sr.step(1); + }, type), + })), { // Phase 1: energy really runs out and aborts the mission (MANUAL_SPEC §12, §17.1, §17.10). name: '09-zero-energy', run: async (sr) => sr(() => { - window.__sr.step(200); // let the hyperwarp finish + const s = window.__sr.state; + window.__sr.teleport(s.sectorX, s.sectorY); // clear the sprite shots + if (window.__sr.state.shieldsActive) window.__sr.press('SHIELDS'); window.__sr.press('TRACKING'); window.__sr.setView('FRONT'); window.__sr.setEnergy(40); @@ -232,6 +302,29 @@ const SEQUENCES = { 84: () => window.__sr.redAlert(), // a long phrase replaces it at once }, }, + // Phase 5 (MANUAL_SPEC §17.7, §17.8, §18.3): a NOVICE fighter's H approaches, is shot, explodes. + 'fighter-kill': { + setup: (d) => { + window.__sr.start(d.difficulty, d.seed); + window.__sr.step(30); + window.__sr.press('COMPUTER'); + window.__sr.press('SHIELDS'); // the manual's NOVICE drill: S and C + window.__sr.step(1); + window.__sr.spawn('fighter', 4000, 256, -256); // in line with the right barrel + }, + frames: 75, + every: 2, + at: {}, + // Fire both barrels once the fighter is about 2700 KM out. + each: () => { + const z = window.__sr.zylons(); + if (!window.__fired && z.ships.some((s) => s.alive && s.z < 2700)) { + window.__fired = true; + window.__sr.press('FIRE'); + window.__sr.press('FIRE'); + } + }, + }, }; async function startServer() { @@ -295,10 +388,14 @@ async function main() { const titles = []; for (let i = 0; i < seq.frames; i++) { if (seq.at[i]) await sr(seq.at[i]); + if (seq.each) await sr(seq.each); await sr(() => window.__sr.step(1)); await page.screenshot({ path: join(dir, `${String(i).padStart(3, '0')}.png`), animations: 'disabled', caret: 'hide' }); titles.push(await sr(() => window.__sr.state.title)); - await sr((n) => window.__sr.step(n), seq.every - 1); + for (let k = 1; k < seq.every; k++) { + if (seq.each) await sr(seq.each); + await sr(() => window.__sr.step(1)); + } } await writeFile(join(dir, 'titles.json'), JSON.stringify({ every: seq.every, titles }, null, 2) + '\n'); console.log(`Wrote ${seq.frames} frames to ${dir}`); diff --git a/src/config/EnemyConfig.ts b/src/config/EnemyConfig.ts deleted file mode 100644 index d6d357a..0000000 --- a/src/config/EnemyConfig.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Enemy speed configuration for tuning - * - * Speeds are defined as "impulse levels" (0-9) which are multiplied by UNITS_PER_IMPULSE. - * The smooth velocity system now handles acceleration/deceleration, so speeds can be - * set higher without appearing jerky. - * - * Player reference (uses 50 units/impulse): - * - Player impulse 1 = 50 units/sec - * - Player impulse 5 = 250 units/sec - * - Player impulse 8 = 400 units/sec - * - Player impulse 9 = 450 units/sec (maximum) - * - * Enemy speeds designed so: - * - Player impulse 6+ = can escape or outrun enemies - * - Player impulse 5 = fighters match speed - * - Player impulse 4 = cruisers match speed - * - Player impulse < 4 = enemies catch up - */ -export const ENEMY_CONFIG = { - speeds: { - // Enemies now use same UNITS_PER_IMPULSE as player for consistent speed scaling - // Fighter pursuit speed matches player impulse 5 (250 u/s) - FIGHTER: 5, // 250 units/sec - matches player impulse 5 - CRUISER: 4, // 200 units/sec - slower but still threatening - BASESTAR: 0, // stationary - }, - - // Speed multipliers for different behaviors - multipliers: { - CRUISER_PATROL: 0.6, // Cruisers patrol at 60% speed (120 u/s) - CRUISER_BACKOFF: 0.5, // Cruisers back off at 50% speed (100 u/s) - CRUISER_STRAFE: 0.3, // Cruisers strafe at 30% speed (60 u/s) - }, - - // Combat distances - comfortable engagement ranges - distances: { - FIGHTER_ORBIT_RADIUS: 40, // Fighter orbit distance - tight, aggressive circling - CRUISER_PREFERRED_MIN: 60, // Cruiser minimum distance - CRUISER_PREFERRED_MAX: 90, // Cruiser maximum distance - }, - - // Units per impulse level - NOW MATCHES PLAYER - // Same as player (50) for consistent speed comparison - // Fighter impulse 5 = 250 units/sec (matches player impulse 5) - UNITS_PER_IMPULSE: 50, -}; - -// Make globally accessible for console testing -// Usage in browser console: ENEMY_CONFIG.speeds.FIGHTER = 6 -if (typeof window !== 'undefined') { - (window as any).ENEMY_CONFIG = ENEMY_CONFIG; -} diff --git a/src/core/debug.ts b/src/core/debug.ts index b9dbfe7..200bfd0 100644 --- a/src/core/debug.ts +++ b/src/core/debug.ts @@ -8,7 +8,8 @@ * __sr.galaxy() all 16x8 sectors * __sr.teleport({x, y}) / (x, y) jump to a sector at once (no hyperwarp, no energy cost) * __sr.spawn('fighter'|'cruiser'|'basestar'|'starbase', distance?, x?, y?) place one ahead of the ship - * (x, y: sideways and vertical offset, in the same units as distance) + * (KM; x, y: sideways and vertical offset). A Zylon takes a free + * ship slot (else slot 0), heads straight in, and is not on the map * __sr.setView('FRONT'|'AFT'|'GALACTIC_CHART'|'LONG_RANGE_SCAN') switch view instantly * __sr.step(n) stop the real-time loop and run n fixed 1/60 s frames * __sr.resume() go back to the real-time loop @@ -33,6 +34,8 @@ * __sr.settings(patch?) read or change the bend settings {stars, crt, wasd, mouse} * __sr.redAlert(loops?) start a red-alert flash (255 loops) or stop it with 0 * __sr.stars() the starfield: ship-frame KM position, pixel and colour register + * __sr.zylons() Zylon ships, PLAYER2 (torpedo/meteor), photons, barrel, explosion + * __sr.meteor(x, y, z) put a meteor at a ship-frame KM position (flying in at −8 KM/loop) */ import type { Game, DebugSpawnType } from '../game/Game'; import type { Action } from '../input/Input'; @@ -94,6 +97,8 @@ export function installDebugHook(host: DebugHost): void { settings: (patch?: Partial) => api().settings(patch), redAlert: (loops?: number) => api().redAlert(loops), stars: () => api().stars(), + zylons: () => api().zylons(), + meteor: (x: number, y: number, z: number) => api().meteor(x, y, z), }; (window as unknown as { __sr: typeof sr }).__sr = sr; diff --git a/src/entities/Enemy.ts b/src/entities/Enemy.ts deleted file mode 100644 index 6f31046..0000000 --- a/src/entities/Enemy.ts +++ /dev/null @@ -1,861 +0,0 @@ -import { Transform, Vec3 } from '../core/vec3'; -import { ENEMY_CONFIG } from '../config/EnemyConfig'; -import { random } from '../core/rng'; - -/** - * Enemy types - */ -export const EnemyType = { - FIGHTER: 'FIGHTER', - CRUISER: 'CRUISER', - BASESTAR: 'BASESTAR', -} as const; - -export type EnemyType = (typeof EnemyType)[keyof typeof EnemyType]; - -/** - * Enemy states - */ -export const EnemyState = { - IDLE: 'IDLE', - PATROL: 'PATROL', - ATTACK: 'ATTACK', - EVADE: 'EVADE', -} as const; - -export type EnemyState = (typeof EnemyState)[keyof typeof EnemyState]; - -/** - * Difficulty settings for enemy behavior scaling - */ -export interface DifficultySettings { - aggressionMultiplier: number; // Fire rate multiplier (lower = faster) - evasionChance: number; // Chance per frame to evade - leadAccuracy: number; // 0-1, how accurately enemies lead targets - shieldRegenChance: number; // Basestar shield regen per frame - cruiserProvocationSensitivity: number; // 0=direct hit only, 1=always hostile -} - -export const DIFFICULTY_SETTINGS: Record = { - NOVICE: { - aggressionMultiplier: 1.4, - evasionChance: 0.02, - leadAccuracy: 0.5, - shieldRegenChance: 0.003, - cruiserProvocationSensitivity: 0, - }, - PILOT: { - aggressionMultiplier: 1.0, - evasionChance: 0.03, - leadAccuracy: 0.65, - shieldRegenChance: 0.004, - cruiserProvocationSensitivity: 0.3, - }, - WARRIOR: { - aggressionMultiplier: 0.8, - evasionChance: 0.05, - leadAccuracy: 0.8, - shieldRegenChance: 0.005, - cruiserProvocationSensitivity: 0.6, - }, - COMMANDER: { - aggressionMultiplier: 0.65, - evasionChance: 0.08, - leadAccuracy: 0.95, - shieldRegenChance: 0.007, - cruiserProvocationSensitivity: 1.0, - }, -}; - -/** - * Enemy - Base class for all Zylon enemy ships - */ -export class Enemy { - protected mesh: Transform = new Transform(); - protected type: EnemyType; - protected state: EnemyState; - protected health: number; - protected maxHealth: number; - protected speed: number; - protected position: Vec3; - protected velocity: Vec3; - protected targetPosition: Vec3 | null = null; - - // Combat - protected hasShields: boolean = false; - protected shieldsActive: boolean = false; - protected fireRate: number = 2; // Seconds between shots - protected lastFireTime: number = 0; - protected attackRange: number = 100; - - // Fighter-specific movement - protected orbitDirection: number = 1; // 1 or -1 for orbit direction - protected weavePhase: number = 0; // For sinusoidal weaving - protected orbitAngle: number = 0; // Current angle in orbit - - // Cruiser-specific - protected provoked: boolean = false; - protected patrolWaypoints: Vec3[] = []; - protected currentWaypointIndex: number = 0; - protected waypointPauseTimer: number = 0; - - // Basestar-specific - protected shieldRegenTimer: number = 0; - - // Smooth movement system - prevents teleporting - protected currentVelocity: Vec3 = new Vec3(); - protected targetVelocity: Vec3 = new Vec3(); - protected maxAcceleration: number = 50; // Units per second squared - - // Evasive maneuver state (smooth instead of instant) - protected isEvading: boolean = false; - protected evadeTarget: Vec3 | null = null; - protected evadeTimer: number = 0; - - // Honing behavior for sector entry - protected isHoningIn: boolean = false; - protected honeInTimer: number = 0; - protected honeInDuration: number = 20; // Seconds to home in on player (aggressive pursuit) - protected honeInMinDistance: number = 80; // Stop honing when within attack range - - // Difficulty settings - protected difficultySettings: DifficultySettings = DIFFICULTY_SETTINGS.PILOT; - - // State - public isActive: boolean = true; - public isDestroyed: boolean = false; - - // Track last known player velocity for lead targeting - protected lastPlayerPosition: Vec3 | null = null; - protected estimatedPlayerVelocity: Vec3 = new Vec3(); - - constructor(type: EnemyType, position: Vec3) { - this.type = type; - this.position = position.clone(); - this.velocity = new Vec3(); - this.state = EnemyState.IDLE; - - // Set type-specific properties - // Speed uses same scale as player: impulse * 50 units/sec - switch (type) { - case EnemyType.FIGHTER: - this.health = this.maxHealth = 2; - this.speed = ENEMY_CONFIG.speeds.FIGHTER * ENEMY_CONFIG.UNITS_PER_IMPULSE; - this.fireRate = 1.5; - this.attackRange = 80; - console.log(`🔴 Fighter spawned - impulse: ${ENEMY_CONFIG.speeds.FIGHTER}, speed: ${this.speed} units/sec`); - break; - case EnemyType.CRUISER: - this.health = this.maxHealth = 4; - this.speed = ENEMY_CONFIG.speeds.CRUISER * ENEMY_CONFIG.UNITS_PER_IMPULSE; - this.fireRate = 2.5; - this.attackRange = 120; - console.log(`🟣 Cruiser spawned - impulse: ${ENEMY_CONFIG.speeds.CRUISER}, speed: ${this.speed} units/sec`); - break; - case EnemyType.BASESTAR: - this.health = this.maxHealth = 8; - this.speed = ENEMY_CONFIG.speeds.BASESTAR * ENEMY_CONFIG.UNITS_PER_IMPULSE; - this.fireRate = 3; - this.hasShields = true; - this.shieldsActive = true; - this.attackRange = 150; - console.log(`🟡 Basestar spawned - impulse: ${ENEMY_CONFIG.speeds.BASESTAR}, speed: ${this.speed} units/sec`); - break; - } - - // Initialize type-specific behaviors - if (type === EnemyType.FIGHTER) { - // Randomize orbit direction - this.orbitDirection = random() < 0.5 ? 1 : -1; - this.orbitAngle = random() * Math.PI * 2; - // Fighters are fast and agile - this.maxAcceleration = 50; - } else if (type === EnemyType.CRUISER) { - // Generate patrol waypoints - this.generatePatrolWaypoints(); - // Cruisers are slower to accelerate - this.maxAcceleration = 30; - } else if (type === EnemyType.BASESTAR) { - // Basestars are stationary - this.maxAcceleration = 0; - } - - // Start in honing mode - enemies approach player when sector is entered - this.isHoningIn = true; - this.honeInTimer = 0; - - this.mesh.position.copy(position); - } - - /** - * Set difficulty settings for this enemy - */ - public setDifficulty(difficulty: string): void { - this.difficultySettings = - DIFFICULTY_SETTINGS[difficulty] || DIFFICULTY_SETTINGS.PILOT; - - // Commander difficulty: Cruisers are always hostile - if ( - difficulty === 'COMMANDER' && - this.type === EnemyType.CRUISER && - this.difficultySettings.cruiserProvocationSensitivity >= 1.0 - ) { - this.provoked = true; - } - } - - /** - * Activate honing behavior - makes enemies aggressively pursue player - * Called when player enters a sector to ensure enemies always find the player - */ - public activateHoning(): void { - this.isHoningIn = true; - this.honeInTimer = 0; - } - - /** - * Generate patrol waypoints for Cruiser - */ - private generatePatrolWaypoints(): void { - // Create a figure-8 or rectangular patrol pattern - const centerX = this.position.x; - const centerY = this.position.y; - const centerZ = this.position.z; - const patternSize = 80; - - // Figure-8 pattern with 6 waypoints - this.patrolWaypoints = [ - new Vec3(centerX + patternSize, centerY, centerZ), - new Vec3(centerX + patternSize * 0.5, centerY + 20, centerZ + patternSize * 0.5), - new Vec3(centerX, centerY, centerZ + patternSize), - new Vec3(centerX - patternSize, centerY, centerZ), - new Vec3(centerX - patternSize * 0.5, centerY - 20, centerZ - patternSize * 0.5), - new Vec3(centerX, centerY, centerZ - patternSize), - ]; - - this.currentWaypointIndex = 0; - } - - /** - * Get the Three.js object - */ - public getObject(): Transform { - return this.mesh; - } - - /** - * Get enemy type - */ - public getType(): EnemyType { - return this.type; - } - - /** - * Get position - */ - public getPosition(): Vec3 { - return this.mesh.position.clone(); - } - - /** - * Get collision radius - */ - public getCollisionRadius(): number { - switch (this.type) { - case EnemyType.FIGHTER: - return 1.5; - case EnemyType.CRUISER: - return 2.5; - case EnemyType.BASESTAR: - return 4; - default: - return 2; - } - } - - /** - * Take damage - */ - public takeDamage(amount: number): boolean { - // Trigger provocation for Cruisers - this.onHit(); - - // Basestar shields must be down to take damage - if (this.hasShields && this.shieldsActive) { - // Damage reduces shields - this.shieldsActive = false; - this.updateShieldVisual(); - return false; - } - - this.health -= amount; - - if (this.health <= 0) { - this.health = 0; - this.isDestroyed = true; - this.isActive = false; - return true; - } - - return false; - } - - /** - * Update shield visual - */ - private updateShieldVisual(): void { - // Drawn by the renderer from hasActiveShields() once the ROM sprites exist (Phase 5). - } - - /** - * Update enemy state - */ - public update(deltaTime: number, playerPosition: Vec3): void { - if (!this.isActive) return; - - // Track player velocity for lead targeting - if (this.lastPlayerPosition) { - this.estimatedPlayerVelocity - .copy(playerPosition) - .sub(this.lastPlayerPosition) - .divideScalar(deltaTime); - } - this.lastPlayerPosition = playerPosition.clone(); - - // Calculate distance to player - const distanceToPlayer = this.mesh.position.distanceTo(playerPosition); - - // Update honing behavior - stop when close enough OR time expires - if (this.isHoningIn) { - this.honeInTimer += deltaTime; - // Stop honing when close enough OR timer expires - if (distanceToPlayer < this.honeInMinDistance || this.honeInTimer >= this.honeInDuration) { - this.isHoningIn = false; - } - } - - // Update evasion state - if (this.isEvading) { - this.evadeTimer -= deltaTime; - if (this.evadeTimer <= 0) { - this.isEvading = false; - this.evadeTarget = null; - } - } - - // Update state based on type and distance (no pursuit range limit - always pursue) - this.updateState(distanceToPlayer); - - // Calculate desired velocity based on type-specific behavior - this.targetVelocity.set(0, 0, 0); - - switch (this.type) { - case EnemyType.FIGHTER: - this.updateFighter(deltaTime, playerPosition, distanceToPlayer); - break; - case EnemyType.CRUISER: - this.updateCruiser(deltaTime, playerPosition, distanceToPlayer); - break; - case EnemyType.BASESTAR: - this.updateBasestar(deltaTime, playerPosition, distanceToPlayer); - break; - } - - // NO compensation needed - enemies move independently - // Player movement displacement naturally creates relative motion - // If enemy pursues at 400 u/s and player moves at 450 u/s: - // - Enemy moves 400 u/s toward player - // - Displacement pushes enemy 450 u/s away - // - Net: enemy falls behind at 50 u/s (player escapes) - // Compensation would prevent player from ever escaping! - // this.targetVelocity.add(playerVelocity); // REMOVED - - // Apply smooth velocity interpolation (prevents teleporting) - this.applySmoothedMovement(deltaTime); - - // Basestar shields regenerate with difficulty-scaled chance - if (this.hasShields && !this.shieldsActive) { - if (random() < this.difficultySettings.shieldRegenChance) { - this.shieldsActive = true; - this.updateShieldVisual(); - } - } - } - - /** - * Apply smoothed velocity-based movement to prevent teleporting - */ - private applySmoothedMovement(deltaTime: number): void { - // Skip for stationary enemies - if (this.type === EnemyType.BASESTAR) return; - - // Smoothly interpolate current velocity toward target velocity - const velocityDiff = this.targetVelocity.clone().sub(this.currentVelocity); - const maxChange = this.maxAcceleration * deltaTime; - - if (velocityDiff.length() > maxChange) { - velocityDiff.normalize().multiplyScalar(maxChange); - } - - this.currentVelocity.add(velocityDiff); - - // Apply velocity to position - const movement = this.currentVelocity.clone().multiplyScalar(deltaTime); - this.mesh.position.add(movement); - } - - /** - * Update state based on distance and type - */ - private updateState(distanceToPlayer: number): void { - if (this.type === EnemyType.BASESTAR) { - // Basestar is always stationary but enters attack mode when player is close - this.state = - distanceToPlayer < this.attackRange ? EnemyState.ATTACK : EnemyState.IDLE; - return; - } - - if (this.type === EnemyType.CRUISER && !this.provoked) { - // Unprovoked Cruisers only patrol, never attack - // Always patrol (no IDLE) - enemies never give up pursuit - this.state = - distanceToPlayer < this.attackRange ? EnemyState.ATTACK : EnemyState.PATROL; - return; - } - - // Fighters and provoked Cruisers - ALWAYS pursue, never go IDLE - // Enemies in the same sector as the player should always be hunting - if (distanceToPlayer < this.attackRange) { - this.state = EnemyState.ATTACK; - } else { - // Always PATROL (pursuit) - no distance limit - // This prevents enemies from getting stuck when far away - this.state = EnemyState.PATROL; - } - } - - /** - * Fighter-specific update - aggressive pursuit and strafe-orbit - */ - private updateFighter( - deltaTime: number, - playerPosition: Vec3, - distanceToPlayer: number - ): void { - // Handle honing behavior - approach player aggressively when entering sector - // Removed distance threshold - honing now works at any distance - if (this.isHoningIn) { - this.updateHoningBehavior(playerPosition); - return; - } - - // Handle active evasion - if (this.isEvading && this.evadeTarget) { - this.updateFighterEvade(deltaTime); - return; - } - - switch (this.state) { - case EnemyState.IDLE: - // Should never happen now, but if it does, pursue anyway - this.updateFighterPursuit(deltaTime, playerPosition, distanceToPlayer); - break; - - case EnemyState.PATROL: - // Aggressive pursuit with weaving - this.updateFighterPursuit(deltaTime, playerPosition, distanceToPlayer); - break; - - case EnemyState.ATTACK: - // Strafe-orbit around player - this.updateFighterOrbit(deltaTime, playerPosition, distanceToPlayer); - break; - } - - // Trigger evasive maneuvers (difficulty-scaled) - now smooth instead of instant - if ( - this.state === EnemyState.ATTACK && - !this.isEvading && - random() < this.difficultySettings.evasionChance * deltaTime - ) { - this.initiateEvasiveManeuver(); - } - } - - /** - * Universal honing behavior - aggressively approach player at max speed - * Used when player enters a sector to ensure enemies always find the player - */ - private updateHoningBehavior(playerPosition: Vec3): void { - // Calculate direction to player - const toPlayer = playerPosition.clone().sub(this.mesh.position); - const direction = toPlayer.normalize(); - - // Move toward player at slightly boosted speed (1.1x base speed for trackable pursuit) - // Fighter: 400 * 1.1 = 440 u/s (slightly slower than player max speed of 450) - // Cruiser: 300 * 1.1 = 330 u/s (slower than player max speed) - this.targetVelocity.copy(direction).multiplyScalar(this.speed * 1.1); - - // Face player - this.mesh.lookAt(playerPosition); - } - - /** - * Fighter evasion - smooth movement to evade target - */ - private updateFighterEvade(_deltaTime: number): void { - if (!this.evadeTarget) return; - - const toTarget = this.evadeTarget.clone().sub(this.mesh.position); - const distance = toTarget.length(); - - if (distance < 2) { - // Reached evade position - this.isEvading = false; - this.evadeTarget = null; - return; - } - - // Move toward evade target at high speed - this.targetVelocity.copy(toTarget.normalize()).multiplyScalar(this.speed * 1.5); - } - - /** - * Fighter pursuit behavior - approach with weaving - */ - private updateFighterPursuit( - deltaTime: number, - playerPosition: Vec3, - _distanceToPlayer: number - ): void { - // Update weave phase - this.weavePhase += deltaTime * 3; // 3 rad/s = smoother weave frequency - - // Calculate direction to player - const toPlayer = playerPosition.clone().sub(this.mesh.position); - const direction = toPlayer.normalize(); - - // Add sinusoidal weaving perpendicular to approach direction - // Weave is now a velocity component, not a position offset - const weaveAmplitude = 20; // Units per second lateral velocity - const perpendicular = new Vec3(-direction.z, 0, direction.x).normalize(); - const weaveVelocity = perpendicular.multiplyScalar(Math.sin(this.weavePhase) * weaveAmplitude); - - // Set target velocity: approach + weave - this.targetVelocity.copy(direction).multiplyScalar(this.speed).add(weaveVelocity); - - // Face player - this.mesh.lookAt(playerPosition); - } - - /** - * Fighter orbit behavior - circle-strafe around player - */ - private updateFighterOrbit( - deltaTime: number, - playerPosition: Vec3, - _distanceToPlayer: number - ): void { - const ORBIT_RADIUS = ENEMY_CONFIG.distances.FIGHTER_ORBIT_RADIUS; // Desired orbit distance - const ORBIT_SPEED = 1.0; // Radians per second (reduced for trackable circle-strafing) - - // Update orbit angle - this.orbitAngle += this.orbitDirection * ORBIT_SPEED * deltaTime; - - // Calculate target orbit position - const orbitX = playerPosition.x + Math.cos(this.orbitAngle) * ORBIT_RADIUS; - const orbitZ = playerPosition.z + Math.sin(this.orbitAngle) * ORBIT_RADIUS; - const orbitY = - playerPosition.y + Math.sin(this.orbitAngle * 0.5) * 10; // Slight vertical variation - - const targetOrbitPos = new Vec3(orbitX, orbitY, orbitZ); - - // Calculate velocity to move toward orbit position - const toOrbit = targetOrbitPos.clone().sub(this.mesh.position); - const orbitDistance = toOrbit.length(); - - // Calculate tangent velocity (for smooth orbiting) - const tangent = new Vec3( - -Math.sin(this.orbitAngle), - 0, - Math.cos(this.orbitAngle) - ).multiplyScalar(this.orbitDirection); - - if (orbitDistance > 15) { - // Too far from orbit - move toward it at reduced speed to prevent overshoot - this.targetVelocity.copy(toOrbit.normalize()).multiplyScalar(this.speed * 0.7); - } else { - // Near orbit - combine tangent motion with stronger pull toward ideal radius - const radialCorrection = toOrbit.clone().multiplyScalar(1.5); // Stronger correction - this.targetVelocity.copy(tangent).multiplyScalar(this.speed * 0.6).add(radialCorrection); - } - - // Always face the player - this.mesh.lookAt(playerPosition); - - // Occasionally change orbit direction (less frequent) - if (random() < 0.002 * deltaTime * 60) { - this.orbitDirection *= -1; - } - } - - /** - * Initiate a smooth evasive maneuver (replaces instant teleport) - */ - private initiateEvasiveManeuver(): void { - // Set evade target position (relative to current position) - const dodgeDistance = 15 + random() * 15; // 15-30 units - const dodgeOffset = new Vec3( - (random() - 0.5) * dodgeDistance, - (random() - 0.5) * dodgeDistance * 0.3, // Less vertical - (random() - 0.5) * dodgeDistance - ); - - this.evadeTarget = this.mesh.position.clone().add(dodgeOffset); - this.isEvading = true; - this.evadeTimer = 0.8 + random() * 0.4; // 0.8-1.2 seconds - } - - /** - * Cruiser-specific update - patrol patterns and defensive behavior - */ - private updateCruiser( - deltaTime: number, - playerPosition: Vec3, - distanceToPlayer: number - ): void { - // Handle honing behavior - approach player when entering sector - // Removed distance threshold - honing now works at any distance - if (this.isHoningIn) { - this.updateHoningBehavior(playerPosition); - return; - } - - switch (this.state) { - case EnemyState.IDLE: - // Should never happen now, but if it does, patrol anyway - this.updateCruiserPatrol(deltaTime); - break; - - case EnemyState.PATROL: - // Follow patrol waypoints - this.updateCruiserPatrol(deltaTime); - break; - - case EnemyState.ATTACK: - // Tactical approach - maintain distance - this.updateCruiserAttack(deltaTime, playerPosition, distanceToPlayer); - break; - } - } - - /** - * Cruiser patrol - follow waypoint pattern - */ - private updateCruiserPatrol(deltaTime: number): void { - if (this.patrolWaypoints.length === 0) { - this.targetVelocity.set(0, 0, 0); - return; - } - - // Check if pausing at waypoint (smooth deceleration instead of hard stop) - if (this.waypointPauseTimer > 0) { - this.waypointPauseTimer -= deltaTime; - this.mesh.rotation.y += deltaTime * 0.2; // Slight rotation while paused - // Decelerate to stop - this.targetVelocity.set(0, 0, 0); - return; - } - - const targetWaypoint = this.patrolWaypoints[this.currentWaypointIndex]; - const toWaypoint = targetWaypoint.clone().sub(this.mesh.position); - const distance = toWaypoint.length(); - - if (distance < 8) { - // Near waypoint - brief pause then move to next - this.waypointPauseTimer = 0.3; // Shorter pause for smoother flow - this.currentWaypointIndex = - (this.currentWaypointIndex + 1) % this.patrolWaypoints.length; - this.targetVelocity.set(0, 0, 0); - } else { - // Set target velocity toward waypoint at patrol speed - const patrolSpeed = this.speed * ENEMY_CONFIG.multipliers.CRUISER_PATROL; - this.targetVelocity.copy(toWaypoint.normalize()).multiplyScalar(patrolSpeed); - - // Smoothly rotate to face waypoint - this.mesh.lookAt(targetWaypoint); - } - } - - /** - * Cruiser attack - maintain tactical distance - */ - private updateCruiserAttack( - _deltaTime: number, - playerPosition: Vec3, - distanceToPlayer: number - ): void { - const PREFERRED_MIN = ENEMY_CONFIG.distances.CRUISER_PREFERRED_MIN; - const PREFERRED_MAX = ENEMY_CONFIG.distances.CRUISER_PREFERRED_MAX; - - const toPlayer = playerPosition.clone().sub(this.mesh.position); - - if (distanceToPlayer < PREFERRED_MIN) { - // Too close - back off - const direction = toPlayer.normalize().negate(); - this.targetVelocity.copy(direction).multiplyScalar(this.speed * ENEMY_CONFIG.multipliers.CRUISER_BACKOFF); - } else if (distanceToPlayer > PREFERRED_MAX) { - // Too far - approach - const direction = toPlayer.normalize(); - this.targetVelocity.copy(direction).multiplyScalar(this.speed); - } else { - // In preferred range - strafe slowly - const perpendicular = new Vec3(-toPlayer.z, 0, toPlayer.x).normalize(); - this.targetVelocity.copy(perpendicular).multiplyScalar(this.speed * ENEMY_CONFIG.multipliers.CRUISER_STRAFE); - } - - // Always face the player - this.mesh.lookAt(playerPosition); - } - - /** - * Basestar-specific update - stationary with rotation - */ - private updateBasestar( - deltaTime: number, - playerPosition: Vec3, - _distanceToPlayer: number - ): void { - if (this.state === EnemyState.ATTACK) { - // Track player when in attack range - this.mesh.lookAt(playerPosition); - - // Faster rotation when shields are down (urgency) - if (!this.shieldsActive) { - this.mesh.rotation.y += deltaTime * 0.3; - } - } else { - // Slow idle rotation - this.mesh.rotation.y += deltaTime * 0.2; - } - } - - /** - * Set provoked state (for Cruisers) - */ - public setProvoked(value: boolean): void { - this.provoked = value; - } - - /** - * Check if enemy is provoked - */ - public isProvoked(): boolean { - return this.provoked; - } - - /** - * Handle being hit - may provoke Cruisers - */ - public onHit(): void { - if (this.type === EnemyType.CRUISER) { - this.provoked = true; - } - } - - /** - * Check near miss - may provoke Cruisers based on difficulty - */ - public checkNearMiss(torpedoPosition: Vec3, missDistance: number): void { - if (this.type !== EnemyType.CRUISER || this.provoked) return; - - const distance = this.mesh.position.distanceTo(torpedoPosition); - if (distance < missDistance) { - // Near miss - check provocation based on difficulty sensitivity - if (random() < this.difficultySettings.cruiserProvocationSensitivity) { - this.provoked = true; - } - } - } - - /** - * Check if enemy should fire at player - */ - public shouldFire(currentTime: number, playerPosition: Vec3): boolean { - if (!this.isActive || this.state !== EnemyState.ATTACK) return false; - - // Cruisers only fire when provoked - if (this.type === EnemyType.CRUISER && !this.provoked) return false; - - const distance = this.mesh.position.distanceTo(playerPosition); - if (distance > this.attackRange) return false; - - // Apply difficulty-scaled fire rate - const adjustedFireRate = this.fireRate * this.difficultySettings.aggressionMultiplier; - - // Low health Fighters fire faster (desperation mode) - const healthMultiplier = - this.type === EnemyType.FIGHTER && this.health === 1 ? 0.5 : 1.0; - - if (currentTime - this.lastFireTime >= adjustedFireRate * healthMultiplier) { - this.lastFireTime = currentTime; - return true; - } - - return false; - } - - /** - * Get the predicted position to aim at (lead targeting) - * Returns a position ahead of the player based on projectile travel time - */ - public getLeadTargetPosition( - playerPosition: Vec3, - projectileSpeed: number = 200 - ): Vec3 { - const distance = this.mesh.position.distanceTo(playerPosition); - const travelTime = distance / projectileSpeed; - - // Calculate predicted position based on player velocity - const leadPosition = playerPosition.clone(); - - // Apply lead accuracy based on difficulty (interpolate between direct and full lead) - const leadAmount = this.difficultySettings.leadAccuracy; - const predictedOffset = this.estimatedPlayerVelocity - .clone() - .multiplyScalar(travelTime * leadAmount); - - leadPosition.add(predictedOffset); - - return leadPosition; - } - - /** - * Get firing direction (for creating projectiles) - */ - public getFiringDirection(playerPosition: Vec3): Vec3 { - const targetPos = this.getLeadTargetPosition(playerPosition); - return targetPos.sub(this.mesh.position).normalize(); - } - - /** - * Get health percentage - */ - public getHealthPercent(): number { - return (this.health / this.maxHealth) * 100; - } - - /** - * Check if shields are active - */ - public hasActiveShields(): boolean { - return this.hasShields && this.shieldsActive; - } - - /** - * Dispose of resources - */ - public dispose(): void { - // Nothing to free: the 2D renderer draws from the position each frame. - } -} diff --git a/src/entities/EnemyProjectile.ts b/src/entities/EnemyProjectile.ts deleted file mode 100644 index b65b17b..0000000 --- a/src/entities/EnemyProjectile.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Vec3 } from '../core/vec3'; -import { EnemyType } from './Enemy'; - -/** - * Zylon torpedo (ship frame). Phase 5 replaces it with the §17.7 rules (one at a time, 62-loop - * life, per-level homing); the renderer draws it as a small blob. - */ -export interface EnemyProjectileConfig { - speed: number; - damage: number; -} - -export const PROJECTILE_CONFIGS: Record = { - FIGHTER: { speed: 180, damage: 100 }, - CRUISER: { speed: 150, damage: 200 }, - BASESTAR: { speed: 120, damage: 350 }, -}; - -const HIT_RADIUS = 0.2; - -export class EnemyProjectile { - public readonly position: Vec3; - private readonly velocity: Vec3; - private age: number = 0; - private readonly maxAge: number = 4; // seconds - private readonly damage: number; - public isActive: boolean = true; - public sourceType: EnemyType; - - constructor(position: Vec3, direction: Vec3, enemyType: EnemyType) { - this.sourceType = enemyType; - const config = PROJECTILE_CONFIGS[enemyType]; - this.damage = config.damage; - this.position = position.clone(); - this.velocity = direction.clone().normalize().multiplyScalar(config.speed); - } - - public getPosition(): Vec3 { - return this.position.clone(); - } - - public getDamage(): number { - return this.damage; - } - - public update(deltaTime: number): void { - if (!this.isActive) return; - this.position.add(this.velocity.clone().multiplyScalar(deltaTime)); - this.age += deltaTime; - if (this.age >= this.maxAge) this.isActive = false; - } - - public checkCollision(targetPosition: Vec3, targetRadius: number): boolean { - return this.position.distanceTo(targetPosition) < targetRadius + HIT_RADIUS; - } - - public deactivate(): void { - this.isActive = false; - } - - public dispose(): void {} -} diff --git a/src/entities/PhotonTorpedo.ts b/src/entities/PhotonTorpedo.ts deleted file mode 100644 index d1fc0e1..0000000 --- a/src/entities/PhotonTorpedo.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Vec3 } from '../core/vec3'; - -/** - * Photon torpedo (ship frame). Phase 5 replaces the flight rules with §17.7 (alternating - * barrels, 23-loop refire, 255-loop life, homing); the renderer draws it as a purple blob. - */ -export class PhotonTorpedo { - private readonly centerPosition: Vec3; - private readonly velocity: Vec3; - private age: number = 0; - private readonly maxAge: number = 3; // seconds - private readonly speed: number = 110; // units per second - public isActive: boolean = true; - - constructor(position: Vec3, direction: Vec3) { - this.centerPosition = position.clone(); - this.velocity = direction.clone().normalize().multiplyScalar(this.speed); - } - - /** The live position (moved by turning and flying like every space object). */ - public get position(): Vec3 { - return this.centerPosition; - } - - public getPosition(): Vec3 { - return this.centerPosition.clone(); - } - - public update(deltaTime: number): void { - if (!this.isActive) return; - this.centerPosition.add(this.velocity.clone().multiplyScalar(deltaTime)); - this.age += deltaTime; - if (this.age >= this.maxAge) this.isActive = false; - } - - public checkCollision(targetPosition: Vec3, targetRadius: number): boolean { - return this.centerPosition.distanceTo(targetPosition) < targetRadius + 0.2; - } - - public deactivate(): void { - this.isActive = false; - } - - public dispose(): void {} -} diff --git a/src/game/Game.ts b/src/game/Game.ts index 1c162e9..6096a68 100644 --- a/src/game/Game.ts +++ b/src/game/Game.ts @@ -1,15 +1,11 @@ import { GameLoop } from './GameLoop'; import { GameState, ViewMode, DifficultyLevel } from './GameState'; import { Input, type Action } from '../input/Input'; -import { CombatSystem } from '../systems/CombatSystem'; import { SoundManager } from '../audio/SoundManager'; -import { PhotonTorpedo } from '../entities/PhotonTorpedo'; -import { EnemyProjectile } from '../entities/EnemyProjectile'; import { Starbase } from '../entities/Starbase'; import { ControlPanel, type TrackedPosition } from '../ui/ControlPanel'; import { GalacticChart } from '../views/GalacticChart'; import { LongRangeScan } from '../views/LongRangeScan'; -import { EnemyType, type Enemy } from '../entities/Enemy'; import { createRng, getSeed, random } from '../core/rng'; import { Vec3 } from '../core/vec3'; import { getSettings, onSettingsChange, updateSettings, type Settings } from '../core/settings'; @@ -20,14 +16,15 @@ import { approachVelocity, KM_PER_UNIT, moveInShipFrame, STICK_CENTERED, type St import type { MissionOutcome } from '../rules/rating'; import { VELOCITY_TAB } from '../rules/speed'; import { calcWarpSectors } from '../rules/warp'; -import { rollDamage, SUBSYSTEMS, type Subsystem, type SubsystemStatus } from '../rules/damage'; +import { SUBSYSTEMS, type Subsystem, type SubsystemStatus } from '../rules/damage'; import { MSG, PHRASE, endOfMissionPhrase, subsystemPhrase } from '../rules/messages'; import { Galaxy, RadioFeed, GALAXY_COLUMNS, GALAXY_ROWS, type GalaxyEvent, type SectorPos } from '../sim/galaxy'; import { Renderer, type SpaceFrame, type SpaceObject } from '../render/Renderer'; +import { resolveShipHit, VICINITY_MASK_TABLE, ZylonSim, type SimView, type ZylonEvent, type ZylonType } from '../sim/zylons'; import { CLASSIC_STARS, ENHANCED_STARS, Starfield } from '../render/starfield'; import type { SpaceView } from '../render/projection'; -export type DebugSpawnType = 'fighter' | 'cruiser' | 'basestar' | 'starbase'; +export type DebugSpawnType = ZylonType | 'starbase'; export interface GameDebugApi { state(): Record; @@ -54,19 +51,21 @@ export interface GameDebugApi { settings(patch?: Partial): Settings; redAlert(loops?: number): void; stars(): Array<{ x: number; y: number; z: number; col: number | null; row: number | null; color: number }>; + zylons(): Record; + meteor(x: number, y: number, z: number): void; } type GameOverCallback = (rating: MissionRating) => void; /** Loops the background flashes random colours after a hit with shields up (§17.13). */ const HIT_FLASH_LOOPS = 16; +/** R: the Zylon torpedo's ship is earmarked; θ Φ R and T follow it while the computer is on. */ /** R: REDALERTLIFE on entering a Zylon sector. */ const RED_ALERT_LOOPS = 255; /** Ship velocity (KM/loop) when it drops out of hyperspace; it slows by 1 per loop (R: UPDPANEL). */ const WARP_EXIT_VELOCITY = 120; /** Velocity used for the streaming stars while hyperwarping (Phase 8 brings the ROM's 254 and trails). */ const HYPERWARP_VELOCITY = 112; -const ORIGIN = new Vec3(); /** Fraction of the placeholder hyperwarp after which the ship counts as in hyperspace (Phase 8 replaces it). */ const HYPERSPACE_FROM = 0.5; @@ -97,7 +96,8 @@ export class Game { /** The galaxy map: the one source of Zylon counts (sim/galaxy.ts, §17.4). */ private galaxy: Galaxy; private radioFeed: RadioFeed; - private combatSystem: CombatSystem; + /** Zylon ships, their torpedo, meteors, our photons and explosions (sim/zylons.ts, §16, §17.7, §17.8). */ + private zylons: ZylonSim; private soundManager: SoundManager; private gameState: GameState; private unsubscribeSettings: () => void; @@ -108,12 +108,8 @@ export class Game { private longRangeScan: LongRangeScan; /** Hyperwarp destination dot on the chart (§8); kept between visits. */ private chartCursor: SectorPos = { x: 8, y: 4 }; - /** Ships placed by the debug hook; not part of the galaxy count. */ - private debugExtras = new Set(); // Space objects - private torpedoes: PhotonTorpedo[] = []; - private enemyProjectiles: EnemyProjectile[] = []; private currentStarbase: Starbase | null = null; // Flight @@ -160,6 +156,8 @@ export class Game { this.renderer = new Renderer(container); const settings = getSettings(); this.renderer.setCrt(settings.crt); + // The renderer's flicker and sparkle draw from their own stream, so drawing never shifts the game's. + this.renderer.setRandom(createRng(getSeed() ^ 0x0b5e)); this.starfield = new Starfield(createRng(getSeed() ^ 0x5a17), this.starCount(settings), 'FRONT'); this.unsubscribeSettings = onSettingsChange((s) => { this.renderer.setCrt(s.crt); @@ -182,12 +180,12 @@ export class Game { this.radioFeed = new RadioFeed(this.galaxy); this.chartCursor = { x: this.gameState.sectorX, y: this.gameState.sectorY }; - this.combatSystem = new CombatSystem(this.gameState); + this.zylons = new ZylonSim(random); this.soundManager = new SoundManager(); this.controlPanel = new ControlPanel(this.gameState, random); this.galacticChart = new GalacticChart(container); - this.longRangeScan = new LongRangeScan(container, this.gameState, this.combatSystem, () => this.currentStarbase); + this.longRangeScan = new LongRangeScan(container, this.gameState, () => this.scanBlips()); // §17.1: a game starts at speed key 6. this.shipVelocity = VELOCITY_TAB[this.gameState.targetEngineSpeed]; @@ -212,8 +210,8 @@ export class Game { */ private spawnSectorContents(): void { const { sectorX: x, sectorY: y } = this.gameState; - this.debugExtras.clear(); - this.combatSystem.spawnEnemiesForSector(this.galaxy.zylonsAt(x, y)); + // Zylon ships enter one at a time from the sector's count (sim/zylons.ts, §17.8). + this.zylons.clear(); if (this.galaxy.hasStarbase(x, y)) { const starbasePos = new Vec3((random() - 0.5) * 100, (random() - 0.5) * 30, 100 - random() * 50); @@ -225,10 +223,8 @@ export class Game { * Clear sector contents */ private clearSectorContents(): void { - this.combatSystem.clearEnemies(); + this.zylons.clear(); this.currentStarbase = null; - this.torpedoes = []; - this.enemyProjectiles = []; } public start(): void { @@ -276,29 +272,7 @@ export class Game { this.currentStarbase.update(deltaTime); this.checkDocking(); } - - this.updateTorpedoes(deltaTime); - - // Enemies chase our starship, which sits at the origin. - this.combatSystem.update(deltaTime, ORIGIN); - - const firingEnemy = this.combatSystem.getEnemyFiring(this.gameTime, ORIGIN); - if (firingEnemy) { - const projectile = new EnemyProjectile( - firingEnemy.getPosition(), - firingEnemy.getFiringDirection(ORIGIN), - firingEnemy.getType() - ); - this.enemyProjectiles.push(projectile); - this.soundManager.playEnemyFire(); - } - - this.updateEnemyProjectiles(deltaTime); - this.gameState.isUnderAttack = this.enemyProjectiles.length > 0; - - // Check torpedo collisions; every kill comes off the galaxy map (one source, §17.4) - for (const enemy of this.combatSystem.checkTorpedoCollisions(this.torpedoes)) this.zylonKilled(enemy); - if (this.gameState.isGameOver) return; + this.gameState.isUnderAttack = this.zylons.torpedoFlying; this.renderChart(); this.longRangeScan.update(); @@ -324,6 +298,7 @@ export class Game { this.handleGalaxyEvents(this.galaxy.moveTick(player, this.clock.starDateTicks)); } this.flyLoop(); + if (this.gameState.isGameOver) return; // R: UPDPANEL, UPDTITLE, FLUSHGAMELOOP — readouts, title line, band and shields colours. this.controlPanel.loop(this.trackedPosition()); this.gameState.starDate = this.clock.starDate; @@ -347,26 +322,103 @@ export class Game { // The ROM does not rotate in the Galactic Chart view; in hyperwarp the stick steers the marker. const turn: Stick = view === ViewMode.GALACTIC_CHART || this.isHyperwarping || this.isDocking ? STICK_CENTERED : stick; const dzUnits = this.shipVelocity / KM_PER_UNIT; - for (const p of this.objectPositions()) moveInShipFrame(p, turn, dzUnits); + if (this.currentStarbase) moveInShipFrame(this.currentStarbase.getObject().position, turn, dzUnits); this.wrapSectorObjects(); this.starfield.loop(turn, this.shipVelocity, this.spaceView(), this.clock.loops & 7); + // Zylons, torpedoes, meteors and explosions (R: GAMELOOP steps 8–12, 21, 23, 25–27). + const { sectorX: sx, sectorY: sy } = this.gameState; + const events = this.zylons.loop({ + turn, + velocity: this.shipVelocity, + view: this.simView(), + level: this.gameState.difficulty, + sectorZylons: this.galaxy.zylonsAt(sx, sy), + starbaseSector: this.galaxy.hasStarbase(sx, sy), + hyperwarp: this.isHyperwarping, + count256: this.controlPanel.colors.count256, + computer: this.gameState.attackComputerOn && this.gameState.damage.computer !== 'destroyed', + }); + for (const e of events) this.zylonEvent(e); + if (this.redAlertLife > 0) this.redAlertLife--; if (this.hitFlash > 0) this.hitFlash--; } - /** Live positions (in units) of every space object that turns and flies with the ship. */ - private objectPositions(): Vec3[] { - const out: Vec3[] = []; - for (const e of this.combatSystem.getEnemies()) if (e.isActive) out.push(e.getObject().position); - if (this.currentStarbase) out.push(this.currentStarbase.getObject().position); - for (const t of this.torpedoes) out.push(t.position); - for (const p of this.enemyProjectiles) out.push(p.position); + /** The ROM's SHIPVIEW for the Zylon simulation. */ + private simView(): SimView { + switch (this.gameState.currentView) { + case ViewMode.AFT: + return 'AFT'; + case ViewMode.GALACTIC_CHART: + return 'CHART'; + case ViewMode.LONG_RANGE_SCAN: + return 'LRS'; + default: + return 'FRONT'; + } + } + + /** React to one event of the Zylon simulation (§16, §17.7, §17.12). */ + private zylonEvent(e: ZylonEvent): void { + switch (e.type) { + case 'zylonDestroyed': + this.soundManager.playExplosion(); + this.zylonKilled(e.debug); + break; + case 'basestarHit': + case 'shotDown': + this.soundManager.playExplosion(); + break; + case 'shipHit': + this.shipHit(e.by, e.torpedoLife); + break; + default: + break; + } + } + + /** + * GAMELOOP steps 26–27: the Zylon torpedo or a meteor hit us (§5.9, §16, §17.3, §17.7). + * The hit test reads SHIELDSCOLOR, so damaged shields protect only while they flicker on. + */ + private shipHit(by: 'torpedo' | 'meteor', torpedoLife: number): void { + const r = resolveShipHit({ + shieldsUp: this.controlPanel.colors.shieldsUp, + level: this.gameState.difficulty, + damage: this.gameState.damage, + by, + torpedoLife, + randomByte: () => Math.floor(random() * 256), + }); + if (r.destroyed) { + // SHIP DESTROYED BY ZYLON FIRE: the front view, then the end sequence (R: GAMEOVER). + this.soundManager.playPlayerHit(); + this.switchView(ViewMode.FRONT); + this.endMission('destroyed'); + return; + } + if (r.damage) this.reportDamage(r.damage.system, r.damage.status); + this.soundManager.playShieldHit(); + this.hitFlash = HIT_FLASH_LOOPS; // §17.13: the screen flashes random colours + this.energy.hit(); // −100 (§12.1, §17.1) + } + + /** Long-range scan blips in KM: Zylon ships, the meteor and the starbase (Phase 9 redraws the scan). */ + private scanBlips(): Array<{ x: number; z: number; kind: 'enemy' | 'starbase' }> { + const out: Array<{ x: number; z: number; kind: 'enemy' | 'starbase' }> = []; + for (const s of this.zylons.ships) if (s.alive) out.push({ x: s.x, z: s.z, kind: 'enemy' }); + const m = this.zylons.pl2; + if (m.kind === 'meteor' && m.life > 0) out.push({ x: m.x, z: m.z, kind: 'enemy' }); + if (this.currentStarbase) { + const p = this.currentStarbase.getObject().position; + out.push({ x: p.x * KM_PER_UNIT, z: p.z * KM_PER_UNIT, kind: 'starbase' }); + } return out; } - /** Keep ships and the starbase inside the sector (±500 units, toroidal in x and z). */ + /** Keep the starbase inside the sector (±500 units, toroidal in x and z; Phase 10 rebuilds it). */ private wrapSectorObjects(): void { const wrap = (p: Vec3) => { const H = 500; @@ -375,17 +427,16 @@ export class Game { if (p.z > H) p.z -= 2 * H; else if (p.z < -H) p.z += 2 * H; }; - for (const e of this.combatSystem.getEnemies()) if (e.isActive) wrap(e.getObject().position); if (this.currentStarbase) wrap(this.currentStarbase.getObject().position); } /** * A Zylon ship in the player's sector was destroyed: count it and take it off the map. */ - private zylonKilled(enemy: Enemy): void { + private zylonKilled(debug: boolean): void { this.gameState.enemiesDestroyed++; this.missionScore.zylonDestroyed(); - if (this.debugExtras.delete(enemy)) return; // debug ship: not on the map + if (debug) return; // placed by the debug hook: not on the map this.handleGalaxyEvents(this.galaxy.destroyZylon(this.gameState.sectorX, this.gameState.sectorY)); } @@ -396,19 +447,15 @@ export class Game { for (const e of events) { switch (e.type) { case 'starbaseSurrounded': - if (this.radioFeed.relaysMessages) { - this.controlPanel.setTitle(PHRASE.STARBASE_SURROUNDED); - this.soundManager.playAlert(); - } + // (The "message from starbase" tune is Phase 12; the red alert only sounds on arrival.) + if (this.radioFeed.relaysMessages) this.controlPanel.setTitle(PHRASE.STARBASE_SURROUNDED); break; case 'starbaseDestroyed': { this.missionScore.starbaseDestroyedByZylons(); // -18 (§14.1) if (this.radioFeed.relaysMessages) this.controlPanel.setTitle(PHRASE.STARBASE_DESTROYED); if (e.x === this.gameState.sectorX && e.y === this.gameState.sectorY) { - // The debris becomes two Zylons right here: put them in play (§8.2). + // The debris becomes two Zylons right here; they enter from the new count (§8.2). this.currentStarbase = null; - const live = this.combatSystem.getEnemies().filter((en) => en.isActive && !this.debugExtras.has(en)).length; - this.combatSystem.spawnMore(this.galaxy.zylonsAt(e.x, e.y) - live); } break; } @@ -468,10 +515,9 @@ export class Game { * sits at the origin facing +z. (Phase 6 brings the ROM's target slots 0–3.) */ private trackedPosition(): TrackedPosition | null { - const target = this.combatSystem.getCurrentTarget(); - if (!target || !target.isActive) return null; - const p = target.getPosition(); - return { x: p.x * KM_PER_UNIT, y: p.y * KM_PER_UNIT, z: p.z * KM_PER_UNIT }; + this.controlPanel.setTrackDigit(this.zylons.trackDigit); + const target = this.zylons.trackedShip(); + return target ? { x: target.x, y: target.y, z: target.z } : null; } /** @@ -483,7 +529,7 @@ export class Game { this.dockingCooldown -= 1 / 60; return; } - if (this.currentStarbase.canDock(ORIGIN, this.gameState.engineSpeed) && !this.isDocking) { + if (this.currentStarbase.canDock(new Vec3(), this.gameState.engineSpeed) && !this.isDocking) { this.isDocking = true; this.dockingProgress = 0; // ORBIT ESTABLISHED, then STANDBY; docking also empties the title queue (R: DOCKING). @@ -525,49 +571,6 @@ export class Game { // Losing every starbase does not end the game (§17.4). Zero energy ends it from sim/energy.ts. } - private updateTorpedoes(deltaTime: number): void { - for (let i = this.torpedoes.length - 1; i >= 0; i--) { - const torpedo = this.torpedoes[i]; - torpedo.update(deltaTime); - if (!torpedo.isActive) this.torpedoes.splice(i, 1); - } - } - - private updateEnemyProjectiles(deltaTime: number): void { - for (let i = this.enemyProjectiles.length - 1; i >= 0; i--) { - const projectile = this.enemyProjectiles[i]; - projectile.update(deltaTime); - if (!projectile.isActive) this.enemyProjectiles.splice(i, 1); - } - this.checkEnemyProjectileCollisions(); - } - - /** Zylon torpedoes against our starship at the origin. */ - private checkEnemyProjectileCollisions(): void { - const PLAYER_COLLISION_RADIUS = 2.5; - - for (let i = this.enemyProjectiles.length - 1; i >= 0; i--) { - const projectile = this.enemyProjectiles[i]; - if (!projectile.isActive || !projectile.checkCollision(ORIGIN, PLAYER_COLLISION_RADIUS)) continue; - - // Every hit costs 100 units (§12.1, §17.1) and may damage a subsystem (§17.3) - this.energy.hit(); - const harm = rollDamage(this.gameState.difficulty, this.gameState.damage, 0, () => Math.floor(random() * 256)); - - // R: the hit test reads SHIELDSCOLOR, so damaged shields protect only while they flicker on. - if (this.controlPanel.colors.shieldsUp) { - this.soundManager.playShieldHit(); - this.hitFlash = HIT_FLASH_LOOPS; // §17.13: the screen flashes random colours - } else { - this.soundManager.playPlayerHit(); - } - if (harm) this.reportDamage(harm.system, harm.status); - - projectile.deactivate(); - this.enemyProjectiles.splice(i, 1); - } - } - /** R: DAMAGE — DAMAGE CONTROL now; the subsystem phrase waits in the queue and repeats until docking. */ private reportDamage(system: Subsystem, status: 'damaged' | 'destroyed'): void { this.gameState.damage[system] = status; @@ -661,6 +664,8 @@ export class Game { // Drop out of hyperspace fast and slow down to the chosen speed. this.shipVelocity = WARP_EXIT_VELOCITY; + // R: VICINITYMASK from bits 3..1 of the arrival marker's PM row (Phase 8 brings the real marker). + this.zylons.vicinityMask = VICINITY_MASK_TABLE[((122 + 2 * Math.round(this.hyperwarpAlignment.y)) >> 1) & 7]; this.spawnSectorContents(); this.controlPanel.setTitle(PHRASE.HYPERWARP_COMPLETE); @@ -724,7 +729,7 @@ export class Game { this.controlPanel.setTitle(this.gameState.trackingComputerOn ? PHRASE.COMPUTER_TRACKING_ON : PHRASE.TRACKING_OFF); return; case 'MANUAL_TARGET': - this.combatSystem.selectNextTarget(); + this.zylons.toggleTarget(); return; case 'PAUSE': return; // Phase 11 @@ -753,28 +758,14 @@ export class Game { } /** - * Fire both photon torpedoes along the view direction. - * (Phase 5 brings the ROM's alternating barrels, refire time and homing.) + * TRIGGER (§17.7): one photon per press, from alternating barrels; a barrel refires after 23 + * loops; −10 energy each. Shields never block firing (the manual has no such rule). */ private fireTorpedo(): void { - const view = this.gameState.currentView; - if (view !== ViewMode.FRONT && view !== ViewMode.AFT) return; - - // (The ROM has no title phrase for a refused shot; Phase 5 brings its firing rules.) - if (this.gameState.shieldsActive && this.gameState.difficulty !== DifficultyLevel.NOVICE) return; - if (this.gameState.damage.photons !== 'ok') return; - - // Each photon launched costs 10 units (§12.1); both barrels fire here. - this.energy.firePhoton(); - this.energy.firePhoton(); - if (this.gameState.isGameOver) return; - - const dir = view === ViewMode.AFT ? -1 : 1; - const convergence = new Vec3(0, 0, 50 * dir); - for (const barrelX of [-2, 2]) { - const start = new Vec3(barrelX, -1.4, 0.2 * dir); - this.torpedoes.push(new PhotonTorpedo(start, convergence.clone().sub(start))); - } + const launched = this.zylons.fire(this.simView(), this.gameState.damage.photons, this.isHyperwarping); + if (!launched) return; + this.energy.firePhoton(); // §12.1: −10 per photon + this.soundManager.playTorpedoFire(); } private setEngineSpeed(speed: number): void { @@ -789,22 +780,22 @@ export class Game { /** What the renderer draws for the Front/Aft views this frame. */ private spaceFrame(): SpaceFrame { - const km = (p: Vec3, kind: SpaceObject['kind']): SpaceObject => ({ - kind, - x: p.x * KM_PER_UNIT, - y: p.y * KM_PER_UNIT, - z: p.z * KM_PER_UNIT, - }); const objects: SpaceObject[] = []; - for (const e of this.combatSystem.getEnemies()) if (e.isActive) objects.push(km(e.getObject().position, 'zylon')); - if (this.currentStarbase) objects.push(km(this.currentStarbase.getObject().position, 'starbase')); - for (const t of this.torpedoes) objects.push(km(t.position, 'photon')); - for (const p of this.enemyProjectiles) objects.push(km(p.position, 'zylonTorpedo')); + const z = this.zylons; + for (const sh of z.ships) if (sh.alive) objects.push({ kind: sh.type, x: sh.x, y: sh.y, z: sh.z }); + if (z.pl2.life > 0) objects.push({ kind: z.pl2.kind === 'meteor' ? 'meteor' : 'zylonTorpedo', x: z.pl2.x, y: z.pl2.y, z: z.pl2.z }); + for (const p of z.photons) if (p.life > 0) objects.push({ kind: 'photon', x: p.x, y: p.y, z: p.z }); + if (this.currentStarbase) { + const p = this.currentStarbase.getObject().position; + objects.push({ kind: 'starbase', x: p.x * KM_PER_UNIT, y: p.y * KM_PER_UNIT, z: p.z * KM_PER_UNIT }); + } return { view: this.spaceView(), stars: this.starfield.stars, objects, + fragments: z.explosion?.fragments ?? [], + count256: this.controlPanel.colors.count256, crosshair: this.gameState.attackComputerOn && this.gameState.damage.computer !== 'destroyed', shields: this.controlPanel.colors.shieldsUp, redAlertLife: this.redAlertLife, @@ -826,7 +817,6 @@ export class Game { this.update(DT); this.render(); }; - const ahead = (distance: number) => new Vec3(0, 0, distance); return { state: () => ({ @@ -839,7 +829,7 @@ export class Game { hyperwarpProgress: this.hyperwarpProgress, isDocking: this.isDocking, dockingProgress: this.dockingProgress, - enemiesInSector: this.combatSystem.getEnemies().filter((e) => e.isActive).length, + enemiesInSector: this.zylons.liveShips, starbaseInSector: this.currentStarbase !== null, remainingEnemies: this.galaxy.zylonsLeft, starbasesLeft: this.galaxy.starbasesLeft, @@ -868,17 +858,14 @@ export class Game { this.gameState.sectorY = y; this.spawnSectorContents(); }, - spawn: (type: DebugSpawnType, distance = 60, x = 0, y = 0) => { - const pos = ahead(distance); - pos.x = x; - pos.y = y; + spawn: (type: DebugSpawnType, distance = 4096, x = 0, y = 0) => { if (type === 'starbase') { + const pos = new Vec3(x / KM_PER_UNIT, y / KM_PER_UNIT, distance / KM_PER_UNIT); if (this.currentStarbase) this.currentStarbase.getObject().position.copy(pos); else this.currentStarbase = new Starbase(pos); return; } - const enemyType = { fighter: EnemyType.FIGHTER, cruiser: EnemyType.CRUISER, basestar: EnemyType.BASESTAR }[type]; - this.debugExtras.add(this.combatSystem.spawnEnemy(enemyType, pos)); + this.zylons.spawn(type, { x, y, z: distance }); }, setView: (view: ViewMode) => this.switchView(view), step: (n = 1) => { @@ -892,7 +879,7 @@ export class Game { }, dock: () => { if (!this.currentStarbase) this.currentStarbase = new Starbase(new Vec3()); - this.currentStarbase.getObject().position.copy(ahead(30)); + this.currentStarbase.getObject().position.copy(new Vec3(0, 0, 30)); this.gameState.engineSpeed = 0; this.gameState.targetEngineSpeed = 0; this.shipVelocity = 0; @@ -937,13 +924,19 @@ export class Game { return frames; }, killSector: () => { - // Destroy every live Zylon here through the same path as a torpedo kill. - const live = this.combatSystem.getEnemies().filter((e) => e.isActive); - for (const e of live) { - e.takeDamage(1000); - this.zylonKilled(e); + // Destroy every Zylon of this sector (live or still to come) through the kill path. + let n = 0; + this.zylons.ships.forEach((s, slot) => { + if (!s.alive) return; + this.zylons.destroyShip(slot); + this.zylonKilled(s.debug); + if (!s.debug) n++; + }); + while (!this.gameState.isGameOver && this.galaxy.zylonsAt(this.gameState.sectorX, this.gameState.sectorY) > 0) { + this.zylonKilled(false); + n++; } - return live.length; + return n; }, stick: (x: number, y: number) => { const d = (v: number) => (v > 0 ? 1 : v < 0 ? -1 : 0) as -1 | 0 | 1; @@ -964,6 +957,24 @@ export class Game { row: s.pixel?.row ?? null, color: s.color, })), + zylons: () => { + const z = this.zylons; + return JSON.parse( + JSON.stringify({ + ships: z.ships, + pl2: z.pl2, + photons: z.photons, + barrel: z.barrel, + trackDigit: z.trackDigit, + vicinityMask: z.vicinityMask, + explosionLife: z.explosion?.life ?? 0, + }) + ); + }, + meteor: (x: number, y: number, z: number) => { + const p = this.zylons.pl2; + Object.assign(p, { kind: 'meteor', life: 60, x, y, z, vel: { x: 0, y: 0, z: -8 } }); + }, }; } @@ -984,10 +995,8 @@ export class Game { this.controlPanel.dispose(); this.galacticChart.dispose(); this.longRangeScan.dispose(); - this.combatSystem.dispose(); this.renderer.dispose(); + this.zylons.clear(); this.currentStarbase = null; - this.torpedoes = []; - this.enemyProjectiles = []; } } diff --git a/src/render/Renderer.ts b/src/render/Renderer.ts index 6fa1dfd..bdf0f21 100644 --- a/src/render/Renderer.ts +++ b/src/render/Renderer.ts @@ -21,8 +21,9 @@ import { drawPanelText, drawText, GLYPH_COLUMNS } from './font'; import { ROM_RGB, atariColor } from './palette'; import { CENTER_COL, CENTER_ROW, PLAYFIELD_H, PLAYFIELD_W, projectPoint, type SpaceView } from './projection'; -import type { Star } from './starfield'; +import { starColor, type Star } from './starfield'; import { random } from '../core/rng'; +import { placeSprite, SHAPE, shapeColor, STARBASE_WING_DROP, STARBASE_WING_OFFSET, type ShapeType, type SpritePlacement } from './sprites'; export const FRAME_W = PLAYFIELD_W; export const PANEL_LINES = 23; @@ -62,7 +63,7 @@ export function frameRect(viewW: number, viewH: number): { x: number; y: number; return { x: Math.floor((viewW - w) / 2), y: Math.floor((viewH - h) / 2), w, h, k }; } -export type SpaceObjectKind = 'zylon' | 'starbase' | 'photon' | 'zylonTorpedo'; +export type SpaceObjectKind = 'fighter' | 'cruiser' | 'basestar' | 'starbase' | 'photon' | 'zylonTorpedo' | 'meteor'; export interface SpaceObject { kind: SpaceObjectKind; @@ -72,6 +73,24 @@ export interface SpaceObject { z: number; } +/** A point in the ship frame (KM): an explosion fragment. */ +export interface SpacePoint { + x: number; + y: number; + z: number; +} + +/** The ROM shape type each object is drawn with (§18.3; the Zylon torpedo uses the photon shape). */ +export const OBJECT_SHAPE: Readonly> = { + fighter: SHAPE.FIGHTER, + cruiser: SHAPE.CRUISER, + basestar: SHAPE.BASESTAR, + starbase: SHAPE.STARBASE_CENTER, + photon: SHAPE.PHOTON, + zylonTorpedo: SHAPE.PHOTON, + meteor: SHAPE.METEOR, +}; + /** The panel's fields as text (sim/panel.ts) plus the band colour. */ export interface PanelData { v: string; @@ -91,6 +110,10 @@ export interface SpaceFrame { view: SpaceView; stars: readonly Star[]; objects: readonly SpaceObject[]; + /** Explosion fragments: single playfield pixels coloured like stars (§17.7, R step 17). */ + fragments: readonly SpacePoint[]; + /** R: COUNT256 (starbase pulse) and COUNT8 (star/fragment colours). */ + count256: number; /** Attack computer on: front cross hairs or aft dashes (§5.3, §17.6). */ crosshair: boolean; /** Shields up and working: background $A0 (§17.13). */ @@ -137,27 +160,41 @@ export function crosshairRects(view: SpaceView): Array<[number, number, number, return bars; } -/** Placeholder blob size (playfield pixels) by distance; the ROM sprites arrive in Phase 5. */ -export function blobSize(distanceKm: number): number { - const d = Math.abs(distanceKm); - if (d < 1024) return 4; - if (d < 2560) return 3; - if (d < 5120) return 2; - return 1; +/** + * One sprite drawn in Atari colours (R step 15): hue by type, luminance by range. The basestar's + * colour is XORed with a random byte every frame (it flickers); the starbase pulses with COUNT256; + * photon torpedo rows are ANDed with random bits (they sparkle, R step 6). + */ +export interface DrawnSprite extends SpritePlacement { + color: number; } -const OBJECT_RGB: Record string> = { - // §17.13: Zylons grey/white, brightness falling with distance. - zylon: (d) => (d < 2560 ? ROM_RGB.$0E : ROM_RGB.$06), - starbase: () => ROM_RGB.$28, - photon: () => ROM_RGB.$58, - zylonTorpedo: () => ROM_RGB.$0E, -}; +/** Sprites for one object (three for a starbase: centre and wings), or [] when not on screen. */ +export function objectSprites(o: SpaceObject, view: SpaceView, count256: number, rng: () => number): DrawnSprite[] { + const place = placeSprite(OBJECT_SHAPE[o.kind], o.x, o.y, o.z, view); + if (!place) return []; + const byte = () => Math.floor(rng() * 256) & 0xff; + let color = shapeColor(place.type, place.range); + if (o.kind === 'basestar') color ^= byte(); + if (o.kind === 'starbase') color ^= count256 & 0x0f; + if (o.kind === 'photon' || o.kind === 'zylonTorpedo') place.rows = place.rows.map((r) => r & byte()); + const out: DrawnSprite[] = [{ ...place, color }]; + if (o.kind === 'starbase') { + for (const [type, dx] of [[SHAPE.STARBASE_LEFT, -STARBASE_WING_OFFSET], [SHAPE.STARBASE_RIGHT, STARBASE_WING_OFFSET]] as const) { + const wing = placeSprite(type, o.x, o.y, o.z, view); + if (wing) out.push({ ...wing, col: place.col + dx, line: place.line + STARBASE_WING_DROP, color: shapeColor(type, place.range) ^ (count256 & 0x0f) }); + } + } + return out; +} export class Renderer { public readonly canvas: HTMLCanvasElement; private readonly ctx: CanvasRenderingContext2D; - /** The frame at native resolution, 160 × 120. */ + /** + * The frame at native resolution, 160 × 123, stored with two lines per row so sprites can use + * the Player/Missile scanline (half a playfield row). Drawing uses playfield coordinates. + */ private readonly frame: HTMLCanvasElement; private readonly fctx: CanvasRenderingContext2D; private crt = false; @@ -170,8 +207,9 @@ export class Renderer { this.ctx = this.canvas.getContext('2d')!; this.frame = document.createElement('canvas'); this.frame.width = FRAME_W; - this.frame.height = FRAME_LINES; + this.frame.height = FRAME_LINES * 2; this.fctx = this.frame.getContext('2d')!; + this.fctx.setTransform(1, 0, 0, 2, 0, 0); } /** Random source for the hit flash (the game's seeded stream keeps captures deterministic). */ @@ -222,15 +260,12 @@ export class Renderer { this.pf(s.pixel.col, s.pixel.row, 1, 1, s.color === 3 ? pf2 : STAR_RGB[s.color]); } - // Objects: placeholder blobs, far ones first. - const objs = [...f.objects].sort((a, b) => Math.abs(b.z) - Math.abs(a.z)); - for (const o of objs) { - const px = projectPoint(o.x, o.y, o.z, f.view); + // Explosion fragments: playfield pixels coloured by distance like the stars (R step 17). + for (const p of f.fragments) { + const px = projectPoint(p.x, p.y, p.z, f.view); if (!px) continue; - const d = Math.hypot(o.x, o.y, o.z); - const size = o.kind === 'photon' || o.kind === 'zylonTorpedo' ? Math.min(2, blobSize(d)) : blobSize(d); - const half = Math.floor(size / 2); - this.pf(px.col - half, px.row - half, size, size, OBJECT_RGB[o.kind](d)); + const c = starColor(p.z, px.col, f.count256 & 7); + if (c) this.pf(px.col, px.row, 1, 1, c === 3 ? pf2 : STAR_RGB[c]); } if (f.warpMarker) this.drawWarpMarker(f.warpMarker.dx, f.warpMarker.dy); @@ -246,9 +281,28 @@ export class Renderer { drawText((x, y, w, h) => this.fctx.fillRect(x, y, w, h), title.slice(0, TEXT_COLUMNS), 0, zone.textLine, 1); } + // PLAYER sprites lie over the playfield and the title line (§18.3), far ones first. + const objs = [...f.objects].sort((a, b) => Math.abs(b.z) - Math.abs(a.z)); + for (const o of objs) for (const s of objectSprites(o, f.view, f.count256, this.rng)) this.drawSprite(s); + this.drawPanel(f.panel); } + /** One sprite, one scanline (half a playfield row) per byte, clipped to the playfield. */ + private drawSprite(s: DrawnSprite): void { + this.fctx.fillStyle = atariColor(s.color); + s.rows.forEach((bits, i) => { + const line = s.line + i; + if (line < 0 || line >= PLAYFIELD_H * 2) return; + for (let b = 0; b < 8; b++) { + if (!(bits & (0x80 >> b))) continue; + const col = s.col + b; + if (col < 0 || col >= PLAYFIELD_W) continue; + this.fctx.fillRect(col, line / 2, 1, 0.5); + } + }); + } + /** §18.3 hyperwarp target marker, sky blue, around an offset from the centre. */ private drawWarpMarker(dx: number, dy: number): void { const shape = ['..#.#..', '###.###', '.......', '###.###', '..#.#..']; @@ -309,7 +363,7 @@ export class Renderer { ctx.imageSmoothingEnabled = false; ctx.fillStyle = '#000'; ctx.fillRect(0, 0, cw, ch); - ctx.drawImage(this.frame, 0, 0, FRAME_W, FRAME_LINES, r.x, r.y, r.w, r.h); + ctx.drawImage(this.frame, 0, 0, FRAME_W, FRAME_LINES * 2, r.x, r.y, r.w, r.h); if (this.crt && r.k >= 2) { // Two scanlines per pixel row like the Atari's: darken the bottom of each half row. ctx.fillStyle = 'rgba(0,0,0,0.42)'; diff --git a/src/render/palette.ts b/src/render/palette.ts index 0146f2e..d3e4394 100644 --- a/src/render/palette.ts +++ b/src/render/palette.ts @@ -19,16 +19,12 @@ export const ROM_RGB = { $9F: '#A0C8FF', // hyperwarp marker $4F: '#FFA898', // title line and near stars during a red alert (PF2, R: GAMELOOP step 16) $60: '#24105C', // title line and near stars while the red-alert background is lit - $28: '#F0A040', // starbase (orange $2x, Phase 3 placeholder blob) - $58: '#C070E0', // photon torpedoes (purple $5x) - $0E: '#E0E0E0', // Zylon ships, near (grey/white $0x) - $06: '#808080', // Zylon ships, far } as const; /** * Approximate sRGB of any Atari colour byte (hue in the high nibble, luminance in the low). - * Used where the ROM picks random colours (hit flash, basestar flicker); fixed elements use - * ROM_RGB above. + * Used for the sprites (hue by type, luminance by range, §17.13) and where the ROM picks random + * colours (hit flash, basestar flicker); fixed elements use ROM_RGB above. */ export function atariColor(byte: number): string { const hue = (byte >> 4) & 0x0f; diff --git a/src/render/sprites.test.ts b/src/render/sprites.test.ts new file mode 100644 index 0000000..8c37e85 --- /dev/null +++ b/src/render/sprites.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest'; +import { createRng } from '../core/rng'; +import { objectSprites } from './Renderer'; +import { placeSprite, SHAPE, SHAPE_CELLS, shapeColor, shapeRows, spritesOverlap, viewDistanceHi } from './sprites'; + +const art = (rows: number[]) => rows.map((r) => r.toString(2).padStart(8, '0').replace(/0/g, '.').replace(/1/g, '#')); + +// MANUAL_SPEC §18.3: the manual's sprite plates are the ROM bitmaps at their largest size. +describe('ROM sprite bitmaps', () => { + it('fighter: the 12-row H', () => { + expect(art(shapeRows(SHAPE.FIGHTER, 0))).toEqual([ + '#......#', '#......#', '#......#', '#......#', '#.####.#', '########', + '########', '#.####.#', '#......#', '#......#', '#......#', '#......#', + ]); + }); + it('cruiser: the 9-row arch', () => { + expect(art(shapeRows(SHAPE.CRUISER, 0))).toEqual([ + '...##...', '..####..', '.######.', '.######.', '##.##.##', '##....##', '#......#', '#......#', '#......#', + ]); + }); + it('basestar: the 10-row diamond with wing bars', () => { + expect(art(shapeRows(SHAPE.BASESTAR, 0))).toEqual([ + '...##...', '..####..', '.######.', '########', '...##...', '...##...', '########', '.######.', '..####..', '...##...', + ]); + }); + it('photon / meteor: the 16-row ball', () => { + expect(shapeRows(SHAPE.PHOTON, 0)).toHaveLength(16); + expect(shapeRows(SHAPE.METEOR, 0)).toEqual(shapeRows(SHAPE.PHOTON, 0)); + }); +}); + +// §17.13: 8 size cells by distance, brightness falls with range, nothing beyond 8192 KM. +describe('distance cells and brightness', () => { + it('8 cells per shape, never growing with distance', () => { + for (const type of [SHAPE.FIGHTER, SHAPE.CRUISER, SHAPE.BASESTAR, SHAPE.PHOTON]) { + const heights = Array.from({ length: SHAPE_CELLS }, (_, c) => shapeRows(type, c).length); + for (let c = 1; c < SHAPE_CELLS; c++) expect(heights[c]).toBeLessThanOrEqual(heights[c - 1]); + } + }); + + it('the cell is the |z| high byte / 2, in the view direction; ≥ 8192 KM is not drawn', () => { + expect(placeSprite(SHAPE.FIGHTER, 0, 0, 500, 'FRONT')!.cell).toBe(0); + expect(placeSprite(SHAPE.FIGHTER, 0, 0, 1024, 'FRONT')!.cell).toBe(2); + expect(placeSprite(SHAPE.FIGHTER, 0, 0, 8191, 'FRONT')!.cell).toBe(7); + expect(placeSprite(SHAPE.FIGHTER, 0, 0, 8192, 'FRONT')).toBeNull(); + expect(placeSprite(SHAPE.FIGHTER, 0, 0, -1024, 'FRONT')).toBeNull(); + expect(placeSprite(SHAPE.FIGHTER, 0, 0, -1024, 'AFT')!.cell).toBe(1); + expect(viewDistanceHi(-1, 'AFT')).toBe(0); + }); + + it('Zylons are grey: $0E near down to $04 far', () => { + expect(shapeColor(SHAPE.FIGHTER, 0)).toBe(0x0e); + expect(shapeColor(SHAPE.FIGHTER, 15)).toBe(0x04); + expect(shapeColor(SHAPE.PHOTON, 0) & 0xf0).toBe(0x50); // purple + expect(shapeColor(SHAPE.METEOR, 0) & 0xf0).toBe(0xa0); // green + }); + + it('the basestar flickers: its colour changes from frame to frame', () => { + const rng = createRng(3); + const colors = new Set( + Array.from({ length: 8 }, () => objectSprites({ kind: 'basestar', x: 0, y: 0, z: 2000 }, 'FRONT', 0, rng)[0].color) + ); + expect(colors.size).toBeGreaterThan(4); + const fighter = new Set( + Array.from({ length: 8 }, () => objectSprites({ kind: 'fighter', x: 0, y: 0, z: 2000 }, 'FRONT', 0, rng)[0].color) + ); + expect([...fighter]).toEqual([0x0a]); // range 7: $0A, steady + }); + + it('the starbase is a centre and two wings', () => { + const parts = objectSprites({ kind: 'starbase', x: 0, y: 0, z: 1000 }, 'FRONT', 0, createRng(1)); + expect(parts.map((p) => p.type)).toEqual([SHAPE.STARBASE_CENTER, SHAPE.STARBASE_LEFT, SHAPE.STARBASE_RIGHT]); + expect(parts[1].col).toBe(parts[0].col - 8); + expect(parts[2].col).toBe(parts[0].col + 8); + }); +}); + +describe('collision (Player/Missile overlap)', () => { + it('needs a lit pixel in common', () => { + const a = placeSprite(SHAPE.FIGHTER, 0, 0, 500, 'FRONT')!; + expect(spritesOverlap(a, { ...a })).toBe(true); + expect(spritesOverlap(a, { ...a, col: a.col + 8 })).toBe(false); + // The H is hollow: a 1-pixel dot inside the top gap does not touch it. + expect(spritesOverlap(a, { ...a, col: a.col + 3, rows: [0x80], line: a.line })).toBe(false); + }); +}); diff --git a/src/render/sprites.ts b/src/render/sprites.ts new file mode 100644 index 0000000..dc8dcdd --- /dev/null +++ b/src/render/sprites.ts @@ -0,0 +1,197 @@ +/** + * The ROM's PLAYER sprites (MANUAL_SPEC §17.13, §18.3; R: PLSHAP1TAB L10023, PLSHAP2TAB L10230, + * PLSHAPOFFTAB L11156, PLSHAPHEIGHTTAB L11168, PLSHAPCOLORTAB L11512, PLSHAPBRITTAB L11524, + * PLSTARBAOFFTAB L11199, GAMELOOP step 15). + * + * Every space object that is a PLAYER (Zylon ships, torpedoes, meteor, starbase) is an 8-pixel + * wide bitmap. Each shape type has 8 "shape cells", one per distance step: the high byte of |z| + * (KM, in the view's direction), capped at 15, is the range index; the cell is range / 2. Objects + * 8192 KM or more away are not drawn; cell 6 is the one-pixel Long-Range Scan dot. + * + * One sprite row is one scanline: half a playfield row (Player/Missile single-line resolution), + * so each sprite pixel is twice as wide as it is tall. + * + * Bytes below are copied from the ROM; each byte is one row, bit 7 the leftmost pixel. + */ +import { CENTER_COL, CENTER_ROW, projectPoint, type SpaceView } from './projection'; + +/** R: SHAP.* shape types (PL0SHAPTYPE >> 4). */ +export const SHAPE = { + PHOTON: 0, + FIGHTER: 1, + STARBASE_RIGHT: 2, + STARBASE_CENTER: 3, + STARBASE_LEFT: 4, + TRANSFER_VESSEL: 5, + METEOR: 6, + CRUISER: 7, + BASESTAR: 8, + HYPERWARP_MARKER: 9, +} as const; +export type ShapeType = (typeof SHAPE)[keyof typeof SHAPE]; + +/** R: PLSHAP1TAB — shapes of PLAYER2..4 (torpedoes, meteor, starbase centre, transfer vessel, marker). */ +export const PLSHAP1TAB: readonly number[] = [ + 0x00, 0x18, 0x3C, 0x7E, 0x7E, 0x76, 0xF7, 0xDF, 0xDF, 0xFF, 0xFF, 0xF7, 0x76, 0x7E, 0x7E, 0x3C, + 0x18, 0x10, 0x38, 0x7C, 0x7C, 0xFE, 0xDE, 0xDA, 0xFA, 0xEE, 0xEE, 0x7C, 0x7C, 0x38, 0x10, 0x18, + 0x3C, 0x3C, 0x7E, 0x6E, 0x7A, 0x7E, 0x76, 0x7E, 0x3C, 0x3C, 0x18, 0x10, 0x38, 0x38, 0x7C, 0x74, + 0x7C, 0x6C, 0x38, 0x38, 0x10, 0x10, 0x18, 0x3C, 0x2C, 0x3C, 0x3C, 0x18, 0x08, 0x10, 0x38, 0x38, + 0x28, 0x38, 0x10, 0x3C, 0x3C, 0x24, 0x3C, 0x7E, 0x7E, 0x7E, 0x5A, 0xFF, 0xFF, 0x42, 0x42, 0x42, + 0x42, 0x42, 0x42, 0x1C, 0x1C, 0x14, 0x3E, 0x3E, 0x3E, 0x2A, 0x7F, 0x7F, 0x22, 0x22, 0x22, 0x22, + 0x22, 0x18, 0x18, 0x3C, 0x3C, 0x3C, 0x3C, 0x7E, 0x24, 0x24, 0x24, 0x24, 0x10, 0x10, 0x38, 0x38, + 0x38, 0x7C, 0x28, 0x28, 0x28, 0x18, 0x18, 0x3C, 0x18, 0x18, 0x10, 0x10, 0x38, 0x10, 0x18, 0x7E, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xE7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E, 0x7E, 0x00, 0x18, + 0x3C, 0x7E, 0xFF, 0xFF, 0xFF, 0xE7, 0x66, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E, 0x7E, 0x00, 0x18, 0x3C, + 0x7E, 0xFF, 0xFF, 0xE7, 0x66, 0xFF, 0xFF, 0xFF, 0xFF, 0x3C, 0x18, 0x3C, 0xFF, 0xFF, 0xE7, 0x66, + 0xFF, 0xFF, 0x7E, 0x3C, 0x00, 0x18, 0x3C, 0xFF, 0xFF, 0xFF, 0x3C, 0x18, 0x18, 0x3C, 0xFF, 0x3C, + 0x18, 0x28, 0x28, 0x28, 0x28, 0xEE, 0x00, 0x00, 0xEE, 0x28, 0x28, 0x28, 0x28, +]; + +/** R: PLSHAP2TAB — shapes of PLAYER0..1 (Zylon ships, starbase wings). */ +export const PLSHAP2TAB: readonly number[] = [ + 0x00, 0x81, 0x81, 0x81, 0x81, 0xBD, 0xFF, 0xFF, 0xBD, 0x81, 0x81, 0x81, 0x81, 0x82, 0x82, 0xBA, + 0xFE, 0xFE, 0xBA, 0x82, 0x82, 0x42, 0x5A, 0x7E, 0x7E, 0x5A, 0x42, 0x44, 0x54, 0x7C, 0x7C, 0x54, + 0x44, 0x24, 0x3C, 0x3C, 0x24, 0x28, 0x38, 0x38, 0x28, 0x18, 0x18, 0x10, 0x10, 0xE0, 0xF8, 0xF8, + 0xFE, 0x57, 0xFE, 0xF8, 0xF8, 0xC0, 0xC0, 0xF0, 0xC0, 0xF0, 0xF0, 0xFC, 0xBE, 0xFC, 0xF0, 0x80, + 0x80, 0xC0, 0xC0, 0xF0, 0xBC, 0xF0, 0xC0, 0x07, 0x1F, 0x1F, 0x7F, 0xEA, 0x7F, 0x1F, 0x1F, 0x03, + 0x03, 0x0F, 0x03, 0x0F, 0x0F, 0x3F, 0x7D, 0x3F, 0x0F, 0x01, 0x01, 0x03, 0x03, 0x0F, 0x3D, 0x0F, + 0x03, 0x18, 0x3C, 0x7E, 0x7E, 0xDB, 0xC3, 0x81, 0x81, 0x81, 0x10, 0x38, 0x7C, 0x7C, 0xD6, 0xC6, + 0x82, 0x82, 0x18, 0x3C, 0x3C, 0x66, 0x66, 0x42, 0x42, 0x10, 0x38, 0x38, 0x6C, 0x44, 0x44, 0x18, + 0x3C, 0x24, 0x24, 0x10, 0x38, 0x28, 0x18, 0x3C, 0x7E, 0xFF, 0x18, 0x18, 0xFF, 0x7E, 0x3C, 0x18, + 0x10, 0x38, 0x7C, 0xFE, 0x38, 0x38, 0xFE, 0x7C, 0x38, 0x10, 0x18, 0x3C, 0x7E, 0x18, 0x7E, 0x3C, + 0x18, 0x10, 0x38, 0x7C, 0x10, 0x7C, 0x38, 0x10, 0x18, 0x3C, 0x18, 0x3C, 0x18, 0x10, 0x38, 0x38, + 0x10, +]; + +/** R: PLSHAPOFFTAB — first row of each of the 8 shape cells, per shape type. */ +export const PLSHAPOFFTAB: readonly (readonly number[])[] = [ + [0x01, 0x11, 0x1f, 0x2b, 0x35, 0x3d, 0x75, 0x7a], // 0 photon torpedo (table 1) + [0x01, 0x0d, 0x15, 0x1b, 0x21, 0x25, 0x29, 0x2b], // 1 Zylon fighter (table 2) + [0x2d, 0x38, 0x41, 0x36, 0x36, 0x00, 0x00, 0x00], // 2 starbase right (table 2) + [0x7e, 0x8e, 0x9d, 0xaa, 0xb4, 0xbc, 0x7b, 0x7a], // 3 starbase centre (table 1) + [0x47, 0x52, 0x5b, 0x50, 0x50, 0x00, 0x00, 0x00], // 4 starbase left (table 2) + [0x43, 0x53, 0x61, 0x6c, 0x75, 0x7a, 0x75, 0x7a], // 5 transfer vessel (table 1) + [0x01, 0x11, 0x1f, 0x2b, 0x35, 0x3d, 0x75, 0x7a], // 6 meteor (table 1) + [0x61, 0x6a, 0x72, 0x79, 0x7f, 0x83, 0x29, 0x2b], // 7 Zylon cruiser (table 2) + [0x86, 0x90, 0x9a, 0xa1, 0xa8, 0xad, 0x29, 0x2b], // 8 Zylon basestar (table 2) + [0xc1, 0xc1, 0xc1, 0xc1, 0xc1, 0xc1, 0x75, 0xc1], // 9 hyperwarp target marker (table 1) +]; + +/** R: PLSHAPHEIGHTTAB — rows − 1 of each shape cell, per shape type. */ +export const PLSHAPHEIGHTTAB: readonly (readonly number[])[] = [ + [0x0f, 0x0d, 0x0b, 0x09, 0x07, 0x05, 0x01, 0x01], + [0x0b, 0x07, 0x05, 0x05, 0x03, 0x03, 0x01, 0x01], + [0x09, 0x08, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00], + [0x0f, 0x0e, 0x0c, 0x09, 0x07, 0x04, 0x02, 0x01], + [0x09, 0x08, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00], + [0x0f, 0x0d, 0x0a, 0x08, 0x04, 0x03, 0x01, 0x01], + [0x0f, 0x0d, 0x0b, 0x09, 0x07, 0x05, 0x01, 0x01], + [0x08, 0x07, 0x06, 0x05, 0x03, 0x02, 0x01, 0x01], + [0x09, 0x09, 0x06, 0x06, 0x04, 0x03, 0x01, 0x01], + [0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x01, 0x0b], +]; + +/** R: PLSHAPCOLORTAB — hue (bits 7..4) per shape type: purple, grey, orange, green, sky blue. */ +export const PLSHAPCOLORTAB: readonly number[] = [0x50, 0x00, 0x20, 0x20, 0x20, 0x00, 0xa0, 0x00, 0x00, 0x9f]; + +/** R: PLSHAPBRITTAB — luminance (bits 3..0) by range index 0..15: near bright, far dim. */ +export const PLSHAPBRITTAB: readonly number[] = [ + 0x0e, 0x0e, 0x0e, 0x0c, 0x0c, 0x0c, 0x0a, 0x0a, 0x0a, 0x08, 0x08, 0x08, 0x06, 0x06, 0x04, 0x04, +]; + +/** Shapes drawn from PLSHAP2TAB (the ROM's PLAYER0..1); the others use PLSHAP1TAB. */ +const TABLE2: ReadonlySet = new Set([ + SHAPE.FIGHTER, + SHAPE.STARBASE_RIGHT, + SHAPE.STARBASE_LEFT, + SHAPE.CRUISER, + SHAPE.BASESTAR, +]); + +/** PLAYER objects 8192 KM or more away (in the view's direction) are not drawn (R step 15). */ +export const SPRITE_MAX_DISTANCE = 0x2000; + +/** Number of shape cells per shape type. */ +export const SHAPE_CELLS = 8; + +/** + * The high byte of |z| in the view's direction (R: "EOR #$FF" in the Aft view): z ≥ 0 KM in + * front, z < 0 behind. Returns 255 for an object on the wrong side. + */ +export function viewDistanceHi(zKm: number, view: SpaceView): number { + const hi = Math.floor(zKm / 256) & 0xff; + if (view === 'FRONT') return zKm >= 0 ? hi : 0xff; + return zKm < 0 ? hi ^ 0xff : 0xff; +} + +/** Range index 0..15 for a distance high byte (R step 15). */ +export function rangeIndex(distanceHi: number): number { + return Math.min(15, distanceHi); +} + +/** The shape cell 0..7 for a range index: the closer, the larger. */ +export function shapeCell(range: number): number { + return Math.min(15, Math.max(0, range)) >> 1; +} + +/** Rows of a shape cell, top first (one byte per scanline). */ +export function shapeRows(type: ShapeType, cell: number): number[] { + const table = TABLE2.has(type) ? PLSHAP2TAB : PLSHAP1TAB; + const offset = PLSHAPOFFTAB[type][cell]; + const height = PLSHAPHEIGHTTAB[type][cell] + 1; + return table.slice(offset, offset + height); +} + +/** Colour byte of a PLAYER: hue by type, luminance by range (R step 15, before special effects). */ +export function shapeColor(type: ShapeType, range: number): number { + return (PLSHAPCOLORTAB[type] ^ PLSHAPBRITTAB[Math.min(15, Math.max(0, range))]) & 0xff; +} + +/** A sprite placed on the playfield: left column, top in scanlines (half rows) from row 0. */ +export interface SpritePlacement { + type: ShapeType; + range: number; + cell: number; + /** Playfield column of the leftmost bit. */ + col: number; + /** Top row in scanlines from the playfield's top (2 per playfield row). */ + line: number; + rows: number[]; +} + +/** + * Where a PLAYER object is drawn in a view, or null when it is not on screen (R steps 12 and + * 15; SCREENCOLUMN/SCREENROW place a PLAYER 3 PM pixels left of the projected column and with + * its top one playfield row above the projected row). + */ +export function placeSprite(type: ShapeType, x: number, y: number, z: number, view: SpaceView): SpritePlacement | null { + const hi = viewDistanceHi(z, view); + if (hi >= SPRITE_MAX_DISTANCE >> 8) return null; + const px = projectPoint(x, y, z, view); + if (!px) return null; + const range = rangeIndex(hi); + const cell = shapeCell(range); + return { type, range, cell, col: px.col - 3, line: 2 * (px.row - 1), rows: shapeRows(type, cell) }; +} + +/** R: PLSTARBAOFFTAB — the starbase wings sit 8 PM pixels left and right of the centre, 4 scanlines lower. */ +export const STARBASE_WING_OFFSET = 8; +export const STARBASE_WING_DROP = 4; + +/** Does any lit pixel of sprite a overlap one of sprite b (the Player/Missile collision registers)? */ +export function spritesOverlap(a: SpritePlacement, b: SpritePlacement): boolean { + const dx = b.col - a.col; + if (Math.abs(dx) >= 8) return false; + for (let i = 0; i < a.rows.length; i++) { + const j = a.line + i - b.line; + if (j < 0 || j >= b.rows.length) continue; + // Bit 7 is the leftmost pixel: shift b right by dx to put both in a's frame. + const bRow = dx >= 0 ? b.rows[j] >> dx : (b.rows[j] << -dx) & 0xff; + if (a.rows[i] & bRow) return true; + } + return false; +} + +/** The centre of the playfield in scanlines (R: PM row 122 is the vertical centre). */ +export const CENTER_LINE = 2 * CENTER_ROW; +export { CENTER_COL }; diff --git a/src/sim/zylons.test.ts b/src/sim/zylons.test.ts new file mode 100644 index 0000000..39bda8f --- /dev/null +++ b/src/sim/zylons.test.ts @@ -0,0 +1,395 @@ +import { describe, expect, it } from 'vitest'; +import { createRng } from '../core/rng'; +import { allSystemsOk, type DamageStatus } from '../rules/damage'; +import { COST } from '../rules/energy'; +import { SHAPE, shapeRows } from '../render/sprites'; +import { + BASESTAR_MAX_TORPEDO_AGE, + EXPLOSION_FRAGMENTS, + EXPLOSION_LIFE, + MAX_ZYLON_SHIPS, + METEOR_SPEED, + PHOTON_LIFE, + PHOTON_REFIRE_LOOPS, + resolveShipHit, + ZYLON_SHAPE_TABLE, + ZYLON_TORPEDO_LIFE, + ZylonSim, + type ZylonEvent, + type ZylonLoopInput, +} from './zylons'; + +const input = (over: Partial = {}): ZylonLoopInput => ({ + turn: { x: 0, y: 0 }, + velocity: 0, + view: 'FRONT', + level: 'NOVICE', + sectorZylons: 0, + starbaseSector: false, + hyperwarp: false, + count256: 0, + computer: true, + ...over, +}); + +/** Run `n` loops with COUNT256 counting like the ROM's; returns every event. */ +function run(sim: ZylonSim, n: number, over: Partial = {}, start = 0): ZylonEvent[] { + const out: ZylonEvent[] = []; + for (let i = 0; i < n; i++) out.push(...sim.loop(input({ count256: (start + i) & 0xff, ...over }))); + return out; +} + +/** A photon of a given age flying straight at a target on the axis. */ +function photonAt(sim: ZylonSim, slot: number, age: number, z: number): void { + Object.assign(sim.photons[slot], { life: PHOTON_LIFE - age, x: 0, y: 0, z, vel: { x: 0, y: 0, z: 0 } }); +} + +// MANUAL_SPEC §17.8: type mix 4/8 fighter, 3/8 cruiser, 1/8 basestar on every level. +describe('Zylon type mix', () => { + it('ZYLONSHAPTAB holds 4 fighters, 3 cruisers and 1 basestar in 8 slots', () => { + const count = (t: string) => ZYLON_SHAPE_TABLE.filter((x) => x === t).length; + expect(ZYLON_SHAPE_TABLE).toHaveLength(8); + expect([count('fighter'), count('cruiser'), count('basestar')]).toEqual([4, 3, 1]); + }); + + it('spawned ships follow the mix on every level', () => { + for (const level of ['NOVICE', 'PILOT', 'WARRIOR', 'COMMANDER'] as const) { + const sim = new ZylonSim(createRng(7)); + const seen = { fighter: 0, cruiser: 0, basestar: 0 }; + for (let i = 0; i < 4000; i++) { + sim.clear(); + for (const e of run(sim, 4, { level, sectorZylons: 1 })) if (e.type === 'zylonSpawned') seen[e.zylon]++; + } + const total = seen.fighter + seen.cruiser + seen.basestar; + expect(total).toBe(4000); + expect(seen.fighter / total).toBeCloseTo(4 / 8, 1); + expect(seen.cruiser / total).toBeCloseTo(3 / 8, 1); + expect(seen.basestar / total).toBeCloseTo(1 / 8, 1); + } + }); +}); + +// §17.8: at most two ships and one torpedo; new ones replace the dead while the count allows. +describe('ships and torpedo limits', () => { + it('never more than 2 ships in play, and never more than the sector holds', () => { + for (const count of [1, 2, 4]) { + const sim = new ZylonSim(createRng(count)); + for (let i = 0; i < 3000; i++) { + sim.loop(input({ count256: i & 0xff, sectorZylons: count, velocity: 32 })); + expect(sim.liveShips).toBeLessThanOrEqual(Math.min(MAX_ZYLON_SHIPS, count)); + } + expect(sim.liveShips).toBe(Math.min(MAX_ZYLON_SHIPS, count)); + } + }); + + it('spawns at least 28928 KM ahead', () => { + const sim = new ZylonSim(createRng(3)); + run(sim, 8, { sectorZylons: 2 }); + for (const s of sim.ships) expect(s.z).toBeGreaterThanOrEqual(28928 - 2 * 62); + }); + + it('a new torpedo only once the old one has gone (one PLAYER2)', () => { + const sim = new ZylonSim(createRng(11)); + sim.spawn('fighter', { x: 0, y: 0, z: 4000 }, false); + const fired = run(sim, 400, { sectorZylons: 1 }).filter((e) => e.type === 'zylonFired'); + expect(fired.length).toBeGreaterThan(1); + // A launch never replaces a torpedo still in flight. + const sim2 = new ZylonSim(createRng(11)); + sim2.spawn('fighter', { x: 0, y: 0, z: 4000 }, false); + for (let i = 0; i < 400; i++) { + const flying = sim2.torpedoFlying; + const ev = sim2.loop(input({ count256: i & 0xff, sectorZylons: 1 })); + if (ev.some((e) => e.type === 'zylonFired')) expect(flying, `loop ${i}`).toBe(false); + } + }); + + it('no Zylons, torpedoes or meteors in a starbase sector or during hyperwarp', () => { + for (const over of [{ starbaseSector: true }, { hyperwarp: true }]) { + const sim = new ZylonSim(createRng(5)); + const ev = run(sim, 2000, { sectorZylons: 3, ...over }); + expect(ev).toHaveLength(0); + expect(sim.liveShips).toBe(0); + } + }); +}); + +// §17.7: Zylon torpedo rules. +describe('Zylon torpedo', () => { + it('fires only near our plane and within 8192 KM; never from behind at NOVICE', () => { + const fires = (level: 'NOVICE' | 'PILOT', pos: { x: number; y: number; z: number }) => { + const sim = new ZylonSim(createRng(1)); + sim.spawn('fighter', pos, false); + sim.ships[0].milestoneTimer = 10_000; // hold its course + return run(sim, 9, { level, sectorZylons: 1 }).some((e) => e.type === 'zylonFired'); + }; + expect(fires('NOVICE', { x: 0, y: 0, z: 6000 })).toBe(true); + expect(fires('NOVICE', { x: 0, y: 0, z: 9000 })).toBe(false); // too far + expect(fires('NOVICE', { x: 0, y: 2000, z: 6000 })).toBe(false); // above our plane + expect(fires('NOVICE', { x: 0, y: 0, z: -3000 })).toBe(false); // behind, NOVICE + expect(fires('PILOT', { x: 0, y: 0, z: -3000 })).toBe(true); // behind, PILOT + }); + + it('homes toward our axis at 1 / 4 / 8 / 20 KM per loop by level', () => { + for (const [level, h] of [['NOVICE', 1], ['PILOT', 4], ['WARRIOR', 8], ['COMMANDER', 20]] as const) { + const sim = new ZylonSim(createRng(1)); + Object.assign(sim.pl2, { kind: 'torpedo', life: 62, x: 3000, y: -3000, z: 5000, vel: { x: 0, y: 0, z: -80 } }); + sim.loop(input({ level, count256: 1 })); + expect(sim.pl2.vel).toEqual({ x: -h, y: h, z: -80 }); + } + }); + + it('lives 62 loops', () => { + const sim = new ZylonSim(createRng(1)); + sim.spawn('fighter', { x: 0, y: 0, z: 6000 }, false); + sim.ships[0].milestoneTimer = 10_000; + let i = 0; + while (!sim.loop(input({ count256: i & 0xff, sectorZylons: 1 })).some((e) => e.type === 'zylonFired')) i++; + expect(sim.pl2.kind).toBe('torpedo'); + expect(sim.pl2.life).toBe(ZYLON_TORPEDO_LIFE - 1); + run(sim, ZYLON_TORPEDO_LIFE - 2, {}, i + 1); + expect(sim.pl2.life).toBe(1); + run(sim, 1, {}, i + ZYLON_TORPEDO_LIFE); + expect(sim.pl2.life).toBe(0); + }); +}); + +// §17.7: photons alternate barrels, a barrel refires after 23 loops, life 255, 10 energy each. +describe('photon torpedoes', () => { + it('alternate left and right barrels', () => { + const sim = new ZylonSim(createRng(1)); + expect(sim.fire('FRONT', 'ok', false)).toBe(true); + expect(sim.photons[0].x).toBe(-256); + expect(sim.fire('FRONT', 'ok', false)).toBe(true); + expect(sim.photons[1].x).toBe(256); + expect(sim.photons.map((p) => p.y)).toEqual([-256, -256]); + }); + + it('a barrel refires only once its last torpedo is more than 23 loops old (life < 232)', () => { + const sim = new ZylonSim(createRng(1)); + expect(PHOTON_REFIRE_LOOPS).toBe(23); + sim.fire('FRONT', 'ok', false); // left + sim.fire('FRONT', 'ok', false); // right, at once + for (let loop = 1; loop <= 23; loop++) { + run(sim, 1); + expect(sim.fire('FRONT', 'ok', false), `loop ${loop}`).toBe(false); + } + run(sim, 1); + expect(sim.fire('FRONT', 'ok', false)).toBe(true); // left again after 23 loops + }); + + it('damaged photons fire one barrel every 23 loops; destroyed ones never', () => { + const sim = new ZylonSim(createRng(1)); + expect(sim.fire('FRONT', 'damaged', false)).toBe(true); + expect(sim.fire('FRONT', 'damaged', false)).toBe(false); + run(sim, 23); + expect(sim.fire('FRONT', 'damaged', false)).toBe(false); + run(sim, 1); + expect(sim.fire('FRONT', 'damaged', false)).toBe(true); + expect(sim.photons[1].life).toBe(0); // always the same barrel + const dead = new ZylonSim(createRng(1)); + expect(dead.fire('FRONT', 'destroyed', false)).toBe(false); + }); + + it('fly 102 KM per loop for 255 loops, aft photons fly backwards; cost 10', () => { + const sim = new ZylonSim(createRng(1)); + sim.fire('AFT', 'ok', false); + run(sim, 1, { velocity: 64 }); + expect(sim.photons[0].z).toBe(1 - 102); // not carried by our velocity + run(sim, 253); + expect(sim.photons[0].life).toBe(1); + run(sim, 1); + expect(sim.photons[0].life).toBe(0); + expect(COST.photon).toBe(10); + }); + + it('sparkle: each frame shows a random subset of the shape', async () => { + const { objectSprites } = await import('../render/Renderer'); + const rng = createRng(2); + const full = shapeRows(SHAPE.PHOTON, 1); + const frames = Array.from({ length: 4 }, () => objectSprites({ kind: 'photon', x: 0, y: 0, z: 2600 }, 'FRONT', 0, rng)[0].rows); + for (const rows of frames) rows.forEach((r, i) => expect(r & ~full[i]).toBe(0)); + expect(new Set(frames.map((f) => f.join())).size).toBeGreaterThan(1); + }); +}); + +// §17.7: hits, the basestar rule and explosions. +describe('photon hits', () => { + it('destroys a fighter in front, scoring through zylonDestroyed', () => { + const sim = new ZylonSim(createRng(1)); + sim.spawn('fighter', { x: 0, y: 0, z: 2000 }, false); + photonAt(sim, 0, 40, 1900); + const ev = sim.loop(input({ sectorZylons: 1 })); + expect(ev).toContainEqual(expect.objectContaining({ type: 'zylonDestroyed', zylon: 'fighter', slot: 0 })); + expect(sim.ships[0].alive).toBe(false); + expect(sim.photons[0].life).toBe(0); + }); + + it(`a basestar dies only to a torpedo younger than ${BASESTAR_MAX_TORPEDO_AGE} loops`, () => { + const hit = (age: number) => { + const sim = new ZylonSim(createRng(1)); + sim.spawn('basestar', { x: 0, y: 0, z: 1200 }, false); + sim.ships[0].milestoneTimer = 10_000; + photonAt(sim, 0, age, 1100); + const ev = sim.loop(input({ sectorZylons: 1 })); + return { ev, alive: sim.ships[0].alive, photon: sim.photons[0].life, explosion: sim.explosion !== null }; + }; + const young = hit(14); + expect(young.alive).toBe(false); + expect(young.ev).toContainEqual(expect.objectContaining({ type: 'zylonDestroyed', zylon: 'basestar' })); + const old = hit(15); + expect(old.alive).toBe(true); + expect(old.ev).toContainEqual(expect.objectContaining({ type: 'basestarHit' })); + expect(old.ev.some((e) => e.type === 'zylonDestroyed')).toBe(false); + expect(old.photon).toBe(0); // the torpedo is spent + expect(old.explosion).toBe(true); // and bursts on the hull + }); + + it('misses outside the depth window (HITMINZTAB/HITMAXZTAB)', () => { + const sim = new ZylonSim(createRng(1)); + sim.spawn('fighter', { x: 0, y: 0, z: 6000 }, false); + photonAt(sim, 0, 5, 300); // overlaps on screen, but far nearer than the ship + expect(sim.loop(input({ sectorZylons: 1 })).some((e) => e.type === 'zylonDestroyed')).toBe(false); + }); + + it('explosions are 32 fragments, −7..+7 KM per loop, for 128 loops', () => { + const sim = new ZylonSim(createRng(1)); + sim.spawn('cruiser', { x: 0, y: 0, z: 2000 }, false); + photonAt(sim, 0, 40, 1900); + sim.loop(input({ sectorZylons: 1 })); + expect(sim.explosion!.fragments).toHaveLength(EXPLOSION_FRAGMENTS); + for (const f of sim.explosion!.fragments) for (const v of [f.vel.x, f.vel.y, f.vel.z]) expect(Math.abs(v)).toBeLessThanOrEqual(7); + expect(sim.explosion!.life).toBe(EXPLOSION_LIFE - 1); + run(sim, EXPLOSION_LIFE - 1); + expect(sim.explosion).toBeNull(); + }); +}); + +// §5.9, §17.7: shields up −100 per hit; down = destroyed. +describe('being hit', () => { + const damage = (): DamageStatus => allSystemsOk(); + const byte = (v: number) => () => v; + + it('shields down: a Zylon torpedo destroys the ship', () => { + const r = resolveShipHit({ shieldsUp: false, level: 'NOVICE', damage: damage(), by: 'torpedo', torpedoLife: 20, randomByte: byte(0) }); + expect(r.destroyed).toBe(true); + }); + + it('shields up: costs 100 energy, the ship survives', () => { + const r = resolveShipHit({ shieldsUp: true, level: 'COMMANDER', damage: damage(), by: 'torpedo', torpedoLife: 20, randomByte: byte(0) }); + expect(r).toMatchObject({ destroyed: false, energy: 100 }); + expect(r.damage?.status).toBe('damaged'); // fired from far: damaged, not destroyed + }); + + it('a torpedo that reaches our ship raises shipHit and is used up', () => { + const sim = new ZylonSim(createRng(1)); + Object.assign(sim.pl2, { kind: 'torpedo', life: 30, x: 0, y: 0, z: 200, vel: { x: 0, y: 0, z: -80 } }); + const ev = sim.loop(input({ count256: 1 })); + expect(ev).toContainEqual({ type: 'shipHit', by: 'torpedo', torpedoLife: 30 }); + expect(sim.pl2.life).toBe(0); + expect(sim.explosion).not.toBeNull(); + }); +}); + +// §16, §17.7: meteors. +describe('meteors', () => { + it('about 4 in 256 tries while PLAYER2 is free; with Zylons about, never on their steering loop', () => { + const rate = (sectorZylons: number) => { + const sim = new ZylonSim(createRng(9)); + let spawned = 0; + let tries = 0; + for (let i = 0; i < 40000; i++) { + sim.pl2.life = 0; // keep the slot free + if (sectorZylons) for (const s of sim.ships) s.alive = true; + const ev = sim.loop(input({ count256: i & 0xff, sectorZylons })); + if (ev.some((e) => e.type === 'meteorSpawned')) { + spawned++; + if (sectorZylons) expect(i & 3).not.toBe(0); // the fourth loop steers a ship instead + } + if (!sectorZylons || (i & 3) !== 0) tries++; + } + return spawned / tries; + }; + for (const r of [rate(0), rate(2)]) { + expect(r).toBeGreaterThan(2 / 256); + expect(r).toBeLessThan(6 / 256); + } + }); + + it('start 3840 KM ahead and fly straight at us at −8 KM per loop plus our speed', () => { + const sim = new ZylonSim(createRng(9)); + let i = 0; + while (!sim.loop(input({ count256: i & 0xff })).some((e) => e.type === 'meteorSpawned')) i++; + const m = sim.pl2; + expect(m.kind).toBe('meteor'); + expect(m.z).toBe(0x0f00); + expect(Math.abs(m.x) % 256).toBe(0); + const z = m.z; + sim.loop(input({ count256: 1, velocity: 32 })); + expect(m.z).toBe(z - METEOR_SPEED - 32); + }); + + it('a photon destroys a meteor (no score)', () => { + const sim = new ZylonSim(createRng(1)); + Object.assign(sim.pl2, { kind: 'meteor', life: 60, x: 0, y: 0, z: 2000, vel: { x: 0, y: 0, z: -8 } }); + photonAt(sim, 0, 30, 1900); + const ev = sim.loop(input({ count256: 1 })); + expect(ev).toContainEqual({ type: 'shotDown', kind: 'meteor' }); + expect(ev.some((e) => e.type === 'zylonDestroyed')).toBe(false); + expect(sim.pl2.life).toBe(0); + }); + + it('a meteor hit destroys the ship with shields down', () => { + const sim = new ZylonSim(createRng(1)); + Object.assign(sim.pl2, { kind: 'meteor', life: 60, x: 0, y: 0, z: 100, vel: { x: 0, y: 0, z: -8 } }); + const ev = sim.loop(input({ count256: 1 })); + expect(ev).toContainEqual({ type: 'shipHit', by: 'meteor', torpedoLife: 60 }); + const r = resolveShipHit({ shieldsUp: false, level: 'NOVICE', damage: allSystemsOk(), by: 'meteor', torpedoLife: 60, randomByte: () => 0 }); + expect(r.destroyed).toBe(true); + }); + + it('with shields up a meteor cannot damage at NOVICE, and always destroys a subsystem otherwise', () => { + const novice = resolveShipHit({ shieldsUp: true, level: 'NOVICE', damage: allSystemsOk(), by: 'meteor', torpedoLife: 60, randomByte: () => 0 }); + expect(novice).toMatchObject({ destroyed: false, damage: null, energy: 100 }); + const pilot = resolveShipHit({ shieldsUp: true, level: 'PILOT', damage: allSystemsOk(), by: 'meteor', torpedoLife: 60, randomByte: () => 1 }); + expect(pilot.damage).toMatchObject({ system: 'engines', status: 'destroyed' }); + }); +}); + +// §17.8: back attacks on WARRIOR and COMMANDER only; ships swing with our turns. +describe('Zylon flight', () => { + it('back attacks happen only on WARRIOR and COMMANDER (about 19%)', () => { + for (const level of ['NOVICE', 'PILOT', 'WARRIOR', 'COMMANDER'] as const) { + const sim = new ZylonSim(createRng(21)); + let back = 0; + let rolls = 0; + for (let i = 0; i < 4000; i++) { + sim.clear(); + run(sim, 12, { level, sectorZylons: 1 }); // creation, then the first milestone roll + rolls++; + if (sim.ships.some((s) => s.alive && s.backAttack)) back++; + } + if (level === 'NOVICE' || level === 'PILOT') expect(back).toBe(0); + else expect(back / rolls).toBeCloseTo(48 / 256, 1); + } + }); + + it('in the attack pattern a close ship weaves toward the cross hairs and dives to 2560 KM', () => { + const sim = new ZylonSim(createRng(4)); + sim.spawn('fighter', { x: 3000, y: -3000, z: 5000 }, false); + run(sim, 8, { sectorZylons: 1 }); + expect(sim.ships[0].milestone).toEqual({ x: 15, y: 0, z: 15 }); // left, up, inbound + }); + + it('velocity indices follow the stick (the ROM adds JOYSTICKX in front, subtracts aft)', () => { + const sim = new ZylonSim(createRng(4)); + sim.spawn('fighter', { x: 0, y: 0, z: 20000 }, false); + const s = sim.ships[0]; + s.velIndex = { x: 7, y: 7, z: 7 }; + s.followTimer = { x: 0, y: 0 }; + sim.loop(input({ turn: { x: 1, y: 0 }, count256: 1, sectorZylons: 1 })); + expect(s.velIndex.x).toBe(8); + s.followTimer.x = 0; + sim.loop(input({ turn: { x: 1, y: 0 }, view: 'AFT', count256: 1, sectorZylons: 1 })); + expect(s.velIndex.x).toBe(7); + }); +}); diff --git a/src/sim/zylons.ts b/src/sim/zylons.ts new file mode 100644 index 0000000..791eb0f --- /dev/null +++ b/src/sim/zylons.ts @@ -0,0 +1,676 @@ +/** + * Zylon ships, Zylon torpedoes, meteors, our photon torpedoes and explosions: the ROM's five + * PLAYER space objects and the 32 explosion fragments, simulated one game loop at a time. + * + * MANUAL_SPEC §16 (meteors), §17.7 (combat), §17.8 (Zylon behaviour), §17.13 and §18.3 (sprites). + * ROM routines (Lorenz Wiest's disassembly, line numbers in StarRaiders.source.asm.txt): + * GAMELOOP steps 8–11, 21, 26–27 (L3371–3970), MANEUVER (L5524), INITEXPL (L5909), + * TRIGGER (L6495), COLLISION (L6954), INITPOSVEC (L9595), FLUSHGAMELOOP (L8828–8846) and the + * tables ZYLONSHAPTAB, ZYLONFLPATTAB, ZYLONVELTAB, ZYLONHOMVELTAB, HITMINZTAB, HITMAXZTAB. + * + * Space is the ship frame in KM: our starship sits at the origin facing +z. PLAYER slots: + * ships[0], ships[1] Zylon ships 0 and 1 (PLAYER0..1) + * pl2 the single Zylon photon torpedo, or a meteor (PLAYER2) + * photons[0], [1] our left and right barrel's photon torpedoes (PLAYER3..4) + * + * The ROM stores a coordinate as a sign bit plus 16 bits; the high byte of that 16-bit value is + * what most rules compare, so `hiByte()` reproduces it (−1 KM has high byte $FF). + */ +import { levelIndex, ZYLON_TORPEDO_HOMING, zylonsFireFromBehind, type MissionLevel } from '../rules/levels'; +import { rollDamage, type DamageResult, type DamageStatus, type SubsystemStatus } from '../rules/damage'; +import { placeSprite, SHAPE, spritesOverlap, viewDistanceHi, type ShapeType, type SpritePlacement } from '../render/sprites'; +import type { SpaceView } from '../render/projection'; +import { rotatePitch, rotateYaw, type Stick } from './motion'; + +// --------------------------------------------------------------------------------------------- +// ROM tables and constants +// --------------------------------------------------------------------------------------------- + +/** §17.8: at most two Zylon ships at a time (PLAYER0..1). */ +export const MAX_ZYLON_SHIPS = 2; + +export type ZylonType = 'fighter' | 'cruiser' | 'basestar'; + +/** R: ZYLONSHAPTAB, picked with RANDOM & 7: fighter 4/8, cruiser 3/8, basestar 1/8 (§17.8). */ +export const ZYLON_SHAPE_TABLE: readonly ZylonType[] = [ + 'basestar', + 'fighter', + 'fighter', + 'fighter', + 'cruiser', + 'cruiser', + 'cruiser', + 'fighter', +]; + +/** R: ZYLONFLPATTAB, same index as the shape: the starting flight pattern (0 at NOVICE). */ +export const ZYLON_FLIGHT_PATTERN_TABLE: readonly number[] = [4, 4, 0, 0, 0, 1, 0, 0]; + +/** R: ZYLONVELTAB — velocity (KM/loop) per Zylon velocity index 0..15. */ +export const ZYLON_VELOCITY_TABLE: readonly number[] = [62, 30, 16, 8, 4, 2, 1, 0, 0, -1, -2, -4, -8, -16, -30, -62]; + +export const ZYLON_SHAPE: Readonly> = { + fighter: SHAPE.FIGHTER, + cruiser: SHAPE.CRUISER, + basestar: SHAPE.BASESTAR, +}; + +/** Spawn: z high byte ORed with $71, i.e. at least 28928 KM ahead; x = y + 19 high bytes. */ +export const ZYLON_SPAWN_Z_HI = 0x71; +export const ZYLON_SPAWN_X_HI = 19; +/** Within 8192 KM ($20**) a visible Zylon switches to the attack flight pattern, and may fire. */ +export const ZYLON_ATTACK_HI = 0x20; +/** Attack from the front: dive in to 2560 KM ($0A**), then pull out. */ +export const ZYLON_DIVE_HI = 0x0a; +/** Attack from behind: turn at −2816 KM ($F5**). */ +export const ZYLON_BACK_DIVE_HI = 0xf5; +/** Milestone timer: new milestone velocities every 120 controls (each ship is controlled every 8 loops). */ +export const MILESTONE_CONTROLS = 120; +/** §17.8: WARRIOR and COMMANDER: 48/256 (19%) chance of a back attack per milestone. */ +export const BACK_ATTACK_CHANCE_256 = 48; + +/** §17.7 Zylon torpedo: life 62 loops, speed 80 KM/loop. */ +export const ZYLON_TORPEDO_LIFE = 62; +export const ZYLON_TORPEDO_SPEED = 80; +/** Loops before the next Zylon torpedo after one hit us (R: TORPEDODELAY := 2). */ +export const ZYLON_TORPEDO_DELAY_AFTER_HIT = 2; + +/** §17.7 our photons: life 255 loops, 102 KM/loop, launched ±256 KM sideways and 256 KM below. */ +export const PHOTON_LIFE = 255; +export const PHOTON_SPEED = 102; +export const PHOTON_BARREL_X = 256; +export const PHOTON_BARREL_Y = -256; +/** R: TRIGGER refuses a launch while the barrel's last torpedo has ≥ 232 loops left: 23 loops. */ +export const PHOTON_REFIRE_LIFE = 232; +export const PHOTON_REFIRE_LOOPS = PHOTON_LIFE - PHOTON_REFIRE_LIFE; +/** §17.7: only a photon younger than 15 loops destroys a basestar. */ +export const BASESTAR_MAX_TORPEDO_AGE = 15; + +/** R: HITMINZTAB / HITMAXZTAB — the torpedo's |z| high byte must be in [min, max) for the target's range index / 2. */ +export const HIT_MIN_Z_HI: readonly number[] = [0x00, 0x00, 0x00, 0x02, 0x04, 0x06, 0x08, 0x0c]; +export const HIT_MAX_Z_HI: readonly number[] = [0x0c, 0x0c, 0x0c, 0x0c, 0x0e, 0x0e, 0x0e, 0x20]; + +/** §17.7 meteors: 4/256 on 3 of 4 loops, life 60, flying at −8 KM/loop. */ +export const METEOR_CHANCE_256 = 4; +export const METEOR_LIFE = 60; +export const METEOR_SPEED = 8; + +/** §17.7: an explosion is 32 fragments with velocities −7..+7 KM/loop for 128 loops. */ +export const EXPLOSION_FRAGMENTS = 32; +export const EXPLOSION_LIFE = 128; + +/** R step 26: we are hit when the torpedo or meteor is within −256..+255 KM on every axis. */ +export const SHIP_HIT_KM = 256; + +/** R: VICINITYMASKTAB, indexed by bits 3..1 of the hyperwarp arrival marker's PM row. */ +export const VICINITY_MASK_TABLE: readonly number[] = [0xff, 0xff, 0x3f, 0x0f, 0x3f, 0x7f, 0xff, 0xff]; + +// --------------------------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------------------------- + +export interface Vec3Like { + x: number; + y: number; + z: number; +} + +/** The view the ROM's SHIPVIEW holds; projection and collisions only exist in FRONT and AFT. */ +export type SimView = 'FRONT' | 'AFT' | 'CHART' | 'LRS'; + +export interface ZylonShip extends Vec3Like { + alive: boolean; + type: ZylonType; + /** Placed by the debug hook: not part of the sector's count. */ + debug: boolean; + vel: Vec3Like; + /** Zylon velocity indices 0..15 into ZYLON_VELOCITY_TABLE (kept by the slot, as in the ROM). */ + velIndex: Vec3Like; + /** Milestone velocity indices the velocity indices step toward. */ + milestone: Vec3Like; + milestoneTimer: number; + /** 0 = attack, 1 = ±30 KM/loop, 4 = ±4 KM/loop. */ + flightPattern: number; + backAttack: boolean; + /** R: ZYLONTIMX0/ZYLONTIMY0 — loops until the velocity index follows the stick again. */ + followTimer: { x: number; y: number }; +} + +export interface Player2 extends Vec3Like { + /** What PLAYER2 is: the Zylon torpedo, a meteor, or nothing yet. */ + kind: 'torpedo' | 'meteor' | null; + life: number; + vel: Vec3Like; +} + +export interface Photon extends Vec3Like { + life: number; + vel: Vec3Like; +} + +export interface Fragment extends Vec3Like { + vel: Vec3Like; +} + +export interface Explosion { + life: number; + fragments: Fragment[]; +} + +export interface ZylonLoopInput { + /** Stick as the ship turns this loop (centred in the chart, hyperwarp or docking). */ + turn: Stick; + /** Our velocity in KM per loop. */ + velocity: number; + view: SimView; + level: MissionLevel; + /** Zylon ships the galaxy map holds for this sector (live ones included). */ + sectorZylons: number; + starbaseSector: boolean; + hyperwarp: boolean; + /** R: COUNT256, the loop counter (meteors are tried when bits 1..0 are not 0). */ + count256: number; + /** Attack computer on and not destroyed (the tracked target follows the attacker only then). */ + computer: boolean; +} + +export type ZylonEvent = + | { type: 'zylonDestroyed'; slot: number; zylon: ZylonType; debug: boolean; torpedoAge: number } + | { type: 'basestarHit'; slot: number; torpedoAge: number } + | { type: 'shotDown'; kind: 'torpedo' | 'meteor' } + | { type: 'zylonSpawned'; slot: number; zylon: ZylonType } + | { type: 'zylonFired'; slot: number } + | { type: 'meteorSpawned' } + | { type: 'shipHit'; by: 'torpedo' | 'meteor'; torpedoLife: number }; + +// --------------------------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------------------------- + +/** High byte of a ROM coordinate (sign + 16 bits): −1 → $FF, −65536 → $00. */ +export function hiByte(km: number): number { + return Math.floor(km / 256) & 0xff; +} + +/** R step 11: a PLAYER coordinate beyond ±65535 KM is pinned near the edge (low byte kept). */ +export function correctOverflow(km: number): number { + if (km > 0xffff) return 0xff00 + (Math.floor(km) & 0xff); + if (km < -0x10000) return -0x10000 + (Math.floor(km) & 0xff); + return km; +} + +const clampIndex = (i: number) => Math.max(0, Math.min(15, i)); + +function newShip(): ZylonShip { + return { + alive: false, + type: 'fighter', + debug: false, + x: 0, + y: 0, + z: 0, + vel: { x: 0, y: 0, z: 0 }, + velIndex: { x: 0, y: 0, z: 0 }, + milestone: { x: 0, y: 0, z: 0 }, + milestoneTimer: 0, + flightPattern: 0, + backAttack: false, + followTimer: { x: 0, y: 0 }, + }; +} + +function newPhoton(): Photon { + return { life: 0, x: 0, y: 0, z: 0, vel: { x: 0, y: 0, z: 0 } }; +} + +/** The sprite type of PLAYER2 (the Zylon torpedo is drawn as a photon torpedo, shape 0). */ +function pl2Shape(p: Player2): ShapeType { + return p.kind === 'meteor' ? SHAPE.METEOR : SHAPE.PHOTON; +} + +export interface ShipHitInput { + /** SHIELDSCOLOR is not black (shields on and, if damaged, flickered on). */ + shieldsUp: boolean; + level: MissionLevel; + damage: DamageStatus; + by: 'torpedo' | 'meteor'; + /** The Zylon torpedo's life left when it hit (meteors always destroy: 255). */ + torpedoLife: number; + randomByte: () => number; +} + +export interface ShipHitResult { + /** Shields down: SHIP DESTROYED BY ZYLON FIRE, mission over. */ + destroyed: boolean; + /** Energy taken (§17.1: 100 per hit). */ + energy: number; + /** The subsystem harmed, if any (§17.3). */ + damage: DamageResult | null; +} + +/** + * GAMELOOP steps 26–27: our starship was hit by the Zylon torpedo or a meteor (§5.9, §16, §17.7). + * Every hit rolls DAMAGE and costs 100 energy; with the shields down the ship is destroyed. + */ +export function resolveShipHit(h: ShipHitInput): ShipHitResult { + const life = h.by === 'meteor' ? 255 : h.torpedoLife; + const damage = rollDamage(h.level, h.damage, life, h.randomByte); + return { destroyed: !h.shieldsUp, energy: 100, damage }; +} + +// --------------------------------------------------------------------------------------------- +// The simulation +// --------------------------------------------------------------------------------------------- + +export class ZylonSim { + public readonly ships: ZylonShip[] = [newShip(), newShip()]; + public readonly pl2: Player2 = { kind: null, life: 0, x: 0, y: 0, z: 0, vel: { x: 0, y: 0, z: 0 } }; + public readonly photons: Photon[] = [newPhoton(), newPhoton()]; + public explosion: Explosion | null = null; + /** R: BARRELNR — barrel of the next launch: 0 left, 1 right. */ + public barrel = 0; + /** R: TORPEDODELAY. */ + public torpedoDelay = 0; + /** R: CTRLDZYLON — the ship the game steers this time (alternates every 4 loops). */ + public controlled = 0; + /** R: TRACKDIGIT — the Zylon the panel's θ Φ R follow (T:0 or T:1). */ + public trackDigit = 0; + /** R: ZYLONATTACKER — the ship that fired the current torpedo, until the computer picks it up. */ + private attacker: number | null = null; + /** R: VICINITYMASK — confines a new Zylon's y coordinate. */ + public vicinityMask = 0; + + /** Sprites drawn this loop (R step 15), for the hit tests and the attack-pattern switch. */ + private shown: { + ships: (SpritePlacement | null)[]; + pl2: SpritePlacement | null; + } = { ships: [null, null], pl2: null }; + + private readonly randomByte: () => number; + + /** `random` returns [0, 1) like core/rng's random(). */ + constructor(random: () => number) { + this.randomByte = () => Math.floor(random() * 256) & 0xff; + } + + // ----- queries ----- + + public get liveShips(): number { + return this.ships.filter((s) => s.alive).length; + } + + /** The Zylon torpedo is flying (for the panel's "under attack" state). */ + public get torpedoFlying(): boolean { + return this.pl2.kind === 'torpedo' && this.pl2.life > 0; + } + + /** The tracked Zylon ship (θ Φ R), or null. */ + public trackedShip(): ZylonShip | null { + const s = this.ships[this.trackDigit]; + return s.alive ? s : null; + } + + /** Sprite placement of an object in a view (R step 15), or null when it is not drawn. */ + public static place(type: ShapeType, p: Vec3Like, view: SimView): SpritePlacement | null { + if (view !== 'FRONT' && view !== 'AFT') return null; + return placeSprite(type, p.x, p.y, p.z, view as SpaceView); + } + + // ----- commands ----- + + /** Empty the sector (hyperwarp, teleport). */ + public clear(): void { + for (const s of this.ships) s.alive = false; + this.pl2.life = 0; + this.pl2.kind = null; + for (const p of this.photons) p.life = 0; + this.explosion = null; + this.attacker = null; + this.shown = { ships: [null, null], pl2: null }; + } + + /** M: toggle the tracked Zylon between T:0 and T:1 (R: KEYBOARD 'M'). */ + public toggleTarget(): void { + this.trackDigit ^= 1; + } + + /** Put a ship in play (debug hook): the first free slot, else slot 0. */ + public spawn(type: ZylonType, pos: Vec3Like, debug = true): number { + let slot = this.ships.findIndex((s) => !s.alive); + if (slot < 0) slot = 0; + const s = this.ships[slot]; + Object.assign(s, { alive: true, type, debug, x: pos.x, y: pos.y, z: pos.z }); + s.vel = { x: 0, y: 0, z: 0 }; + // A placed ship starts with no sideways speed and heads in at full speed (indices 7, 7, 15). + s.velIndex = { x: 7, y: 7, z: 15 }; + s.milestone = { x: 7, y: 7, z: 15 }; + s.milestoneTimer = 1; + s.flightPattern = 0; + return slot; + } + + /** Remove a live ship without a torpedo (debug: destroy the sector). Returns its explosion. */ + public destroyShip(slot: number): void { + const s = this.ships[slot]; + if (!s.alive) return; + s.alive = false; + this.initExplosion(s); + } + + /** + * TRIGGER: launch one photon torpedo (§17.7). Returns true when a torpedo left the barrel + * (the caller charges 10 energy and plays the launch sound). + * - The barrel about to fire must have its last torpedo at least 23 loops old. + * - Photons destroyed: no launch. Damaged: always the same barrel. OK: barrels alternate. + */ + public fire(view: SimView, photons: SubsystemStatus, hyperwarp: boolean): boolean { + if (hyperwarp) return false; + const b = this.barrel; + if (this.photons[b].life >= PHOTON_REFIRE_LIFE) return false; + if (photons === 'destroyed') return false; + if (photons === 'ok') this.barrel = b ^ 1; + const p = this.photons[b]; + p.life = PHOTON_LIFE; + p.x = b === 1 ? PHOTON_BARREL_X : -PHOTON_BARREL_X; + p.y = PHOTON_BARREL_Y; + p.z = 1; + p.vel = { x: 0, y: 0, z: view === 'AFT' ? -PHOTON_SPEED : PHOTON_SPEED }; + return true; + } + + // ----- the game loop ----- + + /** One game loop of every PLAYER object and the explosion. Returns what happened. */ + public loop(inp: ZylonLoopInput): ZylonEvent[] { + const events: ZylonEvent[] = []; + this.move(inp); + this.updateShown(inp.view); + this.collision(inp.view, events); + this.trackTarget(inp.computer); + if (!inp.starbaseSector && !inp.hyperwarp) this.maneuver(inp, events); + if (!inp.starbaseSector) this.shipHitCheck(events); + this.flush(); + return events; + } + + /** Steps 8–11: rotate with the stick, fly toward −z, add each object's own velocity. */ + private move(inp: ZylonLoopInput): void { + const step = (p: Vec3Like, vel: Vec3Like, flies: boolean, player: boolean) => { + rotateYaw(p, inp.turn.x); + rotatePitch(p, inp.turn.y); + if (flies) p.z -= inp.velocity; + p.x += vel.x; + p.y += vel.y; + p.z += vel.z; + if (player) { + p.x = correctOverflow(p.x); + p.y = correctOverflow(p.y); + p.z = correctOverflow(p.z); + } + }; + for (const s of this.ships) if (s.alive) step(s, s.vel, true, true); + // Photon torpedoes (ours and the Zylons') are not carried along by our velocity (R step 9). + if (this.pl2.life > 0) step(this.pl2, this.pl2.vel, this.pl2.kind === 'meteor', true); + for (const p of this.photons) if (p.life > 0) step(p, p.vel, false, true); + if (this.explosion) for (const f of this.explosion.fragments) step(f, f.vel, true, false); + } + + private updateShown(view: SimView): void { + this.shown.ships = this.ships.map((s) => (s.alive ? ZylonSim.place(ZYLON_SHAPE[s.type], s, view) : null)); + this.shown.pl2 = this.pl2.life > 0 ? ZylonSim.place(pl2Shape(this.pl2), this.pl2, view) : null; + } + + /** COLLISION: our photons against the Zylon ships, the Zylon torpedo and the meteor. */ + private collision(view: SimView, events: ZylonEvent[]): void { + if (view !== 'FRONT' && view !== 'AFT') return; + for (let i = 1; i >= 0; i--) { + const p = this.photons[i]; + if (p.life <= 0) continue; + const ps = ZylonSim.place(SHAPE.PHOTON, p, view); + if (!ps) continue; + // The collision register's priority: ship 1, then the torpedo/meteor, then ship 0. + const hit0 = !!this.shown.ships[0] && spritesOverlap(ps, this.shown.ships[0]!); + const hit1 = !!this.shown.ships[1] && spritesOverlap(ps, this.shown.ships[1]!); + const hit2 = !!this.shown.pl2 && spritesOverlap(ps, this.shown.pl2!); + const target = hit1 ? 1 : hit2 ? 2 : hit0 ? 0 : -1; + if (target < 0) continue; + const obj: Vec3Like = target === 2 ? this.pl2 : this.ships[target]; + if (target === 2 ? this.pl2.life <= 0 : !this.ships[target].alive) continue; + + // Depth window: the torpedo's |z| must suit the target's range (HITMINZTAB/HITMAXZTAB). + const idx = Math.min(15, viewDistanceHi(obj.z, view)) >> 1; + const tz = viewDistanceHi(p.z, view); + if (tz >= HIT_MAX_Z_HI[idx] || tz < HIT_MIN_Z_HI[idx]) continue; + + const age = PHOTON_LIFE - p.life; + p.life = 0; + if (target === 2) { + const kind = this.pl2.kind === 'meteor' ? 'meteor' : 'torpedo'; + this.pl2.life = 0; + events.push({ type: 'shotDown', kind }); + } else { + const ship = this.ships[target]; + if (ship.type === 'basestar' && age >= BASESTAR_MAX_TORPEDO_AGE) { + // Too far: the torpedo bursts on the basestar but it survives (R: SKIP142 carry set). + events.push({ type: 'basestarHit', slot: target, torpedoAge: age }); + } else { + ship.alive = false; + events.push({ type: 'zylonDestroyed', slot: target, zylon: ship.type, debug: ship.debug, torpedoAge: age }); + } + } + this.initExplosion(obj); + } + } + + /** GAMELOOP step 23: the tracked Zylon follows the attacker, or the other ship when it dies. */ + private trackTarget(computer: boolean): void { + if (!computer) return; + let x = this.trackDigit; + if (this.attacker !== null) { + x = this.attacker; + this.attacker = null; + } + if (!this.ships[x].alive && this.ships[x ^ 1].alive) x ^= 1; + else if (!this.ships[x].alive) x = this.trackDigit; + this.trackDigit = x; + } + + /** MANEUVER (R L5524). */ + private maneuver(inp: ZylonLoopInput, events: ZylonEvent[]): void { + // (2) Zylons swing with our turns: each x/y velocity index follows the stick when its timer + // runs out (reversed outside the Front view), then the timer restarts from the new index. + const inv = inp.view === 'FRONT' ? 1 : -1; + for (const s of this.ships) { + for (const axis of ['x', 'y'] as const) { + s.followTimer[axis]--; + if (s.followTimer[axis] >= 0) continue; + const idx = clampIndex(s.velIndex[axis] + inv * inp.turn[axis]); + s.velIndex[axis] = idx; + s.followTimer[axis] = (idx < 8 ? idx : idx ^ 0x0f) * 2; + } + } + + // (3) The Zylon torpedo homes toward our axis at the level's rate (§17.7). + if (this.pl2.kind === 'torpedo') { + const h = ZYLON_TORPEDO_HOMING[inp.level]; + this.pl2.vel.y = this.pl2.y >= 0 ? -h : h; + this.pl2.vel.x = this.pl2.x >= 0 ? -h : h; + } + + // (4) Three loops of four: try for a meteor. The fourth: steer a Zylon ship. + if ((inp.count256 & 3) !== 0) { + this.tryMeteor(inp.view, events); + return; + } + + // (5) Alternate the ship the game steers. + this.controlled ^= 1; + const slot = this.controlled; + const s = this.ships[slot]; + + // (6) A new ship replaces a dead one while the sector's count allows it. + if (!s.alive) { + if (this.liveShips >= inp.sectorZylons) { + this.tryMeteor(inp.view, events); + return; + } + this.createShip(slot, inp.level); + events.push({ type: 'zylonSpawned', slot, zylon: s.type }); + } + + // (7) Close (z < 8192 KM) and visible, or far behind: switch to the attack pattern. + if (hiByte(s.z) < ZYLON_ATTACK_HI && (s.z < 0 || this.shown.ships[slot] !== null)) s.flightPattern = 0; + + // (8) Every 120 controls: re-roll the back attack and pick new milestone velocities. + s.milestoneTimer--; + if (s.milestoneTimer < 0) { + s.milestoneTimer = MILESTONE_CONTROLS; + const level = levelIndex(inp.level); + s.backAttack = ((this.randomByte() < BACK_ATTACK_CHANCE_256 ? level >> 1 : level >> 2) & 1) === 1; + let a = s.flightPattern; + for (const axis of ['z', 'x', 'y'] as const) { + if (this.randomByte() & 0x80) a ^= 0x0f; + s.milestone[axis] = a; + } + } + + // (9) Attack pattern: weave around our cross hairs and dive in and out. + if (s.flightPattern === 0) { + const zh = hiByte(s.z); + if (s.backAttack) s.milestone.z = zh >= ZYLON_BACK_DIVE_HI ? 15 : 0; + else s.milestone.z = zh < ZYLON_DIVE_HI ? 0 : 15; + s.milestone.x = s.x >= 0 ? 15 : 0; + s.milestone.y = s.y >= 0 ? 15 : 0; + } + + // (10) Velocity indices step one toward the milestones; the velocity is taken from the + // index before the step (R: the table is read with the index loaded before INC/DEC). + for (const axis of ['z', 'x', 'y'] as const) { + const before = s.velIndex[axis]; + if (before < s.milestone[axis]) s.velIndex[axis] = before + 1; + else if (before > s.milestone[axis]) s.velIndex[axis] = before - 1; + s.vel[axis] = ZYLON_VELOCITY_TABLE[before]; + } + + // (11) Launch the Zylon torpedo? + this.tryLaunch(slot, inp.level, events); + } + + /** (6) Create a Zylon ship: type 4/8 fighter, 3/8 cruiser, 1/8 basestar, ≥ 28928 KM ahead. */ + private createShip(slot: number, level: MissionLevel): void { + const s = this.ships[slot]; + const i = this.randomByte() & 7; + s.alive = true; + s.debug = false; + s.type = ZYLON_SHAPE_TABLE[i]; + s.flightPattern = level === 'NOVICE' ? 0 : ZYLON_FLIGHT_PATTERN_TABLE[i]; + s.milestoneTimer = 1; + const yHi = this.randomByte() & this.vicinityMask; + const xHi = (yHi + ZYLON_SPAWN_X_HI) & 0xff; + s.y = yHi * 256; + s.x = xHi * 256; + s.z = (xHi | ZYLON_SPAWN_Z_HI) * 256; + this.randomInvertXY(s); + } + + /** (11) Fire when PLAYER2 is free, the ship is near our horizontal plane and within 8192 KM. */ + private tryLaunch(slot: number, level: MissionLevel, events: ZylonEvent[]): void { + const s = this.ships[slot]; + const p = this.pl2; + if (p.kind === 'torpedo' || p.kind === null) { + if (p.life > 0) return; + if (this.torpedoDelay > 0) { + this.torpedoDelay--; + return; + } + } + // y high byte in $FE..$02 (R: ADC #2, CMP #5). + if (((hiByte(s.y) + 2) & 0xff) >= 5) return; + let zh = hiByte(s.z); + let vz = -ZYLON_TORPEDO_SPEED; + if (s.z < 0) { + zh ^= 0xff; + if (!zylonsFireFromBehind(level)) return; // never shot in the back at NOVICE + vz = ZYLON_TORPEDO_SPEED; + } + if (zh >= ZYLON_ATTACK_HI) return; + p.kind = 'torpedo'; + p.life = ZYLON_TORPEDO_LIFE; + p.x = s.x; + p.y = s.y; + p.z = s.z; + p.vel = { x: 0, y: 0, z: vz }; + this.attacker = slot; + events.push({ type: 'zylonFired', slot }); + } + + /** (4) A meteor in 4 of 256 tries, when PLAYER2 is dead or not on screen. */ + private tryMeteor(view: SimView, events: ZylonEvent[]): void { + const p = this.pl2; + if (p.life > 0 && this.shown.pl2 !== null) return; + if (this.randomByte() >= METEOR_CHANCE_256) return; + p.kind = 'meteor'; + this.initPosVec(p, view); + p.life = METEOR_LIFE; + p.vel = { x: 0, y: 0, z: -METEOR_SPEED }; + events.push({ type: 'meteorSpawned' }); + } + + /** INITPOSVEC: a random position at the far end of the view (R L9595). */ + private initPosVec(p: Vec3Like, view: SimView): void { + const rndY = this.randomByte() & 0x0f; + const rndX = this.randomByte() & 0x0f; + p.y = rndY * 256; + p.x = rndX * 256; + p.z = 0x0f00; + if (view === 'AFT') { + // z high byte := −MAX(RNDY, RNDX), low byte $80, sign negative. + const hi = (0 - Math.max(rndX, rndY)) & 0xff; + p.z = hi * 256 + 0x80 - 0x10000; + } + if (view === 'LRS') { + p.x = this.randomByte() * 256; + const zHi = this.randomByte(); + p.z = zHi & 1 ? zHi * 256 : zHi * 256 - 0x10000; + } + this.randomInvertXY(p); + } + + /** RNDINVXY: random signs for y and x. */ + private randomInvertXY(p: Vec3Like): void { + if (!(this.randomByte() & 1)) p.y = -p.y; + if (!(this.randomByte() & 1)) p.x = -p.x; + } + + /** Steps 26–27: the Zylon torpedo or a meteor reached us. */ + private shipHitCheck(events: ZylonEvent[]): void { + const p = this.pl2; + if (p.life <= 0) return; + const near = (v: number) => v >= -SHIP_HIT_KM && v < SHIP_HIT_KM; + if (!near(p.x) || !near(p.y) || !near(p.z)) return; + events.push({ type: 'shipHit', by: p.kind === 'meteor' ? 'meteor' : 'torpedo', torpedoLife: p.life }); + this.initExplosion(p); + p.life = 0; + this.torpedoDelay = ZYLON_TORPEDO_DELAY_AFTER_HIT; + } + + /** INITEXPL: 32 fragments from the object's position, random velocities −7..+7 (R L5909). */ + private initExplosion(at: Vec3Like): void { + const v = () => { + const r = this.randomByte() & 0x87; // NEG!7: sign bit and 0..7 + return r & 0x80 ? -(r & 7) : r & 7; + }; + const fragments: Fragment[] = []; + for (let i = 0; i < EXPLOSION_FRAGMENTS; i++) { + fragments.push({ x: at.x, y: at.y, z: at.z, vel: { z: v(), x: v(), y: v() } }); + } + this.explosion = { life: EXPLOSION_LIFE, fragments }; + } + + /** FLUSHGAMELOOP: torpedo lifetimes and the explosion count down every loop. */ + private flush(): void { + for (const p of this.photons) if (p.life > 0) p.life--; + if (this.pl2.kind === 'torpedo' && this.pl2.life > 0) this.pl2.life--; + if (this.explosion && --this.explosion.life <= 0) this.explosion = null; + } +} diff --git a/src/systems/CombatSystem.ts b/src/systems/CombatSystem.ts deleted file mode 100644 index e4d3119..0000000 --- a/src/systems/CombatSystem.ts +++ /dev/null @@ -1,279 +0,0 @@ -import { Vec3 } from '../core/vec3'; -import { Enemy, EnemyType } from '../entities/Enemy'; -import { PhotonTorpedo } from '../entities/PhotonTorpedo'; -import { GameState, DifficultyLevel } from '../game/GameState'; -import { random } from '../core/rng'; - -/** - * CombatSystem - Manages enemies, combat, and targeting - */ -export class CombatSystem { - private gameState: GameState; - - // Enemies in current sector - private enemies: Enemy[] = []; - - // Targeting - private currentTargetIndex: number = -1; - - constructor(gameState: GameState) { - this.gameState = gameState; - } - - /** - * Spawn the Zylons of the current sector. `count` comes from the galaxy map - * (sim/galaxy.ts), the one source of Zylon counts. - */ - public spawnEnemiesForSector(count: number): void { - // Clear existing enemies - this.clearEnemies(); - this.spawnMore(count); - } - - /** - * Add `count` more Zylons around the player (e.g. the 2 made from a starbase destroyed - * in this sector, §8.2) without touching the ones already here. - */ - public spawnMore(count: number): void { - if (count <= 0) return; - const enemyCount = count; - - for (let i = 0; i < enemyCount; i++) { - // Determine type based on difficulty and random chance - let type: EnemyType; - const roll = random(); - - switch (this.gameState.difficulty) { - case DifficultyLevel.NOVICE: - type = EnemyType.FIGHTER; - break; - case DifficultyLevel.PILOT: - type = roll < 0.8 ? EnemyType.FIGHTER : EnemyType.CRUISER; - break; - case DifficultyLevel.WARRIOR: - if (roll < 0.6) type = EnemyType.FIGHTER; - else if (roll < 0.9) type = EnemyType.CRUISER; - else type = EnemyType.BASESTAR; - break; - case DifficultyLevel.COMMANDER: - if (roll < 0.4) type = EnemyType.FIGHTER; - else if (roll < 0.7) type = EnemyType.CRUISER; - else type = EnemyType.BASESTAR; - break; - default: - type = EnemyType.FIGHTER; - } - - // Random position around the player - const angle = random() * Math.PI * 2; - const distance = 50 + random() * 150; - const height = (random() - 0.5) * 50; - - const position = new Vec3( - Math.cos(angle) * distance, - height, - Math.sin(angle) * distance - ); - - const enemy = new Enemy(type, position); - // Set difficulty for enemy AI scaling - enemy.setDifficulty(this.gameState.difficulty); - // Activate honing behavior to ensure enemies pursue player after hyperwarp - enemy.activateHoning(); - this.enemies.push(enemy); - } - - // Auto-select first target - if (this.enemies.length > 0 && this.currentTargetIndex < 0) { - this.currentTargetIndex = 0; - } - } - - /** - * Spawn one enemy at a given position (used by the ?debug=1 hook). - * Configured exactly like a sector spawn. - */ - public spawnEnemy(type: EnemyType, position: Vec3): Enemy { - const enemy = new Enemy(type, position); - enemy.setDifficulty(this.gameState.difficulty); - enemy.activateHoning(); - this.enemies.push(enemy); - if (this.currentTargetIndex < 0) { - this.currentTargetIndex = this.enemies.length - 1; - } - return enemy; - } - - /** - * Clear all enemies from scene - */ - public clearEnemies(): void { - for (const enemy of this.enemies) { - enemy.dispose(); - } - this.enemies = []; - this.currentTargetIndex = -1; - } - - /** - * Get current target - */ - public getCurrentTarget(): Enemy | null { - if (this.currentTargetIndex >= 0 && this.currentTargetIndex < this.enemies.length) { - const target = this.enemies[this.currentTargetIndex]; - if (target.isActive) { - return target; - } - } - // Find next active target (no recursive call to avoid stack overflow) - return this.selectNextTarget(); - } - - /** - * Select nearest enemy as target (T key) - */ - public selectNearestTarget(playerPosition: Vec3): Enemy | null { - let nearest: Enemy | null = null; - let nearestDistance = Infinity; - - for (let i = 0; i < this.enemies.length; i++) { - const enemy = this.enemies[i]; - if (!enemy.isActive) continue; - - const distance = playerPosition.distanceTo(enemy.getPosition()); - if (distance < nearestDistance) { - nearestDistance = distance; - nearest = enemy; - this.currentTargetIndex = i; - } - } - - return nearest; - } - - /** - * Cycle to next target (M key) - */ - public selectNextTarget(): Enemy | null { - if (this.enemies.length === 0) return null; - - // Find next active enemy - const startIndex = this.currentTargetIndex; - let index = (startIndex + 1) % this.enemies.length; - - while (index !== startIndex) { - if (this.enemies[index].isActive) { - this.currentTargetIndex = index; - return this.enemies[index]; - } - index = (index + 1) % this.enemies.length; - } - - // Check if start is still valid - if (this.enemies[startIndex]?.isActive) { - return this.enemies[startIndex]; - } - - this.currentTargetIndex = -1; - return null; - } - - /** - * Check torpedo collisions with enemies - */ - public checkTorpedoCollisions(torpedoes: PhotonTorpedo[]): Enemy[] { - const destroyed: Enemy[] = []; - - for (const torpedo of torpedoes) { - if (!torpedo.isActive) continue; - - for (const enemy of this.enemies) { - if (!enemy.isActive) continue; - - if (torpedo.checkCollision(enemy.getPosition(), enemy.getCollisionRadius())) { - // Hit! - torpedo.deactivate(); - - if (enemy.takeDamage(1)) { - // Enemy destroyed - // The caller removes it from the galaxy map and counts the kill. - destroyed.push(enemy); - } - - break; - } - } - } - - return destroyed; - } - - /** - * Update all enemies - */ - public update(deltaTime: number, playerPosition: Vec3): void { - for (const enemy of this.enemies) { - enemy.update(deltaTime, playerPosition); - } - - // Remove destroyed enemies from scene after animation - for (let i = this.enemies.length - 1; i >= 0; i--) { - const enemy = this.enemies[i]; - if (enemy.isDestroyed) { - enemy.dispose(); - this.enemies.splice(i, 1); - - // Update target index - if (this.currentTargetIndex >= i) { - this.currentTargetIndex = Math.max(0, this.currentTargetIndex - 1); - } - } - } - } - - /** - * Check if any enemy should fire - */ - public getEnemyFiring(currentTime: number, playerPosition: Vec3): Enemy | null { - for (const enemy of this.enemies) { - if (enemy.shouldFire(currentTime, playerPosition)) { - return enemy; - } - } - return null; - } - - /** - * Get active enemy count - */ - public getActiveEnemyCount(): number { - return this.enemies.filter((e) => e.isActive).length; - } - - /** - * Check for near misses that may provoke Cruisers - */ - public checkNearMisses(torpedoPosition: Vec3): void { - const NEAR_MISS_DISTANCE = 50; // Units within which a torpedo provokes - - for (const enemy of this.enemies) { - if (enemy.isActive) { - enemy.checkNearMiss(torpedoPosition, NEAR_MISS_DISTANCE); - } - } - } - - /** - * Get all enemies - */ - public getEnemies(): Enemy[] { - return this.enemies; - } - - /** - * Dispose of resources - */ - public dispose(): void { - this.clearEnemies(); - } -} diff --git a/src/views/LongRangeScan.ts b/src/views/LongRangeScan.ts index dc0608d..4b59102 100644 --- a/src/views/LongRangeScan.ts +++ b/src/views/LongRangeScan.ts @@ -1,6 +1,4 @@ import { GameState } from '../game/GameState'; -import { CombatSystem } from '../systems/CombatSystem'; -import { Starbase } from '../entities/Starbase'; import { random } from '../core/rng'; /** @@ -12,9 +10,8 @@ export class LongRangeScan { private scanElement: HTMLElement; private gameState: GameState; - // Real world data access - private combatSystem: CombatSystem; - private getStarbase: () => Starbase | null; + /** Ship-frame positions (KM) of the Zylons, meteor and starbase (Game.scanBlips). */ + private getBlips: () => Array<{ x: number; z: number; kind: 'enemy' | 'starbase' }>; private isVisible: boolean = false; private animationId: number | null = null; @@ -27,13 +24,11 @@ export class LongRangeScan { constructor( container: HTMLElement, gameState: GameState, - combatSystem: CombatSystem, - getStarbase: () => Starbase | null + getBlips: () => Array<{ x: number; z: number; kind: 'enemy' | 'starbase' }> ) { this.container = container; this.gameState = gameState; - this.combatSystem = combatSystem; - this.getStarbase = getStarbase; + this.getBlips = getBlips; this.scanElement = this.createScan(); this.container.appendChild(this.scanElement); @@ -379,8 +374,8 @@ export class LongRangeScan { if (layer) { layer.innerHTML = ''; // Clear - // Map scale: range +/- 500 units - const RANGE = 500; + // Map scale: ±40,000 KM (MANUAL_SPEC §10; Phase 9 redraws the scan). + const RANGE = 40000; // Shared Projection: Transform World Coords directly to Screen Coords (Heads-Up) const renderObj = (worldX: number, worldZ: number, _type: string, _extraStyle: string = '') => { @@ -405,7 +400,7 @@ export class LongRangeScan { // 1. Update Stars (already in DOM, just move them) const starElements = this.scanElement.querySelectorAll('.scan-star'); this.stars.forEach((star, index) => { - const result = renderObj(star.x, star.y, 'star'); + const result = renderObj(star.x * (RANGE / 500), star.y * (RANGE / 500), 'star'); // stars live in ±500 const el = starElements[index] as HTMLElement; if (el) { if (result.visible) { @@ -431,18 +426,7 @@ export class LongRangeScan { } }; - const enemies = this.combatSystem.getEnemies(); - for (const enemy of enemies) { - if (!enemy.isActive) continue; - const pos = enemy.getPosition(); - createBlip(pos.x, -pos.z, 'enemy'); - } - - const starbase = this.getStarbase(); - if (starbase) { - const pos = starbase.getObject().position; - createBlip(pos.x, -pos.z, 'starbase'); - } + for (const b of this.getBlips()) createBlip(b.x, -b.z, b.kind); } }