sf-a64 / main.js
jordonpeter01's picture
Update main.js
f3dbbad verified
let snakeBody = [];
let food;
let score = 0;
let direction = 'right';
$(document).ready(function() {
initGame();
});
function initGame() {
createFood();
renderGameBoard();
$(document).keydown(function(event) {
switch (event.key) {
case 'ArrowUp':
direction = 'up';
break;
case 'ArrowDown':
direction = 'down';
break;
case 'ArrowLeft':
direction = 'left';
break;
case 'ArrowRight':
direction = 'right';
break;
}
});
setInterval(updateGame, 100);
}
function createFood() {
food = {
x: Math.floor(Math.random() * 20),
y: Math.floor(Math.random() * 20)
};
$('#game-board').append('<div class="food" style="left:'+ food.x * 20 + 'px; top:'+ food.y * 20 + 'px;"></div>');
}
function renderGameBoard() {
$('#game-board').html('');
for (let i = 0; i < snakeBody.length; i++) {
$('#game-board').append('<div class="snake-body" style="left:'+ snakeBody[i].x * 20 + 'px; top:'+ snakeBody[i].y * 20 + 'px;"></div>');
}
}
function updateGame() {
let head = snakeBody[0];
let newHead;
switch (direction) {
case 'up':
newHead = { x: head.x, y: head.y - 1 };
break;
case 'down':
newHead = { x: head.x, y: head.y + 1 };
break;
case 'left':
newHead = { x: head.x - 1, y: head.y };
break;
case 'right':
newHead = { x: head.x + 1, y: head.y };
break;
}
snakeBody.unshift(newHead);
if (checkCollision()) {
gameOver();
} else {
renderGameBoard();
checkFood();
}
}
function checkCollision() {
let head = snakeBody[0];
for (let i = 1; i < snakeBody.length; i++) {
if (head.x === snakeBody[i].x && head.y === snakeBody[i].y) {
return true;
}
}
return false;
}
function checkFood() {
let head = snakeBody[0];
if (head.x === food.x && head.y === food.y) {
score++;
$('#score').text(score);
createFood();
} else {
snakeBody.pop();
}
}
function gameOver() {
alert('Game Over! Your score is '+ score);
initGame();
}