-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.js
142 lines (104 loc) · 2.42 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
$(document).ready(function(){
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
var cw = 10;
var d;
var food;
var score;
// create the snake
var snake_array;
function init(){
d = "right";
//create snake
create_snake();
// create food
create_food();
score = 0;
// move the snake every 60ms,,
if(typeof game_loop != "undefined")
clearInterval(game_loop);
game_loop = setInterval(paint, 60);
}
init();
function create_snake(){
var length = 5;
snake_array = [];
for(var i = length-1; i >= 0; i--){
snake_array.push({x:i, y:0});
}
}
function create_food(){
food = {
x: Math.round(Math.random()*(w-cw)/cw),
y: Math.round(Math.random()*(h-cw)/cw)
};
}
// paint the snake
function paint(){
// painting the canvas
ctx.fillStyle = "white";
ctx.fillRect(0,0,w,h);
ctx.strokeStyle = "black";
ctx.strokeRect(0,0,w,h);
// move the snake
var nx = snake_array[0].x;
var ny = snake_array[0].y;
if(d == "right") nx++;
else if(d == "left") nx--;
else if(d == "up") ny--;
else if(d == "down") ny++;
// game over
if(nx == -1 || nx == w/cw || ny == -1 || ny == h/cw){
init();
return;
}
if(nx == food.x && ny == food.y) {
//eat the food
var tail = {x:nx, y:ny};
// hey,,you scored. one
score ++;
//create food
create_food();
}else{
var tail = snake_array.pop();
tail.x = nx;
tail.y = ny;
}
snake_array.unshift(tail);
// draw the snake
for(var i = 0; i < snake_array.length; i++){
var c = snake_array[i];
//paint snake
paint_cell(c.x, c.y);
}
// paint food
paint_cell(food.x, food.y);
//display score
var score_text = "Score: " + score;
ctx.fillText(score_text, 5, h-5);
}
function paint_cell(x, y) {
ctx.fillStyle = "blue";
ctx.fillRect(x*cw, y*cw, cw, cw);
ctx.strokeStyle = "white";
ctx.strokeRect(x*cw, y*cw, cw, cw);
}
function check_collision(x, y, array){
console.log("inside check_collision");
for(var i = 0; i < array.length; i++){
if(array[i].x == x && array[i].y == y)
return true;
}
return false;
}
//set keyboard controlls
$(document).keydown(function(e){
var key = e.which;
if(key == "37" && d != "right") d = "left";
else if(key == "38" && d != "down") d = "up";
else if(key == "39" && d != "left") d = "right";
else if(key == "40" && d != "up") d = "down";
})
})