Select free cell by board engine.
authorOleksandr Gavenko <gavenkoa@gmail.com>
Thu, 02 Jul 2015 03:02:38 +0300
changeset 162 f2c55c5744ab
parent 161 ddc36c6cc097
child 163 87479ae56889
Select free cell by board engine.
board.js
--- a/board.js	Thu Jul 02 01:43:15 2015 +0300
+++ b/board.js	Thu Jul 02 03:02:38 2015 +0300
@@ -989,6 +989,25 @@
     if (brd.da === 0) cnt++; if (brd.db === 0) cnt++; if (brd.dc === 0) cnt++; if (brd.dd === 0) cnt++;
     return cnt;
 }
+BoardObj.indexes = ["aa", "ab", "ac", "ad", "ba", "bb", "bc", "bd", "ca", "cb", "cc", "cd", "da", "db", "dc", "dd"];
+/** Put random value to free cell uniformly. */
+BoardObj.prototype.rnd = function(val) {
+    var brd = this.brd;
+    var idx;
+    var free = 0;
+    for (var i = BoardObj.indexes.length-1; i >= 0; i--) {
+        var idx = BoardObj.indexes[i];
+        if (brd[idx] === 0) {
+            free++;
+            if (Math.random()*free < 1)
+                idx = i;
+        }
+    }
+    if (free === 0)
+        throw new Error('There are no free space...');
+    brd[idx] = val;
+}
+
 BoardObj.scoreLookup = [0]; // [ 0, 4, 16, 48, 128, 320, 768, 1792, 4096, 9216, 20480, 45056, 98304];
 (function() {
     for (var i = 1; i < 16; i++)