美文网首页
day12作业

day12作业

作者: 上邪5415 | 来源:发表于2018-09-05 08:40 被阅读0次

    用pygame编写多个球各自移动,两球相撞互相反弹,球碰到边界反弹,球通过点击屏幕产生。

    import pygame
    import random
    pygame.init()
    window = pygame.display.set_mode((400, 600))
    window.fill((255, 255, 255))
    pygame.display.flip()
    circle_list = []
    ball_list = [] #接触的球列表
    while True:
        pygame.time.delay(10)
        window.fill((255, 255, 255))
        for item in circle_list:
            pygame.draw.circle(window, item['color:'], (item['circle_x:'], item['circle_y:']), 20, 0)
            item['circle_x:'] += item['x_speed:']
            item['circle_y:'] += item['y_speed:']
            if 20<item['circle_x:']<380 and 20<item['circle_y:']<580:
                for other in circle_list:
                    if ((item['circle_x:']-other['circle_x:'])**2+(item['circle_y:']-other['circle_y:'])**2)**0.5<=40 and item !=other :
                        item['x_speed:'] *= -1
                        item['y_speed:'] *= -1
                        break
            if item['circle_x:']< 20 :
                item['circle_x:'] = 20
                item['x_speed:'] *= -1
            if item['circle_x:']> 380 :
                item['circle_x:'] = 380
                item['x_speed:'] *= -1
            if item['circle_y:']< 20 :
                item['circle_y:'] = 20
                item['y_speed:'] *= -1
            if item['circle_y:']> 580 :
                item['circle_y:'] = 580
                item['y_speed:'] *= -1
    
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
                x, y = event.pos
                count = 0
                for item in circle_list:
                    if  ((item['circle_x:']-x)**2+(item['circle_y:']-y)**2)**0.5<=40:
                        count = 1
                if count == 1:
                    continue
                list1 = [-2,-1,1,2]
                x_speed = list1[random.randint(0,3)]
                y_speed = list1[random.randint(0,3)]
                if  20<=x<380 and 20<y<580:
                    circle_dict = {'color:':color,'circle_x:': x, 'circle_y:': y,'x_speed:':x_speed,'y_speed:':y_speed}
                    circle_list.append(circle_dict)
    
    

    相关文章

      网友评论

          本文标题:day12作业

          本文链接:https://www.haomeiwen.com/subject/qupowftx.html