Python程序:用Pygame Zero做一个会自动变色、四处移动、碰壁反弹的小球

import pgzrun
from pgzhelper import *   # pygame zero helper导入,否则无法使用放大缩小acotr的大小的函数
import colorsys
import random

WIDTH=500
HEIGHT=500

class ColorBall:
    def __init__(self, pos):
        self.pos = pos
        self.radius = random.randint(10, 50)
        self.hue = 0.0  # 色相值(0.0-1.0)
        self.dx=random.randint(-1,1)
        self.dy=random.randint(-1,1)
        while self.dx==0:
            self.dx=random.randint(-1,1)
        while self.dy==0:
            self.dy=random.randint(-1,1)

    def draw(self):
        # 将HSV转换为RGB(hue为动态变化的色相值)
        rgb = colorsys.hsv_to_rgb(self.hue, 1, 1)
        color = (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255))
        # 绘制实心圆
        screen.draw.filled_circle(self.pos, self.radius, color)

    def update(self):
        # 每帧增加色相值实现颜色渐变(0.005控制变色速度)
        self.hue = (self.hue + 0.005) % 1.0
        new_x = self.pos[0] + self.dx
        new_y = self.pos[1] + self.dy
        
        # 左边界检测(左边缘接触)
        if (new_x - self.radius) < 0:
            self.dx = abs(self.dx)  # 向右反弹
        # 右边界检测(右边缘接触)
        elif (new_x + self.radius) > WIDTH:
            self.dx = -abs(self.dx)  # 向左反弹
        
        # 上边界检测(上边缘接触)
        if (new_y - self.radius) < 0:
            self.dy = abs(self.dy)  # 向下反弹
        # 下边界检测(下边缘接触)
        elif (new_y + self.radius) > HEIGHT:
            self.dy = -abs(self.dy)  # 向上反弹
        
        self.pos = (new_x, new_y)

Balls = []

def draw():
    global Balls

    screen.clear()
    for Ball in Balls:
        Ball.draw()

def update():
    global Balls

    for Ball in Balls:
        Ball.update()

def on_mouse_down(pos,button):
    if button==mouse.LEFT:
        Ball=ColorBall(pos)
        Balls.append(Ball)

pgzrun.go()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值