-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
94 lines (74 loc) · 2.29 KB
/
script.js
File metadata and controls
94 lines (74 loc) · 2.29 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
let canvas = document.getElementById("snake");
let context = canvas.getContext("2d");
let box = 32;
let snake = [];
snake[0] = {
x: 8 * box,
y: 8 * box
}
let direcao = "direita";
let comida = [];
comida = {
x: Math.floor(Math.random() * 15 + 1) * box,
y: Math.floor(Math.random() * 15 + 1) * box
}
function criarBG(){
context.fillStyle = "#a6c7a5";
context.fillRect(0, 0, 16 * box, 16 * box);
}
function criarCobrinha(){
for (i=0; i<snake.length; i++) {
context.fillStyle = "green";
context.fillRect(snake[i].x, snake[i].y, box, box);
}
}
//criando a comida
function criarComida() {
context.fillStyle = "red";
context.fillRect(comida.x, comida.y, box, box);
}
//recupera o evento de clique da tecla
document.addEventListener('keydown', update);
function update(evento){
if (evento.keyCode == 37 && direcao != "direita") { direcao = "esquerda"};
if (evento.keyCode == 38 && direcao != "baixo") { direcao = "cima"};
if (evento.keyCode == 39 && direcao != "esquerda") { direcao = "direita"};
if (evento.keyCode == 40 && direcao != "cima") { direcao = "baixo"};
}
function iniciarJogo(){
//criar o limite do campo para ao cruzar, resurgir do lado oposto
if (snake[0].x > 15 * box && direcao == "direita" ) {snake[0].x = 0};
if (snake[0].x < 0 && direcao == "esquerda" ) {snake[0].x = 16 * box};
if (snake[0].y > 15 * box && direcao == "baixo" ) {snake[0].y = 0};
if (snake[0].y < 0 && direcao == "cima" ) {snake[0].y = 16 * box};
//criar choque contra o corpo e game over
for(i = 1; i < snake.length; i++){
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
clearInterval(jogo);
alert("Game Over :(");
}
}
criarBG();
criarCobrinha();
criarComida();
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direcao == "direita") snakeX += box;
if (direcao == "esquerda") snakeX -= box;
if (direcao == "cima") snakeY -= box;
if (direcao == "baixo") snakeY += box;
if (snakeX != comida.x || snakeY != comida.y){
//elimina a "bunda" da cobra para após acrescentar a frente a "cabeça"
snake.pop();
} else {
comida.x = Math.floor(Math.random() * 15 + 1) * box;
comida.y = Math.floor(Math.random() * 15 + 1) * box;
}
//cria a cabeca
let novaCabeca = {
x: snakeX,
y: snakeY
}
snake.unshift(novaCabeca);
}
let jogo = setInterval(iniciarJogo, 100);