将列表分配给构造函数

我正在编写一个 Hangman 游戏,为此我创建了下面的课程。


其中一种方法是用*符号隐藏单词并显示猜测的字母。


为此,我在方法中创建了一个列表,并在方法中def hide_word(self)调用它constructor以显示板上隐藏的单词print_game_status(self)。


我想知道上面标记的行是有效的还是不好的做法。


PS:部分线路未完成。


# Class

class Hangman:


    # Constructor

    def __init__(self, word):

        self.word = word

        self.hidedWord = self.hide_word() # <-- This is valid or is a bad practice?


    # Method to guess the letter

    def guess(self, letter):

        if letter in self.word:

            correctLetters.append(letter)

            self.hidedWord[1] = 'Y' # <-- This only a test, at first it works

        else:

            wrongLetters.append(letter)


    # Method to check if game is over

    # def hangman_over(self):


    # Method to check if the player won

    # def hangman_won(self):


    # Method to hide the letter on the board

    def hide_word(self):

        return ['*' for x in self.word]


    # Method to check the status game and print the board on the screen

    def print_game_status(self):

     print(board[0])

     print(*self.hidedWord)

     print('Wrong letters: ' + ', '.join(wrongLetters))

     print('Correct letters: ' + ', '.join(correctLetters))


# Function to read a word randomly from the word bank

def rand_word():

    with open('palavras.txt', 'rt') as f:

        bank = f.readlines()

    return bank[random.randint(0, bank.index(max(bank)))].strip()


# Main function

def main():

    # Object

    game = Hangman(rand_word())


    # While the game is not over, print the status, request a letter and read caracter

    while(exit != True):

        # Check the status game

        game.print_game_status()


        # Input from user

        inputUser = input('Type a letter: ')

        game.guess(inputUser)



不负相思意
浏览 96回答 1
1回答

偶然的你

由于您只处理单词,这意味着输入通常很短,因此hidedWord您constructor不需要self.hide_word().但是,如果您正在处理较长的输入,例如长句子甚至文本,最好只调用self.hide_word()一次并有一个属性来保存其值,因为每次调用该函数都会减慢您的游戏速度。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python