UNPKG

jocly

Version:

Board games 3D/2D UI and AI web library

3 lines 49.2 kB
function JocLog(){if("undefined"!=typeof jQuery){for(var t=[],e=0;e<arguments.length;e++){var r=arguments[e];"string"!=typeof r&&(r=JSON.stringify(r)),t.push(""+r)}jQuery("<p/>").text(t.join(" ")).appendTo(jQuery("#jocly-log"))}else console.warn.apply(console,arguments)}var JocUtil={JSON:JSON};JocUtil.reload=function(){window.location.reload()},JocUtil.setTimeout=function(t,e){return setTimeout(t,e)},JocUtil.setInterval=function(t,e){return setInterval(t,e)},JocUtil.clearTimeout=function(t){clearTimeout(t)},JocUtil.schedule=function(t,e,r){JocUtil.setTimeout(function(){t[e](r)},0)},JocUtil.setPref=function(t,e,r){var i="jocly_pref";arguments.length<3&&(r={}),r.appId&&(i+="_"+r.appId),r.game&&(i+="_"+r.game),i+="_"+t,"boolean"==typeof e&&(e="$#@"+e),"object"!=typeof e&&"array"!=typeof e||(e="$#@JSON@"+JSON.stringify(e)),window.localStorage.setItem(i,e)},JocUtil.getPref=function(t,e){var r="jocly_pref";arguments.length<2&&(e={}),e.appId&&(r+="_"+e.appId),e.game&&(r+="_"+e.game),r+="_"+t;var i=window.localStorage.getItem(r);return"$#@true"==i?i=!0:"$#@false"==i?i=!1:"string"==typeof i&&"$#@JSON@"==i.substr(0,8)&&(i=JSON.parse(i.substr(8))),null==i&&void 0!==e.defaultValue&&(i=e.defaultValue),i},JocUtil.filterLevels=function(t,e,r){var i=parseInt(JocUtil.getPref("calibration",{defaultValue:0}));parseInt(JocUtil.getPref("calibrationDate",{defaultValue:0}))<(new Date).getTime()-864e5&&(i=0);var o=[];if(t){var n=null,a=0;for(var s in t){var c=t[s];if(c.isDefault&&(n=c,bestLevelFound=!0),c.isDefault=!1,c.fullLabel=strings["comp-level"]+" "+c.label,c.optionValue=s,c.calRatio){i||(i=function(){for(var t=(new Date).getTime(),e=[],r=[],i=0;i<100;i++)e.push(i);for(var i=0;i<1e3;i++){for(;e.length>0;)r.push(e.shift());var o=e;e=r,r=o}return(new Date).getTime()-t}(),JocLog("Calibration",i),JocUtil.setPref("calibration",i,{}),JocUtil.setPref("calibrationDate",(new Date).getTime(),{}));var h=i*c.calRatio;if(h>6e4&&o.length>=2)continue;(null==n||h<3e3&&h>a)&&(n=c,a=h)}else null==n&&(n=c);o.push(c)}n&&(n.isDefault=!0)}else{var l=9;e&&(l=e);for(var u=0;u<=l;u++){var c={fullLabel:strings["comp-level"]+" "+(u+1),optionValue:"machine-"+u,isDefault:!1};void 0!==r&&u==r&&(c.isDefault=!0),o.push(c)}}return o},JocUtil.cookieSupportTested=!1,JocUtil.cookieSupport=!0,JocUtil.hasCookieSupport=function(){if(JocUtil.cookieSupportTested)return JocUtil.cookieSupport;if(0==document.cookie.length){var t=new Date;t.setTime(t.getTime()+31536e6),document.cookie="jocly="+escape("{}")+"; path=/; expires="+t.toGMTString()+";",0==document.cookie.length&&(JocUtil.cookieSupport=!1)}return JocUtil.cookieSupportTested=!0,JocUtil.cookieSupport},JocUtil.getCookieData=function(){if(JocUtil.hasCookieSupport()){var t=document.cookie.split(";");for(var e in t){var r=/^ *(.*)$/.exec(t[e])[1];if(0==r.indexOf("jocly="))try{return JSON.parse(unescape(r.substring(6)))}catch(t){JocLog("Unable to parse cookie",r)}}return{}}var i=window.localStorage.getItem("jocly");return null==i?{}:JSON.parse(i)},JocUtil.setCookieData=function(t,e){if(JocUtil.hasCookieSupport()){var r=JocUtil.getCookieData();null==e?delete r[t]:r[t]=e;var i=new Date;i.setTime(i.getTime()+31536e6);var o="jocly="+escape(JSON.stringify(r))+"; path=/; expires="+i.toGMTString()+";";document.cookie=o}else{var r=window.localStorage.getItem("jocly");r=null==r?{}:JSON.parse(r),r[t]=e,window.localStorage.setItem("jocly",JSON.stringify(r))}},JocUtil.extend=function(t,e){for(var r in e)t[r]=e[r]},JocUtil.md5=function(t){function e(t,e){return t<<e|t>>>32-e}function r(t,e){var r,i,o,n,a;return o=2147483648&t,n=2147483648&e,r=1073741824&t,i=1073741824&e,a=(1073741823&t)+(1073741823&e),r&i?2147483648^a^o^n:r|i?1073741824&a?3221225472^a^o^n:1073741824^a^o^n:a^o^n}function i(t,e,r){return t&e|~t&r}function o(t,e,r){return t&r|e&~r}function n(t,e,r){return t^e^r}function a(t,e,r){return e^(t|~r)}function s(t,o,n,a,s,c,h){return t=r(t,r(r(i(o,n,a),s),h)),r(e(t,c),o)}function c(t,i,n,a,s,c,h){return t=r(t,r(r(o(i,n,a),s),h)),r(e(t,c),i)}function h(t,i,o,a,s,c,h){return t=r(t,r(r(n(i,o,a),s),h)),r(e(t,c),i)}function l(t,i,o,n,s,c,h){return t=r(t,r(r(a(i,o,n),s),h)),r(e(t,c),i)}function u(t){var e,r,i="",o="";for(r=0;r<=3;r++)e=t>>>8*r&255,o="0"+e.toString(16),i+=o.substr(o.length-2,2);return i}var f,m,p,g,d,v,S,J,C,y=Array();for(t=function(t){t=t.replace(/\r\n/g,"\n");for(var e="",r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?e+=String.fromCharCode(i):i>127&&i<2048?(e+=String.fromCharCode(i>>6|192),e+=String.fromCharCode(63&i|128)):(e+=String.fromCharCode(i>>12|224),e+=String.fromCharCode(i>>6&63|128),e+=String.fromCharCode(63&i|128))}return e}(t),y=function(t){for(var e,r=t.length,i=r+8,o=(i-i%64)/64,n=16*(o+1),a=Array(n-1),s=0,c=0;c<r;)e=(c-c%4)/4,s=c%4*8,a[e]=a[e]|t.charCodeAt(c)<<s,c++;return e=(c-c%4)/4,s=c%4*8,a[e]=a[e]|128<<s,a[n-2]=r<<3,a[n-1]=r>>>29,a}(t),v=1732584193,S=4023233417,J=2562383102,C=271733878,f=0;f<y.length;f+=16)m=v,p=S,g=J,d=C,v=s(v,S,J,C,y[f+0],7,3614090360),C=s(C,v,S,J,y[f+1],12,3905402710),J=s(J,C,v,S,y[f+2],17,606105819),S=s(S,J,C,v,y[f+3],22,3250441966),v=s(v,S,J,C,y[f+4],7,4118548399),C=s(C,v,S,J,y[f+5],12,1200080426),J=s(J,C,v,S,y[f+6],17,2821735955),S=s(S,J,C,v,y[f+7],22,4249261313),v=s(v,S,J,C,y[f+8],7,1770035416),C=s(C,v,S,J,y[f+9],12,2336552879),J=s(J,C,v,S,y[f+10],17,4294925233),S=s(S,J,C,v,y[f+11],22,2304563134),v=s(v,S,J,C,y[f+12],7,1804603682),C=s(C,v,S,J,y[f+13],12,4254626195),J=s(J,C,v,S,y[f+14],17,2792965006),S=s(S,J,C,v,y[f+15],22,1236535329),v=c(v,S,J,C,y[f+1],5,4129170786),C=c(C,v,S,J,y[f+6],9,3225465664),J=c(J,C,v,S,y[f+11],14,643717713),S=c(S,J,C,v,y[f+0],20,3921069994),v=c(v,S,J,C,y[f+5],5,3593408605),C=c(C,v,S,J,y[f+10],9,38016083),J=c(J,C,v,S,y[f+15],14,3634488961),S=c(S,J,C,v,y[f+4],20,3889429448),v=c(v,S,J,C,y[f+9],5,568446438),C=c(C,v,S,J,y[f+14],9,3275163606),J=c(J,C,v,S,y[f+3],14,4107603335),S=c(S,J,C,v,y[f+8],20,1163531501),v=c(v,S,J,C,y[f+13],5,2850285829),C=c(C,v,S,J,y[f+2],9,4243563512),J=c(J,C,v,S,y[f+7],14,1735328473),S=c(S,J,C,v,y[f+12],20,2368359562),v=h(v,S,J,C,y[f+5],4,4294588738),C=h(C,v,S,J,y[f+8],11,2272392833),J=h(J,C,v,S,y[f+11],16,1839030562),S=h(S,J,C,v,y[f+14],23,4259657740),v=h(v,S,J,C,y[f+1],4,2763975236),C=h(C,v,S,J,y[f+4],11,1272893353),J=h(J,C,v,S,y[f+7],16,4139469664),S=h(S,J,C,v,y[f+10],23,3200236656),v=h(v,S,J,C,y[f+13],4,681279174),C=h(C,v,S,J,y[f+0],11,3936430074),J=h(J,C,v,S,y[f+3],16,3572445317),S=h(S,J,C,v,y[f+6],23,76029189),v=h(v,S,J,C,y[f+9],4,3654602809),C=h(C,v,S,J,y[f+12],11,3873151461),J=h(J,C,v,S,y[f+15],16,530742520),S=h(S,J,C,v,y[f+2],23,3299628645),v=l(v,S,J,C,y[f+0],6,4096336452),C=l(C,v,S,J,y[f+7],10,1126891415),J=l(J,C,v,S,y[f+14],15,2878612391),S=l(S,J,C,v,y[f+5],21,4237533241),v=l(v,S,J,C,y[f+12],6,1700485571),C=l(C,v,S,J,y[f+3],10,2399980690),J=l(J,C,v,S,y[f+10],15,4293915773),S=l(S,J,C,v,y[f+1],21,2240044497),v=l(v,S,J,C,y[f+8],6,1873313359),C=l(C,v,S,J,y[f+15],10,4264355552),J=l(J,C,v,S,y[f+6],15,2734768916),S=l(S,J,C,v,y[f+13],21,1309151649),v=l(v,S,J,C,y[f+4],6,4149444226),C=l(C,v,S,J,y[f+11],10,3174756917),J=l(J,C,v,S,y[f+2],15,718787259),S=l(S,J,C,v,y[f+9],21,3951481745),v=r(v,m),S=r(S,p),J=r(J,g),C=r(C,d);return(u(v)+u(S)+u(J)+u(C)).toLowerCase()},JocUtil.sha1=function(t){function e(t,e){return t<<e|t>>>32-e}function r(t){var e,r,i="";for(e=7;e>=0;e--)r=t>>>4*e&15,i+=r.toString(16);return i}var i,o,n,a,s,c,h,l,u,f=new Array(80),m=1732584193,p=4023233417,g=2562383102,d=271733878,v=3285377520;t=function(t){t=t.replace(/\r\n/g,"\n");for(var e="",r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?e+=String.fromCharCode(i):i>127&&i<2048?(e+=String.fromCharCode(i>>6|192),e+=String.fromCharCode(63&i|128)):(e+=String.fromCharCode(i>>12|224),e+=String.fromCharCode(i>>6&63|128),e+=String.fromCharCode(63&i|128))}return e}(t);var S=t.length,J=new Array;for(o=0;o<S-3;o+=4)n=t.charCodeAt(o)<<24|t.charCodeAt(o+1)<<16|t.charCodeAt(o+2)<<8|t.charCodeAt(o+3),J.push(n);switch(S%4){case 0:o=2147483648;break;case 1:o=t.charCodeAt(S-1)<<24|8388608;break;case 2:o=t.charCodeAt(S-2)<<24|t.charCodeAt(S-1)<<16|32768;break;case 3:o=t.charCodeAt(S-3)<<24|t.charCodeAt(S-2)<<16|t.charCodeAt(S-1)<<8|128}for(J.push(o);J.length%16!=14;)J.push(0);for(J.push(S>>>29),J.push(S<<3&4294967295),i=0;i<J.length;i+=16){for(o=0;o<16;o++)f[o]=J[i+o];for(o=16;o<=79;o++)f[o]=e(f[o-3]^f[o-8]^f[o-14]^f[o-16],1);for(a=m,s=p,c=g,h=d,l=v,o=0;o<=19;o++)u=e(a,5)+(s&c|~s&h)+l+f[o]+1518500249&4294967295,l=h,h=c,c=e(s,30),s=a,a=u;for(o=20;o<=39;o++)u=e(a,5)+(s^c^h)+l+f[o]+1859775393&4294967295,l=h,h=c,c=e(s,30),s=a,a=u;for(o=40;o<=59;o++)u=e(a,5)+(s&c|s&h|c&h)+l+f[o]+2400959708&4294967295,l=h,h=c,c=e(s,30),s=a,a=u;for(o=60;o<=79;o++)u=e(a,5)+(s^c^h)+l+f[o]+3395469782&4294967295,l=h,h=c,c=e(s,30),s=a,a=u;m=m+a&4294967295,p=p+s&4294967295,g=g+c&4294967295,d=d+h&4294967295,v=v+l&4294967295}var u=r(m)+r(p)+r(g)+r(d)+r(v);return u.toLowerCase()};var MersenneTwister=function(t){void 0==t&&(t=(new Date).getTime()),this.N=624,this.M=397,this.MATRIX_A=2567483615,this.UPPER_MASK=2147483648,this.LOWER_MASK=2147483647,this.mt=new Array(this.N),this.mti=this.N+1,this.init_genrand(t)};MersenneTwister.prototype.init_genrand=function(t){for(this.mt[0]=t>>>0,this.mti=1;this.mti<this.N;this.mti++){var t=this.mt[this.mti-1]^this.mt[this.mti-1]>>>30;this.mt[this.mti]=(1812433253*((4294901760&t)>>>16)<<16)+1812433253*(65535&t)+this.mti,this.mt[this.mti]>>>=0}},MersenneTwister.prototype.init_by_array=function(t,e){var r,i,o;for(this.init_genrand(19650218),r=1,i=0,o=this.N>e?this.N:e;o;o--){var n=this.mt[r-1]^this.mt[r-1]>>>30;this.mt[r]=(this.mt[r]^(1664525*((4294901760&n)>>>16)<<16)+1664525*(65535&n))+t[i]+i,this.mt[r]>>>=0,r++,i++,r>=this.N&&(this.mt[0]=this.mt[this.N-1],r=1),i>=e&&(i=0)}for(o=this.N-1;o;o--){var n=this.mt[r-1]^this.mt[r-1]>>>30;this.mt[r]=(this.mt[r]^(1566083941*((4294901760&n)>>>16)<<16)+1566083941*(65535&n))-r,this.mt[r]>>>=0,r++,r>=this.N&&(this.mt[0]=this.mt[this.N-1],r=1)}this.mt[0]=2147483648},MersenneTwister.prototype.genrand_int32=function(){var t,e=new Array(0,this.MATRIX_A);if(this.mti>=this.N){var r;for(this.mti==this.N+1&&this.init_genrand(5489),r=0;r<this.N-this.M;r++)t=this.mt[r]&this.UPPER_MASK|this.mt[r+1]&this.LOWER_MASK,this.mt[r]=this.mt[r+this.M]^t>>>1^e[1&t];for(;r<this.N-1;r++)t=this.mt[r]&this.UPPER_MASK|this.mt[r+1]&this.LOWER_MASK,this.mt[r]=this.mt[r+(this.M-this.N)]^t>>>1^e[1&t];t=this.mt[this.N-1]&this.UPPER_MASK|this.mt[0]&this.LOWER_MASK,this.mt[this.N-1]=this.mt[this.M-1]^t>>>1^e[1&t],this.mti=0}return t=this.mt[this.mti++],t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,(t^=t>>>18)>>>0},MersenneTwister.prototype.genrand_int31=function(){return this.genrand_int32()>>>1},MersenneTwister.prototype.genrand_real1=function(){return this.genrand_int32()*(1/4294967295)},MersenneTwister.prototype.random=function(){return this.genrand_int32()*(1/4294967296)},MersenneTwister.prototype.genrand_real3=function(){return(this.genrand_int32()+.5)*(1/4294967296)},MersenneTwister.prototype.genrand_res53=function(){return(67108864*(this.genrand_int32()>>>5)+(this.genrand_int32()>>>6))*(1/9007199254740992)},"undefined"!=typeof module&&module.exports?(exports.MersenneTwister=MersenneTwister,exports.JocUtil=JocUtil):(this.MersenneTwister=MersenneTwister,this.JocUtil=JocUtil); var JoclyUCT={};"undefined"==typeof WorkerGlobalScope&&"undefined"==typeof SystemJS?(module.exports.JoclyUCT=JoclyUCT,function(){var e=require,o=e("./jocly.util.js");global.MersenneTwister=o.MersenneTwister,global.JocUtil=o.JocUtil}()):this.JoclyUCT=JoclyUCT,function(){function e(e,o){this.visits=1,this.children=null,this.who=o,this.parents=[],e&&this.parents.push(e),this.known=!1,this.evaluation=0,this.staticEvalSum=0,this.staticEvalCount=0,this.depth=e?e.depth+1:0}e.prototype={addParent:function(e){this.parents.push(e),e.depth+1<this.depth&&(this.depth=e.depth+1)}};var o={"-1":-1,1:1,2:0,0:0};JoclyUCT.startMachine=function(t,n){function i(e){var o=D,t=!1,n=0,i=1;if(0==e)return 0;for(e<0&&(e=-e,o=A,t=!0);;){if(e>o.v)n+=i,o.m||(o.m={v:e,l:null,m:null}),o=o.m;else{if(!(e<o.v))break;n-=i,o.l||(o.l={v:e,l:null,m:null}),o=o.l}i/=2}return t&&(n=-n),n}function a(e,o){for(var t=void 0,n=0;n<o.length;n++){var i=o[n];(void 0===t||i.evaluation*i.who>t*i.who)&&(t=i.evaluation)}return t}function l(e,o){for(var t=void 0,n=0;n<o.length;n++){var i=o[n];(void 0===t||i.evaluation*i.who<t*i.who)&&(t=i.evaluation)}return-t}function r(e,o){for(var t=1,n=0;n<o.length;n++){var i=o[n];value1=(i.evaluation+1)/2,1==e.who?t*=1-i.evaluation:t*=i.evaluation}return 1==e.who?2*(1-t)-1:2*t-1}function s(e,o,n){if(!(t.mOptions.uctTransposition&&!t.mOptions.uctIgnoreLoop&&e.sign in n)){var i=[];if(T.ignoreLeaf){for(var s=!1,h=0;h<e.children.length;h++)if(e.children[h].n.children){s=!0;break}if(s)for(var h=0;h<e.children.length;h++){var c=e.children[h].n;(c.known||c.children)&&i.push(c)}}if(0==i.length)for(var h=0;h<e.children.length;h++)i.push(e.children[h].n);var p;switch(T.propagation){case"maximin":p=l(e,i);break;case"minimax2min-avg":var d=l(e,i),m=a(e,i);p=(d+m)/2;break;case"minimax2min-best":var d=l(e,i),m=a(e,i);p=1==e.who?Math.max(d,m):Math.min(d,m);break;case"product":p=GetPropabilityProductEval(e,i);break;case"minimax":case"mixed":default:p=a(e,i),"mixed"==T.propagation&&T.productRatio>0&&(m=r(e,i),p=T.productRatio*m+(1-T.productRatio)*p),T.useDepthWeights&&(p=g(p,e.depth+1))}T.uncertaintyFactor&&(p*=1-Math.pow(10,-T.uncertaintyFactor)*Math.log(e.depth+1)),e.evaluation!==p?(e.evaluation=p,T.directVisits||(e.visits+=o),v(e,o,n)):T.directVisits||u(e,o,n)}}function v(e,o,n){if(0!=e.parents.length){t.mOptions.uctTransposition&&!t.mOptions.uctIgnoreLoop&&(n||(n={}),n[e.sign]=!0);for(var i=0;i<e.parents.length;i++){var a=e.parents[i];T.useAlphaBeta&&a.children.sort(function(o,t){return(t.evaluation-o.evaluation)*e.who}),s(a,o,n)}}}function u(e,o,n){if(0!=e.parents.length){t.mOptions.uctTransposition&&!t.mOptions.uctIgnoreLoop&&(n||(n={}),n[e.sign]=!0);for(var i=0;i<e.parents.length;i++){var a=e.parents[i];a.sign in n||(a.visits+=o,n[a.sign]=!0,u(a,o,n))}}}function h(e,o){if(!(t.mOptions.uctTransposition&&!t.mOptions.uctIgnoreLoop&&e.sign in o)){for(var n=!0,i=0;i<e.children.length;i++){if(0==e.children[i].n.known){n=!1;break}}1==n&&(e.known=!0,c(e,o))}}function c(e,o){if(0!=e.known&&0!=e.parents.length){t.mOptions.uctTransposition&&!t.mOptions.uctIgnoreLoop&&(o||(o={}),o[e.sign]=!0);for(var n=0;n<e.parents.length;n++)h(e.parents[n],o)}}function p(e){for(var o=1,t=0,n=0;n<32;n++){var i=e>>>n&1;t=o?t<<1|i:t<<1|1-i,o=i}return t}function d(){function n(e,n,a){for(var l=null,r=Date.now(),s=0;s<T.playoutDepth||n.mWho==T.playoutCeil*O.who;s++){if(n.mMoves&&0!=n.mMoves.length||n.GenerateMoves(t),n.mFinished){l={finished:!0,winner:o[n.mWinner]};break}for(var v=[],u=0;u<n.mMoves.length;u++){var h=new(t.GetBoardClass())(t);h.CopyFrom(n),h.ApplyMove(t,n.mMoves[u]),t.AddVisit(h),h.mMoves=[],h.Evaluate(t);var c=h.mEvaluation;h.mFinished?c=1==h.mWinner?Number.MAX_VALUE:-1==h.mWinner?-Number.MAX_VALUE:0:isNaN(h.mEvaluation)&&console.error("Evaluation in not a number !"),v.push({move:n.mMoves[u],evaluation:c,board:h}),t.RemoveVisit(h)}v.sort(function(e,o){var t=e.evaluation*n.mWho;return o.evaluation*n.mWho-t});for(var p,d=v.length,g=1/T.playoutSpread,f=(1-Math.pow(g,d+1))/(1-g)-1,w=Math.random()*f,M=void 0,x=0,b=!1,u=0;u<d;u++){var y=v[u],C=y.evaluation;if(C!==M){if(b)break;p=[y],M=C}else p.push(y);x+=Math.pow(g,u+1),x>=w&&(b=!0)}var V=p[Math.floor(Math.random()*p.length)];if(n=V.board,t.AddVisit(n),a.push(n.GetSignature()),n.mWho=-n.mWho,n.mFinished){l={finished:!0,winner:o[n.mWinner]};break}}null===l&&(l={finished:!1,eval:n.mEvaluation}),k+=Date.now()-r,E++;var B;if(l.finished)B=l.winner;else{T.debugRawEval&&(e.rawEval=l.eval);var D=i(l.eval);m(D,e.depth),B=D}return B}x++;var a=new(t.GetBoardClass())(t);a.CopyFrom(t.mBoard);for(var l=0,r=O,s=0,u=0,h=[],d=[],g=x,f={},w=-2,D=2;;){if(d.push(r),s>u&&(u=s),null===r.children)break;var A;if(T.useAlphaBeta){A=[];for(var L=0;L<r.children.length;L++){var S=r.children[L],W=S.n;if(A.push(S),1==W.who&&W.evaluation>w&&(w=W.evaluation),-1==W.who&&W.evaluation<D&&(D=W.evaluation),D<w){C+=r.children.length-1-L;break}}}else A=r.children;if(t.mOptions.uctTransposition&&!t.mOptions.uctIgnoreLoop){for(var N=[],L=0;L<A.length;L++)A[L].n.sign in f||N.push(A[L]);A=N}var R,U,G=[];if(U=T.directVisits?Math.log(g):Math.log(r.visits),T.distributeEval?function(){for(var e={},o=[],t=0;t<A.length;t++){var n=A[t],i=n.n;if(!i.known){var a=(i.evaluation*i.who+1)/2;void 0===e[a]&&(e[a]=[],o.push(a)),e[a].push(n)}}o.sort(function(e,o){return e-o});for(var l=1/(o.length+1),r=0,s=0;s<o.length;s++){r++;for(var v=o[s],u=e[v],h=l*r,t=0;t<u.length;t++){var c,n=u[t],i=n.n;c=T.directVisits?h+T.c*Math.sqrt(U/n.f):h+T.c*Math.sqrt(U/i.visits),(0==G.length||c>=R)&&(G.length>0&&c>R&&(G=[]),R=c,G.push(n))}}}():function(){for(var e=0;e<A.length;e++){var o=A[e],t=o.n;if(!t.known){var n,i=(t.evaluation*t.who+1)/2;n=T.directVisits?i+T.c*Math.sqrt(U/o.f):i+T.c*Math.sqrt(U/t.visits),(0==G.length||n>=R)&&(G.length>0&&n>R&&(G=[]),R=n,G.push(o))}}}(),0==G.length)return;var F=G[Math.floor(Math.random()*G.length)];T.directVisits&&(F.f++,g=F.f),r=F.n,t.mOptions.uctTransposition&&!t.mOptions.uctIgnoreLoop&&(f[r.sign]=1),s++,h.push(F.m),a.ApplyMove(t,F.m),t.AddVisit(a),a.mMoves=[],M.push(a.GetSignature()),"states"==t.mOptions.uctTransposition&&(l^=p(a.GetSignature())),a.mWho=-a.mWho}if(r==O||r.visits>=T.minVisitsExpand)if(a.mMoves&&0!=a.mMoves.length||a.GenerateMoves(t),a.mFinished)r.known=!0,r.evaluation=o[a.mWinner],c(r);else{r.children=[];for(var J=void 0,I=!0,L=0;L<a.mMoves.length;L++){var P=a.mMoves[L],q=[],X=new(t.GetBoardClass())(t);X.CopyFrom(a),X.ApplyMove(t,P),t.AddVisit(X),X.mMoves=[],X.mWho=-X.mWho,s>V&&(V=s);var _=X.GetSignature();q.push(_);var j;"states"==t.mOptions.uctTransposition?(j=l^_,j^=s):"state"==t.mOptions.uctTransposition&&(j=_);var W=null;t.mOptions.uctTransposition&&(W=B[j]),W?(y++,W.addParent(r)):(W=new e(r,-r.who),b++,t.mOptions.uctTransposition&&(B[j]=W,W.sign=j),X.Evaluate(t),X.mFinished?(W.known=!0,W.evaluation=o[X.mWinner]):(isNaN(X.mEvaluation)&&console.error("Evaluation in not a number !",X.mEvaluation),W.evaluation=n(W,X,q)),W.staticEvalSum=W.evaluation,W.staticEvalCount=1),0==W.known&&(I=!1);var z={n:W,m:new(t.GetMoveClass())(P).Strip()};T.directVisits&&(z.f=1),r.children.push(z);var H=W.evaluation*W.who;(void 0===J||H>J*W.who)&&(J=W.evaluation);for(var K=0;K<q.length;K++)t.RemoveVisit(null,q[K])}if(r.evaluation=J,v(r,T.propagateMultiVisits?a.mMoves.length:1),T.directVisits)for(var L=0;L<d.length;L++)d[L].visits+=T.propagateMultiVisits?a.mMoves.length:1;I&&(r.known=!0,c(r))}else if(!r.known){var Q=n(r,a,M);if(r.staticEvalSum+=Q,r.staticEvalCount++,r.evaluation=r.staticEvalSum/r.staticEvalCount,v(r,1),T.directVisits)for(var L=0;L<d.length;L++)d[L].visits++}}function m(e,o){for(;L.length<=o;)L.push({count:0,sum:0});var t=L[o];t.sum+=e,t.count++}function g(e,o){var t=L[o];if(void 0===t){for(;L.length<o;)L.push({count:0,sum:0});return L.push({count:1,sum:e}),e}var n=t.count>0?t.sum/t.count:0;return e>n?e=(e-n)/(1-n):e<n&&(e=-(n-e)/(n+1)),e}function f(){if(t.mAborted)return void t.mAbortCallback.call(t);var e=Date.now(),o=0;if(T.maxDuration>0&&(o=Math.round(100*(e-S)/(1e3*T.maxDuration))),T.maxLoops>0&&(o=Math.max(o,100*x/T.maxLoops)),T.maxNodes>0&&(o=Math.max(o,100*b/T.maxNodes)),o=Math.min(100,o),o!=W&&(W=o,t.mProgressCallback&&t.mProgressCallback(o)),!O.children||0==O.known&&(T.maxDuration<=0||e<1e3*T.maxDuration+S)&&(T.maxLoops<=0||x<T.maxLoops)&&(T.maxNodes<=0||b<T.maxNodes)){do{M=[];try{d()}catch(e){console.error("UCT step",e)}for(var n=0;n<M.length;n++)t.RemoveVisit(null,M[n])}while(Date.now()-100<e);setTimeout(f,0)}else{T.log&&w(O);var i=void 0;if(t.mBestMoves=[],"maxvisits"==T.pickMove&&T.directVisits){for(var n=0;n<O.children.length;n++){var a=O.children[n],l=a.n;l.evaluation==l.who&&t.mBestMoves.push(a.m)}if(0==t.mBestMoves.length)for(var n=0;n<O.children.length;n++){var a=O.children[n];(void 0===i||i<=a.f)&&((void 0===i||i<a.f)&&(t.mBestMoves=[]),i=a.f,t.mBestMoves.push(a.m))}}else{var r=void 0,s=[];"besteval-multivisits"==T.pickMove&&O.children.forEach(function(e){(e.n.visits>1||1==e.n.known)&&s.push(e)}),0==s.length&&(s=O.children);for(var n=0;n<s.length;n++){var a=s[n],l=a.n,v=l.staticEvalSum/l.staticEvalCount;(void 0===i||i>=l.evaluation*O.who)&&((void 0===i||i>l.evaluation*O.who||i==l.evaluation*O.who&&(void 0===r||r>O.who*v))&&(r=v,t.mBestMoves=[]),i=l.evaluation*O.who,t.mBestMoves.push(a.m))}}JocUtil.schedule(t,"Done",{})}}function w(e){function o(e,n){if("minimax"!=T.propagation&&("mixed"!=T.propagation||T.productRatio>0))return void console.warn("Cannot display minimax tree on propagation",T.propagation,"pp ratio",T.productRatio);for(var i="",a=0;a<n;a++)i+=" ";console.log(i+"*",n,"*",-e.who,"eval",e.evaluation);for(var a=0;a<e.children.length;a++){var l=e.children[a],r=l.n;console.log(i," "+(r.evaluation==e.evaluation?"*":" ")+" move",new(t.GetMoveClass())(l.m).ToString(),"visits",r.visits,"eval",r.evaluation,"known",r.known,"sev",r.staticEvalSum+"/"+r.staticEvalCount,"who",r.who,"children",r.children?r.children.length:"no"),r.children&&r.evaluation==e.evaluation&&o(r,n+1)}}function n(e){if(i++,e.children)for(var o=0;o<e.children.length;o++){var t=e.children[o];t.n.who!=-e.who&&a++,n(t.n)}}if(console.log(" duration",Date.now()-S),console.log(" evaluation:",e.evaluation),console.log(" fully explored:",e.known),console.log(" node count:",b),console.log(" redundant node count:",y),console.log(" max depth:",V),console.log(" alpha-beta",T.useAlphaBeta,"skipped",C),console.log(" ",x,"steps, per step",(Date.now()-S)/x,"ms"),console.log(" ",E,"playouts",k,"ms, per playout",k/E,"ms"),console.log(" UCT c",T.c),console.log(" tree",O),T.showMinimaxTree&&(console.log("Minimax tree"),o(e,0)),T.checkSide){var i=0,a=0;n(O),console.log(" tree side alternance","node",i,"errors",a)}}var M,x=0,b=0,y=0,k=0,E=0,C=0,V=0,T={minVisitsExpand:n.level.minVisitsExpand||1,playoutSpread:n.level.playoutSpread||2,playoutDepth:void 0!==n.level.playoutDepth?n.level.playoutDepth:0,c:void 0!==n.level.c?n.level.c:.3,playoutCeil:void 0!==n.level.playoutCeil?n.level.playoutCeil:0,log:!!n.level.log,maxDuration:void 0!==n.level.maxDuration?n.level.maxDuration:2,maxLoops:void 0!==n.level.maxLoops?n.level.maxLoops:0,maxNodes:void 0!==n.level.maxNodes?n.level.maxNodes:0,showMinimaxTree:!!n.level.showMinimaxTree,showBestLine:!!n.level.showBestLine,ignoreLeaf:void 0!==n.level.ignoreLeaf&&n.level.ignoreLeaf,propagateMultiVisits:void 0===n.level.propagateMultiVisits||n.level.propagateMultiVisits,propagation:void 0===n.level.propagation?"mixed":n.level.propagation,useDepthWeights:void 0!==n.level.useDepthWeights&&n.level.useDepthWeights,productRatio:void 0===n.level.productRatio?0:n.level.productRatio,useAlphaBeta:void 0!==n.level.useAlphaBeta&&n.level.useAlphaBeta,uncertaintyFactor:void 0===n.level.uncertaintyFactor?0:n.level.uncertaintyFactor,directVisits:void 0===n.level.directVisits||n.level.directVisits,distributeEval:void 0===n.level.distributeEval||n.level.distributeEval,pickMove:void 0===n.level.pickMove?"besteval":n.level.pickMove,debugRawEval:void 0!==n.level.debugRawEval&&n.level.debugRawEval},B={};T.log&&console.log("Running UCT AI - ",n.level.label,"- Player",1==t.mWho?"A":"B");var D={v:0,l:null,m:{v:Number.MAX_VALUE,l:null,m:null}},A=JSON.parse(JSON.stringify(D)),L=[];if(t.mBoard.mMoves&&0!=t.mBoard.mMoves.length||t.mBoard.GenerateMoves(t),1==t.mBoard.mMoves.length)return t.mBestMoves=[t.mBoard.mMoves[0]],void JocUtil.schedule(t,"Done",{});0==t.mBoard.mMoves.length&&console.error("No move available",t);var O=new e(null,-t.mWho);b++,t.mOptions.uctTransposition&&(B[t.mBoard.GetSignature()]=O);var S=Date.now(),W=-1;f()}}(); try{exports.Game=JocGame=function(){},exports.Board=JocBoard=function(){},exports.Move=JocMove=function(){}}catch(e){global.JocGame=exports.Game=function(){},global.JocBoard=exports.Board=function(){},global.JocMove=exports.Move=function(){},function(){var e=require,t=e("./jocly.util.js");global.MersenneTwister=t.MersenneTwister,global.JocUtil=t.JocUtil,global.JoclyUCT=e("./jocly.uct.js").JoclyUCT}()}JocGame.PLAYER_A=1,JocGame.PLAYER_B=-1,JocGame.DRAW=2,"undefined"!=typeof document?JocGame.CLICK="ontouchstart"in document.documentElement?"touchstart":"click":JocGame.CLICK="click",JocGame.MOUSEMOVE_EVENT="touchmove mousemove",JocGame.MOUSEDOWN_EVENT="touchstart mousedown",JocGame.MOUSEUP_EVENT="touchend mouseup joclyclick",JocGame.MAX_VALUE=Math.pow(2,53),JocGame.prototype={},JocGame.prototype.Init=function(e){this.mWho=JocGame.PLAYER_A,this.mViewAs=JocGame.PLAYER_A,this.mTopLevel=3,this.mLoopMax=300,this.mPreventRepeat=!1,e&&(this.mOptions=e.game,this.mViewOptions=e.view,this.mSkin=this.mViewOptions.skins[0].name,this.mNotation=!1,this.mShowMoves=this.mViewOptions.useShowMoves,this.mSounds=!!this.mViewOptions.sounds,this.mAutoComplete=!1,void 0!==this.mOptions.level&&(this.mTopLevel=this.mOptions.level),void 0!==this.mOptions.loopMax&&(this.mLoopMax=this.mOptions.loopMax),this.mVisitedBoards={},void 0!==this.mOptions.viewAs?this.mViewAs=this.mOptions.viewAs:this.mOptions.viewAs=this.mViewAs),this.mNextSchedule=null,this.mPlayedMoves=[],this.mFullPlayedMoves=[],this.mViewInited=!1,this.mGameInited=!1,e&&e.initial?this.GameInitGame(e.initial):this.GameInitGame(),this.mBoard=new(this.GetBoardClass())(this),this.mBoard.InitialPosition&&this.mBoard.InitialPosition(this),this.mBoard.mMoves=[],this.mBoard.mWho=this.mWho,this.listeners=[]},JocGame.prototype.AddListener=function(e){this.listeners.push(e)},JocGame.prototype.RemoveListener=function(e){for(var t=this.listeners.length-1;t>=0;t--)this.listeners[t]==e&&this.listeners.splice(t,1)},JocGame.prototype.DispatchMessage=function(e){var t=this;this.listeners.forEach(function(o){o.call(t,e)})},JocGame.prototype.HumanMove=function(e){this.DispatchMessage({type:"human-move",move:e})},JocGame.prototype.MakeMove=function(e){this.HumanMove(e)},JocGame.prototype.MachineMove=function(e){this.DispatchMessage({type:"machine-move",result:e})},JocGame.prototype.MachineProgress=function(e){this.DispatchMessage({type:"machine-progress",progress:e})},JocGame.prototype.PlayMove=function(e){var t=this;return new Promise(function(o,i){t.mOldBoard=new(t.GetBoardClass())(t),t.mOldBoard.CopyFrom(t.mBoard),t.ApplyMove(e),t.MoveShown=function(){delete t.MoveShown,o()},t.mBoard.PlayedMove(t,e)&&(delete t.MoveShown,o())})},JocGame.prototype.InvertWho=function(){var e=this.GetWho();this.SetWho(-e)},JocGame.prototype.AttachElement=function(e,t){t=t||{};var o=this;return this.widget=e,new Promise(function(e,t){if(o.gamePreAttachProto)t(new Error("Game already attached"));else{var i={meta:{"jocly-xdview.js":{globals:{jQuery:"jquery.js",THREE:"three.js"}}}};i.meta["games/"+o.module+"/"+o.name+"-view.js"]={globals:{xdview:"jocly-xdview.js",jQuery:"jquery.js",THREE:"three.js"}}}SystemJS.config(i),Promise.all([SystemJS.import("jocly-xdview.js"),SystemJS.import("games/"+o.module+"/"+o.name+"-view.js")]).then(function(t){var i=t[0],s=t[1];o.gamePreAttachProto=Object.getPrototypeOf(o);var a=Object.assign({},o.gamePreAttachProto,i.view.Game,s.view.Game);Object.setPrototypeOf(o,a);var r=o.mBoardClass;o.boardPreAttachProto=r.prototype,Object.assign(r.prototype,o.boardPreAttachProto,i.view.Board,s.view.Board);var n=o.mMoveClass;o.movePreAttachProto=n.prototype,Object.assign(n.prototype,o.movePreAttachProto,s.view.Move),o.mGeometry={width:o.widget.clientWidth,height:o.widget.clientHeight},o.mWidget=jQuery(o.widget);var m=o.mViewOptions&&o.mViewOptions.defaultOptions;if(m){const h={mSkin:"skin",mNotation:"notation",mSounds:"sounds",mShowMoves:"moves",mAutoComplete:"autocomplete"};for(var d in h)void 0!==m[h[d]]&&(o[d]=m[h[d]])}o.UpdateSounds(),e()},function(e){t(e)})})},JocGame.prototype.DetachElement=function(){var e=this;return this.widget=element,new Promise(function(t,o){e.gamePreAttachProto?t():o(new Error("Game not attached"))})},JocGame.prototype.GetBoardClass=function(){return this.mBoardClass},JocGame.prototype.GetMoveClass=function(){return this.mMoveClass},JocGame.prototype.CreateMove=function(e){return new this.mMoveClass(e)},JocGame.prototype.CloneBoard=function(e){var t=new(this.GetBoardClass())(this);return t.CopyFrom(e),t},JocGame.prototype.InitView=function(){console.log("Abstract InitView called")},JocGame.prototype.LoadCss=function(){document.querySelectorAll("head link[class='jocly-css']").forEach(function(e){e.parentNode.removeChild(e)});var e=this,t=document.querySelector("head");(this.mViewOptions.css||[]).forEach(function(o){var i=document.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute("type","text/css"),i.setAttribute("class","jocly-css"),i.setAttribute("href",e.mViewOptions.fullPath+"/"+o),t.appendChild(i)})},JocGame.prototype.GameInitView=function(){this.mGeometry.width>0&&this.mGeometry.height>0&&(this.LoadCss(),this.InitView(),this.mViewInited=!0)},JocGame.prototype.DestroyView=function(){this.mWidget&&this.mWidget.empty()},JocGame.prototype.GameDestroyView=function(){this.mViewInited&&(this.DestroyView(),this.mViewInited=!1)},JocGame.prototype.CanPlaySound=function(e){return!0},JocGame.prototype.UpdateSounds=function(){function e(e,o,i){var s=$("<audio/>").attr("id","jocly-sound-"+e).attr("preload","auto");$("<source/>").attr("src",o+"/res/sounds/"+i+".ogg").attr("type","audio/ogg").appendTo(s),$("<source/>").attr("src",o+"/res/sounds/"+i+".mp3").attr("type","audio/mp3").appendTo(s),s.appendTo(t)}var t=$("#jocly-sounds");0==t.length&&(t=$("<div/>").attr("id","jocly-sounds").css({display:"none"}).appendTo($("body"))),t.empty();var o={useraction:"bells1",usermove:"bells1",win:"winblues",loss:"lose",end:"draw"};for(var i in o)e(i,this.config.baseURL,o[i]);if(this.config.view.sounds)for(var i in this.config.view.sounds)$("#jocly-sound-"+i).remove(),this.config.view.sounds[i]&&this.config.view.sounds[i]&&e(i,this.config.baseURL+"games/"+this.config.model.module,this.config.view.sounds[i])},JocGame.prototype.PlaySound=function(e){if(this.CanPlaySound(e)){var t=document.getElementById("jocly-sound-"+e);if(t&&this.mSounds)if(void 0===this.mNeedPhonegapMedia&&(this.mNeedPhonegapMedia=!1,this.mNeedPhonegapMedia=window&&window.cordova&&"undefined"!=typeof Media),this.mNeedPhonegapMedia){if(void 0===this.mPhonegapMediaLib&&(this.mPhonegapMediaLib={}),void 0===this.mPhonegapMediaLib[e]){for(var o=t.firstChild;o&&(!/source/i.test(o.nodeName)||"audio/mp3"!=o.getAttribute("type"));)o=o.nextSibling;if(o){var i=o.getAttribute("src"),s=/^([^#\?]*)\/[^#\?]+/.exec(window.location.pathname);s&&(i=i.replace(/^\./,s[1])),i=i.replace(/%20/g," "),this.mPhonegapMediaLib[e]=new Media(i,function(){},function(e){console.warn("Jocly PlaySound: Media did not play "+e.code)},function(e){})}else this.mPhonegapMediaLib[e]=null}this.mPhonegapMediaLib[e]&&this.mPhonegapMediaLib[e].play()}else t.cloneNode(!0).play()}},JocGame.prototype.InitGame=function(){},JocGame.prototype.GameInitGame=function(){0==this.mGameInited&&(this.mVisitedBoards={},arguments.length>0&&arguments[0]?this.mInitial=arguments[0]:this.mInitial=null,this.InitGame(),this.mGameInited=!0)},JocGame.prototype.DestroyGame=function(){},JocGame.prototype.GameDestroyGame=function(){if(this.mGameInited&&(this.DestroyGame(),this.mGameInited=!1),this.aiWorker)try{this.aiWorker.terminate(),delete this.aiWorker}catch(e){console.warn("Cannot terminate worker",e)}},JocGame.prototype.DisplayBoard=function(){this.mBoard.Display&&this.mBoard.Display(this)},JocGame.prototype.SetWho=function(e){this.mWho=e,this.mBoard.mWho=e},JocGame.prototype.GetWho=function(){return this.mWho},JocGame.prototype.HumanTurn=function(){this.mBoard.mMoves&&0!=this.mBoard.mMoves.length||(this.mCurrentLevel=-1,this.mBoard.GenerateMoves(this)),this.mBoard.HumanTurn(this)},JocGame.prototype.HumanTurnEnd=function(){this.mBoard.HumanTurnEnd(this)},JocGame.prototype.PlayedMove=function(e,t){return this.mOldBoard=t,this.mBoard.PlayedMove(this,e)},JocGame.prototype.ShowEnd=function(){return this.mBoard.ShowEnd(this)},JocGame.prototype.EvaluateBoard=function(){this.mBoard.mFinished=!1,this.mBoard.mMoves=[],this.mCurrentLevel=-1,this.mBoard.GenerateMoves(this),0==this.mBoard.mFinished&&this.mBoard.Evaluate(this,!0,!0)},JocGame.prototype.GetFinished=function(){return this.EvaluateBoard(),this.mBoard.mFinished?this.mBoard.mWinner:0},JocGame.prototype.IsValidMove=function(e){var t=new(this.GetMoveClass())(e);return this.mBoard.IsValidMove(this,t)},JocGame.prototype.AddVisit=function(e,t){e&&(t=e.GetSignature()),void 0===this.mVisitedBoards[t]?this.mVisitedBoards[t]=1:this.mVisitedBoards[t]++},JocGame.prototype.RemoveVisit=function(e,t){e&&(t=e.GetSignature());var o=this.mVisitedBoards[t];void 0!==o&&(o>1?this.mVisitedBoards[t]--:delete this.mVisitedBoards[t])};var engdbg_loops,engdbg_time,engdbg_t0;JocGame.prototype.StartMachine=function(e){if(engdbg_loops=0,engdbg_time=0,engdbg_t0=Date.now(),this.mDoneCallback=e.Done||this.MachineMove,this.mProgressCallback=e.Progress||this.MachineProgress,void 0!==e.level&&(this.mTopLevel=e.level),void 0!==e.maxDepth&&(this.mTopLevel=e.maxDepth),this.mStartTime=(new Date).getTime(),this.mExploredCount=0,this.mPickedMoveIndex=0,this.mBestMoves=[],this.mContexts=[],this.mDuration=0,this.mAborted=!1,this.mRandomSeed=0,e.randomSeed&&!isNaN(parseInt(e.randomSeed))&&(this.mRandomSeed=parseInt(e.randomSeed)),"function"==typeof this.mBoard.StaticGenerateMoves){var t=this.mBoard.StaticGenerateMoves(this);if(t&&t.length>0)return this.mBestMoves=t,void JocUtil.schedule(this,"Done",{})}this.mOptions.levelOptions&&(this.mOptions.levelOptionsSaved=JSON.parse(JSON.stringify(this.mOptions.levelOptions)),e.level&&Object.assign(this.mOptions.levelOptions,e.level));var o=e.threaded&&"object"==typeof window&&window.Worker;if(e.level&&"uct"==e.level.ai&&JoclyUCT)o?this.StartThreadedMachine(e,"uct"):JoclyUCT.startMachine(this,e);else if(o)this.StartThreadedMachine(e,"alpha-beta");else{this.mSavedVisitedBoards={};for(var i in this.mVisitedBoards)this.mSavedVisitedBoards[i]=this.mVisitedBoards[i];this.Engine(this.mBoard,this.mTopLevel,!1,0,e.potential),this.Run()}},JocGame.prototype.StartThreadedMachine=function(e,t){var o=this;delete e.Done,delete e.Progress;var i=Date.now();this.aiWorker||(this.aiWorker=new Worker(this.config.baseURL+"jocly.aiworker.js"),this.aiWorker.postMessage({type:"Init",baseURL:this.config.baseURL,options:e,t0:i})),this.aiWorker.onmessage=function(e){var t=e.data;switch(t.type){case"Progress":o.mProgressCallback(t.percent);break;case"Done":o.mBestMoves=t.data.moves,o.mPickedMoveIndex=t.data.moveIndex,o.mExploredCount=t.data.explored,o.mDuration=t.data.duration,o.mBoard.evaluation=t.data.evaluation,o.Done()}},this.aiWorker.postMessage({type:"Play",playedMoves:this.mPlayedMoves,gameOptions:this.mOptions,gameName:this.name,options:e,algo:t,t0:i})},JocGame.prototype.StopThreadedMachine=function(){if(this.aiWorker)try{this.aiWorker.terminate(),delete this.aiWorker}catch(e){console.warn("Cannot terminate worker",e)}},JocGame.prototype.ScheduleStep=function(){this.mNextSchedule=this.ExecuteStep},JocGame.prototype.Random=function(e){return this.mRandomSeed?this.mRandomSeed%e:Math.floor(Math.random()*e)},JocGame.prototype.ArrayShuffle=function(e){var t=e.length;if(!(t<=0))for(;--t;){var o;o=this.mRandomSeed?this.mRandomSeed%(t+1):Math.floor(Math.random()*(t+1));var i=e[t];e[t]=e[o],e[o]=i}},JocGame.prototype.Done=function(){if(this.mDuration=(new Date).getTime()-this.mStartTime,this.mOptions.levelOptionsSaved&&(this.mOptions.levelOptions=this.mOptions.levelOptionsSaved,this.mOptions.levelOptionsSaved=null),this.mSavedVisitedBoards&&(this.mVisitedBoards=this.mSavedVisitedBoards),this.mDoneCallback){this.mPickedMoveIndex=this.Random(this.mBestMoves.length);try{this.mProgressCallback&&this.mProgressCallback(100),this.mDoneCallback({moves:this.mBestMoves,move:this.mBestMoves[this.mPickedMoveIndex],moveIndex:this.mPickedMoveIndex,explored:this.mExploredCount,duration:this.mDuration,evaluation:this.mBoard.mEvaluation})}catch(e){JocLog("!!! Done:"+e,e.stack?e.stack:"")}}},JocGame.prototype.Run=function(){var e=Date.now();try{for(var t=(new Date).getTime();this.mNextSchedule&&(new Date).getTime()-t<20&&0==this.mAborted;){var o=this.mNextSchedule;this.mNextSchedule=null,o.call(this)}this.mAborted?this.mAbortCallback():this.mNextSchedule&&JocUtil.schedule(this,"Run",{})}catch(e){JocLog("JocGame.Run "+e+"\n"+e.stack)}var i=Date.now();engdbg_loops++,engdbg_time+=i-e},JocGame.prototype.Abort=function(e){var t=this;this.mAbortCallback=function(){t.mOptions.levelOptionsSaved&&(t.mOptions.levelOptions=t.mOptions.levelOptionsSaved,t.mOptions.levelOptionsSaved=null),t.mSavedVisitedBoards&&(t.mVisitedBoards=t.mSavedVisitedBoards,t.mSavedVisitedBoards=null),e()},this.mAborted=!0},JocGame.prototype.Engine=function(e,t,o,i,s){function a(e,t){return(t.evaluation-e.evaluation)*r.mBoard.mWho}var r={mBoard:e,mLevel:t,mBAlpha:o,mAlpha:i,mBestEvaluation:0,mMoveIndex:0,mNextBoard:null,mNextBoards:null};if(this.mContexts.push(r),r.mBoard.mFinished=!1,r.mBoard.mWinner=JocGame.DRAW,this.mCurrentLevel=t,void 0===r.mBoard.mMoves&&(r.mBoard.mMoves=[]),0==r.mBoard.mMoves.length&&r.mBoard.GenerateMoves(this),0==r.mBoard.mMoves.length&&0==r.mBoard.mFinished&&(r.mBoard.Evaluate(this,!0,!1),0==r.mBoard.mFinished&&(JocLog("!!! No move possible while not finished - player",this.mWho,"board",r.mBoard),r.mBoard.mFinished=!0)),r.mBoard.mFinished){switch(r.mBoard.mWinner){case JocGame.PLAYER_A:r.mBoard.mEvaluation=JocGame.MAX_VALUE-(this.mTopLevel-r.mLevel);break;case JocGame.PLAYER_B:r.mBoard.mEvaluation=-JocGame.MAX_VALUE+(this.mTopLevel-r.mLevel)}return r.mBestEvaluation=r.mBoard.mEvaluation,void this.ExecuteStep2()}if(r.mExploCtrl={exploFrom:this.mExploredCount,exploTo:this.mExploredCount+s},r.mBoard.QuickEvaluate){var n=[];for(var m in r.mBoard.mMoves){var h=r.mBoard.MakeAndApply(this,m),d=h.QuickEvaluate(this);n.push({move:r.mBoard.mMoves[m],board:h,evaluation:d})}n.sort(a),r.mBoard.mMoves=[],r.mNextBoards=[],void 0!==this.mOptions.capMoves&&(n=n.slice(0,this.mOptions.capMoves));for(var m in n)r.mBoard.mMoves.push(n[m].move),r.mNextBoards.push(n[m].board)}this.ExecuteStep()},JocGame.prototype.ExecuteStep=function(){this.mExploredCount++;var e=this.mContexts[this.mContexts.length-1];if(e.mNextBoards?e.mNextBoard=e.mNextBoards[e.mMoveIndex]:e.mNextBoard=e.mBoard.MakeAndApply(this,e.mMoveIndex),this.mProgressCallback){var t=null;if(e.mLevel==this.mTopLevel)t=Math.floor(100*e.mMoveIndex/e.mBoard.mMoves.length);else if(e.mLevel==this.mTopLevel-1){var o=this.mContexts[0],i=1/o.mBoard.mMoves.length;t=Math.floor(100*(o.mMoveIndex*i+e.mMoveIndex*i/e.mBoard.mMoves.length))}if(null!=t)try{this.mProgressCallback(t)}catch(e){}}var s=e.mNextBoard;if(s.mFinished=!1,s.mWinner=0,s.Evaluate(this,0==e.mLevel,!1,this),e.mLevel<0&&(s.mEvaluation=0),s.mFinished)switch(s.mWinner){case JocGame.PLAYER_A:s.mEvaluation=JocGame.MAX_VALUE-(this.mTopLevel-e.mLevel);break;case JocGame.PLAYER_B:s.mEvaluation=-JocGame.MAX_VALUE+(this.mTopLevel-e.mLevel);break;case JocGame.DRAW:s.mEvaluation=0}else if(e.mLevel==this.mTopLevel&&1==e.mBoard.mMoves.length);else if(e.mLevel>0){var a=(e.mExploCtrl.exploTo-this.mExploredCount)/e.mBoard.mMoves.length;if(a>=1)return s.mWho=-s.mWho,void this.Engine(s,e.mLevel-1,0!=e.mMoveIndex,e.mBestEvaluation,a)}this.ExecuteStep2()},JocGame.prototype.ExecuteStep2=function(){var e=this.mContexts[this.mContexts.length-1];if(e.mBoard.mMoves.length>0&&(0==e.mMoveIndex?(e.mBestEvaluation=e.mNextBoard.mEvaluation,e.mLevel==this.mTopLevel&&this.SetBest(e.mBoard.mMoves[0],e.mBoard)):e.mNextBoard.mWho>0?e.mNextBoard.mEvaluation>e.mBestEvaluation?(e.mBestEvaluation=e.mNextBoard.mEvaluation,e.mLevel==this.mTopLevel&&this.SetBest(e.mBoard.mMoves[e.mMoveIndex],e.mBoard)):e.mLevel==this.mTopLevel&&e.mNextBoard.mEvaluation==e.mBestEvaluation&&this.AddBest(e.mBoard.mMoves[e.mMoveIndex],e.mBoard):e.mNextBoard.mEvaluation<e.mBestEvaluation?(e.mBestEvaluation=e.mNextBoard.mEvaluation,e.mLevel==this.mTopLevel&&this.SetBest(e.mBoard.mMoves[e.mMoveIndex],e.mBoard)):e.mLevel==this.mTopLevel&&e.mNextBoard.mEvaluation==e.mBestEvaluation&&this.AddBest(e.mBoard.mMoves[e.mMoveIndex],e.mBoard)),e.mBoard.mEvaluation=e.mBestEvaluation,e.mBAlpha&&(e.mBoard.mWho==JocGame.PLAYER_A&&e.mBestEvaluation>e.mAlpha||e.mBoard.mWho==JocGame.PLAYER_B&&e.mBestEvaluation<e.mAlpha)&&(e.mMoveIndex=e.mBoard.mMoves.length-1),++e.mMoveIndex<e.mBoard.mMoves.length)this.ScheduleStep();else if(this.mContexts.pop(),this.mContexts.length>0){var e=this.mContexts[this.mContexts.length-1];e.mNextBoard.mWho=-e.mNextBoard.mWho,this.ExecuteStep2()}else delete e.mBoard.mMoves,this.Done()},JocGame.prototype.SetBest=function(e,t){var o=new(this.GetMoveClass())({});o.CopyFrom(e),this.mBestMoves=[o]},JocGame.prototype.AddBest=function(e,t){var o=new(this.GetMoveClass())({});o.CopyFrom(e),this.mBestMoves.push(o)},JocGame.prototype.GetRepeatOccurence=function(e){return this.mOptions.preventRepeat?this.mVisitedBoards[e.GetSignature()]:-1},JocGame.prototype.HandleRepeat=function(e){if(this.mOptions.preventRepeat){var t=e.GetSignature(!0);void 0===this.mVisitedBoards[t]?this.mVisitedBoards[t]=1:this.mVisitedBoards[t]++}},JocGame.prototype.UnhandleRepeat=function(e){if(this.mOptions.preventRepeat){var t=e.GetSignature(!0);1==this.mVisitedBoards[t]?delete this.mVisitedBoards[t]:this.mVisitedBoards[t]>1&&this.mVisitedBoards[t]--}},JocGame.prototype.ApplyMove=function(e){var t=new(this.GetMoveClass())({});t.CopyFrom(e),this.mPlayedMoves.push(t),this.mFullPlayedMoves.length<this.mPlayedMoves.length?this.mFullPlayedMoves.push(t):t.Equals(this.mFullPlayedMoves[this.mPlayedMoves.length-1])||(this.mFullPlayedMoves=this.mFullPlayedMoves.slice(0,this.mPlayedMoves.length-1),this.mFullPlayedMoves.push(t)),this.mBoard.ApplyMove(this,e),this.mBoard.mMoves=[],this.HandleRepeat(this.mBoard)},JocGame.prototype.BackTo=function(e,t){t||(t=this.mFullPlayedMoves),this.mWho=JocGame.PLAYER_A,this.mBoard=new(this.GetBoardClass())(this),this.mBoard.InitialPosition&&this.mBoard.InitialPosition(this),this.mInitial&&this.mInitial.turn&&(this.mWho=this.mInitial.turn),this.mBoard.mMoves=[],this.mBoard.mWho=this.mWho,this.mBestMoves=[],this.mVisitedBoards={},this.mPlayedMoves=[];for(var o=0;o<e;o++)this.mBoard.ApplyMove(this,t[o]),this.HandleRepeat(this.mBoard),this.mBoard.mWho=-this.mBoard.mWho,this.mPlayedMoves.push(t[o]);this.mWho=this.mBoard.mWho},JocGame.prototype.ExportInitialBoardState=function(e){if(!this.mInitialString)return null;if("function"!=typeof this.Import)return null;try{if(!this.Import("pjn",this.mInitialString).status)return null;var t=new(this.GetBoardClass())(this);t.InitialPosition&&t.InitialPosition(this);return{boardState:t.ExportBoardState(this,e),turn:t.mWho}}catch(e){return null}},JocGame.prototype.Load=function(e){if(this.mWho=JocGame.PLAYER_A,this.mBoard=new(this.GetBoardClass())(this),this.mBoard.mMoves=[],e.initialBoard){if("function"!=typeof this.Import)throw new Error("Import not supported");var t=this.Import("pjn",e.initialBoard);if(!t.status){var o=new Error("import failed");switch(t.error){case"parse":o=new Error("import failed: parse error");break;case"unsupported":o=new Error("import failed: unsupported format")}throw o}this.mInitial=t.initial,this.mInitial.turn&&(this.mWho=this.mInitial.turn),this.mInitialString=e.initialBoard}this.mBoard.InitialPosition&&this.mBoard.InitialPosition(this),this.mBoard.mWho=this.mWho,this.mBestMoves=[],this.mVisitedBoards={};var i=e.playedMoves;this.mPlayedMoves=[],this.mFullPlayedMoves=[];for(var s in i){var a=new(this.GetMoveClass())(i[s]);if(!this.IsValidMove(a))throw"invalid-move";this.mBoard.ApplyMove(this,a),this.HandleRepeat(this.mBoard),this.mBoard.mWho=-this.mBoard.mWho,this.mPlayedMoves.push(a),this.mFullPlayedMoves.push(a),this.mBoard.mMoves=[]}this.mWho=this.mBoard.mWho,0==this.mBoard.mFinished&&this.mBoard.Evaluate(this,!0,!0)},JocGame.prototype.CloseView=function(){},JocMove.prototype={},JocMove.prototype.CopyFrom=function(e){var t=JSON.parse(JSON.stringify(e));for(var o in t)this[o]=t[o]},JocMove.prototype.Equals=function(e){return JSON.stringify(this)==JSON.stringify(e)},JocMove.prototype.ToString=function(){return JSON.stringify(this)},JocMove.prototype.Strip=function(){return this},JocBoard.prototype={},JocBoard.prototype.Init=function(e){},JocBoard.prototype.InitBoard=function(e){this.mDepth=0,this.mMoves=[],this.mEvaluation=0,this.mFinished=!1,this.mWinner=0,this.Init(e)},JocBoard.prototype.CopyFrom=function(e){var t=e.mSignature;delete e.mSignature;var o=JSON.parse(JSON.stringify(e));for(var i in o)this[i]=o[i];e.mSignature=t},JocBoard.prototype.GetSignature=function(){if(arguments[0]||!this.mSignature){var e=this.mMoves;delete this.mMoves,delete this.mSignature,this.mSignature=JocUtil.md5(JSON.stringify(this)),this.mMoves=e}return this.mSignature},JocBoard.prototype.ApplyMove=function(e,t){JocLog("Method JocBoard:ApplyMove() must be overloaded")},JocBoard.prototype.GenerateMoves=function(e){JocLog("Method JocBoard:GenerateMoves() must be overloaded")},JocBoard.prototype.Evaluate=function(e,t,o){JocLog("Method JocBoard:Evaluate() must be overloaded"),this.mEvaluation=0},JocBoard.prototype.HumanTurn=function(){},JocBoard.prototype.HumanTurnEnd=function(){},JocBoard.prototype.PlayedMove=function(){},JocBoard.prototype.ShowEnd=function(){},JocBoard.prototype.MakeAndApply=function(e,t){var o=new(e.GetBoardClass())(e);return o.CopyFrom(this),o.mWho=this.mWho,o.mBoardClass=this.mBoardClass,o.ApplyMove(e,this.mMoves[t]),o.mMoves=[],o},JocBoard.prototype.IsValidMove=function(e,t){"function"!=typeof t.Equals&&(t=e.CreateMove(t)),this.mMoves&&0!=this.mMoves.length||(this.mCurrentLevel=-1,this.GenerateMoves(e));for(var o in this.mMoves)if(t.Equals(this.mMoves[o]))return!0;return console.error("Invalid move "+JSON.stringify(t)+" in "+JSON.stringify(this.mMoves)),!1},JocBoard.prototype.PushMove=function(e,t){this.mMoves.push(e.CreateMove(t))},JocBoard.prototype.GenerateMoveObjects=function(e){var t=[];this.mMoves=[],this.GenerateMoves(e);for(var o=0;o<this.mMoves.length;o++)t.push(e.CreateMove(this.mMoves[o]));this.mMoves=t},JocBoard.prototype.ExportBoardState=function(e){return JSON.stringify(this)},JocGame.prototype.GetBestMatchingMove=function(e,t){var o=[],i=this;t.forEach(function(e){"function"==typeof e.ToString?o.push(e.ToString()):o.push(i.CreateMove(e).ToString())});var s=1/0,a=[];if(t.forEach(function(t,i){var r=JocGame.Levenshtein(e,o[i])/(Math.max(o[i].length,e.length)+1);r==s?a.push(i):r<s&&(a=[i],s=r)}),1==a.length)return t[a[0]];var r=a,n=[];return r.forEach(function(t){var i=o[t];(e.indexOf(i)>=0||i.indexOf(e)>=0)&&n.push(t)}),1==n.length?t[n[0]]:(s=1/0,a=[],r.forEach(function(t){var i=0,r=e.replace(/[A-Z]/g,""),n=o[t].replace(/[A-Z]/g,"");i+=JocGame.Levenshtein(r,n)/(Math.max(r.length,n.length)+1),i+=r.indexOf(n)>=0||n.indexOf(r)>=0?0:1,r=e.replace(/[a-z]/g,""),n=o[t].replace(/[a-z]/g,""),i+=JocGame.Levenshtein(r,n)/(Math.max(r.length,n.length)+1),i+=r.indexOf(n)>=0||n.indexOf(r)>=0?0:1,i==s?a.push(t):i<s&&(a=[t],s=i)}),1==a.length?t[a[0]]:null)},JocBoard.prototype.PickMoveFromDatabase=function(e,t){if(!this.mMoves||0==this.mMoves.length){var o=[];this.mMoves=[],this.GenerateMoves(e);for(var i=0;i<this.mMoves.length;i++)o.push(e.CreateMove(this.mMoves[i]));this.mMoves=o}if(0==this.mMoves.length)return null;var s=this.mWho+"#"+this.GetSignature(),a=t[s];if(!a)return null;for(var r=0,i=0;i<a.length;i++)r+=a[i].e;for(var n=Math.random()*r,m=0,i=0;i<a.length;i++){var h=a[i];if((m+=h.e)>n){var d=e.GetBestMatchingMove(h.m,this.mMoves);if(d)return[d]}}return null},JocBoard.prototype.CompactMoveString=function(e,t){return"function"!=typeof t.ToString&&(t=e.CreateMove(t)),t.ToString()},JocGame.Zobrist=function(e){var t=new MersenneTwister(12345),o=[];for(var i in e)o.push(i);o.sort(),this.seed={};for(var s=0;s<o.length;s++){for(var i=o[s],a=e[i],r={values:{},seeds:[]},n=0,m=0;m<a.values.length;m++)r.values[a.values[m]]=n++;switch(a.type){case"array":for(var h=0;h<a.size;h++){for(var d=[],l=0;l<n;l++)d.push(t.genrand_int32());r.seeds.push(d)}r.type="array";break;default:for(var l=0;l<n;l++)r.seeds.push(t.genrand_int32());r.type="simple"}this.seed[i]=r}},JocGame.Zobrist.prototype={update:function(e,t){var o=this.seed[t];if(void 0===o)return console.error("Unknown Zobrist parameter",t),0;var i=o.values[arguments[2]];if(void 0===i)return console.error("Undeclared Zobrist value",arguments[2],"as param",t),0;switch(o.type){case"simple":e^=o.seeds[i];break;case"array":var s=o.seeds[arguments[3]];if(void 0===s)return console.error("Undeclared Zobrist array index",arguments[3],"as param",t),0;e^=s[i]}return e}},JocGame.Levenshtein=function(e,t){if(e==t)return 0;var o=e.length,i=t.length;if(0===o)return i;if(0===i)return o;var s=!1;try{s=!"0"[0]}catch(e){s=!0}s&&(e=e.split(""),t=t.split(""));for(var s=Array(o+1),a=Array(o+1),r=0,n=0,m=0,r=0;r<o+1;r++)s[r]=r;for(var h="",d="",n=1;n<=i;n++){for(a[0]=n,d=t[n-1],r=0;r<o;r++){var h=e[r],m=h==d?0:1,h=s[r+1]+1,l=a[r]+1,m=s[r]+m;l<h&&(h=l),m<h&&(h=m),a[r+1]=h}r=s,s=a,a=r}return s[o]};