[英]Pygame KEYDOWN not working
I am trying to make a rectangle move up and down on the screen.我试图让一个矩形在屏幕上上下移动。 But when I press the keys to make it go up or down I have to continuously press it each time to make it move.
但是当我按下按键使其上升或下降时,我每次都必须连续按下它才能使其移动。 The way I interpreted
pygame.KEYDOWN
was that I can hold down the desired key and the rectangle would move until I release the key.我解释
pygame.KEYDOWN
的方式是我可以按住所需的键,矩形会移动,直到我松开键。
Code for key pressed:按键代码:
while True:
for event in pygame.event.get():
# all keys
keys = pygame.key.get_pressed()
# quit game
if event.type == pygame.QUIT or keys[pygame.K_ESCAPE]:
pygame.quit()
quit()
# check key down presses
elif event.type == pygame.KEYDOWN:
# left paddle
if keys[pygame.K_q]:
left.move(-30)
if keys[pygame.K_a]:
left.move(30)
# right paddle
if keys[pygame.K_p]:
right.move(-30)
if keys[pygame.K_l]:
right.move(30)
# user let up on a key
elif event.type == pygame.KEYUP:
if event.key == keys[pygame.K_q] or event.key == keys[pygame.K_a]:
left.move(0)
elif event.key == pygame.K_p or event.key == pygame.K_l:
right.move(0)
# call animation function
draw()
# FPS
clock.tick(120)
The left
and right
objects are coming from the following class: left
和right
对象来自以下类:
import pygame
class Paddle:
def __init__(self, screen, h, w, left):
self.screen = screen
self.width = w
self.y = h / 2
self.pad_width = 10
self.pad_height = 70
if left:
self.x = self.pad_width / 2
else:
self.x = self.width - self.pad_width * 1.5
def show(self):
WHITE = (255, 255, 255)
rect = pygame.Rect(self.x, self.y, self.pad_width, self.pad_height)
pygame.draw.rect(self.screen, WHITE, rect)
def move(self, speed):
self.y += speed
Your game loop should comprise of three main steps:您的游戏循环应包括三个主要步骤:
I think by doing steps 1 and 2 together you may have confused yourself a bit.我认为通过同时执行步骤 1 和步骤 2,您可能会感到有些困惑。
Firstly, KEYDOWN
detects a key being pressed , rather than being down .首先,
KEYDOWN
检测到一个键被按下,而不是被按下。 Because of this I suggest keeping track of current key states, as a basic example:因此,我建议跟踪当前的关键状态,作为一个基本示例:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
q_down = True
else:
if event.key == pygame.K_q:
q_down = False
Now user input is handled you can simply use:现在处理用户输入,您可以简单地使用:
if q_down: left.move(-30)
in your game loop to update the game state (note this should be outside your event loop).在你的游戏循环中更新游戏状态(注意这应该在你的事件循环之外)。
I also suggest your read this post from game dev SE and have a look at the linked resources to better understand the game loop.我还建议您阅读 game dev SE 的这篇文章,并查看链接资源以更好地理解游戏循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.