【pygame】pygame实现植物大战僵尸(V1.0)

前言

        最近心血来潮,想着搞个游戏玩玩,但是自己不知道做啥,就只能复刻以下植物大战僵尸了:)

        由于代码实在太长,这里只给大家展示以下主要部分了。

代码

# coding:gbk
__author__ = "苏朗"
import pygame as p
import sys,pyautogui
from random import randint
from pygame.locals import *
from var import *
from classes import *
import classes as cls
from table import table
p.init()
p.mixer.init()

names = ["sunflower","peashooter"]
#窗口代码
clock = p.time.Clock()
scr = p.display.set_mode((DISPLAT_WEIGHT,DISPLAT_HEIGHT))
p.display.set_icon(p.image.load(r"可爱项目(python)\植物大战僵尸\res\sunflower\sunlight.jpg"))
background = p.image.load(r"C:\Users\Administrator\.vscode\可爱项目(python)\植物大战僵尸\res\background.jpg")
background = p.transform.scale(background,(DISPLAT_WEIGHT,DISPLAT_HEIGHT))
#主代码
SUN_EVEVT = p.USEREVENT+1
p.time.set_timer(SUN_EVEVT,20000)
PEA_EVEVT = p.USEREVENT+2
p.time.set_timer(PEA_EVEVT,2000)
ZOMBIE_EVEVT = p.USEREVENT+3
p.time.set_timer(ZOMBIE_EVEVT,15000)

shovel_img = p.image.load(r"C:\Users\Administrator\.vscode\可爱项目(python)\植物大战僵尸\res\shovel.jpg")
shovel_img.set_colorkey((255,255,255))
sun_kc = p.image.load(r"C:\Users\Administrator\.vscode\可爱项目(python)\植物大战僵尸\res\sunflower\sunflower_kc.jpg")
sun_kc.set_colorkey((255,255,255))
pea_kc = p.image.load(r"C:\Users\Administrator\.vscode\可爱项目(python)\植物大战僵尸\res\peashooter\peashooter_kc.jpg")
pea_kc.set_colorkey((255,255,255))
all_kc = {"sunflower":sun_kc,"peashooter":pea_kc}
sunlight_img = p.image.load(r"C:\Users\Administrator\.vscode\可爱项目(python)\植物大战僵尸\res\sunflower\sunlight.jpg")
sunlight_img.set_colorkey((255,255,255))

plant = None
plant_name = ""
shovel = False
shovel_pos = (920,5)
nomoney = {"time":0,"bool":False,"pos":None}
norest = {"time":0,"bool":False,"pos":None}
def in_rect(pos:list,rect:p.rect.Rect):
    x = rect.x
    y = rect.y
    if (pos[0] in range(x,x+rect.width)) and (pos[1] in range(y,y+rect.height)):
        return True
    else:
        return False
def get_gpos(pos:list):
    for i in range(9):
        for j in range(5):
            rect = p.rect.Rect(10+i*100,70+j*100,100,100)
            if in_rect(pos=pos,rect=rect):
                return j+1,i+1
def game_over():
    global died,sunlights,my_map
    bg = p.surface.Surface((900,600))
    bg.fill((50,50,50))
    scr.blit(bg,(50,50))
    wd1 = FONT.render("你死了!",True,(255,255,255))
    scr.blit(wd1,(100,100))
    wd2 = FONT.render("按【R】键重来",True,(255,255,255))
    scr.blit(wd2,(100,150))
    wd3 = FONT.render("按【Q】键退出",True,(255,255,255))
    scr.blit(wd3,(100,200))
    for e in p.event.get():         #事件监听
        if e.type==p.QUIT:
            p.quit()
            sys.exit()
        elif e.type==p.KEYDOWN:
            if e.key==p.K_r:
                died = False
                cls.died = died
                sunlights = 500
                cls.sunlights = sunlights
                my_map = [
                    [None,None,None,None,None,None,None,None,False],
                    [None,None,None,None,None,None,None,None,False],
                    [None,None,None,None,None,None,None,None,False],
                    [None,None,None,None,None,None,None,None,False],
                    [None,None,None,None,None,None,None,None,False],
                ]
                cls.my_map = my_map
                plant_t.Group.empty()
                zombie_t.Group.empty()
            elif e.key==p.K_q:
                p.quit()
                sys.exit()

