cC3B3digo20js20para20un20juego20de20culebras202D
Aquí tienes un ejemplo de código en JavaScript para un juego de culebras 2D:
// Configuración del juego
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const tileSize = 20;
const gameSize = canvas.width / tileSize;
let snake = [{x: 10, y: 10}];
let apple = {x: 5, y: 5};
let direction = "right";
// Función principal del juego
function gameLoop() {
clearCanvas();
moveSnake();
drawSnake();
drawApple();
checkCollision();
setTimeout(gameLoop, 100);
}
// Función para limpiar el canvas
function clearCanvas() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
// Función para mover la serpiente
function moveSnake() {
const head = {x: snake[0].x, y: snake[0].y};
if (direction === "up") head.y--;
if (direction === "down") head.y++;
if (direction === "left") head.x--;
if (direction === "right") head.x++;
snake.unshift(head);
snake.pop();
}
// Función para dibujar la serpiente
function drawSnake() {
snake.forEach((segment) => {
ctx.fillStyle = "green";
ctx.fillRect(segment.x * tileSize, segment.y * tileSize, tileSize, tileSize);
});
}
// Función para dibujar la manzana
function drawApple() {
ctx.fillStyle = "red";
ctx.fillRect(apple.x * tileSize, apple.y * tileSize, tileSize, tileSize);
}
// Función para verificar colisiones
function checkCollision() {
const head = snake[0];
// Verificar colisión con la pared
if (head.x < 0 || head.x === gameSize || head.y < 0 || head.y === gameSize) {
gameOver();
}
// Verificar colisión con la serpiente
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
}
}
// Verificar colisión con la manzana
if (head.x === apple.x && head.y === apple.y) {
snake.push({});
generateApple();
}
}
// Función para generar una nueva manzana
function generateApple() {
apple.x = Math.floor(Math.random() * gameSize);
apple.y = Math.floor(Math.random() * gameSize);
}
// Función para finalizar el juego
function gameOver() {
alert("Game over!");
snake = [{x: 10, y: 10}];
direction = "right";
}
// Event listener para detectar las teclas presionadas
document.addEventListener("keydown", (event) => {
if (event.key === "ArrowUp" && direction !== "down") direction = "up";
if (event.key === "ArrowDown" && direction !== "up") direction = "down";
if (event.key === "ArrowLeft" && direction !== "right") direction = "left";
if (event.key === "ArrowRight" && direction !== "left") direction = "right";
});
// Iniciar el juego
gameLoop();
Este es un ejemplo básico de un juego de culebras 2D en JavaScript. Utiliza el canvas HTML para dibujar los elementos del juego y detectar las teclas presionadas para controlar la dirección de la serpiente. El juego se ejecuta en un bucle principal que se repite cada 100 milisegundos. El objetivo es comer las manzanas sin chocar con la pared o con la serpiente misma
原文地址: https://www.cveoy.top/t/topic/hRVQ 著作权归作者所有。请勿转载和采集!