SoFunction
Updated on 2025-03-03

Sample code for implementing the Plant vs. Zombies game based on Python

introduction

Plants vs. Zombies is a classic tower defense game where players plant various plants to resist zombies’ attacks. Developed by PopCap Games, the game has been loved by players around the world since its release. This article will explain in detail how to implement a simple plant vs. zombie game using Python and Pygame libraries. We will gradually analyze the game logic, interface design, character model, etc., and provide complete code examples to help newbies understand and implement this game.

1. Preparation for game development environment

Before we start coding, we need to prepare the development environment. We will use the following technology stack:

  • Python: Programming Language
  • Pygame: A library for developing games

The Pygame library can be installed through the following command:

pip install pygame

2. Project structure definition

A simple plant vs. zombie game can contain the following files:

plants_vs_zombies/  
├──  
├──  
├──  
├──  
├── resources/  
│   ├── plants/  
│   ├── zombies/  
│   └──  
└──

  • : The main entrance to the game
  • : Game logic and control
  • : Definition of plants
  • : Definition of zombie
  • resources/: store all images and resource files

3. Main program entrance

First, we create the main entrance file of the game. In this file, we will initialize Pygame, set the window size and title, and start the game loop.

import pygame  
from game import Game  
  
# Initialize Pygame()  
  
# Settings windowWIDTH, HEIGHT = 800, 600  
screen = .set_mode((WIDTH, HEIGHT))  
.set_caption("Plant vs. Zombies")  
  
# Game main loopdef main():  
    game = Game(screen)  
    ()  
  
if __name__ == "__main__":  
    main()

4. Game logic

Next, we write the game logic. In this class, we will handle the game's status, update the screen, and check events.

import pygame  
from plants import Plant  
from zombies import Zombie  
  
class Game:  
    def __init__(self, screen):  
         = screen  
         = ()  
         = True  
         = []  
         = []  
        self.load_resources()  
  
    def load_resources(self):  
        # Load initial resources, such as plants and zombies (the actual resources are not loaded here for the time being)        pass  
  
    def run(self):  
        while :  
            self.handle_events()  
            ()  
            ()  
            (60)  # Control frame rate  
    def handle_events(self):  
        for event in ():  
            if  == :  
                 = False  
            elif  == :  
                # When clicking on the mouse, place a plant in the click position                x, y = .get_pos()  
                # Here we randomly select a plant type, which can actually be used as a selection interface                plant_type = "peashooter"  # Suppose there is a picture of a pea shooter                (Plant(x, y, f"resources/plants/{plant_type}.png"))  
  
    def update(self):  
        # Update plant and zombie status        for plant in :  
            ()  
        for zombie in :  
            ()  
  
            # Here you can add zombie generation logic, such as generating a zombie every once in a while            if len() < 5 and .get_ticks() % 5000 == 0:  
                (Zombie(WIDTH, (50, HEIGHT - 100), f"resources/zombies/"))  
  
    def draw(self):  
        ((255, 255, 255))  # Fill background color  
        # Draw plants and zombies        for plant in :  
            ()  
        for zombie in :  
            ()  
  
        ()  # Update the screen

V. Plants

We need to create a class for various plants. Each plant may have different properties and methods, such as attacking, generating sunlight, etc.

import pygame  
  
class Plant:  
    def __init__(self, x, y, image_path):  
         = x  
         = y  
         = (image_path)  
         = .get_rect(center=(x, y))  
         = 100  # Initial Health         = False  # Are you shooting        self.shot_count = 0  # Shooting Counter  
    def update(self):  
        # Update plant status (such as blood loss, etc.)        # Here you can add shooting logic, such as shooting every once in a while        if not  and .get_ticks() % 2000 == 0:  
             = True  
            self.shot_count = 0  
  
        if :  
            self.shot_count += 1  
            if self.shot_count >= 20:  # Assume that it shoots every 20 frames                 = False  
                self.shot_count = 0  
                # Here you can add the logic for firing bullets  
    def draw(self, screen):  
        (, (, ))

6. Zombies

Again, we create a class for zombies. Zombies will also have different types, with different movement speeds and health points.

import pygame  
import random  
  
class Zombie:  
    def __init__(self, x, y, image_path):  
         = x  
         = y  
         = (image_path)  
         = .get_rect(center=(x, y))  
         = 50  # Initial Health         = (1, 3)  # Random movement speed  
    def update(self):  
        # Zombies move to the left         -=   
  
        # Check if the zombies are out of the screen, and if so, remove them        if  < -:  
            ()  # Suppose we have a kill method to remove zombies (it is not actually defined and needs to be added in the class)  
    def kill(self):  
        # The logic for actually removing zombies (here you can remove them from the list)        pass  
  
    def draw(self, screen):  
        (, (, ))

Note: In the above code, the kill method of the Zombie class is a placeholder. In fact, we need to handle the removal of zombies in the game logic. An easy way is to store the zombies in a list and remove them from the list when it needs to be removed.

7. Resource preparation and loading

In the resource directory, we need to prepare image files for plants and zombies. You can find suitable materials online or draw them yourself. Make sure that the naming of the image file is consistent with the path in the code.

For example, name the pea shooter's picture and put it in the resources/plants/ directory, and name the ordinary zombies picture and put it in the resources/zombies/ directory.

8. Complete game logic

In order to improve the game logic, we need to add the following functions:

Collision Detection: Detects whether plants and zombies collide and updates their health based on the collision results.
Bullet System: Add bullets to plants to reduce the health of the zombies when the bullet hits them.
Game End Conditions: The game ends when all zombies are destroyed or the health of the plants is reduced to zero.
Scoring system: Record player scores and achievements.
The implementation of these functions requires further coding and debugging, and this article will not be expanded in detail.

9. Case demonstration and operation

Once all the code files and resource files are ready, run to start the game. You will see a simple Plant vs. Zombies game interface, which can be planted by clicking the mouse, and the zombies will be generated from the right side of the screen and moved to the left.

10. Summary

This article details how to use Python and Pygame libraries to implement a simple plant vs. zombie game. The game logic, interface design, character model and other aspects were gradually analyzed, and a complete code example was provided. I hope this article can help newbies understand and implement this game and lay the foundation for further game development.

Of course, this is just a simple implementation, and there are many things to improve and expand. For example, you can add more plant and zombie types, increase level design, optimize game performance, improve user experience, and more.

The above is the detailed content of the sample code for implementing the Plant vs. Zombie Game based on Python. For more information about the Python Plant vs. Zombie Game, please follow my other related articles!