ThePythonGameBook

learn Python. Create Games

User Tools

Site Tools


en:resources:people:yipyip:auswahlrahmen

Auswahlrahmen

This little demo shows how to implement a selection-rectangle controlled with mouse-movement and left mouse-button.

auswahlrahmen.py
#!/usr/bin/env python
 
####
 
import pygame as pyg
 
####
 
class Display(object):
 
 
  def __init__(self, width, height):
 
    self.fsa = {(pyg.MOUSEMOTION, None): (None, None),
                (pyg.MOUSEMOTION, 'drawing'): ('drawing', self.update_pos),
                (pyg.MOUSEBUTTONDOWN, None): ('drawing', self.start_rect),
                (pyg.MOUSEBUTTONUP, 'drawing'): ('fin', None),
                (pyg.MOUSEMOTION, 'fin'): ('fin', None),
                (pyg.MOUSEBUTTONDOWN, 'fin'): (None, None),
                (pyg.MOUSEBUTTONUP, None): (None, None)}
 
    pyg.init()
    self.screen = pyg.display.set_mode((width, height), pyg.DOUBLEBUF)
    self.set_color((255, 255, 255))
    self.state = None
 
 
  def set_color(self, color):
 
    self.act_color = color
 
 
  def dispatch_events(self):
 
    event = pyg.event.poll()
    if event == pyg.NOEVENT:
      return
 
    if event.type == pyg.QUIT:
      return 'q'          
    if event.type == pyg.KEYDOWN:
      if event.key == pyg.K_ESCAPE:
        return 'q'
 
    if not event.type in (pyg.MOUSEMOTION, pyg.MOUSEBUTTONDOWN, pyg.MOUSEBUTTONUP):
      return
    self.state, func = self.fsa.get((event.type, self.state))
    if func:
      func(event)
 
 
  def start_rect(self, ev):
 
    self.pos0 = ev.pos
    self.pos1 = self.pos0
 
 
  def update_pos(self, ev):
 
    self.pos1 = ev.pos
 
 
  def flip(self):
 
    pyg.display.flip()
    self.screen.fill((0,0,0))
 
 
  def mouse_rect(self):
 
    if not self.state:
      return
 
    x0, y0 = self.pos0
    x1, y1 = self.pos1
    pyg.draw.rect(self.screen, self.act_color, (x0, y0, x1 - x0, y1 - y0), 1)
 
####
 
class Controller(object):
 
 
  def __init__(self):
 
    self.display = Display(800, 600)
 
 
  def run(self):
 
    ev = None
    while not ev == 'q':
      ev = self.display.dispatch_events()
      self.display.mouse_rect()
      self.display.flip()
 
####
 
if __name__ == '__main__':
 
  Controller().run()
/var/www/horst/thepythongamebook.com/data/pages/en/resources/people/yipyip/auswahlrahmen.txt · Last modified: 2014/01/09 11:07 (external edit)