pygame中的窗口边框

问题描述

我正在创建一个游戏,但不想让游戏角色移出窗口。我尝试使用这种代码

if circleX - 16 == 0:
    circleX = 16
elif circleY - 16 == 0:
    circleY = 16
elif circleY + 16 == 500:
    circleY = 484
elif circleX + 16 == 500:
    circleX = 484
elif circleY - 16 == 0 and circleX - 16 == 0:
    circleY = 16
    circleX = 16
elif circleY + 16 == 500 and circleX + 16 == 500:
    circleX = 484
    circleY = 484
elif circleY + 16 == 500 and circleX - 16 == 0:
    circleY = 484
    circleX = 16
elif circleY - 16 == 0 and circleX + 16 == 500:
    circleX = 484
    circleY = 16

但是它似乎不起作用,我在做什么错了?

解决方法

我建议使用pygame.Rect对象将圆限制在窗口的边界内。下面的window Surface 的显示内容:

radius = 16
clampRect = window.get_rect().inflate(-radius*2,-radius*2)
circleX = max(clampRect.left,min(clampRect.right,circleX))
circleY = max(clampRect.top,min(clampRect.bottom,circleY))

说明:

get_rect()生成一个pygame.Rect,其大小为pygame.Surface,与显示器相关联。 inflate()生成一个新的矩形,其大小随圆的直径而改变,该矩形保持围绕其当前中心为中心。
在下文中,minmax用于在矩形定义的区域中夹持圆心。

,

您可以避免边界使用相同关系比较==。我使用<=>=作为比较边界。

我不知道您的代码和上下文,但是我想circleXcircleY在其他方法上已更改。

如果它像circleX += 20那样更改变量,则可以传递所有if条件。否则,如果线程环境中的某些事件调用它的速度太快,我们就不能相信circleX的值。

我建议进行以下比较:

if circleX - 16 <= 0:  # Left border
    circleX = 16
elif circleY - 16 <= 0:  # Top
    circleY = 16
elif circleY + 16 >= 500:  # Bottom
    circleY = 484
elif circleX + 16 >= 500:  # Right
    circleX = 484
elif circleY - 16 <= 0 and circleX - 16 <= 0:  # Top Left corner
    circleY = 16
    circleX = 16
elif circleY + 16 >= 500 and circleX + 16 >= 500:  # Bottom right
    circleX = 484
    circleY = 484
elif circleY + 16 >= 500 and circleX - 16 <= 0:  # Bottom left
    circleY = 484
    circleX = 16
elif circleY - 16 <= 0 and circleX + 16 >= 500:  # Top right
    circleX = 484
    circleY = 16

,如果有以下条件,可通过减少使用来缩短它:

if circleX - 16 <= 0:      # Left border
    circleX = 16
    if circleY - 16 <= 0:  # Top Left corner
        circleY = 16
elif circleY - 16 <= 0:      # Top
    circleY = 16
    if circleX + 16 >= 500:  # Top right
        circleX = 484
elif circleY + 16 >= 500:  # Bottom
    circleY = 484
    if circleX - 16 <= 0:  # Bottom left
        circleX = 16
elif circleX + 16 >= 500:    # Right
    circleX = 484
    if circleY + 16 >= 500:  # Bottom right
        circleY = 484

但是,我个人更喜欢的短代码是:

circleX = min(max(16,circleX),484)
circleY = min(max(16,circleY),484)