Un code fait par mes soins permettant d'utiliser l'algorithme A* dans des programmes ecrits en Javascript.
L'interface est ecrite en oriente objet, donc c'est vraiment simple a utiliser.

Voici la documentation associee (des commentaires sont egalements presents dans le fichier source, en francais en ce qui concerne les commentaires inline, et dans un anglais approximatif pour les commentaires de fonctions) :

Le code source associe :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
===========================================================================
======================== A* (A Star) algorithm ============================
===========================================================================
====== INFORMATIONS:
====== 
====== Version 1.0b - August 2008
====== By Mael Nison (nison_m@epitech.net), for the Kyria Project
====== 
====== The main comments (functions descriptions, readme, ...) are in
====== english, but single-line comments are in french.
===========================================================================
====== NOTES:
====== 
====== #1: The lists are under a special shape, because we need to destroy
====== elements by their keys.
====== 
====== #2: The response of the getBetterNode() function is under the shape:
====== [ID of the best node, content of the best node]
====== The best node is directly put in the black list.
===========================================================================
====== CONFIGURATION OPTIONS (second parameter of the constructor):
====== 
====== -- iterations --
====== Maximal number of nodes which will be read. Usefull for big maps.
====== Default value is the width of the map by its height (width*height).
====== You don't have to use an upper value, but you can use a lowest. As
====== you want ...
====== 
====== -- debug --
====== If set on 'true', display some information on the screen. You can use it
====== if you want to know how A* works. Default value is false.
======
====== -- ondbg --
====== Function called when a debug text must be displayed
====== 
====== -- diagonal --
====== If set on 'true', A* will check diagonal nodes (a). If set on 'false',
====== it will only check the closest nodes (b).
====== a. + + +  b. X + X
======    + O +     + 0 +
======    + + +     X + X
====== Default value is false. If you want to use it, you may need
====== to change the heuristic (look underneath).
====== 
====== -- cost --
====== It's a function which is called to get the cost of the current node.
====== Default is: function(obj, fromX, fromY, toX, toY) { return obj.map[toY][toX]; }
====== (obj is the Pathfinder object)
====== 
====== -- heuristic --
====== It's a function called to get an approximative value from the current
====== node to the end of the path. Default value is the Manhattan heuristic.
======
====== -- wall --
====== Function called to check if the current node is a wall. It return a boolean.
===========================================================================
*/
 
/*
===========================================================================
====== [Object] Astar(map, [, configuration]);
====== 
====== It's the constructor of the class. It don't return anything else
====== than itself.
====== 
====== @map must be an array which contain other arrays. These arrays must
====== have the same length.
====== 
====== @configuration is an optionnal argument. It's an object. All pairs
====== of key/value will be copied in the configuration array. See the main
====== documentation for more information.
===========================================================================
*/
function AStar(map) {
	this.map    = map;
	this.height = map.length;
	this.width  = map[0].length;
	this.configuration.iterations = this.height*this.width;
	if(arguments.length > 1) {
		for(var key in arguments[1]) {
			this.configuration[key] = arguments[1][key];
		}
	}
}
 
AStar.prototype.configuration = {iterations:Number.MAX_VALUE,debug:false,diagonal:false,cost:function(obj, fromX, fromY, toX, toY) { return obj.map[toY][toX]; },heuristic:function(obj, x, y) { return ( Math.abs(obj.endX - x) + Math.abs(obj.endY - y) ); },wall:function(obj, fromX, fromY, toX, toY) { return false; },ondbg:function(text) { document.write(text); }};
AStar.prototype.black         = new Array();
AStar.prototype.white         = new Array();
AStar.prototype.startX        = 0;
AStar.prototype.startY        = 0;
AStar.prototype.endX          = 0;
AStar.prototype.endY          = 0;
 
