What class should the text class inherit?

Asked

Viewed 37 times

0

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

  • I think it will help you: https://www.pygame.org/docs/ref/font.html when you finish reading, you can post the answer that will help other people too =)

1 answer

3


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

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

It would make sense for a class like that to inherit from pygame. Surface - why this would allow you to update your content, and already use your own "Text" class object as a parameter for a "blit" and stamp the text on the screen. Unfortunately the pygame surfaces do not get along well with inheritance: it is no use to inherit the Surface class, because its sub-class will not function as a parameter for the blit in another Surface, and have methods like "get_at" that work. (This is a defect of Pygame himself)

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

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

To summarize: Or don’t inherit anything, and do all the functionality yourself, or inherit from pygame.sprite.Sprite yourself.

  • This answer implicitly considers that the code is in Python 3. If by chance you are in Python 2, you should always inherit from object. (But try using Python 3 for new projects)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.