Skip to content

Instantly share code, notes, and snippets.

@SilasRodrigues19
Created April 1, 2023 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SilasRodrigues19/fde0dd94f2db61881d81f3d1763c2098 to your computer and use it in GitHub Desktop.
Save SilasRodrigues19/fde0dd94f2db61881d81f3d1763c2098 to your computer and use it in GitHub Desktop.
js/script.js
let canvas = document.getElementById('snake');
let context = canvas.getContext('2d');
let box = 32;
let snake = [];
snake[0] = {
x: 8 * box,
y: 8 * box,
};
let direction = 'right';
let food = {
x: Math.floor(Math.random() * 15 + 1) * box,
y: Math.floor(Math.random() * 15 + 1) * box,
};
const foodImg = new Image();
foodImg.src =
'https://png.pngtree.com/png-vector/20220709/ourmid/pngtree-vector-clip-art-and-illustration-of-red-apple-png-image_5827049.png';
function drawScore() {
context.fillStyle = '#fff';
context.font = '2rem Arial';
context.fillText(snake.length, 2 * box, 1.6 * box);
}
let score = 0; //contador de peças da cobrinha
function criarBG() {
context.fillStyle = 'black';
context.fillRect(0, 0, 16 * box, 16 * box);
}
function criarCobrinha() {
for (i = 0; i < snake.length; i++) {
context.fillStyle = '#FFF';
context.fillRect(snake[i].x, snake[i].y, box, box);
}
}
function drawFood() {
context.drawImage(foodImg, food.x, food.y, box, box);
}
document.addEventListener('keydown', update);
function update(event) {
if (event.keyCode == 37 && direction != 'right') direction = 'left';
if (event.keyCode == 38 && direction != 'down') direction = 'up';
if (event.keyCode == 39 && direction != 'left') direction = 'right';
if (event.keyCode == 40 && direction != 'up') direction = 'down';
}
function iniciarJogo() {
if (snake[0].x > 15 * box && direction == 'right') snake[0].x = 0;
if (snake[0].x < 0 && direction == 'left') snake[0].x = 16 * box;
if (snake[0].y > 15 * box && direction == 'down') snake[0].y = 0;
if (snake[0].y < 0 && direction == 'up') snake[0].y = 16 * box;
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();
drawFood();
drawScore();
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction == 'right') snakeX += box;
if (direction == 'left') snakeX -= box;
if (direction == 'up') snakeY -= box;
if (direction == 'down') snakeY += box;
if (snakeX != food.x || snakeY != food.y) {
snake.pop();
} else {
food.x = Math.floor(Math.random() * 15 + 1) * box;
food.y = Math.floor(Math.random() * 15 + 1) * box;
score++; //incrementa o contador quando a cobrinha ganha uma peça
}
let newHead = {
x: snakeX,
y: snakeY,
};
snake.unshift(newHead);
}
let jogo = setInterval(iniciarJogo, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment