当前位置:   article > 正文

python实现超级玛丽小游戏(动图演示+源码分享)

python实现超级玛丽小游戏(动图演示+源码分享)
大家好,我是梦执,对梦执着。希望能和大家共同进步!

下面给大家带来python实现超级玛丽小游戏的源码分享

效果演示:
d61f3f0576034af9a5345be6da56e1ce.gif#pic_center

 

1.基础设置(tools部分)

这个部分设置马里奥以及游戏中蘑菇等怪的的移动设置。

  1. import os
  2. import pygame as pg
  3. keybinding = {
  4. 'action':pg.K_s,
  5. 'jump':pg.K_a,
  6. 'left':pg.K_LEFT,
  7. 'right':pg.K_RIGHT,
  8. 'down':pg.K_DOWN
  9. }
  10. class Control(object):
  11. """Control class for entire project. Contains the game loop, and contains
  12. the event_loop which passes events to States as needed. Logic for flipping
  13. states is also found here."""
  14. def __init__(self, caption):
  15. self.screen = pg.display.get_surface()
  16. self.done = False
  17. self.clock = pg.time.Clock()
  18. self.caption = caption
  19. self.fps = 60
  20. self.show_fps = False
  21. self.current_time = 0.0
  22. self.keys = pg.key.get_pressed()
  23. self.state_dict = {}
  24. self.state_name = None
  25. self.state = None
  26. def setup_states(self, state_dict, start_state):
  27. self.state_dict = state_dict
  28. self.state_name = start_state
  29. self.state = self.state_dict[self.state_name]
  30. def update(self):
  31. self.current_time = pg.time.get_ticks()
  32. if self.state.quit:
  33. self.done = True
  34. elif self.state.done:
  35. self.flip_state()
  36. self.state.update(self.screen, self.keys, self.current_time)
  37. def flip_state(self):
  38. previous, self.state_name = self.state_name, self.state.next
  39. persist = self.state.cleanup()
  40. self.state = self.state_dict[self.state_name]
  41. self.state.startup(self.current_time, persist)
  42. self.state.previous = previous
  43. def event_loop(self):
  44. for event in pg.event.get():
  45. if event.type == pg.QUIT:
  46. self.done = True
  47. elif event.type == pg.KEYDOWN:
  48. self.keys = pg.key.get_pressed()
  49. self.toggle_show_fps(event.key)
  50. elif event.type == pg.KEYUP:
  51. self.keys = pg.key.get_pressed()
  52. self.state.get_event(event)
  53. def toggle_show_fps(self, key):
  54. if key == pg.K_F5:
  55. self.show_fps = not self.show_fps
  56. if not self.show_fps:
  57. pg.display.set_caption(self.caption)
  58. def main(self):
  59. """Main loop for entire program"""
  60. while not self.done:
  61. self.event_loop()
  62. self.update()
  63. pg.display.update()
  64. self.clock.tick(self.fps)
  65. if self.show_fps:
  66. fps = self.clock.get_fps()
  67. with_fps = "{} - {:.2f} FPS".format(self.caption, fps)
  68. pg.display.set_caption(with_fps)
  69. class _State(object):
  70. def __init__(self):
  71. self.start_time = 0.0
  72. self.current_time = 0.0
  73. self.done = False
  74. self.quit = False
  75. self.next = None
  76. self.previous = None
  77. self.persist = {}
  78. def get_event(self, event):
  79. pass
  80. def startup(self, current_time, persistant):
  81. self.persist = persistant
  82. self.start_time = current_time
  83. def cleanup(self):
  84. self.done = False
  85. return self.persist
  86. def update(self, surface, keys, current_time):
  87. pass
  88. def load_all_gfx(directory, colorkey=(255,0,255), accept=('.png', 'jpg', 'bmp')):
  89. graphics = {}
  90. for pic in os.listdir(directory):
  91. name, ext = os.path.splitext(pic)
  92. if ext.lower() in accept:
  93. img = pg.image.load(os.path.join(directory, pic))
  94. if img.get_alpha():
  95. img = img.convert_alpha()
  96. else:
  97. img = img.convert()
  98. img.set_colorkey(colorkey)
  99. graphics[name]=img
  100. return graphics
  101. def load_all_music(directory, accept=('.wav', '.mp3', '.ogg', '.mdi')):
  102. songs = {}
  103. for song in os.listdir(directory):
  104. name,ext = os.path.splitext(song)
  105. if ext.lower() in accept:
  106. songs[name] = os.path.join(directory, song)
  107. return songs
  108. def load_all_fonts(directory, accept=('.ttf')):
  109. return load_all_music(directory, accept)
  110. def load_all_sfx(directory, accept=('.wav','.mpe','.ogg','.mdi')):
  111. effects = {}
  112. for fx in os.listdir(directory):
  113. name, ext = os.path.splitext(fx)
  114. if ext.lower() in accept:
  115. effects[name] = pg.mixer.Sound(os.path.join(directory, fx))
  116. return effects

2.设置背景音乐以及场景中的文字(setup部分)

