All files / components/combat/hooks useCombatAudio.ts

88.97% Statements 113/127
82.5% Branches 33/40
100% Functions 17/17
88.97% Lines 113/127

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                                2x           2x 98x 98x 98x 98x     98x 49x 49x 49x                   98x 18x 18x     18x 1x       17x       17x               98x 16x 16x 1x 1x   16x                 98x 16x 16x             98x 9x   9x 1x         8x     5x 5x     1x 1x   1x 1x     1x 1x           8x 8x 7x 7x   1x               98x 4x   4x             4x   1x 3x   1x 2x   1x     1x     4x 4x 4x 4x                   98x 2x   2x           2x   1x     1x     2x 2x 2x 2x                 98x 1x   1x         1x   1x 1x 1x 1x                 98x 1x   1x         1x   1x 1x 1x 1x                 98x 1x   1x         1x   1x 1x 1x 1x                   98x 30x 30x   28x                 98x       29x               29x   29x 1x 1x 1x     28x 28x   27x   27x               98x 1x 1x                   98x 3x     98x                              
/**
 * Combat Audio Hook for Black Trigram
 * Provides comprehensive audio feedback for combat actions
 */
 
import { useAudio } from "../../../audio/AudioProvider";
import { useCallback, useRef, useEffect } from "react";
 
/**
 * Attack intensity levels for sound selection
 */
export type AttackIntensity = "light" | "medium" | "heavy" | "critical";
 
/**
 * Maximum number of simultaneous sounds to prevent audio chaos
 */
const MAX_SIMULTANEOUS_SOUNDS = 5;
 
/**
 * Combat audio hook for playing attack, hit, block, dodge, and stance sounds
 * @returns Object with methods for playing various combat sounds
 */
export const useCombatAudio = () => {
  const audio = useAudio();
  const lastPlayTime = useRef<Record<string, number>>({});
  const activeSounds = useRef(new Set<string>());
  const timeoutIds = useRef<Set<NodeJS.Timeout>>(new Set());
 
  // Cleanup all timeouts on unmount
  useEffect(() => {
    return () => {
      timeoutIds.current.forEach(clearTimeout);
      timeoutIds.current.clear();
    };
  }, []);
 
  /**
   * Check if we can play a sound (rate limiting and simultaneous sound check)
   * @param soundType - Type of sound to check
   * @param minInterval - Minimum interval between plays in milliseconds
   * @returns True if sound can be played
   */
  const canPlaySound = useCallback((soundType: string, minInterval = 50): boolean => {
    const now = Date.now();
    const lastTime = lastPlayTime.current[soundType] || 0;
    
    // Rate limiting check
    if (now - lastTime < minInterval) {
      return false;
    }
 
    // Check simultaneous sounds limit
    Iif (activeSounds.current.size >= MAX_SIMULTANEOUS_SOUNDS) {
      return false;
    }
 
    return true;
  }, []);
 
  /**
   * Register a sound as active and auto-remove after duration
   * @param soundId - ID of the sound to register
   * @param duration - Duration in milliseconds (default 500ms)
   */
  const registerActiveSound = useCallback((soundId: string, duration = 500) => {
    activeSounds.current.add(soundId);
    const timeoutId = setTimeout(() => {
      activeSounds.current.delete(soundId);
      timeoutIds.current.delete(timeoutId);
    }, duration);
    timeoutIds.current.add(timeoutId);
  }, []);
 
  /**
   * Get a random variant from a pool
   * @param base - Base sound ID
   * @param count - Number of variants
   * @returns Random variant ID
   */
  const getRandomVariant = useCallback((base: string, count: number): string => {
    const variant = Math.floor(Math.random() * count) + 1;
    return `${base}_${variant}`;
  }, []);
 
  /**
   * Play attack sound based on intensity
   * @param intensity - Attack intensity (light, medium, heavy, critical)
   */
  const playAttackSound = useCallback(async (intensity: AttackIntensity = "light") => {
    const soundType = `attack_${intensity}`;
    
    if (!canPlaySound(soundType)) {
      return;
    }
 
    let soundId: string;
 
    switch (intensity) {
      case "light":
        // 8 variations of light punch sounds
        soundId = getRandomVariant("attack_punch_light", 8);
        break;
      case "medium":
        // 4 variations of medium punch sounds
        soundId = getRandomVariant("attack_punch_medium", 4);
        break;
      case "heavy":
        soundId = "attack_heavy";
        break;
      case "critical":
        // 4 variations of critical attack sounds
        soundId = getRandomVariant("attack_critical", 4);
        break;
      default:
        console.warn(`Unknown attack intensity: ${intensity}, defaulting to light`);
        soundId = getRandomVariant("attack_punch_light", 8);
    }
 
    try {
      await audio.playSFX(soundId);
      lastPlayTime.current[soundType] = Date.now();
      registerActiveSound(soundId, 400);
    } catch (error) {
      console.warn(`Failed to play attack sound: ${soundId}`, error);
    }
  }, [audio, canPlaySound, getRandomVariant, registerActiveSound]);
 
  /**
   * Play hit reaction sound based on damage amount
   * @param damage - Damage amount to determine hit intensity
   */
  const playHitSound = useCallback(async (damage: number) => {
    const soundType = "hit";
    
    Iif (!canPlaySound(soundType, 100)) {
      return;
    }
 
    let soundId: string;
 
    // Determine hit intensity based on damage
    if (damage >= 40) {
      // Critical hit (4 variations)
      soundId = getRandomVariant("hit_critical", 4);
    } else if (damage >= 25) {
      // Heavy hit (4 variations)
      soundId = getRandomVariant("hit_heavy", 4);
    } else if (damage >= 10) {
      // Medium hit (4 variations)
      soundId = getRandomVariant("hit_medium", 4);
    } else {
      // Light hit (4 variations)
      soundId = getRandomVariant("hit_light", 4);
    }
 
    try {
      await audio.playSFX(soundId);
      lastPlayTime.current[soundType] = Date.now();
      registerActiveSound(soundId, 500);
    } catch (error) {
      console.warn(`Failed to play hit sound: ${soundId}`, error);
    }
  }, [audio, canPlaySound, getRandomVariant, registerActiveSound]);
 
  /**
   * Play block/parry sound
   * @param guardBroken - Whether the guard was broken or successfully blocked
   */
  const playBlockSound = useCallback(async (guardBroken: boolean = false) => {
    const soundType = "block";
    
    Iif (!canPlaySound(soundType, 150)) {
      return;
    }
 
    let soundId: string;
 
    if (guardBroken) {
      // 4 variations of guard break sounds
      soundId = getRandomVariant("block_break", 4);
    } else {
      // 4 variations of successful block sounds
      soundId = getRandomVariant("block_success", 4);
    }
 
    try {
      await audio.playSFX(soundId);
      lastPlayTime.current[soundType] = Date.now();
      registerActiveSound(soundId, 400);
    } catch (error) {
      console.warn(`Failed to play block sound: ${soundId}`, error);
    }
  }, [audio, canPlaySound, getRandomVariant, registerActiveSound]);
 
  /**
   * Play dodge sound
   */
  const playDodgeSound = useCallback(async () => {
    const soundType = "dodge";
    
    Iif (!canPlaySound(soundType, 200)) {
      return;
    }
 
    // 8 variations of dodge sounds
    const soundId = getRandomVariant("dodge", 8);
 
    try {
      await audio.playSFX(soundId);
      lastPlayTime.current[soundType] = Date.now();
      registerActiveSound(soundId, 300);
    } catch (error) {
      console.warn(`Failed to play dodge sound: ${soundId}`, error);
    }
  }, [audio, canPlaySound, getRandomVariant, registerActiveSound]);
 
  /**
   * Play stance change sound
   */
  const playStanceChangeSound = useCallback(async () => {
    const soundType = "stance";
    
    Iif (!canPlaySound(soundType, 250)) {
      return;
    }
 
    // 4 variations of stance change sounds
    const soundId = getRandomVariant("stance_change", 4);
 
    try {
      await audio.playSFX(soundId);
      lastPlayTime.current[soundType] = Date.now();
      registerActiveSound(soundId, 400);
    } catch (error) {
      console.warn(`Failed to play stance change sound: ${soundId}`, error);
    }
  }, [audio, canPlaySound, getRandomVariant, registerActiveSound]);
 
  /**
   * Play special technique sound (e.g., Geon special)
   */
  const playSpecialTechniqueSound = useCallback(async () => {
    const soundType = "special";
    
    Iif (!canPlaySound(soundType, 300)) {
      return;
    }
 
    // 4 variations of special Geon technique sounds
    const soundId = getRandomVariant("attack_special_geon", 4);
 
    try {
      await audio.playSFX(soundId, 0.8);
      lastPlayTime.current[soundType] = Date.now();
      registerActiveSound(soundId, 600);
    } catch (error) {
      console.warn(`Failed to play special technique sound: ${soundId}`, error);
    }
  }, [audio, canPlaySound, getRandomVariant, registerActiveSound]);
 
  /**
   * Play combat theme music with fade-in
   * @param fadeInDuration - Fade-in duration in milliseconds
   */
  const playCombatMusic = useCallback(async (fadeInDuration: number = 2000) => {
    try {
      await audio.fadeIn("combat_theme", fadeInDuration);
    } catch (error) {
      console.warn("Failed to play combat music", error);
    }
  }, [audio]);
 
  /**
   * Play archetype-specific music theme
   * @param archetype - Player archetype (musa, amsalja, hacker, jeongbo_yowon, jojik_pokryeokbae)
   * @param fadeInDuration - Fade-in duration in milliseconds
   */
  const playArchetypeMusic = useCallback(async (
    archetype: string,
    fadeInDuration: number = 2000
  ) => {
    const archetypeMap: Record<string, string> = {
      musa: "musa_warrior_theme",
      amsalja: "amsalja_shadow_theme",
      hacker: "hacker_cyber_theme",
      jeongbo_yowon: "jeongbo_intel_theme",
      jojik_pokryeokbae: "jojik_street_theme",
    };
 
    const musicId = archetypeMap[archetype.toLowerCase()];
    
    if (!musicId) {
      console.warn(`Unknown archetype: ${archetype}, using combat theme`);
      await playCombatMusic(fadeInDuration);
      return;
    }
 
    try {
      await audio.fadeIn(musicId, fadeInDuration);
    } catch (error) {
      console.warn(`Failed to play archetype music: ${musicId}`, error);
      // Fallback to combat theme
      await playCombatMusic(fadeInDuration);
    }
  }, [audio, playCombatMusic]);
 
  /**
   * Stop combat music with fade-out
   * @param fadeOutDuration - Fade-out duration in milliseconds
   */
  const stopCombatMusic = useCallback(async (fadeOutDuration: number = 2000) => {
    try {
      await audio.fadeOut(fadeOutDuration);
    } catch (error) {
      console.warn("Failed to stop combat music", error);
    }
  }, [audio]);
 
  /**
   * Get number of currently active sounds
   * @returns Number of active sounds
   */
  const getActiveSoundCount = useCallback((): number => {
    return activeSounds.current.size;
  }, []);
 
  return {
    playAttackSound,
    playHitSound,
    playBlockSound,
    playDodgeSound,
    playStanceChangeSound,
    playSpecialTechniqueSound,
    playCombatMusic,
    playArchetypeMusic,
    stopCombatMusic,
    getActiveSoundCount,
  };
};
 
export default useCombatAudio;