前言

哈喽!大家好,我是魔王呐~

看到下面这一段话,大家是不是会想起你在某种时候玩过的一款游戏呐~

我拥有着绚烂的外表,但这美丽只在瞬间绽放。烟花散尽之后你会多一个朋友,但是我的身影已经消失在你的视线之外。
                                         一魅惑菇

晃着脑袋生产阳光的向日葵,突突突吐着子弹的豌豆射手!​

行动迟缓种类丰富的僵尸……

印象最深的是“僵尸吃掉了你的脑子!”

还有疯狂的戴夫,无一不唤醒着我们的童年记忆​

山民们闯到哪一关了?解锁了哪些植物?


在今天,就让我们来上一个大工程,制作植物大战僵尸小游戏里的冒险模式~

相关准备

在开始之前,我们要准备好游戏的相关素材~没有(不想找)的小伙伴可以找我领取呐`

展示部分素材









代码 ❤

import pygame as pgfrom source.main import mainif __name__=='__main__':main()pg.quit()
__author__ = 'marble_xu'START_LEVEL_NUM = 1ORIGINAL_CAPTION = 'Plant VS Zombies Game'SCREEN_WIDTH = 800SCREEN_HEIGHT = 600SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)GRID_X_LEN = 9GRID_Y_LEN = 5GRID_X_SIZE = 80GRID_Y_SIZE = 100WHITE= (255, 255, 255)NAVYBLUE = ( 60,60, 100)SKY_BLUE = ( 39, 145, 251)BLACK= (0, 0, 0)LIGHTYELLOW= (234, 233, 171)RED= (255, 0, 0)PURPLE = (255, 0, 255)GOLD = (255, 215, 0)GREEN= (0, 255, 0)SIZE_MULTIPLIER = 1.3#GAME INFO DICTIONARY KEYSCURRENT_TIME = 'current time'LEVEL_NUM = 'level num'#STATES FOR ENTIRE GAMEMAIN_MENU = 'main menu'LOAD_SCREEN = 'load screen'GAME_LOSE = 'game los'GAME_VICTORY = 'game victory'LEVEL = 'level'MAIN_MENU_IMAGE = 'MainMenu'OPTION_ADVENTURE = 'Adventure'GAME_LOOSE_IMAGE = 'GameLoose'GAME_VICTORY_IMAGE = 'GameVictory'#MAP COMPONENTSBACKGROUND_NAME = 'Background'BACKGROUND_TYPE = 'background_type'INIT_SUN_NAME = 'init_sun_value'ZOMBIE_LIST = 'zombie_list'MAP_EMPTY = 0MAP_EXIST = 1BACKGROUND_OFFSET_X = 220MAP_OFFSET_X = 35MAP_OFFSET_Y = 100#MENUBARCHOOSEBAR_TYPE = 'choosebar_type'CHOOSEBAR_STATIC = 0CHOOSEBAR_MOVE = 1CHOSSEBAR_BOWLING = 2MENUBAR_BACKGROUND = 'ChooserBackground'MOVEBAR_BACKGROUND = 'MoveBackground'PANEL_BACKGROUND = 'PanelBackground'START_BUTTON = 'StartButton'CARD_POOL = 'card_pool'MOVEBAR_CARD_FRESH_TIME = 6000CARD_MOVE_TIME = 60#PLANT INFOPLANT_IMAGE_RECT = 'plant_image_rect'CAR = 'car'SUN = 'Sun'SUNFLOWER = 'SunFlower'PEASHOOTER = 'Peashooter'SNOWPEASHOOTER = 'SnowPea'WALLNUT = 'WallNut'CHERRYBOMB = 'CherryBomb'THREEPEASHOOTER = 'Threepeater'REPEATERPEA = 'RepeaterPea'CHOMPER = 'Chomper'CHERRY_BOOM_IMAGE = 'Boom'PUFFSHROOM = 'PuffShroom'POTATOMINE = 'PotatoMine'SQUASH = 'Squash'SPIKEWEED = 'Spikeweed'JALAPENO = 'Jalapeno'SCAREDYSHROOM = 'ScaredyShroom'SUNSHROOM = 'SunShroom'ICESHROOM = 'IceShroom'HYPNOSHROOM = 'HypnoShroom'WALLNUTBOWLING = 'WallNutBowling'REDWALLNUTBOWLING = 'RedWallNutBowling'PLANT_HEALTH = 5WALLNUT_HEALTH = 30WALLNUT_CRACKED1_HEALTH = 20WALLNUT_CRACKED2_HEALTH = 10WALLNUT_BOWLING_DAMAGE = 10PRODUCE_SUN_INTERVAL = 7000FLOWER_SUN_INTERVAL = 22000SUN_LIVE_TIME = 7000SUN_VALUE = 25ICE_SLOW_TIME = 2000FREEZE_TIME = 7500ICETRAP = 'IceTrap'#PLANT CARD INFOCARD_SUNFLOWER = 'card_sunflower'CARD_PEASHOOTER = 'card_peashooter'CARD_SNOWPEASHOOTER = 'card_snowpea'CARD_WALLNUT = 'card_wallnut'CARD_CHERRYBOMB = 'card_cherrybomb'CARD_THREEPEASHOOTER = 'card_threepeashooter'CARD_REPEATERPEA = 'card_repeaterpea'CARD_CHOMPER = 'card_chomper'CARD_PUFFSHROOM = 'card_puffshroom'CARD_POTATOMINE = 'card_potatomine'CARD_SQUASH = 'card_squash'CARD_SPIKEWEED = 'card_spikeweed'CARD_JALAPENO = 'card_jalapeno'CARD_SCAREDYSHROOM = 'card_scaredyshroom'CARD_SUNSHROOM = 'card_sunshroom'CARD_ICESHROOM = 'card_iceshroom'CARD_HYPNOSHROOM = 'card_hypnoshroom'CARD_REDWALLNUT = 'card_redwallnut'#BULLET INFOBULLET_PEA = 'PeaNormal'BULLET_PEA_ICE = 'PeaIce'BULLET_MUSHROOM = 'BulletMushRoom'BULLET_DAMAGE_NORMAL = 1#ZOMBIE INFOZOMBIE_IMAGE_RECT = 'zombie_image_rect'ZOMBIE_HEAD = 'ZombieHead'NORMAL_ZOMBIE = 'Zombie'CONEHEAD_ZOMBIE = 'ConeheadZombie'BUCKETHEAD_ZOMBIE = 'BucketheadZombie'FLAG_ZOMBIE = 'FlagZombie'NEWSPAPER_ZOMBIE = 'NewspaperZombie'BOOMDIE = 'BoomDie'LOSTHEAD_HEALTH = 5NORMAL_HEALTH = 10FLAG_HEALTH = 15CONEHEAD_HEALTH = 20BUCKETHEAD_HEALTH = 30NEWSPAPER_HEALTH = 15ATTACK_INTERVAL = 1000ZOMBIE_WALK_INTERVAL = 70ZOMBIE_START_X = SCREEN_WIDTH + 50#STATEIDLE = 'idle'FLY = 'fly'EXPLODE = 'explode'ATTACK = 'attack'ATTACKED = 'attacked'DIGEST = 'digest'WALK = 'walk'DIE = 'die'CRY = 'cry'FREEZE = 'freeze'SLEEP = 'sleep'#LEVEL STATECHOOSE = 'choose'PLAY = 'play'#BACKGROUNDBACKGROUND_DAY = 0BACKGROUND_NIGHT = 1
__author__ = 'marble_xu'from . import toolfrom . import constants as cfrom .state import mainmenu, screen, leveldef main():game = tool.Control()state_dict = {c.MAIN_MENU: mainmenu.Menu(),c.GAME_VICTORY: screen.GameVictoryScreen(),c.GAME_LOSE: screen.GameLoseScreen(),c.LEVEL: level.Level()}game.setup_states(state_dict, c.MAIN_MENU)game.main()

完整代码太多,需要的小可耐们可以点击左侧流动文字领取或私信我领取呐`

