-
Notifications
You must be signed in to change notification settings - Fork 32
Purogo MoreRubyMoreFun
In the last section Purogo/UsingParameters we changed our hex program so we could pass in a length as a parameter to /draw. This is cool, but we can take using parameters to the next level and make a Purogo program which can draw any polygon! We just need to use a little more Ruby syntax. Enter this program and call it 'polygon1':
turtle("polygon maker") do |*args|
if args[0]
sides = args[0].to_i
else
sides = 4
end
if args[1]
length = args[1].to_i
else
length = 5
end
angle = 360 / sides
sides.times do
forward length
turnright angle
end
end
Run this and pass in some values '/draw 4 5', '/draw 8 15', etc... Let's figure out what we changed from last time. For starters, we added a new first parameter for the number of sides we want:
if args[0]
sides = args[0].to_i
else
sides = 4
end
This is pretty much exactly the same code as Purogo/UsingParameters, but we changed the local variable name to sides. We also accept a second parameter for length. Notice that instead of getting the zeroth element we are getting from the first element (args[1]). The next line is the magic of this program:
angle = 360 / sides
Remember that for regular polygons the angle to turn is this simple equation right? Ok all we did once we had the angle calculated was change turnright to use this new value:
turnright angle
Let's now take a break and learn about how to customize our programs a bit more in Purogo/CustomizingOurDrawings.