【发布时间】:2019-03-27 04:29:26
【问题描述】:
我已经实现了一个记忆游戏,用户必须在 5 秒的计时器运行时在脑海中对数字进行排序。
请看下面的代码:
from random import randint
from threading import Timer
def timeout():
print("Time over\n#####################\n")
while True:
list = []
for i in range(5):
list.append(randint(1000, 10000))
t = Timer(5, timeout)
t.start()
print(list)
print('[ 1 , 2 , 3 , 4 , 5 ]')
solution = sorted(list)[2]
print('please select the 3rd largest number in this row (1-5):')
input_string = input()
selection = int(input_string)
if solution == list[selection - 1]:
print("Your guess is correct\n")
else:
print("Your guess is wrong\n")
t.join()
这里是游戏交互本身(请忽略语法高亮):
USER@HOST:~/$ python3 memory_game.py
[8902, 8655, 1680, 6763, 4489]
[ 1 , 2 , 3 , 4 , 5 ]
please select the 3rd largest number in this row (1-5):
4
Your guess is correct
Time over
#####################
[5635, 3810, 1114, 5042, 1481]
[ 1 , 2 , 3 , 4 , 5 ]
please select the 3rd largest number in this row (1-5):
4
Your guess is wrong
Time over
#####################
[6111, 1430, 7999, 3352, 2742]
[ 1 , 2 , 3 , 4 , 5 ]
please select the 3rd largest number in this row (1-5):
23
Traceback (most recent call last):
File "memory_game.py", line 24, in <module>
if solution == list[selection - 1]:
IndexError: list index out of range
Time over
#####################
谁能帮我解决这些问题:
1. 只有当玩家需要超过 5 秒的时间才能回答时,才应该写下“超时”。如果玩家及时解决了它,下一个挑战应该会静默出现。
2. 如果玩家没有写任何猜测并按下“Enter”,程序将终止并显示错误消息:
回溯(最近一次通话最后):
文件“memory_game.py”,第 22 行,在
选择 = int(输入字符串)
ValueError:以 10 为基数的 int 的无效文字:''
3. 如果玩家输入任何随机数,程序会以“索引超出范围错误”退出 - 我找不到在哪里放置 try: 除了:
任何帮助将不胜感激 - 谢谢!
【问题讨论】:
标签: python-3.x error-handling timer