Source for: lesson3.py [raw]

 1class Box():
 2
 3    def __init__(self, x=0, y=0, w=1, h=1):
 4        """Accept arguments to define our box, and store them."""
 5        self.x = x
 6        self.y = y
 7        self.w = w
 8        self.h = h
 9
10    def __repr__(self):
11        return "Box(%s, %s, %s, %s)" % (self.x, self.y, self.w, self.h)
12
13
14many_boxes = [Box() for i in range(5000)]
15
16big_box = Box(0, 0, 30, 50)
17
18# We add a "separation" constant so you can see the boxes individually
19separation = .2
20
21
22def layout(_boxes):
23    # Because we modify the box list, we will work on a copy
24    boxes = _boxes[:]
25    # The 1st box is at 0,0 so no need to do anything with it, right?
26    previous = boxes.pop(0)
27    while boxes:
28        # We take the new 1st box
29        box = boxes.pop(0)
30        # And put it next to the other
31        box.x = previous.x + previous.w + separation
32        # At the same vertical location
33        box.y = previous.y
34        # But if it's too far to the right...
35        if (box.x + box.w) > big_box.w:
36            # We go all the way left and a little down
37            box.x = 0
38            box.y = previous.y + previous.h + separation
39        previous = box
40
41
42layout(many_boxes)
43
44import svgwrite
45
46
47def draw_boxes(boxes, fname, size):
48    dwg = svgwrite.Drawing(fname, profile="full", size=size)
49    # Draw the "big box"
50    dwg.add(
51        dwg.rect(
52            insert=(f"{big_box.x}cm", f"{big_box.y}cm"),
53            size=(f"{big_box.w}cm", f"{big_box.h}cm"),
54            fill="lightblue",
55        )
56    )
57    # Draw all the boxes
58    for box in boxes:
59        dwg.add(
60            dwg.rect(
61                insert=(f"{box.x}cm", f"{box.y}cm"),
62                size=(f"{box.w}cm", f"{box.h}cm"),
63                fill="red",
64            )
65        )
66    dwg.save()
67
68
69# Make the visible part of the drawing larger to show big_box
70draw_boxes(many_boxes, "lesson3.svg", ("50cm", "90cm"))
71