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. http://www.pygame.org 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