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
| import pygame
from pygame import event, mouse, Rect, QUIT, K_c, key, draw
from collections import defaultdict
SIZE = 5
WIDTH = 900
HEIGHT = 600
class Table(defaultdict):
def __init__(self):
super().__init__(list)
self.fence = defaultdict(lambda: HEIGHT - 10*SIZE, {})
self.columns = defaultdict(list)
def update(self, x, y):
i = x // SIZE
x = i * SIZE
y = SIZE * (y // SIZE)
rects = self[i]
# insert sorted in sorted list without duplicate.
for k, r in enumerate(rects):
if y <= r.y:
if y != r.y:
rects.insert(k, Rect(x, y, SIZE, SIZE))
break
else:
rects.append( Rect(x, y, SIZE, SIZE))
def draw(self, screen):
for j, rects in self.items():
# shift red rects down and stack up.
for k in range(len(rects)-1, -1, -1):
r = rects[k]
if r.y > self.fence[j]:
rects.pop(-1)
self.fence[j] -= SIZE
else:
draw.rect(screen, 'black', r)
r.y += SIZE
draw.rect(screen, 'red', r)
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode(size=(WIDTH, HEIGHT))
clock = pygame.time.Clock()
table = Table()
done = False
while not done:
for e in event.get():
if e.type == QUIT:
done = True
break
keys = key.get_pressed()
if keys[K_c]:
table.update(*mouse.get_pos())
else: # no break.
table.draw(screen)
clock.tick(60)
pygame.display.flip()
pygame.quit() |
Partager