rename GameOver to GameTerminated to avoid ambiguity
rename GameOver to GameTerminated to avoid ambiguity

function GameManager(size, InputManager, Actuator, ScoreManager) { function GameManager(size, InputManager, Actuator, ScoreManager) {
this.size = size; // Size of the grid this.size = size; // Size of the grid
this.inputManager = new InputManager; this.inputManager = new InputManager;
this.scoreManager = new ScoreManager; this.scoreManager = new ScoreManager;
this.actuator = new Actuator; this.actuator = new Actuator;
   
this.startTiles = 2; this.startTiles = 2;
   
this.inputManager.on("move", this.move.bind(this)); this.inputManager.on("move", this.move.bind(this));
this.inputManager.on("restart", this.restart.bind(this)); this.inputManager.on("restart", this.restart.bind(this));
this.inputManager.on("keepPlaying", this.keepPlaying.bind(this)); this.inputManager.on("keepPlaying", this.keepPlaying.bind(this));
   
this.setup(); this.setup();
} }
   
// Restart the game // Restart the game
GameManager.prototype.restart = function () { GameManager.prototype.restart = function () {
this.actuator.continue(); this.actuator.continue();
this.setup(); this.setup();
}; };
   
// Keep playing after winning // Keep playing after winning
GameManager.prototype.keepPlaying = function () { GameManager.prototype.keepPlaying = function () {
this.keepPlaying = true; this.keepPlaying = true;
this.actuator.continue(); this.actuator.continue();
}; };
   
GameManager.prototype.isGameOver = function () { GameManager.prototype.isGameTerminated = function () {
if (this.over || (this.won && !this.keepPlaying)) { if (this.over || (this.won && !this.keepPlaying)) {
return true; return true;
} else { } else {
return false; return false;
} }
}; };
   
// Set up the game // Set up the game
GameManager.prototype.setup = function () { GameManager.prototype.setup = function () {
this.grid = new Grid(this.size); this.grid = new Grid(this.size);
   
this.score = 0; this.score = 0;
this.over = false; this.over = false;
this.won = false; this.won = false;
this.keepPlaying = false; this.keepPlaying = false;
   
// Add the initial tiles // Add the initial tiles
this.addStartTiles(); this.addStartTiles();
   
// Update the actuator // Update the actuator
this.actuate(); this.actuate();
}; };
   
// Set up the initial tiles to start the game with // Set up the initial tiles to start the game with
GameManager.prototype.addStartTiles = function () { GameManager.prototype.addStartTiles = function () {
for (var i = 0; i < this.startTiles; i++) { for (var i = 0; i < this.startTiles; i++) {
this.addRandomTile(); this.addRandomTile();
} }
}; };
   
// Adds a tile in a random position // Adds a tile in a random position
GameManager.prototype.addRandomTile = function () { GameManager.prototype.addRandomTile = function () {
if (this.grid.cellsAvailable()) { if (this.grid.cellsAvailable()) {
var value = Math.random() < 0.9 ? 2 : 4; var value = Math.random() < 0.9 ? 2 : 4;
var tile = new Tile(this.grid.randomAvailableCell(), value); var tile = new Tile(this.grid.randomAvailableCell(), value);
   
this.grid.insertTile(tile); this.grid.insertTile(tile);
} }
}; };
   
// Sends the updated grid to the actuator // Sends the updated grid to the actuator
GameManager.prototype.actuate = function () { GameManager.prototype.actuate = function () {
if (this.scoreManager.get() < this.score) { if (this.scoreManager.get() < this.score) {
this.scoreManager.set(this.score); this.scoreManager.set(this.score);
} }
   
this.actuator.actuate(this.grid, { this.actuator.actuate(this.grid, {
score: this.score, score: this.score,
over: this.over, over: this.over,
won: this.won, won: this.won,
bestScore: this.scoreManager.get(), bestScore: this.scoreManager.get(),
gameOver: this.isGameOver() terminated: this.isGameTerminated()
}); });
   
}; };
   
