【问题标题】:How do I get the square to continually move across the screen as a direction key is held down?当按住方向键时,如何让方块在屏幕上不断移动?
【发布时间】:2015-12-23 01:16:46
【问题描述】:

当我在 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)

【问题讨论】:

  • 也许this SO answer中描述的解决方案之一可能对您有所帮助。

标签: python macos boolean pygame


【解决方案1】:

我通过缩进解决了这个问题...

    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)

... 后退四个空格。另外,我了解到,对于此类业余问题,某些子 reddit(如 /r/learpython)是获得答案的好地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多