Кристиян обнови решението на 02.12.2015 14:35 (преди над 9 години)
+class TurtleGraphics
+ class Turtle
+ end
+
+ class Canvas
+ end
+end
+
+class TurtleGraphics::Turtle
+ def initialize(x, y)
+ @max_x = x
+ @max_y = y
+ @matrix = Array.new(@max_x) { Array.new(@max_y, 0) }
+ @orientation = 0 # directions are measured with degrees
+ end
+
+ def spawn_at(row, column)
+ @x = row
+ @y = column
+ @matrix[@x][@y] += 1
+ end
+
+ def fix_position
+ @x = 0 if @x == @max_x
+ @x = @max_x - 1 if @x < 0
+ @y = 0 if @y == @max_y
+ @y = @max_y - 1 if @y < 0
+ end
+
+ def all_steps
+ @matrix.flatten.reduce(:+)
+ end
+
+ def draw(ascii_canvas = nil, &block)
+ instance_eval &block
+ if ascii_canvas
+ ascii_canvas.steps = all_steps
+ ascii_canvas.range = max_intensity / ascii_canvas.symbols.size.to_f
+ end
+ @matrix
+ end
+
+ def move
+ unless instance_variable_defined? :@x
+ spawn_at(0, 0)
+ end
+ case @orientation
+ when 0 then @y += 1
+ when 90 then @x += 1
+ when 180 then @y -= 1
+ when 270 then @x -= 1
+ end
+ fix_position
+ @matrix[@x][@y] += 1
+ end
+
+ def turn_left
+ @orientation -= 90
+ if @orientation == -90
+ @orientation = 270
+ end
+ end
+
+ def look(orientation)
+ directions = {left: 180, right: 0, up: 90, down: 270}
+ @orientation = directions[orientation]
+ end
+
+ def max_intensity
+ @matrix.flatten.max
+ end
+
+ def turn_right
+ @orientation += 90
+ if @orientation == 360
+ @orientation = 0
+ end
+ end
+end
+
+class TurtleGraphics::Canvas::ASCII
+ attr_accessor :steps, :range, :symbols
+
+ def initialize(symbols)
+ @steps = 0
+ @range
+ @symbols = symbols
+ end
+end