根据Ruby中的外观更改位置

时间:2018-11-13 19:03:19

标签: ruby

我需要实现一种移动方法,该方法可以根据朝向改变位置,位置是[x,y],我认为如果向南移动是y + 1,向北y-1,向东x-1,向西x + 1。这种运动形成矩阵。 这是我的代码。非常感谢您的帮助!

# Models the Robot behavior for the game
class Robot
 FACINGS = [:south, :east, :north, :west]

 def initialize(attr = {})
  @position = attr[:position] || [1, 1]
  # @move = attr[:move]
  @facing_index = facing_index(attr[:facing]) || 0 # south
  @facing = facing
  # @errors =
 end

 def position
  @position
 end

 def move

 end

 def facing
  @facing = FACINGS[@facing_index]
 end

 def errors
 end

 private

 def facing_index(facing)
  facing if facing.is_a? Integer
  FACINGS.index(facing&.to_sym)
 end
end

3 个答案:

答案 0 :(得分:1)

添加MOVES,该标签说明了如何根据自己的面对面进行移动。

MOVES = {
  north: [0, 1],
  south: [0, -1],
  east:  [1, 0],
  west:  [-1,0]
}

def move
  move = MOVES.fetch(@facing)
  @position[0] += move[0]
  @position[1] += move[1]
end

MOVES.fetch(@facing)代替了MOVES[@facing],因此如果该面没有动静,则会引发错误。

您也可以使用case语句来执行此操作,但这使move变得简单且由数据驱动。您可以添加更多方向,例如northeast: [1,1]。而且,如果将其设置为实例变量,则可以自定义各个机器人的移动方式。

# Define `moves` and `moves=` to get and set `@moves`
attr_accessor :moves

def initialize(attr = {})
  ...
  # Initialize `moves` with either Robot.new(moves: {...})
  # or the default MOVES
  @moves ||= attr[:moves] || MOVES
  ...
end

def move
  move = moves.fetch(@facing)
  @position[0] += move[0]
  @position[1] += move[1]
end

答案 1 :(得分:1)

DIRECTION_NUMBER = { :north=>0, :east=>1, :south=>2, :west=>3 }

@left = { :north=>:west, :west=>:south, :south=>:east, :east=>:north }
@right = @left.invert
  #=> {:west=>:north, :south=>:west, :east=>:south, :north=>:east}

def turn_left
  @facing = @left[@facing]
end

def turn_right
  @facing = @right[@facing]
end

def move(direction)
  x, y = @location
  @location =
  case direction
  when :north
    [x,y+1]
  when :east
    [x+1,y]
  when :south
    [x,y-1]
  else
    [x-1,y]
  end
  update_facing(direction)
end

private

def update_facing(direction)
  change = (DIRECTION_NUMBER[direction] - DIRECTION_NUMBER[@facing]) % 4
  case change
  when 1
    turn_right
  when 2
    turn_right; turn_right
  when 3
    turn_left
  end
end

@location = [3, 3]    
@facing = :east

move(:south)
@location   #=> [3, 2]
@facing     #=> :south

move(:north)
@location   #=> [3, 3]
@facing     #=> :north

move(:west)
@location   #=> [2, 3]
@facing     #=> :west

move(:east)
@location   #=> [3, 3]
@facing     #=> :east

答案 2 :(得分:1)

FACINGS枚举示例。

document.getElementById(myGridID).addEventListener("paste", function(e) {
    var clipboardContent = window.clipboardData ? window.clipboardData.getData("Text") : (e.clipboardData ? e.clipboardData.getData("text/plain") : "");
    if(clipboardContent != null && clipboardContent.indexOf('\t') >= 0)
    {
        MyExcelPasteFunction(myGridID, clipboardContent);
        e.preventDefault();
    }
});