正方形不移动

-1 投票
2 回答
41 浏览
提问于 2025-04-14 17:00

我想让一个正方形在屏幕上移动。我打算通过给正方形的x坐标加上50来实现这个目标:

while run:
    pygame.time.delay(500)
    square = Square("crimson",x,200)
    x+=50

但是每次运行后,正方形只是变得越来越长,变成了一个横向的长方形。下面是完整的代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((500,500))

class Square(pygame.sprite.Sprite):
    def __init__(self,col,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50,50))
        self.image.fill(col)
        self.rect = self.image.get_rect()
        self.rect.center = (x,y)

x = 200

squares = pygame.sprite.Group()
run = True
while run:
    pygame.time.delay(500)
    square = Square("crimson",x,200)
    x+=50
    screen.fill("cyan")
    squares.add(square)
    squares.update()
    squares.draw(screen)
    pygame.display.flip()

我尝试过调整.fill().draw()的顺序,但结果总是一样。难道screen.fill("cyan")不应该把屏幕上的所有东西都擦掉,然后再绘制出移动的正方形吗?

2 个回答

0

pygame.Rect.move_ip 方法是用来移动一个 pygame.Rect 的实例的。你的代码是在创建一系列的方块,而不是在移动一个单独的方块。

import pygame

pygame.init()
screen = pygame.display.set_mode((500, 500))

class Square(pygame.sprite.Sprite):
    def __init__(self, col, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        self.image.fill(col)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)


squares = pygame.sprite.Group()
x = 0
# Create a square
square = Square("crimson", x, 200)
squares.add(square)
run = True
while run:
    pygame.time.delay(500)
    x += 50
    # Move the square
    square.rect.move_ip(x, 0)
    screen.fill("cyan")
    squares.update()
    squares.draw(screen)
    pygame.display.flip()
1

在每次循环中,你的主循环会在你的精灵组 squares 中添加一个精灵,这个精灵的位置比上一个精灵向右偏移了50个像素。

所以,你并不是在画一个长长的矩形,而是多个重叠的正方形。每个正方形都比它旁边的正方形向右偏移了50个像素。

我想你是想要让你的正方形移动。这意味着你需要:

  1. class Square 中添加一个 update() 方法,这个方法在被调用时会把一个 Square 对象的矩形的x坐标增加50个像素。
  2. 只需一次将你的正方形添加到精灵组中。

下面是一个例子,使用的是Python 3.10.5和Pygame 2.5.2,在Windows 10上测试过:

import pygame

pygame.init()
screen = pygame.display.set_mode((500,500))

class Square(pygame.sprite.Sprite):
    def __init__(self,col,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50,50))
        self.image.fill(col)
        self.rect = self.image.get_rect()
        self.rect.center = (x,y)

    def update(self):
        # move the rectangle in place (ip) by adding
        # 50 pixels to its x-coordinate.
        self.rect.move_ip(50, 0)

x = 200

squares = pygame.sprite.Group()
run = True

# Initialize your square *once*
square = Square("crimson",x,200)

# Add your square to the list *once*.
squares.add(square)

while run:
    # Make sure we can exit the game
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    pygame.time.delay(500)
    screen.fill("cyan")    
    squares.update() # calls update() on all sprites in the group
    squares.draw(screen)
    pygame.display.flip()

撰写回答