File size: 20,503 Bytes
1ecc382 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 |
/**
* Core Battle Engine for Pictuary
* Implements the battle system as defined in battle_system_design.md
*/
import {
BattleState,
BattlePiclet,
PicletDefinition,
BattleAction,
MoveAction,
BattleEffect,
DamageAmount,
StatModification,
HealAmount,
StatusEffect,
BaseStats,
Move
} from './types';
import { PicletType, AttackType, getEffectivenessMultiplier } from '../types/picletTypes';
export class BattleEngine {
private state: BattleState;
constructor(playerPiclet: PicletDefinition, opponentPiclet: PicletDefinition, playerLevel = 50, opponentLevel = 50) {
this.state = {
turn: 1,
phase: 'selection',
playerPiclet: this.createBattlePiclet(playerPiclet, playerLevel),
opponentPiclet: this.createBattlePiclet(opponentPiclet, opponentLevel),
fieldEffects: [],
log: [],
winner: undefined
};
this.log('Battle started!');
this.log(`${playerPiclet.name} vs ${opponentPiclet.name}`);
}
private createBattlePiclet(definition: PicletDefinition, level: number): BattlePiclet {
// Calculate stats based on level (simplified formula)
const statMultiplier = 1 + (level - 50) * 0.02; // 2% per level above/below 50
const hp = Math.floor(definition.baseStats.hp * statMultiplier);
const attack = Math.floor(definition.baseStats.attack * statMultiplier);
const defense = Math.floor(definition.baseStats.defense * statMultiplier);
const speed = Math.floor(definition.baseStats.speed * statMultiplier);
return {
definition,
currentHp: hp,
maxHp: hp,
level,
attack,
defense,
speed,
accuracy: 100, // Base accuracy
statusEffects: [],
moves: definition.movepool.slice(0, 4).map(move => ({
move,
currentPP: move.pp
})),
statModifiers: {},
temporaryEffects: []
};
}
public getState(): BattleState {
return JSON.parse(JSON.stringify(this.state)); // Deep clone for immutability
}
public isGameOver(): boolean {
return this.state.phase === 'ended';
}
public getWinner(): 'player' | 'opponent' | 'draw' | undefined {
return this.state.winner;
}
public executeActions(playerAction: BattleAction, opponentAction: BattleAction): void {
if (this.state.phase !== 'selection') {
throw new Error('Cannot execute actions - battle is not in selection phase');
}
this.state.phase = 'execution';
this.log(`Turn ${this.state.turn} - Actions: ${playerAction.type} vs ${opponentAction.type}`);
// Determine action order based on priority and speed
const actions = this.determineActionOrder(playerAction, opponentAction);
// Execute actions in order
for (const action of actions) {
if (this.state.phase === 'ended') break;
this.executeAction(action);
}
// End of turn processing
this.processTurnEnd();
// Check for battle end
this.checkBattleEnd();
if (this.state.phase !== 'ended') {
this.state.turn++;
this.state.phase = 'selection';
}
}
private determineActionOrder(playerAction: BattleAction, opponentAction: BattleAction): Array<BattleAction & { executor: 'player' | 'opponent' }> {
const playerPriority = this.getActionPriority(playerAction, this.state.playerPiclet);
const opponentPriority = this.getActionPriority(opponentAction, this.state.opponentPiclet);
const playerSpeed = this.state.playerPiclet.speed;
const opponentSpeed = this.state.opponentPiclet.speed;
// Higher priority goes first, then speed, then random
let playerFirst = false;
if (playerPriority > opponentPriority) {
playerFirst = true;
} else if (playerPriority < opponentPriority) {
playerFirst = false;
} else if (playerSpeed > opponentSpeed) {
playerFirst = true;
} else if (playerSpeed < opponentSpeed) {
playerFirst = false;
} else {
playerFirst = Math.random() < 0.5; // Speed tie
}
return playerFirst
? [
{ ...playerAction, executor: 'player' as const },
{ ...opponentAction, executor: 'opponent' as const }
]
: [
{ ...opponentAction, executor: 'opponent' as const },
{ ...playerAction, executor: 'player' as const }
];
}
private getActionPriority(action: BattleAction, piclet: BattlePiclet): number {
if (action.type === 'move') {
const move = piclet.moves[action.moveIndex]?.move;
return move?.priority || 0;
}
return 6; // Switch actions have highest priority
}
private executeAction(action: BattleAction & { executor: 'player' | 'opponent' }): void {
if (action.type === 'move') {
this.executeMove(action);
} else if (action.type === 'switch') {
this.log(`${action.executor} attempted to switch (not implemented)`);
}
}
private executeMove(action: MoveAction & { executor: 'player' | 'opponent' }): void {
const attacker = action.executor === 'player' ? this.state.playerPiclet : this.state.opponentPiclet;
const defender = action.executor === 'player' ? this.state.opponentPiclet : this.state.playerPiclet;
const moveData = attacker.moves[action.moveIndex];
if (!moveData || moveData.currentPP <= 0) {
this.log(`${attacker.definition.name} has no PP left for that move!`);
return;
}
const move = moveData.move;
this.log(`${attacker.definition.name} used ${move.name}!`);
// Consume PP
moveData.currentPP--;
// Check if move hits
if (!this.checkMoveHits(move, attacker, defender)) {
this.log(`${attacker.definition.name}'s attack missed!`);
return;
}
// Process effects
for (const effect of move.effects) {
this.processEffect(effect, attacker, defender, move);
}
}
private checkMoveHits(move: Move, attacker: BattlePiclet, defender: BattlePiclet): boolean {
// Simple accuracy check - can be enhanced later
const accuracy = move.accuracy;
const roll = Math.random() * 100;
return roll < accuracy;
}
private processEffect(effect: BattleEffect, attacker: BattlePiclet, defender: BattlePiclet, move: Move): void {
// Check condition (simplified for now)
if (effect.condition && !this.checkCondition(effect.condition, attacker, defender)) {
return;
}
const target = this.resolveTarget(effect.target, attacker, defender);
if (!target) return;
switch (effect.type) {
case 'damage':
this.processDamageEffect(effect, attacker, target, move);
break;
case 'modifyStats':
this.processModifyStatsEffect(effect, target);
break;
case 'applyStatus':
this.processApplyStatusEffect(effect, target);
break;
case 'heal':
this.processHealEffect(effect, target);
break;
case 'manipulatePP':
this.processManipulatePPEffect(effect, target);
break;
case 'fieldEffect':
this.processFieldEffect(effect);
break;
case 'counter':
this.processCounterEffect(effect, attacker, target);
break;
case 'priority':
this.processPriorityEffect(effect, target);
break;
case 'removeStatus':
this.processRemoveStatusEffect(effect, target);
break;
case 'mechanicOverride':
this.processMechanicOverrideEffect(effect, target);
break;
default:
this.log(`Effect ${effect.type} not implemented yet`);
}
}
private checkCondition(condition: string, attacker: BattlePiclet, defender: BattlePiclet): boolean {
switch (condition) {
case 'always':
return true;
case 'ifLowHp':
return attacker.currentHp / attacker.maxHp < 0.25;
case 'ifHighHp':
return attacker.currentHp / attacker.maxHp > 0.75;
case 'ifLucky50':
return Math.random() < 0.5;
case 'ifUnlucky50':
return Math.random() >= 0.5;
case 'whileFrozen':
return attacker.statusEffects.includes('freeze');
// Type-specific conditions
case 'ifMoveType:flora':
case 'ifMoveType:space':
case 'ifMoveType:beast':
case 'ifMoveType:bug':
case 'ifMoveType:aquatic':
case 'ifMoveType:mineral':
case 'ifMoveType:machina':
case 'ifMoveType:structure':
case 'ifMoveType:culture':
case 'ifMoveType:cuisine':
case 'ifMoveType:normal':
// Would need move context to check, placeholder for now
return true;
// Status-specific conditions
case 'ifStatus:burn':
return attacker.statusEffects.includes('burn');
case 'ifStatus:freeze':
return attacker.statusEffects.includes('freeze');
case 'ifStatus:paralyze':
return attacker.statusEffects.includes('paralyze');
case 'ifStatus:poison':
return attacker.statusEffects.includes('poison');
case 'ifStatus:sleep':
return attacker.statusEffects.includes('sleep');
case 'ifStatus:confuse':
return attacker.statusEffects.includes('confuse');
// Weather conditions (placeholder)
case 'ifWeather:storm':
case 'ifWeather:rain':
case 'ifWeather:sun':
case 'ifWeather:snow':
return false; // Weather system not implemented yet
// Combat conditions
case 'ifDamagedThisTurn':
// Would need turn tracking, placeholder
return false;
case 'ifNotSuperEffective':
// Would need move context, placeholder
return false;
case 'ifStatusMove':
// Would need move context, placeholder
return false;
default:
return true; // Default to true for unimplemented conditions
}
}
private resolveTarget(target: string, attacker: BattlePiclet, defender: BattlePiclet): BattlePiclet | null {
switch (target) {
case 'self':
return attacker;
case 'opponent':
return defender;
default:
return null; // Multi-target not implemented yet
}
}
private processDamageEffect(effect: { amount?: DamageAmount; formula?: string; value?: number; multiplier?: number }, attacker: BattlePiclet, target: BattlePiclet, move: Move): void {
let damage = 0;
// Handle different damage formulas
if (effect.formula) {
damage = this.calculateDamageByFormula(effect, attacker, target, move);
} else if (effect.amount) {
damage = this.calculateStandardDamage(effect.amount, attacker, target, move);
}
// Apply damage
if (damage > 0) {
target.currentHp = Math.max(0, target.currentHp - damage);
this.log(`${target.definition.name} took ${damage} damage!`);
}
// Handle special formula effects
if (effect.formula === 'drain') {
const healAmount = Math.floor(damage * (effect.value || 0.5));
attacker.currentHp = Math.min(attacker.maxHp, attacker.currentHp + healAmount);
if (healAmount > 0) {
this.log(`${attacker.definition.name} recovered ${healAmount} HP from draining!`);
}
} else if (effect.formula === 'recoil') {
const recoilDamage = Math.floor(damage * (effect.value || 0.25));
attacker.currentHp = Math.max(0, attacker.currentHp - recoilDamage);
if (recoilDamage > 0) {
this.log(`${attacker.definition.name} took ${recoilDamage} recoil damage!`);
}
}
}
private calculateDamageByFormula(effect: { formula?: string; value?: number; multiplier?: number }, attacker: BattlePiclet, target: BattlePiclet, move: Move): number {
switch (effect.formula) {
case 'fixed':
return effect.value || 0;
case 'percentage':
return Math.floor(target.maxHp * ((effect.value || 0) / 100));
case 'recoil':
case 'drain':
case 'standard':
return this.calculateStandardDamage('normal', attacker, target, move) * (effect.multiplier || 1);
default:
return 0;
}
}
private calculateStandardDamage(amount: DamageAmount, attacker: BattlePiclet, target: BattlePiclet, move: Move): number {
const baseDamage = this.getDamageAmount(amount);
// Type effectiveness
const effectiveness = getEffectivenessMultiplier(
move.type,
target.definition.primaryType,
target.definition.secondaryType
);
// STAB (Same Type Attack Bonus)
const stab = (move.type === attacker.definition.primaryType || move.type === attacker.definition.secondaryType) ? 1.5 : 1;
// Damage calculation (simplified)
const attackStat = attacker.attack;
const defenseStat = target.defense;
let damage = Math.floor((baseDamage * (attackStat / defenseStat) * 0.5) + 10);
damage = Math.floor(damage * effectiveness * stab);
// Random factor (85-100%)
damage = Math.floor(damage * (0.85 + Math.random() * 0.15));
// Minimum 1 damage for effective moves
if (effectiveness > 0 && damage < 1) {
damage = 1;
}
// Log effectiveness messages
if (effectiveness === 0) {
this.log("It had no effect!");
} else if (effectiveness > 1) {
this.log("It's super effective!");
} else if (effectiveness < 1) {
this.log("It's not very effective...");
}
return damage;
}
private processModifyStatsEffect(effect: { stats: Partial<Record<keyof BaseStats | 'accuracy', StatModification>> }, target: BattlePiclet): void {
for (const [stat, modification] of Object.entries(effect.stats)) {
const multiplier = this.getStatModifier(modification);
if (stat === 'accuracy') {
target.accuracy = Math.floor(target.accuracy * multiplier);
} else {
const statKey = stat as keyof BaseStats;
(target as any)[statKey] = Math.floor((target as any)[statKey] * multiplier);
}
this.log(`${target.definition.name}'s ${stat} ${modification.includes('increase') ? 'rose' : 'fell'}!`);
}
}
private processApplyStatusEffect(effect: { status: StatusEffect; chance?: number }, target: BattlePiclet): void {
// Check chance if specified
if (effect.chance !== undefined) {
const roll = Math.random() * 100;
if (roll >= effect.chance) {
return; // Status effect failed to apply
}
}
if (!target.statusEffects.includes(effect.status)) {
target.statusEffects.push(effect.status);
this.log(`${target.definition.name} was ${effect.status}ed!`);
}
}
private processHealEffect(effect: { amount?: HealAmount; formula?: string; value?: number }, target: BattlePiclet): void {
let healAmount = 0;
if (effect.formula) {
switch (effect.formula) {
case 'percentage':
healAmount = Math.floor(target.maxHp * ((effect.value || 0) / 100));
break;
case 'fixed':
healAmount = effect.value || 0;
break;
default:
healAmount = this.getHealAmount(effect.amount || 'medium', target.maxHp);
}
} else if (effect.amount) {
healAmount = this.getHealAmount(effect.amount, target.maxHp);
}
const oldHp = target.currentHp;
target.currentHp = Math.min(target.maxHp, target.currentHp + healAmount);
const actualHeal = target.currentHp - oldHp;
if (actualHeal > 0) {
this.log(`${target.definition.name} recovered ${actualHeal} HP!`);
}
}
private getDamageAmount(amount: DamageAmount): number {
switch (amount) {
case 'weak': return 40;
case 'normal': return 70;
case 'strong': return 100;
case 'extreme': return 140;
default: return 70;
}
}
private getStatModifier(modification: StatModification): number {
switch (modification) {
case 'increase': return 1.25;
case 'decrease': return 0.75;
case 'greatly_increase': return 1.5;
case 'greatly_decrease': return 0.5;
default: return 1.0;
}
}
private getHealAmount(amount: HealAmount, maxHp: number): number {
switch (amount) {
case 'small': return Math.floor(maxHp * 0.25);
case 'medium': return Math.floor(maxHp * 0.5);
case 'large': return Math.floor(maxHp * 0.75);
case 'full': return maxHp;
default: return Math.floor(maxHp * 0.5);
}
}
private processTurnEnd(): void {
// Process status effects
this.processStatusEffects(this.state.playerPiclet);
this.processStatusEffects(this.state.opponentPiclet);
// Decrement temporary effects
this.processTemporaryEffects(this.state.playerPiclet);
this.processTemporaryEffects(this.state.opponentPiclet);
}
private processStatusEffects(piclet: BattlePiclet): void {
for (const status of piclet.statusEffects) {
switch (status) {
case 'burn':
case 'poison':
const damage = Math.floor(piclet.maxHp / 8);
piclet.currentHp = Math.max(0, piclet.currentHp - damage);
this.log(`${piclet.definition.name} was hurt by ${status}!`);
break;
// Other status effects can be implemented later
}
}
}
private processTemporaryEffects(piclet: BattlePiclet): void {
// Decrement duration of temporary effects
piclet.temporaryEffects = piclet.temporaryEffects.filter(effect => {
effect.duration--;
return effect.duration > 0;
});
}
private checkBattleEnd(): void {
if (this.state.playerPiclet.currentHp <= 0 && this.state.opponentPiclet.currentHp <= 0) {
this.state.winner = 'draw';
this.state.phase = 'ended';
this.log('Battle ended in a draw!');
} else if (this.state.playerPiclet.currentHp <= 0) {
this.state.winner = 'opponent';
this.state.phase = 'ended';
this.log(`${this.state.opponentPiclet.definition.name} wins!`);
} else if (this.state.opponentPiclet.currentHp <= 0) {
this.state.winner = 'player';
this.state.phase = 'ended';
this.log(`${this.state.playerPiclet.definition.name} wins!`);
}
}
private log(message: string): void {
this.state.log.push(message);
}
// Public method to get battle log
public getLog(): string[] {
return [...this.state.log];
}
// Additional effect processors for advanced features
private processManipulatePPEffect(effect: { action: string; amount?: string; value?: number; targetMove?: string }, target: BattlePiclet): void {
// Placeholder implementation
this.log(`PP manipulation effect (${effect.action}) not fully implemented yet`);
}
private processFieldEffect(effect: { effect: string; target: string; stackable?: boolean }): void {
// Add field effect to battle state
const fieldEffect = {
name: effect.effect,
duration: 5, // Default duration
effect: effect
};
// Check if effect already exists and is not stackable
if (!effect.stackable) {
this.state.fieldEffects = this.state.fieldEffects.filter(fe => fe.name !== effect.effect);
}
this.state.fieldEffects.push(fieldEffect);
this.log(`Field effect '${effect.effect}' was applied!`);
}
private processCounterEffect(effect: { counterType: string; strength: string }, attacker: BattlePiclet, target: BattlePiclet): void {
// Store counter effect for processing later
target.temporaryEffects.push({
effect: {
type: 'counter',
counterType: effect.counterType,
strength: effect.strength
} as any,
duration: 1
});
this.log(`${target.definition.name} is preparing to counter ${effect.counterType} attacks!`);
}
private processPriorityEffect(effect: { value: number; condition?: string }, target: BattlePiclet): void {
// Store priority modification for next move
target.statModifiers.priority = (target.statModifiers.priority || 0) + effect.value;
this.log(`${target.definition.name}'s move priority changed by ${effect.value}!`);
}
private processRemoveStatusEffect(effect: { status: string }, target: BattlePiclet): void {
if (target.statusEffects.includes(effect.status as any)) {
target.statusEffects = target.statusEffects.filter(s => s !== effect.status);
this.log(`${target.definition.name} was cured of ${effect.status}!`);
}
}
private processMechanicOverrideEffect(effect: { mechanic: string; value: any; condition?: string }, target: BattlePiclet): void {
// Store mechanic override for processing
// This is a placeholder - full implementation would be complex
this.log(`Mechanic override '${effect.mechanic}' applied to ${target.definition.name}!`);
}
} |