Keyboard Demo

一个简单的键盘录入示例,基于《Python游戏编程入门》,书中代码有逻辑错误,已给予改动。

import sys, random, time, 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))

#main program begins
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
speed = 0

key_flag = False
correct_answer = 97 # "a"
seconds = 11
score = 0
clock_start = 0
game_over = True

#repeating loop
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()
	if keys[K_ESCAPE]:
		sys.exit()

	if keys[K_RETURN]:
		if game_over:
			game_over = False
			score = 0
			seconds = 11
			clock_start = time.clock()
	
	current = time.clock() - clock_start
	
	if seconds - current < 0:
		game_over = True
	elif current <= 10:
		if keys[correct_answer]:
			correct_answer = random.randint(97,122)
			score += 1

	#clear the screen
	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 type the big yellow letters as fast as you can.")
	print_text(font1, 0, 40, "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)))
		speed = score * 6
		print_text(font2, 0, 240, chr(correct_answer-32), yellow)	
				
	print_text(font1, 0, 100, "Speed:" + str(speed) + "letters /min")

	if game_over:
		print_text(font1, 0, 160, "Press Enter to start...")




	#update the display
	pygame.display.update()

运行示例:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值