Improve sound playing code to check for specific level pack sounds.
This commit is contained in:
		| @@ -5,6 +5,7 @@ import json | |||||||
| import os | import os | ||||||
| import pygame | import pygame | ||||||
| from libstormgames import * | from libstormgames import * | ||||||
|  | from src.pack_sound_system import PackSoundSystem | ||||||
| from src.level import Level | from src.level import Level | ||||||
| from src.object import Object | from src.object import Object | ||||||
| from src.player import Player | from src.player import Player | ||||||
| @@ -17,6 +18,7 @@ class WickedQuest: | |||||||
|     def __init__(self): |     def __init__(self): | ||||||
|         """Initialize game and load sounds.""" |         """Initialize game and load sounds.""" | ||||||
|         self.sounds = initialize_gui("Wicked Quest") |         self.sounds = initialize_gui("Wicked Quest") | ||||||
|  |         self.soundSystem = None  # Will be created when game is selected | ||||||
|         self.currentLevel = None |         self.currentLevel = None | ||||||
|         self.gameStartTime = None |         self.gameStartTime = None | ||||||
|         self.lastThrowTime = 0 |         self.lastThrowTime = 0 | ||||||
| @@ -32,6 +34,20 @@ class WickedQuest: | |||||||
|         self.survivalWave = 1 |         self.survivalWave = 1 | ||||||
|         self.survivalScore = 0 |         self.survivalScore = 0 | ||||||
|  |  | ||||||
|  |     def initialize_pack_sounds(self): | ||||||
|  |         """Initialize pack-specific sound system after game selection.""" | ||||||
|  |         if self.currentGame: | ||||||
|  |             self.soundSystem = PackSoundSystem(self.sounds, "sounds/", levelPackName=self.currentGame) | ||||||
|  |         else: | ||||||
|  |             self.soundSystem = PackSoundSystem(self.sounds, "sounds/") | ||||||
|  |      | ||||||
|  |     def get_sounds(self): | ||||||
|  |         """Get the current sound system (pack-specific if available, otherwise original).""" | ||||||
|  |         if self.soundSystem is None and self.currentGame is not None: | ||||||
|  |             # Initialize pack sounds if not done yet | ||||||
|  |             self.initialize_pack_sounds() | ||||||
|  |         return self.soundSystem if self.soundSystem else self.sounds | ||||||
|  |  | ||||||
|     def load_level(self, levelNumber): |     def load_level(self, levelNumber): | ||||||
|         """Load a level from its JSON file.""" |         """Load a level from its JSON file.""" | ||||||
|         levelFile = get_level_path(self.currentGame, levelNumber) |         levelFile = get_level_path(self.currentGame, levelNumber) | ||||||
| @@ -43,7 +59,7 @@ class WickedQuest: | |||||||
|             if self.player is None: |             if self.player is None: | ||||||
|                 self.player = Player(levelData["player_start"]["x"],  |                 self.player = Player(levelData["player_start"]["x"],  | ||||||
|                                    levelData["player_start"]["y"],  |                                    levelData["player_start"]["y"],  | ||||||
|                                    self.sounds) |                                    self.get_sounds()) | ||||||
|             else: |             else: | ||||||
|                 # Reset player for new level. |                 # Reset player for new level. | ||||||
|                 self.player.isDucking = False |                 self.player.isDucking = False | ||||||
| @@ -63,7 +79,7 @@ class WickedQuest: | |||||||
|  |  | ||||||
|             # Pass existing player to new level |             # Pass existing player to new level | ||||||
|             pygame.event.clear() |             pygame.event.clear() | ||||||
|             self.currentLevel = Level(levelData, self.sounds, self.player) |             self.currentLevel = Level(levelData, self.get_sounds(), self.player) | ||||||
|  |  | ||||||
|             return True |             return True | ||||||
|         except FileNotFoundError: |         except FileNotFoundError: | ||||||
| @@ -109,7 +125,7 @@ class WickedQuest: | |||||||
|         options.append("Cancel") |         options.append("Cancel") | ||||||
|          |          | ||||||
|         # Use instruction_menu for consistent behavior |         # Use instruction_menu for consistent behavior | ||||||
|         choice = instruction_menu(self.sounds, "Select a save file to load:", *options) |         choice = instruction_menu(self.get_sounds(), "Select a save file to load:", *options) | ||||||
|          |          | ||||||
|         if choice == "Cancel" or choice is None: |         if choice == "Cancel" or choice is None: | ||||||
|             return None |             return None | ||||||
| @@ -140,8 +156,8 @@ class WickedQuest: | |||||||
|              |              | ||||||
|             if success: |             if success: | ||||||
|                 try: |                 try: | ||||||
|                     if 'save' in self.sounds: |                     if 'save' in self.get_sounds(): | ||||||
|                         play_sound(self.sounds['save']) |                         play_sound(self.get_sounds()['save']) | ||||||
|                     else: |                     else: | ||||||
|                         print("Save sound not found in sounds dictionary") |                         print("Save sound not found in sounds dictionary") | ||||||
|                 except Exception as e: |                 except Exception as e: | ||||||
| @@ -199,7 +215,7 @@ class WickedQuest: | |||||||
|         if movementDistance > 0 and not player.isJumping: |         if movementDistance > 0 and not player.isJumping: | ||||||
|             player.distanceSinceLastStep += movementDistance |             player.distanceSinceLastStep += movementDistance | ||||||
|             if player.should_play_footstep(currentTime): |             if player.should_play_footstep(currentTime): | ||||||
|                 play_sound(self.sounds[player.footstepSound]) |                 play_sound(self.get_sounds()[player.footstepSound]) | ||||||
|                 player.distanceSinceLastStep = 0 |                 player.distanceSinceLastStep = 0 | ||||||
|                 player.lastStepTime = currentTime |                 player.lastStepTime = currentTime | ||||||
|  |  | ||||||
| @@ -241,19 +257,19 @@ class WickedQuest: | |||||||
|  |  | ||||||
|         # Handle attack with either CTRL key |         # Handle attack with either CTRL key | ||||||
|         if (keys[pygame.K_LCTRL] or keys[pygame.K_RCTRL]) and player.start_attack(currentTime): |         if (keys[pygame.K_LCTRL] or keys[pygame.K_RCTRL]) and player.start_attack(currentTime): | ||||||
|             play_sound(self.sounds[player.currentWeapon.attackSound]) |             play_sound(self.get_sounds()[player.currentWeapon.attackSound]) | ||||||
|  |  | ||||||
|         # Handle jumping |         # Handle jumping | ||||||
|         if (keys[pygame.K_w] or keys[pygame.K_UP]) and not player.isJumping: |         if (keys[pygame.K_w] or keys[pygame.K_UP]) and not player.isJumping: | ||||||
|             player.isJumping = True |             player.isJumping = True | ||||||
|             player.jumpStartTime = currentTime |             player.jumpStartTime = currentTime | ||||||
|             play_sound(self.sounds['jump']) |             play_sound(self.get_sounds()['jump']) | ||||||
|  |  | ||||||
|         # Handle instant landing with broom (press down while jumping) |         # Handle instant landing with broom (press down while jumping) | ||||||
|         if (player.isJumping and (keys[pygame.K_s] or keys[pygame.K_DOWN]) and  |         if (player.isJumping and (keys[pygame.K_s] or keys[pygame.K_DOWN]) and  | ||||||
|             player.currentWeapon and player.currentWeapon.name == "witch_broom"): |             player.currentWeapon and player.currentWeapon.name == "witch_broom"): | ||||||
|             player.isJumping = False |             player.isJumping = False | ||||||
|             play_sound(self.sounds[player.footstepSound])  # Landing sound |             play_sound(self.get_sounds()[player.footstepSound])  # Landing sound | ||||||
|             # Reset step distance tracking after landing |             # Reset step distance tracking after landing | ||||||
|             player.distanceSinceLastStep = 0 |             player.distanceSinceLastStep = 0 | ||||||
|             player.lastStepTime = currentTime |             player.lastStepTime = currentTime | ||||||
| @@ -263,7 +279,7 @@ class WickedQuest: | |||||||
|         # Check if jump should end naturally |         # Check if jump should end naturally | ||||||
|         if player.isJumping and currentTime - player.jumpStartTime >= player.get_current_jump_duration(): |         if player.isJumping and currentTime - player.jumpStartTime >= player.get_current_jump_duration(): | ||||||
|             player.isJumping = False |             player.isJumping = False | ||||||
|             play_sound(self.sounds[player.footstepSound])  # Landing sound |             play_sound(self.get_sounds()[player.footstepSound])  # Landing sound | ||||||
|             # Reset step distance tracking after landing |             # Reset step distance tracking after landing | ||||||
|             player.distanceSinceLastStep = 0 |             player.distanceSinceLastStep = 0 | ||||||
|             player.lastStepTime = currentTime |             player.lastStepTime = currentTime | ||||||
| @@ -290,7 +306,7 @@ class WickedQuest: | |||||||
|         try: |         try: | ||||||
|             speak(f"Level {self.currentLevel.levelId}, {self.currentLevel.levelName}, complete!") |             speak(f"Level {self.currentLevel.levelId}, {self.currentLevel.levelName}, complete!") | ||||||
|             pygame.mixer.music.stop() |             pygame.mixer.music.stop() | ||||||
|             cut_scene(self.sounds, '_finish_level') |             cut_scene(self.get_sounds(), '_finish_level') | ||||||
|         except: |         except: | ||||||
|             pass |             pass | ||||||
|  |  | ||||||
| @@ -316,7 +332,7 @@ class WickedQuest: | |||||||
|             pygame.event.clear() |             pygame.event.clear() | ||||||
|             self.player.scoreboard.add_high_score() |             self.player.scoreboard.add_high_score() | ||||||
|  |  | ||||||
|         cut_scene(self.sounds, "game_over") |         cut_scene(self.get_sounds(), "game_over") | ||||||
|         display_text(report) |         display_text(report) | ||||||
|  |  | ||||||
|     def display_survival_stats(self, timeTaken): |     def display_survival_stats(self, timeTaken): | ||||||
| @@ -430,8 +446,8 @@ class WickedQuest: | |||||||
|                         for ext in ['.wav', '.ogg', '.mp3']: |                         for ext in ['.wav', '.ogg', '.mp3']: | ||||||
|                             endFile = os.path.join(gamePath, f'end{ext}') |                             endFile = os.path.join(gamePath, f'end{ext}') | ||||||
|                             if os.path.exists(endFile): |                             if os.path.exists(endFile): | ||||||
|                                 self.sounds['end_scene'] = pygame.mixer.Sound(endFile) |                                 self.get_sounds()['end_scene'] = pygame.mixer.Sound(endFile) | ||||||
|                                 cut_scene(self.sounds, 'end_scene') |                                 cut_scene(self.get_sounds(), 'end_scene') | ||||||
|                                 break |                                 break | ||||||
|                         else: |                         else: | ||||||
|                             messagebox("Congratulations! You've completed all available levels!") |                             messagebox("Congratulations! You've completed all available levels!") | ||||||
| @@ -455,7 +471,7 @@ class WickedQuest: | |||||||
|             if self.saveManager.has_saves(): |             if self.saveManager.has_saves(): | ||||||
|                 custom_options.append("load_game") |                 custom_options.append("load_game") | ||||||
|              |              | ||||||
|             choice = game_menu(self.sounds, None, *custom_options) |             choice = game_menu(self.get_sounds(), None, *custom_options) | ||||||
|  |  | ||||||
|             if choice == "exit": |             if choice == "exit": | ||||||
|                 exit_game() |                 exit_game() | ||||||
| @@ -468,6 +484,8 @@ class WickedQuest: | |||||||
|                         self.currentGame = save_data['game_state']['currentGame'] |                         self.currentGame = save_data['game_state']['currentGame'] | ||||||
|                         self.gameStartTime = save_data['game_state']['gameStartTime'] |                         self.gameStartTime = save_data['game_state']['gameStartTime'] | ||||||
|                         current_level = save_data['game_state']['currentLevel'] |                         current_level = save_data['game_state']['currentLevel'] | ||||||
|  |                         # Initialize pack-specific sound system | ||||||
|  |                         self.initialize_pack_sounds() | ||||||
|                          |                          | ||||||
|                         # Load the level |                         # Load the level | ||||||
|                         if self.load_level(current_level): |                         if self.load_level(current_level): | ||||||
| @@ -479,9 +497,11 @@ class WickedQuest: | |||||||
|                     else: |                     else: | ||||||
|                         messagebox(f"Failed to load save: {save_data}") |                         messagebox(f"Failed to load save: {save_data}") | ||||||
|             elif choice == "play": |             elif choice == "play": | ||||||
|                 self.currentGame = select_game(self.sounds) |                 self.currentGame = select_game(self.get_sounds()) | ||||||
|                 if self.currentGame is None: |                 if self.currentGame is None: | ||||||
|                     continue  # User cancelled game selection, return to main menu |                     continue  # User cancelled game selection, return to main menu | ||||||
|  |                 # Initialize pack-specific sound system | ||||||
|  |                 self.initialize_pack_sounds() | ||||||
|                 # Validate level files before starting |                 # Validate level files before starting | ||||||
|                 errors = self.validate_levels() |                 errors = self.validate_levels() | ||||||
|                 if errors: |                 if errors: | ||||||
| @@ -492,7 +512,7 @@ class WickedQuest: | |||||||
|                     continue |                     continue | ||||||
|                 if self.currentGame: |                 if self.currentGame: | ||||||
|                     # Ask player to choose game mode |                     # Ask player to choose game mode | ||||||
|                     mode_choice = game_mode_menu(self.sounds) |                     mode_choice = game_mode_menu(self.get_sounds()) | ||||||
|                     if mode_choice == "story": |                     if mode_choice == "story": | ||||||
|                         self.player = None  # Reset player for new game |                         self.player = None  # Reset player for new game | ||||||
|                         self.gameStartTime = pygame.time.get_ticks() |                         self.gameStartTime = pygame.time.get_ticks() | ||||||
| @@ -511,14 +531,14 @@ class WickedQuest: | |||||||
|                 pygame.event.clear() |                 pygame.event.clear() | ||||||
|                 display_text(lines) |                 display_text(lines) | ||||||
|             elif choice == "learn_sounds": |             elif choice == "learn_sounds": | ||||||
|                 choice = learn_sounds(self.sounds) |                 choice = learn_sounds(self.get_sounds()) | ||||||
|  |  | ||||||
|     def start_survival_mode(self): |     def start_survival_mode(self): | ||||||
|         """Initialize and start survival mode.""" |         """Initialize and start survival mode.""" | ||||||
|         self.survivalGenerator = SurvivalGenerator(self.currentGame) |         self.survivalGenerator = SurvivalGenerator(self.currentGame) | ||||||
|         self.survivalWave = 1 |         self.survivalWave = 1 | ||||||
|         self.survivalScore = 0 |         self.survivalScore = 0 | ||||||
|         self.player = Player(0, 0, self.sounds) |         self.player = Player(0, 0, self.get_sounds()) | ||||||
|         self.gameStartTime = pygame.time.get_ticks() |         self.gameStartTime = pygame.time.get_ticks() | ||||||
|          |          | ||||||
|         # Show intro message before level starts |         # Show intro message before level starts | ||||||
| @@ -526,7 +546,7 @@ class WickedQuest: | |||||||
|          |          | ||||||
|         # Generate first survival segment |         # Generate first survival segment | ||||||
|         levelData = self.survivalGenerator.generate_survival_level(self.survivalWave, 300) |         levelData = self.survivalGenerator.generate_survival_level(self.survivalWave, 300) | ||||||
|         self.currentLevel = Level(levelData, self.sounds, self.player) |         self.currentLevel = Level(levelData, self.get_sounds(), self.player) | ||||||
|          |          | ||||||
|         self.survival_loop() |         self.survival_loop() | ||||||
|      |      | ||||||
| @@ -592,7 +612,7 @@ class WickedQuest: | |||||||
|                 # Check lock system - only advance if no active enemies remain |                 # Check lock system - only advance if no active enemies remain | ||||||
|                 if self.currentLevel.isLocked and any(enemy.isActive for enemy in self.currentLevel.enemies): |                 if self.currentLevel.isLocked and any(enemy.isActive for enemy in self.currentLevel.enemies): | ||||||
|                     speak("You must defeat all enemies before proceeding to the next wave!") |                     speak("You must defeat all enemies before proceeding to the next wave!") | ||||||
|                     play_sound(self.sounds['locked']) |                     play_sound(self.get_sounds()['locked']) | ||||||
|                     # Push player back a bit |                     # Push player back a bit | ||||||
|                     self.player.xPos -= 5 |                     self.player.xPos -= 5 | ||||||
|                 else: |                 else: | ||||||
| @@ -640,7 +660,7 @@ class WickedQuest: | |||||||
|         self.player.xPos = playerX |         self.player.xPos = playerX | ||||||
|          |          | ||||||
|         # Create new level |         # Create new level | ||||||
|         self.currentLevel = Level(levelData, self.sounds, self.player) |         self.currentLevel = Level(levelData, self.get_sounds(), self.player) | ||||||
|  |  | ||||||
|  |  | ||||||
| def game_mode_menu(sounds): | def game_mode_menu(sounds): | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user