-1
我想讓矩形在屏幕上上下移動。但是,當我按下鍵使其升高或降低時,我必須每次不斷按下它使其移動。我解釋pygame.KEYDOWN
的方式是,我可以按住所需的鍵,矩形會移動,直到我釋放鍵。Pygame KEYDOWN不工作
代碼鍵按下:
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)
的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
'KEYDOWN'可以檢測到關鍵*不會*下降。你應該檢測到'KEYDOWN'和'KEYUP'並跟蹤每個鍵的當前狀態(提示,在所有情況下使用'event.key'而不是'keys') –
@NickA我將事件改爲'if event.key == pygame.K_q:'等,但我仍然需要每次按下鍵使其移動。 – kstullich
你需要保持當前的按鍵狀態'q_down = True/False',這取決於它是否被按下/釋放,然後在你的遊戲循環中你可以做'if q_down:left.move(-30)'(注意我說在你的遊戲循環中,不是事件處理循環) –