大球吃小球

2018-07-31  本文已影响0人  蘑菇plus
# encoding = utf - 8
# Time: 2018 / 7 / 26
# 20: 23
# Author: 蘑菇plus
# Email: 497392071 @ qq.com
# File: 显示图形.py
# Software: PyCharm
import pygame
import random
from math import sqrt
from random import randint
all_balls=[]
def random_color():
    return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

if __name__ == '__main__':
     pygame.init()
     screen=pygame.display.set_mode((600,400))
     screen.fill((255,255,255))
     pygame.display.flip()
     while True:
         pygame.time.Clock().tick(60)
         for event in pygame.event.get():
            if event.type==pygame.QUIT:
                exit()
         #点击鼠标创建一个球
            if event.type==pygame.MOUSEBUTTONDOWN:
             ball={
                 'r':randint(10,35),
                 'place':screen,
                 'color':random_color(),
                 'pos':event.pos,
                 'x_speed':random.randint(-3,3),
                 'y_speed':random.randint(-3,3)
             }
             all_balls.append(ball)
         #刷新屏幕
         screen.fill((255, 255, 255))
         #取出字典里存储的球的数据
         for ball in all_balls:
             x,y=ball['pos']
             x_speed=ball['x_speed']
             y_speed=ball['y_speed']
             r=ball['r']
         #确定圆是否还在界面内
             if x + ball['r'] >= 600:
                 x = 600 - ball['r']
                 x_speed *= -1
             if x - ball['r'] <= 0:
                 x = 0 + ball['r']
                 x_speed *= -1
             if y - ball['r'] <= 0:
                 y = 0 + ball['r']
                 y_speed *= -1
             if y + ball['r'] >= 400:
                 y = 400 - ball['r']
                 y_speed *= -1
             x+=x_speed
             y+=y_speed
         #画圆
             pygame.draw.circle(screen,ball['color'],(x,y), ball['r'])
             #更新球的数据
             ball['pos']=x,y
             ball['x_speed']=x_speed
             ball['y_speed']=y_speed


             for ball2 in all_balls:
                if all_balls.index(ball)==all_balls.index(ball2):
                    pass
                else:
                    x2,y2=ball2['pos']
                    distance=sqrt((x-x2)**2+(y-y2)**2)
                    if distance<=ball['r']+ball2['r']:
                        ball['r']=int(ball['r']+ball2['r']/3)
                        all_balls.remove(ball2)
         pygame.display.update()
上一篇下一篇

猜你喜欢

热点阅读