改善我在python 3中执行hangman游戏代码的建议

我正在为使用python 3构建的3.子手游戏使用此代码。

The code is working perfectly, as soon as you have your words.txt file with some words in same folder as the script, but I need suggestions to improve it.

有很多代码重复和要点,我可以编写出更好的代码,而且我在代码重构中苦苦挣扎。有什么意见和建议吗?

class Hangman(object):
    def __init__(self):
        self.secret_word = self.get_secret_word()
        self.correct_letters = []
        self.missed_letters = []
        self.error = 0

    def get_secret_word(self):
        from random import choice

        with open("words.txt") as f:
            wordsList = f.read().splitlines()
            secretWord = choice(wordsList).lower()
        return secretWord

    def read_player_input(self):
        self.inputChar = input("\nType a letter: ")

    def guess_letter(self):
        if (
            self.inputChar in self.secret_word
            and self.inputChar not in self.correct_letters
        ):
            self.correct_letters.append(self.inputChar)
            return True
        elif (
            self.inputChar not in self.secret_word
            and self.inputChar not in self.missed_letters
        ):
            self.missed_letters.append(self.inputChar)
            self.error += 1
            print(f"\nError {self.error}.")
            return False
        else:
            print("\nYou've already tried this letter.")
            return False

    def print_encoded_word(self):
        self.encoded_word = ""
        for letter in self.secret_word:
            if letter not in self.correct_letters:
                self.encoded_word += "_"
            else:
                self.encoded_word += letter
        print()
        print(self.encoded_word)

        print("\nCorrect letters: ", end="")
        for letter in self.correct_letters:
            print(letter + " ", end="")

        print("\nWrong letters: ", end="")
        for letter in self.missed_letters:
            print(letter + " ", end="")

    def game_continue(self):
        return set(self.correct_letters) != set(self.secret_word) and (self.error <= 3)

    def won_game(self):
        if set(self.correct_letters) == set(self.secret_word):
            print(self.secret_word)
            print("You win!")
        else:
            print(f"You lose. Secret word is {self.secret_word}")


def main():

    hangman = Hangman()

    hangman.print_encoded_word()
    hangman.read_player_input()
    hangman.guess_letter()

    while hangman.game_continue():
        hangman.print_encoded_word()
        hangman.read_player_input()
        hangman.guess_letter()

    hangman.won_game()


if __name__ == "__main__":
    main()
评论