Which class should the text class inherit?

0

When using pygame it is very common that user classes inherit from pygame classes, for example a class of characters usually vaqi extend the class pygame.sprite.Sprite. But is a text class could inherit from which pygame class?

    
asked by anonymous 25.10.2017 / 01:51

1 answer

3

There is no "recipe" of which class to inherit. You are the one who knows what your class will have to "know" to do, and if it is appropriate that it inherits from some other class or not.

What will your text class have as functionality? If it is a facility for displaying text on the screen, having font attributes, color, perhaps by automatically positioning text and breaking lines, it may not inherit from any other class.

It would even make sense for a class to inherit from pygame.Surface - why would it allow you to update your content, and already use your own "Text" class object as a parameter to a "blit" and to print the text on screen. Unfortunately, pygame's Surfaces do not do well with inheritance: it's no use inheriting the Surface class, because its sub-class will not work as a parameter for the blit on another Surface, and have methods like "get_at" that work. (This is a Pygame bug itself)

So, it makes sense, for example, that your "Text" class has an "update" method that re-creates a surface with the source and message parameters configured, and a "draw" method that blits the same on the screen.

Now, notice that nothing prevents your text class from being itself a "sprite" - in this case, if it has the "update" method, the "rect" attribute, and an "image" attribute that is just one Surface with rendered text, it may belong to a group of sprites and the text will be drawn on the screen by the same mechanism as your other game objects.

In short: Or do not inherit anything, and do all the functionality yourself, or inherit from pygame.sprite.Sprite same.

    
25.10.2017 / 07:48