pygame games - Zombie battle

Game diagram

Game introduction:

Player 1 controls the up, down, left and right movement of the characters through the wa s d key, and the Q key is to fire bullets.

Player 2 controls the up and down left and right movement of characters by ↑ ↓ ←→ key, and the space bar is to launch bullets.

The number of zombies defeated by players is shown on the top of the game

If one of the two players touches the zombie, it will be judged as a failure of the game.

Game making steps

1. Collect materials
2. Write the code and make the general window
3. Define the PlaneGame class, Sprite class and background class of the main game
4. Define the first and second heroes, bullets and monsters.
5. Define function (control player movement, bullet launch, monster random appearance)
6. Improve the layout

Gathering Materials

Prepare the required picture material through ps processing.

Materials for background music

Write program code

1. Create the PlaneGame class of the main game for initialization

    def __init__(self):
        self.screen = pygame.display.set_mode((SCREEN_RECT.width, SCREEN_RECT.height))
        self.clock = pygame.time.Clock()
        self.__create_sprites()
        pygame.time.set_timer(CREATE_ENEMY_EVENT, 500)
        # pygame.time.set_timer(HERO_FIRE_EVENT,500)
        self.jifen = 0
        self.kifen = 0

2. Start the game

 def start_game(self):
        print("Start the game")
        while True:
            self.clock.tick(60)
            self.name = pygame.display.set_caption("Zombie War")
            self.__handler_event()
            self.__check_collide()
            self.__update_sprites()
            self.__print_score()
            pygame.display.update()

3. Create a privatized spirit family

    def __create_sprites(self):
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)
        self.eero = Eero()
        self.eero_group = pygame.sprite.Group(self.eero)
        self.enemy = Enemy()
        self.enemy_group = pygame.sprite.Group(self.enemy)
        bg1 = BackGround()
        bg2 = BackGround(True)
        self.back_group = pygame.sprite.Group(bg1, bg2)

4. Create a listening event (including the setting of the keyboard key to exit the window and launch bullets)

def __handler_event(self):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        elif event.type == CREATE_ENEMY_EVENT:
            new_enemy = Enemy()
            self.enemy_group.add(new_enemy)
        #print("enemy aircraft coming out...")

        elif event.type == HERO_FIRE_EVENT:
            self.hero.fire()
            self.eero.fire()

        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_RIGHT]:
            self.hero.speed = 8
        elif keys_pressed[pygame.K_LEFT]:
            self.hero.speed = -8
        elif keys_pressed[pygame.K_UP]:
            self.hero.speed1 = -8
        elif keys_pressed[pygame.K_DOWN]:
            self.hero.speed1 = 8
        elif keys_pressed[pygame.K_SPACE]:
            self.hero.fire()
        else:
            self.hero.speed = 0
            self.hero.speed1 = 0
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_d]:
            self.eero.speed = 8
        elif keys_pressed[pygame.K_a]:
            self.eero.speed = -8
        elif keys_pressed[pygame.K_w]:
            self.eero.speed2 = -8
        elif keys_pressed[pygame.K_s]:
            self.eero.speed2 = 8
        elif keys_pressed[pygame.K_q]:
            self.eero.fire()
        else:
            self.eero.speed = 0
            self.eero.speed2 = 0

5. Create a collision detection event (when a monster touches a character and exits the game)

    def __check_collide(self):
        if pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True):
            self.jifen += 1
        elif pygame.sprite.groupcollide(self.eero.bulletsa, self.enemy_group, True, True):
            self.kifen += 1
        enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
        enemies2 = pygame.sprite.spritecollide(self.eero, self.enemy_group, True)

        if len(enemies) > 0:
            self.hero.kill()
            self.hero.rect.y = 10000000000
        if len(enemies2) > 0:
            self.eero.kill()
            self.eero.rect.y = 10000000000
        if self.hero.rect.y == self.eero.rect.y:
            self.__game_over()

6. Create refresh screen refresh sprite group (including background picture, hero picture, bullet picture, zombie picture refresh and draw to the screen)

    def __update_sprites(self):
        # 1 update position 2 draw
        self.back_group.update()
        self.back_group.draw(self.screen)
        self.hero_group.update()
        self.hero_group.draw(self.screen)
        self.eero_group.update()
        self.eero_group.draw(self.screen)
        self.enemy_group.update()
        self.enemy_group.draw(self.screen)
        self.hero.bullets.update()
        self.hero.bullets.draw(self.screen)
        self.eero.bulletsa.update()
        self.eero.bulletsa.draw(self.screen)

7. Create spirit class

