-2
After learning Javascript, I created a challenge for myself: remake the "cobrinha game". However, I have a problem: I want that when the snake goes through the food, the food changes places, but it remains in the same place.
//canvas
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = "lightgreen";
ctx.fillRect(0, 0, canvas.width, canvas.height);
//variaveis
let grid = 20;
let size = 5;
let directions = [];
//cobra
let head = {
x: 10,
y: 10,
};
let tail = {
x: 10,
y: 10,
};
//comida
let food = {
x: Math.floor(Math.random() * grid) * grid,
y: Math.floor(Math.random() * grid) * grid,
};
//função principal
function main(e) {
switch (e.keyCode) {
case 37:
head.x--;
directions.push('left');
break;
case 38:
head.y--;
directions.push('up');
break;
case 39:
head.x++;
directions.push('right');
break;
case 40:
head.y++;
directions.push('down');
break;
};
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, grid, grid);
ctx.fillStyle = 'black';
ctx.fillRect(head.x * grid, head.y * grid, grid, grid);
if (directions.length >= size) {
ctx.fillStyle = 'lightgreen';
ctx.fillRect(tail.x * grid, tail.y * grid, grid, grid);
switch (directions.shift()) {
case 'left':
tail.x--;
break;
case 'up':
tail.y--;
break;
case 'right':
tail.x++
break;
case 'down':
tail.y++;
break;
};
};
if (head.x == food.x && head.y == food.y) {
food.x = Math.floor(Math.random() * grid) * grid;
food.y = Math.floor(Math.random() * grid) * grid;
};
};
document.addEventListener('keydown', main);
<!DOCTYPE html>
<html lang="pt-br">
<head>
<title>Jogo da cobrinha</title>
<meta charset="utf-8" />
<meta name="author" content="Tomás Ricardo" />
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>
Hello Thomas, if you put one
console.log(head.x, food.x, head.y, food.y);
before IF will notice that the X and Y values of both are totally different. And the problem with this location difference is because of how you added the objects:ctx.fillRect(food.x, food.y, grid, grid);
ctx.fillRect(head.x * grid, head.y * grid, grid, grid);
– Guilherme Nascimento
Good afternoon, Tomás. Do not add "[Solved]" to the question title. If any answer has solved your problem, just mark the answer as accepted.
– Wallace Maxters