PyGame test: rhombs

Printer-friendly versionPrinter-friendly version
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python
 
"""
 
    Esperimento per il disegnamento di rombi e gestione di hovering
    ecc.. usando la geometria analitica.
    Per strutture piu' complesse (non geometriche) si possono usare
    cose come il controllo dell'alpha-channel sul pixel cliccato, ma
    penso proprio che cosi' sia piu' veloce.. ma dovrei fare qualche
    benchmark prima.
 
    Full + images:
    http://hackzine.org/sites/hackzine.org/files/rhomb_20090714-211658.tbz2
 
"""
 
import pygame
 
"""
    Check if a rhomb contains a given point
    point : the clicked point
    center : the center of the rhomb
    size : the size of the rhomb: half the diagonals
    THE RHOMB DIAGONALS MUST BE ALIGNED TO AXIS..
"""
def rhomb_contains(point, center, size):
  Cx, Cy = center
  Px, Py = point
  Rw, Rh = size
 
  # Calcultate deltas
  Dx, Dy = Px - Cx, Py - Cy
 
  # Outside bounding box
  if not Dx >= -Rw and Dx <= Rw: return False
  if not Dy >= -Rh and Dy <= Rh: return False
 
  result = (abs(Dx) <= ((1 - abs(1.0 * Dy / Rh)) * Rw))
 
  #print "center=%d,%d mouse=%d,%d distance=%d,%d result=%s" % (Cx,Cy,Px,Py,Dx,Dy,result)
 
  return result
 
 
