-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2048units.html
1080 lines (1028 loc) · 33.6 KB
/
2048units.html
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
<!DOCTYPE html>
<html style="width: 99%;height: 99%;">
<head>
<meta name="viewport" content="width=device-width,height=window-height, initial-scale=1.0">
<title>2048 Units</title>
</head>
<style type="text/css">
body {
background-color: #202020;
width: 95%;
height: 95%;
color-scheme: dark;
}
.area {
/* width: 95vw;
aspect-ratio: 1;
min-width: 20em;
max-width: 95vh; */
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
.basegrid {
--columns: 4;
--rows: 4;
/*
--fit-view-size: min( 95vh ,95vw );
width: calc( var(--fit-view-size) );
height: calc( var(--fit-view-size) );
font-size: calc( var(--fit-view-size) * 0.165 / max(var(--rows), var(--columns)));
*/
--max-width: 95vw;
--max-height: 95vh;
width: calc( var(--fit-view-size) * (var(--columns) + 0.1) );
height: calc( var(--fit-view-size) * (var(--rows) + 0.1) );
--fit-view-size: min( var(--max-height) / ( var(--rows) + 0.1 ) , var(--max-width) / ( var(--columns) + 0.1 ));
border-radius: calc( var(--fit-view-size) * 0.1 );
background-color: hsl(0, 0%, 27%);
font-size: calc( var(--fit-view-size) / 6 );
}
.overgrid{
position: absolute;
}
.cell {
border-radius: 5%;
border-style: none;
text-align: center;
position: absolute;
--margin: 0.5em;
--size: 4.5em;
--x: 0;
--y: 0;
margin: var(--margin);
width: var(--size);
height: var(--size);
left: calc(var(--x) * (var(--size) + var(--margin)));
top: calc(var(--y) * (var(--size) + var(--margin)));
offset-anchor: center;
font-size: larger;
}
.fg {
background-color: #808080;
z-index: 3;
transition: left 0.2s, top 0.2s ease-in;
-webkit-transition: left 0.2s, top 0.2s ease-in;
animation: spawn 0.3s ease-in;
}
.bg {
background-color: #303030;
z-index: 1;
}
.immovable-cell{
transition: none;
-webkit-transition: none;
animation: none;
}
.info_cell {
background-color: #808080;
border-radius: 5%;
border-style: none;
text-align: center;
position: relative;
float: left;
margin: 0.3em;
width: 4.5em;
height: 4.5em;
z-index: 3;
offset-anchor: center;
font-size: x-small;
text-align: center;
}
.cellLabel {
font-family: sans-serif;
text-align: center;
margin: 0px;
position: absolute;
font-size: 1.5em;
top: 50%;
left: 50%;
transform: translate(-50%, -60%);
}
.cellCornerMark {
font-family: sans-serif;
text-align: center;
margin: 0px;
position: absolute;
font-size: 1em;
top: 90%;
left: 90%;
transform: translate(-100%, -100%);
}
.largeFont {
font-size: 1.5em;
}
.plate {
background-color: #303030;
border-radius: 0.7em;
border-style: none;
z-index: 1;
margin: 0.5em;
}
.circle {
background: #808080;
border-radius: 50%;
height: 0.5em;
width: 0.5em;
position: absolute;
}
.toast {
background-color: #404040;
box-shadow: 0 0 1em 0 #000000;
position: fixed;
right: 1em;
bottom: 1em;
border-radius: 0.7em;
border-style: none;
z-index: 1;
margin: 0.5em;
padding: 1em;
opacity: 0%;
z-index: 99;
transition: 0.3s ease-in;
max-width: calc(100vw - 5em);
}
textarea {
font-family: sans-serif;
background-color: #202020;
color: #ffffff;
border-radius: 0.5em;
margin: 0.3em;
border-width: 0;
}
div {
font-family: sans-serif;
color: #ffffff;
}
p {
text-align: center;
margin: 0.2em;
width: 100%;
}
button {
color: #ffffff;
background-color: #606060;
margin: 0.2em;
border-radius: 0.5em;
border-width: 0;
padding: 0.5em;
}
button:hover {
background-color: #808080;
}
button:active {
background-color: #202020;
}
.flex1 {
display: -webkit-flex;
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.flex2 {
display: -webkit-flex;
display: flex;
flex-direction: row;
}
.flex-col {
display: -webkit-flex;
display: flex;
flex-direction: column;
}
@keyframes spawn {
0% {
scale: 110%;
}
100% {
scale: 100%;
}
}
</style>
<body>
<div class='flex1'>
<div class="info" id="info_header" style="flex:2;float:left;order:0;">
<div class="flex-col">
<div style="float: left;">
<p style="font-size: xxx-large;margin: 0;">2048 Units</p>
</div>
<div class="plate" style="float: left;padding: 0.5em;">
<div class="flex2">
<div style="float: left;margin: 0.2em;flex:2">
<p style="text-align: center;">SCORE</p>
<p id="score" style="text-align: center;"></p>
</div>
<div style="float: left;margin: 0.2em;flex:2">
<p style="text-align: center;">COMPLEXITY</p>
<p id="complexity" style="text-align: center;"></p>
</div>
<button id="buttonUndo" onclick="undo()" style="flex:1">UNDO</button>
</div>
</div>
</div>
</div>
<div class="area" style="order:1;">
<div id="basegrid" class="grid basegrid">
<div id="bggrid" class="grid overgrid">
</div>
<div id="gamegrid" class="grid overgrid">
</div>
</div>
<div id="touchArea" class="overgrid" style="z-index: 100;
width: 100%;
height: 100%;">
</div>
</div>
<div id="otherinfo" class="flex-col" style="flex:2;float: left;max-height: 98%;order:3;">
<div class="plate" style="float: inline-start;padding: 0.3em;">
<p>Discovered Units:</p>
<div id="discoveredUnits" style="float: inline-start;height: auto;">
</div>
</div>
<div class="plate" style="float:inline-start;">
<p>Save & Load:</p>
<div class="flex2">
<button onclick="exportState()" style="flex: 1;">
Export
</button>
<button onclick="importState()" style="flex: 1;">
Import
</button>
</div>
<form>
<textarea id="leveldata" style="flex:1">
</textarea>
</form>
<div>
<p>The game saves state automatically on quit.</p>
<p>However undo history isn't saved.</p>
</div>
</div>
<div class="plate">
Grid size: <input id="gridWidthSet" type="number" name="Columns" min="3" max="16"
value="4" size="3">×
<input id="gridHeightSet" type="number" name="Rows" min="3" max="16"
value="4" size="3">
<button onclick="newGame()" style="flex: 1;">
New Game
</button>
</div>
<div class="plate" style="float:inline-start">
<p>A game about physical units.</p>
<a href="https://github.com/Blue-Beaker/2048-units">
<p>Source Code</p>
</a>
</div>
</div>
</div>
<div class="toast" id="toast">
TOAST INFO
</div>
</body>
<script>
"use strict";
const DIR_UP = 0
const DIR_RIGHT = 1
const DIR_DOWN = 2
const DIR_LEFT = 3
const gamegrid = document.getElementById("gamegrid")
const bggrid = document.getElementById("bggrid")
const discoveredUnitsElement = document.getElementById("discoveredUnits")
const GRID_WIDTH_SETTER = document.getElementById("gridWidthSet")
const GRID_HEIGHT_SETTER = document.getElementById("gridHeightSet")
var WIDTH = 4
var HEIGHT = 4
var CELLS_PER_ROUND = 1 //Number of cells spawned after every move. Turn this to 0 for puzzle mode
var debug = false
//Ingame Variables
var undos = []
var cells = []
var gameState = {
score: 0,
unlockedUnits: ["m1"],
discoveredUnits: [],
}
function resetVariables() {
cells = [],
gameState = {
score: 0,
unlockedUnits: ["m1"],
discoveredUnits: [],
}
}
//Used after every round
var wait = false
var cellsToDelete = []
//Get and set cell in the grid
function getCell(x, y) {
if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT) {
return cells[y][x]
} else {
return undefined
}
}
function setCell(x, y, cell) {
if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT) {
cells[y][x] = cell
}
}
function getSide(x, y, side) {
if (side == DIR_UP) {
return [x, y - 1]
}
else if (side == DIR_DOWN) {
return [x, y + 1]
}
else if (side == DIR_LEFT) {
return [x - 1, y]
}
else if (side == DIR_RIGHT) {
return [x + 1, y]
} else {
return undefined
}
}
function getSideCell(x, y, side) {
var [x, y] = getSide(x, y, side)
return getCell(x, y)
}
function logDebug(data) {
if (debug)
console.log(data)
}
function spawnCells(count = 2) {
var emptyCells = []
//Get empty cells for spawning
for (let y = 0; y < HEIGHT; y++) {
for (let x = 0; x < WIDTH; x++) {
if (getCell(x, y) === null) {
emptyCells[emptyCells.length] = [x, y]
}
}
}
//Spawn cells
for (let index = 0; index < count; index++) {
if (emptyCells.length == 0) {
logDebug(`out of space`)
return
}
var chosenCell = Math.floor(Math.random() * emptyCells.length);
var [x, y] = emptyCells.splice(chosenCell, 1)[0] //Dont spawn on same cell
new cellGrid(x, y, getUnitFromID(gameState.unlockedUnits[Math.floor(Math.random() * gameState.unlockedUnits.length)]))
}
}
const KEYMAPPING = {
ArrowUp: DIR_UP,
ArrowDown: DIR_DOWN,
ArrowLeft: DIR_LEFT,
ArrowRight: DIR_RIGHT,
w: DIR_UP,
s: DIR_DOWN,
a: DIR_LEFT,
d: DIR_RIGHT,
}
//Handle keyboard event
function onkeydown(event) {
logDebug(event)
if (wait) { return }
if (document.activeElement instanceof HTMLTextAreaElement) { return }
if (document.activeElement instanceof HTMLInputElement) { return }
if (KEYMAPPING[event.key] != null) {
move(KEYMAPPING[event.key])
} else if (event.key == "Backspace" || event.key == "z") {
undo()
}
else {
return
}
event.preventDefault()
}
//Handle touch and mouse event
var touchDown = 0
var touchX = 0
var touchY = 0
function onTouch(event) {
var touchPos
if (event instanceof TouchEvent) {
touchPos = { x: event.changedTouches[0].clientX, y: event.changedTouches[0].clientY }
} else if (event instanceof MouseEvent) {
touchPos = { x: event.clientX, y: event.clientY }
if (event.button == 2 && event.type == "mouseup") {
undo()
}
}
if (event.type == "touchstart" || event.type == "mousedown") {
touchX = touchPos.x
touchY = touchPos.y
}
else if (event.type == "mouseup" || event.type == "touchend" && event.touches.length == 0) {
var dx = touchPos.x - touchX
var dy = touchPos.y - touchY
var length = 100
if (Math.abs(dx / dy) > 1.5) {
if (dx > length) {
move(DIR_RIGHT)
} else if (dx < -length) {
move(DIR_LEFT)
}
} else if (Math.abs(dy / dx) > 1.5) {
if (dy > length) {
move(DIR_DOWN)
} else if (dy < -length) {
move(DIR_UP)
}
}
logDebug(dx + " " + dy)
}
event.preventDefault()
logDebug(event.type + " " + touchPos.x + " " + touchPos.y)
logDebug(event)
}
//Coloring
function getColor(units) {
var color = 0x808080
if (units.m != null) {
color += units.m * 0x202000
}
if (units.s != null) {
color -= units.s * 0x2700
}
if (units.kg != null) {
color += units.kg * 0x270000
}
if (units.A != null) {
color += units.A * 0x27
}
if(isUnitImmovable(units)) {
color -= 0x202020
}
return color.toString(16)
}
//Logic
function multiply(units1, units2) {
var units3 = {}
for (const key in units1) { //multiply units1
units3[key] = units1[key]
}
for (const key in units2) { //multiply units2
if (units1[key] != null) {
units3[key] = units1[key] + units2[key]
} else {
units3[key] = units2[key]
}
}
return units3
}
function divide(units1, units2) {
var units3 = {}
for (const key in units1) { //multiply units1
units3[key] = units1[key]
}
for (const key in units2) { //divide by units2
if (units1[key] != null) {
units3[key] = units1[key] - units2[key]
} else {
units3[key] = -units2[key]
}
}
return units3
}
const unitNameDict = {
m1: ["m", "L"],
m2: ["m²", "S"],
m3: ["m³", "V"],
s1: ["s", "t"],
s_1: ["Hz", "f"],
m1s_1: ["m/s", "v"],
m1s_2: ["m/s²", "a"],
kg1: ["kg", "m"],
m_3kg1: ["kg/m³", "ρ"],
m1s_2kg1: ["N", "F,G"],
m1s_1kg1: ["<div style='font-size:0.8em;'>kg⋅m/s\nN⋅s</div>", "P,I"],
m_1s_2kg1: ["Pa", "p"],
m2s_2kg1: ["J", "E,W,Q"],
m2s_3kg1: ["W", "P"],
A1: ["A", "I"],
s1A1: ["C", "Q"],
m_1A1: ["A/m", "H"],
m2s_3kg1A_1: ["V", "U,E,φ"],
m1s_3kg1A_1: ["V/m", "E"],
m2s_3kg1A_2: ["Ω", "R"],
m_2s4kg_1A2: ["F", "C"],
s_2kg1A_1: ["T", "B"],
m2s_2kg1A_1: ["Wb", "φ"],
wl1:[" ",""], //Wall, immovable
}
const unitBase = ["m", "s", "kg", "A","wl"]
//Unit IDs and names
function getUnitID(units) {
var unitID = ""
for (const key in unitBase) {
var unit = unitBase[key]
if (units[unit] && units[unit] != 0) {
unitID += (unit + units[unit]).replace("-", "_")
}
}
unitID = unitID
return unitID
}
function getUnitFromID(unitID = "") {
if (!unitID) return {}
var unit = {}
var matched = unitID.matchAll("([a-zA-Z]+)(_?[0-9]+)")
for (const match of matched) {
unit[match[1]] = Number.parseInt(match[2].replace("_", "-"))
}
return unit
}
function getUnitName(units) {
var unitID = getUnitID(units)
return getUnitNameFromID(unitID)
}
function getUnitNameFromID(unitID) {
if (unitID.length == 0) { return "1" }
if (unitNameDict[unitID] == null) { return undefined }
return unitNameDict[unitID][0]
}
function getSymbol(unitID) {
if (unitID.length == 0) { return "" }
if (unitNameDict[unitID] == null) { return undefined }
return unitNameDict[unitID][1]
}
function getRawName(units) {
var name = ""
for (const key in units) {
name += (key + "=" + units[key])
}
return name
}
function isUnitImmovable(units){
return (units.wl != null && units.wl != 0) //Immovable if unit is a wall
}
//Cell
class cellGrid {
constructor(x, y, units = { m: 1 }) {
if (getCell(x, y) === undefined) {
logDebug(`${x},${y} is out of bounds`)
return
} else if (getCell(x, y) instanceof cellGrid) {
logDebug(`replacing ${x},${y}`)
getCell(x, y).remove()
}
this.units = units
this.x = parseInt(x)
this.y = parseInt(y)
this.cell = document.createElement("div")
this.cell.classList.add("cell")
this.cell.classList.add("fg")
gamegrid.appendChild(this.cell)
this.updateVisuals()
this.updatePosition()
setCell(x, y, this)
}
isImmovable(){
return isUnitImmovable(this.units) //Immovable if unit is a wall
}
updateVisuals() {
if(this.isImmovable()){
this.cell.classList.add("immovable-cell")
this.cell.innerHTML = "<div class=circle style='left:0.5em;top:0.5em;' ></div><div class=circle style='right:0.5em;top:0.5em;'></div><div class=circle style='left:0.5em;bottom:0.5em;'></div><div class=circle style='right:0.5em;bottom:0.5em;'></div>"
}else{
this.cell.innerHTML = "<div class='cellLabel largeFont'>" + this.getName() + "</div>" + "<div class='cellCornerMark'>" + this.getSymbol() + "</div>"
}
this.cell.style.setProperty("background","#" + this.getColor())
}
updatePosition() {
this.cell.style.setProperty("--x", this.x)
this.cell.style.setProperty("--y", this.y)
// this.cell.style.left = this.x * 125 + "px"
// this.cell.style.top = this.y * 125 + "px"
}
getUnitID() {
return getUnitID(this.units)
}
getName() {
return getUnitName(this.units) || getUnitID(this.units)
}
getSymbol() {
return getSymbol(this.getUnitID())
}
getColor() {
return getColor(this.units)
}
canMerge(obj, dir) {
if (obj instanceof cellGrid) {
if(this.isImmovable() || obj.isImmovable()){
return false
}
if (dir == DIR_UP) {
return getUnitName(divide(obj.units, this.units)) != null
} else if (dir == DIR_DOWN) {
return getUnitName(divide(this.units, obj.units)) != null
} else {
return getUnitName(multiply(this.units, obj.units)) != null
}
}
}
move(dir) {
if(this.isImmovable()){
return false
}
var y2 = this.y
var x2 = this.x
var success = 0
while (getSideCell(x2, y2, dir) === null) {
var [x2, y2] = getSide(x2, y2, dir)
}
success ||= this.relocate(x2, y2)
var [x3, y3] = getSide(x2, y2, dir)
success ||= this.tryMerge(x3, y3, dir)
return success > 0
}
relocate(x, y) {
if (x == this.x && y == this.y) {
logDebug(`Already at ${x},${y}`)
return false
}
if (getCell(x, y) !== null) {
logDebug(`${x},${y} isn't empty`)
return false
}
logDebug(`moving ${this.x},${this.y} to ${x},${y}`)
setCell(this.x, this.y, null)
this.x = x
this.y = y
setCell(x, y, this)
this.updatePosition()
return true
}
tryMerge(x, y, dir) {
var cell2 = getCell(x, y)
if (!this.canMerge(cell2, dir)) { return false }
cell2.remove()
var newUnits
if (dir == DIR_DOWN) {
newUnits = divide(this.units, cell2.units)
} else if (dir == DIR_UP) {
newUnits = divide(cell2.units, this.units)
} else {
newUnits = multiply(this.units, cell2.units)
}
this.relocate(x, y)
this.remove()
new cellGrid(x, y, newUnits)
}
remove() {
setCell(this.x, this.y, null)
cellsToDelete.push(this.cell)
this.cell.style.zIndex = 2
}
}
//init scripts
function initGrid() {
var basegrid = document.getElementById("basegrid")
basegrid.style.setProperty("--columns", WIDTH)
basegrid.style.setProperty("--rows", HEIGHT)
cells = []
for (let y = 0; y < HEIGHT; y++) {
var row = []
for (let x = 0; x < WIDTH; x++) {
var cell = document.createElement("div")
cell.classList.add("cell")
cell.classList.add("bg")
cell.style.float = "left"
cell.style.setProperty("--x", x)
cell.style.setProperty("--y", y)
// cell.style.left = x * 125 + "px"
// cell.style.top = y * 125 + "px"
bggrid.appendChild(cell)
row[x] = null
}
cells[y] = row
}
}
function clear() {
while (bggrid.hasChildNodes()) {
bggrid.removeChild(bggrid.childNodes[0])
}
while (gamegrid.hasChildNodes()) {
gamegrid.removeChild(gamegrid.childNodes[0])
}
while (discoveredUnitsElement.hasChildNodes()) {
discoveredUnitsElement.removeChild(discoveredUnitsElement.childNodes[0])
}
gameState.discoveredUnits = []
gameState.score = 0
}
function newGame() {
WIDTH = GRID_WIDTH_SETTER.value
HEIGHT = GRID_HEIGHT_SETTER.value
clear()
resetVariables()
initGrid()
spawnCells(2)
updateRound()
logUndo()
}
//Move all cells in grid
function move(dir) {
var success = 0
if (dir == DIR_UP) {
for (let y = 0; y < HEIGHT; y++) {
for (let x = 0; x < WIDTH; x++) {
trymove(x, y, dir)
}
}
} else if (dir == DIR_DOWN) {
for (let y = HEIGHT - 1; y >= 0; y--) {
for (let x = 0; x < WIDTH; x++) {
trymove(x, y, dir)
}
}
} else if (dir == DIR_LEFT) {
for (let x = 0; x < WIDTH; x++) {
for (let y = 0; y < HEIGHT; y++) {
trymove(x, y, dir)
}
}
} else if (dir == DIR_RIGHT) {
for (let x = WIDTH - 1; x >= 0; x--) {
for (let y = 0; y < HEIGHT; y++) {
trymove(x, y, dir)
}
}
}
if (success > 0) {
updateRound()
wait = true
setTimeout(() => {
spawnCells(CELLS_PER_ROUND)
afterRound()
wait = false
}, 200);
}
function trymove(x, y, dir) {
if (getCell(x, y) instanceof cellGrid) {
if (getCell(x, y).move(dir)) {
success += 1
}
} else {
return false
}
}
}
//Update when doing a round
function updateRound() {
var complexity = 0
for (const y in cells) {
var row = cells[y]
for (const x in row) {
var cell = row[x]
if (cell instanceof cellGrid) {
for (const key in cell.units) {
var power = cell.units[key]
complexity += Math.abs(power)
}
var units = cell.units
var unitID = getUnitID(cell.units)
if (!gameState.discoveredUnits.includes(unitID) && !isUnitImmovable(cell.units)) {
pushDiscovered(unitID)
}
}
}
}
gameState.score = Math.max(gameState.score, complexity)
document.getElementById("complexity").textContent = complexity
document.getElementById("score").textContent = gameState.score
unlockNewUnitsWhenReady()
}
function pushDiscovered(unitID) {
gameState.discoveredUnits.push(unitID)
pushDiscoveredToWindow(unitID)
}
function pushDiscoveredToWindow(unitID) {
var newDiscovered = document.createElement("div")
newDiscovered.style.backgroundColor = "#" + getColor(getUnitFromID(unitID))
newDiscovered.classList.add("info_cell")
//newDiscovered.innerHTML = "<p class='cellLabel'>" + (getUnitNameFromID(unitID) || unitID) + "</p>"
newDiscovered.innerHTML = "<div class='cellLabel'>" + (getUnitNameFromID(unitID) || unitID) + "</div>" +
"<div class='cellCornerMark'>" + getSymbol(unitID) + "</div>"
discoveredUnitsElement.appendChild(newDiscovered)
}
const unlockableUnits = {
s1: 3,
kg1: 8,
A1: 13
}
function unlockNewUnitsWhenReady() {
for (const unitID in unlockableUnits) {
if (!gameState.unlockedUnits.includes(unitID) && gameState.discoveredUnits.length >= unlockableUnits[unitID]) {
gameState.unlockedUnits.push(unitID)
}
}
}
//Update after completing a round
function afterRound() {
for (const y in cells) {
var row = cells[y]
for (const x in row) {
var cell = row[x]
if (cell instanceof cellGrid) {
cell.updateVisuals()
}
}
}
for (const i in cellsToDelete) {
if (cellsToDelete[i].parentNode == gamegrid)
gamegrid.removeChild(cellsToDelete[i])
}
cellsToDelete = []
updateRound()
logUndo()
saveState()
}
function logUndo() {
undos.push(serialize())
}
function undo() {
if (undos.length < 2) {
logDebug("Nothing to undo!")
return
}
logDebug(undos[undos.length - 2])
loadGameFromData(undos[undos.length - 2])
undos.pop()
}
//Manipulate cellV2
function dumpGrid() {
var cellsToExportV2 = []
for (const y in cells) {
var rowToExport = []
var row = cells[y]
for (const x in row) {
var cell = row[x]
if (cell instanceof cellGrid) {
rowToExport[x] = cell.getUnitID()
} else {
rowToExport[x] = null
}
}
cellsToExportV2[y] = rowToExport
}
return cellsToExportV2
}
function loadGrid(cellsV2) {
for (const y in cellsV2) {
var row = cellsV2[y]
for (const x in row) {
var cell = row[x]
if (typeof (cell) == 'string') {
new cellGrid(x, y, getUnitFromID(cell))
} else
if (cell != null) {
new cellGrid(x, y, cell)
}
}
}
}
//Deprecated old save format
function saveGridV1() {
var cellsToExport = []
for (const y in cells) {
var row = cells[y]
for (const x in row) {
var cell = row[x]
if (cell instanceof cellGrid) {
cellsToExport.push({ x: cell.x, y: cell.y, units: cell.units })
}
}
}
return cellsToExport
}
//save and load
function serialize() {
var savedata = Object.assign({}, gameState)
savedata.id = "2048units_savedata"
// savedata.cells=saveGridV1()
savedata.cellsV2 = dumpGrid()
savedata.gridWidth = WIDTH
savedata.gridHeight = HEIGHT
savedata.cellsPerRound = CELLS_PER_ROUND
return savedata
}
function exportState() {
document.getElementById("leveldata").value = (JSON.stringify(serialize()))
toast("Exported! Copy the code from the box below and save it somewhere!")
}
function loadData() {
return JSON.parse(document.getElementById("leveldata").value)
}
function importState() {
try {
var savedData = loadData()
loadGameFromData(savedData)
toast("Loaded!")
}
catch (err) {
toast("Paste the code in the box below first!")
}
}
function loadGameFromData(savedData) {
if (savedData.id != "2048units_savedata") return;
WIDTH = savedData.gridWidth || 4
HEIGHT = savedData.gridHeight || 4
CELLS_PER_ROUND = savedData.cellsPerRound || 1
GRID_WIDTH_SETTER.value=WIDTH
GRID_HEIGHT_SETTER.value=HEIGHT
clear()
initGrid()
if (savedData.cellsV2 != null) {
loadGrid(savedData.cellsV2)
}
else if (savedData.cells != null) {
for (const i in savedData.cells) {
const cell = savedData.cells[i]
new cellGrid(cell.x, cell.y, cell.units)
}
}
if (savedData.score != null) {
gameState.score = savedData.score
} else {