Drawing with Chunky
In the 1960s Seymour Papert and his colleagues invented the Logo language: children steered a turtle that left a trail wherever it walked. Here Chunky is the turtle. What you write in turtle do … end are commands for Chunky:
forward 100– walk 100 steps straight ahead, drawing as you goright 90,left 90– turn by 90 degreespen_up,pen_down,color "red",pen_width 5
Chunky starts in the middle, looking up. A square is “forward and turn right” four times – a loop, as in lesson 6:
turtle do
4.times do
forward 100
right 90
end
endThe => #<Turtle 4 lines …> below is Chunky's log: every line is recorded. Walking round a polygon, Chunky turns all the way round once, 360 degrees – 360.0 / corners at each corner. That makes a method as in lesson 22, this time with two parameters – and the methods you write yourself work inside the turtle block too. Two things are new: (3..8).each walks through the numbers 3 to 8 (a range), and { … } is the short way of writing do … end:
def polygon(corners, side)
corners.times do
forward side
right 360.0 / corners
end
end
turtle do
(3..8).each do |corners|
color "hsl(#{corners * 45}, 70%, 45%)"
polygon(corners, 60)
end
end
# turn twice all the way round and it becomes a star
turtle { 5.times { forward 150; right 144 } }Now for some magic: a method that calls itself. A tree is a trunk with two smaller trees on top – and each of those is a trunk with two even smaller trees … To stop somewhere, the method needs a base case: return if depth == 0 ends it right away when the depth is 0 – then it draws nothing. This is called recursion. At the end Chunky walks back, so the caller carries on where it left off.
def tree(length, depth)
return if depth == 0 # the base case
forward length
left 25
tree(length * 0.7, depth - 1) # the small tree on the left
right 50
tree(length * 0.7, depth - 1) # the small tree on the right
left 25
back length # back to the foot of the trunk
end
turtle do
color "#3a8d3a"
tree(80, 7)
endn is four curves of depth n - 1, each a third as long, with left 60, right 120 and left 60 in between. Fill in the else branch – three curves of depth 3 make the flake.def koch(length, depth)
if depth == 0
forward length
else
# four times koch(length / 3.0, depth - 1),
# with left 60, right 120, left 60 in between
end
end
turtle do
color "#2a6fb0"
3.times do
koch(270, 3)
right 120
end
end
7.0 keeps the fraction.turtle do
color "#d4a017"
# 7.times do
# forward ...
# right ... # three times around in seven turns
# end
end