Blue
Blue

Reputation: 251

Pygame - Creating a "Enemy" class, and then importing it into game

Okay, so basically what I'm trying to do is keep the main file a little cleaner and I'm starting with the "Zombie" enemy by making it's own file which will most likely contain all enemies, and importing it in.

So I'm confused on how I'd set-up the Class for a sprite, you don't have to tell me how to get it to move or anything like that I just want it to simply appear. The game doensn't break when I run it as is, I just wanted to ask this question before I goto sleep so I can hopefully get a lot done with the project done tomorrow (School related)

Code is unfinished like I said just wanted to ask while I get some actual sleep just a few google searches and attempts.

Eventually I'll take from the advice given here to make a "Hero" class as well, and as well as working with importing other factors if we have the time.

Zombie code:

import pygame
from pygame.locals import *

class ZombieEnemy(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('images/zombie.png')
#       self.images.append(img)
        # self.image = self.images[0]
        self.rect = self.image.get_rect()

zombieX = 100
zombieY = 340
zombieX_change = 0

Main Code:

import pygame
from pygame.locals import *
import Zombie
# Intialize the pygame
pygame.init()

# Create the screen 
screen = pygame.display.set_mode((900, 567))


#Title and Icon
pygame.display.set_caption("Fighting Game")

# Add's logo to the window 
# icon = pygame.image.load('')
# pygame.display.set_icon(icon)

# Player
playerImg = pygame.image.load('images/character.png')
playerX = 100
playerY = 340
playerX_change = 0

def player(x,y):
    screen.blit(playerImg,(x,y))

Zombie.ZombieEnemy()

def zombie(x,y):
    screen.blit()

# Background

class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load('images/background.png')
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location

BackGround = Background('background.png', [0,0])

#  Game Loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # If keystroke is pressed check right, left.
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            #playerX_change = -2.0
            BackGround.rect.left = BackGround.rect.left + 2.5
        if event.key == pygame.K_RIGHT:
            #playerX_change = 2.0
            BackGround.rect.left = BackGround.rect.left - 2.5
    # if event.type == pygame.KEYUP:
    #     if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
    #         BackGround.rect.left = 0

    screen.blit(BackGround.image, BackGround.rect)
    playerX += playerX_change
    player(playerX,playerY)
    pygame.display.flip()

Upvotes: 2

Views: 1900

Answers (2)

Kingsley
Kingsley

Reputation: 14916

Your sprite code is basically mostly there already. But as you say, it needs an update() function to move the sprites somehow.

The idea with Sprites in PyGame is to add them to a SpriteGroup, then use the group functionality for handling the sprites together.

You might want to modify the Zombie class to take an initial co-ordinate location:

class ZombieEnemy(pygame.sprite.Sprite):
    def __init__( self, x=0, y=0 ):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('images/zombie.png')
        self.rect = self.image.get_rect()
        self.rect.center = ( x, y )           # NOTE: centred on the co-ords

Which allows the game to create a Zombie at a particular starting point (perhaps even a random one).

So to have a sprite group, first you need to create the container:

all_zombies = pygame.sprite.Group()

Then when you create a new zombie, add it to the group. Say you wanted to start with 3 randomly-positioned zombies:

for i in range( 3 ):
    new_x = random.randrange( 0, WINDOW_WIDTH )       # random x-position
    new_y = random.randrange( 0, WINDOW_HEIGHT )      # random y-position
    all_zombies.add( Zombie( new_x, new_y ) )         # create, and add to group

Then in the main loop, call .update() and .draw() on the sprite group. This will move and paint all sprites added to the group. In this way, you may have separate groups of enemies, bullets, background-items, etc. The sprite groups allow easy drawing and collision detection between other groups. Think of colliding a hundred bullets against a thousand enemies!

while running:
    for event in pygame.event.get():
        # ... handle events

    # Move anything that needs to
    all_zombies.update()                 # call the update() of all zombie sprites
    playerX += playerX_change

    # Draw everything
    screen.blit(BackGround.image, BackGround.rect)
    player(playerX,playerY)                          
    all_zombies.draw( screen )           # paint every sprite in the group

    pygame.display.flip()

EDIT: Added screen parameter to all_zombies.draw()

It's probably worthwhile defining your player as a sprite too, and having a single-entry group for it as well.

Upvotes: 4

furas
furas

Reputation: 142909

First you could keep position in Rect() in class. And you would add method which draws/blits it.

import pygame

class ZombieEnemy(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('images/zombie.png')
        self.rect = self.image.get_rect()
        self.rect.x = 100
        self.rect.y = 340
        self.x_change = 0

    def draw(self, screen):
        screen.blit(self.image, self.rect)

Next you have to assign to variable when you create it

zombie = Zombie.ZombieEnemy()

And then you can use it to draw it

zombie.draw(screen)

in

screen.blit(BackGround.image, BackGround.rect)
player(playerX,playerY)

zombie.draw(screen)

pygame.display.flip()

The same way you can create class Player and add method draw() to class Background and then use .

background.draw(screen)
player.draw(screen)

zombie.draw(screen)

pygame.display.flip()

Later you can use pygame.sprite.Group() to keep all objects in one group and draw all of them using one command - group.draw()

Upvotes: 0

Related Questions