【问题标题】:How to STOP generating numbers如何停止生成数字
【发布时间】: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()的调用放在循环之外。
  • 如果我把它放在循环之外,它打开的窗口将是黑色的。它不会显示任何东西(我不知道为什么)。
  • 为什么不把xy = random.randint(0,10) 放在start_the_game() 函数的上方?
  • 我试过你说的 quamrana 和窗口会变成全黑。但是,如果我退出程序,在关闭前一秒钟,它将显示 2 个我想要的数字。
  • 您需要将该函数一分为二:生成随机数的部分(在循环外调用),以及将数字呈现到屏幕上的部分(在循环内调用)。跨度>

标签: python random pygame


【解决方案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 放在循环外的函数中,它只会被调用一次。

【讨论】:

  • 感谢 Zev,您的代码终于帮我让代码工作了。
猜你喜欢
  • 1970-01-01
  • 2017-06-14
  • 2013-05-14
  • 2013-06-25
  • 2011-12-29
  • 1970-01-01
  • 2018-06-29
  • 2018-05-08
  • 2012-04-06
相关资源
最近更新 更多