Pygame | 9 - Sprite实现小球运动的案例

这个案例实现了三个继承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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值