gpt4 book ai didi

python - 有人能告诉我我的 WIP Python 刽子手游戏出了什么问题吗?

转载 作者:太空宇宙 更新时间:2023-11-03 16:55:54 27 4
gpt4 key购买 nike

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

我收到此错误:

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

它只是无法正常工作。有人能指出我正确的方向吗?

最佳答案

问题是 letter 是一个字符串,而hiddenWord 需要一个整数索引。要解决此问题,您需要在修改hiddenWord 时使用该字母的索引。一个简单的方法是使用 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

关于python - 有人能告诉我我的 WIP Python 刽子手游戏出了什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com