Boa noite Pessoal,
Estou tentando desenvolver uma versao bem simples do joguinho snake, porém estou travado numa parte, que é a seguinte, eu quero que o usuario tecle pra cima, baixo ou lados e após ele soltar o snake seguir na direcao teclada.Nao estou obetendo exito nesta parte que resumidamente seria a seguinte:
document.addEventListener("keydown", function(e){
delete teclas[e.keyCode];
});
document.addEventListener("keyup", function(e){
teclas[e.keyCode] = true;
});
Segue o Codigo todo:
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style type="text/css">
canvas {
position: absolute;
left: 20%;
top:50%;
background-color:black;
margin-top: -200px;
margin-left: -200px;
}
</style>
</head>
<body>
<canvas id="mycanvas" height="400" width="400" >
Atualize seu navegador.
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var teclas = {};
var press_cima = false;
var press_baixo = false;
var press_esquerdo= false;
var press_direito = false;
var snake = {
x:canvas.width/2 - 8,
y:canvas.height/2 -8,
altura:16,
largura:16,
speed:1
}
var food = {
x:0,
y:0,
altura:0,
largura:0
};
document.addEventListener("keydown", function(e){
delete teclas[e.keyCode];
});
document.addEventListener("keyup", function(e){
teclas[e.keyCode] = true;
});
function mover(){
if(39 in teclas){ // DIREITO
if(snake.x < canvas.width-snake.largura)
snake.x += 1;
}else if(37 in teclas){ //ESQUERDO
if(snake.x > 0)
snake.x -= 1;
}else if (40 in teclas) { // BAIXO
if(snake.y < canvas.height-snake.altura)
snake.y += 1;
}else if(38 in teclas){ //CIMA
if(snake.y > 0)
snake.y -= 1;
}
}
function aleatorio() {
food.x = Math.floor(Math.random()*((canvas.width - 8)-(0)+1)+0);
food.y = Math.floor(Math.random()*((canvas.height - 8)-(0)+1)+0);
food.altura = 16;
food.largura = 16;
if(food.x % 2 != 0 || food.y % 2 != 0 ){
aleatorio();
}
}
function colisao() {
// body...
if(snake.x == food.x && snake.y == food.y ){
alert("colidiu");
}
}
function desenha() {
ctx.clearRect(0,0,canvas.width, canvas.height);
mover();
//colisao();
ctx.fillStyle = "white";
ctx.fillRect(snake.x,snake.y,snake.largura,snake.altura);
ctx.fillRect(food.x,food.y,food.largura, food.altura);
}
setInterval(desenha,5);
aleatorio();
</script>
</body>