import pygame
from random import randint
from math import sqrt
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((600,400))
screen.fill((255, 255, 255))
pygame.display.set_caption('球球球')
pygame.display.flip()
# all_balls中保存多个球
# 每个球要保存:半径、圆心坐标、颜色、x速度、y速度
all_balls = [
# {
# 'r': randint(10, 20),
# 'pos': (100, 100),
# 'color':random_color,
# 'x_speed': randint(-3, 3),
# 'y_speed': randint(-3, 3),
# }
]
while True:
random_color = randint(0, 255), randint(0, 255), randint(0, 255)
pygame.time.delay(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
# 点一下鼠标创建一个球
ball = {
'r': randint(10, 25),
'pos': event.pos,
'color': random_color,
'x_speed': randint(-3, 3),
'y_speed': randint(-3, 3)
}
# 保存球
all_balls.append(ball)
#刷新界面
screen.fill((255, 255, 255))
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']
# 球碰到边界弹回
if x + ball_dict['r'] >= 600:
x = 600 - ball_dict['r']
x_speed *= -1
if x <= ball_dict['r']:
x = ball_dict['r']
x_speed *= -1
if y + ball_dict['r'] >= 400:
y = 400 - ball_dict['r']
y_speed *= -1
if y <= ball_dict['r']:
y = ball_dict['r']
y_speed *= -1
x += x_speed
y += y_speed
pygame.draw.circle(screen, ball_dict['color'], (x, y), ball_dict['r'])
# 更新球对应的坐标
ball_dict['pos'] = x, y
ball_dict['x_speed'] = x_speed
ball_dict['y_speed'] = y_speed
# 遍历第二个球
for two_ball in all_balls:
if all_balls.index(ball_dict) == all_balls.index(two_ball):
pass
else:
one_ball_x, one_ball_y = ball_dict['pos']
two_ball_x, two_ball_y = two_ball['pos']
new_R = ball_dict['r'] + two_ball['r']
new_X = (one_ball_x - two_ball_x) ** 2
new_Y = (one_ball_y - two_ball_y) ** 2
# 判断两个球之间的距离
if sqrt(new_X + new_Y) <= new_R:
if ball_dict['r'] >= two_ball['r']:
ball_dict['r'] = ball_dict['r'] + two_ball['r']
all_balls.remove(two_ball)
pygame.display.update()
球球球
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 野球场,是讲规矩的。 野球场的人,都是有故事的。 1 在野球场子里,判断力是真的很重要的一件事情。有时候你看着一个...