All files / systems/combat BalanceSystem.ts

11.76% Statements 6/51
9.52% Branches 2/21
9.09% Functions 1/11
10.63% Lines 5/47

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                                                                  13x   13x   13x   13x   13x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
/**
 * 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
 * 
 * @module systems/combat/BalanceSystem
 * @category Combat System
 * @korean 균형시스템
 */
 
import { PlayerState } from "../player";
import { BodyRegion } from "@/types";
 
/**
 * 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
    } 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 {
    if (balance >= 80) return BalanceLevel.STABLE;
    if (balance >= 50) return BalanceLevel.UNSTEADY;
    if (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];
  }
}
 
export default BalanceSystem;