day11-作业

2018-07-30  本文已影响0人  七一欧

代码:

"""qiyiou"""
import pygame
import random
import math


# random_color = 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()

   # all_balls中保存多个球
   # 每个球要保存:半径、圆心坐标、颜色、x速度、y速度
   random_color = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

   all_balls = [
       {'r':random.randint(10,20),
        'pos':(100,100),
        'color':random_color,
        'x_speed':random.randint(-1,1),
        'y_speed': random.randint(-1, 1)
        },
       {'r': random.randint(10, 20),
        'pos': (100, 100),
        'color': random_color,
        'x_speed': random.randint(-1, 1),
        'y_speed': random.randint(-1, 1)
        }
   ]


   while True:
       random_color = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

       for event in pygame.event.get():
           if event.type == pygame.QUIT:
               exit()

           if event.type == pygame.MOUSEBUTTONDOWN:
               ball = {
                   'r':random.randint(10,20),
                   'pos':event.pos,
                   'color':random_color,
                   'x_speed':random.randint(-3,3),
                   'y_speed':random.randint(-3,3)
               }
       #     保存球
               all_balls.append(ball)


       # 刷新界面
       screen.fill((255,255,255))


       for ball1_dict in all_balls:
           # 取出原来的x坐标和y坐标以及他们的速度
           x1,y1 = ball1_dict['pos']
           x_speed = ball1_dict['x_speed']
           y_speed = ball1_dict['y_speed']
           ball1_r = ball1_dict['r']
           if x1+ball1_r >= 600:
               x_speed *= -1
           if x1-ball1_r <= 0:
               x_speed *= -1
           if y1+ball1_r >= 400:
               y_speed *= -1
           if y1-ball1_r<= 0:
               y_speed *= -1

           x1 += x_speed
           y1 += y_speed


           pygame.draw.circle(screen,ball1_dict['color'],(x1,y1),ball1_dict['r'])
           pygame.time.delay(5)
           # 更新球对应的坐标
           ball1_dict['pos'] = x1,y1
           # 更新球对应的速度
           ball1_dict['x_speed'] = x_speed
           ball1_dict['y_speed'] = y_speed

           for ball2_dict in all_balls:
               if all_balls.index(ball1_dict) == all_balls.index(ball2_dict):
                   pass
               else:
                   x2,y2 = ball2_dict['pos']#取ball2坐标
                   ball2_r =  ball2_dict['r'] #取ball2半径

                   a = (x1-x2)**2+(y1-y2)**2
                   if math.sqrt(a) <= (ball1_r+ball2_r):
                       if ball1_r >= ball2_r:
                           ball1_dict['r'] =  ball1_dict['r'] + ball2_dict['r']
                           all_balls.remove(ball2_dict)


       pygame.display.update()


结果:

上一篇下一篇

猜你喜欢

热点阅读