pyautogui.press("shift")
p.mixer.music.load(r"C:\Users\Administrator\.vscode\可爱项目(python)\植物大战僵尸\snd\bgm.mp3")
p.mixer.music.play(-1)
normal_zombie()
while True:
    p.display.set_caption("植物大战僵尸(代码复刻版)   fps:%.0f"%clock.get_fps())
    if died:
        game_over()
    else:
        for e in p.event.get():         #事件监听
            if e.type==p.QUIT:
                p.quit()
                sys.exit()
            if e.type==p.MOUSEBUTTONDOWN:
                pos = list(p.mouse.get_pos())
                for sun in sunlight.Group:
                    if in_rect(pos=pos,rect=sun.rect):
                        sun.get()
                        sunlights = cls.sunlights
                for n,k in all_kc.items():
                    rect = p.rect.Rect(220+names.index(n)*60,5,k.get_rect().width,k.get_rect().height)
                    if in_rect(pos=pos,rect=rect):
                        plant = p.image.load(table[n][0])
                        plant = p.transform.scale_by(plant,(0.5,0.5))
                        plant.set_colorkey((255,255,255))
                        plant_name = n
                s_rect = shovel_img.get_rect()
                if in_rect(pos=pos,rect=p.rect.Rect(shovel_pos[0],shovel_pos[1],s_rect.width,s_rect.height)):
                    shovel = True
            if e.type==p.MOUSEBUTTONUP:
                pos = list(p.mouse.get_pos())
                try:
                    r,c = get_gpos(pos=pos)
                except:
                    plant = None
                    shovel = False
                    continue
                if plant != None:
                    if pos[1]>DOCK_Y and table[plant_name][1]<=sunlights and my_map[r-1][c-1]==None:
                        exec("%s(r,c)"%plant_name)
                        sunlights -= table[plant_name][1]
                        cls.sunlights = sunlights#文件同步
                    elif table[plant_name][2]>sunlights:
                        nomoney["bool"] = True
                        nomoney["pos"] = ((c-1)*110-50,100+((r-1)*110))
                    elif my_map[r-1][c-1]!=None:
                        norest["bool"] = True
                        norest["pos"] = ((c-1)*110-50,100+((r-1)*110))
                    plant = None
                elif shovel:
                    shovel_plant = my_map[r-1][c-1]
                    if shovel_plant != None:
                        sunlights += int(shovel_plant.need_sun/2)
                        cls.sunlights = sunlights#文件同步
                        shovel_plant.kill()
                        shovel_plant = None
                        my_map[r-1][c-1] = None
                    shovel = False
            if e.type==SUN_EVEVT:
                sunlight(randint(0,ROAD_X))
            if e.type==PEA_EVEVT:
                for peas in peashooter.Group:
                    if my_map[peas.pos[0]-1][8]:
                        peas.shoot()
            if e.type==ZOMBIE_EVEVT:
                normal_zombie()
        scr.blit(background,(0,0))
        plant_t.Group.draw(scr)
        plant_t.Group.update()
        zombie_t.Group.draw(scr)
        zombie_t.Group.update()
        item_t.Group.draw(scr)
        item_t.Group.update()
        for enum,kc in enumerate(all_kc.values()):
            scr.blit(kc,(220+enum*60,5))
        scr.blit(sunlight_img,(10,10))
        scr.blit(FONT.render(":%d"%sunlights,True,(255,255,255)),(65,10))
        for sunf in sunflower.Group:
            if sunf.last_time>600:
                pos = list(sunf.rect.center)
                sunlight(pos[0],pos[1])
                sunf.last_time = 0
        gps = get_gpos(p.mouse.get_pos())
        if plant!=None:
            scr.blit(plant,p.mouse.get_pos())
        if shovel:
            scr.blit(shovel_img,p.mouse.get_pos())
        else:
            scr.blit(shovel_img,shovel_pos)
        if nomoney["bool"]:
            nomoney["time"] += 1
            scr.blit(FONT.render("你没阳光!",True,(255,255,255)),nomoney["pos"])
            if nomoney["time"]==100:
                nomoney["bool"] = False
                nomoney["time"] = 0
        if norest["bool"]:
            norest["time"] += 1
            scr.blit(FONT.render("没有地方!",True,(255,255,255)),norest["pos"])
            if norest["time"]==100:
                norest["bool"] = False
                norest["time"] = 0

        for z in zombie_t.Group:
            scr.blit(FONT.render(str(z.hp),True,(255,255,255)),(z.rect.x+2,z.rect.y-10))
        for pl in plant_t.Group:
            scr.blit(FONT.render(str(pl.hp),True,(255,255,255)),(pl.rect.x+20,pl.rect.y-10))

    cls.my_map = my_map#文件同步
    died = cls.died
    p.display.flip()
    clock.tick(60)

