Skip to content

Instantly share code, notes, and snippets.

@alessandrostein
Last active August 28, 2018 21:25
Show Gist options
  • Save alessandrostein/220b68c7ff893873dcde233ca441db50 to your computer and use it in GitHub Desktop.
Save alessandrostein/220b68c7ff893873dcde233ca441db50 to your computer and use it in GitHub Desktop.
COMANDS = [:place, :move, :left, :right, :report]
DIRECTIONS = [:north, :east, :south, :west]
TABLETOP_MAX_WIDTH = 4
TABLETOP_MAX_HEIGHT = 4
@x, @y, @position = [0,0, :north]
def place(params)
args = params.split(",")
position_x = args[0].to_i
@x = position_x > TABLETOP_MAX_WIDTH ? TABLETOP_MAX_WIDTH : position_x
position_y = args[1].to_i
@y = position_y > TABLETOP_MAX_HEIGHT ? TABLETOP_MAX_HEIGHT : position_y
@position = to_sym(args[2])
end
def move
case @position
when :north # Move to up
@y -= @y > 0 ? 1 : 0
when :east # Move to right
@x += @x < TABLETOP_MAX_WIDTH ? 1 : 0
when :south # Move to down
@y += @y < TABLETOP_MAX_HEIGHT ? 1 : 0
when :west # Move to left
@x -= @x > 0 ? 1 : 0
end
end
def left
# Rotate the robot 90 degrees
@position = DIRECTIONS[DIRECTIONS.index(@position) - 1]
end
def right
# Rotate the robot 90 degrees
@position = DIRECTIONS[DIRECTIONS.index(@position) + 1] || DIRECTIONS[0]
end
def report
p "#{@x},#{@y},#{@position.upcase}"
end
def to_sym(value)
value.downcase.to_sym
end
def is_not_valid_comand(action)
p "#{action} is not a valid command"
end
def robot_is_not_placed
p "Robot is not placed"
end
robot_placed = false
while (input = $stdin.gets.chomp) do
action, params = input.split
robot_placed = true if to_sym(action) == :place
if robot_placed && COMANDS.include?(to_sym(action))
params ? send(to_sym(action), params) : send(to_sym(action))
else
break if to_sym(action) == :quit
robot_placed ? is_not_valid_comand(action) : robot_is_not_placed
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment