Skip to content

Instantly share code, notes, and snippets.

@0x796935
Created October 15, 2023 12:42
Show Gist options
  • Save 0x796935/67d216becf7357109e536a774841abf7 to your computer and use it in GitHub Desktop.
Save 0x796935/67d216becf7357109e536a774841abf7 to your computer and use it in GitHub Desktop.
Fix
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
</head>
<body>
<canvas id="canvas" width="480" height="480"></canvas>
<script>
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let rows = 20;
let cols = 20;
let snake = [{x: 19, y:3}];
let food = {x: 4, y: 5};
let cellWidth = canvas.width / cols;
let cellHeight = canvas.height / rows;
let direction = 'LEFT';
let foodCollected = false;
placeFood();
setInterval(gameLoop, 500);
document.addEventListener('keydown', keyDown);
draw();
function draw() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
snake.forEach(part => add(part.x, part.y));
ctx.fillStyle = 'yellow';
add(food.x, food.y); //food
requestAnimationFrame(draw);
}
function placeFood(){
let randomX = Math.floor(Math.random() * cols);
let randomY = Math.floor(Math.random() * rows);
food = {x: randomX, y: randomY};
}
function add(x, y) {
ctx.fillRect(x * cellWidth, y * cellHeight, cellWidth - 1, cellHeight - 1);
}
function shiftsnake() {
for (let i = snake.length - 1; i > 0; i--) {
const part = snake[i];
const lastPart = snake[i - 1];
part.x = lastPart.x;
part.y = lastPart.y;
}
}
function gameLoop() {
// if(foodCollected) {
// snake = [{x: snake[0].x, y: snake[0].y}, ...snake];
// foodCollected = false;
// }
if(foodCollected) {
snake.push({x: snake[snake.length - 1].x, y: snake[snake.length - 1].y});
foodCollected = false;
}
shiftsnake();
if (direction == 'LEFT') {
snake[0].x--;
}
if (direction == 'RIGHT') {
snake[0].x++;
}
if (direction == 'UP') {
snake[0].y--;
}
if (direction == 'DOWN') {
snake[0].y++;
}
if(snake[0].x == food.x && snake[0].y == food.y) {
foodCollected = true;
placeFood();
}
}
function keyDown(e) {
if (e.keyCode == 37) {
direction = 'LEFT';
}
if (e.keyCode == 38) {
direction = 'UP';
}
if (e.keyCode == 39) {
direction = 'RIGHT';
}
if (e.keyCode == 40) {
direction = 'DOWN';
}
}
</script>
</body>
</html>
if(foodCollected) {
snake.push({x: snake[snake.length - 1].x, y: snake[snake.length - 1].y});
foodCollected = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment