Python:游戏:测试打字速度
生活随笔
收集整理的這篇文章主要介紹了
Python:游戏:测试打字速度
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
現(xiàn)在寫(xiě)書(shū)的人真是一點(diǎn)責(zé)任心都沒(méi)有,最近看了幾本書(shū),其中的代碼都存在錯(cuò)誤。
最近迷戀 Python?游戲,買(mǎi)了《Python游戲編程入門(mén)》[美] Jonathan S·Harbour 著?一書(shū)來(lái)看。
其中第四章:Bomb Catcher游戲中,測(cè)試打字速度的程序代碼嚴(yán)重有誤。
改程序屏幕上隨機(jī)顯示一個(gè)字母,按鍵輸入該字母后隨機(jī)顯示下一個(gè),計(jì)算平均一分鐘可以輸入多少個(gè)字母,原代碼中計(jì)算速度的一塊有誤,附上我修改后的代碼
import sys import random import time import pygame from pygame.locals import *def print_text(font, x, y, text, color=(255, 255, 255)):imgText = font.render(text, True, color)screen.blit(imgText, (x, y))pygame.init() screen = pygame.display.set_mode((600, 500)) pygame.display.set_caption('Keyboard Demo') font1 = pygame.font.Font(None, 24) font2 = pygame.font.Font(None, 200) white = (255, 255, 255) yellow = (255, 255, 0)key_flag = False correct_answer = 97 # a seconds = 11 score = 0 speed = 0 clock_start = 0 game_over = Truewhile True:for event in pygame.event.get():if event.type == QUIT:sys.exit()elif event.type == KEYDOWN:key_flag = Trueelif event.type == KEYUP:key_flag = Falsekeys = pygame.key.get_pressed() # keys 是一個(gè)元組,窮舉了所有的按鍵,未按下為 0,按下為 1if keys[K_ESCAPE]:sys.exit()if keys[K_RETURN]:if game_over:game_over = Falseclock_start = time.time()score = 0seconds = 11speed = 0clock = clock_startif not game_over:current = time.time() - clock_startif seconds < current:game_over = Trueelse:if keys[correct_answer]:correct_answer = random.randint(97, 122)clock_start = time.time()score += 1speed = 60 * score / (clock_start - clock)screen.fill((0, 100, 0))print_text(font1, 0, 0, "Let's see how fast you can type!")print_text(font1, 0, 20, "Try to keep up for 10 seconds...")if key_flag:print_text(font1, 500, 0, "<key>")if not game_over:print_text(font1, 0, 80, "Time: " + str(int(seconds-current)))print_text(font1, 0, 100, "Speed: " + str(int(speed)) + " letters/min")if game_over:print_text(font1, 0, 160, "Press Enter to start...")print_text(font2, 0, 240, chr(correct_answer-32), yellow)pygame.display.update()?
轉(zhuǎn)載于:https://www.cnblogs.com/gl1573/p/9571560.html
總結(jié)
以上是生活随笔為你收集整理的Python:游戏:测试打字速度的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 技术简历制作注意点
- 下一篇: 机器学习:Python实现聚类算法(二)