O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Displaying the End Game Messages

Whether the player wins or loses, we need to let him know with a message onscreen. The showtext() function takes a string as its argument and then uses Pygame to show it.

technicalstuff.eps You don’t necessarily need to know this, but this function draws (or renders) text onto a surface object using your choice of font and font size. It then creates a rectangle from that surface object, repositions it in the center of the screen, and copies (or blits) the text onto the rectangle.

You can reuse this function in your own programs. To adapt it, the things you need to know are that freesansbold.ttf is the name of the font, 64 is the font size in points, PURPLE is the text color, WHITE is the background color for the text, and the center of the text is at pixel position X=220 and Y=200.

The values we’ve used position the text across the middle of the giant raspberry. The text is huge. We have room for only about nine characters in the game window, but that’s perfect for this game.

def showtext(text):

fontObj=pygame.font.Font(‘freesansbold.ttf’,64)

textsurface=fontObj.render(text, True, PURPLE, WHITE)

textRectObj=textsurface.get_rect()

textRectObj.center=(220,200)

gameSurface.blit(textsurface,textRectObj)

pygame.display.update()

Now you know how to display text, you can create functions called gameover() for when the player loses and gamewon() for win the player wins. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required