File size: 1,980 Bytes
b11323b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | // 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);
});
|