refactor grid, gamemanager, tile
refactor grid, gamemanager, tile

file:a/README.md -> file:b/README.md
--- a/README.md
+++ b/README.md
@@ -13,9 +13,7 @@
 
 ### Screenshot
 
-<p align="center">
-  <img src="http://pictures.gabrielecirulli.com/2048-20140309-234100.png" alt="Screenshot"/>
-</p>
+[![Screenshot](http://pictures.gabrielecirulli.com/2048-20140309-234100.png)](http://pictures.gabrielecirulli.com/2048-20140309-234100.png)
 
 That screenshot is fake, by the way. I never reached 2048 :smile:
 

file:a/index.html -> file:b/index.html
--- a/index.html
+++ b/index.html
@@ -22,8 +22,8 @@
         <div class="best-container">0</div>
       </div>
     </div>
-    <p class="game-intro">Join the numbers and get to the <strong>2048 tile!</strong></p>
-
+    <p class="game-intro">Join the numbers and get the <strong>2048 tile!</strong></p>
+    <a class="restart-button">New Game</a>
     <div class="game-container">
       <div class="game-message">
         <p></p>
@@ -83,7 +83,7 @@
   <script src="js/html_actuator.js"></script>
   <script src="js/grid.js"></script>
   <script src="js/tile.js"></script>
-  <script src="js/local_score_manager.js"></script>
+  <script src="js/local_storage_manager.js"></script>
   <script src="js/game_manager.js"></script>
   <script src="js/application.js"></script>
 </body>

--- a/js/application.js
+++ b/js/application.js
@@ -1,5 +1,5 @@
 // Wait till the browser is ready to render the game (avoids glitches)
 window.requestAnimationFrame(function () {
-  new GameManager(4, KeyboardInputManager, HTMLActuator, LocalScoreManager);
+  new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
 });
 

--- a/js/game_manager.js
+++ b/js/game_manager.js
@@ -1,7 +1,7 @@
-function GameManager(size, InputManager, Actuator, ScoreManager) {
+function GameManager(size, InputManager, Actuator, StorageManager) {
   this.size         = size; // Size of the grid
   this.inputManager = new InputManager;
-  this.scoreManager = new ScoreManager;
+  this.storageManager = new StorageManager;
   this.actuator     = new Actuator;
 
   this.startTiles   = 2;
@@ -15,6 +15,7 @@
 
 // Restart the game
 GameManager.prototype.restart = function () {
+  this.storageManager.clearGameState();
   this.actuator.continue();
   this.setup();
 };
@@ -35,15 +36,25 @@
 
 // Set up the game
 GameManager.prototype.setup = function () {
-  this.grid        = new Grid(this.size);
-
-  this.score       = 0;
-  this.over        = false;
-  this.won         = false;
-  this.keepPlaying = false;
-
-  // Add the initial tiles
-  this.addStartTiles();
+  var previousState = this.storageManager.getGameState();
+
+  if (previousState) {
+    this.grid        = new Grid(previousState.grid.size,
+                                previousState.grid.cells); // Reload grid
+    this.score       = previousState.score;
+    this.over        = previousState.over;
+    this.won         = previousState.won;
+    this.keepPlaying = previousState.keepPlaying;
+  } else {
+    this.grid        = new Grid(this.size);
+    this.score       = 0;
+    this.over        = false;
+    this.won         = false;
+    this.keepPlaying = false;
+
+    // Add the initial tiles
+    this.addStartTiles();
+  }
 
   // Update the actuator
   this.actuate();
@@ -68,18 +79,31 @@
 
 // Sends the updated grid to the actuator
 GameManager.prototype.actuate = function () {
-  if (this.scoreManager.get() < this.score) {
-    this.scoreManager.set(this.score);
-  }
+  if (this.storageManager.getBestScore() < this.score) {
+    this.storageManager.setBestScore(this.score);
+  }
+
+  this.storageManager.setGameState(this.serialize());
 
   this.actuator.actuate(this.grid, {
     score:      this.score,
     over:       this.over,
     won:        this.won,
-    bestScore:  this.scoreManager.get(),
+    bestScore:  this.storageManager.getBestScore(),
     terminated: this.isGameTerminated()
   });
 
+};
+
+GameManager.prototype.serialize = function () {
+  return {
+    size:        this.size,
+    grid:        this.grid.serialize(),
+    score:       this.score,
+    over:        this.over,
+    won:         this.won,
+    keepPlaying: this.keepPlaying
+  };
 };
 
 // Save all tile positions and remove merger info

file:a/js/grid.js -> file:b/js/grid.js
--- a/js/grid.js
+++ b/js/grid.js
@@ -1,20 +1,36 @@
-function Grid(size) {
+function Grid(size, previousState) {
   this.size = size;
-
-  this.cells = [];
-
-  this.build();
+  this.cells = previousState ? this.fromState(previousState) : this.empty();
 }
 
 // Build a grid of the specified size
-Grid.prototype.build = function () {
+Grid.prototype.empty = function () {
+  var cells = [];
+
   for (var x = 0; x < this.size; x++) {
-    var row = this.cells[x] = [];
+    var row = cells[x] = [];
 
     for (var y = 0; y < this.size; y++) {
       row.push(null);
     }
   }
+
+  return cells;
+};
+
+Grid.prototype.fromState = function (state) {
+  var cells = [];
+
+  for (var x = 0; x < this.size; x++) {
+    var row = cells[x] = [];
+
+    for (var y = 0; y < this.size; y++) {
+      var tile = state[x][y];
+      row.push(tile ? new Tile(tile.position, tile.value) : null);
+    }
+  }
+
+  return cells;
 };
 
 // Find the first available random position
@@ -83,3 +99,20 @@
          position.y >= 0 && position.y < this.size;
 };
 
+Grid.prototype.serialize = function () {
+  var cellState = [];
+
+  for (var x = 0; x < this.size; x++) {
+    var row = cellState[x] = [];
+
+    for (var y = 0; y < this.size; y++) {
+      row.push(this.cells[x][y] ? this.cells[x][y].serialize() : null);
+    }
+  }
+
+  return {
+    size: this.size,
+    cells: cellState
+  };
+};
+

--- a/js/keyboard_input_manager.js
+++ b/js/keyboard_input_manager.js
@@ -39,16 +39,17 @@
     39: 1, // Right
     40: 2, // Down
     37: 3, // Left
-    75: 0, // vim keybindings
-    76: 1,
-    74: 2,
-    72: 3,
+    75: 0, // Vim up
+    76: 1, // Vim right
+    74: 2, // Vim down
+    72: 3, // Vim left
     87: 0, // W
     68: 1, // D
     83: 2, // S
     65: 3  // A
   };
 
+  // Respond to direction keys
   document.addEventListener("keydown", function (event) {
     var modifiers = event.altKey || event.ctrlKey || event.metaKey ||
                     event.shiftKey;
@@ -59,34 +60,32 @@
         event.preventDefault();
         self.emit("move", mapped);
       }
-
-      if (event.which === 32) self.restart.bind(self)(event);
     }
   });
 
-  var retry = document.querySelector(".retry-button");
-  retry.addEventListener("click", this.restart.bind(this));
-  retry.addEventListener(this.eventTouchend, this.restart.bind(this));
+  // Respond to button presses
+  this.bindButtonPress(".retry-button", this.restart);
+  this.bindButtonPress(".restart-button", this.restart);
+  this.bindButtonPress(".keep-playing-button", this.keepPlaying);
 
-  var keepPlaying = document.querySelector(".keep-playing-button");
-  keepPlaying.addEventListener("click", this.keepPlaying.bind(this));
-  keepPlaying.addEventListener("touchend", this.keepPlaying.bind(this));
-
-  // Listen to swipe events
+  // Respond to swipe events
   var touchStartClientX, touchStartClientY;
   var gameContainer = document.getElementsByClassName("game-container")[0];
 
   gameContainer.addEventListener(this.eventTouchstart, function (event) {
-    if (( !window.navigator.msPointerEnabled && event.touches.length > 1) || event.targetTouches > 1) return;
-    
-    if(window.navigator.msPointerEnabled){
-        touchStartClientX = event.pageX;
-        touchStartClientY = event.pageY;
+    if ((!window.navigator.msPointerEnabled && event.touches.length > 1) ||
+        event.targetTouches > 1) {
+      return; // Ignore if touching with more than 1 finger
+    }
+
+    if (window.navigator.msPointerEnabled) {
+      touchStartClientX = event.pageX;
+      touchStartClientY = event.pageY;
     } else {
-        touchStartClientX = event.touches[0].clientX;
-        touchStartClientY = event.touches[0].clientY;
+      touchStartClientX = event.touches[0].clientX;
+      touchStartClientY = event.touches[0].clientY;
     }
-    
+
     event.preventDefault();
   });
 
@@ -95,15 +94,19 @@
   });
 
   gameContainer.addEventListener(this.eventTouchend, function (event) {
-    if (( !window.navigator.msPointerEnabled && event.touches.length > 0) || event.targetTouches > 0) return;
+    if ((!window.navigator.msPointerEnabled && event.touches.length > 0) ||
+        event.targetTouches > 0) {
+      return; // Ignore if still touching with one or more fingers
+    }
 
     var touchEndClientX, touchEndClientY;
-    if(window.navigator.msPointerEnabled){
-        touchEndClientX = event.pageX;
-        touchEndClientY = event.pageY;
+
+    if (window.navigator.msPointerEnabled) {
+      touchEndClientX = event.pageX;
+      touchEndClientY = event.pageY;
     } else {
-        touchEndClientX = event.changedTouches[0].clientX;
-        touchEndClientY = event.changedTouches[0].clientY;
+      touchEndClientX = event.changedTouches[0].clientX;
+      touchEndClientY = event.changedTouches[0].clientY;
     }
 
     var dx = touchEndClientX - touchStartClientX;
@@ -129,3 +132,9 @@
   this.emit("keepPlaying");
 };
 
+KeyboardInputManager.prototype.bindButtonPress = function (selector, fn) {
+  var button = document.querySelector(selector);
+  button.addEventListener("click", fn.bind(this));
+  button.addEventListener(this.eventTouchend, fn.bind(this));
+};
+

--- a/js/local_score_manager.js
+++ /dev/null
@@ -1,49 +1,1 @@
-window.fakeStorage = {
-  _data: {},
 
-  setItem: function (id, val) {
-    return this._data[id] = String(val);
-  },
-
-  getItem: function (id) {
-    return this._data.hasOwnProperty(id) ? this._data[id] : undefined;
-  },
-
-  removeItem: function (id) {
-    return delete this._data[id];
-  },
-
-  clear: function () {
-    return this._data = {};
-  }
-};
-
-function LocalScoreManager() {
-  this.key     = "bestScore";
-
-  var supported = this.localStorageSupported();
-  this.storage = supported ? window.localStorage : window.fakeStorage;
-}
-
-LocalScoreManager.prototype.localStorageSupported = function () {
-  var testKey = "test";
-  var storage = window.localStorage;
-
-  try {
-    storage.setItem(testKey, "1");
-    storage.removeItem(testKey);
-    return true;
-  } catch (error) {
-    return false;
-  }
-};
-
-LocalScoreManager.prototype.get = function () {
-  return this.storage.getItem(this.key) || 0;
-};
-
-LocalScoreManager.prototype.set = function (score) {
-  this.storage.setItem(this.key, score);
-};
-
-

--- /dev/null
+++ b/js/local_storage_manager.js
@@ -1,1 +1,62 @@
+window.fakeStorage = {
+  _data: {},
 
+  setItem: function (id, val) {
+    return this._data[id] = String(val);
+  },
+
+  getItem: function (id) {
+    return this._data.hasOwnProperty(id) ? this._data[id] : undefined;
+  },
+
+  removeItem: function (id) {
+    return delete this._data[id];
+  },
+
+  clear: function () {
+    return this._data = {};
+  }
+};
+
+function LocalStorageManager() {
+  this.bestScoreKey     = "bestScore";
+  this.gameStateKey     = "gameState";
+
+  var supported = this.localStorageSupported();
+  this.storage = supported ? window.localStorage : window.fakeStorage;
+}
+
+LocalStorageManager.prototype.localStorageSupported = function () {
+  var testKey = "test";
+  var storage = window.localStorage;
+
+  try {
+    storage.setItem(testKey, "1");
+    storage.removeItem(testKey);
+    return true;
+  } catch (error) {
+    return false;
+  }
+};
+
+LocalStorageManager.prototype.getBestScore = function () {
+  return this.storage.getItem(this.bestScoreKey) || 0;
+};
+
+LocalStorageManager.prototype.setBestScore = function (score) {
+  this.storage.setItem(this.bestScoreKey, score);
+};
+
+LocalStorageManager.prototype.getGameState = function () {
+  var stateJSON = this.storage.getItem(this.gameStateKey);
+  return stateJSON ? JSON.parse(stateJSON) : null;
+};
+
+LocalStorageManager.prototype.setGameState = function (gameState) {
+  this.storage.setItem(this.gameStateKey, JSON.stringify(gameState));
+};
+
+LocalStorageManager.prototype.clearGameState = function () {
+  this.storage.removeItem(this.gameStateKey);
+};
+

file:a/js/tile.js -> file:b/js/tile.js
--- a/js/tile.js
+++ b/js/tile.js
@@ -16,3 +16,13 @@
   this.y = position.y;
 };
 
+Tile.prototype.serialize = function () {
+  return {
+    position: {
+      x: this.x,
+      y: this.y
+    },
+    value: this.value
+  };
+};
+

--- a/style/main.css
+++ b/style/main.css
@@ -143,8 +143,21 @@
   100% {
     opacity: 1; } }
 
+.restart-button {
+  display: inline-block;
+  background: #8f7a66;
+  border-radius: 3px;
+  padding: 0 20px;
+  text-decoration: none;
+  color: #f9f6f2;
+  height: 40px;
+  line-height: 42px;
+  display: block;
+  width: 100px;
+  margin: 10px auto 10px auto;
+  text-align: center; }
+
 .game-container {
-  margin-top: 40px;
   position: relative;
   padding: 15px;
   cursor: default;
@@ -516,7 +529,6 @@
     margin-bottom: 10px; }
 
   .game-container {
-    margin-top: 40px;
     position: relative;
     padding: 10px;
     cursor: default;

--- a/style/main.scss
+++ b/style/main.scss
@@ -168,10 +168,17 @@
   line-height: 42px;
 }
 
+.restart-button {
+  @include button;
+  display: block;
+  width: 100px;
+  margin: 10px auto 10px auto;
+  text-align: center;
+}
+
 // Game field mixin used to render CSS at different width
 @mixin game-field {
   .game-container {
-    margin-top: 40px;
     position: relative;
     padding: $grid-spacing;
 

comments