le code ne fonctionne pas
Posté : 03 août 2020, 11:57
Bonjour, c'est toujours relatif au même jeu du serpent. Je ne trouve pas l'erreur qui fait que ça ne marche après avoir suivi et répéter le tuto. Je pense qu'il s'agit d'un nombre impaire de d'accolade dans la 1ière partie du code. J'ai trouvé 12 ouvrantes et 11 fermantes. Avant document.onkeydown =
Le code html reste inchangé :
et le code javascript est :
J'ai une croix rouge à la ligne 100 : document.onkeydown = function.handelKeyDown(e)
Merci d'avance.
Le code html reste inchangé :
Code : Tout sélectionner
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Jeu du serpent</title>
</head>
<body>
<h1>hello</h1>
<script src="script4.js"></script>
</body>
</html>
Code : Tout sélectionner
window.onload = function()
{
var canvasWidth = 900;
var canvasHeight = 600;
var blockSize = 30;
var ctx;
var delay = 100;
var snakee;
init();
function init()
{
var canvas = document.createElement('canvas');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.border = "1px solid";
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
snakee = new Snake([[6,4],[5,4],[4,4]], "right");
refreshCanvas();
}
function refreshCanvas()
{
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
snakee.advance();
snakee.draw();
setTimeout(refreshCanvas,delay);
}
function drawBlock(ctx, position)
{
var x = position[0] * blockSize;
var y = position[1] * blockSize;
ctx.fillRect(x ,y ,blockSize ,blockSize);
}
function Snake(body, direction)
{
this.body = body;
this.direction = direction;
this.draw = function()
{
ctx.save();
ctx.fillStyle = "#ff0000";
for (var i = 0; i < this.body.length; i++)
{
drawBlock(ctx, this.body);
}
ctx.restore();
};
this.advance = function()
{
var nextPosition = this.body[0].slice();
switch(this.direction)
{
case "left":
nextPosition[0]-= 1;
break;
case "right":
nextPosition[0]+= 1;
break;
case "down":
nextPosition[1]+= 1;
break;
case "up":
nextPosition[1]-= 1;
break;
default:
throw("Invalid Direction");
}
this.body.unshift(nextPosition);
this.body.pop();
};
this.setDirection = function(newDirection)
{
var allowedDirections;
switch(this.direction)
{
case "left":
case "right":
allowedDirections = ["up","down"];
break;
case "down":
case "up":
allowedDirections = ["left","right"];
break;
default:
throw("Invalid Direction");
}
if(allowedDirections.indexOf(newDirection) > -1)
{
this.direction = newDirection;
}
};
}
document.onkeydown = function.handelKeyDown(e)
{
var key = e.keyCode;
var newDirection;
switch(key)
{
case 37:
newDirection = "left";
break;
case 38:
newDirection = "up";
break;
case 39:
newDirection = "right";
break;
case 40:
newDirection = "down";
break;
default:
return;
}
snakee.setDirection(newDirection);
}
Merci d'avance.