# frozen_string_literal: true # Ruby module to wrap robot moves features module ToyRobotCli # Ruby class to handle Robot moves on square table top class Robot # Valid directions what robot can be faced VALID_DIRECTIONS = %w[NORTH EAST SOUTH WEST].freeze # Initialize a new Robot instance. def initialize @position = nil @direction = nil end # Place the robot on the table at the specified coordinates and facing direction. # Example: # >> robot = ToyRobotCli::Robot.new # => # # >> robot.place(0, 0, "SOUTH") # => 2 # # Arguments: # coordinate_x: (Integer) - The X-coordinate of the robot's position. # coordinate_y: (Integer) - The Y-coordinate of the robot's position. # facing: (String) - The direction the robot is facing (NORTH, EAST, SOUTH, WEST). def place(coordinate_x, coordinate_y, facing) return unless valid_position?(coordinate_x, coordinate_y) && VALID_DIRECTIONS.include?(facing) @position = Matrix[[coordinate_x], [coordinate_y]] @direction = VALID_DIRECTIONS.index(facing) end # Move the robot one unit forward in the current direction. def move return unless placed? new_position = @position + direction_vector @position = new_position if valid_position?(new_position[0, 0], new_position[1, 0]) end # Rotate the robot 90 degrees to the left. def left return unless placed? @direction = (@direction - 1) % VALID_DIRECTIONS.length end # Rotate the robot 90 degrees to the right. def right return unless placed? @direction = (@direction + 1) % VALID_DIRECTIONS.length end # Report the current position and direction of the robot. # Example: # >> robot = ToyRobotCli::Robot.new # => # # >> robot.place(0, 0, "SOUTH") # => 2 # >> robot.report # => "0,0,SOUTH" # # Returns: # (String) - The current position and direction of the robot in the format "X,Y,FACING". def report return unless placed? coordinate_x, coordinate_y = @position.to_a.flatten "#{coordinate_x},#{coordinate_y},#{VALID_DIRECTIONS[@direction]}" end private # Check if the specified position is valid within the table boundaries. def valid_position?(coordinate_x, coordinate_y) (0..4).cover?(coordinate_x) && (0..4).cover?(coordinate_y) end # Check if the robot is placed on the table. def placed? !@position.nil? && !@direction.nil? end # Calculate the direction vector based on the current direction. def direction_vector direction = Matrix[[0], [0]] update_direction(direction) direction end # Update the direction vector based on the current direction. def update_direction(direction) case @direction when 0 direction[1, 0] = -1 when 1 direction[0, 0] = 1 when 2 direction[1, 0] = 1 when 3 direction[0, 0] = -1 end end end end