about summary refs log tree commit diff stats
path: root/app/assets/javascripts/wittle/puzzle.js
diff options
context:
space:
mode:
authorStar Rauchenberger <fefferburbia@gmail.com>2023-10-28 00:16:07 -0400
committerStar Rauchenberger <fefferburbia@gmail.com>2023-10-28 00:16:07 -0400
commitb496a29a7de381765f3c45ced9fa18f026b2e314 (patch)
tree34f6558ffed34b0ec922c90e6407d165e9256b59 /app/assets/javascripts/wittle/puzzle.js
parentd09db2d6d0727faba8e5078900f2fbd1e18ea49f (diff)
downloadwittle-b496a29a7de381765f3c45ced9fa18f026b2e314.tar.gz
wittle-b496a29a7de381765f3c45ced9fa18f026b2e314.tar.bz2
wittle-b496a29a7de381765f3c45ced9fa18f026b2e314.zip
serve
Diffstat (limited to 'app/assets/javascripts/wittle/puzzle.js')
-rw-r--r--app/assets/javascripts/wittle/puzzle.js507
1 files changed, 507 insertions, 0 deletions
diff --git a/app/assets/javascripts/wittle/puzzle.js b/app/assets/javascripts/wittle/puzzle.js new file mode 100644 index 0000000..a7ad10a --- /dev/null +++ b/app/assets/javascripts/wittle/puzzle.js
@@ -0,0 +1,507 @@
1namespace(function() {
2
3// A 2x2 grid is internally a 5x5:
4// corner, edge, corner, edge, corner
5// edge, cell, edge, cell, edge
6// corner, edge, corner, edge, corner
7// edge, cell, edge, cell, edge
8// corner, edge, corner, edge, corner
9//
10// Corners and edges will have a value of true if the line passes through them
11// Cells will contain an object if there is an element in them
12window.Puzzle = class {
13 constructor(width, height, pillar=false) {
14 if (pillar === true) {
15 this.newGrid(2 * width, 2 * height + 1)
16 } else {
17 this.newGrid(2 * width + 1, 2 * height + 1)
18 }
19 this.pillar = pillar
20 this.settings = {
21 // If true, negation symbols are allowed to cancel other negation symbols.
22 NEGATIONS_CANCEL_NEGATIONS: true,
23
24 // If true, and the count of polyominos and onimoylops is zero, they cancel regardless of shape.
25 SHAPELESS_ZERO_POLY: false,
26
27 // If true, the traced line cannot go through the placement of a polyomino.
28 PRECISE_POLYOMINOS: true,
29
30 // If false, incorrect elements will not flash when failing the puzzle.
31 FLASH_FOR_ERRORS: true,
32
33 // If true, mid-segment startpoints will constitute solid lines, and form boundaries for the region.
34 FAT_STARTPOINTS: false,
35
36 // If true, custom mechanics are displayed (and validated) in this puzzle.
37 CUSTOM_MECHANICS: false,
38
39 // If true, polyominos may be placed partially off of the grid as an intermediate solution step.
40 // OUT_OF_BOUNDS_POLY: false,
41 }
42 }
43
44 static deserialize(json) {
45 var parsed = JSON.parse(json)
46 // Claim that it's not a pillar (for consistent grid sizing), then double-check ourselves later.
47 var puzzle = new Puzzle((parsed.grid.length - 1)/2, (parsed.grid[0].length - 1)/2)
48 puzzle.name = parsed.name
49 puzzle.autoSolved = parsed.autoSolved
50 puzzle.grid = parsed.grid
51 // Legacy: Grid squares used to use 'false' to indicate emptiness.
52 // Legacy: Cells may use {} to represent emptiness
53 // Now, we use:
54 // Cells default to null
55 // During onTraceStart, empty cells that are still inbounds are changed to {'type': 'nonce'} for tracing purposes.
56 // Lines default to {'type':'line', 'line':0}
57 for (var x=0; x<puzzle.width; x++) {
58 for (var y=0; y<puzzle.height; y++) {
59 var cell = puzzle.grid[x][y]
60 if (cell === false || cell == null || cell.type == null) {
61 if (x%2 === 1 && y%2 === 1) puzzle.grid[x][y] = null
62 else puzzle.grid[x][y] = {'type':'line', 'line':window.LINE_NONE}
63 } else {
64 if (cell.type === 'poly' || cell.type === 'ylop') {
65 if (cell.rot === 'all') {
66 // Legacy: Polys and ylops used to have a rot value (before I started using polyshape).
67 // rot=all is a holdover that was used to represent rotation polyominos.
68 puzzle.grid[x][y].polyshape |= window.ROTATION_BIT
69 delete puzzle.grid[x][y].rot
70 }
71 // Fixup: Sometimes we have a polyshape which is empty. Just ignore these objects.
72 if (puzzle.grid[x][y].polyshape & ~window.ROTATION_BIT === 0) puzzle.grid[x][y] = null
73 } else if ((x%2 !== 1 || y%2 !== 1) && cell.color != null) {
74 // Legacy: Lines used to use 'color' instead of 'line', but that was redundant with actual colors
75 cell.line = cell.color
76 delete cell.color
77 } else if (cell.gap === true) {
78 // Legacy: Gaps used to be null/true, are now null/1/2
79 puzzle.grid[x][y].gap = window.GAP_BREAK
80 }
81 }
82 }
83 }
84 // Legacy: Startpoints used to be only parsed.start
85 if (parsed.start) {
86 parsed.startPoints = [parsed.start]
87 }
88 // Legacy: Startpoints used to be a separate array, now they are flags
89 if (parsed.startPoints) {
90 for (var startPoint of parsed.startPoints) {
91 puzzle.grid[startPoint.x][startPoint.y].start = true
92 }
93 }
94 // Legacy: Endpoints used to be only parsed.end
95 if (parsed.end) {
96 parsed.endPoints = [parsed.end]
97 }
98 // Legacy: Endpoints used to be a separate array, now they are flags
99 if (parsed.endPoints) {
100 for (var endPoint of parsed.endPoints) {
101 puzzle.grid[endPoint.x][endPoint.y].end = endPoint.dir
102 }
103 }
104 // Legacy: Dots and gaps used to be separate arrays
105 // Now, they are flags on the individual lines.
106 if (parsed.dots) {
107 for (var dot of parsed.dots) {
108 puzzle.grid[dot.x][dot.y].dot = window.DOT_BLACK
109 }
110 }
111 if (parsed.gaps) {
112 for (var gap of parsed.gaps) {
113 puzzle.grid[gap.x][gap.y].gap = window.GAP_BREAK
114 }
115 }
116 if (parsed.settings) {
117 for (var key of Object.keys(parsed.settings)) {
118 puzzle.settings[key] = parsed.settings[key]
119 }
120 }
121 puzzle.pillar = parsed.pillar
122 puzzle.symmetry = parsed.symmetry
123 puzzle.largezero = puzzle.width * puzzle.height
124 return puzzle
125 }
126
127 serialize() {
128 return JSON.stringify(this)
129 }
130
131 clone() {
132 return Puzzle.deserialize(this.serialize())
133 }
134
135 // This is explicitly *not* just clearing the grid, so that external references
136 // to the grid are not also cleared.
137 newGrid(width, height) {
138 if (width == null) { // Called by someone who just wants to clear the grid.
139 width = this.width
140 height = this.height
141 }
142 this.grid = []
143 for (var x=0; x<width; x++) {
144 this.grid[x] = []
145 for (var y=0; y<height; y++) {
146 if (x%2 === 1 && y%2 === 1) this.grid[x][y] = null
147 else this.grid[x][y] = {'type':'line', 'line':LINE_NONE}
148 }
149 }
150 // Performance: A large value which is === 0 to be used for pillar wrapping.
151 // Performance: Getting the size of the grid has a nonzero cost.
152 // Definitely getting the length of the first element isn't optimized.
153 this.largezero = width * height * 2
154 this.width = this.grid.length
155 this.height = this.grid[0].length
156 }
157
158 // Wrap a value around at the width of the grid. No-op if not in pillar mode.
159 _mod(val) {
160 if (this.pillar === false) return val
161 return (val + this.largezero) % this.width
162 }
163
164 // Determine if an x, y pair is a safe reference inside the grid. This should be invoked at the start of every
165 // function, but then functions can access the grid directly.
166 _safeCell(x, y) {
167 if (x < 0 || x >= this.width) return false
168 if (y < 0 || y >= this.height) return false
169 return true
170 }
171
172 getCell(x, y) {
173 x = this._mod(x)
174 if (!this._safeCell(x, y)) return null
175 return this.grid[x][y]
176 }
177
178 setCell(x, y, value) {
179 x = this._mod(x)
180 if (!this._safeCell(x, y)) return
181 this.grid[x][y] = value
182 }
183
184 getSymmetricalDir(dir) {
185 if (this.symmetry != null) {
186 if (this.symmetry.x === true) {
187 if (dir === 'left') return 'right'
188 if (dir === 'right') return 'left'
189 }
190 if (this.symmetry.y === true) {
191 if (dir === 'top') return 'bottom'
192 if (dir === 'bottom') return 'top'
193 }
194 }
195 return dir
196 }
197
198 // The resulting position is guaranteed to be gridsafe.
199 getSymmetricalPos(x, y) {
200 if (this.symmetry != null) {
201 if (this.pillar === true) {
202 x += this.width/2
203 if (this.symmetry.x === true) {
204 x = this.width - x
205 }
206 } else {
207 if (this.symmetry.x === true) {
208 x = (this.width - 1) - x
209 }
210 }
211 if (this.symmetry.y === true) {
212 y = (this.height - 1) - y
213 }
214 }
215 return {'x':this._mod(x), 'y':y}
216 }
217
218 getSymmetricalCell(x, y) {
219 var pos = this.getSymmetricalPos(x, y)
220 return this.getCell(pos.x, pos.y)
221 }
222
223 matchesSymmetricalPos(x1, y1, x2, y2) {
224 return (y1 === y2 && this._mod(x1) === x2)
225 }
226
227 // A variant of getCell which specifically returns line values,
228 // and treats objects as being out-of-bounds
229 getLine(x, y) {
230 var cell = this.getCell(x, y)
231 if (cell == null) return null
232 if (cell.type !== 'line') return null
233 return cell.line
234 }
235
236 updateCell2(x, y, key, value) {
237 x = this._mod(x)
238 if (!this._safeCell(x, y)) return
239 var cell = this.grid[x][y]
240 if (cell == null) return
241 cell[key] = value
242 }
243
244 getValidEndDirs(x, y) {
245 x = this._mod(x)
246 if (!this._safeCell(x, y)) return []
247
248 var dirs = []
249 var leftCell = this.getCell(x - 1, y)
250 if (leftCell == null || leftCell.gap === window.GAP_FULL) dirs.push('left')
251 var topCell = this.getCell(x, y - 1)
252 if (topCell == null || topCell.gap === window.GAP_FULL) dirs.push('top')
253 var rightCell = this.getCell(x + 1, y)
254 if (rightCell == null || rightCell.gap === window.GAP_FULL) dirs.push('right')
255 var bottomCell = this.getCell(x, y + 1)
256 if (bottomCell == null || bottomCell.gap === window.GAP_FULL) dirs.push('bottom')
257 return dirs
258 }
259
260 // Note: Does not use this.width/this.height, so that it may be used to ask about resizing.
261 getSizeError(width, height) {
262 if (this.pillar && width < 4) return 'Pillars may not have a width of 1'
263 if (width * height < 25) return 'Puzzles may not be smaller than 2x2 or 1x4'
264 if (width > 21 || height > 21) return 'Puzzles may not be larger than 10 in either dimension'
265 if (this.symmetry != null) {
266 if (this.symmetry.x && width <= 2) return 'Symmetrical puzzles must be sufficiently wide for both lines'
267 if (this.symmetry.y && height <= 2) return 'Symmetrical puzzles must be sufficiently wide for both lines'
268 if (this.pillar && this.symmetry.x && width % 4 !== 0) return 'X + Pillar symmetry must be an even number of rows, to keep both startpoints at the same parity'
269 }
270
271 return null
272 }
273
274
275 // Called on a solution. Computes a list of gaps to show as hints which *do not*
276 // break the path.
277 loadHints() {
278 this.hints = []
279 for (var x=0; x<this.width; x++) {
280 for (var y=0; y<this.height; y++) {
281 if (x%2 + y%2 === 1 && this.getLine(x, y) > window.LINE_NONE) {
282 this.hints.push({'x':x, 'y':y})
283 }
284 }
285 }
286 }
287
288 // Show a hint on the grid.
289 // If no hint is provided, will select the best one it can find,
290 // prioritizing breaking current lines on the grid.
291 // Returns the shown hint.
292 showHint(hint) {
293 if (hint != null) {
294 this.grid[hint.x][hint.y].gap = window.GAP_BREAK
295 return
296 }
297
298 var goodHints = []
299 var badHints = []
300
301 for (var hint of this.hints) {
302 if (this.getLine(hint.x, hint.y) > window.LINE_NONE) {
303 // Solution will be broken by this hint
304 goodHints.push(hint)
305 } else {
306 badHints.push(hint)
307 }
308 }
309 if (goodHints.length > 0) {
310 var hint = goodHints.splice(window.randInt(goodHints.length), 1)[0]
311 } else if (badHints.length > 0) {
312 var hint = badHints.splice(window.randInt(badHints.length), 1)[0]
313 } else {
314 return
315 }
316 this.grid[hint.x][hint.y].gap = window.GAP_BREAK
317 this.hints = badHints.concat(goodHints)
318 return hint
319 }
320
321 clearLines() {
322 for (var x=0; x<this.width; x++) {
323 for (var y=0; y<this.height; y++) {
324 this.updateCell2(x, y, 'line', 0)
325 this.updateCell2(x, y, 'dir', null)
326 }
327 }
328 }
329
330 _floodFill(x, y, region, col) {
331 var cell = col[y]
332 if (cell === MASKED_PROCESSED) return
333 if (cell !== MASKED_INB_NONCOUNT) {
334 region.push({'x':x, 'y':y})
335 }
336 col[y] = MASKED_PROCESSED
337
338 if (y < this.height - 1) this._floodFill(x, y + 1, region, col)
339 if (y > 0) this._floodFill(x, y - 1, region, col)
340 if (x < this.width - 1) this._floodFill(x + 1, y, region, this.grid[x+1])
341 else if (this.pillar !== false) this._floodFill(0, y, region, this.grid[0])
342 if (x > 0) this._floodFill(x - 1, y, region, this.grid[x-1])
343 else if (this.pillar !== false) this._floodFill(this.width-1, y, region, this.grid[this.width-1])
344 }
345
346 // Re-uses the same grid, but only called on edges which border the outside
347 // Called first to mark cells that are connected to the outside, i.e. should not be part of any region.
348 _floodFillOutside(x, y, col) {
349 var cell = col[y]
350 if (cell === MASKED_PROCESSED) return
351 if (x%2 !== y%2 && cell !== MASKED_GAP2) return // Only flood-fill through gap-2
352 if (x%2 === 0 && y%2 === 0 && cell === MASKED_DOT) return // Don't flood-fill through dots
353 col[y] = MASKED_PROCESSED
354
355 if (x%2 === 0 && y%2 === 0) return // Don't flood fill through corners (what? Clarify.)
356
357 if (y < this.height - 1) this._floodFillOutside(x, y + 1, col)
358 if (y > 0) this._floodFillOutside(x, y - 1, col)
359 if (x < this.width - 1) this._floodFillOutside(x + 1, y, this.grid[x+1])
360 else if (this.pillar !== false) this._floodFillOutside(0, y, this.grid[0])
361 if (x > 0) this._floodFillOutside(x - 1, y, this.grid[x-1])
362 else if (this.pillar !== false) this._floodFillOutside(this.width-1, y, this.grid[this.width-1])
363 }
364
365 // Returns the original grid (pre-masking). You will need to switch back once you are done flood filling.
366 switchToMaskedGrid() {
367 // Make a copy of the grid -- we will be overwriting it
368 var savedGrid = this.grid
369 this.grid = new Array(this.width)
370 // Override all elements with empty lines -- this means that flood fill is just
371 // looking for lines with line=0.
372 for (var x=0; x<this.width; x++) {
373 var savedRow = savedGrid[x]
374 var row = new Array(this.height)
375 var skip = 1
376 if (x%2 === 1) { // Cells are always part of the region
377 for (var y=1; y<this.height; y+=2) row[y] = MASKED_INB_COUNT
378 skip = 2 // Skip these cells during iteration
379 }
380 for (var y=0; y<this.height; y+=skip) {
381 var cell = savedRow[y]
382 if (cell.line > window.LINE_NONE) {
383 row[y] = MASKED_PROCESSED // Traced lines should not be a part of the region
384 } else if (cell.gap === window.GAP_FULL) {
385 row[y] = MASKED_GAP2
386 } else if (cell.dot > window.DOT_NONE) {
387 row[y] = MASKED_DOT
388 } else {
389 row[y] = MASKED_INB_COUNT
390 }
391 }
392 this.grid[x] = row
393 }
394
395 // Starting at a mid-segment startpoint
396 if (this.startPoint != null && this.startPoint.x%2 !== this.startPoint.y%2) {
397 if (this.settings.FAT_STARTPOINTS) {
398 // This segment is not in any region (acts as a barrier)
399 this.grid[this.startPoint.x][this.startPoint.y] = MASKED_OOB
400 } else {
401 // This segment is part of this region (acts as an empty cell)
402 this.grid[this.startPoint.x][this.startPoint.y] = MASKED_INB_NONCOUNT
403 }
404 }
405
406 // Ending at a mid-segment endpoint
407 if (this.endPoint != null && this.endPoint.x%2 !== this.endPoint.y%2) {
408 // This segment is part of this region (acts as an empty cell)
409 this.grid[this.endPoint.x][this.endPoint.y] = MASKED_INB_NONCOUNT
410 }
411
412 // Mark all outside cells as 'not in any region' (aka null)
413
414 // Top and bottom edges
415 for (var x=1; x<this.width; x+=2) {
416 this._floodFillOutside(x, 0, this.grid[x])
417 this._floodFillOutside(x, this.height - 1, this.grid[x])
418 }
419
420 // Left and right edges (only applies to non-pillars)
421 if (this.pillar === false) {
422 for (var y=1; y<this.height; y+=2) {
423 this._floodFillOutside(0, y, this.grid[0])
424 this._floodFillOutside(this.width - 1, y, this.grid[this.width-1])
425 }
426 }
427
428 return savedGrid
429 }
430
431 getRegions() {
432 var regions = []
433 var savedGrid = this.switchToMaskedGrid()
434
435 for (var x=0; x<this.width; x++) {
436 for (var y=0; y<this.height; y++) {
437 if (this.grid[x][y] == MASKED_PROCESSED) continue
438
439 // If this cell is empty (aka hasn't already been used by a region), then create a new one
440 // This will also mark all lines inside the new region as used.
441 var region = []
442 this._floodFill(x, y, region, this.grid[x])
443 regions.push(region)
444 }
445 }
446 this.grid = savedGrid
447 return regions
448 }
449
450 getRegion(x, y) {
451 x = this._mod(x)
452 if (!this._safeCell(x, y)) return
453
454 var savedGrid = this.switchToMaskedGrid()
455 if (this.grid[x][y] == MASKED_PROCESSED) {
456 this.grid = savedGrid
457 return null
458 }
459
460 // If the masked grid hasn't been used at this point, then create a new region.
461 // This will also mark all lines inside the new region as used.
462 var region = []
463 this._floodFill(x, y, region, this.grid[x])
464
465 this.grid = savedGrid
466 return region
467 }
468
469 logGrid() {
470 var output = ''
471 for (var y=0; y<this.height; y++) {
472 var row = []
473 for (var x=0; x<this.width; x++) {
474 var cell = this.getCell(x, y)
475 if (cell == null) row[x] = ' '
476 else if (cell.type === 'nonce') row[x] = ' '
477 else if (cell.start === true) row[x] = 'S'
478 else if (cell.end != null) row[x] = 'E'
479 else if (cell.type === 'line') {
480 if (cell.gap > 0) row[x] = ' '
481 if (cell.dot > 0) row[x] = 'X'
482 if (cell.line === 0) row[x] = '.'
483 if (cell.line === 1) row[x] = '#'
484 if (cell.line === 2) row[x] = '#'
485 if (cell.line === 3) row[x] = 'o'
486 } else row[x] = '?'
487 }
488 output += row.join('') + '\n'
489 }
490 console.info(output)
491 }
492}
493
494// The grid contains 5 colors:
495// null: Out of bounds or already processed
496var MASKED_OOB = null
497var MASKED_PROCESSED = null
498// 0: In bounds, awaiting processing, but should not be part of the final region.
499var MASKED_INB_NONCOUNT = 0
500// 1: In bounds, awaiting processing
501var MASKED_INB_COUNT = 1
502// 2: Gap-2. After _floodFillOutside, this means "treat normally" (it will be null if oob)
503var MASKED_GAP2 = 2
504// 3: Dot (of any kind), otherwise identical to 1. Should not be flood-filled through (why the f do we need this)
505var MASKED_DOT = 3
506
507})