File size: 20,291 Bytes
7428b13 a46ce65 7428b13 4c208f2 a6cc65f d871370 e8aa797 a46ce65 7428b13 c61508c 7428b13 4c208f2 7428b13 4c208f2 7428b13 4c208f2 7428b13 81b3c3b e40394b 81b3c3b e8aa797 a6cc65f 7428b13 4c208f2 7428b13 a46ce65 4c208f2 7428b13 4c208f2 a46ce65 4c208f2 7428b13 8f5f6c9 4c208f2 8f5f6c9 4c208f2 a46ce65 8f5f6c9 81b3c3b 4c208f2 81b3c3b 4c208f2 a46ce65 4c208f2 a46ce65 4c208f2 e8aa797 4c208f2 a46ce65 4c208f2 a46ce65 4c208f2 a46ce65 4c208f2 81b3c3b a6cc65f 81b3c3b a6cc65f 81b3c3b 5529e9d a6cc65f 81b3c3b 5529e9d 81b3c3b a6cc65f 81b3c3b a6cc65f 81b3c3b a6cc65f 81b3c3b a6cc65f 81b3c3b a6cc65f 81b3c3b a6cc65f 81b3c3b a6cc65f 81b3c3b 5529e9d 81b3c3b e40394b a6cc65f e40394b a6cc65f e40394b 81b3c3b e40394b 81b3c3b e40394b 81b3c3b 4c208f2 a46ce65 4c208f2 7428b13 4c208f2 7428b13 4c208f2 7428b13 4c208f2 7428b13 e8aa797 82b6f62 e8aa797 82b6f62 e8aa797 82b6f62 e8aa797 7428b13 90a88fc 7428b13 90a88fc 7428b13 4c208f2 7428b13 4c208f2 81b3c3b e40394b 7428b13 4c208f2 c61508c 4c208f2 7428b13 e8aa797 7428b13 90a88fc 7428b13 e95e2d9 7428b13 afa3e65 7428b13 e95e2d9 7428b13 e8aa797 7428b13 |
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 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 |
<script lang="ts">
import { onMount } from 'svelte';
import { fade } from 'svelte/transition';
import type { PicletInstance, BattleMove } from '$lib/db/schema';
import BattleField from '../Battle/BattleField.svelte';
import BattleControls from '../Battle/BattleControls.svelte';
import { BattleEngine } from '$lib/battle-engine/BattleEngine';
import type { BattleState, MoveAction } from '$lib/battle-engine/types';
import { picletInstanceToBattleDefinition, battlePicletToInstance, stripBattlePrefix } from '$lib/utils/battleConversion';
import { calculateBattleXp, processAllLevelUps } from '$lib/services/levelingService';
import { db } from '$lib/db/index';
import { getEffectivenessText, getEffectivenessColor } from '$lib/types/picletTypes';
export let playerPiclet: PicletInstance;
export let enemyPiclet: PicletInstance;
export let isWildBattle: boolean = true;
export let onBattleEnd: (result: any) => void = () => {};
export let rosterPiclets: PicletInstance[] = []; // All roster piclets passed from parent
// Initialize battle engine
let battleEngine: BattleEngine;
let battleState: BattleState;
let currentPlayerPiclet = playerPiclet;
let currentEnemyPiclet = enemyPiclet;
// Battle state
let currentMessage = isWildBattle
? `A wild ${enemyPiclet.nickname} appeared!`
: `Trainer wants to battle!`;
let battlePhase: 'intro' | 'main' | 'moveSelect' | 'picletSelect' | 'ended' = 'intro';
let processingTurn = false;
let battleEnded = false;
// HP animation states
let playerHpPercentage = playerPiclet.currentHp / playerPiclet.maxHp;
let enemyHpPercentage = enemyPiclet.currentHp / enemyPiclet.maxHp;
// Visual effects state
let playerEffects: Array<{type: string, emoji: string, duration: number}> = [];
let enemyEffects: Array<{type: string, emoji: string, duration: number}> = [];
let playerFlash = false;
let enemyFlash = false;
let playerFaint = false;
let enemyFaint = false;
// Battle results state
let battleResultsVisible = false;
let battleResults = {
victory: false,
xpGained: 0,
levelUps: [],
newLevel: 0
};
onMount(() => {
// Initialize battle engine with converted piclet definitions
const playerDefinition = picletInstanceToBattleDefinition(playerPiclet);
const enemyDefinition = picletInstanceToBattleDefinition(enemyPiclet);
battleEngine = new BattleEngine(playerDefinition, enemyDefinition, playerPiclet.level, enemyPiclet.level);
battleState = battleEngine.getState();
// Start intro sequence
setTimeout(() => {
currentMessage = `Go, ${playerPiclet.nickname}!`;
setTimeout(() => {
currentMessage = `What will ${playerPiclet.nickname} do?`;
battlePhase = 'main';
}, 1500);
}, 2000);
});
function handleAction(action: string) {
if (processingTurn || battleEnded) return;
switch (action) {
case 'catch':
if (isWildBattle) {
processingTurn = true;
currentMessage = 'You threw a Piclet Ball!';
setTimeout(() => {
currentMessage = 'The wild piclet broke free!';
processingTurn = false;
}, 2000);
}
break;
case 'run':
if (isWildBattle) {
currentMessage = 'Got away safely!';
battleEnded = true;
setTimeout(() => onBattleEnd(false), 1500);
} else {
currentMessage = "You can't run from a trainer battle!";
}
break;
}
}
function handleMoveSelect(move: BattleMove) {
if (!battleEngine) return;
battlePhase = 'main';
processingTurn = true;
// Find the corresponding move in the battle engine
const battleMove = battleState.playerPiclet.moves.find(m => m.move.name === move.name);
if (!battleMove) return;
const moveAction: MoveAction = {
type: 'move',
moveIndex: battleState.playerPiclet.moves.indexOf(battleMove)
};
try {
// Choose random enemy move (could be improved with AI)
const availableEnemyMoves = battleState.opponentPiclet.moves.filter(m => m.currentPP > 0);
if (availableEnemyMoves.length === 0) {
currentMessage = `${currentEnemyPiclet.nickname} has no moves left!`;
processingTurn = false;
return;
}
const randomEnemyMove = availableEnemyMoves[Math.floor(Math.random() * availableEnemyMoves.length)];
const enemyMoveIndex = battleState.opponentPiclet.moves.indexOf(randomEnemyMove);
const enemyAction: MoveAction = {
type: 'move',
moveIndex: enemyMoveIndex
};
// Get log entries before action to track new messages
const logBefore = battleEngine.getLog();
// Execute the turn - battle engine handles priority automatically
battleEngine.executeActions(moveAction, enemyAction);
battleState = battleEngine.getState();
// Get only the new log entries from this turn
const logAfter = battleEngine.getLog();
const newLogEntries = logAfter.slice(logBefore.length);
const result = { log: newLogEntries };
// Show battle messages with timing and visual effects
if (result.log && result.log.length > 0) {
let messageIndex = 0;
function showNextBattleMessage() {
if (messageIndex < result.log.length) {
const message = result.log[messageIndex];
currentMessage = message;
// Trigger visual effects based on message content
triggerVisualEffectsFromMessage(message);
messageIndex++;
setTimeout(showNextBattleMessage, 1500);
} else {
// After all messages, check battle end or continue
finalizeTurn();
}
}
showNextBattleMessage();
} else {
finalizeTurn();
}
function finalizeTurn() {
// Update UI state from battle engine
updateUIFromBattleState();
// Check for battle end
if (battleState.winner) {
battleEnded = true;
const winMessage = battleState.winner === 'player'
? `${currentEnemyPiclet.nickname} fainted! You won!`
: `${currentPlayerPiclet.nickname} fainted! You lost!`;
currentMessage = winMessage;
// Process battle results with XP and level ups
setTimeout(async () => {
await handleBattleResults(battleState.winner === 'player');
}, 2000);
} else {
setTimeout(() => {
currentMessage = `What will ${currentPlayerPiclet.nickname} do?`;
processingTurn = false;
}, 1000);
}
}
} catch (error) {
console.error('Battle engine error:', error);
currentMessage = 'Something went wrong in battle!';
processingTurn = false;
}
}
function triggerVisualEffectsFromMessage(message: string) {
// Use internal battle prefixes for reliable animation targeting
const playerInternalName = battleState?.playerPiclet?.definition?.name || '';
const enemyInternalName = battleState?.opponentPiclet?.definition?.name || '';
// Damage effects
if (message.includes('took') && message.includes('damage')) {
if (message.includes(playerInternalName)) {
triggerDamageFlash('player');
updateUIFromBattleState();
} else if (message.includes(enemyInternalName)) {
triggerDamageFlash('enemy');
updateUIFromBattleState();
}
}
// Critical hit effects
if (message.includes('critical hit')) {
triggerEffect('both', 'critical', 'π₯', 1000);
}
// Effectiveness messages
if (message.includes("It's super effective")) {
triggerEffect('both', 'superEffective', 'β‘', 800);
} else if (message.includes("not very effective")) {
triggerEffect('both', 'notVeryEffective', 'π¨', 800);
}
// Status effects
if (message.includes('was burned')) {
const target = message.includes(playerInternalName) ? 'player' : 'enemy';
triggerEffect(target, 'burn', 'π₯', 1200);
} else if (message.includes('was poisoned')) {
const target = message.includes(playerInternalName) ? 'player' : 'enemy';
triggerEffect(target, 'poison', 'β οΈ', 1200);
} else if (message.includes('was paralyzed')) {
const target = message.includes(playerInternalName) ? 'player' : 'enemy';
triggerEffect(target, 'paralyze', 'β‘', 1200);
} else if (message.includes('fell asleep')) {
const target = message.includes(playerInternalName) ? 'player' : 'enemy';
triggerEffect(target, 'sleep', 'π΄', 1200);
} else if (message.includes('was frozen')) {
const target = message.includes(playerInternalName) ? 'player' : 'enemy';
triggerEffect(target, 'freeze', 'βοΈ', 1200);
}
// Stat changes
if (message.includes("'s") && (message.includes('rose') || message.includes('fell'))) {
const target = message.includes(playerInternalName) ? 'player' : 'enemy';
const isIncrease = message.includes('rose');
if (message.includes('attack')) {
triggerEffect(target, isIncrease ? 'attackUp' : 'attackDown', isIncrease ? 'βοΈ' : 'π»', 1000);
} else if (message.includes('defense')) {
triggerEffect(target, isIncrease ? 'defenseUp' : 'defenseDown', isIncrease ? 'π‘οΈ' : 'π»', 1000);
} else if (message.includes('speed')) {
triggerEffect(target, isIncrease ? 'speedUp' : 'speedDown', isIncrease ? 'π¨' : 'π', 1000);
} else if (message.includes('accuracy')) {
triggerEffect(target, isIncrease ? 'accuracyUp' : 'accuracyDown', isIncrease ? 'π―' : 'ποΈ', 1000);
}
}
// Healing effects
if (message.includes('recovered') && message.includes('HP')) {
const target = message.includes(playerInternalName) ? 'player' : 'enemy';
triggerEffect(target, 'heal', 'π', 1000);
// Update HP bar immediately for healing animation sync
updateUIFromBattleState();
}
// Miss effects
if (message.includes('missed')) {
triggerEffect('both', 'miss', 'π«', 800);
}
// Faint effects
if (message.includes('fainted')) {
if (message.includes(playerInternalName)) {
triggerFaintAnimation('player');
} else if (message.includes(enemyInternalName)) {
triggerFaintAnimation('enemy');
}
}
}
function triggerDamageFlash(target: 'player' | 'enemy') {
if (target === 'player') {
playerFlash = true;
setTimeout(() => playerFlash = false, 1000); // Match original Snaplings flicker duration
} else {
enemyFlash = true;
setTimeout(() => enemyFlash = false, 1000); // Match original Snaplings flicker duration
}
}
function triggerFaintAnimation(target: 'player' | 'enemy') {
if (target === 'player') {
playerFaint = true;
// Don't reset - faint animation should persist until battle ends
} else {
enemyFaint = true;
// Don't reset - faint animation should persist until battle ends
}
}
function triggerEffect(target: 'player' | 'enemy' | 'both', type: string, emoji: string, duration: number) {
const effect = { type, emoji, duration };
if (target === 'player' || target === 'both') {
playerEffects = [...playerEffects, effect];
setTimeout(() => {
playerEffects = playerEffects.filter(e => e !== effect);
}, duration);
}
if (target === 'enemy' || target === 'both') {
enemyEffects = [...enemyEffects, effect];
setTimeout(() => {
enemyEffects = enemyEffects.filter(e => e !== effect);
}, duration);
}
}
function updateUIFromBattleState() {
if (!battleState) return;
// Update player piclet state
currentPlayerPiclet = battlePicletToInstance(battleState.playerPiclet, currentPlayerPiclet);
playerHpPercentage = battleState.playerPiclet.currentHp / battleState.playerPiclet.maxHp;
// Update enemy piclet state
currentEnemyPiclet = battlePicletToInstance(battleState.opponentPiclet, currentEnemyPiclet);
enemyHpPercentage = battleState.opponentPiclet.currentHp / battleState.opponentPiclet.maxHp;
}
function handlePicletSelect(piclet: PicletInstance) {
if (!battleEngine) return;
battlePhase = 'main';
currentMessage = `Come back, ${currentPlayerPiclet.nickname}!`;
setTimeout(() => {
// Convert the selected piclet to battle definition and switch
const newPicletDefinition = picletInstanceToBattleDefinition(piclet);
try {
// TODO: Implement switching in battle engine
// For now, just update the UI
currentPlayerPiclet = piclet;
playerHpPercentage = piclet.currentHp / piclet.maxHp;
currentMessage = `Go, ${piclet.nickname}!`;
setTimeout(() => {
currentMessage = `What will ${piclet.nickname} do?`;
}, 1500);
} catch (error) {
console.error('Switch error:', error);
currentMessage = 'Unable to switch Piclets!';
}
}, 1500);
}
function handleBack() {
battlePhase = 'main';
}
async function handleBattleResults(playerWon: boolean) {
if (playerWon) {
// Calculate XP gained from defeating the enemy
const xpGained = calculateBattleXp(currentEnemyPiclet, 1);
if (xpGained > 0) {
// Animate XP gain by updating UI first
const updatedPlayerPiclet = {
...currentPlayerPiclet,
xp: currentPlayerPiclet.xp + xpGained
};
currentPlayerPiclet = updatedPlayerPiclet;
// Wait a moment for XP bar animation
await new Promise(resolve => setTimeout(resolve, 1500));
// Process any level ups
const { newInstance, levelUpInfo } = processAllLevelUps(updatedPlayerPiclet);
// Save updated Piclet to database
if (newInstance.id) {
await db.picletInstances.update(newInstance.id, newInstance);
}
// Update local state with final leveled instance
currentPlayerPiclet = newInstance;
// Show level up results if any occurred
if (levelUpInfo.length > 0) {
battleResults = {
victory: true,
xpGained,
levelUps: levelUpInfo,
newLevel: newInstance.level
};
battleResultsVisible = true;
// Auto-dismiss after showing level up
setTimeout(() => {
battleResultsVisible = false;
onBattleEnd(true);
}, 4000);
} else {
// No level up, just end battle
onBattleEnd(true);
}
} else {
onBattleEnd(true);
}
} else {
// Player lost - no XP gained
onBattleEnd(false);
}
}
</script>
<div class="battle-page" transition:fade={{ duration: 300 }}>
<nav class="battle-nav">
<button class="back-button" on:click={() => onBattleEnd('cancelled')} style="display: none;">
β Back
</button>
<h1>{isWildBattle ? 'Wild Battle' : 'Battle'}</h1>
<div class="nav-spacer"></div>
</nav>
<div class="battle-content">
<BattleField
playerPiclet={currentPlayerPiclet}
enemyPiclet={currentEnemyPiclet}
{playerHpPercentage}
{enemyHpPercentage}
showIntro={battlePhase === 'intro'}
{battleState}
{playerEffects}
{enemyEffects}
{playerFlash}
{enemyFlash}
{playerFaint}
{enemyFaint}
/>
<BattleControls
{currentMessage}
{battlePhase}
{processingTurn}
{battleEnded}
{isWildBattle}
playerPiclet={currentPlayerPiclet}
enemyPiclet={currentEnemyPiclet}
{rosterPiclets}
{battleState}
onAction={handleAction}
onMoveSelect={handleMoveSelect}
onPicletSelect={handlePicletSelect}
onBack={handleBack}
/>
</div>
<!-- Battle Results Overlay -->
{#if battleResultsVisible}
<div class="battle-results-overlay" transition:fade={{ duration: 300 }}>
<div class="battle-results-card">
<h2>{battleResults.victory ? 'Victory!' : 'Defeat!'}</h2>
{#if battleResults.levelUps.length > 0}
{#each battleResults.levelUps as levelUp}
<div class="level-up" transition:fade={{ duration: 500 }}>
<h3>π Level Up! π</h3>
<p><strong>{currentPlayerPiclet.nickname}</strong> grew to level <strong>{levelUp.newLevel}</strong>!</p>
<div class="stat-changes">
{#if levelUp.statChanges.hp > 0}
<div class="stat-change">HP +{levelUp.statChanges.hp}</div>
{/if}
{#if levelUp.statChanges.attack > 0}
<div class="stat-change">Attack +{levelUp.statChanges.attack}</div>
{/if}
{#if levelUp.statChanges.defense > 0}
<div class="stat-change">Defense +{levelUp.statChanges.defense}</div>
{/if}
{#if levelUp.statChanges.speed > 0}
<div class="stat-change">Speed +{levelUp.statChanges.speed}</div>
{/if}
</div>
</div>
{/each}
{/if}
</div>
</div>
{/if}
</div>
<style>
.battle-page {
position: fixed;
inset: 0;
z-index: 1000;
height: 100vh;
display: flex;
flex-direction: column;
background: #f8f9fa;
overflow: hidden;
padding-top: env(safe-area-inset-top);
}
@media (max-width: 768px) {
.battle-page {
background: white;
}
.battle-page::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: env(safe-area-inset-top);
background: white;
z-index: 1;
}
}
.battle-nav {
display: none; /* Hide navigation in battle */
}
.back-button {
background: none;
border: none;
color: #007bff;
font-size: 1rem;
cursor: pointer;
padding: 0.5rem;
}
.battle-nav h1 {
margin: 0;
font-size: 1.25rem;
font-weight: 600;
color: #1a1a1a;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
.nav-spacer {
width: 60px;
}
.battle-content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
position: relative;
background: #f8f9fa;
}
/* Battle Results Overlay */
.battle-results-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 2000;
}
.battle-results-card {
background: white;
border-radius: 16px;
padding: 2rem;
max-width: 400px;
width: 90%;
text-align: center;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
.battle-results-card h2 {
margin: 0 0 1rem 0;
font-size: 1.8rem;
font-weight: 700;
color: #1a1a1a;
}
.level-up {
background: linear-gradient(135deg, #fff3e0 0%, #ffcc02 100%);
border-radius: 12px;
padding: 1.5rem;
margin: 1rem 0;
border: 3px solid #ff6f00;
animation: levelUpPulse 0.6s ease-in-out;
}
.level-up h3 {
margin: 0 0 0.5rem 0;
font-size: 1.4rem;
color: #e65100;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}
.level-up p {
margin: 0 0 1rem 0;
font-size: 1.2rem;
color: #bf360c;
}
.stat-changes {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
justify-content: center;
}
.stat-change {
background: rgba(76, 175, 80, 0.2);
border: 1px solid #4caf50;
border-radius: 20px;
padding: 0.25rem 0.75rem;
font-size: 0.9rem;
font-weight: 600;
color: #2e7d32;
}
@keyframes levelUpPulse {
0% {
transform: scale(0.9);
opacity: 0;
}
50% {
transform: scale(1.05);
}
100% {
transform: scale(1);
opacity: 1;
}
}
</style> |