1

我制作了一个代码,在屏幕上呈现 2 个不同的随机数,但它只是不断更新数字。一旦前 2 个出现在屏幕上,我希望程序停止更新这些数字。这是代码:

import pygame
import random

pygame.init()

clock = pygame.time.Clock()
surface = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Projecte MatZanfe")
font = pygame.font.SysFont('comicsans', 50)
base_font = pygame.font.Font(None, 32)
user_text = ''
color_active = pygame.Color('lightskyblue3')
def start_the_game():
    # Variables
    is_correct = False
    points = 0
    x = random.randint(0,10)
    y = random.randint(0,10)
    z = x + y
    surface.fill((255,70,90))
    text = font.render (str(x) + "+" + str(y), True, (255,255,255))
    input_rect = pygame.Rect(200,200,180,50)

    pygame.draw.rect(surface,color_active,input_rect)
    text_surface = base_font.render(user_text,True,(255,255,255))
    surface.blit(text_surface, input_rect)
    surface.blit(text,(260,120))
    input_rect.w = max(100,text_surface.get_width()+10)

running = True
while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    start_the_game()
    pygame.display.update()
pygame.quit()

也许使用 if 语句将是解决方案,但我不知道应该在哪里以及应该在代码中引入什么。你会怎么做?

4

1 回答 1

1

正如@jasonharper 建议的那样,您可能最好使用两个功能,一个用于初始化事物,另一个用于显示游戏:

def start_the_game():
    x = random.randint(0, 10)
    y = random.randint(0, 10)
    return x, y


def display_the_game(x, y):
    # Variables
    is_correct = False
    points = 0

    z = x + y
    surface.fill((255, 70, 90))
    text = font.render(str(x) + "+" + str(y), True, (255, 255, 255))
    input_rect = pygame.Rect(200, 200, 180, 50)

    pygame.draw.rect(surface, color_active, input_rect)
    text_surface = base_font.render(user_text, True, (255, 255, 255))
    surface.blit(text_surface, input_rect)
    surface.blit(text, (260, 120))
    input_rect.w = max(100, text_surface.get_width() + 10)


x, y = start_the_game()
while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    display_the_game(x, y)
    pygame.display.update()
pygame.quit()

通过random.randint在循环之外放入一个函数,它只会被调用一次。

于 2021-08-17T18:15:47.200 回答