-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexolve-multi.js
3336 lines (3166 loc) · 100 KB
/
exolve-multi.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/*
MIT License
Copyright (c) 2019 Viresh Ratnakar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The latest code and documentation for exolve can be found at:
https://github.com/viresh-ratnakar/exolve
*/
const VERSION = 'Exolve v0.36 October 22 2019 (w/reentrancy via DoctorBud)'
let puzzleInstanceId = 0;
let puzzleInstances = {};
const exolvePrefix = 'exolve-';
class Puzzle {
constructor() {
const puzzleThis = this;
puzzleInstanceId = puzzleInstanceId + 1;
this.id = puzzleInstanceId;
const puzzlePrefix = `${exolvePrefix}${puzzleInstanceId}-`;
puzzleInstances[puzzlePrefix] = this;
// ------ Begin globals.
let puzzleId = 'exolve-grid'
let gridWidth = 0
let gridHeight = 0
let boxWidth = 0
let boxHeight = 0
let gridFirstLine = -1
let gridLastLine = -1
let preludeFirstLine = -1
let preludeLastLine = -1
let acrossFirstLine = -1
let acrossLastLine = -1
let downFirstLine = -1
let downLastLine = -1
let nodirFirstLine = -1
let nodirLastLine = -1
let explanationsFirstLine = -1
let explanationsLastLine = -1
// Each nina will be an array containing location [i,j] pairs and/or span
// class names.
let ninas = []
// For span-class-specified ninas, ninaClassElements[] stores the elements
// along with the colours to apply to them when showing the ninas.
let ninaClassElements = []
let showingNinas = false
let grid = []
let clues = {}
let cellColours = []
let submitURL = null
let submitKeys = []
let hasDiagramlessCells = false
let hasUnsolvedCells = false
let hasSomeAnnos = false
let hasAcrossClues = false
let hasDownClues = false
let hasNodirClues = false
// Clues labeled non-numerically (like [A] a clue...) use this to create a
// unique clueIndex.
let nextNonNumId = 1
let nonNumClueIndices = {}
const SQUARE_DIM = 31
const SQUARE_DIM_BY2 = 16
const GRIDLINE = 1
const BAR_WIDTH = 3
const BAR_WIDTH_BY2 = 2
const SEP_WIDTH = 2
const SEP_WIDTH_BY2 = 1.5
const HYPHEN_WIDTH = 9
const HYPHEN_WIDTH_BY2 = 5
const CIRCLE_RADIUS = 0.0 + SQUARE_DIM / 2.0
const NUMBER_START_X = 2
const NUMBER_START_Y = 10
const LIGHT_START_X = 16.5
const LIGHT_START_Y = 21.925
let answersList = []
let revelationList = []
let currentRow = -1
let currentCol = -1
let currentDirectionIsAcross = true
let currentClueIndex = null
let activeCells = [];
let activeClues = [];
let numCellsToFill = 0
let allClueIndices = []
let orphanClueIndices = []
// For the orhpan-clues widget.
let posInOrphanClueIndices = 0
const BLOCK_CHAR = '⬛';
const ACTIVE_COLOUR = 'mistyrose'
const ORPHAN_CLUES_COLOUR = 'white'
const TRANSPARENT_WHITE = 'rgba(255,255,255,0.0)'
let nextPuzzleTextLine = 0
const STATE_SEP = 'eexxoollvvee'
// Variables set by exolve-option
let hideInferredNumbers = false
let cluesPanelLines = -1
// Variables set in init().
let puzzleTextLines;
let numPuzzleTextLines;
let svg;
let gridInputWrapper;
let gridInput;
let questions;
let background;
let acrossClues;
let downClues;
let nodirClues;
let acrossPanel;
let downPanel;
let nodirPanel;
let currentClue;
let currentClueParent;
let ninaGroup;
let statusNumFilled;
let statusNumTotal;
let savingURL;
let clearButton;
let clearAllButton;
let checkButton;
let checkAllButton;
let ninasButton;
let revealButton;
let revealAllButton;
let submitButton;
// ------ End globals.
// ------ Begin functions.
// Set up globals, version number and user agent in bug link.
function init(puzzleText) {
puzzleTextLines = []
let rawLines = puzzleText.trim().split('\n');
for (let rawLine of rawLines) {
let cIndex = rawLine.indexOf('#');
// A # followed by a non-space/non-eol character is not a comment marker.
while (cIndex >= 0 && cIndex + 1 < rawLine.length &&
rawLine.charAt(cIndex + 1) != ' ') {
cIndex = rawLine.indexOf('#', cIndex + 1);
}
if (cIndex >= 0) {
rawLine = rawLine.substr(0, cIndex).trim()
}
if (!rawLine) {
continue;
}
puzzleTextLines.push(rawLine)
}
numPuzzleTextLines = puzzleTextLines.length
svg = document.getElementById(puzzlePrefix + 'grid');
gridInputWrapper = document.getElementById(puzzlePrefix + 'grid-input-wrapper');
gridInput = document.getElementById(puzzlePrefix + 'grid-input');
questions = document.getElementById(puzzlePrefix + 'questions');
background =
document.createElementNS('http://www.w3.org/2000/svg', 'rect');
acrossPanel = document.getElementById(puzzlePrefix + 'across-clues-panel')
downPanel = document.getElementById(puzzlePrefix + 'down-clues-panel')
nodirPanel = document.getElementById(puzzlePrefix + 'nodir-clues-panel')
acrossClues = document.getElementById(puzzlePrefix + 'across')
downClues = document.getElementById(puzzlePrefix + 'down')
nodirClues = document.getElementById(puzzlePrefix + 'nodir')
currentClue = document.getElementById(puzzlePrefix + 'current-clue')
currentClueParent = document.getElementById(puzzlePrefix + 'current-clue-parent')
ninaGroup = document.getElementById(puzzlePrefix + 'nina-group')
statusNumFilled = document.getElementById(puzzlePrefix + 'status-num-filled')
statusNumTotal = document.getElementById(puzzlePrefix + 'status-num-total')
savingURL = document.getElementById(puzzlePrefix + 'saving-url')
clearButton = document.getElementById(puzzlePrefix + 'clear')
clearAllButton = document.getElementById(puzzlePrefix + 'clear-all')
checkButton = document.getElementById(puzzlePrefix + 'check')
checkAllButton = document.getElementById(puzzlePrefix + 'check-all')
ninasButton = document.getElementById(puzzlePrefix + 'ninas')
revealButton = document.getElementById(puzzlePrefix + 'reveal')
revealAllButton = document.getElementById(puzzlePrefix + 'reveal-all')
submitButton = document.getElementById(puzzlePrefix + 'submit')
let info = 'Version: ' + VERSION + ', User Agent: ' + navigator.userAgent
document.getElementById(puzzlePrefix + 'report-bug').href =
'https://github.com/viresh-ratnakar/exolve/issues/new?body=' +
encodeURIComponent(info);
}
// puzzleTextLines[] has been parsed till line # nextPuzzleTextLine. Fine the
// next line beginning with 'exolve-<section>' and return <section> as well
// as the 'value' of the section (the part after ':').
function parseToNextSection() {
const MARKER = 'exolve-'
while (nextPuzzleTextLine < numPuzzleTextLines &&
puzzleTextLines[nextPuzzleTextLine].trim().indexOf(MARKER) != 0) {
nextPuzzleTextLine++;
}
if (nextPuzzleTextLine >= numPuzzleTextLines) {
return null
}
// Skip past MARKER
let line = puzzleTextLines[nextPuzzleTextLine].trim().substr(MARKER.length)
let index = line.indexOf(':')
if (index < 0) {
index = line.length
}
nextPuzzleTextLine++
return {'section': line.substr(0, index).trim().toLowerCase(),
'value': line.substr(index + 1).trim()}
}
// Parse a nina line, which consists of cell locations of the nina specified
// using "chess notation" (a1 = bottom-left, etc.). Convert the cell locations
// to [row col] and push an array of these locations to the global ninas array.
function parseNina(s) {
let nina = []
let cellsOrClasses = s.split(' ')
for (let cellOrClass of cellsOrClasses) {
let cellLocation = parseCellLocation(cellOrClass)
if (!cellLocation) {
// Must be a class name, for a span-class-specified nina
nina.push(cellOrClass)
} else {
nina.push(cellLocation)
}
}
if (nina.length > 0) {
ninas.push(nina)
}
}
function parseColour(s) {
let colourAndCells = s.split(' ')
let colour = ''
for (let c of colourAndCells) {
if (!colour) {
colour = c
continue;
}
let cellLocation = parseCellLocation(c)
if (!cellLocation) {
addError('Could not parse cell location in: ' + c)
return
} else {
cellColours.push(cellLocation.concat(colour))
}
}
}
// Parse a question line and create the question element for it (which includes
// an input box for the answer). The solution answer may be provided after the
// last ')'.
function parseQuestion(s) {
let enumParse = parseEnum(s)
let inputLen = enumParse.len + enumParse.hyphenAfter.length +
enumParse.wordEndAfter.length
let afterEnum = enumParse.afterEnum
let rawQ = s.substr(0, afterEnum)
let hideEnum = false
if (inputLen > 0) {
if (s.substr(afterEnum, 1) == '*') {
beforeEnum = s.lastIndexOf('(', afterEnum - 1)
if (beforeEnum < 0) {
addError('Could not find open-paren strangely')
return
}
rawQ = s.substr(0, beforeEnum)
afterEnum++
hideEnum = true
}
}
let correctAnswer = s.substr(afterEnum).trim()
const question = document.createElement('div')
question.setAttributeNS(null, 'class', 'question');
const questionText = document.createElement('span')
questionText.innerHTML = rawQ
question.appendChild(questionText)
question.appendChild(document.createElement('br'))
if (inputLen == 0) {
hideEnum = true
inputLen = '30'
}
const TEXTAREA_COLS = 68
let rows = Math.floor(inputLen / TEXTAREA_COLS)
if (rows * TEXTAREA_COLS < inputLen) {
rows++
}
let cols = (rows > 1) ? TEXTAREA_COLS : inputLen
let aType = 'input'
if (rows > 1) {
aType = 'textarea'
}
const answer = document.createElement(aType)
if (rows > 1) {
answer.setAttributeNS(null, 'rows', '' + rows);
answer.setAttributeNS(null, 'cols', '' + cols);
} else {
answer.setAttributeNS(null, 'size', '' + cols);
}
answer.setAttributeNS(null, 'class', 'answer');
answersList.push({
'ans': correctAnswer,
'input': answer,
'hasEnum': (inputLen > 0),
});
if (!hideEnum) {
let answerValue = ''
let wordEndIndex = 0
let hyphenIndex = 0
for (let i = 0; i < enumParse.len; i++) {
answerValue = answerValue + '?'
if (wordEndIndex < enumParse.wordEndAfter.length &&
i == enumParse.wordEndAfter[wordEndIndex]) {
answerValue = answerValue + ' '
wordEndIndex++
}
if (hyphenIndex < enumParse.hyphenAfter.length &&
i == enumParse.hyphenAfter[hyphenIndex]) {
answerValue = answerValue + '-'
hyphenIndex++
}
}
answer.setAttributeNS(null, 'placeholder', '' + answerValue);
}
answer.setAttributeNS(null, 'class', 'answer');
if (rows == 1) {
answer.setAttributeNS(null, 'type', 'text');
}
answer.setAttributeNS(null, 'maxlength', '' + inputLen);
answer.setAttributeNS(null, 'autocomplete', 'off');
answer.setAttributeNS(null, 'spellcheck', 'false');
question.appendChild(answer)
questions.appendChild(question)
answer.addEventListener('input', updateAndSaveState);
}
function parseSubmit(s) {
let parts = s.split(' ')
if (s.length < 2) {
addError('Submit section must have a URL and a param name for the solution')
return
}
submitURL = parts[0]
submitKeys = []
for (let i = 1; i < parts.length; i++) {
submitKeys.push(parts[i])
}
}
function parseOption(s) {
let sparts = s.split(' ')
for (let spart of sparts) {
spart = spart.trim().toLowerCase()
if (spart == "hide-inferred-numbers") {
hideInferredNumbers = true
continue
}
let kv = spart.split(':')
if (kv.length != 2) {
addError('Expected exolve-option: key:value, got: ' + spart)
return
}
if (kv[0] == 'clues-panel-lines') {
cluesPanelLines = parseInt(kv[1])
if (isNaN(cluesPanelLines)) {
addError('Unexpected value in exolve-option: clue-panel-lines: ' + kv[1])
}
continue
}
addError('Unexpected exolve-option: ' + spart)
return
}
}
// The overall parser for the puzzle text. Also takes care of parsing and
// displaying all exolve-* sections except prelude, grid, across, down (for
// these, it just captures where the start and end lines are).
function parseOverallDisplayMost() {
let sectionAndValue = parseToNextSection()
while (sectionAndValue && sectionAndValue.section != 'end') {
let firstLine = nextPuzzleTextLine
let nextSectionAndValue = parseToNextSection()
let lastLine = nextPuzzleTextLine - 2
if (sectionAndValue.section == 'begin') {
} else if (sectionAndValue.section == 'id') {
puzzleId = sectionAndValue.value
} else if (sectionAndValue.section == 'title') {
document.getElementById(puzzlePrefix + 'title').innerHTML = sectionAndValue.value
} else if (sectionAndValue.section == 'setter') {
if (sectionAndValue.value.trim() != '') {
document.getElementById(puzzlePrefix + 'setter').innerHTML =
'By ' + sectionAndValue.value
}
} else if (sectionAndValue.section == 'copyright') {
document.getElementById(puzzlePrefix + 'copyright').innerHTML =
'Ⓒ ' + sectionAndValue.value
} else if (sectionAndValue.section == 'width') {
gridWidth = parseInt(sectionAndValue.value)
boxWidth = (SQUARE_DIM * gridWidth) + gridWidth + 1
} else if (sectionAndValue.section == 'height') {
gridHeight = parseInt(sectionAndValue.value)
boxHeight = (SQUARE_DIM * gridHeight) + gridHeight + 1
} else if (sectionAndValue.section == 'prelude') {
preludeFirstLine = firstLine
preludeLastLine = lastLine
} else if (sectionAndValue.section == 'grid') {
gridFirstLine = firstLine
gridLastLine = lastLine
} else if (sectionAndValue.section == 'nina') {
parseNina(sectionAndValue.value)
} else if (sectionAndValue.section == 'colour' ||
sectionAndValue.section == 'color') {
parseColour(sectionAndValue.value)
} else if (sectionAndValue.section == 'question') {
parseQuestion(sectionAndValue.value)
} else if (sectionAndValue.section == 'submit') {
parseSubmit(sectionAndValue.value)
} else if (sectionAndValue.section == 'across') {
acrossFirstLine = firstLine
acrossLastLine = lastLine
} else if (sectionAndValue.section == 'down') {
downFirstLine = firstLine
downLastLine = lastLine
} else if (sectionAndValue.section == 'nodir') {
nodirFirstLine = firstLine
nodirLastLine = lastLine
} else if (sectionAndValue.section == 'option') {
parseOption(sectionAndValue.value)
} else if (sectionAndValue.section == 'explanations') {
explanationsFirstLine = firstLine
explanationsLastLine = lastLine
}
sectionAndValue = nextSectionAndValue
}
}
// Extracts the prelude from its previously identified lines and sets up
// its display.
function parseAndDisplayPrelude() {
if (preludeFirstLine >= 0 && preludeFirstLine <= preludeLastLine) {
let preludeText = puzzleTextLines[preludeFirstLine]
let l = preludeFirstLine + 1
while (l <= preludeLastLine) {
preludeText = preludeText + '\n' + puzzleTextLines[l]
l++;
}
document.getElementById(puzzlePrefix + 'prelude').innerHTML = preludeText
}
}
// Extracts the explanations section from its previously identified lines,
// populates its element, and adds it to revelationList.
function parseAndDisplayExplanations() {
if (explanationsFirstLine >= 0 &&
explanationsFirstLine <= explanationsLastLine) {
let explanationsText = puzzleTextLines[explanationsFirstLine]
let l = explanationsFirstLine + 1
while (l <= explanationsLastLine) {
explanationsText = explanationsText + '\n' + puzzleTextLines[l]
l++;
}
const explanations = document.getElementById(puzzlePrefix + 'explanations')
explanations.innerHTML = explanationsText
revelationList.push(explanations)
}
}
// Append an error message to the errors div. Scuttle everything by seting
// gridWidth to 0.
function addError(error) {
document.getElementById(puzzlePrefix + 'errors').innerHTML =
document.getElementById(puzzlePrefix + 'errors').innerHTML + '<br/>' +
error;
gridWidth = 0
}
// Run some checks for serious problems with grid id, dimensions, etc. If found,
// abort with error.
function checkIdAndConsistency() {
if (puzzleId.match(/[^a-zA-Z\d-]/)) {
addError('Puzzle id should only have alphanumeric characters or -: ' +
puzzleId)
return
}
if (gridWidth < 1 || gridWidth > 25 || gridHeight < 1 || gridHeight > 25) {
addError('Bad/missing width/height');
return
} else if (gridFirstLine < 0 || gridLastLine < gridFirstLine ||
gridHeight != gridLastLine - gridFirstLine + 1) {
addError('Mismatched width/height');
return
}
for (let i = 0; i < gridHeight; i++) {
let lineW = puzzleTextLines[i + gridFirstLine].toUpperCase().
replace(/[^A-Z.0]/g, '').length
if (gridWidth != lineW) {
addError('Width in row ' + i + ' is ' + lineW + ', not ' + gridWidth);
return
}
}
if (submitURL && submitKeys.length != answersList.length + 1) {
addError('Have ' + submitKeys.length + ' submit paramater keys, need ' +
(answersList.length + 1));
return
}
}
// Parse grid lines into a gridWidth x gridHeight array of objects that have
// the following properties:
// isLight
// hasBarAfter
// hasBarUnder
// hasCircle
// isDiagramless
// startsClueLabel
// startsAcrossClue
// startsDownClue
// acrossClueLabel: #
// downClueLabel: #
// Also set the following globals:
// hasDiagramlessCells
// hasUnsolvedCells
function parseGrid() {
let hasSolvedCells = false
for (let i = 0; i < gridHeight; i++) {
grid[i] = new Array(gridWidth)
let gridLine = puzzleTextLines[i + gridFirstLine].
replace(/\s/g, '').toUpperCase()
let gridLineIndex = 0
for (let j = 0; j < gridWidth; j++) {
grid[i][j] = {};
let letter = gridLine.charAt(gridLineIndex);
if (letter != '.') {
grid[i][j].isLight = true
if (letter != '0') {
letter = letter.toUpperCase()
if (letter < 'A' || letter > 'Z') {
addError('Bad grid entry: ' + letter);
gridWidth = 0
return
}
grid[i][j].solution = letter
}
} else {
grid[i][j].isLight = false
}
grid[i][j].hasBarAfter = false
grid[i][j].hasBarUnder = false
grid[i][j].hasCircle = false
grid[i][j].isDiagramless = false
grid[i][j].prefill = false
gridLineIndex++
let thisChar = ''
while (gridLineIndex < gridLine.length &&
(thisChar = gridLine.charAt(gridLineIndex)) &&
(thisChar == '|' ||
thisChar == '_' ||
thisChar == '+' ||
thisChar == '@' ||
thisChar == '*' ||
thisChar == '!' ||
thisChar == ' ')) {
if (thisChar == '|') {
grid[i][j].hasBarAfter = true
} else if (thisChar == '_') {
grid[i][j].hasBarUnder = true
} else if (thisChar == '+') {
grid[i][j].hasBarAfter = true
grid[i][j].hasBarUnder = true
} else if (thisChar == '@') {
grid[i][j].hasCircle = true
} else if (thisChar == '*') {
grid[i][j].isDiagramless = true
} else if (thisChar == '!') {
grid[i][j].prefill = true
} else if (thisChar == ' ') {
} else {
addError('Should not happen! thisChar = ' + thisChar);
return
}
gridLineIndex++
}
if (grid[i][j].isDiagramless && letter == '.') {
grid[i][j].solution = '1'
}
if (grid[i][j].prefill &&
(!grid[i][j].isLight || letter < 'A' || letter > 'Z')) {
addError('Bad pre-filled cell (' + i + ',' + j +
') with letter: ' + letter)
return
}
if (grid[i][j].isDiagramless) {
hasDiagramlessCells = true
}
if (letter == '0') {
hasUnsolvedCells = true
}
if (letter >= 'A' && letter <= 'Z' && !grid[i][j].prefill) {
hasSolvedCells = true
}
}
}
if (hasUnsolvedCells && hasSolvedCells) {
addError('Either all or no solutions should be provided')
}
}
function startsAcrossClue(i, j) {
if (!grid[i][j].isLight) {
return false;
}
if (j > 0 && grid[i][j - 1].isLight && !grid[i][j - 1].hasBarAfter) {
return false;
}
if (grid[i][j].hasBarAfter) {
return false;
}
if (j == gridWidth - 1) {
return false;
}
if (!grid[i][j + 1].isLight) {
return false;
}
return true;
}
function startsDownClue(i, j) {
if (!grid[i][j].isLight) {
return false;
}
if (i > 0 && grid[i - 1][j].isLight && !grid[i - 1][j].hasBarUnder) {
return false;
}
if (grid[i][j].hasBarUnder) {
return false;
}
if (i == gridHeight - 1) {
return false;
}
if (!grid[i + 1][j].isLight) {
return false;
}
return true;
}
// Sets starts{Across,Down}Clue (boolean) and startsClueLabel (#) in
// grid[i][j]s where clues start.
function markClueStartsUsingGrid() {
if (hasDiagramlessCells && hasUnsolvedCells) {
// Cannot rely on grid. Clue starts should be provided in clues using
// prefixes like #a8, #d2, etc.
return
}
let nextClueNumber = 1
for (let i = 0; i < gridHeight; i++) {
for (let j = 0; j < gridWidth; j++) {
if (startsAcrossClue(i, j)) {
grid[i][j].startsAcrossClue = true
grid[i][j].startsClueLabel = '' + nextClueNumber
clues['A' + nextClueNumber] = {'cells': []}
}
if (startsDownClue(i, j)) {
grid[i][j].startsDownClue = true
grid[i][j].startsClueLabel = '' + nextClueNumber
clues['D' + nextClueNumber] = {'cells': []}
}
if (grid[i][j].startsClueLabel) {
nextClueNumber++
}
}
}
}
// If there are any html closing tags, move past them.
function adjustAfterEnum(clueLine, afterEnum) {
let lineAfter = clueLine.substr(afterEnum)
while (lineAfter.trim().substr(0, 2) == '</') {
let closer = clueLine.indexOf('>', afterEnum);
if (closer < 0) {
return afterEnum
}
afterEnum = closer + 1
lineAfter = clueLine.substr(afterEnum)
}
return afterEnum
}
// Parse a cell location in "chess notation" (a1 = bottom-left, etc.) and
// return a two-element array [row, col].
function parseCellLocation(s) {
s = s.trim()
let col = s.charCodeAt(0) - 'a'.charCodeAt(0)
let row = gridHeight - parseInt(s.substr(1))
if (isNaN(row) || isNaN(col) ||
row < 0 || row >= gridHeight || col < 0 || col >= gridWidth) {
return null
}
return [row, col];
}
// Parse an enum like (4) or (4,5), or (5-2,4).
// Return an object with the following properties:
// len
// hyphenAfter[] (0-based indices)
// wordEndAfter[] (0-based indices)
// afterEnum index after enum
function parseEnum(clueLine) {
let parse = {
'len': 0,
'wordEndAfter': [],
'hyphenAfter': [],
'afterEnum': clueLine.length,
};
let enumLocation = clueLine.search(/\([1-9]+[0-9\-,'’\s]*\)/)
if (enumLocation < 0) {
// Look for the the string 'word'/'letter'/? in parens.
enumLocation = clueLine.search(/\([^)]*(word|letter|\?)[^)]*\)/i)
if (enumLocation >= 0) {
let enumEndLocation =
enumLocation + clueLine.substr(enumLocation).indexOf(')')
if (enumEndLocation <= enumLocation) {
return parse
}
parse.afterEnum = adjustAfterEnum(clueLine, enumEndLocation + 1)
}
return parse
}
let enumEndLocation =
enumLocation + clueLine.substr(enumLocation).indexOf(')')
if (enumEndLocation <= enumLocation) {
return parse
}
parse.afterEnum = adjustAfterEnum(clueLine, enumEndLocation + 1)
let enumLeft = clueLine.substring(enumLocation + 1, enumEndLocation)
let nextPart
while (enumLeft && (nextPart = parseInt(enumLeft)) && !isNaN(nextPart) &&
nextPart > 0) {
parse.len = parse.len + nextPart
enumLeft = enumLeft.replace(/\s*\d+\s*/, '')
let nextSymbol = enumLeft.substr(0, 1)
if (nextSymbol == '-') {
parse.hyphenAfter.push(parse.len - 1)
enumLeft = enumLeft.substr(1)
} else if (nextSymbol == ',') {
parse.wordEndAfter.push(parse.len - 1)
enumLeft = enumLeft.substr(1)
} else if (nextSymbol == '\'') {
enumLeft = enumLeft.substr(1)
} else if (enumLeft.indexOf('’') == 0) {
// Fancy apostrophe
enumLeft = enumLeft.substr('’'.length)
} else {
break;
}
}
return parse
}
// Parse a clue label from the start of clueLine.
// Return an object with the following properties:
// error
// isFiller
// clueLabel
// isNonNum
// dir
// hasChildren
// skip
function parseClueLabel(clueLine) {
let parse = {};
parse.dir = ''
parse.hasChilden = false
parse.skip = 0
const numberParts = clueLine.match(/^\s*[1-9]\d*/)
if (numberParts && numberParts.length == 1) {
let clueNum = parseInt(numberParts[0])
parse.clueLabel = '' + clueNum
parse.isNonNum = false
parse.skip = numberParts[0].length
} else {
let bracOpenParts = clueLine.match(/^\s*\[/)
if (!bracOpenParts || bracOpenParts.length != 1) {
parse.isFiller = true
return parse
}
let pastBracOpen = bracOpenParts[0].length
let bracEnd = clueLine.indexOf(']')
if (bracEnd < 0) {
parse.error = 'Missing matching ] in clue label in ' + clueLine
return parse
}
parse.clueLabel = clueLine.substring(pastBracOpen, bracEnd).trim()
let temp = parseInt(parse.clueLabel)
if (!isNaN(temp)) {
parse.error = 'Numeric label not allowed in []: ' + clueLabel
return parse
}
if (parse.clueLabel.charAt(parse.clueLabel.length - 1) == '.') {
// strip trailing period
parse.clueLabel = parse.clueLabel.substr(0, parse.clueLabel.length - 1).trim()
}
parse.isNonNum = true
parse.skip = bracEnd + 1
}
clueLine = clueLine.substr(parse.skip)
const dirParts = clueLine.match(/^[aAdD]/) // no leading space
if (dirParts && dirParts.length == 1) {
parse.dir = dirParts[0].trim().toUpperCase()
parse.skip += dirParts[0].length
clueLine = clueLine.substr(dirParts[0].length)
}
const commaParts = clueLine.match(/^\s*,/)
if (commaParts && commaParts.length == 1) {
parse.hasChildren = true
parse.skip += commaParts[0].length
clueLine = clueLine.substr(commaParts[0].length)
}
// Consume trailing period if it is there.
const periodParts = clueLine.match(/^\s*\./)
if (periodParts && periodParts.length == 1) {
parse.hasChildren = false
parse.skip += periodParts[0].length
clueLine = clueLine.substr(periodParts[0].length)
}
return parse
}
// Parse a single clue.
// Return an object with the following properties:
// clueIndex
// clueLabel
// isNonNum
// children[] (raw parseClueLabel() resutls, not yet clueIndices)
// clue
// len
// hyphenAfter[] (0-based indices)
// wordEndAfter[] (0-based indices)
// startCell[] optional, used in diagramless+unsolved and nonth -numeric labels
// anno (the part after the enum, if present)
// isFiller
// error
function parseClue(dir, clueLine) {
let parse = {};
clueLine = clueLine.trim()
if (clueLine.indexOf('#') == 0) {
let startCell = parseCellLocation(clueLine.substr(1));
if (startCell) {
parse.startCell = startCell
}
clueLine = clueLine.replace(/^#[a-z][0-9]*\s*/, '')
}
let clueLabelParse = parseClueLabel(clueLine)
if (clueLabelParse.error) {
parse.error = clueLabelParse.error
return parse
}
if (clueLabelParse.isFiller) {
parse.isFiller = true
return parse
}
if (clueLabelParse.dir && clueLabelParse.dir != dir) {
parse.error = 'Explicit dir ' + clueLabelParse.dir + ' does not match ' + dir + ' in clue: ' + clueLine
return parse
}
parse.clueLabel = clueLabelParse.clueLabel
parse.isNonNum = clueLabelParse.isNonNum
let clueIndex = dir + parse.clueLabel
if (parse.isNonNum) {
let nonNumIndex = dir + '#' + (nextNonNumId++)
if (!nonNumClueIndices[parse.clueLabel]) {
nonNumClueIndices[parse.clueLabel] = []
}
nonNumClueIndices[parse.clueLabel].push(nonNumIndex)
clueIndex = nonNumIndex
}
parse.clueIndex = clueIndex
clueLine = clueLine.substr(clueLabelParse.skip)
parse.children = []
while (clueLabelParse.hasChildren) {
clueLabelParse = parseClueLabel(clueLine)
if (clueLabelParse.error) {
parse.error = 'Error in linked clue number/label: ' + clueLabelParse.error
return parse
}
parse.children.push(clueLabelParse)
clueLine = clueLine.substr(clueLabelParse.skip)
}
let enumParse = parseEnum(clueLine)
parse.len = enumParse.len
parse.hyphenAfter = enumParse.hyphenAfter
parse.wordEndAfter = enumParse.wordEndAfter
parse.clue = clueLine.substr(0, enumParse.afterEnum).trim()
parse.anno = clueLine.substr(enumParse.afterEnum).trim()
return parse
}
// Parse across and down clues from their exolve sections previously
// identified by parseOverallDisplayMost().
function parseClueLists() {
// Parse across, down, nodir clues
for (let clueDirection of ['A', 'D', 'X']) {
let first, last
if (clueDirection == 'A') {
first = acrossFirstLine
last = acrossLastLine
} else if (clueDirection == 'D') {
first = downFirstLine
last = downLastLine
} else {
first = nodirFirstLine
last = nodirLastLine
}
if (first < 0 || last < first) {
continue
}
let prev = null
let filler = ''
for (let l = first; l <= last; l++) {
let clueLine = puzzleTextLines[l].trim();
if (clueLine == '') {
continue;
}
let clueParse = parseClue(clueDirection, clueLine)
if (clueParse.error) {
addError('Clue parsing error in: ' + clueLine + ': ' + clueParse.error);
return
}
if (clueParse.isFiller) {
filler = filler + clueLine + '\n'
continue
}
if (!clueParse.clueIndex) {
addError('Could not parse clue: ' + clueLine);
return
}
if (clues[clueParse.clueIndex] && clues[clueParse.clueIndex].clue) {
addError('Clue entry already exists for clue: ' + clueLine);
return
}
if (!clues[clueParse.clueIndex]) {
clues[clueParse.clueIndex] = {'cells': []}
}
clues[clueParse.clueIndex].clue = clueParse.clue
clues[clueParse.clueIndex].clueLabel = clueParse.clueLabel
clues[clueParse.clueIndex].isNonNum = clueParse.isNonNum
clues[clueParse.clueIndex].displayLabel = clueParse.clueLabel
clues[clueParse.clueIndex].clueDirection = clueDirection
clues[clueParse.clueIndex].fullDisplayLabel = clueParse.clueLabel
if (clueDirection != 'X' && clueParse.clueLabel) {
clues[clueParse.clueIndex].fullDisplayLabel =
clues[clueParse.clueIndex].fullDisplayLabel + clueDirection.toLowerCase()