当前位置:   article > 正文

【Pygame小游戏】确实会玩—教你如何在”吃豆豆“上完美躺赢……(收藏起来偷偷学)_吃豆豆python游戏

吃豆豆python游戏

导语

​昨晚玩起了小时候玩的游戏“吃豆豆”,但是我发现,一局游戏三条命,我根本不能吃完所有的豆豆,总是被敌人吃掉,

于是,我在想怎么能够保证我达到吃完所有豆豆的目标,然后我就想到了一个办法:

自己找资料找素材学习仿写了一款吃豆豆的小游戏,然后给我自己无限开挂!

哈哈哈!这不?完全解决了我的问题,完美的躺赢了!聪明的我.jpg

正文

一、首先

1)素材

首先找到吃豆豆游戏的界面按照上面的素材找找准备下相似的图片!如下:

2)环境

本文的环境都跟之前的差不多:Python3、Pycharm、Pygame模块。

  1. 模块安装:
  2. pip install -i https://pypi.douban.com/simple/ pygame

​二、正式开始

这款吃豆豆的小游戏:主要分为4块主要内容,分别是。Levels.py、Sprites.py、cfg.py、Game.py

1)配置文件:cfg.py

  1. import os
  2. '''定义一些颜色'''
  3. BLACK = (0, 0, 0)
  4. WHITE = (255, 255, 255)
  5. BLUE = (0, 0, 255)
  6. GREEN = (0, 255, 0)
  7. RED = (255, 0, 0)
  8. YELLOW = (255, 255, 0)
  9. PURPLE = (255, 0, 255)
  10. SKYBLUE = (0, 191, 255)
  11. '''游戏素材路径'''
  12. BGMPATH = os.path.join(os.getcwd(), 'resources/sounds/bg.mp3')
  13. ICONPATH = os.path.join(os.getcwd(), 'resources/images/icon.png')
  14. FONTPATH = os.path.join(os.getcwd(), 'resources/font/ALGER.TTF')
  15. HEROPATH = os.path.join(os.getcwd(), 'resources/images/pacman.png')
  16. BlinkyPATH = os.path.join(os.getcwd(), 'resources/images/Blinky.png')
  17. ClydePATH = os.path.join(os.getcwd(), 'resources/images/Clyde.png')
  18. InkyPATH = os.path.join(os.getcwd(), 'resources/images/Inky.png')
  19. PinkyPATH = os.path.join(os.getcwd(), 'resources/images/Pinky.png')

