Python 使用类(高效地创建类,每帧绘制和更新类的所有实例)

Python 使用类(高效地创建类,每帧绘制和更新类的所有实例),python,pygame,Python,Pygame,我自己一直在做一个“子弹地狱”游戏,但我很难使用类(我是python新手),下面我附上了我的代码(我不会包含太多,但我不知道如何解决这个问题)。目前我一直在努力 1.创建类的不同实例 2.每帧都画 3.根据x和y速度每帧更新其位置 import pygame # Define colors needed BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) bulletArray =

我自己一直在做一个“子弹地狱”游戏,但我很难使用类(我是python新手),下面我附上了我的代码(我不会包含太多,但我不知道如何解决这个问题)。目前我一直在努力 1.创建类的不同实例 2.每帧都画 3.根据x和y速度每帧更新其位置

import pygame

# Define colors needed

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

bulletArray = []

BulletSprite = ("Bullet4.png")

pygame.init()

class Bullet:
  def __init__(self, sprite, x, y, xSpeed, ySpeed):
    pygame.sprite.Sprite.__init__(self)
    self.x = x
    self.y = y
    self.xSpeed = xSpeed
    self.ySpeed = ySpeed
    bulletArray.append(self)


    def update(self):
      pass

    def draw(screen):
      self.screen = screen
      screen.blit(screen, (x, y))

#Set the width and height of the game screen
size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Bullet stuff")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()


testBullet = Bullet(BulletSprite, 200, 200, 2, 2)
#Main Program Loop
while not done:
  # --- Main event loop
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      done = True

  # --- Game logic should go here



  print(bulletArray)
  # --- background image.
  screen.fill(WHITE)

  # --- Drawing code should go here


  # --- Updates the screen every frame with whats been drawn
  pygame.display.flip()

  # --- Limit to 60 frames per second
  clock.tick(60)

# Close the window and quit.
pygame.quit()

若您使用PyGame,这种机制的大部分已经自动处理了

PyGame精灵基本上由以下部分组成:

  • 要绘制以表示对象的图像
  • 围绕对象的矩形,用于记住位置并检查碰撞
  • 一个
    update()
    函数,用于处理精灵的任何移动
使用现有的PyGame Sprite布局很方便,因为库代码已经提供了很多功能

让我们制作一个BulletSprite:

class BulletSprite( pygame.sprite.Sprite ):

    def __init__( self, bitmap, x, y ):
        pygame.sprite.Sprite.__init__( self )
        self.image        = bitmap                 # How the sprite looks
        self.rect         = bitmap.get_rect()      # Bounding box the size of the image
        self.rect.centerx = x                      # position the bullet 
        self.rect.centery = y                      #   about its centre
就这样。这将为您提供一个静止的精灵,在
(x,y)
屏幕上绘制为给定位图

现在让我们使用它:

# Create a group of 100 bullets
sprite_image = pygame.image.load( "bullet.png" )
all_bullets  = pygame.sprite.Group()               # Group to hold the sprites
for i in range( 100 ):
    random_x   = 50 + random.randrange( 950 )      # TODO: use proper screen size
    random_y   = 50 + random.randrange( 950 )
    new_sprite = BulletSprite( sprite_image, random_x, random_y )
    all_bullets.add( new_sprite )

# Main Window loop
while True:
    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            break

    # Paint the window
    window.fill( ( 0, 0, 0 ) )       # Paint it Black
    all_bullets.update()             # move all the bullets
    all_bullets.draw( window )       # Paint all the bullets

    pygame.display.flip()
pygame.quit()
就这样。创建精灵后,需要两行代码来移动它们并绘制它们

但他们还不会动。要让它们移动,
BulletSprite
需要有一个
update()
函数。此函数执行移动精灵所需的任何操作-应用速度、重力等。净效果是精灵的矩形(x,y)发生了变化

因此,给精灵添加一些更改-首先是
x
y
速度,然后是运动代码

class BulletSprite( pygame.sprite.Sprite ):

    def __init__( self, bitmap, x, y ):
        pygame.sprite.Sprite.__init__( self )
        self.image        = bitmap                 # How the sprite looks
        self.rect         = bitmap.get_rect()      # Bounding box the size of the image
        self.rect.centerx = x                      # position the bullet 
        self.rect.centery = y                      #   about its centre

        self.x_move = random.randrange( -3, 3 )    # simple random velocity
        self.y_move = random.randrange( -3, 3 )

    def update( self ):
        x = self.rect.centerx + self.x_move        # calculate the new position
        y = self.rect.centerx + self.y_move        # by applying an offset

        # has the sprite gone off-screen
        if ( x < 0 or x > 1000 or y < 0 or y > 1000 )
            self.kill()                            # remove from the group
        else:           
            self.rect.centerx = x                  # RE-position the bullet 
            self.rect.centery = y                      
