我正在尝试创建一个刽子手游戏。
我收到此错误消息:
Traceback (most recent call last):
File "C:/Users/<user>/Downloads/wordgame.py", line 23, in <module>
so_far= "-" * len(word)
NameError: name 'word' is not defined
如果有人可以帮我解决如何解决这个问题,如果可以,请查看我的代码并给我一些提示,如果我朝着正确的方向前进,无论如何要改进。谢谢。
import random
HANGMAN = ('''
O''', '''
O
|''', '''
O
/|\ ''', '''
O
/|\
\ ''', '''
O
/|\
/ \ ''')
words=['train','tees','tweed','conquer','conquet','washing']
lives = len(HANGMAN) - 1
wrong = 0
used = []
so_far= "-" * len(word)
print ("Welcome to Hangman!")
def pickaword():
word = random.choice(words)
return word
def displayBoard(HANGMAN, wrongLetters, correctLetters, word):
print (HANGMAN[len(missedLetters)])
print ("wrong letters:")
for letter in wrongLetters:
print (letter, end )
def guessaletter(guessedLetters):
while True:
guess = raw_input("Guess a letter.")
guess = guess.lower()
if len(guess) != 1:
print("Please only enter a single letter.")
# Stops user from inputing more that 1 letter.
elif guess in guessedLetters:
print("You have already guessed that letter. Choose again!")
# Stops user from guessing the same letter twice.
elif guess not in "abcdefghijklmnopqrstuvwyz":
print("Please enter a valid letter")
# Stops user from enterting a invalid letter
else:
return guess
def guessaword(word, wrong, so_farm, lives):
while wrong < lives and so_far != word:
print (HANGMAN[wrong])
print ("You have used the following letters:" + used)
print ("So farm the word is", + so_far)
"""def reveal(hidden, guessedLetters):
display = ''
for letter in hidden:
letter += display
else:
lives -=1
return display"""
答案 0 :(得分:1)
您也可以使用全局
def pickaword():
global word
word = random.choice(words)
然后使用函数外的全局变量或者使用另一个函数。
答案 1 :(得分:0)
这是因为你试图得到一个不存在的变量word
的长度。
您需要先使用pickaword
功能,才能为word
提供值:
word = pickaword()
一个好的下一步,也可以帮助理解这个问题,就是开始制作用户玩游戏的功能或循环。您需要做的第一件事就是为用户选择一个词来猜测。只有在您选择了一个单词后,才能显示so_far
。但如果没有选择一个单词,那么你需要多少破折号就不清楚了。
你在guessaword
中也有一个拼写错误:第三个参数可能是so_far
。