pygame移动广场走出界限

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pygame移动广场走出界限相关的知识,希望对你有一定的参考价值。

我目前正在编制一个移动广场。我想用我的钥匙来控制它,并且它不会超出界限。但是,我无法让它移出边界(窗口的一侧)。这是我的代码:

import sys, pygame
pygame.init()

width, height = 700, 700

screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
clock = pygame.time.Clock()

FPS = 120
x1 = 0
y1 = 0

xmb1 = False
xmf1 = False
ymb1 = False
ymf1 = False
squareh = 50
squarew = 50
squares = 3

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

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                xmb1 = True
            if event.key == pygame.K_RIGHT:
                xmf1 = True
            if event.key == pygame.K_UP:
                ymb1 = True
            if event.key == pygame.K_DOWN:
                ymf1 = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                xmb1 = False
            if event.key == pygame.K_RIGHT:
                xmf1 = False
            if event.key == pygame.K_UP:
                ymb1 = False
            if event.key == pygame.K_DOWN:
                ymf1 = False

    if x1 == 0:
        xmb1 = False
    if y1 == 0:
        ymb1 = False
    if x1 == width - squarew:
        xmfl = False
    if y1 == height - squareh:
        ymf1 == False
    if xmb1:
        x1 -= squares
    if xmf1:
        x1 += squares
    if ymb1:
        y1 -= squares
    if ymf1:
        y1 += squares
    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE, (x1, y1, squareh, squarew), 0)
    pygame.display.flip()
    clock.tick(FPS)

有人知道如何解决这个问题吗?我刚刚学习了pygame(昨晚!)

答案

你有一个名为xmfl的变量(小写L)而不是xmf1(带1)

要回答你的问题:

我会改变这段代码:

if xmb1:
    x1 -= squares
if xmf1:
    x1 += squares
if ymb1:
    y1 -= squares
if ymf1:
    y1 += squares

对此

if xmb1 and not (x1 <= 0):
    x1 -= squares
if xmf1 and not (x1 + squarew >= width):
    x1 += squares
if ymb1 and not (y1 <= 0):
    y1 -= squares
if ymf1 and not (y1 + squareh >= height):
    y1 += squares

我可能会向后退y方向...因为我使用了pygame已经有一段时间了。

代码的作用是检查我们是否已经处于董事会的边缘。如果我们处于边缘,不要允许进一步的移动。如果我们不在边缘,请继续。

如果这有帮助和/或我是否可以为您回答任何问题,请告诉我。

以上是关于pygame移动广场走出界限的主要内容,如果未能解决你的问题,请参考以下文章

使用 pygame 移动图像

Pygame,角色移动速度

Pygame移动加速问题,平台游戏[重复]

如何移动pygame rect?

Pygame sprite创建重复而不是移动

Pygame的图像移动