1
0
Fork 0

feat(minigames): add procedural SFX and hit explosions to the versus duel

Sound is synthesized with the Web Audio API (no new assets): a launch
thump on fire, noise-burst impacts (splash for a miss, a bigger double
boom for a destroyed emplacement), a chime when the turn passes to you,
and victory/defeat fanfares. A mute button and volume slider live in the
match header; the setting persists per browser
(polaris:call-for-fire-versus-sound).

Adds a one-shot explosion VFX on hit and destroyed cells on both boards
(larger burst for a destroyed emplacement), suppressed under
prefers-reduced-motion. Only shots that arrive while watching animate, so
loading a match does not replay every past hit.
This commit is contained in:
Jason Fraley 2026-10-11 22:28:10 -04:00
parent a1a2dbdcac
commit 8afbf00805
5 changed files with 587 additions and 17 deletions

View file

@ -1943,6 +1943,64 @@
accent-color: var(--poker-trim);
}
/* Call for Fire: Versus */
.versus-sound-toggle {
display: flex;
align-items: center;
gap: 0.4rem;
}
.versus-sound-volume {
width: 4.5rem;
accent-color: #f59e0b;
}
.versus-explosion {
position: absolute;
inset: -25%;
z-index: 2;
border-radius: 9999px;
pointer-events: none;
background: radial-gradient(
circle,
rgba(254, 240, 138, 0.95) 0%,
rgba(249, 115, 22, 0.85) 42%,
rgba(239, 68, 68, 0) 72%
);
animation: versus-explosion 650ms ease-out both;
}
.versus-explosion-destroyed {
background: radial-gradient(
circle,
#ffffff 0%,
rgba(248, 113, 113, 0.95) 38%,
rgba(185, 28, 28, 0) 74%
);
}
@keyframes versus-explosion {
0% {
opacity: 0;
transform: scale(0.3);
}
25% {
opacity: 1;
transform: scale(0.85);
}
100% {
opacity: 0;
transform: scale(1.9);
}
}
@media (prefers-reduced-motion: reduce) {
.versus-explosion {
animation: none;
opacity: 0;
}
}
.poker-action-console:not(.poker-action-console-complete) {
grid-template-columns: minmax(0, 1.5fr) minmax(10rem, 0.8fr);
}

View file

