python - 使用 Python 输入速度跟踪器
问题描述
我正在关注如何使用 pygame 制作打字速度计算器的本教程,并且每当我运行代码时,一切都会按原样呈现,但是当我尝试单击文本字段输入一些文本时,它只是冻结并且没有任何反应。我试图在线搜索或观看教程,但一切都是空的。
import sys
import time
import random
import pygame
from pygame.locals import *
"""Python Script for a typing speed test game"""
class Game(object):
def __init__(self):
self.h = 720
self.w = 1280
self.reset = True
self.active = False
self.word = ""
self.input_text = ""
self.time_start = 0
self.total_time = 0
self.accuracy = "0%"
self.wpm = 0
self.results = "Speed(WPM):0 Accuracy:0% Time:0"
self.end = False
self.head_col = (255,213,102)
self.text_col = (255,255,255)
self.result_color = (53,209,29)
pygame.init()
self.open_image = pygame.image.load("splash.jpg")
self.open_image = pygame.transform.scale(self.open_image, (self.w,self.h))
self.background = pygame.image.load("background.jpg")
self.background = pygame.transform.scale(self.background, (self.w, self.h))
self.screen = pygame.display.set_mode((self.w,self.h))
pygame.display.set_caption = "Type Speed Test"
def draw_text(self, screen, msg, y, fsize, color):
font = pygame.font.SysFont("consolas", fsize)
text = font.render(msg, 1, color)
text_rect = text.get_rect(center=(self.w/2, y))
screen.blit(text, text_rect)
pygame.display.update()
def get_sentences(self):
f = open("sentences.txt").read()
sentence = f.split("\n")
sentences = random.choice(sentence)
return sentences
def show_results(self, screen):
if(not self.end):
#Calculate Time
self.total_time = time.Time() - self.time_start
#Calcualte Accuracy
count = 0
for i,c in enumarate(self.word):
try:
if self.input_text[i] == c:
count += 1
except:
pass
self.accuracy = count/len(self.word)*100
#Calculate wpm
self.wpm = len(self.input_text)*60/(5*self.total_time)
self.end = True
print(self.total_time)
self.results = "Time:" + str(round(self.total_time))
+ " secs Accuracy: " + str(round(self.accuracy)) + "%"
+ " WPM: " + str(round(self.wpm))
#restart icon
self.time_img = pygame.image.load("icon.png")
self.time_img = pygame.transform.scale(self.time_img, (80,320))
#screen.blit(self.time_img, (80,320))
screen.blit(self.time_img, (self.w/2-75, self.h-140))
self.draw_text(screen, "Reset", self/h - 70, 26, (100,100,100))
print(self.results)
pygame.display.update()
def run(self):
self.reset_game()
self.running=True
while(self.running):
clock = pygame.time.Clock()
self.screen.fill((0,0,0), (50,250,650,50))
pygame.draw.rect(self.screen,self.head_col, (50,250,650,50), 2)
# update the text of user input
self.draw_text(self.screen, self.input_text, 274, 26,(250,250,250))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
self.running = False
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
x,y = pygame.mouse.get_pos()
# position of input box
if(x>=50 and x<=650 and y>=250 and y<=300):
self.active = True
self.input_text = ''
self.time_start = time.time()
# position of reset box
if(x>=310 and x<=510 and y>=390 and self.end):
self.reset_game()
x,y = pygame.mouse.get_pos()
elif event.type == pygame.KEYDOWN:
if self.active and not self.end:
if event.key == pygame.K_RETURN:
print(self.input_text)
self.show_results(self.screen)
print(self.results)
self.draw_text(self.screen, self.results,350, 28, self.RESULT_C)
self.end = True
elif event.key == pygame.K_BACKSPACE:
self.input_text = self.input_text[:-1]
else:
try:
self.input_text += event.unicode
except:
pass
pygame.display.update()
clock.tick(60)
def reset_game(self):
self.screen.blit(self.open_image, (0,0))
pygame.display.update()
time.sleep(1)
self.reset=False
self.end = False
self.input_text=''
self.word = ''
self.time_start = 0
self.total_time = 0
self.wpm = 0
# Get random sentence
self.word = self.get_sentences()
if (not self.word): self.reset_game()
#drawing heading
self.screen.fill((0,0,0))
self.screen.blit(self.background,(0,0))
msg = "Typing Speed Test"
self.draw_text(self.screen, msg,80, 80,self.head_col)
# draw the rectangle for input box
pygame.draw.rect(self.screen,(255,192,25), (50,250,650,50), 2)
# draw the sentence string
self.draw_text(self.screen, self.word,200, 28,self.text_col)
pygame.display.update()
Game().run()
如何解决这个问题?
解决方案
您从不处理 KEYDOWN 事件。因为 else if 语句缩进很远。
您应该更改以下内容。
class Game(object):
...
def run(self):
...
while(self.running):
...
for event in pygame.event.get():
if event.type == QUIT:
...
elif event.type == pygame.MOUSEBUTTONUP:
...
elif event.type == pygame.KEYDOWN:
...
对此:
class Game(object):
...
def run(self):
...
while(self.running):
...
for event in pygame.event.get():
if event.type == QUIT:
...
elif event.type == pygame.MOUSEBUTTONUP:
...
elif event.type == pygame.KEYDOWN:
...
推荐阅读
- ios - 设置 contentInset 时 UINavigationBar 自动折叠
- java - 使用 Groovy 根据条件访问 JSON 中的值
- ember.js - ember-cli 上的生产构建错误(UglifyWriter)无法读取 null 的属性“_walk”
- python - 无法安装 python3-setuptools
- azure - 检测密钥的 Application Insights 错误
- permissions - UWSGI 日志轮换出现错误:“父目录具有不安全的权限”
- javascript - 井字游戏应用程序中的撤消按钮使用 ReactJS
- asp.net - 用于连接 SQL Server 并以 JSON 格式返回响应的 Web API
- bash - 一行中的多个 awks
- arrays - 使用多字符分隔符将字符串拆分为数组