ai.js
author Oleksandr Gavenko <gavenkoa@gmail.com>
Fri, 26 Sep 2014 02:21:28 +0300
changeset 149 2839f8227a38
parent 148 93c122e0ea90
child 152 07814b979a8a
permissions -rw-r--r--
Refactoring: take proper name to function.

"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;
}

ai.brdCache = function() {
    this.cache = [];
}
ai.brdCache.prototype.get = function(brd) {
    var compr = brd.compress();
    var subCache = this.cache[compr[0]];
    if (subCache) {
        return subCache[compr[1]];
    }
    return undefined;
}
ai.brdCache.prototype.put = function(brd, val) {
    var compr = brd.compress();
    var subCache = this.cache[compr[0]];
    if (subCache) {
        subCache[compr[1]] = val;
    } else {
        this.cache[compr[0]] = [];
        this.cache[compr[0]][compr[1]] = val;
    }
}

// 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;
}
/** Select best direction for next step. */
ai.BlindRandom.prototype.analyse = function(brd2d) {
    var origBrd = new this.brdEngine(brd2d);
    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 };
/** Select best direction for next step. */
ai.BlindWeightRandom.prototype.analyse = function(brd2d) {
    var origBrd = new this.brdEngine(brd2d);
    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;
}
/** Select best direction for next step. */
ai.BlindCycle.prototype.analyse = function(brd2d) {
    var origBrd = new this.brdEngine(brd2d);
    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.maxVal();
    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.freeCnt();
    return weight;
}
/** Select best direction for next step. */
ai.OneStepAhead.prototype.analyse = function(brd2d) {
    var origBrd = new this.brdEngine(brd2d);
    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.maxVal();
    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.freeCnt();
    return weight;
}
/** Select best direction for next step. */
ai.StaticDeepMerges.prototype.analyse = function(brd2d) {
    var origBrd = new this.brdEngine(brd2d);
    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.maxVal();
        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.freeCnt();
    return score;
}
/** Select best direction for next step. */
ai.expectimax.prototype.analyse = function(brd2d) {
    this.brdCache = new ai.brdCache();
    var origBrd = new this.brdEngine(brd2d);
    var nextBrd = new this.brdEngine();
    var maxW = -1;
    var bestDir;
    this.cleanup();
    this.depthLimit = this.cfg.depth;
    var freeCnt = origBrd.freeCnt();
    if (freeCnt >= 6)
        this.depthLimit = Math.min(this.depthLimit, 6 - freeCnt/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);
    var wCached = this.brdCache.get(brd);
    if (wCached)
        return wCached;
    var wMin = +Infinity;
    var randBoard = new this.brdEngine();
    var nextBrd = new this.brdEngine();
    for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
            if (brd.get(i, j) === 0) {
                brd.copy(randBoard);
                randBoard.set(i, j, 1);
                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;
                var balance = this.cfg.balance;
                if (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));
                    }
                }
                wMin = Math.min(wMin, balance * wMax2 + (1 - balance) * wMax4);
            }
        }
    }
    this.brdCache.put(brd, wMin);
    return wMin;
}
/* Mark that next board will be unrelated to previous, so any stored precompution can be cleared. */
ai.expectimax.prototype.cleanup = function() {
}