class GameSprite(pygame.sprite.Sprite):
    def __init__(self, image_name, speed=1):
        super().__init__()
        self.image = pygame.image.load(image_name)
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self, *args):
        self.rect.x += self.spee

8. Create background class

class BackGround(GameSprite):
    def __init__(self, is_alt=False):
        image_name = "./pictures/scene.png"
        super().__init__(image_name)
        if is_alt:
            self.rect.x = 1101

9. Create first hero and first bullet

class Hero(GameSprite):
    def __init__(self):
        super().__init__("./pictures/player.png")
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom - 120

        self.bullets = pygame.sprite.Group()
        self.speed1 = 0

    def update(self):
        self.rect.x += self.speed
        self.rect.y += self.speed1
        if self.rect.y + self.rect.height <= 0:
            self.rect.y = 50
        elif self.rect.y + self.rect.height >= 600:
            self.rect.y = 500
        elif self.rect.left < 0:
            self.rect.left = 0
        elif self.rect.right > SCREEN_RECT.right:
            self.rect.right = SCREEN_RECT.right

    def fire(self):

        for i in (0, 1):
            self.bullet = Bullet()
            # Set sprite location
            self.bullet.rect.x = self.rect.x + 15 * i + self.rect.width
            self.bullet.rect.centery = self.rect.centery - 20
            # Add sprites to sprite group
            self.bullets.add(self.bullet)
class Bullet(GameSprite):
    def __init__(self):
        super().__init__("./pictures/boom.png", 20)

    def update(self):
        super().update()

        # Determine whether to exceed the screen if it is removed from the sprite group

        if self.rect.bottom < 0:
            self.kill()

10. Create second hero and second bullet

class Eero(GameSprite):
    def __init__(self):
        super().__init__("./pictures/player1.png")
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom - 200
        self.speed2 = 0
        self.bulletsa = pygame.sprite.Group()

    def update(self):
        self.rect.x += self.speed
        self.rect.y += self.speed2
        if self.rect.y + self.rect.height <= 0:
            self.rect.y = 50
        elif self.rect.y + self.rect.height >= 700:
            self.rect.y = 500
        elif self.rect.left < 0:
            self.rect.left = 0
        elif self.rect.right > SCREEN_RECT.right:
            self.rect.right = SCREEN_RECT.right

    def fire(self):
        for i in range(1, 4):
            self.bullet2 = Bullet2()
            # Set sprite location
            self.bullet2.rect.x = self.rect.x + 15 * i + self.rect.width
            self.bullet2.rect.centery = self.rect.centery - 20
            # Add sprites to sprite group
            self.bulletsa.add(self.bullet2)
class Bullet2(GameSprite):
    def __init__(self):
        super().__init__("./pictures/boom.png", 10)

    def update(self):
        super().update()

        if self.rect.bottom < 0:
            self.kill()

11. Create monster class

class Enemy(GameSprite):
    def __init__(self):
        super().__init__("./pictures/monster1.png")
        self.speed = random.randint(5, 8)
        self.rect.x = 1101
        max_y = SCREEN_RECT.height - self.rect.height
        self.rect.y = random.randint(self.rect.height, max_y)

    def update(self):
        self.rect.x -= self.speed
        if self.rect.right <= 0:
            # print("the plane flies out of the screen")
            self.kill()

    def __del__(self):
        pass
    # print("enemy aircraft destroyed% s"%self.rect)

12. Create game ending interface

import pygame
from sys import exit

pygame.init()
screen = pygame.display.set_mode((1101, 600), 0, 32)
pygame.display.set_caption("Zombie War")
upImageFilename = 'pictures/game.jpg'
downImageFilename = 'pictures/game.jpg'


class Button(object):
    def __init__(self, upimage, downimage, position):
        self.imageUp = pygame.image.load(upimage).convert_alpha()
        self.imageDown = pygame.image.load(downimage).convert_alpha()
        self.position = position

    def isOver(self):
        point_x, point_y = pygame.mouse.get_pos()
        x, y = self.position
        w, h = self.imageUp.get_size()

        in_x = x - w / 2 < point_x < x + w / 2
        in_y = y - h / 2 < point_y < y + h / 2
        return in_x and in_y

    def render(self):
        w, h = self.imageUp.get_size()
        x, y = self.position

        if self.isOver():
            screen.blit(self.imageDown, (x - w / 2, y - h / 2))
        else:
            screen.blit(self.imageUp, (x - w / 2, y - h / 2))


button = Button(upImageFilename, downImageFilename, (550, 300))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
    screen.fill((100, 200, 200))
    button.render()
    pygame.display.update()

Posted by ss32 on Tue, 14 Apr 2020 00:28:40 -0700