创建一个可以创建随机球的函数 (createball)。球是 x 和 y 位置、运动向量 dx、dy 和颜色 ((x, y, dx, dy, color)) 的元组。创建一定数量的球(max_balls),位置随机(random.randint(a, b)),颜色随机(random.choice(seq)):
radius = 25
color_list = [GREEN, BLUE, RED]
def createball():
x = random.randint(radius, screensize[0]-radius)
y = random.randint(radius, screensize[1]-radius)
color = random.choice(color_list)
return x, y, 2, 2, color
按照分配 (x2, y2, dx2, dy2) 中的建议将 3 个球装箱并存储到变量中:
x, y, dx, dy, color = createball()
x2, y2, dx2, dy2, color2 = createball()
x3, y3, dx3, dy3, color3 = createball()
创建一个函数 (moveball),它可以移动球,在击球时改变方向并改变颜色。在应用循环中移动球:
def moveball(x, y, dx, dy, color):
x, y = x + dx, y + dy
if not radius < x < screensize[0]-radius:
dx = -dx
color = random.choice(color_list)
if not radius < y < screensize[1]-radius:
dy = -dy
color = random.choice(color_list)
return x, y, dx, dy, color
while run:
# [...]
x, y, dx, dy, color = moveball(x, y, dx, dy, color)
x2, y2, dx2, dy2, color2 = moveball(x2, y2, dx2, dy2, color2)
x3, y3, dx3, dy3, color3 = moveball(x3, y3, dx3, dy3, color3)
看例子:
import pygame
import sys
import random
pygame.init()
screensize = (800,600)
screen = pygame.display.set_mode(screensize,0)
pygame.display.set_caption("Animation Test")
clock = pygame.time.Clock()
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
radius = 25
color_list = [GREEN, BLUE, RED]
def createball():
x = random.randint(radius, screensize[0]-radius)
y = random.randint(radius, screensize[1]-radius)
color = random.choice(color_list)
return x, y, 2, 2, color
def moveball(x, y, dx, dy, color):
x, y = x + dx, y + dy
if not radius < x < screensize[0]-radius:
dx = -dx
color = random.choice(color_list)
if not radius < y < screensize[1]-radius:
dy = -dy
color = random.choice(color_list)
return x, y, dx, dy, color
x, y, dx, dy, color = createball()
x2, y2, dx2, dy2, color2 = createball()
x3, y3, dx3, dy3, color3 = createball()
go = True
while go:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
go = False
x, y, dx, dy, color = moveball(x, y, dx, dy, color)
x2, y2, dx2, dy2, color2 = moveball(x2, y2, dx2, dy2, color2)
x3, y3, dx3, dy3, color3 = moveball(x3, y3, dx3, dy3, color3)
screen.fill(WHITE)
pygame.draw.circle(screen, color, (x, y), radius)
pygame.draw.circle(screen, color2, (x2, y2), radius)
pygame.draw.circle(screen, color3, (x3, y3), radius)
pygame.display.flip()
可以在Use vector2 in pygame 找到更复杂的球类方法。