python植物大战僵尸代码

用Python给我写一个植物大战僵尸的代码 我可以用 Python 为您编写一个简单的植物大战僵尸游戏。请注意,这只是一个简单的版本,没有图形界面和音效,仅用于演示游戏的基本原理。 # Plant vs Zombies class Plant: def __init__(self, name, power): self.name = name self.power = power class Zo... 阅读详情

二话不说,直接上代码。

import pygame
import random
import sys
#1 配置图片地址
#IMAGE_PATH = 'grassland.png'
#1 设置页面宽高
scrrr_width=800
scrrr_height =560
#1 创建控制游戏结束的状态
GAMEOVER = False
#4 图片加载报错处理
LOG = '文件:{}中的方法:{}出错'.format(__file__,__name__)
#3 创建地图类
class Map():
    #3 存储两张不同颜色的图片名称
    map_names_list = ['**************', '*******************']
    #3 初始化地图
    def __init__(self, x, y, img_index):
        self.image = pygame.image.load(Map.map_names_list[img_index])
        self.position = (x, y)
        # 是否能够种植
        self.can_grow = True
    #3 加载地图
    def load_map(self):
         MainGame.window.blit(self.image,self.position)
#4 植物类
class Plant(pygame.sprite.Sprite):
    def __init__(self):
        super(Plant, self).__init__()
        self.live=True

    # 加载图片
    def load_image(self):
        if hasattr(self, 'image') and hasattr(self, 'rect'):
            MainGame.window.blit(self.image, self.rect)
        else:
            print(LOG)
#5 向日葵类
class Sunflower(Plant):
    def __init__(self,x,y):
        super(Sunflower, self).__init__()
        self.image = pygame.image.load('**************')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.price = 50
        self.hp = 100
        #5 时间计数器
        self.time_count = 0

    #5 新增功能:生成阳光
    def produce_money(self):
        self.time_count += 1
        if self.time_count == 25:
            MainGame.money += 10
            self.time_count = 0
    #5 向日葵加入到窗口中
    def display_sunflower(self):
        MainGame.window.blit(self.image,self.rect)
#6 豌豆射手类
class PeaShooter(Plant):
    def __init__(self,x,y):
        super(PeaShooter, self).__init__()
        # self.image 为一个 surface
        self.image = pygame.image.load('**************')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.price = 50
        self.hp = 200
        #6 发射计数器
        self.shot_count = 0

    #6 增加射击方法
    def shot(self):
        #6 记录是否应该射击
        should_fire = False
        for zombie in MainGame.zombie_list:
            if zombie.rect.y == self.rect.y and zombie.rect.x < 800 and zombie.rect.x > self.rect.x:
                should_fire = True
        #6 如果活着
        if self.live and should_fire:
            self.shot_count += 1
            #6 计数器到25发射一次
            if self.shot_count == 25:
                #6 基于当前豌豆射手的位置,创建子弹
                peabullet = PeaBullet(self)
                #6 将子弹存储到子弹列表中
                MainGame.peabullet_list.append(peabullet)
                self.shot_count = 0

    #6 将豌豆射手加入到窗口中的方法
    def display_peashooter(self):
        MainGame.window.blit(self.image,self.rect)

#7 豌豆子弹类
class PeaBullet(pygame.sprite.Sprite):
    def __init__(self,peashooter):
        self.live = True
        self.image = pygame.image.load('**************')
        self.damage = 100
        self.speed  = 10
        self.rect = self.image.get_rect()
        self.rect.x = peashooter.rect.x + 60
        self.rect.y = peashooter.rect.y + 15

    def move_bullet(self):
        #7 在屏幕范围内,实现往右移动
        if self.rect.x < scrrr_width:
            self.rect.x += self.speed
        else:
            self.live = False

    #7 新增,子弹与僵尸的碰撞
    def hit_zombie(self):
        for zombie in MainGame.zombie_list:
            if pygame.sprite.collide_rect(self,zombie):
                #打中僵尸之后,修改子弹的状态,
                self.live = False
                #僵尸掉血
                zombie.hp -= self.damage
                if zombie.hp <= 0:
                    zombie.live = False
                    self.nextLevel()
    #7闯关方法
    def nextLevel(self):
        MainGame.score += 20
        MainGame.remnant_score -=20
        for i in range(1,100):
            if MainGame.score==100*i and MainGame.remnant_score==0:
                MainGame.remnant_score=100*i
                MainGame.shaoguan+=1
                MainGame.produce_zombie+=50



    def display_peabullet(self):
        MainGame.window.blit(self.image,self.rect)