""" Main """
def main():
    # Settings and default values..
    screensize = sw, sh = 800, 600
    rhombsize = Rw, Rh = 100, 50
    mousepos = Mx, My = 0, 0
    clicklog = []
    clicklog_maxlen = 10
    max_fps = 40 # Maximum framerate
    
    # Initialize pygame
    pygame.init()
    screen = pygame.display.set_mode(screensize)
    pygame.display.set_caption("Rhomb test")
    
    # Load resources..
    clock = pygame.time.Clock()
    rh_n = pygame.image.load("rhomb-normal.png")
    rh_h = pygame.image.load("rhomb-hovered.png")
    tfont = pygame.font.SysFont("monospace", 14, False, False)
    lfont = pygame.font.SysFont("monospace", 12, False, False)
    
    # rhomb centers
    rcenters = [
            (0, -3),
            (-0.5, -2.5),(0.5, -2.5),
            (-1, -2),(0, -2),(1, -2),
            (-1.5, -1.5), (-0.5, -1.5), (0.5, -1.5), (1.5, -1.5),
            (-2, -1), (-1, -1), (0, -1), (1, -1), (2, -1), 
            (-2.5, -0.5), (-1.5, -0.5), (-0.5, -0.5), (0.5, -0.5), (1.5, -0.5), (2.5, -0.5),
            (-3, 0), (-2, 0), (-1, 0), (0, 0), (1, 0), (2, 0), (3,0),
            (-2.5, 0.5), (-1.5, 0.5), (-0.5, 0.5), (0.5, 0.5), (1.5, 0.5), (2.5, 0.5),
            (-2, 1), (-1, 1), (0, 1), (1, 1), (2, 1), 
            (-1.5, 1.5), (-0.5, 1.5), (0.5, 1.5), (1.5, 1.5),
            (-1, 2),(0, 2),(1, 2),
            (-0.5, 2.5),(0.5, 2.5),
            (0, 3),
            ]
    
    # Game is running
    running = True
    
    # The Main loop
    while running:
        click = False # Is there a mousedown event in this cycle?
        st_lines = [] # Flush upper-left corner log
        
        # Check events
        for ev in pygame.event.get():
            if ev.type == pygame.QUIT:
                running = False
                print "Received pygame QUIT"
            elif ev.type == pygame.KEYDOWN:
                if ev.key == pygame.K_ESCAPE or ev.key == pygame.K_q:
                    running = False
                    print "Received user QUIT"
            elif ev.type == pygame.MOUSEMOTION:
                mousepos = Mx, My = ev.pos
            elif ev.type == pygame.MOUSEBUTTONDOWN:
                click = True
        
        # Fill the screen
        screen.fill((0x00,)*3)
        
        # Add mouse position to log
        st_lines.append("Mouse: %d,%d" % mousepos)
        
        # Add FPS to log
        st_lines.append("FPS: %d (MAX: %d)" % (clock.get_fps(),max_fps));
 
        # Draw rhombs
        RC = 0 # Rhomb counter
        for VCx, VCy in rcenters:
            
            # Calculate real centers
            Cx, Cy = sw / 2 + VCx * Rw, sh / 2 + VCy * Rh
            
            # Calculate distance (FOR DEBUGGING ONLY)
            Dx, Dy = Mx - Cx, My - Cy
            
            # Calculate range (FOR DEBUGGING ONLY)
            XR = (1 - abs(1.0 * Dy / Rh)) * Rw
            
            # If is hovered, add line to log and draw lighter rhomb
            if rhomb_contains(mousepos, (Cx, Cy), (Rw / 2 - 1, Rh / 2 - 1)):
                rhomb = rh_h
                st_lines.append("HOVER RHOMB=(%d,%d) MOUSE=(%d,%d) DIST=(%d,%d) XRANGE=%d" % (
                    Cx, Cy , Mx, My, Dx, Dy, XR))
                
                # If is clicked, append event to log
                if click:
                    clicklog.append("| %3d | %3d,%3d | %3d,%3d |" % (RC,Cx,Cy,Mx,My))
                    #clicklog = ["| %3d | %3d,%3d | %3d,%3d |" % (RC,Cx,Cy,Mx,My)] + clicklog
                    if len(clicklog) > clicklog_maxlen:
                        clicklog = clicklog[-clicklog_maxlen:]
                        #clicklog = clicklog[:clicklog_maxlen]
            else:
                # Normal rhomb. No hover, no click
                rhomb = rh_n
            
            # Draw rect
            rect = rhomb.get_rect(center=(Cx, Cy))
            screen.blit(rhomb, rect)
            
            # Draw label
            rlabel = lfont.render("%d,%d" % (Cx,Cy), True, (0, 0, 0))
            rrc = rlabel.get_rect(center=(Cx,Cy))
            screen.blit(rlabel,rrc)
            
            # Increment rhomb counter
            RC+=1
 
        
 
        # Draw topleft console
        yoff = 10
        for stline in st_lines:
            st_text = tfont.render(stline, True, (0, 0xff, 0))
            st_text_r = st_text.get_rect(topleft=(10, yoff))
            screen.blit(st_text, st_text_r)
            yoff += st_text_r.height + 1
        
        # Draw bottomright (click) console
        yoff = sh-10
        for stline in clicklog:
            st_text = tfont.render(stline, True, (0, 0xff, 0))
            st_text_r = st_text.get_rect(bottomright=(sw-10, yoff))
            screen.blit(st_text, st_text_r)
            yoff -= (st_text_r.height + 1)
            #"CLICK %3d : %3d,%3d : %3d,%3d"
        if len(clicklog) > 0:
            st_text = tfont.render(" RHOMB  CENTER    MOUSE    ", True, (0,0,0), (0, 0xff, 0))
            st_text_r = st_text.get_rect(bottomright=(sw-10, yoff))
            screen.blit(st_text, st_text_r)
 
        # refresh display
        pygame.display.flip()
        
        # wait for 1/maxfps seconds..
        clock.tick(max_fps)
        
    # terminated. quit pygame (not needed but good..)
    pygame.quit()
    print "Bye.."
 
 
if __name__ == '__main__': main()

2 comments

 
Anonymous wrote 5 weeks 2 days ago

race egypt

ears ve soap replica watches uk binary maple dame era

 
Anonymous wrote 10 weeks 15 hours ago

chews esq

polo lays handla viagra items mite lob buy levaquin online stuart coin won sulk

Who Am I?

~redShadow~ A.K.A. Samuele Santi is an Italian Open Source developer, currently working as a freelance developer, mainly in the web applications sector. Favourite programming languages: PHP and, of course, Python!

code (3) cars (1) como lake rovers (1) cartoons (1) debian (1) blogroll (7) arduino (1) debug (1) apache (1) Drupal Forms (1) development (11) circuits (1) documentation (2) database (3) apt (1) awstats (3) curl (1) 2v (1) address book (2) dmcrypt (1) e-mail (2) blender (3) aircrack (1) 3d (3) Drupal (21) alcool (1) cryptography (1) caos (1) doku (1) C++ (2) audio (1) cocktails (1) aoe (1) algorythms (1) bash (11) contact manager (1) archive (1) camera mia (1) backup (3) citroen (1)