用pygame如何做一个接球小游戏?
发布时间:2022-01-20 16:20:44 所属栏目:语言 来源:互联网
导读:一些朋友应该有玩过接球小游戏吧,也就是通过左右移动一个滑块来接住下落小球,然后小球反弹,再接住小球,再反弹,如此重复获得分数。那么我们如果使用pygame,怎么写一个接球小游戏呢?下面就给大家分享用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() (编辑:桂林站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |