Fix issue #2: Add animations

This commit is contained in:
Gitea OpenCode Agent
2026-10-27 16:28:34 +00:00
parent 39b2d72808
commit a167649327
3 changed files with 570 additions and 4 deletions

View File

@@ -2,6 +2,7 @@
import { deckValidation, loadDecks, type SavedDeck } from '~/utils/decks'
import { loadPlaymatChoice, savePlaymatChoice, type PlaymatSelection } from '~/utils/playmat'
import { cardBackVars } from '~/utils/cardBack'
import { diffGameState, type GameAnimations } from '~/utils/gameAnimations'
interface AbilityView {
index: number
@@ -94,6 +95,19 @@ interface MatchSummary {
players: string[]
}
interface FloatingLabel {
id: number
targetId: string
text: string
tone: 'damage' | 'heal'
}
interface ManaBurst {
id: number
color: string
amount: number
}
type PlaymatView = { kind: 'card'; oracleId: string } | { kind: 'upload'; id: string }
definePageMeta({ middleware: 'auth' })
@@ -125,6 +139,17 @@ const playmatOpen = ref(false)
const playmatBusy = ref(false)
let events: EventSource | undefined
const cardEnterAnimations = reactive<Record<string, number>>({})
const cardDamageAnimations = reactive<Record<string, number>>({})
const cardAttackAnimations = reactive<Record<string, number>>({})
const playerHitAnimations = reactive<Record<string, number>>({})
const playerHealAnimations = reactive<Record<string, number>>({})
const floatingLabels = ref<FloatingLabel[]>([])
const manaBursts = ref<ManaBurst[]>([])
const animationTimers = new Set<ReturnType<typeof setTimeout>>()
let previousState: MatchView | null = null
let animationCounter = 0
const tableEl = ref<HTMLElement | null>(null)
const sidebarEl = ref<HTMLElement | null>(null)
const panning = ref(false)
@@ -401,9 +426,10 @@ async function connect() {
if (!token.value) return
connection.value = 'connecting'
try {
state.value = await $fetch<MatchView>(`${apiBase}/games/${gameId.value}/state`, {
const next = await $fetch<MatchView>(`${apiBase}/games/${gameId.value}/state`, {
query: { token: token.value },
})
applyState(next, false)
} catch (caught) {
error.value = errorMessage(caught)
token.value = ''
@@ -420,7 +446,7 @@ async function connect() {
events.onmessage = (event) => {
try {
const next = JSON.parse(event.data) as MatchView
state.value = next
applyState(next)
connection.value = 'live'
if (!defenderId.value || !next.players.some(player => player.id === defenderId.value)) {
defenderId.value = next.players.find(player => player.id !== next.viewerId)?.id ?? ''
@@ -520,6 +546,7 @@ async function leaveGame() {
sessionStorage.removeItem(`${SESSION_PREFIX}${gameId.value}`)
events?.close()
events = undefined
resetAnimations()
state.value = null
token.value = ''
connection.value = 'offline'
@@ -766,6 +793,98 @@ function errorMessage(caught: unknown): string {
return data?.error ?? (caught instanceof Error ? caught.message : String(caught))
}
const MANA_COLORS: Record<string, string> = {
W: '#f5f2d6',
U: '#7aa2f7',
B: '#b6a2d8',
R: '#e07a7a',
G: '#7dd3a0',
C: '#c4c8d4',
}
function manaColor(color: string): string {
return MANA_COLORS[color] ?? 'var(--accent)'
}
function scheduleAnimation(callback: () => void, delay: number) {
const timer = setTimeout(() => {
animationTimers.delete(timer)
callback()
}, delay)
animationTimers.add(timer)
}
/** Flash a keyed CSS animation, then let it be applied again next time. */
function pulse(map: Record<string, number>, id: string, duration: number) {
const token = ++animationCounter
map[id] = token
scheduleAnimation(() => {
if (map[id] === token) delete map[id]
}, duration)
}
function addFloatingLabel(targetId: string, text: string, tone: FloatingLabel['tone']) {
const id = ++animationCounter
floatingLabels.value.push({ id, targetId, text, tone })
scheduleAnimation(() => {
floatingLabels.value = floatingLabels.value.filter(label => label.id !== id)
}, 1100)
}
function addManaBurst(color: string, amount: number) {
const id = ++animationCounter
manaBursts.value.push({ id, color, amount })
scheduleAnimation(() => {
manaBursts.value = manaBursts.value.filter(burst => burst.id !== id)
}, 1100)
}
function labelsFor(targetId: string): FloatingLabel[] {
return floatingLabels.value.filter(label => label.targetId === targetId)
}
function playAnimations(animations: GameAnimations) {
for (const id of animations.enteringCardIds) pulse(cardEnterAnimations, id, 520)
for (const id of animations.attackingCardIds) pulse(cardAttackAnimations, id, 540)
for (const damage of animations.damagedCards) {
pulse(cardDamageAnimations, damage.cardId, 500)
addFloatingLabel(damage.cardId, `−${damage.amount}`, 'damage')
}
for (const change of animations.lifeChanges) {
if (change.amount < 0) {
pulse(playerHitAnimations, change.playerId, 700)
addFloatingLabel(change.playerId, `−${Math.abs(change.amount)}`, 'damage')
} else {
pulse(playerHealAnimations, change.playerId, 700)
addFloatingLabel(change.playerId, `+${change.amount}`, 'heal')
}
}
for (const gain of animations.manaGains) addManaBurst(gain.color, gain.amount)
}
function applyState(next: MatchView, animate = true) {
if (animate) playAnimations(diffGameState(previousState, next))
previousState = next
state.value = next
}
function resetAnimations() {
previousState = null
for (const timer of animationTimers) clearTimeout(timer)
animationTimers.clear()
for (const map of [
cardEnterAnimations,
cardDamageAnimations,
cardAttackAnimations,
playerHitAnimations,
playerHealAnimations,
]) {
for (const key of Object.keys(map)) delete map[key]
}
floatingLabels.value = []
manaBursts.value = []
}
watch(() => game.value?.step, () => {
selectedAttackers.value = []
for (const key of Object.keys(attackTargets)) delete attackTargets[key]
@@ -800,6 +919,8 @@ onMounted(async () => {
onUnmounted(() => {
window.removeEventListener('keydown', onKeydown)
events?.close()
for (const timer of animationTimers) clearTimeout(timer)
animationTimers.clear()
})
</script>
@@ -944,12 +1065,23 @@ onUnmounted(() => {
v-for="(player, playerIndex) in state.players"
:key="player.id"
class="panel player"
:class="{ current: game.activePlayer === player.id, dead: player.lost }"
:class="{
current: game.activePlayer === player.id,
dead: player.lost,
'anim-hit': playerHitAnimations[player.id],
'anim-heal': playerHealAnimations[player.id],
}"
>
<header class="player-head">
<strong class="grow">{{ player.name }}</strong>
<span v-if="player.id === viewerId" class="tag">you</span>
<span class="life">{{ player.life }}</span>
<span
class="life"
:class="{
'life-hit': playerHitAnimations[player.id],
'life-heal': playerHealAnimations[player.id],
}"
>{{ player.life }}</span>
<span class="tag">hand {{ player.handCount ?? 0 }}</span>
<span class="tag">library {{ player.libraryCount ?? 0 }}</span>
<span v-if="game.priority === player.id" class="tag good">priority</span>
@@ -962,6 +1094,13 @@ onUnmounted(() => {
title="Change your playmat"
@click="togglePlaymat"
>Playmat</button>
<span
v-for="label in labelsFor(player.id)"
:key="label.id"
class="float-text player-float"
:class="label.tone"
aria-hidden="true"
>{{ label.text }}</span>
</header>
<p v-if="player.commanderDamage?.length" class="damage">
@@ -1027,6 +1166,9 @@ onUnmounted(() => {
positioned: isPositioned(card),
dragging: dragPreview?.cardId === card.id,
movable: card.controller === viewerId,
'anim-enter': cardEnterAnimations[card.id],
'anim-damage': cardDamageAnimations[card.id],
'anim-attack': cardAttackAnimations[card.id],
}"
:style="permStyle(card)"
:title="card.oracleText"
@@ -1055,6 +1197,13 @@ onUnmounted(() => {
</div>
</GameCard>
</CardHover>
<span
v-for="label in labelsFor(card.id)"
:key="label.id"
class="float-text card-float"
:class="label.tone"
aria-hidden="true"
>{{ label.text }}</span>
</div>
<p v-if="!player.battlefield?.length" class="muted">No permanents.</p>
</div>
@@ -1087,6 +1236,15 @@ onUnmounted(() => {
<span v-for="(amount, color) in game.manaPool" :key="color" class="tag">
<ManaCost :cost="`{${color}}`" /> {{ amount }}
</span>
<span
v-for="burst in manaBursts"
:key="burst.id"
class="mana-burst"
:style="{ color: manaColor(burst.color) }"
aria-hidden="true"
>
<ManaCost :cost="`{${burst.color}}`" /> +{{ burst.amount }}
</span>
</div>
</div>
<p v-if="!game.hand.length" class="muted">No cards in hand.</p>
@@ -1582,6 +1740,7 @@ onUnmounted(() => {
}
.player-head {
position: relative;
display: flex;
align-items: center;
flex-wrap: wrap;
@@ -1594,10 +1753,122 @@ onUnmounted(() => {
}
.life {
display: inline-block;
font-size: 1.2rem;
font-weight: 700;
}
.player.anim-hit {
animation: player-hit 700ms ease-out;
}
.player.anim-heal {
animation: player-heal 700ms ease-out;
}
.life.life-hit {
animation: life-hit 700ms ease-out;
}
.life.life-heal {
animation: life-heal 700ms ease-out;
}
.float-text {
position: absolute;
top: -0.2rem;
left: 50%;
z-index: 35;
font-size: 1rem;
font-weight: 800;
line-height: 1;
pointer-events: none;
text-shadow: 0 1px 3px #000, 0 0 8px currentColor;
animation: float-up 1.05s ease-out forwards;
}
.float-text.damage {
color: var(--bad);
}
.float-text.heal {
color: var(--ok);
}
.player-float {
top: 0.15rem;
}
.card-float {
top: 22%;
font-size: 1.15rem;
transform: translateX(-50%);
}
@keyframes player-hit {
0%, 100% {
box-shadow: none;
}
18% {
box-shadow: inset 0 0 0 2px var(--bad), 0 0 26px rgb(224 122 122 / 55%);
}
55% {
box-shadow: inset 0 0 0 1px var(--bad), 0 0 12px rgb(224 122 122 / 30%);
}
}
@keyframes player-heal {
0%, 100% {
box-shadow: none;
}
18% {
box-shadow: inset 0 0 0 2px var(--ok), 0 0 26px rgb(125 211 160 / 45%);
}
55% {
box-shadow: inset 0 0 0 1px var(--ok), 0 0 12px rgb(125 211 160 / 25%);
}
}
@keyframes life-hit {
0%, 100% {
color: var(--text);
transform: scale(1);
}
28% {
color: var(--bad);
transform: scale(1.35);
}
}
@keyframes life-heal {
0%, 100% {
color: var(--text);
transform: scale(1);
}
28% {
color: var(--ok);
transform: scale(1.3);
}
}
@keyframes float-up {
0% {
opacity: 0;
transform: translate(-50%, 0.45rem) scale(0.75);
}
18% {
opacity: 1;
transform: translate(-50%, 0) scale(1.15);
}
72% {
opacity: 1;
}
100% {
opacity: 0;
transform: translate(-50%, -1.5rem) scale(0.95);
}
}
.damage {
display: flex;
flex-wrap: wrap;
@@ -1712,6 +1983,7 @@ onUnmounted(() => {
}
.perm {
position: relative;
display: flex;
flex-direction: column;
gap: 0.25rem;
@@ -1719,6 +1991,67 @@ onUnmounted(() => {
cursor: pointer;
}
.perm.anim-enter .game-card {
animation: perm-enter 520ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.perm.anim-damage .game-card {
animation: perm-damage 500ms ease-in-out;
}
.perm.anim-attack .game-card {
animation: perm-attack 540ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
@keyframes perm-enter {
0% {
opacity: 0;
filter: brightness(1.8);
transform: translateY(-1.6rem) scale(0.65) rotate(-5deg);
}
65% {
opacity: 1;
filter: brightness(1.15);
transform: translateY(0.15rem) scale(1.04) rotate(1deg);
}
100% {
opacity: 1;
filter: none;
transform: none;
}
}
@keyframes perm-damage {
0%, 100% {
filter: none;
transform: translateX(0);
}
16% {
filter: brightness(1.5) drop-shadow(0 0 0.5rem var(--bad));
transform: translateX(-0.32rem) rotate(-1deg);
}
38% {
transform: translateX(0.3rem) rotate(1deg);
}
60% {
transform: translateX(-0.2rem);
}
80% {
transform: translateX(0.12rem);
}
}
@keyframes perm-attack {
0%, 100% {
filter: none;
transform: translateY(0) scale(1);
}
42% {
filter: brightness(1.25) drop-shadow(0 0 0.5rem var(--bad));
transform: translateY(-0.45rem) scale(1.06);
}
}
.perm.movable {
cursor: grab;
}
@@ -2013,6 +2346,35 @@ onUnmounted(() => {
gap: 0.25rem;
}
.mana-burst {
display: inline-flex;
align-items: center;
gap: 0.1rem;
font-size: 0.85rem;
font-weight: 700;
text-shadow: 0 0 8px currentColor;
animation: mana-burst 1.05s ease-out forwards;
}
@keyframes mana-burst {
0% {
opacity: 0;
transform: translateY(0.45rem) scale(0.7);
}
20% {
opacity: 1;
transform: translateY(0) scale(1.12);
}
70% {
opacity: 1;
transform: translateY(-0.2rem) scale(1);
}
100% {
opacity: 0;
transform: translateY(-0.8rem) scale(0.95);
}
}
.hand-fan {
position: relative;
height: 12em;
@@ -2140,6 +2502,20 @@ onUnmounted(() => {
align-items: center;
}
@media (prefers-reduced-motion: reduce) {
.perm.anim-enter .game-card,
.perm.anim-damage .game-card,
.perm.anim-attack .game-card,
.player.anim-hit,
.player.anim-heal,
.life.life-hit,
.life.life-heal,
.float-text,
.mana-burst {
animation: none;
}
}
@media (max-width: 1000px) {
.game-page {
height: auto;

View File

@@ -0,0 +1,105 @@
// Animation cues are derived by diffing two match snapshots, so they work for
// every client (including spectators) without adding anything to the wire format.
export interface AnimationCardSnapshot {
id: string
damage?: number
attacking?: string
}
export interface AnimationPlayerSnapshot {
id: string
life?: number
battlefield?: readonly AnimationCardSnapshot[]
}
export interface AnimationStateSnapshot {
id?: string
players?: readonly AnimationPlayerSnapshot[]
game?: {
manaPool?: Record<string, number>
}
}
export interface CardDamageAnimation {
cardId: string
amount: number
}
export interface LifeChangeAnimation {
playerId: string
amount: number
}
export interface ManaGainAnimation {
color: string
amount: number
}
export interface GameAnimations {
enteringCardIds: string[]
attackingCardIds: string[]
damagedCards: CardDamageAnimation[]
lifeChanges: LifeChangeAnimation[]
manaGains: ManaGainAnimation[]
}
function emptyAnimations(): GameAnimations {
return {
enteringCardIds: [],
attackingCardIds: [],
damagedCards: [],
lifeChanges: [],
manaGains: [],
}
}
function cardsByPlayer(state: AnimationStateSnapshot): Map<string, AnimationCardSnapshot> {
const cards = new Map<string, AnimationCardSnapshot>()
for (const player of state.players ?? []) {
for (const card of player.battlefield ?? []) cards.set(card.id, card)
}
return cards
}
/**
* Compare the previous and current match state and return the visual cues that
* should play for the current state. The first snapshot has nothing to compare
* against and produces no animations.
*/
export function diffGameState(
previous: AnimationStateSnapshot | null | undefined,
next: AnimationStateSnapshot,
): GameAnimations {
const animations = emptyAnimations()
if (!previous) return animations
if (previous.id && next.id && previous.id !== next.id) return animations
const previousCards = cardsByPlayer(previous)
const nextCards = cardsByPlayer(next)
for (const [id, card] of nextCards) {
const before = previousCards.get(id)
if (!before) animations.enteringCardIds.push(id)
else {
const amount = (card.damage ?? 0) - (before.damage ?? 0)
if (amount > 0) animations.damagedCards.push({ cardId: id, amount })
}
if (card.attacking && !before?.attacking) animations.attackingCardIds.push(id)
}
for (const player of next.players ?? []) {
const before = previous.players?.find(entry => entry.id === player.id)
if (!before || before.life === undefined || player.life === undefined) continue
const amount = player.life - before.life
if (amount) animations.lifeChanges.push({ playerId: player.id, amount })
}
const previousPool = previous.game?.manaPool ?? {}
const nextPool = next.game?.manaPool ?? {}
for (const color of new Set([...Object.keys(nextPool), ...Object.keys(previousPool)])) {
const amount = (nextPool[color] ?? 0) - (previousPool[color] ?? 0)
if (amount > 0) animations.manaGains.push({ color, amount })
}
return animations
}

View File

@@ -0,0 +1,85 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { diffGameState } from '../app/utils/gameAnimations.ts'
test('diffGameState ignores the first snapshot', () => {
const animations = diffGameState(undefined, {
id: 'game',
players: [{ id: 'p1', life: 40, battlefield: [{ id: 'card-1' }] }],
game: { manaPool: { G: 2 } },
})
assert.deepEqual(animations, {
enteringCardIds: [],
attackingCardIds: [],
damagedCards: [],
lifeChanges: [],
manaGains: [],
})
})
test('diffGameState detects entering and attacking permanents', () => {
const animations = diffGameState(
{ id: 'game', players: [{ id: 'p1', battlefield: [{ id: 'old' }] }] },
{
id: 'game',
players: [{
id: 'p1',
battlefield: [{ id: 'old' }, { id: 'new', attacking: 'p2' }],
}],
},
)
assert.deepEqual(animations.enteringCardIds, ['new'])
assert.deepEqual(animations.attackingCardIds, ['new'])
})
test('diffGameState reports damage and life changes', () => {
const animations = diffGameState(
{
id: 'game',
players: [
{ id: 'p1', life: 40, battlefield: [{ id: 'creature', damage: 1 }] },
{ id: 'p2', life: 40 },
],
},
{
id: 'game',
players: [
{ id: 'p1', life: 40, battlefield: [{ id: 'creature', damage: 4 }] },
{ id: 'p2', life: 33 },
],
},
)
assert.deepEqual(animations.damagedCards, [{ cardId: 'creature', amount: 3 }])
assert.deepEqual(animations.lifeChanges, [{ playerId: 'p2', amount: -7 }])
})
test('diffGameState only animates mana gains', () => {
const animations = diffGameState(
{ id: 'game', players: [], game: { manaPool: { G: 1, R: 2 } } },
{ id: 'game', players: [], game: { manaPool: { G: 3, R: 0, U: 1 } } },
)
assert.deepEqual(animations.manaGains, [
{ color: 'G', amount: 2 },
{ color: 'U', amount: 1 },
])
})
test('diffGameState is quiet when nothing visible changed', () => {
const state = {
id: 'game',
players: [{ id: 'p1', life: 40, battlefield: [{ id: 'creature', damage: 2 }] }],
game: { manaPool: { W: 1 } },
}
assert.deepEqual(diffGameState(state, state), {
enteringCardIds: [],
attackingCardIds: [],
damagedCards: [],
lifeChanges: [],
manaGains: [],
})
})