#9 僵尸类
class Zombie(pygame.sprite.Sprite):
    def __init__(self,x,y):
        super(Zombie, self).__init__()
        self.image = pygame.image.load('**************')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.hp = 1000
        self.damage = 2
        self.speed = 1
        self.live = True
        self.stop = False
    #9 僵尸的移动
    def move_zombie(self):
        if self.live and not self.stop:
            self.rect.x -= self.speed
            if self.rect.x < -80:
                #8 调用游戏结束方法
                MainGame().gameOver()

    #9 判断僵尸是否碰撞到植物,如果碰撞,调用攻击植物的方法
    def hit_plant(self):
        for plant in MainGame.plants_list:
            if pygame.sprite.collide_rect(self,plant):
                #8  僵尸移动状态的修改
                self.stop = True
                self.eat_plant(plant)
    #9 僵尸攻击植物
    def eat_plant(self,plant):
        #9 植物生命值减少
        plant.hp -= self.damage
        #9 植物死亡后的状态修改,以及地图状态的修改
        if plant.hp <= 0:
            a = plant.rect.y // 80 - 1
            b = plant.rect.x // 80
            map = MainGame.map_list[a][b]
            map.can_grow = True
            plant.live = False
            #8 修改僵尸的移动状态
            self.stop = False



    #9 将僵尸加载到地图中
    def display_zombie(self):
        MainGame.window.blit(self.image,self.rect)
#1 主程序
class MainGame():
    #2 创建关数,得分,剩余分数,钱数
    shaoguan = 1
    score = 0
    remnant_score = 100
    money = 200
    #3 存储所有地图坐标点
    map_points_list = []
    #3 存储所有的地图块
    map_list = []
    #4 存储所有植物的列表
    plants_list = []
    #7 存储所有豌豆子弹的列表
    peabullet_list = []
    #9 新增存储所有僵尸的列表
    zombie_list = []
    count_zombie = 0
    produce_zombie = 100
    #1 加载游戏窗口
    def init_window(self):
        #1 调用显示模块的初始化
        pygame.display.init()
        #1 创建窗口
        MainGame.window = pygame.display.set_mode([scrrr_width,scrrr_height])

    #2 文本绘制
    def draw_text(self, content, size, color):
        pygame.font.init()
        font = pygame.font.SysFont('kaiti', size)
        text = font.render(content, True, color)
        return text

    #2 加载帮助提示
    def load_help_text(self):
        text1 = self.draw_text('1.按左键创建向日葵 2.按右键创建豌豆射手', 26, (255, 0, 0))
        MainGame.window.blit(text1, (5, 5))

    #3 初始化坐标点
    def init_plant_points(self):
        for y in range(1, 7):
            points = []
            for x in range(10):
                point = (x, y)
                points.append(point)
            MainGame.map_points_list.append(points)
            print("MainGame.map_points_list", MainGame.map_points_list)

    #3 初始化地图
    def init_map(self):
        for points in MainGame.map_points_list:
            temp_map_list = list()
            for point in points:
                # map = None
                if (point[0] + point[1]) % 2 == 0:
                    map = Map(point[0] * 80, point[1] * 80, 0)
                else:
                    map = Map(point[0] * 80, point[1] * 80, 1)
                # 将地图块加入到窗口中
                temp_map_list.append(map)
                print("temp_map_list", temp_map_list)
            MainGame.map_list.append(temp_map_list)
        print("MainGame.map_list", MainGame.map_list)

    #3 将地图加载到窗口中
    def load_map(self):
        for temp_map_list in MainGame.map_list:
            for map in temp_map_list:
                map.load_map()

    #6 增加豌豆射手发射处理
    def load_plants(self):
        for plant in MainGame.plants_list:
            #6 优化加载植物的处理逻辑
            if plant.live:
                if isinstance(plant, Sunflower):
                    plant.display_sunflower()
                    plant.produce_money()
                elif isinstance(plant, PeaShooter):
                    plant.display_peashooter()
                    plant.shot()
            else:
                MainGame.plants_list.remove(plant)

    #7 加载所有子弹的方法
    def load_peabullets(self):
        for b in MainGame.peabullet_list:
            if b.live:
                b.display_peabullet()
                b.move_bullet()
                # v1.9 调用子弹是否打中僵尸的方法
                b.hit_zombie()
            else:
                MainGame.peabullet_list.remove(b)

    #8事件处理

    def deal_events(self):
        #8 获取所有事件
        eventList = pygame.event.get()
        #8 遍历事件列表,判断
        for e in eventList:
            if e.type == pygame.QUIT:
                self.gameOver()
            elif e.type == pygame.MOUSEBUTTONDOWN:
                # print('按下鼠标按键')
                print(e.pos)
                # print(e.button)#左键1  按下滚轮2 上转滚轮为4 下转滚轮为5  右键 3

                x = e.pos[0] // 80
                y = e.pos[1] // 80
                print(x, y)
                map = MainGame.map_list[y - 1][x]
                print(map.position)
                #8 增加创建时候的地图装填判断以及金钱判断
                if e.button == 1:
                    if map.can_grow and MainGame.money >= 50:
                        sunflower = Sunflower(map.position[0], map.position[1])
                        MainGame.plants_list.append(sunflower)
                        print('当前植物列表长度:{}'.format(len(MainGame.plants_list)))
                        map.can_grow = False
                        MainGame.money -= 50
                elif e.button == 3:
                    if map.can_grow and MainGame.money >= 50:
                        peashooter = PeaShooter(map.position[0], map.position[1])
                        MainGame.plants_list.append(peashooter)
                        print('当前植物列表长度:{}'.format(len(MainGame.plants_list)))
                        map.can_grow = False
                        MainGame.money -= 50

    #9 新增初始化僵尸的方法
    def init_zombies(self):
        for i in range(1, 7):
            dis = random.randint(1, 5) * 200
            zombie = Zombie(800 + dis, i * 80)
            MainGame.zombie_list.append(zombie)

    #9将所有僵尸加载到地图中
    def load_zombies(self):
        for zombie in MainGame.zombie_list:
            if zombie.live:
                zombie.display_zombie()
                zombie.move_zombie()
                # v2.0 调用是否碰撞到植物的方法
                zombie.hit_plant()
            else:
                MainGame.zombie_list.remove(zombie)
    #1 开始游戏
    def start_game(self):
        #1 初始化窗口
        self.init_window()
        #3 初始化坐标和地图
        self.init_plant_points()
        self.init_map()
        #9 调用初始化僵尸的方法
        self.init_zombies()
        #1 只要游戏没结束,就一直循环
        while not GAMEOVER:
            #1 渲染白色背景
            MainGame.window.fill((255, 255, 255))
            #2 渲染的文字和坐标位置
            MainGame.window.blit(self.draw_text('当前钱数$: {}'.format(MainGame.money), 26, (255, 0, 0)), (500, 40))
            MainGame.window.blit(self.draw_text(
                '当前关数{},得分{},距离下关还差{}分'.format(MainGame.shaoguan, MainGame.score, MainGame.remnant_score), 26,
                (255, 0, 0)), (5, 40))
            self.load_help_text()

            #3 需要反复加载地图
            self.load_map()
            #6 调用加载植物的方法
            self.load_plants()
            #7  调用加载所有子弹的方法
            self.load_peabullets()
            #8 调用事件处理的方法
            self.deal_events()
            #9 调用展示僵尸的方法
            self.load_zombies()
            #9 计数器增长,每数到100,调用初始化僵尸的方法
            MainGame.count_zombie += 1
            if MainGame.count_zombie == MainGame.produce_zombie:
                self.init_zombies()
                MainGame.count_zombie = 0
            #9 pygame自己的休眠
            pygame.time.wait(10)
            #1 实时更新
            pygame.display.update()

    #10 程序结束方法
    def gameOver(self):
        MainGame.window.blit(self.draw_text('游戏结束', 50, (255, 0, 0)), (300, 200))
        print('游戏结束')
        pygame.time.wait(400)
        global GAMEOVER
        GAMEOVER = True
        pygame.quit()
        sys.exit()
        
#1 启动主程序
if __name__ == '__main__':
    game = MainGame()
    game.start_game()

此代码仅供参考,可以自己发挥创造。
在这里插入图片描述
好了,本文最后记得要关注、点赞+收藏哦~
♡♡♡

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

相关推荐

python植物大战僵尸源码教学

大家好,给大家分享一下一个有趣的事情,很多人还不知道这一点。下面详细解释一下。现在让我们来看看!下面给大家带来python实现植物大战僵尸的的源码分享,只含有冒险模式。

wenangou的博客 4558

Python植物大战僵尸丨进阶(完整代码)

Python开发植物大战僵尸小游戏的完整代码。

AIGC 863

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

setupCards函数:遍历初始化__init__函数中传入这个关卡选好的植物卡片list,依次创建Card类,设置每个卡片的显示位置;checkCardClick函数:检查鼠标是否点击了卡片栏上的某个植物卡片,如果选择了一个可种植的卡片,返回结果。canClick:判断这个卡片是否能种植(有没有足够的点数,是否还在冷却时间内);update 函数:通过设置图片的透明度来表示这个卡片是否能选择。每个植物卡片是一个单独的Card类,用来显示这个植物。self.card_list: 植物卡片的list;

2401_84010816的博客 1607

python实现植物大战僵尸

植物大战僵尸是一款十分经典的游戏,在github上就有python版的开源代码()打开后可以看见有六个版本,在这里我选的是第一个版本。太阳花,豌豆射手,寒冰射手,坚果,樱桃炸弹。新增加植物:双重豌豆射手,三重豌豆射手,食人花 ,小喷菇,土豆地雷,倭瓜。

xyx2023的博客 6774

Python 开发植物大战僵尸杂交版辅助【全网最详细_查找 + 代码编写一体化零基础也能学会】

写这篇文章的目的是告诉大家游戏单机辅助是如何编写的,这种方法在其他部分非单机游戏也能适用,开发者该如何去防范,知攻善防,并不鼓励大家写游戏外挂。游戏辅助本身就是利用游戏漏洞进行开发的,在单机游戏中,游戏数据都是存储在本地的,运行游戏后通过使用相应的内存查找工具获取到当前游戏数据的存储地址,通过对其数据进行修改来达到游戏规则之外的效果,使玩家可以轻松通过。

于高山之巅,方见大河奔涌;于群峰之上,更觉长风浩荡。 5541

python 植物大战僵尸代码

这个代码实现了基本的植物和僵尸的模拟,但是缺乏游戏的完整逻辑,比如植物攻击行为和僵尸移动。你需要根据游戏的具体规则来填充相应的逻辑。例如,你可以使用Pygame的定时器来模拟植物的攻击,并使用键盘或鼠标事件来控制植物的放置。此外,你还需要加载相应的图像资源,并处理游戏结束条件。植物大战僵尸是一款由PopCap Games开发的经典消除类游戏。以下是一个简单的Python实现,用于模拟植物大战僵尸的游戏逻辑。# 游戏结束,关闭Pygame。# 定义游戏中的一些常量。# 定义植物和僵尸的类。

2401_83470102的博客 1220

Python植物大战僵尸源代码及素材

Python植物大战僵尸源程序包含一个game.py及一个图片素材包,植物大战僵尸的素材包请在百度网盘下载,https://pan.baidu.com/s/1w3_9205lUfideePeV-vZ6g。提取码请回复:植物大战资源。 #1 引入需要的模块 import pygame import random #1 配置图片地址 IMAGE_PATH = 'imgs/' #1 设置页面宽高 scrrr_width=800 scrrr_height =560 #1 创建控制游戏结束的状态 GAMEOVER

Python代码大全 2万+

植物大战僵尸的代码如何使用python来实现

前言 文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。 作者:程序IT圈 PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取http://t.cn/A6Zvjdun 功能介绍 最近一直在给这个植物大战僵尸游戏添加新的植物和僵尸, 因为网上的图片资源有限,能加的植物和僵尸比较少, 目前进展如下。 ...

qq_46614154的博客 1827

Python植物大战僵尸丨基础(完整代码)

Python开发植物大战僵尸小游戏的完整代码。

AIGC 1390

帮我用Python写一段完整的植物大战僵尸代码

当然可以!下面是一段简单的 Python 代码,模拟一个植物大战僵尸的游戏过程: # 先定义 Plant 和 Zombie 类,表示植物和僵尸 class Plant: def __init__(self, name, attack_points): self.name = name self.attack_points = attack_points ...

