Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript I've run into a problem trying to make a snake using HTML and java. I've identified the line that causes the error but doesn't know how to fix it.

user36021

New Coder
<!DOCTYPE html>
<html lang="en">
<head>
<--error-->
<script src="index.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{
margin: 0px;
padding: 0px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center:
}
canvas{
box-shadow: black 20px 10px 50px;
}
</style>
<title>Snake</title>
</head>
<body>
<canvas id="game" width="400" height="400"/>


</body>
</html>
Java
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
let speed = 7;
let tileCount = 20;
let tileSize = canvas.width / tileCount - 2;
let headX = 10;
let headY = 10;
let xVelocity=0;
let yVelocity=0;
//game loop
function drawGame(){
clearScreen();
changeSnakePosition();
drawSnake();
setTimeout(drawGame, 1000/ speed);
}
function clearScreen(){
ctx.fillStyle = 'black';
ctx.fillRect(0,0,canvas.width,canvas.height);
}
function drawSnake(){
ctx.fillStyle = 'orange';
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize,tileSize);
}

function changeSnakePosition(){
headX = headX + xVelocity;
headY = headY + yVelocity;
}
document.body.addEventListener('keydown', keyDown);
//up
function keyDown(event){
if(event.keyCode == 38){
yVelocity = -1;
xVelocity = 0;
}
}
//down
function keyDown(event){
if(event.keyCode == 40){
yVelocity = 1;
xVelocity = 0;
}
}
//left
function keyDown(event){
if(event.keyCode == 37){
yVelocity = 0;
xVelocity = -1;
}
}
//right
function keyDown(event){
if(event.keyCode == 39){
yVelocity = 0;
xVelocity = 1;
}
}
drawGame();
 
Oh ok, I hadn't seen that comment. 😅

Is your JS file the name as what you're calling in the html? And is it located in the same folder as you html file?
If yes to both, then I'm not sure why there's an error.

Can you copy and past the error given in the console when you run it in your browser.
 

New Threads

Buy us a coffee!

Back
Top Bottom