当前位置 博文首页 > pygame实现滑块接小球游戏

    pygame实现滑块接小球游戏

    作者:靠谱的人 时间:2021-08-01 18:32

    用pygame做一个滑块接小球的游戏,供大家参考,具体内容如下

    先上图

    游戏很简单也很弱智,主要用到了pygame画圆,画方块,随机数等,可以锻炼基本的鼠标控制,游戏设计思维,简单地碰撞判断等,废话不多说,上代码

    写之前,先思考能用到哪些参数

    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    # 生命和得分
    lives = 3
    score = 0
    # 设置颜色
    white = 255, 255, 255
    yellow = 255, 255, 0
    black = 0, 0, 0
    red = 220, 50, 50
    # 设置字体
    font = pygame.font.Font(None, 38)
    pygame.mouse.set_visible(False)
    game_over = True
    # 设置鼠标坐标及鼠标事件参数
    # 鼠标坐标
    mouse_x = mouse_y = 0
    # 滑板坐标
    pos_x = 300
    pos_y = 580
    # 球坐标
    ball_x = random.randint(0, 500)
    ball_y = -50
    # 球半径
    radius = 30
    # 下落速度
    vel = 0.5
    
    def print_text(font, x, y, text, color=white):
        imgText = font.render(text, True, color)
        screen.blit(imgText, (x, y))

    解释下:

    game_over一开始设置为True 是因为开局先停止,等鼠标点击后再开始,这也用到当死了以后,从新开始游戏
    pygame.mouse.set_visible(False)是让鼠标不可见

    然后是游戏主体部分

    # 主循环
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            elif event.type == pygame.MOUSEMOTION:
                mouse_x, mouse_y = event.pos
                move_x, move_y = event.rel
            elif event.type == pygame.MOUSEBUTTONDOWN:
                lives = 3
                score = 0
                game_over = False
    
        keys = pygame.key.get_pressed()
        if keys[K_ESCAPE]:
            exit()
    
        screen.fill((0, 0, 10))
    
        if game_over:
            print_text(font, 220, 300, "Press MouseButton To Start", white)
        else:
            # 球落到了地上
            if ball_y > 600:
                ball_y = -50
                ball_x = random.randint(0, 800)
                lives -= 1
                if lives == 0:
                    game_over = True
            # 球被滑板接住了
            elif pos_y < ball_y and pos_x < ball_x < pos_x + 120:
                score += 10
                ball_y = -50
                ball_x = random.randint(0, 800)
            # 既没有落地上也没被接住的时候,则不断增加y坐标数值使球从顶部落下
            else:
                ball_y += vel
                ball_pos = int(ball_x), int(ball_y)
                pygame.draw.circle(screen, yellow, ball_pos, radius, 0)
    
            # 滑板不要划出边界
            pos_x = mouse_x
            if pos_x < 0:
                pos_x = 0
            elif pos_x > 700:
                pos_x = 700
    
            # 画滑板并跟随鼠标左右移动
            pygame.draw.rect(screen, white, (pos_x, 580, 100, 20), 0)
            print_text(font, 50, 0, "Score: " + str(score), red)
            print_text(font, 650, 0, "Lives:" + str(lives), red)
    
        pygame.display.update()

    基本思路是,当球落到屏幕最下边,或者碰到了滑块,则通过给球的y坐标赋值,让球重新回到最上边去。
    当球的y坐标大于滑块的y坐标,即球下落到滑块的高度,同时球的x坐标又在滑块的x坐标范围内,则视为碰撞,球依然回到顶上去。
    游戏很简单,逻辑也很简单。
    这是基本思路,以后用到sprite精灵类的时候,才是常规的用法,也会有更加严禁的碰撞计算方法。

    jsjbwy
    下一篇:没有了