繁体   English   中英

有人可以告诉我我的WIP Python hangman游戏有什么问题吗?

[英]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

我收到此错误:

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

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

问题在于字母是一个字符串,而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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM