2048

self playing 2048 game

HTML

<body>
    <div id="game1"></div>
    <input type="button" id="next" value="next" />
    <input type="button" id="pause" value="pause" />
    <input type="button" id="run" value="run" />
    <div id="gameOld"></div>
    <div>highest tile:<span class="highesttodate"></span></div>
    <div>longest game:<span class="longesttodate"></span></div>
    <div>total games:<span class="totalgames"></span></div>
</body>

CSS

body {
    margin: 0px;
    padding: 0px;
    background-color:grey;
}

JavaScript

// TODO
// componentise (new fork)
// strategies, best score(weight [culm,moves,comb], random, rotate CW, rotate CCW

// last update
// moved random title logic to after the current move.

$(document).ready( function () {
    var game1 = new Game("game1");
    game1.pause=false;
    game1.highestEver = 0;
    game1.longestEver = 0;
    game1.totalGames = 0;
    var gameOld = new Game("gameOld");
    $('#pause').hide();
    $('#pause').click(function (){
        game1.pause=true;
        $('#pause').hide();
        $('#next').show();
        $('#run').show();
    });
    $('#next').click(function (){
        gameOld.updateDisplay(game1.state);
        if (!game1.next()) {
            alert('GAME OVER');
        }
    });
    $('#run').click(function (){
        $('#pause').show();
        $('#next').hide();
        $('#run').hide();
        run(game1, gameOld);
    });
});

function run(game1, gameOld) {
    gameOld.numberOfMoves=game1.numberOfMoves;
    gameOld.highestTile=game1.highestTile;
    gameOld.lastDirection=game1.lastDirection;
    gameOld.updateDisplay(game1.state);
    if (!game1.next()) {
        if (game1.highestTile>game1.highestEver) {
            game1.highestEver = game1.highestTile;
        }
        if (game1.numberOfMoves>game1.longestEver) {
            game1.longestEver = game1.numberOfMoves;
        }
        $('.highesttodate').text(game1.highestEver );
        $('.longesttodate').text(game1.longestEver );
        if (!game1.pause && game1.totalGames<100) {
            setTimeout(function(){
                run(game1,gameOld);
            }, 5000);  
            game1.totalGames++;
            $('.totalgames').text(game1.totalGames );    
        }
    } else {
        if (!game1.pause) {
            setTimeout(function(){
                run(game1,gameOld);
            }, 50);
        }
    }
}

function Game(elementId) {
    var game = this; // context 
    game.elementId = elementId;
    game.state = [];
    game.lastDirection = '';
  ...