-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.html
92 lines (75 loc) · 2.15 KB
/
snake.html
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
<canvas id="canvas" width="400" height="400"></canvas>
<script>
window.onload = function(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
document.addEventListener("keydown", function(e){
console.log(e.keyCode);
switch(e.keyCode){
case 37:
velX = -1;
velY = 0;
break;
case 38:
velY = -1;
velX = 0;
break;
case 39:
velX = 1;
velY =0;
break;
case 40:
velY = 1;
velX = 0
break;
}
});
setInterval(jogo, 100);
}
positionX = 10;
positionY = 10;
foodX = 15;
foodY = 15;
velX = 0;
velY = 0;
grid = 20;
snake = [];
tam = 5;
function jogo(){
positionX += velX;
positionY +=velY;
console.log(positionX);
if(positionX < 0){
positionX = grid;
}
if(positionX > grid){
positionX = 0;
}
if(positionY < 0){
positionY = grid;
}
if(positionY > grid){
positionY = 0;
}
ctx.fillStyle = "#9aff94";
ctx.fillRect(0,0, canvas.width, canvas.height);
ctx.fillStyle = "black";
for(var i=0; i < snake.length; i ++){
ctx.fillRect(snake[i].x * grid, snake[i].y * grid, grid - 1 , grid - 1);
if(snake[i].x == positionX && snake[i].y == positionY){
tam = 5;
}
}
snake.push({x: positionX, y: positionY});
while(snake.length > tam){
snake.shift();
}
ctx.fillStyle = "red";
ctx.fillRect(foodX* grid, foodY * grid, grid - 1, grid - 1);
if(positionX == foodX && positionY == foodY){
tam++;
foodX = Math.floor(Math.random() * grid);
foodY = Math.floor(Math.random() * grid);
}
}
</script>