// Save all tile positions and remove merger info // Save all tile positions and remove merger info
GameManager.prototype.prepareTiles = function () { GameManager.prototype.prepareTiles = function () {
this.grid.eachCell(function (x, y, tile) { this.grid.eachCell(function (x, y, tile) {
if (tile) { if (tile) {
tile.mergedFrom = null; tile.mergedFrom = null;
tile.savePosition(); tile.savePosition();
} }
}); });
}; };
   
// Move a tile and its representation // Move a tile and its representation
GameManager.prototype.moveTile = function (tile, cell) { GameManager.prototype.moveTile = function (tile, cell) {
this.grid.cells[tile.x][tile.y] = null; this.grid.cells[tile.x][tile.y] = null;
this.grid.cells[cell.x][cell.y] = tile; this.grid.cells[cell.x][cell.y] = tile;
tile.updatePosition(cell); tile.updatePosition(cell);
}; };
   
// Move tiles on the grid in the specified direction // Move tiles on the grid in the specified direction
GameManager.prototype.move = function (direction) { GameManager.prototype.move = function (direction) {
// 0: up, 1: right, 2:down, 3: left // 0: up, 1: right, 2:down, 3: left
var self = this; var self = this;
   
if (this.isGameOver()) return; // Don't do anything if the game's over if (this.isGameTerminated()) return; // Don't do anything if the game's over
   
var cell, tile; var cell, tile;
   
var vector = this.getVector(direction); var vector = this.getVector(direction);
var traversals = this.buildTraversals(vector); var traversals = this.buildTraversals(vector);
var moved = false; var moved = false;
   
// Save the current tile positions and remove merger information // Save the current tile positions and remove merger information
this.prepareTiles(); this.prepareTiles();
   
// Traverse the grid in the right direction and move tiles // Traverse the grid in the right direction and move tiles
traversals.x.forEach(function (x) { traversals.x.forEach(function (x) {
traversals.y.forEach(function (y) { traversals.y.forEach(function (y) {
cell = { x: x, y: y }; cell = { x: x, y: y };
tile = self.grid.cellContent(cell); tile = self.grid.cellContent(cell);
   
if (tile) { if (tile) {
var positions = self.findFarthestPosition(cell, vector); var positions = self.findFarthestPosition(cell, vector);
var next = self.grid.cellContent(positions.next); var next = self.grid.cellContent(positions.next);
   
// Only one merger per row traversal? // Only one merger per row traversal?
if (next && next.value === tile.value && !next.mergedFrom) { if (next && next.value === tile.value && !next.mergedFrom) {
var merged = new Tile(positions.next, tile.value * 2); var merged = new Tile(positions.next, tile.value * 2);
merged.mergedFrom = [tile, next]; merged.mergedFrom = [tile, next];
   
self.grid.insertTile(merged); self.grid.insertTile(merged);
self.grid.removeTile(tile); self.grid.removeTile(tile);
   
// Converge the two tiles' positions // Converge the two tiles' positions
tile.updatePosition(positions.next); tile.updatePosition(positions.next);
   
// Update the score // Update the score
self.score += merged.value; self.score += merged.value;
   
// The mighty 2048 tile // The mighty 2048 tile
if (merged.value === 2048) self.won = true; if (merged.value === 2048) self.won = true;
} else { } else {
self.moveTile(tile, positions.farthest); self.moveTile(tile, positions.farthest);
} }
   
if (!self.positionsEqual(cell, tile)) { if (!self.positionsEqual(cell, tile)) {
moved = true; // The tile moved from its original cell! moved = true; // The tile moved from its original cell!
} }
} }
}); });
}); });
   
if (moved) { if (moved) {
this.addRandomTile(); this.addRandomTile();
   
if (!this.movesAvailable()) { if (!this.movesAvailable()) {
this.over = true; // Game over! this.over = true; // Game over!
} }
   
this.actuate(); this.actuate();
} }
}; };
   