__author__ = 'marble_xu'import osimport jsonfrom abc import abstractmethodimport pygame as pgfrom . import constants as cclass State():def __init__(self):self.start_time = 0.0self.current_time = 0.0self.done = Falseself.next = Noneself.persist = {}@abstractmethoddef startup(self, current_time, persist):'''abstract method'''def cleanup(self):self.done = Falsereturn self.persist@abstractmethoddef update(self, surface, keys, current_time):'''abstract method'''class Control():def __init__(self):self.screen = pg.display.get_surface()self.done = Falseself.clock = pg.time.Clock()self.fps = 60self.keys = pg.key.get_pressed()self.mouse_pos = Noneself.mouse_click = [False, False]# value:[left mouse click, right mouse click]self.current_time = 0.0self.state_dict = {}self.state_name = Noneself.state = Noneself.game_info = {c.CURRENT_TIME:0.0,c.LEVEL_NUM:c.START_LEVEL_NUM} def setup_states(self, state_dict, start_state):self.state_dict = state_dictself.state_name = start_stateself.state = self.state_dict[self.state_name]self.state.startup(self.current_time, self.game_info)def update(self):self.current_time = pg.time.get_ticks()if self.state.done:self.flip_state()self.state.update(self.screen, self.current_time, self.mouse_pos, self.mouse_click)self.mouse_pos = Noneself.mouse_click[0] = Falseself.mouse_click[1] = Falsedef flip_state(self):previous, self.state_name = self.state_name, self.state.nextpersist = self.state.cleanup()self.state = self.state_dict[self.state_name]self.state.startup(self.current_time, persist)def event_loop(self):for event in pg.event.get():if event.type == pg.QUIT:self.done = Trueelif event.type == pg.KEYDOWN:self.keys = pg.key.get_pressed()elif event.type == pg.KEYUP:self.keys = pg.key.get_pressed()elif event.type == pg.MOUSEBUTTONDOWN:self.mouse_pos = pg.mouse.get_pos()self.mouse_click[0], _, self.mouse_click[1] = pg.mouse.get_pressed()print('pos:', self.mouse_pos, ' mouse:', self.mouse_click)def main(self):while not self.done:self.event_loop()self.update()pg.display.update()self.clock.tick(self.fps)print('game over')def get_image(sheet, x, y, width, height, colorkey=c.BLACK, scale=1):image = pg.Surface([width, height])rect = image.get_rect()image.blit(sheet, (0, 0), (x, y, width, height))image.set_colorkey(colorkey)image = pg.transform.scale(image, (int(rect.width*scale),int(rect.height*scale)))return imagedef load_image_frames(directory, image_name, colorkey, accept):frame_list = []tmp = {}# image_name is "Peashooter", pic name is 'Peashooter_1', get the index 1index_start = len(image_name) + 1 frame_num = 0;for pic in os.listdir(directory):name, ext = os.path.splitext(pic)if ext.lower() in accept:index = int(name[index_start:])img = pg.image.load(os.path.join(directory, pic))if img.get_alpha():img = img.convert_alpha()else:img = img.convert()img.set_colorkey(colorkey)tmp[index]= imgframe_num += 1for i in range(frame_num):frame_list.append(tmp[i])return frame_listdef load_all_gfx(directory, colorkey=c.WHITE, accept=('.png', '.jpg', '.bmp', '.gif')):graphics = {}for name1 in os.listdir(directory):# subfolders under the folder resources\graphicsdir1 = os.path.join(directory, name1)if os.path.isdir(dir1):for name2 in os.listdir(dir1):dir2 = os.path.join(dir1, name2)if os.path.isdir(dir2):# e.g. subfolders under the folder resources\graphics\Zombiesfor name3 in os.listdir(dir2):dir3 = os.path.join(dir2, name3)# e.g. subfolders or pics under the folder resources\graphics\Zombies\ConeheadZombieif os.path.isdir(dir3):# e.g. it's the folder resources\graphics\Zombies\ConeheadZombie\ConeheadZombieAttackimage_name, _ = os.path.splitext(name3)graphics[image_name] = load_image_frames(dir3, image_name, colorkey, accept)else:# e.g. pics under the folder resources\graphics\Plants\Peashooterimage_name, _ = os.path.splitext(name2)graphics[image_name] = load_image_frames(dir2, image_name, colorkey, accept)breakelse:# e.g. pics under the folder resources\graphics\Screenname, ext = os.path.splitext(name2)if ext.lower() in accept:img = pg.image.load(dir2)if img.get_alpha():img = img.convert_alpha()else:img = img.convert()img.set_colorkey(colorkey)graphics[name] = imgreturn graphicsdef loadZombieImageRect():file_path = os.path.join('source', 'data', 'entity', 'zombie.json')f = open(file_path)data = json.load(f)f.close()return data[c.ZOMBIE_IMAGE_RECT]def loadPlantImageRect():file_path = os.path.join('source', 'data', 'entity', 'plant.json')f = open(file_path)data = json.load(f)f.close()return data[c.PLANT_IMAGE_RECT]pg.init()pg.display.set_caption(c.ORIGINAL_CAPTION)SCREEN = pg.display.set_mode(c.SCREEN_SIZE)GFX = load_all_gfx(os.path.join("resources","graphics"))ZOMBIE_RECT = loadZombieImageRect()PLANT_RECT = loadPlantImageRect()

