[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Text() class, a pygame.font.Font() helper classes



I'm sure you have your own text wrappers. I think pygame should get some support. I'm thinking of having a Text() or TextGroup() that is similar to SpriteGroups().

I have a Text() class that is a wrapper to pygame.font.Font(), and does some basic functions. It cache's the font.render() result, and uses cache on .draw(). It also only re-renders the text, if it has changed ( in color, size, text, font, etc... ) otherwise uses cache.

The second class, FPSText() is a quick way to get a Text() object with the current FPS.

I was going to make a TextGroup() that acts like a spritegroup, containing my Text() objects. I also planned a multi-line object, and the ability to have different colors in a single Text() line. ( think of standard RPG has a paragraph of text with certain words escaped with color codes ). Right now I need to improve the color methods to use multiple types of color definitions ( str, or tuple )

[ In the future could maybe even make clickable links ( aka: url), that onclick() call a callback function defined on Text() creation. example: civilization in-game-help. )

1)  Is this something that pygame would add? ( I know theres a new dev version of pygame, but i'm not sure if it has anything like this. )
2)  Should I be using pygame.color.Color() OR pygame.Color() ? ( Or use either, they point to same class? )
3) Any feedback would be appreciated, thanks.

Here is example usage of Text() and FPSText()

Example usage:

    in Game.init():
        # create text, later change font
        t = Text('foo')
        t.match_font('arial')
       
        # 2) use filepath to tff
        t2 = Text('foo', font='ttf/freesansbold.ttf')
        # 3) list of font names (without .ttf) to search OS for.
        t3 = Text('foo', font='arial, verdana, foobar')   
       
        # set loc using alignment  [and optional offset ]
        t = Text("align=topright,offset(x,y)", size=16,color="darkred")
        t.align( "bottomleft", self.width, self.height)
        t.align( "topright", self.width, self.height, (-60,80))
       
        # usage in Game()
        self.points = Text("Points: None!")
        self.fps = FPSText()

        # ... append a bunch of Text() objects to align_list
        self.align_list = []
        self.align_list.append( t1 )
        self.align_list.append( t2 )
        self.align_list.append( t3 )
       
    in Game.draw(self):
        self.points = "Points: %s" % ( player_points ) # caches if same value
        self.text.draw()
        self.fps.draw()
        self.fps.tick()
       
        for t in self.align_list: t.draw()

[ note: the attached code has a module 'game', which is just a wrapper to boilerplate of a pygame game. makes test_text.py code simpler. ]

Attachment: jakelib.text - v0.0.6.zip
Description: Zip archive

Attachment: screenshot.v0.0.6.png
Description: PNG image