-
Notifications
You must be signed in to change notification settings - Fork 0
/
Index.js
142 lines (122 loc) · 2.56 KB
/
Index.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
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
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
class SnakePart {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let speed = 10
let tilecount = 20
let headX = 10
let headY = 10
let titlesize = canvas.width / tilecount - 2;
const snakePart = []
let taillength = 2;
let Vx = 0
let Vy = 0
let Ax = 5;
let Ay = 5;
// main game loop
function drawGame() {
clearscreen()
cheakApplepos()
let result = isgameover()
if(result){
return
}
changeSnakePOS()
DRAWAPPLE()
DrawSnake();
setTimeout(drawGame, 1000 / speed)
}
function cheakApplepos() {
if (Ax === headX && Ay === headY) {
Ax = Math.floor(Math.random() * tilecount)
Ay = Math.floor(Math.random() * tilecount)
taillength += 1;
}
}
function isgameover(){
let gameover = false
if(headX<0){
gameover = true
}
else if(headX===tilecount){
gameover = true
}
else if(headY<0){
gameover = true
}
else if(headY===tilecount){
gameover = true
}
if(gameover){
ctx.fillStyle = "white";
ctx.font = "50px Arial";
ctx.textAlign = "center";
ctx.fillText("Game Over", canvas.width/2, canvas.height/2);
}
return gameover
}
function clearscreen() {
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, canvas.width, canvas.height)
}
function DRAWAPPLE() {
ctx.fillStyle = 'red'
ctx.fillRect(Ax * tilecount, Ay * tilecount, titlesize, titlesize)
}
function DrawSnake() {
ctx.fillStyle = 'orange'
ctx.fillRect(headX * tilecount, headY * tilecount, titlesize, titlesize)
ctx.fillStyle = 'green';
for (let i = 0; i < snakePart.length; i++) {
let part = snakePart[i]
ctx.fillRect(part.x * tilecount, part.y * tilecount, titlesize, titlesize)
}
snakePart.push(new SnakePart(headX, headY))
while (snakePart.length > taillength) {
snakePart.shift();
}
}
function changeSnakePOS() {
headX = headX + Vx;
headY = headY + Vy
}
document.body.addEventListener('keydown', keydown);
function keydown(event) {
switch (event.keyCode) {
case 38:
if (Vy == 1) {
return;
}
Vy = -1;
Vx = 0;
break;
case 37:
if (Vx == 1) {
return;
}
Vy = 0;
Vx = -1;
break;
case 39:
if (Vx == -1) {
return;
}
Vy = 0;
Vx = +1;
break;
case 40:
if (Vy == -1) {
return;
}
Vy = 1;
Vx = 0;
break
default:
break;
}
}
drawGame()