完整代码太多,需要的小可耐们可以点击左侧流动文字领取或私信我领取呐`



效果展示(部分)

首页

挑选植物页面


战斗页面


战斗胜利页面

植物大站僵尸经典语录

1、我会一直很努力的笑着为你制造阳光,因为我知道你喜欢阳光灿烂的感觉。 —— 向日葵

2、我的出现就是为了毁灭,毁灭敌人,还有我自己。你会记住我吗?就算只有一刹那,我也觉得,自己很美丽。 —— 樱桃

3、只需要一点点的时间,我就会告诉你为了你我有多么的奋不顾身。 —— 土豆雷

4、有人说我很丑,有人说我很凶,其实那都是我伪装出的外表,其实我也很脆弱,其实我也需要保护。
 —— 大嘴花

5、当我还是一个完整的坚果,我就在那里了,当我的身躯残破,眼中含着泪水,我依旧在那里,为什么要这么坚持,因为我身后我有我想保护的朋友。 —— 坚果

6、你喜欢谁,我就是谁,你需要谁,我就是谁。没有自我,是不是很可悲呢?没关系,你开心就好。 —— 模仿者

7、我年龄小,个子也小,可是我已经懂得了战斗的含义,我甚至还懂得了炮灰的含义。我不怕,我也不怨你,因为我和你一样,都憧憬着胜利的一刻。   —— 小蘑菇

8、也许我现在的用处不大,也许我属于被你鄙视的行列,但是给我一点机会,我也有变成神的可能。 —— 大喷菇

9、不要埋怨那个坑好吗?我只是想在这个战场,留下一点点证明我曾经存在过的痕迹。   —— 毁灭菇

10、保护你们是我的天职,消失的前一刻我不会哭,因为我没有眼睛。 —— 南瓜头

11、我将他们拖下水,我把眼泪流在水里,二十五个能量值换来我的同归于尽。 —— 缠绕海草

12、不要靠近我,我是个暴脾气。我不惜毁掉自己为你清出这条笔直的大路,却在灰飞中湮灭,因为,我有过誓言,我说到做到。 —— 火爆辣椒

尾语

成功没有快车道,幸福没有高速路。

所有的成功,都来自不倦地努力和奔跑,所有的幸福都来自平凡的奋斗和坚持

——励志语录

本文章就写完啦~感兴趣的小伙伴可以复制代码去试试

你们的支持是我最大的动力!!记得三连哦~ 欢迎大家阅读往期的文章呀