implement tile movement
[2048.git] / js / html_actuator.js
blob:a/js/html_actuator.js -> blob:b/js/html_actuator.js
--- a/js/html_actuator.js
+++ b/js/html_actuator.js
@@ -5,13 +5,15 @@
 HTMLActuator.prototype.actuate = function (grid) {
   var self = this;
 
-  this.clearContainer();
+  window.requestAnimationFrame(function () {
+    self.clearContainer();
 
-  grid.cells.forEach(function (column) {
-    column.forEach(function (cell) {
-      if (cell) {
-        self.addTile(cell);
-      }
+    grid.cells.forEach(function (column) {
+      column.forEach(function (cell) {
+        if (cell) {
+          self.addTile(cell);
+        }
+      });
     });
   });
 };
@@ -23,15 +25,36 @@
 };
 
 HTMLActuator.prototype.addTile = function (tile) {
-  var element = document.createElement("div");
+  var self = this;
 
-  var x = tile.x + 1;
-  var y = tile.y + 1;
-  var position = "tile-position-" + x + "-" + y;
+  var element   = document.createElement("div");
+  var position  = tile.previousPosition || { x: tile.x, y: tile.y };
+  positionClass = this.positionClass(position);
 
-  element.classList.add("tile", "tile-" + tile.value, position);
+  element.classList.add("tile", "tile-" + tile.value, positionClass);
   element.textContent = tile.value;
 
   this.tileContainer.appendChild(element);
+
+
+  if (tile.previousPosition) {
+    window.requestAnimationFrame(function () {
+      // console.log( + " === " + positionClass);
+      element.classList.remove(element.classList[2]);
+      element.classList.add(self.positionClass({ x: tile.x, y: tile.y }));
+    });
+  } else {
+    element.classList.add("tile-new");
+  }
+
 };
 
+HTMLActuator.prototype.normalizePosition = function (position) {
+  return { x: position.x + 1, y: position.y + 1 };
+};
+
+HTMLActuator.prototype.positionClass = function (position) {
+  position = this.normalizePosition(position);
+  return "tile-position-" + position.x + "-" + position.y;
+};
+

comments