Python中的全局变量以及如何避免它们?

时间:2019-01-20 04:59:10

标签: python function global-variables

我正在写一个子手。 该脚本包含两个功能: setup()初始化所有变量(单词,猜测数,要检查的字母列表等)和main(主要游戏循环)。 setup()做的最后一件事是调用main()。 在main()中,您可以调用setup()来重置游戏。

根据设计,main()函数需要访问setup()创建的变量,反之亦然。它要求我大量使用“全局”语句-用于setup()中的所有声明。

我应该如何避免使用“坏的”全局变量?

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

0 个答案:

没有答案