Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. # works on things turning and moving
  2. class Grid
  3. attr_accessor :x, :y
  4.  
  5. def at(x, y)
  6. self.x = x
  7. self.y = y
  8. end
  9.  
  10. def coordinates
  11. [x, y]
  12. end
  13.  
  14. def advance(bearing)
  15. self.y += 1 if bearing == :north
  16. self.y -= 1 if bearing == :south
  17. self.x += 1 if bearing == :east
  18. self.x -= 1 if bearing == :west
  19. end
  20. end
  21.  
  22. # can orient and move
  23. class Robot
  24. DIRECTIONS = [:north, :east, :south, :west].freeze
  25. attr_accessor :bearing, :grid
  26.  
  27. def initialize
  28. @grid = Grid.new
  29. end
  30.  
  31. def place(args = {})
  32. x = args[:x]
  33. y = args[:y]
  34. direction = args[:direction]
  35.  
  36. at(x, y)
  37. self.bearing = direction
  38. self
  39. end
  40.  
  41. def orient(direction)
  42. raise ArgumentError unless DIRECTIONS.include? direction
  43. self.bearing = direction
  44. end
  45.  
  46. def turn_right
  47. current_index = DIRECTIONS.index(bearing)
  48. next_indext = (current_index + 1) % 4
  49. self.bearing = DIRECTIONS[next_indext]
  50. end
  51.  
  52. def turn_left
  53. current_index = DIRECTIONS.index(bearing)
  54. next_indext = (current_index - 1)
  55. self.bearing = DIRECTIONS[next_indext]
  56. end
  57.  
  58. def at(x, y)
  59. grid.at(x, y)
  60. end
  61.  
  62. def coordinates
  63. grid.coordinates
  64. end
  65.  
  66. def advance
  67. grid.advance(bearing)
  68. end
  69. end
  70.  
  71. # handles instructions for robot
  72. class Simulator
  73. DICTIONARY = { 'L' => :turn_left,
  74. 'R' => :turn_right,
  75. 'A' => :advance }.freeze
  76.  
  77. def instructions(command_string)
  78. command_string.chars.map do |letter|
  79. DICTIONARY[letter]
  80. end
  81. end
  82.  
  83. def place(robot, args = {})
  84. robot.place(args)
  85. end
  86.  
  87. def evaluate(robot, command_string)
  88. instructions = instructions(command_string)
  89. instructions.each do |instruction|
  90. robot.send(instruction)
  91. end
  92. end
  93. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement