Skip to content

Instantly share code, notes, and snippets.

@miio
Last active December 15, 2015 08:39
Show Gist options
  • Save miio/5232324 to your computer and use it in GitHub Desktop.
Save miio/5232324 to your computer and use it in GitHub Desktop.
@near_blocks = []
@cost = nil
def nears(i,j)
[[i-1,j],[i+1,j],[i,j-1],[i,j+1]]
end
def near_astar map_sizes, ignores, target, current
x = current[:x]
y = current[:y]
tx = target[:x]
ty = target[:y]
# check not goal
return [] if nears(tx, ty).select{|n| ignores.select{|i| i[:x] == n[0] and i[:y] == n[1]}.length > 0 }.length >= 4
costs = []
positions = {}
nears(x, y).each do |e|
next if ignores.select{|i| i[:x] == e[0] and i[:y] == e[1]}.length > 0
# calc cost
if tx >= e[0]
cost = tx - e[0]
else
cost = tx + e[0]
end
if ty >= e[1]
cost += ty - e[1]
else
cost += ty + e[1]
end
costs << cost
positions[cost] = e
end
# retry or return if low cost?
unless costs.empty?
# retry or return if low cost?
cost = nil
loop do
cost = costs.min
break unless @near_blocks.include?(positions[cost])
costs.delete cost
return if costs.empty?
end
e = positions[cost]
@cost = cost
@near_blocks << e
# return if bingo
return if tx == e[0] and ty == e[1]
# next loop
near_astar map_sizes, ignores, target, {x: e[0], y: e[1]}
end
end
ignores = []
near_astar({x: 10, y: 10}, ignores, {x: 5, y: 5}, {x: 8, y: 1})
p @near_blocks
@cost = nil
@near_blocks = []
ignores = [{x: 8, y: 5}, {x: 7, y:5}]
near_astar({x: 10, y: 10}, ignores, {x: 5, y: 5}, {x: 8, y: 1})
p @near_blocks
@miio
Copy link
Author

miio commented Mar 24, 2013

$ ruby astar.rb    
[[8, 2], [8, 3], [8, 4], [8, 5], [7, 5], [6, 5], [5, 5]]
[[8, 2], [8, 3], [8, 4], [7, 4], [6, 4], [5, 4], [5, 5]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment