Pygame中分数文本无法显示的问题求助
Let's walk through the most likely reasons your score text isn't showing up, starting with the biggest red flag in your code:
1. The score is drawn entirely outside the visible screen area
Your code positions the score at (WIDTH/2 - SCORE.get_width()/2, HEIGHT + SCORE.get_height()).
Pygame's screen coordinate system starts at (0, 0) (top-left corner) and goes up to (WIDTH, HEIGHT) (bottom-right corner). By setting the y-position to HEIGHT + SCORE.get_height(), you're placing the text below the bottom edge of the screen—it's technically being drawn, you just can't see it!
Fix:
Adjust the y-coordinate to place it inside the screen. For example, to put it just above the bottom edge with a small margin:
screen.blit(SCORE, ((WIDTH / 2) - (SCORE.get_width() / 2), HEIGHT - SCORE.get_height() - 10))
2. Font loading might be failing silently
While you mentioned fonts are initialized, pygame.font.SysFont will fall back to a default font if it can't find 'Comic Sans' (which isn't available on all systems). In rare cases, this fallback might result in a font that renders text with zero height, making it invisible.
Quick test:
Add a check to verify the font loaded correctly:
scoreFont = pygame.font.SysFont('Comic Sans', 20, bold=True) if not scoreFont: print("Warning: Failed to load 'Comic Sans' font!")
You can also try swapping in a more universally available font like 'Arial' or 'Courier New' to rule this out.
3. Text color matches the background
Your score text is rendered in black (0, 0, 0). If your game's screen background is also black, the text will blend in completely.
Quick test:
Temporarily change the text color to a bright color like red to see if it appears:
SCORE = scoreFont.render(f'X {x_score} : {o_score} O', True, (255, 0, 0))
4. Edge case: Global variable initialization issues
You're using global x_score, o_score, but if these variables weren't properly initialized in the global scope (e.g., they weren't set to 0 or another integer), the rendered text might be empty or malformed. That said, this would likely still show X : O at the very least, so this is less likely than the first three issues.
Start with adjusting the position—this is almost certainly the root cause here!
内容的提问来源于stack exchange,提问作者Kory

