• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

pygame实现滑块接小球游戏

python 搞代码 4年前 (2022-01-08) 22次浏览 已收录 0个评论

这篇文章主要为大家详细介绍了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 = mous<a style="color:transparent">来源gao*daima.com搞@代#码网</a>e_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  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精灵类的时候,才是常规的用法,也会有更加严禁的碰撞计算方法。

以上就是pygame实现滑块接小球游戏的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:pygame实现滑块接小球游戏

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址