当前位置:   article > 正文

涨知识!用 Python 实现植物大战僵尸代码

python植物大战僵尸代码解释

 

作者 | marble_xu

责编 | 毛中政

出品 | CSDN博客

功能介绍

最近一直在给这个植物大战僵尸游戏添加新的植物和僵尸, 因为网上的图片资源有限,能加的植物和僵尸比较少, 目前进展如下。

功能实现如下:

  • 支持的植物类型:太阳花,豌豆射手,寒冰射手,坚果,樱桃炸弹。新增加植物:双重豌豆射手,三重豌豆射手,食人花 ,小喷菇,土豆地雷,倭瓜。

  • 支持的僵尸类型:普通僵尸,棋子僵尸,路障僵尸,铁桶僵尸。新增加读报僵尸。

  • 使用json文件保存关卡信息,设置僵尸出现的时间和位置。

  • 增加每关开始时选择上场植物。

  • 增加除草机。

下面是游戏的截图:

图1:新增的植物和僵尸

图2:每关开始选择上场植物卡片

图3:选择植物在哪里种植

植物卡片选择和种植

如图3所示,游戏中可以种植物的方格一共有45个(有5行,每行9列)。

这篇文章要介绍的是:

  • 上方植物卡片栏的实现。

  • 点击植物卡片,鼠标切换为植物图片。

  • 鼠标移动时,判断当前在哪个方格中,并显示半透明的植物作为提示。

完整代码

游戏实现代码的github链接:

https://github.com/marblexu/PythonPlantsVsZombies

这边是csdn的下载链接:

https://download.csdn.net/download/marble_xu/11982275

代码实现

所有的植物卡片的名称和属性都保存在单独的list中,每个list index都对应一种植物。

比如list index 0 就是太阳花:

  • card_name_list[0] 是太阳花卡片的名字,用来获取太阳花卡片的图片。

  • plant_name_list[0] 是太阳花的名字,用来获取太阳花卡片的图片。

  • plant_sun_list[0] 是种植太阳花需要花费的太阳点数。

  • plant_frozen_time_list[0] 是太阳花的冷却时间。

代码在source\component\menubar.py中:

  1. card_name_list = [c.CARD_SUNFLOWER, c.CARD_PEASHOOTER, c.CARD_SNOWPEASHOOTER, c.CARD_WALLNUT,
  2.                   c.CARD_CHERRYBOMB, c.CARD_THREEPEASHOOTER, c.CARD_REPEATERPEA, c.CARD_CHOMPER,
  3.                   c.CARD_PUFFMUSHROOM, c.CARD_POTATOMINE, c.CARD_SQUASH]
  4. plant_name_list = [c.SUNFLOWER, c.PEASHOOTER, c.SNOWPEASHOOTER, c.WALLNUT,
  5.                    c.CHERRYBOMB, c.THREEPEASHOOTER, c.REPEATERPEA, c.CHOMPER,
  6.                    c.PUFFMUSHROOM, c.POTATOMINE, c.SQUASH]
  7. plant_sun_list = [501001755015032520015002550]
  8. plant_frozen_time_list = [050005000100005000500050005000800080008000]
  9. all_card_list = [012345678910]

植物卡片类

代码在source\component\menubar.py中,每个植物卡片是一个单独的Card类,用来显示这个植物。

  • checkMouseClick函数:判断鼠标是否点击到这个卡片;

  • canClick:判断这个卡片是否能种植(有没有足够的点数,是否还在冷却时间内);

  • update 函数:通过设置图片的透明度来表示这个卡片是否能选择。

  1. class Card():
  2.     def __init__(selfxyname_indexscale=0.78):
  3.         self.loadFrame(card_name_list[name_index], scale)
  4.         self.rect = self.image.get_rect()
  5.         self.rect.x = x
  6.         self.rect.y = y
  7.         self.name_index = name_index
  8.         self.sun_cost = plant_sun_list[name_index]
  9.         self.frozen_time = plant_frozen_time_list[name_index]
  10.         self.frozen_timer = -self.frozen_time
  11.         self.select = True
  12.     def loadFrame(selfnamescale):
  13.         frame = tool.GFX[name]
  14.         rect = frame.get_rect()
  15.         widthheight = rect.wrect.h
  16.         self.image = tool.get_image(frame, 0, 0, widthheightc.BLACKscale)
  17.     def checkMouseClick(selfmouse_pos):
  18.         xy = mouse_pos
  19.         if(x >= self.rect.x and x <= self.rect.right and
  20.            y >= self.rect.y and y <= self.rect.bottom):
  21.             return True
  22.         return False
  23.     def canClick(selfsun_valuecurrent_time):
  24.         if self.sun_cost <= sun_value and (current_time - self.frozen_timer) > self.frozen_time:
  25.             return True
  26.         return False
  27.     def canSelect(self):
  28.         return self.select
  29.     def setSelect(selfcan_select):
  30.         self.select = can_select
  31.         if can_select:
  32.             self.image.set_alpha(255)
  33.         else:
  34.             self.image.set_alpha(128)
  35.     def setFrozenTime(selfcurrent_time):
  36.         self.frozen_timer = current_time
  37.     def update(selfsun_valuecurrent_time):
  38.         if (self.sun_cost > sun_value or
  39.             (current_time - self.frozen_timer) <= self.frozen_time):
  40.             self.image.set_alpha(128)
  41.         else:
  42.             self.image.set_alpha(255)
  43.     def draw(selfsurface):
  44.         surface.blit(self.imageself.rect)

卡片栏类

代码在source\component\menubar.py中,MenuBar类显示图3中的植物卡片栏:

  • self.sun_value:当前采集的太阳点数;

  • self.card_list: 植物卡片的list;

  • setupCards函数:遍历初始化__init__函数中传入这个关卡选好的植物卡片list,依次创建Card类,设置每个卡片的显示位置;

  • checkCardClick函数:检查鼠标是否点击了卡片栏上的某个植物卡片,如果选择了一个可种植的卡片,返回结果。

  1. class MenuBar():
  2.     def __init__(selfcard_listsun_value):
  3.         self.loadFrame(c.MENUBAR_BACKGROUND)
  4.         self.rect = self.image.get_rect()
  5.         self.rect.x = 10
  6.         self.rect.y = 0
  7.         self.sun_value = sun_value
  8.         self.card_offset_x = 32
  9.         self.setupCards(card_list)
  10.     def loadFrame(selfname):
  11.         frame = tool.GFX[name]
  12.         rect = frame.get_rect()
  13.         frame_rect = (rect.xrect.yrect.wrect.h)
  14.         self.image = tool.get_image(tool.GFX[name], *frame_rectc.WHITE, 1)
  15.     def update(selfcurrent_time):
  16.         self.current_time = current_time
  17.         for card in self.card_list:
  18.             card.update(self.sun_valueself.current_time)
  19.     def createImage(selfxynum):
  20.         if num == 1:
  21.             return
  22.         img = self.image
  23.         rect = self.image.get_rect()
  24.         width = rect.w
  25.         height = rect.h
  26.         self.image = pg.Surface((width * numheight)).convert()
  27.         self.rect = self.image.get_rect()
  28.         self.rect.x = x
  29.         self.rect.y = y
  30.         for i in range(num):
  31.             x = i * width
  32.             self.image.blit(img, (x,0))
  33.         self.image.set_colorkey(c.BLACK)
  34.     def setupCards(selfcard_list):
  35.         self.card_list = []
  36.         x = self.card_offset_x
  37.         y = 8
  38.         for index in card_list:
  39.             x += 55
  40.             self.card_list.append(Card(xyindex))
  41.     def checkCardClick(selfmouse_pos):
  42.         result = None
  43.         for card in self.card_list:
  44.             if card.checkMouseClick(mouse_pos):
  45.                 if card.canClick(self.sun_valueself.current_time):
  46.                     result = (plant_name_list[card.name_index], card.sun_cost)
  47.                 break
  48.         return result
  49.     def checkMenuBarClick(selfmouse_pos):
  50.         xy = mouse_pos
  51.         if(x >= self.rect.x and x <= self.rect.right and
  52.            y >= self.rect.y and y <= self.rect.bottom):
  53.             return True
  54.         return False
  55.     def decreaseSunValue(selfvalue):
  56.         self.sun_value -= value
  57.     def increaseSunValue(selfvalue):
  58.         self.sun_value += value
  59.     def setCardFrozenTime(selfplant_name):
  60.         for card in self.card_list:
  61.             if plant_name_list[card.name_index] == plant_name:
  62.                 card.setFrozenTime(self.current_time)
  63.                 break
  64.     def drawSunValue(self):
  65.         self.value_image = getSunValueImage(self.sun_value)
  66.         self.value_rect = self.value_image.get_rect()
  67.         self.value_rect.x = 21
  68.         self.value_rect.y = self.rect.bottom - 21
  69.         self.image.blit(self.value_imageself.value_rect)
  70.     def draw(selfsurface):
  71.         self.drawSunValue()
  72.         surface.blit(self.imageself.rect)
  73.         for card in self.card_list:
  74.             card.draw(surface)

鼠标图片切换

