"""pygame小球事件练习.py, 新建Ball类,给它加image属性,rect属性,设它的透明色为黑色,新建xspeed和yspeed属性,值为随机数。新建反弹bounce方法,到了边缘就会反向移动。新建update方法,让球移动后重画。主程序中新建两个事件USEREVENT,让它们自动定时发生,一个是定时生成事件,一个是定时消除事件。小球生成后加入到group,以便同时操作它们。作者:李兴球,风火轮少儿编程
import pygame
from pygame.locals import *
from random import randint,choice
class Ball(pygame.sprite.Sprite):
def __init__(self,radius,x,y,screen):
pygame.sprite.Sprite.__init__(self)
self.radius = radius
self.screen_width = screen.get_width()
self.screen_height = screen.get_height()
self.image = pygame.Surface((radius * 2,radius * 2 ))
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
pygame.draw.circle(self.image,(255,0,0),(radius,radius),radius)
self.image.set_colorkey((0,0,0))
self.xspeed = randint(-5,5)
self.yspeed = randint(-5,5)
def bounce(self):
if self.rect.right >= self.screen_width or self.rect.left<=0:self.xspeed = -self.xspeed
if self.rect.bottom >= self.screen_height or self.rect.top<=0:self.yspeed = -self.yspeed
def update(self):
self.rect.move_ip(self.xspeed,self.yspeed) #移动
self.bounce() #碰到边缘就反弹
screen.blit(self.image,self.rect) #重画
if __name__ == "__main__":
width,height = 800,600
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption("测试练习")
group = pygame.sprite.Group()
ball1 = Ball(20,width//2,height//2,screen)
ball2 = Ball(20,width//2,height//2,screen)
group.add(ball1)
group.add(ball2)
produceball = USEREVENT + 1
deleteball = USEREVENT + 2
pygame.time.set_timer(produceball,1000)
pygame.time.set_timer(deleteball,1000)
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT : running = False
if event.type == produceball : group.add( Ball(20,width//2,height//2,screen))
if event.type == deleteball : choice(list(group)).remove(group) #从group中随机选择一个球,移除它.
screen.fill((0,255,255))
group.update()
pygame.display.update()
pygame.quit()