如何在 Pygame 中制作边框

2024-04-29

我试图让游戏的某个区域周围有边框,并使用一种尺寸来不断更改我的代码,以便它适用于一种尺寸:

这是代码:

# screen, xpos, ypos, height, width, border width, color
def draw_borders(s, x, y, h, w, bw, c):
    draw(s, color, x, y, w, bw)
    draw(s, color, x, y, bw, h)
    draw(s, color, x, h+bw, w, bw)
    draw(s, color, w, y+bw, bw, h)
# draw is just a function that calls pygame.draw.rect with all the values given


def draw(s, color, x, y, w, h):
    pygame.draw.rect(s, color, (x,y,w,h))

其使用的数据是:

# sw = screen width
# I have my default sw at 500x500 but it works for any window size
draw_borders(10, 10, sw-20 sh-20)

问题是这些框没有对齐,因此当值有任何不同时,构成边框的 4 个框不匹配以构成实际边框,因此我无法获得未定义为窗口大小的框。

所以我想我的问题是:

1-有没有更简单的方法来制作边框?

2-如果不是,我该如何制作,以便无论传入的数据是什么,边框都对齐?


如果你想画边框,那么可以直接使用pygame.draw.rect() https://www.pygame.org/docs/ref/draw.html#pygame.draw.rect通过设置width争论。

def draw_borders(s, x, y, w, h, bw, c):
    pygame.draw.rect(s, c, (x, y, w, h), bw)

或者绘制一个封闭的多边形

def draw_borders(s, x, y, w, h, bw, c):
    pygame.draw.lines(s, c, True, [(x, y), (x+w, y), (x+w, y+h), (x, y+h)], bw)

如果你想消除角落的缺失,那么你必须将边框缝合4个矩形:

def draw_borders(s, x, y, w, h, bw, c):
    pygame.draw.rect(s, c, (x, y, w, bw))
    pygame.draw.rect(s, c, (x, y+h-bw, w, bw))
    pygame.draw.rect(s, c, (x, y, bw, h))
    pygame.draw.rect(s, c, (x+w-bw, y, bw, h))

或由 4 条单独的行组成:

def draw_borders(s, x, y, w, h, bw, c):
    pygame.draw.line(s, c, (x-bw//2+1, y), (x+w+bw//2, y), bw)
    pygame.draw.line(s, c, (x-bw//2+1, y+h), (x+w+bw//2, y+h), bw)
    pygame.draw.line(s, c, (x, y-bw//2+1), (x, y+h+bw//2), bw)
    pygame.draw.line(s, c, (x+w, y-bw//2+1), (x+w, y+h+bw//2), bw)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Pygame 中制作边框 的相关文章

随机推荐