类BulletSprite(pygame.sprite.sprite):
定义初始化(自、位图、x、y):
pygame.sprite.sprite.\uuuuu init\uuuuuuu(自我)
self.image=位图#精灵的外观
self.rect=bitmap.get_rect()#边界框图像的大小
self.rect.centerx=x#定位项目符号
self.rect.centery=y#关于其中心
self.x_move=random.randrange(-3,3)#简单随机速度
self.y_move=random.randrange(-3,3)
def更新(自我):
x=self.rect.centerx+self.x#移动#计算新位置
y=self.rect.centerx+self.y#通过应用偏移移动
#精灵离开屏幕了吗
如果(x<0或x>1000或y<0或y>1000)
self.kill()#从组中删除
其他:
self.rect.centerx=x#重新定位项目符号
self.rect.centery=y

每次对您的精灵组调用
update()
all\u bullets
)时,精灵库将对组中的每个精灵调用
update()
函数。代码检查项目符号是否在屏幕外(我懒洋洋地使用1000作为屏幕宽度和高度的占位符),如果是,则
sprite.kill()
函数处理从组中删除和清理。这很简单。

若您使用PyGame,这种机制的大部分已经自动处理了

PyGame精灵基本上由以下部分组成:

  • 要绘制以表示对象的图像
  • 围绕对象的矩形,用于记住位置并检查碰撞
  • 一个
    update()
    函数,用于处理精灵的任何移动
使用现有的PyGame Sprite布局很方便,因为库代码已经提供了很多功能

让我们制作一个BulletSprite:

class BulletSprite( pygame.sprite.Sprite ):

    def __init__( self, bitmap, x, y ):
        pygame.sprite.Sprite.__init__( self )
        self.image        = bitmap                 # How the sprite looks
        self.rect         = bitmap.get_rect()      # Bounding box the size of the image
        self.rect.centerx = x                      # position the bullet 
        self.rect.centery = y                      #   about its centre
就这样。这将为您提供一个静止的精灵,在
(x,y)
屏幕上绘制为给定位图

现在让我们使用它:

# Create a group of 100 bullets
sprite_image = pygame.image.load( "bullet.png" )
all_bullets  = pygame.sprite.Group()               # Group to hold the sprites
for i in range( 100 ):
    random_x   = 50 + random.randrange( 950 )      # TODO: use proper screen size
    random_y   = 50 + random.randrange( 950 )
    new_sprite = BulletSprite( sprite_image, random_x, random_y )
    all_bullets.add( new_sprite )

# Main Window loop
while True:
    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            break

    # Paint the window
    window.fill( ( 0, 0, 0 ) )       # Paint it Black
    all_bullets.update()             # move all the bullets
    all_bullets.draw( window )       # Paint all the bullets

    pygame.display.flip()
pygame.quit()
就这样。创建精灵后,需要两行代码来移动它们并绘制它们

但他们还不会动。要让它们移动,
BulletSprite
需要有一个
update()
函数。此函数执行移动精灵所需的任何操作-应用速度、重力等。净效果是精灵的矩形(x,y)发生了变化

因此,给精灵添加一些更改-首先是
x
y
速度,然后是运动代码

class BulletSprite( pygame.sprite.Sprite ):

    def __init__( self, bitmap, x, y ):
        pygame.sprite.Sprite.__init__( self )
        self.image        = bitmap                 # How the sprite looks
        self.rect         = bitmap.get_rect()      # Bounding box the size of the image
        self.rect.centerx = x                      # position the bullet 
        self.rect.centery = y                      #   about its centre

        self.x_move = random.randrange( -3, 3 )    # simple random velocity
        self.y_move = random.randrange( -3, 3 )

    def update( self ):
        x = self.rect.centerx + self.x_move        # calculate the new position
        y = self.rect.centerx + self.y_move        # by applying an offset

        # has the sprite gone off-screen
        if ( x < 0 or x > 1000 or y < 0 or y > 1000 )
            self.kill()                            # remove from the group
        else:           
            self.rect.centerx = x                  # RE-position the bullet 
            self.rect.centery = y                      
类BulletSprite(pygame.sprite.sprite):
定义初始化(自、位图、x、y):
pygame.sprite.sprite.\uuuuu init\uuuuuuu(自我)
self.image=位图#精灵的外观
self.rect=bitmap.get_rect()#边界框图像的大小
self.rect.centerx=x#定位项目符号
self.rect.centery=y#关于其中心
self.x_move=random.randrange(-3,3)#简单随机速度
self.y_move=random.randrange(-3,3)
def更新(自我):
x=self.rect.centerx+self.x#移动#计算新位置
y=self.rect.centerx+self.y#通过应用偏移移动
#精灵离开屏幕了吗
如果(x<0或x>1000或y<0或y>1000)
self.kill()#从组中删除
其他:
self.rect.centerx=x#重新定位项目符号
self.rect.centery=y
每次对您的精灵组调用
update()
all\u bullets
)时,精灵库将对组中的每个精灵调用
update()
函数。代码检查项目符号是否在屏幕外(我懒洋洋地使用1000作为屏幕宽度和高度的占位符),如果是,则
sprite.kill()
函数处理从