接着我昨天的问题,下面是我在实际项目中的代码,不确定这样写行不行。
def lines_array(*coordinate)
count = LineInfo.where(player: self.to_pointer).count
if count == 0
return []
else
lines = LineInfo.where(player: self.to_pointer).execute
first = true
path = []
construct_path = ->(*coordinate, &operation) {
if lines.empty?
return path
elsif lines.size == 1
operation.call lines
return path
else
target_index = 0
if first
target_index = -1
first = false
end
base_x, base_y = transform_coordinate coordinate
lines.sort_by! do |line|
x, y = transform_coordinate( line.pointArray[-1].split(':') )
(base_x - x)**2 + (base_y - y)**2
end
the_line = operation.call lines
x, y = the_line.pointArray[target_index].split ':'
construct_path.call(x, y) do |lines|
the_line = lines.shift
path << {
color: the_line.color,
style: the_line.style,
pointArray: converse_coordinates(the_line.pointArray)
}
the_line
end
end
}
construct_path.call(*coordinate) do |lines|
the_line = lines.shift
path << {
color: the_line.color,
style: the_line.style,
pointArray: converse_coordinates(the_line.pointArray)
}
the_line
end
end
end
def transform_coordinate(coordinate)
[coordinate[0].to_i, coordinate[1].to_i]
end
def converse_coordinates(ary)
if ary.nil?
[]
else
ary.map do |coordinate|
x, y = coordinate.split ':'
"{#{x}, #{y}}"
end
end
end
最后的调用像这个样子
player.lines_array( '123', '456' )
其中 line 的 pointArray 是一个 [ "123:456", "789:123" , ... ] 这样的坐标字串数组。 coordinate 是一个点的坐标 x ,y 字串数组,像这个样子 [ '123', '456' ]