day12-大球吃小球

import pygame
from random import randint

if __name__ == '__main__':
    pygame.init()
    window = pygame.display.set_mode((1000,600))
    window.fill((255,255,255))
    pygame.display.flip()
    ball_list = [] #{'ball_x':x,'ball_y':y,'speed':randint(1,3),'color':color,'radius':radius2}
    while True:
        # 不断的画圆
        pygame.time.delay(10) #延迟10毫秒
        window.fill((255,255,255)) #填白,将之前的界面中的球填充
        for item in ball_list:
            pygame.draw.circle(window,item['color'],(item['ball_x'],item['ball_y']),item['radius']) #画球
            if item['ball_x'] < item['radius'] or item['ball_x'] > 1000-item['radius']: #触碰边界反向
                item['speed'][0] *= -1
            if item['ball_y'] < item['radius'] or item['ball_y'] > 600-item['radius']:#触屏边界方向
                item['speed'][1] *= -1
            item['ball_x'] += item['speed'][0]
            item['ball_y'] += item['speed'][1]

            for item2 in ball_list:
                if item == item2:
                    pass
                else:

                    if (item['ball_x'] - item2['ball_x']) ** 2 + \
                            (item['ball_y'] - item2['ball_y']) ** 2 <= (item['radius'] + item2['radius']) ** 2:
                        if item['radius'] == item2['radius']: #改变一个球的方向即可,相同的球撞开
                            item['speed'][0] = -item['speed'][0]
                            item['speed'][1] = -item['speed'][1]

                        if item['radius'] > item2['radius']:#大球吃小球
                            if item['radius'] + int(item2['radius']/5) <= 100:
                                item['radius'] = item['radius'] + int(item2['radius']/5)
                                ball_list.remove(item2)
                            else:#球最大100
                                item['radius'] = 100
                                ball_list.remove(item2)

        pygame.display.update() #更新界面
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                x,y = event.pos
                color = (randint(0,255),randint(0,255),randint(0,255)) #随机取颜色球
                radius2 = randint(10,20) #随机取半径
                pygame.draw.circle(window, color, (x, y), radius2)  # 画球
                ball_dict = {'ball_x':x,'ball_y':y,'speed':[randint(1,3),randint(1,3)],'color':color,'radius':radius2}
                ball_list.append(ball_dict)#

你可能感兴趣的:(day12-大球吃小球)