InicioInfoAprende a crear el juego de la víbora (Snake Game)

Aprende a crear el juego de la víbora (Snake Game)

Info10/22/2013
Muy buenas a todos, espero que estén muy bien, en esta ocasión les mostraré cómo pueden crear el juego de la víbora (o también conocido como Snake Game), para que recuerden los tiempos cuando todavía los celulares sólo eran monocromáticos.

Primero necesitan crear un archivo snake.html, el cual tendrá el siguiente código:


<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="snake.js" type="text/javascript"></script>

<style>
.game
{
margin: 0 auto;
width: 450px;
}
</style>
</head>

<body>
<div class="game">
<canvas id="snake" width="450" height="450"></canvas>
</div>
</body>
</html>



Como puedes ver estamos haciendo uso de la librería jQuery v.1.10.1, pero de igual forma puede funcionar en versiones anteriores.

Con ayuda de la etiqueta <canvas> podremos crear nuestro pequeño juego, recuerda que debe tener el id "snake".

Ahora el archivo snake.js, lo grabamos en la misma carpeta y tendrá el siguiente código:


$(document).on('ready', function() {
//Vamos a crear un contexto 2d de nuestro canvas.
var canvas = $("#snake"[0];
var context = canvas.getContext("2d";

//Obtenemos el ancho y alto de nuestro canvas.
var width = $("#snake".width();
var height = $("#snake".height();

//Definimos algunas variables para configurar nuestro juego
var cellWidth = 10;
var d;
var food;
var score;
var level = 1; //1 El nivel más lento, 10 el nivel más rápido.
var background = 'white';
var border = 'black';
var snakeColor = 'black';

//Creamos nuestra víbora
var snake;

//El juego tiene la dirección "right" por defecto y se ejecuta la función paint
//dependiendo el nivel que hayas configurado arriba
function init()
{
d = "right";
createSnake();
createFood();
score = 0;

if(typeof gameLoop != "undefined" {
clearInterval(gameLoop);
}

gameLoop = setInterval(paint, 1000 / level);
}

init();

//Creamos la víbora
function createSnake()
{
var length = 5;
snake = [];

for(var i = length - 1; i >= 0; i--)
{
snake.push({ x: i, y: 0 });
}
}

//Creamos la comida de la víbora de manera aleatoria
function createFood()
{
food = {
x: Math.round(Math.random() * (width - cellWidth) / cellWidth),
y: Math.round(Math.random() * (height - cellWidth) / cellWidth),
};
}

//Dibujamos la víbora
function paint()
{
context.fillStyle = background;
context.fillRect(0, 0, width, height);
context.strokeStyle = border;
context.strokeRect(0, 0, width, height);

var nx = snake[0].x;
var ny = snake[0].y;

if (d == "right" {
nx++;
} else if (d == "left" {
nx--;
} else if (d == "up" {
ny--;
} else if (d == "down" {
ny++;
}

if (nx == -1 || nx == width / cellWidth || ny == -1 || ny == height / cellWidth || checkCollision(nx, ny, snake)) {
init();

return;
}

if(nx == food.x && ny == food.y) {
var tail = {
x: nx,
y: ny
};

score++;

createFood();
} else {
var tail = snake.pop();

tail.x = nx;
tail.y = ny;
}

snake.unshift(tail);

for(var i = 0; i < snake.length; i++) {
var c = snake;

paintCell(c.x, c.y);
}

paintCell(food.x, food.y);

var scoreText = "www.codejobs.biz - Score: " + score;

context.fillText(scoreText, 5, height - 5);
}

//Pintamos la celda
function paintCell(x, y)
{
context.fillStyle = snakeColor;
context.fillRect(x * cellWidth, y * cellWidth, cellWidth, cellWidth);
context.strokeStyle = background;
context.strokeRect(x * cellWidth, y * cellWidth, cellWidth, cellWidth);
}

//Verificiamos si hubo alguna colisión (si la hubo el juego se reinicia)
function checkCollision(x, y, array)
{
for(var i = 0; i < array.length; i++)
{
if(array.x == x && array.y == y) {
return true;
}
}

return false;
}

//Captamos las flechas de nuestro teclado para poder mover a nuestra víbora
$(document).on('keydown', function(e) {
var key = e.which;

if (key == "37" && d != "right" {
d = "left";
} else if (key == "38" && d != "down" {
d = "up";
} else if (key == "39" && d != "left" {
d = "right";
} else if (key == "40" && d != "up" {
d = "down";
}
});
});



Cómo puedes ver el juego es muy sencillo de crear y pueden incluso configurar el nivel, los colores, entre otras cosas. Espero les haya sido de ayuda.
Datos archivados del Taringa! original
0puntos
225visitas
0comentarios
Actividad nueva en Posteamelo
0puntos
2visitas
0comentarios
Dar puntos:

Dejá tu comentario

0/2000

Autor del Post

j
jpmini🇦🇷
Usuario
Puntos0
Posts22
Ver perfil →
PosteameloArchivo Histórico de Taringa! (2004-2017). Preservando la inteligencia colectiva de la internet hispanohablante.

CONTACTO

18 de Septiembre 455, Casilla 52

Chillán, Región de Ñuble, Chile

Solo correo postal

© 2026 Posteamelo.com. No afiliado con Taringa! ni sus sucesores.

Contenido preservado con fines históricos y culturales.