@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Crosshair, Clock, RotateCcw, Shuffle, Target, Trophy, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@ -21,6 +21,8 @@ import {
import { cellsForFob } from "@/lib/minigames/call-for-fire-versus/engine";
import type { VersusFobView, VersusShotView } from "@/lib/minigames/call-for-fire-versus/types";
import { cn } from "@/lib/utils";
import { VersusSoundToggle } from "./VersusSoundToggle";
import { useVersusSounds } from "./useVersusSounds";
const BOARD = 10;
const CORRECTION_STEP = 50;
@ -103,10 +105,12 @@ function PlacementPhase({
match,
onMatch,
waiting,
onUi,
}: {
match: VersusMatchView;
onMatch: (next: VersusMatchView) => void;
waiting: boolean;
onUi: () => void;
}) {
const [placements, setPlacements] = useState<Record<string, FobPlacement>>(() => {
const initial: Record<string, FobPlacement> = {};
@ -188,10 +192,11 @@ function PlacementPhase({
...current,
[selectedId]: { assetId: selectedId, origin, orientation: placeOrientation },
}));
onUi();
const nextUnplaced = FOB_FLEET.find((f) => f.id !== selectedId && !placements[f.id]);
if (nextUnplaced) setSelectedId(nextUnplaced.id);
},
[occupied, orientation, placements, selectedId],
[occupied, onUi, orientation, placements, selectedId],
);
/** Double-click a placed line emplacement to flip its orientation in place. */
@ -228,8 +233,9 @@ function PlacementPhase({
...current,
[assetId]: { ...placement, orientation: nextOrientation },
}));
onUi();
},
[placements],
[onUi, placements],
);
const allPlaced = FOB_FLEET.every((definition) => placements[definition.id]);
@ -287,6 +293,7 @@ function PlacementPhase({
onClick={() => {
setPlacements(randomFleet());
setError(null);
onUi();
}}
>
<Shuffle /> Auto-deploy
@ -457,10 +464,10 @@ function buildBoards(you: VersusMatchView["you"]) {
for (const fob of you.fleet) {
for (const cell of fob.cells) myCells.set(key(cell), fob);
}
const incoming = new Map<string, VersusShotView>();
for (const shot of you.incoming) incoming.set(key(shot.grid), shot);
const myShots = new Map<string, VersusShotView>();
for (const shot of you.shots) myShots.set(key(shot.grid), shot);
const incoming = new Map<string, { shot: VersusShotView; index: number }>();
you.incoming.forEach((shot, index) => incoming.set(key(shot.grid), { shot, index }));
const myShots = new Map<string, { shot: VersusShotView; index: number }>();
you.shots.forEach((shot, index) => myShots.set(key(shot.grid), { shot, index }));
return { myCells, incoming, myShots };
}
@ -468,10 +475,12 @@ function BattlePhase({
match,
currentUserId,
onMatch,
onFire,
}: {
match: VersusMatchView;
currentUserId: number | string;
onMatch: (next: VersusMatchView) => void;
onFire: () => void;
}) {
const you = match.you;
const now = useNow();
@ -484,6 +493,12 @@ function BattlePhase({
const yourTurn = match.turnUserId !== null && String(match.turnUserId) === String(currentUserId);
const boards = buildBoards(you);
const firstShot = you.lastImpact === null;
// Only animate explosions for shots that arrive while watching (not those
// already on the board when the page loaded).
const initialIncomingRef = useRef<number | null>(null);
if (initialIncomingRef.current === null) initialIncomingRef.current = you.incoming.length;
const initialOutgoingRef = useRef<number | null>(null);
if (initialOutgoingRef.current === null) initialOutgoingRef.current = you.shots.length;
const secondsLeft =
match.turnDeadline === null
@ -507,6 +522,7 @@ function BattlePhase({
setBusy(false);
if (result.success && result.data) {
onMatch(result.data);
onFire();
setPendingGrid(null);
setRangeM(0);
setDeflectionM(0);
@ -517,6 +533,7 @@ function BattlePhase({
deflectionM,
firstShot,
match.matchId,
onFire,
onMatch,
pendingGrid,
rangeM,
@ -576,13 +593,25 @@ function BattlePhase({
{hit && (
<span
className={cn(
"absolute text-[11px] font-bold",
hit.outcome === "miss" ? "text-sky-300" : "text-red-300",
"absolute z-[3] text-[11px] font-bold",
hit.shot.outcome === "miss" ? "text-sky-300" : "text-red-300",
)}
>
{hit.outcome === "miss" ? "•" : "✕"}
{hit.shot.outcome === "miss" ? "•" : "✕"}
</span>
)}
{hit &&
hit.shot.outcome !== "miss" &&
initialIncomingRef.current !== null &&
hit.index >= initialIncomingRef.current && (
<span
className={cn(
"versus-explosion",
hit.shot.outcome === "destroyed" && "versus-explosion-destroyed",
)}
aria-hidden="true"
/>
)}
</ReadOnlyCell>
);
})}
@ -608,17 +637,34 @@ function BattlePhase({
key={`${x}-${y}`}
label={`grid ${cellLabel(x, y)}`}
className={cn(
shot?.outcome === "hit" && shot.assetId && fobStyle(shot.assetId).cell,
shot?.outcome === "destroyed" && "border-red-500/70 bg-red-600/40 text-red-50",
shot?.outcome === "hit" &&
!shot.assetId &&
shot && shot.shot.outcome === "hit" && shot.shot.assetId
? fobStyle(shot.shot.assetId).cell
: undefined,
shot &&
shot.shot.outcome === "destroyed" &&
"border-red-500/70 bg-red-600/40 text-red-50",
shot &&
shot.shot.outcome === "hit" &&
!shot.shot.assetId &&
"border-amber-500/70 bg-amber-500/20 text-amber-200",
pending && "border-sky-400 ring-2 ring-sky-400/60",
)}
interactive={Boolean(yourTurn && firstShot)}
onClick={() => setPendingGrid({ x, y })}
>
{pending ? "◉" : shot ? (shot.outcome === "miss" ? "•" : "✕") : ""}
{pending ? "◉" : shot ? (shot.shot.outcome === "miss" ? "•" : "✕") : ""}
{shot &&
shot.shot.outcome !== "miss" &&
initialOutgoingRef.current !== null &&
shot.index >= initialOutgoingRef.current && (
<span
className={cn(
"versus-explosion",
shot.shot.outcome === "destroyed" && "versus-explosion-destroyed",
)}
aria-hidden="true"
/>
)}
</ReadOnlyCell>
);
})}
@ -914,12 +960,19 @@ export function VersusMatch({
operatorsOnline: string[];
}) {
const waiting = match.you.opponentUserId === VERSUS_WAITING_USER_ID;
const sounds = useVersusSounds(match, currentUserId);
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-sm font-semibold">{match.name ?? "Artillery duel"}</h2>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<VersusSoundToggle
muted={sounds.muted}
volume={sounds.volume}
onToggleMuted={sounds.toggleMuted}
onVolumeChange={sounds.setVolume}
/>
<span>
{operatorsOnline.length} operator{operatorsOnline.length === 1 ? "" : "s"} on the net
</span>
@ -930,11 +983,16 @@ export function VersusMatch({
</div>
{match.phase === "placing" ? (
<PlacementPhase match={match} onMatch={onMatch} waiting={waiting} />
<PlacementPhase match={match} onMatch={onMatch} waiting={waiting} onUi={sounds.playUi} />
) : match.phase === "complete" ? (
<ResultPanel match={match} currentUserId={currentUserId} onLeave={onLeave} />
) : (
<BattlePhase match={match} currentUserId={currentUserId} onMatch={onMatch} />
<BattlePhase
match={match}
currentUserId={currentUserId}
onMatch={onMatch}
onFire={sounds.playFire}
/>
)}
</div>
);

View file

@ -0,0 +1,41 @@
"use client";
import { Volume2, VolumeX } from "lucide-react";
import { Button } from "@/components/ui/button";
export function VersusSoundToggle({
muted,
volume,
onToggleMuted,
onVolumeChange,
}: {
muted: boolean;
volume: number;
onToggleMuted: () => void;
onVolumeChange: (volume: number) => void;
}) {
return (
<div className="versus-sound-toggle" aria-label="Duel sound controls">
<Button
type="button"
variant="outline"
size="icon"
onClick={onToggleMuted}
aria-label={muted ? "Unmute duel sounds" : "Mute duel sounds"}
title={muted ? "Unmute duel sounds" : "Mute duel sounds"}
>
{muted ? <VolumeX aria-hidden="true" /> : <Volume2 aria-hidden="true" />}
</Button>
<input
type="range"
min={0}
max={1}
step={0.05}
value={muted ? 0 : volume}
onChange={(event) => onVolumeChange(Number(event.target.value))}
aria-label="Duel sound volume"
className="versus-sound-volume"
/>
</div>
);
}

View file

@ -0,0 +1,196 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { VersusMatchView } from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import { DEFAULT_VERSUS_SOUND_VOLUME, VersusSoundEngine } from "./versusSound";
const SOUND_SETTINGS_KEY = "polaris:call-for-fire-versus-sound";
interface VersusSoundSettings {
readonly muted: boolean;
readonly volume: number;
}
const DEFAULT_SETTINGS: VersusSoundSettings = {
muted: false,
volume: DEFAULT_VERSUS_SOUND_VOLUME,
};
function clampVolume(value: number): number {
if (!Number.isFinite(value)) return DEFAULT_VERSUS_SOUND_VOLUME;
return Math.min(1, Math.max(0, value));
}
function readStoredSettings(): VersusSoundSettings {
if (typeof window === "undefined") return DEFAULT_SETTINGS;
try {
const raw = window.localStorage.getItem(SOUND_SETTINGS_KEY);
if (!raw) return DEFAULT_SETTINGS;
const parsed: unknown = JSON.parse(raw);
if (
typeof parsed !== "object" ||
parsed === null ||
typeof (parsed as { muted?: unknown }).muted !== "boolean" ||
typeof (parsed as { volume?: unknown }).volume !== "number"
) {
return DEFAULT_SETTINGS;
}
return {
muted: (parsed as { muted: boolean }).muted,
volume: clampVolume((parsed as { volume: number }).volume),
};
} catch {
return DEFAULT_SETTINGS;
}
}
function writeStoredSettings(settings: VersusSoundSettings): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(SOUND_SETTINGS_KEY, JSON.stringify(settings));
} catch {
// Storage may be unavailable (private mode); sound still works this session.
}
}
function isExplosive(outcome: string): boolean {
return outcome === "hit" || outcome === "destroyed";
}
export interface VersusSoundControls {
muted: boolean;
volume: number;
toggleMuted: () => void;
setVolume: (volume: number) => void;
/** Call on a shot the player fires (launch sound before the impact lands). */
playFire: () => void;
/** Call on an editor action (place, rotate, auto-deploy). */
playUi: () => void;
}
/**
* Wires the versus sound engine to match transitions: new outgoing/incoming
* shots play an impact, the turn passing to the player plays a chime, and
* completion plays a fanfare. Settings persist per browser.
*/
export function useVersusSounds(
match: VersusMatchView | null,
currentUserId: number | string,
): VersusSoundControls {
const [settings, setSettings] = useState<VersusSoundSettings>(DEFAULT_SETTINGS);
const settingsRef = useRef<VersusSoundSettings>(DEFAULT_SETTINGS);
settingsRef.current = settings;
const engineRef = useRef<VersusSoundEngine | null>(null);
const loadedRef = useRef(false);
const prevOutgoingRef = useRef<number | null>(null);
const prevIncomingRef = useRef<number | null>(null);
const prevTurnRef = useRef<number | null | undefined>(undefined);
const prevPhaseRef = useRef<string | null>(null);
const ensureEngine = useCallback((): VersusSoundEngine => {
const engine = engineRef.current ?? new VersusSoundEngine();
engineRef.current = engine;
engine.setVolume(settingsRef.current.volume);
engine.setMuted(settingsRef.current.muted);
engine.unlock();
return engine;
}, []);
const toggleMuted = useCallback(() => {
const muted = !settingsRef.current.muted;
settingsRef.current = { ...settingsRef.current, muted };
setSettings((current) => ({ ...current, muted }));
ensureEngine();
}, [ensureEngine]);
const setVolume = useCallback(
(volume: number) => {
const next = clampVolume(volume);
settingsRef.current = { ...settingsRef.current, volume: next };
setSettings((current) => ({ ...current, volume: next }));
ensureEngine();
},
[ensureEngine],
);
const playFire = useCallback(() => {
ensureEngine().play({ type: "fire" });
}, [ensureEngine]);
const playUi = useCallback(() => {
ensureEngine().play({ type: "ui" });
}, [ensureEngine]);
useEffect(() => {
setSettings(readStoredSettings());
loadedRef.current = true;
}, []);
useEffect(() => {
if (loadedRef.current) writeStoredSettings(settings);
}, [settings]);
useEffect(() => {
return () => {
engineRef.current?.dispose();
engineRef.current = null;
};
}, []);
useEffect(() => {
if (!match) {
prevOutgoingRef.current = null;
prevIncomingRef.current = null;
prevTurnRef.current = undefined;
prevPhaseRef.current = null;
return;
}
const engine = engineRef.current;
const you = match.you;
const outgoing = you.shots.length;
const incoming = you.incoming.length;
if (engine) {
if (prevOutgoingRef.current !== null && outgoing > prevOutgoingRef.current) {
for (const shot of you.shots.slice(prevOutgoingRef.current)) {
engine.play({ type: "impact", outcome: shot.outcome });
}
}
if (prevIncomingRef.current !== null && incoming > prevIncomingRef.current) {
for (const shot of you.incoming.slice(prevIncomingRef.current)) {
engine.play({ type: "impact", outcome: shot.outcome });
}
}
const turnBecameYours =
prevTurnRef.current !== undefined &&
prevTurnRef.current !== match.turnUserId &&
match.turnUserId !== null &&
String(match.turnUserId) === String(currentUserId) &&
match.phase === "battle";
if (turnBecameYours) engine.play({ type: "your-turn" });
if (prevPhaseRef.current !== null && prevPhaseRef.current !== "complete" && match.phase === "complete") {
const won =
match.result?.winnerUserId !== null &&
match.result?.winnerUserId !== undefined &&
String(match.result.winnerUserId) === String(currentUserId);
engine.play({ type: won ? "victory" : "defeat" });
}
}
prevOutgoingRef.current = outgoing;
prevIncomingRef.current = incoming;
prevTurnRef.current = match.turnUserId;
prevPhaseRef.current = match.phase;
}, [match, currentUserId]);
return {
muted: settings.muted,
volume: settings.volume,
toggleMuted,
setVolume,
playFire,
playUi,
};
}

View file

@ -0,0 +1,217 @@
/**
* Procedural sound effects for the Call for Fire versus mode.
*
* Pure Web Audio, no sampled assets: impacts are synthesized noise bursts and
* notifications are short tones, so nothing new ships in /public. Client-only:
* the AudioContext is created lazily and only resumes after a user gesture.
*/
export const DEFAULT_VERSUS_SOUND_VOLUME = 0.35;
export type VersusImpactOutcome = "miss" | "hit" | "destroyed";
export type VersusSoundEvent =
| { readonly type: "fire" }
| { readonly type: "impact"; readonly outcome: VersusImpactOutcome }
| { readonly type: "your-turn" }
| { readonly type: "victory" }
| { readonly type: "defeat" }
| { readonly type: "ui" };
type Tone = readonly [frequency: number, offset: number, duration: number];
function clampVolume(value: number): number {
if (!Number.isFinite(value)) return DEFAULT_VERSUS_SOUND_VOLUME;
return Math.min(1, Math.max(0, value));
}
export class VersusSoundEngine {
private context: AudioContext | null = null;
private master: GainNode | null = null;
private muted = false;
private volume = DEFAULT_VERSUS_SOUND_VOLUME;
private noiseBuffer: AudioBuffer | null = null;
setMuted(muted: boolean): void {
this.muted = muted;
this.applyGain();
}
setVolume(volume: number): void {
this.volume = clampVolume(volume);
this.applyGain();
}
/** Resume the context; call from a user gesture before expecting audio. */
unlock(): void {
const context = this.ensureContext();
if (!context) return;
if (context.state === "suspended") void context.resume().catch(() => undefined);
}
dispose(): void {
const context = this.context;
this.context = null;
this.master = null;
this.noiseBuffer = null;
if (context) void context.close().catch(() => undefined);
}
play(event: VersusSoundEvent): void {
const context = this.ensureContext();
const master = this.master;
if (!context || this.muted || !master) return;
const now = context.currentTime;
switch (event.type) {
case "fire":
this.playFire(context, now);
return;
case "impact":
this.playImpact(context, now, event.outcome);
return;
case "your-turn":
this.playTones(context, now, [
[880, 0, 0.09],
[1320, 0.1, 0.09],
], "triangle", 0.16);
return;
case "victory":
this.playTones(context, now, [
[523, 0, 0.12],
[659, 0.11, 0.12],
[784, 0.22, 0.14],
[1047, 0.35, 0.24],
], "triangle", 0.2);
return;
case "defeat":
this.playTones(context, now, [
[392, 0, 0.14],
[311, 0.14, 0.16],
[233, 0.3, 0.28],
], "sine", 0.18);
return;
case "ui":
this.playTone(context, now, 720, 0.04, 0.05, "triangle");
return;
}
}
private ensureContext(): AudioContext | null {
if (typeof window === "undefined") return null;
if (this.context) return this.context;
const ctor = (window.AudioContext ??
(window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext) as
| typeof AudioContext
| undefined;
if (!ctor) return null;
try {
const context = new ctor();
const master = context.createGain();
master.gain.value = this.muted ? 0 : this.volume;
master.connect(context.destination);
this.context = context;
this.master = master;
return context;
} catch {
return null;
}
}
private applyGain(): void {
if (this.master && this.context) this.master.gain.value = this.muted ? 0 : this.volume;
}
private playTone(
context: AudioContext,
at: number,
frequency: number,
duration: number,
gain: number,
type: OscillatorType,
endFrequency?: number,
): void {
const master = this.master;
if (!master) return;
const osc = context.createOscillator();
const envelope = context.createGain();
osc.type = type;
osc.frequency.setValueAtTime(frequency, at);
if (endFrequency !== undefined) {
osc.frequency.exponentialRampToValueAtTime(Math.max(1, endFrequency), at + duration);
}
envelope.gain.setValueAtTime(0.0001, at);
envelope.gain.exponentialRampToValueAtTime(gain, at + Math.min(0.015, duration * 0.3));
envelope.gain.exponentialRampToValueAtTime(0.0001, at + duration);
osc.connect(envelope);
envelope.connect(master);
osc.start(at);
osc.stop(at + duration + 0.02);
}
private playTones(
context: AudioContext,
at: number,
tones: readonly Tone[],
type: OscillatorType,
gain: number,
): void {
for (const [frequency, offset, duration] of tones) {
this.playTone(context, at + offset, frequency, duration, gain, type);
}
}
private noise(context: AudioContext): AudioBuffer {
if (this.noiseBuffer) return this.noiseBuffer;
const length = Math.floor(context.sampleRate);
const buffer = context.createBuffer(1, length, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i += 1) data[i] = Math.random() * 2 - 1;
this.noiseBuffer = buffer;
return buffer;
}
private playNoise(
context: AudioContext,
at: number,
duration: number,
gain: number,
filterFrequency: number,
): void {
const master = this.master;
if (!master) return;
const source = context.createBufferSource();
source.buffer = this.noise(context);
const filter = context.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.setValueAtTime(filterFrequency, at);
const envelope = context.createGain();
envelope.gain.setValueAtTime(gain, at);
envelope.gain.exponentialRampToValueAtTime(0.0001, at + duration);
source.connect(filter);
filter.connect(envelope);
envelope.connect(master);
source.start(at);
source.stop(at + duration + 0.02);
}
private playFire(context: AudioContext, at: number): void {
this.playTone(context, at, 180, 0.22, 0.26, "sawtooth", 60);
this.playNoise(context, at, 0.14, 0.12, 900);
}
private playImpact(context: AudioContext, at: number, outcome: VersusImpactOutcome): void {
if (outcome === "miss") {
this.playNoise(context, at, 0.22, 0.16, 1400);
this.playTone(context, at, 150, 0.16, 0.11, "sine", 70);
return;
}
const destroyed = outcome === "destroyed";
this.playNoise(context, at, destroyed ? 0.7 : 0.45, destroyed ? 0.46 : 0.32, 2200);
this.playTone(context, at, 120, 0.35, 0.28, "sine", 40);
if (destroyed) {
this.playNoise(context, at + 0.16, 0.5, 0.32, 1600);
this.playTone(context, at + 0.14, 90, 0.4, 0.26, "sine", 32);
}
}
}