找回密码
 中文实名注册
查看: 285|回复: 0

用Pygame写一个学习打字的小游戏

[复制链接]

704

主题

1096

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
22189
发表于 2023-5-19 18:54:36 | 显示全部楼层 |阅读模式
[Python] 纯文本查看 复制代码
import sys
import random
import time
import pygame
#from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("打字速度")
font1 = pygame.font.SysFont("SimHei", 24)
font2 = pygame.font.SysFont("SimHei", 200)
white = 255, 255, 255
yellow = 255, 255, 0
# 是否按键
key_flag = False
# 游戏是否开始 默认是结束的
game_over = True
# 随机的字母
correct_answer = random.randint(97, 122)
# 分数
score = 0
# 开始时间
clock_start = 0
# 读秒倒计时
seconds = 11


def print_text(font, x, y, text, color=white):
    img_text = font.render(text, True, color)
    screen.blit(img_text, (x, y))


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            key_flag = True
        elif event.type == pygame.KEYUP:
            key_flag = False
    keys = pygame.key.get_pressed()
    if keys[pygame.K_ESCAPE]:
        sys.exit()
    if keys[pygame.K_RETURN]:
        if game_over:
            game_over = False
            score = 0
            clock_start = time.perf_counter()
            seconds = 11

    screen.fill((0, 100, 0))
    current = time.perf_counter() - clock_start
    print_text(font1, 0, 0, "看看你的速度有多快")
    print_text(font1, 0, 30, "请在10秒内尝试")

    if seconds - current < 0:
        game_over = True
    elif current <= 10:
        if keys[correct_answer]:
            correct_answer = random.randint(97, 122)
            score += 1
            clock_start = time.perf_counter()
    # 如果按键了
    if key_flag:
        print_text(font1, 500, 0, "按键了")

    if not game_over:
        print_text(font1, 0, 80, "Time: " + str(int(seconds - current)))
        print_text(font1, 500, 40,  str(int(time.perf_counter())))

    print_text(font1, 0, 100, "分数: " + str(score))

    if game_over:
        print_text(font1, 0, 160, "请按enter开始游戏...")

    print_text(font2, 0, 240, chr(correct_answer - 32), yellow)

    pygame.display.update()

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 中文实名注册

本版积分规则

小黑屋|东台市机器人学会 ( 苏ICP备2021035350号-1;苏ICP备2021035350号-2;苏ICP备2021035350号-3 )

GMT+8, 2024-12-4 01:59 , Processed in 0.037583 second(s), 26 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表