【发布时间】:2021-08-17 16:24:35
【问题描述】:
我编写了一个代码,可以在屏幕上呈现 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 语句将是解决方案,但我不知道我应该在哪里以及在代码中引入什么。你会怎么做?
【问题讨论】:
-
按照你的逻辑,你不断地在最后的
while loop开始你的游戏(running总是正确的)。也许把对start_the_game()的调用放在循环之外。 -
如果我把它放在循环之外,它打开的窗口将是黑色的。它不会显示任何东西(我不知道为什么)。
-
为什么不把
x和y= random.randint(0,10)放在start_the_game()函数的上方? -
我试过你说的 quamrana 和窗口会变成全黑。但是,如果我退出程序,在关闭前一秒钟,它将显示 2 个我想要的数字。
-
您需要将该函数一分为二:生成随机数的部分(在循环外调用),以及将数字呈现到屏幕上的部分(在循环内调用)。跨度>