@@ -132,7 +132,7 @@ function findEnemyToAttack(player, allPlayers) {
132132}
133133
134134function findNextMovement ( player , allPlayers , map ) {
135- let targetKeys = { } ;
135+ let targetKeys = { } ; // "x,y" ==> { x, y } of alive enemy
136136 allPlayers
137137 . filter ( p => p . alive && p . type !== player . type )
138138 . map ( p => getAdjacents ( p . pos ) . filter ( pos => map [ pos . y ] [ pos . x ] === FREE ) )
@@ -152,34 +152,33 @@ function findNextMovement(player, allPlayers, map) {
152152 let xy = `${ adj . x } ,${ adj . y } ` ;
153153 if ( targetKeys [ xy ] ) {
154154 // found a path to a target!
155- // add it so at the end of the iteration we chose the right one based on first step order
155+ // add it so at the end of the iteration we chose the right one based on enemy order
156156 targetPaths . push ( [ ...path , adj , targetKeys [ xy ] ] ) ;
157157 } else if ( ! visited [ xy ] && map [ adj . y ] [ adj . x ] === FREE ) {
158- // we push the extended path for the next iteration
158+ // new extended path to explore at next iteration
159159 newPaths . push ( [ ...path , adj ] ) ;
160160 }
161161 visited [ xy ] = true ; // mark as visited so other paths ignore it
162162 } ) ;
163163 } ) ;
164164
165165 if ( targetPaths . length > 0 ) {
166- // if we found multiple shortest paths, take the step to reach the first target according top-to-bottom/left-to-right order
166+ // we got one or more paths reaching a target for the first time, here is where our search ends
167+ // if we found multiple shortest paths, use the one that reaches the first target according top-to-bottom/left-to-right order
167168 targetPaths = targetPaths . sort ( ( p1 , p2 ) =>
168169 p1 [ p1 . length - 1 ] . y === p2 [ p2 . length - 1 ] . y
169170 ? p1 [ p1 . length - 1 ] . x - p2 [ p2 . length - 1 ] . x
170171 : p1 [ p1 . length - 1 ] . y - p2 [ p2 . length - 1 ] . y
171172 ) ;
172173
173- // we return the first step to take for the shortest path ([0] is the player current position)
174+ // return the first step to take for the shortest path ([0] is the player current position)
174175 return targetPaths [ 0 ] [ 1 ] ;
175176 }
176177
178+ // no paths to a target found yet, keep iterating with the paths after one more step
177179 paths = newPaths ;
178- if ( paths . length < 1 ) return null ; // no reachables targets!
180+ if ( paths . length < 1 ) return null ; // no reachables targets, search ends without a result
179181 }
180-
181- // explode paths until one or more targets are reached
182- // once that happens, use the path for the top-to-bottom/left-to-right first target reached
183182}
184183
185184function getAdjacents ( pos ) {
0 commit comments