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

2024-05-29 07:05:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在做一个我自己的“子弹地狱”游戏,但是我在努力工作与类(我是新的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()

Tags: theselfeventinitdefdisplayscreenpygame
1条回答
网友
1楼 · 发布于 2024-05-29 07:05:54

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

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

  • 用来表示物体的图像
  • 围绕对象的矩形,用于记住位置并检查碰撞
  • 一个update()函数来处理精灵的任何移动

使用现有的PyGame Sprite布局很方便,因为库代码已经提供了很多功能

让我们做一个子弹精灵:

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

就这样。这将为您提供一个静止的sprite,在屏幕上(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)被改变

所以给sprite添加一些更改-首先是xy速度,然后是运动代码

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                      

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

相关问题 更多 >

    热门问题