Repository navigation
Expand file tree
/
Copy pathworld.js
More file actions
122 lines (105 loc) · 2.18 KB
/
Copy pathworld.js
File metadata and controls
122 lines (105 loc) · 2.18 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
/**
* Beware of the magic numbers!
*/
var W = 512,
H = 416,
TILE = 32,
MAP = {};
function randRange(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
/**
* Generate Top soild
*/
function genTop(map) {
var lastY = 12,
x, y;
//loop over horizontally
for(x = 0; x < 16; ++x) {
if(!map[x]) map[x] = [];
//some varience to the terrain
lastY = (lastY == 12 ? randRange(lastY - 2, lastY) : randRange(lastY - 1, lastY + 1));
for(y = lastY; y < 13; ++y) {
if(y === lastY) {
map[x][y] = 11;
} else {
map[x][y] = 28;
}
}
}
}
/**
* Generate underground
*/
function genMiddle(map, level) {
var x, y, r;
for(x = 0; x < 16; ++x) {
if(!map[x]) map[x] = [];
for(y = 0; y < 13; ++y) {
r = randRange(1, 100);
if(level == 1) {
//choose iron or stone
map[x][y] = (r > 85) ? 15 : 30;
} else if(level == 2) {
if(r > 95) map[x][y] = 5
else if(r > 85) map[x][y] = 10;
else if(r > 70) map[x][y] = 15;
else map[x][y] = 30;
} else if(level == 3) {
map[x][y] = 37;
}
}
}
}
/**
* Generate an empty array
*/
function genAir(map) {
for(var i = 0; i < 16; ++i) {
map[i] = [];
}
}
/**
* Generate a new chunk
*/
this.generate = function(chunkX, chunkY) {
//initialize the giant array
if(!MAP[chunkX+","+chunkY]) MAP[chunkX+","+chunkY] = [];
var chunk = MAP[chunkX+","+chunkY];
//don't generate the sky
if(chunkY < 0) {
genAir(chunk);
return;
}
//on the ground
if(chunkY == 0) {
genTop(chunk);
} //iron and maybe gold
else if(chunkY > 0 && chunkY < 3) {
genMiddle(chunk, 1);
} //diamond, gold and iron
else if(chunkY >= 3 && chunkY < 5) {
genMiddle(chunk, 2);
} //bedrock and lava
else {
genMiddle(chunk, 3);
}
};
this.load = function(chunkX, chunkY) {
//generate if it doesn't exist
if(!MAP[chunkX+","+chunkY]) this.generate(chunkX, chunkY);
return MAP[chunkX+","+chunkY];
}
this.updateBlock = function(key, data) {
if(!MAP[key]) return;
console.log(key, data, MAP[key]);
//if remove
if(data.a === 0) {
if(!MAP[key][data.x]) return;
delete MAP[key][data.x][data.y];
} //if add
else if(data.a === 1) {
if(MAP[key][data.x][data.y]) return;
MAP[key][data.x][data.y] = data.b;
}
}