-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
617 lines (548 loc) · 19.7 KB
/
Copy pathscript.js
File metadata and controls
617 lines (548 loc) · 19.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
// Este é o código completo e funcional para o seu arquivo script.js
(() => {
const TILE = 8;
const MAP_SCALE = 1;
const WATER = 0, LAND = 1;
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const dpr = Math.max(1, Math.min(window.devicePixelRatio || 1, 2));
let w = 0, h = 0;
let terrain, fire;
const humans = [];
const trees = [];
let wood = 0;
// Canvas secundário para o terreno
const terrainCanvas = document.createElement('canvas');
const terrainCtx = terrainCanvas.getContext('2d');
let offsetX = 0, offsetY = 0;
let scale = 1;
let running = true;
let speedMul = 1;
let brushSize = 2;
let mapSize = 600;
let date;
let tool = 'paint_land';
let brushPos = null;
const categoryButtons = document.querySelectorAll('#category-bar button');
const toolPanels = document.querySelectorAll('.tool-panel');
const toolButtons = document.querySelectorAll('.tool-button');
const backButtons = document.querySelectorAll('#back-button');
categoryButtons.forEach(button => {
button.addEventListener('click', () => {
categoryButtons.forEach(btn => btn.classList.remove('active'));
button.classList.add('active');
const category = button.dataset.category;
toolPanels.forEach(panel => panel.classList.remove('active'));
document.getElementById(`panel-${category}`).classList.add('active');
});
});
backButtons.forEach(button => {
button.addEventListener('click', () => {
toolPanels.forEach(panel => panel.classList.remove('active'));
document.getElementById('panel-terrain').classList.add('active');
categoryButtons.forEach(btn => btn.classList.remove('active'));
document.querySelector('[data-category="terrain"]').classList.add('active');
});
});
toolButtons.forEach(button => {
button.addEventListener('click', () => {
toolButtons.forEach(btn => btn.classList.remove('active'));
button.classList.add('active');
tool = button.dataset.tool;
});
});
document.getElementById('brush').addEventListener('input', e => brushSize = +e.target.value);
document.getElementById('speed').addEventListener('input', e => speedMul = +e.target.value);
document.getElementById('pause').addEventListener('click', () => {
running = !running;
document.getElementById('pause').textContent = running ? '⏸️ Pausar' : '▶️ Continuar';
});
document.getElementById('reset').addEventListener('click', resetWorld);
document.getElementById('map-size').addEventListener('change', e => {
mapSize = parseInt(e.target.value);
resize();
});
const timeEl = document.getElementById('time');
const dateEl = document.getElementById('date');
const eraEl = document.getElementById('era');
const infoPanel = document.getElementById('human-info');
const infoName = document.getElementById('info-name');
const infoAge = document.getElementById('info-age');
const infoHP = document.getElementById('info-hp');
const humansCountEl = document.getElementById('humansCount');
const woodCountEl = document.getElementById('woodCount');
class Human {
constructor(x, y) {
this.x = x;
this.y = y;
this.dir = Math.random() * Math.PI * 2;
this.timer = 0;
this.hp = 100;
this.speechCooldown = 0;
this.mate = null;
this.age = 0;
this.name = this.generateName();
this.resources = { wood: 0 };
this.targetTree = null;
this.state = 'wandering';
}
generateName() {
const names = ['Ana', 'João', 'Maria', 'Pedro', 'Sofia', 'Lucas', 'Laura', 'Gabriel'];
return names[Math.floor(Math.random() * names.length)];
}
move(dt) {
if (this.state === 'wandering') {
this.timer -= dt;
if (this.timer <= 0) {
this.timer = 0.2 + Math.random() * 0.6;
this.dir += (Math.random() - 0.5) * 1.5;
}
const speed = 1.2 * speedMul;
const nx = this.x + Math.cos(this.dir) * speed * dt * 6;
const ny = this.y + Math.sin(this.dir) * speed * dt * 6;
const ix = Math.floor(nx), iy = Math.floor(ny);
if (inBounds(ix, iy) && terrain[idx(ix, iy)] > 0.5) { // Ajuste para terreno semi-sólido
this.x = nx;
this.y = ny;
} else {
this.dir += Math.PI * (0.4 + Math.random() * 0.6);
}
} else if (this.state === 'gathering' && this.targetTree) {
const dx = this.targetTree.x - this.x;
const dy = this.targetTree.y - this.y;
this.dir = Math.atan2(dy, dx);
const speed = 1.5 * speedMul;
this.x += Math.cos(this.dir) * speed * dt * 6;
this.y += Math.sin(this.dir) * speed * dt * 6;
if (Math.hypot(dx, dy) < 0.5) {
this.resources.wood += 1;
this.targetTree.isDead = true;
this.state = 'wandering';
wood += 1;
}
}
}
talk() {
if (this.speechCooldown <= 0 && Math.random() < 0.005) {
const speech = document.createElement("div");
speech.className = "speech";
speech.style.left = `${(this.x * TILE * scale) + offsetX}px`;
speech.style.top = `${(this.y * TILE * scale) + offsetY}px`;
const msgs = ["Olá!", "Estou com fome.", "Vamos construir!", "Me apaixonei!", "Que belo dia."];
speech.innerText = msgs[Math.floor(Math.random() * msgs.length)];
document.body.appendChild(speech);
setTimeout(() => speech.remove(), 2000);
this.speechCooldown = 200;
}
this.speechCooldown--;
}
draw(ctx) {
const size = TILE * 0.8;
ctx.fillStyle = this.hp > 50 ? '#f5f5f4' : '#fde047';
ctx.fillRect(this.x * TILE - size / 2, this.y * TILE - size / 2, size, size);
}
}
class Tree {
constructor(x, y) {
this.x = x;
this.y = y;
this.growth = 0;
this.age = 0;
this.isDead = false;
}
grow(dt) {
this.age += dt * 0.1 * speedMul;
if (this.age > 10 && this.growth < 3) {
this.growth++;
this.age = 0;
}
}
draw(ctx) {
if(this.isDead) return;
let color = '#006400';
let size = TILE * 0.3;
if (this.growth === 1) size = TILE * 0.4;
if (this.growth === 2) size = TILE * 0.6;
if (this.growth === 3) {
size = TILE * 0.8;
color = '#004d00';
}
ctx.fillStyle = color;
ctx.fillRect(this.x * TILE - size / 2, this.y * TILE - size / 2, size, size);
ctx.fillStyle = '#8B4513';
ctx.fillRect(this.x * TILE - TILE * 0.1, this.y * TILE, TILE * 0.2, TILE * 0.5);
}
}
class Raindrop {
constructor() {
this.x = Math.random() * w * TILE;
this.y = Math.random() * h * TILE;
this.speed = 4 + Math.random() * 4;
this.length = 10;
}
fall() {
this.y += this.speed;
if (this.y > h * TILE) {
this.y = -this.length;
this.x = Math.random() * w * TILE;
}
}
draw(ctx) {
ctx.strokeStyle = "rgba(173,216,230,0.7)";
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x, this.y + this.length);
ctx.stroke();
}
}
const rain = [];
for (let i = 0; i < 200; i++) rain.push(new Raindrop());
function resize() {
const vw = Math.floor(window.innerWidth);
const vh = Math.floor(window.innerHeight);
canvas.width = Math.floor(vw * dpr);
canvas.height = Math.floor(vh * dpr);
canvas.style.width = vw + 'px';
canvas.style.height = vh + 'px';
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
w = Math.floor(mapSize / MAP_SCALE);
h = Math.floor(mapSize / MAP_SCALE);
terrain = new Float32Array(w * h); // Alterado para Float32Array para valores decimais
fire = new Uint8Array(w * h);
// Configura o canvas do terreno
terrainCanvas.width = w * TILE;
terrainCanvas.height = h * TILE;
generateIslands();
}
window.addEventListener('resize', resize);
resize();
function idx(x, y) { return y * w + x; }
function inBounds(x, y) { return x >= 0 && y >= 0 && x < w && y < h; }
function generateIslands() {
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const dxc = (x - w / 2) / (w / 2);
const dyc = (y - h / 2) / (h / 2);
const r = Math.hypot(dxc, dyc);
const n = Math.random() * 0.15 - 0.075;
const v = (0.7 - r) + n;
terrain[idx(x, y)] = v > 0 ? 1 : 0;
}
}
humans.length = 0;
drawTerrain(); // Renderiza o mapa após a geração
}
function resetWorld() {
generateIslands();
fire.fill(0);
humans.length = 0;
trees.length = 0;
wood = 0;
date = new Date(1900, 0, 1, 5, 57, 0);
updateCounts();
}
resetWorld();
let lastPointers = [];
canvas.addEventListener('pointerdown', e => {
e.preventDefault();
canvas.setPointerCapture(e.pointerId);
lastPointers.push(e);
const pos = getMapPos(e);
if (inBounds(Math.floor(pos.x), Math.floor(pos.y))) {
applyTool(pos.x, pos.y);
}
});
canvas.addEventListener('pointermove', e => {
e.preventDefault();
for (let i = 0; i < lastPointers.length; i++) {
if (lastPointers[i].pointerId === e.pointerId) {
lastPointers[i] = e;
break;
}
}
const pos = getMapPos(e);
brushPos = {x: pos.x, y: pos.y};
if (e.buttons === 1 || e.pointerType === 'touch') {
if (inBounds(Math.floor(pos.x), Math.floor(pos.y))) {
applyTool(pos.x, pos.y);
}
}
if (lastPointers.length === 2) {
const [p1, p2] = lastPointers;
const currentDist = Math.hypot(p1.clientX - p2.clientX, p1.clientY - p2.clientY);
if (lastPinchDist === 0) { lastPinchDist = currentDist; return; }
const delta = currentDist - lastPinchDist;
scale += delta * 0.005;
scale = Math.max(0.5, Math.min(2, scale));
lastPinchDist = currentDist;
} else if (lastPointers.length === 1 && e.pointerType === 'mouse' && e.buttons === 1) {
const dx = e.movementX;
const dy = e.movementY;
offsetX += dx;
offsetY += dy;
} else if (lastPointers.length === 1 && e.pointerType === 'touch') {
const dx = e.clientX - (e.prevX || e.clientX);
const dy = e.clientY - (e.prevY || e.clientY);
offsetX += dx;
offsetY += dy;
e.prevX = e.clientX; e.prevY = e.clientY;
}
});
canvas.addEventListener('pointerup', e => {
lastPointers = lastPointers.filter(p => p.pointerId !== e.pointerId);
brushPos = null;
});
function getMapPos(e) {
const rect = canvas.getBoundingClientRect();
const clientX = e.clientX, clientY = e.clientY;
const x = (clientX - rect.left - offsetX) / scale / TILE;
const y = (clientY - rect.top - offsetY) / scale / TILE;
return { x: x, y: y };
}
let lastPinchDist = 0;
function forBrush(cx, cy, r, fn) {
let changed = false;
for (let y = Math.floor(cy - r); y <= Math.ceil(cy + r); y++) {
for (let x = Math.floor(cx - r); x <= Math.ceil(cx + r); x++) {
const dist = Math.hypot(x - cx, y - cy);
if (dist <= r) {
const intensity = 1 - (dist / r);
if (inBounds(x, y)) {
const oldValue = terrain[idx(x, y)];
const newValue = fn(oldValue, intensity);
if (newValue !== oldValue) {
terrain[idx(x, y)] = newValue;
changed = true;
}
}
}
}
}
if (changed) {
drawTerrain();
}
}
function applyTool(x, y) {
if (tool === 'paint_land') {
forBrush(x, y, brushSize, (current, intensity) => {
return Math.min(1, current + 0.1 * intensity);
});
} else if (tool === 'paint_water' || tool === 'erase') {
forBrush(x, y, brushSize, (current, intensity) => {
return Math.max(0, current - 0.1 * intensity);
});
} else {
// Ferramentas que não precisam de suavização
switch (tool) {
case 'paint_all_land': terrain.fill(1); drawTerrain(); break;
case 'paint_all_water': terrain.fill(0); drawTerrain(); break;
case 'spawn_human': if (terrain[idx(Math.floor(x), Math.floor(y))] > 0.5) spawnHuman(x, y); break;
case 'spawn_seed': if (terrain[idx(Math.floor(x), Math.floor(y))] > 0.5) trees.push(new Tree(Math.floor(x), Math.floor(y))); break;
case 'fire': if (terrain[idx(Math.floor(x), Math.floor(y))] > 0.5) fire[idx(Math.floor(x), Math.floor(y))] = 255; break;
case 'rain': if (fire[idx(Math.floor(x), Math.floor(y))] > 0) fire[idx(Math.floor(x), Math.floor(y))] = Math.max(0, fire[idx(Math.floor(x), Math.floor(y))] - 220); break;
}
}
}
// NOVA FUNÇÃO: Desenha o terreno apenas quando necessário
function drawTerrain() {
terrainCtx.clearRect(0, 0, w * TILE, h * TILE);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const c = terrain[idx(x, y)];
const landColor = [22, 101, 52];
const waterColor = [3, 105, 161];
const r = Math.round(waterColor[0] + (landColor[0] - waterColor[0]) * c);
const g = Math.round(waterColor[1] + (landColor[1] - waterColor[1]) * c);
const b = Math.round(waterColor[2] + (landColor[2] - waterColor[2]) * c);
terrainCtx.fillStyle = `rgb(${r},${g},${b})`;
terrainCtx.fillRect(x * TILE, y * TILE, TILE, TILE);
}
}
}
function spawnHuman(x, y) { humans.push(new Human(x, y)); updateCounts(); }
function updateCounts() {
humansCountEl.textContent = `Humanos: ${humans.length}`;
woodCountEl.textContent = `Madeira: ${wood}`;
}
function inspectHuman(x, y) {
let nearestHuman = null;
let minDistance = Infinity;
for (const h of humans) {
const dist = Math.hypot(h.x - x, h.y - y);
if (dist < minDistance) {
minDistance = dist;
nearestHuman = h;
}
}
if (nearestHuman && minDistance < 2) {
infoName.textContent = nearestHuman.name;
infoAge.textContent = Math.floor(nearestHuman.age);
infoHP.textContent = Math.floor(nearestHuman.hp);
infoPanel.style.display = 'block';
} else {
infoPanel.style.display = 'none';
}
}
function stepHumans(dt) {
for (let i = humans.length - 1; i >= 0; i--) {
const h = humans[i];
if (h.state === 'wandering' && h.resources.wood === 0) {
let nearestTree = null;
let minDistance = Infinity;
for (const tree of trees) {
if (!tree.isDead) {
const dist = Math.hypot(h.x - tree.x, h.y - tree.y);
if (dist < minDistance) {
minDistance = dist;
nearestTree = tree;
}
}
}
if (nearestTree && minDistance < 10) {
h.state = 'gathering';
h.targetTree = nearestTree;
}
}
h.move(dt);
h.talk();
const fx = Math.floor(h.x), fy = Math.floor(h.y);
const fval = inBounds(fx, fy) ? fire[idx(fx, fy)] : 0;
if (fval > 0) h.hp -= 25 * dt; else h.hp = Math.min(100, h.hp + 4 * dt);
h.age += 0.001 * speedMul;
if (h.hp <= 0 || h.age > 80 + Math.random() * 20) { humans.splice(i, 1); continue; }
if (h.mate === null && h.age > 18) {
let nearestMate = null;
let minDistance = Infinity;
for (const other of humans) {
if (other !== h && other.mate === null && other.age > 18) {
const dist = Math.hypot(h.x - other.x, h.y - other.y);
if (dist < minDistance) {
minDistance = dist;
nearestMate = other;
}
}
}
if (nearestMate && minDistance < 5) {
h.mate = nearestMate;
nearestMate.mate = h;
}
}
if (h.mate !== null && Math.random() < 0.0001 * speedMul) {
if (h.age > 20 && h.mate.age > 20) {
spawnHuman((h.x + h.mate.x) / 2, (h.y + h.mate.y) / 2);
}
}
}
for (let i = trees.length - 1; i >= 0; i--) {
if (trees[i].isDead) {
trees.splice(i, 1);
}
}
updateCounts();
}
function stepFire(dt) {
const toAdd = [];
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const id = idx(x, y);
const f = fire[id];
if (f > 0) {
fire[id] = Math.max(0, f - (60 * dt));
if (Math.random() < 0.03 * dt * speedMul) {
const nx = x + (Math.random() < 0.5 ? -1 : 1);
const ny = y + (Math.random() < 0.5 ? -1 : 1);
if (inBounds(nx, ny)) {
const nid = idx(nx, ny);
if (terrain[nid] > 0.5 && fire[nid] < 120) { toAdd.push(nid) } // Ajuste para terreno semi-sólido
}
}
}
}
}
for (const id of toAdd) fire[id] = 200;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(offsetX, offsetY);
ctx.scale(scale, scale);
// Desenha o canvas pré-renderizado do terreno
ctx.drawImage(terrainCanvas, 0, 0);
for(const tree of trees) {
tree.draw(ctx);
}
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const f = fire[idx(x, y)];
if (f > 0) {
const a = Math.min(0.8, f / 255);
ctx.fillStyle = `rgba(239,68,68,${a})`;
ctx.fillRect(x * TILE, y * TILE, TILE, TILE);
}
}
}
if (tool === 'rain') {
for (const r of rain) {
r.draw(ctx);
}
}
for (const h of humans) {
h.draw(ctx);
}
if (brushPos && (tool === 'paint_land' || tool === 'paint_water' || tool === 'erase')) {
const radius = brushSize * TILE;
ctx.beginPath();
ctx.arc(brushPos.x * TILE, brushPos.y * TILE, radius, 0, 2 * Math.PI);
ctx.strokeStyle = '#fca5a5';
ctx.lineWidth = 2;
ctx.stroke();
}
ctx.restore();
}
function getEra(year) {
if (year < 500) return "Antiguidade";
if (year < 1500) return "Idade Média";
if (year < 1800) return "Idade Moderna";
if (year < 2100) return "Idade Contemporânea";
return "Futuro";
}
function updateClock(dt) {
const HOURS_PER_SECOND = 1;
const minutesToAdd = dt * HOURS_PER_SECOND * 60 * speedMul;
date.setMinutes(date.getMinutes() + minutesToAdd);
const d = date.getDate();
const m = date.getMonth() + 1;
const y = date.getFullYear();
const h = String(date.getHours()).padStart(2, '0');
const min = String(date.getMinutes()).padStart(2, '0');
eraEl.textContent = `Era: ${getEra(y)}`;
dateEl.textContent = `Data: ${String(d).padStart(2, '0')}/${String(m).padStart(2, '0')}/${y}`;
timeEl.textContent = `Hora: ${h}:${min}`;
}
let last = performance.now();
let fpsEl = document.getElementById('fps');
let fpsTimer = 0, frames = 0;
function frame(now) {
requestAnimationFrame(frame);
const dt = Math.min(0.05, (now - last) / 1000);
last = now;
if (running) {
stepFire(dt);
stepHumans(dt);
trees.forEach(tree => tree.grow(dt));
if (tool === 'rain') {
for(const r of rain) r.fall();
}
updateClock(dt);
}
draw();
frames++;
fpsTimer += dt;
if (fpsTimer >= 0.5) {
fpsEl.textContent = `FPS: ${Math.round(frames / fpsTimer)}`;
fpsTimer = 0;
frames = 0;
}
}
requestAnimationFrame(frame);
})();