2048 JS Remake

The popular mobile game remade using the HTML5 JavaScript Canvas

by Taylor Lopez

HTML

<canvas id="gameBoard"></canvas>

CSS

#gameBoard {
    border: solid black 1px;
}

JavaScript

var board;

function Board()
{
    this.width = 450;
    this.height = 450;
    this.tileHeight = 100;
    this.tileWidth = 100;
    this.paddingX = 10;
    this.paddingY = 10;
    this.canvas = $("#gameBoard")[0];
    this.ctx = this.canvas.getContext('2d');
    this.canvas.width = this.width;
    this.canvas.height = this.height;
    this.canvas.style.width = this.width + "px";
    this.canvas.style.height = this.height + "px";
    this.dataHeight = 4;
    this.dataWidth = 4;
    this.data = new Array(this.dataHeight);
    for (var i = 0; i < this.dataHeight; i++)
        this.data[i] = new Array(this.dataWidth);
    var numStartingTiles = 2;
    for (var i = 0; i < numStartingTiles; i++)
        this.addNewTile();
}
Board.prototype.addNewTile = function()
{
    var openCoordinates = [];
    for (var y = 0; y < this.dataHeight; y++)
        for (var x = 0; x < this.dataWidth; x++)
            if (typeof this.data[y][x] === 'undefined')
                openCoordinates.push({x: x, y: y});
    if (openCoordinates.length === 0)
        return false;
    var newTileIndex = Math.floor(Math.random() * openCoordinates.length);
    this.data[openCoordinates[newTileIndex].y][openCoordinates[newTileIndex].x] = new Tile();
    return true;
};
Board.prototype.toString = function()
{
    var returnString = "";
    
    for (var y = 0; y < this.dataHeight; y++)
    {
        for (var x = 0; x < this.dataWidth; x++)
        {
            returnString += "[";
            returnString += typeof this.data[y][x] === "undefined" ? "0" : this.data[y][x].value;
            returnString += "]";
        }
        returnString += "\n";
    }
    
    return returnString;
};

// TODO: "same" detection logic needs work.

Board.prototype.slideColumn = function(x, dir)
{
    var curColumnVals = [];
    var newColumnVals = [];
    var same = true;
    var foundZero = false;
    
    for (var y = 0; y < this.dataHeight; y++)
        if (typeof this.data[y][x] !== 'undefined' &&...