Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spiral with logo DSL
class Turtle
DIRECTIONS = [:UP, :RIGHT, :DOWN, :LEFT]
def initialize(size)
@size = size
@array = Array.new(size)
@array.map! {|line| line = Array.new(size, " ")}
@direction = :RIGHT
@x = 0
@y = 0
@array[@y][@x] = "*"
end
def walk(step_numbers)
step_numbers.times do
case @direction
when :UP
@y = @y - 1 if @y > 0
when :DOWN
@y = @y + 1 if @y < @size
when :LEFT
@x = @x - 1 if @x > 0
when :RIGHT
@x = @x + 1 if @x < @size
end
@array[@y][@x] = "*"
end
end
def print()
@array.each {|line| puts(line.join(''))}
end
def turn()
@direction = DIRECTIONS[(DIRECTIONS.index(@direction) + 1) % 4]
end
end
size = 16
t = Turtle.new(size)
size.downto(0) do |step|
t.walk(step)
t.turn
end
t.print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.