Make a way to stop statistic gathering.
"use strict";
/** @fileOverview AI modules. */
/** @module */
var ai = {};
/** Directions. @constant */
ai.dirs = ["up", "right", "down", "left"];
/** Possible direction function names. @constant */
ai.canDirs = ["canUp", "canRight", "canDown", "canLeft"];
/** Create empty 'to' if argument missing. */
ai.copyObj = function(from, to) {
if (to == null || typeof to !== "object")
to = {};
if (from == null || typeof from !== "object")
return to;
for (var attr in from) {
if (from.hasOwnProperty(attr))
to[attr] = from[attr];
}
return to;
}
// Each strategy is a function that except current board position as 2d array and context from
// previous call to share state/precomputed values between calls.
////////////////////////////////////////////////////////////////
// Blind random AI.
////////////////////////////////////////////////////////////////
/** Blind random AI.
* @param {Board} brdEngine board engine from board.js
* @constructor */
ai.BlindRandom = function(brdEngine) {
this.brdEngine = brdEngine;
}
ai.BlindRandom.prototype.analyse = function(brd) {
var origBrd = new this.brdEngine(brd);
while (true) {
var rnd = Math.floor(Math.random()*4);
if (origBrd[ai.canDirs[rnd]]())
return ai.dirs[rnd];
}
}
/* Mark that next board will be unrelated to previous, so any stored precompution can be cleared. */
ai.BlindRandom.prototype.cleanup = function() { }
////////////////////////////////////////////////////////////////
// Blind weight random AI.
////////////////////////////////////////////////////////////////
/**
* @name ai.BlindWeightRandom.cfg
* @namespace
* @property {number} left weight
* @property {number} right weight
* @property {number} up weight
* @property {number} down weight
*/
/** Blind weight random AI.
* @param {Board} brdEngine board engine from board.js
* @param {ai.BlindWeightRandom.cfg} cfg configuration settings
* @constructor */
ai.BlindWeightRandom = function(brdEngine, cfg) {
this.brdEngine = brdEngine;
this.cfg = ai.copyObj(ai.BlindWeightRandom.bestCfg);
ai.copyObj(cfg, this.cfg);
var total = this.cfg.left + this.cfg.right + this.cfg.up + this.cfg.down;
this.threshold1 = this.cfg.left/total;
this.threshold2 = (this.cfg.left + this.cfg.down)/total;
this.threshold3 = (this.cfg.left + this.cfg.down + this.cfg.right)/total;
}
ai.BlindWeightRandom.bestCfg = { left: 1, right: 16, up: 4, down: 8 };
ai.BlindWeightRandom.prototype.analyse = function(brd) {
var origBrd = new this.brdEngine(brd);
while (true) {
var rnd = Math.random();
if (rnd < this.threshold1)
var dir = 0;
else if (rnd < this.threshold2)
var dir = 1;
else if (rnd < this.threshold3)
var dir = 2;
else
var dir = 3;
if (origBrd[ai.canDirs[dir]]())
return ai.dirs[dir];
}
}
/* Mark that next board will be unrelated to previous, so any stored precompution can be cleared. */
ai.BlindWeightRandom.prototype.cleanup = function() { }
////////////////////////////////////////////////////////////////
// Blind cycle AI.
////////////////////////////////////////////////////////////////
/**
* @name ai.BlindCycle.cfg
* @namespace
* @property {boolean} whilePossible move in one direction while possible
* @property {boolean} down switch direction clockwise
*/
/** Blind cycle AI.
* @param {Board} brdEngine board engine from board.js
* @param {ai.BlindCycle.cfg} cfg configuration settings
* @constructor */
ai.BlindCycle = function(brdEngine, cfg) {
this.brdEngine = brdEngine;
this.cfg = cfg || {};
this.cfg.whilePossible = this.cfg.whilePossible || false;
this.cfg.clockwise = this.cfg.clockwise || false;
}
ai.BlindCycle.dirs = ["left", "down", "right", "up"];
ai.BlindCycle.canDirs = ["canLeft", "canDown", "canRight", "canUp"];
ai.BlindCycle.prototype.nextDir = function(dir) {
if (this.cfg.clockwise)
return (dir + (4-1)) % 4;
else
return (dir + 1) % 4;
}
ai.BlindCycle.prototype.analyse = function(brd) {
var origBrd = new this.brdEngine(brd);
this.prevDir = this.prevDir || 0;
if (!this.cfg.whilePossible)
this.prevDir = this.nextDir(this.prevDir);
while (true) {
if (origBrd[ai.BlindCycle.canDirs[this.prevDir]]())
return ai.BlindCycle.dirs[this.prevDir];
this.prevDir = this.nextDir(this.prevDir);
}
}
/* Mark that next board will be unrelated to previous, so any stored precompution can be cleared. */
ai.BlindCycle.prototype.cleanup = function() {
delete this.prevDir;
}
////////////////////////////////////////////////////////////////
// 1 step deep with linear weight function on score, max value,
// bonuses for max value stay at corner or edge and bonuses
// for each free field.
////////////////////////////////////////////////////////////////
/**
* Defines coefficient for linear resulted weight function.
* @name ai.OneStepAhead.cfg
* @namespace
* @property {number} scoreCoef multiplicator for score
* @property {number} maxValCoef multiplicator for max value
* @property {number} cornerBonus bonus for max value at board corner
* @property {number} edgeBonus bonus for max value at board edge
* @property {number} freeBonus bonus for each free cell
*/
/** 1 step deep with * AI.
* @param {Board} brdEngine board engine from board.js
* @param {ai.OneStepAhead.cfg} cfg configuration settings
* @constructor */
ai.OneStepAhead = function(brdEngine, cfg) {
this.brdEngine = brdEngine;
this.cfg = ai.copyObj(ai.OneStepAhead.bestCfg);
ai.copyObj(cfg, this.cfg);
}
ai.OneStepAhead.bestCfg = {scoreCoef: 1, maxValCoef: 0, cornerBonus: 0, edgeBonus: 0, freeBonus: 0};
ai.OneStepAhead.prototype.weight = function(brd) {
var weight = 0;
if (this.cfg.scoreCoef > 0)
weight += this.cfg.scoreCoef * brd.score();
var max = brd.max();
if (this.cfg.maxValCoef > 0)
weight += this.cfg.maxValCoef * max;
if (this.cfg.cornerBonus > 0 && brd.atCorner(max))
weight += this.cfg.cornerBonus;
if (this.cfg.edgeBonus > 0 && brd.atEdge(max))
weight += this.cfg.edgeBonus;
if (this.cfg.freeBonus > 0)
weight += this.cfg.freeBonus * brd.free();
return weight;
}
ai.OneStepAhead.prototype.analyse = function(brd) {
var origBrd = new this.brdEngine(brd);
var nextBrd = new this.brdEngine();
var maxWeight = -1;
var bestDir;
for (var i = 0; i < ai.dirs.length; i++) {
var dir = ai.dirs[i];
if (origBrd[dir](nextBrd)) {
var weight = this.weight(nextBrd);
if (maxWeight < weight) {
bestDir = dir;
maxWeight = weight;
}
}
}
return bestDir;
}
/* Mark that next board will be unrelated to previous, so any stored precompution can be cleared. */
ai.OneStepAhead.prototype.cleanup = function() { }
////////////////////////////////////////////////////////////////
// N level deep on score value without random simulation.
////////////////////////////////////////////////////////////////
/**
* Defines coefficient for linear resulted weight function.
* @name ai.StaticDeepMerges.cfg
* @namespace
* @property {number} scoreCoef multiplicator for score
* @property {number} maxValCoef multiplicator for max value
* @property {number} cornerBonus bonus for max value at board corner
* @property {number} edgeBonus bonus for max value at board edge
* @property {number} freeBonus bonus for each free cell
*/
/** Deep merges AI without random simulation.
* @param {Board} brdEngine board engine from board.js
* @param {Object} cfg configuration settings
* @constructor */
ai.StaticDeepMerges = function(brdEngine, cfg) {
this.brdEngine = brdEngine;
this.cfg = ai.copyObj(ai.OneStepAhead.bestCfg);
ai.copyObj(cfg, this.cfg);
}
ai.StaticDeepMerges.bestCfg = {scoreCoef: 1, maxValCoef: 0, cornerBonus: 0, edgeBonus: 0, freeBonus: 0, weightThreshold: 10};
ai.StaticDeepMerges.prototype.weight = function(brd) {
var weight = 0;
if (this.cfg.scoreCoef > 0)
weight += this.cfg.scoreCoef * brd.score();
var max = brd.max();
if (this.cfg.maxValCoef > 0)
weight += this.cfg.maxValCoef * max;
if (this.cfg.cornerBonus > 0 && brd.atCorner(max))
weight += this.cfg.cornerBonus;
if (this.cfg.edgeBonus > 0 && brd.atEdge(max))
weight += this.cfg.edgeBonus;
if (this.cfg.freeBonus > 0)
weight += this.cfg.freeBonus * brd.free();
return weight;
}
ai.StaticDeepMerges.prototype.analyse = function(brd) {
var origBrd = new this.brdEngine(brd);
var nextBrd = new this.brdEngine();
var prevScore = -1, nextScore = -1;
var maxWeight = -1;
var bestDir;
for (var i = 0; i < ai.dirs.length; i++) {
var dir = ai.dirs[i];
if (origBrd[dir](nextBrd)) {
var weight = this.evalFn(nextBrd);
var ok = (weight - maxWeight) > this.cfg.weightThreshold;
if ( ! ok && maxWeight <= weight) {
nextScore = this.weight(nextBrd);
ok = prevScore < nextScore;
}
if (ok) {
prevScore = nextScore;
maxWeight = weight;
bestDir = dir;
}
}
}
return bestDir;
}
ai.StaticDeepMerges.prototype.evalFn = function(brd) {
var currScore = brd.score();
var maxWeight = currScore;
var nextBrd = new this.brdEngine();
for (var i = 0; i < ai.dirs.length; i++) {
if (brd[ai.dirs[i]](nextBrd)) {
var score = nextBrd.score();
if (score > currScore)
maxWeight = Math.max(maxWeight, this.evalFn(nextBrd));
}
}
return maxWeight;
}
/* Mark that next board will be unrelated to previous, so any stored precompution can be cleared. */
ai.StaticDeepMerges.prototype.cleanup = function() { }
////////////////////////////////////////////////////////////////
// N level deep with random simulation.
////////////////////////////////////////////////////////////////
/**
* Defines coefficient for linear resulted weight function.
* @name ai.expectimax.cfg
* @namespace
* @property {number} scoreCoef multiplicator for score
* @property {number} maxValCoef multiplicator for max value
* @property {number} cornerBonus bonus for max value at board corner
* @property {number} edgeBonus bonus for max value at board edge
* @property {number} freeBonus bonus for each free cell
*/
/** N level deep with random simulation.
* @param {Board} brdEngine board engine from board.js
* @param {ai.expectimax.cfg} cfg configuration settings
* @constructor */
ai.expectimax = function(brdEngine, cfg) {
this.brdEngine = brdEngine;
this.cfg = ai.copyObj(ai.expectimax.bestCfg);
ai.copyObj(cfg, this.cfg);
if (this.cfg.balance <= 0)
this.cfg.balance = ai.expectimax.bestCfg.balance;
if ( this.cfg.balance > 1)
this.cfg.balance = 1;
if (!this.cfg.depth || this.cfg.depth < 0 || 9 <= this.cfg.depth)
this.cfg.depth = ai.expectimax.bestCfg.depth;
}
ai.expectimax.bestCfg = {balance: .9, depth: 5, scoreCoef: 1, maxValCoef: 0, cornerBonus: 0, edgeBonus: 0, freeBonus: 0};
ai.expectimax.prototype.weight = function(brd) {
var score = 0;
var cfg = this.cfg;
if (cfg.scoreCoef > 0)
score += cfg.scoreCoef * brd.score();
if (cfg.maxValCoef > 0 || cfg.cornerBonus > 0 || cfg.edgeBonus > 0) {
var max = brd.max();
if (cfg.maxValCoef > 0)
score += cfg.maxValCoef * max;
if (cfg.cornerBonus > 0)
if (brd.atCorner(max))
score += cfg.cornerBonus;
if (cfg.edgeBonus > 0)
if (brd.atEdge(max))
score += cfg.edgeBonus;
if (cfg.freeBonus > 0)
score += cfg.freeBonus * brd.free();
}
return score;
}
ai.expectimax.prototype.analyse = function(brd) {
var origBrd = new this.brdEngine(brd);
var nextBrd = new this.brdEngine();
var maxW = -1;
var bestDir;
this.cleanup();
this.depthLimit = this.cfg.depth;
var free = origBrd.free();
if (free >= 6)
this.depthLimit = Math.min(this.depthLimit, 6 - free/3);
for (var i = 0; i < ai.dirs.length; i++) {
var dir = ai.dirs[i];
if (origBrd[dir](nextBrd)) {
var w = this.evalFn(nextBrd, 1);
if (w > maxW) {
maxW = w;
bestDir = dir;
}
}
}
this.cleanup();
return bestDir;
}
ai.expectimax.prototype.evalFn = function(brd, depth) {
if (depth >= this.depthLimit)
return this.weight(brd);
if (this.cache[depth]) {
var cache = this.cache[depth];
for (var i = cache.length-1; i >= 0; i--) {
if (brd.equals(cache[i].brd))
return cache[i].weight;
}
} else {
this.cache[depth] = [];
}
var wMin = +Infinity;
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (brd.get(i, j) === 0) {
var randBoard = brd.copy();
randBoard.set(i, j, 1);
var nextBrd = new this.brdEngine();
var wMax2 = 0;
for (var diri = 0; diri < ai.dirs.length; diri++) {
if (randBoard[ai.dirs[diri]](nextBrd))
wMax2 = Math.max(wMax2, this.evalFn(nextBrd, depth+1));
}
var wMax4 = 0;
if (this.cfg.balance < 1) {
randBoard.set(i, j, 2);
for (var diri = 0; diri < ai.dirs.length; diri++) {
if (randBoard[ai.dirs[diri]](nextBrd))
wMax4 = Math.max(wMax4, this.evalFn(nextBrd, depth+1));
}
var balance = this.cfg.balance;
}
wMin = Math.min(wMin, balance * wMax2 + (1 - balance) * wMax4);
}
}
}
this.cache[depth].push({brd: brd, weight: wMin});
return wMin;
}
/* Mark that next board will be unrelated to previous, so any stored precompution can be cleared. */
ai.expectimax.prototype.cleanup = function() {
this.cache = [];
}