基于Python实现经典植物大战僵尸游戏

目录
  • 游戏截图
  • 动态演示
  • 源码分享
    • state/tool.py
    • state/constants.py
    • state/main.py
    • 主执行文件main.py

游戏截图

动态演示

源码分享

state/tool.py

import os
import json
from abc import abstractmethod
import pygame as pg
from . import constants as c

class State():
    def __init__(self):
        self.start_time = 0.0
        self.current_time = 0.0
        self.done = False
        self.next = None
        self.persist = {}

    @abstractmethod
    def startup(self, current_time, persist):
        '''abstract method'''

    def cleanup(self):
        self.done = False
        return self.persist

    @abstractmethod
    def update(self, surface, keys, current_time):
        '''abstract method'''

class Control():
    def __init__(self):
        self.screen = pg.display.get_surface()
        self.done = False
        self.clock = pg.time.Clock()
        self.fps = 60
        self.keys = pg.key.get_pressed()
        self.mouse_pos = None
        self.mouse_click = [False, False]  # value:[left mouse click, right mouse click]
        self.current_time = 0.0
        self.state_dict = {}
        self.state_name = None
        self.state = None
        self.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_dict
        self.state_name = start_state
        self.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 = None
        self.mouse_click[0] = False
        self.mouse_click[1] = False

    def flip_state(self):
        previous, self.state_name = self.state_name, self.state.next
        persist = 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 = True
            elif 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 image

def load_image_frames(directory, image_name, colorkey, accept):
    frame_list = []
    tmp = {}
    # image_name is "Peashooter", pic name is 'Peashooter_1', get the index 1
    index_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]= img
            frame_num += 1

    for i in range(frame_num):
        frame_list.append(tmp[i])
    return frame_list

def load_all_gfx(directory, colorkey=c.WHITE, accept=('.png', '.jpg', '.bmp', '.gif')):
    graphics = {}
    for name1 in os.listdir(directory):
        # subfolders under the folder resources\graphics
        dir1 = 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\Zombies
                    for name3 in os.listdir(dir2):
                        dir3 = os.path.join(dir2, name3)
                        # e.g. subfolders or pics under the folder resources\graphics\Zombies\ConeheadZombie
                        if os.path.isdir(dir3):
                            # e.g. it's the folder resources\graphics\Zombies\ConeheadZombie\ConeheadZombieAttack
                            image_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\Peashooter
                            image_name, _ = os.path.splitext(name2)
                            graphics[image_name] = load_image_frames(dir2, image_name, colorkey, accept)
                            break
                else:
                # e.g. pics under the folder resources\graphics\Screen
                    name, 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] = img
    return graphics

def 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()

state/constants.py


START_LEVEL_NUM = 1

ORIGINAL_CAPTION = 'Plant VS Zombies Game'

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)

GRID_X_LEN = 9
GRID_Y_LEN = 5
GRID_X_SIZE = 80
GRID_Y_SIZE = 100

