|
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) |
14 | 17 | } |
15 | 18 |
|
16 | | - _isCollision (x, y) { return (this.carts.filter((c) => c.x === x && c.y === y).length > 1) } |
| 19 | + _isCollision (x, y) { return (this.carts.filter((c) => c.x === x && c.y === y && c.ghost !== true).length > 1) } |
17 | 20 | _isIntersection (s) { return s === '+' } |
18 | 21 | _isTurn (s) { return this.trackTurns.indexOf(s) >= 0 } |
19 | 22 |
|
@@ -98,7 +101,7 @@ class Track { |
98 | 101 | let output = '' |
99 | 102 | const layout = JSON.parse(JSON.stringify(this.layout)) // Deep copy |
100 | 103 | // Include the carts |
101 | | - this.carts.forEach((cart) => { |
| 104 | + this.carts.filter((c) => c.ghost !== true).forEach((cart) => { |
102 | 105 | // If another cart is at the spot, draw a collision instead |
103 | 106 | if (this.cartDirections.indexOf(layout[cart.y][cart.x]) >= 0) { |
104 | 107 | layout[cart.y][cart.x] = 'X' |
@@ -166,17 +169,26 @@ class Track { |
166 | 169 | // Check for collision |
167 | 170 | if (this._isCollision(cart.x, cart.y)) { |
168 | 171 | this.collision = { x: cart.x, y: cart.y } |
169 | | - throw new Error(`collision at ${cart.x}, ${cart.y}`) // Stop everything |
| 172 | + |
| 173 | + if (!this.options.removeCrashedCarts) { |
| 174 | + throw new Error(`collision at ${cart.x}, ${cart.y}`) // Stop everything |
| 175 | + } |
| 176 | + this.carts.filter((c) => c.x === cart.x && c.y === cart.y).forEach((c) => { |
| 177 | + c.ghost = true // Ghost carts are dead and no longer collide |
| 178 | + // we leave them in the array so that it doesn't mess up the loops |
| 179 | + // necessary to finish out each cycle tick |
| 180 | + }) |
170 | 181 | } |
171 | 182 | // rotate the cart when entering a turn |
172 | 183 | if (this._isTurn(s)) { |
173 | 184 | cart.direction = this._rotate(s, a, d) |
174 | | - return |
| 185 | + return true |
175 | 186 | } |
176 | 187 | // rotate (or not) the cart when entering an intersection |
177 | 188 | if (this._isIntersection(s)) { |
178 | 189 | cart.direction = this._intersect(cart) |
179 | 190 | } |
| 191 | + return true |
180 | 192 | } |
181 | 193 |
|
182 | 194 | /** |
|
0 commit comments