-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgame.js
More file actions
1362 lines (1313 loc) · 49.7 KB
/
game.js
File metadata and controls
1362 lines (1313 loc) · 49.7 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
let defaultWorldInfo = {
"dirName": "default-world",
"seed": 1234,
}
worldInfo = defaultWorldInfo;
// set the seed to a random integer
worldInfo.seed = Math.floor(Math.random() * 100000);
let dirCoords = {
"n": [0,-1],
"e": [1,0],
"s": [0,1],
"w": [-1,0]
}
defaultPlayer = {
x: 0,
y: 0,
z: 1,
dir: 0,
name: "player",
tile: "stone",
tool: "place",
avatar: "red"
}
player = defaultPlayer;
class Camera {
constructor(x, y) {
this.x = x||0;
this.y = y||0;
}
}
camera = new Camera(0, 0);
ticks = 0;
let avatars = {
"red": { texture: "avatars/red.png" },
"orange": { texture: "avatars/orange.png" },
"yellow": { texture: "avatars/yellow.png" },
"lime": { texture: "avatars/lime.png" },
"cyan": { texture: "avatars/cyan.png" },
"blue": { texture: "avatars/blue.png" },
"magenta": { texture: "avatars/magenta.png" },
"black": { texture: "avatars/black.png" },
"white": { texture: "avatars/white.png" },
}
let avatarArray = Object.keys(avatars);
let solidTypes = {"wall":true, "door":true};
let passableTypes = {"floor":true, "liquid":true, "effect":true, "item":true, "ceiling":true};
let placeableTypes = {"floor":true, "liquid":true, "effect":true, "item":true};
let ceilingTypes = {"ceiling":true};
// Chunk class with a constructor
class Chunk {
constructor(x, y, data) {
this.x = x; // Chunk position
this.y = y;
if (data && data.tiles) {
this.tiles = data.tiles;
}
else {
this.tiles = []; // Array of tiles in the chunk
this.tiles.length = CHUNK_SIZE * CHUNK_SIZE; // Initialize the array
}
if (data && data.entities) {
this.entities = data.entities;
}
else {
this.entities = []; // Array of entities in the chunk
}
this.loadTime = ticks; // When the chunk was loaded
}
}
let textures = {};
let canvas = document.getElementById("gameCanvas");
let SCALE = 64;
let TILE_PIXELS = SCALE; // How many pixels wide and high each tile is
let TILE_PIXELS_HALF = TILE_PIXELS / 2;
let PIXEL_PIXELS = TILE_PIXELS/32;
const CHUNK_SIZE = 16; // How many tiles wide and high each chunk is
let RENDER_DISTANCE = 1; // How many chunks to render on each side of the player
let SIM_DISTANCE = 2; // How many chunks to simulate on each side of the player
let CAMERA_SPEED = 0.1; // How fast the camera moves
function updateScale() {
var canvas = document.getElementById("gameCanvas");
// if the scale is under 2, set it to 2
if (SCALE < 2) { SCALE = 2; }
// if the scale is over 512, set it to 512
if (SCALE > 512) { SCALE = 512; }
TILE_PIXELS = SCALE;
TILE_PIXELS_HALF = TILE_PIXELS / 2;
PIXEL_PIXELS = TILE_PIXELS/32;
SCREEN_WIDTH_HALF = canvas.width / 2 - TILE_PIXELS_HALF;
SCREEN_HEIGHT_HALF = canvas.height / 2 - TILE_PIXELS_HALF;
RENDER_DISTANCE = Math.ceil(CHUNK_SIZE / TILE_PIXELS);
SIM_DISTANCE = RENDER_DISTANCE * 2;
if (SCALE >= 16 && SCALE <= 32) { RENDER_DISTANCE++ }
if (SCALE >= 512) { CAMERA_SPEED = 1;}
// camera speed minimum of 0.1 and maximum of 0.5
else { CAMERA_SPEED = Math.max(SCALE / 320, 0.1); }
}
loadedChunks = {};
// Create a 10x10 of chunks
/*for (var x = -5; x < 5; x++) {
for (var y = -5; y < 5; y++) {
loadedChunks[x + ',' + y] = generateChunk(x,y);
}
}*/
const PIover2 = Math.PI / 2;
function perlin(x,y,N) {
var z = 0, s = 0;
for (var i = 0; i < N; i++) {
var pp = 1/(1 << i); // (1 << i) same as Math.pow(2,i)
var e = PIover2*pp; // rotate angle
var ss = Math.sin(e);
var cc = Math.cos(e);
var xx = (x*ss+y*cc); // rotation
var yy = (-x*cc+y*ss);
s += pp; // total amplitude
z += pp*Math.abs(noise.perlin2(xx/pp,yy/pp));
}
return 2*z/s;
}
function randomSeeded(seed) {
var x = Math.sin(seed) * 10000;
return x - Math.floor(x);
}
let biomes = {
"grassland": {
"temp": 0.6,
"ground": [ // [depth,tile]
[0.3,"water"],
[0.35,"wet_sand_floor"],
[0.45,"sand_floor"],
[0.9,"grass_floor"],
[1,"stone",1]
],
"decor": [ // [tile,chance,floortype]
["tree",0.025,"grass_floor"],
["bush",0.0125,"grass_floor"],
["berry_bush",0.0125,"grass_floor"],
["small_rock",0.05],
[["flowers","red_flowers","cyan_flowers","pink_flowers","yellow_flowers","white_flowers","clovers"],0.075,"grass_floor"],
["grass_patch",0.01,"sand_floor"],
["wet_sand_pile",0.03,"wet_sand_floor"],
["water_hole",0.03,"sand_floor"],
["water_hole",0.03,"wet_sand_floor"],
["mushroom",0.03,"grass_floor"],
]
},
"forest": {
"temp": 0.4,
"ground": [
[0.3,"water"],
[0.325,"wet_sand_floor"],
[0.4,"sand_floor"],
[0.8,"grass_floor"],
[1,"stone",1],
],
"decor": [
["tree",0.2,"grass_floor"],
["stump",0.02,"grass_floor"],
["dead_tree",0.05,"grass_floor"],
["bush",0.1,"grass_floor"],
["berry_bush",0.1,"grass_floor"],
["small_rock",0.04],
["large_rock",0.02],
["stick",0.06,"grass_floor"],
["pinecone",0.03,"grass_floor"],
["leaf",0.05],
["acorn",0.05],
["stick",0.01,"sand_floor"],
["stick_pile",0.001,"grass_floor"],
[["flowers","red_flowers","cyan_flowers","pink_flowers","yellow_flowers","white_flowers","clovers"],0.05,"grass_floor"],
["moss",0.03,"grass_floor"],
["lichen",0.03,"grass_floor"],
["mushroom",0.03,"grass_floor"],
["log",0.0075],
["wet_sand_pile",0.03,"wet_sand_floor"],
]
},
"desert": {
"temp": 1,
"ground": [
[0.2,"water"],
[0.25,"wet_sand_floor"],
[0.9,"sand_floor"],
[1,"sandstone",1]
],
"decor": [
["small_rock",0.02],
["small_sandstone",0.03],
["large_rock",0.02],
["wet_sand_pile",0.03,"wet_sand_floor"],
["stick_pile",0.01],
]
}
}
let biomeTemps = []
// loop through biomes and add [temp,biome name]
for (let biome in biomes) {
biomeTemps.push([biomes[biome].temp,biome]);
}
// sort biomeTemps by temp in ascending order
biomeTemps.sort(function(a,b) {
return a[0] - b[0];
});
function generateChunk(chunkX,chunkY) { // do the same thing as above
var chunk = new Chunk(chunkX,chunkY);
noise.seed(worldInfo.seed);
for (var x = CHUNK_SIZE*chunkX; x < CHUNK_SIZE*chunkX+CHUNK_SIZE; x++) {
for (var y = CHUNK_SIZE*chunkY; y < CHUNK_SIZE*chunkY+CHUNK_SIZE; y++) {
// noise.simplex2 and noise.perlin2 for 2d noise
var value = Math.abs(perlin(x / 50, y / 50, 3));
var biomevalue = Math.abs(perlin(x / 100, y / 100, 3));
var decorvalue = randomSeeded(worldInfo.seed*x+y);
// loop through the biomeTemps. if the value is less than the first item, set the biome to the second item
var biome = "grassland";
for (var i = 0; i < biomeTemps.length; i++) {
if (biomevalue < biomeTemps[i][0]) {
biome = biomeTemps[i][1];
break;
}
}
// set tiletype to the last ground type in the biome
var tiletype = biomes[biome].ground[biomes[biome].ground.length-1][1];
var z = 0;
// loop through the biome's ground types. if the value is less than the first item, set tiletype to the second item, and z to the third item (or 0 if undefined)
for (var i = 0; i < biomes[biome].ground.length; i++) {
if (value < biomes[biome].ground[i][0]) {
tiletype = biomes[biome].ground[i][1];
z = biomes[biome].ground[i][2] || 0;
break;
}
}
var tileindex = tileIndex(x,y);
chunk.tiles[tileindex] = {id:tiletype};
// if z is not 0, set it
if (z !== 0) { chunk.tiles[tileindex].z = z; }
// if the biome has a decor property, loop through it. if the decorvalue is less than the second item, add the first item to possibleDecors
if (biomes[biome].decor && tileTypes[tiletype].type==="floor") {
var possibleDecors = [];
for (var i = 0; i < biomes[biome].decor.length; i++) {
if (decorvalue < biomes[biome].decor[i][1] && (biomes[biome].decor[i][2]===undefined || biomes[biome].decor[i][2]===tiletype)) {
// if its an array, pick a random item, else just add it
if (Array.isArray(biomes[biome].decor[i][0])) {
possibleDecors.push(biomes[biome].decor[i][0][Math.floor(Math.random()*biomes[biome].decor[i][0].length)]);
}
else {
possibleDecors.push(biomes[biome].decor[i][0]);
}
}
}
// if possibleDecors is not empty, pick a random decor from it
if (possibleDecors.length > 0) {
var decor = possibleDecors[Math.floor(Math.random()*possibleDecors.length)];
chunk.tiles[tileindex] = {id:decor,under:chunk.tiles[tileindex]};
}
}
}
}
/* Checkerboard pattern:
var tileType = randomTypes[Math.floor(Math.random() * randomTypes.length)];
for (var i = 0; i < CHUNK_SIZE * CHUNK_SIZE; i++) {
chunk.tiles[i] = {id: tileType};
} */
return chunk;
}
function updateChunk(chunk,chunkX,chunkY) {
// loop through every item in chunk.tiles. if the tile type has an onUpdate function, call it
for (var x = CHUNK_SIZE*chunkX; x < CHUNK_SIZE*chunkX+CHUNK_SIZE; x++) {
for (var y = CHUNK_SIZE*chunkY; y < CHUNK_SIZE*chunkY+CHUNK_SIZE; y++) {
var tileindex = tileIndex(x,y);
var tile = chunk.tiles[tileindex];
if (tileTypes[tile.id].onUpdate) {
tileTypes[tile.id].onUpdate(tile,x,y);
}
if (tileTypes[tile.id].border && tile.sides) {
if (tileTypes[tile.id].under) {
tile.under = {id:chooseTile(tileTypes[tile.id].under)};
}
}
}
}
}
function loadChunk(x,y) {
// if the file savePath + "/chunks/" + x + "_" + y + ".json" exists, load it as new Chunk(x,y,data), and return it
// otherwise generateChunk(x,y) and return the result
if (isNode && fs.existsSync(savePath + "/chunks/" + x + "_" + y + ".json")) {
var data = JSON.parse(fs.readFileSync(savePath + "/chunks/" + x + "_" + y + ".json"));
return new Chunk(x,y,data);
}
else {
var chunk = generateChunk(x,y);
loadedChunks[x + ',' + y] = chunk;
updateChunk(chunk,x,y);
saveChunk(x,y);
return chunk;
}
}
function saveChunk(x,y) {
// save the chunk at x,y to the file savePath + "/chunks/" + x + "_" + y + ".json"
if (isNode) {
fs.writeFileSync(savePath + "/chunks/" + x + "_" + y + ".json", JSON.stringify(loadedChunks[x + ',' + y]));
}
}
function saveChunkAtTile(x,y) {
// tile coords instead of chunk coords
var chunkcoords = coordsToChunkNums(x,y);
saveChunk(chunkcoords.x, chunkcoords.y);
}
function unloadChunk(x,y) {
if (isNode) { saveChunk(x,y); }
delete loadedChunks[x + ',' + y];
}
function savePlayer() {
// save the player to savePath + "/players/" + player.name + ".json"
if (isNode) {
fs.writeFileSync(savePath + "/players/" + player.name + ".json", JSON.stringify(player));
}
}
function coordsToChunk(x, y) {
return Math.floor(x / CHUNK_SIZE) + ',' + Math.floor(y / CHUNK_SIZE);
}
function coordsToChunkNums(x, y) {
return {x: Math.floor(x / CHUNK_SIZE), y: Math.floor(y / CHUNK_SIZE)};
}
function getChunk(x, y, isChunk=false) {
if (isChunk) { chunkCoords = {x:x,y:y} }
else { chunkCoords = coordsToChunkNums(x, y); }
var chunk = loadedChunks[chunkCoords.x + ',' + chunkCoords.y];
if (chunk === undefined) {
chunk = loadChunk(chunkCoords.x, chunkCoords.y);
loadedChunks[chunkCoords.x + ',' + chunkCoords.y] = chunk;
}
return chunk;
}
function chunkTick(chunk) {
// loop through the entities in the chunk. if the entity has an onTick function, call it
for (var i = 0; i < chunk.entities.length; i++) {
var entity = chunk.entities[i];
if (entityTypes[entity.id].onTick) {
entityTypes[entity.id].onTick(entity);
}
}
}
function tileIndex(x, y) {
if (x < 0) { x = CHUNK_SIZE + (x%CHUNK_SIZE); } // account for negative values
if (y < 0) { y = CHUNK_SIZE + (y%CHUNK_SIZE); }
return (x % CHUNK_SIZE) + (y % CHUNK_SIZE) * CHUNK_SIZE;
}
function getTile(x, y) {
// calculate which chunk the tile is in, then return the tile at that position
var chunk = getChunk(x, y);
return chunk.tiles[tileIndex(x, y)];
}
function getMousePos(evt) {
if (!evt) {
if (typeof lastmouseevt === 'undefined') { return {x:0,y:0} }
evt = lastmouseevt;
}
else { lastmouseevt = evt; }
if (evt.touches) {
evt.preventDefault();
evt = evt.touches[0];
}
var canvas = document.getElementById("gameCanvas");
var rect = canvas.getBoundingClientRect();
// convert the mouse position to the game coordinates
return {
x: Math.floor((evt.clientX - rect.left) / TILE_PIXELS - (SCREEN_WIDTH_HALF / TILE_PIXELS) + camera.x),
y: Math.floor((evt.clientY - rect.top) / TILE_PIXELS - (SCREEN_HEIGHT_HALF / TILE_PIXELS) + camera.y)
};
}
function updateMousePos() {
mousePos = getMousePos();
}
function lookingAtCoords() {
if (player.dir === 0) { // looking up
return [Math.ceil(player.x), Math.ceil(player.y) - 1];
} else if (player.dir === 1) { // looking right
return [Math.ceil(player.x) + 1, Math.ceil(player.y)];
} else if (player.dir === 2) { // looking down
return [Math.ceil(player.x), Math.ceil(player.y) + 1];
} else if (player.dir === 3) { // looking left
return [Math.ceil(player.x) - 1, Math.ceil(player.y)];
}
}
function lookingAt() {
var coords = lookingAtCoords();
return getTile(coords[0], coords[1]);
}
function pushEntity(entity) {
// the entity is the player, with an x, y, and dir
// dir 0 = north, 1 = east, 2 = south, 3 = west
// move the player in the opposite direction they are facing
var dir = entity.dir;
var targetX = 0;
var targetY = 0;
if (dir === 0) { targetY += 1; }
else if (dir === 1) { targetX -= 1; }
else if (dir === 2) { targetY -= 1; }
else if (dir === 3) { targetX += 1; }
if (isPassable(player.x + targetX, player.y + targetY)) {
moveEntity(player, player.x + targetX, player.y + targetY);
updateMousePos();
hideCursor = true;
return true;
}
else {
// check if adjacent tiles are passable, and move there instead if so, and update direction
for (var i = 0; i < 4; i++) {
var targetX = 0;
var targetY = 0;
if (i === 0) { targetY += 1; }
else if (i === 1) { targetX -= 1; }
else if (i === 2) { targetY -= 1; }
else if (i === 3) { targetX += 1; }
if (isPassable(player.x + targetX, player.y + targetY)) {
entity.dir = i;
moveEntity(player, player.x + targetX, player.y + targetY);
updateMousePos();
hideCursor = true;
return true;
}
}
}
return false;
}
function updateAdjacent(x,y) {
// run onUpdate of the 4 adjacent tiles
for (var i = 0; i < 4; i++) {
var targetX = 0;
var targetY = 0;
if (i === 0) { targetY += 1; }
else if (i === 1) { targetX -= 1; }
else if (i === 2) { targetY -= 1; }
else if (i === 3) { targetX += 1; }
var adjTile = getTile(x+targetX,y+targetY);
if (adjTile && tileTypes[adjTile.id].onUpdate) { tileTypes[adjTile.id].onUpdate(adjTile,x+targetX,y+targetY); }
}
}
function placeTile(type,x,y) {
var tile = getTile(x,y);
if (x===player.x && y===player.y && !passableTypes[tileTypes[type].type]) {
if (!pushEntity(player)) {
return false;
}
else { savePlayer(); }
}
if (!placeableTypes[tileTypes[tile.id].type] || tile.id===type) {
return false;
}
else if (tileTypes[tile.id].type === "liquid" && !passableTypes[tileTypes[type].type]) {
removeTile(x,y);
}
// set tile.under to a copy of the current tile's object
tile.under = JSON.parse(JSON.stringify(tile));
if (tile.id !== type) {
tile.id = type;
}
if (tileTypes[type].type === "floor") {
tile.z = tile.z+1 || 1;
}
else { tile.z = 1; }
if (tileTypes[type].onPlace) { tileTypes[type].onPlace(tile,x,y); }
if (tileTypes[type].onUpdate) { tileTypes[type].onUpdate(tile,x,y); }
updateAdjacent(x,y);
saveChunkAtTile(x,y);
return true;
}
function chooseTile(data) {
// if data is a string, return it
if (typeof data === 'string') { return data; }
// if data is an array, choose a random element
else if (Array.isArray(data)) {
return data[Math.floor(Math.random() * data.length)];
}
// if data is an object, choose a key based on the values as chances
else if (typeof data === 'object') {
var sum = 0;
for (var key in data) { sum += data[key]; }
var rand = Math.random() * sum;
for (var key in data) {
rand -= data[key];
if (rand <= 0) { return key; }
} }
// if it is null, return null
else if (data === null) { return null; }
}
function removeTile(x,y) {
// set the tile type to null
var tile = getTile(x,y);
if (tileTypes[tile.id].unbreakable) { return false; }
if (tileTypes[tile.id].onRemove) { tileTypes[tile.id].onRemove(tile,x,y); }
if (tile.z === -10) {
tile.id = "rough_rock_floor";
}
else if (tile.under) {
setTile(x,y,tile.under);
}
else if (tileTypes[tile.id].under) {
tile.id = chooseTile(tileTypes[tile.id].under);
// subtract one from z, or -1 if tileTypes[tile.id].type is floor otherwise 0
tile.z = tile.z-1 || (tileTypes[tile.id].type === 'floor' ? -1 : 0);
}
else { tile.id = null; }
updateAdjacent(x,y);
saveChunkAtTile(x,y);
return true;
}
function setTile(x,y,object) {
// calculate which chunk the tile is in, then set the tile at that position
var chunk = getChunk(x, y);
chunk.tiles[tileIndex(x, y)] = object;
saveChunkAtTile(x,y);
}
function tryMove(entity,x,y) {
// change the direction based on the difference between the new and old coordinates
var dir = 0;
if (entity.y < y) { dir = 2; }
else if (entity.y > y) { dir = 0; }
if (entity.x < x) { dir = 1; }
else if (entity.x > x) { dir = 3; }
entity.dir = dir;
if (isPassable(x,y) || entity.noclip) {
moveEntity(entity,x,y);
return true;
}
return false;
}
function moveEntity(entity, x, y) {
if (entity.id) {
var chunkNums = coordsToChunkNums(Math.round(entity.x), Math.round(entity.y));
var newChunkNums = coordsToChunkNums(Math.round(x), Math.round(y));
//console.log(chunkNums, newChunkNums);
// if these are different, remove the entity from the old chunk's chunk.entities and add it to the new one
if (chunkNums.x !== newChunkNums.x || chunkNums.y !== newChunkNums.y) {
var oldChunk = getChunk(chunkNums.x, chunkNums.y);
var newChunk = getChunk(newChunkNums.x, newChunkNums.y);
oldChunk.entities.splice(oldChunk.entities.indexOf(entity), 1);
newChunk.entities.push(entity);
saveChunk(chunkNums.x, chunkNums.y);
saveChunk(newChunkNums.x, newChunkNums.y);
}
}
entity.x = x;
entity.y = y;
}
function generateUID() {
return parseInt(Date.now().toString() + Math.random().toString().substring(10));
}
function placeEntity(entity, x, y) {
// get the chunk at the entity's position
var chunk = getChunk(x, y);
chunk.entities.push(
{id:entity, x:x, y:y, z:1, vx:0, vy:0, vz:0, dir:0, phase:0, uid:generateUID()}
);
}
function isPassable(x, y) {
var tile = getTile(Math.round(x), Math.round(y));
if (tileTypes[tile.id].type === "door") {
return Boolean(tile.open);
}
// if the tile's id isn't null and in passableTypes, return true
return passableTypes[tileTypes[tile.id].type] && tile.id !== null;
}
function chooseTexture(tile, x, y, effects=true, isEntity=false) {
if (typeof tile === 'string') {
return textures[tile];
}
if (!isEntity) { var tileInfo = tileTypes[tile.id]; }
else { var tileInfo = entityTypes[tile.id]; }
var texture = tileInfo.texture;
if (tile.open && tileInfo.openTexture) {
texture = tileInfo.openTexture;
}
// if the texture is a function, call it
if (typeof texture === 'function') {
texture = texture(x, y);
}
// if the texture is an array, it is an animation, use ticks to choose which frame to use
if (Array.isArray(texture)) {
if (SCALE > 8 && effects) {
texture = texture[Math.floor(ticks / (tileInfo.animTicks||10)) % texture.length];
}
else {
texture = texture[0];
}
}
texture = textures[texture];
if (SCALE > 8 && tileInfo.flow && effects) {
texture = flowTexture(texture,
Math.floor(ticks * tileInfo.flow) % texture.width
);
}
return texture;
}
function ratioScale(width, height, scale) {
// scale to fit into a TILE_PIXELS x TILE_PIXELS square, without changing the aspect ratio
scale = (scale || 1) * TILE_PIXELS;
if (width === height) { return {width:scale, height:scale}; }
var ratio = width / height;
if (ratio > 1) {
return {width: scale, height: scale / ratio};
}
else {
return {width: scale * ratio, height: scale};
}
}
function drawImageRotated(ctx, image, x, y, w, h, degrees){
ctx.save();
ctx.translate(x+w/2, y+h/2);
ctx.rotate(degrees*Math.PI/180.0);
ctx.translate(-x-w/2, -y-h/2);
ctx.drawImage(image, x, y, w, h);
ctx.restore();
}
function drawImageFlipped(ctx,image,x,y,w,h) {
// draw the image onto ctx flipped horizontally
ctx.save();
ctx.translate(x+w/2, y+h/2);
ctx.scale(-1, 1);
ctx.translate(-x-w/2, -y-h/2);
ctx.drawImage(image, x, y, w, h);
ctx.restore();
}
function drawTilePosX(x,scale) {
scale = scale || {x:1,y:1};
return Math.round((x - camera.x)*TILE_PIXELS+SCREEN_WIDTH_HALF+((TILE_PIXELS-scale.width)/2));
}
function drawTilePosY(y,scale) {
scale = scale || {x:1,y:1};
return Math.round((y - camera.y)*TILE_PIXELS+SCREEN_HEIGHT_HALF+((TILE_PIXELS-scale.height)))
}
let drawQueue = {
bigTiles: [],
bigFloors: [],
ceilings: [],
solids: [],
entities: [],
overlays: [],
};
let offScrCan = document.createElement("canvas");
let textureCache = {};
function cacheCanvas(key) {
var cachecanvas = document.createElement("canvas");
cachecanvas.width = offScrCan.width;
cachecanvas.height = offScrCan.height;
var ctx3 = cachecanvas.getContext("2d");
ctx3.drawImage(offScrCan, 0,0);
textureCache[key] = cachecanvas;
return cachecanvas;
}
function maskedTexture(texture,mask) {
if (textureCache[texture.src+mask.src]) { return textureCache[texture.src+mask.src]; }
// return a new texture with the mask applied
if (mask.width === 0) { return texture }
var ctx2 = offScrCan.getContext("2d");
offScrCan.width = mask.width;
offScrCan.height = mask.height;
ctx2.drawImage(mask, 0,0);
ctx2.globalCompositeOperation = 'source-in';
ctx2.drawImage(texture, 0,0);
ctx2.globalCompositeOperation = 'source-over';
// copy the canvas and cache
return cacheCanvas(texture.src+mask.src);
}
function flowTexture(texture,step) {
if (textureCache[texture.src+step]) { return textureCache[texture.src+step]; }
var ctx2 = offScrCan.getContext("2d");
offScrCan.width = texture.width;
offScrCan.height = texture.height;
ctx2.drawImage(texture, step,0); // draw the texture step pixels to the right
ctx2.drawImage(texture, -texture.width+step,0); // draw the rest of the texture on the other side
return cacheCanvas(texture.src+step);
}
function drawTile(tile, x, y, ctx, half, mask) {
// use the tile's texture, x-camera.x, y-camera.y, and TILE_PIXELS
if (tile.id === null) { return; }
if (tile.under && !half) {
drawTile(tile.under, x, y, ctx);
}
if (SCALE > 8 && tileTypes[tile.id].border === 1) {
mask = "bumpy_border/"+(tile.sides || "none")+".png";
}
var texture = chooseTexture(tile,x,y);
if (mask) {
var maskTexture = chooseTexture(mask,x,y);
texture = maskedTexture(texture,maskTexture);
//ctx.drawImage(texture, drawTilePosX(x,scale), drawTilePosY(y,scale), scale.width, scale.height);
}
var scale = ratioScale(texture.width, texture.height, tileTypes[tile.id].scale);
if (SCALE > 8 && tileTypes[tile.id].randRot) {
// choose 0, 90, 180, or 270 degrees based on its position as a seed
var degrees = (Math.floor(randomSeeded(worldInfo.seed*x+y+(tile.z||0))*100)) % 4 * 90;
drawImageRotated(ctx, texture, drawTilePosX(x,scale), drawTilePosY(y,scale), scale.width, scale.height, degrees)
}
else {
if (ceilingTypes[tileTypes[tile.id].type]) {
drawQueue.ceilings.push([texture, drawTilePosX(x,scale), drawTilePosY(y,scale), scale.width, scale.height])
}
else if (solidTypes[tileTypes[tile.id].type]) {
drawQueue.solids.push([texture, drawTilePosX(x,scale), drawTilePosY(y,scale), scale.width, scale.height])
}
else if (tileTypes[tile.id].scale > 1) {
if (isPassable(x,y)) {
drawQueue.bigFloors.push([texture, drawTilePosX(x,scale), drawTilePosY(y,scale), scale.width, scale.height])
}
else {
drawQueue.bigTiles.push([texture, drawTilePosX(x,scale), drawTilePosY(y,scale), scale.width, scale.height])
}
}
else {
// if half, draw the bottom half of the tile only
if (!half) {
ctx.drawImage(texture, drawTilePosX(x,scale), drawTilePosY(y,scale), scale.width, scale.height);
}
else {
ctx.drawImage(texture, drawTilePosX(x,scale), drawTilePosY(y,scale)+scale.height/2, scale.width, scale.height/2);
}
}
}
if (tile.z < 0) { // -z darkness
ctx.globalAlpha = Math.min(Math.abs(tile.z)*7,75)/100;
ctx.drawImage(textures["shadow.png"], drawTilePosX(x,scale), drawTilePosY(y,scale), scale.width, scale.height);
ctx.globalAlpha = 1;
}
}
function drawAvatar(avatar, x, y, ctx) {
// use the avatar's texture, x-camera.x, y-camera.y, and TILE_PIXELS
var texture = textures[avatars[avatar].texture];
var scale = ratioScale(texture.width, texture.height, avatars[avatar].scale);
var degrees = player.dir * 90;
drawImageRotated(ctx, texture, Math.round((x - camera.x)*TILE_PIXELS+SCREEN_WIDTH_HALF+((TILE_PIXELS-scale.width)/2)), Math.round((y - camera.y)*TILE_PIXELS+SCREEN_HEIGHT_HALF+((TILE_PIXELS-scale.height)/2)), scale.width, scale.height, degrees);
}
function drawEntity(entity, ctx) {
//console.log(entity)
var texture = chooseTexture(entity,entity.x,entity.y,false,true)
var scale = ratioScale(texture.width, texture.height, entityTypes[entity.id].scale);
var screenX = Math.round((entity.x - camera.x)*TILE_PIXELS+SCREEN_WIDTH_HALF+((TILE_PIXELS-scale.width)/2));
var screenY = Math.round((entity.y - camera.y)*TILE_PIXELS+SCREEN_HEIGHT_HALF+((TILE_PIXELS-scale.height)/2)) - (entity.z*PIXEL_PIXELS || 0);
// if the entity dir is 2 or 3, flip is true, otherwise false
var flip = (entity.dir === 2 || entity.dir === 3);
if (flip) {
drawImageFlipped(ctx, texture, screenX, screenY, scale.width, scale.height);
}
else {
ctx.drawImage(texture, screenX, screenY, scale.width, scale.height);
}
var under = getTile(Math.round(entity.x), Math.round(entity.y));
if (tileTypes[under.id].type == "liquid") {
//drawQueue.overlays.push([under,entity.x,entity.y]);
}
}
window.addEventListener('load', function() {
let canvas = document.getElementById("gameCanvas");
let ctx = canvas.getContext('2d');
canvas.oncontextmenu=function(){return false;};
canvas.style.backgroundImage = "url('textures/sky.png')";
// set tiling to repeat
canvas.style.backgroundRepeat = "repeat";
canvas.style.backgroundSize = "1016px 720px";
// set offset
canvas.style.backgroundPosition = "0px 0px";
// set height and width to fill the screen
canvas.width = Math.floor(window.innerWidth);
canvas.height = Math.floor(window.innerHeight);
// if the width and height arent divisble by 8, make them
if(canvas.width % 8 != 0) {
canvas.width = canvas.width - (canvas.width % 8);
}
if(canvas.height % 8 != 0) {
canvas.height = canvas.height - (canvas.height % 8);
}
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
ctx.imageSmoothingEnabled = false;
updateScale();
// if the app is running in node
isNode = typeof process !== 'undefined';
if (isNode) {
mainPath = process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + '/Library/Application Support' : process.env.HOME + "/.local/share");
path = mainPath + "/sandtiles/" + "gamedata";
fs = require('fs');
function checkFolder(directory) {
// if the path doesn't exist, create it
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
console.log("Created directory: " + directory);
}
}
function writeFile(file, data) {
fs.writeFileSync(file, data);
}
function readFile(file) {
return fs.readFileSync(file, 'utf8');
}
checkFolder(mainPath + "/sandtiles");
checkFolder(path);
checkFolder(path + "/saves");
savePath = path + "/saves/" + worldInfo.dirName;
checkFolder(savePath);
checkFolder(savePath + "/chunks");
// if the world info file doesn't exist, create it
if (!fs.existsSync(path + "/saves/" + worldInfo.dirName + "/worldinfo.json")) {
writeFile(path + "/saves/" + worldInfo.dirName + "/worldinfo.json", JSON.stringify(worldInfo));
}
// if the world info file exists, load it
else {
worldInfo = JSON.parse(readFile(path + "/saves/" + worldInfo.dirName + "/worldinfo.json"));
// loop through default world info, if any of the values are undefined, set them to the default
for (let key in defaultWorldInfo) {
if (worldInfo[key] == undefined) {
worldInfo[key] = defaultWorldInfo[key];
}
}
}
checkFolder(savePath + "/players");
// if the file in players for (player.name).json doesn't exist, create it
if (!fs.existsSync(savePath + "/players/" + player.name + ".json")) {
writeFile(savePath + "/players/" + player.name + ".json", JSON.stringify(player));
}
// if the file in players for (player.name).json exists, load it
else {
player = JSON.parse(readFile(savePath + "/players/" + player.name + ".json"));
// loop through default player, if any of the values are undefined, set them to the default
for (let key in defaultPlayer) {
if (player[key] == undefined) {
player[key] = defaultPlayer[key];
}
}
camera.x = player.x;
camera.y = player.y;
}
}
// when the window is resized, resize the canvas
window.addEventListener('resize', function() {
canvas.width = Math.floor(window.innerWidth);
canvas.height = Math.floor(window.innerHeight);
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
ctx.imageSmoothingEnabled = false;
updateScale();
});
for (let tile in tileTypes) {
// if tileTypes[tile].texture is an array, load each url in the array
loadTexture(tileTypes[tile].texture)
loadTexture(tileTypes[tile].openTexture)
loadTexture(tileTypes[tile].textureList)
if (!tileTypes[tile].type) {
// if the tile type ends in "_floor", set its type to "floor"
if (tile.endsWith("_floor")) {
tileTypes[tile].type = "floor";
}
// otherwise set it to wall
else {
tileTypes[tile].type = "wall";
}
}
}
let extraTextures = ["bumpy_border/e.png","bumpy_border/es.png","bumpy_border/esw.png","bumpy_border/ew.png","bumpy_border/n.png","bumpy_border/ne.png","bumpy_border/nes.png","bumpy_border/nesw.png","bumpy_border/new.png","bumpy_border/none.png","bumpy_border/ns.png","bumpy_border/nsw.png","bumpy_border/nw.png","bumpy_border/s.png","bumpy_border/sw.png","bumpy_border/w.png"]
for (let i = 0; i < extraTextures.length; i++) {
loadTexture(extraTextures[i])
}
for (let entity in entityTypes) {
loadTexture(entityTypes[entity].texture)
loadTexture(entityTypes[entity].textureList)
if (!entityTypes[entity].type) {
entityTypes[entity].type = "entity";
}
}
function loadTexture(texture) {
if (texture === undefined) {return false}
if (!Array.isArray(texture)) {
var texturelist = [texture];
}
else {
var texturelist = texture;
}
for (let i = 0; i < texturelist.length; i++) {
let textureurl = texturelist[i];
// load and cache the "textures/"+tile.texture images
let texture = new Image();
texture.src = "textures/" + textureurl;
textures[textureurl] = texture;
}
return true;
}
for (let avatar in avatars) {
let textureurl = avatars[avatar].texture;
// load and cache the "textures/"+tile.texture images
let texture = new Image();
texture.src = "textures/" + textureurl;
textures[textureurl] = texture;
}
function drawChunk(chunk) {
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
// loop through 1d array chunk.tiles and draw each tile
for (var i = 0; i < CHUNK_SIZE * CHUNK_SIZE; i++) {
var x = (i % CHUNK_SIZE) + chunk.x * CHUNK_SIZE;
var y = Math.floor(i / CHUNK_SIZE) + chunk.y * CHUNK_SIZE;
// if the tile is within the scale, draw it
if (Math.abs(x - player.x) < SCALE * CHUNK_SIZE && Math.abs(y - player.y) < SCALE * CHUNK_SIZE) {
drawTile(chunk.tiles[i], x, y, ctx, false, tileTypes[chunk.tiles[i].id].mask);
}
}
// loop through the chunk.entities array and draw each entity
for (var i = 0; i < chunk.entities.length; i++) {
var entity = chunk.entities[i];
drawQueue.entities.push(entity);
}
}
function drawScreen() {
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
var currentChunk = getChunk(Math.floor(camera.x), Math.floor(camera.y))// || {x:Math.floor(camera.x / CHUNK_SIZE),y:Math.floor(camera.y / CHUNK_SIZE)};
// in a RENDER_DISTANCE by RENDER_DISTANCE grid around currentChunk's x and y, draw each chunk
for (var x = -RENDER_DISTANCE; x <= RENDER_DISTANCE; x++) {
for (var y = -RENDER_DISTANCE; y <= RENDER_DISTANCE; y++) {
var chunk = getChunk(currentChunk.x + x, currentChunk.y + y, true);
drawChunk(chunk);
}
}
for (var chunkCoords in loadedChunks) {
var chunk = loadedChunks[chunkCoords];
// if the chunk is outside the render distance, unloadChunk(chunk.x,chunk.y)
if ((ticks-chunk.loadTime > 100) && (Math.abs(chunk.x - currentChunk.x) > RENDER_DISTANCE || Math.abs(chunk.y - currentChunk.y) > RENDER_DISTANCE)) {
unloadChunk(chunk.x, chunk.y);
//console.log("Unloaded "+chunk.x+","+chunk.y);
}
else { chunkTick(chunk) }
}
/*for (var i = 0; i < drawQueue.bigFloors.length; i++) {
var item = drawQueue.bigFloors[i];
ctx.drawImage(item[0], item[1], item[2], item[3], item[4]);
}
drawQueue.bigFloors = [];*/
// Draw a small square centered at player.x, player.y
//ctx.fillStyle = '#ff0000';
//ctx.fillRect((player.x - camera.x)*TILE_PIXELS+SCREEN_WIDTH_HALF + TILE_PIXELS_HALF/2, (player.y - camera.y)*TILE_PIXELS+SCREEN_HEIGHT_HALF + TILE_PIXELS_HALF/2, TILE_PIXELS_HALF, TILE_PIXELS_HALF);
// draw player
drawAvatar(player.avatar, player.x, player.y, ctx);
// if the tile type of the tile under the player is a liquid, draw the bottom half of the tile with 50% opacity
if (tileTypes[getTile(player.x, player.y).id].type == "liquid") {
ctx.globalAlpha = 0.5;
drawTile(getTile(player.x, player.y), player.x, player.y, ctx, true);
ctx.globalAlpha = 1;
}
if (drawQueue.entities.length) {
// sort the entities by y position
drawQueue.entities.sort(function(a, b) {
return a.y - b.y;
});
for (var i = 0; i < drawQueue.entities.length; i++) {
var entity = drawQueue.entities[i];
drawEntity(entity, ctx);
}
drawQueue.entities = [];
}
if (drawQueue.overlays.length) {
ctx.globalAlpha = 0.5;
for (var i = 0; i < drawQueue.overlays.length; i++) {
var item = drawQueue.overlays[i];
drawTile(item[0], item[1], item[2], ctx, true);
}
ctx.globalAlpha = 1;