3

我需要创建一个方法 turn_left 来改变朝向,朝向总是从 :south 开始(我正在实现一个移动到板中的机器人)所以如果我调用方法 turn_left 应该将朝向更改为东,然后到北,然后再到西返回南方。我在想这样的事情:

    {
     0: S
     1: E
     2: N
     3: W
    }

这是我的代码

# Models the Robor behavior for the game
class Robot

 def initialize(attr = {})
 # @position = attr[:position]
 # @move = attr[:move]
   @facing = :south
 # @turn_left =
 # @turn_right =
 # @errors =
 end

 def position
 end

 def move
 end

 def facing
  @facing
 end

 def turn_left

 end

 def turn_right
 end

 def errors
 end
end

非常感谢!!!

4

4 回答 4

5

像这样的东西怎么样:

class Robot
  FACINGS = [:south, :east, :north, :west]

  def initialize(attr = {})
    @facing_index = 0 # south
  end

  def facing
    FACINGS[@facing_index]
  end

  def turn_left
    @facing_index += 1
    @facing_index %= 4
  end

  def turn_right
    @facing_index -= 1
    @facing_index %= 4
  end
end

%= 4或者,如果您真的想进一步概括这一点,%= FACINGS.length)执行模算术以将当前索引“包装”回 0-3 范围内。

因此,通过增加/减少这个数字,您可以在四个方向之间切换。


我不知道您打算如何实施position,moveerrors,但我认为这超出了您的问题范围。

于 2018-11-13T17:03:36.840 回答
4

您可以将方向存储在数组中:

def initialize
  @dirs = [:S, :W, :N, :E]
end

first入口是面向的方向:

def facing
  @dirs.first
end

当机器人左转时,你rotate!逆时针排列数组:

def turn_left
  @dirs.rotate! -1
end

或右转时顺时针:(1此处可省略)

def turn_right
  @dirs.rotate! 1
end
于 2018-11-13T17:08:27.570 回答
4
left = {:n=>:w, :w=>:s, :s=>:e, :e=>:n}
right = left.invert
  #=> {:w=>:n, :s=>:w, :e=>:s, :n=>:e}

pos = :s

pos = left[pos]
  #=> :e
pos = right[pos]
  #=> :w
于 2018-11-13T17:13:32.940 回答
2

我会用度数而不是枚举。这样,您可以通过从当前面中添加/减去n度来操纵面。

class Robot
  attr_accessor :facing

  def initialize(**attrs)
    self.facing = attrs[:facing] || 180 # south
  end

  def rotate!(degrees)
    self.facing = (self.facing + degrees) % 360
  end

  def rotate_left!
    rotate!(-90)
  end

  def rotate_right!
    rotate!(90)
  end
end

然后,您可以使用一种相对简单的方法将度数转换为基数(罗盘点):

class Robot
  COMPASS_POINTS = %w[N E S W]

  # ...

  def compass_point
    seg_size = 360 / COMPASS_POINTS.size
    COMPASS_POINTS[((facing + (seg_size / 2)) % 360) / seg_size]
  end
end

这个取自geocoder gem

这可能看起来有点复杂,但可以让您存储已执行的命令,rotate: 90或者rotate: -90如果您想跟踪它。如果需要,它还可以让您将机器人旋转完整(无级)360 度。

于 2018-11-13T17:59:11.853 回答