Add character emotes across bot friend and ranked matches
This commit is contained in:
@@ -14,6 +14,7 @@ interface FriendConfig {
|
||||
matchId: string; slot: 0 | 1; engine: MatchEngine; peer: GamePeer; clock: GameClock;
|
||||
setOffset(offset: number): void; changed(): void; finished(): void;
|
||||
saved?: { confirmed?: MatchCheckpoint; epoch: number };
|
||||
onEmote?(id: unknown): void;
|
||||
}
|
||||
export function createFriendMatch(config: FriendConfig) {
|
||||
const { peer, engine, clock } = config;
|
||||
@@ -160,6 +161,10 @@ export function createFriendMatch(config: FriendConfig) {
|
||||
if (message.type === 'ping' || message.type === 'clock:ping') { send(message.type === 'ping' ? 'pong' : 'clock:pong', { sentAt: message.sentAt, remoteAt: now() }); return; }
|
||||
if (message.type === 'clock:pong') { if (Number.isFinite(message.remoteAt)) clockReplies.get(message.sentAt)?.resolve(message.remoteAt); clockReplies.delete(message.sentAt); return; }
|
||||
if (message.type === 'pong') return;
|
||||
if (message.type === 'emote') {
|
||||
if (!recovering && engine.view().phase !== 'finished') config.onEmote?.(message.id);
|
||||
return;
|
||||
}
|
||||
if (message.type === 'ready') { if (message.slot === config.slot) throw new Error('INVALID_SLOT'); peerReady = true; maybeStart(); return; }
|
||||
if (message.type === 'resume' || message.type === 'resume:ack') {
|
||||
if (!recovering) return;
|
||||
@@ -205,6 +210,10 @@ export function createFriendMatch(config: FriendConfig) {
|
||||
catch { abort('connection_failed'); }
|
||||
},
|
||||
get recovering() { return recovering; },
|
||||
sendEmote(id: import('../../constants/emotes.js').EmoteId) {
|
||||
if (stopped || recovering || !peer.connected || engine.view().phase === 'finished') return false;
|
||||
try { send('emote', { id }); return true; } catch { return false; }
|
||||
},
|
||||
submitAction() { if (!recovering && !stopped) run(() => exchange!.commit(engine.view().ownAction)); },
|
||||
requestRematch() { engine.requestRematch(config.slot); if (peer.connected) send('match:rematch'); config.changed(); },
|
||||
snapshot: () => ({ confirmed: structuredClone(confirmed), epoch: peer.epoch, privateChoice }),
|
||||
|
||||
@@ -238,6 +238,15 @@ export function createLobbyFeatures(options: LobbyOptions) {
|
||||
consume(status); return status.match?.ownAction === action;
|
||||
} catch (error) { options.onError(error); return false; }
|
||||
},
|
||||
async sendEmote(id: import('../../constants/emotes.js').EmoteId) {
|
||||
if (!latest?.match || !active) return false;
|
||||
const matchId = latest.match.matchId;
|
||||
try {
|
||||
const status = await api.request<RankedStatus>('/api/ranked/emote', 'POST', { matchId, id });
|
||||
if (!active || latest?.match?.matchId !== matchId) return false;
|
||||
consume(status); return true;
|
||||
} catch (error) { options.onError(error); return false; }
|
||||
},
|
||||
leave,
|
||||
async rematch() { await leave(); if (!active) await start(); },
|
||||
};
|
||||
|
||||
+2
-1
@@ -110,7 +110,8 @@ function showMatch(state: LocalMatchState) {
|
||||
if (currentScreen !== 'result' || state.phase !== 'finished') setScreen('match');
|
||||
if (!view) view = createMatchView(el('match'), action => currentMatch?.ranked ? lobby!.submitAction(action) : controller?.submitAction(action) ?? Promise.resolve(false),
|
||||
() => { void perform(() => currentMatch?.ranked ? lobby!.rematch() : controller ? controller.rematch() : rematch(), 'rematch'); },
|
||||
() => { void perform(leave); }, () => setScreen('result'), footer.openRules);
|
||||
() => { void perform(leave); }, () => setScreen('result'), footer.openRules, undefined,
|
||||
id => currentMatch?.ranked ? lobby!.sendEmote(id) : controller?.sendEmote(id) ?? false);
|
||||
view.update(state);
|
||||
if (state.finished?.saved && !state.ranked) stats(state.finished.stats);
|
||||
if (state.saveStatus === 'failed') el('reconnect').hidden = false;
|
||||
|
||||
@@ -4,6 +4,8 @@ import type { ActiveMatch, LocalMatchState, MatchCheckpoint, RecordAck, ResultSu
|
||||
import type { ActionId } from '../shared/types.js';
|
||||
import type { SessionStorage } from './result-reporter.js';
|
||||
import { createFriendMatch, type GamePeer } from './friend-match.js';
|
||||
import { createEmotes } from '../shared/emotes.js';
|
||||
import type { EmoteId } from '../../constants/emotes.js';
|
||||
|
||||
export interface GameClock { now(): number; setTimeout(fn: () => void, ms: number): any; clearTimeout(id: any): void }
|
||||
export interface ControllerConfig {
|
||||
@@ -20,12 +22,14 @@ export function createMatchController(config: ControllerConfig) {
|
||||
const engine = createMatchEngine({ ...config.activeMatch, selfIndex: config.selfIndex, clock: { now: () => clock.now() + offset }, random: config.random });
|
||||
let friend: ReturnType<typeof createFriendMatch> | undefined;
|
||||
const listeners = new Set<(state: LocalMatchState) => void>();
|
||||
const emotes = createEmotes();
|
||||
const view = () => ({ ...engine.view(), appearances: config.activeMatch.appearances, emotes: emotes.view(clock.now() + offset) });
|
||||
let timer: any, destroyed = false, started = false, recording = false;
|
||||
function publish() {
|
||||
if (destroyed) return;
|
||||
const checkpoint: ControllerCheckpoint = { gameSessionId: config.gameSessionId, activeMatch: config.activeMatch, checkpoint: engine.checkpoint(), epoch: 0, ...friend?.snapshot() };
|
||||
config.storage.setItem(GAME_CHECKPOINT_KEY, JSON.stringify(checkpoint));
|
||||
for (const listener of listeners) listener({ ...engine.view(), appearances: config.activeMatch.appearances });
|
||||
for (const listener of listeners) listener(view());
|
||||
}
|
||||
async function record() {
|
||||
const state = engine.view(); if (!state.finished || state.finished.saved || recording || destroyed) return;
|
||||
@@ -63,7 +67,8 @@ export function createMatchController(config: ControllerConfig) {
|
||||
if (config.activeMatch.mode === 'friend') {
|
||||
if (!config.peer) throw new Error('PEER_REQUIRED');
|
||||
friend = createFriendMatch({ matchId: config.activeMatch.matchId, slot: config.selfIndex, engine, peer: config.peer, clock,
|
||||
setOffset: value => { offset = value; }, changed: publish, finished: () => { void record(); }, saved });
|
||||
setOffset: value => { offset = value; }, changed: publish, finished: () => { void record(); }, saved,
|
||||
onEmote: id => { if (emotes.send(config.selfIndex === 0 ? 1 : 0, id, clock.now() + offset)) publish(); } });
|
||||
await friend.start(); return;
|
||||
}
|
||||
if (!saved) engine.start();
|
||||
@@ -86,8 +91,16 @@ export function createMatchController(config: ControllerConfig) {
|
||||
await config.onRematch?.();
|
||||
if (!destroyed) friend?.requestRematch();
|
||||
},
|
||||
view: () => ({ ...engine.view(), appearances: config.activeMatch.appearances }),
|
||||
subscribe(listener: (state: LocalMatchState) => void) { listeners.add(listener); listener({ ...engine.view(), appearances: config.activeMatch.appearances }); return () => { listeners.delete(listener); }; },
|
||||
sendEmote(id: EmoteId) {
|
||||
if (destroyed || !started || engine.view().phase === 'finished' || friend?.recovering) return false;
|
||||
const now = clock.now() + offset;
|
||||
if (config.activeMatch.mode === 'friend' && !config.peer?.connected) return false;
|
||||
if (!emotes.send(config.selfIndex, id, now)) return false;
|
||||
if (friend && !friend.sendEmote(id)) return false;
|
||||
publish(); return true;
|
||||
},
|
||||
view,
|
||||
subscribe(listener: (state: LocalMatchState) => void) { listeners.add(listener); listener(view()); return () => { listeners.delete(listener); }; },
|
||||
retrySave: record,
|
||||
destroy() { destroyed = true; clock.clearTimeout(timer); friend?.destroy(); listeners.clear(); },
|
||||
};
|
||||
|
||||
@@ -6,19 +6,34 @@ import { createActionRenderer } from './action-renderer.js';
|
||||
import { actionIcon, ashPileArt, checkIcon, fighterArt } from './fighter-art.js';
|
||||
import { createFinishCutscene } from './finish-cutscene.js';
|
||||
import { matchIntroductionMessage } from '../shared/match-introduction.js';
|
||||
import { EMOTE_COOLDOWN_MS, EMOTE_IDS, EMOTE_LABELS, EMOTE_LINES, type EmoteId } from '../../constants/emotes.js';
|
||||
|
||||
const fighter = (i: number, appearance?: FighterAppearance) => `<div class="fighter" data-fighter="${i}">
|
||||
<div class="emote-bubble" role="status" hidden></div>
|
||||
<div class="avatar"><div class="aura"></div><div class="motion-trails"><i></i><i></i><i></i></div><div class="character-direction">${fighterArt(i, false, appearance)}</div>${ashPileArt()}<div class="projectile"></div><div class="shield"></div><div class="impact"></div></div>
|
||||
<div class="fighter-caption"><span class="choice-status"></span><span class="action-label"></span><span class="energy-change" aria-hidden="true"></span></div>
|
||||
</div>`;
|
||||
|
||||
export function createMatchView(container: HTMLElement, onAction: (action: ActionId) => Promise<boolean>, onRematch: () => void, onLeave: () => void, onResult: () => void = () => {}, onRules: () => void = () => {}, appearances?: [FighterAppearance, FighterAppearance]) {
|
||||
export function createMatchView(container: HTMLElement, onAction: (action: ActionId) => Promise<boolean>, onRematch: () => void, onLeave: () => void, onResult: () => void = () => {}, onRules: () => void = () => {}, appearances?: [FighterAppearance, FighterAppearance], onEmote?: (id: EmoteId) => boolean | Promise<boolean>) {
|
||||
container.innerHTML = `<section class="match-introduction waiting" hidden><div class="queue-fighter" aria-hidden="true"></div><h1 role="status"></h1></section><div class="match-top"><div class="match-title"><span class="mode-label"></span><h1 class="turn-heading"></h1></div><details class="match-menu"><summary aria-label="대전 메뉴">메뉴</summary><div class="match-menu-items"><button class="match-rules quiet">규칙</button><button class="leave quiet">나가기</button></div></details></div>
|
||||
<div class="timing"><span class="selection-status" role="status"></span><span class="time-label" aria-label="남은 시간"></span><div class="time-track" role="progressbar" aria-label="남은 선택 시간" aria-valuemin="0" aria-valuemax="100"><span></span></div></div>
|
||||
<div class="arena"><div class="arena-floor" aria-hidden="true"></div><div class="result-banner" hidden><h2></h2><p class="finish-reason"></p></div>${fighter(0, appearances?.[0])}<div class="duel-cue"><span class="versus" aria-hidden="true">VS</span><strong class="countdown-number" role="status"></strong></div><span class="clash-label" role="status"></span><div class="clash-burst" aria-hidden="true"></div>${fighter(1, appearances?.[1])}</div>
|
||||
<div class="player-controls" role="group" aria-label="내 행동 선택"><div class="energy">${actionIcon('charge')}<strong class="energy-count"></strong></div><div class="action-buttons">${ACTION_IDS.map(id => `<button data-action="${id}" aria-label="${ACTIONS[id].name}, ${ACTIONS[id].effect}${ACTIONS[id].cost ? `, 기 ${ACTIONS[id].cost} 소모` : ''}"><span class="action-symbol">${actionIcon(id)}</span><strong>${ACTIONS[id].name}</strong><small>${id === 'charge' || id === 'guard' ? ACTIONS[id].effect : `기 ${ACTIONS[id].cost} 소모`}</small><span class="chosen-mark">${checkIcon}</span></button>`).join('')}</div></div>
|
||||
<details class="emote-menu"><summary>감정표현</summary><div>${EMOTE_IDS.map(id => `<button type="button" data-emote="${id}">${EMOTE_LABELS[id]}</button>`).join('')}</div></details>
|
||||
<div class="match-result" hidden><div class="result-stats"></div><p class="save-status" role="status"></p><div class="split"><button class="rematch primary">다시 대전</button><button class="home-return">시작 화면</button></div><p class="rematch-status" role="status"></p></div>`;
|
||||
const arena = container.querySelector<HTMLElement>('.arena')!;
|
||||
const emoteMenu = container.querySelector<HTMLDetailsElement>('.emote-menu')!;
|
||||
let emoteReadyAt = 0, sendingEmote = false;
|
||||
emoteMenu.querySelectorAll<HTMLButtonElement>('[data-emote]').forEach(button => {
|
||||
button.onclick = async () => {
|
||||
if (!current || sendingEmote || Date.now() < emoteReadyAt) return;
|
||||
const matchId = current.matchId;
|
||||
sendingEmote = true; emoteMenu.open = false;
|
||||
emoteMenu.querySelector('summary')?.focus();
|
||||
try { if (await onEmote?.(button.dataset.emote as EmoteId) && current?.matchId === matchId) emoteReadyAt = Date.now() + EMOTE_COOLDOWN_MS; }
|
||||
finally { sendingEmote = false; }
|
||||
};
|
||||
});
|
||||
const renderer = createActionRenderer(arena);
|
||||
const cutscene = createFinishCutscene(() => { tick(); el('.result-banner h2').focus({ preventScroll: true }); }, appearances);
|
||||
const appearanceSignatures = [0, 1].map(i => appearanceKey(appearances?.[i]));
|
||||
@@ -55,6 +70,8 @@ export function createMatchView(container: HTMLElement, onAction: (action: Actio
|
||||
arena.hidden = !!introduction;
|
||||
const revealing = resultReported !== s.matchId && !!s.reveal && now < s.reveal.revealEndsAt;
|
||||
const resultVisible = s.phase === 'finished' && !revealing;
|
||||
emoteMenu.hidden = !onEmote || !!introduction || s.phase === 'finished' || !s.opponentPresent;
|
||||
emoteMenu.querySelectorAll<HTMLButtonElement>('button').forEach(button => { button.disabled = sendingEmote || Date.now() < emoteReadyAt; });
|
||||
if (resultVisible && resultReported !== s.matchId) renderer.reset();
|
||||
const recovering = !resultVisible && !s.opponentPresent;
|
||||
const phase = revealing ? 'revealing' : resultVisible ? 'finished' : s.phase;
|
||||
@@ -93,6 +110,13 @@ export function createMatchView(container: HTMLElement, onAction: (action: Actio
|
||||
});
|
||||
container.querySelectorAll<HTMLElement>('[data-fighter]').forEach((node, i) => {
|
||||
const self = i === s.selfIndex;
|
||||
const bubble = node.querySelector<HTMLElement>('.emote-bubble');
|
||||
const emote = s.emotes?.[i];
|
||||
if (bubble) {
|
||||
const line = emote && emote.expiresAt > now && !resultVisible ? EMOTE_LINES[(s.appearances ?? appearances)?.[i]?.characterId ?? i]?.[emote.id] : '';
|
||||
bubble.hidden = !line;
|
||||
if (bubble.textContent !== (line ?? '')) bubble.textContent = line ?? '';
|
||||
}
|
||||
node.dataset.locked = String(self && !!s.ownAction && phase === 'selecting');
|
||||
if (resultVisible && !s.aborted && s.finished?.reason === 'hit' && s.reveal?.matchId === s.matchId
|
||||
&& s.reveal.hitIndex === i && s.reveal.actions[1 - i] === 'beam') node.dataset.ash = 'true';
|
||||
@@ -129,6 +153,7 @@ export function createMatchView(container: HTMLElement, onAction: (action: Actio
|
||||
update(state: LocalMatchState) {
|
||||
if (current?.matchId === state.matchId && current.version > state.version) return;
|
||||
if (lastId !== state.matchId) {
|
||||
emoteReadyAt = 0; emoteMenu.open = false;
|
||||
cutscene.reset(); renderer.reset(); lastId = state.matchId; busy = false; submission++;
|
||||
el('.match-introduction .queue-fighter').innerHTML = fighterArt(state.selfIndex, false, (state.appearances ?? appearances)?.[state.selfIndex]);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
/* Match layout only; character poses, projectiles and finish cutscenes stay in game.css. */
|
||||
.emote-menu { position: absolute; z-index: 8; left: var(--edge); bottom: 130px; }
|
||||
.emote-menu summary { cursor: pointer; padding: 8px 12px; border: 1px solid #56615a; background: #fffdf1; color: #232a2c; }
|
||||
.emote-menu > div { position: absolute; bottom: 100%; display: grid; grid-template-columns: repeat(2, 64px); gap: 4px; padding: 6px; background: #fffdf1; border: 1px solid #56615a; }
|
||||
.emote-menu button { padding: 10px 6px; min-height: 44px; }
|
||||
.emote-bubble { position: absolute; z-index: 7; top: -28px; left: 50%; transform: translateX(-50%); width: max-content; max-width: min(180px, 39vw); padding: 9px 12px; border: 2px solid #36433b; border-radius: 14px; background: #fffdf1; color: #232a2c; font-size: clamp(12px, 2vw, 17px); text-align: center; overflow-wrap: anywhere; pointer-events: none; }
|
||||
.emote-bubble::after { content: ''; position: absolute; top: 100%; left: 50%; border: 7px solid transparent; border-top-color: #36433b; }
|
||||
@media (max-height: 500px) { .emote-menu { bottom: 95px; } }
|
||||
body:is([data-screen=match], [data-screen=result]) {
|
||||
overflow: hidden;
|
||||
background: #d9ddd4;
|
||||
|
||||
Reference in New Issue
Block a user