python小游戏学习笔记4-3(彩色小球跟随鼠标随机变色弹跳)

import pgzrun  #导入游戏库
import random
WIDTH = 800    #设置窗口宽度
HEIGHT = 600   #设置窗口高度

balls = []  #类似建立一个空文档

def draw(): #这段是整个框架,之后两段是在里面填充
    screen.fill('white')
    for ball in balls: #绘制所有的圆
        screen.draw.filled_circle((ball[0],ball[1]),ball[4],(ball[5],ball[6],ball[7]))

def update():
    # 设置小球自动弹跳
    for ball in balls:
        ball[0] = ball[0] + ball[2]
        ball[1] = ball[1] + ball[3]
        if ball[0] > WIDTH - ball[4] or ball[0] < ball[4]:
            ball[2] = - ball[2]
        if ball[1] > HEIGHT - ball[4] or ball[1] < ball[4]:
            ball[3] = - ball[3]

def on_mouse_move(pos,rel,buttons):#当鼠标移动时
    if mouse.LEFT in buttons:      #当鼠标左键按下时
        x = pos[0]      #鼠标的x坐标,设为小球的x坐标
        y = pos[1]      #鼠标的y坐标,设为小球的y坐标
        speed_x = random.randint(1,5)  #小球x方向的速度
        speed_y = random.randint(1, 5) #小球y方向的速度
        r = random.randint(5,50)       #小球半径
        colorR = random.randint(10,255) #小球三个颜色分量
        colorG = random.randint(10,255)
        colorB = random.randint(10,255)

        # 储存小球所有信息的列表,比如ball【0】就是x,ball【5】就是colorR 这是一个倒叙手法!!!圆形时间叙事 (这段可以跟上段update互换)
        ball = [x,y,speed_x,speed_y,r,colorR,colorG,colorB]
        balls.append(ball) #把单个小球的信息添加到balls中,


pgzrun.go()

许多个淡紫色小球同时无规律运动:

import pgzrun  #导入游戏库
import random
WIDTH = 800    #设置窗口宽度
HEIGHT = 600   #设置窗口高度

balls = []  #类似建立一个空文档

for i in range(25):
    x = random.randint(100,WIDTH-100)
    y = random.randint(100,HEIGHT-100)
    speedx = random.randint(1,4)
    speedy = random.randint(1, 4)
    r = 20
    ball = [x,y,speedx,speedy]
    balls.append(ball)

def draw(): #这段是整个框架,之后两段是在里面填充
    screen.fill('white')
    for ball in balls: #绘制所有的圆
        screen.draw.filled_circle((ball[0],ball[1]),r,(189,193,243))

def update():
    # 设置小球自动弹跳
    for ball in balls:
        ball[0] = ball[0] + ball[2]
        ball[1] = ball[1] + ball[3]
        if ball[0] > WIDTH - r or ball[0]  HEIGHT - r or ball[1] < r:
            ball[3] = - ball[3]

pgzrun.go()

你可能感兴趣的:(python小游戏学习笔记4-3(彩色小球跟随鼠标随机变色弹跳))