// Get the vector representing the chosen direction // Get the vector representing the chosen direction
GameManager.prototype.getVector = function (direction) { GameManager.prototype.getVector = function (direction) {
// Vectors representing tile movement // Vectors representing tile movement
var map = { var map = {
0: { x: 0, y: -1 }, // up 0: { x: 0, y: -1 }, // up
1: { x: 1, y: 0 }, // right 1: { x: 1, y: 0 }, // right
2: { x: 0, y: 1 }, // down 2: { x: 0, y: 1 }, // down
3: { x: -1, y: 0 } // left 3: { x: -1, y: 0 } // left
}; };
   
return map[direction]; return map[direction];
}; };
   
// Build a list of positions to traverse in the right order // Build a list of positions to traverse in the right order
GameManager.prototype.buildTraversals = function (vector) { GameManager.prototype.buildTraversals = function (vector) {
var traversals = { x: [], y: [] }; var traversals = { x: [], y: [] };
   
for (var pos = 0; pos < this.size; pos++) { for (var pos = 0; pos < this.size; pos++) {
traversals.x.push(pos); traversals.x.push(pos);
traversals.y.push(pos); traversals.y.push(pos);
} }
   
// Always traverse from the farthest cell in the chosen direction // Always traverse from the farthest cell in the chosen direction
if (vector.x === 1) traversals.x = traversals.x.reverse(); if (vector.x === 1) traversals.x = traversals.x.reverse();
if (vector.y === 1) traversals.y = traversals.y.reverse(); if (vector.y === 1) traversals.y = traversals.y.reverse();
   
return traversals; return traversals;
}; };
   
GameManager.prototype.findFarthestPosition = function (cell, vector) { GameManager.prototype.findFarthestPosition = function (cell, vector) {
var previous; var previous;
   
// Progress towards the vector direction until an obstacle is found // Progress towards the vector direction until an obstacle is found
do { do {
previous = cell; previous = cell;
cell = { x: previous.x + vector.x, y: previous.y + vector.y }; cell = { x: previous.x + vector.x, y: previous.y + vector.y };
} while (this.grid.withinBounds(cell) && } while (this.grid.withinBounds(cell) &&
this.grid.cellAvailable(cell)); this.grid.cellAvailable(cell));
   
return { return {
farthest: previous, farthest: previous,
next: cell // Used to check if a merge is required next: cell // Used to check if a merge is required
}; };
}; };
   
GameManager.prototype.movesAvailable = function () { GameManager.prototype.movesAvailable = function () {
return this.grid.cellsAvailable() || this.tileMatchesAvailable(); return this.grid.cellsAvailable() || this.tileMatchesAvailable();
}; };
   
// Check for available matches between tiles (more expensive check) // Check for available matches between tiles (more expensive check)
GameManager.prototype.tileMatchesAvailable = function () { GameManager.prototype.tileMatchesAvailable = function () {
var self = this; var self = this;
   
var tile; var tile;
   
for (var x = 0; x < this.size; x++) { for (var x = 0; x < this.size; x++) {
for (var y = 0; y < this.size; y++) { for (var y = 0; y < this.size; y++) {
tile = this.grid.cellContent({ x: x, y: y }); tile = this.grid.cellContent({ x: x, y: y });
   
if (tile) { if (tile) {
for (var direction = 0; direction < 4; direction++) { for (var direction = 0; direction < 4; direction++) {
var vector = self.getVector(direction); var vector = self.getVector(direction);
var cell = { x: x + vector.x, y: y + vector.y }; var cell = { x: x + vector.x, y: y + vector.y };
   
var other = self.grid.cellContent(cell); var other = self.grid.cellContent(cell);
   
if (other && other.value === tile.value) { if (other && other.value === tile.value) {
return true; // These two tiles can be merged return true; // These two tiles can be merged
} }
} }
} }
} }
} }
   
return false; return false;
}; };
   
