当按下方向键时,如何使正方形在屏幕上不断移动?

2024-04-20 06:48:30 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在Windows pc上运行此代码时,当我按住相应的键时,方块会继续沿着适当的方向在屏幕上移动,但当我在raspberry pi或mac上运行时,方块会跳5个像素然后停止。当我按下相应的键时,如何让它在屏幕上移动?你知道吗

import pygame, sys, time
from pygame.locals import *
pygame.init()
x = 400
screen = pygame.display.set_mode((x, x))
pygame.display.set_caption('This is printed on the top of the tab or window!')

BLACK = (0,0,0)
WHITE = (255,255,255)

moveSpeed = 5

moveLeft = False
moveRight = False
moveDown = False
moveUp = False

player = pygame.Rect(150, 150, 50, 50)
pygame.draw.rect(screen, BLACK, player)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT:
                moveLeft = False
                moveRight = True
            if event.key == K_DOWN:
                moveUp = False
                moveDown = True
            if event.key == K_UP:
                moveDown = False
                moveUp = True
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
            if event.key == K_LEFT:
                moveLeft = False
            if event.key == K_RIGHT:
                moveRight = False
            if event.key == K_DOWN:
                moveDown = False
            if event.key == K_UP:
                moveUp = False
        if moveLeft and player.left > 0:
            player.left -= moveSpeed
        if moveRight and player.right < x:
            player.right += moveSpeed
        if moveDown and player.bottom < x:
            player.bottom += moveSpeed
        if moveUp and player.top > 0:
            player.top -= moveSpeed
        screen.fill(WHITE)
        pygame.draw.rect(screen, BLACK, player)
        pygame.display.update()
        time.sleep(0.02)

Tags: andkeyeventfalsetrueifdisplayscreen
1条回答
网友
1楼 · 发布于 2024-04-20 06:48:30

我通过缩进线条解决了这个问题。。。你知道吗

    if moveLeft and player.left > 0:
        player.left -= moveSpeed
    if moveRight and player.right < x:
        player.right += moveSpeed
    if moveDown and player.bottom < x:
        player.bottom += moveSpeed
    if moveUp and player.top > 0:
        player.top -= moveSpeed
    screen.fill(WHITE)
    pygame.draw.rect(screen, BLACK, player)
    pygame.display.update()
    time.sleep(0.02)

。。。后退四格。此外,我还了解到,对于像这样的业余问题,/r/learpython这样的子reddit是一个很好的获得答案的地方。你知道吗

相关问题 更多 >