All files / blacktrigram/src/systems/combat TrainingCombatSystem.ts

82.47% Statements 193/234
66.66% Branches 16/24
81.25% Functions 13/16
82.47% Lines 193/234

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 3381x 1x                 1x 1x 2x 2x 2x   1x 2x 2x 2x         1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x         1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x     1x 1x 1x   1x 1x       1x 1x 1x     1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x     1x   1x 1x         1x 1x 1x 1x 1x     1x 1x   1x 1x   1x 1x         1x 1x 1x 1x 1x     1x 1x         1x 1x 1x 1x 1x 1x   1x 1x 1x 1x     1x 1x 1x     1x 2x 2x 1x 2x   2x 1x 2x   2x 1x   1x 1x   1x         1x   1x 1x 1x 1x 1x   1x   1x 1x 1x         1x 1x   1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x         1x                                                 1x                                         1x 1x 1x 1x 1x 1x         1x             1x 1x 1x         1x 1x 1x 1x   1x 1x 1x 1x   1x  
import { PlayerArchetype, TrigramStance } from "../../types/common";
import { CombatSystem } from "../CombatSystem";
import { PlayerState } from "../player";
import { KoreanTechnique } from "../vitalpoint";
import { TrainingCombatResult } from "./types";
 
/**
 * Training-specific combat system for Korean martial arts practice
 * Focuses on technique accuracy, form analysis, and educational feedback
 */
export class TrainingCombatSystem extends CombatSystem {
  private trainingDummy: PlayerState;
  private accuracyHistory: number[] = [];
  private techniqueAttempts: number = 0;
  private successfulTechniques: number = 0;
 
  constructor() {
    super();
    this.trainingDummy = this.createTrainingDummy();
  }
 
  /**
   * Create a training dummy with infinite health for practice
   */
  private createTrainingDummy(): PlayerState {
    return {
      id: "training_dummy",
      name: { korean: "훈련 더미", english: "Training Dummy" },
      archetype: PlayerArchetype.MUSA,
      health: 1000,
      maxHealth: 1000,
      ki: 1000,
      maxKi: 1000,
      stamina: 1000,
      maxStamina: 1000,
      energy: 1000,
      maxEnergy: 1000,
      attackPower: 50,
      defense: 100,
      speed: 30,
      technique: 50,
      pain: 0,
      consciousness: 100,
      balance: 100,
      momentum: 0,
      currentStance: TrigramStance.GAN, // Mountain stance - defensive
      combatState: "idle" as any,
      position: { x: 600, y: 400 },
      isBlocking: false,
      isStunned: false,
      isCountering: false,
      lastActionTime: 0,
      recoveryTime: 0,
      lastStanceChangeTime: 0,
      statusEffects: [],
      activeEffects: [],
      vitalPoints: [],
      totalDamageReceived: 0,
      totalDamageDealt: 0,
      hitsTaken: 0,
      hitsLanded: 0,
      perfectStrikes: 0,
      vitalPointHits: 0,
    };
  }
 
  /**
   * Execute a training technique with detailed analysis
   */
  executeTrainingTechnique(
    player: PlayerState,
    technique: KoreanTechnique,
    targetedVitalPointId?: string
  ): TrainingCombatResult {
    this.techniqueAttempts++;
 
    // Base combat resolution
    const baseResult = this.resolveAttack(
      player,
      this.trainingDummy,
      technique,
      targetedVitalPointId
    );
 
    // Calculate training-specific scores
    const accuracyScore = this.calculateAccuracyScore(player, technique);
    const techniqueScore = this.calculateTechniqueScore(player, technique);
    const formScore = this.calculateFormScore(player, technique);
 
    this.accuracyHistory.push(accuracyScore);
    if (this.accuracyHistory.length > 10) {
      this.accuracyHistory.shift(); // Keep last 10 attempts
    }
 
    if (baseResult.hit) {
      this.successfulTechniques++;
    }
 
    // Generate improvement feedback
    const improvementAreas = this.generateImprovementAreas(
      accuracyScore,
      techniqueScore,
      formScore
    );
 
    const nextTrainingGoals = this.generateTrainingGoals(
      player,
      technique,
      accuracyScore
    );
 
    return {
      ...baseResult,
      accuracyScore,
      techniqueScore,
      formScore,
      improvementAreas,
      nextTrainingGoals,
    };
  }
 
  /**
   * Calculate accuracy score based on stance, timing, and targeting
   */
  private calculateAccuracyScore(
    player: PlayerState,
    _technique: KoreanTechnique
  ): number {
    let score = 0.5; // Base score
 
    // Player technique skill
    score += (player.technique / 100) * 0.2;
 
    return Math.min(1.0, Math.max(0.0, score));
  }
 
  /**
   * Calculate technique execution score
   */
  private calculateTechniqueScore(
    player: PlayerState,
    _technique: KoreanTechnique
  ): number {
    let score = 0.6; // Base execution
 
    // Ki and stamina availability
    const kiRatio = player.ki / player.maxKi;
    const staminaRatio = player.stamina / player.maxStamina;
 
    score += kiRatio * 0.2;
    score += staminaRatio * 0.2;
 
    return Math.min(1.0, Math.max(0.0, score));
  }
 
  /**
   * Calculate form score based on balance and positioning
   */
  private calculateFormScore(
    _player: PlayerState,
    _technique: KoreanTechnique
  ): number {
    let score = 0.5; // Base form
 
    // For now, return base form score
    return Math.min(1.0, Math.max(0.0, score));
  }
 