/*
===========================================================================
====== [Array] AStar.process(startX, startY, endX, endY);
====== 
====== Use this function to get the best path between two nodes. Its
====== response will be an array. The first item will be the global
====== deplacement cost, the second will be the path used, and the third
====== will be the error number. This last item is in the array only if none
====== paths has been found.
====== 1 = The maximal number of iterations has been reach (often, if you
======     had put a low iteration number in the configuration)
====== 2 = All nodes have been checked, and there is no path to go to the
======     end node. (you can have this error if the start or the end nodes
======     are outside the map)
====== 
====== @startX and @startY are the cartesians positions of the start node.
====== @endX and @endY are the cartesians positions of the end node.
===========================================================================
*/
AStar.prototype.process = function(startX,startY,endX,endY){
		// On convertis les valeur entrées en paramètre afin qu'elles soient de type INT (sinon, erreurs avec les chaînes de caractères)
			startX = parseInt(startX);
			startY = parseInt(startY);
			endX   = parseInt(endX);
			endY   = parseInt(endY);
		// Au cas où la position de départ est la même que celle d'arrivée on ne lance PAS l'algorithme (sinon, bug) et on calcule directement le chemin
			if(startX == endX && startY == endY) return [this.cost(startX, startY, startX, startY, true), [[startX,startY]]];
		// On met à zéro le nombre d'itérations
			var iters = 0;
		// On nettoie les listes (#1)
			this.white  = {length:0,id:0,array:{},push:function(element){this.array[this.id]=element; this.id++; this.length++; return this.id-1; },remove:function(id){delete this.array[id]; this.length--;}};
			this.black  = {length:0,id:0,array:{},push:function(element){this.array[this.id]=element; this.id++; this.length++; return this.id-1; },remove:function(id){delete this.array[id]; this.length--;}};
		// On enregistre les paramètres du parcours
			this.startX = startX;
			this.startY = startY;
			this.endX   = endX;
			this.endY   = endY;
		// On ajoute la case de départ à la liste ouverte
			this.white.push(this.node(-1, startX, startY));
		// On boucle tant qu'il y a des éléments dans la liste ouverte
			while(iters < this.configuration.iterations && this.white.length > 0) {
				// On incrémente le nombre d'itérations (ne fait pas partie de l'algorithme en lui-même...il s'agit juste d'une protection pour éviter les boucles infinies)
					iters++;
				// On récupère la case avec le plus petit coût F et on la transfère dans la liste noire (#2)
					var node = this.getBetterNode();
					if(this.configuration.debug) this.configuration.ondbg("Noeud lu: X:"+node[1].x+" Y:"+node[1].y+" F:"+node[1].F+" G:"+node[1].G+" H:"+node[1].H+" PARENT:"+node[1].parent+"<br />");
				// On vérifie que cette case ne soit pas la case finale (auquel cas on quitte la boucle)
					if(node[1].x == endX && node[1].y == endY) {
						if(this.configuration.debug) this.configuration.ondbg('<br />Chemin trouvé !<br />');
						var parent = node[0];
						var path   = new Array();
						do {
							if(this.configuration.debug) this.configuration.ondbg('&nbsp;&nbsp;&nbsp;&nbsp;Passage par #'+parent+',  X:'+this.black.array[parent].x+' Y:'+this.black.array[parent].y+' (parent: #'+this.black.array[parent].parent+')<br>');
							path[path.length] = [this.black.array[parent].x, this.black.array[parent].y];
							parent = this.black.array[parent].parent;
						} while(parent >= 0);
						var reversePath = new Array();
						for(var t=0; t<path.length; t++) {
							reversePath[t] = path[path.length-1-t];
						}
						return [node[1].G+this.cost(this.black.array[node[1].parent].x, this.black.array[node[1].parent].y, endX, endY, true), reversePath];
					}
				// On vérifie les quatres cases alentours
					this.check(node[0], node[1].x+0, node[1].y-1); // En haut
					this.check(node[0], node[1].x+0, node[1].y+1); // En bas
					this.check(node[0], node[1].x-1, node[1].y+0); // A gauche
					this.check(node[0], node[1].x+1, node[1].y+0); // A droite
				// Plus les quatres cases diagonale, si l'option à été activée
					if(this.configuration.diagonal) {
						this.check(node[0], node[1].x+1, node[1].y-1); // En haut à droite
						this.check(node[0], node[1].x-1, node[1].y+1); // En bas à gauche
						this.check(node[0], node[1].x+1, node[1].y+1); // En bas à droite
						this.check(node[0], node[1].x-1, node[1].y-1); // En haut à gauche
					}
				if(this.configuration.debug) this.configuration.ondbg('<br>');
			}
		// On calcule le code d'erreur
			if(iters == this.configuration.iterations) {
				var errCode = 1;
			} else if(this.white.length == 0) {
				var errCode = 2;
			} else {
				var errCode = -1;
			}
		// Si aucun chemin n'a été trouvé, on renvois un triplet contenant false et le code d'erreur de l'algorithme
			return [false, false, errCode];
	}
 
