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