问题描述
我正在学习Python,并决定升级一个版本的hangman游戏,该版本在我所观看的其中一门课程中用作示例,结果代码如下:
import random
word_dictionary = {
1: "mouse",2: "house",3: "show",4: "see",5: "leave",6: "shower",7: "showcase",8: "coding",9: "elephant",10: "apartment",}
random_number = random.randint(1,10)
random_word = word_dictionary[random_number]
secret_word = random_word
word_len = len(secret_word)
guess = None
tip = 0
tip_num = None
tip_previous = None
tip_position = None
tip_model_formula = "_"*word_len
tip_model_list = list(tip_model_formula)
send_tip = None
print("Word has",word_len," letters")
while guess != secret_word:
guess = input("Enter your guess: ")
if guess != secret_word:
print("Wrong answer! Try again!")
tip += 1
if tip == 5:
tip_num = random.randint(0,word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_previous = tip_num
print("here's a tip:\n" + send_tip)
if tip == 10:
tip_num = random.randint(0,word_len)
while tip_num == tip_previous:
tip_num = random.randint(0,word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_previous = tip_num
print("here's a tip:\n" + send_tip)
if tip == 15:
tip_num = random.randint(0,word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_previous = tip_num
print("here's a tip:\n" + send_tip)
if tip == 16:
print("You lost!")
exit()
print("You win!")
(这是从字典中随机选择一个单词作为秘密单词,并让玩家对其进行猜测,每5次尝试,玩家经过16次尝试后获得1个提示,即单词的一个字母,您将丢失并且必须重新启动。)
当我运行它时,有时它会按预期运行,但有时会退出并显示以下错误:
Traceback (most recent call last):
File "E:\Program Files\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pydev\pydevd.py",line 1448,in _exec
pydev_imports.execfile(file,globals,locals) # execute the script
File "E:\Program Files\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py",line 18,in execfile
exec(compile(contents+"\n",file,'exec'),glob,loc)
File "C:/Users/rafae/PycharmProjects/Beginning/Beg.py",line 55,in <module>
tip_position = secret_word[tip_num]
IndexError: string index out of range
我不知道为什么这会随机发生,并且一直试图找出一个小时没有成功。 感谢您的任何事先帮助。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)