# pathfinding
rng = new Chance 19930910
class Pathfinder
constructor: (@gridData, @targetPosition, @fillCallback, @visitedCallback, @foundCallback) ->
@width = @gridData[0].length
@height = @gridData.length
parseGridData: ->
data = []
for row, y in @gridData
for cell, x in row
index = y * @width + x
node =
open: !!cell
visited: false
index: 0
x: x
y: y
data[index] = node
data
beginFill: (x, y) ->
@startPosition = [x, y]
@reset()
@closeNode x, y
@addNeighbors x, y
@stepInterval = setInterval =>
@nextStep()
, 1000 / 60
nextStep: ->
if @open.length is 0
clearInterval @stepInterval
return
[x, y] = @iToC @open.shift()
@closeNode x, y
@addNeighbors x, y
addNeighbors: (x, y) ->
{index} = @data[@cToI x, y]
@addOpen x + 1, y, index
@addOpen x - 1, y, index
@addOpen x, y + 1, index
@addOpen x, y - 1, index
addOpen: (x, y, nodeIndex) ->
index = @cToI x, y
node = @data[index]
if node.open
if node.open
@open.push index
node.index = nodeIndex + 1
node.open = false
node.visited = true
@visitedCallback x, y, node.index
[tX, tY] = @targetPosition
if x is tX and y is tY
@targetFound()
closeNode: (x, y) ->
node = @data[@cToI x, y]
node.open = false
@fillCallback x, y, node.index
targetFound: ->
clearInterval @stepInterval
@solutionPath = []
@solutionPath.push @targetPosition
while @walkSolution()
true
pathFound: ->
path = @solutionPath.reverse()
@foundCallback...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.