All files / systems/trigram StanceManager.ts

93.87% Statements 46/49
88.88% Branches 32/36
80% Functions 8/10
93.87% Lines 46/49

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                                                        126x 126x   126x                         3x                       5x                                         17x             17x 2x                   15x 17x 3x                     12x 17x     17x           17x                                       7x             7x 1x                     6x 1x 1x                       5x             5x   5x                       10x             10x 2x       8x 10x 1x       7x       7x                     21x 3x     18x 18x       18x     18x 18x 21x   21x                             2x   1x       1x 1x   2x                            
import { TrigramStance } from "../../types/common";
import { PlayerState } from "../player";
import { PLAYER_ARCHETYPES_DATA } from "../types";
import { TrigramCalculator } from "./TrigramCalculator";
import { StanceLaterality, TrigramTransitionCost } from "./types";
 
export interface StanceChangeResult {
  readonly success: boolean;
  readonly updatedPlayer: PlayerState;
  readonly cost: TrigramTransitionCost;
  readonly laterality?: StanceLaterality;
  readonly message?: string;
}
 
/**
 * Manager for trigram stance changes and laterality state
 * 
 * **Korean**: 자세 관리자
 * 
 * Manages both trigram stance selection (8 stances) and laterality (left/right).
 * Supports authentic Korean martial arts stance configurations with:
 * - 8 trigram stances (☰–☷)
 * - 2 laterality options (left/right foot forward)
 * - 16 total stance configurations
 * 
 * Laterality transitions take 400ms (24 frames @ 60fps) and cost 2 stamina.
 */
export class StanceManager {
  private readonly minTransitionInterval = 500;
  private readonly lateralityTransitionTime = 400; // 400ms for stance side switch
  private currentStance?: TrigramStance;
  private currentLaterality: StanceLaterality = "right"; // Default: right foot forward
 
  constructor() {
    // No initialization needed
  }
 
  /**
   * Get the current stance
   * 
   * @returns Current trigram stance or undefined if not set
   * @korean 현재자세가져오기
   */
  public getCurrent(): TrigramStance | undefined {
    return this.currentStance;
  }
 
  /**
   * Get the current stance laterality (left or right foot forward)
   * 
   * **Korean**: 현재 측면성
   * 
   * @returns Current laterality ("left" or "right")
   * @korean 현재측면성가져오기
   */
  public getCurrentLaterality(): StanceLaterality {
    return this.currentLaterality;
  }
 
  /**
   * Switch stance side (left ↔ right) without changing trigram stance
   * 
   * **Korean**: 자세 측면 전환
   * 
   * Mirrors the current guard position from left to right or vice versa.
   * Takes 400ms (24 frames @ 60fps) and costs 2 stamina.
   * 
   * Korean terminology:
   * - 왼발서기 (Oenbal Seogi): Left foot forward
   * - 오른발서기 (Oreun Bal Seogi): Right foot forward
   * 
   * @param player - Current player state
   * @param currentLaterality - Current laterality to toggle from
   * @returns Result with updated laterality
   * @korean 측면전환
   */
  public switchStanceSide(player: PlayerState, currentLaterality: StanceLaterality): StanceChangeResult {
    const lateralityCost: TrigramTransitionCost = {
      ki: 0,
      stamina: 2,
      timeMilliseconds: this.lateralityTransitionTime,
    };
 
    // Check if player has enough stamina
    if (player.stamina < lateralityCost.stamina) {
      return {
        success: false,
        updatedPlayer: player,
        cost: lateralityCost,
        laterality: currentLaterality,
        message: "Insufficient stamina to switch stance side",
      };
    }
 
    // Check cooldown
    const timeSinceLastChange = Date.now() - (player.lastStanceChangeTime || 0);
    if (timeSinceLastChange < this.minTransitionInterval) {
      return {
        success: false,
        updatedPlayer: player,
        cost: lateralityCost,
        laterality: currentLaterality,
        message: "Stance side switch on cooldown",
      };
    }
 
    // Switch laterality (toggle from current)
    const newLaterality: StanceLaterality = 
      currentLaterality === "left" ? "right" : "left";
    this.currentLaterality = newLaterality;
 
    // Apply stamina cost and update timestamp
    const updatedPlayer: PlayerState = {
      ...player,
      stamina: Math.max(0, player.stamina - lateralityCost.stamina),
      lastStanceChangeTime: Date.now(),
    };
 
    return {
      success: true,
      updatedPlayer,
      cost: lateralityCost,
      laterality: newLaterality,
    };
  }
 
  /**
   * Attempt to change stance
   * 
   * @param player - Current player state
   * @param newStance - Target trigram stance
   * @returns Result with success status and updated player
   * @korean 자세변경
   */
  changeStance(
    player: PlayerState,
    newStance: TrigramStance
  ): StanceChangeResult {
    const cost = this.getStanceTransitionCost(
      player.currentStance,
      newStance,
      player
    );
 
    // Check if transition is possible
    if (!this.canChangeStance(player, newStance)) {
      return {
        success: false,
        updatedPlayer: player,
        cost,
        laterality: this.currentLaterality,
        message:
          "Cannot change stance - insufficient resources or cooldown active",
      };
    }
 
    // Same stance - no cost, but update laterality info
    if (player.currentStance === newStance) {
      this.currentStance = newStance;
      return {
        success: true,
        updatedPlayer: {
          ...player,
          lastStanceChangeTime: Date.now(),
        },
        cost: { ki: 0, stamina: 0, timeMilliseconds: 0 },
        laterality: this.currentLaterality,
      };
    }
 
    // Apply stance change
    const updatedPlayer: PlayerState = {
      ...player,
      currentStance: newStance,
      ki: Math.max(0, player.ki - cost.ki),
      stamina: Math.max(0, player.stamina - cost.stamina),
      lastStanceChangeTime: Date.now(),
    };
    this.currentStance = newStance;
 
    return {
      success: true,
      updatedPlayer,
      cost,
      laterality: this.currentLaterality,
    };
  }
 
  /**
   * Check if player can change to the specified stance
   */
  canChangeStance(player: PlayerState, newStance: TrigramStance): boolean {
    const cost = this.getStanceTransitionCost(
      player.currentStance,
      newStance,
      player
    );
 
    // Check resources
    if (player.ki < cost.ki || player.stamina < cost.stamina) {
      return false;
    }
 
    // Check cooldown
    const timeSinceLastChange = Date.now() - (player.lastStanceChangeTime || 0);
    if (timeSinceLastChange < this.minTransitionInterval) {
      return false;
    }
 
    // Check if player is stunned or incapacitated
    Iif (player.isStunned || player.consciousness < 50) {
      return false;
    }
 
    return true;
  }
 
  /**
   * Calculate the cost of transitioning between stances
   */
  getStanceTransitionCost(
    fromStance: TrigramStance,
    toStance: TrigramStance,
    player: PlayerState
  ): TrigramTransitionCost {
    if (fromStance === toStance) {
      return { ki: 0, stamina: 0, timeMilliseconds: 0 };
    }
 
    const baseCost = { ki: 10, stamina: 15, timeMilliseconds: 500 };
    const difficulty = TrigramCalculator.calculateTransitionDifficulty(
      fromStance,
      toStance
    );
    const difficultyMultiplier = 1 + difficulty;
 
    // Apply archetype modifiers
    const archetypeData = PLAYER_ARCHETYPES_DATA[player.archetype];
    const favoredStances = archetypeData.favoredStances || [];
    const archetypeModifier = favoredStances.includes(toStance) ? 0.8 : 1.0;
 
    return {
      ki: Math.floor(baseCost.ki * difficultyMultiplier * archetypeModifier),
      stamina: Math.floor(
        baseCost.stamina * difficultyMultiplier * archetypeModifier
      ),
      timeMilliseconds: Math.floor(
        baseCost.timeMilliseconds * difficultyMultiplier
      ),
    };
  }
 
  /**
   * Get optimal stance recommendation
   */
  getOptimalStance(player: PlayerState, opponent?: PlayerState): TrigramStance {
    if (opponent) {
      // Get counter stance against opponent
      return TrigramCalculator.getCounterStance(opponent.currentStance);
    }
 
    // Default to archetype preferred stance
    const archetypeData = PLAYER_ARCHETYPES_DATA[player.archetype];
    const favoredStances = archetypeData.favoredStances || [];
 
    return favoredStances.length > 0 ? favoredStances[0] : TrigramStance.GEON; // Fix: Use enum value
  }
 
  /**
   * Get all valid transitions from current stance
   */
  getValidTransitions(player: PlayerState): TrigramStance[] {
    return Object.values(TrigramStance).filter(
      (
        stance // Fix: Use enum values
      ) => this.canChangeStance(player, stance)
    );
  }
}