该部分主要设置场景中的背景音乐,以及字体的显示等设置。

  1. import os
  2. import pygame as pg
  3. from . import tools
  4. from .import constants as c
  5. ORIGINAL_CAPTION = c.ORIGINAL_CAPTION
  6. os.environ['SDL_VIDEO_CENTERED'] = '1'
  7. pg.init()
  8. pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT])
  9. pg.display.set_caption(c.ORIGINAL_CAPTION)
  10. SCREEN = pg.display.set_mode(c.SCREEN_SIZE)
  11. SCREEN_RECT = SCREEN.get_rect()
  12. FONTS = tools.load_all_fonts(os.path.join("resources","fonts"))
  13. MUSIC = tools.load_all_music(os.path.join("resources","music"))
  14. GFX = tools.load_all_gfx(os.path.join("resources","graphics"))
  15. SFX = tools.load_all_sfx(os.path.join("resources","sound"))

3.设置游戏规则(load_screen)

  1. from .. import setup, tools
  2. from .. import constants as c
  3. from .. import game_sound
  4. from ..components import info
  5. class LoadScreen(tools._State):
  6. def __init__(self):
  7. tools._State.__init__(self)
  8. def startup(self, current_time, persist):
  9. self.start_time = current_time
  10. self.persist = persist
  11. self.game_info = self.persist
  12. self.next = self.set_next_state()
  13. info_state = self.set_overhead_info_state()
  14. self.overhead_info = info.OverheadInfo(self.game_info, info_state)
  15. self.sound_manager = game_sound.Sound(self.overhead_info)
  16. def set_next_state(self):
  17. """Sets the next state"""
  18. return c.LEVEL1
  19. def set_overhead_info_state(self):
  20. """sets the state to send to the overhead info object"""
  21. return c.LOAD_SCREEN
  22. def update(self, surface, keys, current_time):
  23. """Updates the loading screen"""
  24. if (current_time - self.start_time) < 2400:
  25. surface.fill(c.BLACK)
  26. self.overhead_info.update(self.game_info)
  27. self.overhead_info.draw(surface)
  28. elif (current_time - self.start_time) < 2600:
  29. surface.fill(c.BLACK)
  30. elif (current_time - self.start_time) < 2635:
  31. surface.fill((106, 150, 252))
  32. else:
  33. self.done = True
  34. class GameOver(LoadScreen):
  35. """A loading screen with Game Over"""
  36. def __init__(self):
  37. super(GameOver, self).__init__()
  38. def set_next_state(self):
  39. """Sets next state"""
  40. return c.MAIN_MENU
  41. def set_overhead_info_state(self):
  42. """sets the state to send to the overhead info object"""
  43. return c.GAME_OVER
  44. def update(self, surface, keys, current_time):
  45. self.current_time = current_time
  46. self.sound_manager.update(self.persist, None)
  47. if (self.current_time - self.start_time) < 7000:
  48. surface.fill(c.BLACK)
  49. self.overhead_info.update(self.game_info)
  50. self.overhead_info.draw(surface)
  51. elif (self.current_time - self.start_time) < 7200:
  52. surface.fill(c.BLACK)
  53. elif (self.current_time - self.start_time) < 7235:
  54. surface.fill((106, 150, 252))
  55. else:
  56. self.done = True
  57. class TimeOut(LoadScreen):
  58. """Loading Screen with Time Out"""
  59. def __init__(self):
  60. super(TimeOut, self).__init__()
  61. def set_next_state(self):
  62. """Sets next state"""
  63. if self.persist[c.LIVES] == 0:
  64. return c.GAME_OVER
  65. else:
  66. return c.LOAD_SCREEN
  67. def set_overhead_info_state(self):
  68. """Sets the state to send to the overhead info object"""
  69. return c.TIME_OUT
  70. def update(self, surface, keys, current_time):
  71. self.current_time = current_time
  72. if (self.current_time - self.start_time) < 2400:
  73. surface.fill(c.BLACK)
  74. self.overhead_info.update(self.game_info)
  75. self.overhead_info.draw(surface)
  76. else:
  77. self.done = True

