Snake (version 1)

I am finding that my goal to complete something every day leads to a natural drive to finish projects that require a longer amount of time, especially by splitting them into smaller projects. This is exemplified with my projects from yesterday and today. A week ago, I made a jsfiddle to create a canvas element with a square, and allow the user to control the square using the keyboard. I hoped that I would eventually make the popular game "Snake" with it, but that was a task that was a little more challenging than I expected.

After breaking my other computer yesterday, I spent the time while it was backing up finally getting around to generating Snake. More elements started to come together yesterday as I created ways to save drawings in my simple drawing application, so I decided to give Snake another try today. The process was quite iterative and I built small aspects of the program, checked to see that they worked, then built the next component.

The first step was to put all of the move assignments into the Snake object. I also changed the program so that the direction event listener was also located in the Snake object. After setting those parameters, I determined the best way to get the snake to move at a particular speed was to create a setInterval() which called the Snake.move() command after a particular number of milliseconds.

My next challenge was placing the apple and determining the best place to call it. I finally decided that it would become the next head of the snake. In order to do this, I stored the potential future location of the snake, and then checked to see if it was an apple.

        var nextloc = [front[0] + xstep, front[1] + ystep];
    if (nextloc[0]==this.apple[0] && nextloc[1] == this.apple[1]) {
        this.locations.unshift([this.apple[0],this.apple[1]]);
        this.placeApple();
    } else {
        // update and draw the new locations
        // add a new location to the front
        this.locations.unshift(nextloc);
        // delete the location from the end
        this.locations.pop();
    }

This allowed me to avoid an issue where a user would get the apple, then lose because they hit the tail at the same time.

The final decision I made was that the snake could not go back on itself. I ended up solving this problem by only allowing one change of move per turn. This might not be the best option, but it does make it a little easier to code. This is determined by the lastMove variable that is changed each time.

Ultimately, I had a fun time making the game, and this is probably it for now, unless I find another fun way to modify this to make it a little more interesting. This is naturally up as a fiddle here