Some Pygame tips

For the last few days, I was trying to make a simple game with pygame. It was very interesting to learn pygame, and I got thrilled when I created my own game. is the official website for pygame. There is a myriad of tutorial links and simple documentation in this site.Here in this post I would like to share some useful codes, that’s I found confusing or tricky in the beginning. Before that let me tell about my game. It is a word game that checks your typing speed.A word will appear on the screen and you have to type it down before it disappears. I will attach the source code very soon.

1) Display text / string on-screen

screen = display.set_mode((900,800))

#This line of code set the window size.

basicfont = pygame.font.Font('freesansbold.ttf',28)

#Here we set the custom font. The first argument denote the font name.
#If it is not specified, pygame use default font.The second argument is the font size.

text = basicfont.render('Text to display ',True , [255, 255, 255])

#The ‘text to display’ can only be a single line: newline characters are not rendered.
#The second argument is a boolean:if true the characters will have smooth edges.
#The third argument is the color of the text [e.g.: (0,0,255) for blue].


#This code display the ‘text’ at position (200,200) on the screen.

The above code will help you to display text on the screen. But in-order to display numerals (especially when you want to display pints)you need a slight change in second line of code:
suppose you need to display points( suppose ‘points’ is numeral here)
text = basicfont.render(‘Your score :’+str(points), True, [255,0,0])

2) Read character from keyboard

def getkeypress():
        for event in pygame.event.get():
                if event.type == pygame.KEYDOWN :
                        key_val = event.key
                        character = chr(key_val)
                        return character
Explanation: The for statement listens for all events in pygame. When a key is pressed on keyboard pygame.KEYDOWN will identify it. ‘event.key’ returns an integer value corresponding to each key_val.The ‘chr()’ function is a built-in function which return corresponding letter/key for the ‘key_val’.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s