这对您来说似乎非常基础,我想我知道我的代码有什么问题,我似乎无法弄清楚如何修复。基本上,我正在建立一个非常简单的刽子手游戏,我想让用户每次猜错信都会失去生命。这是代码:
import random
word_choice = ["list", "microsoft", "cars", "philosophy", "mother", "powder", "star", "baby", "elephant"]
guessed_letters = []
right_guessed_letters = []
def user_turn(c):
lives = 10
while True:
guess = input("\nGuess a letter or a word: ")
guessed_letters.append(guess)
print ("\n")
if lives != 0 and guess != comp_choice:
if guess in comp_choice:
right_guessed_letters.append(guess)
for i in comp_choice:
if i in right_guessed_letters:
print (i, end= ' ')
else:
print ('-', end = ' ')
else:
lose_life(lives)
continue
elif guess == comp_choice:
print ("Good job, you guessed the word correctly!")
break
elif lives == 0:
print ("You lost, your lives are all depleated...")
break
def lose_life(l):
l -= 1
print (f'Wrong letter, you have {l} lives remaining')
print (f"The letters you already guessed are {guessed_letters}")
comp_choice = random.choice(word_choice)
word = '-' * len(comp_choice)
print (f"Your word is : {word} long.")
user_turn(comp_choice)
基本上,我的问题是用户只能失去一条生命。事实上,我希望每次调用lose_life,用户都会失去生命,所以他的生命每次都减少一次,然而变量生命在功能完成后立即获得它的原始值。因此,每次调用该函数时,用户都处于九次生命中。这是输出:
microsoft
Your word is : --------- long.
Guess a letter or a word: d
Wrong letter, you have 9 lives remaining
The letters you already guessed are ['d']
Guess a letter or a word: e
Wrong letter, you have 9 lives remaining
The letters you already guessed are ['d', 'e']
Guess a letter or a word:
无论如何,如果你能提供帮助,我们将非常感激!
答案 0 :(得分:3)
你的lose_life
函数没有返回任何内容,所以它实际上只是打印两个语句。
如果您在return l
函数的末尾添加了lose_life
,并将else语句中的lose_life(lives)
更改为lives = lose_life(lives)
,则它现在可以正常工作。
如果这看起来很麻烦并且你有冒险的感觉,你可以考虑改用Classes:
class Live(object):
def __init__(self, value=10):
self.value = value
def __str__(self):
return str(self.value)
def __repr__(self):
return self.__str__()
def lose(self):
self.value -= 1
print(f'Wrong letter, you have {self.value} lives remaining')
print(f"The letters you already guessed are {guessed_letters}")
def gain(self):
self.value += 1
# insert your own print messages if you wish.
请注意,我不建议为此用例执行此操作(KISS主要适用),但对于需要自己的属性和功能的对象的更复杂项目,类非常适用于此目的。