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:


Ex07. Text

To create text output, we need a font, and then we may create a text image by using its render method


We use the get_rect method to find the region on main display to blit it to. It is also possible to add more elements to the image prior to sending it to main display, as we will do in Button example later.



# Ex07.py 
# Text

import pygame as pg

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

width, height = 640, 480

pg.init()

screen = pg.display.set_mode((width, height))
pg.display.set_caption('Ex07. Text')

screen.fill(pg.Color("white"))

# font
font = pg.font.SysFont("arial",56)

# create Text Surface, and get bounding rect
text = font.render("Hello pygame!", True, cmap[0])
rect = text.get_rect()

# center on screen
rect.center = (width/2,height/2)

screen.blit(text,rect)

pg.display.update()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True
            
pg.quit()

This is the output:


Ex06. 4 Arcs

Arcs are same as an ellipse with start angle of 0 and stop angle of 360.


Here we have 4 arcs based on the same ellipse (and its bounding rectangle), with different start and stop angles.



# Ex06.py 
# 4 Arcs

import pygame as pg
from math import radians as rad

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


pg.init()

screen = pg.display.set_mode((640, 480))
pg.display.set_caption('Ex06. 4 Arcs')

rect = pg.Rect(50,50,540,380)

screen.fill(pg.Color("white"))

def get_rad(start,stop):
 return rad(start), rad(stop)

# arc angles
arc1_start, arc1_stop = get_rad(0,45)
arc2_start, arc2_stop = get_rad(60,180)
arc3_start, arc3_stop = get_rad(190,255)
arc4_start, arc4_stop = get_rad(260,355)

pg.draw.arc(screen,cmap[0],rect,arc1_start,arc1_stop,3)
pg.draw.arc(screen,cmap[1],rect,arc2_start,arc2_stop,3)
pg.draw.arc(screen,cmap[2],rect,arc3_start,arc3_stop,3)
pg.draw.arc(screen,cmap[3],rect,arc4_start,arc4_stop,3)

pg.display.update()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True
            
pg.quit()

This is the output:


Ex05. 4 Circles

We use the rectangles from Example 1. For the rectangle we need a center point obtained by rect1.center, etc.


We also need a radius which we have set to 100.



# Ex05.py 
# 4 Circles

import pygame as pg

white = pg.Color('white')
blue = pg.Color('blue')
red = pg.Color('red')
green = pg.Color('green')
purple = pg.Color('purple')

pg.init()

screen = pg.display.set_mode((640, 480))
pg.display.set_caption('Ex05. 4 Circles')

w,h = 250,200 # dimensions of each rectangle
# top row - blue, red
# bottom row - green, purple

padx,pady = 20,10
radius = 100

rect = pg.Rect(0,0,w,h)

rect1 = rect.copy()
rect1.bottomright=(320-padx,240-pady)

rect2 = rect.copy()
rect2.bottomleft=(320+padx,240-pady)

rect3 = rect.copy()
rect3.topright=(320-padx,240+pady)

rect4 = rect.copy()
rect4.topleft=(320+padx,240+pady)


screen.fill(white)
pg.draw.circle(screen,blue,rect1.center,radius)
pg.draw.circle(screen,red,rect2.center,radius)
pg.draw.circle(screen,green,rect3.center,radius)
pg.draw.circle(screen,purple,rect4.center,radius)

pg.display.update()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True
            
pg.quit()

This is the output:


Ex04. 4 Ellipses

4 ellipses are drawn. We use the same bounding rectangles as in example 1.


Thus we change the draw.rectangle to draw.ellipse from that example.



# Ex04.py 
# 4 Ellipses

import pygame as pg

white = pg.Color('white')
blue = pg.Color('blue')
red = pg.Color('red')
green = pg.Color('green')
purple = pg.Color('purple')

pg.init()

screen = pg.display.set_mode((640, 480))
pg.display.set_caption('Ex01. 4 Ellipses')

w,h = 250,200 # dimensions of each rectangle
# top row - blue, red
# bottom row - green, purple

padx,pady = 20,10

