Pygame独立运动图像在屏幕上

时间:2016-02-12 23:54:51

标签: python-2.7 pygame

我是Python和Pygame的新手。我希望在pygame中有一个屏幕,其中相同图像的多个副本独立移动。我试图将它作为一个类编写,然后在while循环中调用它的实例,但它不起作用。有人可以说明我怎样才能使用class基本上做这样的事情?

1 个答案:

答案 0 :(得分:1)

我试图保持一切简单

示例:

import pygame
pygame.init()

WHITE = (255,255,255)
BLUE = (0,0,255)
window_size = (400,400)
screen = pygame.display.set_mode(window_size)
clock = pygame.time.Clock()

class Image():
    def __init__(self,x,y,xd,yd):
        self.image = pygame.Surface((40,40))
        self.image.fill(BLUE)
        self.x = x
        self.y = y
        self.x_delta = xd
        self.y_delta = yd
    def update(self):
        if 0 <= self.x + self.x_delta <= 360:
            self.x += self.x_delta
        else:
            self.x_delta *= -1
        if 0 <= self.y + self.y_delta <= 360:
            self.y += self.y_delta
        else:
            self.y_delta *= -1
        screen.blit(self.image,(self.x,self.y))

list_of_images = []
list_of_images.append(Image(40,80,2,0))
list_of_images.append(Image(160,240,0,-2))

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    screen.fill(WHITE)
    for image in list_of_images:
        image.update()
    pygame.display.update()
    clock.tick(30)

pygame.quit()

每个图像都可以从列表中单独调用,只需将Image.x / y更改为您想要的任何内容即可移动