创建一个类的多个实例 [英] Create multiple instances of a class

查看:141
本文介绍了创建一个类的多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Pygame中从事太空侵略者类型的游戏。到目前为止,我只掌握了游戏的基础知识:

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?

推荐答案

假设您有一艘船在您的游戏中被称为敌人的职业。为了简洁起见,我不会明确定义函数,而只会使用 pass 语句作为占位符。

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 = []

要添加单个敌人,只需追加<$ c的构造函数调用$ c> enemy 到您的列表。您可以根据需要进行多次。

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())

在评论中还提到了@monkey,您可以轻松地使用列表推导将活动敌人的列表一次设置为多个对象实例。

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.

这是一个如何在Pygame中巧妙地进行面向对象游戏编程的基本示例。

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

这篇关于创建一个类的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