Pages

miercuri, 29 august 2012

PyGame : Test class show text "Hello World" .

I wrote in my journal:
Today I received an email in which I asked about python and how to display a text message. I hate this approach, especially on the internet there are hundreds of materials on this subject.
This made ​​me remember my blog and I write a new tutorial on pygame.
I use the old class from last pygame tutorials, see here.
The source code it's pretty simple.
The news is function show_text().
To do this I use pygame functions, see pygame documentation.
Let's see the final source code.

import pygame
from pygame.locals import *

screen_mode = (640, 480)
color_black = 0, 0, 0

class Game:
 def __init__(self):
  pygame.init()
  self.screen = pygame.display.set_mode(screen_mode)
  pygame.display.set_caption("Pygame text window")

  self.quit = False
  
 def update(self):
  print "update function"
  self.show_text()
  return
 
 def draw(self):
  self.screen.fill(color_black)
  self.show_text()
  pygame.display.flip()

 def show_text(self):
  font = pygame.font.Font(None, 36)
  text = font.render("Hello World!", 1, (100, 100, 100))
  textpos = text.get_rect()
  textpos.centerx = self.screen.get_rect().centerx
  self.screen.blit(text, textpos)

 def mainLoop(self):

  while not self.quit:
   for event in pygame.event.get():
    if event.type == pygame.QUIT:
     self.quit = True
    elif  event.type  == pygame.MOUSEBUTTONDOWN:
     print pygame.mouse.get_pressed()
     
     self.update()
   self.draw()
 
if __name__ == '__main__':
 game = Game()
 game.mainLoop()

The result is this: