Pygame英雄死亡场景字体不显示问题排查求助
Hey there! Let's break down why your "GAME OVER" text isn't appearing when your hero's life hits 0 or below. Looking at your code snippet, here are the most common culprits and how to fix them:
1. Font Initialization Issues
First, double-check that font_end is properly set up before you try to render text. If you skip this step or use an invalid font path, font_end.render() will fail silently (or throw an error you might miss).
Make sure you have something like this in your game setup code:
# Use a system font (like Arial) font_end = pygame.font.SysFont("Arial", 48) # OR use a custom font file (replace with your actual path) font_end = pygame.font.Font("fonts/your-font.ttf", 48)
If font_end is None (because the font wasn't found), the render call won't create a valid text surface—so nothing gets drawn to the screen.
2. Drawing Order & Overlapping Elements
Your current code draws the background, then the text—but if later in your main loop you re-draw the background or other elements (like the hero's grave image) over the text, it'll get completely covered up.
For example, if your main loop looks like this:
while running: # ... event handling ... if hero.life <= 0: # Your game over code here # Then you re-draw the background and hero fenetre.blit(fond_jeu, (0,0)) fenetre.blit(hero.image, hero.rect) pygame.display.flip()
The background you draw after the game over block will erase the text you just rendered. Fix this by restructuring your drawing logic to handle game over as a separate state:
while running: # ... event handling ... if hero.life <= 0: hero.image = pygame.image.load("images/grave2.png").convert_alpha() hero.alive = 0 # Draw in the correct order: background → text → hero (so text stays visible) fenetre.blit(fond_jeu, (0,0)) text_end = font_end.render("GAME OVER", True, (255,255,255)) fenetre.blit(text_end, (30, 30)) fenetre.blit(hero.image, hero.rect) pygame.display.flip() # Optional: Pause the loop or wait for player input here else: # Normal game drawing fenetre.blit(fond_jeu, (0,0)) fenetre.blit(hero.image, hero.rect) # ... other game elements ... pygame.display.flip()
3. Forgetting to Refresh the Display
If you don't call pygame.display.flip() or pygame.display.update() after blitting the text, the changes won't show up on the screen. Your code snippet doesn't include this step—make sure to add it right after drawing the text to force the screen to update.
4. Verify the Condition is Actually Triggered
It's possible the hero.life <= 0 condition isn't being met at all. Add a quick print statement inside the block to confirm:
if hero.life <= 0: print("Game over condition triggered!") # Check if this appears in your console # Rest of your code...
If you don't see this message, you'll need to debug how hero.life is being updated—maybe it's not being decremented correctly when the hero takes damage.
内容的提问来源于stack exchange,提问作者Shuiza