/*
===========================================================================
====== *** PRIVATE FUNCTION, YOU DON'T HAVE TO USE IT ***
====== 
====== [Void] AStar.check(parent, x, y);
====== 
====== If necessary, add the checked node to the white list.
====== 
====== @parent is the parent node of the checked node.
====== @x and @y are the cartesians positions of the checked node.
===========================================================================
*/
AStar.prototype.check = function(parent, x, y){
		// On vérifie que la case existe dans la carte (qu'elle ne soit pas en dehors de la zone) et qu'elle ne soit pas un bloc
			if(x>=0 && x<this.width && y>=0 && y<this.height && !this.configuration.wall(this, this.black.array[parent].x, this.black.array[parent].y, x, y)) {
				var id = this.exist("white", x, y);
				if(typeof(id) != "boolean") {
					if(this.white.array[id].G > this.black.array[parent].G+this.cost(this.black.array[parent].x, this.black.array[parent].y, x, y, false)){
						this.white.array[id].G = this.black.array[parent].G+this.cost(this.black.array[parent].x, this.black.array[parent].y, x, y, false);
						this.white.array[id].F = this.white.array[id].G + this.white.array[id].H;
						this.white.array[id].parent = parent;
						if(this.configuration.debug) this.configuration.ondbg("&nbsp;&nbsp;&nbsp;&nbsp;Noeud modifié ("+id+"): X:"+x+" Y:"+y+" F:"+this.white.array[id].F+" G:"+this.white.array[id].G+" H:"+this.white.array[id].H+" PARENT:"+parent+"<br />");
					}
				} else if(typeof(this.exist("black", x, y))=="boolean") {
					var node = this.node(parent, x, y);
					var id   = this.white.push(node);
					if(this.configuration.debug) this.configuration.ondbg("&nbsp;&nbsp;&nbsp;&nbsp;Noeud ajouté ("+id+"): X:"+x+" Y:"+y+" F:"+node.F+" G:"+node.G+" H:"+node.H+" PARENT:"+parent+"<br />");
				}
			} else if(this.configuration.debug) this.configuration.ondbg('&nbsp;&nbsp;&nbsp;&nbsp;Refus d\'accèder à la case '+x+', '+y+'<br>');
	}
 
/*
===========================================================================
====== *** PRIVATE FUNCTION, YOU DON'T HAVE TO USE IT ***
====== 
====== [Integer/Boolean] AStar.exist(type, x, y);
====== 
====== Return 'false' if a node with specified positions exist in the @type
====== list. Else, return the ID of the node matched. You may need a typeof
====== to get the real response of this function (it can return 0 or 'false').
====== 
====== @type is the list where the search will be perform (can be "white"
====== or "black").
===========================================================================
*/
AStar.prototype.exist = function(type, x, y) {
		var test   = (type=="white") ? this.white : this.black;
		var result = false;
		for(var tmp in test.array) {
			if(test.array[tmp].x == x && test.array[tmp].y == y){
				result = tmp;
				break;
			}
		}
		return result;
	}
 
/*
===========================================================================
====== *** PRIVATE FUNCTION, YOU DON'T HAVE TO USE IT ***
====== 
====== [Array] AStar.node(parent, x, y);
====== 
====== Build a node.
====== 
====== @parent is the parent node of the node to build
====== @x and @y are the cartesians positions of the node to build.
===========================================================================
*/
AStar.prototype.node = function(parent, x, y){
		if(parent >= 0) {
			var oldCost = this.black.array[parent].G;
			var oldx    = this.black.array[parent].x;
			var oldy    = this.black.array[parent].y;
		} else {
			var oldCost = 0;
			var oldx    = x;
			var oldy    = y;
		}
		var node = {}
		node.x = x;
		node.y = y;
		node.G = oldCost + this.cost(oldx, oldy, x, y, false);
		node.H = this.heuristic(x, y);
		node.F = node.G + node.H;
		node.parent = parent;
		return node;
	}
 
/*
===========================================================================
====== *** PRIVATE FUNCTION, YOU DON'T HAVE TO USE IT ***
====== 
====== [Integer] AStar.cost(fromX, fromY, toX, toY [, real=false]);
====== 
====== Return the cost to go onto the targeted node (use the cost
====== configuration callback).
====== 
====== @fromX and @fromY are the cartesians positions of the parent of the
====== node looked.
====== @toX and @toY are the cartesians positions of the node looked.
====== @real is egal to 'false' if the end node of the path must always
====== return 0.
===========================================================================
*/
AStar.prototype.cost = function(fromX, fromY, toX, toY, real) {
		if(typeof(real)=="undefined") var real = false;
		return (toX!=this.endX || toY!=this.endY || real) ? this.configuration.cost(this, fromX, fromY, toX, toY) : 0;
	}
 
