前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python:游戏:测试打字速度

Python:游戏:测试打字速度

作者头像
丹枫无迹
发布2019-09-11 19:32:20
1.7K0
发布2019-09-11 19:32:20
举报
文章被收录于专栏:学无止境学无止境

现在写书的人真是一点责任心都没有,最近看了几本书,其中的代码都存在错误。

最近迷恋 Python 游戏,买了《Python游戏编程入门》[美] Jonathan S·Harbour 著 一书来看。

其中第四章:Bomb Catcher游戏中,测试打字速度的程序代码严重有误。

改程序屏幕上随机显示一个字母,按键输入该字母后随机显示下一个,计算平均一分钟可以输入多少个字母,原代码中计算速度的一块有误,附上我修改后的代码

代码语言:javascript
复制
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 = True

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == KEYDOWN:
            key_flag = True
        elif event.type == KEYUP:
            key_flag = False

    keys = pygame.key.get_pressed()     # keys 是一个元组,穷举了所有的按键,未按下为 0,按下为 1
    if keys[K_ESCAPE]:
        sys.exit()
    if keys[K_RETURN]:
        if game_over:
            game_over = False
            clock_start = time.time()
            score = 0
            seconds = 11
            speed = 0
            clock = clock_start

    if not game_over:
        current = time.time() - clock_start
        if seconds < current:
            game_over = True
        else:
            if keys[correct_answer]:
                correct_answer = random.randint(97, 122)
                clock_start = time.time()
                score += 1
                speed = 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()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-09-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档