[英]Can someone tell me what is wrong with my WIP Python hangman game?
import random
words = ["antelope", "attacking", "architect", "defector", "mindless", "trauma", "immunity",
"fairytale", "approaching", "cuteness", "identical", "caterpillar"]
lives = 6
word = random.choice(words)
guessedWord = False
print "Welcome to Hangman. You have 6 lives, good luck!"
hiddenWord = "_ " * len(word)
print hiddenWord
while True:
if lives == 0 and not guessedWord == True:
break
guess = raw_input("Guess A Letter: ")
if len(guess) > 1:
print "Please only guess letters."
else:
if guess.isdigit() == True:
print "Please only guess letters."
else:
for letter in word:
if guess == letter:
hiddenWord[letter] == letter
print "Nice, You got a letter!"
print hiddenWord
else:
"That letter is not in this word. -1 life."
lives = lives - 1
I get this error: 我收到此错误:
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
exec codeObject in __main__.__dict__
File "C:\Users\Brian Gunsel\Desktop\Code\Python\hangman.py", line 28, in <module>
hiddenWord[letter] == letter
TypeError: string indices must be integers, not str
And it just isn't working properly. 而且它只是无法正常工作。 Can someone point me in the right direction? 有人可以指出我正确的方向吗?
The problem is that letter is a string, and hiddenWord is expecting an integer index. 问题在于字母是一个字符串,而hiddenWord需要一个整数索引。 To fix this, you want to use the index of that letter when modifying hiddenWord. 要解决此问题,您需要在修改hiddenWord时使用该字母的索引。 An easy way to do this is with enumerate()
. 一个简单的方法是使用enumerate()
。
for i, letter in enumerate(word):
if guess == letter:
hiddenWord = hiddenWord[:i] + letter + hiddenWord[i+1:]
print "Nice, You got a letter!"
print hiddenWord
else:
"That letter is not in this word. -1 life."
lives = lives - 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.