方块不动

问题描述 投票:0回答:1

我正在尝试在屏幕上进行方形移动。我计划通过将 int 50 添加到我的方形对象的 x 坐标变量来实现此目的:

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")
擦除屏幕上的所有内容,然后绘图会产生正方形移动的错觉吗?

python pygame game-development pygame-surface
1个回答
0
投票

在每次迭代中,主循环都会向 sprite 组添加一个 sprite

squares
,距离最后一个 sprite 右侧 50 像素。

因此,你没有一个单一的拉长矩形,而是多个重叠的正方形。每个方格与其相邻方格右侧相距 50 像素。

我认为你的意思是“移动”你的方块。这意味着您需要:

    update()
  1. 添加一个
    class Square
    方法,在调用时将 50 个像素添加到
    Square
    对象矩形的 x 坐标。
    将您的方块添加到精灵组
  2. 一次
  3. 这是一个示例,在 Windows 10 上使用 Python 3.10.5 和 Pygame 2.5.2 进行测试:

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: pygame.time.delay(500) screen.fill("cyan") squares.update() # calls update() on all sprites in the group squares.draw(screen) pygame.display.flip()

© www.soinside.com 2019 - 2024. All rights reserved.