# BOXES v0.3

In our previous lesson we ended with something like a line of army ants, all our boxes lined up. Let's make it better by making them organize themselves in rows.

The code for the `Box`

class is just like before. Since you have seen it twice
already, I will not show it. You can still see it in our full listing

But now, let's organize our boxes in rank and file. In fact, let's put our many boxes inside a big box.

16big_box = Box(0, 0, 30, 50)

We will get our boxes one at a time, put the first in 0,0 and the next one right at its right, and so on, and when we are about to step outside of the big box, we go back to the left, a little down, and do it all over again.

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)

And now we can draw it. Just so we are sure we are staying inside the big box, we will draw it too, in light blue.

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"))

And here is the output:

That is strangely satisfying! Of course we are doing something wrong in that we are overflowing the big box vertically.

So, we could have more than one big box. And use them as pages?

Further references:

- Full source code for this lesson lesson3.py
- Difference with code from last lesson