python - 如何在 Pygame 中克隆 Sprite ?

标签 python class pygame sprite clone

我正在 Pygame 和 Python 2.7 中将草添加到滚动平台中。问题是,到目前为止我只有一根草,我希望有更多。基本上我希望有克隆。

我听说类可以克隆 Sprite ,但我不太确定类是如何工作的,甚至不知道如何制作一个。我在网上找到的所有教程只会让我更加困惑。

这部分调用grass_rotate函数并生成grass_rect:

grass_rect = grass.get_rect(topleft = (grass_x, 480 - player_y + 460))
grass_rotate(screen, grass_rect, (grass_x, 480 - player_y + 460), grass_angle)

这是grass_rotate函数:

def grass_rotate(screen, grass_rect, topleft, grass_angle):
    rotated_grass = pygame.transform.rotate(grass, grass_angle)
    rotated_grass_rect = rotated_grass.get_rect(center = grass_rect.center)
    screen.blit(rotated_grass, rotated_grass_rect)

最佳答案

为了回答你的问题,为了制作 Sprite 的旋转“克隆”,我认为最好基于pygame.sprite.Sprite制作一个 Sprite 对象,并提供位图旋转选项。

首先让我们制作一个非常简单的 Sprite :

class Grass( pygame.sprite.Sprite ):
    """ Creates a tuft of grass at (x,y) """
    def __init__( self, image, x, y ):
        pygame.sprite.Sprite.__init__(self)
        self.image    = image
        self.rect     = self.image.get_rect()
        self.rect.center = ( x, y )

因为这是基于 sprite library ,它会自动从 pygame.sprite.Sprite 获取(继承)函数 Grass.draw()

编辑:以上段落是错误的。 Sprite 不继承draw(),这只是 Sprite 组的一部分。有必要实现您自己的 draw(),前提是不使用 Sprite Groups:

    def draw( self, surface ):
        surface.blit( self.image, self.rect )

因此,要将其显示在屏幕上,我们可以这样做:

grass_image = pygame.image.load( 'grass_clump.png' ).convert_alpha()
my_grass1 = Grass( grass_image, 10, 10 )
my_grass2 = Grass( grass_image, 50, 40 )

...

my_grass1.draw( window )
my_grass2.draw( window )

...

但是我们想稍微随机化角度,所以每一丛草都不是那么平坦和规则。实现此目的的一种方法是在初始化 Grass Sprite 时创建图像的旋转副本 (Grass.__init__())。 PyGame 已经有一个 rotozoom function就是这样做的。

所以我们基本上有相同的东西,除了现在我们添加一个额外的可选参数用于旋转。我将其默认为None,并且如果没有该参数,该类可以自由选择自己的随机角度。

### Creates a sprite that is rotated slightly to the left or right
class Grass( pygame.sprite.Sprite ):
    """ Creates a tuft of grass at a jaunty angle """
    def __init__( self, image, x, y, rotation=None ):
        pygame.sprite.Sprite.__init__(self)
        if ( rotation == None ):                                       # choose random angle if none
            angle = random.randrange( -15, 16 )                        # choose random angle if none
        self.image    = pygame.transform.rotozoom( image, angle, 1 )   # rotate the image
        self.rect     = self.image.get_rect()
        self.rect.center = ( x, y )

现在我们需要将所有这些放在一起。 PyGame 和 Pygame 的 Sprite 库非常有用的功能之一是 Sprite Groups。我不想在这里详细讨论,但本质上它允许您同时对一大堆 Sprite 进行操作,从而使代码变得更加容易。

现在我们想要很多草的克隆,所以我们只制作 50 个,然后添加到一个新组中:

### create lots of grass sprites, adding them to a group
grass_image = pygame.image.load( 'grass_clump_48.png' ).convert_alpha()
all_grass_sprites = pygame.sprite.Group()
for i in range( 50 ):
    new_x     = random.randrange( WINDOW_WIDTH )
    new_y     = random.randrange( WINDOW_HEIGHT )
    new_grass = Grass( grass_image, new_x, new_y )
    all_grass_sprites.add( new_grass )

要将它们绘制到窗口,您可以使用 for() 语句循环遍历组中的所有 Sprite 。但这不是必需的,因为 Sprite 组已经可以为我们做到这一点:

all_grass_sprites.draw( window )   # draws all the grass sprites

grass_sprites_clones

太简单了吧?!

这丛草来自Open Clip Art (公共(public)领域许可。)

引用代码如下:

import pygame
import random

# Window size
WINDOW_WIDTH    = 400
WINDOW_HEIGHT   = 400
WINDOW_SURFACE  = pygame.HWSURFACE|pygame.DOUBLEBUF

GREEN = ( 130, 220,   0 )  # background colour

### Creates a sprite that is rotated slightly to the left or right
class Grass( pygame.sprite.Sprite ):
    """ Creates a tuft of grass at a jaunty angle """
    def __init__( self, image, x, y, rotation=None ):
        pygame.sprite.Sprite.__init__(self)
        if ( rotation == None ):                                       # choose random angle if none
            angle = random.randrange( -15, 14 )                        # choose random angle if none
        self.image    = pygame.transform.rotozoom( image, angle, 1 )   # rotate the image
        self.rect     = self.image.get_rect()
        self.rect.center = ( x, y )


### Initialisation
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption("Grass Sprite Clones")

### create lots of grass sprites, adding them to a group
grass_image = pygame.image.load( 'grass_clump_48.png' ).convert_alpha()
all_grass_sprites = pygame.sprite.Group()
for i in range( 50 ):
    new_x     = random.randrange( WINDOW_WIDTH )
    new_y     = random.randrange( WINDOW_HEIGHT )
    new_grass = Grass( grass_image, new_x, new_y )
    all_grass_sprites.add( new_grass )

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.MOUSEBUTTONUP ):
            # On mouse-click
            pass

    # Update the window, but not more than 60fps
    window.fill( GREEN )
    all_grass_sprites.draw( window )   # draws all the grass sprites
    pygame.display.flip()

    # Clamp FPS
    clock.tick(60)

pygame.quit()

关于python - 如何在 Pygame 中克隆 Sprite ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65113332/

相关文章:

c++ - 我什么时候需要实现 operator [] ?

python - pygame:检测操纵杆断开连接,并等待它重新连接

python-3.x - Pygame:用颜色填充文本的透明区域

python - 代码味道 - if/else 构造

python - 如何将数据帧的 pyspark 列中包含的 unicode 列表转换为浮点列表?

Python 在迭代处理我的 1GB csv 文件时停止

python - 在 IPython 中控制列表可视化

function - Dart&Flutter:如何在另一个类中调用一个类方法

c++ - 类声明

python - 检测鼠标左键和右键单击