如何控制Pygame中函数的迭代?函数调用时机与次数问题求助
Let's break down and fix the two problems you're facing:
Problem 1: Function Runs Multiple Times (Instead of Once)
Your current code calls display_equation() twice every frame once the 5000ms mark passes (once inside the if tks > 5000 block, once unconditionally after it). Even before that, it's called once per frame. To pick a single random equation and keep it displayed, we need to:
- Select the random equation only once when the timer hits 5000ms.
- Render that same equation every frame afterward (since Pygame redraws the screen each frame).
Problem 2: Function Runs Immediately (Instead of After 5000ms)
The unconditional display_equation() call at the end of your loop runs every frame from the moment the game starts. We need to remove that and only render the equation after the timer condition is met and we've selected our equation.
Fixed Code
Here's the adjusted code with comments explaining the changes:
import pygame import random pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() done = False equations = ['2 + 2', '3 + 1', '4 + 4', '7 - 4'] font = pygame.font.SysFont("comicsansms", 72) # New variables to track our equation state selected_equation = None equation_displayed = False # Flag to check if we've picked our equation def display_equation(equation): # Modify function to accept the pre-selected equation text = font.render(equation, True, (0, 128, 0)) screen.blit(text, (320 - text.get_width() // 2, 240 - text.get_height() // 2)) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: done = True screen.fill((255, 255, 255)) tks = pygame.time.get_ticks() # Check if 5000ms have passed and we haven't selected an equation yet if tks > 5000 and not equation_displayed: selected_equation = random.choice(equations) equation_displayed = True # Set flag so we don't pick again # Only render if we've selected an equation if equation_displayed: display_equation(selected_equation) pygame.display.update() clock.tick(60)
Key Changes Explained
- State Tracking Variables:
selected_equationstores our random choice once it's made, andequation_displayedensures we only pick the equation one time. - Modified
display_equation(): Now takes the pre-selected equation as an argument, so we're not re-picking a random one every frame. - Conditional Rendering: We only call
display_equation()after we've selected our equation, which happens exactly once when the timer exceeds 5000ms. - Removed Unconditional Call: The extra
display_equation()at the end of the loop is gone, so nothing renders until the 5000ms mark.
This way, your game will wait 5 seconds, pick one random equation, and display it consistently on screen until the game closes.
内容的提问来源于stack exchange,提问作者Shokhrukh Valiev

