2.10000014450.4001,309.3-- Create a new turtle "object" with the given parameters.
-- step_size: How far the turtle moves with the F command.
-- angle_inc: The turn amount (in degrees) for +/- commands.
function make_turtle(step_size, angle_inc)
return {d=step_size, a=math.rad(angle_inc), width=2}
end
-- Move the given turtle to point (x,y) facing angle a (degrees).
function place_turtle(turtle, x, y, a)
turtle.x = x
turtle.y = y
turtle.facing = math.rad(a)
end
-- Draw a path from the turtles current position to its next position,
-- taking into account its step size and current direction.
function draw_forward(turtle)
local new_x = turtle.x + turtle.d * math.cos(turtle.facing)
local new_y = turtle.y - turtle.d * math.sin(turtle.facing)
local p = path(turtle.x, turtle.y, new_x, new_y)
p.strokeWidth = turtle.width
turtle.x, turtle.y = new_x, new_y
end
-- Turn the turtle right (CCW) by its angle increment.
function right(turtle)
turtle.facing = turtle.facing - turtle.a
end
-- Turn the turtle left (CW) by its angle increment.
function left(turtle)
turtle.facing = turtle.facing + turtle.a
end
-- Mapping of command character to turtle action.
local actions = {
["F"] = function(turtle) draw_forward(turtle) end,
["-"] = function(turtle) left(turtle) end,
["+"] = function(turtle) right(turtle) end,
}
-- Drive the turtle according to the given direction string.
function drive_turtle(turtle, directions)
for char in directions:gmatch(".") do
local fnc = actions[char]
if fnc ~= nil then
fnc(turtle)
end
end
if turtle.path ~= nil then
turtle.path.closed = true
end
end
local t = make_turtle(20, 45)
place_turtle(t, 0, 0, 90)
drive_turtle(t, string.rep("F-F+FF++F", 4))
ellipse(0, 0, 1, 1)
Layer 1