Lesson Notes
Biggest Problem with Large Programs: Integration breaks at interfaces
The Controller manages the logic of your program and manages objects on screen so they appear to be ’in the same environment’.
Controller Class: Create and manage the program resources (framework, models, other data...)
The controller should, at minimum, contain:
We are going to build a program that adds dancing snowmen on screen. When the user clicks on the screen, another dancing snowman is added at that location.
class Snowman:
def __init__(self, x, y):
self.color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
self.speed = 5
#makes background transparent pygame.SRCALPHA
self.image = pygame.Surface( (40, 70) , pygame.SRCALPHA)
self.rect = self.image.get_rect()
# Draw the snowman on the model surface
head_radius = 5
head = pygame.draw.circle(self.image, self.color, (self.rect.width/2, head_radius), head_radius)
body_radius = 10
body = pygame.draw.circle(self.image, self.color, (self.rect.width/2, head.bottom+body_radius), body_radius)
bottom_radius = 20
bottom = pygame.draw.circle(self.image, self.color, (self.rect.width/2, body.bottom+bottom_radius), bottom_radius)
def update(self):
size = pygame.display.get_window_size()
if self.rect.y < 10:
self.direction = "DOWN"
elif self.rect.bottom > size[1]:
self.direction = "UP"
if self.direction == "UP":
self.rect.y = self.rect.y - 1
else:
self.rect.y = self.rect.y + 1
if self.rect.x < 0:
self.rect.x += random.randint(0, self.speed)
elif self.rect.right > size[0] :
self.rect.x += random.randint(-self.speed, 0)
else:
self.rect.x += random.randint(-self.speed, self.speed)
The Controller is responsible for 4 things:
You must import your models into the controller to use them:
from snowman import Snowman
The __init__
should create any initial resources and instances of the models
def __init__(self):
# Initialize the game engine
pygame.init()
# Set the height and width of the screen
self.screen = pygame.display.set_mode()
# Get width and height of a window as a list of 2 items [w, h]
size_list = pygame.display.get_window_size()
width = size_list[0]
height = size_list[1]
self.snowpeoples = [] #empty because we will start out with no snowmen
The main loop is a method of the controller.
REMINDER: The GUI main loop has the following algorithm for each display frame:
- Check for events
- This should be in a separate event loop
- Respond to events with corresponding actions
- Perform any actions required for that frame based on state
- rather than events
- Redraw the next frame
- Update the screen