WHITE        = (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 KEYS
CURRENT_TIME = 'current time'
LEVEL_NUM = 'level num'

#STATES FOR ENTIRE GAME
MAIN_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 COMPONENTS
BACKGROUND_NAME = 'Background'
BACKGROUND_TYPE = 'background_type'
INIT_SUN_NAME = 'init_sun_value'
ZOMBIE_LIST = 'zombie_list'

MAP_EMPTY = 0
MAP_EXIST = 1

BACKGROUND_OFFSET_X = 220
MAP_OFFSET_X = 35
MAP_OFFSET_Y = 100

#MENUBAR
CHOOSEBAR_TYPE = 'choosebar_type'
CHOOSEBAR_STATIC = 0
CHOOSEBAR_MOVE = 1
CHOSSEBAR_BOWLING = 2
MENUBAR_BACKGROUND = 'ChooserBackground'
MOVEBAR_BACKGROUND = 'MoveBackground'
PANEL_BACKGROUND = 'PanelBackground'
START_BUTTON = 'StartButton'
CARD_POOL = 'card_pool'

MOVEBAR_CARD_FRESH_TIME = 6000
CARD_MOVE_TIME = 60

#PLANT INFO
PLANT_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 = 5
WALLNUT_HEALTH = 30
WALLNUT_CRACKED1_HEALTH = 20
WALLNUT_CRACKED2_HEALTH = 10
WALLNUT_BOWLING_DAMAGE = 10

PRODUCE_SUN_INTERVAL = 7000
FLOWER_SUN_INTERVAL = 22000
SUN_LIVE_TIME = 7000
SUN_VALUE = 25

ICE_SLOW_TIME = 2000

FREEZE_TIME = 7500
ICETRAP = 'IceTrap'

#PLANT CARD INFO
CARD_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 INFO
BULLET_PEA = 'PeaNormal'
BULLET_PEA_ICE = 'PeaIce'
BULLET_MUSHROOM = 'BulletMushRoom'
BULLET_DAMAGE_NORMAL = 1

#ZOMBIE INFO
ZOMBIE_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 = 5
NORMAL_HEALTH = 10
FLAG_HEALTH = 15
CONEHEAD_HEALTH = 20
BUCKETHEAD_HEALTH = 30
NEWSPAPER_HEALTH = 15

ATTACK_INTERVAL = 1000
ZOMBIE_WALK_INTERVAL = 70

ZOMBIE_START_X = SCREEN_WIDTH + 50

#STATE
IDLE = 'idle'
FLY = 'fly'
EXPLODE = 'explode'
ATTACK = 'attack'
ATTACKED = 'attacked'
DIGEST = 'digest'
WALK = 'walk'
DIE = 'die'
CRY = 'cry'
FREEZE = 'freeze'
SLEEP = 'sleep'

#LEVEL STATE
CHOOSE = 'choose'
PLAY = 'play'

#BACKGROUND
BACKGROUND_DAY = 0
BACKGROUND_NIGHT = 1

state/main.py

from . import tool
from . import constants as c
from .state import mainmenu, screen, level

def 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()

主执行文件main.py

import pygame as pg
from source.main import main

if __name__=='__main__':
    main()
    pg.quit()

到此这篇关于基于Python实现经典植物大战僵尸游戏的文章就介绍到这了,更多相关Python植物大战僵尸内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 13个有趣又好玩的Python游戏代码分享

    目录 1.吃金币 2.打乒乓 3.滑雪 4.并夕夕版飞机大战 5.打地鼠 6.小恐龙 7.消消乐 8.俄罗斯方块 9.贪吃蛇 10.24点小游戏 11.平衡木 12.外星人入侵 13.井字棋888 经常听到有朋友说,学习编程是一件非常枯燥无味的事情.其实,大家有没有认真想过,可能是我们的学习方法不对? 比方说,你有没有想过,可以通过打游戏来学编程? 今天我想跟大家分享几个Python小游戏,教你如何通过边打游戏边学编程! 1.吃金币 源码分享: import os import cfg impo

  • Python Pygame实战之赛车游戏的实现

    目录 导语 一.环境安装 1)运行环境 2)素材环境 二.代码展示 三.效果展示 游戏开始—— 游戏界面—— 游戏结束—— 导语 小伙伴们大家好~ 如今的游戏可谓是层出不穷,NBA 2K系列啊,FIFA系列啊更是经典中的经典,不过小编发现,赛车游戏也是深受大家欢迎啊,像跑跑卡丁车.QQ飞车,还有主机游戏极品飞车系列. 咳咳咳......小编那时候主要是最喜欢里面的人物颜值来的! 赛车游戏,通常以款式多样的车型.各式各样的赛道.身临其境的拟真度吸引了众多玩家,而玩家在游戏中需要驾驶各类赛车驰骋在世

  • 教你用Python写一个植物大战僵尸小游戏

    一.前言 上次写了一个俄罗斯方块,感觉好像大家都看懂了,这次就更新一个植物大战僵尸吧 二.引入模块 import pygame import random 三.完整代码 配置图片地址 IMAGE_PATH = 'imgs/' 设置页面宽高 scrrr_width = 800 scrrr_height = 560 创建控制游戏结束的状态 GAMEOVER = False 图片加载报错处理 LOG = '文件:{}中的方法:{}出错'.format(__file__, __name__) 创建地图类

  • 详解如何利用Python制作24点小游戏

    目录 先睹为快 游戏规则(改编自维基百科) 逐步实现 Step1:制作24点生成器 Step2:定义游戏精灵类 Step3:实现游戏主循环 先睹为快 24点 游戏规则(改编自维基百科) 从1~10这十个数字中随机抽取4个数字(可重复),对这四个数运用加.减.乘.除和括号进行运算得出24.每个数字都必须使用一次,但不能重复使用. 逐步实现 Step1:制作24点生成器 既然是24点小游戏,当然要先定义一个24点游戏生成器啦.主要思路就是随机生成4个有解的数字,且范围在1~10之间,代码实现如下:

  • python实现植物大战僵尸游戏实例代码

    开发思路 完整项目地址:https://github.com/371854496/... 觉得还OK的话,点下Star,作者不易,thank you! 实现方法 1.引入需要的模块,配置图片路径,设置界面宽高背景颜色,创建游戏主入口. #1引入需要的模块 import pygame import random #1配置图片地址 IMAGE_PATH = 'imgs/' #1设置页面宽高 scrrr_width=800 scrrr_height =560 #1创建控制游戏结束的状态 GAMEOVE

  • 基于Python编写简易版的天天跑酷游戏的示例代码

    写出来的效果图就是这样了: 下面就更新一下全部的代码吧 还是老样子先定义 import pygame,sys import random 写一下游戏配置 width = 1200            #窗口宽度 height = 508            #窗口高度 size = width, height    score=None              #分数 myFont=myFont1=None     #字体 surObject=None          #障碍物图片   

  • 基于Python实现经典植物大战僵尸游戏

    目录 游戏截图 动态演示 源码分享 state/tool.py state/constants.py state/main.py 主执行文件main.py 游戏截图 动态演示 源码分享 state/tool.py import os import json from abc import abstractmethod import pygame as pg from . import constants as c class State(): def __init__(self): self.s

  • 基于Java实现经典蜘蛛纸牌游戏

    目录 效果展示 游戏结构 核心代码 AboutDialog.java类 PKCard.java类 SpiderMenuBar.java类 Spider.java 类 效果展示 前面的导入过程这里就不多说了,不会的可以自己去问度娘.导入后,选择Spider.java类直接运行就可以了,下面是游戏运行的截图: 游戏结构 核心代码 代码显示:代码注释很清楚 ,大家可以自行参考. AboutDialog.java类 import javax.swing.*; import java.awt.*; /*

  • 基于Python实现英语单词小游戏

    目录 导语 一.敲代码之前的小tips 二.运行环境 三.素材(图片等) 四.代码展示 1)主程序(英文打字小游戏主入口模块) 2)游戏配置信息模块 3)游戏视图模块 4)PyGame游戏精灵模块 五.效果展示 1)游戏界面 2)游戏设置 ​3)随机截图 4)游戏结束 导语 相信大家对于英语四级一点都不陌生了吧? 很多学校都是要求学生必须考过英语四级,不然就不能毕业. 一开始我抱着侥幸心理,心想上高中的时候英语不错,四级应该也很容易.不过成绩出来我就傻眼了,没有通过.然后我就制定了周密的学习计划

  • 基于Python实现贪吃蛇小游戏(附源码)

    目录 前言 主要设计 应用知识点 1.python知识点 2.pygamezero知识点 功能截图 代码实现 1.蛇的表示 2.蛇的前进移动 3.控制移动方向 4.游戏失败 5.食物的随机出现 6.游戏得分 源码 总结 前言 这几年人工智能技术大发展,Python因此几乎成了第一位的语言.实际上,多年来,它不仅在软件工程师中得到广泛使用,也是各行业通用的专家语言,就是说,不管孩子以后做什么,都可能用得着.准备针对我自己上小学的孩子,每周抽出些时间,通过学习他们感兴趣的小游戏,逐步把python知

  • 基于Python+Pygame实现经典赛车游戏

    目录 导语 一.环境安装 二.代码展示 1.主程序main.py 2.地图设置maps.py 三.效果展示 1.游戏界面 2.游戏运行中 3.15分到手 导语 哈喽!哈喽~我是木木子,很久没给大家更新游戏的类似啦—— 有粉丝投稿,说最近由于受疫情影响封闭在家不能离开小区,前不久刚刚报名的驾照考试只能无线延期,在家里还是挺无聊的,“憋在家里没事干的时候去打打游戏写写代码还挺好的. 于是,小编灵机一动,就有了今天这款简易版本的<赛车计划>也就是咳咳咳....... 通俗点儿就是一款代码写的一款关于

  • Python基于分水岭算法解决走迷宫游戏示例

    本文实例讲述了Python基于分水岭算法解决走迷宫游戏.分享给大家供大家参考,具体如下: #Solving maze with morphological transformation """ usage:Solving maze with morphological transformation needed module:cv2/numpy/sys ref: 1.http://www.mazegenerator.net/ 2.http://blog.leanote.com

  • Android植物大战僵尸小游戏

    Android植物大战僵尸小游戏全部内容如下: 相关下载:Android植物大战僵尸小游戏 具体代码如下所示: package com.example.liu.mygame; import com.example.liu.mygame.global.Config; import com.example.liu.mygame.tools.DeviceTools; import com.example.liu.mygame.view.GameView; import android.os.Bundl

  • 基于python pygame实现的兔子吃月饼小游戏

    目录 小游戏规则简介 实现 初始化游戏窗口 游戏逻辑 实现玩家类 实现月饼类 交互逻辑 总结 中秋佳节就快来临,给各位大佬整个兔子吃月饼的小游戏助助兴,废话不多说,开整. 小游戏规则简介 玩家通过"wsad"或者"↑↓←→"键控制兔子移动,使得兔子可以吃到更多的月饼,月饼一旦生成之后位置不会变,也不会消失,就等着兔子去吃,就是这么简单.但是吃了月饼会变重,重到一定程度会有想不到的效果. 实现 使用Python的pygame模块开发,pygame是用来开发游戏软件的P

随机推荐