代码在source\state\level.py中,setupMouseImage 函数实现鼠标图片切换为选中的植物:

  • self.mouse_image :根据 plant_name 获取选中的植物图片;

  • self.mouse_rect:选中植物图片的位置,在drawMouseShow函数中,需要将植物图片的位置设置成当前鼠标的位置;

  • pg.mouse.set_visible(False):隐藏默认的鼠标显示,这样效果就是鼠标图片切换为选中的植物了。

  1.    def setupMouseImage(self, plant_name, plant_cost):
  2.         frame_list = tool.GFX[plant_name]
  3.         if plant_name in tool.PLANT_RECT:
  4.             data = tool.PLANT_RECT[plant_name]
  5.             x, y, width, height = data['x'], data['y'], data['width'], data['height']
  6.         else:
  7.             x, y = 00
  8.             rect = frame_list[0].get_rect()
  9.             width, height = rect.w, rect.h
  10.         if plant_name == c.POTATOMINE or plant_name == c.SQUASH:
  11.             color = c.WHITE
  12.         else:
  13.             color = c.BLACK
  14.         self.mouse_image = tool.get_image(frame_list[0], x, y, width, height, color, 1)
  15.         self.mouse_rect = self.mouse_image.get_rect()
  16.         pg.mouse.set_visible(False)
  17.         self.drag_plant = True
  18.         self.plant_name = plant_name
  19.         self.plant_cost = plant_cost
  20.     def drawMouseShow(self, surface):
  21.         if self.hint_plant:
  22.             surface.blit(self.hint_image, self.hint_rect)
  23.         x, y = pg.mouse.get_pos()
  24.         self.mouse_rect.centerx = x
  25.         self.mouse_rect.centery = y
  26.         surface.blit(self.mouse_image, self.mouse_rect)

提示种在哪个方格中

先看下map类,代码在source\component\map.py 中:

  • self.map:二维list,用来保存每个方格的状态。每个entry初始化为 0, 表示可以种植物,值为1时表示这个方格已经种了植物。

  • getMapIndex 函数:传入参数是游戏中的坐标位置(比如当前鼠标的位置),返回该位置在地图的哪个方格中。

  • getMapGridPos 函数:传入一个方格的index,返回在该方格中种植物的坐标位置。

  • showPlant 函数:根据传入的坐标位置,判断该位置所在的方格是否能种植物,如果能种,就返回返回在该方格中种植物的坐标位置。

  1. MAP_EMPTY = 0
  2. MAP_EXIST = 1
  3. class Map():
  4.     def __init__(selfwidthheight):
  5.         self.width = width
  6.         self.height = height
  7.         self.map = [[0 for x in range(self.width)] for y in range(self.height)]
  8.     def isValid(selfmap_xmap_y):
  9.         if (map_x < 0 or map_x >= self.width or
  10.             map_y < 0 or map_y >= self.height):
  11.             return False
  12.         return True
  13.     def isMovable(selfmap_xmap_y):
  14.         return (self.map[map_y][map_x] == c.MAP_EMPTY)
  15.     def getMapIndex(selfxy):
  16.         x -= c.MAP_OFFSET_X
  17.         y -= c.MAP_OFFSET_Y
  18.         return (x // c.GRID_X_SIZEy // c.GRID_Y_SIZE)
  19.     def getMapGridPos(selfmap_xmap_y):
  20.         return (map_x * c.GRID_X_SIZE + c.GRID_X_SIZE//2 + c.MAP_OFFSET_X,
  21.                 map_y * c.GRID_Y_SIZE + c.GRID_Y_SIZE//5 * 3 + c.MAP_OFFSET_Y)
  22.     def setMapGridType(selfmap_xmap_ytype):
  23.         self.map[map_y][map_x] = type
  24.     def getRandomMapIndex(self):
  25.         map_x = random.randint(0, self.width-1)
  26.         map_y = random.randint(0, self.height-1)
  27.         return (map_xmap_y)
  28.     def showPlant(selfxy):
  29.         pos = None
  30.         map_xmap_y = self.getMapIndex(xy)
  31.         if self.isValid(map_xmap_yand self.isMovable(map_xmap_y):
  32.             pos = self.getMapGridPos(map_xmap_y)
  33.         return pos

代码在source\state\level.py中:

  • canSeedPlant 函数:判断当前鼠标位置能否种植物;

  • setupHintImage 函数:如果当前鼠标位置能种植物,且有选择了一个植物卡片,则设置self.hint_image 显示当前会在哪一个方格中种植物,self.hint_rect 是植物种的坐标位置。

  1.     def canSeedPlant(self):
  2.         x, y = pg.mouse.get_pos()
  3.         return self.map.showPlant(x, y)
  4.     def setupHintImage(self):
  5.         pos = self.canSeedPlant()
  6.         if pos and self.mouse_image:
  7.             if (self.hint_image and pos[0] == self.hint_rect.x and
  8.                 pos[1] == self.hint_rect.y):
  9.                 return
  10.             width, height = self.mouse_rect.w, self.mouse_rect.h
  11.             image = pg.Surface([width, height])
  12.             image.blit(self.mouse_image, (00), (00, width, height))
  13.             image.set_colorkey(c.BLACK)
  14.             image.set_alpha(128)
  15.             self.hint_image = image
  16.             self.hint_rect = image.get_rect()
  17.             self.hint_rect.centerx = pos[0]
  18.             self.hint_rect.bottom = pos[1]
  19.             self.hint_plant = True
  20.         else:
  21.             self.hint_plant = False

编译环境:python3.7 + pygame1.9。

原文链接:https://blog.csdn.net/marble_xu/article/details/103100614

版权声明:本文为CSDN博主「marble_xu」的原创文章。

想为博主点赞?

想要请教博主?

扫描下方二维码,快速获取与博主直面沟通的方式吧!

 

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

闽ICP备14008679号