/*
===========================================================================
====== *** PRIVATE FUNCTION, YOU DON'T HAVE TO USE IT ***
====== 
====== [Array] AStar.heuristic(x, y);
====== 
====== Call the heuristic configuration callback.
====== 
====== @x and @y are the cartesians positions of the node looked.
===========================================================================
*/
AStar.prototype.heuristic = function(x, y) {
		return this.configuration.heuristic(this, x, y);
	}
 
/*
===========================================================================
====== *** PRIVATE FUNCTION, YOU DON'T HAVE TO USE IT ***
====== 
====== [Array] AStar.getBetterNode( [Void] );
====== 
====== Return the node with the lowest F cost in the white list, and move it
====== into the black list. If you need to make references to this node
====== after, you must call it in the black list, not in the white.
===========================================================================
*/
AStar.prototype.getBetterNode = function(){
		var min = Number.MAX_VALUE;
		var id = false;
		for(var tmp in this.white.array) {
			if(this.white.array[tmp].F <= min) {
				min = this.white.array[tmp].F;
				id = tmp;
			}
		}
		this.black.array[id] = this.white.array[id];
		this.white.remove(id);
		return new Array(id, this.black.array[id]);
	}
Elle permet de retrouver rapidement le plus court chemin entre deux points.

Pour l'utiliser, il n'y a que deux fonctions à connaitre: le constructeur et la méthode process().

Voici la documentation des fonctions:

<void> function AStar(array Map [, object Config]);

@Map contient un objet qui devra contenir la carte. Par exemple, le tableau suivant est valide et contiendra
une carte où tout les déplacements couteront 1:
[ [ 1 , 1 ] ,
[ 1 , 1 ] ]

@Config contient un objet recensant la configuration du moteur AStar. Il est optionnel, et s'il est mentionné,
tous les paramètres qui ne sont pas indiqués seront remplacés par ceux par défaut. Consultez la
documentation des options pour plus de détails.
<array> function AStar.process(int startX, int startY, int endX, int endY);

@startX et @startY contiennent simplement les coordonnées de départ.
@endX et @endY contiennent simplement les coordonnées de fin.

La fonction retourne un tableau, contenant deux ou trois valeurs:
1: (int / bool) Contient false si aucun chemin n'a été trouvé, et dans le cas contraire le coût total
2: (array / bool) Contient false si aucun chemin n'a été trouvé, et dans le cas contraire le chemin trouvé
3: (int) N'est présent que si une erreur s'est déroulée. Contient le numéro de l'erreur. Consultez la
documentation des erreurs pour plus de détails.
Documentation des codes d'erreur:
  • -1 Erreur inconnue (vous foutez pas de ma gueule ...)
    1 Nombre maximal d'itérations atteint, et aucun chemin trouvé.
    2 Pas de chemin disponible.


Documentation des options:
  • iterations Contient le nombre maximal d'itérations qu'effectuera le moteur AStar avant de déclarer un chemin introuvable. Par défaut, Number.MAX_VALUE, soit la valeur maximale que supporte le navigateur internet (au-delà, c'est NaN).

    debug Si true, affiche quelques informations à l'écran. Pas besoin de l'utiliser, normalement. false par défaut.

    ondbg Contient une fonction callback appelée lorsqu'il y a un débugguage. Par défaut:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    function(msg){document.write(msg);}
    diagonal Si true, le moteur AStar recherchera également les chemins avec les diagonales. Par défaut, false.

    cost Contient une fonction callback appelée pour calculer le cout de déplacement sur une case. Par défaut:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    function(obj, fromX, fromY, toX, toY) { return obj.map[toY][toX]; }
    heuristic Contient une fonction callback appelée pour calculer le cout avec l'heuristique. Par défaut, l'heuristique de Manhattan est utilisée.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    function(obj, x, y) { return ( Math.abs(obj.endX - x) + Math.abs(obj.endY - y) ); }
    wall Contient une fonction callback appelée pour savoir si une case est un mur ou non. Par défaut:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    function(obj, fromX, fromY, toX, toY) { return false; }


Dans toutes les fonctions callback, @obj représente l'objet AStar lui-même, et @obj.map permet d'accéder à la carte précédement enregistrée lors de la création de l'objet. Notez qu'il est tout à fait possible de remplir le case du tableau avec des objets, puis de redéfinir les fonctions calklback afin de tenir compte de plusieurs paramètres (par exemple, pour Kyria, j'ai pris en compte les autorisations de déplacement vers la gauche/droite/haut/bas).