添加TextScore函数后Pygame游戏卡顿,求问题原因
TextScore() Let's cut to the chase—your TextScore() function is the main culprit here, and it has nothing to do with memory bottlenecks. Here's the breakdown:
The Core Problem: Reinitializing Fonts Every Frame
Take a close look at your TextScore function:
def TextScore(game): text = pygame.font.SysFont(None, 30) text2 = text.render("Your Score is: " + str(game), True, (37, 97, 188)) screen.blit(text2, (10, 45))
You’re creating a brand new pygame.font.SysFont instance every single frame (which runs 60+ times per second). Font initialization is a surprisingly expensive operation—Pygame has to load and process font data each time, and that repeated overhead adds up quickly to cause the slowdown you’re seeing.
Fix 1: Initialize the Font Once, Reuse It
Move the font creation to the top of your code, outside any functions or the main loop. Then reuse that pre-initialized font object in TextScore:
# Initialize your score font ONCE at the start of the program score_font = pygame.font.SysFont(None, 30) def TextScore(game): text2 = score_font.render(f"Your Score is: {game}", True, (37, 97, 188)) screen.blit(text2, (10, 45))
This way, you only pay the font initialization cost once, not hundreds of times per second—you’ll notice an immediate speedup.
Bonus: Fix Other Minor Performance/Glitch Issues
While we’re troubleshooting, let’s fix a couple other things that could cause problems down the line:
Stop Modifying Lists Mid-Iteration
In your bullet cleanup and collision code, you’re usingbullets.remove(bullet)while looping through thebulletslist. This can cause skipped elements or errors because you’re changing the list size during iteration. Instead, create new lists for active bullets:# Clean up off-screen bullets bullets = [bullet for bullet in bullets if bullet[1] >= 0] # Collision detection (replace your existing loop) active_bullets = [] for bullet in bullets: collision = iscollision(enemyX, enemyY, bullet[0], bullet[1]) if collision: score += 1 print(score) enemyX = random.randint(0, 476) enemyY = random.randint(0, 30) else: active_bullets.append(bullet) bullets = active_bulletsUse F-Strings for Cleaner, Slightly Faster String Handling
Swapping string concatenation for an f-string makes the code cleaner and marginally more efficient:text2 = score_font.render(f"Your Score is: {game}", True, (37, 97, 188))
Final Thought
Your 50% memory usage doesn’t rule out per-frame performance hits—operations that are cheap once become crippling when repeated hundreds of times per second. Fixing the font initialization alone should get your game running smoothly again.
内容的提问来源于stack exchange,提问作者Dudeness

