Wednesday, July 16, 2014

Pygame example (Window, Sound, Key handling)

Here is a small introductory example for pygame. In it we can learn to initialize pygame, create a window, display an integer as text on the screen and play sounds.

Pressing the key a will increase the score by 5 and update the value of the integer on the screen and also play a tick sound. Meanwhile the Mario soundtrack will keep running in the background.

You need to have at least python 2.7 with pygame installed.   

------------------------------------------------------Example --------------------------------------------
import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')

WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 128)
score=27

fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render(str(score), True, GREEN, BLUE)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (30, 20)

pygame.mixer.music.load('mario.wav')
pygame.mixer.music.play(-1, 0.0)

while True: # main game loop
     DISPLAYSURF.fill(WHITE)
     textSurfaceObj = fontObj.render(str(score), True, GREEN, BLUE)
     DISPLAYSURF.blit(textSurfaceObj, textRectObj)
     for event in pygame.event.get():
         if event.type == QUIT:
             pygame.mixer.music.stop()
             pygame.quit()
             sys.exit()
         elif event.type == KEYUP:
                 if event.key==K_a:
                     soundObj = pygame.mixer.Sound('beepingsound.wav')
                     soundObj.play()
                     score= score +5
     pygame.display.update()