11const { dynamicSortMultiple } = require ( '../day-04/helpers' )
22
33class Track {
4- constructor ( track ) {
4+ constructor ( track , options ) {
55 this . layout = [ ]
66 this . carts = [ ]
77 this . cartDirections = [ '^' , '>' , 'v' , '<' ]
88 this . collision = false
99 this . frame = 0
1010 this . interSectionOrder = [ - 1 , 0 , 1 ]
11+ this . options = options || {
12+ removeCrashedCarts : false
13+ }
1114 this . trackTurns = [ '\\' , '/' ]
1215 this . trackTypes = this . trackTurns . concat ( [ '-' , '|' , '+' ] )
1316 this . setLayout ( track )
@@ -81,14 +84,16 @@ class Track {
8184 */
8285 advance ( ) {
8386 this . frame ++
84- this . carts . sort ( dynamicSortMultiple ( 'y' , 'x' ) ) . forEach ( ( c ) => {
85- try {
86- this . moveCart ( c )
87- } catch ( err ) {
88- console . error ( `Problem moving cart in frame ${ this . frame } ` )
89- console . error ( err )
90- }
91- } )
87+ while ( this . carts . filter ( ( c ) => c . moved === this . frame ) . length < this . carts . length ) {
88+ this . carts . filter ( ( c ) => c . moved !== this . frame ) . sort ( dynamicSortMultiple ( 'y' , 'x' ) ) . forEach ( ( c ) => {
89+ try {
90+ this . moveCart ( c )
91+ } catch ( err ) {
92+ console . error ( `Problem moving cart in frame ${ this . frame } ` )
93+ console . error ( err )
94+ }
95+ } )
96+ }
9297 }
9398
9499 /**
@@ -157,6 +162,7 @@ class Track {
157162 const l = ( d % 3 === 0 ) ? - 1 : 1 // (+/-) distance of travel on the axis
158163 // move the cart
159164 cart [ a ] = cart [ a ] + l
165+ cart . moved = this . frame
160166 const s = this . getSegment ( cart . x , cart . y ) // Segment of track the cart is now on
161167
162168 // Make sure cart hasn't run off the rails
@@ -166,17 +172,28 @@ class Track {
166172 // Check for collision
167173 if ( this . _isCollision ( cart . x , cart . y ) ) {
168174 this . collision = { x : cart . x , y : cart . y }
169- throw new Error ( `collision at ${ cart . x } , ${ cart . y } ` ) // Stop everything
175+ console . log ( `Collision in frame ${ this . frame } . removeCrashedCarts is ${ this . options . removeCrashedCarts } ` )
176+
177+ // Handle crashed carts
178+ if ( this . options . removeCrashedCarts ) {
179+ this . carts . filter ( ( c ) => c . x === cart . x && c . y === cart . y ) . forEach ( ( c ) => {
180+ this . carts . splice ( this . carts . indexOf ( c ) , 1 )
181+ } )
182+ } else {
183+ throw new Error ( `collision at ${ cart . x } , ${ cart . y } ` ) // Stop everything
184+ }
170185 }
186+
171187 // rotate the cart when entering a turn
172188 if ( this . _isTurn ( s ) ) {
173189 cart . direction = this . _rotate ( s , a , d )
174- return
190+ return true
175191 }
176192 // rotate (or not) the cart when entering an intersection
177193 if ( this . _isIntersection ( s ) ) {
178194 cart . direction = this . _intersect ( cart )
179195 }
196+ return true
180197 }
181198
182199 /**
0 commit comments