Tend to one direction strategy.
authorOleksandr Gavenko <gavenkoa@gmail.com>
Sat, 04 Jul 2015 00:33:19 -0500
changeset 172 021cd45cb5ef
parent 171 6fce1391c2c0
child 173 865ce4c30bed
Tend to one direction strategy.
2048.html
ai.js
--- a/2048.html	Fri Jul 03 23:45:55 2015 -0500
+++ b/2048.html	Sat Jul 04 00:33:19 2015 -0500
@@ -189,6 +189,10 @@
         <button class="ai">enable</button>
         <h5>bling random</h5>
       </div>
+      <div class="ai wide control" id="ai-always-up">
+        <button class="ai">enable</button>
+        <h5>always up</h5>
+      </div>
       <div class="ai wide control" id="ai-blind-weight-random">
         <button class="ai">enable</button>
         <h5>bling weight random</h5>
@@ -794,6 +798,9 @@
       "ai-blind-random": function() {
         return new ai.BlindRandom(ui.brdEngine);
       },
+      "ai-always-up": function() {
+        return new ai.AlwaysUp(ui.brdEngine);
+      },
       "ai-blind-weight-random": function(aiDom) {
         var cfg = ui.ai.parseCfg(aiDom);
         return new ai.BlindWeightRandom(ui.brdEngine, cfg);
--- a/ai.js	Fri Jul 03 23:45:55 2015 -0500
+++ b/ai.js	Sat Jul 04 00:33:19 2015 -0500
@@ -87,6 +87,51 @@
 
 
 ////////////////////////////////////////////////////////////////
+// Always up AI.
+////////////////////////////////////////////////////////////////
+
+/** Always up AI.
+ * @param {Board} brd  board engine from board.js
+ * @constructor */
+ai.AlwaysUp = function(brd) {
+    this.brd = brd;
+}
+/** Select best direction for next step. */
+ai.AlwaysUp.prototype.analyse = function(brd2d) {
+    var origBrd = new this.brd(brd2d);
+    var nextBrd = new this.brd();
+    var tmpBrd = new this.brd();
+    if (origBrd.canUp())
+        return "up";
+    var canRight = origBrd.right(nextBrd);
+    if (canRight) {
+        var canRightUp = nextBrd.up(tmpBrd);
+        var rightScore = tmpBrd.score();
+    }
+    var canLeft = origBrd.left(nextBrd);
+    if (canLeft) {
+        var canLeftUp = nextBrd.up(tmpBrd);
+        var leftScore = tmpBrd.score();
+    }
+    if (canRight && canLeft) {
+        if (canRightUp && canLeftUp)
+            return (rightScore > leftScore) ? "right": "left";
+        else if (canRightUp)
+            return "right";
+        else
+            return "left";
+    } else if (canRight)
+        return "right";
+    else if (canLeft)
+        return "left";
+    return "down";
+}
+/* Mark that next board will be unrelated to previous, so any stored precompution can be cleared. */
+ai.AlwaysUp.prototype.cleanup = function() { }
+
+
+
+////////////////////////////////////////////////////////////////
 // Blind weight random AI.
 ////////////////////////////////////////////////////////////////