document.addEventListener("DOMContentLoaded", function() {
// Wait till the browser is ready to render the game (avoids glitches)
window.requestAnimationFrame(function() {
var manager = new GameManager(4, KeyboardInputManager, HTMLActuator);
});
});
function GameManager(size, InputManager, Actuator) {
this.size = size; // Size of the grid
this.inputManager = new InputManager;
this.actuator = new Actuator;
this.startTiles = 2;
this.inputManager.on("move", this.move.bind(this));
this.inputManager.on("restart", this.restart.bind(this));
this.setup();
}
// Restart the game
GameManager.prototype.restart = function() {
this.actuator.restart();
this.setup();
};
// Set up the game
GameManager.prototype.setup = function() {
this.grid = new Grid(this.size);
this.score = 0;
this.over = false;
this.won = false;
// Add the initial tiles
this.addStartTiles();
// Update the actuator
this.actuate();
};
// Set up the initial tiles to start the game with
GameManager.prototype.addStartTiles = function() {
for (var i = 0; i < this.startTiles; i++) {
this.addRandomTile();
}
};
// Adds a tile in a random position
GameManager.prototype.addRandomTile = function() {
if (this.grid.cellsAvailable()) {
var value = Math.random() < 0.9 ? 2 : 4;
var tile = new Tile(this.grid.randomAvailableCell(), value);
this.grid.insertTile(tile);
}
};
// Sends the updated grid to the actuator
GameManager.prototype.actuate = function() {
this.actuator.actuate(this.grid, {
score: this.score,
over: this.over,
won: this.won
});
};
// Save all tile positions and remove merger info
GameManager.prototype.prepareTiles = function() {
this.grid.eachCell(function(x, y, tile) {
if (tile) {
tile.mergedFrom = null;
tile.savePosition();
}
});
};
// Move a tile and its...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.