weixin_35749545的博客 502

Python 开发植物大战僵尸游戏

作者:楷楷 链接:https://segmentfault.com/a/1190000019418065 开发思路 完整项目地址: https://github.com/371854496/pygame 更多好玩有趣的python,尽在公众号「Python专栏」,后台回复「机器学习电子书」免费获取100本机器学习电子书 引入需要的模块,配置图片路径,设置界面宽高背景颜色,创建游戏主入口。 ...

Python专栏 8086

使用Python打造简易版《植物大战僵尸》游戏

植物大战僵尸》是一款深受玩家喜爱的策略塔防游戏,以其独特的游戏机制和丰富的角色设定吸引了全球玩家。在本文中,我们将使用Python编程语言,结合简单的图形库(如Pygame),来制作一个简化的《植物大战僵尸》游戏版本。这个简化版将涵盖基本的游戏逻辑:玩家在草地上种植植物来防御僵尸的进攻。虽然无法完全复制原作的复杂度和精美度,但我们将尽力提供一个有趣且教育意义丰富的项目。

sj4568的博客 1180

不要迷恋我,虽然我利用Python来耍植物大战僵尸

比如说咱们玩的游戏它也是一个程序吧,游戏的角色血量、蓝条是不是都是一个数值储存在变量内,那么如果我们找到存放这个数值的变量(也可以叫做地址),修改这个变量的值,那么是不是就可以做到给咱们得人物加血量、修改人物等级的一系列操作。 首先确定修改哪一款游戏的数据,然后确定修改游戏的哪一个数据,然后去寻找这个游戏内这个数据的地址,然后去修改这个数据。

落伍的码农 1万+

用Python轻松打造定制款《植物大战僵尸》!玩这个游戏我都用脚本

植物大战僵尸》这款游戏也算是曾经风靡一时,不少网友曾用Python开发《坦克大战》、《飞机大战》、《扫雷》等经典游戏,开发《植物大战僵尸》当然也没问题。相比《坦克大战》等游戏,《植物大战僵尸》的游戏元素更多,设计起来会更加复杂,不过不必担心,因为我们这次不是从0开始凭空开发,而是借助一款植物大战僵尸的Python开源框架来实现。 01. 现有框架 1).先睹为快 既然是借助框架...

PythonJavaPHP的博客 1276

中文Python-植物大战僵尸游戏

本文介绍了一款使用中文Python开发的《植物大战僵尸》游戏,采用Pygame库实现。游戏包含仿古风格界面设计、多种植物与僵尸角色、音效系统等核心功能。代码展示了向日葵、豌豆射手等植物的类实现,包括绘制图形、生命值显示、攻击逻辑等。游戏支持在多种开发环境中运行,使用中文关键字编写但可转换为西文代码。主要特点包括:自定义颜色主题、程序生成音效、面向对象设计以及经典游戏玩法的简化实现。

weixin_47842539的博客 663

python入门小项目 | 用Python复刻了植物大战僵尸

Python+游戏太好玩了,这篇让你更好的理解比较复杂的游戏

m0_68104000的博客 3047

Python实现植物大战僵尸

该项目使用json文件存储关卡数据(例如僵尸的位置和时间,背景信息),并且支持白天状态功能和夜间状态切换功能。实施植物有:向日葵,豌豆,wallnut,snowpeashooter,cherrybomb,threepeashooter,剁碎,puffshroom,potatomine,穗状花序,scaredyshroom,南瓜,scaredyshroom,墨西哥胡椒,sunShroom,iceShroom,hypnoShroom。实施僵尸有:僵尸,鞭毛僵尸,锥头僵尸,水头僵尸,报纸僵尸。

不脱发的程序猿 8750

植物大战僵尸-源代码

{"name": "豌豆射手", "cost": 100, "type": "peashooter"},{"name": "樱桃炸弹", "cost": 150, "type": "cherrybomb"},game_over_text = big_font.render("游戏结束!", True, RED){"name": "向日葵", "cost": 50, "type": "sunflower"},{"name": "寒冰射手", "cost": 150, "type": "snowpea"},

weixin_45313958的博客 1562
上一篇: python之变量
下一篇: python最全讲解(1)
cpkiteman
博客等级 码龄5年 9粉丝 21原创
评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值