[Solution] [Quiz] Turtle Graphics (#104)
Here is my quick solution.
( Quick, so, it will fail the unit test, since it does not check the
parameters and throw the expected exception; however, it shows the
example graphics correctly )
# Created by Morton Goldberg on November 02, 2006.
# Modified on November 14, 2006
# An implementation of Turtle Procedure Notation (TPN) as described in
# H. Abelson & A. diSessa, "Turtle Geometry", MIT Press, 1981.
# Turtles navigate by traditional geographic coordinates: X-axis pointing
# east, Y-axis pointing north, and angles measured clockwise from the
# Y-axis (north) in degrees.
include Math # turtles understand math methods
DEG = Math::PI / 180.0
alias run instance_eval
attr_reader :xy, :heading
# Place the turtle at [x, y]. The turtle does not draw when it changes
@xy = coords.dup
# Set the turtle's heading to <degrees>.
@heading = degrees
# Raise the turtle's pen. If the pen is up, the turtle will not draw;
# i.e., it will cease to lay a track until a pen_down command is given.
@pen = false
# Lower the turtle's pen. If the pen is down, the turtle will draw;
# i.e., it will lay a track until a pen_up command is given.
@pen = true
# Is the pen up?
# Is the pen down?
# Places the turtle at the origin, facing north, with its pen up.
# The turtle does not draw when it goes home.
@xy = [0.0, 0.0]
@heading = 0.0
# Homes the turtle and empties out it's track.
@track = 
# Turn right through the angle <degrees>.
@heading += degrees
# Turn left through the angle <degrees>.
# Move forward by <steps> turtle steps.
x = @xy + steps * cos((90 - @heading) * DEG)
y = @xy + steps * sin((90 - @heading) * DEG)
# Move backward by <steps> turtle steps.
# Move to the given point.
if !@track.empty? && @track.last.last == @xy
@track.last << pt.dup
@track << [@xy.dup, pt.dup]
@xy = pt.dup
# Turn to face the given point.
@heading = 90 - acos((pt - @xy) / distance(pt)) / DEG
# Return the distance between the turtle and the given point.
sqrt((@xy - pt) ** 2 + (@xy - pt) ** 2)
# Traditional abbreviations for turtle commands.
alias fd forward
alias bk back
alias rt right
alias lt left
alias pu pen_up
alias pd pen_down
alias pu? pen_up?
alias pd? pen_down?
alias set_h heading=
alias set_xy xy=
alias face toward
alias dist distance
|All times are GMT. The time now is 12:58 AM.|
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.