From b7476f1f62f9e7c5ff6d32c14617cfa5ecab51af Mon Sep 17 00:00:00 2001 From: Gabriele Cirulli Date: Sat, 8 Mar 2014 13:32:37 +0100 Subject: [PATCH] make actuator properly create html elements --- index.html | 13 +------------ js/game_manager.js | 4 +++- js/html_actuator.js | 37 ++++++++++++++++++++++++++++++------- 3 files changed, 34 insertions(+), 20 deletions(-) diff --git a/index.html b/index.html index 3975e81..263bf72 100644 --- a/index.html +++ b/index.html @@ -46,18 +46,7 @@
-
- 2 -
-
- 4 -
-
- 512 -
-
- 2048 -
+
diff --git a/js/game_manager.js b/js/game_manager.js index 26c73d6..f64660a 100644 --- a/js/game_manager.js +++ b/js/game_manager.js @@ -25,7 +25,9 @@ GameManager.prototype.addStartTiles = function () { // Adds a tile in a random position GameManager.prototype.addRandomTile = function () { - var tile = new Tile(this.grid.randomAvailableCell()); + var value = Math.random() < 0.9 ? 2 : 4; + var tile = new Tile(this.grid.randomAvailableCell(), value); + this.grid.insertTile(tile); }; diff --git a/js/html_actuator.js b/js/html_actuator.js index 25022e8..cd6e2bb 100644 --- a/js/html_actuator.js +++ b/js/html_actuator.js @@ -1,13 +1,36 @@ function HTMLActuator() { - + this.tileContainer = document.getElementsByClassName("tile-container")[0]; } HTMLActuator.prototype.actuate = function (grid) { - // Temporary debug visualizer - grid.cells.forEach(function (row) { - var mapped = row.map(function (tile) { - return tile ? tile.value : " "; - }).join(" | "); - console.log(mapped); + var self = this; + + this.clearContainer(); + + grid.cells.forEach(function (column) { + column.forEach(function (cell) { + if (cell) { + self.addTile(cell); + } + }); }); }; + +HTMLActuator.prototype.clearContainer = function () { + while (this.tileContainer.firstChild) { + this.tileContainer.removeChild(this.tileContainer.firstChild); + } +}; + +HTMLActuator.prototype.addTile = function (tile) { + var element = document.createElement("div"); + + var x = tile.x + 1; + var y = tile.y + 1; + var position = "tile-position-" + x + "-" + y; + + element.classList.add("tile", "tile-" + tile.value, position); + element.textContent = tile.value; + + this.tileContainer.appendChild(element); +}; -- GitLab