【问题标题】:Assigning a list into constructor将列表分配给构造函数
【发布时间】:2020-02-03 18:00:26
【问题描述】:

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

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

为此,我在方法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)

    # According to the game status, print the message on screen to user
    # if game.hangman_won():
    #  print('\nCongratulations! You won!!!')
    # else:
    # print('\nGame over! You lost.')
    # print('The word was {}'.format(game.word))

    # print('\nIt was good to play with you. But now go study!\n')


# Run program
if __name__ == '__main__':
    main()

【问题讨论】:

  • 没关系。 Minor nit:最好使用“hidden”而不是“hided”——我认为这不是正确的英语。

标签: python python-3.x list oop python-requests


【解决方案1】:

由于您只处理单词,这意味着输入通常很短,因此您不需要 constructor 中的 hidedWord 的附加属性,只要您需要此值,您只需调用 self.hide_word() 即可。

但是,如果您要处理较长的输入,例如长句子甚至文本,最好只调用一次 self.hide_word() 并有一个属性来保存其值,因为每次调用该函数都会减慢您的游戏速度。

【讨论】:

  • 谢谢@Issac Newton,这个想法是只在列表中存储* 符号一次。在此之后,程序将用*符号替换列表中猜测字母的对应位置。像这样tru*c*,对卡车一词。
猜你喜欢
  • 2022-01-18
  • 2021-11-24
  • 2013-11-05
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
相关资源
最近更新 更多