代码少,就把类文件和函数文件放一块了。颜色随机,小球个数number适当调整,在这种算法下比较吃显卡
import pygame
import sys
from pygame.sprite import Group
from pygame.sprite import Sprite
import random
#小球个数
number = 20
move_speed = 5
up_left = 7
up_right = 9
down_left = 3
down_right = 1
black = (0,0,0)
windows_width = 1200
windows_height = 600
#小球类
class Bound(Sprite):
def __init__(self,direction,start_x,start_y,color):
super(Bound,self).__init__()
self.color = color
self.start_direction = direction
self.rect = pygame.Rect(start_x,start_y,20,20)
#检查边界,并设置反弹
def check_border(self):
if self.rect.top <= 0:
#左上
if self.start_direction == up_left:
self.start_direction = down_left
#右上
elif self.start_direction == up_right:
self.start_direction = down_right
elif self.rect.bottom >= windows_height:
#右下
if self.start_direction == down_right:
self.start_direction = up_right
#左下
elif self.start_direction == down_left:
self.start_direction = up_left
elif self.rect.left <= 0:
#左上
if self.start_direction == up_left:
self.start_direction = up_right
#左下
elif self.start_direction == down_left:
self.start_direction = down_right
elif self.rect.right >= windows_width:
#右上
if self.start_direction == up_right:
self.start_direction = up_left
#右下
elif self.start_direction == down_right:
self.start_direction = down_left
#判断走的方向,并更新数据
def type_judge(self):
if self.start_direction == up_right:
self.rect.top -= move_speed
self.rect.right += move_speed
elif self.start_direction == up_left:
self.rect.top -= move_speed
self.rect.left -= move_speed
elif self.start_direction == down_left:
self.rect.bottom += move_speed
self.rect.left -= move_speed
elif self.start_direction == down_right:
self.rect.bottom += move_speed
self.rect.right += move_speed
def draw_buf(self,windows):
pygame.draw.rect(windows, self.color, self.rect)
#主程序
def run():
pygame.init()
windows = pygame.display.set_mode((windows_width, windows_height))
pygame.display.set_caption('Bound')
#小球组
bufs = Group()
for i in range(number):
direction = random.choice([1,3,7,9])
color1 = random.randint(0,255)
color2 = random.randint(0,255)
color3 = random.randint(0,255)
color = [color1,color2,color3]
start_x = random.randint(0,windows_width)
start_y = random.randint(0,windows_height)
print(color)
new_buf = Bound(direction,start_x,start_y,color)
bufs.add(new_buf)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
for buf in bufs:
buf.check_border()
buf.type_judge()
buf.draw_buf(windows)
pygame.display.flip()
pygame.time.delay(1)
windows.fill(black)
run()
20个方块就是这个样子