Tomáš Hobza
Tomáš Hobza

Reputation: 53

javascript - not working for loop

I'm coding Snake Game, but I have an issue.

var ctx = document.getElementById('ctx').getContext('2d');
var canvas = document.getElementById('ctx');

var y = [240, 230, 220];
var x = [240, 240, 240];

var xSpeed = 0;
var ySpeed = 0;

function load() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (p = 0; p < x.length; p++) {
        ctx.fillStyle = "black";
        ctx.fillRect(x[p], y[p], 10, 10);
    }
}

function keyDown() {
    var key = event.keyCode; /*getting keyCode of pressed key*/
    ctx.fillStyle = "black"; /*color of rectangle*/
    switch (key) {
        case 39: //RIGHT
            xSpeed = 10;
            ySpeed = 0;
            break;
        case 37: //LEFT
            xSpeed = -10;
            ySpeed = 0;
            break;
        case 38: //UP
            xSpeed = 0;
            ySpeed = -10;
            break;
        case 40: //DOWN
            xSpeed = 0;
            ySpeed = 10;
            break;
    }
}

function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    if (x[0] >= 490) {
        xSpeed = 0;
    } else if (y[0] >= 490) {
        ySpeed = 0;
    }

    //console.clear();

    y[0] += ySpeed;
    x[0] += xSpeed;

    for (i = x.lenght; i >= 0; i--) {
        y[i] = y[i - 1];
        x[i] = x[i - 1];
        console.log(i);
    }


    for (i = 0; i < x.length; i++) {
        ctx.fillStyle = "black";
        ctx.fillRect(x[i], y[i], 10, 10);
        //console.log("y= " + y[i]);
        //console.log("x= " + x[i]);
    }

    //console.log(xSpeed);
    //console.log(ySpeed);
}

setInterval(update, 500);
<!DOCTYPE html>
<html>

<head>
    <link rel="shortcut icon" href="#">
    <title>The Snake Game</title>
</head>
<style>
    #ctx {
        position: absolute;
        /*it can be fixed too*/
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        /*this to solve "the content will not be cut when the window is smaller than the content":*/
        max-width: 100%;
        max-height: 100%;
        overflow: auto;
    }
</style>

<body onkeydown="keyDown()" onload="load()">
    <center><canvas id="ctx" width="500" height="500" style="border:1px solid black"></canvas></center>
</body>
<script src="script.js"></script>

</html>

The for loop inside of update function is not loggin, so it looks like it's not working.

for (i = x.lenght; i >= 0; i--) {
    y[i] = y[i - 1];
    x[i] = x[i - 1];
    console.log(i);
}

I don't know what I've done wrong, but I think it's just another one stupid mistake. Please don't criticize me so much, I'm just nooby 14 y.o. programmer. Thanks in advice, Tomas ;-)

Upvotes: -1

Views: 61

Answers (2)

Nisarg Shah
Nisarg Shah

Reputation: 14561

var ctx = document.getElementById('ctx').getContext('2d');
var canvas = document.getElementById('ctx');

var y = [240, 230, 220];
var x = [240, 240, 240];

var xSpeed = 0;
var ySpeed = 0;

function load() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (p = 0; p < x.length; p++) {
        ctx.fillStyle = "black";
        ctx.fillRect(x[p], y[p], 10, 10);
    }
}

function keyDown() {
    var key = event.keyCode; /*getting keyCode of pressed key*/
    ctx.fillStyle = "black"; /*color of rectangle*/
    
    // Prevent the snake from going in the reverse direction.
    switch (key) {
        case 39: //RIGHT
            if(xSpeed != -10) {
              xSpeed = 10;
              ySpeed = 0;
            }
            break;
        case 37: //LEFT
            if(xSpeed != 10) {
              xSpeed = -10;
              ySpeed = 0;
            }
            break;
        case 38: //UP
            if(ySpeed != 10) {
              xSpeed = 0;
              ySpeed = -10;
            }
            break;
        case 40: //DOWN
            if(ySpeed != -10) {
              xSpeed = 0;
              ySpeed = 10;
            }
            break;
    }
}

function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    if (x[0] >= 490) {
        xSpeed = 0;
    } else if (y[0] >= 490) {
        ySpeed = 0;
    }

    if((xSpeed + ySpeed) != 0) {
      for(var idx = x.length - 1; idx >= 1; idx--) {
          y[idx] = y[idx - 1];
          x[idx] = x[idx - 1];
      }
    }
    
    y[0] += ySpeed;
    x[0] += xSpeed;
    
    for (i = 0; i < x.length; i++) {
        ctx.fillStyle = "black";
        ctx.fillRect(x[i], y[i], 10, 10);
    }
}

setInterval(update, 500);
<!DOCTYPE html>
<html>

<head>
    <link rel="shortcut icon" href="#">
    <title>The Snake Game</title>
</head>
<style>
    #ctx {
        position: absolute;
        /*it can be fixed too*/
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        /*this to solve "the content will not be cut when the window is smaller than the content":*/
        max-width: 100%;
        max-height: 100%;
        overflow: auto;
    }
</style>

<body onkeydown="keyDown()" onload="load()">
    <center><canvas id="ctx" width="500" height="500" style="border:1px solid black"></canvas></center>
</body>
<script src="script.js"></script>

</html>

I really liked your code, especially for how simple it is! So I have added a slightly improved version here. These are the issues I noticed:

Spoilers

  • In the keyDown function, by adding the condition to check previous speed you can prevent the snake from reversing its direction.

  • In update function you should update the location of x[0] and y[0] only after updating the "tail" elements. Otherwise, you would not have the new location for the x[1] and y[1] element.

  • Also, you might need to put an if condition for (xSpeed + ySpeed) != 0 around the loop that updates the location of the tail elements. This would help ensure that the snake doesn't jumble up into single element before the user interacts with it.

Upvotes: 0

Arrabidas92
Arrabidas92

Reputation: 1153

On a first sight it's just a typing mistake because you wrote x.lenght instead of x.length.

Upvotes: 3

Related Questions