GameManager.prototype.positionsEqual = function (first, second) { GameManager.prototype.positionsEqual = function (first, second) {
return first.x === second.x && first.y === second.y; return first.x === second.x && first.y === second.y;
}; };
   
function HTMLActuator() { function HTMLActuator() {
this.tileContainer = document.querySelector(".tile-container"); this.tileContainer = document.querySelector(".tile-container");
this.scoreContainer = document.querySelector(".score-container"); this.scoreContainer = document.querySelector(".score-container");
this.bestContainer = document.querySelector(".best-container"); this.bestContainer = document.querySelector(".best-container");
this.messageContainer = document.querySelector(".game-message"); this.messageContainer = document.querySelector(".game-message");
   
this.score = 0; this.score = 0;
} }
   
HTMLActuator.prototype.actuate = function (grid, metadata) { HTMLActuator.prototype.actuate = function (grid, metadata) {
var self = this; var self = this;
   
window.requestAnimationFrame(function () { window.requestAnimationFrame(function () {
self.clearContainer(self.tileContainer); self.clearContainer(self.tileContainer);
   
grid.cells.forEach(function (column) { grid.cells.forEach(function (column) {
column.forEach(function (cell) { column.forEach(function (cell) {
if (cell) { if (cell) {
self.addTile(cell); self.addTile(cell);
} }
}); });
}); });
   
self.updateScore(metadata.score); self.updateScore(metadata.score);
self.updateBestScore(metadata.bestScore); self.updateBestScore(metadata.bestScore);
   
if (metadata.gameOver) { if (metadata.terminated) {
if (metadata.over) self.message(false); // You lose if (metadata.over) {
else if (metadata.won) self.message(true); // You win! self.message(false); // You lose
  } else if (metadata.won) {
  self.message(true); // You win!
  }
} }
   
}); });
}; };
   
// Continues the game (both restart and keep playing) // Continues the game (both restart and keep playing)
HTMLActuator.prototype.continue = function () { HTMLActuator.prototype.continue = function () {
this.clearMessage(); this.clearMessage();
}; };
   
HTMLActuator.prototype.clearContainer = function (container) { HTMLActuator.prototype.clearContainer = function (container) {
while (container.firstChild) { while (container.firstChild) {
container.removeChild(container.firstChild); container.removeChild(container.firstChild);
} }
}; };
   
HTMLActuator.prototype.addTile = function (tile) { HTMLActuator.prototype.addTile = function (tile) {
var self = this; var self = this;
   
var wrapper = document.createElement("div"); var wrapper = document.createElement("div");
var inner = document.createElement("div"); var inner = document.createElement("div");
var position = tile.previousPosition || { x: tile.x, y: tile.y }; var position = tile.previousPosition || { x: tile.x, y: tile.y };
var positionClass = this.positionClass(position); var positionClass = this.positionClass(position);
   
// We can't use classlist because it somehow glitches when replacing classes // We can't use classlist because it somehow glitches when replacing classes
var classes = ["tile", "tile-" + tile.value, positionClass]; var classes = ["tile", "tile-" + tile.value, positionClass];
   
if (tile.value > 2048) classes.push("tile-gold"); if (tile.value > 2048) classes.push("tile-gold");
   
this.applyClasses(wrapper, classes); this.applyClasses(wrapper, classes);
   
inner.classList.add("tile-inner"); inner.classList.add("tile-inner");
inner.textContent = tile.value; inner.textContent = tile.value;
   
if (tile.previousPosition) { if (tile.previousPosition) {
// Make sure that the tile gets rendered in the previous position first // Make sure that the tile gets rendered in the previous position first
window.requestAnimationFrame(function () { window.requestAnimationFrame(function () {
classes[2] = self.positionClass({ x: tile.x, y: tile.y }); classes[2] = self.positionClass({ x: tile.x, y: tile.y });
self.applyClasses(wrapper, classes); // Update the position self.applyClasses(wrapper, classes); // Update the position
}); });
} else if (tile.mergedFrom) { } else if (tile.mergedFrom) {
classes.push("tile-merged"); classes.push("tile-merged");
this.applyClasses(wrapper, classes); this.applyClasses(wrapper, classes);
   
// Render the tiles that merged // Render the tiles that merged
tile.mergedFrom.forEach(function (merged) { tile.mergedFrom.forEach(function (merged) {
self.addTile(merged); self.addTile(merged);
}); });
} else { } else {
classes.push("tile-new"); classes.push("tile-new");
this.applyClasses(wrapper, classes); this.applyClasses(wrapper, classes);
} }
   
// Add the inner part of the tile to the wrapper // Add the inner part of the tile to the wrapper
wrapper.appendChild(inner); wrapper.appendChild(inner);
   
// Put the tile on the board // Put the tile on the board
this.tileContainer.appendChild(wrapper); this.tileContainer.appendChild(wrapper);
}; };
   
