亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將列表分配給構造函數

將列表分配給構造函數

不負相思意 2022-06-14 17:15:07
我正在編寫一個 Hangman 游戲,為此我創建了下面的課程。其中一種方法是用*符號隱藏單詞并顯示猜測的字母。為此,我在方法中創建了一個列表,并在方法中def hide_word(self)調用它constructor以顯示板上隱藏的單詞print_game_status(self)。我想知道上面標記的行是有效的還是不好的做法。PS:部分線路未完成。# Classclass 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 bankdef rand_word():    with open('palavras.txt', 'rt') as f:        bank = f.readlines()    return bank[random.randint(0, bank.index(max(bank)))].strip()# Main functiondef 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)
查看完整描述

1 回答

?
偶然的你

TA貢獻1841條經驗 獲得超3個贊

由于您只處理單詞,這意味著輸入通常很短,因此hidedWordconstructor不需要self.hide_word().

但是,如果您正在處理較長的輸入,例如長句子甚至文本,最好只調用self.hide_word()一次并有一個屬性來保存其值,因為每次調用該函數都會減慢您的游戲速度。


查看完整回答
反對 回復 2022-06-14
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號