Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 | 21x 21x 21x 21x 21x 241x 241x 241x 241x 21x 21x 21x 21x 4x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 11x 32x 32x 16x 39x 20x 12x 8x 8x 8x 12x 12x 6x 6x 3x 3x 6x 6x 2x 4x | /**
* Balance System for managing stability and vulnerability windows.
*
* **Korean**: 균형 시스템 (Balance System)
*
* Implements physical balance and stability mechanics. Loss of balance creates
* vulnerability windows where damage is increased and defensive options limited.
* Balance is affected by:
* - Leg strikes
* - Throws and sweeps
* - Heavy impacts
* - Fatigue (low stamina)
*
* ## Balance States
*
* - **Stable**: 80-100 balance - Full mobility and defense
* - **Unsteady**: 50-79 balance - Reduced evasion, slower movement
* - **Off-Balance**: 20-49 balance - Vulnerability window, defense penalty
* - **Falling**: 0-19 balance - Severe vulnerability, possible knockdown
*
* ## Fall System Integration
*
* When balance falls below 20%, the system can trigger fall animations (낙법).
* Fall direction is determined by attack vector and player stance.
*
* @module systems/combat/BalanceSystem
* @category Combat System
* @korean 균형시스템
*/
import { BodyRegion } from "@/types";
import type { TrigramStance } from "@/types/common";
import {
determineFallDirection,
determineFallFromStance,
getRecoveryConfig,
isVulnerableFrame,
} from "../animation";
import type {
FallType,
GroundState,
RecoveryAnimationType,
} from "../animation/core/types";
import { PlayerState } from "../player";
/**
* Balance levels representing physical stability.
*
* **Korean**: 균형 수준
*/
export enum BalanceLevel {
/** Stable footing (80-100) */
STABLE = "stable",
/** Unsteady but controlled (50-79) */
UNSTEADY = "unsteady",
/** Off-balance, vulnerable (20-49) */
OFF_BALANCE = "off_balance",
/** Falling or knocked down (0-19) */
FALLING = "falling",
}
/**
* Effects of balance on combat performance.
*/
interface BalanceEffects {
/** Balance value range */
readonly range: readonly [number, number];
/** Defense multiplier */
readonly defenseMultiplier: number;
/** Evasion success chance modifier */
readonly evasionModifier: number;
/** Movement speed multiplier */
readonly movementSpeedMultiplier: number;
/** Vulnerability to attacks multiplier */
readonly vulnerabilityMultiplier: number;
/** Can perform evasive actions */
readonly canEvade: boolean;
/** Risk of knockdown */
readonly knockdownRisk: number;
}
/**
* Balance System managing stability and vulnerability.
*
* Balance represents physical stability and center of gravity control.
* Low balance creates vulnerability windows where opponents can capitalize
* with increased damage and reduced defensive options.
*
* @example
* ```typescript
* const balanceSystem = new BalanceSystem();
*
* // Apply balance disruption from leg strike
* const newPlayer = balanceSystem.disruptBalance(
* player,
* 15,
* BodyRegion.LEFT_LEG
* );
*
* // Check if vulnerable
* const isVulnerable = balanceSystem.isVulnerable(newPlayer);
*
* // Apply recovery
* const recovered = balanceSystem.applyRecovery(newPlayer, 1000);
* ```
*
* @public
* @korean 균형시스템
*/
export class BalanceSystem {
/**
* Balance level effects and thresholds.
*/
private readonly balanceEffects: Record<BalanceLevel, BalanceEffects> = {
[BalanceLevel.STABLE]: {
range: [80, 100],
defenseMultiplier: 1.0,
evasionModifier: 1.0,
movementSpeedMultiplier: 1.0,
vulnerabilityMultiplier: 1.0,
canEvade: true,
knockdownRisk: 0.0,
},
[BalanceLevel.UNSTEADY]: {
range: [50, 79],
defenseMultiplier: 0.85,
evasionModifier: 0.7,
movementSpeedMultiplier: 0.85,
vulnerabilityMultiplier: 1.15,
canEvade: true,
knockdownRisk: 0.1,
},
[BalanceLevel.OFF_BALANCE]: {
range: [20, 49],
defenseMultiplier: 0.6,
evasionModifier: 0.4,
movementSpeedMultiplier: 0.6,
vulnerabilityMultiplier: 1.5, // 50% more damage taken
canEvade: false,
knockdownRisk: 0.3,
},
[BalanceLevel.FALLING]: {
range: [0, 19],
defenseMultiplier: 0.3,
evasionModifier: 0.0,
movementSpeedMultiplier: 0.3,
vulnerabilityMultiplier: 2.0, // 100% more damage taken
canEvade: false,
knockdownRisk: 0.8,
},
};
/**
* Balance disruption multipliers by body region.
*/
private readonly regionMultipliers: Record<string, number> = {
[BodyRegion.LEFT_LEG]: 2.5,
[BodyRegion.RIGHT_LEG]: 2.5,
[BodyRegion.CORE]: 2.0,
[BodyRegion.TORSO]: 1.5,
[BodyRegion.HEAD]: 1.0,
default: 0.5,
};
/**
* Base balance recovery rate per second.
*/
private readonly baseRecoveryRate = 8.0; // 8 points per second
/**
* Maximum balance value.
*/
private readonly maxBalance = 100;
/**
* Disrupts balance from combat impact.
*
* Calculates balance loss based on damage amount and body region hit.
* Leg strikes cause maximum balance disruption.
*
* @param player - Current player state
* @param impact - Impact force amount
* @param region - Body region affected
* @returns Updated player state with reduced balance
*
* @example
* ```typescript
* // Leg sweep causes major balance disruption
* player = system.disruptBalance(
* player,
* 20,
* BodyRegion.RIGHT_LEG
* );
* ```
*
* @public
* @korean 균형파괴
*/
disruptBalance(
player: PlayerState,
impact: number,
region?: BodyRegion
): PlayerState {
// Get multiplier based on region
const multiplier = region
? this.regionMultipliers[region] ?? this.regionMultipliers.default
: this.regionMultipliers.default;
// Calculate balance loss
const balanceLoss = impact * multiplier * 0.6; // 0.6 = balance sensitivity
// Apply balance loss, clamped to 0
const newBalance = Math.max(0, player.balance - balanceLoss);
return {
...player,
balance: newBalance,
};
}
/**
* Applies balance recovery over time.
*
* Balance recovers quickly when not being disrupted, allowing
* fighters to regain stable footing between exchanges.
*
* @param player - Current player state
* @param deltaTime - Time elapsed in milliseconds
* @returns Updated player state with recovered balance
*
* @example
* ```typescript
* // In game loop
* player = system.applyRecovery(player, 16); // ~60fps
* ```
*
* @public
* @korean 균형회복
*/
applyRecovery(player: PlayerState, deltaTime: number): PlayerState {
// Already at maximum balance
if (player.balance >= this.maxBalance) {
return player;
}
const deltaSeconds = deltaTime / 1000;
const level = this.getBalanceLevel(player.balance);
// Recovery modifier based on balance level
let recoveryModifier = 1.0;
if (level === BalanceLevel.OFF_BALANCE) {
recoveryModifier = 0.7; // Harder to recover when off-balance
I} else if (level === BalanceLevel.FALLING) {
recoveryModifier = 0.4; // Very hard to recover when falling
}
// Stamina affects recovery rate
const staminaFactor = player.stamina / player.maxStamina;
const finalModifier = recoveryModifier * (0.5 + staminaFactor * 0.5);
const recovery = this.baseRecoveryRate * deltaSeconds * finalModifier;
const newBalance = Math.min(this.maxBalance, player.balance + recovery);
return {
...player,
balance: newBalance,
};
}
/**
* Determines balance level from balance value.
*
* @param balance - Balance value (0-100)
* @returns Current balance level
*
* @public
* @korean 균형수준확인
*/
getBalanceLevel(balance: number): BalanceLevel {
Iif (balance >= 80) return BalanceLevel.STABLE;
if (balance >= 50) return BalanceLevel.UNSTEADY;
Eif (balance >= 20) return BalanceLevel.OFF_BALANCE;
return BalanceLevel.FALLING;
}
/**
* Gets effects for a specific balance level.
*
* @param level - Balance level
* @returns Effects applied at that level
*
* @public
* @korean 균형효과
*/
getEffects(level: BalanceLevel): BalanceEffects {
return this.balanceEffects[level];
}
/**
* Applies balance effects to player state.
*
* Modifies player stats based on current balance level.
*
* @param player - Current player state
* @returns Modified player state with balance effects
*
* @public
* @korean 균형효과적용
*/
applyEffects(player: PlayerState): PlayerState {
const level = this.getBalanceLevel(player.balance);
const effects = this.getEffects(level);
return {
...player,
defense: Math.floor(player.defense * effects.defenseMultiplier),
speed: Math.floor(player.speed * effects.movementSpeedMultiplier),
};
}
/**
* Checks if player is vulnerable due to balance.
*
* @param player - Current player state
* @returns True if off-balance or falling
*
* @public
* @korean 균형취약확인
*/
isVulnerable(player: PlayerState): boolean {
const level = this.getBalanceLevel(player.balance);
return level === BalanceLevel.OFF_BALANCE || level === BalanceLevel.FALLING;
}
/**
* Calculates damage multiplier for vulnerable balance state.
*
* @param player - Current player state
* @returns Damage multiplier (1.0 = normal, >1.0 = increased damage)
*
* @public
* @korean 취약성배율
*/
getVulnerabilityMultiplier(player: PlayerState): number {
const level = this.getBalanceLevel(player.balance);
const effects = this.getEffects(level);
return effects.vulnerabilityMultiplier;
}
/**
* Checks if knockdown should occur, using a provided random function for determinism.
*
* @param player - Current player state
* @param randomFn - Optional random number generator (returns number in [0,1)), defaults to Math.random
* @returns True if knockdown should occur
*
* @public
* @korean 넘어짐확인
*/
shouldKnockdown(
player: PlayerState,
randomFn: () => number = Math.random
): boolean {
const level = this.getBalanceLevel(player.balance);
const effects = this.getEffects(level);
return randomFn() < effects.knockdownRisk;
}
/**
* Gets bilingual name for balance level.
*
* @param level - Balance level
* @returns Korean and English level names
*
* @public
* @korean 균형이름
*/
getLevelName(level: BalanceLevel): { korean: string; english: string } {
const names: Record<BalanceLevel, { korean: string; english: string }> = {
[BalanceLevel.STABLE]: {
korean: "안정",
english: "Stable",
},
[BalanceLevel.UNSTEADY]: {
korean: "불안정",
english: "Unsteady",
},
[BalanceLevel.OFF_BALANCE]: {
korean: "균형상실",
english: "Off-Balance",
},
[BalanceLevel.FALLING]: {
korean: "낙하중",
english: "Falling",
},
};
return names[level];
}
/**
* Gets color indicator for balance level (for UI).
*
* @param level - Balance level
* @returns Hex color code
*
* @public
* @korean 균형색상
*/
getLevelColor(level: BalanceLevel): number {
const colors: Record<BalanceLevel, number> = {
[BalanceLevel.STABLE]: 0x00ff00, // Green
[BalanceLevel.UNSTEADY]: 0xffff00, // Yellow
[BalanceLevel.OFF_BALANCE]: 0xff8800, // Orange
[BalanceLevel.FALLING]: 0xff0000, // Red
};
return colors[level];
}
/**
* Checks if balance is low enough to trigger fall animation.
*
* Falls occur when balance drops below 20% (FALLING state).
* This creates realistic knockdown conditions from balance loss.
*
* @param player - Current player state
* @returns True if fall animation should trigger
*
* @example
* ```typescript
* if (balanceSystem.shouldTriggerFall(player)) {
* const fallType = balanceSystem.determineFallType(
* player,
* attackAngle,
* attackHeight
* );
* animationMachine.transitionTo(FALL_TYPE_TO_ANIMATION[fallType]);
* }
* ```
*
* @public
* @korean 낙법발동확인
*/
shouldTriggerFall(player: PlayerState): boolean {
return player.balance < 20; // FALLING threshold
}
/**
* Determines which fall animation to play based on attack and stance.
*
* Calculates fall direction using:
* - Attack angle relative to player
* - Attack height (high/mid/low)
* - Player's current stance bias
*
* Korean falling techniques (낙법):
* - 전방낙법 (Jeonbang Nakbeop): Forward fall
* - 후방낙법 (Hubang Nakbeop): Backward fall
* - 측방낙법 (Cheukbang Nakbeop): Side fall
*
* @param player - Current player state
* @param attackAngle - Angle of attack in radians (0 = from front)
* @param attackHeight - Attack height: 'high', 'mid', or 'low'
* @returns Fall type to use for animation
*
* @example
* ```typescript
* // Player facing forward (0°), attacked from behind (π)
* const fallType = balanceSystem.determineFallType(
* player,
* Math.PI,
* 'mid'
* );
* // Returns: 'forward' (pushed forward by rear attack)
*
* // Low sweep from right side
* const fallType = balanceSystem.determineFallType(
* player,
* Math.PI/2,
* 'low'
* );
* // Returns: 'side_right' (swept to the side)
* ```
*
* @public
* @korean 낙법유형결정
*/
determineFallType(
_player: PlayerState,
attackAngle: number,
attackHeight: "high" | "mid" | "low" = "mid"
): FallType {
// Get player facing angle from position or default to 0
const playerFacing = 0; // Default facing forward
// Use attack direction to determine fall
return determineFallDirection(attackAngle, playerFacing, attackHeight);
}
/**
* Determines fall type based on player stance when no attack direction available.
*
* Uses stance bias to determine likely fall direction when balance is lost
* without a specific attack (e.g., from fatigue, leg damage accumulation).
*
* @param stance - Current trigram stance
* @returns Fall type based on stance characteristics
*
* @example
* ```typescript
* // Player in Heaven stance (aggressive forward)
* const fallType = balanceSystem.determineFallTypeFromStance(
* TrigramStance.GEON
* );
* // Returns: 'forward' (Heaven stance has forward bias)
* ```
*
* @public
* @korean 자세낙법결정
*/
determineFallTypeFromStance(stance: TrigramStance): FallType {
return determineFallFromStance(stance);
}
/**
* Check if player is in a grounded state based on animation state.
*
* Player is considered grounded when in any ground_* animation state
* (ground_prone, ground_supine, ground_side_left, ground_side_right).
*
* @param animationState - Current animation state from AnimationStateMachine
* @returns True if player is on the ground
*
* @example
* ```typescript
* const isGrounded = balanceSystem.isGrounded("ground_prone");
* // Returns: true
*
* const notGrounded = balanceSystem.isGrounded("idle");
* // Returns: false
* ```
*
* @public
* @korean 지면상태확인
*/
isGrounded(animationState: string): boolean {
return animationState.startsWith("ground_");
}
/**
* Get ground state from animation state.
*
* Extracts the ground position type from animation state name.
* Returns null if not in a ground state.
*
* @param animationState - Current animation state from AnimationStateMachine
* @returns Ground state or null if not grounded
*
* @example
* ```typescript
* const state = balanceSystem.getGroundState("ground_prone");
* // Returns: "prone"
*
* const none = balanceSystem.getGroundState("idle");
* // Returns: null
* ```
*
* @public
* @korean 지면자세가져오기
*/
getGroundState(animationState: string): GroundState | null {
if (!this.isGrounded(animationState)) {
return null;
}
// Extract ground state from animation state name
// "ground_prone" -> "prone"
const groundType = animationState.replace("ground_", "");
// Validate that it's a valid ground state
Eif (
groundType === "prone" ||
groundType === "supine" ||
groundType === "side_left" ||
groundType === "side_right"
) {
return groundType as GroundState;
}
return null;
}
/**
* Check if player can execute recovery based on stamina.
*
* Some recovery animations (like roll recovery) require stamina.
* This checks if player has sufficient stamina for the recovery type.
*
* @param player - Current player state
* @param recoveryType - Type of recovery animation
* @returns True if player has enough stamina
*
* @example
* ```typescript
* // Roll recovery costs 20 stamina
* const canRoll = balanceSystem.canRecoverWithType(player, "roll_recovery");
* // Returns: true if player.stamina >= 20
*
* // Normal recoveries have no cost
* const canStand = balanceSystem.canRecoverWithType(player, "prone_standup");
* // Returns: true (no stamina requirement)
* ```
*
* @public
* @korean 회복가능확인
*/
canRecoverWithType(
player: PlayerState,
recoveryType: RecoveryAnimationType
): boolean {
const config = getRecoveryConfig(recoveryType);
// Check if player has enough stamina
return player.stamina >= config.staminaCost;
}
/**
* Apply stamina cost for recovery animation.
*
* Deducts stamina cost from player state for recovery animations
* that require stamina (like roll recovery).
*
* @param player - Current player state
* @param recoveryType - Type of recovery animation
* @returns Updated player state with stamina deducted
*
* @example
* ```typescript
* // Roll recovery costs 20 stamina
* const recovered = balanceSystem.applyRecoveryCost(player, "roll_recovery");
* // recovered.stamina = player.stamina - 20
* ```
*
* @public
* @korean 회복비용적용
*/
applyRecoveryCost(
player: PlayerState,
recoveryType: RecoveryAnimationType
): PlayerState {
const config = getRecoveryConfig(recoveryType);
if (config.staminaCost === 0) {
return player;
}
return {
...player,
stamina: Math.max(0, player.stamina - config.staminaCost),
};
}
/**
* Get damage multiplier during recovery animation.
*
* Some recovery animations (like defensive getup) provide damage reduction.
* This returns the multiplier to apply to incoming damage.
*
* @param recoveryType - Type of recovery animation
* @param currentFrame - Current frame in the animation
* @returns Damage multiplier (1.0 = normal, 0.5 = 50% reduction)
*
* @example
* ```typescript
* // Defensive getup has 50% damage reduction
* const multiplier = balanceSystem.getRecoveryDamageMultiplier("defensive_getup", 20);
* // Returns: 0.5 (50% damage reduction)
*
* // Normal recoveries have no reduction
* const normal = balanceSystem.getRecoveryDamageMultiplier("prone_standup", 15);
* // Returns: 1.0 (full damage)
* ```
*
* @public
* @korean 회복피해배율
*/
getRecoveryDamageMultiplier(
recoveryType: RecoveryAnimationType,
currentFrame: number
): number {
const config = getRecoveryConfig(recoveryType);
// Only apply damage reduction during vulnerable frames
if (!isVulnerableFrame(recoveryType, currentFrame)) {
return 1.0; // No vulnerability = full damage (or no damage if invulnerable)
}
// Apply damage reduction
// damageReduction of 0.5 means 50% reduction, so multiplier is 0.5
return 1.0 - config.damageReduction;
}
}
export default BalanceSystem;
|