作业1:
"""__author__=xx"""
import pygame
from random import randint
from math import sqrt,fabs
# 写一个函数,判断两个球是否相遇
def is_ball_meet(ball_1, ball_2):
x1, y1 = ball_1['pos']
r1 = ball_1['r']
x2, y2 = ball_2['pos']
r2 = ball_2['r']
if (r1 + r2) > sqrt((x1-x2)**2 + (y1-y2)**2):
return True
return False
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((254,254,254))
pygame.display.flip()
# all_balls中保存多个球
# 每个球要保存:半径、圆心、颜色、x速度、y速度
all_balls = []
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
ball_dict1 = {'r':randint(10,30), 'pos':event.pos, 'color':(randint(1,255),randint(1,255),randint(1,255)), 'x_speed':randint(-5,5), 'y_speed':randint(-5,5)}
all_balls.append(ball_dict1)
# 刷新界面
screen.fill((254,254,254))
pygame.time.delay(100)
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
r = ball_dict['r']
if 2 * r > 400:
print('游戏结束')
exit()
if x - r <= 0:
x = r
x_speed = int(fabs(x_speed))
if x + r >= 600:
x = 600 - r
x_speed = -int(fabs(x_speed))
if y - r <= 0:
y = r
y_speed = int(fabs(y_speed))
if y + r >= 400:
y = 400 - r
y_speed = -int(fabs(y_speed))
pygame.draw.circle(screen,ball_dict['color'],(x,y),r)
# 更新球对应的坐标
ball_dict['pos'] = x,y
ball_dict['x_speed'] = x_speed
ball_dict['y_speed'] = y_speed
if (len(all_balls) > 1):
all_balls1 = []
for item in all_balls:
all_balls1.append(item)
for item1 in all_balls:
if item1 not in all_balls1:
if is_ball_meet(item, item1):
item['r'] += item1['r']
all_balls.remove(item1)
# if (len(all_balls) > 1):
# index_list = []
# for index1 in range(len(all_balls)):
# for index2 in range(index1+1, len(all_balls)):
# if is_ball_meet(all_balls[index1], all_balls[index2]):
# index_list.append(index1)
# all_balls[index2]['r'] += all_balls[index1]['r']
# for index3 in index_list:
# del all_balls[index3]
pygame.display.flip()