当前位置:   article > 正文

python植物大战僵尸源码教学_植物大战僵尸源代码

植物大战僵尸源代码

大家好,给大家分享一下一个有趣的事情,很多人还不知道这一点。下面详细解释一下。现在让我们来看看!

大家好,我是梦执,对梦执着。希望能和大家共同进步!

下面给大家带来python实现植物大战僵尸的的源码分享,只含有冒险模式python 安装后怎么用

游戏截图

d7481ff08c634f8684f4a3e0a2677a5e.png

75b735af0c924d02862c9143b89f1d01.png
87d3d56a25e546bb8dcb9e9285fb77cf.png

动态演示

3be67b68cae34dc2b12f56eafd0fec07.gif#pic_center

源码分享

state/tool.py

  1. import os
  2. import json
  3. from abc import abstractmethod
  4. import pygame as pg
  5. from . import constants as c
  6. class State():
  7. def __init__(self):
  8. self.start_time = 0.0
  9. self.current_time = 0.0
  10. self.done = False
  11. self.next = None
  12. self.persist = {}
  13. @abstractmethod
  14. def startup(self, current_time, persist):
  15. '''abstract method'''
  16. def cleanup(self):
  17. self.done = False
  18. return self.persist
  19. @abstractmethod
  20. def update(self, surface, keys, current_time):
  21. '''abstract method'''
  22. class Control():
  23. def __init__(self):
  24. self.screen = pg.display.get_surface()
  25. self.done = False
  26. self.clock = pg.time.Clock()
  27. self.fps = 60
  28. self.keys = pg.key.get_pressed()
  29. self.mouse_pos = None
  30. self.mouse_click = [False, False] # value:[left mouse click, right mouse click]
  31. self.current_time = 0.0
  32. self.state_dict = {}
  33. self.state_name = None
  34. self.state = None
  35. self.game_info = {c.CURRENT_TIME:0.0,
  36. c.LEVEL_NUM:c.START_LEVEL_NUM}
  37. def setup_states(self, state_dict, start_state):
  38. self.state_dict = state_dict
  39. self.state_name = start_state
  40. self.state = self.state_dict[self.state_name]
  41. self.state.startup(self.current_time, self.game_info)
  42. def update(self):
  43. self.current_time = pg.time.get_ticks()
  44. if self.state.done:
  45. self.flip_state()
  46. self.state.update(self.screen, self.current_time, self.mouse_pos, self.mouse_click)
  47. self.mouse_pos = None
  48. self.mouse_click[0] = False
  49. self.mouse_click[1] = False
  50. def flip_state(self):
  51. previous, self.state_name = self.state_name, self.state.next
  52. persist = self.state.cleanup()
  53. self.state = self.state_dict[self.state_name]
  54. self.state.startup(self.current_time, persist)
  55. def event_loop(self):
  56. for event in pg.event.get():
  57. if event.type == pg.QUIT:
  58. self.done = True
  59. elif event.type == pg.KEYDOWN:
  60. self.keys = pg.key.get_pressed()
  61. elif event.type == pg.KEYUP:
  62. self.keys = pg.key.get_pressed()
  63. elif event.type == pg.MOUSEBUTTONDOWN:
  64. self.mouse_pos = pg.mouse.get_pos()
  65. self.mouse_click[0], _, self.mouse_click[1] = pg.mouse.get_pressed()
  66. print('pos:', self.mouse_pos, ' mouse:', self.mouse_click)
  67. def main(self):
  68. while not self.done:
  69. self.event_loop()
  70. self.update()
  71. pg.display.update()
  72. self.clock.tick(self.fps)
  73. print('game over')
  74. def get_image(sheet, x, y, width, height, colorkey=c.BLACK, scale=1):
  75. image = pg.Surface([width, height])
  76. rect = image.get_rect()
  77. image.blit(sheet, (0, 0), (x, y, width, height))
  78. image.set_colorkey(colorkey)
  79. image = pg.transform.scale(image,
  80. (int(rect.width*scale),
  81. int(rect.height*scale)))
  82. return image
  83. def load_image_frames(directory, image_name, colorkey, accept):
  84. frame_list = []
  85. tmp = {}
  86. # image_name is "Peashooter", pic name is 'Peashooter_1', get the index 1
  87. index_start = len(image_name) + 1
  88. frame_num = 0;
  89. for pic in os.listdir(directory):
  90. name, ext = os.path.splitext(pic)
  91. if ext.lower() in accept:
  92. index = int(name[index_start:])
  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. tmp[index]= img
  100. frame_num += 1
  101. for i in range(frame_num):
  102. frame_list.append(tmp[i])
  103. return frame_list
  104. def load_all_gfx(directory, colorkey=c.WHITE, accept=('.png', '.jpg', '.bmp', '.gif')):
  105. graphics = {}
  106. for name1 in os.listdir(directory):
  107. # subfolders under the folder resources\graphics
  108. dir1 = os.path.join(directory, name1)
  109. if os.path.isdir(dir1):
  110. for name2 in os.listdir(dir1):
  111. dir2 = os.path.join(dir1, name2)
  112. if os.path.isdir(dir2):
  113. # e.g. subfolders under the folder resources\graphics\Zombies
  114. for name3 in os.listdir(dir2):
  115. dir3 = os.path.join(dir2, name3)
  116. # e.g. subfolders or pics under the folder resources\graphics\Zombies\ConeheadZombie
  117. if os.path.isdir(dir3):
  118. # e.g. it's the folder resources\graphics\Zombies\ConeheadZombie\ConeheadZombieAttack
  119. image_name, _ = os.path.splitext(name3)
  120. graphics[image_name] = load_image_frames(dir3, image_name, colorkey, accept)
  121. else:
  122. # e.g. pics under the folder resources\graphics\Plants\Peashooter
  123. image_name, _ = os.path.splitext(name2)
  124. graphics[image_name] = load_image_frames(dir2, image_name, colorkey, accept)
  125. break
  126. else:
  127. # e.g. pics under the folder resources\graphics\Screen
  128. name, ext = os.path.splitext(name2)
  129. if ext.lower() in accept:
  130. img = pg.image.load(dir2)
  131. if img.get_alpha():
  132. img = img.convert_alpha()
  133. else:
  134. img = img.convert()
  135. img.set_colorkey(colorkey)
  136. graphics[name] = img
  137. return graphics
  138. def loadZombieImageRect():
  139. file_path = os.path.join('source', 'data', 'entity', 'zombie.json')
  140. f = open(file_path)
  141. data = json.load(f)
  142. f.close()
  143. return data[c.ZOMBIE_IMAGE_RECT]
  144. def loadPlantImageRect():
  145. file_path = os.path.join('source', 'data', 'entity', 'plant.json')
  146. f = open(file_path)
  147. data = json.load(f)
  148. f.close()
  149. return data[c.PLANT_IMAGE_RECT]
  150. pg.init()
  151. pg.display.set_caption(c.ORIGINAL_CAPTION)
  152. SCREEN = pg.display.set_mode(c.SCREEN_SIZE)
  153. GFX = load_all_gfx(os.path.join("resources","graphics"))
  154. ZOMBIE_RECT = loadZombieImageRect()
  155. PLANT_RECT = loadPlantImageRect()

