大球吃小球-pygame
2018-07-30 本文已影响0人
KingJX
"""
大球吃小球
"""
import pygame
import random
from math import sqrt
from random import randint
def ball_color():
return randint(0,255),randint(0,255),randint(0,255)
all_balls = []
radius = 'radius'
center = 'pos'
color = 'color'
x_speed = 'x_speed'
y_speed = 'y_speed'
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((800,600))
screen.fill((255,255,255))
pygame.display.flip()
while True:
pygame.time.delay(5)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
ball = {radius:randint(10,25), center:event.pos, color: ball_color(),x_speed:randint(-2,2),y_speed:randint(-2,2)}
all_balls.append(ball)
screen.fill((255,255,255))
for ball_dict in all_balls:
x, y = ball_dict[center]
x_speed1 = ball_dict[x_speed]
y_speed1 = ball_dict[y_speed]
x += x_speed1
y += y_speed1
if x + ball_dict[radius] >= 800:
x = 800 - ball_dict[radius]
x_speed1 *= -1
if x - ball_dict[radius] <= 0:
x = ball_dict[radius]
x_speed1 *= -1
if y + ball_dict[radius] >= 600:
y = 600 - ball_dict[radius]
y_speed1 *= -1
if y - ball_dict[radius] <= 0:
y = ball_dict[radius]
y_speed1 *= -1
a = all_balls[:]
for index1 in all_balls:
for index2 in all_balls:
if index1 == index2:
continue
else:
x1,y1 = index1[center]
x2,y2 = index2[center]
if sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) < index1[radius]+index2[radius]:
if index1[radius] < index2[radius]:
index2[radius] += index1[radius]
all_balls.remove(index1)
else:
index1[radius] += index2[radius]
all_balls.remove(index2)
pygame.draw.circle(screen, ball_dict[color], (x, y), ball_dict[radius])
ball_dict[center] = x, y
ball_dict[x_speed] = x_speed1
ball_dict[y_speed] = y_speed1
pygame.display.update()
大球吃小球.png