pygame反弹小球事件USEREVENT练习.py,作者:李兴球

本教程通过创建Ball类并使用Pygame实现小球在屏幕上的随机移动和边缘碰撞反弹。通过设置USEREVENT定时触发小球的生成与销毁,演示了如何控制多个小球的群体行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

"""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()
    
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李兴球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值