rect = pg.Rect(0,0,w,h)

rect1 = rect.copy()
rect1.bottomright=(320-padx,240-pady)

rect2 = rect.copy()
rect2.bottomleft=(320+padx,240-pady)

rect3 = rect.copy()
rect3.topright=(320-padx,240+pady)

rect4 = rect.copy()
rect4.topleft=(320+padx,240+pady)


screen.fill(white)
pg.draw.ellipse(screen,blue,rect1)
pg.draw.ellipse(screen,red,rect2)
pg.draw.ellipse(screen,green,rect3)
pg.draw.ellipse(screen,purple,rect4)

pg.display.update()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True
            
pg.quit()

This is the output:


Ex03. Polygon

Two five sided polygons are drawn, one on top of another Each gets five coordinates in a for loop.


Since we did not specify a width, it is filled with the color, either cmap[0]=red, or cmap[2]=blue for the two polygons.



# Ex03.py 
# Polygon

import pygame as pg
from math import sin,cos,radians

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


pg.init()

screen = pg.display.set_mode((640, 480))
pg.display.set_caption('Ex03. Polygon')

center = 300,240
radius = 200

screen.fill(pg.Color("white"))

poly1 = []

for i in range(5):
 angDeg = 45*i
 angRad = radians(angDeg)
 poly1.append((center[0]+radius*cos(angRad),
       center[1]+radius*sin(angRad) ) )

poly2 = []

for i in range(4,9):
 angDeg = 45*i
 angRad = radians(angDeg)
 poly2.append((center[0]+radius*cos(angRad),
       center[1]+radius*sin(angRad) ) )

pg.draw.polygon(screen,cmap[0],poly1)
pg.draw.polygon(screen,cmap[2],poly2)

pg.display.update()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True
            
pg.quit()

This is the output:


Friday, February 3, 2017

Ex02. 180 Radial Lines

180 lines are draw from 300, 240 in different directions.


All the lines have a length of 200. They have a width of 5 and have the 8 colors defined in the colors list. It is converted to pygame colors in cmap tuple.



# Ex02.py 
# 180 Radial Lines

import pygame as pg
from math import sin,cos,radians

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


pg.init()

screen = pg.display.set_mode((640, 480))
pg.display.set_caption('Ex02. 180 Radial Lines')

center = 300,240
radius = 200

screen.fill(pg.Color("white"))

for i in range(180):
 angDeg = 2*i
 angRad = radians(angDeg)
 pos = ( center[0]+radius*cos(angRad),
   center[1]+radius*sin(angRad)  )
 pg.draw.line(screen,cmap[i%8],center,pos,5)

pg.display.update()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True
            
pg.quit()

This is the output:


Ex01. 4 Rectangles

Four rectangles are drawn, 2 in each of 2 rows. We use a Rect object with width of w and height of h. It is copied 4 times and translated to different positions.


They are separated by 2*padx in x-direction and 2*pady in the y-direction.



# Ex01.py 
# 4 Rectangles

import pygame as pg

white = pg.Color('white')
blue = pg.Color('blue')
red = pg.Color('red')
green = pg.Color('green')
purple = pg.Color('purple')

pg.init()

screen = pg.display.set_mode((640, 480))
pg.display.set_caption('Ex01. 4 Rectangles')

w,h = 250,200 # dimensions of each rectangle
# top row - blue, red
# bottom row - green, purple

padx,pady = 20,10

rect = pg.Rect(0,0,w,h)

rect1 = rect.copy()
rect1.bottomright=(320-padx,240-pady)

rect2 = rect.copy()
rect2.bottomleft=(320+padx,240-pady)

rect3 = rect.copy()
rect3.topright=(320-padx,240+pady)

rect4 = rect.copy()
rect4.topleft=(320+padx,240+pady)


screen.fill(white)
pg.draw.rect(screen,blue,rect1)
pg.draw.rect(screen,red,rect2)
pg.draw.rect(screen,green,rect3)
pg.draw.rect(screen,purple,rect4)

pg.display.update()

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True
            
pg.quit()

This is the output: