Pygame:按住键时玩家不会移动

时间:2019-12-23 05:17:03

标签: python pygame

只是从pygame开始,然后按住箭头键尝试获取一个简单的点在屏幕上移动。当前,它仅在您按下键时移动,但是您必须反复按下它。

import random
import pygame
import keyboard
import time
from pygame.locals import *

class Player:
    def __init__(self):
        self.x = 150
        self.y = 150

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Smile, you're beautiful!")
player = Player()
while True:
    pygame.time.Clock().tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                player.x += 5
            if event.key == pygame.K_DOWN:
                player.y += 5
            if event.key == pygame.K_LEFT:
                player.x -= 5
            if event.key == pygame.K_UP:
                player.y -= 5
        pygame.event.pump()
    pygame.display.flip()
    pygame.display.update()
    screen.fill((0,0,0))
    pygame.draw.circle(screen, (180, 180, 180), (player.x, player.y), 5)

此外,对于您可能对我的当前代码有任何建议,可以对它们进行改进或更改以提高效率,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要使用pygame.key.get_pressed而不是按键事件。这样,您可以知道每个刻度线当前正在按下哪些键

while True:
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_RIGHT]:
        player.x += 5
    if pressed[pygame.K_DOWN]:
        player.y += 5
    if pressed[pygame.K_LEFT]:
        player.x -= 5
    if pressed[pygame.K_UP]:
        player.y -= 5