2)定义一些精灵类:Sprites.py

  1. import random
  2. import pygame
  3. '''墙类'''
  4. class Wall(pygame.sprite.Sprite):
  5. def __init__(self, x, y, width, height, color, **kwargs):
  6. pygame.sprite.Sprite.__init__(self)
  7. self.image = pygame.Surface([width, height])
  8. self.image.fill(color)
  9. self.rect = self.image.get_rect()
  10. self.rect.left = x
  11. self.rect.top = y
  12. '''食物类'''
  13. class Food(pygame.sprite.Sprite):
  14. def __init__(self, x, y, width, height, color, bg_color, **kwargs):
  15. pygame.sprite.Sprite.__init__(self)
  16. self.image = pygame.Surface([width, height])
  17. self.image.fill(bg_color)
  18. self.image.set_colorkey(bg_color)
  19. pygame.draw.ellipse(self.image, color, [0, 0, width, height])
  20. self.rect = self.image.get_rect()
  21. self.rect.left = x
  22. self.rect.top = y
  23. '''角色类'''
  24. class Player(pygame.sprite.Sprite):
  25. def __init__(self, x, y, role_image_path):
  26. pygame.sprite.Sprite.__init__(self)
  27. self.role_name = role_image_path.split('/')[-1].split('.')[0]
  28. self.base_image = pygame.image.load(role_image_path).convert()
  29. self.image = self.base_image.copy()
  30. self.rect = self.image.get_rect()
  31. self.rect.left = x
  32. self.rect.top = y
  33. self.prev_x = x
  34. self.prev_y = y
  35. self.base_speed = [30, 30]
  36. self.speed = [0, 0]
  37. self.is_move = False
  38. self.tracks = []
  39. self.tracks_loc = [0, 0]
  40. '''改变速度方向'''
  41. def changeSpeed(self, direction):
  42. if direction[0] < 0:
  43. self.image = pygame.transform.flip(self.base_image, True, False)
  44. elif direction[0] > 0:
  45. self.image = self.base_image.copy()
  46. elif direction[1] < 0:
  47. self.image = pygame.transform.rotate(self.base_image, 90)
  48. elif direction[1] > 0:
  49. self.image = pygame.transform.rotate(self.base_image, -90)
  50. self.speed = [direction[0] * self.base_speed[0], direction[1] * self.base_speed[1]]
  51. return self.speed
  52. '''更新角色位置'''
  53. def update(self, wall_sprites, gate_sprites):
  54. if not self.is_move:
  55. return False
  56. x_prev = self.rect.left
  57. y_prev = self.rect.top
  58. self.rect.left += self.speed[0]
  59. self.rect.top += self.speed[1]
  60. is_collide = pygame.sprite.spritecollide(self, wall_sprites, False)
  61. if gate_sprites is not None:
  62. if not is_collide:
  63. is_collide = pygame.sprite.spritecollide(self, gate_sprites, False)
  64. if is_collide:
  65. self.rect.left = x_prev
  66. self.rect.top = y_prev
  67. return False
  68. return True
  69. '''生成随机的方向'''
  70. def randomDirection(self):
  71. return random.choice([[-0.5, 0], [0.5, 0], [0, 0.5], [0, -0.5]])

