Saturday, February 4, 2017

Ex08. Keyboard

Here we use a class Keyboard to hold the font, the text surface, rectangle, etc. It is possible we can use several functions instead. However then we will have to deal with a lot of global variables, and using the global keyword.


We create a Keboard object. It gets the letter typed via the getText method. A key press will generate a KEYDOWN event when it is pressed down. Most keys will have a unicode representation. Some might be empty string, if they do not. We can draw the text using its update() method.



# Ex08.py 
# Keyboard

import pygame as pg
width, height = 640, 480

class Keyboard():

 def __init__(self):
  self.font = pg.font.SysFont("arial",72)
  self.col = pg.Color('black')
  self.text = self.font.render(" ", True, self.col)
  self.rect = pg.Rect(0,0,100,100)

 def getText(self,char):
  self.text = self.font.render(" " + char, True, self.col)
  self.rect = self.text.get_rect()
  self.rect.center = (width/2,height/2)

 def update(self,surface):
  surface.blit(self.text,self.rect)


colors = ['red','green','blue','cyan',
    'purple','brown','magenta','orange','white']
cmap = list(map(pg.Color,colors))

pg.init()

screen = pg.display.set_mode((width, height))
pg.display.set_caption('Ex08. Keyboard')

keyboard = Keyboard()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True
        if event.type == pg.KEYDOWN:
         keyboard.getText(event.unicode)
    
    screen.fill(cmap[-1])
    keyboard.update(screen)
    pg.display.update()
            
pg.quit()

This is the output after pressing P:


No comments:

Post a Comment