[英]Ending my secret word game and outputting user guess count in Python
我正在嘗試用 Python 編寫一個類似 Hangman 的文字游戲。 用戶可以猜測的次數沒有限制。
除了一個小問題外,我的游戲運行正常:當用戶猜出完整的單詞時,游戲並沒有結束並告訴他們他們贏了,以及猜了多少次。
def main():
print("Welcome to the Secret Word Game!")
print()
word = ["m","o","u","n","t","a","i","n"]
guessed = []
wrong = []
guesses = 0
while True:
out = ""
for letter in word:
if letter in guessed:
out = out + letter
else:
out = out + "*"
if out == word:
print("You guessed", word)
break
print("Guess a letter from the secret word:", out)
guess = input()
if guess in guessed or guess in wrong:
print("Already guessed", guess)
guesses +=1
elif guess in word:
print("Correct!",guess,"is in the secret word!")
guessed.append(guess)
guesses+=1
else:
print("Wrong!")
wrong.append(guess)
guesses+=1
print()
print(guesses)
main()
您不會退出,因為您的終止條件不可能為 True:
if out == word:
out
是一個長度為 8 的字符串; word
是 8 個單字符字符串的列表。 如果將word
的初始化更改為
word = "mountain"
然后您的程序運行良好,生成逐個猜測更新和適當數量的猜測。
Welcome to the Secret Word Game!
Guess a letter from the secret word: ********
n
Correct! n is in the secret word!
Guess a letter from the secret word: ***n***n
e
Wrong!
Guess a letter from the secret word: ***n***n
t
Correct! t is in the secret word!
Guess a letter from the secret word: ***nt**n
a
Correct! a is in the secret word!
Guess a letter from the secret word: ***nta*n
o
Correct! o is in the secret word!
Guess a letter from the secret word: *o*nta*n
i
Correct! i is in the secret word!
Guess a letter from the secret word: *o*ntain
f
Wrong!
Guess a letter from the secret word: *o*ntain
m
Correct! m is in the secret word!
Guess a letter from the secret word: mo*ntain
u
Correct! u is in the secret word!
You guessed mountain
9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.