<p>多亏了@aenda和@lennon310的建议,并对以下帖子做了一些研究:<a href="http://www.garyrobinson.net/2009/10/non-blocking-raw_input-for-python.html" rel="nofollow noreferrer">Non-blocking raw_input code from Gary Robinson</a>,<a href="https://stackoverflow.com/questions/3471461/raw-input-and-timeout">Raw input and timeout</a>和{a3}我能够做一些细微的修改,并生成以下代码来解决我的问题。在</p>
<pre><code>timeout=7
class AlarmException(Exception):
pass
def alarmHandler(signum,frame):
raise AlarmException
def my_raw_input(prompt,timeout):
signal.signal(signal.SIGALRM,alarmHandler)
signal.alarm(timeout)
try:
userGuess=int(raw_input(prompt))
signal.alarm(0)
return userGuess
except AlarmException:
print "Uh-oh! Time's for that one!"
signal.signal(signal.SIGALRM,signal.SIG_IGN)
return ''
def level_one():
goodGuess=0
badGuess=0
time_easy_level = default_timer()
numbers_with_operators=[]
local_operators_easy=["+","-"]
global continuePlaying
global timeout
#====Repeat operations 5 times=================
for x in range(5):
#===10 random numbers between 1 and 10 are generated =========
easy_level=[randint(1,10) for i in range(1,10)]
#===Each list of random numbers is appended with a random operator===
for item in easy_level:
numbers_with_operators.append(item)
time.sleep(1)
numbers_with_operators.append(local_operators_easy[randint(0,1)])
if len(numbers_with_operators)==18:
numbers_with_operators.append(randint(1,10))
print numbers_with_operators
user_guess = my_raw_input("What's the result? ",timeout)
computer_result=compute_list(numbers_with_operators)
if user_guess==computer_result:
goodGuess+=1
timeout=7
print "Good guess!"
else:
print "Sorry, that is not the result"
badGuess+=1
timeout=7
print computer_result
print "That was the number operation "+str(x)
del numbers_with_operators[:]
duration=default_timer()-time_easy_level
continuePlaying=False
print "Your results are: \n"
print "Good guesses: "+str(goodGuess)+"\nBad guesses: "+str(badGuess)
print "Total seconds playing:\n"+str(duration)+" seconds"
return continuePlaying
</code></pre>