forked from vincentinttsh/Snake-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHW4.js
More file actions
115 lines (86 loc) · 2.08 KB
/
Copy pathHW4.js
File metadata and controls
115 lines (86 loc) · 2.08 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
/*
Create by Learn Web Developement
Youtube channel : https://www.youtube.com/channel/UC8n8ftV94ZU_DJLOLtrpORA
*/
const cvs = document.getElementById("snake");
const ctx = cvs.getContext("2d");
// create the unit
const box = 32;
// load images
const ground = new Image();
ground.src = "img/ground.png";
// load audio files
let up = new Audio();
let right = new Audio();
let left = new Audio();
let down = new Audio();
up.src = "audio/up.mp3";
right.src = "audio/right.mp3";
left.src = "audio/left.mp3";
down.src = "audio/down.mp3";
// create the snake
let snake = [];
snake[0] = {
x: Math.floor(Math.random() * 17 + 1) * box,
y: Math.floor(Math.random() * 15 + 3) * box
};
// create the score var
let score = 0;
//control the snake
box_x = -1;
box_y = -1;
// draw everything to the canvas
function draw() {
ctx.drawImage(ground, 0, 0);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i == 0) ? "green" : "white";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "red";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
// old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// move
snakeY += box * box_y
snakeX += box * box_x;
// add new Head
let newHead = {
x: snakeX,
y: snakeY
}
// change direction
let change = false;
if (snakeX < 2 * box) {
box_x *= -1;
score += 5;
left.play();
change = true;
}
if (snakeX > 16 * box) {
box_x *= -1;
score += 5;
right.play();
change = true;
}
if (snakeY < 4 * box) {
box_y *= -1;
score += 5;
up.play();
change = true;
}
if (snakeY > 16 * box) {
box_y *= -1;
score += 5;
down.play();
change = true;
}
if (!change)
snake.pop()
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "45px Changa one";
ctx.fillText(score, 2 * box, 1.6 * box);
}
// call draw function every 100 ms
let game = setInterval(draw, 100);