脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - pygame实现滑块接小球游戏

pygame实现滑块接小球游戏

2021-12-02 10:58靠谱的人 Python

这篇文章主要为大家详细介绍了pygame实现滑块接小球游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

先上图

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精灵类的时候,才是常规的用法,也会有更加严禁的碰撞计算方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_43085185/article/details/117844288

延伸 · 阅读

精彩推荐