1
1
const { dynamicSortMultiple } = require ( '../day-04/helpers' )
2
2
3
3
class Track {
4
- constructor ( track ) {
4
+ constructor ( track , options ) {
5
5
this . layout = [ ]
6
6
this . carts = [ ]
7
7
this . cartDirections = [ '^' , '>' , 'v' , '<' ]
8
8
this . collision = false
9
9
this . frame = 0
10
10
this . interSectionOrder = [ - 1 , 0 , 1 ]
11
+ this . options = options || {
12
+ removeCrashedCarts : false
13
+ }
11
14
this . trackTurns = [ '\\' , '/' ]
12
15
this . trackTypes = this . trackTurns . concat ( [ '-' , '|' , '+' ] )
13
16
this . setLayout ( track )
@@ -81,14 +84,16 @@ class Track {
81
84
*/
82
85
advance ( ) {
83
86
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
+ }
92
97
}
93
98
94
99
/**
@@ -157,6 +162,7 @@ class Track {
157
162
const l = ( d % 3 === 0 ) ? - 1 : 1 // (+/-) distance of travel on the axis
158
163
// move the cart
159
164
cart [ a ] = cart [ a ] + l
165
+ cart . moved = this . frame
160
166
const s = this . getSegment ( cart . x , cart . y ) // Segment of track the cart is now on
161
167
162
168
// Make sure cart hasn't run off the rails
@@ -166,17 +172,28 @@ class Track {
166
172
// Check for collision
167
173
if ( this . _isCollision ( cart . x , cart . y ) ) {
168
174
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
+ }
170
185
}
186
+
171
187
// rotate the cart when entering a turn
172
188
if ( this . _isTurn ( s ) ) {
173
189
cart . direction = this . _rotate ( s , a , d )
174
- return
190
+ return true
175
191
}
176
192
// rotate (or not) the cart when entering an intersection
177
193
if ( this . _isIntersection ( s ) ) {
178
194
cart . direction = this . _intersect ( cart )
179
195
}
196
+ return true
180
197
}
181
198
182
199
/**
0 commit comments