3)定义关卡:Levels.py

  1. import pygame
  2. from .Sprites import *
  3. '''关卡数量'''
  4. NUMLEVELS = 1
  5. '''关卡一'''
  6. class Level1():
  7. def __init__(self):
  8. self.info = 'level1'
  9. '''创建墙'''
  10. def setupWalls(self, wall_color):
  11. self.wall_sprites = pygame.sprite.Group()
  12. wall_positions = [
  13. [0, 0, 6, 600], [0, 0, 600, 6], [0, 600, 606, 6], [600, 0, 6, 606], [300, 0, 6, 66], [60, 60, 186, 6],
  14. [360, 60, 186, 6], [60, 120, 66, 6], [60, 120, 6, 126], [180, 120, 246, 6], [300, 120, 6, 66],
  15. [480, 120, 66, 6], [540, 120, 6, 126], [120, 180, 126, 6], [120, 180, 6, 126], [360, 180, 126, 6],
  16. [480, 180, 6, 126], [180, 240, 6, 126], [180, 360, 246, 6], [420, 240, 6, 126], [240, 240, 42, 6],
  17. [324, 240, 42, 6], [240, 240, 6, 66], [240, 300, 126, 6], [360, 240, 6, 66], [0, 300, 66, 6],
  18. [540, 300, 66, 6], [60, 360, 66, 6], [60, 360, 6, 186], [480, 360, 66, 6], [540, 360, 6, 186],
  19. [120, 420, 366, 6], [120, 420, 6, 66], [480, 420, 6, 66], [180, 480, 246, 6], [300, 480, 6, 66],
  20. [120, 540, 126, 6], [360, 540, 126, 6]
  21. ]
  22. for wall_position in wall_positions:
  23. wall = Wall(*wall_position, wall_color)
  24. self.wall_sprites.add(wall)
  25. return self.wall_sprites
  26. '''创建门'''
  27. def setupGate(self, gate_color):
  28. self.gate_sprites = pygame.sprite.Group()
  29. self.gate_sprites.add(Wall(282, 242, 42, 2, gate_color))
  30. return self.gate_sprites
  31. '''创建角色'''
  32. def setupPlayers(self, hero_image_path, ghost_images_path):
  33. self.hero_sprites = pygame.sprite.Group()
  34. self.ghost_sprites = pygame.sprite.Group()
  35. self.hero_sprites.add(Player(287, 439, hero_image_path))
  36. for each in ghost_images_path:
  37. role_name = each.split('/')[-1].split('.')[0]
  38. if role_name == 'Blinky':
  39. player = Player(287, 199, each)
  40. player.is_move = True
  41. player.tracks = [
  42. [0, -0.5, 4], [0.5, 0, 9], [0, 0.5, 11], [0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 11], [0, 0.5, 3],
  43. [0.5, 0, 15], [0, -0.5, 15], [0.5, 0, 3], [0, -0.5, 11], [-0.5, 0, 3], [0, -0.5, 11], [-0.5, 0, 3],
  44. [0, -0.5, 3], [-0.5, 0, 7], [0, -0.5, 3], [0.5, 0, 15], [0, 0.5, 15], [-0.5, 0, 3], [0, 0.5, 3],
  45. [-0.5, 0, 3], [0, -0.5, 7], [-0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 11], [0, -0.5, 7], [0.5, 0, 5]
  46. ]
  47. self.ghost_sprites.add(player)
  48. elif role_name == 'Clyde':
  49. player = Player(319, 259, each)
  50. player.is_move = True
  51. player.tracks = [
  52. [-1, 0, 2], [0, -0.5, 4], [0.5, 0, 5], [0, 0.5, 7], [-0.5, 0, 11], [0, -0.5, 7],
  53. [-0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 7], [0, 0.5, 15], [0.5, 0, 15], [0, -0.5, 3],
  54. [-0.5, 0, 11], [0, -0.5, 7], [0.5, 0, 3], [0, -0.5, 11], [0.5, 0, 9]
  55. ]
  56. self.ghost_sprites.add(player)
  57. elif role_name == 'Inky':
  58. player = Player(255, 259, each)
  59. player.is_move = True
  60. player.tracks = [
  61. [1, 0, 2], [0, -0.5, 4], [0.5, 0, 10], [0, 0.5, 7], [0.5, 0, 3], [0, -0.5, 3],
  62. [0.5, 0, 3], [0, -0.5, 15], [-0.5, 0, 15], [0, 0.5, 3], [0.5, 0, 15], [0, 0.5, 11],
  63. [-0.5, 0, 3], [0, -0.5, 7], [-0.5, 0, 11], [0, 0.5, 3], [-0.5, 0, 11], [0, 0.5, 7],
  64. [-0.5, 0, 3], [0, -0.5, 3], [-0.5, 0, 3], [0, -0.5, 15], [0.5, 0, 15], [0, 0.5, 3],
  65. [-0.5, 0, 15], [0, 0.5, 11], [0.5, 0, 3], [0, -0.5, 11], [0.5, 0, 11], [0, 0.5, 3], [0.5, 0, 1]
  66. ]
  67. self.ghost_sprites.add(player)
  68. elif role_name == 'Pinky':
  69. player = Player(287, 259, each)
  70. player.is_move = True
  71. player.tracks = [
  72. [0, -1, 4], [0.5, 0, 9], [0, 0.5, 11], [-0.5, 0, 23], [0, 0.5, 7], [0.5, 0, 3],
  73. [0, -0.5, 3], [0.5, 0, 19], [0, 0.5, 3], [0.5, 0, 3], [0, 0.5, 3], [0.5, 0, 3],
  74. [0, -0.5, 15], [-0.5, 0, 7], [0, 0.5, 3], [-0.5, 0, 19], [0, -0.5, 11], [0.5, 0, 9]
  75. ]
  76. self.ghost_sprites.add(player)
  77. return self.hero_sprites, self.ghost_sprites
  78. '''创建食物'''
  79. def setupFood(self, food_color, bg_color):
  80. self.food_sprites = pygame.sprite.Group()
  81. for row in range(19):
  82. for col in range(19):
  83. if (row == 7 or row == 8) and (col == 8 or col == 9 or col == 10):
  84. continue
  85. else:
  86. food = Food(30 * col + 32, 30 * row + 32, 4, 4, food_color, bg_color)
  87. is_collide = pygame.sprite.spritecollide(food, self.wall_sprites, False)
  88. if is_collide:
  89. continue
  90. is_collide = pygame.sprite.spritecollide(food, self.hero_sprites, False)
  91. if is_collide:
  92. continue
  93. self.food_sprites.add(food)
  94. return self.food_sprites

