这个问题可能是由于没有正确调整矩形大小或位置所致。你可以在调用pygame.draw.rect绘制矩形前,使用pygame.Rect的move方法和inflate方法来调整矩形的位置和大小。
以下是代码示例:
import pygame
pygame.init()
# 设置窗口
win_width = 800
win_height = 600
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("Boids Algorithm")
# 定义颜色
white = (255, 255, 255)
# 定义一个矩形
rect = pygame.Rect(0, 0, 50, 50)
rect.center = (win_width // 2, win_height // 2)
def draw_rect():
# 将矩形移到窗口中央,同时将矩形的大小增大一倍
rect.move_ip((win_width // 2 - rect.centerx, win_height // 2 - rect.centery))
rect.inflate_ip(rect.width, rect.height)
# 绘制矩形
pygame.draw.rect(win, white, rect)
# 主循环
while True:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 绘图
win.fill((0, 0, 0))
draw_rect()
pygame.display.update()
在这个例子中,我们在每次绘制矩形前都会将矩形移到窗口中央,并将矩形的大小增大一倍,这样就可以正确显示矩形了。