София обнови решението на 02.12.2015 15:17 (преди около 9 години)
+module TurtleGraphics
+require 'matrix'
+ class Turtle
+ ORIENTATIONS = [:left, :up, :right, :down]
+
+ def initialize(rows, columns)
+ @rows = rows
+ @columns = columns
+ @orientation = :right
+ @canvas = Matrix.zero(rows,columns).to_a
+ @current_position = {row: 0, column: 0}
+ @canvas[0][0] = 1
+ end
+
+ def draw(renderer = nil, &block)
+ self.instance_exec &block
+
+ if renderer.nil?
+ @canvas
+ else
+ renderer.render(@canvas)
+ end
+ end
+
+ def move
+ case @orientation
+ when :right
+ @current_position[:column] += 1
+ when :left
+ @current_position[:column] -= 1
+ when :up
+ @current_position[:row] -= 1
+ when :down
+ @current_position[:row] += 1
+ end
+
+ outliner(@current_position[:row], @current_position[:column])
+ end
+
+ def turn_left
+ current_orientation = ORIENTATIONS.index(@orientation)
+ @orientation = ORIENTATIONS[current_orientation - 1]
+ end
+
+ def turn_right
+ current_orientation = ORIENTATIONS.index(@orientation)
+ @orientation = ORIENTATIONS[(current_orientation + 1) % 4]
+ end
+
+ def look(orientation)
+ @orientation = orientation
+ end
+
+ def spawn_at(row = 0, column = 0)
+ @canvas[0][0] = 0
+ @canvas[row][column] = 1
+ @current_position = {row: row, column: column}
+ end
+
+ private
+ def outliner(current_row, current_column)
+ current_row = 0 if current_row >= @rows
+ current_column = 0 if current_column >= @columns
+ current_row = @rows - 1 if current_row < 0
+ column_column = @columns - 1 if current_column < 0
+ @current_position[:row] = current_row
+ @current_position[:column] = current_column
+ @canvas[current_row][current_column] += 1
+ end
+ end
+end