美文网首页
Day12—作业

Day12—作业

作者: C0mpass | 来源:发表于2018-09-04 23:48 被阅读0次
    • pygame大球吃小球
    """__author__=Zeng"""
    import pygame
    from random import randint
    from math import sqrt
    from math import fabs
    
    if __name__ == '__main__':
        # 初始化游戏模块
        pygame.init()
        # 创建窗体
        window = pygame.display.set_mode((400, 600))
        window.fill((255, 255, 255))
    
        balls = []  # 创建一个列表来存放多个小球
        # 游戏运行
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    # 鼠标点下事件创建小球
                    ball = {
                            'color':(randint(0,255), randint(0,255), randint(0,255)),
                            'r':randint(10,20),
                            'pos':event.pos,
                            'x_speed':randint(-2,2),
                            'y_speed':randint(-2,2)
                    }
                    balls.append(ball)
            # 屏幕重覆盖
            window.fill((255, 255, 255))
            # 各个球相对位置判断
            for ball in balls:
                x,y = ball['pos']
                # 遍历其他球
                for ball1 in balls:
                    x1,y1 = ball1['pos']
                    # 如果两个球相撞,半径大的球吃掉半径小的球,而小球消失
                    if ball1['pos'] != ball['pos'] and sqrt((x-x1)**2+(y-y1)**2) < (ball['r']+ball1['r']):
                        # 球半径大的吸收半径小的,将小球销毁
                        if ball['r'] >= ball1['r']:
                            ball['r'] += ball1['r']
                            # 如果球的半径过大,将其销毁,改变为初始的任意球
                            if (x-ball['r'] <= 0 or x+ball['r'] >= 400) or (y-ball['r'] <= 0 or y+ball['r'] >= 600):
                                ball['r'] = randint(10,20)
                            balls.remove(ball1)
                x_speed = ball['x_speed']
                y_speed = ball['y_speed']
                x += x_speed
                y += y_speed
                # 越界判断,越界改变方向轴速度
                if x > 400 - ball['r']:
                    x = 400 - ball['r']
                    ball['x_speed'] = 0 - ball['x_speed']
                elif x < ball['r']:
                    x = ball['r']
                    ball['x_speed'] = 0 - ball['x_speed']
                if y > 600 - ball['r']:
                    y = 600 - ball['r']
                    ball['y_speed'] = 0 - ball['y_speed']
                elif y < ball['r']:
                    y = ball['r']
                    ball['y_speed'] = 0 - ball['y_speed']
                pygame.draw.circle(window,ball['color'],(x,y),ball['r'])
                # 更新球坐标
                ball['pos'] = x,y
            pygame.time.delay(10)
            pygame.display.flip()
    

    相关文章

      网友评论

          本文标题:Day12—作业

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