繁体   English   中英

如何阻止 random.choice() 在 while 循环中进行选择?

[英]How to stop a random.choice() from choosing in a while loop?

我正在使用 Pygame 制作 Hangman 游戏,但遇到了问题。 在我的代码中,我有一个“while run:”循环,它在 FPS = 60 时刷新。在那个循环中,有一个“random.choice(topics)”,它在 Hangman 中挑选一个随机主题,该主题将决定哪一组单词将使用。 我的问题是每次循环重置时,“random.choice(topics)”都会在屏幕上选择另一个主题。 主题在可用主题之间不断切换。

我想知道如何让特定的代码行运行一次来选择一个主题而不是在多个主题之间切换?

这是循环的一个片段:

while run:
    clock.tick(FPS)  # FPS = 60

    # draw title
    topics = ["PLACES", "SPORTS", "FOOD AND DRINK", "OPPOSITE WORDS"]
    text = TITLE_FONT.render(random.choice(topics), 1, BLACK)
    window.blit(text, (WIDTH/2 - text.get_width()/2, 20))

    draw() # not important here

while循环之前选择它:

topics = ["PLACES", "SPORTS", "FOOD AND DRINK", "OPPOSITE WORDS"]
text = TITLE_FONT.render(random.choice(topics), 1, BLACK)

while run:
    clock.tick(FPS)  # FPS = 60

    # draw title    
    window.blit(text, (WIDTH/2 - text.get_width()/2, 20))

如果需要根据条件选择,说明选择一个新的有变量的主题。 选择主题时重置变量。 所以你总是可以通过设置choose_topic = True来选择一个新主题:

choose_topic = True

while run:
    clock.tick(FPS)  # FPS = 60

    if choose_topic:
        choose_topic = False
        topics = ["PLACES", "SPORTS", "FOOD AND DRINK", "OPPOSITE WORDS"]
        text = TITLE_FONT.render(random.choice(topics), 1, BLACK)

    # draw title    
    window.blit(text, (WIDTH/2 - text.get_width()/2, 20))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM