Create multiple instances of a class

2019-09-20 06:07发布

问题:

I'm working on a space invaders type of game in Pygame. So far I just have the basics of the game down:

import pygame, sys, os, math, random, time
from pygame.locals import *

pygame.init()

window = pygame.display.set_mode((1000,500))
screen = pygame.display.get_surface()

spaceBackground = pygame.image.load("C:/Users/LN/Desktop/space-background.png")
spaceShip = pygame.image.load("C:/Users/LN/Desktop/space-ship.png")
bullet = pygame.image.load("C:/Users/LN/Desktop/bullet.png")
enemyShip = pygame.image.load("C:/Users/LN/Desktop/enemyAircraft.png")
class move():
    '''Move the space ship'''

    def _init_(self):
        screen.blit(spaceBackground, (0,0))
        self.position = spaceShip.get_rect()
        self.position = self.position.move(500,477)
        global place
        place = self.position
        pygame.display.flip()

    def moveUp(self):
        screen.blit(spaceBackground, self.position, self.position)
        self.position = self.position.move(0,-2)
        global place
        place = self.position

    def moveDown(self):
        screen.blit(spaceBackground, self.position, self.position)
        self.position = self.position.move(0,2)
        global place
        place = self.position

    def moveLeft(self):
        screen.blit(spaceBackground, self.position, self.position)
        self.position = self.position.move(-2,0)
        global place
        place = self.position

    def moveRight(self):
        screen.blit(spaceBackground, self.position, self.position)
        self.position = self.position.move(2,0)
        global place
        place = self.position

    def update(self):
        screen.blit(spaceShip, self.position)

    def notTooLow(self):
        if self.position[1] < (478):
            return True
        else:
            return False

    def notTooHigh(self):
        if self.position[1] > (4):
            return True
        else:
            return False
    def notTooRight(self):
        if self.position[0] < (974):
            return True
        else:
            return False

    def notTooLeft(self):
        if self.position[0] > (5):
            return True
        else:
            return False


class shoot():
    '''Shoots bullets out of the ship'''

    def _init_(self):
        global bulletUp
        bulletUp = False
        self.position = (0,0)

    def startMoveUp(self):
        self.position = place
        self.position = self.position.move(11,0)

    def bulletOnScreen(self):
        if self.position[1] > -5:
            return True
        else:
            global bulletUp
            bulletUp = False

    def moveUp(self):
        screen.blit(spaceBackground, self.position)
        self.position = self.position.move(0,-6)
        screen.blit(bullet, self.position)
        screen.blit(spaceShip, place)


class enemy():
    '''Spawn and control enemies'''

    def _init_(self):
        global numbEnemy
        numbEnemy = 0
        self.position = enemyShip.get_rect()

    def moveSpawn(self):
        self.position = self.position.move(0,50)

    def spawnEnemy(self):                                 
        screen.blit(enemyShip, (500, 20))
        self.position = enemyShip.get_rect()

    def moveEnemy(self):
        screen.blit(spaceBackground, self.position)
        self.position = self.position.move(0,1)
        screen.blit(enemyShip, self.position)






move = move()
move._init_()
shoot = shoot()
shoot._init_()
enemy = enemy()
enemy._init_()



counter = 0
while True:
    if counter//300*300 == counter:
        enemy.spawnEnemy()
    if counter//2*2 == counter:
        enemy.moveEnemy()
    if pygame.key.get_pressed()[K_UP] and move.notTooHigh():
        move.moveUp()
    pygame.event.pump()
    if pygame.key.get_pressed()[K_DOWN] and move.notTooLow():
        move.moveDown()

What I'm not sure how to do, is create multiple enemy ships. Is there a simple way to make it so I can spawn another ship, without deleting the other?

回答1:

Let's say you have a class called enemy in your game. For the sake of brevity, I won't define the functions explicitly and will just use pass statements as placeholders.

class Enemy:
    def __init__(self):
        pass

    def update(self):
        pass

    def draw(self, display_surface):
        pass

To create multiple enemies you just need to do create a list of enemies where you will store all your reference to your currently active enemy objects.

enemies = []

To add a single enemy, you just append a call of the constructor of enemy to your list. You can do this as many times as you want.

enemies.append(Enemy())

As @monkey also mentioned in the comments, you can easily use list comprehension to set your list of active enemies to multiple object instances at once.

enemies = [Enemy() for x in range(10)]

Then in your game loop, you do something like the following in every iteration:

for enemy in enemies: # loop through all your active enemies
    enemy.update() # Update the state of every enemy.

for enemy in enemies: # once again loop through all your active enemies
    enemy.draw(display_surface) # Draw the image of every enemy to the display surface.

And that is a basic example of how you neatly do object-oriented game programming in Pygame.