// boot the game and let the ai handle it window.requestAnimationFrame(function () { var gm = new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager); var aiDelay = 80; var aiTimer = null; function getCells() { var cells = []; for (var x = 0; x < 4; x++) { cells[x] = []; for (var y = 0; y < 4; y++) { var t = gm.grid.cells[x][y]; cells[x][y] = t ? t.value : 0; } } return cells; } function doMove() { if (gm.over) { // auto restart after a short pause setTimeout(function () { gm.storageManager.clearGameState(); gm.actuator.continueGame(); gm.setup(); scheduleNext(); }, 1500); return; } // keep going past 2048 if (gm.won && typeof gm.keepPlaying !== "boolean") { gm.keepPlaying(); } else if (gm.won && !gm.keepPlaying) { gm.keepPlaying = true; gm.actuator.continueGame(); } var cells = getCells(); fetch("/api/move", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cells: cells }) }).then(function (r) { return r.json(); }) .then(function (data) { if (data.direction >= 0) { gm.move(data.direction); } scheduleNext(); }) .catch(function () { // server might be busy, retry scheduleNext(); }); } function scheduleNext() { aiTimer = setTimeout(doMove, aiDelay); } // start after a tiny delay so the board renders first setTimeout(function () { scheduleNext(); }, 500); });