4.设置游戏内菜单等(main_menu)

  1. import pygame as pg
  2. from .. import setup, tools
  3. from .. import constants as c
  4. from .. components import info, mario
  5. class Menu(tools._State):
  6. def __init__(self):
  7. """Initializes the state"""
  8. tools._State.__init__(self)
  9. persist = {c.COIN_TOTAL: 0,
  10. c.SCORE: 0,
  11. c.LIVES: 3,
  12. c.TOP_SCORE: 0,
  13. c.CURRENT_TIME: 0.0,
  14. c.LEVEL_STATE: None,
  15. c.CAMERA_START_X: 0,
  16. c.MARIO_DEAD: False}
  17. self.startup(0.0, persist)
  18. def startup(self, current_time, persist):
  19. """Called every time the game's state becomes this one. Initializes
  20. certain values"""
  21. self.next = c.LOAD_SCREEN
  22. self.persist = persist
  23. self.game_info = persist
  24. self.overhead_info = info.OverheadInfo(self.game_info, c.MAIN_MENU)
  25. self.sprite_sheet = setup.GFX['title_screen']
  26. self.setup_background()
  27. self.setup_mario()
  28. self.setup_cursor()
  29. def setup_cursor(self):
  30. """Creates the mushroom cursor to select 1 or 2 player game"""
  31. self.cursor = pg.sprite.Sprite()
  32. dest = (220, 358)
  33. self.cursor.image, self.cursor.rect = self.get_image(
  34. 24, 160, 8, 8, dest, setup.GFX['item_objects'])
  35. self.cursor.state = c.PLAYER1
  36. def setup_mario(self):
  37. """Places Mario at the beginning of the level"""
  38. self.mario = mario.Mario()
  39. self.mario.rect.x = 110
  40. self.mario.rect.bottom = c.GROUND_HEIGHT
  41. def setup_background(self):
  42. """Setup the background image to blit"""
  43. self.background = setup.GFX['level_1']
  44. self.background_rect = self.background.get_rect()
  45. self.background = pg.transform.scale(self.background,
  46. (int(self.background_rect.width*c.BACKGROUND_MULTIPLER),
  47. int(self.background_rect.height*c.BACKGROUND_MULTIPLER)))
  48. self.viewport = setup.SCREEN.get_rect(bottom=setup.SCREEN_RECT.bottom)
  49. self.image_dict = {}
  50. self.image_dict['GAME_NAME_BOX'] = self.get_image(
  51. 1, 60, 176, 88, (170, 100), setup.GFX['title_screen'])
  52. def get_image(self, x, y, width, height, dest, sprite_sheet):
  53. """Returns images and rects to blit onto the screen"""
  54. image = pg.Surface([width, height])
  55. rect = image.get_rect()
  56. image.blit(sprite_sheet, (0, 0), (x, y, width, height))
  57. if sprite_sheet == setup.GFX['title_screen']:
  58. image.set_colorkey((255, 0, 220))
  59. image = pg.transform.scale(image,
  60. (int(rect.width*c.SIZE_MULTIPLIER),
  61. int(rect.height*c.SIZE_MULTIPLIER)))
  62. else:
  63. image.set_colorkey(c.BLACK)
  64. image = pg.transform.scale(image,
  65. (int(rect.width*3),
  66. int(rect.height*3)))
  67. rect = image.get_rect()
  68. rect.x = dest[0]
  69. rect.y = dest[1]
  70. return (image, rect)
  71. def update(self, surface, keys, current_time):
  72. """Updates the state every refresh"""
  73. self.current_time = current_time
  74. self.game_info[c.CURRENT_TIME] = self.current_time
  75. self.update_cursor(keys)
  76. self.overhead_info.update(self.game_info)
  77. surface.blit(self.background, self.viewport, self.viewport)
  78. surface.blit(self.image_dict['GAME_NAME_BOX'][0],
  79. self.image_dict['GAME_NAME_BOX'][1])
  80. surface.blit(self.mario.image, self.mario.rect)
  81. surface.blit(self.cursor.image, self.cursor.rect)
  82. self.overhead_info.draw(surface)
  83. def update_cursor(self, keys):
  84. """Update the position of the cursor"""
  85. input_list = [pg.K_RETURN, pg.K_a, pg.K_s]
  86. if self.cursor.state == c.PLAYER1:
  87. self.cursor.rect.y = 358
  88. if keys[pg.K_DOWN]:
  89. self.cursor.state = c.PLAYER2
  90. for input in input_list:
  91. if keys[input]:
  92. self.reset_game_info()
  93. self.done = True
  94. elif self.cursor.state == c.PLAYER2:
  95. self.cursor.rect.y = 403
  96. if keys[pg.K_UP]:
  97. self.cursor.state = c.PLAYER1
  98. def reset_game_info(self):
  99. """Resets the game info in case of a Game Over and restart"""
  100. self.game_info[c.COIN_TOTAL] = 0
  101. self.game_info[c.SCORE] = 0
  102. self.game_info[c.LIVES] = 3
  103. self.game_info[c.CURRENT_TIME] = 0.0
  104. self.game_info[c.LEVEL_STATE] = None
  105. self.persist = self.game_info

5.main()

  1. from . import setup,tools
  2. from .states import main_menu,load_screen,level1
  3. from . import constants as c
  4. def main():
  5. """Add states to control here."""
  6. run_it = tools.Control(setup.ORIGINAL_CAPTION)
  7. state_dict = {c.MAIN_MENU: main_menu.Menu(),
  8. c.LOAD_SCREEN: load_screen.LoadScreen(),
  9. c.TIME_OUT: load_screen.TimeOut(),
  10. c.GAME_OVER: load_screen.GameOver(),
  11. c.LEVEL1: level1.Level1()}
  12. run_it.setup_states(state_dict, c.MAIN_MENU)
  13. run_it.main()

6.调用以上函数实现

  1. import sys
  2. import pygame as pg
  3. from 小游戏.超级玛丽.data.main import main
  4. import cProfile
  5. if __name__=='__main__':
  6. main()
  7. pg.quit()
  8. sys.exit()

在这里主要给大家展示主体的代码,完整资源可私聊我领取!!

 

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

闽ICP备14008679号