1 line
2.1 KiB
JavaScript
1 line
2.1 KiB
JavaScript
(function(){"use strict";class O{constructor(t){this.rank=t[0],this.suit=t[1]}get integerValue(){return"A23456789TJQK".indexOf(this.rank)}isSequential(t){return(this.integerValue+13+1)%13===t.integerValue||(this.integerValue+13-1)%13===t.integerValue}get toString(){return this.rank+this.suit}}class v{constructor(t){this.array=t}get isCleared(){return this.array.every(t=>t===0)}get freeCardIndices(){let t=[];for(let e=this.array.length-1;e>=0;e--){if(this.array[e]===0)continue;const n=Math.floor((e-3)/2);(e>=18||e<=17&&e>=9&&this.array[e+9]===0&&this.array[e+10]===0||e<=8&&e>=3&&this.array[e+6+n]===0&&this.array[e+7+n]===0||e<=2&&e>=0&&this.array[e+3+e]===0&&this.array[e+4+e]===0)&&t.push(e)}return t}}class o{static gameWon(){return"You have won."}static gameLost(){return"There are no more valid moves."}static match(t){return"Move "+t+" onto the stock."}static flipStock(){return"Draw a new stock card."}}const l=Object.freeze({won:!0,lost:!1});function g(r,t){let e=r.filter(a=>a.startsWith("Move")).length;return t.filter(a=>a.startsWith("Move")).length>e?t:r}async function h(r,t,e=null,n=0,a=[],d=[]){let i=JSON.parse(JSON.stringify(a)),s=JSON.parse(JSON.stringify(d)),J=new v(r);if(s=g(s,i),s=JSON.parse(JSON.stringify(s)),e&&e.postMessage({msg:"solve-progress",moveCount:s.length}),J.isCleared)return i.push(o.gameWon()),[l.won,i,[]];if(n>=t.length)return i.push(o.gameLost()),[l.lost,i,s];const m=new O(t[n]);let f=J.freeCardIndices;for(let u=0;u<f.length;u++){let S=new O(r[f[u]]);if(!S.isSequential(m))continue;let N=JSON.parse(JSON.stringify(t));N.splice(++n,0,S.toString),i=JSON.parse(JSON.stringify(a)),i.push(o.match(S.toString));let y=JSON.parse(JSON.stringify(r));y[f[u]]=0;let p=await h(y,N,e,n,i,s);if(p[0]===l.won)return p;s=g(s,p[2]),s=JSON.parse(JSON.stringify(s))}i=JSON.parse(JSON.stringify(a)),i.push(o.flipStock());let c=await h(r,t,e,++n,i,s);return c[0]===l.won?c:(s=g(s,c[2]),s=JSON.parse(JSON.stringify(s)),[l.lost,a,s])}const w=async r=>{let t=await h(r.slice(0,28),r.slice(28,52),self);postMessage({msg:"solve-result",result:t})};addEventListener("message",async r=>{r.data.msg==="try-to-solve"&&w(r.data.game)})})();
|