diff --git a/data/blockfighter.json b/data/blockfighter.json index b27f6f2..c6d38cd 100644 --- a/data/blockfighter.json +++ b/data/blockfighter.json @@ -1,44 +1,44 @@ { "levels": [ - { "level": 1, "opponentId": "ethel", "skill": 1, "speed": 1, "tagline": "A gentle warm-up over tea.", + { "level": 1, "personality": "balanced", "stage": "#ff9ecf", "opponentId": "ethel", "skill": 1, "speed": 1, "tagline": "A gentle warm-up over tea.", "dropPattern": ["RRRRRR", "GGGGGG", "BBBBBB", "YYYYYY"] }, - { "level": 2, "opponentId": "kona", "skill": 1, "speed": 1, "tagline": "Good puppy. Surprisingly good at gems.", + { "level": 2, "personality": "rusher", "stage": "#ffd166", "opponentId": "kona", "skill": 1, "speed": 1, "tagline": "Good puppy. Surprisingly good at gems.", "dropPattern": ["YYYYYY", "BBBBBB", "GGGGGG", "RRRRRR"] }, - { "level": 3, "opponentId": "bernie", "skill": 2, "speed": 1, "tagline": "All fun and games... until the gems drop.", + { "level": 3, "personality": "builder", "stage": "#5cf2a8", "opponentId": "bernie", "skill": 2, "speed": 1, "tagline": "All fun and games... until the gems drop.", "dropPattern": ["RRRGGG", "RRRGGG", "BBBYYY", "BBBYYY"] }, - { "level": 4, "opponentId": "brad", "skill": 2, "speed": 1, "tagline": "Less salmon, more smashing.", + { "level": 4, "personality": "rusher", "stage": "#4cc9f0", "opponentId": "brad", "skill": 2, "speed": 1, "tagline": "Less salmon, more smashing.", "dropPattern": ["GGGYYY", "GGGYYY", "RRRBBB", "RRRBBB"] }, - { "level": 5, "opponentId": "jerry", "skill": 3, "speed": 2, "tagline": "Y'all ready for a real scrap?", + { "level": 5, "personality": "balanced", "stage": "#ff7b54", "opponentId": "jerry", "skill": 3, "speed": 2, "tagline": "Y'all ready for a real scrap?", "dropPattern": ["RRGGBB", "RRGGBB", "YYRRGG", "YYRRGG"] }, - { "level": 6, "opponentId": "jeff", "skill": 3, "speed": 2, "tagline": "Plays slow. Wins fast. You've been warned.", + { "level": 6, "personality": "turtle", "stage": "#9b8cff", "opponentId": "jeff", "skill": 3, "speed": 2, "tagline": "Plays slow. Wins fast. You've been warned.", "dropPattern": ["BBYYRR", "BBYYRR", "GGBBYY", "GGBBYY"] }, - { "level": 7, "opponentId": "mario", "skill": 4, "speed": 2, "tagline": "Welcome to the maze of falling gems!", + { "level": 7, "personality": "chainer", "stage": "#ff4d6d", "opponentId": "mario", "skill": 4, "speed": 2, "tagline": "Welcome to the maze of falling gems!", "dropPattern": ["RRGGYY", "BBRRGG", "YYBBRR", "GGYYBB"] }, - { "level": 8, "opponentId": "juliet", "skill": 4, "speed": 2, "tagline": "A summer day, a storm of gems.", + { "level": 8, "personality": "builder", "stage": "#ffd166", "opponentId": "juliet", "skill": 4, "speed": 2, "tagline": "A summer day, a storm of gems.", "dropPattern": ["GGBBRR", "YYGGBB", "RRYYGG", "BBRRYY"] }, - { "level": 9, "opponentId": "michael", "skill": 5, "speed": 3, "tagline": "Easy vibes, heavy chains, mon.", + { "level": 9, "personality": "chainer", "stage": "#5cf2a8", "opponentId": "michael", "skill": 5, "speed": 3, "tagline": "Easy vibes, heavy chains, mon.", "dropPattern": ["RGGBBY", "YRGGBB", "BYRGGB", "BBYRGG"] }, - { "level": 10, "opponentId": "croc", "skill": 5, "speed": 3, "tagline": "The party's over when your board fills up.", + { "level": 10, "personality": "rusher", "stage": "#3ddc97", "opponentId": "croc", "skill": 5, "speed": 3, "tagline": "The party's over when your board fills up.", "dropPattern": ["GBYRGB", "BYRGBY", "YRGBYR", "RGBYRG"] }, - { "level": 11, "opponentId": "gerome", "skill": 6, "speed": 3, "tagline": "Extreme victory or nothing!", + { "level": 11, "personality": "rusher", "stage": "#ff7b54", "opponentId": "gerome", "skill": 6, "speed": 3, "tagline": "Extreme victory or nothing!", "dropPattern": ["RYRYRY", "GBGBGB", "YRYRYR", "BGBGBG"] }, - { "level": 12, "opponentId": "beth", "skill": 6, "speed": 3, "tagline": "These parts have rules, stranger.", + { "level": 12, "personality": "turtle", "stage": "#e0a15c", "opponentId": "beth", "skill": 6, "speed": 3, "tagline": "These parts have rules, stranger.", "dropPattern": ["BRBRBR", "YGYGYG", "RBRBRB", "GYGYGY"] }, - { "level": 13, "opponentId": "steve", "skill": 7, "speed": 4, "tagline": "Stupid Earth gems. Prepare to lose.", + { "level": 13, "personality": "builder", "stage": "#b56bff", "opponentId": "steve", "skill": 7, "speed": 4, "tagline": "Stupid Earth gems. Prepare to lose.", "dropPattern": ["RGBYRG", "BYRGBY", "GBYRGB", "YRGBYR"] }, - { "level": 14, "opponentId": "fireball", "skill": 7, "speed": 4, "tagline": "No x-ray eyes. Just flawless drops.", + { "level": 14, "personality": "rusher", "stage": "#ff5c3a", "opponentId": "fireball", "skill": 7, "speed": 4, "tagline": "No x-ray eyes. Just flawless drops.", "dropPattern": ["RRYYRR", "YYRRYY", "GGBBGG", "BBGGBB"] }, - { "level": 15, "opponentId": "natasha", "skill": 8, "speed": 4, "tagline": "Your secrets fall with your gems.", + { "level": 15, "personality": "chainer", "stage": "#ff3d81", "opponentId": "natasha", "skill": 8, "speed": 4, "tagline": "Your secrets fall with your gems.", "dropPattern": ["RGYBGR", "BYGRYB", "GRBYRG", "YBRGBY"] }, - { "level": 16, "opponentId": "victor", "skill": 8, "speed": 4, "tagline": "Every drop calculated. Centuries ago.", + { "level": 16, "personality": "turtle", "stage": "#8a5cff", "opponentId": "victor", "skill": 8, "speed": 4, "tagline": "Every drop calculated. Centuries ago.", "dropPattern": ["RGBYBG", "YBGRGB", "GYRBRY", "BRYGYR"] }, - { "level": 17, "opponentId": "balam", "skill": 9, "speed": 5, "tagline": "Mystical powers meet falling blocks.", + { "level": 17, "personality": "builder", "stage": "#00e5c0", "opponentId": "balam", "skill": 9, "speed": 5, "tagline": "Mystical powers meet falling blocks.", "dropPattern": ["GYBRYG", "RBYGBR", "YGRBGY", "BRGYRB"] }, - { "level": 18, "opponentId": "cybro", "skill": 9, "speed": 5, "tagline": "The future has already beaten you.", + { "level": 18, "personality": "chainer", "stage": "#33b6ff", "opponentId": "cybro", "skill": 9, "speed": 5, "tagline": "The future has already beaten you.", "dropPattern": ["RBGYRB", "GYRBGY", "BRYGBR", "YGBRYG"] }, - { "level": 19, "opponentId": "zanthor", "skill": 10, "speed": 5, "tagline": "Alacazam! Your board is doomed!", + { "level": 19, "personality": "balanced", "stage": "#c45cff", "opponentId": "zanthor", "skill": 10, "speed": 5, "tagline": "Alacazam! Your board is doomed!", "dropPattern": ["RYGBRY", "GBRYGB", "YRBGYR", "BGYRBG"] }, - { "level": 20, "opponentId": "blackwind", "skill": 10, "speed": 5, "tagline": "The final showdown on the high seas!", + { "level": 20, "personality": "chainer", "stage": "#2ee6ff", "opponentId": "blackwind", "skill": 10, "speed": 5, "tagline": "The final showdown on the high seas!", "dropPattern": ["RGBYRG", "YBRGYB", "GRYBGR", "BYGRBY"] } ] } diff --git a/src/data/assetManifest.js b/src/data/assetManifest.js index 306a174..8156631 100644 --- a/src/data/assetManifest.js +++ b/src/data/assetManifest.js @@ -486,6 +486,11 @@ export const MANIFEST = { // so its audio only downloads once Colorado Defense is actually entered. (scene) => musicFrom(scene, 'arcadedark-music'), ], + blockfighter: [ + // arcadedark soundtrack (see services/soundtrack.js) — lazy-loaded here + // so its audio only downloads once Block Fighter is actually entered. + (scene) => musicFrom(scene, 'arcadedark-music'), + ], tempest: [ // arcadedark soundtrack (see services/soundtrack.js) — lazy-loaded here // so its audio only downloads once Tempest is actually entered. diff --git a/src/games/blockfighter/BFArena.js b/src/games/blockfighter/BFArena.js new file mode 100644 index 0000000..70c3bdf --- /dev/null +++ b/src/games/blockfighter/BFArena.js @@ -0,0 +1,347 @@ +// Block Fighter — centre stage. Two original procedural "gem-golems" (floating +// crystal limbs around a glowing core) act out the fight: they jab on small +// attacks, throw combos on chains, fire beams on supers, stagger when garbage +// lands on their side, block when an attack is cancelled out, and drop on a KO. +// BFBackdrop is the scrolling synthwave sky + perspective grid. + +import { W, H, D, ARENA } from './BFLayout.js'; +import { HORIZON_Y, isWebGL } from './BFArt.js'; + +function hexStr(n) { return `#${(n >>> 0).toString(16).padStart(6, '0')}`; } +function mix(a, b, t) { + const ar = (a >> 16) & 255, ag = (a >> 8) & 255, ab = a & 255; + const br = (b >> 16) & 255, bg = (b >> 8) & 255, bb = b & 255; + return (Math.round(ar + (br - ar) * t) << 16) | (Math.round(ag + (bg - ag) * t) << 8) | Math.round(ab + (bb - ab) * t); +} + +function canvasTex(scene, key, w, h, draw) { + if (scene.textures.exists(key)) return key; + const tex = scene.textures.createCanvas(key, w, h); + draw(tex.getContext(), w, h); + tex.refresh(); + return key; +} + +function poly(ctx, pts) { + ctx.beginPath(); + pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); + ctx.closePath(); +} + +// Builds the part textures for one golem color + head style. Returns keys. +function golemTextures(scene, color, style) { + const neon = hexStr(color); + const light = hexStr(mix(color, 0xffffff, 0.55)); + const dark = hexStr(mix(color, 0x05010f, 0.82)); + const body = hexStr(mix(color, 0x140628, 0.88)); + const k = `bf-golem-${color.toString(16)}-${style}`; + + const shade = (ctx, pts, x0, y0, x1, y1) => { + poly(ctx, pts); + const g = ctx.createLinearGradient(x0, y0, x1, y1); + g.addColorStop(0, hexStr(mix(color, 0x2a1050, 0.7))); + g.addColorStop(1, body); + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = 3; + ctx.strokeStyle = neon; + ctx.stroke(); + }; + + const torso = canvasTex(scene, `${k}-torso`, 120, 130, (ctx) => { + shade(ctx, [[20, 10], [100, 10], [114, 52], [92, 122], [28, 122], [6, 52]], 0, 0, 120, 130); + // facet lines + ctx.strokeStyle = 'rgba(255,255,255,0.18)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(20, 10); ctx.lineTo(60, 64); ctx.lineTo(100, 10); ctx.moveTo(6, 52); ctx.lineTo(60, 64); ctx.lineTo(114, 52); + ctx.moveTo(60, 64); ctx.lineTo(60, 122); ctx.stroke(); + // core + const g = ctx.createRadialGradient(60, 60, 0, 60, 60, 22); + g.addColorStop(0, '#ffffff'); g.addColorStop(0.35, light); g.addColorStop(0.8, neon); g.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(60, 60, 22, 0, Math.PI * 2); ctx.fill(); + poly(ctx, [[60, 46], [72, 60], [60, 74], [48, 60]]); + ctx.fillStyle = 'rgba(255,255,255,0.85)'; ctx.fill(); + }); + + const head = canvasTex(scene, `${k}-head`, 90, 90, (ctx) => { + let pts; + if (style === 1) pts = [[20, 18], [70, 18], [82, 46], [70, 80], [20, 80], [8, 46]]; + else if (style === 2) pts = [[45, 2], [62, 22], [80, 14], [78, 50], [64, 82], [26, 82], [12, 50], [10, 14], [28, 22]]; + else if (style === 3) pts = [[14, 30], [26, 8], [36, 24], [46, 4], [56, 24], [66, 8], [76, 30], [80, 60], [62, 84], [28, 84], [10, 60]]; + else pts = [[45, 6], [80, 36], [70, 80], [20, 80], [10, 36]]; + shade(ctx, pts, 0, 0, 90, 90); + // visor + const vg = ctx.createLinearGradient(0, 40, 0, 58); + vg.addColorStop(0, '#ffffff'); vg.addColorStop(1, neon); + ctx.fillStyle = vg; + poly(ctx, [[30, 44], [84, 40], [80, 56], [32, 58]]); + ctx.fill(); + ctx.fillStyle = '#ffffff'; + ctx.fillRect(62, 45, 12, 6); + }); + + const fist = canvasTex(scene, `${k}-fist`, 52, 52, (ctx) => { + shade(ctx, [[10, 6], [42, 6], [48, 20], [44, 46], [8, 46], [4, 20]], 0, 0, 52, 52); + ctx.strokeStyle = 'rgba(255,255,255,0.3)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(14, 18); ctx.lineTo(40, 18); ctx.moveTo(14, 28); ctx.lineTo(40, 28); ctx.stroke(); + ctx.fillStyle = light; + ctx.fillRect(42, 14, 4, 22); + }); + + const shoulder = canvasTex(scene, `${k}-shoulder`, 44, 44, (ctx) => { + const g = ctx.createRadialGradient(18, 16, 2, 22, 22, 22); + g.addColorStop(0, light); g.addColorStop(0.5, neon); g.addColorStop(1, dark); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(22, 22, 19, 0, Math.PI * 2); ctx.fill(); + ctx.lineWidth = 2; ctx.strokeStyle = '#ffffff'; ctx.stroke(); + }); + + const foot = canvasTex(scene, `${k}-foot`, 64, 32, (ctx) => { + shade(ctx, [[8, 4], [38, 4], [60, 18], [60, 28], [4, 28]], 0, 0, 64, 32); + }); + + canvasTex(scene, 'bf-shadow', 160, 40, (ctx) => { + const g = ctx.createRadialGradient(80, 20, 0, 80, 20, 80); + g.addColorStop(0, 'rgba(0,0,0,0.65)'); g.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = g; + ctx.save(); ctx.scale(1, 0.25); ctx.beginPath(); ctx.arc(80, 80, 80, 0, Math.PI * 2); ctx.fill(); ctx.restore(); + }); + + return { torso, head, fist, shoulder, foot }; +} + +class Golem { + constructor(scene, x, y, facing, color, style) { + this.scene = scene; + this.color = color; + this.facing = facing; // 1 faces right, -1 faces left + this.baseX = x; + this.baseY = y; + this.state = 'idle'; + this.phase = Math.random() * 10; + const t = golemTextures(scene, color, style); + const add = (key, bx, by, origin = 0.5) => { + const img = scene.add.image(0, 0, key).setOrigin(origin); + img.bx = bx; img.by = by; + return img; + }; + this.shadow = scene.add.image(0, 2, 'bf-shadow'); + this.ring = scene.add.image(0, 0, 'bf-ring').setTint(color).setBlendMode('ADD').setScale(1.6, 0.35).setAlpha(0.55); + this.footB = add(t.foot, -20, -14); + this.footF = add(t.foot, 26, -14); + this.fistB = add(t.fist, -34, -112); + this.shoulderB = add(t.shoulder, -40, -150); + this.torso = add(t.torso, 0, -100); + this.head = add(t.head, 4, -196); + this.shoulderF = add(t.shoulder, 42, -146); + this.fistF = add(t.fist, 58, -106); + this.parts = [this.footB, this.footF, this.fistB, this.shoulderB, this.torso, this.head, this.shoulderF, this.fistF]; + this.c = scene.add.container(x, y, [this.ring, this.shadow, ...this.parts]).setDepth(D.fighter); + this.c.setScale(facing, 1); + // pose offsets (tweened) + this.p = { kx: 0, ky: 0, rot: 0, fx: 0, fy: 0, bx: 0, by: 0, hx: 0, hy: 0, hr: 0, lean: 0 }; + if (isWebGL(scene) && this.c.postFX) { + try { this.c.postFX.addGlow(color, 2.2, 0, false, 0.1, 10); } catch (_) { /* optional */ } + } + } + + update(time) { + const p = this.p; + const t = time / 1000 + this.phase; + const ko = this.state === 'ko'; + const bob = ko ? 0 : Math.sin(t * 3.2) * 5; + const sway = ko ? 0 : Math.sin(t * 3.2 + 1.2) * 6; + const set = (img, dx, dy, rot = 0) => { img.setPosition(img.bx + dx, img.by + dy); img.setRotation(rot); }; + set(this.footB, 0, 0); + set(this.footF, 0, 0); + set(this.torso, p.lean * 0.4, bob); + set(this.head, p.hx + p.lean * 0.8, bob * 1.3 + p.hy, p.hr); + set(this.shoulderB, p.lean * 0.5, bob); + set(this.shoulderF, p.lean * 0.5, bob); + set(this.fistB, p.bx + p.lean * 0.6, sway + p.by, p.bx * 0.004); + set(this.fistF, p.fx + p.lean * 0.6, -sway + p.fy, p.fx * 0.003); + this.c.setPosition(this.baseX + p.kx * this.facing, this.baseY + p.ky); + this.c.setRotation(p.rot * this.facing); + this.ring.setAlpha(ko ? 0.15 : 0.45 + 0.2 * Math.sin(t * 4)); + } + + tween(cfg) { return this.scene.tweens.add({ targets: this.p, ...cfg }); } + + reset() { + this.scene.tweens.killTweensOf(this.p); + Object.keys(this.p).forEach((k) => { this.p[k] = 0; }); + this.state = 'idle'; + this.parts.forEach((pt) => pt.clearTint().setAlpha(1)); + } + + fistWorld(front = true) { + const img = front ? this.fistF : this.fistB; + return { x: this.c.x + img.x * this.facing, y: this.c.y + img.y }; + } + coreWorld() { return { x: this.c.x + this.torso.x * this.facing, y: this.c.y + this.torso.y }; } + + jab() { + if (this.state === 'ko') return; + this.tween({ fx: 90, lean: 10, duration: 70, yoyo: true, hold: 70, ease: 'Quad.easeOut' }); + } + + combo(n = 3) { + if (this.state === 'ko') return; + for (let i = 0; i < n; i++) { + const front = i % 2 === 0; + this.scene.time.delayedCall(i * 130, () => { + if (this.state === 'ko') return; + this.tween(front + ? { fx: 100, fy: -10, lean: 12, duration: 60, yoyo: true, hold: 40 } + : { bx: 120, by: -6, lean: 14, duration: 60, yoyo: true, hold: 40 }); + }); + } + } + + windUp(ms = 260) { + if (this.state === 'ko') return; + this.tween({ lean: -14, fx: -24, bx: -18, fy: 10, duration: ms, ease: 'Sine.easeOut' }); + } + + release() { + if (this.state === 'ko') return; + this.scene.tweens.killTweensOf(this.p); + this.tween({ + fx: 110, bx: 130, fy: -20, by: -26, lean: 18, duration: 90, ease: 'Quad.easeOut', + onComplete: () => this.tween({ fx: 0, bx: 0, fy: 0, by: 0, lean: 0, duration: 380, delay: 220, ease: 'Sine.easeInOut' }), + }); + } + + hit(power = 4) { + if (this.state === 'ko') return; + this.flash(); + const k = Math.min(70, 14 + power * 2.5); + this.scene.tweens.killTweensOf(this.p); + this.tween({ kx: -k, hr: -0.35, hx: -12, lean: -10, fx: -20, bx: -20, duration: 80, ease: 'Quad.easeOut' }); + this.tween({ kx: 0, hr: 0, hx: 0, lean: 0, fx: 0, bx: 0, delay: 160, duration: 420, ease: 'Sine.easeOut' }); + } + + block() { + if (this.state === 'ko') return; + this.tween({ fx: 18, fy: -70, bx: 50, by: -58, lean: -4, duration: 90, yoyo: true, hold: 260 }); + const s = this.scene; + const pos = this.coreWorld(); + const shield = s.add.image(pos.x + 70 * this.facing, pos.y - 20, 'bf-ring').setTint(this.color) + .setBlendMode('ADD').setScale(0.4, 1.4).setDepth(D.fighter + 1).setAlpha(0.9); + s.tweens.add({ targets: shield, scaleX: 0.7, scaleY: 1.8, alpha: 0, duration: 420, onComplete: () => shield.destroy() }); + } + + flash() { + this.parts.forEach((pt) => pt.setTintFill(0xffffff)); + this.scene.time.delayedCall(70, () => this.parts.forEach((pt) => pt.clearTint())); + } + + ko() { + this.state = 'ko'; + this.flash(); + this.scene.tweens.killTweensOf(this.p); + this.tween({ kx: -90, ky: -60, rot: -0.6, duration: 260, ease: 'Quad.easeOut' }); + this.tween({ ky: 0, rot: -1.45, kx: -130, delay: 260, duration: 420, ease: 'Bounce.easeOut' }); + this.tween({ hx: -10, hy: 20, hr: -0.8, fx: -40, fy: 60, bx: 30, by: 70, delay: 300, duration: 300 }); + this.scene.time.delayedCall(700, () => this.parts.forEach((pt) => pt.setTint(0x777788))); + } + + victory() { + if (this.state === 'ko') return; + this.state = 'win'; + this.tween({ fy: -150, fx: 10, duration: 220, ease: 'Back.easeOut' }); + this.tween({ ky: -50, duration: 260, yoyo: true, repeat: 2, ease: 'Sine.easeOut' }); + } + + destroy() { this.scene.tweens.killTweensOf(this.p); this.c.destroy(); } +} + +// Persistent synthwave backdrop shared by menus and battles: sky, sun, +// scrolling perspective grid and rising embers. +export class BFBackdrop { + constructor(scene) { + this.scene = scene; + this.objs = []; + this.track(scene.add.image(W / 2, H / 2, 'bf-bg').setDepth(D.bg)); + this.grid = this.track(scene.add.graphics().setDepth(D.floor)); + this.scan = this.track(scene.add.tileSprite(W / 2, H / 2, W, H, 'bf-scan').setDepth(D.top - 1).setAlpha(0.35)); + this.scroll = 0; + this.speed = 1; + this.embers = this.track(scene.add.particles(0, 0, 'bf-spark', { + x: { min: 0, max: W }, y: H + 10, + lifespan: 5200, speedY: { min: -90, max: -35 }, speedX: { min: -14, max: 14 }, + scale: { start: 0.35, end: 0 }, alpha: { start: 0.55, end: 0 }, frequency: 160, + tint: [0xff3da8, 0x2ee6ff, 0xb86bff], blendMode: 'ADD', + }).setDepth(D.arena)); + } + + track(o) { this.objs.push(o); return o; } + + setTempo(speed) { this.speed = speed; } + + update(time, delta) { + const g = this.grid; + g.clear(); + this.scroll = (this.scroll + delta * 0.00035 * this.speed) % 1; + const vx = W / 2; + const top = HORIZON_Y; + const depth = H - top; + for (let i = 0; i < 14; i++) { + const z = (i + this.scroll) / 14; + const y = top + depth * z * z; + g.lineStyle(z > 0.5 ? 2 : 1, 0xff3da8, 0.15 + z * 0.55); + g.lineBetween(0, y, W, y); + } + g.lineStyle(1.5, 0xb86bff, 0.35); + for (let i = -18; i <= 18; i++) g.lineBetween(vx + i * 14, top, vx + i * 150, H); + } + + destroy() { + for (const o of this.objs) { try { o.destroy(); } catch (_) {} } + this.objs = []; + } +} + +export class BFArena { + // colors: [p1Color, p2Color], styles: [p1HeadStyle, p2HeadStyle] + constructor(scene, colors, styles = [0, 1]) { + this.scene = scene; + this.fighters = [ + new Golem(scene, ARENA.fighterX[0], ARENA.floorY, 1, colors[0], styles[0]), + new Golem(scene, ARENA.fighterX[1], ARENA.floorY, -1, colors[1], styles[1]), + ]; + } + + update(time) { + for (const f of this.fighters) f.update(time); + } + + // ── fight choreography ── + attack(idx, power, { chain = 1, super: isSuper = false } = {}) { + const f = this.fighters[idx]; + if (isSuper || chain >= 4) { f.windUp(180); this.scene.time.delayedCall(180, () => f.release()); } + else if (chain >= 2 || power >= 8) f.combo(Math.min(5, chain + 1)); + else f.jab(); + } + + windUp(idx) { this.fighters[idx].windUp(); } + hit(idx, power) { this.fighters[idx].hit(power); } + block(idx) { this.fighters[idx].block(); } + ko(idx) { this.fighters[idx].ko(); this.fighters[1 - idx].victory(); } + reset() { this.fighters.forEach((f) => f.reset()); } + launchPoint(idx) { return this.fighters[idx].fistWorld(true); } + core(idx) { return this.fighters[idx].coreWorld(); } + + destroy() { + this.fighters.forEach((f) => f.destroy()); + } +} + +// Standalone golem for menus / VS splash. +export function makeGolem(scene, x, y, facing, color, style, scale = 1, depth = D.fighter) { + const g = new Golem(scene, x, y, facing, color, style); + g.c.setScale(facing * scale, scale).setDepth(depth); + const baseUpdate = g.update.bind(g); + g.update = (time) => { baseUpdate(time); g.c.setScale(facing * scale, scale); }; + return g; +} diff --git a/src/games/blockfighter/BFArt.js b/src/games/blockfighter/BFArt.js new file mode 100644 index 0000000..402dbff --- /dev/null +++ b/src/games/blockfighter/BFArt.js @@ -0,0 +1,434 @@ +// Block Fighter — procedural neon art. Every texture is painted once onto a +// canvas (gradients, glows, bevels) so the game ships no image files. +// +// bf-gem-{c} glossy faceted gem, with a faint per-color glyph so +// colors stay readable for color-blind players +// bf-crash-{c} glowing crash orb in a dark socket +// bf-counter-{c}-{n} cracked-glass counter gem showing n (1..COUNTER_START) +// bf-diamond prism diamond +// bf-power-{c} 120×120 nine-slice source for power gems +// bf-power-glint white bevel overlay for the power-gem shimmer +// bf-ghost-{c} landing-shadow outline +// bf-spark/shard/ring/star/streak/glow/beam particle + FX textures +// bf-bg synthwave sky, sun, mountains and horizon +// bf-scan 4×4 scanline tile + +import { CELL, GEM_HEX, GEM_LIGHT, GEM_DARK, W, H, ARENA } from './BFLayout.js'; +import { COUNTER_START } from './BlockFighterLogic.js'; + +export const POWER_SRC = 120; +export const POWER_SLICE = 26; + +function canvasTex(scene, key, w, h, draw) { + if (scene.textures.exists(key)) return; + const tex = scene.textures.createCanvas(key, w, h); + if (!tex) return; + const ctx = tex.getContext(); + draw(ctx, w, h); + tex.refresh(); +} + +function rr(ctx, x, y, w, h, r) { + ctx.beginPath(); + ctx.moveTo(x + r, y); + ctx.arcTo(x + w, y, x + w, y + h, r); + ctx.arcTo(x + w, y + h, x, y + h, r); + ctx.arcTo(x, y + h, x, y, r); + ctx.arcTo(x, y, x + w, y, r); + ctx.closePath(); +} + +function hexToRgb(hex) { + const n = parseInt(hex.slice(1), 16); + return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; +} +const rgba = (hex, a) => { const [r, g, b] = hexToRgb(hex); return `rgba(${r},${g},${b},${a})`; }; + +// Small embossed glyph per color: ▲ red, ● green, ◆ blue, ★ gold. +function glyph(ctx, c, cx, cy, s, style) { + ctx.save(); + ctx.fillStyle = style; + ctx.beginPath(); + if (c === 0) { + ctx.moveTo(cx, cy - s); ctx.lineTo(cx + s * 0.95, cy + s * 0.7); ctx.lineTo(cx - s * 0.95, cy + s * 0.7); + } else if (c === 1) { + ctx.arc(cx, cy, s * 0.8, 0, Math.PI * 2); + } else if (c === 2) { + ctx.moveTo(cx, cy - s); ctx.lineTo(cx + s * 0.8, cy); ctx.lineTo(cx, cy + s); ctx.lineTo(cx - s * 0.8, cy); + } else { + for (let i = 0; i < 10; i++) { + const a = -Math.PI / 2 + i * Math.PI / 5; + const rad = i % 2 ? s * 0.42 : s; + ctx.lineTo(cx + Math.cos(a) * rad, cy + Math.sin(a) * rad); + } + } + ctx.closePath(); + ctx.fill(); + ctx.restore(); +} + +function paintGem(ctx, c, x, y, w, h, radius, inset) { + const base = GEM_HEX[c], light = GEM_LIGHT[c], dark = GEM_DARK[c]; + // outer body + rr(ctx, x, y, w, h, radius); + let g = ctx.createLinearGradient(x, y, x + w, y + h); + g.addColorStop(0, light); + g.addColorStop(0.35, base); + g.addColorStop(1, dark); + ctx.fillStyle = g; + ctx.fill(); + // bevel facets: top/left light, bottom/right dark + const ix = x + inset, iy = y + inset, iw = w - inset * 2, ih = h - inset * 2; + ctx.fillStyle = 'rgba(255,255,255,0.22)'; + ctx.beginPath(); ctx.moveTo(x + 4, y + 4); ctx.lineTo(x + w - 4, y + 4); ctx.lineTo(ix + iw, iy); ctx.lineTo(ix, iy); ctx.closePath(); ctx.fill(); + ctx.fillStyle = 'rgba(255,255,255,0.10)'; + ctx.beginPath(); ctx.moveTo(x + 4, y + 4); ctx.lineTo(ix, iy); ctx.lineTo(ix, iy + ih); ctx.lineTo(x + 4, y + h - 4); ctx.closePath(); ctx.fill(); + ctx.fillStyle = 'rgba(0,0,0,0.28)'; + ctx.beginPath(); ctx.moveTo(x + 4, y + h - 4); ctx.lineTo(ix, iy + ih); ctx.lineTo(ix + iw, iy + ih); ctx.lineTo(x + w - 4, y + h - 4); ctx.closePath(); ctx.fill(); + ctx.fillStyle = 'rgba(0,0,0,0.16)'; + ctx.beginPath(); ctx.moveTo(x + w - 4, y + 4); ctx.lineTo(ix + iw, iy); ctx.lineTo(ix + iw, iy + ih); ctx.lineTo(x + w - 4, y + h - 4); ctx.closePath(); ctx.fill(); + // table (inner face) + rr(ctx, ix, iy, iw, ih, Math.max(3, radius - inset / 2)); + g = ctx.createRadialGradient(ix + iw * 0.3, iy + ih * 0.28, 2, ix + iw * 0.5, iy + ih * 0.5, Math.max(iw, ih) * 0.75); + g.addColorStop(0, light); + g.addColorStop(0.45, base); + g.addColorStop(1, rgba(dark, 0.9)); + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; + ctx.stroke(); + // outer rim + rr(ctx, x + 0.5, y + 0.5, w - 1, h - 1, radius); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(0,0,0,0.55)'; + ctx.stroke(); + rr(ctx, x + 2.5, y + 2.5, w - 5, h - 5, radius - 2); + ctx.lineWidth = 1.2; + ctx.strokeStyle = rgba(light, 0.55); + ctx.stroke(); +} + +function specular(ctx, x, y, rx, ry) { + ctx.save(); + ctx.translate(x, y); + ctx.rotate(-0.55); + const g = ctx.createRadialGradient(0, 0, 0, 0, 0, rx); + g.addColorStop(0, 'rgba(255,255,255,0.95)'); + g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; + ctx.scale(1, ry / rx); + ctx.beginPath(); + ctx.arc(0, 0, rx, 0, Math.PI * 2); + ctx.fill(); + ctx.restore(); +} + +function radialDot(ctx, cx, cy, r, stops) { + const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, r); + for (const [o, col] of stops) g.addColorStop(o, col); + ctx.fillStyle = g; + ctx.beginPath(); + ctx.arc(cx, cy, r, 0, Math.PI * 2); + ctx.fill(); +} + +export function makeTextures(scene) { + const S = CELL; + for (let c = 0; c < 4; c++) { + canvasTex(scene, `bf-gem-${c}`, S, S, (ctx) => { + paintGem(ctx, c, 3, 3, S - 6, S - 6, 11, 11); + glyph(ctx, c, S / 2, S / 2 + 1, 8, 'rgba(255,255,255,0.22)'); + specular(ctx, 19, 16, 11, 5); + }); + + canvasTex(scene, `bf-crash-${c}`, S, S, (ctx) => { + const m = S / 2; + radialDot(ctx, m, m, m - 1, [[0, 'rgba(0,0,0,0.65)'], [0.85, 'rgba(10,0,25,0.55)'], [1, 'rgba(0,0,0,0)']]); + radialDot(ctx, m, m, m - 4, [[0, '#ffffff'], [0.22, GEM_LIGHT[c]], [0.6, GEM_HEX[c]], [1, GEM_DARK[c]]]); + ctx.lineWidth = 2.5; + ctx.strokeStyle = rgba(GEM_LIGHT[c], 0.9); + ctx.beginPath(); ctx.arc(m, m, m - 9, 0, Math.PI * 2); ctx.stroke(); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(255,255,255,0.55)'; + ctx.beginPath(); ctx.arc(m, m, m - 4, -2.6, -0.9); ctx.stroke(); + glyph(ctx, c, m, m + 1, 7, 'rgba(255,255,255,0.75)'); + specular(ctx, m - 8, m - 10, 8, 4); + }); + + for (let n = 1; n <= COUNTER_START; n++) { + canvasTex(scene, `bf-counter-${c}-${n}`, S, S, (ctx) => { + rr(ctx, 3, 3, S - 6, S - 6, 10); + const g = ctx.createLinearGradient(0, 3, 0, S - 3); + g.addColorStop(0, rgba(GEM_DARK[c], 0.95)); + g.addColorStop(1, '#0c0518'); + ctx.fillStyle = g; + ctx.fill(); + rr(ctx, 8, 8, S - 16, S - 16, 7); + ctx.fillStyle = rgba(GEM_HEX[c], 0.22); + ctx.fill(); + // cracks + ctx.strokeStyle = rgba(GEM_LIGHT[c], 0.35); + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(10, 14); ctx.lineTo(20, 22); ctx.lineTo(17, 31); + ctx.moveTo(S - 10, S - 16); ctx.lineTo(S - 21, S - 24); ctx.lineTo(S - 16, S - 34); + ctx.moveTo(S - 14, 9); ctx.lineTo(S - 19, 18); + ctx.stroke(); + rr(ctx, 3.5, 3.5, S - 7, S - 7, 10); + ctx.lineWidth = 3; + ctx.strokeStyle = GEM_HEX[c]; + ctx.stroke(); + // digit with a neon glow + ctx.font = `bold 34px Righteous, "Arial Black", sans-serif`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.shadowColor = GEM_HEX[c]; + ctx.shadowBlur = 10; + ctx.fillStyle = GEM_LIGHT[c]; + ctx.fillText(String(n), S / 2, S / 2 + 2); + ctx.shadowBlur = 0; + ctx.fillStyle = '#ffffff'; + ctx.fillText(String(n), S / 2, S / 2 + 2); + }); + } + + canvasTex(scene, `bf-power-${c}`, POWER_SRC, POWER_SRC, (ctx, w) => { + paintGem(ctx, c, 2, 2, w - 4, w - 4, 18, 18); + rr(ctx, 9, 9, w - 18, w - 18, 12); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(255,255,255,0.5)'; + ctx.stroke(); + specular(ctx, 22, 18, 14, 5); + }); + + canvasTex(scene, `bf-ghost-${c}`, S, S, (ctx) => { + rr(ctx, 6, 6, S - 12, S - 12, 10); + ctx.fillStyle = rgba(GEM_HEX[c], 0.14); + ctx.fill(); + ctx.setLineDash([7, 5]); + ctx.lineWidth = 2.5; + ctx.strokeStyle = rgba(GEM_LIGHT[c], 0.75); + ctx.stroke(); + }); + } + + canvasTex(scene, 'bf-power-glint', POWER_SRC, POWER_SRC, (ctx, w) => { + rr(ctx, 4, 4, w - 8, w - 8, 16); + ctx.lineWidth = 6; + ctx.strokeStyle = 'rgba(255,255,255,0.9)'; + ctx.stroke(); + rr(ctx, 14, 14, w - 28, w - 28, 10); + ctx.fillStyle = 'rgba(255,255,255,0.35)'; + ctx.fill(); + }); + + canvasTex(scene, 'bf-diamond', S, S, (ctx) => { + const m = S / 2; + radialDot(ctx, m, m, m, [[0, 'rgba(255,255,255,0.65)'], [1, 'rgba(255,255,255,0)']]); + const pts = [[m, 4], [S - 6, m - 6], [m, S - 3], [6, m - 6]]; + ctx.beginPath(); + pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); + ctx.closePath(); + let g; + if (ctx.createConicGradient) { + g = ctx.createConicGradient(0, m, m - 4); + ['#ff6bd6', '#ffd36b', '#6bffb8', '#6bd6ff', '#b86bff', '#ff6bd6'].forEach((col, i) => g.addColorStop(i / 5, col)); + } else { + g = ctx.createLinearGradient(0, 0, S, S); + g.addColorStop(0, '#ff6bd6'); g.addColorStop(0.5, '#6bffb8'); g.addColorStop(1, '#6bd6ff'); + } + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = '#ffffff'; + ctx.stroke(); + // facet lines + ctx.lineWidth = 1; + ctx.strokeStyle = 'rgba(255,255,255,0.7)'; + ctx.beginPath(); + ctx.moveTo(6, m - 6); ctx.lineTo(S - 6, m - 6); + ctx.moveTo(m - 10, m - 6); ctx.lineTo(m, 4); ctx.lineTo(m + 10, m - 6); + ctx.moveTo(m - 10, m - 6); ctx.lineTo(m, S - 3); ctx.lineTo(m + 10, m - 6); + ctx.stroke(); + specular(ctx, m - 6, 16, 7, 3); + }); + + // ── particles / fx ── + canvasTex(scene, 'bf-spark', 32, 32, (ctx) => radialDot(ctx, 16, 16, 16, + [[0, 'rgba(255,255,255,1)'], [0.3, 'rgba(255,255,255,0.8)'], [1, 'rgba(255,255,255,0)']])); + canvasTex(scene, 'bf-glow', 128, 128, (ctx) => radialDot(ctx, 64, 64, 64, + [[0, 'rgba(255,255,255,0.9)'], [0.4, 'rgba(255,255,255,0.35)'], [1, 'rgba(255,255,255,0)']])); + canvasTex(scene, 'bf-shard', 18, 18, (ctx) => { + ctx.fillStyle = '#ffffff'; + ctx.beginPath(); ctx.moveTo(9, 0); ctx.lineTo(18, 7); ctx.lineTo(11, 18); ctx.lineTo(0, 11); ctx.closePath(); ctx.fill(); + ctx.fillStyle = 'rgba(0,0,0,0.25)'; + ctx.beginPath(); ctx.moveTo(9, 9); ctx.lineTo(18, 7); ctx.lineTo(11, 18); ctx.closePath(); ctx.fill(); + }); + canvasTex(scene, 'bf-ring', 96, 96, (ctx) => { + ctx.lineWidth = 6; + ctx.strokeStyle = '#ffffff'; + ctx.beginPath(); ctx.arc(48, 48, 42, 0, Math.PI * 2); ctx.stroke(); + }); + canvasTex(scene, 'bf-star', 40, 40, (ctx) => { + ctx.fillStyle = '#ffffff'; + ctx.beginPath(); + for (let i = 0; i < 8; i++) { + const a = i * Math.PI / 4; + const r = i % 2 ? 4 : 20; + ctx.lineTo(20 + Math.cos(a) * r, 20 + Math.sin(a) * r); + } + ctx.closePath(); ctx.fill(); + radialDot(ctx, 20, 20, 8, [[0, 'rgba(255,255,255,1)'], [1, 'rgba(255,255,255,0)']]); + }); + canvasTex(scene, 'bf-streak', 16, 96, (ctx) => { + const g = ctx.createLinearGradient(0, 0, 0, 96); + g.addColorStop(0, 'rgba(255,255,255,0)'); + g.addColorStop(1, 'rgba(255,255,255,0.85)'); + ctx.fillStyle = g; + rr(ctx, 2, 0, 12, 96, 6); + ctx.fill(); + }); + canvasTex(scene, 'bf-beam', 64, 48, (ctx) => { + const g = ctx.createLinearGradient(0, 0, 0, 48); + g.addColorStop(0, 'rgba(255,255,255,0)'); + g.addColorStop(0.35, 'rgba(255,255,255,0.7)'); + g.addColorStop(0.5, 'rgba(255,255,255,1)'); + g.addColorStop(0.65, 'rgba(255,255,255,0.7)'); + g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, 64, 48); + }); + canvasTex(scene, 'bf-scan', 4, 4, (ctx) => { + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + ctx.fillRect(0, 0, 4, 1); + }); + canvasTex(scene, 'bf-pixel', 4, 4, (ctx) => { ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, 4, 4); }); + + makeBackground(scene); +} + +// Synthwave backdrop: deep sky, stars, striped sun, wireframe mountains. +// The perspective grid floor is animated separately (BFArena). +export const HORIZON_Y = 640; + +function makeBackground(scene) { + canvasTex(scene, 'bf-bg', W, H, (ctx) => { + let g = ctx.createLinearGradient(0, 0, 0, HORIZON_Y); + g.addColorStop(0, '#05010f'); + g.addColorStop(0.55, '#1c0634'); + g.addColorStop(0.85, '#47104f'); + g.addColorStop(1, '#8a1d5e'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, HORIZON_Y); + + // stars (deterministic) + let seed = 1337; + const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }; + for (let i = 0; i < 260; i++) { + const x = rnd() * W, y = rnd() * HORIZON_Y * 0.85; + const a = 0.25 + rnd() * 0.75; + ctx.fillStyle = `rgba(255,255,255,${a * (1 - y / HORIZON_Y)})`; + const s = rnd() < 0.08 ? 2.4 : 1.3; + ctx.fillRect(x, y, s, s); + } + + // sun: drawn on its own canvas so the stripes can be cut out of it + const sun = document.createElement('canvas'); + const R = 230; + sun.width = R * 2; sun.height = R * 2; + const sc = sun.getContext('2d'); + g = sc.createLinearGradient(0, 0, 0, R * 2); + g.addColorStop(0, '#fff27a'); + g.addColorStop(0.45, '#ff9a3d'); + g.addColorStop(0.8, '#ff2f8f'); + g.addColorStop(1, '#c4128a'); + sc.fillStyle = g; + sc.beginPath(); sc.arc(R, R, R, 0, Math.PI * 2); sc.fill(); + sc.globalCompositeOperation = 'destination-out'; + for (let i = 0; i < 9; i++) { + const y = R * 0.95 + i * i * 4.2 + i * 10; + sc.fillRect(0, y, R * 2, 3 + i * 1.6); + } + const sunY = HORIZON_Y - R * 0.72; + // glow behind sun + radialDot(ctx, ARENA.cx, sunY + 20, R * 1.9, [[0, 'rgba(255,80,160,0.45)'], [0.5, 'rgba(255,40,140,0.12)'], [1, 'rgba(255,40,140,0)']]); + ctx.drawImage(sun, ARENA.cx - R, sunY - R); + + // mountain ridges, back to front + const ridge = (base, amp, step, fill, line, seedOff) => { + let s2 = seedOff; + const r2 = () => { s2 = (s2 * 48271) % 2147483647; return s2 / 2147483647; }; + ctx.beginPath(); + ctx.moveTo(0, HORIZON_Y); + const pts = []; + for (let x = 0; x <= W + step; x += step) { + const centre = 1 - Math.min(1, Math.abs(x - ARENA.cx) / 420); // keep a dip so the sun shows + const y = base - (0.35 + r2() * 0.65) * amp * (1 - centre * 0.85); + pts.push([x, y]); + ctx.lineTo(x, y); + } + ctx.lineTo(W, HORIZON_Y); + ctx.closePath(); + ctx.fillStyle = fill; + ctx.fill(); + ctx.strokeStyle = line; + ctx.lineWidth = 1.5; + ctx.beginPath(); + pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); + ctx.stroke(); + // wireframe drops + ctx.globalAlpha = 0.35; + pts.forEach(([x, y], i) => { if (i % 2 === 0) { ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + step * 0.4, HORIZON_Y); ctx.stroke(); } }); + ctx.globalAlpha = 1; + }; + ridge(HORIZON_Y, 190, 90, '#1a0430', 'rgba(190,60,255,0.55)', 7); + ridge(HORIZON_Y, 110, 70, '#120226', 'rgba(255,61,168,0.6)', 99); + + // floor + g = ctx.createLinearGradient(0, HORIZON_Y, 0, H); + g.addColorStop(0, '#2a0738'); + g.addColorStop(0.25, '#0d0221'); + g.addColorStop(1, '#030008'); + ctx.fillStyle = g; + ctx.fillRect(0, HORIZON_Y, W, H - HORIZON_Y); + // horizon line glow + g = ctx.createLinearGradient(0, HORIZON_Y - 10, 0, HORIZON_Y + 10); + g.addColorStop(0, 'rgba(255,61,168,0)'); + g.addColorStop(0.5, 'rgba(255,120,220,0.95)'); + g.addColorStop(1, 'rgba(255,61,168,0)'); + ctx.fillStyle = g; + ctx.fillRect(0, HORIZON_Y - 10, W, 20); + + // vignette + g = ctx.createRadialGradient(W / 2, H / 2, H * 0.35, W / 2, H / 2, H * 1.05); + g.addColorStop(0, 'rgba(0,0,0,0)'); + g.addColorStop(1, 'rgba(0,0,0,0.7)'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + }); +} + +// Chrome-gradient fill for big display text (Phaser Text uses a canvas). +export function chromeText(text, top = '#ffffff', mid = '#ffd8f4', low = '#ff3da8') { + try { + const ctx = text.context; + const g = ctx.createLinearGradient(0, 0, 0, text.height); + g.addColorStop(0, top); + g.addColorStop(0.48, mid); + g.addColorStop(0.52, low); + g.addColorStop(1, '#3a0a5c'); + text.setFill(g); + } catch (_) { /* plain fill is fine */ } + return text; +} + +export function isWebGL(scene) { + return scene.game.renderer?.type === 2; // Phaser.WEBGL +} + +// Neon glow on an object when WebGL is available; silently skipped otherwise. +export function glow(scene, obj, color, strength = 4, quality = 0.1) { + if (!isWebGL(scene) || !obj?.preFX) return null; + try { return obj.preFX.addGlow(color, strength, 0, false, quality, 10); } catch (_) { return null; } +} diff --git a/src/games/blockfighter/BFBoard.js b/src/games/blockfighter/BFBoard.js new file mode 100644 index 0000000..634803c --- /dev/null +++ b/src/games/blockfighter/BFBoard.js @@ -0,0 +1,440 @@ +// Block Fighter — one player's board view. +// +// Keeps a persistent sprite per engine cell (keyed by the cell's stable id) and +// diffs each replayed snapshot against it, so gems visibly drop in, fall in +// cascades, change state, fuse into power gems and shatter, instead of the +// board being redrawn from scratch. Also owns the falling piece, its ghost, +// the incoming-garbage tray and the danger overlay. + +import { + WIDTH, HEIGHT, HIDDEN_ROWS, KIND, COUNTER_START, +} from './BlockFighterLogic.js'; +import { + CELL, BOARD_W, BOARD_H, BOARD_TOP, BOARD_LEFT, SIDE_COLOR, GEM_COLORS, + TRAY_Y, D, cellX, cellY, +} from './BFLayout.js'; +import { POWER_SLICE, glow } from './BFArt.js'; + +export function textureFor(cell) { + if (!cell) return null; + if (cell.kind === KIND.DIAMOND) return 'bf-diamond'; + if (cell.kind === KIND.CRASH) return `bf-crash-${cell.color}`; + if (cell.kind === KIND.COUNTER) return `bf-counter-${cell.color}-${Math.max(1, Math.min(COUNTER_START, cell.count))}`; + return `bf-gem-${cell.color}`; +} + +export class BFBoard { + // hooks: { fx, sound } — optional collaborators for shatter/fuse effects + constructor(scene, idx, hooks = {}) { + this.scene = scene; + this.idx = idx; + this.left = BOARD_LEFT[idx]; + this.hooks = hooks; + this.objs = []; + this.sprites = new Map(); // key -> { img, r, c, tex } + this.powers = new Map(); // powerId -> { ns, glint, g } + this.danger = 0; + this.dangerT = 0; + this.glintAt = 0; + + this.drawFrame(); + + // Everything that moves inside the well lives in one masked container so + // gems slide in from behind the top edge. + this.cont = scene.add.container(0, 0).setDepth(D.cells); + const maskG = scene.make.graphics({ add: false }); + maskG.fillStyle(0xffffff); + maskG.fillRect(this.left, BOARD_TOP, BOARD_W, BOARD_H); + this.maskG = maskG; + this.cont.setMask(maskG.createGeometryMask()); + this.objs.push(this.cont); + + this.ghostImgs = [0, 1].map(() => scene.add.image(0, 0, 'bf-ghost-0').setVisible(false)); + this.pieceImgs = [0, 1].map(() => scene.add.image(0, 0, 'bf-gem-0').setVisible(false)); + this.cont.add([...this.ghostImgs, ...this.pieceImgs]); + + this.drawTray(); + this.drawDanger(); + } + + track(o) { this.objs.push(o); return o; } + + // ── static chrome ────────────────────────────────────────────────────────── + drawFrame() { + const s = this.scene; + const { left } = this; + const col = SIDE_COLOR[this.idx]; + const g = this.track(s.add.graphics().setDepth(D.frame)); + // smoked-glass well + g.fillStyle(0x05010f, 0.82); + g.fillRoundedRect(left - 12, BOARD_TOP - 12, BOARD_W + 24, BOARD_H + 24, 16); + g.fillGradientStyle(0x1a0838, 0x1a0838, 0x07020f, 0x07020f, 0.9); + g.fillRect(left, BOARD_TOP, BOARD_W, BOARD_H); + // faint grid + g.lineStyle(1, 0x7a3cff, 0.12); + for (let c = 1; c < WIDTH; c++) g.lineBetween(left + c * CELL, BOARD_TOP, left + c * CELL, BOARD_TOP + BOARD_H); + for (let r = 1; r < BOARD_H / CELL; r++) g.lineBetween(left, BOARD_TOP + r * CELL, left + BOARD_W, BOARD_TOP + r * CELL); + // spawn column lane + g.fillStyle(0xff2e63, 0.05); + g.fillRect(left + 3 * CELL, BOARD_TOP, CELL, BOARD_H); + + // neon border (separate object so it can glow) + const border = this.track(s.add.graphics().setDepth(D.frame + 0.5)); + border.lineStyle(4, col, 1); + border.strokeRoundedRect(left - 10, BOARD_TOP - 10, BOARD_W + 20, BOARD_H + 20, 14); + border.lineStyle(1.5, 0xffffff, 0.6); + border.strokeRoundedRect(left - 10, BOARD_TOP - 10, BOARD_W + 20, BOARD_H + 20, 14); + this.border = border; + + // spawn marker + const mx = left + 3 * CELL + CELL / 2; + const arrow = this.track(s.add.triangle(mx, BOARD_TOP - 2, 0, 0, 26, 0, 13, 12, 0xff2e63, 0.9).setDepth(D.frame + 1)); + this.arrow = arrow; + } + + drawTray() { + const s = this.scene; + const cx = this.left + BOARD_W / 2; + this.trayBg = this.track(s.add.graphics().setDepth(D.ui)); + this.trayPips = []; + for (let i = 0; i < WIDTH; i++) { + const img = this.track(s.add.image(this.left + i * CELL + CELL / 2, TRAY_Y, 'bf-counter-0-5') + .setDisplaySize(30, 30).setDepth(D.ui + 1).setVisible(false)); + this.trayPips.push(img); + } + this.trayText = this.track(s.add.text(cx, TRAY_Y, '', { + fontFamily: 'Righteous', fontSize: '26px', color: '#ffffff', stroke: '#2a0010', strokeThickness: 6, + }).setOrigin(0.5).setDepth(D.ui + 2)); + this.trayCount = 0; + } + + drawDanger() { + const s = this.scene; + const g = this.track(s.add.graphics().setDepth(D.danger).setAlpha(0)); + g.lineStyle(10, 0xff1744, 1); + g.strokeRoundedRect(this.left - 6, BOARD_TOP - 6, BOARD_W + 12, BOARD_H + 12, 12); + g.fillGradientStyle(0xff1744, 0xff1744, 0xff1744, 0xff1744, 0.35, 0.35, 0, 0); + g.fillRect(this.left, BOARD_TOP, BOARD_W, 120); + this.dangerG = g; + this.dangerText = this.track(s.add.text(this.left + BOARD_W / 2, BOARD_TOP + 44, 'DANGER', { + fontFamily: 'Righteous', fontSize: '40px', color: '#ffffff', stroke: '#ff1744', strokeThickness: 8, + }).setOrigin(0.5).setDepth(D.danger + 1).setAlpha(0)); + } + + // ── snapshot diffing ─────────────────────────────────────────────────────── + // snap: { board, powerGems }, e: the engine event (type + extras) + applySnapshot(snap, e = {}) { + const s = this.scene; + const type = e.type; + const cleared = new Map(); + for (const cc of e.cells ?? []) if (cc.id != null && (type === 'clear' || type === 'diamond')) cleared.set(cc.id, cc); + + const seen = new Set(); + const powerKeys = new Set(); + let garbageOrder = 0; + + for (let r = 0; r < HEIGHT; r++) { + for (let c = 0; c < WIDTH; c++) { + const cell = snap.board[r][c]; + if (!cell) continue; + const key = cell.id ?? `p${r},${c}`; + if (cell.powerId != null) { powerKeys.add(key); continue; } + seen.add(key); + const tex = textureFor(cell); + const x = cellX(this.left, c); + const y = cellY(r); + let sp = this.sprites.get(key); + if (!sp) { + const img = s.add.image(x, y, tex); + this.cont.add(img); + sp = { img, r, c, tex }; + this.sprites.set(key, sp); + if (type === 'garbage') { + const dist = (r - HIDDEN_ROWS + 3) * CELL + 40; + img.y = y - dist; + const delay = c * 28 + garbageOrder * 4; + garbageOrder += 1; + s.tweens.add({ + targets: img, y, delay, duration: 300 + dist * 0.25, ease: 'Bounce.easeOut', + }); + } else if (type === 'place') { + img.y = y - CELL * 0.6; + s.tweens.add({ + targets: img, y, duration: 70, ease: 'Quad.easeIn', + onComplete: () => this.squash(img), + }); + } else { + img.setScale(0.2); + s.tweens.add({ targets: img, scale: 1, duration: 160, ease: 'Back.easeOut' }); + } + } else { + if (sp.r !== r || sp.c !== c) { + const dist = Math.abs(sp.r - r) + Math.abs(sp.c - c); + s.tweens.killTweensOf(sp.img); + sp.img.setScale(1); + s.tweens.add({ + targets: sp.img, x, y, duration: Math.min(380, 90 + dist * 50), ease: 'Quad.easeIn', + onComplete: () => this.squash(sp.img), + }); + sp.r = r; sp.c = c; + } + if (sp.tex !== tex) { + const wasCounter = sp.tex.startsWith('bf-counter'); + sp.img.setTexture(tex); + sp.tex = tex; + if (wasCounter && cell.kind !== KIND.COUNTER) { + // counter matured / purged: bright flip + sp.img.setScale(1.3); + s.tweens.add({ targets: sp.img, scale: 1, duration: 220, ease: 'Back.easeOut' }); + this.hooks.fx?.sparkle(x, y, GEM_COLORS[cell.color], 4); + } else { + sp.img.setScale(1.12); + s.tweens.add({ targets: sp.img, scale: 1, duration: 120 }); + } + } + } + sp.img.setVisible(r >= HIDDEN_ROWS - 3); // allow drop-ins from above the mask + } + } + + // sprites that vanished: cleared → shatter; absorbed into power gem → melt + for (const [key, sp] of this.sprites) { + if (seen.has(key)) continue; + this.sprites.delete(key); + const cc = cleared.get(key); + s.tweens.killTweensOf(sp.img); + if (cc) { + if (cc.r >= HIDDEN_ROWS) this.hooks.fx?.shatter(sp.img.x, sp.img.y, cc.color == null ? 0xffffff : GEM_COLORS[cc.color], cc.kind); + sp.img.destroy(); + } else if (powerKeys.has(key)) { + s.tweens.add({ targets: sp.img, alpha: 0, scale: 1.08, duration: 140, onComplete: () => sp.img.destroy() }); + } else { + s.tweens.add({ targets: sp.img, alpha: 0, scale: 0.4, duration: 160, onComplete: () => sp.img.destroy() }); + } + } + + this.applyPowers(snap.powerGems ?? [], type, cleared); + this.cont.bringToTop(this.ghostImgs[0]); + this.cont.bringToTop(this.ghostImgs[1]); + this.cont.bringToTop(this.pieceImgs[0]); + this.cont.bringToTop(this.pieceImgs[1]); + } + + powerRect(g) { + return { + x: this.left + g.x * CELL + (g.w * CELL) / 2, + y: cellY(g.y) - CELL / 2 + (g.h * CELL) / 2, + w: g.w * CELL - 4, + h: g.h * CELL - 4, + }; + } + + applyPowers(list, type, cleared) { + const s = this.scene; + const live = new Set(); + for (const g of list) { + live.add(g.id); + const rect = this.powerRect(g); + let pw = this.powers.get(g.id); + if (!pw) { + const ns = s.add.nineslice(rect.x, rect.y, `bf-power-${g.color}`, undefined, + rect.w, rect.h, POWER_SLICE, POWER_SLICE, POWER_SLICE, POWER_SLICE); + const glint = s.add.nineslice(rect.x, rect.y, 'bf-power-glint', undefined, + rect.w, rect.h, POWER_SLICE, POWER_SLICE, POWER_SLICE, POWER_SLICE).setBlendMode('ADD').setAlpha(0.9); + this.cont.add([ns, glint]); + pw = { ns, glint, g: { ...g } }; + this.powers.set(g.id, pw); + ns.setScale(0.86); + s.tweens.add({ targets: [ns, glint], scale: 1, duration: 260, ease: 'Back.easeOut' }); + s.tweens.add({ targets: glint, alpha: 0, duration: 420 }); + this.hooks.fx?.fuse(rect.x, rect.y, rect.w, rect.h, GEM_COLORS[g.color]); + this.hooks.sound?.fuse?.(g.w * g.h); + } else { + const old = pw.g; + const sizeChanged = old.w !== g.w || old.h !== g.h; + const moved = old.x !== g.x || old.y !== g.y; + if (sizeChanged || moved) { + s.tweens.killTweensOf([pw.ns, pw.glint]); + const proxy = { x: pw.ns.x, y: pw.ns.y, w: pw.ns.width, h: pw.ns.height }; + s.tweens.add({ + targets: proxy, x: rect.x, y: rect.y, w: rect.w, h: rect.h, + duration: sizeChanged ? 220 : Math.min(380, 90 + Math.abs(old.y - g.y) * 50), + ease: sizeChanged ? 'Back.easeOut' : 'Quad.easeIn', + onUpdate: () => { + pw.ns.setPosition(proxy.x, proxy.y).setSize(proxy.w, proxy.h); + pw.glint.setPosition(proxy.x, proxy.y).setSize(proxy.w, proxy.h); + }, + }); + if (sizeChanged) { + pw.glint.setAlpha(0.9); + s.tweens.add({ targets: pw.glint, alpha: 0, duration: 420 }); + this.hooks.fx?.fuse(rect.x, rect.y, rect.w, rect.h, GEM_COLORS[g.color]); + this.hooks.sound?.fuse?.(g.w * g.h); + } + } + pw.g = { ...g }; + } + } + for (const [id, pw] of this.powers) { + if (live.has(id)) continue; + this.powers.delete(id); + s.tweens.killTweensOf([pw.ns, pw.glint]); + if (cleared.size) { + const { x, y, width, height } = pw.ns; + this.hooks.fx?.powerShatter(x, y, width, height, GEM_COLORS[pw.g.color]); + pw.ns.destroy(); pw.glint.destroy(); + } else { + s.tweens.add({ targets: [pw.ns, pw.glint], alpha: 0, duration: 160, onComplete: () => { pw.ns.destroy(); pw.glint.destroy(); } }); + } + } + } + + squash(img) { + if (!img.active) return; + img.setScale(1.12, 0.84); + this.scene.tweens.add({ targets: img, scaleX: 1, scaleY: 1, duration: 140, ease: 'Back.easeOut' }); + } + + // ── falling piece ────────────────────────────────────────────────────────── + // cells: [{r,c,half}], fall: 0..1 sub-cell offset, ghost: [{r,c}] | null + setPiece(piece, cells, fall, ghost) { + if (!piece) { + this.pieceImgs.forEach((i) => i.setVisible(false)); + this.ghostImgs.forEach((i) => i.setVisible(false)); + return; + } + const dy = fall * CELL; + cells.forEach(({ r, c, half }, i) => { + const cell = piece[half]; + const img = this.pieceImgs[i]; + const tex = textureFor(cell); + if (img.texture.key !== tex) img.setTexture(tex); + img.setPosition(cellX(this.left, c), cellY(r) + dy).setVisible(true); + }); + if (ghost) { + ghost.forEach(({ r, c }, i) => { + const half = cells[i].half; + const cell = piece[half]; + const tex = `bf-ghost-${cell.color ?? 2}`; + const img = this.ghostImgs[i]; + if (img.texture.key !== tex) img.setTexture(tex); + img.setPosition(cellX(this.left, c), cellY(r)).setVisible(r >= HIDDEN_ROWS); + }); + } else { + this.ghostImgs.forEach((i) => i.setVisible(false)); + } + } + + pieceSquash() { + for (const img of this.pieceImgs) { + if (!img.visible) continue; + img.setScale(1.15, 0.8); + this.scene.tweens.add({ targets: img, scaleX: 1, scaleY: 1, duration: 120 }); + } + } + + // hard-drop streak from the piece's current cells down to where it lands + dropTrail(fromCells, toCells, color) { + const s = this.scene; + fromCells.forEach((fc, i) => { + const tc = toCells[i]; + if (!tc) return; + const y0 = Math.max(cellY(fc.r) - CELL / 2, BOARD_TOP); + const y1 = cellY(tc.r) + CELL / 2; + if (y1 - y0 < CELL * 1.5) return; + const img = s.add.image(cellX(this.left, tc.c), (y0 + y1) / 2, 'bf-streak') + .setDisplaySize(CELL * 0.7, y1 - y0).setTint(color).setBlendMode('ADD').setDepth(D.fx).setAlpha(0.85); + s.tweens.add({ targets: img, alpha: 0, scaleX: 0.02, duration: 260, onComplete: () => img.destroy() }); + }); + } + + // ── tray / danger ────────────────────────────────────────────────────────── + setIncoming(n, patternRow) { + const rowKey = patternRow ? patternRow.join('') : ''; + if (n === this.trayCount && rowKey === this.trayRowKey) return; + this.trayRowKey = rowKey; + const changed = n !== this.trayCount; + const grew = n > this.trayCount; + this.trayCount = n; + const g = this.trayBg; + g.clear(); + if (n <= 0) { + this.trayPips.forEach((p) => p.setVisible(false)); + this.trayText.setText(''); + return; + } + const rows = Math.ceil(n / WIDTH); + g.fillStyle(0x2a0010, 0.85); + g.fillRoundedRect(this.left - 4, TRAY_Y - 22, BOARD_W + 8, 44, 10); + g.lineStyle(2, rows >= 3 ? 0xff1744 : 0xff7a3d, 1); + g.strokeRoundedRect(this.left - 4, TRAY_Y - 22, BOARD_W + 8, 44, 10); + for (let i = 0; i < WIDTH; i++) { + const pip = this.trayPips[i]; + const show = i < Math.min(n, WIDTH); + pip.setVisible(show); + if (show) pip.setTexture(`bf-counter-${patternRow?.[i] ?? 0}-5`).setDisplaySize(30, 30).setAlpha(0.85); + } + this.trayText.setText(n > WIDTH ? `${n}` : ''); + if (changed && grew) { + this.trayText.setScale(1.6); + this.scene.tweens.add({ targets: this.trayText, scale: 1, duration: 220, ease: 'Back.easeOut' }); + for (const p of this.trayPips) { + if (!p.visible) continue; + p.y = TRAY_Y - 14; + this.scene.tweens.add({ targets: p, y: TRAY_Y, duration: 220, ease: 'Bounce.easeOut' }); + } + } + } + + trayPoint() { return { x: this.left + BOARD_W / 2, y: TRAY_Y }; } + centre() { return { x: this.left + BOARD_W / 2, y: BOARD_TOP + BOARD_H / 2 }; } + + setDanger(level) { this.danger = level; } + + setBorderGlow(on) { + if (on && !this.borderGlow) this.borderGlow = glow(this.scene, this.border, SIDE_COLOR[this.idx], 3); + } + + // per-frame cosmetic animation + update(time, delta) { + const pulse = Math.sin(time / 160); + for (const sp of this.sprites.values()) { + if (sp.tex.startsWith('bf-crash')) { + if (!this.scene.tweens.isTweening(sp.img)) sp.img.setScale(1 + pulse * 0.05); + } else if (sp.tex === 'bf-diamond') { + sp.img.setAngle(Math.sin(time / 300) * 8); + } + } + for (const img of this.pieceImgs) { + if (!img.visible) continue; + const k = img.texture.key; + if (k.startsWith('bf-crash')) img.setScale(1 + pulse * 0.06); + else if (k === 'bf-diamond') img.setAngle(Math.sin(time / 200) * 12); + } + // a slow shimmer sweeps across power gems + if (time > this.glintAt && this.powers.size) { + this.glintAt = time + 1400 + Math.random() * 1200; + const list = [...this.powers.values()]; + const pw = list[Math.floor(Math.random() * list.length)]; + pw.glint.setAlpha(0); + this.scene.tweens.add({ targets: pw.glint, alpha: 0.45, yoyo: true, duration: 260 }); + } + // danger overlay + const target = this.danger; + this.dangerT += (target - this.dangerT) * Math.min(1, delta / 120); + const beat = 0.55 + 0.45 * Math.abs(Math.sin(time / (target > 0.9 ? 140 : 260))); + this.dangerG.setAlpha(this.dangerT * beat); + this.dangerText.setAlpha(this.dangerT > 0.5 ? this.dangerT * beat : 0); + this.arrow.setAlpha(0.6 + 0.4 * Math.abs(Math.sin(time / 300))); + } + + destroy() { + for (const sp of this.sprites.values()) sp.img.destroy(); + for (const pw of this.powers.values()) { pw.ns.destroy(); pw.glint.destroy(); } + this.sprites.clear(); + this.powers.clear(); + for (const o of this.objs) { try { o.destroy(); } catch (_) {} } + this.objs = []; + this.maskG?.destroy(); + } +} diff --git a/src/games/blockfighter/BFFX.js b/src/games/blockfighter/BFFX.js new file mode 100644 index 0000000..a34b27f --- /dev/null +++ b/src/games/blockfighter/BFFX.js @@ -0,0 +1,183 @@ +// Block Fighter — juice. Particle bursts, camera shake, hit-stop, chrome +// callouts, full-screen flashes and the attack projectiles that arc from one +// board, through the arena, into the other board's garbage tray. + +import { W, H, D, ARENA, GEM_COLORS, FONT_DISPLAY } from './BFLayout.js'; +import { chromeText, glow } from './BFArt.js'; + +const PALETTE = [...GEM_COLORS, 0xffffff]; + +export class BFFX { + constructor(scene, settings = {}) { + this.scene = scene; + this.settings = settings; + this.objs = []; + this.hitstopUntil = 0; + this.calloutStack = 0; + + // one emitter set per color so bursts can share pools + this.shards = PALETTE.map((tint) => this.track(scene.add.particles(0, 0, 'bf-shard', { + emitting: false, lifespan: { min: 380, max: 720 }, speed: { min: 140, max: 420 }, + angle: { min: 0, max: 360 }, rotate: { start: 0, end: 540 }, gravityY: 900, + scale: { start: 1.1, end: 0.2 }, alpha: { start: 1, end: 0 }, tint, + }).setDepth(D.fx))); + this.sparks = PALETTE.map((tint) => this.track(scene.add.particles(0, 0, 'bf-spark', { + emitting: false, lifespan: { min: 250, max: 520 }, speed: { min: 60, max: 260 }, + angle: { min: 0, max: 360 }, scale: { start: 0.9, end: 0 }, alpha: { start: 1, end: 0 }, + blendMode: 'ADD', tint, + }).setDepth(D.fx + 1))); + this.stars = this.track(scene.add.particles(0, 0, 'bf-star', { + emitting: false, lifespan: 600, speed: { min: 30, max: 120 }, angle: { min: 0, max: 360 }, + scale: { start: 0.7, end: 0 }, rotate: { start: 0, end: 180 }, blendMode: 'ADD', + }).setDepth(D.fx + 2)); + + this.flashRect = this.track(scene.add.rectangle(W / 2, H / 2, W, H, 0xffffff, 1) + .setDepth(D.callout - 1).setAlpha(0).setBlendMode('ADD')); + } + + track(o) { this.objs.push(o); return o; } + + colorIdx(color) { + const i = GEM_COLORS.indexOf(color); + return i >= 0 ? i : 4; + } + + // ── bursts ── + shatter(x, y, color, kind) { + const i = this.colorIdx(color); + this.shards[i].explode(kind === 'crash' ? 10 : 6, x, y); + this.sparks[i].explode(kind === 'crash' ? 8 : 4, x, y); + const ring = this.scene.add.image(x, y, 'bf-ring').setTint(color).setBlendMode('ADD').setDepth(D.fx).setScale(0.2); + this.scene.tweens.add({ targets: ring, scale: 0.9, alpha: 0, duration: 300, onComplete: () => ring.destroy() }); + } + + powerShatter(x, y, w, h, color) { + const i = this.colorIdx(color); + const n = Math.round((w * h) / 1400); + for (let k = 0; k < Math.min(6, Math.ceil(n / 4)); k++) { + const px = x + (Math.random() - 0.5) * w * 0.8; + const py = y + (Math.random() - 0.5) * h * 0.8; + this.shards[i].explode(8, px, py); + this.sparks[i].explode(6, px, py); + } + const flash = this.scene.add.rectangle(x, y, w, h, 0xffffff, 0.9).setBlendMode('ADD').setDepth(D.fx); + this.scene.tweens.add({ targets: flash, alpha: 0, scaleX: 1.15, scaleY: 1.15, duration: 260, onComplete: () => flash.destroy() }); + this.stars.explode(6, x, y); + } + + fuse(x, y, w, h, color) { + const r = this.scene.add.rectangle(x, y, w, h).setStrokeStyle(4, color, 1).setDepth(D.fx).setBlendMode('ADD'); + this.scene.tweens.add({ targets: r, scaleX: 1.25, scaleY: 1.25, alpha: 0, duration: 380, onComplete: () => r.destroy() }); + this.stars.explode(4, x, y); + } + + sparkle(x, y, color, n = 4) { + this.sparks[this.colorIdx(color)].explode(n, x, y); + } + + puff(x, y, color) { + const i = this.colorIdx(color); + this.sparks[i].explode(8, x, y + 24); + } + + // ── screen ── + shake(strength) { + if (this.settings.shake === false) return; + const s = Math.min(0.022, 0.0025 + strength * 0.0011); + this.scene.cameras.main.shake(120 + strength * 12, s); + } + + hitstop(ms) { + this.hitstopUntil = Math.max(this.hitstopUntil, this.scene.time.now + ms); + } + + frozen() { return this.scene.time.now < this.hitstopUntil; } + + flash(color = 0xffffff, alpha = 0.35, ms = 220) { + this.flashRect.setFillStyle(color, 1).setAlpha(alpha); + this.scene.tweens.killTweensOf(this.flashRect); + this.scene.tweens.add({ targets: this.flashRect, alpha: 0, duration: ms }); + } + + // ── callouts ── + // style: 'chain' | 'big' | 'small' | 'announce' + callout(text, { x = ARENA.cx, y = ARENA.calloutY, color = '#ff3da8', size = 64, hold = 700, style = 'chain' } = {}) { + const s = this.scene; + const off = style === 'small' ? 0 : (this.calloutStack++ % 3) * 70; + const t = s.add.text(x, y + off, text, { + fontFamily: FONT_DISPLAY, fontSize: `${size}px`, color: '#ffffff', + stroke: '#14001f', strokeThickness: Math.max(6, size / 7), align: 'center', + }).setOrigin(0.5).setDepth(D.callout); + if (style !== 'small') chromeText(t, '#ffffff', '#ffe9fb', color); + t.setShadow(0, 0, color, 18, true, true); + glow(s, t, hexNum(color), 2); + t.setScale(style === 'announce' ? 3 : 2.2).setAlpha(0).setAngle(style === 'chain' ? -6 : 0); + s.tweens.add({ targets: t, scale: 1, alpha: 1, angle: 0, duration: 180, ease: 'Back.easeOut' }); + s.tweens.add({ + targets: t, y: t.y - 40, alpha: 0, delay: hold, duration: 320, ease: 'Quad.easeIn', + onComplete: () => { t.destroy(); this.calloutStack = Math.max(0, this.calloutStack - 1); }, + }); + return t; + } + + // ── projectiles ── + // Fires an energy orb along a high arc; resolves when it lands. + projectile(from, to, color, power, onHit) { + const s = this.scene; + const size = Math.min(2.2, 0.55 + power * 0.06); + const orb = s.add.image(from.x, from.y, 'bf-glow').setTint(color).setBlendMode('ADD').setDepth(D.projectile).setScale(size); + const core = s.add.image(from.x, from.y, 'bf-spark').setDepth(D.projectile + 1).setScale(size * 1.3); + const trail = s.add.particles(0, 0, 'bf-spark', { + follow: orb, lifespan: 320, speed: { min: 0, max: 40 }, scale: { start: size * 0.9, end: 0 }, + alpha: { start: 0.8, end: 0 }, tint: color, blendMode: 'ADD', frequency: 16, + }).setDepth(D.projectile - 1); + const midX = (from.x + to.x) / 2; + const peak = Math.min(from.y, to.y) - 220 - power * 4; + const st = { t: 0 }; + s.tweens.add({ + targets: st, t: 1, duration: 520 + Math.min(260, power * 8), ease: 'Sine.easeIn', + onUpdate: () => { + const t = st.t; + const x = (1 - t) * (1 - t) * from.x + 2 * (1 - t) * t * midX + t * t * to.x; + const y = (1 - t) * (1 - t) * from.y + 2 * (1 - t) * t * peak + t * t * to.y; + orb.setPosition(x, y); + core.setPosition(x, y).setAngle(t * 720); + }, + onComplete: () => { + trail.stop(); + s.time.delayedCall(360, () => trail.destroy()); + orb.destroy(); + core.destroy(); + const i = this.colorIdx(color); + this.sparks[i].explode(14, to.x, to.y); + this.shards[i].explode(8, to.x, to.y); + const ring = s.add.image(to.x, to.y, 'bf-ring').setTint(color).setBlendMode('ADD').setDepth(D.fx).setScale(0.3); + s.tweens.add({ targets: ring, scale: 1.6 + power * 0.03, alpha: 0, duration: 380, onComplete: () => ring.destroy() }); + onHit?.(); + }, + }); + } + + // Straight beam across the arena (super attacks). + beam(from, to, color, ms = 420) { + const s = this.scene; + const len = Math.hypot(to.x - from.x, to.y - from.y); + const ang = Math.atan2(to.y - from.y, to.x - from.x); + const b = s.add.image((from.x + to.x) / 2, (from.y + to.y) / 2, 'bf-beam') + .setRotation(ang).setTint(color).setBlendMode('ADD').setDepth(D.projectile).setScale(len / 64, 0.1); + const coreB = s.add.image(b.x, b.y, 'bf-beam').setRotation(ang).setBlendMode('ADD').setDepth(D.projectile + 1) + .setScale(len / 64, 0.45); + s.tweens.add({ targets: b, scaleY: 1.6, duration: 90, yoyo: true, hold: Math.max(0, ms - 180) }); + s.tweens.add({ targets: [b, coreB], alpha: 0, delay: ms - 100, duration: 140, onComplete: () => { b.destroy(); coreB.destroy(); } }); + this.sparks[this.colorIdx(color)].explode(20, to.x, to.y); + } + + destroy() { + for (const o of this.objs) { try { o.destroy(); } catch (_) {} } + this.objs = []; + } +} + +function hexNum(hex) { + return parseInt(String(hex).replace('#', ''), 16) || 0xffffff; +} diff --git a/src/games/blockfighter/BFHud.js b/src/games/blockfighter/BFHud.js new file mode 100644 index 0000000..f0f14e9 --- /dev/null +++ b/src/games/blockfighter/BFHud.js @@ -0,0 +1,290 @@ +// Block Fighter — battle HUD: portraits and names, round pips, the mode line +// (level / wave / timer), super meters under each board, NEXT and NEXT+1 +// previews in the outer gutters, live stats, and neon touch controls. + +import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { SUPER_MAX, SUPER_TIER } from './BlockFighterLogic.js'; +import { + W, D, BOARD_LEFT, BOARD_W, SIDE_COLOR, SIDE_HEX, SIDE_PANEL_X, NEXT_Y, STATS_Y, + PORTRAIT, SUPER_Y, TOUCH_Y, FONT_DISPLAY, FONT_BODY, ARENA, +} from './BFLayout.js'; +import { textureFor } from './BFBoard.js'; +import { chromeText, glow } from './BFArt.js'; + +export class BFHud { + // opts: { names:[p1,p2], opponent, versus, roundsToWin, superKeys:[str,str], touch, onTouch(action, down) } + constructor(scene, opts) { + this.scene = scene; + this.opts = opts; + this.objs = []; + this.portraits = []; + this.superShown = [-1, -1]; + this.superReady = [0, 0]; + + this.drawTop(); + for (const i of [0, 1]) { + this.drawNext(i); + this.drawStats(i); + this.drawSuper(i); + } + if (opts.touch) this.drawTouch(); + } + + track(o) { this.objs.push(o); return o; } + + text(x, y, str, style = {}) { + return this.track(this.scene.add.text(x, y, str, { + fontFamily: FONT_BODY, fontSize: '20px', color: '#e8dcff', ...style, + }).setDepth(D.ui)); + } + + // ── top bar ── + drawTop() { + const s = this.scene; + const { names, opponent, versus } = this.opts; + const bar = this.track(s.add.graphics().setDepth(D.ui - 1)); + bar.fillGradientStyle(0x05010f, 0x05010f, 0x05010f, 0x05010f, 0.85, 0.85, 0, 0); + bar.fillRect(0, 0, W, 150); + + // portraits + this.portraits.push(createPlayerPortrait(s, PORTRAIT.x[0], PORTRAIT.y, PORTRAIT.r, D.ui, 'BlockFighterGame')); + if (versus) { + const g = this.track(s.add.graphics().setDepth(D.ui)); + g.fillStyle(0x1a0838, 1); g.fillCircle(PORTRAIT.x[1], PORTRAIT.y, PORTRAIT.r); + g.lineStyle(3, SIDE_COLOR[1], 1); g.strokeCircle(PORTRAIT.x[1], PORTRAIT.y, PORTRAIT.r); + this.text(PORTRAIT.x[1], PORTRAIT.y, 'P2', { fontFamily: FONT_DISPLAY, fontSize: '44px', color: SIDE_HEX[1] }).setOrigin(0.5).setDepth(D.ui + 1); + this.oppPortrait = null; + } else { + this.oppPortrait = createOpponentPortrait(s, opponent, PORTRAIT.x[1], PORTRAIT.y, PORTRAIT.r, D.ui, { playIntro: false }); + this.portraits.push(this.oppPortrait); + } + for (const i of [0, 1]) { + const ring = this.track(s.add.graphics().setDepth(D.ui + 2)); + ring.lineStyle(4, SIDE_COLOR[i], 1); + ring.strokeCircle(PORTRAIT.x[i], PORTRAIT.y, PORTRAIT.r + 4); + } + + // names + const nameX = [PORTRAIT.x[0] + PORTRAIT.r + 22, PORTRAIT.x[1] - PORTRAIT.r - 22]; + this.nameTexts = names.map((n, i) => { + const t = this.text(nameX[i], 74, n.toUpperCase(), { + fontFamily: FONT_DISPLAY, fontSize: '34px', color: SIDE_HEX[i], stroke: '#05010f', strokeThickness: 6, + }).setOrigin(i === 0 ? 0 : 1, 0.5); + t.setShadow(0, 0, SIDE_HEX[i], 14, true, true); + return t; + }); + + // round pips + this.pips = [[], []]; + const rtw = this.opts.roundsToWin ?? 1; + if (rtw > 1) { + for (const i of [0, 1]) { + for (let k = 0; k < rtw; k++) { + const x = i === 0 ? nameX[0] + 14 + k * 34 : nameX[1] - 14 - k * 34; + const pip = this.track(s.add.star(x, 118, 5, 7, 15, 0x2a1050).setStrokeStyle(2, SIDE_COLOR[i], 1).setDepth(D.ui)); + this.pips[i].push(pip); + } + } + } + + this.modeText = chromeText(this.text(W / 2, 46, '', { + fontFamily: FONT_DISPLAY, fontSize: '38px', color: '#ffffff', stroke: '#14001f', strokeThickness: 6, + }).setOrigin(0.5), '#ffffff', '#c9f6ff', '#2ee6ff'); + this.subText = this.text(W / 2, 96, '', { fontSize: '22px', color: '#d6c2ff' }).setOrigin(0.5); + this.timerText = this.text(W / 2, 140, '', { + fontFamily: FONT_DISPLAY, fontSize: '40px', color: '#ffd21f', stroke: '#14001f', strokeThickness: 6, + }).setOrigin(0.5); + } + + setMode(main, sub = '') { + this.modeText.setText(main); + chromeText(this.modeText, '#ffffff', '#c9f6ff', '#2ee6ff'); + this.subText.setText(sub); + } + + setTimer(str, urgent = false) { + this.timerText.setText(str).setColor(urgent ? '#ff2e63' : '#ffd21f'); + } + + setRounds(wins) { + wins.forEach((w, i) => this.pips[i].forEach((pip, k) => { + const lit = k < w; + pip.setFillStyle(lit ? SIDE_COLOR[i] : 0x2a1050, 1); + if (lit && !pip.lit) { + pip.setScale(2); + this.scene.tweens.add({ targets: pip, scale: 1, duration: 300, ease: 'Back.easeOut' }); + } + pip.lit = lit; + })); + } + + emote(emotion) { this.oppPortrait?.playEmotion?.(emotion); } + + // ── NEXT preview ── + drawNext(i) { + const s = this.scene; + const x = SIDE_PANEL_X[i]; + const g = this.track(s.add.graphics().setDepth(D.ui - 1)); + g.fillStyle(0x05010f, 0.78); + g.fillRoundedRect(x - 62, NEXT_Y - 96, 124, 236, 14); + g.lineStyle(3, SIDE_COLOR[i], 0.9); + g.strokeRoundedRect(x - 62, NEXT_Y - 96, 124, 236, 14); + g.lineStyle(1, SIDE_COLOR[i], 0.4); + g.lineBetween(x - 50, NEXT_Y + 62, x + 50, NEXT_Y + 62); + this.text(x, NEXT_Y - 76, 'NEXT', { fontFamily: FONT_DISPLAY, fontSize: '22px', color: SIDE_HEX[i] }).setOrigin(0.5); + const big = [this.track(s.add.image(x, NEXT_Y - 16, 'bf-gem-0').setDepth(D.ui)), + this.track(s.add.image(x, NEXT_Y + 30, 'bf-gem-0').setDepth(D.ui))]; + big.forEach((b) => b.setScale(0.8)); + const small = [this.track(s.add.image(x, NEXT_Y + 86, 'bf-gem-0').setDepth(D.ui).setScale(0.45)), + this.track(s.add.image(x, NEXT_Y + 114, 'bf-gem-0').setDepth(D.ui).setScale(0.45))]; + if (!this.nextImgs) this.nextImgs = []; + this.nextImgs[i] = { big, small, x }; + } + + setNext(i, next, next2) { + const n = this.nextImgs[i]; + if (!n || !next) return; + const changed = n.big[0].texture.key !== textureFor(next.b) || n.big[1].texture.key !== textureFor(next.a); + n.big[0].setTexture(textureFor(next.b)); + n.big[1].setTexture(textureFor(next.a)); + if (next2) { n.small[0].setTexture(textureFor(next2.b)); n.small[1].setTexture(textureFor(next2.a)); } + if (changed) { + for (const img of n.big) { + img.y += 30; img.setAlpha(0); + this.scene.tweens.add({ targets: img, y: img.y - 30, alpha: 1, duration: 160, ease: 'Quad.easeOut' }); + } + } + } + + // ── stats ── + drawStats(i) { + const x = SIDE_PANEL_X[i]; + if (!this.statTexts) this.statTexts = []; + const lbl = { fontSize: '17px', color: '#a996d6' }; + const val = { fontFamily: FONT_DISPLAY, fontSize: '34px', color: '#ffffff' }; + this.text(x, STATS_Y, 'SENT', lbl).setOrigin(0.5); + const sent = this.text(x, STATS_Y + 34, '0', val).setOrigin(0.5); + this.text(x, STATS_Y + 84, 'BEST CHAIN', lbl).setOrigin(0.5); + const chain = this.text(x, STATS_Y + 118, '-', val).setOrigin(0.5); + this.text(x, STATS_Y + 168, 'POWER', lbl).setOrigin(0.5); + const power = this.text(x, STATS_Y + 202, '-', val).setOrigin(0.5); + this.statTexts[i] = { sent, chain, power, last: {} }; + } + + setStats(i, { sent, chain, power }) { + const st = this.statTexts[i]; + const bump = (t, v, key) => { + const str = String(v); + if (st.last[key] === str) return; + st.last[key] = str; + t.setText(str).setScale(1.4); + this.scene.tweens.add({ targets: t, scale: 1, duration: 200 }); + }; + bump(st.sent, sent, 'sent'); + bump(st.chain, chain > 0 ? `×${chain}` : '-', 'chain'); + bump(st.power, power > 0 ? `${power}` : '-', 'power'); + } + + // ── super meter ── + drawSuper(i) { + const s = this.scene; + const left = BOARD_LEFT[i]; + if (!this.superG) this.superG = []; + if (!this.superHint) this.superHint = []; + this.superG[i] = this.track(s.add.graphics().setDepth(D.ui)); + this.text(left, SUPER_Y - 28, 'SUPER', { fontFamily: FONT_DISPLAY, fontSize: '18px', color: SIDE_HEX[i] }).setOrigin(0, 0.5); + this.superHint[i] = this.text(left + BOARD_W, SUPER_Y - 28, '', { fontSize: '16px', color: '#ffffff' }).setOrigin(1, 0.5); + this.setSuper(i, 0, false); + } + + // value 0..SUPER_MAX; canPurge tells whether tier 1 is usable now + setSuper(i, value, canPurge) { + const v = Math.round(value); + const ready = v >= SUPER_MAX ? 3 : (v >= SUPER_TIER ? 1 : 0); + if (v === this.superShown[i] && ready === this.superReady[i] && canPurge === this.superPurge?.[i]) return ready > this.superReady[i]; + const rose = ready > this.superReady[i]; + this.superShown[i] = v; + this.superReady[i] = ready; + this.superPurge = this.superPurge ?? [false, false]; + this.superPurge[i] = canPurge; + const g = this.superG[i]; + const left = BOARD_LEFT[i]; + const segW = (BOARD_W - 12) / 3; + g.clear(); + for (let k = 0; k < 3; k++) { + const x = left + k * (segW + 6); + g.fillStyle(0x14062a, 0.95); + g.fillRoundedRect(x, SUPER_Y - 14, segW, 28, 6); + const fill = Math.max(0, Math.min(1, (v - k * SUPER_TIER) / SUPER_TIER)); + if (fill > 0) { + const full = fill >= 1; + const c = k === 2 && full ? 0xffd21f : SIDE_COLOR[i]; + g.fillStyle(c, full ? 1 : 0.55); + g.fillRoundedRect(x + 2, SUPER_Y - 12, Math.max(6, (segW - 4) * fill), 24, 5); + if (full) { g.fillStyle(0xffffff, 0.35); g.fillRoundedRect(x + 4, SUPER_Y - 10, segW - 8, 7, 3); } + } + g.lineStyle(2, SIDE_COLOR[i], 0.8); + g.strokeRoundedRect(x, SUPER_Y - 14, segW, 28, 6); + } + const keys = this.opts.superKeys?.[i]; + let hint = ''; + if (ready === 3) hint = keys ? `${keys.overdrive} OVERDRIVE` : 'OVERDRIVE READY'; + else if (ready >= 1 && canPurge) hint = keys ? `${keys.purge} PURGE` : 'PURGE READY'; + this.superHint[i].setText(hint).setColor(ready === 3 ? '#ffd21f' : '#ffffff'); + if (rose) { + this.superHint[i].setScale(1.5); + this.scene.tweens.add({ targets: this.superHint[i], scale: 1, duration: 260, ease: 'Back.easeOut' }); + } + if (this.touchSuper) this.touchSuper.setAlpha(ready >= 1 && i === 0 ? 1 : 0.45); + return rose; + } + + // ── touch controls ── + drawTouch() { + const s = this.scene; + const defs = [ + { glyph: '◀', action: 'left' }, { glyph: '▶', action: 'right' }, + { glyph: '⟲', action: 'rotateCCW' }, { glyph: '⟳', action: 'rotateCW' }, + { glyph: '▼', action: 'softDrop' }, { glyph: '⤓', action: 'hardDrop' }, + { glyph: '★', action: 'super' }, + ]; + const gap = 84; + const x0 = ARENA.cx - ((defs.length - 1) * gap) / 2; + defs.forEach((def, k) => { + const x = x0 + k * gap; + const isSuper = def.action === 'super'; + const g = this.track(s.add.graphics().setDepth(D.touch)); + const col = isSuper ? 0xffd21f : 0x2ee6ff; + g.fillStyle(0x0a0320, 0.85); + g.fillCircle(x, TOUCH_Y, 36); + g.lineStyle(3, col, 0.9); + g.strokeCircle(x, TOUCH_Y, 36); + const t = this.text(x, TOUCH_Y, def.glyph, { fontFamily: FONT_DISPLAY, fontSize: '30px', color: isSuper ? '#ffd21f' : '#e8fbff' }) + .setOrigin(0.5).setDepth(D.touch + 1); + if (isSuper) { this.touchSuper = t; t.setAlpha(0.45); } + const zone = this.track(s.add.zone(x, TOUCH_Y, 80, 80).setInteractive({ useHandCursor: true }).setDepth(D.touch + 2)); + const press = () => { g.setAlpha(0.6); this.opts.onTouch?.(def.action, true); }; + const release = () => { g.setAlpha(1); this.opts.onTouch?.(def.action, false); }; + zone.on('pointerdown', press); + zone.on('pointerup', release); + zone.on('pointerout', release); + }); + } + + flashName(i) { + const t = this.nameTexts[i]; + t.setScale(1.25); + this.scene.tweens.add({ targets: t, scale: 1, duration: 260 }); + } + + glowNames() { + this.nameTexts.forEach((t, i) => glow(this.scene, t, SIDE_COLOR[i], 1.5)); + } + + destroy() { + for (const p of this.portraits) { try { p.destroy(); } catch (_) {} } + this.portraits = []; + for (const o of this.objs) { try { o.destroy(); } catch (_) {} } + this.objs = []; + } +} diff --git a/src/games/blockfighter/BFLayout.js b/src/games/blockfighter/BFLayout.js new file mode 100644 index 0000000..dbe2a51 --- /dev/null +++ b/src/games/blockfighter/BFLayout.js @@ -0,0 +1,65 @@ +// Block Fighter — screen layout for the 1920×1080 canvas. Every coordinate the +// battle screen uses lives here so the modules agree on where things are. +// +// ┌──────────────── top bar: portraits · names · round pips · mode ───────────────┐ +// │ NEXT │ P1 board │ arena (avatar duel) │ P2 board │ NEXT │ +// │ stats│ │ sun · grid floor · two gem-golems │ │ stats│ +// │ │ super bar │ touch controls │ super bar │ │ +// └──────────────────────────────────────────────────────────────────────────────┘ + +import { WIDTH, VISIBLE_ROWS, HIDDEN_ROWS } from './BlockFighterLogic.js'; + +export const W = 1920; +export const H = 1080; + +export const CELL = 60; +export const BOARD_W = CELL * WIDTH; // 360 +export const BOARD_H = CELL * VISIBLE_ROWS; // 720 +export const BOARD_TOP = 196; +export const BOARD_MARGIN = 290; +export const BOARD_LEFT = [BOARD_MARGIN, W - BOARD_MARGIN - BOARD_W]; // 290, 1270 +export const BOARD_BOTTOM = BOARD_TOP + BOARD_H; // 916 + +export const SIDE_COLOR = [0x2ee6ff, 0xff3da8]; // P1 cyan, P2 magenta +export const SIDE_HEX = ['#2ee6ff', '#ff3da8']; + +// Centre arena between the boards. +export const ARENA = { + left: BOARD_LEFT[0] + BOARD_W, // 650 + right: BOARD_LEFT[1], // 1270 + cx: W / 2, + floorY: 770, + fighterX: [W / 2 - 150, W / 2 + 150], + calloutY: 330, +}; + +// Outer gutters (NEXT previews, stats). +export const SIDE_PANEL_X = [BOARD_LEFT[0] / 2 - 4, W - BOARD_LEFT[0] / 2 + 4]; // 141, 1779 +export const NEXT_Y = 300; +export const STATS_Y = 560; + +export const PORTRAIT = { y: 112, r: 54, x: [140, W - 140] }; +export const TRAY_Y = BOARD_TOP - 34; // incoming-garbage tray above each board +export const SUPER_Y = BOARD_BOTTOM + 60; // super meter under each board +export const TOUCH_Y = 1010; + +export const D = { + bg: -20, bgFx: -18, floor: -15, arena: -10, fighter: -5, + frame: -2, grid: -1, ghost: 1, cells: 5, power: 6, piece: 8, danger: 10, + fx: 20, projectile: 24, callout: 28, ui: 30, touch: 34, + overlay: 60, overlayUI: 62, top: 80, +}; + +export const cellX = (left, c) => left + c * CELL + CELL / 2; +export const cellY = (r) => BOARD_TOP + (r - HIDDEN_ROWS) * CELL + CELL / 2; + +// Neon gem palette (index = engine color 0 red, 1 green, 2 blue, 3 yellow). +export const GEM_COLORS = [0xff2e63, 0x2bff88, 0x2f9bff, 0xffd21f]; +export const GEM_HEX = ['#ff2e63', '#2bff88', '#2f9bff', '#ffd21f']; +export const GEM_LIGHT = ['#ff9db6', '#b5ffd6', '#a9d6ff', '#fff0a6']; +export const GEM_DARK = ['#6e0420', '#036332', '#062f73', '#7a5600']; +export const GEM_NAMES = ['RED', 'GREEN', 'BLUE', 'GOLD']; + +export const FONT_DISPLAY = 'Righteous'; +export const FONT_BODY = '"Julius Sans One"'; +export const FONT_PIXEL = 'm6x11'; diff --git a/src/games/blockfighter/BFModes.js b/src/games/blockfighter/BFModes.js new file mode 100644 index 0000000..ca4cad8 --- /dev/null +++ b/src/games/blockfighter/BFModes.js @@ -0,0 +1,70 @@ +// Block Fighter — game modes. Each describes how a "fight" is set up and when +// it ends; the scene asks the mode for opponents, rounds and scoring. +// +// ladder the 20-fighter ladder, best of 3 rounds, saves progress +// survival endless waves; each wave is a fresh board against a tougher +// fighter; your super meter carries over; one loss ends the run +// rush 2 minutes vs a counter-punching sandbag; score = total attack; +// knocking the sandbag out refills its board for a bonus +// versus two players on one keyboard, best of 3 + +import { PERSONALITIES } from './BlockFighterAI.js'; + +export const MODES = { + ladder: { + id: 'ladder', title: 'LADDER', blurb: 'Climb 20 fighters. Best of three rounds.', + roundsToWin: 2, ai: true, saveProgress: true, + }, + survival: { + id: 'survival', title: 'SURVIVAL', blurb: 'Endless waves. Your super meter carries over.', + roundsToWin: 1, ai: true, + }, + rush: { + id: 'rush', title: 'GARBAGE RUSH', blurb: 'Two minutes. Send as much as you can.', + roundsToWin: 1, ai: true, timeLimitMs: 120000, + }, + versus: { + id: 'versus', title: 'LOCAL VERSUS', blurb: 'Two players, one keyboard. Best of three.', + roundsToWin: 2, ai: false, + }, +}; + +export const RUSH_KO_BONUS = 25; + +// Survival wave n (1-based) → fight parameters. +export function survivalWave(n, roster) { + const skill = Math.min(10, 1 + Math.floor((n - 1) * 0.75)); + const speed = Math.min(5, 1 + Math.floor((n - 1) / 3)); + const personality = PERSONALITIES[(n * 3) % PERSONALITIES.length]; + const pool = roster.length ? roster : [{ id: 'rival', name: 'Rival', spriteIndex: 0, speech: {} }]; + const opponent = pool[(n * 7 + 3) % pool.length]; + return { + skill, speed, personality, opponent, + tagline: `Wave ${n}`, + dropPattern: null, + stage: ['#ff3da8', '#2ee6ff', '#b86bff', '#ffd21f', '#2bff88'][n % 5], + }; +} + +export function rushSetup(roster) { + const opponent = roster.find((o) => o.id === 'bernie') ?? roster[0] ?? { id: 'sandbag', name: 'Sandbag', spriteIndex: 0, speech: {} }; + return { + skill: 3, speed: 2, personality: 'turtle', opponent: { ...opponent, name: 'Sandbag' }, + tagline: 'It hits back. A little.', dropPattern: null, stage: '#ffd21f', + }; +} + +// Letter grade for the results screen. +export function rankFor({ won, sent, bestChain, bestPower, seconds }) { + let pts = 0; + pts += Math.min(40, sent * 0.8); + pts += Math.min(25, (bestChain - 1) * 8); + pts += Math.min(15, bestPower * 0.8); + pts += won ? 20 : 0; + if (seconds > 0) pts += Math.min(10, (sent / seconds) * 20); + if (pts >= 85) return 'S'; + if (pts >= 68) return 'A'; + if (pts >= 50) return 'B'; + if (pts >= 32) return 'C'; + return 'D'; +} diff --git a/src/games/blockfighter/BFScreens.js b/src/games/blockfighter/BFScreens.js new file mode 100644 index 0000000..2a5313a --- /dev/null +++ b/src/games/blockfighter/BFScreens.js @@ -0,0 +1,333 @@ +// Block Fighter — menus and overlays in the neon arcade style: mode select, +// ladder, VS splash, settings, pause, confirm and results. Each function +// builds its objects through scene.track() so the scene can clear a screen +// in one call; golems returned in scene.menuGolems are animated by the scene. + +import { W, H, D, SIDE_COLOR, SIDE_HEX, FONT_DISPLAY, FONT_BODY } from './BFLayout.js'; +import { chromeText, glow } from './BFArt.js'; +import { makeGolem } from './BFArena.js'; +import { createOpponentPortrait } from '../../ui/Portrait.js'; +import * as SFX from './BFSound.js'; + +const hexNum = (h) => parseInt(String(h ?? '#ff3da8').replace('#', ''), 16); + +// ── primitives ─────────────────────────────────────────────────────────────── +export function neonButton(scene, x, y, label, onClick, { + w = 280, h = 64, color = 0x2ee6ff, size = 26, depth = D.ui, ghost = false, disabled = false, +} = {}) { + const c = scene.add.container(x, y).setDepth(depth); + const g = scene.add.graphics(); + const draw = (hover) => { + g.clear(); + g.fillStyle(hover ? color : 0x0a0320, hover ? 1 : (ghost ? 0.55 : 0.9)); + g.fillRoundedRect(-w / 2, -h / 2, w, h, 12); + g.lineStyle(3, color, disabled ? 0.35 : 1); + g.strokeRoundedRect(-w / 2, -h / 2, w, h, 12); + if (!hover) { g.lineStyle(1, 0xffffff, 0.25); g.strokeRoundedRect(-w / 2 + 4, -h / 2 + 4, w - 8, h - 8, 9); } + }; + draw(false); + const t = scene.add.text(0, 0, label, { + fontFamily: FONT_DISPLAY, fontSize: `${size}px`, color: disabled ? '#6d5f8f' : '#f2ecff', + }).setOrigin(0.5); + if (t.width > w - 20) t.setScale((w - 20) / t.width); + c.add([g, t]); + if (!disabled) { + const zone = scene.add.zone(0, 0, w, h).setInteractive({ useHandCursor: true }); + c.add(zone); + zone.on('pointerover', () => { draw(true); t.setColor('#05010f'); SFX.menu(scene); }); + zone.on('pointerout', () => { draw(false); t.setColor('#f2ecff'); c.setScale(1); }); + zone.on('pointerdown', () => c.setScale(0.96)); + zone.on('pointerup', () => { c.setScale(1); SFX.select(scene); onClick?.(); }); + } + return scene.track(c); +} + +function panel(scene, x, y, w, h, color = 0xff3da8, depth = D.overlay) { + const g = scene.track(scene.add.graphics().setDepth(depth)); + g.fillStyle(0x07021a, 0.96); + g.fillRoundedRect(x - w / 2, y - h / 2, w, h, 22); + g.lineStyle(4, color, 1); + g.strokeRoundedRect(x - w / 2, y - h / 2, w, h, 22); + g.lineStyle(1, 0xffffff, 0.3); + g.strokeRoundedRect(x - w / 2 + 6, y - h / 2 + 6, w - 12, h - 12, 18); + return g; +} + +function dim(scene, alpha = 0.7) { + return scene.track(scene.add.rectangle(W / 2, H / 2, W, H, 0x05010f, alpha).setDepth(D.overlay).setInteractive()); +} + +function label(scene, x, y, str, style = {}, depth = D.ui) { + return scene.track(scene.add.text(x, y, str, { + fontFamily: FONT_BODY, fontSize: '22px', color: '#d6c2ff', align: 'center', ...style, + }).setOrigin(0.5).setDepth(depth)); +} + +function bigTitle(scene, x, y, str, size = 120, low = '#ff3da8', depth = D.ui) { + const t = scene.track(scene.add.text(x, y, str, { + fontFamily: FONT_DISPLAY, fontSize: `${size}px`, color: '#ffffff', stroke: '#14001f', strokeThickness: Math.round(size / 9), + }).setOrigin(0.5).setDepth(depth)); + chromeText(t, '#ffffff', '#ffe9fb', low); + t.setShadow(0, 0, low, 26, true, true); + return t; +} + +// ── mode select ────────────────────────────────────────────────────────────── +export function showModeSelect(scene, { modes, bests, levelsCompleted, total, onPick, onSettings, onBack }) { + const title = bigTitle(scene, W / 2, 190, 'BLOCK FIGHTER', 132); + title.setScale(0.6).setAlpha(0); + scene.tweens.add({ targets: title, scale: 1, alpha: 1, duration: 500, ease: 'Back.easeOut' }); + glow(scene, title, 0xff3da8, 2); + label(scene, W / 2, 292, 'CRASH · FUSE · CHAIN · BURY YOUR RIVAL', { fontSize: '26px', color: '#c9f6ff', stroke: '#14001f', strokeThickness: 7 }); + + scene.menuGolems = [ + makeGolem(scene, 250, 900, 1, SIDE_COLOR[0], 0, 1.25, D.fighter), + makeGolem(scene, W - 250, 900, -1, SIDE_COLOR[1], 2, 1.25, D.fighter), + ]; + + const cards = [ + { id: 'ladder', color: 0x2ee6ff, icon: '⚔', stat: `Defeated ${levelsCompleted} / ${total}` }, + { id: 'survival', color: 0x2bff88, icon: '∞', stat: bests.survival ? `Best: wave ${bests.survival}` : 'No run yet' }, + { id: 'rush', color: 0xffd21f, icon: '⏱', stat: bests.rush ? `Best: ${bests.rush} sent` : 'No score yet' }, + { id: 'versus', color: 0xff3da8, icon: '👥', stat: 'P1: WASD · F G · R\nP2: ← → ↑ ↓ · , . · /' }, + ]; + const cw = 300, ch = 330, gap = 28; + const x0 = W / 2 - ((cards.length - 1) * (cw + gap)) / 2; + cards.forEach((card, k) => { + const m = modes[card.id]; + const x = x0 + k * (cw + gap); + const y = 600; + const c = scene.track(scene.add.container(x, y + 60).setDepth(D.ui).setAlpha(0)); + scene.tweens.add({ targets: c, y, alpha: 1, delay: 120 + k * 70, duration: 360, ease: 'Back.easeOut' }); + const g = scene.add.graphics(); + const draw = (hover) => { + g.clear(); + g.fillStyle(hover ? 0x1a0838 : 0x0a0320, 0.92); + g.fillRoundedRect(-cw / 2, -ch / 2, cw, ch, 18); + g.fillStyle(card.color, hover ? 0.24 : 0.12); + g.fillRoundedRect(-cw / 2, -ch / 2, cw, 110, { tl: 18, tr: 18, bl: 0, br: 0 }); + g.lineStyle(hover ? 5 : 3, card.color, 1); + g.strokeRoundedRect(-cw / 2, -ch / 2, cw, ch, 18); + }; + draw(false); + const icon = scene.add.text(0, -ch / 2 + 56, card.icon, { fontFamily: FONT_DISPLAY, fontSize: '58px', color: '#ffffff' }).setOrigin(0.5); + const t = scene.add.text(0, -24, m.title, { fontFamily: FONT_DISPLAY, fontSize: '34px', color: '#ffffff' }).setOrigin(0.5); + t.setShadow(0, 0, `#${card.color.toString(16).padStart(6, '0')}`, 14, true, true); + const b = scene.add.text(0, 34, m.blurb, { + fontFamily: FONT_BODY, fontSize: '19px', color: '#d6c2ff', align: 'center', wordWrap: { width: cw - 40 }, + }).setOrigin(0.5); + const st = scene.add.text(0, ch / 2 - 46, card.stat, { + fontFamily: FONT_BODY, fontSize: '17px', color: `#${card.color.toString(16).padStart(6, '0')}`, align: 'center', + }).setOrigin(0.5); + const zone = scene.add.zone(0, 0, cw, ch).setInteractive({ useHandCursor: true }); + c.add([g, icon, t, b, st, zone]); + zone.on('pointerover', () => { draw(true); scene.tweens.add({ targets: c, scale: 1.05, duration: 120 }); SFX.menu(scene); }); + zone.on('pointerout', () => { draw(false); scene.tweens.add({ targets: c, scale: 1, duration: 120 }); }); + zone.on('pointerup', () => { SFX.select(scene); onPick(card.id); }); + }); + + neonButton(scene, W / 2 - 160, H - 110, 'Settings', onSettings, { w: 260, h: 60, color: 0xb86bff, size: 24 }); + neonButton(scene, W / 2 + 160, H - 110, 'Back', onBack, { w: 260, h: 60, color: 0xb86bff, size: 24, ghost: true }); +} + +// ── ladder ─────────────────────────────────────────────────────────────────── +export function showLadder(scene, { bank, levelsCompleted, opponentFor, canPersist, onPick, onBack, onReset }) { + bigTitle(scene, W / 2, 110, 'THE LADDER', 84, '#2ee6ff'); + label(scene, W / 2, 182, `Defeated ${levelsCompleted} / ${bank.length} · best of three rounds`, { fontSize: '24px', color: '#9fe9ff' }); + const nextLevel = Math.min(levelsCompleted + 1, bank.length); + const COLS = 10, SIZE = 140, GAP = 18; + const gridW = COLS * SIZE + (COLS - 1) * GAP; + const left = W / 2 - gridW / 2 + SIZE / 2; + bank.forEach((lv, i) => { + const col = i % COLS, row = Math.floor(i / COLS); + const x = left + col * (SIZE + GAP); + const y = 370 + row * (SIZE + 90); + const cleared = lv.level <= levelsCompleted; + const playable = lv.level <= nextLevel; + const opp = opponentFor(lv); + const hue = hexNum(lv.stage); + const c = scene.track(scene.add.container(x, y).setDepth(D.ui).setAlpha(0)); + scene.tweens.add({ targets: c, alpha: 1, delay: i * 25, duration: 220 }); + const g = scene.add.graphics(); + const stroke = cleared ? 0x2bff88 : playable ? hue : 0x3a2a5a; + const draw = (hover) => { + g.clear(); + g.fillStyle(playable ? 0x120530 : 0x0a0318, 0.92); + g.fillRoundedRect(-SIZE / 2, -SIZE / 2, SIZE, SIZE + 50, 14); + g.lineStyle(hover ? 5 : 3, stroke, playable || cleared ? 1 : 0.5); + g.strokeRoundedRect(-SIZE / 2, -SIZE / 2, SIZE, SIZE + 50, 14); + }; + draw(false); + const objs = [g]; + objs.push(scene.add.text(-SIZE / 2 + 12, -SIZE / 2 + 8, String(lv.level), { + fontFamily: FONT_DISPLAY, fontSize: '24px', color: playable || cleared ? '#ffffff' : '#5b4c7a', + })); + if (scene.textures.exists('opponents')) { + const face = scene.add.image(0, 8, 'opponents', opp.spriteIndex ?? 0).setDisplaySize(92, 92); + if (!playable) face.setTint(0x2a2440).setAlpha(0.7); + objs.push(face); + } + objs.push(scene.add.text(0, SIZE / 2 + 4, playable || cleared ? opp.name : 'LOCKED', { + fontFamily: FONT_BODY, fontSize: '15px', color: cleared ? '#9dffc8' : playable ? '#ffffff' : '#5b4c7a', + }).setOrigin(0.5)); + objs.push(scene.add.text(0, SIZE / 2 + 26, playable || cleared ? (lv.personality ?? 'balanced').toUpperCase() : '', { + fontFamily: FONT_BODY, fontSize: '12px', color: `#${hue.toString(16).padStart(6, '0')}`, + }).setOrigin(0.5)); + if (cleared) objs.push(scene.add.text(SIZE / 2 - 12, -SIZE / 2 + 8, '✓', { fontFamily: FONT_DISPLAY, fontSize: '24px', color: '#2bff88' }).setOrigin(1, 0)); + c.add(objs); + if (playable) { + const zone = scene.add.zone(0, 25, SIZE, SIZE + 50).setInteractive({ useHandCursor: true }); + c.add(zone); + zone.on('pointerover', () => { draw(true); c.setScale(1.06); SFX.menu(scene); }); + zone.on('pointerout', () => { draw(false); c.setScale(1); }); + zone.on('pointerup', () => { SFX.select(scene); onPick(lv.level); }); + } + }); + neonButton(scene, W / 2, H - 120, `FIGHT LEVEL ${nextLevel}`, () => onPick(nextLevel), { w: 360, h: 70, color: 0x2ee6ff, size: 30 }); + neonButton(scene, W / 2 + 330, H - 120, 'Back', onBack, { w: 200, h: 60, color: 0xb86bff, size: 24, ghost: true }); + neonButton(scene, W / 2 - 360, H - 120, 'Reset Progress', onReset, { w: 240, h: 60, color: 0xff2e63, size: 22, ghost: true }); + if (!canPersist) label(scene, W / 2, H - 50, 'Sign in to save your progress across devices.', { fontSize: '18px', color: '#a996d6' }); +} + +// ── VS splash ──────────────────────────────────────────────────────────────── +export function showVs(scene, { p1Name, p2Name, opponent, stage, tagline, info, versus, headStyle, onFight, onBack }) { + const hue = hexNum(stage); + // diagonal split panels + const g = scene.track(scene.add.graphics().setDepth(D.ui - 2)); + g.fillStyle(SIDE_COLOR[0], 0.16); + g.fillPoints([{ x: 0, y: 150 }, { x: W / 2 + 80, y: 150 }, { x: W / 2 - 80, y: 870 }, { x: 0, y: 870 }], true); + g.fillStyle(hue, 0.16); + g.fillPoints([{ x: W / 2 + 80, y: 150 }, { x: W, y: 150 }, { x: W, y: 870 }, { x: W / 2 - 80, y: 870 }], true); + const bolt = scene.track(scene.add.graphics().setDepth(D.ui - 1)); + bolt.lineStyle(6, 0xffffff, 1); + bolt.beginPath(); + const pts = [[W / 2 + 80, 150], [W / 2 + 30, 380], [W / 2 + 60, 400], [W / 2 - 20, 640], [W / 2 + 10, 660], [W / 2 - 80, 870]]; + pts.forEach(([x, y], i) => (i ? bolt.lineTo(x, y) : bolt.moveTo(x, y))); + bolt.strokePath(); + glow(scene, bolt, 0xffffff, 4); + scene.tweens.add({ targets: bolt, alpha: 0.4, yoyo: true, repeat: -1, duration: 90, repeatDelay: 900 }); + + const g1 = makeGolem(scene, -200, 760, 1, SIDE_COLOR[0], 0, 1.8, D.ui); + const g2 = makeGolem(scene, W + 200, 760, -1, versus ? SIDE_COLOR[1] : hue, headStyle ?? 1, 1.8, D.ui); + scene.menuGolems = [g1, g2]; + scene.tweens.add({ targets: g1, baseX: 470, duration: 520, ease: 'Back.easeOut' }); + scene.tweens.add({ targets: g2, baseX: W - 470, duration: 520, ease: 'Back.easeOut' }); + + const n1 = scene.track(scene.add.text(110, 230, p1Name.toUpperCase(), { + fontFamily: FONT_DISPLAY, fontSize: '64px', color: SIDE_HEX[0], stroke: '#05010f', strokeThickness: 8, + }).setDepth(D.ui)); + n1.setShadow(0, 0, SIDE_HEX[0], 18, true, true); + const n2 = scene.track(scene.add.text(W - 110, 230, p2Name.toUpperCase(), { + fontFamily: FONT_DISPLAY, fontSize: '64px', color: stage ?? SIDE_HEX[1], stroke: '#05010f', strokeThickness: 8, + }).setOrigin(1, 0).setDepth(D.ui)); + n2.setShadow(0, 0, stage ?? SIDE_HEX[1], 18, true, true); + scene.tweens.add({ targets: n1, x: { from: -400, to: 110 }, duration: 420, ease: 'Quad.easeOut' }); + scene.tweens.add({ targets: n2, x: { from: W + 400, to: W - 110 }, duration: 420, ease: 'Quad.easeOut' }); + + if (!versus && opponent) { + scene.portraits.push(createOpponentPortrait(scene, opponent, W - 250, 420, 110, D.ui, { playIntro: true })); + } + + const vsGlow = scene.track(scene.add.image(W / 2, 470, 'bf-glow').setTint(0x14001f).setScale(4.2, 2.6).setAlpha(0.85).setDepth(D.ui + 1)); + vsGlow.setBlendMode('NORMAL'); + const vs = bigTitle(scene, W / 2, 470, 'VS', 170, '#ff3da8', D.ui + 2); + vs.setScale(3).setAlpha(0); + scene.tweens.add({ targets: vs, scale: 1, alpha: 1, delay: 380, duration: 260, ease: 'Back.easeOut', onStart: () => SFX.ready(scene) }); + + if (tagline) label(scene, W / 2, 640, `“${tagline}”`, { fontSize: '28px', color: '#ffe9fb', fontStyle: 'italic', stroke: '#14001f', strokeThickness: 6 }, D.ui + 2); + if (info) label(scene, W / 2, 900, info, { fontSize: '24px', color: '#c9f6ff', stroke: '#14001f', strokeThickness: 6 }, D.ui + 2); + + neonButton(scene, W / 2 - 130, H - 120, 'FIGHT!', onFight, { w: 260, h: 74, color: 0xffd21f, size: 34, depth: D.ui + 3 }); + neonButton(scene, W / 2 + 130, H - 120, 'Back', onBack, { w: 200, h: 62, color: 0xb86bff, size: 24, ghost: true, depth: D.ui + 3 }); +} + +// ── overlays ───────────────────────────────────────────────────────────────── +export function showConfirm(scene, { title, message, yes, onYes, onNo, color = 0xff2e63 }) { + dim(scene); + panel(scene, W / 2, H / 2, 700, 340, color); + bigTitle(scene, W / 2, H / 2 - 96, title, 54, `#${color.toString(16).padStart(6, '0')}`, D.overlayUI); + label(scene, W / 2, H / 2 - 10, message, { fontSize: '24px', color: '#f2ecff', lineSpacing: 6 }, D.overlayUI); + neonButton(scene, W / 2 - 150, H / 2 + 100, yes, onYes, { w: 250, h: 60, color, depth: D.overlayUI }); + neonButton(scene, W / 2 + 150, H / 2 + 100, 'Cancel', onNo, { w: 250, h: 60, color: 0xb86bff, ghost: true, depth: D.overlayUI }); +} + +export function showPause(scene, { onResume, onRestart, onQuit, controls }) { + dim(scene, 0.75); + panel(scene, W / 2, H / 2, 760, 600, 0x2ee6ff); + bigTitle(scene, W / 2, H / 2 - 220, 'PAUSED', 72, '#2ee6ff', D.overlayUI); + label(scene, W / 2, H / 2 - 90, controls, { fontSize: '20px', color: '#d6c2ff', lineSpacing: 8 }, D.overlayUI); + neonButton(scene, W / 2, H / 2 + 60, 'Resume', onResume, { w: 300, h: 62, color: 0x2ee6ff, depth: D.overlayUI }); + if (onRestart) neonButton(scene, W / 2, H / 2 + 140, 'Restart', onRestart, { w: 300, h: 58, color: 0xffd21f, ghost: true, depth: D.overlayUI }); + neonButton(scene, W / 2, H / 2 + 216, 'Quit to Menu', onQuit, { w: 300, h: 58, color: 0xff2e63, ghost: true, depth: D.overlayUI }); +} + +export function showSettings(scene, { settings, onChange, onClose }) { + dim(scene, 0.78); + panel(scene, W / 2, H / 2, 820, 640, 0xb86bff); + bigTitle(scene, W / 2, H / 2 - 250, 'SETTINGS', 64, '#b86bff', D.overlayUI); + const rows = [ + { key: 'das', name: 'Auto-repeat delay', values: [90, 120, 150, 190, 240], fmt: (v) => `${v} ms` }, + { key: 'arr', name: 'Auto-repeat speed', values: [20, 33, 45, 70, 100], fmt: (v) => `${v} ms` }, + { key: 'ghost', name: 'Landing ghost', values: [true, false], fmt: (v) => (v ? 'ON' : 'OFF') }, + { key: 'shake', name: 'Screen shake', values: [true, false], fmt: (v) => (v ? 'ON' : 'OFF') }, + { key: 'sfx', name: 'Sound effects', values: [true, false], fmt: (v) => (v ? 'ON' : 'OFF') }, + ]; + rows.forEach((row, k) => { + const y = H / 2 - 150 + k * 78; + label(scene, W / 2 - 330, y, row.name, { fontSize: '26px', color: '#f2ecff' }, D.overlayUI).setOrigin(0, 0.5); + const val = label(scene, W / 2 + 230, y, row.fmt(settings[row.key]), { + fontFamily: FONT_DISPLAY, fontSize: '28px', color: '#ffd21f', + }, D.overlayUI); + const step = (dir) => { + const i = row.values.indexOf(settings[row.key]); + const n = row.values[(Math.max(0, i) + dir + row.values.length) % row.values.length]; + settings[row.key] = n; + val.setText(row.fmt(n)); + onChange(settings); + }; + neonButton(scene, W / 2 + 110, y, '◀', () => step(-1), { w: 56, h: 52, color: 0xb86bff, size: 22, depth: D.overlayUI }); + neonButton(scene, W / 2 + 350, y, '▶', () => step(1), { w: 56, h: 52, color: 0xb86bff, size: 22, depth: D.overlayUI }); + }); + neonButton(scene, W / 2, H / 2 + 250, 'Done', onClose, { w: 260, h: 62, color: 0xb86bff, depth: D.overlayUI }); +} + +// data: { title, won, lines:[[label, value]], rank, note, buttons:[{label, onClick, color, primary}] } +export function showResults(scene, data) { + dim(scene, 0.72); + const color = data.won ? 0xffd21f : 0xff2e63; + panel(scene, W / 2, H / 2, 860, 720, color); + const t = bigTitle(scene, W / 2, H / 2 - 270, data.title, 96, data.won ? '#ffd21f' : '#ff2e63', D.overlayUI); + t.setScale(2).setAlpha(0); + scene.tweens.add({ targets: t, scale: 1, alpha: 1, duration: 300, ease: 'Back.easeOut' }); + if (data.subtitle) label(scene, W / 2, H / 2 - 190, data.subtitle, { fontSize: '26px', color: '#f2ecff' }, D.overlayUI); + + if (data.rank) { + const rc = { S: '#ffd21f', A: '#2bff88', B: '#2ee6ff', C: '#b86bff', D: '#ff2e63' }[data.rank]; + const r = scene.track(scene.add.text(W / 2 + 290, H / 2 - 40, data.rank, { + fontFamily: FONT_DISPLAY, fontSize: '150px', color: rc, stroke: '#05010f', strokeThickness: 10, + }).setOrigin(0.5).setDepth(D.overlayUI)); + r.setShadow(0, 0, rc, 30, true, true); + r.setScale(0).setAngle(-30); + scene.tweens.add({ targets: r, scale: 1, angle: -8, delay: 500, duration: 360, ease: 'Back.easeOut', onStart: () => SFX.impact(scene, 6) }); + label(scene, W / 2 + 290, H / 2 + 60, 'RANK', { fontSize: '20px', color: '#a996d6' }, D.overlayUI); + } + + (data.lines ?? []).forEach(([k, v], i) => { + const y = H / 2 - 120 + i * 50; + const a = label(scene, W / 2 - 340, y, k, { fontSize: '24px', color: '#a996d6' }, D.overlayUI).setOrigin(0, 0.5); + const b = label(scene, W / 2 + 120, y, String(v), { fontFamily: FONT_DISPLAY, fontSize: '30px', color: '#ffffff' }, D.overlayUI).setOrigin(1, 0.5); + for (const o of [a, b]) { + o.setAlpha(0); + scene.tweens.add({ targets: o, alpha: 1, delay: 200 + i * 90, duration: 200 }); + } + }); + if (data.note) label(scene, W / 2, H / 2 + 190, data.note, { fontSize: '24px', color: '#ffd21f' }, D.overlayUI); + + const btns = data.buttons ?? []; + const bw = btns.length > 2 ? 250 : 290; + const x0 = W / 2 - ((btns.length - 1) * (bw + 20)) / 2; + btns.forEach((b, i) => neonButton(scene, x0 + i * (bw + 20), H / 2 + 280, b.label, b.onClick, { + w: bw, h: 64, color: b.color ?? (b.primary ? 0xffd21f : 0xb86bff), ghost: !b.primary, size: 24, depth: D.overlayUI, + })); +} + diff --git a/src/games/blockfighter/BFSound.js b/src/games/blockfighter/BFSound.js new file mode 100644 index 0000000..281c87e --- /dev/null +++ b/src/games/blockfighter/BFSound.js @@ -0,0 +1,182 @@ +// Block Fighter — Web Audio synths for the neon arcade. No audio files; silent +// without Web Audio or when the game is muted. Every call is wrapped so audio +// can never break the game. +// +// move / rotate crisp UI ticks while steering the pair +// lock / slam a soft thud on landing, a heavy one on hard drop +// shatter(chain) glass burst plus a bell that climbs with chain length +// fuse(size) shimmering sweep as a power gem forms or grows +// whoosh / impact(pow) an attack leaving and landing +// garbage(n) counter gems raining in +// counterTick counters stepping down +// heartbeat danger pulse (call on a timer while in danger) +// superCharge / superFire meter full, super unleashed +// ready / fight / ko announcer stings +// sting('win'|'lose') end-of-match +// menu / select menu blips + +function ctxOf(scene) { + const sm = scene?.sound; + if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null; + return sm.context; +} +const noiseCache = new WeakMap(); +function noise(ac) { + if (noiseCache.has(ac)) return noiseCache.get(ac); + const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + noiseCache.set(ac, buf); + return buf; +} +function out(scene, ac, gain) { + const sm = scene.sound; + const node = sm.masterVolumeNode ?? sm.destination ?? null; + const g = ac.createGain(); + g.gain.value = node ? gain : gain * (sm.volume ?? 1); + g.connect(node ?? ac.destination); + return g; +} +function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.004, detune = 0 } = {}) { + const o = ac.createOscillator(); o.type = type; + o.detune.value = detune; + o.frequency.setValueAtTime(f, t0); + if (glide !== 1) o.frequency.exponentialRampToValueAtTime(Math.max(20, f * glide), t0 + d); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(a, t0 + attack); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.05); +} +function hiss(ac, dest, t0, { f = 1000, q = 1, type = 'bandpass', a = 1, d = 0.2, attack = 0.003, fEnd = null } = {}) { + const n = ac.createBufferSource(); n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = type; bp.frequency.setValueAtTime(f, t0); bp.Q.value = q; + if (fEnd) bp.frequency.exponentialRampToValueAtTime(fEnd, t0 + d); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(a, t0 + attack); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + n.connect(bp); bp.connect(g); g.connect(dest); + n.start(t0, Math.random() * 1.5); n.stop(t0 + d + 0.05); +} +const play = (scene, gain, fn) => { + try { + if (scene?.bfSfxOff) return; + const ac = ctxOf(scene); if (!ac) return; + fn(ac, out(scene, ac, gain), ac.currentTime + 0.005); + } catch (_) { /* decoration */ } +}; + +// pentatonic ladder for chain pitches +const SCALE = [0, 3, 5, 7, 10, 12, 15, 17, 19, 22, 24, 27]; +const note = (base, step) => base * Math.pow(2, SCALE[Math.min(step, SCALE.length - 1)] / 12); + +export const move = (scene) => play(scene, 0.12, (ac, o, t) => { + tone(ac, o, t, 1400, { type: 'square', a: 0.25, d: 0.025 }); +}); + +export const rotate = (scene) => play(scene, 0.14, (ac, o, t) => { + tone(ac, o, t, 900, { type: 'triangle', a: 0.5, d: 0.06, glide: 1.6 }); +}); + +export const lock = (scene) => play(scene, 0.3, (ac, o, t) => { + tone(ac, o, t, 180, { type: 'sine', a: 0.7, d: 0.09, glide: 0.5 }); + hiss(ac, o, t, { f: 2600, q: 1.2, a: 0.25, d: 0.04 }); +}); + +export const slam = (scene) => play(scene, 0.42, (ac, o, t) => { + hiss(ac, o, t, { f: 3000, q: 0.5, a: 0.5, d: 0.12, fEnd: 400 }); + tone(ac, o, t + 0.02, 130, { type: 'sine', a: 1, d: 0.18, glide: 0.4 }); + tone(ac, o, t + 0.02, 65, { type: 'triangle', a: 0.6, d: 0.22, glide: 0.6 }); +}); + +export const shatter = (scene, chain = 1, size = 4) => play(scene, 0.34, (ac, o, t) => { + hiss(ac, o, t, { f: 5200, q: 0.8, a: 0.7, d: 0.22 + Math.min(0.3, size * 0.015), fEnd: 1800 }); + for (let i = 0; i < 5; i++) tone(ac, o, t + Math.random() * 0.08, 2400 + Math.random() * 3000, { a: 0.1, d: 0.06 }); + const base = 440; + const f = note(base, (chain - 1) * 2); + tone(ac, o, t, f, { type: 'triangle', a: 0.55, d: 0.35 }); + tone(ac, o, t + 0.07, f * 1.5, { type: 'sine', a: 0.35, d: 0.4 }); + if (chain >= 3) tone(ac, o, t + 0.14, f * 2, { type: 'square', a: 0.12, d: 0.4 }); +}); + +export const fuse = (scene, cells = 4) => play(scene, 0.22, (ac, o, t) => { + const f = 520 + Math.min(12, cells) * 30; + tone(ac, o, t, f, { type: 'sawtooth', a: 0.18, d: 0.32, glide: 2, detune: -8 }); + tone(ac, o, t, f, { type: 'sawtooth', a: 0.18, d: 0.32, glide: 2, detune: 8 }); + for (let i = 0; i < 4; i++) tone(ac, o, t + 0.06 * i, f * 2 * (1 + i * 0.25), { type: 'sine', a: 0.15, d: 0.15 }); +}); + +export const whoosh = (scene, power = 4) => play(scene, 0.3, (ac, o, t) => { + hiss(ac, o, t, { f: 400, q: 2, a: 0.8, d: 0.45 + Math.min(0.3, power * 0.01), attack: 0.08, fEnd: 3200 }); + tone(ac, o, t, 220, { type: 'sawtooth', a: 0.12, d: 0.4, glide: 3 }); +}); + +export const impact = (scene, power = 4) => play(scene, Math.min(0.6, 0.3 + power * 0.012), (ac, o, t) => { + hiss(ac, o, t, { f: 1800, q: 0.6, a: 0.8, d: 0.2, fEnd: 200 }); + tone(ac, o, t, 160, { type: 'sine', a: 1, d: 0.35, glide: 0.35 }); + tone(ac, o, t, 55, { type: 'triangle', a: 0.7, d: 0.4, glide: 0.7 }); +}); + +export const garbage = (scene, n = 6) => play(scene, 0.22, (ac, o, t) => { + const k = Math.min(10, Math.ceil(n / 2)); + for (let i = 0; i < k; i++) { + tone(ac, o, t + i * 0.035, 300 - i * 12, { type: 'square', a: 0.25, d: 0.05, glide: 0.6 }); + } + hiss(ac, o, t + k * 0.035, { f: 300, q: 1, type: 'lowpass', a: 0.6, d: 0.2 }); +}); + +export const counterTick = (scene) => play(scene, 0.08, (ac, o, t) => { + tone(ac, o, t, 2000, { type: 'square', a: 0.2, d: 0.02 }); +}); + +export const heartbeat = (scene, urgent = false) => play(scene, urgent ? 0.4 : 0.28, (ac, o, t) => { + tone(ac, o, t, 70, { type: 'sine', a: 1, d: 0.14, glide: 0.6 }); + tone(ac, o, t + 0.18, 62, { type: 'sine', a: 0.7, d: 0.14, glide: 0.6 }); +}); + +export const superCharge = (scene) => play(scene, 0.25, (ac, o, t) => { + [0, 4, 7, 12].forEach((s, i) => tone(ac, o, t + i * 0.06, 523 * Math.pow(2, s / 12), { type: 'square', a: 0.22, d: 0.18 })); +}); + +export const superFire = (scene) => play(scene, 0.45, (ac, o, t) => { + tone(ac, o, t, 110, { type: 'sawtooth', a: 0.4, d: 0.7, glide: 8, attack: 0.3 }); + hiss(ac, o, t, { f: 300, q: 3, a: 0.6, d: 0.6, attack: 0.3, fEnd: 6000 }); + tone(ac, o, t + 0.55, 80, { type: 'sine', a: 1, d: 0.5, glide: 0.5 }); + hiss(ac, o, t + 0.55, { f: 2000, q: 0.5, a: 0.8, d: 0.4, fEnd: 300 }); +}); + +export const ready = (scene) => play(scene, 0.3, (ac, o, t) => { + [0, 7, 12].forEach((s, i) => tone(ac, o, t + i * 0.09, 330 * Math.pow(2, s / 12), { type: 'square', a: 0.25, d: 0.12 })); +}); + +export const fight = (scene) => play(scene, 0.45, (ac, o, t) => { + for (const s of [0, 7, 12]) tone(ac, o, t, 196 * Math.pow(2, s / 12), { type: 'sawtooth', a: 0.3, d: 0.6, detune: Math.random() * 10 - 5 }); + hiss(ac, o, t, { f: 1200, q: 0.4, a: 0.5, d: 0.3, fEnd: 300 }); + tone(ac, o, t, 98, { type: 'sine', a: 0.8, d: 0.5, glide: 0.5 }); +}); + +export const ko = (scene) => play(scene, 0.55, (ac, o, t) => { + hiss(ac, o, t, { f: 2500, q: 0.4, a: 1, d: 0.5, fEnd: 150 }); + tone(ac, o, t, 220, { type: 'sawtooth', a: 0.5, d: 1.2, glide: 0.25 }); + tone(ac, o, t, 55, { type: 'sine', a: 1, d: 1.1, glide: 0.5 }); +}); + +export const sting = (scene, kind) => play(scene, 0.35, (ac, o, t) => { + const seq = kind === 'win' ? [0, 4, 7, 12, 16, 19, 24] : [12, 10, 7, 3, 0]; + seq.forEach((s, i) => tone(ac, o, t + i * (kind === 'win' ? 0.08 : 0.16), 392 * Math.pow(2, s / 12), + { type: 'square', a: 0.22, d: kind === 'win' ? 0.25 : 0.4 })); + if (kind === 'win') for (const s of [0, 4, 7]) tone(ac, o, t + 0.6, 784 * Math.pow(2, s / 12), { type: 'triangle', a: 0.2, d: 0.9 }); +}); + +export const menu = (scene) => play(scene, 0.14, (ac, o, t) => { + tone(ac, o, t, 1046, { type: 'square', a: 0.25, d: 0.04 }); +}); + +export const select = (scene) => play(scene, 0.22, (ac, o, t) => { + tone(ac, o, t, 784, { type: 'square', a: 0.3, d: 0.08 }); + tone(ac, o, t + 0.07, 1568, { type: 'square', a: 0.25, d: 0.12 }); +}); + +export const speedUp = (scene) => play(scene, 0.3, (ac, o, t) => { + for (let i = 0; i < 6; i++) tone(ac, o, t + i * 0.07, 600 + i * 120, { type: 'square', a: 0.2, d: 0.06 }); +}); diff --git a/src/games/blockfighter/BFStore.js b/src/games/blockfighter/BFStore.js new file mode 100644 index 0000000..9c48b0b --- /dev/null +++ b/src/games/blockfighter/BFStore.js @@ -0,0 +1,43 @@ +// Block Fighter — what persists between visits (localStorage when available). +// Nothing here throws: storage is a convenience, never a requirement. +// +// readSettings / writeSettings control feel + effects toggles +// readBests / recordBest per-mode high scores (survival, rush) + +const SETTINGS_KEY = 'blockfighter.settings.v1'; +const BESTS_KEY = 'blockfighter.bests.v1'; +const ls = () => { try { return globalThis.localStorage ?? null; } catch (_) { return null; } }; + +export const DEFAULT_SETTINGS = { + das: 150, // ms before a held direction auto-repeats + arr: 45, // ms between auto-repeats + ghost: true, // landing shadow + shake: true, // screen shake + sfx: true, // synth sound effects +}; + +export function readSettings() { + try { + const s = JSON.parse(ls()?.getItem(SETTINGS_KEY) || '{}') || {}; + return { ...DEFAULT_SETTINGS, ...s }; + } catch (_) { return { ...DEFAULT_SETTINGS }; } +} + +export function writeSettings(s) { + try { ls()?.setItem(SETTINGS_KEY, JSON.stringify(s)); } catch (_) { /* */ } +} + +export function readBests() { + try { + return { survival: 0, rush: 0, ...(JSON.parse(ls()?.getItem(BESTS_KEY) || '{}') || {}) }; + } catch (_) { return { survival: 0, rush: 0 }; } +} + +// Returns true when value beats the stored best for mode. +export function recordBest(mode, value) { + const b = readBests(); + if (!(value > (b[mode] ?? 0))) return false; + b[mode] = value; + try { ls()?.setItem(BESTS_KEY, JSON.stringify(b)); } catch (_) { /* */ } + return true; +} diff --git a/src/games/blockfighter/BlockFighterAI.js b/src/games/blockfighter/BlockFighterAI.js index 570829a..f88af66 100644 --- a/src/games/blockfighter/BlockFighterAI.js +++ b/src/games/blockfighter/BlockFighterAI.js @@ -1,12 +1,29 @@ // Block Fighter AI — placement search over the headless engine. // Skill 1-10 controls lookahead, blunder rate, evaluation richness, and how // fast the AI physically executes its plan (one input per movePeriodMs). +// Personality reshapes the evaluation so fighters play visibly differently: +// balanced the tuned all-rounder +// builder hoards giant power gems, holds crash gems back +// rusher pops anything it can, constant small pressure +// chainer sets up cascades and rewards chain depth +// turtle keeps the stack low, purges counters early import { - WIDTH, HEIGHT, SPAWN_COL, KIND, - legalPlacements, simulatePlacement, makeRng, peekPiece, + WIDTH, HEIGHT, SPAWN_COL, KIND, SUPER_COST, + legalPlacements, simulatePlacement, makeRng, peekPiece, canUseSuper, colorGroups, } from './BlockFighterLogic.js'; +export const PERSONALITIES = ['balanced', 'builder', 'rusher', 'chainer', 'turtle']; + +// Multipliers / additions applied over the skill profile's weights. +const PERSONALITY_MODS = { + balanced: {}, + builder: { power: 1.9, cluster: 1.3, crash: 0.5, smallClear: 30 }, + rusher: { attack: 1.3, cleared: 1.8, power: 0.4, cluster: 0.8, smallClear: -10 }, + chainer: { crash: 1.3, cluster: 1.15, chainBonus: 28 }, + turtle: { height: 1.6, spawnCol: 1.6, counters: 2.2, bumpy: 1.5, attack: 0.9 }, +}; + // skill → knobs (interpolated linearly between anchor rows) const SKILL_ANCHORS = [ { skill: 1, lookahead: 1, blunder: 0.45, movePeriodMs: 620, profile: 'basic' }, @@ -42,18 +59,35 @@ const EVAL_WEIGHTS = { aggressive: { attack: 60, cleared: 4, cluster: 3.5, crash: 8, power: 7, height: 1.2, spawnCol: 4, counters: 1.5, bumpy: 1 }, }; -export function createAI({ skill = 5, speed = 1, seed = 1 } = {}) { +function weightsFor(profile, personality) { + const base = { ...EVAL_WEIGHTS[profile], smallClear: 0, chainBonus: 0 }; + const mods = PERSONALITY_MODS[personality] ?? {}; + for (const [k, v] of Object.entries(mods)) { + if (k === 'smallClear' || k === 'chainBonus') base[k] = v; + else base[k] *= v; + } + return base; +} + +export function createAI({ skill = 5, speed = 1, seed = 1, personality = 'balanced', useSupers = true } = {}) { const knobs = knobsFor(skill); // higher level speed also quickens the AI's hands a bit knobs.movePeriodMs = Math.round(knobs.movePeriodMs * (1 - 0.08 * (speed - 1))); + const pers = PERSONALITY_MODS[personality] ? personality : 'balanced'; return { skill, knobs, + personality: pers, + weights: weightsFor(knobs.profile, pers), rng: makeRng(seed), plan: null, // { col, orient } nextActionAt: 0, + fresh: false, // plan not yet started (for hesitation) + // low skill fighters pause to "think" before moving a new piece + hesitateMs: skill <= 5 ? (6 - skill) * 90 : 0, useSoftDrop: skill >= 4, useHardDrop: skill >= 7, + useSupers: useSupers && skill >= 3, }; } @@ -107,14 +141,17 @@ function evaluateBoard(player, w) { function scorePlacement(result, w) { if (!result) return -Infinity; if (result.died) return -1e9; - return w.attack * result.attack + w.cleared * result.cleared + evaluateBoard(result.player, w); + let s = w.attack * result.attack + w.cleared * result.cleared + evaluateBoard(result.player, w); + if (result.cleared > 0 && result.cleared < 5 && !result.powerCells) s -= w.smallClear; + if (result.chain > 1) s += w.chainBonus * (result.chain - 1) * (result.chain - 1); + return s; } // ── Planning ───────────────────────────────────────────────────────────────── export function planPlacement(ai, match, pIdx) { const player = match.players[pIdx]; if (!player.piece) return null; - const w = EVAL_WEIGHTS[ai.knobs.profile]; + const w = ai.weights ?? EVAL_WEIGHTS[ai.knobs.profile]; const options = []; for (const { col, orient } of legalPlacements(player)) { @@ -156,13 +193,51 @@ export function planPlacement(ai, match, pIdx) { } ai.plan = { col: pick.col, orient: pick.orient }; ai.nextActionAt = 0; + ai.fresh = true; return ai.plan; } +// ── Super moves ────────────────────────────────────────────────────────────── +// Returns the super tier to fire now, or null. Call between inputs; after an +// Overdrive the scene should re-plan (the falling piece changed). +export function decideSuper(ai, match, pIdx) { + if (!ai.useSupers) return null; + const player = match.players[pIdx]; + if (!player.piece) return null; + let counters = 0; + let maxH = 0; + for (let c = 0; c < WIDTH; c++) { + for (let r = 0; r < HEIGHT; r++) if (player.board[r][c]) { maxH = Math.max(maxH, HEIGHT - r); break; } + } + for (const row of player.board) for (const cell of row) if (cell?.kind === KIND.COUNTER) counters += 1; + + const turtle = ai.personality === 'turtle'; + if (canUseSuper(match, pIdx, 1)) { + const needCounters = turtle ? 3 : 6; + const needHeight = turtle ? 5 : 8; + // hoard toward Overdrive unless under real pressure + const saving = !turtle && player.super >= SUPER_COST[3] - 40 && maxH < 10; + if (counters >= needCounters && maxH >= needHeight && !saving) return 1; + } + if (canUseSuper(match, pIdx, 3)) { + const biggest = colorGroups(player.board)[0]?.size ?? 0; + const need = ai.personality === 'rusher' ? 6 : ai.personality === 'builder' ? 12 : 8; + if (biggest >= need) return 3; + } + return null; +} + // ── Execution: one input per movePeriodMs ──────────────────────────────────── export function nextAction(ai, match, pIdx, nowMs) { const player = match.players[pIdx]; if (!player.piece || !ai.plan) return null; + if (ai.fresh) { + ai.fresh = false; + if (ai.hesitateMs) { + ai.nextActionAt = nowMs + ai.hesitateMs * (0.4 + ai.rng() * 1.2); + return null; + } + } if (nowMs < ai.nextActionAt) return null; const piece = player.piece; @@ -180,6 +255,6 @@ export function nextAction(ai, match, pIdx, nowMs) { action = 'softDrop'; } - if (action) ai.nextActionAt = nowMs + ai.knobs.movePeriodMs; + if (action) ai.nextActionAt = nowMs + ai.knobs.movePeriodMs * (0.8 + ai.rng() * 0.4); return action; } diff --git a/src/games/blockfighter/BlockFighterGame.js b/src/games/blockfighter/BlockFighterGame.js index d12cc8b..08f9a1f 100644 --- a/src/games/blockfighter/BlockFighterGame.js +++ b/src/games/blockfighter/BlockFighterGame.js @@ -1,32 +1,65 @@ +// Block Fighter — neon arcade falling-gem duel. This scene is the orchestrator: +// menus and modes, the per-frame loop (input with DAS/ARR, gravity, lock +// delay, AI), and the replay queue that feeds engine events to the board views, +// effects, arena fighters, HUD and synth sounds. +// +// BlockFighterLogic pure engine (events + snapshots) +// BlockFighterAI placement search, personalities, super use +// BFLayout/BFArt coordinates, procedural textures +// BFBoard per-player well with persistent, animated gem sprites +// BFFX / BFSound particles, shake, hit-stop, projectiles / Web Audio synths +// BFArena backdrop + the two gem-golems acting out the fight +// BFHud / BFScreens battle HUD / menus and overlays +// BFModes / BFStore ladder, survival, rush, versus / settings + bests + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; +import { getGameSoundtrack } from '../../services/soundtrack.js'; import { api } from '../../services/api.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; import { - WIDTH, VISIBLE_ROWS, HIDDEN_ROWS, KIND, SPEED_GRAVITY_MS, + HIDDEN_ROWS, HEIGHT, SPAWN_COL, SPEED_GRAVITY_MS, createMatch, spawnPiece, stepDown, hardDrop, moveLeft, moveRight, rotateCW, rotateCCW, getGhostCells, pieceCells, peekPiece, + canStepDown, lockNow, useSuper, canUseSuper, resetBoard, + SUPER_MAX, SUPER_TIER, } from './BlockFighterLogic.js'; -import { createAI, planPlacement, nextAction } from './BlockFighterAI.js'; +import { createAI, planPlacement, nextAction, decideSuper } from './BlockFighterAI.js'; +import { + W, D, ARENA, BOARD_TOP, SIDE_COLOR, SIDE_HEX, GEM_COLORS, CELL, +} from './BFLayout.js'; +import { makeTextures } from './BFArt.js'; +import { BFBoard } from './BFBoard.js'; +import { BFFX } from './BFFX.js'; +import { BFArena, BFBackdrop } from './BFArena.js'; +import { BFHud } from './BFHud.js'; +import * as SFX from './BFSound.js'; +import { + neonButton, showModeSelect, showLadder, showVs, showConfirm, showPause, showSettings, showResults, +} from './BFScreens.js'; +import { readSettings, writeSettings, readBests, recordBest } from './BFStore.js'; +import { MODES, RUSH_KO_BONUS, survivalWave, rushSetup, rankFor } from './BFModes.js'; -const CELL = 52; -const BOARD_W = CELL * WIDTH; // 312 -const BOARD_H = CELL * VISIBLE_ROWS; // 624 -const BOARD_TOP = 240; -const BOARD_LEFT = [360, GAME_WIDTH - 360 - BOARD_W]; // P1 left, AI right +const LOCK_MS = 450; +const LOCK_RESETS = 12; +const SOFT_DROP_MS = 32; +const REPLAY_DELAY = { + place: 90, settle: 210, clear: 300, diamond: 360, counter: 150, garbage: 480, + attack: 80, super: 300, spawn: 0, lose: 0, +}; -const FELT = 0x101626; -const FRAME = 0x0a1020; -const CELLBG = 0x182238; -const GRIDLN = 0x243352; -const GEM_COLORS = [0xe04444, 0x2ecc71, 0x3f8efc, 0xf1c40f]; -const GEM_HEX = ['#e04444', '#2ecc71', '#3f8efc', '#f1c40f']; +const KEYMAP_SOLO = [{ + left: ['ArrowLeft', 'KeyA'], right: ['ArrowRight', 'KeyD'], soft: ['ArrowDown', 'KeyS'], + hard: ['Space'], cw: ['ArrowUp', 'KeyX', 'KeyW'], ccw: ['KeyZ'], + purge: ['KeyC'], overdrive: ['KeyV'], smart: ['ShiftLeft', 'ShiftRight'], +}]; +const KEYMAP_VERSUS = [ + { left: ['KeyA'], right: ['KeyD'], soft: ['KeyS'], hard: ['KeyW'], cw: ['KeyG'], ccw: ['KeyF'], purge: [], overdrive: [], smart: ['KeyR'] }, + { left: ['ArrowLeft'], right: ['ArrowRight'], soft: ['ArrowDown'], hard: ['ArrowUp'], cw: ['Period'], ccw: ['Comma'], purge: [], overdrive: [], smart: ['Slash'] }, +]; +const CONTROLS_SOLO = '← → move ↑ / X rotate Z rotate back\n↓ soft drop (tap at the bottom to lock) SPACE slam\nC Purge V Overdrive SHIFT best super ESC pause'; +const CONTROLS_VERSUS = 'P1: A D move · S soft · W slam · F G rotate · R super\nP2: ← → move · ↓ soft · ↑ slam · , . rotate · / super\nESC pause'; -const D = { felt: -2, frame: -1, grid: 0, cells: 5, piece: 8, fx: 12, ui: 30, overlay: 60, overlayUI: 62 }; -const REPLAY_DELAY = { place: 70, settle: 150, clear: 230, diamond: 260, counter: 140, garbage: 200, attack: 60, spawn: 0, lose: 0 }; +const hexNum = (h) => parseInt(String(h ?? '#ff3da8').replace('#', ''), 16); export default class BlockFighterGame extends Phaser.Scene { constructor() { super('BlockFighterGame'); } @@ -37,29 +70,43 @@ export default class BlockFighterGame extends Phaser.Scene { this.roster = []; this.levelsCompleted = 0; this.canPersist = true; - this.view = 'select'; - this.portraits = []; // active Portrait handles (DOM-backed, not in layer) + this.view = 'loading'; + this.ready = false; + this.screenObjs = []; + this.overlayObjs = []; + this.trackInto = null; + this.portraits = []; + this.menuGolems = []; this.match = null; - this.overlayUp = false; + this.fight = null; + this.paused = false; } async create() { + this.isShutdown = false; + this.events.once('shutdown', () => { + this.isShutdown = true; + this.input.keyboard?.off('keydown', this.onKeyDown, this); + this.input.keyboard?.off('keyup', this.onKeyUp, this); + this.clearAll(); + }); try { - const music = this.cache.json.get('music'); - if (music?.tracks) new MusicPlayer(this, music.tracks); + const { tracks, volume } = getGameSoundtrack(this); + if (tracks.length) this.music = new MusicPlayer(this, tracks, volume, { right: W - 6, top: 1080 - 92 }); } catch (_) { /* optional */ } - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, FELT).setDepth(D.felt); + this.settings = readSettings(); + this.bfSfxOff = !this.settings.sfx; + makeTextures(this); + this.backdrop = new BFBackdrop(this); const raw = this.cache.json.get('blockfighter'); this.bank = (raw?.levels ?? []).slice().sort((a, b) => a.level - b.level); - try { const res = await fetch('data/opponents.json'); const json = await res.json(); this.roster = json.opponents ?? []; } catch (_) { this.roster = []; } - try { const res = await api.get('/puzzles/blockfighter/progress'); this.levelsCompleted = res?.levelsCompleted ?? 0; @@ -67,753 +114,928 @@ export default class BlockFighterGame extends Phaser.Scene { this.canPersist = false; this.levelsCompleted = 0; } + if (this.isShutdown) return; - this.makeTextures(); - this.layer = this.add.container(0, 0); - this.showLevelSelect(); + this.input.keyboard.on('keydown', this.onKeyDown, this); + this.input.keyboard.on('keyup', this.onKeyUp, this); + this.ready = true; + this.showMenu(); } opponentFor(levelDef) { const opp = this.roster.find((o) => o.id === levelDef.opponentId); if (opp) return opp; - console.warn(`blockfighter: opponent '${levelDef.opponentId}' not in roster; using stub`); return { id: levelDef.opponentId, spriteIndex: 0, name: levelDef.opponentId, bio: '', speech: {} }; } - // ── Generated gem textures ────────────────────────────────────────────────── + // ── object tracking ────────────────────────────────────────────────────────── + track(o) { (this.trackInto ?? this.screenObjs).push(o); return o; } - makeTextures() { - if (this.textures.exists('bf-gem-0')) return; - for (let c = 0; c < 4; c++) { - const color = GEM_COLORS[c]; - let g = this.make.graphics({ add: false }); - g.fillStyle(color, 1); - g.fillRoundedRect(2, 2, CELL - 4, CELL - 4, 10); - g.fillStyle(0xffffff, 0.32); - g.fillRoundedRect(7, 6, CELL - 14, 14, 6); - g.lineStyle(2, 0x000000, 0.35); - g.strokeRoundedRect(2, 2, CELL - 4, CELL - 4, 10); - g.generateTexture(`bf-gem-${c}`, CELL, CELL); - g.destroy(); - - g = this.make.graphics({ add: false }); - g.fillStyle(0x000000, 0.25); - g.fillCircle(CELL / 2, CELL / 2, CELL / 2 - 2); - g.fillStyle(color, 1); - g.fillCircle(CELL / 2, CELL / 2, CELL / 2 - 5); - g.fillStyle(0xffffff, 0.85); - g.fillCircle(CELL / 2, CELL / 2, 7); - g.lineStyle(3, 0xffffff, 0.5); - g.strokeCircle(CELL / 2, CELL / 2, CELL / 2 - 10); - g.generateTexture(`bf-crash-${c}`, CELL, CELL); - g.destroy(); - - g = this.make.graphics({ add: false }); - g.fillStyle(color, 0.45); - g.fillRoundedRect(3, 3, CELL - 6, CELL - 6, 8); - g.lineStyle(3, color, 0.95); - g.strokeRoundedRect(3, 3, CELL - 6, CELL - 6, 8); - g.generateTexture(`bf-counter-${c}`, CELL, CELL); - g.destroy(); - } - const g = this.make.graphics({ add: false }); - g.fillStyle(0xffffff, 1); - const m = CELL / 2; - g.fillPoints([ - { x: m, y: 3 }, { x: CELL - 4, y: m }, { x: m, y: CELL - 3 }, { x: 4, y: m }, - ], true); - g.fillStyle(0xb8e8ff, 0.85); - g.fillPoints([ - { x: m, y: 12 }, { x: CELL - 13, y: m }, { x: m, y: CELL - 12 }, { x: 13, y: m }, - ], true); - g.generateTexture('bf-diamond', CELL, CELL); - g.destroy(); + overlay(fn) { + this.closeOverlay(); + this.trackInto = this.overlayObjs; + try { fn(); } finally { this.trackInto = null; } } - // ── View management ───────────────────────────────────────────────────────── + closeOverlay() { + for (const o of this.overlayObjs) { try { o.destroy(); } catch (_) {} } + this.overlayObjs = []; + } - clearLayer() { + clearScreen() { + this.closeOverlay(); + for (const o of this.screenObjs) { try { o.destroy(); } catch (_) {} } + this.screenObjs = []; for (const p of this.portraits) { try { p.destroy(); } catch (_) {} } this.portraits = []; - this.input.keyboard.off('keydown', this.onKeyDown, this); - this.layer.removeAll(true); - this.boardObjs = null; + for (const g of this.menuGolems) { try { g.destroy(); } catch (_) {} } + this.menuGolems = []; + this.tweens.timeScale = 1; } - // ── Level select ──────────────────────────────────────────────────────────── - - showLevelSelect() { - this.view = 'select'; - this.overlayUp = false; + clearBattle() { + this.boards?.forEach((b) => b.destroy()); + this.boards = null; + this.hud?.destroy(); this.hud = null; + this.fx?.destroy(); this.fx = null; + this.arena?.destroy(); this.arena = null; this.match = null; - this.clearLayer(); - const cx = GAME_WIDTH / 2; + this.paused = false; + } - const title = this.add.text(cx, 84, 'BLOCK FIGHTER', { - fontFamily: 'Righteous', fontSize: '64px', color: COLORS.goldHex, - }).setOrigin(0.5); - const sub = this.add.text(cx, 138, 'Match gems, drop crash gems, and bury your rival in counter gems. Beat each fighter to unlock the next.', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex, - }).setOrigin(0.5); - this.layer.add([title, sub]); + clearAll() { + this.clearBattle(); + this.clearScreen(); + } + // ── menus ──────────────────────────────────────────────────────────────────── + showMenu() { + this.clearAll(); + this.fight = null; + this.run = null; + this.view = 'menu'; + this.backdrop.setTempo(1); + showModeSelect(this, { + modes: MODES, + bests: readBests(), + levelsCompleted: this.levelsCompleted, + total: this.bank.length, + onPick: (id) => this.pickMode(id), + onSettings: () => this.openSettings(), + onBack: () => this.scene.start('GameMenu'), + }); + } + + openSettings() { + this.overlay(() => showSettings(this, { + settings: { ...this.settings }, + onChange: (s) => { + this.settings = { ...s }; + this.bfSfxOff = !s.sfx; + writeSettings(this.settings); + if (this.fx) this.fx.settings = this.settings; + }, + onClose: () => this.closeOverlay(), + })); + } + + pickMode(id) { + if (id === 'ladder') return this.showLadderScreen(); + if (id === 'survival') { this.run = { wave: 1, superCarry: 0, sent: 0, bestChain: 0 }; return this.showFightIntro({ mode: 'survival' }); } + if (id === 'rush') return this.showFightIntro({ mode: 'rush' }); + if (id === 'versus') return this.showFightIntro({ mode: 'versus' }); + return null; + } + + showLadderScreen() { + this.clearAll(); + this.view = 'ladder'; if (!this.bank.length) { - const msg = this.add.text(cx, 520, 'No levels found in /data/blockfighter.json', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.dangerHex, align: 'center', - }).setOrigin(0.5); - const back = new Button(this, cx, GAME_HEIGHT - 90, 'Back', () => this.scene.start('GameMenu'), { variant: 'ghost' }); - this.layer.add([msg, back]); + this.track(this.add.text(W / 2, 520, 'No levels found in /data/blockfighter.json', { + fontFamily: '"Julius Sans One"', fontSize: '26px', color: '#ff2e63', + }).setOrigin(0.5).setDepth(D.ui)); return; } - - const nextLevel = Math.min(this.levelsCompleted + 1, this.bank.length); - const prog = this.add.text(cx, 182, `Defeated ${this.levelsCompleted} / ${this.bank.length}`, { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.textHex, - }).setOrigin(0.5); - this.layer.add(prog); - - const COLS = 10; - const SIZE = 128; - const GAP = 16; - const gridW = COLS * SIZE + (COLS - 1) * GAP; - const left = cx - gridW / 2 + SIZE / 2; - const top = 300; - - this.bank.forEach((lv, i) => { - const col = i % COLS; - const row = Math.floor(i / COLS); - const x = left + col * (SIZE + GAP); - const y = top + row * (SIZE + GAP + 36); - const level = lv.level; - const cleared = level <= this.levelsCompleted; - const playable = level <= nextLevel; - const opp = this.opponentFor(lv); - - const fill = cleared ? 0x1f5c3a : playable ? 0x1e3a52 : 0x16202b; - const stroke = cleared ? 0x2ecc71 : playable ? COLORS.gold : 0x2a3744; - const tile = this.add.rectangle(x, y, SIZE, SIZE + 28, fill).setStrokeStyle(playable || cleared ? 3 : 2, stroke, 1); - const num = this.add.text(x, y - SIZE / 2 + 22, String(level), { - fontFamily: 'Righteous', fontSize: '26px', - color: playable || cleared ? COLORS.textHex : '#54606b', - }).setOrigin(0.5); - const objs = [tile, num]; - - if (this.textures.exists('opponents')) { - const face = this.add.image(x, y + 6, 'opponents', opp.spriteIndex ?? 0).setDisplaySize(76, 76); - if (!playable && !cleared) { face.setTint(0x333a44); face.setAlpha(0.7); } - objs.push(face); - } - const tag = this.add.text(x, y + SIZE / 2 + 2, cleared ? `✓ ${opp.name}` : playable ? opp.name : 'locked', { - fontFamily: '"Julius Sans One"', fontSize: '15px', - color: cleared ? '#9be7b4' : playable ? COLORS.mutedHex : '#54606b', - }).setOrigin(0.5); - objs.push(tag); - this.layer.add(objs); - - if (playable) { - tile.setInteractive({ useHandCursor: true }); - tile.on('pointerover', () => tile.setStrokeStyle(4, COLORS.gold, 1)); - tile.on('pointerout', () => tile.setStrokeStyle(3, stroke, 1)); - tile.on('pointerup', () => this.showIntro(level)); - } + showLadder(this, { + bank: this.bank, + levelsCompleted: this.levelsCompleted, + opponentFor: (lv) => this.opponentFor(lv), + canPersist: this.canPersist, + onPick: (level) => this.showFightIntro({ mode: 'ladder', level }), + onBack: () => this.showMenu(), + onReset: () => this.overlay(() => showConfirm(this, { + title: 'Reset Progress?', + message: 'This clears every fighter you have beaten and\nstarts you back at Level 1. This cannot be undone.', + yes: 'Reset', + onYes: () => { + api.post('/puzzles/blockfighter/reset').catch(() => {}); + this.levelsCompleted = 0; + this.showLadderScreen(); + }, + onNo: () => this.closeOverlay(), + })), }); + } - const resume = new Button(this, cx - 150, GAME_HEIGHT - 78, `Fight Level ${nextLevel}`, () => this.showIntro(nextLevel), - { width: 280, height: 58, fontSize: 24 }); - const back = new Button(this, cx + 170, GAME_HEIGHT - 78, 'Back', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 180, height: 58, fontSize: 24 }); - const reset = new Button(this, 210, GAME_HEIGHT - 78, 'Reset Progress', () => this.confirmResetProgress(), - { variant: 'ghost', width: 260, height: 58, fontSize: 22, textColor: COLORS.dangerHex }); - this.layer.add([resume, back, reset]); - - if (!this.canPersist) { - const note = this.add.text(cx, GAME_HEIGHT - 28, 'Sign in to save your progress across devices.', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5); - this.layer.add(note); + // Resolve a fight description into concrete parameters. + fightDef({ mode, level }) { + if (mode === 'ladder') { + const lv = this.bank.find((l) => l.level === level); + if (!lv) return null; + return { + skill: lv.skill, speed: lv.speed, personality: lv.personality ?? 'balanced', + opponent: this.opponentFor(lv), tagline: lv.tagline, dropPattern: lv.dropPattern, stage: lv.stage ?? '#ff3da8', + }; } + if (mode === 'survival') return survivalWave(this.run?.wave ?? 1, this.roster); + if (mode === 'rush') return rushSetup(this.roster); + return { + skill: 0, speed: 3, personality: null, opponent: { id: 'p2', name: 'Player 2', spriteIndex: 0, speech: {} }, + tagline: 'Settle it on the grid.', dropPattern: null, stage: SIDE_HEX[1], + }; } - confirmResetProgress() { - const cx = GAME_WIDTH / 2; - const cy = GAME_HEIGHT / 2; - const dim = this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.62).setDepth(D.overlay).setInteractive(); - const panel = this.add.graphics().setDepth(D.overlay); - panel.fillStyle(COLORS.panel, 0.98); - panel.fillRoundedRect(cx - 320, cy - 160, 640, 320, 20); - panel.lineStyle(3, COLORS.danger, 1); - panel.strokeRoundedRect(cx - 320, cy - 160, 640, 320, 20); - const title = this.add.text(cx, cy - 92, 'Reset Progress?', { - fontFamily: 'Righteous', fontSize: '52px', color: COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.overlayUI); - const msg = this.add.text(cx, cy - 14, - 'This clears every fighter you have beaten and\nstarts you back at Level 1. This cannot be undone.', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, align: 'center', lineSpacing: 6, - }).setOrigin(0.5).setDepth(D.overlayUI); - const yes = new Button(this, cx - 150, cy + 88, 'Reset', () => { - api.post('/puzzles/blockfighter/reset').catch(() => {}); - this.levelsCompleted = 0; - this.showLevelSelect(); - }, { width: 250, height: 58, fontSize: 24, textColor: COLORS.dangerHex }).setDepth(D.overlayUI); - const no = new Button(this, cx + 150, cy + 88, 'Cancel', () => this.showLevelSelect(), - { variant: 'ghost', width: 250, height: 58, fontSize: 24 }).setDepth(D.overlayUI); - this.layer.add([dim, panel, title, msg, yes, no]); + showFightIntro(spec) { + const def = this.fightDef(spec); + if (!def) return; + this.clearAll(); + this.view = 'vs'; + const versus = spec.mode === 'versus'; + let info = ''; + if (spec.mode === 'ladder') { + const stars = '★'.repeat(Math.ceil(def.skill / 2)) + '☆'.repeat(5 - Math.ceil(def.skill / 2)); + info = `LEVEL ${spec.level} · SKILL ${stars} · SPEED ${'⚡'.repeat(def.speed)} · STYLE ${def.personality.toUpperCase()}`; + } else if (spec.mode === 'survival') { + info = `WAVE ${this.run.wave} · STYLE ${def.personality.toUpperCase()} · SPEED ${'⚡'.repeat(def.speed)}`; + } else if (spec.mode === 'rush') { + info = 'Two minutes · knock the sandbag out for a bonus'; + } else { + info = 'Best of three rounds'; + } + showVs(this, { + p1Name: versus ? 'Player 1' : 'You', + p2Name: def.opponent.name, + opponent: versus ? null : def.opponent, + stage: def.stage, + tagline: def.tagline, + info, + versus, + headStyle: versus ? 2 : 1 + ((def.opponent.spriteIndex ?? 0) % 3), + onFight: () => this.startFight(spec, def), + onBack: () => (spec.mode === 'ladder' ? this.showLadderScreen() : this.showMenu()), + }); } - // ── Pre-battle intro ──────────────────────────────────────────────────────── - - showIntro(level) { - const lv = this.bank.find((l) => l.level === level); - if (!lv) return; - this.view = 'intro'; - this.clearLayer(); - const cx = GAME_WIDTH / 2; - const opp = this.opponentFor(lv); - - const title = this.add.text(cx, 110, `LEVEL ${level}`, { - fontFamily: 'Righteous', fontSize: '48px', color: COLORS.goldHex, - }).setOrigin(0.5); - const vs = this.add.text(cx, 560, 'VS', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.mutedHex, - }).setOrigin(0.5).setAlpha(0.6); - this.layer.add([title, vs]); - - this.portraits.push(createOpponentPortrait(this, opp, cx, 360, 150, D.ui, { playIntro: true })); - - const name = this.add.text(cx, 552 + 80, opp.name, { - fontFamily: 'Righteous', fontSize: '54px', color: COLORS.textHex, - }).setOrigin(0.5); - const bio = this.add.text(cx, 552 + 140, opp.bio ?? '', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.mutedHex, - }).setOrigin(0.5); - const tagline = this.add.text(cx, 552 + 188, lv.tagline ?? '', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.goldHex, fontStyle: 'italic', - }).setOrigin(0.5); - - const stars = '★'.repeat(Math.ceil(lv.skill / 2)) + '☆'.repeat(5 - Math.ceil(lv.skill / 2)); - const bolts = '⚡'.repeat(lv.speed); - const statText = this.add.text(cx, 552 + 248, `Skill ${stars} Speed ${bolts}`, { - fontFamily: '"Julius Sans One"', fontSize: '28px', color: COLORS.textHex, - }).setOrigin(0.5); - this.layer.add([name, bio, tagline, statText]); - - const fight = new Button(this, cx - 130, GAME_HEIGHT - 110, 'FIGHT!', () => this.startBattle(level), - { width: 240, height: 66, fontSize: 30 }); - const back = new Button(this, cx + 140, GAME_HEIGHT - 110, 'Back', () => this.showLevelSelect(), - { variant: 'ghost', width: 200, height: 66, fontSize: 24 }); - this.layer.add([fight, back]); - } - - // ── Battle setup ──────────────────────────────────────────────────────────── - - startBattle(level) { - const lv = this.bank.find((l) => l.level === level); - if (!lv) return; + // ── fight / round lifecycle ───────────────────────────────────────────────── + startFight(spec, def) { + this.clearAll(); this.view = 'battle'; - this.overlayUp = false; - this.level = level; - this.levelDef = lv; - this.opponent = this.opponentFor(lv); - this.clearLayer(); + const mode = MODES[spec.mode]; + const versus = spec.mode === 'versus'; + this.fight = { + spec, def, mode, versus, + wins: [0, 0], round: 0, + totals: { sent: [0, 0], bestChain: [0, 0], bestPower: [0, 0], supers: [0, 0], seconds: 0 }, + rushScore: 0, rushKOs: 0, + timeLeft: mode.timeLimitMs ?? 0, + }; + this.humans = versus ? [0, 1] : [0]; + this.keymap = versus ? KEYMAP_VERSUS : KEYMAP_SOLO; + + const oppColor = versus ? SIDE_COLOR[1] : hexNum(def.stage); + this.fx = new BFFX(this, this.settings); + this.arena = new BFArena(this, [SIDE_COLOR[0], oppColor], [0, versus ? 2 : 1 + ((def.opponent.spriteIndex ?? 0) % 3)]); + this.hud = new BFHud(this, { + names: [versus ? 'Player 1' : 'You', def.opponent.name], + opponent: def.opponent, + versus, + roundsToWin: mode.roundsToWin, + superKeys: versus + ? [{ purge: 'R', overdrive: 'R' }, { purge: '/', overdrive: '/' }] + : [{ purge: 'C', overdrive: 'V' }, null], + touch: !versus, + onTouch: (action, down) => this.onTouch(action, down), + }); + this.hud.glowNames(); + neonButton(this, 80, 1040, '❚❚', () => { + if (this.phase === 'play' || this.phase === 'intro' || this.paused) this.togglePause(); + }, { w: 70, h: 52, color: 0xb86bff, size: 22, ghost: true, depth: D.touch }); + this.startRound(); + } + + modeLine() { + const f = this.fight; + const sm = f.spec.mode; + const round = f.mode.roundsToWin > 1 ? `ROUND ${f.round}` : ''; + if (sm === 'ladder') return [`LEVEL ${f.spec.level}`, round]; + if (sm === 'survival') return [`WAVE ${this.run.wave}`, 'SURVIVAL']; + if (sm === 'rush') return ['GARBAGE RUSH', `SCORE ${f.rushScore}`]; + return ['VERSUS', round]; + } + + startRound() { + const f = this.fight; + f.round += 1; + this.boards?.forEach((b) => b.destroy()); + this.closeOverlay(); + this.arena.reset(); + this.tweens.timeScale = 1; const seed = (Date.now() ^ (Math.random() * 0xffffffff)) >>> 0; - this.match = createMatch({ seed, dropPatterns: [lv.dropPattern, lv.dropPattern] }); - this.ai = createAI({ skill: lv.skill, speed: lv.speed, seed: seed ^ 0x9e3779b9 }); - this.gravityMs = SPEED_GRAVITY_MS[Math.max(1, Math.min(5, lv.speed))]; + this.match = createMatch({ seed, dropPatterns: [f.def.dropPattern, f.def.dropPattern] }); + if (f.spec.mode === 'survival' && this.run?.superCarry) this.match.players[0].super = this.run.superCarry; + // autoplay (attract/testing): the left side is driven by an AI too + this.ais = [ + this.autoplay ? createAI({ skill: 7, speed: f.def.speed, seed: seed ^ 0x51ed, personality: 'chainer' }) : null, + f.versus ? null : createAI({ skill: f.def.skill, speed: f.def.speed, seed: seed ^ 0x9e3779b9, personality: f.def.personality }), + ]; + this.humans = (f.versus ? [0, 1] : [0]).filter((i) => !this.ais[i]); + this.baseGravity = SPEED_GRAVITY_MS[Math.max(1, Math.min(5, f.def.speed))]; + this.gravityMs = this.baseGravity; + this.speedStage = 0; + this.roundTime = 0; this.gravTimer = [0, 0]; + this.lockTimer = [0, 0]; + this.lockResets = [0, 0]; + this.softTimer = [0, 0]; this.replayQueue = [[], []]; this.replayTimer = [0, 0]; - this.matchEnded = false; + this.pieceShown = [false, false]; + this.inFlight = [0, 0]; + this.buffer = [[], []]; + this.held = [{ left: 0, right: 0, soft: false }, { left: 0, right: 0, soft: false }]; + this.das = [{ dir: 0, t: 0, rep: 0 }, { dir: 0, t: 0, rep: 0 }]; + this.heartAt = 0; + this.aiSuperAt = [0, 0]; + this.emoteAt = 0; + this.superWasReady = [0, 0]; - this.drawBattleChrome(); + const hooks = { fx: this.fx, sound: { fuse: (n) => SFX.fuse(this, n) } }; + this.boards = [new BFBoard(this, 0, hooks), new BFBoard(this, 1, hooks)]; + this.boards.forEach((b) => b.setBorderGlow(true)); + this.hud.setRounds(f.wins); + const [main, sub] = this.modeLine(); + this.hud.setMode(main, sub); + this.hud.setTimer(f.mode.timeLimitMs ? this.fmtTime(f.timeLeft) : ''); + this.refreshHud(true); + for (const i of [0, 1]) this.hud.setNext(i, peekPiece(this.match, 0), peekPiece(this.match, 1)); - this.input.keyboard.on('keydown', this.onKeyDown, this); - - for (const i of [0, 1]) this.beginSpawn(i); + // READY → FIGHT + this.phase = 'intro'; + const label = f.mode.roundsToWin > 1 ? `ROUND ${f.round}` : (f.spec.mode === 'survival' ? `WAVE ${this.run.wave}` : 'READY'); + this.fx.callout(label, { size: 96, color: '#2ee6ff', hold: 650, style: 'announce' }); + SFX.ready(this); + this.time.delayedCall(1050, () => { + if (!this.fight || this.phase !== 'intro') return; + this.fx.callout('FIGHT!', { size: 140, color: '#ffd21f', hold: 450, style: 'announce' }); + this.fx.flash(0xffd21f, 0.25); + SFX.fight(this); + this.phase = 'play'; + for (const i of [0, 1]) this.beginSpawn(i); + }); } - drawBattleChrome() { - const cx = GAME_WIDTH / 2; - const hud = this.add.text(cx, 56, `Level ${this.level} — vs ${this.opponent.name}`, { - fontFamily: 'Righteous', fontSize: '38px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.ui); - this.layer.add(hud); + fmtTime(ms) { + const s = Math.max(0, Math.ceil(ms / 1000)); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; + } - this.boardObjs = []; - this.pieceImgs = []; - this.ghostImgs = []; - this.garbageTexts = []; - this.sentTexts = []; - this.previewImgs = []; - - for (const i of [0, 1]) { - const left = BOARD_LEFT[i]; - const g = this.add.graphics().setDepth(D.frame); - g.fillStyle(FRAME, 1); - g.fillRoundedRect(left - 16, BOARD_TOP - 16, BOARD_W + 32, BOARD_H + 32, 14); - g.fillStyle(CELLBG, 1); - g.fillRect(left, BOARD_TOP, BOARD_W, BOARD_H); - this.layer.add(g); - - const grid = this.add.graphics().setDepth(D.grid); - grid.lineStyle(1, GRIDLN, 0.8); - for (let c = 0; c <= WIDTH; c++) grid.lineBetween(left + c * CELL, BOARD_TOP, left + c * CELL, BOARD_TOP + BOARD_H); - for (let r = 0; r <= VISIBLE_ROWS; r++) grid.lineBetween(left, BOARD_TOP + r * CELL, left + BOARD_W, BOARD_TOP + r * CELL); - // danger marker over the spawn column - grid.fillStyle(0xe04444, 0.5); - grid.fillTriangle( - left + 3 * CELL + CELL / 2 - 12, BOARD_TOP - 16, - left + 3 * CELL + CELL / 2 + 12, BOARD_TOP - 16, - left + 3 * CELL + CELL / 2, BOARD_TOP - 4, - ); - this.layer.add(grid); - - const label = this.add.text(left + BOARD_W / 2, BOARD_TOP + BOARD_H + 36, i === 0 ? 'YOU' : this.opponent.name.toUpperCase(), { - fontFamily: 'Righteous', fontSize: '24px', color: i === 0 ? COLORS.accentHex ?? '#5bc0de' : COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.ui); - this.layer.add(label); - - // pending garbage indicator + sent counter above the board - const gt = this.add.text(left + BOARD_W / 2, BOARD_TOP - 44, '', { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.ui); - this.garbageTexts.push(gt); - const st = this.add.text(left + (i === 0 ? -16 : BOARD_W + 16), BOARD_TOP - 44, 'Sent: 0', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, - }).setOrigin(i === 0 ? 1 : 0, 0.5).setDepth(D.ui); - this.sentTexts.push(st); - this.layer.add([gt, st]); - - // next-piece preview in the centre gutter - const px = i === 0 ? BOARD_LEFT[0] + BOARD_W + 90 : BOARD_LEFT[1] - 90; - const pg = this.add.graphics().setDepth(D.frame); - pg.fillStyle(FRAME, 1); - pg.fillRoundedRect(px - 44, 290 - 70, 88, 150, 10); - const pl = this.add.text(px, 290 - 92, 'NEXT', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.layer.add([pg, pl]); - this.previewImgs.push([ - this.add.image(px, 290 - 28, 'bf-gem-0').setDepth(D.ui).setVisible(false), - this.add.image(px, 290 + 28, 'bf-gem-0').setDepth(D.ui).setVisible(false), - ]); - this.layer.add(this.previewImgs[i]); - - this.boardObjs.push([]); // cell images, rebuilt per render - this.pieceImgs.push([ - this.add.image(0, 0, 'bf-gem-0').setDepth(D.piece).setVisible(false), - this.add.image(0, 0, 'bf-gem-0').setDepth(D.piece).setVisible(false), - ]); - this.layer.add(this.pieceImgs[i]); - this.ghostImgs.push([ - this.add.rectangle(0, 0, CELL - 8, CELL - 8).setStrokeStyle(2, 0xffffff, 0.35).setDepth(D.grid + 1).setVisible(false), - this.add.rectangle(0, 0, CELL - 8, CELL - 8).setStrokeStyle(2, 0xffffff, 0.35).setDepth(D.grid + 1).setVisible(false), - ]); - this.layer.add(this.ghostImgs[i]); + // ── input ──────────────────────────────────────────────────────────────────── + actionFor(code) { + if (!this.keymap) return null; + for (let i = 0; i < this.keymap.length; i++) { + for (const [act, codes] of Object.entries(this.keymap[i])) { + if (codes.includes(code)) return { i, act }; + } } - - // portraits - this.portraits.push(createPlayerPortrait(this, 165, 380, 84, D.ui, 'BlockFighterGame')); - this.oppPortrait = createOpponentPortrait(this, this.opponent, GAME_WIDTH - 165, 380, 84, D.ui, { playIntro: false }); - this.portraits.push(this.oppPortrait); - - // chain callout - this.calloutText = this.add.text(GAME_WIDTH / 2, 620, '', { - fontFamily: 'Righteous', fontSize: '54px', color: COLORS.goldHex, stroke: '#000000', strokeThickness: 6, - }).setOrigin(0.5).setDepth(D.fx).setAlpha(0); - this.layer.add(this.calloutText); - - const quit = new Button(this, 140, GAME_HEIGHT - 60, 'Levels', () => this.showLevelSelect(), - { variant: 'ghost', width: 180, height: 52, fontSize: 22 }); - this.layer.add(quit); - - this.drawTouchControls(); + return null; } - drawTouchControls() { - const y = GAME_HEIGHT - 110; - const cx = GAME_WIDTH / 2; - const defs = [ - { x: cx - 290, glyph: '◀', action: 'left', repeat: true }, - { x: cx - 174, glyph: '▶', action: 'right', repeat: true }, - { x: cx - 58, glyph: '⟲', action: 'rotateCCW', repeat: false }, - { x: cx + 58, glyph: '⟳', action: 'rotateCW', repeat: false }, - { x: cx + 174, glyph: '▼', action: 'softDrop', repeat: true }, - { x: cx + 290, glyph: '⤓', action: 'hardDrop', repeat: false }, - ]; - for (const def of defs) { - const g = this.add.graphics().setDepth(D.ui); - g.fillStyle(COLORS.panel, 0.9); - g.fillCircle(def.x, y, 46); - g.lineStyle(2, COLORS.gold, 0.7); - g.strokeCircle(def.x, y, 46); - const t = this.add.text(def.x, y, def.glyph, { - fontFamily: 'Righteous', fontSize: '34px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui + 1); - const zone = this.add.zone(def.x, y, 96, 96).setInteractive({ useHandCursor: true }).setDepth(D.ui + 2); - let repeatEvt = null; - const stop = () => { if (repeatEvt) { repeatEvt.remove(); repeatEvt = null; } }; - zone.on('pointerdown', () => { - this.playerAction(def.action); - if (def.repeat) { - stop(); - repeatEvt = this.time.addEvent({ delay: 120, loop: true, callback: () => this.playerAction(def.action) }); - } - }); - zone.on('pointerup', stop); - zone.on('pointerout', stop); - this.layer.add([g, t, zone]); - } - } - - // ── Input ─────────────────────────────────────────────────────────────────── - onKeyDown(event) { + if (event.code === 'Escape' || event.code === 'KeyP') { + if (this.view === 'battle' && (this.phase === 'play' || this.phase === 'intro')) this.togglePause(); + return; + } + if (this.view !== 'battle' || this.paused) return; + const hit = this.actionFor(event.code); + if (!hit) return; + if (['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Slash'].includes(event.code)) event.preventDefault?.(); + if (event.repeat) return; + this.press(hit.i, hit.act, true); + } + + onKeyUp(event) { if (this.view !== 'battle') return; - switch (event.code) { - case 'ArrowLeft': case 'KeyA': this.playerAction('left'); break; - case 'ArrowRight': case 'KeyD': this.playerAction('right'); break; - case 'ArrowDown': case 'KeyS': this.playerAction('softDrop'); break; - case 'ArrowUp': case 'KeyX': if (!event.repeat) this.playerAction('rotateCW'); break; - case 'KeyZ': if (!event.repeat) this.playerAction('rotateCCW'); break; - case 'Space': if (!event.repeat) this.playerAction('hardDrop'); event.preventDefault(); break; - default: break; - } + const hit = this.actionFor(event.code); + if (hit) this.press(hit.i, hit.act, false); } - playerAction(action) { this.applyAction(0, action); } + onTouch(action, down) { + const map = { left: 'left', right: 'right', softDrop: 'soft', hardDrop: 'hard', rotateCW: 'cw', rotateCCW: 'ccw', super: 'smart' }; + this.press(0, map[action], down); + } - applyAction(idx, action) { + // held actions (left/right/soft) vs one-shots (everything else) + press(i, act, down) { + if (!this.held) return; + const h = this.held[i]; + if (act === 'left' || act === 'right') { + const dir = act === 'left' ? -1 : 1; + h[act] = down ? performance.now() : 0; + if (down) { + this.das[i] = { dir, t: 0, rep: 0 }; + this.act(i, act); + } else { + const other = act === 'left' ? 'right' : 'left'; + this.das[i] = h[other] ? { dir: -dir, t: 0, rep: 0 } : { dir: 0, t: 0, rep: 0 }; + } + return; + } + if (act === 'soft') { + h.soft = down; + if (down) { this.softTimer[i] = SOFT_DROP_MS; } + return; + } + if (down) this.act(i, act); + } + + busy(i) { + return !this.match || this.phase !== 'play' || this.replayQueue[i].length > 0 + || !this.match.players[i].piece || !this.pieceShown[i]; + } + + act(i, act) { + if (!this.match || this.paused || this.phase !== 'play') return; const m = this.match; - if (!m || m.over || this.overlayUp || this.view !== 'battle') return; - if (this.replayQueue[idx].length) return; // board busy animating - const p = m.players[idx]; - if (!p.piece) return; - - let locked = false; - let events = null; - switch (action) { - case 'left': if (moveLeft(m, idx) && idx === 0) playSound(this, SFX.UI_PICK); break; - case 'right': if (moveRight(m, idx) && idx === 0) playSound(this, SFX.UI_PICK); break; - case 'rotateCW': if (rotateCW(m, idx) && idx === 0) playSound(this, SFX.UI_PICK); break; - case 'rotateCCW': if (rotateCCW(m, idx) && idx === 0) playSound(this, SFX.UI_PICK); break; - case 'softDrop': { - const r = stepDown(m, idx); - locked = r.locked; events = r.events; - this.gravTimer[idx] = 0; - break; - } - case 'hardDrop': { - events = hardDrop(m, idx); - locked = true; - break; - } + if (act === 'purge' || act === 'overdrive' || act === 'smart') { + let tier = act === 'purge' ? 1 : act === 'overdrive' ? 3 : null; + if (act === 'smart') tier = canUseSuper(m, i, 3) ? 3 : (canUseSuper(m, i, 1) ? 1 : null); + if (tier) this.doSuper(i, tier); + return; + } + if (this.busy(i)) { + if (this.buffer[i].length < 3 && act !== 'soft') this.buffer[i].push(act); + return; + } + switch (act) { + case 'left': if (moveLeft(m, i)) { SFX.move(this); this.lockReset(i); } break; + case 'right': if (moveRight(m, i)) { SFX.move(this); this.lockReset(i); } break; + case 'cw': if (rotateCW(m, i)) { SFX.rotate(this); this.lockReset(i); } break; + case 'ccw': if (rotateCCW(m, i)) { SFX.rotate(this); this.lockReset(i); } break; + case 'hard': this.doHardDrop(i); break; + case 'soft': this.softStep(i); break; default: break; } - if (locked) this.onLocked(idx, events); - else this.updatePieceSprites(idx); } - // ── Spawn / lock / replay flow ────────────────────────────────────────────── - - beginSpawn(idx) { - const events = spawnPiece(this.match, idx); - this.enqueue(idx, events); - if (this.match.players[idx].piece && idx === 1) { - planPlacement(this.ai, this.match, 1); + lockReset(i) { + if (this.lockTimer[i] > 0 && this.lockResets[i] < LOCK_RESETS) { + this.lockTimer[i] = 0; + this.lockResets[i] += 1; } } - onLocked(idx, events) { - playSound(this, SFX.UI_PLACE); - this.updatePieceSprites(idx); // hides the piece (now null) - this.enqueue(idx, events); + softStep(i) { + const m = this.match; + if (canStepDown(m, i)) { + stepDown(m, i); + this.gravTimer[i] = 0; + } else { + this.onLocked(i, lockNow(m, i)); + } } - enqueue(idx, events) { - if (events?.length) this.replayQueue[idx].push(...events); - this.updateMeters(); + doHardDrop(i) { + const m = this.match; + const p = m.players[i]; + if (!p.piece) return; + const from = pieceCells(p.piece); + const to = getGhostCells(p); + const color = GEM_COLORS[p.piece.a.color ?? p.piece.b.color ?? 0] ?? 0xffffff; + this.boards[i].dropTrail(from, to, color); + const events = hardDrop(m, i); + this.onLocked(i, events, { slam: true, at: to }); } - // process one queued event; returns the delay before the next one - processEvent(idx, e) { - const left = BOARD_LEFT[idx]; + doSuper(i, tier) { + const events = useSuper(this.match, i, tier); + if (!events) return false; + this.fight.totals.supers[i] += 1; + this.replayQueue[i].push(...events); + if (tier === 3 && this.ais[i] && this.match.players[i].piece) planPlacement(this.ais[i], this.match, i); + return true; + } + + // ── spawn / lock / replay ─────────────────────────────────────────────────── + beginSpawn(i) { + const events = spawnPiece(this.match, i); + this.lockTimer[i] = 0; + this.lockResets[i] = 0; + this.gravTimer[i] = 0; + this.replayQueue[i].push(...events); + if (this.ais[i] && this.match.players[i].piece) planPlacement(this.ais[i], this.match, i); + } + + onLocked(i, events, { slam = false, at = null } = {}) { + this.pieceShown[i] = false; + this.boards[i].setPiece(null); + if (slam) { + SFX.slam(this); + if (at?.[0]) this.fx.puff(this.boards[i].left + at[0].c * CELL + CELL / 2, BOARD_TOP + (at[0].r - HIDDEN_ROWS) * CELL + CELL / 2, 0xffffff); + if (i === 0 || this.fight.versus) this.fx.shake(1); + } else { + SFX.lock(this); + } + this.replayQueue[i].push(...(events ?? [])); + } + + processEvent(i, e) { + const board = this.boards[i]; + const f = this.fight; switch (e.type) { case 'spawn': - this.updatePieceSprites(idx); - this.updatePreviews(); - if (idx === 0) playSound(this, SFX.UI_CHIME); + this.pieceShown[i] = true; + this.hud.setNext(i, peekPiece(this.match, this.match.players[i].pieceIndex), peekPiece(this.match, this.match.players[i].pieceIndex + 1)); break; case 'place': case 'settle': + board.applySnapshot(e, e); + break; case 'counter': - this.renderBoard(idx, e); + board.applySnapshot(e, e); + SFX.counterTick(this); break; case 'garbage': - this.renderBoard(idx, e); - if (e.cells?.length) playSound(this, SFX.GEM_CHAIN); - break; - case 'clear': - case 'diamond': { - this.renderBoard(idx, e); - playSound(this, SFX.GEM_MATCH_4); - for (const cell of e.cells ?? []) { - if (cell.r < HIDDEN_ROWS) continue; - const fx = this.add.rectangle( - left + cell.c * CELL + CELL / 2, - BOARD_TOP + (cell.r - HIDDEN_ROWS) * CELL + CELL / 2, - CELL - 4, CELL - 4, 0xffffff, 0.9, - ).setDepth(D.fx); - this.layer.add(fx); - this.tweens.add({ targets: fx, alpha: 0, scale: 1.4, duration: 260, onComplete: () => fx.destroy() }); + board.applySnapshot(e, e); + if (e.cells?.length) { + SFX.garbage(this, e.cells.length); + this.fx.shake(Math.min(8, e.cells.length / 3)); + this.arena.hit(i, e.cells.length); + this.emote(i === 0 ? 'happy' : 'upset'); } - if (e.type === 'clear' && e.chain >= 2) { - this.showCallout(`${e.chain} CHAIN!`); - if (idx === 0) this.oppPortrait?.playEmotion('upset'); - else this.oppPortrait?.playEmotion('happy'); + break; + case 'clear': { + board.applySnapshot(e, e); + const n = e.cells?.length ?? 0; + SFX.shatter(this, e.chain, n); + this.fx.shake(Math.min(10, n / 3 + (e.chain - 1) * 2)); + if (e.powerCells >= 4) this.fx.callout(e.powerCells >= 12 ? 'MEGA POWER!' : 'POWER!', { + x: board.centre().x, y: BOARD_TOP + 260, size: 46, color: '#ffd21f', hold: 500, + }); + if (e.chain >= 2) { + const big = e.chain >= 4; + this.fx.callout(big ? `${e.chain} CHAIN!!` : `${e.chain} CHAIN`, { + x: board.centre().x, y: BOARD_TOP + 160, size: 52 + e.chain * 8, color: SIDE_HEX[i], hold: 600, + }); + if (e.chain >= 3) { this.fx.hitstop(60 + e.chain * 20); this.fx.flash(SIDE_COLOR[i], 0.18 + e.chain * 0.03); } + this.emote(i === 0 ? 'upset' : 'happy'); } break; } - case 'attack': { - if (e.sent > 0) { - this.showCallout(`${idx === 0 ? 'YOU' : this.opponent.name} +${e.sent} ▶`, idx === 0 ? '#9be7b4' : '#ff8a8a'); - if (e.sent >= 6) this.oppPortrait?.playEmotion(idx === 0 ? 'upset' : 'happy'); - } + case 'diamond': + board.applySnapshot(e, e); + SFX.shatter(this, 3, e.cells?.length ?? 0); + this.fx.flash(0xffffff, 0.4); + this.fx.shake(6); + this.fx.callout('DIAMOND!', { x: board.centre().x, y: BOARD_TOP + 200, size: 64, color: '#b86bff', hold: 600 }); + break; + case 'attack': + this.onAttack(i, e); + break; + case 'super': { + board.applySnapshot(e, e); + SFX.superFire(this); + const name = e.name ?? (e.tier === 3 ? 'OVERDRIVE' : 'PURGE'); + this.fx.callout(`${name}!`, { size: 110, color: e.tier === 3 ? '#ffd21f' : SIDE_HEX[i], hold: 700, style: 'announce' }); + this.fx.flash(e.tier === 3 ? 0xffd21f : SIDE_COLOR[i], 0.35); + this.fx.shake(6); + this.arena.attack(i, 20, { super: true }); + this.time.delayedCall(200, () => { + if (!this.arena) return; + const from = this.arena.core(i); + this.fx?.beam(from, this.boards?.[i]?.centre() ?? from, e.tier === 3 ? 0xffd21f : SIDE_COLOR[i], 380); + }); break; } case 'lose': - this.renderBoard(idx, e); - this.endMatch(); + board.applySnapshot(e, e); + this.endRound(i); break; default: - this.renderBoard(idx, e); + board.applySnapshot(e, e); break; } - this.updateMeters(); + if (f.spec.mode === 'rush' && e.type === 'attack' && i === 0) { + f.rushScore += e.amount; + this.hud.setMode('GARBAGE RUSH', `SCORE ${f.rushScore}`); + } return REPLAY_DELAY[e.type] ?? 120; } - showCallout(text, color = COLORS.goldHex) { - this.calloutText.setText(text).setColor(color).setAlpha(1).setScale(0.7); - this.tweens.add({ targets: this.calloutText, scale: 1, duration: 140, ease: 'Back.easeOut' }); - this.tweens.add({ targets: this.calloutText, alpha: 0, delay: 850, duration: 300 }); - } - - // ── Rendering ─────────────────────────────────────────────────────────────── - - renderBoard(idx, snap) { - for (const o of this.boardObjs[idx]) o.destroy(); - this.boardObjs[idx] = []; - const left = BOARD_LEFT[idx]; - const inPower = new Set(); - for (const g of snap.powerGems ?? []) { - for (let r = g.y; r < g.y + g.h; r++) for (let c = g.x; c < g.x + g.w; c++) inPower.add(r * WIDTH + c); - const vr = Math.max(g.y, HIDDEN_ROWS); - const vh = g.y + g.h - vr; - if (vh <= 0) continue; - const gx = left + g.x * CELL; - const gy = BOARD_TOP + (vr - HIDDEN_ROWS) * CELL; - const pg = this.add.graphics().setDepth(D.cells); - pg.fillStyle(GEM_COLORS[g.color], 1); - pg.fillRoundedRect(gx + 2, gy + 2, g.w * CELL - 4, vh * CELL - 4, 12); - pg.fillStyle(0xffffff, 0.28); - pg.fillRoundedRect(gx + 8, gy + 6, g.w * CELL - 16, 16, 8); - pg.lineStyle(3, 0xffffff, 0.55); - pg.strokeRoundedRect(gx + 4, gy + 4, g.w * CELL - 8, vh * CELL - 8, 10); - pg.lineStyle(2, 0x000000, 0.35); - pg.strokeRoundedRect(gx + 2, gy + 2, g.w * CELL - 4, vh * CELL - 4, 12); - this.layer.add(pg); - this.boardObjs[idx].push(pg); + onAttack(i, e) { + const j = 1 - i; + const power = e.amount; + this.arena.attack(i, power, { chain: e.chain ?? 1 }); + if (e.offset > 0) { + this.arena.block(i); + this.fx.callout(`BLOCK ${e.offset}`, { + x: this.boards[i].trayPoint().x, y: BOARD_TOP + 60, size: 34, color: '#9fe9ff', hold: 400, style: 'small', + }); } - for (let r = HIDDEN_ROWS; r < snap.board.length; r++) { - for (let c = 0; c < WIDTH; c++) { - const cell = snap.board[r][c]; - if (!cell || inPower.has(r * WIDTH + c)) continue; - const x = left + c * CELL + CELL / 2; - const y = BOARD_TOP + (r - HIDDEN_ROWS) * CELL + CELL / 2; - const img = this.add.image(x, y, this.textureFor(cell)).setDepth(D.cells); - this.layer.add(img); - this.boardObjs[idx].push(img); - if (cell.kind === KIND.COUNTER) { - const t = this.add.text(x, y, String(cell.count), { - fontFamily: 'Righteous', fontSize: '26px', color: '#ffffff', stroke: '#000000', strokeThickness: 4, - }).setOrigin(0.5).setDepth(D.cells + 1); - this.layer.add(t); - this.boardObjs[idx].push(t); - } + if (e.sent > 0) { + SFX.whoosh(this, e.sent); + this.inFlight[j] += e.sent; + const from = this.arena.launchPoint(i); + const to = this.boards[j].trayPoint(); + if (e.sent >= 12) { + this.fx.callout(e.sent >= 24 ? `MEGA CRASH +${e.sent}` : `+${e.sent}`, { + size: e.sent >= 24 ? 84 : 70, color: SIDE_HEX[i], hold: 600, + }); } + const sent = e.sent; + const match = this.match; + this.fx.projectile(from, to, SIDE_COLOR[i], sent, () => { + if (!this.match || this.match !== match) return; + this.inFlight[j] = Math.max(0, this.inFlight[j] - sent); + SFX.impact(this, sent); + this.fx?.shake(Math.min(9, 2 + sent / 4)); + if (sent >= 10) this.fx?.hitstop(70); + this.arena?.hit(j, sent); + }); } } - textureFor(cell) { - if (cell.kind === KIND.DIAMOND) return 'bf-diamond'; - if (cell.kind === KIND.CRASH) return `bf-crash-${cell.color}`; - if (cell.kind === KIND.COUNTER) return `bf-counter-${cell.color}`; - return `bf-gem-${cell.color}`; + emote(emotion) { + if (this.fight?.versus || this.time.now < this.emoteAt) return; + this.emoteAt = this.time.now + 3500; + this.hud?.emote(emotion); } - updatePieceSprites(idx) { - const p = this.match.players[idx]; - const imgs = this.pieceImgs[idx]; - const ghosts = this.ghostImgs[idx]; - if (!p.piece) { - imgs.forEach((img) => img.setVisible(false)); - ghosts.forEach((g) => g.setVisible(false)); - return; - } - const left = BOARD_LEFT[idx]; - const cells = pieceCells(p.piece); - cells.forEach(({ r, c, half }, i) => { - imgs[i] - .setTexture(this.textureFor(p.piece[half])) - .setPosition(left + c * CELL + CELL / 2, BOARD_TOP + (r - HIDDEN_ROWS) * CELL + CELL / 2) - .setVisible(true) - .setAlpha(r < HIDDEN_ROWS ? 0.45 : 1); - }); - getGhostCells(p).forEach(({ r, c }, i) => { - ghosts[i] - .setPosition(left + c * CELL + CELL / 2, BOARD_TOP + (r - HIDDEN_ROWS) * CELL + CELL / 2) - .setVisible(r >= HIDDEN_ROWS); - }); - } - - updatePreviews() { - if (!this.match) return; - for (const i of [0, 1]) { - const p = this.match.players[i]; - const next = peekPiece(this.match, p.pieceIndex); - this.previewImgs[i][0].setTexture(this.textureFor(next.b)).setVisible(true); - this.previewImgs[i][1].setTexture(this.textureFor(next.a)).setVisible(true); - } - } - - updateMeters() { - if (!this.match || !this.garbageTexts) return; - for (const i of [0, 1]) { - const pending = this.match.players[i].pendingGarbage; - this.garbageTexts[i].setText(pending > 0 ? `⚠ ${pending} incoming` : ''); - this.sentTexts[i].setText(`Sent: ${this.match.players[i].garbageSent}`); - } - } - - // ── Main loop ─────────────────────────────────────────────────────────────── - + // ── per-frame ──────────────────────────────────────────────────────────────── update(time, delta) { - if (this.view !== 'battle' || !this.match || this.overlayUp) return; + if (!this.ready) return; + this.backdrop?.update(time, delta); + for (const g of this.menuGolems) g.update(time); + if (this.view !== 'battle' || !this.match) return; + + this.arena.update(time); + this.boards.forEach((b) => b.update(time, delta)); + this.refreshHud(); + if (this.paused || this.phase !== 'play') { this.drawPieces(); return; } + if (this.fx.frozen()) return; + const m = this.match; + const f = this.fight; + this.roundTime += delta; + + // rush clock + if (f.mode.timeLimitMs) { + f.timeLeft -= delta; + this.hud.setTimer(this.fmtTime(f.timeLeft), f.timeLeft < 15000); + if (f.timeLeft <= 0) { this.endFight(0); return; } + } + + // late-round speed-ups keep fights from stalling + const stage = this.roundTime > 150000 ? 2 : this.roundTime > 90000 ? 1 : 0; + if (stage > this.speedStage) { + this.speedStage = stage; + this.gravityMs = Math.max(120, Math.round(this.baseGravity * Math.pow(0.68, stage))); + this.fx.callout('SPEED UP!', { size: 76, color: '#ff7a3d', hold: 700 }); + SFX.speedUp(this); + this.backdrop.setTempo(1 + stage * 0.8); + } for (const i of [0, 1]) { - // replay queued engine events (board is frozen while animating) + // replay queued engine events (input is buffered meanwhile) if (this.replayQueue[i].length) { this.replayTimer[i] -= delta; - if (this.replayTimer[i] <= 0) { + while (this.replayTimer[i] <= 0 && this.replayQueue[i].length && this.phase === 'play') { const e = this.replayQueue[i].shift(); - this.replayTimer[i] = this.processEvent(i, e); + this.replayTimer[i] += this.processEvent(i, e); } - continue; + if (this.replayQueue[i].length || this.phase !== 'play') continue; } + this.replayTimer[i] = 0; if (m.over) continue; - const p = m.players[i]; - if (!p.piece) { - if (!p.lost) this.beginSpawn(i); - continue; - } + if (!p.piece) { if (!p.lost) this.beginSpawn(i); continue; } + if (!this.pieceShown[i]) continue; - // AI inputs - if (i === 1) { - const act = nextAction(this.ai, m, 1, time); - if (act) { - this.applyAction(1, act); - if (!m.players[1].piece) continue; // locked via soft/hard drop - } - } + // buffered inputs land first + while (this.buffer[i].length && p.piece) this.act(i, this.buffer[i].shift()); + if (!p.piece) continue; + + if (this.ais[i]) this.aiTick(i, time); + else this.humanTick(i, delta); + if (!p.piece) continue; // gravity this.gravTimer[i] += delta; if (this.gravTimer[i] >= this.gravityMs) { - this.gravTimer[i] = 0; - const r = stepDown(m, i); - if (r.locked) this.onLocked(i, r.events); - else this.updatePieceSprites(i); + this.gravTimer[i] -= this.gravityMs; + if (canStepDown(m, i)) stepDown(m, i); } - } - } - - // ── End of match ──────────────────────────────────────────────────────────── - - endMatch() { - if (this.matchEnded) return; - this.matchEnded = true; - const won = this.match.winner === 0; - const p = this.match.players[0]; - - this.oppPortrait?.playEmotion(won ? 'upset' : 'happy'); - playSound(this, won ? SFX.VICTORY_SHORT : SFX.CASINO_LOSE); - - api.post('/history/single-player', { - slug: 'blockfighter', - score: p.garbageSent, - opponentScores: [this.match.players[1].garbageSent], - result: won ? 'win' : 'loss', - }).catch(() => {}); - - if (won) { - if (this.level > this.levelsCompleted) this.levelsCompleted = this.level; - api.post('/puzzles/blockfighter/complete', { level: this.level }) - .then((res) => { - if (res?.levelsCompleted != null) this.levelsCompleted = Math.max(this.levelsCompleted, res.levelsCompleted); - }) - .catch(() => {}); - } - - this.time.delayedCall(900, () => this.showEndModal(won)); - } - - showEndModal(won) { - if (this.view !== 'battle' || !this.match) return; // user already left the battle - this.overlayUp = true; - const cx = GAME_WIDTH / 2; - const cy = GAME_HEIGHT / 2; - const dim = this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.62).setDepth(D.overlay).setInteractive(); - const panel = this.add.graphics().setDepth(D.overlay); - panel.fillStyle(COLORS.panel, 0.98); - panel.fillRoundedRect(cx - 340, cy - 210, 680, 420, 20); - panel.lineStyle(3, won ? COLORS.accent : COLORS.danger, 1); - panel.strokeRoundedRect(cx - 340, cy - 210, 680, 420, 20); - this.layer.add([dim, panel]); - - const p = this.match.players[0]; - const title = this.add.text(cx, cy - 140, won ? 'VICTORY!' : 'DEFEATED', { - fontFamily: 'Righteous', fontSize: '64px', color: won ? COLORS.goldHex : COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.overlayUI); - const stat = this.add.text(cx, cy - 55, - won - ? `You beat ${this.opponent.name}!\nGarbage sent: ${p.garbageSent} Best chain: ${p.bestChain}` - : `${this.opponent.name} buried you in gems.\nGarbage sent: ${p.garbageSent} Best chain: ${p.bestChain}`, { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.textHex, align: 'center', lineSpacing: 8, - }).setOrigin(0.5).setDepth(D.overlayUI); - this.layer.add([title, stat]); - - const btns = []; - if (won) { - const hasNext = this.level < this.bank.length; - if (hasNext) { - btns.push(new Button(this, cx, cy + 50, `Next Fight (${this.level + 1})`, () => this.showIntro(this.level + 1), - { width: 340, height: 60, fontSize: 26 }).setDepth(D.overlayUI)); + // lock delay + if (!canStepDown(m, i)) { + this.lockTimer[i] += delta; + if (this.lockTimer[i] >= LOCK_MS) { + this.onLocked(i, lockNow(m, i)); + continue; + } } else { - btns.push(this.add.text(cx, cy + 45, 'You beat every fighter. Champion!', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.overlayUI)); + this.lockTimer[i] = 0; } - btns.push(new Button(this, cx - 110, cy + 135, 'Rematch', () => this.startBattle(this.level), - { width: 200, height: 54, fontSize: 22, variant: 'ghost' }).setDepth(D.overlayUI)); - } else { - btns.push(new Button(this, cx - 110, cy + 80, 'Retry', () => this.startBattle(this.level), - { width: 200, height: 60, fontSize: 26 }).setDepth(D.overlayUI)); } - btns.push(new Button(this, cx + 120, won ? cy + 135 : cy + 80, 'Levels', () => this.showLevelSelect(), - { width: 200, height: 54, fontSize: 22, variant: 'ghost' }).setDepth(D.overlayUI)); - this.layer.add(btns); + this.drawPieces(); + this.updateDanger(time); + } + + humanTick(i, delta) { + const das = this.das[i]; + if (das.dir) { + das.t += delta; + if (das.t >= this.settings.das) { + das.rep += delta; + while (das.rep >= this.settings.arr && this.match.players[i].piece) { + das.rep -= this.settings.arr; + this.act(i, das.dir < 0 ? 'left' : 'right'); + } + } + } + if (this.held[i].soft) { + this.softTimer[i] += delta; + while (this.softTimer[i] >= SOFT_DROP_MS && this.match.players[i].piece) { + this.softTimer[i] -= SOFT_DROP_MS; + this.softStep(i); + if (!this.match.players[i].piece) break; + } + } + } + + aiTick(i, time) { + const m = this.match; + const ai = this.ais[i]; + if (time > this.aiSuperAt[i]) { + this.aiSuperAt[i] = time + 300; + const tier = decideSuper(ai, m, i); + if (tier) { this.doSuper(i, tier); return; } + } + const a = nextAction(ai, m, i, time); + if (!a) return; + switch (a) { + case 'left': moveLeft(m, i); break; + case 'right': moveRight(m, i); break; + case 'rotateCW': rotateCW(m, i); break; + case 'rotateCCW': rotateCCW(m, i); break; + case 'softDrop': this.softStep(i); break; + case 'hardDrop': this.doHardDrop(i); break; + default: break; + } + } + + drawPieces() { + const m = this.match; + for (const i of [0, 1]) { + const p = m.players[i]; + if (!p.piece || !this.pieceShown[i] || this.replayQueue[i].length) { this.boards[i].setPiece(null); continue; } + const falling = canStepDown(m, i); + const frac = falling ? Math.min(0.92, this.gravTimer[i] / this.gravityMs) : 0; + const ghost = this.settings.ghost ? getGhostCells(p) : null; + this.boards[i].setPiece(p.piece, pieceCells(p.piece), frac, ghost); + } + } + + stackHeight(i) { + const b = this.match.players[i].board; + for (let r = 0; r < HEIGHT; r++) if (b[r][SPAWN_COL]) return HEIGHT - r; + return 0; + } + + updateDanger(time) { + let worst = 0; + for (const i of [0, 1]) { + const h = this.stackHeight(i); + const level = Math.max(0, Math.min(1, (h - 8) / 4)); + this.boards[i].setDanger(level); + if (this.humans.includes(i)) worst = Math.max(worst, level); + } + if (worst > 0.2 && time > this.heartAt) { + this.heartAt = time + (worst > 0.7 ? 520 : 860); + SFX.heartbeat(this, worst > 0.7); + } + } + + refreshHud(force = false) { + if (!this.hud || !this.match) return; + for (const i of [0, 1]) { + const p = this.match.players[i]; + const pend = Math.max(0, p.pendingGarbage - this.inFlight[i]); + this.boards[i].setIncoming(pend, p.dropPattern[p.patternRow]); + const rose = this.hud.setSuper(i, p.super, canUseSuper(this.match, i, 1)); + const ready = p.super >= SUPER_MAX ? 3 : p.super >= SUPER_TIER ? 1 : 0; + if ((rose || ready > this.superWasReady[i]) && !force && this.humans.includes(i)) SFX.superCharge(this); + this.superWasReady[i] = ready; + this.hud.setStats(i, { sent: p.garbageSent, chain: p.bestChain, power: p.bestPower }); + } + } + + // ── pause ──────────────────────────────────────────────────────────────────── + togglePause() { + if (this.paused) { this.paused = false; this.closeOverlay(); return; } + this.paused = true; + this.overlay(() => showPause(this, { + controls: this.fight?.versus ? CONTROLS_VERSUS : CONTROLS_SOLO, + onResume: () => this.togglePause(), + onRestart: this.fight?.spec.mode === 'survival' ? null : () => { + const { spec, def } = this.fight; + this.startFight(spec, def); + }, + onQuit: () => this.showMenu(), + })); + } + + // ── round / fight end ─────────────────────────────────────────────────────── + accumulate() { + const t = this.fight.totals; + for (const i of [0, 1]) { + const p = this.match.players[i]; + t.sent[i] += p.garbageSent; + t.bestChain[i] = Math.max(t.bestChain[i], p.bestChain); + t.bestPower[i] = Math.max(t.bestPower[i], p.bestPower); + } + t.seconds += this.roundTime / 1000; + } + + endRound(loser) { + const f = this.fight; + if (!f || this.phase !== 'play') return; + const winner = 1 - loser; + + // Rush: knocking out the sandbag refills its board and scores a bonus + if (f.spec.mode === 'rush' && loser === 1) { + f.rushKOs += 1; + f.rushScore += RUSH_KO_BONUS; + this.hud.setMode('GARBAGE RUSH', `SCORE ${f.rushScore}`); + this.fx.callout(`K.O. +${RUSH_KO_BONUS}`, { size: 110, color: '#ffd21f', hold: 700, style: 'announce' }); + SFX.ko(this); + this.fx.shake(10); + this.arena.fighters[1].ko(); + this.time.delayedCall(1100, () => { + if (!this.match || this.fight !== f) return; + const snap = resetBoard(this.match, 1); + this.replayQueue[1] = []; + this.match.players[0].pendingGarbage = 0; + this.inFlight = [0, 0]; + this.boards[1].applySnapshot(snap, { type: 'reset' }); + this.arena.fighters[1].reset(); + this.beginSpawn(1); + }); + return; + } + + this.phase = 'ko'; + this.accumulate(); + f.wins[winner] += 1; + this.hud.setRounds(f.wins); + this.boards[loser].setPiece(null); + this.arena.ko(loser); + SFX.ko(this); + this.fx.flash(0xffffff, 0.55, 400); + this.fx.shake(14); + this.fx.callout('K.O.', { size: 200, color: '#ff2e63', hold: 1100, style: 'announce' }); + this.tweens.timeScale = 0.4; + this.time.delayedCall(900, () => { this.tweens.timeScale = 1; }); + if (!f.versus) this.hud.emote(loser === 0 ? 'happy' : 'upset'); + + this.time.delayedCall(2000, () => { + if (this.fight !== f) return; + if (f.wins[winner] >= f.mode.roundsToWin) this.endFight(winner); + else this.startRound(); + }); + } + + endFight(winner) { + const f = this.fight; + if (!f || this.phase === 'over') return; + if (this.phase === 'play') this.accumulate(); + this.phase = 'over'; + const mode = f.spec.mode; + const won = winner === 0; + const t = f.totals; + const quit = () => this.showMenu(); + + let data; + if (mode === 'ladder') { + const level = f.spec.level; + api.post('/history/single-player', { + slug: 'blockfighter', score: t.sent[0], opponentScores: [t.sent[1]], result: won ? 'win' : 'loss', + }).catch(() => {}); + if (won) { + if (level > this.levelsCompleted) this.levelsCompleted = level; + api.post('/puzzles/blockfighter/complete', { level }) + .then((res) => { if (res?.levelsCompleted != null) this.levelsCompleted = Math.max(this.levelsCompleted, res.levelsCompleted); }) + .catch(() => {}); + } + const hasNext = level < this.bank.length; + const buttons = []; + if (won && hasNext) buttons.push({ label: `Next Fight (${level + 1})`, primary: true, onClick: () => this.showFightIntro({ mode: 'ladder', level: level + 1 }) }); + buttons.push({ label: won ? 'Rematch' : 'Retry', primary: !won, onClick: () => this.startFight(f.spec, f.def) }); + buttons.push({ label: 'Ladder', onClick: () => this.showLadderScreen() }); + data = { + title: won ? 'VICTORY!' : 'DEFEATED', + won, + subtitle: won ? `You beat ${f.def.opponent.name} ${f.wins[0]}–${f.wins[1]}` : `${f.def.opponent.name} wins ${f.wins[1]}–${f.wins[0]}`, + note: won && !hasNext ? 'You beat every fighter. Champion of the grid!' : '', + buttons, + }; + } else if (mode === 'survival') { + if (won) { + this.run.superCarry = this.match?.players[0].super ?? 0; + this.run.sent += t.sent[0]; + this.run.bestChain = Math.max(this.run.bestChain, t.bestChain[0]); + const cleared = this.run.wave; + this.run.wave += 1; + data = { + title: `WAVE ${cleared} CLEAR`, won: true, + subtitle: `Super meter carried: ${Math.floor(this.run.superCarry)} / ${SUPER_MAX}`, + buttons: [ + { label: `Wave ${this.run.wave}`, primary: true, onClick: () => this.showFightIntro({ mode: 'survival' }) }, + { label: 'Give Up', onClick: () => this.finishSurvival() }, + ], + }; + } else { + this.run.sent += t.sent[0]; + this.run.bestChain = Math.max(this.run.bestChain, t.bestChain[0]); + return this.time.delayedCall(800, () => this.finishSurvival()); + } + } else if (mode === 'rush') { + const score = f.rushScore; + const best = recordBest('rush', score); + const timeUp = f.timeLeft <= 0; + if (timeUp) { this.fx.callout('TIME!', { size: 160, color: '#ffd21f', hold: 900, style: 'announce' }); SFX.ko(this); } + data = { + title: timeUp ? 'TIME UP' : 'TOPPED OUT', won: timeUp, + subtitle: `Final score ${score}`, + note: best ? 'NEW BEST!' : `Best: ${readBests().rush}`, + buttons: [ + { label: 'Again', primary: true, onClick: () => this.startFight(f.spec, this.fightDef(f.spec)) }, + { label: 'Menu', onClick: quit }, + ], + }; + data.lines = [['Score', score], ['Sandbag K.O.s', f.rushKOs], ['Best chain', t.bestChain[0] ? `×${t.bestChain[0]}` : '-'], ['Biggest power gem', t.bestPower[0] || '-']]; + data.rank = rankFor({ won: timeUp, sent: score / 2, bestChain: t.bestChain[0], bestPower: t.bestPower[0], seconds: t.seconds }); + } else { + data = { + title: winner === 0 ? 'PLAYER 1 WINS' : 'PLAYER 2 WINS', won: true, + subtitle: `${f.wins[0]} – ${f.wins[1]}`, + buttons: [ + { label: 'Rematch', primary: true, onClick: () => this.startFight(f.spec, f.def) }, + { label: 'Menu', onClick: quit }, + ], + }; + data.lines = [ + ['Sent (P1 · P2)', `${t.sent[0]} · ${t.sent[1]}`], + ['Best chain', `×${t.bestChain[0] || 0} · ×${t.bestChain[1] || 0}`], + ['Supers used', `${t.supers[0]} · ${t.supers[1]}`], + ]; + } + + if (!data.lines) { + data.lines = [ + ['Garbage sent', t.sent[0]], + ['Best chain', t.bestChain[0] ? `×${t.bestChain[0]}` : '-'], + ['Biggest power gem', t.bestPower[0] ? `${t.bestPower[0]} cells` : '-'], + ['Supers used', t.supers[0]], + ['Fight time', this.fmtTime(t.seconds * 1000)], + ]; + data.rank = rankFor({ won, sent: t.sent[0], bestChain: t.bestChain[0], bestPower: t.bestPower[0], seconds: t.seconds }); + } + if (!data.buttons.some((b) => b.label === 'Menu')) data.buttons.push({ label: 'Menu', onClick: quit }); + + SFX.sting(this, data.won ? 'win' : 'lose'); + this.time.delayedCall(1200, () => { + if (this.fight !== f) return; + this.overlay(() => showResults(this, data)); + }); + return null; + } + + finishSurvival() { + const r = this.run; + const waves = r.wave - 1; + const best = recordBest('survival', waves); + SFX.sting(this, waves > 0 ? 'win' : 'lose'); + this.overlay(() => showResults(this, { + title: 'RUN OVER', won: waves > 0, + subtitle: `You survived ${waves} wave${waves === 1 ? '' : 's'}`, + lines: [['Waves cleared', waves], ['Garbage sent', r.sent], ['Best chain', r.bestChain ? `×${r.bestChain}` : '-']], + rank: rankFor({ won: waves >= 5, sent: r.sent / Math.max(1, waves), bestChain: r.bestChain, bestPower: 0, seconds: 0 }), + note: best ? 'NEW BEST!' : `Best: wave ${readBests().survival}`, + buttons: [ + { label: 'New Run', primary: true, onClick: () => this.pickMode('survival') }, + { label: 'Menu', onClick: () => this.showMenu() }, + ], + })); } } + diff --git a/src/games/blockfighter/BlockFighterLogic.js b/src/games/blockfighter/BlockFighterLogic.js index ce108dd..da681dd 100644 --- a/src/games/blockfighter/BlockFighterLogic.js +++ b/src/games/blockfighter/BlockFighterLogic.js @@ -24,6 +24,14 @@ export const POWER_BONUS = 0.5; // extra attack per cleared power-gem cell export const ATTACK_DISCOUNT = 2; // cells "free" per clear step before attack export const DIAMOND_DAMAGE_DIV = 2; +// Super meter: 0..SUPER_MAX, spent in SUPER_TIER units. +export const SUPER_MAX = 300; +export const SUPER_TIER = 100; +export const SUPER_COST = { 1: 100, 3: 300 }; // tier 1 = Purge, tier 3 = Overdrive +export const SUPER_PER_ATTACK = 4; // per point of attack (sent or offset) +export const SUPER_PER_CHAIN = 12; // per chain link beyond the first +export const SUPER_PER_POWER = 2; // per cleared power-gem cell + export const SPEED_GRAVITY_MS = [null, 900, 750, 600, 475, 350]; // index = level speed 1-5 export const COLOR_LETTERS = 'RGBY'; @@ -68,7 +76,12 @@ function createPlayer(dropPattern) { garbageSent: 0, garbageReceived: 0, bestChain: 0, - lastResolve: { attack: 0, cleared: 0, chain: 0 }, + bestPower: 0, // largest power gem (cells) ever cleared + lastResolve: { attack: 0, cleared: 0, chain: 0, powerCells: 0 }, + nextCellId: 1, // stable ids let the renderer track cells as they fall + super: 0, + overdrive: 0, // pieces left to be forced into crash pairs + supersUsed: 0, lost: false, }; } @@ -83,6 +96,22 @@ export function createMatch({ seed = 1, dropPatterns = [null, null] } = {}) { }; } +// Wipe one player's board back to empty and reopen the match (Garbage Rush +// refills the sandbag this way). Stats and the super meter are kept. +export function resetBoard(match, pIdx) { + const p = match.players[pIdx]; + const fresh = createPlayer(null); + p.board = fresh.board; + p.powerGems = fresh.powerGems; + p.piece = null; + p.pendingGarbage = 0; + p.overdrive = 0; + p.lost = false; + match.over = false; + match.winner = null; + return snapshot(p); +} + function getSeqPiece(match, index) { while (match.pieceSeq.length <= index) { const i = match.pieceSeq.length; @@ -152,6 +181,10 @@ export function spawnPiece(match, pIdx) { const proto = getSeqPiece(match, player.pieceIndex); player.pieceIndex += 1; const piece = { a: { ...proto.a }, b: { ...proto.b }, row: 1, col: SPAWN_COL, orient: 0 }; + if (player.overdrive > 0) { + player.overdrive -= 1; + overdrivePiece(player, piece); + } if (!pieceFits(player.board, piece)) { player.lost = true; @@ -181,7 +214,7 @@ function dropGarbage(player) { const color = player.dropPattern[(player.patternRow + rowOffset) % 4][col]; const r = topOfStack(player.board, col) - 1; if (r < 0) continue; // column already full; the loss check happens at spawn - player.board[r][col] = { color, kind: KIND.COUNTER, count: COUNTER_START }; + player.board[r][col] = { color, kind: KIND.COUNTER, count: COUNTER_START, id: player.nextCellId++ }; placed.push({ r, c: col, color }); } player.patternRow = (player.patternRow + Math.ceil(n / WIDTH)) % 4; @@ -258,13 +291,13 @@ function lockPiece(match, pIdx) { const events = []; const live = !match.headless; // headless sims (AI search) skip snapshot events const push = (type, extra) => { if (live) events.push(evt(player, type, extra)); }; - player.lastResolve = { attack: 0, cleared: 0, chain: 0 }; + player.lastResolve = { attack: 0, cleared: 0, chain: 0, powerCells: 0 }; // Place: vertical pairs stack in-column; horizontal halves settle independently. const placedCells = []; const place = (half, r, c) => { if (r < 0) return; - player.board[r][c] = { ...half }; + player.board[r][c] = { ...half, id: player.nextCellId++ }; placedCells.push({ r, c }); }; let diamondPos = null; @@ -299,7 +332,7 @@ function lockPiece(match, pIdx) { if (cell && cell.color === below.color) { if (cell.powerId != null) player.powerGems.delete(cell.powerId); player.board[r][c] = null; - wiped.push({ r, c, color: cell.color, kind: cell.kind }); + wiped.push({ r, c, color: cell.color, kind: cell.kind, id: cell.id }); } } } @@ -307,7 +340,7 @@ function lockPiece(match, pIdx) { player.lastResolve.cleared += wiped.length; } player.board[diamondPos.r][diamondPos.c] = null; - push('diamond', { cells: wiped }); + push('diamond', { cells: wiped, color: below?.color ?? null, at: diamondPos }); } attack += runCascade(player, live ? events : null); @@ -321,7 +354,7 @@ function lockPiece(match, pIdx) { if (cell?.kind === KIND.COUNTER) { cell.count -= 1; if (cell.count <= 0) { - player.board[r][c] = { color: cell.color, kind: KIND.GEM }; + player.board[r][c] = { color: cell.color, kind: KIND.GEM, id: cell.id }; matured.push({ r, c, color: cell.color }); } } @@ -332,15 +365,128 @@ function lockPiece(match, pIdx) { attack += runCascade(player, live ? events : null); } - // Damage: offset our own pending garbage first, remainder goes to opponent. - player.lastResolve.attack = attack; + applyAttack(player, opponent, attack, push); + return events; +} + +// Damage: offset our own pending garbage first, remainder goes to opponent. +// Also charges the super meter. +function applyAttack(player, opponent, attack, push) { + const lr = player.lastResolve; + lr.attack = attack; + if (lr.powerCells > player.bestPower) player.bestPower = lr.powerCells; + const gain = attack * SUPER_PER_ATTACK + + Math.max(0, lr.chain - 1) * SUPER_PER_CHAIN + + lr.powerCells * SUPER_PER_POWER; + player.super = Math.min(SUPER_MAX, player.super + gain); if (attack > 0) { const offset = Math.min(attack, player.pendingGarbage); player.pendingGarbage -= offset; const sent = attack - offset; opponent.pendingGarbage += sent; player.garbageSent += sent; - push('attack', { amount: attack, offset, sent }); + push('attack', { amount: attack, offset, sent, chain: lr.chain, fromPower: lr.powerCells > 0, powerCells: lr.powerCells }); + } +} + +// ── Lock-delay support (timing lives in the scene) ────────────────────────── +export function canStepDown(match, pIdx) { + const player = match.players[pIdx]; + if (!player.piece || player.lost) return false; + return pieceFits(player.board, { ...player.piece, row: player.piece.row + 1 }); +} + +// Lock the current piece where it is (it must be resting). Returns events. +export function lockNow(match, pIdx) { + const player = match.players[pIdx]; + if (!player.piece || player.lost) return []; + return lockPiece(match, pIdx); +} + +// ── Super moves ────────────────────────────────────────────────────────────── +// Largest connected same-color groups (gems + crash gems), biggest first. +export function colorGroups(board) { + const seen = new Set(); + const groups = []; + for (let r = 0; r < HEIGHT; r++) { + for (let c = 0; c < WIDTH; c++) { + const cell = board[r][c]; + if (!cell || (cell.kind !== KIND.GEM && cell.kind !== KIND.CRASH) || seen.has(r * WIDTH + c)) continue; + let size = 0; + const stack = [[r, c]]; + seen.add(r * WIDTH + c); + while (stack.length) { + const [gr, gc] = stack.pop(); + size += 1; + for (const [dr, dc] of ORTH) { + const nr = gr + dr, nc = gc + dc; + if (nr < 0 || nr >= HEIGHT || nc < 0 || nc >= WIDTH || seen.has(nr * WIDTH + nc)) continue; + const n = board[nr][nc]; + if (n && n.color === cell.color && (n.kind === KIND.GEM || n.kind === KIND.CRASH)) { + seen.add(nr * WIDTH + nc); + stack.push([nr, nc]); + } + } + } + groups.push({ color: cell.color, size }); + } + } + return groups.sort((a, b) => b.size - a.size); +} + +function overdrivePiece(player, piece) { + const groups = colorGroups(player.board); + const first = groups[0]?.color ?? 0; + const second = groups.find((g) => g.color !== first)?.color ?? ((first + 1) % NUM_COLORS); + if (piece.a.kind !== KIND.DIAMOND) piece.a = { color: first, kind: KIND.CRASH }; + piece.b = { color: piece.a.kind === KIND.DIAMOND ? first : second, kind: KIND.CRASH }; +} + +export function canUseSuper(match, pIdx, tier) { + const player = match.players[pIdx]; + const cost = SUPER_COST[tier]; + if (!cost || match.over || player.lost || player.super < cost) return false; + if (tier === 1) { + for (const row of player.board) for (const cell of row) if (cell?.kind === KIND.COUNTER) return true; + return false; + } + return true; +} + +// tier 1 PURGE: every counter gem on your board becomes a plain gem now, then +// the board resolves (any crash gems touching them fire). +// tier 3 OVERDRIVE: the falling piece and the next one become crash pairs in +// the colors of your two biggest groups. +// Returns an event list, or null when the super can't be used. +export function useSuper(match, pIdx, tier) { + if (!canUseSuper(match, pIdx, tier)) return null; + const player = match.players[pIdx]; + const opponent = match.players[1 - pIdx]; + const events = []; + const live = !match.headless; + const push = (type, extra) => { if (live) events.push(evt(player, type, extra)); }; + player.super -= SUPER_COST[tier]; + player.supersUsed += 1; + player.lastResolve = { attack: 0, cleared: 0, chain: 0, powerCells: 0 }; + + if (tier === 1) { + const purged = []; + for (let r = 0; r < HEIGHT; r++) { + for (let c = 0; c < WIDTH; c++) { + const cell = player.board[r][c]; + if (cell?.kind === KIND.COUNTER) { + player.board[r][c] = { color: cell.color, kind: KIND.GEM, id: cell.id }; + purged.push({ r, c, color: cell.color }); + } + } + } + push('super', { tier, name: 'PURGE', cells: purged }); + const attack = runCascade(player, live ? events : null); + applyAttack(player, opponent, attack, push); + } else { + if (player.piece) overdrivePiece(player, player.piece); + player.overdrive = 1; + push('super', { tier, name: 'OVERDRIVE', piece: player.piece ? { ...player.piece, a: { ...player.piece.a }, b: { ...player.piece.b } } : null }); } return events; } @@ -352,15 +498,16 @@ function runCascade(player, events) { const fell = settle(player); const fused = fuseAll(player); if ((fell || fused) && events) events.push(evt(player, 'settle')); - const { cleared, powerCells } = crashClear(player); + const { cleared, powerCells, powerShapes } = crashClear(player); if (!cleared.length) break; chain += 1; player.bestChain = Math.max(player.bestChain, chain); player.lastResolve.cleared += cleared.length; + player.lastResolve.powerCells += powerCells; player.lastResolve.chain = Math.max(player.lastResolve.chain, chain); const mult = CHAIN_MULT[Math.min(chain - 1, CHAIN_MULT.length - 1)]; attack += Math.max(0, Math.ceil((cleared.length - ATTACK_DISCOUNT + powerCells * POWER_BONUS) * mult)); - if (events) events.push(evt(player, 'clear', { cells: cleared, chain })); + if (events) events.push(evt(player, 'clear', { cells: cleared, chain, powerCells, powerShapes })); } return attack; } @@ -550,7 +697,7 @@ function crashClear(player) { if (group.length >= 2) group.forEach(([gr, gc]) => toClear.add(gr * WIDTH + gc)); } } - if (!toClear.size) return { cleared: [], powerCells: 0 }; + if (!toClear.size) return { cleared: [], powerCells: 0, powerShapes: [] }; // Counter gems adjacent to a cleared cell of their own color also clear. for (const key of [...toClear]) { @@ -565,12 +712,17 @@ function crashClear(player) { } const cleared = []; + const powerShapes = []; let powerCells = 0; for (const key of toClear) { const r = Math.floor(key / WIDTH), c = key % WIDTH; const cell = board[r][c]; - if (cell.powerId != null) { powerCells += 1; powerGems.delete(cell.powerId); } - cleared.push({ r, c, color: cell.color, kind: cell.kind }); + if (cell.powerId != null) { + powerCells += 1; + const g = powerGems.get(cell.powerId); + if (g) { powerShapes.push({ ...g }); powerGems.delete(cell.powerId); } + } + cleared.push({ r, c, color: cell.color, kind: cell.kind, id: cell.id, power: cell.powerId != null }); board[r][c] = null; } // Drop powerId from any cells whose gem was destroyed (partial overlap can't @@ -582,7 +734,7 @@ function crashClear(player) { if (cell?.powerId != null && !powerGems.has(cell.powerId)) delete cell.powerId; } } - return { cleared, powerCells }; + return { cleared, powerCells, powerShapes }; } // ── AI support ─────────────────────────────────────────────────────────────── @@ -629,6 +781,7 @@ export function simulatePlacement(match, pIdx, col, orient) { attack: player.lastResolve.attack, cleared: player.lastResolve.cleared, chain: player.lastResolve.chain, + powerCells: player.lastResolve.powerCells, died: spawnBlocked, }; } diff --git a/src/games/blockfighter/tutorial.md b/src/games/blockfighter/tutorial.md index 358d48e..90e9bae 100644 --- a/src/games/blockfighter/tutorial.md +++ b/src/games/blockfighter/tutorial.md @@ -1,51 +1,81 @@ # Block Fighter -Go head-to-head against a rival in a falling-gem battle. Win by making your -opponent's board overflow — the fight is lost when a board's **spawn column** -(marked by the red arrow) fills to the top. +A neon falling-gem duel. Two gem-golems face off between the boards, and every +gem you crash turns into a punch thrown at your rival. You win when your rival's +**spawn column** (marked by the red arrow) fills to the top. -## The Basics +## Controls -- Pairs of gems fall onto your board. Move them with **← →** (or A/D), rotate - with **↑ / X / Z**, drop faster with **↓** (or S), and slam them down with - **Space**. On a touchscreen, use the buttons along the bottom. -- Gems come in four colors. They stack where they land — horizontal pairs split - and each half falls to its own column. +| Action | Keyboard | Touch | +|---|---|---| +| Move | **← →** or **A D** (hold to slide) | ◀ ▶ | +| Rotate | **↑ / X / W** clockwise, **Z** back | ⟳ ⟲ | +| Soft drop | **↓ / S**. Tap it at the bottom to lock right away | ▼ | +| Slam (hard drop) | **Space** | ⤓ | +| Purge / Overdrive | **C** / **V**, or **Shift** for the best one available | ★ | +| Pause | **Esc** or **P** | ❚❚ | + +A pair that touches down can still slide and spin for a moment before it locks. +Use that window to tuck gems into gaps. Horizontal pairs split, and each half +falls to its own column. ## Crash Gems -The round, glowing orbs are **Crash Gems**. When a Crash Gem touches any gem of -its own color, it destroys the entire connected group of that color. This is -your only way to clear gems — plan your stacks so one Crash Gem wipes out a -big cluster. +The pulsing orbs are **Crash Gems**. When one touches gems of its own color, the +whole connected group shatters. Crash Gems are your only way to clear gems, so +build big same-color groups first and crash them later. ## Power Gems -Build a solid rectangle of one color (2×2 or bigger) and it fuses into a giant -**Power Gem**. Power Gems count extra when destroyed, so building big before -you crash sends a much bigger attack. +Fill a solid rectangle of one color (2×2 or larger) and it fuses into a single +glowing **Power Gem**. Power Gems grow as you add full rows or columns beside +them. Shattering one hits much harder and fills your super meter faster. ## Chains -When gems are destroyed, everything above falls. If that drop brings another -Crash Gem into contact with its color, you get a **chain** — and every link in -the chain multiplies your attack. +When gems shatter, everything above them falls. If that fall brings another +Crash Gem into contact with its color, you get a **chain**. Each link +multiplies your attack, and your golem goes from a jab to a flurry to a +full-power strike. -## Counter Gems +## Counter Gems and Blocking -Attacks land on the enemy board as **Counter Gems** — numbered blocks that -can't be crashed right away. Each number ticks down once per piece you drop; -at zero they become normal gems. You can also destroy a Counter Gem early by -clearing gems of its color right next to it. If you attack while garbage is -queued against you, your attack cancels it out first. +Your attacks fly across the arena and land in your rival's **incoming tray** +above their board. On their next piece they rain down as numbered +**Counter Gems**. Each number ticks down once per piece dropped. At zero the +gem turns into a normal gem. You can break a Counter Gem early by shattering +gems of its color right next to it. + +If you attack while garbage is waiting in your own tray, your attack cancels it +first (a **block**). Only the leftover attack reaches your rival. + +## The Super Meter + +Attacks, chains and Power Gems fill the three-segment super meter under your +board. + +- **Purge** (1 segment): every Counter Gem on your board turns into a normal gem + at once, and any Crash Gem touching them fires. It's your comeback move. +- **Overdrive** (full meter): your falling pair and the next one become Crash + Gems in the colors of your two biggest groups. Line up a huge clear. ## The Diamond -Every 25th piece carries a **Diamond**. It destroys every gem of whatever -color it lands on — a great panic button, but it sends a weaker attack. +Every 25th piece carries a **Diamond**. It destroys every gem of the color it +lands on. It's a great panic button, but it sends a weaker attack. -## The Ladder +## Modes -Each level is a single battle against one fighter. Beat them to unlock the -next — opponents get smarter and faster as you climb. Lose, and you can retry -as many times as you like. +- **Ladder**: 20 fighters, each with their own style (builders, rushers, + chainers, turtles). Best of three rounds. Beat a fighter to unlock the next. +- **Survival**: endless waves of tougher fighters. Your super meter carries + over. One loss ends the run. +- **Garbage Rush**: two minutes to send as much attack as you can at a sandbag + that hits back. Knocking it out refills its board for a bonus. +- **Local Versus**: two players on one keyboard. + - P1: **A D** move, **S** soft, **W** slam, **F G** rotate, **R** super. + - P2: **← →** move, **↓** soft, **↑** slam, **, .** rotate, **/** super. + +Long rounds speed up at 1:30 and again at 2:30, so a stalled fight still ends. +Settings on the main menu let you tune auto-repeat and turn off the landing +ghost, screen shake or sound effects. diff --git a/src/services/soundtrack.js b/src/services/soundtrack.js index 9822745..7231f7c 100644 --- a/src/services/soundtrack.js +++ b/src/services/soundtrack.js @@ -24,6 +24,7 @@ export const GAME_SOUNDTRACK_OVERRIDES = { totalannihilation: 'hacker', coloradodefense: 'arcadedark', tempest: 'arcadedark', + blockfighter: 'arcadedark', defender: 'arcadedark', geometrywars: 'arcadedark', mastermind: 'hacker', diff --git a/tools/verifyBlockFighter.js b/tools/verifyBlockFighter.js index 0239948..3308c82 100644 --- a/tools/verifyBlockFighter.js +++ b/tools/verifyBlockFighter.js @@ -1,22 +1,26 @@ // Headless verification for Block Fighter. -// node server/scripts/verifyBlockFighter.js [--quick] +// node tools/verifyBlockFighter.js [--quick] // Exits non-zero on any failure. // // 1. Fixture tests: exact engine behavior on hand-built boards. // 2. AI-vs-AI self-play with invariant checks after every lock. // 3. Skill differentiation matrix (higher skill should win more). -// 4. Level bank lint (data/blockfighter.json vs opponents.json). +// 4. Supers + personalities in self-play. +// 5. Level bank lint (data/blockfighter.json vs opponents.json). import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; import { - WIDTH, HEIGHT, SPAWN_COL, KIND, COUNTER_START, SPEED_GRAVITY_MS, + WIDTH, HEIGHT, SPAWN_COL, KIND, COUNTER_START, SPEED_GRAVITY_MS, SUPER_MAX, createMatch, spawnPiece, stepDown, hardDrop, moveLeft, moveRight, rotateCW, rotateCCW, + canStepDown, lockNow, useSuper, canUseSuper, } from '../src/games/blockfighter/BlockFighterLogic.js'; -import { createAI, planPlacement, nextAction } from '../src/games/blockfighter/BlockFighterAI.js'; +import { + createAI, planPlacement, nextAction, decideSuper, PERSONALITIES, +} from '../src/games/blockfighter/BlockFighterAI.js'; const __dirname = dirname(fileURLToPath(import.meta.url)); const QUICK = process.argv.includes('--quick'); @@ -199,6 +203,89 @@ console.log('Fixtures:'); check('blocked spawn loses the match', p.lost && m.over && m.winner === 1); } +{ + // Cell ids: unique, stable through settling. + const m = freshMatch(); + const p = m.players[0]; + dropPiece(m, 0, gem(0), gem(1), 0); + dropPiece(m, 0, gem(2), gem(3), 0); + const ids = p.board.flat().filter(Boolean).map((c) => c.id); + check('placed cells get unique ids', ids.length === 4 && new Set(ids).size === 4 && ids.every((x) => x > 0)); + const topId = cellAt(p, BOTTOM - 3, 0).id; + put(p, BOTTOM, 1, crash(0)); // crash beside the red at the bottom + put(p, BOTTOM - 1, 1, gem(0)); + dropPiece(m, 0, gem(2), gem(2), 4); + check('ids survive a cascade fall', cellAt(p, BOTTOM - 2, 0)?.id === topId, + JSON.stringify(p.board.map((row) => row[0]?.id ?? '.'))); +} +{ + // Power gem cells keep their ids when fused. + const m = freshMatch(); + const p = m.players[0]; + dropPiece(m, 0, gem(2), gem(2), 0); + dropPiece(m, 0, gem(2), gem(2), 1); + const cells = p.board.flat().filter((c) => c?.powerId != null); + check('fused cells keep ids', cells.length === 4 && cells.every((c) => c.id > 0)); +} +{ + // canStepDown / lockNow agree with stepDown. + const m = freshMatch(); + const p = m.players[0]; + p.piece = { a: gem(0), b: gem(1), row: 1, col: 2, orient: 0 }; + check('canStepDown true in open air', canStepDown(m, 0)); + while (canStepDown(m, 0)) stepDown(m, 0); + check('canStepDown false when resting', !canStepDown(m, 0) && p.piece.row === BOTTOM); + const ev = lockNow(m, 0); + check('lockNow locks the resting piece', !p.piece && cellAt(p, BOTTOM, 2)?.color === 0 && ev.length > 0); +} +{ + // Super meter fills from attacks; Purge turns counters into gems and fires crash gems. + const m = freshMatch(); + const p = m.players[0]; + for (let r = 0; r < 4; r++) for (let c = 0; c < 2; c++) put(p, BOTTOM - r, c, gem(1)); + dropPiece(m, 0, crash(1), gem(0), 2, 3); + check('super meter charges from an attack', p.super > 0 && p.super <= SUPER_MAX, `super=${p.super}`); + + const m2 = freshMatch(); + const q = m2.players[0]; + put(q, BOTTOM, 0, counter(2)); + put(q, BOTTOM, 1, counter(2)); + put(q, BOTTOM, 2, crash(2)); + put(q, BOTTOM, 4, counter(3)); + check('purge unavailable without meter', !canUseSuper(m2, 0, 1)); + q.super = 100; + check('purge available with meter + counters', canUseSuper(m2, 0, 1)); + const ev = useSuper(m2, 0, 1); + check('purge returns events', Array.isArray(ev) && ev[0]?.type === 'super'); + check('purge converts counters and fires crash', countCells(q, (c) => c.kind === KIND.COUNTER) === 0 + && countCells(q, (c) => c.color === 2) === 0 && cellAt(q, BOTTOM, 4)?.kind === KIND.GEM, + JSON.stringify(q.board[BOTTOM])); + check('purge spends meter (the purge clear recharges a little)', q.super < 100, `super=${q.super}`); + check('purge refused when empty', useSuper(m2, 0, 1) === null); +} +{ + // Overdrive: current and next piece become crash pairs in the biggest group colors. + const m = freshMatch(); + const p = m.players[0]; + for (let c = 0; c < 4; c++) { put(p, BOTTOM, c, gem(3)); put(p, BOTTOM - 1, c, gem(3)); } + put(p, BOTTOM, 4, gem(1)); put(p, BOTTOM, 5, gem(1)); + spawnPiece(m, 0); + p.super = 300; + check('overdrive available at full meter', canUseSuper(m, 0, 3)); + useSuper(m, 0, 3); + check('overdrive converts falling piece', p.piece.a.kind === KIND.CRASH && p.piece.b.kind === KIND.CRASH + && p.piece.a.color === 3 && p.piece.b.color === 1, JSON.stringify(p.piece)); + hardDrop(m, 0); + spawnPiece(m, 0); + check('overdrive converts the next piece too', p.piece.a.kind === KIND.CRASH && p.piece.b.kind === KIND.CRASH); + hardDrop(m, 0); + spawnPiece(m, 0); + const proto = m.pieceSeq[p.pieceIndex - 1]; + check('overdrive wears off after two pieces', + p.piece.a.kind === proto.a.kind && p.piece.b.kind === proto.b.kind && p.piece.b.color === proto.b.color); + check('overdrive spent meter', p.super < 300 && p.supersUsed === 1); +} + // ── 2 & 3. Self-play with invariants + skill matrix ───────────────────────── function checkInvariants(match, tag) { for (const p of match.players) { @@ -230,12 +317,15 @@ function checkInvariants(match, tag) { } const TICK_MS = 25; -function playMatch(skillA, skillB, seed, speed = 3, pieceCap = 1200) { +function playMatch(skillA, skillB, seed, speed = 3, pieceCap = 1200, opts = {}) { const match = createMatch({ seed }); + const supers = opts.supers ?? false; + const pers = opts.personalities ?? ['balanced', 'balanced']; const ais = [ - createAI({ skill: skillA, speed, seed: seed * 2 + 1 }), - createAI({ skill: skillB, speed, seed: seed * 3 + 7 }), + createAI({ skill: skillA, speed, seed: seed * 2 + 1, personality: pers[0], useSupers: supers }), + createAI({ skill: skillB, speed, seed: seed * 3 + 7, personality: pers[1], useSupers: supers }), ]; + const superCount = [0, 0]; const gravityMs = SPEED_GRAVITY_MS[speed]; const gravTimer = [0, 0]; let now = 0; @@ -251,6 +341,14 @@ function playMatch(skillA, skillB, seed, speed = 3, pieceCap = 1200) { const p = match.players[i]; if (!p.piece) continue; let locked = false; + const tier = decideSuper(ais[i], match, i); + if (tier) { + useSuper(match, i, tier); + superCount[i] += 1; + checkInvariants(match, `super(seed=${seed})`); + if (match.over) break; + if (tier === 3 && match.players[i].piece) planPlacement(ais[i], match, i); + } const act = nextAction(ais[i], match, i, now); if (act === 'left') moveLeft(match, i); else if (act === 'right') moveRight(match, i); @@ -273,7 +371,7 @@ function playMatch(skillA, skillB, seed, speed = 3, pieceCap = 1200) { } } } - return { winner: match.over ? match.winner : null, pieces }; + return { winner: match.over ? match.winner : null, pieces, superCount }; } console.log('\nSelf-play invariants:'); @@ -310,7 +408,51 @@ console.log('\nSkill differentiation:'); } } -// ── 4. Level bank lint ─────────────────────────────────────────────────────── +console.log('\nSupers & personalities:'); +{ + const games = QUICK ? 6 : 20; + let supers = 0, decided = 0; + for (let s = 1; s <= games; s++) { + const r = playMatch(6, 6, s * 313, 3, 1200, { supers: true }); + supers += r.superCount[0] + r.superCount[1]; + if (r.winner !== null) decided += 1; + } + check(`self-play with supers runs clean (${games} games)`, true); + check('AIs actually use supers', supers > 0, `supers=${supers}`); + check('super games still reach a decision', decided >= games * 0.8, `${decided}/${games}`); + + for (const pers of PERSONALITIES) { + let wins = 0, done = 0, pieces = 0; + const n = QUICK ? 4 : 10; + for (let s = 1; s <= n; s++) { + const flip = s % 2 === 0; + const r = playMatch(6, 6, s * 53 + pers.length, 3, 1200, { + supers: true, personalities: flip ? ['balanced', pers] : [pers, 'balanced'], + }); + pieces += r.pieces; + if (r.winner === null) continue; + done += 1; + if ((flip && r.winner === 1) || (!flip && r.winner === 0)) wins += 1; + } + check(`${pers} finishes games (${wins}/${done} wins vs balanced, ${(pieces / n).toFixed(0)} pcs avg)`, done >= n * 0.75); + } + { + // higher skill still beats lower skill with supers on and differing styles + let hiWins = 0, decided = 0; + const n = QUICK ? 6 : 16; + for (let s = 1; s <= n; s++) { + const flip = s % 2 === 1; + const pers = PERSONALITIES[s % PERSONALITIES.length]; + const r = playMatch(flip ? 2 : 9, flip ? 9 : 2, s * 71, 3, 1200, { supers: true, personalities: [pers, pers] }); + if (r.winner === null) continue; + decided += 1; + if ((flip && r.winner === 1) || (!flip && r.winner === 0)) hiWins += 1; + } + check(`skill 9 beats 2 with supers (${hiWins}/${decided})`, decided && hiWins / decided >= 0.7); + } +} + +// ── 5. Level bank lint ─────────────────────────────────────────────────────── console.log('\nLevel bank:'); { const bank = JSON.parse(readFileSync(join(__dirname, '../data/blockfighter.json'), 'utf8')); @@ -325,9 +467,10 @@ console.log('\nLevel bank:'); if (!(lv.speed >= 1 && lv.speed <= 5)) ok = false; if (lv.dropPattern && !(Array.isArray(lv.dropPattern) && lv.dropPattern.length === 4 && lv.dropPattern.every((row) => /^[RGBY]{6}$/.test(row)))) ok = false; + if (lv.personality != null && !PERSONALITIES.includes(lv.personality)) ok = false; if (!ids.has(lv.opponentId)) console.warn(` warn: level ${lv.level} opponent '${lv.opponentId}' not in roster`); }); - check('levels contiguous with valid skill/speed/dropPattern', ok); + check('levels contiguous with valid skill/speed/dropPattern/personality', ok); } console.log(failures ? `\n${failures} FAILURE(S)` : '\nAll checks passed.');