大球吃小球
import pygame
import random
from math import sqrt
def rand_color():
return random.randint(0,255),random.randint(0,255),random.randint(0,255)
def crash(item1,item2):
item1x,item1y = item1['pos']
item2x,item2y = item2['pos']
dx = item2x- item1x
dy = item2y - item1y
dist = int(sqrt(dx*dx+dy*dy))
if dist<item1['r']+item2['r']:
if item2['r']>item1['r']:
item2['r']+=1
if item1 in all_balls[:]:
all_balls.remove(item1)
else:
item1['r']+=1
if item2 in all_balls[:]:
all_balls.remove(item2)
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((600,600))
screen.fill((123,123,20))
pygame.display.flip()
all_balls = []
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
ball ={
'r':random.randint(5,15),
'color':rand_color(),
'pos':event.pos,
'x_speed':random.randint(-3,3),
'y_speed':random.randint(-3,3)
}
all_balls.append(ball)
screen.fill((123, 123, 20))
for ball in all_balls:
# pygame.time.wait(2)
x,y = ball['pos']
x+=ball['x_speed']
y+=ball['y_speed']
if x + ball['r'] >= 600 or x -ball['r'] <= 0:
ball['x_speed'] *= -1
if y + ball['r'] >= 600 or y - ball['r'] <= 0:
ball['y_speed']*= -1
ball['pos'] = x,y
pygame.draw.circle(screen,ball['color'],(x,y),ball['r'])
pygame.display.update()
index = len(all_balls)
for item1 in all_balls:
for item2 in all_balls:
if item1!=item2:
crash(item1,item2)