我正在尝试纠正迭代列表中每个项目的代码,以将所有匹配的项目替换为相同的项目。目前,仅替换第一个实例。它适用于刽子手风格的游戏。这是我的代码:
if guess in self.word:
print(f"Good guess! {guess} is in the word.")
guessed = True
for g in self.word:
if g == guess:
guess_index = self.word.find(guess)
self.word_guessed[guess_index] = guess
self.num_letters -= 1
print(f"Your progress so far: {self.word_guessed}.")
else:
self.num_lives -= 1
print(f"Sorry. {guess} is not in the word. Try again.")
print(f"You have {self.num_lives} lives left.")
print(f"Your progress so far: {self.word_guessed}.")
有什么想法可以确保每个实例都被替换。我想我需要某种形式的 while 循环,但不确定条件应该是什么。
我尝试了不同的 while 循环,但找不到一个可以工作的。如果被猜的词是 apple,我最终会得到 [a,p,_,l,e]
要替换单词中猜测的字母的所有实例,您不需要 while 循环。您可以继续使用 for 循环,但需要调整更新 word_guessed 列表的方式。
目前,您正在查找第一次出现的猜测字母的索引并替换它,但您需要查找所有出现的字母并替换它们。 试试这个:
class HangmanGame:
def __init__(self, word):
self.word = word
self.word_guessed = ['_' for _ in word]
self.num_letters = len(word)
self.num_lives = 6
def guess_letter(self, guess):
if guess in self.word:
print(f"Good guess! {guess} is in the word.")
guessed = True
for i in range(len(self.word)):
if self.word[i] == guess:
self.word_guessed[i] = guess
self.num_letters -= 1
print(f"Your progress so far: {' '.join(self.word_guessed)}.")
else:
self.num_lives -= 1
print(f"Sorry. {guess} is not in the word. Try again.")
print(f"You have {self.num_lives} lives left.")
print(f"Your progress so far: {' '.join(self.word_guessed)}.")
# Example usage:
game = HangmanGame("hangman")
game.guess_letter("a")
输出:
Good guess! a is in the word.
Your progress so far: _ a _ _ _ a _.
你不需要类来实现这个猜谜游戏
def guess_me(secret='Replace each item in the list', moves=5):
guess = ''.join(i if i.isspace() else '_' for i in secret)
print(guess)
while moves > 0:
x = input(f'moves {moves} enter letter ')
if x in secret:
guess = ''.join(i if i==x else guess[n] for n,i in enumerate(s))
print(guess)
else:
moves -= 1
print('nope')
if guess == secret: return True
return False