盒子里的弹珠世界

"""
   盒子里的弹球小世界
"""
import pygame
from random import randint
from pygame.locals import *

RED = (255,0,0)
BLUE = (0,0,255)

class Ball(pygame.sprite.Sprite):
    """
       球类,继承自角色类,它会在一个矩形范围内受重力移动。
    """
    def __init__(self,radius,box,color):
        """
           radius:半径,box:所在的盒子,color:颜色
        """
        pygame.sprite.Sprite.__init__(self)
        self.radius = radius
        self.image = pygame.Surface((radius*2,radius*2))
        self.image.set_colorkey((0,0,0))   # 设置不渲染颜色
        pygame.draw.circle(self.image,color,(radius,radius),radius)
        self.rect = self.image.get_rect(center=pos)
        self.speed = [randint(-5,5),randint(-5,5)]
        self.gravity = 0.5                 # 重力加速度
        self.box = box                     # 保存自己的盒子
        self.set_boundary()                # 设置反弹边界值

    def set_boundary(self):
        """设置反弹的边界"""
        self.left_boundary = self.box.rect.left     # 左边界
        self.right_boundary = self.box.rect.right   # 右边界
        self.top_boundary = self.box.rect.top       # 上边界
        self.bottom_boundary = self.box.rect.bottom # 下边界
        
    def update(self):
        """更新坐标,碰到边缘就反弹。"""
        
        self.rect.move_ip(*self.speed)             # 移动矩形对象
        if self.rect.left <= self.left_boundary or \
           self.rect.right >= self.right_boundary:
               self.speed[0] = -self.speed[0]
               
        # 下面通过加上高度,从而对碰到下边缘进行预判
        if self.rect.bottom + self.rect.height >= self.bottom_boundary:
            self.speed[1] = -self.speed[1]
        else:
            self.speed[1] = self.speed[1] + self.gravity
        self.set_boundary()

You must log in to read the rest of this article. Please log in or register as a user.