forked from thejoshwolfe/snakefall
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMain.js
More file actions
6802 lines (6384 loc) · 289 KB
/
Copy pathMain.js
File metadata and controls
6802 lines (6384 loc) · 289 KB
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
function unreachable() { return new Error("unreachable"); }
if (typeof VERSION !== "undefined") {
document.getElementById("versionSpan").innerHTML =
'<a href="https://github.com/thejoshwolfe/snakefall/blob/' + VERSION.sha1 + '/README.md">' + VERSION.tag + '</a>';
}
$(document).ready(function () {
$(window).on("mousemove", function (e) {
$("#openEditorButton").css({ opacity: 1 });
clearTimeout(window.myTimeout);
window.myTimeout = setTimeout(function () {
$("#openEditorButton").css({ opacity: .2 });
}, 5000);
});
});
var sv = false;
var didResize = false;
var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");
var canvas3 = document.getElementById("canvas3");
var canvas4 = document.getElementById("canvas4");
var canvas5 = document.getElementById("canvas5");
var canvas6 = document.getElementById("canvas6");
var canvas7 = document.getElementById("canvas7");
var SPACE = "0".charCodeAt(0);
var WALL = "1".charCodeAt(0);
var SPIKE = "2".charCodeAt(0);
var FRUIT_v0 = "3".charCodeAt(0); //legacy
var EXIT = "4".charCodeAt(0);
var PORTAL = "5".charCodeAt(0);
var RAINBOW = "P".charCodeAt(0);
var TRELLIS = "p".charCodeAt(0);
var ONEWAYWALLU = "u".charCodeAt(0);
var ONEWAYWALLD = "d".charCodeAt(0);
var ONEWAYWALLL = "l".charCodeAt(0);
var ONEWAYWALLR = "r".charCodeAt(0);
var CLOSEDLIFT = "c".charCodeAt(0);
var OPENLIFT = "o".charCodeAt(0);
var CLOUD = "C".charCodeAt(0);
var BUBBLE = "b".charCodeAt(0);
var LAVA = "v".charCodeAt(0);
var WATER = "w".charCodeAt(0);
var validTileCodes = [SPACE, WALL, SPIKE, EXIT, PORTAL, RAINBOW, TRELLIS, ONEWAYWALLU, ONEWAYWALLD, ONEWAYWALLL, ONEWAYWALLR, CLOSEDLIFT, OPENLIFT, CLOUD, BUBBLE, LAVA, WATER];
var OWWCounter = 0;
// object types
var SNAKE = "s";
var BLOCK = "b";
var MIKE = "x";
var FRUIT = "f";
var POISONFRUIT = "p";
var newSpikeDeath = [];
var lowDeath = false;
var dieOnSplock = false;
var theseDyingLocations = [];
var infiniteDeath = false;
var checkResult = false;
var cr = false;
var cs = false;
var cs2 = false;
var dont = false;
var fruitLog = [];
var poisonFruitLog = [];
var postPortalSnakeOutline = [];
var portalConflicts = [];
var portalFailure = false;
var portalOutOfBounds = false;
var cycle = false;
var cycleId = -1;
var multiDiagrams = false;
var tileSize = 34;
var borderRadiusFactor = 3.4;
var borderRadius = tileSize / borderRadiusFactor;
var blockRadiusFactor = 5;
var blockRadius = tileSize / blockRadiusFactor;
var level;
var unmoveStuff = { undoStack: [], redoStack: [], spanId: "movesSpan", undoButtonId: "unmoveButton", redoButtonId: "removeButton" };
var uneditStuff = { undoStack: [], redoStack: [], spanId: "editsSpan", undoButtonId: "uneditButton", redoButtonId: "reeditButton" };
var paradoxes = [];
var enhanced = false;
var oldRowcols = [];
var animationsOn = true; //defaults
var defaultOn = true;
var replayAnimationsOn = false;
var blockFixOn = false;
function updateSwitches() {
var fitDefault = "";
if ((fitDefault = localStorage.getItem("cachedFitDefault")) !== null) {
if (fitDefault === "fitCanvas") document.getElementById("fitCanvasDefault").checked = true;
else if (fitDefault === "fitControls") document.getElementById("fitControlsDefault").checked = true;
}
if (localStorage.getItem("cachedAO") !== null) animationsOn = JSON.parse(localStorage.getItem("cachedAO"));
if (localStorage.getItem("cachedDO") !== null) {
defaultOn = JSON.parse(localStorage.getItem("cachedDO"));
document.getElementById("defaultSlider").checked = defaultOn;
}
if (localStorage.getItem("cachedRAO") !== null) {
replayAnimationsOn = JSON.parse(localStorage.getItem("cachedRAO"));
document.getElementById("replayAnimationSlider").checked = replayAnimationsOn;
}
if (defaultOn && persistentState.showEditor) animationsOn = false;
}
var cursor = 0;
var cursorOffset = 0;
var replayString = false;
var replayLength = 0;
var switchSnakesArray = [];
function loadLevel(newLevel) {
level = newLevel;
currentSerializedLevel = compressSerialization(stringifyLevel(newLevel));
var string = stringifyLevel(newLevel);
var levelString = string.substring(string.indexOf("?") + 1, string.indexOf("/")); //everything before objects
if (levelString.match(/[a-z]/i)) enhanced = true;
// don't know why this was defaulting to true
persistentState.highlightFruits = false;
var snakes = getSnakes();
var fruits = getObjectsOfType(FRUIT);
var poisonFruits = getObjectsOfType(POISONFRUIT);
fruits.sort(compareLocations);
for (var i = 0; i < fruits.length; i++) {
fruitLog.push([fruits[i], i + 1]);
}
poisonFruits.sort(compareLocations);
for (var i = 0; i < poisonFruits.length; i++) {
poisonFruitLog.push([poisonFruits[i], i + 1]);
}
if (snakes.length === 0) document.getElementById("highlightSnakesButton").disabled = true;
else document.getElementById("highlightSnakesButton").disabled = false;
if (fruits.length === 0) document.getElementById("highlightFruitsButton").disabled = true;
else document.getElementById("highlightFruitsButton").disabled = false;
if (poisonFruits.length === 0) document.getElementById("highlightPoisonFruitsButton").disabled = true;
else document.getElementById("highlightPoisonFruitsButton").disabled = false;
activateAnySnakePlease();
unmoveStuff.undoStack = [];
unmoveStuff.redoStack = [];
undoStuffChanged(unmoveStuff);
uneditStuff.undoStack = [];
uneditStuff.redoStack = [];
undoStuffChanged(uneditStuff);
blockRenderCache = {};
mikeRenderCache = {};
// alert(document.getElementById("editorPane").style.offsetHeight);
if (!persistentState.showEditor) document.getElementById("ghostEditorPane").style.display = "none";
// else openEditorButtonLocation(false, localStorage.getItem("editorLocation"));
// document.getElementById("ghostEditorPane").style.height = document.getElementById("editorPane").style.offsetHeight;
// document.getElementById("ghostEditorPane").style.height = tileSize * level.height; // doesn't add up
recalculateBorderRadius();
recalculateBlockRadius();
updateSwitches();
drawStaticCanvases(level);
render();
if (sv) {
fitCanvas(2);
toggleTheme(0);
render();
}
else {
var fitDefault = localStorage.getItem("cachedFitDefault") !== null ? localStorage.getItem("cachedFitDefault") : fitDefault = "";
if (fitDefault == "" || fitDefault === "fitControls") { fitCanvas(1); fitDefault = "fitControls" }
else { fitCanvas(0); fitDefault === "fitCanvas" }
localStorage.setItem("cachedFitDefault", fitDefault);
}
}
function drawStaticCanvases(level) {
resizeCanvasContainer();
[canvas1, canvas3, canvas5, canvas7].forEach(function (canvas) {
canvas.width = tileSize * level.width;
canvas.height = tileSize * level.height;
});
var context = canvas1.getContext("2d");
populateThemeVars();
context.fillStyle = "white";
drawBackground(context, canvas1);
context = canvas3.getContext("2d");
var rng = new Math.seedrandom("b");
for (var r = 0; r < level.height; r++) {
for (var c = 0; c < level.width; c++) {
var location = getLocation(level, r, c);
var tileCode = level.map[location];
if (tileCode === SPIKE || tileCode === RAINBOW || tileCode === ONEWAYWALLU || tileCode === ONEWAYWALLD) drawTile(context, tileCode, r, c, level, location, rng, true, true);
}
}
context = canvas5.getContext("2d");
for (var r = 0; r < level.height; r++) {
for (var c = 0; c < level.width; c++) {
var location = getLocation(level, r, c);
var tileCode = level.map[location];
if (tileCode === WATER || tileCode === LAVA) drawTile(context, tileCode, r, c, level, rng, location, false);
}
}
for (var r = 0; r < level.height; r++) {
for (var c = 0; c < level.width; c++) {
var location = getLocation(level, r, c);
var tileCode = level.map[location];
if (tileCode === WALL) drawTile(context, tileCode, r, c, level, location, rng, true, true);
}
}
for (var r = 0; r < level.height; r++) {
for (var c = 0; c < level.width; c++) {
var location = getLocation(level, r, c);
var tileCode = level.map[location];
if (tileCode === WALL) drawTile(context, tileCode, r, c, level, location, rng, false, true);
}
}
for (var r = 0; r < level.height; r++) {
for (var c = 0; c < level.width; c++) {
var location = getLocation(level, r, c);
var tileCode = level.map[location];
if (tileCode === TRELLIS) drawTile(context, tileCode, r, c, level, location, rng, false, true);
}
}
}
var magicNumber_v0 = "3tFRIoTU";
var magicNumber = "HyRr4JK1";
var exampleLevel = magicNumber_v0 + "&" +
"17&31" +
"?" +
"0000000000000000000000000000000" +
"0000000000000000000000000000000" +
"0000000000000000000000000000000" +
"0000000000000000000000000000000" +
"0000000000000000000000000000000" +
"0000000000000000000000000000000" +
"0000000000000000000040000000000" +
"0000000000000110000000000000000" +
"0000000000000111100000000000000" +
"0000000000000011000000000000000" +
"0000000000000010000010000000000" +
"0000000000000010100011000000000" +
"0000001111111000110000000110000" +
"0000011111111111111111111110000" +
"0000011111111101111111111100000" +
"0000001111111100111111111100000" +
"0000001111111000111111111100000" +
"/" +
"s0 ?351&350&349/" +
"f0 ?328/" +
"f1 ?366/";
var testLevel_v0 = "3tFRIoTU&5&5?0005*00300024005*001000/b0?7&6&15&23/s3?18/s0?1&0&5/s1?2/s4?10/s2?17/b2?9/b3?14/b4?19/b1?4&20/b5?24/";
var testLevel_v0_converted = "HyRr4JK1&5&5?0005*4024005*001000/b0?7&6&15&23/s3?18/s0?1&0&5/s1?2/s4?10/s2?17/b2?9/b3?14/b4?19/b1?4&20/b5?24/f0?8/";
function parseLevel(string) {
// magic number
var plCursor = 0;
skipWhitespace();
var versionTag = string.substr(plCursor, magicNumber.length);
switch (versionTag) {
case magicNumber_v0:
case magicNumber: break;
default: throw new Error("not a snakefall level");
}
plCursor += magicNumber.length;
consumeKeyword("&");
var level = {
height: -1,
width: -1,
map: [],
objects: [],
};
// height, width
level.height = readInt();
consumeKeyword("&");
level.width = readInt();
// map
var mapData = readRun();
mapData = decompressSerialization(mapData);
if (level.height * level.width !== mapData.length) throw parserError("height, width, and map.length do not jive");
var upconvertedObjects = [];
var fruitCount = 0;
var tileCounter = 0;
for (var i = 0; i < mapData.length; i++) {
var tileCode = mapData[i].charCodeAt(0);
if (tileCode === FRUIT_v0 && versionTag === magicNumber_v0) {
// fruit used to be a tile code. now it's an object.
upconvertedObjects.push({
type: FRUIT,
id: fruitCount++,
dead: false, // unused
locations: [i],
splocks: []
});
tileCode = SPACE;
}
if (validTileCodes.indexOf(tileCode) === -1) throw parserError("invalid tilecode: " + JSON.stringify(mapData[i]));
if (tileCode === RAINBOW || tileCode === TRELLIS || tileCode === ONEWAYWALLU || tileCode === ONEWAYWALLD || tileCode === ONEWAYWALLL || tileCode === ONEWAYWALLR || tileCode === CLOSEDLIFT || tileCode === OPENLIFT || tileCode === CLOUD || tileCode === BUBBLE || tileCode === LAVA || tileCode === WATER) tileCounter++;
level.map.push(tileCode);
}
// objects
skipWhitespace();
while (plCursor < string.length) {
var object = {
type: "?",
id: -1,
dead: false,
locations: [],
splocks: []
};
// type
object.type = string[plCursor];
var locationsLimit;
if (object.type === SNAKE || object.type === BLOCK || object.type === MIKE) locationsLimit = -1;
else if (object.type === FRUIT || object.type === POISONFRUIT) locationsLimit = 1;
else throw parserError("expected object type code");
plCursor += 1;
// id
object.id = readInt();
// locations
var locationsData = readRun();
var locationStrings = locationsData.split("&");
if (locationStrings.length === 0) throw parserError("locations must be non-empty");
if (locationsLimit !== -1 && locationStrings.length > locationsLimit) throw parserError("too many locations");
locationStrings.forEach(function (locationString) {
var location = parseInt(locationString);
if (!(0 <= location && location < level.map.length)) throw parserError("location out of bounds: " + JSON.stringify(locationString));
object.locations.push(location);
});
// splocks
if (object.type === BLOCK && string.substring(plCursor, plCursor + 1) === "?") {
var splockData = readRun();
var splockStrings = splockData.split("&");
splockStrings.forEach(function (splockString) {
var location = parseInt(splockString);
if (!(0 <= location && location < level.map.length)) throw parserError("splock out of bounds: " + JSON.stringify(splockString));
object.splocks.push(location);
});
}
level.objects.push(object);
skipWhitespace();
}
//describe level type
if (enhanced) {
document.getElementById("levelType").innerHTML = "Enhanced Level";
document.getElementById("levelTypeSpan").innerHTML = "contains new user-created elements";
document.getElementById("additions").style.display = "none";
if (persistentState.showEditor && tileCounter === 0) {
document.getElementById("additions").innerHTML = "all initial enhanced elements have been removed but the level is not saved";
document.getElementById("additions").style.display = "block";
}
}
else {
document.getElementById("levelType").innerHTML = "Standard Level";
document.getElementById("levelTypeSpan").innerHTML = "contains only original Snakebird elements";
if (persistentState.showEditor && tileCounter > 0) {
document.getElementById("additions").innerHTML = "enhanced elements have been added to this level but the level is not saved";
document.getElementById("additions").style.display = "block";
}
else document.getElementById("additions").style.display = "none";
}
for (var i = 0; i < upconvertedObjects.length; i++) {
level.objects.push(upconvertedObjects[i]);
}
return level;
function skipWhitespace() {
while (" \n\t\r".indexOf(string[plCursor]) !== -1) {
plCursor += 1;
}
}
function consumeKeyword(keyword) {
skipWhitespace();
if (string.indexOf(keyword, plCursor) !== plCursor) throw parserError("expected " + JSON.stringify(keyword));
plCursor += 1;
}
function readInt() {
skipWhitespace();
for (var i = plCursor; i < string.length; i++) {
if ("0123456789".indexOf(string[i]) === -1) break;
}
var substring = string.substring(plCursor, i);
if (substring.length === 0) throw parserError("expected int");
plCursor = i;
return parseInt(substring, 10);
}
function readRun() {
consumeKeyword("?");
var endIndex = string.indexOf("/", plCursor);
var substring = string.substring(plCursor, endIndex);
plCursor = endIndex + 1;
return substring;
}
function parserError(message) {
return new Error("parse error at position " + plCursor + ": " + message);
}
}
function serializeTileCode(tileCode) {
return String.fromCharCode(tileCode);
}
function stringifyLevel(level) {
var output = magicNumber + "&";
output += level.height + "&" + level.width + "\n";
output += "?\n";
for (var r = 0; r < level.height; r++) {
output += " " + level.map.slice(r * level.width, (r + 1) * level.width).map(serializeTileCode).join("") + "\n";
}
output += "/\n";
output += serializeObjects(level.objects);
// sanity check
// var shouldBeTheSame = parseLevel(output);
// if (!deepEquals(level, shouldBeTheSame)) throw asdf; // serialization/deserialization is broken
return output;
}
function serializeObjects(objects) {
var output = "";
for (var i = 0; i < objects.length; i++) {
var object = objects[i];
output += object.type + object.id + " ";
output += "?" + object.locations.join("&");
if (object.splocks.length != 0) output += "/?" + object.splocks.join("&");
output += "/\n";
}
return output;
}
function serializeObjectState(object) {
if (object == null) return [0, [], []];
return [object.dead, copyArray(object.locations), copyArray(object.splocks)];
}
var base66 = "----0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
function compressSerialization(string) {
string = string.replace(/\s+/g, "");
// run-length encode several 0's in a row, etc.
// 2000000000000003 -> 2*A03 ("A" is 14 in base66 defined above)
var result = "";
var runStart = 0;
for (var i = 1; i < string.length + 1; i++) {
var runLength = i - runStart;
if (string[i] === string[runStart] && runLength < base66.length - 1) continue;
// end of run
if (runLength >= 4) {
// compress
result += "*" + base66[runLength] + string[runStart];
} else {
// literal
result += string.substring(runStart, i);
}
runStart = i;
}
return result;
}
function decompressSerialization(string) {
string = string.replace(/\s+/g, "");
var result = "";
for (var i = 0; i < string.length; i++) {
if (string[i] === "*") {
i += 1;
var runLength = base66.indexOf(string[i]);
i += 1;
var char = string[i];
for (var j = 0; j < runLength; j++) {
result += char;
}
} else {
result += string[i];
}
}
return result;
}
var replayMagicNumber = "nmGTi8PB";
function stringifyReplay() {
var output = replayMagicNumber + "&";
// only specify the snake id in an input if it's different from the previous.
// the first snake index is 0 to optimize for the single-snake case.
var currentSnakeId = 0;
for (var i = 0; i < unmoveStuff.undoStack.length; i++) {
var firstChange = unmoveStuff.undoStack[i][0];
if (firstChange[0] !== "i") throw unreachable();
var snakeId = firstChange[1];
var dr = firstChange[2];
var dc = firstChange[3];
var directionCode;
if (dr === -1 && dc === 0) directionCode = "u";
else if (dr === 0 && dc === -1) directionCode = "l";
else if (dr === 1 && dc === 0) directionCode = "d";
else if (dr === 0 && dc === 1) directionCode = "r";
else throw unreachable();
if (snakeId !== currentSnakeId) {
output += snakeId; // int to string
currentSnakeId = snakeId;
}
output += directionCode;
}
return output;
}
function advance() {
var expectedPrefix = replayMagicNumber + "&";
if (cursor <= expectedPrefix.length) {
cursor = expectedPrefix.length;
activeSnakeId = 0;
}
var snakeIdStr = "";
var c = replayString.charAt(cursor);
cursor++;
if ('0' <= c && c <= '9') {
//check if number has up to 3 digits (999)
var d = replayString.charAt(cursor);
var e = replayString.charAt(cursor + 1);
if ('0' <= d && d <= '9') {
c = c + d;
cursor++;
cursorOffset++;
if ('0' <= e && e <= '9') {
c = c + e;
cursor++;
cursorOffset++;
}
}
//add cursor location of snake switch (location of last digit in multi-digit numbers)
if (!switchSnakesArray.includes(cursor)) switchSnakesArray.push(cursor);
snakeIdStr += c;
if (cursor >= replayString.length) throw new Error("replay string has unexpected end of input");
c = replayString.charAt(cursor);
cursor++;
}
if (snakeIdStr.length > 0) {
activeSnakeId = parseInt(snakeIdStr);
cursorOffset++;
// don't just validate when switching snakes, but on every move.
}
// doing a move.
if (!getSnakes().some(function (snake) {
return snake.id === activeSnakeId;
})) {
throw new Error("invalid snake id: " + activeSnakeId);
}
switch (c) {
case 'l': move(0, -1, replayAnimationsOn); break;
case 'u': move(-1, 0, replayAnimationsOn); break;
case 'r': move(0, 1, replayAnimationsOn); break;
case 'd': move(1, 0, replayAnimationsOn); break;
default: throw new Error("replay string has invalid direction: " + c);
}
var pre = cursor - expectedPrefix.length - cursorOffset;
var post = replayLength - cursor + expectedPrefix.length + cursorOffset;
var movesText = pre + "\xa0\xa0✾\xa0\xa0" + post;
document.getElementById("movesSpan").textContent = movesText;
}
function parseAndLoadReplay(string) {
replayString = decompressSerialization(string);
var expectedPrefix = replayMagicNumber + "&";
if (replayString.substring(0, expectedPrefix.length) !== expectedPrefix) throw new Error("unrecognized replay string");
cursor = expectedPrefix.length;
if (!switchSnakesArray.includes(cursor)) switchSnakesArray.push(cursor);
replayLength = 0;
while (cursor < replayString.length) {
var c = replayString.charAt(cursor);
switch (c) {
case 'l':
case 'u':
case 'r':
case 'd': replayLength++; break;
}
cursor++;
}
var movesText = "0\xa0\xa0✾\xa0\xa0" + replayLength;
document.getElementById("movesSpan").textContent = movesText;
cursor = expectedPrefix.length;
// the starting snakeid is 0, which may not exist, but we only validate it when doing a move.
// now that the replay was executed successfully, undo it all so that it's available in the redo buffer.
// reset(unmoveStuff);
// document.getElementById("removeButton").classList.add("click-me");
}
var currentSerializedLevel;
function saveLevel() {
if (isDead()) return alert("Can't save while a snake is dead");
var serializedLevel = compressSerialization(stringifyLevel(level));
currentSerializedLevel = serializedLevel;
var hash = "#level=" + serializedLevel;
expectHash = hash;
location.hash = hash;
// This marks a starting point for solving the level.
unmoveStuff.undoStack = [];
unmoveStuff.redoStack = [];
editorHasBeenTouched = false;
undoStuffChanged(unmoveStuff);
location.reload();
}
function saveReplay() {
if (dirtyState === EDITOR_DIRTY) return alert("Can't save a replay with unsaved editor changes.");
// preserve the level in the url bar.
var hash = "#level=" + currentSerializedLevel;
if (dirtyState === REPLAY_DIRTY) {
// there is a replay to save
hash += "#replay=" + compressSerialization(stringifyReplay());
}
expectHash = hash;
location.hash = hash;
}
function deepEquals(a, b) {
if (a == null) return b == null;
if (typeof a === "string" || typeof a === "number" || typeof a === "boolean") return a === b;
if (Array.isArray(a)) {
if (!Array.isArray(b)) return false;
if (a.length !== b.length) return false;
for (var i = 0; i < a.length; i++) {
if (!deepEquals(a[i], b[i])) return false;
}
return true;
}
// must be objects
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) return false;
aKeys.sort();
bKeys.sort();
if (!deepEquals(aKeys, bKeys)) return false;
for (var i = 0; i < aKeys.length; i++) {
if (!deepEquals(a[aKeys[i]], b[bKeys[i]])) return false;
}
return true;
}
function getLocation(level, r, c) {
if (!isInBounds(level, r, c)) throw unreachable();
return r * level.width + c;
}
function getRowcol(level, location) {
if (location < 0 || location >= level.width * level.height) throw unreachable();
var r = Math.floor(location / level.width);
var c = location % level.width;
return { r: r, c: c };
}
function isInBounds(level, r, c) {
if (c < 0 || c >= level.width) return false;;
if (r < 0 || r >= level.height) return false;;
return true;
}
function offsetLocation(location, dr, dc) {
var rowcol = getRowcol(level, location);
return getLocation(level, rowcol.r + dr, rowcol.c + dc);
}
var SHIFT = 1;
var CTRL = 2;
var CMD = 3;
var ALT = 4;
document.addEventListener("keydown", function (event) {
var modifierMask = (
(event.shiftKey ? SHIFT : 0) |
(event.ctrlKey ? CTRL : 0) |
(event.metaKey ? CMD : 0) |
(event.altKey ? ALT : 0)
);
if (!sv) {
switch (event.keyCode) {
case 37: // left
if (modifierMask === 0) { replayString = false; move(0, -1); break; }
return;
case 38: // up
if (modifierMask === 0) { replayString = false; move(-1, 0); break; }
return;
case 39: // right
if (modifierMask === 0) { replayString = false; move(0, 1); break; }
return;
case 40: // down
if (modifierMask === 0) { replayString = false; move(1, 0); break; }
return;
case 8: // backspace
if (modifierMask === 0) { undo(unmoveStuff); break; }
if (modifierMask === SHIFT) { redo(unmoveStuff); break; }
return;
case 48: //zero
fitCanvas(1);
return;
case 187: //equals and plus
changeCanvasSize(2);
return;
case 189: //minus
changeCanvasSize(-2);
return;
case "Q".charCodeAt(0):
if (modifierMask === 0) { undo(unmoveStuff); break; }
if (modifierMask === SHIFT) { redo(unmoveStuff); break; }
return;
case "Z".charCodeAt(0):
if (modifierMask === 0) { undo(unmoveStuff); break; }
if (modifierMask === SHIFT && !replayString) { redo(unmoveStuff); break; }
if (modifierMask === SHIFT && replayString) { advance(); break; }
if (persistentState.showEditor && modifierMask === (CTRL | CMD)) { undo(uneditStuff); break; }
if (persistentState.showEditor && modifierMask === (CTRL | CMD | SHIFT)) { redo(uneditStuff); break; }
return;
case "Y".charCodeAt(0):
if (modifierMask === 0 && !replayString) { redo(unmoveStuff); break; }
if (modifierMask === 0 && replayString) { advance(); break; }
if (persistentState.showEditor && modifierMask === (CTRL | CMD)) { redo(uneditStuff); break; }
return;
case "R".charCodeAt(0):
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode(RAINBOW); break; }
if (persistentState.showEditor && modifierMask === CTRL) { setPaintBrushTileCode("resize"); break; }
if (modifierMask === 0) { reset(unmoveStuff); break; }
if (modifierMask === SHIFT) { unreset(unmoveStuff); break; }
return;
case 220: // backslash
if (modifierMask === 0) {
if (dirtyState != EDITOR_DIRTY) { openEditorButton(); break; }
else {
if (confirm("Hide editor and cancel changes without saving?\n\nNote: To avoid seeing this prompt in the future, save changes before closing the editor")) {
openEditorButton();
location.reload();
}
break;
}
}
return;
case "A".charCodeAt(0):
if (!persistentState.showEditor && modifierMask === 0) { replayString = false; move(0, -1); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode("select"); break; }
if (persistentState.showEditor && modifierMask === (CTRL | CMD)) { selectAll(); break; }
return;
case "E".charCodeAt(0):
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(SPACE); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode(EXIT); break; }
return;
case 46: // delete
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(SPACE); break; }
return;
case "W".charCodeAt(0):
if (!persistentState.showEditor && modifierMask === 0) { replayString = false; move(-1, 0); break; }
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(WALL); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode(WATER); break; }
return;
case "S".charCodeAt(0):
if (!persistentState.showEditor && modifierMask === 0) { replayString = false; move(1, 0); break; }
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(SPIKE); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode(SNAKE); break; }
if (persistentState.showEditor && modifierMask === (CTRL | CMD)) { saveLevel(); break; }
if (!persistentState.showEditor && modifierMask === (CTRL | CMD)) { saveReplay(); break; }
if (modifierMask === (CTRL | SHIFT)) { saveReplay(); break; }
return;
case "X".charCodeAt(0):
if (persistentState.showEditor && modifierMask === (CTRL | CMD)) { cutSelection(); break; }
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(CLOSEDLIFT); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode(OPENLIFT); break; }
return;
case "F".charCodeAt(0):
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(FRUIT); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode(POISONFRUIT); break; }
return;
case "D".charCodeAt(0):
if (!persistentState.showEditor && modifierMask === 0) { replayString = false; move(0, 1); break; }
return;
case "B".charCodeAt(0):
if (persistentState.showEditor && modifierMask === 0 && !splockIsActive) { setPaintBrushTileCode(BLOCK); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode(BUBBLE); break; }
if (persistentState.showEditor && modifierMask === 0 && paintBrushTileCode === BLOCK && blockIsInFocus && splockIsActive) { toggleSplockButton(); break; }
return;
case "P".charCodeAt(0):
if (!persistentState.showEditor && modifierMask === 0) { replayString = false; move(-1, 0); break; }
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(PORTAL); break; }
return;
case "U".charCodeAt(0):
if (!persistentState.showEditor && modifierMask === 0) { replayString = false; move(-1, 0); break; }
return;
case "L".charCodeAt(0):
if (!persistentState.showEditor && modifierMask === 0) { replayString = false; move(-1, 0); break; }
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(LAVA); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { setPaintBrushTileCode(WATER); break; }
return;
case "G".charCodeAt(0):
if (modifierMask === 0) { toggleGrid(); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { toggleGravity(); break; }
return;
case "C".charCodeAt(0):
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(CLOUD); break; }
if (persistentState.showEditor && modifierMask === SHIFT) { toggleCollision(); break; }
if (persistentState.showEditor && modifierMask === (CTRL | CMD)) { copySelection(); break; }
return;
case "V".charCodeAt(0):
if (persistentState.showEditor && modifierMask === (CTRL | CMD)) { setPaintBrushTileCode("paste"); break; }
return;
case "H".charCodeAt(0):
if (persistentState.showEditor && modifierMask === 0) { toggleHotkeys(); break; }
return;
case "T".charCodeAt(0):
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(TRELLIS); break; }
if ((!persistentState.showEditor) || (persistentState.showEditor && modifierMask === SHIFT)) { toggleTheme(); break; }
return;
case "O".charCodeAt(0):
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode([ONEWAYWALLU, ONEWAYWALLD, ONEWAYWALLL, ONEWAYWALLR]); break; }
return;
case "M".charCodeAt(0):
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(MIKE); break; }
return;
case 190:
openEditorButtonLocation(true);
return;
case 53: // 5
if (modifierMask === 0) { highlightSnakes(); break; }
case 54: // 6
if (modifierMask === 0) { highlightFruits(); break; }
case 55: // 7
if (modifierMask === 0) { highlightPoisonFruits(); break; }
case 56: // 8
if (modifierMask === 0) { clearHighlights(); break; }
case 57: // 9
if (modifierMask === 0) { fitCanvas(0); break; }
case 191:
if (modifierMask === 0) { if (multiDiagrams) { cycle = true; cycleId++; render(); } break; }
case 13:
if (modifierMask === 0 && !replayString) { redo(unmoveStuff); break; }
if (modifierMask === 0 && replayString) { advance(); break; }
case 32: // spacebar
if (persistentState.showEditor && modifierMask === 0 && paintBrushTileCode === BLOCK && blockIsInFocus) { toggleSplockButton(); break; }
if (modifierMask === 0) { switchSnakes(1); break; }
if (modifierMask === SHIFT) { switchSnakes(-1); break; }
return;
case 9: // tab
if (modifierMask === 0) { switchSnakes(1); break; }
if (modifierMask === SHIFT) { switchSnakes(-1); break; }
return;
case "1".charCodeAt(0):
case "2".charCodeAt(0):
case "3".charCodeAt(0):
case "4".charCodeAt(0):
var index = event.keyCode - "1".charCodeAt(0);
var delta;
if (modifierMask === 0) {
delta = 1;
} else if (modifierMask === SHIFT) {
delta = -1;
} else return;
if (isAlive()) {
(function () {
var snakes = findSnakesOfColor(index);
if (snakes.length === 0) return;
for (var i = 0; i < snakes.length; i++) {
if (snakes[i].id === activeSnakeId) {
activeSnakeId = snakes[(i + delta + snakes.length) % snakes.length].id;
return;
}
}
activeSnakeId = snakes[0].id;
})();
}
break;
case 27: // escape
if (persistentState.showEditor && modifierMask === 0) { setPaintBrushTileCode(null); break; }
return;
default: return;
}
}
else if (!cs2) advanceAll();
event.preventDefault();
render();
});
function changeCanvasSize(delta) {
if (delta !== 34) tileSize += delta;
else tileSize = 34;
recalculateBorderRadius();
recalculateBlockRadius();
textStyle.fontSize = tileSize * 5;
blockRenderCache = {};
mikeRenderCache = {};
drawStaticCanvases(getLevel());
resizeCanvasContainer();
render();
}
document.getElementById("switchSnakesButton").addEventListener("click", function () {
switchSnakes(1);
render();
});
function switchSnakes(delta) {
if (!isAlive()) return;
var snakes = getSnakes();
snakes.sort(compareId);
for (var i = 0; i < snakes.length; i++) {
if (snakes[i].id === activeSnakeId) {
activeSnakeId = snakes[(i + delta + snakes.length) % snakes.length].id;
return;
}
}
activeSnakeId = snakes[0].id;
}
document.getElementById("arrowUp").addEventListener("click", function () {
replayString = false;
move(-1, 0);
return;
});
document.getElementById("arrowDown").addEventListener("click", function () {
replayString = false;
move(1, 0);
return;
});
document.getElementById("arrowLeft").addEventListener("click", function () {
replayString = false;
move(0, -1);
return;
});
document.getElementById("arrowRight").addEventListener("click", function () {
replayString = false;
move(0, 1);
return;
});
document.getElementById("minus").addEventListener("click", function () {
changeCanvasSize(-2);
return;
});
document.getElementById("plus").addEventListener("click", function () {
changeCanvasSize(2);
return;
});
document.getElementById("fitControls").addEventListener("click", function () {
fitCanvas(1);
return;
});
document.getElementById("fitCanvas").addEventListener("click", function () {
fitCanvas(0);
return;
});
document.getElementById("fitControlsDefault").addEventListener("click", function () {
document.getElementById("fitCanvasDefault").checked = false;
localStorage.setItem("cachedFitDefault", "fitControls");
});
document.getElementById("fitCanvasDefault").addEventListener("click", function () {
document.getElementById("fitControlsDefault").checked = false;
localStorage.setItem("cachedFitDefault", "fitCanvas");
});
document.getElementById("paintSplockButton").addEventListener("click", function () {
toggleSplockButton();
});
document.getElementById("highlightSnakesButton").addEventListener("click", function () {
highlightSnakes();
});
document.getElementById("highlightFruitsButton").addEventListener("click", function () {
highlightFruits();
});
document.getElementById("highlightPoisonFruitsButton").addEventListener("click", function () {
highlightPoisonFruits();
});
document.getElementById("clearHighlightsButton").addEventListener("click", function () {
clearHighlights();
});
document.getElementById("showGridButton").addEventListener("click", function () {
toggleGrid();
});
document.getElementById("openEditorButton").addEventListener("click", function () {
openEditorButton();
});
document.getElementById("closeEditorButton").addEventListener("click", function () {
openEditorButton();
});
document.getElementById("hideHotkeyButton").addEventListener("click", function () {
toggleHotkeys();
});