# coding=utf-8
# Time : 2018/7/30 16:40
# Author : 云水君
# Email : 632942444@qq.com
# File : 多个球运动.py
# Software: PyCharm
import pygame
from random import randint
def draw_ball(place, color, pos):
pygame.draw.circle(place, color, pos, 20)
def collision(pos1, pos2, r1, r2): # 碰撞检测
x1, y1 = pos1
x2, y2 = pos2
if (x1-x2)**2 + (y1-y2)**2 <= (r1+r2)**2:
return True
return False
def abs(n): # 取绝对值
if n >= 0:
return n
else:
return -n
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("多个球移动")
screen.fill((255, 255, 255))
pygame.display.flip()
# 初始求的信息
balls = [{"r": randint(10, 25),
"pos": (100, 100),
"color": (randint(0, 253), randint(1, 253), randint(1, 253)),
"x_speed": randint(-2, 2),
"y_speed": randint(-2, 2)}]
while True:
pygame.time.delay(10)
screen.fill((255, 255, 255))
index = 0
balls_temp = []
for ball_dict in balls[:]: # 将第一个球 从列表中取出来
r = ball_dict["r"]
color = ball_dict["color"]
x, y = ball_dict["pos"]
x_speed = ball_dict["x_speed"]
y_speed = ball_dict["y_speed"]
balls_temp.append(ball_dict) # 将已经取出的第一个球存入一个临时列表
for ball_dict2 in balls[:]: # 将第二个球从列表中取出来
if ball_dict2 not in balls_temp: # 判断第二球有没有在第一次循环中被取出。
pos2 = ball_dict2["pos"]
r2 = ball_dict2["r"]
if collision((x, y), pos2, r, r2): # 如果发生碰撞 删除掉半径小的球
print("碰撞到一起了")
if r2 <= r:
balls.remove(ball_dict2)
ball_dict["r"] = int((r2**2 + r**2)**0.5)
else:
balls.remove(ball_dict) # 如果第一个球是小球,就把第一个球删除掉
ball_dict2["r"] = int((r2**2 + r**2)**0.5)
break # 此处是重点!把第一个球删除掉后,一定要退出当前循环,不然后面如果还要删除这个球,就会出错!!!
if x + r >= 600: # 边界检测
x_speed = -abs(x_speed) # 边界检测满足条件,改变速度一定要用绝对值,不然球会在边界来回震动!
if x - r <= 0:
x_speed = abs(x_speed)
if y + r >= 400:
y_speed = -abs(y_speed)
if y - r <= 0:
y_speed = abs(y_speed)
x += x_speed; y += y_speed
pygame.draw.circle(screen, color, (x, y), r)
index += 1
ball_dict["pos"] = (x, y)
ball_dict["x_speed"] = x_speed
ball_dict["y_speed"] = y_speed
pygame.display.update()
for event in pygame.event.get(): # 每次循环检测有没有事件发生
if event.type == pygame.MOUSEBUTTONDOWN: # 每按一次鼠标 产生一个新的球
balls.append(
{"r": randint(10, 25),
"pos": event.pos,
"color": (randint(1, 253), randint(1, 254), randint(1, 253)),
"x_speed": randint(-2, 2),
"y_speed": randint(-2, 2)
})
if event.type == pygame.QUIT:
exit()
网友评论