-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.js
162 lines (94 loc) · 2.59 KB
/
snake.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
143
144
145
const cvs = document.getElementById("snake");
const ctx = cvs.getContext("2d");
const box = 32;
const ground = new Image();
ground.src = "original.jpg";
const foodImg = new Image();
foodImg.src = "çizgili.png";
let dead = new Audio();
let eat = new Audio();
let up = new Audio();
let right = new Audio();
let left = new Audio();
let down = new Audio();
dead.src = "geberik.mp3";
eat.src = "bone.mp3";
up.src = "beam.mp3";
right.src = "beam.mp3";
left.src = "beam.mp3";
down.src = "beam.mp3";
let snake = [];
snake[0] = {
x : 9 * box,
y : 10 * box
};
let food = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
let score = 0;
let d;
document.addEventListener("keydown",direction);
function direction(event){
let key = event.keyCode;
if( key == 37 && d != "RIGHT"){
left.play();
d = "LEFT";
}else if(key == 38 && d != "DOWN"){
d = "UP";
up.play();
}else if(key == 39 && d != "LEFT"){
d = "RIGHT";
right.play();
}else if(key == 40 && d != "UP"){
d = "DOWN";
down.play();
}
}
function collision(head,array){
for(let i = 0; i < array.length; i++){
if(head.x == array[i].x && head.y == array[i].y){
return true;
}
}
return false;
}
function draw(){
ctx.drawImage(ground,0,0);
for( let i = 0; i < snake.length ; i++){
ctx.fillStyle = ( i == 0 )? "red" : "green";
ctx.fillRect(snake[i].x,snake[i].y,box,box);
ctx.strokeStyle = "black";
ctx.strokeRect(snake[i].x,snake[i].y,box,box);
}
ctx.drawImage(foodImg, food.x, food.y);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if( d == "LEFT") snakeX -= box;
if( d == "UP") snakeY -= box;
if( d == "RIGHT") snakeX += box;
if( d == "DOWN") snakeY += box;
if(snakeX == food.x && snakeY == food.y){
score++;
eat.play();
food = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
}else{
snake.pop();
}
let newHead = {
x : snakeX,
y : snakeY
}
if(snakeX < box || snakeX > 17 * box || snakeY < 3*box || snakeY > 17*box || collision(newHead,snake)){
clearInterval(game);
dead.play();
}
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "45px Changa one";
ctx.fillText(score,2*box,1.6*box);
}
let game = setInterval(draw,100);