BOXES v0.2

In our previous lesson we created a rather disappointing drawing using boxes. Let's introduce a new wrinkle, and lay out the many boxes.

This code is just like before:

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

But now, so they are not all stuck one on top of the other, let's lay the boxes down in a line, one next to the other.

16# We add a "separation" constant so you can see the boxes individually
17separation = .2
18
19
20def layout(boxes):
21    for i, box in enumerate(boxes):
22        box.x = i * (1 + separation)
23
24
25layout(many_boxes)

And we can see that they all have different coordinates now by printing a few of them. And yes, some of those numbers do look funny. Floating point numbers are weird.

print([(box.x, box.y) for box in many_boxes[:10]])
[(0.0, 0), (1.2, 0), (2.4, 0), (3.5999999999999996, 0), (4.8, 0), (6.0, 0), (7.199999999999999, 0), (8.4, 0), (9.6, 0), (10.799999999999999, 0)]

Let's draw them!

27import svgwrite
28
29
30def draw_boxes(boxes, fname, size):
31    dwg = svgwrite.Drawing(fname, profile="full", size=size)
32    # Draw all the boxes
33    for box in boxes:
34        dwg.add(
35            dwg.rect(
36                insert=(f"{box.x}cm", f"{box.y}cm"),
37                size=(f"{box.w}cm", f"{box.h}cm"),
38                fill="red",
39            )
40        )
41    dwg.save()
42
43
44draw_boxes(many_boxes, "lesson2.svg", ("5cm", "2cm"))

And here is the output:

lesson2.svg

That was more or less what we expected, right? Of course since there are 5000 small boxes that row of boxes goes on for quite a while.

We could just go to the right for a while, then start a new row. Let's do that in the next lesson.


Further references:

results matching ""

    No results matching ""