这个案例实现了三个继承Sprite的小球在屏幕中不停碰撞运动的效果
第一个文件Ball.py
import pygame
from pygame.locals import BLEND_ADD
class Ball(pygame.sprite.Sprite):
def __init__(self, color, initial_position):
pygame.sprite.Sprite.__init__(self)
# 这里直接加载一个图片文件
self.image = pygame.image.load('background.jpg').convert_alpha()
self.rect = self.image.fill(color, None, BLEND_ADD)
self.rect.topleft = initial_position
class MoveBall(Ball):
def __init__(self, color, initial_position, speed, border):
super(MoveBall, self).__init__(color, initial_position)
self.speed = speed
self.border = border
self.update_time = 0
def update(self, current_time):
if self.update_time < current_time:
if self.rect.left < 0 or self.rect.left > self.border[0] - self.rect.w:
self.speed[0] *= -1
if self.rect.top < 0 or self.rect.top > self.border[1] - self.rect.h:
self.speed[1] *= -1
self.rect.x += self.speed[0]
self.rect.y += self.speed[1]
self.update_time = current_time + 10
第二个文件Main.py
import pygame
from pygame.locals import QUIT
from Ball import MoveBall
pygame.init()
screen = pygame.display.set_mode([800, 600])
# A container class to hold and manage multiple Sprite objects.
balls = pygame.sprite.Group()
for color, location, speed in [([255, 0, 0], [50, 50], [2, 3]),
([0, 255, 0], [100, 100], [3, 2]),
([0, 0, 255], [150, 150], [4, 3])]:
balls.add(MoveBall(color, location, speed, (800, 600)))
while True:
if pygame.event.poll().type == QUIT:
pygame.quit()
exit()
screen.fill((0, 0, 0))
current_time = pygame.time.get_ticks()
# 分组统一管理
balls.update(current_time)
balls.draw(screen)
pygame.display.update()