Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

python - Create multiple instances of a class

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...