Border Avoider

Everybody at some point has played the fairly straightforward game of avoid the border of the screen. This seemed like a somewhat simple game to implement after starting some other games that featured functions and objects necessary to give this a go. I had keyboard event listeners in Snake and Moving Square, and I had some basic timing and collision detection in Snake. I also had some recent experience with generating random sequences.

The first step was to set up the borders and find a way to draw them. I initialize the borders with a simple straight line, and ultimately decided to merely draw lines rather than determining a way to create smooth borders. Some basic play-testing revealed cues into how to set the borders to avoid impossible tasks.

move : function() {
    Block.direction = '';
    Block.move();
    newTop = Math.floor(Math.random()*200);
    while (Math.abs(newTop - this.topPoints[this.topPoints.length-1])>40) {
        newTop = Math.floor(Math.random()*300);
    }
    newBottom = Math.floor(Math.random()*300+100);
    while (Math.abs(newBottom - this.bottomPoints[this.bottomPoints.length-1])>40 || 
          Math.abs(newBottom-newTop)<100) {
        newBottom = Math.floor(Math.random()*300+100);
    }
    this.topPoints.shift();
    this.topPoints.push(newTop);
    this.bottomPoints.shift();
    this.bottomPoints.push(newBottom);

The system only updates the last point after taking away the first, and then it redraws the entire border. This section is set up on a timing loop. I settled on a distance required to keep the borders with a big enough gap to avoid, but also realized that each step should not be too large, otherwise it would also be impossible. Quick testing helped me settle on the numbers above.

The timing was very similar to Snake. I wrote a collision detection mechanism to be called each time the borders moved. Instead of wasting lots of time determining how to find the whole area, I decided to just check for front two corners ahead of the line. In reality, all that I needed to do was fine the top point in the y-direction and compare it to the top-right corner of the block. The same approach was used for the bottom-right corner.

function Collision() {
collision = false
// Check top right corner
var xtr = Block.location[0]+20;
var ytr = Block.location[1];
var wallx = Math.floor((Block.location[0]+20)/10); //lower end
var ytWall = Boundries.topPoints[wallx] + 
    (Boundries.topPoints[wallx+1] -Boundries.topPoints[wallx])*(xtr-10*wallx)/10;
if (ytr<ytWall) {
    collision =  true;
    endGame();
} 
// check bottom right corner
var ybr= Block.location[1]+20;
var ybWall = Boundries.bottomPoints[wallx] + 
    (Boundries.bottomPoints[wallx+1]-Boundries.bottomPoints[wallx])*(xtr-10*wallx)/10;
if (ybr>ybWall) {
    collision =  true;
    endGame();
} 
return collision;
}

The whole code is up on jsfiddle right here. The game isn't as fun as Snake or Simon, but it still is playable enough.