import pygame
import math
import random
def random_color():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
def random_speed():
return random.randint(-3, 3)
def impact(ball1, ball2):
x1, y1 = ball1['pos']
x2, y2 = ball2['pos']
distance_x = x1 - x2
distance_y = y1 - y2
distance = math.sqrt(distance_x ** 2 + distance_y ** 2)
if distance <= ball1['r'] + ball2['r']:
if ball1['r'] > ball2['r']:
ball1['r'] = ball2['r'] + ball1['r']
all_balls.remove(ball2)
else:
ball2['r'] = ball2['r'] + ball1['r']
all_balls.remove(ball1)
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
pygame.display.flip()
# all_ball中保存多个球
# 每个球要保存:半径、圆心坐标、颜色、x速度、y速度
all_balls = [
{'r': random.randint(10, 20), 'pos': (100, 100), 'color': random_color(),
'x_speed': random_speed(), 'y_speed': random_speed()},
{'r': random.randint(10, 20), 'pos': (100, 100), 'color': random_color(),
'x_speed': random_speed(), 'y_speed': random_speed()},
]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
# 点击鼠标创建一个球
ball = {'r': random.randint(10, 25),
'pos': event.pos,
'color': random_color(),
'x_speed': random_speed(),
'y_speed': random_speed()
}
# 保存球
all_balls.append(ball)
# 刷新界面
screen.fill((255, 255, 255))
pygame.time.delay(10)
# 多球运动
for ball_dict in all_balls:
# 取出球原来的x坐标和y坐标以及他们的速度
x, y = ball_dict['pos']
x_speed = ball_dict['x_speed']
y_speed = ball_dict['y_speed']
x += x_speed
y += y_speed
if x + ball_dict['r'] >= 600:
x = 600 -ball_dict['r']
ball_dict['x_speed'] *= -1
if x - ball_dict['r'] <= 0:
x = ball_dict['r']
ball_dict['x_speed'] *= -1
if y + ball_dict['r'] >= 400:
y = 400 -ball_dict['r']
ball_dict['y_speed'] *= -1
if y - ball_dict['r'] <= 0:
y = ball_dict['r']
ball_dict['y_speed'] *= -1
pygame.draw.circle(screen, ball_dict['color'], (x, y), ball_dict['r'])
# 更新球对应的坐标
ball_dict['pos'] = x, y
pygame.display.update()
for ball1 in all_balls:
for ball2 in all_balls:
if ball1 == ball2:
continue
impact(ball1, ball2)
网友评论