state/constants.py

  1. START_LEVEL_NUM = 1
  2. ORIGINAL_CAPTION = 'Plant VS Zombies Game'
  3. SCREEN_WIDTH = 800
  4. SCREEN_HEIGHT = 600
  5. SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)
  6. GRID_X_LEN = 9
  7. GRID_Y_LEN = 5
  8. GRID_X_SIZE = 80
  9. GRID_Y_SIZE = 100
  10. WHITE = (255, 255, 255)
  11. NAVYBLUE = ( 60, 60, 100)
  12. SKY_BLUE = ( 39, 145, 251)
  13. BLACK = ( 0, 0, 0)
  14. LIGHTYELLOW = (234, 233, 171)
  15. RED = (255, 0, 0)
  16. PURPLE = (255, 0, 255)
  17. GOLD = (255, 215, 0)
  18. GREEN = ( 0, 255, 0)
  19. SIZE_MULTIPLIER = 1.3
  20. #GAME INFO DICTIONARY KEYS
  21. CURRENT_TIME = 'current time'
  22. LEVEL_NUM = 'level num'
  23. #STATES FOR ENTIRE GAME
  24. MAIN_MENU = 'main menu'
  25. LOAD_SCREEN = 'load screen'
  26. GAME_LOSE = 'game los'
  27. GAME_VICTORY = 'game victory'
  28. LEVEL = 'level'
  29. MAIN_MENU_IMAGE = 'MainMenu'
  30. OPTION_ADVENTURE = 'Adventure'
  31. GAME_LOOSE_IMAGE = 'GameLoose'
  32. GAME_VICTORY_IMAGE = 'GameVictory'
  33. #MAP COMPONENTS
  34. BACKGROUND_NAME = 'Background'
  35. BACKGROUND_TYPE = 'background_type'
  36. INIT_SUN_NAME = 'init_sun_value'
  37. ZOMBIE_LIST = 'zombie_list'
  38. MAP_EMPTY = 0
  39. MAP_EXIST = 1
  40. BACKGROUND_OFFSET_X = 220
  41. MAP_OFFSET_X = 35
  42. MAP_OFFSET_Y = 100
  43. #MENUBAR
  44. CHOOSEBAR_TYPE = 'choosebar_type'
  45. CHOOSEBAR_STATIC = 0
  46. CHOOSEBAR_MOVE = 1
  47. CHOSSEBAR_BOWLING = 2
  48. MENUBAR_BACKGROUND = 'ChooserBackground'
  49. MOVEBAR_BACKGROUND = 'MoveBackground'
  50. PANEL_BACKGROUND = 'PanelBackground'
  51. START_BUTTON = 'StartButton'
  52. CARD_POOL = 'card_pool'
  53. MOVEBAR_CARD_FRESH_TIME = 6000
  54. CARD_MOVE_TIME = 60
  55. #PLANT INFO
  56. PLANT_IMAGE_RECT = 'plant_image_rect'
  57. CAR = 'car'
  58. SUN = 'Sun'
  59. SUNFLOWER = 'SunFlower'
  60. PEASHOOTER = 'Peashooter'
  61. SNOWPEASHOOTER = 'SnowPea'
  62. WALLNUT = 'WallNut'
  63. CHERRYBOMB = 'CherryBomb'
  64. THREEPEASHOOTER = 'Threepeater'
  65. REPEATERPEA = 'RepeaterPea'
  66. CHOMPER = 'Chomper'
  67. CHERRY_BOOM_IMAGE = 'Boom'
  68. PUFFSHROOM = 'PuffShroom'
  69. POTATOMINE = 'PotatoMine'
  70. SQUASH = 'Squash'
  71. SPIKEWEED = 'Spikeweed'
  72. JALAPENO = 'Jalapeno'
  73. SCAREDYSHROOM = 'ScaredyShroom'
  74. SUNSHROOM = 'SunShroom'
  75. ICESHROOM = 'IceShroom'
  76. HYPNOSHROOM = 'HypnoShroom'
  77. WALLNUTBOWLING = 'WallNutBowling'
  78. REDWALLNUTBOWLING = 'RedWallNutBowling'
  79. PLANT_HEALTH = 5
  80. WALLNUT_HEALTH = 30
  81. WALLNUT_CRACKED1_HEALTH = 20
  82. WALLNUT_CRACKED2_HEALTH = 10
  83. WALLNUT_BOWLING_DAMAGE = 10
  84. PRODUCE_SUN_INTERVAL = 7000
  85. FLOWER_SUN_INTERVAL = 22000
  86. SUN_LIVE_TIME = 7000
  87. SUN_VALUE = 25
  88. ICE_SLOW_TIME = 2000
  89. FREEZE_TIME = 7500
  90. ICETRAP = 'IceTrap'
  91. #PLANT CARD INFO
  92. CARD_SUNFLOWER = 'card_sunflower'
  93. CARD_PEASHOOTER = 'card_peashooter'
  94. CARD_SNOWPEASHOOTER = 'card_snowpea'
  95. CARD_WALLNUT = 'card_wallnut'
  96. CARD_CHERRYBOMB = 'card_cherrybomb'
  97. CARD_THREEPEASHOOTER = 'card_threepeashooter'
  98. CARD_REPEATERPEA = 'card_repeaterpea'
  99. CARD_CHOMPER = 'card_chomper'
  100. CARD_PUFFSHROOM = 'card_puffshroom'
  101. CARD_POTATOMINE = 'card_potatomine'
  102. CARD_SQUASH = 'card_squash'
  103. CARD_SPIKEWEED = 'card_spikeweed'
  104. CARD_JALAPENO = 'card_jalapeno'
  105. CARD_SCAREDYSHROOM = 'card_scaredyshroom'
  106. CARD_SUNSHROOM = 'card_sunshroom'
  107. CARD_ICESHROOM = 'card_iceshroom'
  108. CARD_HYPNOSHROOM = 'card_hypnoshroom'
  109. CARD_REDWALLNUT = 'card_redwallnut'
  110. #BULLET INFO
  111. BULLET_PEA = 'PeaNormal'
  112. BULLET_PEA_ICE = 'PeaIce'
  113. BULLET_MUSHROOM = 'BulletMushRoom'
  114. BULLET_DAMAGE_NORMAL = 1
  115. #ZOMBIE INFO
  116. ZOMBIE_IMAGE_RECT = 'zombie_image_rect'
  117. ZOMBIE_HEAD = 'ZombieHead'
  118. NORMAL_ZOMBIE = 'Zombie'
  119. CONEHEAD_ZOMBIE = 'ConeheadZombie'
  120. BUCKETHEAD_ZOMBIE = 'BucketheadZombie'
  121. FLAG_ZOMBIE = 'FlagZombie'
  122. NEWSPAPER_ZOMBIE = 'NewspaperZombie'
  123. BOOMDIE = 'BoomDie'
  124. LOSTHEAD_HEALTH = 5
  125. NORMAL_HEALTH = 10
  126. FLAG_HEALTH = 15
  127. CONEHEAD_HEALTH = 20
  128. BUCKETHEAD_HEALTH = 30
  129. NEWSPAPER_HEALTH = 15
  130. ATTACK_INTERVAL = 1000
  131. ZOMBIE_WALK_INTERVAL = 70
  132. ZOMBIE_START_X = SCREEN_WIDTH + 50
  133. #STATE
  134. IDLE = 'idle'
  135. FLY = 'fly'
  136. EXPLODE = 'explode'
  137. ATTACK = 'attack'
  138. ATTACKED = 'attacked'
  139. DIGEST = 'digest'
  140. WALK = 'walk'
  141. DIE = 'die'
  142. CRY = 'cry'
  143. FREEZE = 'freeze'
  144. SLEEP = 'sleep'
  145. #LEVEL STATE
  146. CHOOSE = 'choose'
  147. PLAY = 'play'
  148. #BACKGROUND
  149. BACKGROUND_DAY = 0
  150. BACKGROUND_NIGHT = 1

state/main.py

  1. from . import tool
  2. from . import constants as c
  3. from .state import mainmenu, screen, level
  4. def main():
  5. game = tool.Control()
  6. state_dict = {c.MAIN_MENU: mainmenu.Menu(),
  7. c.GAME_VICTORY: screen.GameVictoryScreen(),
  8. c.GAME_LOSE: screen.GameLoseScreen(),
  9. c.LEVEL: level.Level()}
  10. game.setup_states(state_dict, c.MAIN_MENU)
  11. game.main()

主执行文件main.py

  1. import pygame as pg
  2. from source.main import main
  3. if __name__=='__main__':
  4. main()
  5. pg.quit()

还有植物和僵尸的源码,实在太多了,需要的小伙伴直接私聊我领取!!

文章知识点与官方知识档案匹配,可进一步学习相关知识
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/413791
推荐阅读
相关标签
  

闽ICP备14008679号