什么是PyGame精灵,他们做什么?

2024-06-30 15:11:19 发布

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

我已经找到了很多关于如何和何时使用精灵的教程,但是我仍然不知道它们是什么或者它们是做什么的。 默认的想法似乎是您将pygame.sprite.Sprite类的子类化,并向该类添加rect和{}属性。 但是为什么我需要子类化Sprite类,它对我的代码有什么影响? 我无论如何都可以这样做:

class MySprite:  # No subclassing!
    def __init__(self, image):
        self.image = image
        self.rect = image.get_rect()

而且看起来效果不错。 我也试着浏览源代码,但是couldn't find a sprite file。在


Tags: no代码rectimageself属性def教程
2条回答

精灵只是游戏中可以与其他精灵或其他东西互动的物体。这些可以包括角色、建筑或其他游戏中的对象。在

精灵有一个子类的原因更多的是为了方便。当一个对象从sprite.Sprite类继承时,可以将它们添加到精灵组中。在

示例:

import pygame

class car(sprite.Sprite):
    def __init__(self):
        sprite.Sprite.__init__() # necessary to initialize Sprite class
        self.image = image # insert image
        self.rect = self.image.get_rect() #define rect
        self.rect.x = 0 # set up sprite location
        self.rect.y = 0 # set up sprite location
    def update(self):
        pass # put code in here

cars = pygame.sprite.Group()# define a group

pygame.sprite.Group.add(car())# add an instance of car to group

我不能将精灵添加到精灵组,除非它们继承自精灵类。这很有用,因为我现在可以更新组中的所有精灵,并使用一个函数绘制它们:

^{pr2}$

我也可以使用组进行碰撞检测:

# check to see if sprite collides with any sprite in the car group
collided = pygame.sprite.Sprite.spritecollide(sprite, cars, False)

note: In the above code pygame.sprite.Sprite.spritecollide returns a list.

总之,sprite类对于处理大量sprite非常有用,否则将需要更多代码来管理。Sprite类提供了一组通用变量,可用于定义精灵。在

子类化时,继承类中的方法和函数。这个游戏精灵类包含许多预先编写的方法,您可以调用这些方法,而无需手动重新编写代码。在

如果您决定像上面那样创建一个孤立/独立的MySprite类,那么您将无法使用任何预先编写的代码。只要你能独立完成类的所有函数,就可以了。在

相关问题 更多 >