-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgameVisualization.js
More file actions
88 lines (72 loc) · 2.09 KB
/
gameVisualization.js
File metadata and controls
88 lines (72 loc) · 2.09 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
const width = window.innerWidth || document.documentElement.clientWidth;
const height = window.innerHeight || document.documentElement.clientHeight;
const canvas = document.getElementById('game');
const size = 65;
game = new GameSimulation(size);
let pause = true;
let cellSize = Math.floor((height - 50) / size);
if (width < height) {
cellSize = Math.floor((width - 50) / size);
}
const getMousePosition = function(e) {
const mouseX = e.pageX - canvas.offsetLeft;
const mouseY = e.pageY - canvas.offsetTop;
const pos = [0, 0];
pos[1] = Math.floor(mouseX / cellSize);
pos[0] = Math.floor(mouseY / cellSize);
return pos;
}
const canvasSize = cellSize * size;
canvas.width = canvasSize;
canvas.height = canvasSize;
canvas.addEventListener('click', function(e) {
pos = getMousePosition(e);
game.bearEntity(pos[0], pos[1]);
updateCanvas();
}, false);
canvas.addEventListener('auxclick', function(e) {
pos = getMousePosition(e);
game.killEntity(pos[0], pos[1]);
updateCanvas();
}, false);
document.addEventListener('keypress', function(e) {
if (e.key == ' ') {
if (pause) {
pause = false;
} else {
pause = true;
}
} else if (e.key == 'r') {
pause = true;
game.setEntities(game.initEntities());
updateCanvas();
}
})
document.addEventListener('contextmenu', event => event.preventDefault());
const gctx = canvas.getContext('2d');
gctx.strokeRect(0, 0, canvasSize, canvasSize);
const updateCanvas = function() {
gctx.clearRect(0, 0, canvasSize, canvasSize);
gctx.strokeRect(0, 0, canvasSize, canvasSize);
const entities = game.getEntities();
for (var row = 0; row < game.size; row++) {
const startPosY = row * cellSize;
for (var col = 0; col < game.size; col++) {
const startPosX = col * cellSize;
if (entities[row][col]) {
gctx.fillRect(startPosX, startPosY, cellSize, cellSize);
} else {
gctx.strokeRect(startPosX, startPosY, cellSize, cellSize);
}
}
}
};
updateCanvas();
const gameLoop = function() {
if (!pause) {
updateCanvas();
game.update();
}
setTimeout(gameLoop, 300);
}
gameLoop();