Attachment 'sq.py'

Download

   1 #!/usr/bin/env python
   2 # vim: ts=4:expandtab
   3 import pygame, random, sys
   4 pygame.init()
   5 
   6 color, back = (255,25,255), (10,10,10)
   7 W,H=800,600
   8 screen = pygame.display.set_mode((W,H))
   9 
  10 figs = [] # [ [ Rect, color, width ]
  11 for i in xrange(10):
  12     col = random.randint(0,255),random.randint(0,255),random.randint(0,255)
  13     x, y = random.randint(10,W-50), random.randint(10,H-50)
  14     w, h = random.randint(50, W-x), random.randint(50, H-y)
  15     figs.append([pygame.Rect(x,y,w,h),col])
  16     
  17 def draw_all(scr, figs):
  18     scr.fill(back)
  19     for f in figs:
  20         pygame.draw.rect(scr,f[1],f[0],0)
  21         
  22 def draw_2circle(scr, pos):
  23     pygame.draw.circle(scr, (255,255,255), pos, 2)
  24     pygame.draw.circle(scr, (0,0,0), pos, 3, 1)
  25     
  26 def draw_focus(scr, f):
  27     draw_2circle(scr, f[0].topleft)
  28     draw_2circle(scr, f[0].topright)
  29     draw_2circle(scr, f[0].bottomleft)
  30     draw_2circle(scr, f[0].bottomright)
  31 
  32 def get_focus(figs, pos):
  33     'Returns index or -1 if not found'
  34     for i in xrange(len(figs)-1, -1, -1):
  35         if figs[i][0].collidepoint(pos):
  36             return i
  37     return -1
  38 
  39 def upfocus(f, figs):
  40     if f < len(figs)-1:
  41         figs[f:f+2]=[figs[f+1],figs[f]]
  42         return f+1
  43     return f
  44 
  45 def downfocus(f, figs):
  46     if f > 0:
  47         figs[f-1:f+1]=[figs[f],figs[f-1]]
  48         return f-1
  49     return f
  50 focus = len(figs)-1 
  51 
  52 while True:
  53     event = pygame.event.wait()
  54     print event
  55     if event.type == pygame.QUIT:
  56         sys.exit()
  57     elif event.type == pygame.MOUSEBUTTONDOWN:
  58         nfocus = get_focus(figs, event.pos)
  59         if event.button == 1:
  60             if nfocus >= 0:
  61                 focus = nfocus
  62         elif event.button == 4:
  63             focus = upfocus(focus,figs)
  64         elif event.button == 5:
  65             focus = downfocus(focus,figs)
  66     elif event.type == pygame.MOUSEMOTION:
  67         if event.buttons[0]:
  68             figs[focus][0].move_ip(event.rel)
  69         elif event.buttons[2]:
  70             figs[focus][0].inflate_ip(event.rel)
  71     elif event.type == pygame.KEYDOWN:
  72         if event.key == 270:
  73             focus = upfocus(focus,figs)
  74         elif event.key == 269:
  75             focus = downfocus(focus,figs)
  76     draw_all(screen, figs)
  77     draw_focus(screen, figs[focus])
  78     pygame.display.flip()

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.

You are not allowed to attach a file to this page.