Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snake Game in Javascript

Tags:

javascript

I'm really new to Javascript, so I decided to create a simple SnakeGame to embed in HTML. However, my code for changing the snake's direction freezes up after a few turns.

Note: I'm running this in an HTML Canvas.

Source:

var Canvas;
var ctx;

var fps = 60;

var x = 0;
var seconds = 0;

var lastLoop;
var thisLoop;
var tempFPS = 0;
var blockList = [];
var DEFAULT_DIRECTION = "Right";

var pendingDirections = [];

function update() {
    x += 1;

    thisLoop = new Date();
    tempFPS = 1000 / (thisLoop - lastLoop);
    lastLoop = thisLoop;
    tempFPS = Math.round(tempFPS*10)/10;

    if (x==10){
        document.getElementById("FPS").innerHTML = ("FPS: " + tempFPS);
    }

    //Rendering
    for (var i = 0; i<blockList.length; i++){
        var block = blockList[i];
        draw(block.x, block.y);
    }

    if (x==5){
        x=0;
        seconds+=1;

        //Updates once per x frames
        moveBlocks();
    }
}

function moveBlocks(){
    if(blockList.length === 0){
        return;
    }


    for (var j = 0; j<pendingDirections.length; j++){
        if (b >= blockList.length -1){
            pendingDirections.shift();

        }else {
            //Iterates through each direction that is pending
            var b = pendingDirections[j].block;
            try{
                blockList[b].direction = pendingDirections[j].direction;
            } catch(err){
                alert(err);
            }
            pendingDirections[j].block++;
        }
    }

    for (var i = 0; i<blockList.length; i++){
        var block = blockList[i];
        clear(block.x, block.y);
        if (block.direction == "Down"){
            block.y += BLOCK_SIZE;
        } else if (block.direction == "Up"){
            block.y -= BLOCK_SIZE;
        } else if (block.direction == "Left"){
            block.x -= BLOCK_SIZE;
        } else if (block.direction == "Right"){
            block.x += BLOCK_SIZE;
        } else {
            alert(block.direction);
        }
        draw(block.x, block.y);
    }
}

function init(){
    lastLoop = new Date();
    window.setInterval(update, 1000/fps);
    Canvas = document.getElementById("Canvas");
    ctx = Canvas.getContext("2d");
}

//The width/height of each block
var BLOCK_SIZE = 30;

//Draws a block
function draw(x, y) {

    ctx.fillStyle = "#000000";
    ctx.fillRect(x,y,BLOCK_SIZE,BLOCK_SIZE);
}

function clear(x,y){
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(x,y,BLOCK_SIZE,BLOCK_SIZE);
}

function processInput(key){
    if (key == 110){
        //n (new)
        newBlock(BLOCK_SIZE*4,0);
        newBlock(BLOCK_SIZE*3,0);
        newBlock(BLOCK_SIZE*2,0);
        newBlock(BLOCK_SIZE*1,0);
        newBlock(0,0);

    } else if (key == 119){
        changeDirection("Up");
    } else if (key == 115){
        changeDirection("Down");
    } else if (key == 97){
        changeDirection("Left");
    } else if (key == 100){
        changeDirection("Right");
    } else if (key==122){
        var pDir = "Pending Directions: ";
        for (var i = 0; i<pendingDirections.length; i++){
            pDir += pendingDirections[i].direction + ", ";
        }
        alert(pDir);
    } else if (key == 120){
        var dir = "Directions: ";   
        for (var j = 0; j<blockList.length; j++){
            dir += blockList[j].direction + ", ";
        }
        alert(dir);
    } else {
        alert("KEY: " +key);
    }
}

function changeDirection(d){
    var LD = blockList[0].direction;
    var valid = false;

    if (d == "Up"){
        if(LD != "Down"){
            valid = true;
        }
    } else if (d == "Down"){
        if(LD != "Up"){
            valid = true;
        }
    } else if (d == "Left"){
        if(LD != "Right"){
            valid = true;
        }
    } else if (d == "Right"){
        if(LD != "Left"){
            valid = true;
        }
    }  

    if (d == LD) { valid = false;}

    if (valid){     
        var dir = {'direction' : d, 'block' : 0};
        pendingDirections.unshift(dir);
    }
}
function newBlock(x, y){
    var block = {'x': x, 'y' : y, 'direction' : DEFAULT_DIRECTION};
    //This works: alert(block['x']);
    draw(x,y);
    blockList.push(block);
}

Thanks

like image 774
michael99man Avatar asked Sep 29 '26 01:09

michael99man


1 Answers

As Evan said, the main issue is how you are handling pending directions.

The issue occurs when you turn twice in rapid succession, which causes two pending directions to be added for the same block. If these aren't handled in the correct order, then the blocks may move in the wrong direction. On every update, only one pending direction for each block is needed, so I redesigned how this is handled to avoid multiple directions on one block during a single update.

Here is the link to it: http://jsbin.com/EkOSOre/5/edit

Notice, when a change in direction is made, the pending direction on the first block is updated, overwriting any existing pending direction.

if (valid) {
    blockList[0].pendingDirection = direction;
}

Then, when an update occurs, the list of blocks is looped through, and the pending direction of the next block is set to be the current direction of the current block.

if(!!nextBlock) {
    nextBlock.pendingDirection = block.direction;
}

If the current block has a pending direction, set the direction to the pending direction.

if(block.pendingDirection !== null) {
    block.direction = block.pendingDirection;
}

Then update the block locations like normal.

You also had various other issues, such as using a variable (b) before it was initialized, and how you caught the null/undefined error (you should just do a check for that situation and handle it appropriately), but this was the main issue with your algorithm.

You'll also want to remove the old blocks when the user hits 'n', because the old one is left, increasing the speed and number of total blocks present.

Good luck with the rest of the game, and good luck learning JavaScript.

like image 121
forgivenson Avatar answered Oct 01 '26 13:10

forgivenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!