[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()