使用键盘模块移动 pygame 中的对象

Moving objects in pygame using keyboard module

我正在创建 2 人 PONG 游戏,pygame.I 两边都有我的球拍。 其中一个用 WS 移动,另一个用 UPDOWN 箭头移动。 我正在使用此代码移动球拍:

chx = 0.051
chy = 0.051

def ychangeneg():
    global y
    if y <= 4:
        return
    else:
        y -= chy
    return

def ychangepos():
    global y
    if y >= 327:
        return
    else:
        y += chy
    return


def y1changeneg():
    global y1
    if y1 <= 4:
        return
    else:
        y1 -= chy
    return

def y1changepos():
    global y1
    if y1 >= 327:
        return
    else:
        y1 += chy
    return

while True:
    for event in pygame.event.get():
        keyQ = pygame.key.get_pressed()
    
        if event.type == pygame.QUIT:
            system("cls")
            quit()
            

        keyboard.add_hotkey("w",lambda:ychangeneg())
        keyboard.add_hotkey("s",lambda:ychangepos())

        keyboard.add_hotkey("up",lambda:y1changeneg())
        keyboard.add_hotkey("down",lambda:y1changepos())

chy 变量改变球拍的 y 并移动 it.But 我有这些问题:

  1. 当我开始按住一个键时,球拍开始缓慢移动然后变快
  2. 当我同时按住2个键(WUP arrow)时,球拍不动

起初,我找到了一些使用key= pygame.key.get_pressed()的代码,但是当你用这个代码按住一个键时,它会移动但不是连续的。

我建议不要使用键盘模块。相反,看看使用 pygame.key.get_pressed() 按下了哪个键。检查钥匙是否在里面,如果是就修改坐标

有点像这样:

pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.UP]: # this evaluates to true if the up key is pressed
    ychangeneg()
if pressed_keys[pygame.DOWN]:
    ychangepos()
# and so on...

不要混用 pygame.key module with the python keyboard 模块。

请参阅 How can I make a sprite move when key is held down 并根据按下的键更改 y 坐标:

def move_y(y, keys, up, down):
    new_y = y + (keys[down] - keys[up]) * chy
    return max(4, min(327, new_y))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            system("cls")
            quit()

    keyQ = pygame.key.get_pressed()
    y = move_y(y, keyQ, pygame.K_w, pygame.K_s)            
    y1 = move_y(y1, keyQ, pygame.K_UP, pygame.K_DOWN)   

最小示例:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 350))
clock = pygame.time.Clock()

paddle1 = pygame.Rect(10, 0, 10, 20)
paddle1.centery = window.get_rect().centery
paddle2 = pygame.Rect(380, 0, 10, 20)
paddle2.centery = window.get_rect().centery
chy = 10

def move_y(y, keys, up, down):
    new_y = y + (keys[down] - keys[up]) * chy
    return max(4, min(327, new_y))

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False    

    keyQ = pygame.key.get_pressed()
    paddle1.y = move_y(paddle1.y, keyQ, pygame.K_w, pygame.K_s)            
    paddle2.y = move_y(paddle2.y, keyQ, pygame.K_UP, pygame.K_DOWN)     

    window.fill(0)
    pygame.draw.rect(window, (255, 255, 255), paddle1)
    pygame.draw.rect(window, (255, 255, 255), paddle2)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()