Home > OS >  How to stop a random.choice() from choosing in a while loop?
How to stop a random.choice() from choosing in a while loop?

Time:09-29

I'm making a Hangman game using Pygame and have an issue. In my code, I have a "while run:" loop that refreshes at FPS = 60. In that loop, have a "random.choice(topics)" that picks out a random topic in Hangman that will determine which set of words will be used. My issue is that everytime the loop resets, the "random.choice(topics)" picks another topic, and on screen. The topics continuously switches between the topics available.

I was wondering how make that specific line of code run once to pick a topic and not switch between multiple?

Here is a snippet of the loop:

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

CodePudding user response:

Choose it before the while-loop:

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))

If you need to choose it depending on a condition, indicate to choose a new subject with a variable. Reset the variable when the topic is selected. So you can always choose a new topic by setting 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))
  • Related