0

I'm writing a hangman. The script consist of two functions: setup() which initializes all the variables (the word, number of guesses, lists of letters to check etc) and main (which is the main game loop). The last thing setup() does is calling the main(). From main() you can invoke setup() to reset the game.

By design, the main() function needs to access the variables created by setup() and vice versa. It requires me to heavily use "global" statements - for all declarations within setup().

How should I approach it to avoid having "bad" global variables?

import random

def setup():
    with open("Ex30_Pick_a_word/sowpods.txt", "r") as f:
        lines = [x for x in f.readlines()]
    count = 0
    for line in lines:
        count += 1
    global selected_word
    selected_word = lines[random.randint(1, count)].rstrip()

    ## initialize variables
    global guess_state
    guess_state = ['-' for letter in selected_word]
    global bad_letters
    bad_letters = ""
    global chances
    chances = 6

    ##  start game
    print("\n\n\n####     WELCOME TO HANGMAN      ###")
    print("Word to guess is: " + selected_word + ".")  ## debug only ;)
    main()

def main():
    while True:
        success = False
        print("\n""The word is:")
        display = "".join(guess_state)
        print(display)
        global chances
        print("You've got " + str(chances) + " chances left.")
        guess_letter = input("Guess a letter:").capitalize()

        ## logic
        for letter_id, letter in enumerate(selected_word):
            if guess_letter == letter:                      ## if found
                if guess_state[letter_id] == "-":           ## if not yet found
                    guess_state[letter_id] = letter
                    success = True
                    break
        if not success:
            global bad_letters
            if guess_letter in bad_letters:
                print("You've aread tried: \"" + guess_letter + "\"")
            else:
                bad_letters += guess_letter + " "
            chances -= 1
        if ''.join(guess_state) == selected_word:
            print("You've won, the word was: " + selected_word)
            again = input("Do you want to play again? (y/n)")
            if again == "y":
                setup()
            break
        if len(bad_letters) > 0:
            print("\nBad letters: " + bad_letters)
        if chances == 0:
            print("Game Over.")
            again = input("Do you want to play again? (y/n)")
            if again == "y":
                setup()
            break

setup()
  • 1
    You should use a class and instance attributes instead of global names. – Klaus D. Jan 20 '19 at 05:13
  • 1
    Remove the `setup()` function and move all its code into `main()`, above the while loop. Or, modify setup so it's called from main and it _returns_ all the variables to main. – John Gordon Jan 20 '19 at 05:19
  • Possible duplicate of [An alternative to global in Python](https://stackoverflow.com/questions/14135345/an-alternative-to-global-in-python) – stovfl Jan 20 '19 at 11:16

0 Answers0