(可真是一个心血来潮啊!)

效果

结语

        这还只是V1.0,以后还会继续编的,希望以后它能实现好多种植物和僵尸!

        (博主上初中了,不知道还有没有时间)

植物大战僵尸是一款经典的塔防游戏,它包含了许多有趣的元素和策略。要使用Pygame制作一款植物大战僵尸游戏,你需要考虑以下几个步骤: 1. **创建游戏界面**:首先,你需要创建一个基本的游戏界面,包括背景、植物、僵尸和道具等元素。可以使用Pygame的矩形类来创建这些元素。 2. **实现游戏逻辑**:接下来,你需要实现游戏的基本逻辑,包括如何种植植物,如何攻击僵尸,如何处理游戏中的不同状态(例如,僵尸的死亡或植物的升级)等。可以使用Pygame的事件处理机制来处理用户的输入和游戏状态的变化。 3. **添加音效和音乐**:为了增加游戏的吸引力,你可以为游戏添加音效和音乐。Pygame提供了对音频文件的支持,你可以使用Pygame的音效类来加载和播放音频文件。 4. **实现难度系统**:为了增加游戏的挑战性,你可以实现一个难度系统,根据玩家的表现调整游戏的难度。例如,玩家可以通过击败更多的僵尸来提高他们的等级,从而获得更强大的植物和道具。 5. **添加多人模式**:如果你想让游戏更加有趣,你可以考虑添加一个多人模式。玩家可以在同一台机器上与其他玩家进行对战,或者通过网络与其他玩家进行对战。 6. **优化性能**:由于植物大战僵尸是一款塔防游戏,它需要大量的计算资源来处理游戏中的各种元素和逻辑。因此,你需要优化游戏的性能,以确保游戏的流畅运行。 下面是一个简单的示例代码,展示了如何使用Pygame创建一个基本的植物大战僵尸游戏界面: ```python import pygame import sys # 初始化Pygame pygame.init() # 设置窗口大小 screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) # 设置游戏标题 pygame.display.set_caption("植物大战僵尸") # 加载背景图片 background_image = pygame.image.load("background.png") # 创建游戏循环 while True: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: # 处理玩家按键事件,例如种植植物或攻击僵尸等 pass # 填充背景颜色 screen.fill((0, 0, 0)) # 绘制背景图片 screen.blit(background_image, (0, 0)) # 实现你的游戏逻辑,例如种植植物和攻击僵尸等 pass ``` 请注意,这只是一个简单的示例代码,用于展示如何使用Pygame创建一个基本的游戏界面。要制作一款完整的植物大战僵尸游戏,你需要实现更多的游戏元素和逻辑,并优化游戏的性能。此外,你可能还需要学习更多关于Pygame的知识和技术,例如使用粒子系统来模拟游戏中的效果,使用音频和视频文件等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值