Source

sketchbook / drawer / canvas.py

Full commit
 #! /usr/bin/env python
#display

import pygame
from pygame.locals import *

pygame.init()

SCREEN_UPDATE_ADD = 1
SCREEN_UPDATE_BLANK = 2

class AnimatedCanvas(object):
    def __init__(self, win_width, win_height, refresh_rate=100):
        """
        win_width - pixels
        win_height - pixels
        refresh_rate - timeout between screen updates (ms)
        """
        self.dimensions = (win_width, win_height)
        self.refresh_rate = refresh_rate

        self.screen_update = SCREEN_UPDATE_BLANK

        self.clock = pygame.time.Clock()
        self.surface = pygame.display.set_mode(self.dimensions)

    def update(self):
        raise NotImplementedError

    def _draw(self):
        if self.screen_update == SCREEN_UPDATE_BLANK:
            self.surface.fill((0,0,0))
        self.update()
        pygame.display.flip()

    def run(self):
        self.running = True
        pygame.time.set_timer(USEREVENT+1, self.refresh_rate)

        while self.running:
            for event in pygame.event.get():
                if event.type == USEREVENT+1:
                    self._draw()
                if event.type == QUIT:
                    self.running = False
                    break

        pygame.quit()