interstellar_website/secret/snake/game.js
2025-01-05 03:20:42 +01:00

100 lines
2.4 KiB
JavaScript

'use strict';
// Get references to the buttons
const upButton = document.getElementById("up");
const downButton = document.getElementById("down");
const leftButton = document.getElementById("left");
const rightButton = document.getElementById("right");
const startButton = document.getElementById("start");
const grid = document.getElementById("grid");
// Game variables
let snake;
let apple;
let gameInterval;
let isGameRunning = false;
// Initialize the game
function initGame() {
document.getElementById('grid').style.display = 'grid';
document.getElementById('title').style.display = 'none';
document.getElementById('description').style.display = 'none';
snake = [{ x: 10, y: 10 }];
apple = spawnApple();
isGameRunning = true;
gameInterval = setInterval(gameLoop, 100);
// Render grid only during initialization
renderGrid();
render();
}
// Game loop
function gameLoop() {
updateSnake();
checkCollisions();
render();
}
// Spawn an apple at a random position
function spawnApple() {
return {
x: Math.floor(Math.random() * 10),
y: Math.floor(Math.random() * 10),
};
}
// Update the snake's position
function updateSnake() {
// Logic to move the snake based on direction
}
// Check for collisions with walls, itself, or apple
function checkCollisions() {
// Logic to check for collisions
}
// Render the game state
function render() {
// Logic to render the snake and apple on the screen
}
// Render the grid
function renderGrid() {
const gridSize = 10;
grid.innerHTML = ''; // Clear the grid first
for (let y = 0; y < gridSize; y++) {
let row = document.createElement('div');
row.classList.add('row');
for (let x = 0; x < gridSize; x++) {
let cell = document.createElement('div');
cell.classList.add('cell');
row.appendChild(cell);
}
grid.appendChild(row);
}
}
// Button event listeners
upButton.addEventListener("click", () => {
// Logic to move the snake up
});
downButton.addEventListener("click", () => {
// Logic to move the snake down
});
leftButton.addEventListener("click", () => {
// Logic to move the snake left
});
rightButton.addEventListener("click", () => {
// Logic to move the snake right
});
startButton.addEventListener("click", () => {
if (!isGameRunning) {
initGame();
}
});