这个程序测试你的反应速度:一看到DRAW这个词就按回车。但是要小心。在DRAW出现之前按下它,你就输了。你是西方最快的键盘吗?
当您运行fastdraw.py时,输出将如下所示:
Fast Draw, by Al Sweigart email@protected
Time to test your reflexes and see if you are the fastest
draw in the west!
When you see "DRAW", you have 0.3 seconds to press Enter.
But you lose if you press Enter before "DRAW" appears.
Press Enter to begin...
It is high noon...
DRAW!
You took 0.3485 seconds to draw. Too slow!
Enter QUIT to stop, or press Enter to play again.
> quit
Thanks for playing!input()函数在等待用户输入字符串时暂停程序。这个简单的行为意味着我们不能只用input()来创建实时游戏。然而,你的程序将缓冲键盘输入,这意味着如果你在input()被调用之前按下C、A和T键,这些字符将被保存,一旦input()执行,它们将立即出现。
通过记录第 22 行的input()调用之前的时间和第 24 行的input()调用之后的时间,我们可以确定玩家按下回车花了多长时间。然而,如果他们在调用input()之前按下回车,回车按下的缓冲会导致input()立即返回(通常在大约 3 毫秒内)。这就是为什么第 26 行检查时间是否小于 0.01 秒或 10 毫秒,以确定玩家按下回车太快。
"""Fast Draw, by Al Sweigart email@protected
Test your reflexes to see if you're the fastest draw in the west.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, beginner, game"""
import random, sys, time
print('Fast Draw, by Al Sweigart email@protected')
print()
print('Time to test your reflexes and see if you are the fastest')
print('draw in the west!')
print('When you see "DRAW", you have 0.3 seconds to press Enter.')
print('But you lose if you press Enter before "DRAW" appears.')
print()
input('Press Enter to begin...')
while True:
print()
print('It is high noon...')
time.sleep(random.randint(20, 50) / 10.0)
print('DRAW!')
drawTime = time.time()
input() # This function call doesn't return until Enter is pressed.
timeElapsed = time.time() - drawTime
if timeElapsed < 0.01:
# If the player pressed Enter before DRAW! appeared, the input()
# call returns almost instantly.
print('You drew before "DRAW" appeared! You lose.')
elif timeElapsed > 0.3:
timeElapsed = round(timeElapsed, 4)
print('You took', timeElapsed, 'seconds to draw. Too slow!')
else:
timeElapsed = round(timeElapsed, 4)
print('You took', timeElapsed, 'seconds to draw.')
print('You are the fastest draw in the west! You win!')
print('Enter QUIT to stop, or press Enter to play again.')
response = input('> ').upper()
if response == 'QUIT':
print('Thanks for playing!')
sys.exit() 试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。
- 如果把第 22 行的
drawTime = time.time()改成drawTime = 0会怎么样? - 如果把第 30 行的
timeElapsed > 0.3改成timeElapsed < 0.3会怎么样? - 如果把第 24 行的
time.time() - drawTime改成time.time() + drawTime会怎么样? - 如果删除或注释掉第 15 行的
input('Press Enter to begin...')会发生什么?
