我不知道为什么while循环不会中断以完成hangman程序。我已经包含了整个程序,以便为您提供一些背景信息。它将显示游戏结束消息,而不显示获胜消息
import random
import os
import time
def playGame():
wordList = ["dog", "bird", "chair", "computer", "elephant", "school"]
letterList=[]
underscoreList=[]
guessesLeft = 6
word = random.choice(wordList)
#print(word)
for letter in word:
letterList.append(letter)
underscoreList.append("_")
#print(letterList)
#print(underscoreList)
while guessesLeft > 0:
#os.system('clear') #clears screen
print(underscoreList)
print("You Have" , guessesLeft, "Guesses Remaining")
userGuess = (input("Please enter a letter... \n>")).lower()
if len(userGuess) != 1 or not userGuess.isalpha():
print("Please Enter A Single Letter Only")
time.sleep(1)
elif userGuess in letterList:
print(userGuess, "is there")
time.sleep(1)
for position, letter in enumerate(letterList):
if letter == userGuess:
underscoreList[position] = userGuess
elif '_' not in underscoreList:
break
else:
print("Not In Word")
time.sleep(2)
guessesLeft -= 1
if guessesLeft > 0:
print("Congratulations you have guessed the word " , word)
else:
print("You Loser")
playGame()
答案 0 :(得分:0)
只需将省略号移动到代码的开头。因此,现在它在继续执行程序之前先进行检查。
import random
import os
import time
def playGame():
wordList = ["dog", "bird", "chair", "computer", "elephant", "school"]
letterList=[]
underscoreList=[]
guessesLeft = 6
word = random.choice(wordList)
#print(word)
for letter in word:
letterList.append(letter)
underscoreList.append("_")
#print(letterList)
#print(underscoreList)
while guessesLeft > 0:
#os.system('clear') #clears screen
if '_' not in underscoreList:
break
print(underscoreList)
print("You Have" , guessesLeft, "Guesses Remaining")
userGuess = (input("Please enter a letter... \n>")).lower()
if len(userGuess) != 1 or not userGuess.isalpha():
print("Please Enter A Single Letter Only")
time.sleep(1)
elif userGuess in letterList:
print(userGuess, "is there")
time.sleep(1)
for position, letter in enumerate(letterList):
if letter == userGuess:
underscoreList[position] = userGuess
else:
print("Not In Word")
time.sleep(2)
guessesLeft -= 1
if guessesLeft > 0:
print("Congratulations you have guessed the word " , word)
else:
print("You Loser")
playGame()