class Toy::Controller
Constants
- COMMANDS
Attributes
robot[R]
Public Class Methods
new()
click to toggle source
# File lib/toy/controller.rb, line 9 def initialize @robot = Toy::Robot.new end
Public Instance Methods
start()
click to toggle source
# File lib/toy/controller.rb, line 13 def start while command = gets unless Toy::Controller::COMMANDS.include?(command.gsub(/^[A-Z]+/).first) puts 'Invalid command! Type HELP for list of available commands.' and next end case command when /STOP/ break else output = execute(command.strip) puts output if output end end end
Private Instance Methods
action() { |execute and return nil| ... }
click to toggle source
# File lib/toy/controller.rb, line 93 def action(&execute) yield execute and return nil rescue Toy::Robot::Error::PlacementError => e e.message end
execute(command)
click to toggle source
# File lib/toy/controller.rb, line 31 def execute(command) case command when /HELP/ help when /PLACE/ place(command) when /MOVE/ move when /LEFT/ left when /RIGHT/ right when /REPORT/ report end end
help()
click to toggle source
# File lib/toy/controller.rb, line 48 def help "Available commands: #{Toy::Controller::COMMANDS.join(' ')}" end
left()
click to toggle source
# File lib/toy/controller.rb, line 78 def left action { @robot.turn_left! } end
move()
click to toggle source
# File lib/toy/controller.rb, line 74 def move action { @robot.move! } end
place(command)
click to toggle source
# File lib/toy/controller.rb, line 52 def place(command) begin x, y, facing = command.split(' ', 2).last.split(',') x = x.to_i if x.strip.match(/^(\d)+$/) y = y.to_i if y.strip.match(/^(\d)+$/) facing = facing.strip.downcase.to_sym rescue return 'Invalid placement arguments!' end begin @robot.place(x, y, facing) and return nil rescue Toy::Direction::Error::DirectionError => e e.message rescue Toy::Unit::Error::CoordinateError => e e.message rescue Toy::Table::Error::TableError "Not available!" end end
report()
click to toggle source
# File lib/toy/controller.rb, line 86 def report action do x, y, facing = @robot.position return "#{x},#{y},#{facing.upcase}" end end
right()
click to toggle source
# File lib/toy/controller.rb, line 82 def right action { @robot.turn_right! } end