-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
107 lines (88 loc) · 2.32 KB
/
script.js
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
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const box = 32;
const snake = [];
snake[0] = {
x: 8 * box,
y: 8 * box,
};
let direction = "right";
const food = {
x: Math.floor(Math.random() * 15 + 1) * box,
y: Math.floor(Math.random() * 15 + 1) * box,
};
let score = 0;
const movements = {
37: () => {
if (direction != "right") direction = "left";
},
38: () => {
if (direction != "down") direction = "up";
},
39: () => {
if (direction != "left") direction = "right";
},
40: () => {
if (direction != "up") direction = "down";
},
}
function createBackground() {
context.fillStyle = '#000000';
context.fillRect(0, 0, box * 16, box * 16);
}
function createSnake() {
for(let i = 0; i < snake.length; i++) {
context.fillStyle = '#ffffff';
context.fillRect(snake[i].x, snake[i].y, box, box);
}
}
function drawFood() {
context.fillStyle = "red";
context.fillRect(food.x, food.y, box, box);
}
document.addEventListener('keydown', update);
function update(event) {
const move = movements[event.keyCode];
if (move) move();
}
function drawScore() {
context.fillStyle = "#ffffff";
context.font = "16px Helvetica";
context.fillText("Score: "+score, 13 * box, box);
}
function startGame() {
if(snake[0].x > 15 * box && direction === "right") snake[0].x = 0;
if(snake[0].x < 0 && direction === "left") snake[0].x = box * 16;
if(snake[0].y > 15 * box && direction === "down") snake[0].y = 0;
if(snake[0].y < 0 && direction === "up") snake[0].y = box * 16;
for(let i = 1; i < snake.length; i++) {
if(snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
clearInterval(game);
alert("Game Over :(");
}
}
createBackground();
createSnake();
drawFood();
drawScore();
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if(direction === "right") snakeX += box;
if(direction === "left") snakeX -= box;
if(direction === "up") snakeY -= box;
if(direction === "down") snakeY += box;
if (snakeX !== food.x || snakeY !== food.y) {
snake.pop();
}
else {
score += 1;
food.x = Math.floor(Math.random() * 15 + 1) * box;
food.y = Math.floor(Math.random() * 15 + 1) * box;
}
const newHead = {
x: snakeX,
y: snakeY,
};
snake.unshift(newHead);
}
const game = setInterval(startGame, 100);