# touch.py # Walker M. White (wmw2) # November 17, 2013 """Module to show off how to process touches in game2d""" import colormodel from game2d import * ### CONSTANTS ### # Window Size WINDOW_WIDTH = 512 WINDOW_HEIGHT = 512 # Animation Frames that constitute a click CLICK_SPEED = 30 ### CONTROLLER CLASS ### class Touch(Game): """Track the mouse to draw freehand lines Instance Attributes: view: the view (inherited from Game) [GView] last: last mouse position [GPoint or None if mouse was not down last frame] time: frames since mouse last changed (pressed, released) [int >= 0] clicks: # of fast clicks in a row [int >= 0] lines: set of lines to be drawn [list of GLine] """ # THREE MAIN METHODS def init(self): """Special initialization method to create attributes. Not the SAME as __init__. DO NOT DEFINE __init___.""" self.last = None self.time = 0 self.clicks = 0 self.lines = [] def update(self,dt): """Draw new lines or erase them all.""" # helper method to detect a click self._detectClick() # Erase on double click if self.clicks >= 2: self._processDoubleClick() else: self._processDrawing() # Update mouse position (must do last) self.last = self.view.touch def draw(self): """Draw the lines""" for line in self.lines: line.draw(self.view) # HELPER METHODS def _detectClick(self): """Check for change in mouse state. A click is a releas, CLICK_SPEED frames after a down.""" touch = self.view.touch # Look for a release. if touch is None and not self.last is None: # Release; check if fast enough if self.time < CLICK_SPEED: self.clicks = self.clicks + 1 else: self.clicks = 1 # If touch down, increment timer if not touch is None: # Restart timer on a press if self.last is None: self.time = 0 else: self.time = self.time + 1 def _processDoubleClick(self): """Clear the screen and reset click count.""" self.clicks = 0 self.lines = [] def _processDrawing(self): """Add a new line if last is not None""" touch = self.view.touch if not self.last is None and not touch is None: # Specify a line as list of two points points = [self.last.x,self.last.y,touch.x,touch.y] line = GLine(points=points,linecolor=colormodel.RED) self.lines.append(line) # Script Code if __name__ == '__main__': Touch(width=WINDOW_WIDTH,height=WINDOW_HEIGHT,fps=60.0).run()