Pygame武器图像加载错误问题排查与修复求助
Looking at your code snippet, there are two critical typos that are almost certainly causing the wrong images to load:
1. Incorrect variable used in scaling
In the line where you scale the weapon image, you’re referencing img instead of the img_weapon variable you just loaded:
img_weapon = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale)))
Since your character loading code works correctly, img is likely holding the last character image loaded before this weapon loop runs. That’s why you’re seeing character images instead of weapons here. You should use the img_weapon variable you just loaded:
img_weapon = pygame.transform.scale(img_weapon, (int(img_weapon.get_width() * scale), int(img_weapon.get_height() * scale)))
2. Appending the wrong list to your animations
You’re building the weapon image list in weapon_temp_list, but then appending temp_list (a variable likely used in your character loading code) to self.weapons_animations_list:
self.weapons_animations_list.append(temp_list)
This means you’re actually adding character image lists to your weapon animations. Correct this to use the list you built for weapons:
self.weapons_animations_list.append(weapon_temp_list)
Corrected Code Snippet
Here’s the fixed version of your weapon loading loop:
weapon_animation_types = ["empty", "sword", "rifle"] for weapon_animation in weapon_animation_types: weapon_temp_list = [] longueur_fichier_weapon = len(os.listdir(f'img/weapons/{weapon_animation}')) for j in range(longueur_fichier_weapon): img_weapon = pygame.image.load(f'img/weapons/{weapon_animation}/{j}.png') img_weapon = pygame.transform.scale(img_weapon, (int(img_weapon.get_width() * scale), int(img_weapon.get_height() * scale))) weapon_temp_list.append(img_weapon) self.weapons_animations_list.append(weapon_temp_list) self.weapon_image = self.weapons_animations_list[self.weapon][self.weapon_frame_index]
Additional Checks
Just to be thorough, you might want to:
- Verify all temporary weapon images are correctly named (starting from
0.pngup to the total number of files in each subfolder) - Confirm the
img/weapons/directory structure matches your code (each weapon type has its own subfolder with the exact name listed inweapon_animation_types) - Ensure
self.weapons_animations_listis initialized as an empty list before this loop runs (to avoid leftover data from previous test runs)
These fixes should resolve the issue where your weapon system is loading character images instead of your temporary weapon assets.
内容的提问来源于stack exchange,提问作者Nirs123