  /**
   * Generate areas for improvement based on scores
   */
  private generateImprovementAreas(
    accuracy: number,
    technique: number,
    form: number
  ): string[] {
    const areas: string[] = [];
 
    if (accuracy < 0.7) {
      areas.push("targeting_precision");
    }
    if (technique < 0.7) {
      areas.push("technique_execution");
    }
    if (form < 0.7) {
      areas.push("stance_stability");
    }
 
    // Korean translations
    const koreanAreas = areas.map((area) => {
      switch (area) {
        case "targeting_precision":
          return "타겟팅 정확도 - Targeting Precision";
        case "technique_execution":
          return "기법 실행 - Technique Execution";
        case "stance_stability":
          return "자세 안정성 - Stance Stability";
        default:
          return area;
      }
    });
 
    return koreanAreas.length > 0
      ? koreanAreas
      : ["전반적 향상 - Overall Improvement"];
  }
 
  /**
   * Generate next training goals
   */
  private generateTrainingGoals(
    // Fix: Remove unused player parameter
    _player: PlayerState,
    technique: KoreanTechnique,
    accuracy: number
  ): string[] {
    const goals: string[] = [];
 
    if (accuracy > 0.8) {
      goals.push("고급 기법 연습 - Practice Advanced Techniques");
    } else if (accuracy > 0.6) {
      goals.push("연속 기법 연습 - Practice Combo Techniques");
    } else {
      goals.push("기본 자세 연습 - Practice Basic Stances");
    }
 
    // Add stance-specific goals
    const stanceGoals = this.getStanceSpecificGoals(technique.stance);
    goals.push(...stanceGoals);
 
    return goals.slice(0, 3); // Limit to 3 goals
  }
 
  /**
   * Get stance-specific training goals
   */
  private getStanceSpecificGoals(stance: TrigramStance): string[] {
    const stanceGoals: Record<TrigramStance, string[]> = {
      [TrigramStance.GEON]: [
        "천괘 직선 공격 마스터 - Master Heaven's Direct Attacks",
      ],
      [TrigramStance.TAE]: ["태괘 유동성 향상 - Improve Lake's Fluidity"],
      [TrigramStance.LI]: ["리괘 정확성 훈련 - Train Fire's Precision"],
      [TrigramStance.JIN]: ["진괘 폭발력 개발 - Develop Thunder's Power"],
      [TrigramStance.SON]: ["손괘 연속성 연습 - Practice Wind's Continuity"],
      [TrigramStance.GAM]: ["감괘 적응력 향상 - Improve Water's Adaptability"],
      [TrigramStance.GAN]: ["간괘 방어력 강화 - Strengthen Mountain's Defense"],
      [TrigramStance.GON]: ["곤괘 제압력 훈련 - Train Earth's Control"],
    };
 
    return stanceGoals[stance] || ["기본 자세 완성 - Perfect Basic Stance"];
  }
 
  /**
   * Get training statistics
   */
  getTrainingStats() {
    const overallAccuracy =
      this.accuracyHistory.length > 0
        ? this.accuracyHistory.reduce((a, b) => a + b, 0) /
          this.accuracyHistory.length
        : 0;
 
    const successRate =
      this.techniqueAttempts > 0
        ? this.successfulTechniques / this.techniqueAttempts
        : 0;
 
    return {
      totalAttempts: this.techniqueAttempts,
      successfulTechniques: this.successfulTechniques,
      successRate,
      overallAccuracy,
      recentAccuracy: this.accuracyHistory.slice(-5),
      improvementTrend: this.calculateImprovementTrend(),
    };
  }
 
  /**
   * Calculate improvement trend from recent accuracy scores
   */
  private calculateImprovementTrend(): "improving" | "stable" | "declining" {
    if (this.accuracyHistory.length < 5) return "stable";
 
    const recent = this.accuracyHistory.slice(-3);
    const earlier = this.accuracyHistory.slice(-6, -3);
 
    if (earlier.length === 0) return "stable";
 
    const recentAvg = recent.reduce((a, b) => a + b, 0) / recent.length;
    const earlierAvg = earlier.reduce((a, b) => a + b, 0) / earlier.length;
 
    const diff = recentAvg - earlierAvg;
 
    if (diff > 0.1) return "improving";
    if (diff < -0.1) return "declining";
    return "stable";
  }
 
  /**
   * Reset training session
   */
  resetTrainingSession() {
    this.accuracyHistory = [];
    this.techniqueAttempts = 0;
    this.successfulTechniques = 0;
    this.trainingDummy = this.createTrainingDummy();
  }
 
  /**
   * Fix: Add the missing resetTrainingDummy method that tests expect
   */
  resetTrainingDummy() {
    this.trainingDummy = this.createTrainingDummy();
  }
 
  /**
   * Get training dummy for display
   */
  getTrainingDummy(): PlayerState {
    return this.trainingDummy;
  }
 
  /**
   * Update training dummy health (for visual feedback)
   */
  updateTrainingDummy(updates: Partial<PlayerState>) {
    this.trainingDummy = {
      ...this.trainingDummy,
      ...updates,
      // Always keep high health for training
      health: Math.max(this.trainingDummy.health, 900),
    };
  }
}
 
export default TrainingCombatSystem;