test
This commit is contained in:
270
backend/src/game/game-helpers.ts
Normal file
270
backend/src/game/game-helpers.ts
Normal file
@@ -0,0 +1,270 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
|
||||
export type ResolvedTarget =
|
||||
| { kind: 'player'; id: string }
|
||||
| { kind: 'object'; object: GameObject }
|
||||
| { kind: 'stack'; item: StackItem }
|
||||
|
||||
export interface EventContext {
|
||||
kind: TriggerEvent['kind']
|
||||
player?: string
|
||||
subject?: GameObject
|
||||
amount?: number
|
||||
counter?: string
|
||||
ordinal?: number
|
||||
mode?: 'gain' | 'lose'
|
||||
recipient?: 'player' | 'creature' | 'permanent' | 'any'
|
||||
combat?: boolean
|
||||
spell?: GameObject
|
||||
spellItem?: StackItem
|
||||
}
|
||||
|
||||
export interface EffectContext {
|
||||
source: GameObject
|
||||
controller: string
|
||||
targets: TargetChoice[]
|
||||
lastTarget?: ResolvedTarget
|
||||
/** Objects dealt damage by the most recent damage effect, for "dealt damage this way". */
|
||||
lastDamaged?: GameObject[]
|
||||
triggerSubject?: GameObject
|
||||
eventPlayer?: string
|
||||
eventAmount?: number
|
||||
x: number
|
||||
mode: number
|
||||
/** Color picked for a mana ability, so choice effects produce it. */
|
||||
manaColor?: ManaColor
|
||||
/** Whether the "you may" branch was taken; undefined means no branch was offered. */
|
||||
optionalTaken?: boolean
|
||||
}
|
||||
|
||||
export interface ContinuousEffect {
|
||||
id: string
|
||||
sourceId: string
|
||||
controller: string
|
||||
effect: Extract<Effect, { op: 'pump' | 'set_pt' | 'grant' | 'restriction' }>
|
||||
affectedIds: string[]
|
||||
duration: Duration
|
||||
createdTurn: number
|
||||
}
|
||||
|
||||
export interface DamageShield {
|
||||
/** Object or player ids this shield covers; empty with `global` covers everything. */
|
||||
ids: Set<string>
|
||||
global: boolean
|
||||
/** When set, only damage dealt by these source objects is prevented. */
|
||||
sourceIds?: Set<string>
|
||||
/** When set, only damage from sources matching this selector is prevented. */
|
||||
sourceSelector?: ObjectSelector
|
||||
remaining: number | 'all'
|
||||
combatOnly: boolean
|
||||
/** "If damage is prevented this way, ..." follow-up. */
|
||||
then?: Effect[]
|
||||
sourceId?: string
|
||||
controller?: string
|
||||
/** Target choices left over when the shield was made, for its follow-up. */
|
||||
targets?: TargetChoice[]
|
||||
/** Recipient the shield was made for, so "that creature" resolves in the follow-up. */
|
||||
lastTarget?: ResolvedTarget
|
||||
}
|
||||
|
||||
export interface ManaCost {
|
||||
generic: number
|
||||
colored: ManaColor[]
|
||||
hybrid: { colors: ManaColor[]; life: number }[]
|
||||
}
|
||||
|
||||
export const MANA_COLORS: ManaColor[] = ['W', 'U', 'B', 'R', 'G', 'C']
|
||||
export const COLOR_NAMES: Record<string, ManaColor> = {
|
||||
white: 'W',
|
||||
blue: 'U',
|
||||
black: 'B',
|
||||
red: 'R',
|
||||
green: 'G',
|
||||
colorless: 'C',
|
||||
}
|
||||
|
||||
export function emptyPool(): ManaPool {
|
||||
return { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 }
|
||||
}
|
||||
|
||||
export function parseManaCost(symbols: string, x = 0): ManaCost {
|
||||
const cost: ManaCost = { generic: 0, colored: [], hybrid: [] }
|
||||
for (const match of symbols.matchAll(/\{([^}]+)\}/g)) {
|
||||
const symbol = match[1].toUpperCase()
|
||||
if (/^\d+$/.test(symbol)) {
|
||||
cost.generic += Number(symbol)
|
||||
} else if (symbol === 'X') {
|
||||
cost.generic += x
|
||||
} else if (symbol === 'S') {
|
||||
cost.colored.push('C')
|
||||
} else if (/^[WUBRGC]$/.test(symbol)) {
|
||||
cost.colored.push(symbol as ManaColor)
|
||||
} else if (symbol.includes('/')) {
|
||||
const parts = symbol.split('/')
|
||||
const colors = parts
|
||||
.filter(part => /^[WUBRG]$/.test(part))
|
||||
.map(part => part as ManaColor)
|
||||
if (colors.length) cost.hybrid.push({ colors, life: parts.includes('P') ? 2 : 0 })
|
||||
else cost.generic += 1
|
||||
} else {
|
||||
cost.generic += 1
|
||||
}
|
||||
}
|
||||
return cost
|
||||
}
|
||||
|
||||
export interface CostReduction {
|
||||
generic: number
|
||||
colored: ManaColor[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic reductions only remove generic mana; colored ones remove matching pips.
|
||||
* shortcut: hybrid and phyrexian pips are not reduced; upgrade when a card needs it.
|
||||
*/
|
||||
export function reduceManaSymbols(symbols: string, reduction: CostReduction): string {
|
||||
let generic = reduction.generic
|
||||
const colored = [...reduction.colored]
|
||||
const result: string[] = []
|
||||
for (const match of symbols.matchAll(/\{([^}]+)\}/g)) {
|
||||
const symbol = match[1].toUpperCase()
|
||||
if (/^\d+$/.test(symbol) && generic > 0) {
|
||||
const remaining = Math.max(0, Number(symbol) - generic)
|
||||
generic = Math.max(0, generic - Number(symbol))
|
||||
if (remaining > 0) result.push(`{${remaining}}`)
|
||||
continue
|
||||
}
|
||||
const index = colored.indexOf(symbol as ManaColor)
|
||||
if (index >= 0) {
|
||||
colored.splice(index, 1)
|
||||
continue
|
||||
}
|
||||
result.push(`{${match[1]}}`)
|
||||
}
|
||||
return result.join('')
|
||||
}
|
||||
|
||||
export function manaValueOf(definition: CardDefinition): number {
|
||||
if (definition.manaValue !== undefined) return definition.manaValue
|
||||
const cost = parseManaCost(definition.manaCost ?? '')
|
||||
return cost.generic + cost.colored.length + cost.hybrid.length
|
||||
}
|
||||
|
||||
export function colorOfSymbol(symbol: string): ManaColor {
|
||||
const bare = symbol.replace(/[{}]/g, '').toUpperCase()
|
||||
if (bare === 'S') return 'C'
|
||||
if (/^[WUBRGC]$/.test(bare)) return bare as ManaColor
|
||||
return 'C'
|
||||
}
|
||||
|
||||
export function tokenCard(token: {
|
||||
name?: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
keywords?: string[]
|
||||
}): { definition: CardDefinition; backFace?: CardDefinition } {
|
||||
const predefined = predefinedToken(token)
|
||||
const types = predefined?.types ?? token.types
|
||||
const subtypes = predefined?.subtypes ?? token.subtypes
|
||||
const colors = [...new Set([...(predefined?.colors ?? []), ...token.colors])]
|
||||
const keywords = [...(predefined?.keywords ?? []), ...(token.keywords ?? [])]
|
||||
const definition = tokenFace({
|
||||
name: predefined?.name ?? token.name ?? (subtypes.map(capitalize).join(' ') || 'Token'),
|
||||
types,
|
||||
subtypes,
|
||||
colors,
|
||||
power: token.power ?? predefined?.power,
|
||||
toughness: token.toughness ?? predefined?.toughness,
|
||||
keywords,
|
||||
abilities: predefined?.abilities,
|
||||
})
|
||||
const backFace = predefined?.backFace
|
||||
? tokenFace({ ...predefined.backFace, keywords: predefined.backFace.keywords ?? [] })
|
||||
: undefined
|
||||
return { definition, backFace }
|
||||
}
|
||||
|
||||
export function capitalize(word: string): string {
|
||||
return word[0]?.toUpperCase() + word.slice(1)
|
||||
}
|
||||
|
||||
export function tokenFace(fields: {
|
||||
name: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
keywords?: string[]
|
||||
abilities?: Ability[]
|
||||
}): CardDefinition {
|
||||
return {
|
||||
oracleId: `token:${fields.name}`,
|
||||
name: fields.name,
|
||||
typeLine: [fields.types.join(' '), fields.subtypes.length ? `— ${fields.subtypes.join(' ')}` : ''].join(' ').trim(),
|
||||
manaValue: 0,
|
||||
colors: fields.colors,
|
||||
power: fields.power,
|
||||
toughness: fields.toughness,
|
||||
abilities: [
|
||||
...(fields.abilities ?? []),
|
||||
...(fields.keywords ?? []).map(keyword => ({ kind: 'keyword' as const, keyword })),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
export class GameError extends Error {}
|
||||
|
||||
|
||||
export function mulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0
|
||||
let value = state
|
||||
value = Math.imul(value ^ (value >>> 15), value | 1)
|
||||
value ^= value + Math.imul(value ^ (value >>> 7), value | 61)
|
||||
return ((value ^ (value >>> 14)) >>> 0) / 4294967296
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user