day12作业

import pygame
from random import randint

pygame.init()
screen=pygame.display.set_mode((700,500))
screen.fill((255,255,255))
pygame.display.set_caption('游戏事件')

def ran_color():
    return (randint(0,255),randint(0,255),randint(0,255))


pygame.display.flip()
balls=[]
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            exit()
        if event.type==pygame.MOUSEBUTTONDOWN:
        #鼠标点击事件

            ball={'color':ran_color(),
                  'pos':event.pos,
                  'x_speed':randint(-1,2),
                  'y_speed':randint(-1,2),
                  'r':randint(10,20)
                  }
            balls.append(ball)

    screen.fill((255,255,255))
    #刷新界面,不管你是否点击产生,都在不停地刷新

    for ball_dict in balls:
        # 遍历每一个球,x,y最开始是固定的,速度也是固定的,给加起来

        x,y=ball_dict['pos']
        x_speed=ball_dict['x_speed']
        y_speed=ball_dict['y_speed']
        x+=x_speed
        y+=y_speed

        ball_dict['pos']=x,y
        #改变后的位置从新赋回去

        #进行越界判断
        if x+ball_dict['r']>=700 or x<=ball_dict['r']:
            ball_dict['x_speed']*=-1
        elif y+ball_dict['r']>=500 or y<=ball_dict['r']:
            ball_dict['y_speed']*=-1


        #每个值即是每个球,每个球都要画出来
        pygame.draw.circle(screen,ball_dict['color'],ball_dict['pos'],ball_dict['r'])
    pygame.display.update()
    pygame.time.delay(10)

你可能感兴趣的:(day12作业)