Guide language:
Hello, hello, plants vs. zombies are popular for many years, from sunflowers that shake their heads to tutuku ⚾⚾⚾ pea shooters spitting bullets! Slow-moving, diverse zombies… The most memorable was “Zombies eat your brains!” And crazy Dave, all of them reminding us of our childhood. Use Python to restore your childhood memory.
The functions are as follows:
-
Supported plant types: sunflowers, pea shooters, nuts.
-
Supported zombie types: Normal zombie, chess zombie, barricade zombie, iron bucket zombie.
-
Use JSON files to save level information and set the time and location of zombies.
-
Increased the selection of playing plants at the start of each level.
If you are interested in the source code and Python, you can click on this font.
First, configure the image address
Import Pygame from Pygame.locals import * import sys import OS # Initialize Pygame.init () # set bg_size = (1200, Screen = Pygame.display. Set_mode (bg_size) # Set screen caption pygame.display. Set_mode (bg_size) # Set screen caption pygame.display rootpath = os.getcwd() # imgpath = os.path.join(rootpath,background_path) background_path = "Material/images/background1. JPG" sun_path = "material/images/SunBack. PNG" backgrounImg = # loading background images Pygame.image.load (background_path).convert() sunImg = pygame.image.load(sun_path).convert() # set the text myfont = myfont Pygame.font.SysFont("arial",20) txtImg = myfont. Render ("50",True,(255,255,0)) while True: For event in Pygame.event.get (): if event.type == QUIT: Sys.exit () # draw the background screen.blit(backgrounImg, (0, 0)) # draw the top sun number bar screen.blit(sunImg, (250, 0)) screen. Blit (txtImg, (320)). Pygame display. The update ()Copy the code
Two, sunflower
class Sunflower(Plant): def __init__(self,x,y): super(Sunflower, self).__init__() self.image = pygame.image.load('imgs/sunflower.png') self.rect = self.image.get_rect() self.rect.x = x Self.rect. y = y self.price = 50 self.price = 100 # time_count = 0 # def produce_money(self): self.time_count += 1 if self.time_count == 25: Money += 5 self.time_count = 0 def display_sunflower(self) MainGame.window.blit(self.image,self.rect)Copy the code
Pea shooters
Class PeaShooter(Plant): def __init__(self,x,y): super(PeaShooter, Self).__init__() # self. Image for a surface self.image = Pygame.image.load ('imgs/peashooter.png') self Self.image.get_rect () self.rect.x = x self.rect.y = y self.price = 50 self.hp = 200 # shot_count = 0 # Def shot(self): "if you want to shoot a zombie in maingame.zombie_list" if zombie.rect.y == self.rect.y and zombie.rect.x < 800 and zombie.rect.x > self.rect.x: If self.live and self.shot_count == 1 # if self.live and self.shot_count == 1 # # Based on the current pea shooter position, Create bullet Peabullet = Peabullet (self) # Store bullets in bullet list maingame.peabullet_list.append (peabullet) self.shot_count = 0 # Def display_peashooter(self) adds peashooter to window: Maingame.window. Blit (self.image,self.rect) # PeaBullet(pygame.sprite.sprite): def __init__(self,peashooter): self.live = True self.image = pygame.image.load('imgs/peabullet.png') self.damage = 50 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): If self.rect.x < scrrr_width: self.rect.x += self.rect.x += self.speed else: 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()Copy the code
Add nuts
nuts
Import pygame # create class WallNut(pygame.sprite): # create function def __init__(self): super(WallNut, Self).__init__() # Create the Pea Shooter object self.image = Pygame.image.load (' Material /images/ wallnut_00.png ').convert_alpha() # create animation self.images = [pygame.image.load('material/images/WallNut_{:02d}.png'.format(i)) for i in range(0, Images [0].get_rect() self.rect.top = 260 self.rect.left = 230 # update the position of the tree def update(self, *args): self.image = self.images[args[0] % len(self.images)]Copy the code
import pygame from pygame.locals import * import sys from Peashooter import Perashooter from SunFlower import SunFlower from WallNut import WallNut # import os # rootPath = os.getcwd() # backgroundPath = os.path.join(rootPath, 'material/images/background2.jpg') # sunbackPath = os.path.join(rootPath, 'material/images/SunBack. PNG') # initialization pygame pygame. The init () size = (1200, Screen = Pygame.display. Set_mode (size) # set screen caption pygame.display. Set_mode (size) # set screen caption pygame.display pygame.image.load('material/images/background1.jpg').convert_alpha() sunbackImg = pygame.image.load('material/images/SunBack.png').convert_alpha() myfont = pygame.font.SysFont('arial', 30) txtImg = myfont.render("50", True, (0, 0, 0)) peashooter = Perashooter() sunFlower = SunFlower() wallnut = WallNut() index = 0 clock = pygame.time.Clock() while For event in Pygame.event.get (): if event.type == QUIT: True: if index > 100: index = 0 clock.tick(5) pygame.quit() sys.exit() screen.blit(backgroundImg, (0, 0)) screen.blit(sunbackImg, (250, 30)) screen.blit(txtImg, (300, 33)) screen.blit(peashooter.images[index % 13], peashooter.rect) index += 1 screen.blit(sunFlower.images[index % 13], sunFlower.rect) index += 1 screen.blit(wallnut.images[index % 13], wallnut.rect) index += 1 pygame.display.update()Copy the code
5. Zombies
class Zombie(pygame.sprite.Sprite): def __init__(self,x,y): super(Zombie, self).__init__() self.image = pygame.image.load('imgs/zombie.png') 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 move_zombie(self): if self.live and not self.stop: self.rect.x -= self.speed if self.rect.x < -80: Def hit_plant(self): for plant in MainGame. Plants_list: def hit_plant(self): for plant in MainGame. if pygame.sprite.collide_rect(self,plant): Self.stop = True self.eat_plant(plant) def eat_plant(self,plant): If plant. HP -= self. Damage 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 # Def display_zombie(self): maingame.window.blit (self.image,self.rect)Copy the code
6. Bullets
Def __init__(self, rect, bg_size): def __init__(self, rect, bg_size) super(Bullet, Self).__init__() # Create bullet object self.image = pygame.image.load(' Material /images/ bullet_1.png ').convert_alpha() Self.rect = self.image.get_rect() self.rect.top = rect.top self.rect.left Def update(self, *args): if self.rect.left < self.width: self.rect.left += self.speed else: self.kill()Copy the code
import pygame from pygame.locals import * import sys from Bullet import Bullet from Peashooter import Peashooter from Sun import Sun from SunFlower import SunFlower from WallNut import WallNut # Initialize Pygame from Zombie import Zombie pygame.init() size = (1200, Screen = Pygame.display. Set_mode (size) # set screen caption pygame.display. Set_mode (size) # set screen caption pygame.display pygame.image.load('material/images/background1.jpg').convert_alpha() sunbackImg = pygame.image.load('material/images/SunBack.png').convert_alpha() myfont = pygame.font.SysFont('arial', 30) txtImg = myfont.render("1000", True, (0, 0, 0)) peashooter = Peashooter() sunFlower = SunFlower() wallNut = WallNut() zombie = Zombie() sunList = pygame.sprite.Group() sunList.add(peashooter) sunList.add(sunFlower) sunList.add(wallNut) sunList.add(zombie) index = 0 clock = pygame.time.Clock() while True: if index > 100: For event in Pygame.event.get (): if event.type == QUIT: pygame.quit() sys.exit() screen.blit(backgroundImg, (0, 0)) screen.blit(sunbackImg, (250, 30)) screen.blit(txtImg, (300, 33)) if index % 30 == 0: bul = Bullet(peashooter.rect, size) sunList.add(bul) if index % 30 == 0: sun = Sun(sunFlower.rect) sunList.add(sun) sunList.update(index) sunList.draw(screen) index += 1 pygame.display.update()Copy the code
Draw the top card
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)Copy the code
Eight, start the program
Class MainGame(): #2 Create level number, score, remaining score, Shaoguan = 1 score = 0 remNANT_score = 100 money = 200 map_points_list = [] #3 Map_list = [] #4 Peabullet_list = [] #9 New zombie list zombie_list = [] count_zombie = 0 Def init_window(self): Init () #1 Create window 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, Def load_help_text(self): text1 = self.draw_text('1 ') 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", 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) print("temp_map_list", temp_map_list) MainGame.map_list.append(temp_map_list) print("MainGame.map_list", Def load_map(self): for temp_map_list in MainGame. Map_list: for map in temp_map_list: Def load_plants(self): for plant in MainGame. Plants_list: if isinstance(plant, Sunflower): plant.display_sunflower() plant.produce_money() elif isinstance(plant, PeaShooter): plant.display_peashooter() plant.shot() else: Def load_peabullets(self): for b in MainGame. Peabullet_list: if b.live: def load_peabullets(self): for b in MainGame. B.diplay_peabullet () b.move_bullet() # v1.9 call method to check if the bullet hit a zombie b.hit_zombie() else: Def deal_events(self): def deal_events(self): EventList == pyGame.event.get () #8 For e in eventList: if e.type == PyGame.quit: self.gameOver() elif e.type == pygame.MOUSEBUTTONDOWN: Print (e.button)# print(e.button)# print(e.button)# print(e.button)# print(e.button)# print(e.button)# print(e.button)# print(e.button)# print(e.button)# print(e.button)# print(e.button)# print(e.button Print (x, y) map = MainGame. Map_list [y - 1][x] print(map. Position) #8 print(map. if map.can_grow and MainGame.money >= 50: sunflower = Sunflower(map.position[0], Map.position [1]) maingame.plants_list. append(sunflower) print(' list length :{}'. 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)) Def init_zombies(self): for I in range(1, 7): dis = random.randint(1, 5) * 200 zombie = Zombie(800 + dis, I * 80) 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 calls whether to hit the plant method zombie.hit_plant() else: Zombie_list. zombie #1 def start_game(self): Init_points () #3 Initialize coordinates and maps self.init_plant_points() self.init_map() #9 Call the zombie initialization method self.init_zombies() #1 Keep looping while not GAMEOVER until the game is over: #1 Render white background maingame.window.fill ((255, 255, 255)) #2 Render text and coordinate position maingame.window.blit (self.draw_text(' Current money $: {}'. Format (maingame.money), 26, (255, 0, 0), (500, 40)) maingame.window.blit (self.draw_text(' current close {}, Format (MainGame. Shaoguan, MainGame. Score, MainGame. Remnant_score), 26, (255, 0, 0), (5, 40)) self.load_help_text() #3 needs to load the map repeatedly self.load_map() #6 calls the method of loading plants self.load_plants() #7 calls the method of loading all bullets Self.load_peabullets () #8 calls the event handler method self.deal_events() #9 calls the zombie display method self.load_zombies() #9 Count_zombie += 1 if MainGame. Count_zombie == MainGame. Produce_zombie: Self.init_zombies () maingame.count_zombie = 0 #9 Pygame's own sleep PyGame.time.wait (10) #1 Real-time update pyGame.display.update () #10 Def gameOver(self): Maingame.window. blit(self.draw_text(' game over ', 50, (255, 0, 0)), 200)) print(' GAMEOVER ') pygame.time.wait(400) global GAMEOVER GAMEOVER = True #1 game = MainGame() game.start_game()Copy the code
The end:
The article is finished here, like to remember to like oh, need to complete the code can be private xiaobian oh, click on this line of words also!