4)主程序Game.py

  1. import sys
  2. import cfg
  3. import pygame
  4. import modules.Levels as Levels
  5. '''开始某一关游戏'''
  6. def startLevelGame(level, screen, font):
  7. clock = pygame.time.Clock()
  8. SCORE = 0
  9. wall_sprites = level.setupWalls(cfg.SKYBLUE)
  10. gate_sprites = level.setupGate(cfg.WHITE)
  11. hero_sprites, ghost_sprites = level.setupPlayers(cfg.HEROPATH, [cfg.BlinkyPATH, cfg.ClydePATH, cfg.InkyPATH, cfg.PinkyPATH])
  12. food_sprites = level.setupFood(cfg.YELLOW, cfg.WHITE)
  13. is_clearance = False
  14. while True:
  15. for event in pygame.event.get():
  16. if event.type == pygame.QUIT:
  17. sys.exit(-1)
  18. pygame.quit()
  19. if event.type == pygame.KEYDOWN:
  20. if event.key == pygame.K_LEFT:
  21. for hero in hero_sprites:
  22. hero.changeSpeed([-1, 0])
  23. hero.is_move = True
  24. elif event.key == pygame.K_RIGHT:
  25. for hero in hero_sprites:
  26. hero.changeSpeed([1, 0])
  27. hero.is_move = True
  28. elif event.key == pygame.K_UP:
  29. for hero in hero_sprites:
  30. hero.changeSpeed([0, -1])
  31. hero.is_move = True
  32. elif event.key == pygame.K_DOWN:
  33. for hero in hero_sprites:
  34. hero.changeSpeed([0, 1])
  35. hero.is_move = True
  36. if event.type == pygame.KEYUP:
  37. if (event.key == pygame.K_LEFT) or (event.key == pygame.K_RIGHT) or (event.key == pygame.K_UP) or (event.key == pygame.K_DOWN):
  38. hero.is_move = False
  39. screen.fill(cfg.BLACK)
  40. for hero in hero_sprites:
  41. hero.update(wall_sprites, gate_sprites)
  42. hero_sprites.draw(screen)
  43. for hero in hero_sprites:
  44. food_eaten = pygame.sprite.spritecollide(hero, food_sprites, True)
  45. SCORE += len(food_eaten)
  46. wall_sprites.draw(screen)
  47. gate_sprites.draw(screen)
  48. food_sprites.draw(screen)
  49. for ghost in ghost_sprites:
  50. # 幽灵随机运动(效果不好且有BUG)
  51. '''
  52. res = ghost.update(wall_sprites, None)
  53. while not res:
  54. ghost.changeSpeed(ghost.randomDirection())
  55. res = ghost.update(wall_sprites, None)
  56. '''
  57. # 指定幽灵运动路径
  58. if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:
  59. ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
  60. ghost.tracks_loc[1] += 1
  61. else:
  62. if ghost.tracks_loc[0] < len(ghost.tracks) - 1:
  63. ghost.tracks_loc[0] += 1
  64. elif ghost.role_name == 'Clyde':
  65. ghost.tracks_loc[0] = 2
  66. else:
  67. ghost.tracks_loc[0] = 0
  68. ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
  69. ghost.tracks_loc[1] = 0
  70. if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:
  71. ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
  72. else:
  73. if ghost.tracks_loc[0] < len(ghost.tracks) - 1:
  74. loc0 = ghost.tracks_loc[0] + 1
  75. elif ghost.role_name == 'Clyde':
  76. loc0 = 2
  77. else:
  78. loc0 = 0
  79. ghost.changeSpeed(ghost.tracks[loc0][0: 2])
  80. ghost.update(wall_sprites, None)
  81. ghost_sprites.draw(screen)
  82. score_text = font.render("Score: %s" % SCORE, True, cfg.RED)
  83. screen.blit(score_text, [10, 10])
  84. if len(food_sprites) == 0:
  85. is_clearance = True
  86. break
  87. if pygame.sprite.groupcollide(hero_sprites, ghost_sprites, False, False):
  88. is_clearance = False
  89. break
  90. pygame.display.flip()
  91. clock.tick(10)
  92. return is_clearance
  93. '''显示文字'''
  94. def showText(screen, font, is_clearance, flag=False):
  95. clock = pygame.time.Clock()
  96. msg = 'Game Over!' if not is_clearance else 'Congratulations, you won!'
  97. positions = [[235, 233], [65, 303], [170, 333]] if not is_clearance else [[145, 233], [65, 303], [170, 333]]
  98. surface = pygame.Surface((400, 200))
  99. surface.set_alpha(10)
  100. surface.fill((128, 128, 128))
  101. screen.blit(surface, (100, 200))
  102. texts = [font.render(msg, True, cfg.WHITE),
  103. font.render('Press ENTER to continue or play again.', True, cfg.WHITE),
  104. font.render('Press ESCAPE to quit.', True, cfg.WHITE)]
  105. while True:
  106. for event in pygame.event.get():
  107. if event.type == pygame.QUIT:
  108. sys.exit()
  109. pygame.quit()
  110. if event.type == pygame.KEYDOWN:
  111. if event.key == pygame.K_RETURN:
  112. if is_clearance:
  113. if not flag:
  114. return
  115. else:
  116. main(initialize())
  117. else:
  118. main(initialize())
  119. elif event.key == pygame.K_ESCAPE:
  120. sys.exit()
  121. pygame.quit()
  122. for idx, (text, position) in enumerate(zip(texts, positions)):
  123. screen.blit(text, position)
  124. pygame.display.flip()
  125. clock.tick(10)
  126. '''初始化'''
  127. def initialize():
  128. pygame.init()
  129. icon_image = pygame.image.load(cfg.ICONPATH)
  130. pygame.display.set_icon(icon_image)
  131. screen = pygame.display.set_mode([606, 606])
  132. pygame.display.set_caption('吃豆豆小游戏')
  133. return screen
  134. '''主函数'''
  135. def main(screen):
  136. pygame.mixer.init()
  137. pygame.mixer.music.load(cfg.BGMPATH)
  138. pygame.mixer.music.play(-1, 0.0)
  139. pygame.font.init()
  140. font_small = pygame.font.Font(cfg.FONTPATH, 18)
  141. font_big = pygame.font.Font(cfg.FONTPATH, 24)
  142. for num_level in range(1, Levels.NUMLEVELS+1):
  143. level = getattr(Levels, f'Level{num_level}')()
  144. is_clearance = startLevelGame(level, screen, font_small)
  145. if num_level == Levels.NUMLEVELS:
  146. showText(screen, font_big, is_clearance, True)
  147. else:
  148. showText(screen, font_big, is_clearance)
  149. '''run'''
  150. if __name__ == '__main__':
  151. main(initialize())

如需完整的源码主页源码基地免费领取啦~

三、效果展示

1)视频展示——

Python小游戏之如何在“吃豆豆”小游戏中赢得胜利?

2)截图展示——

总结

童年的吃豆豆游戏,用Python找回来!如果有帮助到你,记得三连哦~哈哈哈!

关注小编,获取更多精彩内容啦~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/168175

推荐阅读
相关标签