HTMLActuator.prototype.applyClasses = function (element, classes) { HTMLActuator.prototype.applyClasses = function (element, classes) {
element.setAttribute("class", classes.join(" ")); element.setAttribute("class", classes.join(" "));
}; };
   
HTMLActuator.prototype.normalizePosition = function (position) { HTMLActuator.prototype.normalizePosition = function (position) {
return { x: position.x + 1, y: position.y + 1 }; return { x: position.x + 1, y: position.y + 1 };
}; };
   
HTMLActuator.prototype.positionClass = function (position) { HTMLActuator.prototype.positionClass = function (position) {
position = this.normalizePosition(position); position = this.normalizePosition(position);
return "tile-position-" + position.x + "-" + position.y; return "tile-position-" + position.x + "-" + position.y;
}; };
   
HTMLActuator.prototype.updateScore = function (score) { HTMLActuator.prototype.updateScore = function (score) {
this.clearContainer(this.scoreContainer); this.clearContainer(this.scoreContainer);
   
var difference = score - this.score; var difference = score - this.score;
this.score = score; this.score = score;
   
this.scoreContainer.textContent = this.score; this.scoreContainer.textContent = this.score;
   
if (difference > 0) { if (difference > 0) {
var addition = document.createElement("div"); var addition = document.createElement("div");
addition.classList.add("score-addition"); addition.classList.add("score-addition");
addition.textContent = "+" + difference; addition.textContent = "+" + difference;
   
this.scoreContainer.appendChild(addition); this.scoreContainer.appendChild(addition);
} }
}; };
   
HTMLActuator.prototype.updateBestScore = function (bestScore) { HTMLActuator.prototype.updateBestScore = function (bestScore) {
this.bestContainer.textContent = bestScore; this.bestContainer.textContent = bestScore;
}; };
   
HTMLActuator.prototype.message = function (won) { HTMLActuator.prototype.message = function (won) {
var type = won ? "game-won" : "game-over"; var type = won ? "game-won" : "game-over";
var message = won ? "You win!" : "Game over!"; var message = won ? "You win!" : "Game over!";
   
this.messageContainer.classList.add(type); this.messageContainer.classList.add(type);
this.messageContainer.getElementsByTagName("p")[0].textContent = message; this.messageContainer.getElementsByTagName("p")[0].textContent = message;
}; };
   
HTMLActuator.prototype.clearMessage = function () { HTMLActuator.prototype.clearMessage = function () {
// IE only takes one value to remove at a time. // IE only takes one value to remove at a time.
this.messageContainer.classList.remove("game-won"); this.messageContainer.classList.remove("game-won");
this.messageContainer.classList.remove("game-over"); this.messageContainer.classList.remove("game-over");
}; };
   
comments