Project1

标题: 如何高效地判断地图某处能否抵达? [打印本页]

作者: 受pia专用ID    时间: 2012-6-26 21:23
标题: 如何高效地判断地图某处能否抵达?
本帖最后由 受pia专用ID 于 2012-6-26 21:24 编辑

RUBY 代码复制
  1. class Map
  2.   def initialize
  3.     @things = {}
  4.     @width = 1
  5.     @height = 1
  6.   end
  7.   attr_reader :width, :height
  8.   def set_point(x, y, obj)
  9.     @width = [x + 1, @width].max
  10.     @height = [y + 1, @height].max
  11.     @things[[x,y]] = obj
  12.   end
  13.   def get_point(x, y)
  14.     return @things[[x,y]]
  15.   end
  16.   def passable?(x, y)
  17.     return @things[[x,y]] == nil
  18.   end
  19.   def expand_from(x, y, create = false) #create是否重新生成一个区域
  20.     @area = Map.new if create
  21.     @area.set_point(x, y, true)
  22.     if x > 0 #不是靠在左侧
  23.       nx = x-1 ; ny = y
  24.       if @area.get_point(nx, ny) == nil and @things[[nx, ny]] == nil
  25.         expand_from(nx, ny)
  26.       end
  27.     end
  28.     if x < @width - 1 #不是靠在右侧
  29.       nx = x+1 ; ny = y
  30.       if @area.get_point(nx, ny) == nil and @things[[nx, ny]] == nil
  31.         expand_from(nx, ny)
  32.       end
  33.     end
  34.     if y > 0 #不是靠在上侧
  35.       nx = x ; ny = y-1
  36.       if @area.get_point(nx, ny) == nil and @things[[nx, ny]] == nil
  37.         expand_from(nx, ny)
  38.       end
  39.     end
  40.     if y < @height - 1 #不是靠在下侧
  41.       nx = x  ; ny = y+1
  42.       if @area.get_point(nx, ny) == nil and @things[[nx, ny]] == nil
  43.         expand_from(nx, ny)
  44.       end
  45.     end
  46.   end
  47.   def set_up_map(obj)#以array直接设定
  48.     @width = obj[0].size
  49.     @height = obj.size
  50.     for y in 0...obj.size
  51.       for x in 0...obj[0].size
  52.         set_point(x, y, obj[y][x])
  53.       end
  54.     end
  55.   end
  56.   def test
  57.     return @area
  58.   end
  59.   def reachable?(fx, fy, x, y)
  60.     expand_from(fx, fy)
  61.     if @area.get_point(x, y) == true
  62.       return true
  63.     else
  64.       return false
  65.     end
  66.   end
  67. end

上面是我定义的Map类,以hash表储存。nil表示可以通过,否则不能通过。我定义了reachable?(fx, fy, x, y),意思是判断从fx, fy点能否抵达x,y点,大概意思就是自动寻路。不过我希望找到效率更高的方案。
作者: dant    时间: 2012-7-12 17:41
把能走到的地方记录下来




欢迎光临 Project1 (https://rpg.blue/) Powered by Discuz! X3.1