@vue-skuilder/courseware 0.1.32-f → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/CourseWare.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.mjs +15 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/CourseWare.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CourseWare.d.ts","sourceRoot":"","sources":["../src/CourseWare.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAGrE,qBAAa,UAAU;IACrB,IAAW,SAAS,IAAI,KAAK,CAAC,OAAO,WAAW,CAAC,CAEhD;IAED,IAAW,QAAQ,IAAI,KAAK,CAAC,aAAa,CAAC,CAU1C;IAED;;;OAGG;IACH,IAAW,WAAW,IAAI;QAAE,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAAA;KAAE,CAY3D;IACD,SAAgB,IAAI,EAAE,MAAM,CAAC;IAC7B,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA4B;gBAE7C,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,KAAK,CAAC,OAAO,WAAW,CAAC;IAO1D,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,WAAW,GAAG,SAAS;
|
|
1
|
+
{"version":3,"file":"CourseWare.d.ts","sourceRoot":"","sources":["../src/CourseWare.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAGrE,qBAAa,UAAU;IACrB,IAAW,SAAS,IAAI,KAAK,CAAC,OAAO,WAAW,CAAC,CAEhD;IAED,IAAW,QAAQ,IAAI,KAAK,CAAC,aAAa,CAAC,CAU1C;IAED;;;OAGG;IACH,IAAW,WAAW,IAAI;QAAE,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAAA;KAAE,CAY3D;IACD,SAAgB,IAAI,EAAE,MAAM,CAAC;IAC7B,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA4B;gBAE7C,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,KAAK,CAAC,OAAO,WAAW,CAAC;IAO1D,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,WAAW,GAAG,SAAS;IA6CzD,aAAa,IAAI,KAAK,CAAC,OAAO,WAAW,CAAC;CAMlD"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./shapes-DJ-ujuDr.cjs`);let t=require(`vue`),n=require(`@vue-skuilder/common-ui`),r=require(`@vue-skuilder/common`),a=require(`moment`);a=e.o(a);let o=require(`@vue-skuilder/db`);function randomInt(e,t){return Math.floor(Math.random()*(t-e+1))+e}function shuffle(e){let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}function cos(e){return Math.cos(toRadians(e))}function sin(e){return Math.sin(toRadians(e))}function toRadians(e){return e/360*2*Math.PI}function gradeSpellingAttempt(e,t){let n=Array(t.length).fill(`_`),r=e.split(``);console.log(e,t),console.log(`Attempt char codes:`,e.split(``).map(e=>e.charCodeAt(0))),console.log(`Answer char codes:`,t.split(``).map(e=>e.charCodeAt(0)));for(let e=0;e<t.length;e++)e<r.length&&r[e]===t[e]&&(n[e]=r[e],r[e]=``);for(let e=t.length-1;e>=0;e--)if(n[e]===`_`){let a=r.findIndex(n=>n===t[e]);a!==-1&&(n[e]=t[e],r[a]=``)}return console.log(n.join(` `)),n.join(` `)}var c=(0,t.defineComponent)({name:`FillInView`,components:{MarkdownRenderer:(0,t.defineAsyncComponent)(()=>import(`@vue-skuilder/common-ui`).then(e=>e.MarkdownRenderer)),RadioMultipleChoice:n.RadioMultipleChoice,AudioAutoPlayer:n.AudioAutoPlayer},props:{data:{type:Array,required:!0},modifyDifficulty:{type:Number,required:!1,default:0}},setup(e,{emit:r}){let a=(0,n.useViewable)(e,r,`FillInView`),o=(0,n.useQuestionView)(a);o.question.value=new g(e.data);let c=(0,t.ref)(),l=(0,t.computed)(()=>{if(!o.question.value)throw a.logger.error(`Question not initialized`),Error(`Question not initialized`);return o.question.value});(0,t.onMounted)(()=>{try{o.question.value||(o.question.value=new g(e.data)),o.question.value.options&&(c.value=shuffle(getTruncatedList()))}catch(e){a.logger.error(`Failed to initialize question:`,e)}}),(0,t.onUnmounted)(()=>{o.question.value=void 0});let u=(0,t.computed)(()=>c.value??[]),d=(0,t.computed)(()=>!!e.data[0][`image-1`]),p=(0,t.computed)(()=>{if(!d.value)return[``];let t=[],n=1;for(;e.data[0][`image-${n}`];)t.push(URL.createObjectURL(e.data[0][`image-${n}`])),n++;return t}),m=(0,t.computed)(()=>!!e.data[0][`audio-1`]),h=(0,t.computed)(()=>l.value?.mdText||``),_=(0,t.computed)(()=>{if(!m.value)return[``];let t=[],n=1;for(;e.data[0][`audio-${n}`];)t.push(URL.createObjectURL(e.data[0][`audio-${n}`])),n++;return t}),y=(0,t.computed)(()=>{if(l.value.answers)return l.value.answers[Math.floor(l.value.answers.length*Math.random())];throw Error(`No answers provided`)}),b=(0,t.computed)(()=>{let e=y.value;if(console.log(`Prior answers: ${o.priorAnswers.value}`),e&&o.priorAnswers.value[0]?.[0]&&o.priorAnswers.value[0][1]===`UserInputString`)return gradeSpellingAttempt(o.priorAnswers.value[0][0],e);if(console.log(`found no UserInputString`),y.value){let e=``;for(let t=0;t<y.value.length;t++)e+=`_ `;return e}return``}),x=(0,t.computed)(()=>!!(l.value.answers&&l.value.answers.length>0)),getTruncatedList=()=>{if(!l.value?.options)return;if(l.value.options.length<=6)return l.value.options;let t=[];t.push(l.value.answers[Math.floor(Math.random()*l.value.answers.length)]);let n=shuffle(l.value.options.filter(e=>l.value.answers?.indexOf(e)===-1));return e.modifyDifficulty&&(console.log(`Modifying difficulty: ${e.modifyDifficulty}`),n=e.modifyDifficulty<-200?n.slice(0,1):e.modifyDifficulty<-150?n.slice(0,2):e.modifyDifficulty<-100?n.slice(0,3):e.modifyDifficulty<-50?n.slice(0,4):n.slice(0,5)),t.push(...n.slice(0,5)),t},handleNext=()=>{o.submitAnswer(``)};return(0,t.watch)(()=>e.data,e=>{try{o.question.value=new g(e),o.question.value?.options&&(c.value=shuffle(getTruncatedList()))}catch(e){a.logger.error(`Failed to initialize/update question:`,e)}},{deep:!0}),{...a,...o,question:l,truncatedOptions:u,hasImage:d,imageURLs:p,hasAudio:m,audioURL:_,obscuredAnswer:b,someAnswer:y,isQuestion:x,handleNext,markdownText:h}}}),l=e.a((e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},`default`),u={"data-viewable":`FillInView`},d=[`src`],p={key:4,class:`text-center text-h6`},m={key:5,class:`text-center text-h6`};function _sfc_render$25(e,n,r,a,o,c){let l=(0,t.resolveComponent)(`audio-auto-player`),h=(0,t.resolveComponent)(`markdown-renderer`),g=(0,t.resolveComponent)(`radio-multiple-choice`),_=(0,t.resolveComponent)(`v-spacer`),y=(0,t.resolveComponent)(`v-btn`),b=(0,t.resolveComponent)(`v-card-actions`);return(0,t.openBlock)(),(0,t.createElementBlock)(`div`,u,[e.hasAudio?((0,t.openBlock)(),(0,t.createBlock)(l,{key:0,src:e.audioURL},null,8,[`src`])):(0,t.createCommentVNode)(``,!0),e.hasImage?((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,{key:1},(0,t.renderList)(e.imageURLs,(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`img`,{key:n,src:e},null,8,d))),128)):(0,t.createCommentVNode)(``,!0),e.markdownText?((0,t.openBlock)(),(0,t.createBlock)(h,{key:2,md:e.markdownText},null,8,[`md`])):(0,t.createCommentVNode)(``,!0),e.question?.options?((0,t.openBlock)(),(0,t.createBlock)(g,{key:3,"choice-list":e.truncatedOptions},null,8,[`choice-list`])):e.priorAttempts==1?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,p,[(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(e.obscuredAnswer),1)])):e.priorAttempts==2?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,m,[(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(e.someAnswer),1)])):(0,t.createCommentVNode)(``,!0),e.isQuestion?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createBlock)(b,{key:6},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(_),(0,t.createVNode)(y,{color:`primary`,autofocus:`autofocus`,onClick:e.handleNext},{default:(0,t.withCtx)(()=>n[0]||=[(0,t.createTextVNode)(` Next `)]),_:1},8,[`onClick`])]),_:1}))])}e.a(_sfc_render$25,`_sfc_render`);var h=l(c,[[`render`,_sfc_render$25],[`__scopeId`,`data-v-f91502f8`]]);function splitText(e,t,n){let r=e.split(t),a=r[0],o=r[1].split(n);return{left:a,middle:o[0],right:o[1]}}var g=class BlanksCard extends n.Question{static dataShapes=e.r;static views=[h];mdText=``;answers=null;options=null;splitTextToken(e){if((0,n.containsComponent)(e)){let t=splitText(e.text,`{{`,`}}`),n=splitText(e.raw,`{{`,`}}`),r=[];return n.left.length>0&&r.push({type:`text`,raw:n.left,text:t.left}),n.middle.length>0&&r.push({type:`text`,raw:`{{`+n.middle+`}}`,text:`{{`+t.middle+`}}`}),n.right.length>0&&r.push({type:`text`,raw:n.right,text:t.right}),r}else return[e]}optionsFromString(e){if(!e.startsWith(`{{`)||!e.endsWith(`}}`))throw Error(`string ${e} is not fill-in text - must look like "{{someText}}"`);e=e.substring(2,e.length-2);let t=e.split(`||`);if(t.length>1){let e=t[0].split(`|`).map(e=>e.trim()),n=t[1].split(`|`).map(e=>e.trim()).filter(t=>!e.includes(t));return n.push(e[randomInt(0,e.length-1)]),{answers:e,options:shuffle(n)}}else return{answers:[e.trim()],options:null}}constructor(e){super(e),this.mdText=e[0].Input,this.mdText===void 0&&(this.mdText=``);let t=(0,n.splitByDelimiters)(this.mdText,`{{`,`}}`),r=[];for(let e=0;e<t.length;e++){let a=t[e],o=a.trim();if(o.startsWith(`{{`)&&o.endsWith(`}}`))if((0,n.isInlineComponent)(o.slice(2,-2).trim()))r.push(a);else try{let e=this.optionsFromString(a);this.answers=e.answers,this.options=e.options,this.options?.length?r.push(`{{ || }}`):r.push(`{{ }}`)}catch{r.push(a)}else r.push(a)}this.mdText=r.join(``)}isCorrect(e){if(console.log(`answers:${this.answers}\nuser answer: ${JSON.stringify(e)}`),typeof e==`string`){if(this.answers)return this.answers.includes(e);if(e===``)return!0;throw Error(`Question has no configured answers!`)}else if(Array.isArray(e)){if(this.answers)return e.every(e=>this.answers.includes(e));throw Error(`Question has no configured answers!`)}else return this.isCorrectRadio(e)}dataShapes(){return BlanksCard.dataShapes}views(){return BlanksCard.views}isCorrectRadio(e){return this.answers?this.answers.includes(e.choiceList[e.selection]):!1}},CourseWare=class{get questions(){return this.questionList}get allViews(){let e=[];return this.questionList.forEach(t=>{t.views.forEach(t=>{e.push(t)})}),e}get allViewsMap(){let e={};return this.allViews.forEach(t=>{if(t.name)e[t.name]=t;else throw Error(`View has no name`)}),e}name;questionList;constructor(e,t){this.name=e,this.questionList=t,this.questionList=this.questionList.concat(this.getBaseQTypes())}getQuestion(e){return this.questionList.find(t=>{let n=t.name.replace(/^_/,``).replace(/\d+$/,``),r=e.replace(/^_/,``).replace(/\d+$/,``);return t.name===e||n===r||t.name.includes(r)||e.includes(n)})}getBaseQTypes(){return[g]}},_=new CourseWare(`default`,[g]),y=[`cg-white`,`cg-black`],b=[`a`,`b`,`c`,`d`,`e`,`f`,`g`,`h`],x=[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`],S=[...x].reverse(),C=Array.prototype.concat(...b.map(e=>x.map(t=>e+t))),pos2key=e=>C[8*e[0]+e[1]],key2pos=e=>[e.charCodeAt(0)-97,e.charCodeAt(1)-49],w=C.map(key2pos);function memo(e){let t,ret=()=>(t===void 0&&(t=e()),t);return ret.clear=()=>{t=void 0},ret}var timer=()=>{let e;return{start(){e=performance.now()},cancel(){e=void 0},stop(){if(!e)return 0;let t=performance.now()-e;return e=void 0,t}}},opposite=e=>e===`cg-white`?`cg-black`:`cg-white`,distanceSq=(e,t)=>{let n=e[0]-t[0],r=e[1]-t[1];return n*n+r*r},samePiece=(e,t)=>e.role===t.role&&e.color===t.color,posToTranslate=e=>(t,n)=>[(n?t[0]:7-t[0])*e.width/8,(n?7-t[1]:t[1])*e.height/8],translate=(e,t)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px)`},translateAndScale=(e,t,n=1)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px) scale(${n})`},setVisible=(e,t)=>{e.style.visibility=t?`visible`:`hidden`},eventPosition=e=>{if(e.clientX||e.clientX===0)return[e.clientX,e.clientY];if(e.targetTouches?.[0])return[e.targetTouches[0].clientX,e.targetTouches[0].clientY]},isRightButton=e=>e.button===2,createEl=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};function computeSquareCenter(e,t,n){let r=key2pos(e);return t||(r[0]=7-r[0],r[1]=7-r[1]),[n.left+n.width*r[0]/8+n.width/16,n.top+n.height*(7-r[1])/8+n.height/16]}var diff=(e,t)=>Math.abs(e-t),pawn=e=>(t,n,r,a)=>diff(t,r)<2&&(e===`cg-white`?a===n+1||n<=1&&a===n+2&&t===r:a===n-1||n>=6&&a===n-2&&t===r),knight=(e,t,n,r)=>{let a=diff(e,n),o=diff(t,r);return a===1&&o===2||a===2&&o===1},bishop=(e,t,n,r)=>diff(e,n)===diff(t,r),rook=(e,t,n,r)=>e===n||t===r,queen=(e,t,n,r)=>bishop(e,t,n,r)||rook(e,t,n,r),king=(e,t,n)=>(r,a,o,c)=>diff(r,o)<2&&diff(a,c)<2||n&&a===c&&a===(e===`cg-white`?0:7)&&(r===4&&(o===2&&t.includes(0)||o===6&&t.includes(7))||t.includes(o));function rookFilesOf(e,t){let n=t===`cg-white`?`1`:`8`,r=[];for(let[a,o]of e)a[1]===n&&o.color===t&&o.role===`rook`&&r.push(key2pos(a)[0]);return r}function premove(e,t,n){let r=e.get(t);if(!r)return[];let a=key2pos(t),o=r.role,c=o===`pawn`?pawn(r.color):o===`knight`?knight:o===`bishop`?bishop:o===`rook`?rook:o===`queen`?queen:king(r.color,rookFilesOf(e,r.color),n);return w.filter(e=>(a[0]!==e[0]||a[1]!==e[1])&&c(a[0],a[1],e[0],e[1])).map(pos2key)}function callUserFunction(e,...t){e&&setTimeout(()=>e(...t),1)}function toggleOrientation(e){e.orientation=opposite(e.orientation),e.animation.current=e.draggable.current=e.selected=void 0}function setPieces(e,t){for(let[n,r]of t)r?e.pieces.set(n,r):e.pieces.delete(n)}function setCheck(e,t){if(e.check=void 0,t===!0&&(t=e.turnColor),t)for(let[n,r]of e.pieces)r.role===`king`&&r.color===t&&(e.check=n)}function setPremove(e,t,n,r){unsetPredrop(e),e.premovable.current=[t,n],callUserFunction(e.premovable.events.set,t,n,r)}function unsetPremove(e){e.premovable.current&&(e.premovable.current=void 0,callUserFunction(e.premovable.events.unset))}function setPredrop(e,t,n){unsetPremove(e),e.predroppable.current={role:t,key:n},callUserFunction(e.predroppable.events.set,t,n)}function unsetPredrop(e){let t=e.predroppable;t.current&&(t.current=void 0,callUserFunction(t.events.unset))}function tryAutoCastle(e,t,n){if(!e.autoCastle)return!1;let r=e.pieces.get(t);if(!r||r.role!==`king`)return!1;let a=key2pos(t),o=key2pos(n);if(a[1]!==0&&a[1]!==7||a[1]!==o[1])return!1;a[0]===4&&!e.pieces.has(n)&&(o[0]===6?n=pos2key([7,o[1]]):o[0]===2&&(n=pos2key([0,o[1]])));let c=e.pieces.get(n);return!c||c.color!==r.color||c.role!==`rook`?!1:(e.pieces.delete(t),e.pieces.delete(n),a[0]<o[0]?(e.pieces.set(pos2key([6,o[1]]),r),e.pieces.set(pos2key([5,o[1]]),c)):(e.pieces.set(pos2key([2,o[1]]),r),e.pieces.set(pos2key([3,o[1]]),c)),!0)}function baseMove(e,t,n){let r=e.pieces.get(t),a=e.pieces.get(n);if(t===n||!r)return!1;let o=a&&a.color!==r.color?a:void 0;return n===e.selected&&unselect(e),callUserFunction(e.events.move,t,n,o),tryAutoCastle(e,t,n)||(e.pieces.set(n,r),e.pieces.delete(t)),e.lastMove=[t,n],e.check=void 0,callUserFunction(e.events.change),o||!0}function baseNewPiece(e,t,n,r){if(e.pieces.has(n))if(r)e.pieces.delete(n);else return!1;return callUserFunction(e.events.dropNewPiece,t,n),e.pieces.set(n,t),e.lastMove=[n],e.check=void 0,callUserFunction(e.events.change),e.movable.dests=void 0,e.turnColor=opposite(e.turnColor),!0}function baseUserMove(e,t,n){let r=baseMove(e,t,n);return r&&(e.movable.dests=void 0,e.turnColor=opposite(e.turnColor),e.animation.current=void 0),r}function userMove(e,t,n){if(canMove(e,t,n)){let r=baseUserMove(e,t,n);if(r){let a=e.hold.stop();unselect(e);let o={premove:!1,ctrlKey:e.stats.ctrlKey,holdTime:a};return r!==!0&&(o.captured=r),callUserFunction(e.movable.events.after,t,n,o),!0}}else if(canPremove(e,t,n))return setPremove(e,t,n,{ctrlKey:e.stats.ctrlKey}),unselect(e),!0;return unselect(e),!1}function dropNewPiece(e,t,n,r){let a=e.pieces.get(t);a&&(canDrop(e,t,n)||r)?(e.pieces.delete(t),baseNewPiece(e,a,n,r),callUserFunction(e.movable.events.afterNewPiece,a.role,n,{premove:!1,predrop:!1})):a&&canPredrop(e,t,n)?setPredrop(e,a.role,n):(unsetPremove(e),unsetPredrop(e)),e.pieces.delete(t),unselect(e)}function selectSquare(e,t,n){if(callUserFunction(e.events.select,t),e.selected){if(e.selected===t&&!e.draggable.enabled){unselect(e),e.hold.cancel();return}else if((e.selectable.enabled||n)&&e.selected!==t&&userMove(e,e.selected,t)){e.stats.dragged=!1;return}}(e.selectable.enabled||e.draggable.enabled)&&(isMovable(e,t)||isPremovable(e,t))&&(setSelected(e,t),e.hold.start())}function setSelected(e,t){e.selected=t,isPremovable(e,t)?e.premovable.customDests||(e.premovable.dests=premove(e.pieces,t,e.premovable.castle)):e.premovable.dests=void 0}function unselect(e){e.selected=void 0,e.premovable.dests=void 0,e.hold.cancel()}function isMovable(e,t){let n=e.pieces.get(t);return!!n&&(e.movable.color===`both`||e.movable.color===n.color&&e.turnColor===n.color)}var canMove=(e,t,n)=>t!==n&&isMovable(e,t)&&(e.movable.free||!!e.movable.dests?.get(t)?.includes(n));function canDrop(e,t,n){let r=e.pieces.get(t);return!!r&&(t===n||!e.pieces.has(n))&&(e.movable.color===`both`||e.movable.color===r.color&&e.turnColor===r.color)}function isPremovable(e,t){let n=e.pieces.get(t);return!!n&&e.premovable.enabled&&e.movable.color===n.color&&e.turnColor!==n.color}function canPremove(e,t,n){let r=e.premovable.customDests?.get(t)??premove(e.pieces,t,e.premovable.castle);return t!==n&&isPremovable(e,t)&&r.includes(n)}function canPredrop(e,t,n){let r=e.pieces.get(t),a=e.pieces.get(n);return!!r&&(!a||a.color!==e.movable.color)&&e.predroppable.enabled&&(r.role!==`pawn`||n[1]!==`1`&&n[1]!==`8`)&&e.movable.color===r.color&&e.turnColor!==r.color}function isDraggable(e,t){let n=e.pieces.get(t);return!!n&&e.draggable.enabled&&(e.movable.color===`both`||e.movable.color===n.color&&(e.turnColor===n.color||e.premovable.enabled))}function playPremove(e){let t=e.premovable.current;if(!t)return!1;let n=t[0],r=t[1],a=!1;if(canMove(e,n,r)){let t=baseUserMove(e,n,r);if(t){let o={premove:!0};t!==!0&&(o.captured=t),callUserFunction(e.movable.events.after,n,r,o),a=!0}}return unsetPremove(e),a}function playPredrop(e,t){let n=e.predroppable.current,r=!1;return n?(t(n)&&baseNewPiece(e,{role:n.role,color:e.movable.color},n.key)&&(callUserFunction(e.movable.events.afterNewPiece,n.role,n.key,{premove:!1,predrop:!0}),r=!0),unsetPredrop(e),r):!1}function cancelMove(e){unsetPremove(e),unsetPredrop(e),unselect(e)}function stop(e){e.movable.color=e.movable.dests=e.animation.current=void 0,cancelMove(e)}function getKeyAtDomPos(e,t,n){let r=Math.floor(8*(e[0]-n.left)/n.width);t||(r=7-r);let a=7-Math.floor(8*(e[1]-n.top)/n.height);return t||(a=7-a),r>=0&&r<8&&a>=0&&a<8?pos2key([r,a]):void 0}function getSnappedKeyAtDomPos(e,t,n,r){let a=key2pos(e),o=w.filter(e=>queen(a[0],a[1],e[0],e[1])||knight(a[0],a[1],e[0],e[1])),c=o.map(e=>computeSquareCenter(pos2key(e),n,r)).map(e=>distanceSq(t,e)),[,l]=c.reduce((e,t,n)=>e[0]<t?e:[t,n],[c[0],0]);return pos2key(o[l])}var whitePov=e=>e.orientation===`cg-white`,T=`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR`,E={p:`pawn`,r:`rook`,n:`knight`,b:`bishop`,q:`queen`,k:`king`},D={pawn:`p`,rook:`r`,knight:`n`,bishop:`b`,queen:`q`,king:`k`};function read(e){e===`start`&&(e=T);let t=new Map,n=7,r=0;for(let a of e)switch(a){case` `:case`[`:return t;case`/`:if(--n,n<0)return t;r=0;break;case`~`:{let e=t.get(pos2key([r-1,n]));e&&(e.promoted=!0);break}default:{let e=a.charCodeAt(0);if(e<57)r+=e-48;else{let e=a.toLowerCase();t.set(pos2key([r,n]),{role:E[e],color:a===e?`cg-black`:`cg-white`}),++r}}}return t}function write(e){return S.map(t=>b.map(n=>{let r=e.get(n+t);if(r){let e=D[r.role];return r.color===`cg-white`&&(e=e.toUpperCase()),r.promoted&&(e+=`~`),e}else return`1`}).join(``)).join(`/`).replace(/1{2,}/g,e=>e.length.toString())}function applyAnimation(e,t){t.animation&&(deepMerge(e.animation,t.animation),(e.animation.duration||0)<70&&(e.animation.enabled=!1))}function configure(e,t){if(t.movable?.dests&&(e.movable.dests=void 0),t.drawable?.autoShapes&&(e.drawable.autoShapes=[]),deepMerge(e,t),t.fen&&(e.pieces=read(t.fen),e.drawable.shapes=t.drawable?.shapes||[]),`check`in t&&setCheck(e,t.check||!1),`lastMove`in t&&!t.lastMove?e.lastMove=void 0:t.lastMove&&(e.lastMove=t.lastMove),e.selected&&setSelected(e,e.selected),applyAnimation(e,t),!e.movable.rookCastle&&e.movable.dests){let t=e.movable.color===`cg-white`?`1`:`8`,n=`e`+t,r=e.movable.dests.get(n),a=e.pieces.get(n);if(!r||!a||a.role!==`king`)return;e.movable.dests.set(n,r.filter(e=>!(e===`a`+t&&r.includes(`c`+t))&&!(e===`h`+t&&r.includes(`g`+t))))}}function deepMerge(e,t){for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)&&isPlainObject(e[n])&&isPlainObject(t[n])?deepMerge(e[n],t[n]):e[n]=t[n])}function isPlainObject(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var anim=(e,t)=>t.animation.enabled?animate(e,t):render$2(e,t);function render$2(e,t){let n=e(t);return t.dom.redraw(),n}e.a(render$2,`render`);var makePiece=(e,t)=>({key:e,pos:key2pos(e),piece:t}),closer=(e,t)=>t.sort((t,n)=>distanceSq(e.pos,t.pos)-distanceSq(e.pos,n.pos))[0];function computePlan(e,t){let n=new Map,r=[],a=new Map,o=[],c=[],l=new Map,u,d,p;for(let[t,n]of e)l.set(t,makePiece(t,n));for(let e of C)u=t.pieces.get(e),d=l.get(e),u?d?samePiece(u,d.piece)||(o.push(d),c.push(makePiece(e,u))):c.push(makePiece(e,u)):d&&o.push(d);for(let e of c)d=closer(e,o.filter(t=>samePiece(e.piece,t.piece))),d&&(p=[d.pos[0]-e.pos[0],d.pos[1]-e.pos[1]],n.set(e.key,p.concat(p)),r.push(d.key));for(let e of o)r.includes(e.key)||a.set(e.key,e.piece);return{anims:n,fadings:a}}function step(e,t){let n=e.animation.current;if(n===void 0){e.dom.destroyed||e.dom.redrawNow();return}let r=1-(t-n.start)*n.frequency;if(r<=0)e.animation.current=void 0,e.dom.redrawNow();else{let t=easing(r);for(let e of n.plan.anims.values())e[2]=e[0]*t,e[3]=e[1]*t;e.dom.redrawNow(!0),requestAnimationFrame((t=performance.now())=>step(e,t))}}function animate(e,t){let n=new Map(t.pieces),r=e(t),a=computePlan(n,t);if(a.anims.size||a.fadings.size){let e=t.animation.current&&t.animation.current.start;t.animation.current={start:performance.now(),frequency:1/t.animation.duration,plan:a},e||step(t,performance.now())}else t.dom.redraw();return r}var easing=e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,O=[`green`,`red`,`blue`,`yellow`];function start$2(e,t){if(t.touches&&t.touches.length>1)return;t.stopPropagation(),t.preventDefault(),t.ctrlKey?unselect(e):cancelMove(e);let n=eventPosition(t),r=getKeyAtDomPos(n,whitePov(e),e.dom.bounds());r&&(e.drawable.current={orig:r,pos:n,brush:eventBrush(t),snapToValidMove:e.drawable.defaultSnapToValidMove},processDraw(e))}e.a(start$2,`start`);function processDraw(e){requestAnimationFrame(()=>{let t=e.drawable.current;if(t){let n=getKeyAtDomPos(t.pos,whitePov(e),e.dom.bounds());n||(t.snapToValidMove=!1);let r=t.snapToValidMove?getSnappedKeyAtDomPos(t.orig,t.pos,whitePov(e),e.dom.bounds()):n;r!==t.mouseSq&&(t.mouseSq=r,t.dest=r===t.orig?void 0:r,e.dom.redrawNow()),processDraw(e)}})}function move$1(e,t){e.drawable.current&&(e.drawable.current.pos=eventPosition(t))}e.a(move$1,`move`);function end$1(e){let t=e.drawable.current;t&&(t.mouseSq&&addShape(e.drawable,t),cancel$1(e))}e.a(end$1,`end`);function cancel$1(e){e.drawable.current&&(e.drawable.current=void 0,e.dom.redraw())}e.a(cancel$1,`cancel`);function clear(e){e.drawable.shapes.length&&(e.drawable.shapes=[],e.dom.redraw(),onChange(e.drawable))}function eventBrush(e){let t=(e.shiftKey||e.ctrlKey)&&isRightButton(e),n=e.altKey||e.metaKey||e.getModifierState?.(`AltGraph`);return O[(t?1:0)+(n?2:0)]}function addShape(e,t){let sameShape=e=>e.orig===t.orig&&e.dest===t.dest,n=e.shapes.find(sameShape);n&&(e.shapes=e.shapes.filter(e=>!sameShape(e))),(!n||n.brush!==t.brush)&&e.shapes.push({orig:t.orig,dest:t.dest,brush:t.brush}),onChange(e)}function onChange(e){e.onChange&&e.onChange(e.shapes)}function start$1(e,t){if(!(e.trustAllEvents||t.isTrusted)||t.buttons!==void 0&&t.buttons>1||t.touches&&t.touches.length>1)return;let n=e.dom.bounds(),r=eventPosition(t),a=getKeyAtDomPos(r,whitePov(e),n);if(!a)return;let o=e.pieces.get(a),c=e.selected;if(!c&&e.drawable.enabled&&(e.drawable.eraseOnClick||!o||o.color!==e.turnColor)&&clear(e),t.cancelable!==!1&&(!t.touches||e.blockTouchScroll||o||c||pieceCloseTo(e,r)))t.preventDefault();else if(t.touches)return;let l=!!e.premovable.current,u=!!e.predroppable.current;e.stats.ctrlKey=t.ctrlKey,e.selected&&canMove(e,e.selected,a)?anim(e=>selectSquare(e,a),e):selectSquare(e,a);let d=e.selected===a,p=pieceElementByKey(e,a);if(o&&p&&d&&isDraggable(e,a)){e.draggable.current={orig:a,piece:o,origPos:r,pos:r,started:e.draggable.autoDistance&&e.stats.dragged,element:p,previouslySelected:c,originTarget:t.target,keyHasChanged:!1},p.cgDragging=!0,p.classList.add(`dragging`);let l=e.dom.elements.ghost;l&&(l.className=`ghost ${o.color} ${o.role}`,translate(l,posToTranslate(n)(key2pos(a),whitePov(e))),setVisible(l,!0)),processDrag(e)}else l&&unsetPremove(e),u&&unsetPredrop(e);e.dom.redraw()}e.a(start$1,`start`);function pieceCloseTo(e,t){let n=whitePov(e),r=e.dom.bounds(),a=(r.width/8)**2;for(let o of e.pieces.keys())if(distanceSq(computeSquareCenter(o,n,r),t)<=a)return!0;return!1}function dragNewPiece(e,t,n,r){e.pieces.set(`a0`,t),e.dom.redraw();let a=eventPosition(n);e.draggable.current={orig:`a0`,piece:t,origPos:a,pos:a,started:!0,element:()=>pieceElementByKey(e,`a0`),originTarget:n.target,newPiece:!0,force:!!r,keyHasChanged:!1},processDrag(e)}function processDrag(e){requestAnimationFrame(()=>{let t=e.draggable.current;if(!t)return;e.animation.current?.plan.anims.has(t.orig)&&(e.animation.current=void 0);let n=e.pieces.get(t.orig);if(!n||!samePiece(n,t.piece))cancel(e);else if(!t.started&&distanceSq(t.pos,t.origPos)>=e.draggable.distance**2&&(t.started=!0),t.started){if(typeof t.element==`function`){let e=t.element();if(!e)return;e.cgDragging=!0,e.classList.add(`dragging`),t.element=e}let n=e.dom.bounds();translate(t.element,[t.pos[0]-n.left-n.width/16,t.pos[1]-n.top-n.height/16]),t.keyHasChanged=t.keyHasChanged||t.orig!==getKeyAtDomPos(t.pos,whitePov(e),n)}processDrag(e)})}function move(e,t){e.draggable.current&&(!t.touches||t.touches.length<2)&&(e.draggable.current.pos=eventPosition(t))}function end(e,t){let n=e.draggable.current;if(!n)return;if(t.type===`touchend`&&t.cancelable!==!1&&t.preventDefault(),t.type===`touchend`&&n.originTarget!==t.target&&!n.newPiece){e.draggable.current=void 0;return}unsetPremove(e),unsetPredrop(e);let r=getKeyAtDomPos(eventPosition(t)||n.pos,whitePov(e),e.dom.bounds());r&&n.started&&n.orig!==r?n.newPiece?dropNewPiece(e,n.orig,r,n.force):(e.stats.ctrlKey=t.ctrlKey,userMove(e,n.orig,r)&&(e.stats.dragged=!0)):n.newPiece?e.pieces.delete(n.orig):e.draggable.deleteOnDropOff&&!r&&(e.pieces.delete(n.orig),callUserFunction(e.events.change)),(n.orig===n.previouslySelected||n.keyHasChanged)&&(n.orig===r||!r)?unselect(e):e.selectable.enabled||unselect(e),removeDragElements(e),e.draggable.current=void 0,e.dom.redraw()}function cancel(e){let t=e.draggable.current;t&&(t.newPiece&&e.pieces.delete(t.orig),e.draggable.current=void 0,unselect(e),removeDragElements(e),e.dom.redraw())}function removeDragElements(e){let t=e.dom.elements;t.ghost&&setVisible(t.ghost,!1)}function pieceElementByKey(e,t){let n=e.dom.elements.board.firstChild;for(;n;){if(n.cgKey===t&&n.tagName===`PIECE`)return n;n=n.nextSibling}}function explosion(e,t){e.exploding={stage:1,keys:t},e.dom.redraw(),setTimeout(()=>{setStage(e,2),setTimeout(()=>setStage(e,void 0),120)},120)}function setStage(e,t){e.exploding&&(t?e.exploding.stage=t:e.exploding=void 0,e.dom.redraw())}function start(t,n){function toggleOrientation$1(){toggleOrientation(t),n()}return e.a(toggleOrientation$1,`toggleOrientation`),{set(e){e.orientation&&e.orientation!==t.orientation&&toggleOrientation$1(),applyAnimation(t,e),(e.fen?anim:render$2)(t=>configure(t,e),t)},state:t,getFen:()=>write(t.pieces),toggleOrientation:toggleOrientation$1,setPieces(e){anim(t=>setPieces(t,e),t)},selectSquare(e,n){e?anim(t=>selectSquare(t,e,n),t):t.selected&&(unselect(t),t.dom.redraw())},move(e,n){anim(t=>baseMove(t,e,n),t)},newPiece(e,n){anim(t=>baseNewPiece(t,e,n),t)},playPremove(){if(t.premovable.current){if(anim(playPremove,t))return!0;t.dom.redraw()}return!1},playPredrop(e){if(t.predroppable.current){let n=playPredrop(t,e);return t.dom.redraw(),n}return!1},cancelPremove(){render$2(unsetPremove,t)},cancelPredrop(){render$2(unsetPredrop,t)},cancelMove(){render$2(e=>{cancelMove(e),cancel(e)},t)},stop(){render$2(e=>{stop(e),cancel(e)},t)},explode(e){explosion(t,e)},setAutoShapes(e){render$2(t=>t.drawable.autoShapes=e,t)},setShapes(e){render$2(t=>t.drawable.shapes=e,t)},getKeyAtDomPos(e){return getKeyAtDomPos(e,whitePov(t),t.dom.bounds())},redrawAll:n,dragNewPiece(e,n,r){dragNewPiece(t,e,n,r)},destroy(){stop(t),t.dom.unbind?.(),t.dom.destroyed=!0}}}function defaults(){return{pieces:read(T),orientation:`cg-white`,turnColor:`cg-white`,coordinates:!0,coordinatesOnSquares:!1,ranksPosition:`right`,autoCastle:!0,viewOnly:!1,disableContextMenu:!1,addPieceZIndex:!1,blockTouchScroll:!1,pieceKey:!1,trustAllEvents:!1,highlight:{lastMove:!0,check:!0},animation:{enabled:!0,duration:200},movable:{free:!0,color:`both`,showDests:!0,events:{},rookCastle:!0},premovable:{enabled:!0,showDests:!0,castle:!0,events:{}},predroppable:{enabled:!1,events:{}},draggable:{enabled:!0,distance:3,autoDistance:!0,showGhost:!0,deleteOnDropOff:!1},dropmode:{active:!1},selectable:{enabled:!0},stats:{dragged:!(`ontouchstart`in window)},events:{},drawable:{enabled:!0,visible:!0,defaultSnapToValidMove:!0,eraseOnClick:!0,shapes:[],autoShapes:[],brushes:{green:{key:`g`,color:`#15781B`,opacity:1,lineWidth:10},red:{key:`r`,color:`#882020`,opacity:1,lineWidth:10},blue:{key:`b`,color:`#003088`,opacity:1,lineWidth:10},yellow:{key:`y`,color:`#e68f00`,opacity:1,lineWidth:10},paleBlue:{key:`pb`,color:`#003088`,opacity:.4,lineWidth:15},paleGreen:{key:`pg`,color:`#15781B`,opacity:.4,lineWidth:15},paleRed:{key:`pr`,color:`#882020`,opacity:.4,lineWidth:15},paleGrey:{key:`pgr`,color:`#4a4a4a`,opacity:.35,lineWidth:15},purple:{key:`purple`,color:`#68217a`,opacity:.65,lineWidth:10},pink:{key:`pink`,color:`#ee2080`,opacity:.5,lineWidth:10},white:{key:`white`,color:`white`,opacity:1,lineWidth:10}},prevSvgHash:``},hold:timer()}}var k={hilitePrimary:{key:`hilitePrimary`,color:`#3291ff`,opacity:1,lineWidth:1},hiliteWhite:{key:`hiliteWhite`,color:`#ffffff`,opacity:1,lineWidth:1}};function createDefs(){let e=createElement(`defs`),t=setAttributes(createElement(`filter`),{id:`cg-filter-blur`});return t.appendChild(setAttributes(createElement(`feGaussianBlur`),{stdDeviation:`0.019`})),e.appendChild(t),e}function renderSvg(e,t,n){let r=e.drawable,a=r.current,o=a&&a.mouseSq?a:void 0,c=new Map,l=e.dom.bounds(),u=r.autoShapes.filter(e=>!e.piece);for(let t of r.shapes.concat(u).concat(o?[o]:[])){if(!t.dest)continue;let n=c.get(t.dest)??new Set,r=pos2user(orient(key2pos(t.orig),e.orientation),l),a=pos2user(orient(key2pos(t.dest),e.orientation),l);n.add(moveAngle(r,a)),c.set(t.dest,n)}let d=r.shapes.concat(u).map(e=>({shape:e,current:!1,hash:shapeHash(e,isShort(e.dest,c),!1,l)}));o&&d.push({shape:o,current:!0,hash:shapeHash(o,isShort(o.dest,c),!0,l)});let p=d.map(e=>e.hash).join(`;`);p!==e.drawable.prevSvgHash&&(e.drawable.prevSvgHash=p,syncDefs(r,d,t.querySelector(`defs`)),syncShapes$1(d,t.querySelector(`g`),n.querySelector(`g`),t=>renderShape$1(e,t,r.brushes,c,l)))}function syncDefs(e,t,n){let r=new Map,a;for(let n of t.filter(e=>e.shape.dest&&e.shape.brush))a=makeCustomBrush(e.brushes[n.shape.brush],n.shape.modifiers),n.shape.modifiers?.hilite&&r.set(hilite(a).key,hilite(a)),r.set(a.key,a);let o=new Set,c=n.firstElementChild;for(;c;)o.add(c.getAttribute(`cgKey`)),c=c.nextElementSibling;for(let[e,t]of r.entries())o.has(e)||n.appendChild(renderMarker(t))}function syncShapes$1(e,t,n,r){let a=new Map;for(let t of e)a.set(t.hash,!1);for(let e of[t,n]){let t=[],n=e.firstElementChild,r;for(;n;)r=n.getAttribute(`cgHash`),a.has(r)?a.set(r,!0):t.push(n),n=n.nextElementSibling;for(let n of t)e.removeChild(n)}for(let o of e.filter(e=>!a.get(e.hash)))for(let e of r(o))e.isCustom?n.appendChild(e.el):t.appendChild(e.el)}e.a(syncShapes$1,`syncShapes`);function shapeHash({orig:e,dest:t,brush:n,piece:r,modifiers:a,customSvg:o,label:c},l,u,d){return[d.width,d.height,u,e,t,n,l&&`-`,r&&pieceHash(r),a&&modifiersHash(a),o&&`custom-${textHash(o.html)},${o.center?.[0]??`o`}`,c&&`label-${textHash(c.text)}`].filter(e=>e).join(`,`)}function pieceHash(e){return[e.color,e.role,e.scale].filter(e=>e).join(`,`)}function modifiersHash(e){return[e.lineWidth,e.hilite&&`*`].filter(e=>e).join(`,`)}function textHash(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)>>>0;return t.toString()}function renderShape$1(e,{shape:t,current:n,hash:r},a,o,c){let l=pos2user(orient(key2pos(t.orig),e.orientation),c),u=t.dest?pos2user(orient(key2pos(t.dest),e.orientation),c):l,d=t.brush&&makeCustomBrush(a[t.brush],t.modifiers),p=o.get(t.dest),m=[];if(d){let e=setAttributes(createElement(`g`),{cgHash:r});m.push({el:e}),l[0]!==u[0]||l[1]!==u[1]?e.appendChild(renderArrow(t,d,l,u,n,isShort(t.dest,o))):e.appendChild(renderCircle(a[t.brush],l,n,c))}if(t.label){let e=t.label;e.fill||t.brush&&a[t.brush]&&(e.fill=a[t.brush].color);let n=t.brush?void 0:`tr`;m.push({el:renderLabel(e,r,l,u,p,n),isCustom:!0})}if(t.customSvg){let e=t.customSvg.center??`orig`,[n,a]=e===`label`?labelCoords(l,u,p).map(e=>e-.5):e===`dest`?u:l,o=setAttributes(createElement(`g`),{transform:`translate(${n},${a})`,cgHash:r});o.innerHTML=`<svg width="1" height="1" viewBox="0 0 100 100">${t.customSvg.html}</svg>`,m.push({el:o,isCustom:!0})}return m}e.a(renderShape$1,`renderShape`);function renderCircle(e,t,n,r){let a=circleWidth(),o=(r.width+r.height)/(4*Math.max(r.width,r.height));return setAttributes(createElement(`circle`),{stroke:e.color,"stroke-width":a[n?0:1],fill:`none`,opacity:opacity(e,n),cx:t[0],cy:t[1],r:o-a[1]/2})}function hilite(e){return[`#ffffff`,`#fff`,`white`].includes(e.color)?k.hilitePrimary:k.hiliteWhite}function renderArrow(e,t,n,r,a,o){function renderLine(c){let l=arrowMargin(o&&!a),u=r[0]-n[0],d=r[1]-n[1],p=Math.atan2(d,u),m=Math.cos(p)*l,h=Math.sin(p)*l;return setAttributes(createElement(`line`),{stroke:c?hilite(t).color:t.color,"stroke-width":lineWidth(t,a)+(c?.04:0),"stroke-linecap":`round`,"marker-end":`url(#arrowhead-${c?hilite(t).key:t.key})`,opacity:e.modifiers?.hilite?1:opacity(t,a),x1:n[0],y1:n[1],x2:r[0]-m,y2:r[1]-h})}if(!e.modifiers?.hilite)return renderLine(!1);let c=createElement(`g`),l=setAttributes(createElement(`g`),{filter:`url(#cg-filter-blur)`});return l.appendChild(filterBox(n,r)),l.appendChild(renderLine(!0)),c.appendChild(l),c.appendChild(renderLine(!1)),c}function renderMarker(e){let t=setAttributes(createElement(`marker`),{id:`arrowhead-`+e.key,orient:`auto`,overflow:`visible`,markerWidth:4,markerHeight:4,refX:e.key.startsWith(`hilite`)?1.86:2.05,refY:2});return t.appendChild(setAttributes(createElement(`path`),{d:`M0,0 V4 L3,2 Z`,fill:e.color})),t.setAttribute(`cgKey`,e.key),t}function renderLabel(e,t,n,r,a,o){let c=.4,l=c*.75**e.text.length,u=labelCoords(n,r,a),d=o===`tr`?.4:0,p=setAttributes(createElement(`g`),{transform:`translate(${u[0]+d},${u[1]-d})`,cgHash:t});p.appendChild(setAttributes(createElement(`circle`),{r:c/2,"fill-opacity":o?1:.8,"stroke-opacity":o?1:.7,"stroke-width":.03,fill:e.fill??`#666`,stroke:`white`}));let m=setAttributes(createElement(`text`),{"font-size":l,"font-family":`Noto Sans`,"text-anchor":`middle`,fill:`white`,y:.13*.75**e.text.length});return m.innerHTML=e.text,p.appendChild(m),p}function orient(e,t){return t===`cg-white`?e:[7-e[0],7-e[1]]}function isShort(e,t){return!0===(e&&t.has(e)&&t.get(e).size>1)}function createElement(e){return document.createElementNS(`http://www.w3.org/2000/svg`,e)}function setAttributes(e,t){for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.setAttribute(n,t[n]);return e}function makeCustomBrush(e,t){return t?{color:e.color,opacity:Math.round(e.opacity*10)/10,lineWidth:Math.round(t.lineWidth||e.lineWidth),key:[e.key,t.lineWidth].filter(e=>e).join(``)}:e}function circleWidth(){return[3/64,4/64]}function lineWidth(e,t){return(e.lineWidth||10)*(t?.85:1)/64}function opacity(e,t){return(e.opacity||1)*(t?.9:1)}function arrowMargin(e){return(e?20:10)/64}function pos2user(e,t){let n=Math.min(1,t.width/t.height),r=Math.min(1,t.height/t.width);return[(e[0]-3.5)*n,(3.5-e[1])*r]}function filterBox(e,t){let n={from:[Math.floor(Math.min(e[0],t[0])),Math.floor(Math.min(e[1],t[1]))],to:[Math.ceil(Math.max(e[0],t[0])),Math.ceil(Math.max(e[1],t[1]))]};return setAttributes(createElement(`rect`),{x:n.from[0],y:n.from[1],width:n.to[0]-n.from[0],height:n.to[1]-n.from[1],fill:`none`,stroke:`none`})}function moveAngle(e,t,n=!0){let r=Math.atan2(t[1]-e[1],t[0]-e[0])+Math.PI;return n?(Math.round(r*8/Math.PI)+16)%16:r}function dist(e,t){return Math.sqrt([e[0]-t[0],e[1]-t[1]].reduce((e,t)=>e+t*t,0))}function labelCoords(e,t,n){let r=dist(e,t),a=moveAngle(e,t,!1);if(n&&(r-=33/64,n.size>1)){r-=10/64;let a=moveAngle(e,t);(n.has((a+1)%16)||n.has((a+15)%16))&&a&1&&(r-=.4)}return[e[0]-Math.cos(a)*r,e[1]-Math.sin(a)*r].map(e=>e+.5)}function renderWrap(e,t){e.innerHTML=``,e.classList.add(`cg-wrap`);for(let n of y)e.classList.toggle(`orientation-`+n,t.orientation===n);e.classList.toggle(`manipulable`,!t.viewOnly);let n=createEl(`cg-container`);e.appendChild(n);let r=createEl(`cg-board`);n.appendChild(r);let a,o,c;if(t.drawable.visible&&(a=setAttributes(createElement(`svg`),{class:`cg-shapes`,viewBox:`-4 -4 8 8`,preserveAspectRatio:`xMidYMid slice`}),a.appendChild(createDefs()),a.appendChild(createElement(`g`)),o=setAttributes(createElement(`svg`),{class:`cg-custom-svgs`,viewBox:`-3.5 -3.5 8 8`,preserveAspectRatio:`xMidYMid slice`}),o.appendChild(createElement(`g`)),c=createEl(`cg-auto-pieces`),n.appendChild(a),n.appendChild(o),n.appendChild(c)),t.coordinates){let e=t.orientation===`cg-black`?` black`:``,r=t.ranksPosition===`left`?` left`:``;if(t.coordinatesOnSquares){let a=t.orientation===`cg-white`?e=>e+1:e=>8-e;b.forEach((t,o)=>n.appendChild(renderCoords(x.map(e=>t+e),`squares rank`+a(o)+e+r)))}else n.appendChild(renderCoords(x,`ranks`+e+r)),n.appendChild(renderCoords(b,`files`+e))}let l;return t.draggable.enabled&&t.draggable.showGhost&&(l=createEl(`piece`,`ghost`),setVisible(l,!1),n.appendChild(l)),{board:r,container:n,wrap:e,ghost:l,svg:a,customSvg:o,autoPieces:c}}function renderCoords(e,t){let n=createEl(`coords`,t),r;for(let t of e)r=createEl(`coord`),r.textContent=t,n.appendChild(r);return n}function drop(e,t){if(!e.dropmode.active)return;unsetPremove(e),unsetPredrop(e);let n=e.dropmode.piece;if(n){e.pieces.set(`a0`,n);let r=eventPosition(t),a=r&&getKeyAtDomPos(r,whitePov(e),e.dom.bounds());a&&dropNewPiece(e,`a0`,a)}e.dom.redraw()}function bindBoard(e){let t=e.dom.elements.board;if((e.disableContextMenu||e.drawable.enabled)&&t.addEventListener(`contextmenu`,e=>e.preventDefault()),e.viewOnly)return;let n=startDragOrDraw(e);t.addEventListener(`touchstart`,n,{passive:!1}),t.addEventListener(`mousedown`,n,{passive:!1})}function bindDocument(e,t){let n=[];if(`ResizeObserver`in window||n.push(unbindable(document.body,`chessground.resize`,t)),!e.viewOnly){let t=dragOrDraw(e,move,move$1),r=dragOrDraw(e,end,end$1);for(let e of[`touchmove`,`mousemove`])n.push(unbindable(document,e,t));for(let e of[`touchend`,`mouseup`])n.push(unbindable(document,e,r));let onScroll=()=>e.dom.bounds.clear();n.push(unbindable(document,`scroll`,onScroll,{capture:!0,passive:!0})),n.push(unbindable(window,`resize`,onScroll,{passive:!0}))}return()=>n.forEach(e=>e())}function unbindable(e,t,n,r){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n,r)}var startDragOrDraw=e=>t=>{e.draggable.current?cancel(e):e.drawable.current?cancel$1(e):t.shiftKey||isRightButton(t)?e.drawable.enabled&&start$2(e,t):e.viewOnly||(e.dropmode.active?drop(e,t):start$1(e,t))},dragOrDraw=(e,t,n)=>r=>{e.drawable.current?e.drawable.enabled&&n(e,r):e.viewOnly||t(e,r)};function render$1(e){let t=whitePov(e),n=posToTranslate(e.dom.bounds()),r=e.dom.elements.board,a=e.pieces,o=e.animation.current,c=o?o.plan.anims:new Map,l=o?o.plan.fadings:new Map,u=e.draggable.current,d=computeSquareClasses(e),p=new Set,m=new Set,h=new Map,g=new Map,_,y,b,x,S,C,w,T,E,D;for(y=r.firstChild;y;){if(_=y.cgKey,isPieceNode(y))if(b=a.get(_),S=c.get(_),C=l.get(_),x=y.cgPiece,y.cgDragging&&(!u||u.orig!==_)&&(y.classList.remove(`dragging`),translate(y,n(key2pos(_),t)),y.cgDragging=!1),!C&&y.cgFading&&(y.cgFading=!1,y.classList.remove(`fading`)),b){if(S&&y.cgAnimating&&x===pieceNameOf(b)){let e=key2pos(_);e[0]+=S[2],e[1]+=S[3],y.classList.add(`anim`),translate(y,n(e,t))}else y.cgAnimating&&(y.cgAnimating=!1,y.classList.remove(`anim`),translate(y,n(key2pos(_),t)),e.addPieceZIndex&&(y.style.zIndex=posZIndex(key2pos(_),t)));x===pieceNameOf(b)&&(!C||!y.cgFading)?p.add(_):C&&x===pieceNameOf(C)?(y.classList.add(`fading`),y.cgFading=!0):appendValue(h,x,y)}else appendValue(h,x,y);else if(isSquareNode(y)){let e=y.className;d.get(_)===e?m.add(_):appendValue(g,e,y)}y=y.nextSibling}for(let[e,a]of d)if(!m.has(e)){E=g.get(a),D=E&&E.pop();let o=n(key2pos(e),t);if(D)D.cgKey=e,translate(D,o);else{let t=createEl(`square`,a);t.cgKey=e,translate(t,o),r.insertBefore(t,r.firstChild)}}for(let[o,l]of a)if(S=c.get(o),!p.has(o))if(w=h.get(pieceNameOf(l)),T=w&&w.pop(),T){T.cgKey=o,T.cgFading&&(T.classList.remove(`fading`),T.cgFading=!1);let r=key2pos(o);e.addPieceZIndex&&(T.style.zIndex=posZIndex(r,t)),S&&(T.cgAnimating=!0,T.classList.add(`anim`),r[0]+=S[2],r[1]+=S[3]),translate(T,n(r,t))}else{let a=pieceNameOf(l),c=createEl(`piece`,a),u=key2pos(o);c.cgPiece=a,c.cgKey=o,S&&(c.cgAnimating=!0,u[0]+=S[2],u[1]+=S[3]),translate(c,n(u,t)),e.addPieceZIndex&&(c.style.zIndex=posZIndex(u,t)),r.appendChild(c)}for(let t of h.values())removeNodes(e,t);for(let t of g.values())removeNodes(e,t)}e.a(render$1,`render`);function renderResized$1(e){let t=whitePov(e),n=posToTranslate(e.dom.bounds()),r=e.dom.elements.board.firstChild;for(;r;)(isPieceNode(r)&&!r.cgAnimating||isSquareNode(r))&&translate(r,n(key2pos(r.cgKey),t)),r=r.nextSibling}e.a(renderResized$1,`renderResized`);function updateBounds(e){let t=e.dom.elements.wrap.getBoundingClientRect(),n=e.dom.elements.container,r=t.height/t.width,a=Math.floor(t.width*window.devicePixelRatio/8)*8/window.devicePixelRatio,o=a*r;n.style.width=a+`px`,n.style.height=o+`px`,e.dom.bounds.clear(),e.addDimensionsCssVarsTo?.style.setProperty(`---cg-width`,a+`px`),e.addDimensionsCssVarsTo?.style.setProperty(`---cg-height`,o+`px`)}var isPieceNode=e=>e.tagName===`PIECE`,isSquareNode=e=>e.tagName===`SQUARE`;function removeNodes(e,t){for(let n of t)e.dom.elements.board.removeChild(n)}function posZIndex(e,t){let n=e[1];return`${t?10-n:3+n}`}var pieceNameOf=e=>`${e.color} ${e.role}`;function computeSquareClasses(e){let t=new Map;if(e.lastMove&&e.highlight.lastMove)for(let n of e.lastMove)addSquare(t,n,`last-move`);if(e.check&&e.highlight.check&&addSquare(t,e.check,`check`),e.selected&&(addSquare(t,e.selected,`selected`),e.movable.showDests)){let n=e.movable.dests?.get(e.selected);if(n)for(let r of n)addSquare(t,r,`move-dest`+(e.pieces.has(r)?` oc`:``));let r=e.premovable.customDests?.get(e.selected)??e.premovable.dests;if(r)for(let n of r)addSquare(t,n,`premove-dest`+(e.pieces.has(n)?` oc`:``))}let n=e.premovable.current;if(n)for(let e of n)addSquare(t,e,`current-premove`);else e.predroppable.current&&addSquare(t,e.predroppable.current.key,`current-premove`);let r=e.exploding;if(r)for(let e of r.keys)addSquare(t,e,`exploding`+r.stage);return e.highlight.custom&&e.highlight.custom.forEach((e,n)=>{addSquare(t,n,e)}),t}function addSquare(e,t,n){let r=e.get(t);r?e.set(t,`${r} ${n}`):e.set(t,n)}function appendValue(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function syncShapes(e,t,n){let r=new Map,a=[];for(let t of e)r.set(t.hash,!1);let o=t.firstElementChild,c;for(;o;)c=o.getAttribute(`cgHash`),r.has(c)?r.set(c,!0):a.push(o),o=o.nextElementSibling;for(let e of a)t.removeChild(e);for(let a of e)r.get(a.hash)||t.appendChild(n(a))}function render(e,t){syncShapes(e.drawable.autoShapes.filter(e=>e.piece).map(e=>({shape:e,hash:hash(e),current:!1})),t,t=>renderShape(e,t,e.dom.bounds()))}function renderResized(e){let t=whitePov(e),n=posToTranslate(e.dom.bounds()),r=e.dom.elements.autoPieces?.firstChild;for(;r;)translateAndScale(r,n(key2pos(r.cgKey),t),r.cgScale),r=r.nextSibling}function renderShape(e,{shape:t,hash:n},r){let a=t.orig,o=t.piece?.role,c=t.piece?.color,l=t.piece?.scale,u=createEl(`piece`,`${o} ${c}`);return u.setAttribute(`cgHash`,n),u.cgKey=a,u.cgScale=l,translateAndScale(u,posToTranslate(r)(key2pos(a),whitePov(e)),l),u}var hash=e=>[e.orig,e.piece?.role,e.piece?.color,e.piece?.scale].join(`,`);function Chessground(e,t){let n=defaults();configure(n,t||{});function redrawAll(){let t=`dom`in n?n.dom.unbind:void 0,r=renderWrap(e,n),a=memo(()=>r.board.getBoundingClientRect()),redrawNow=e=>{render$1(o),r.autoPieces&&render(o,r.autoPieces),!e&&r.svg&&renderSvg(o,r.svg,r.customSvg)},onResize=()=>{updateBounds(o),renderResized$1(o),r.autoPieces&&renderResized(o)},o=n;return o.dom={elements:r,bounds:a,redraw:debounceRedraw(redrawNow),redrawNow,unbind:t},o.drawable.prevSvgHash=``,updateBounds(o),redrawNow(!1),bindBoard(o),t||(o.dom.unbind=bindDocument(o,onResize)),o.events.insert?.(r),o}return start(redrawAll(),redrawAll)}function debounceRedraw(e){let t=!1;return()=>{t||(t=!0,requestAnimationFrame(()=>{e(),t=!1}))}}var A=`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1`,Move=class{color;from;to;piece;captured;promotion;flags;san;lan;before;after;constructor(e,t){let{color:n,piece:r,from:a,to:o,flags:c,captured:l,promotion:u}=t,d=algebraic(a),p=algebraic(o);this.color=n,this.piece=r,this.from=d,this.to=p,this.san=e._moveToSan(t,e._moves({legal:!0})),this.lan=d+p,this.before=e.fen(),e._makeMove(t),this.after=e.fen(),e._undoMove(),this.flags=``;for(let e in P)P[e]&c&&(this.flags+=M[e]);l&&(this.captured=l),u&&(this.promotion=u,this.lan+=u)}isCapture(){return this.flags.indexOf(M.CAPTURE)>-1}isPromotion(){return this.flags.indexOf(M.PROMOTION)>-1}isEnPassant(){return this.flags.indexOf(M.EP_CAPTURE)>-1}isKingsideCastle(){return this.flags.indexOf(M.KSIDE_CASTLE)>-1}isQueensideCastle(){return this.flags.indexOf(M.QSIDE_CASTLE)>-1}isBigPawn(){return this.flags.indexOf(M.BIG_PAWN)>-1}},j=-1,M={NORMAL:`n`,CAPTURE:`c`,BIG_PAWN:`b`,EP_CAPTURE:`e`,PROMOTION:`p`,KSIDE_CASTLE:`k`,QSIDE_CASTLE:`q`},N=`a8.b8.c8.d8.e8.f8.g8.h8.a7.b7.c7.d7.e7.f7.g7.h7.a6.b6.c6.d6.e6.f6.g6.h6.a5.b5.c5.d5.e5.f5.g5.h5.a4.b4.c4.d4.e4.f4.g4.h4.a3.b3.c3.d3.e3.f3.g3.h3.a2.b2.c2.d2.e2.f2.g2.h2.a1.b1.c1.d1.e1.f1.g1.h1`.split(`.`),P={NORMAL:1,CAPTURE:2,BIG_PAWN:4,EP_CAPTURE:8,PROMOTION:16,KSIDE_CASTLE:32,QSIDE_CASTLE:64},F={a8:0,b8:1,c8:2,d8:3,e8:4,f8:5,g8:6,h8:7,a7:16,b7:17,c7:18,d7:19,e7:20,f7:21,g7:22,h7:23,a6:32,b6:33,c6:34,d6:35,e6:36,f6:37,g6:38,h6:39,a5:48,b5:49,c5:50,d5:51,e5:52,f5:53,g5:54,h5:55,a4:64,b4:65,c4:66,d4:67,e4:68,f4:69,g4:70,h4:71,a3:80,b3:81,c3:82,d3:83,e3:84,f3:85,g3:86,h3:87,a2:96,b2:97,c2:98,d2:99,e2:100,f2:101,g2:102,h2:103,a1:112,b1:113,c1:114,d1:115,e1:116,f1:117,g1:118,h1:119},I={b:[16,32,17,15],w:[-16,-32,-17,-15]},L={n:[-18,-33,-31,-14,18,33,31,14],b:[-17,-15,17,15],r:[-16,1,16,-1],q:[-17,-16,-15,1,17,16,15,-1],k:[-17,-16,-15,1,17,16,15,-1]},R=[20,0,0,0,0,0,0,24,0,0,0,0,0,0,20,0,0,20,0,0,0,0,0,24,0,0,0,0,0,20,0,0,0,0,20,0,0,0,0,24,0,0,0,0,20,0,0,0,0,0,0,20,0,0,0,24,0,0,0,20,0,0,0,0,0,0,0,0,20,0,0,24,0,0,20,0,0,0,0,0,0,0,0,0,0,20,2,24,2,20,0,0,0,0,0,0,0,0,0,0,0,2,53,56,53,2,0,0,0,0,0,0,24,24,24,24,24,24,56,0,56,24,24,24,24,24,24,0,0,0,0,0,0,2,53,56,53,2,0,0,0,0,0,0,0,0,0,0,0,20,2,24,2,20,0,0,0,0,0,0,0,0,0,0,20,0,0,24,0,0,20,0,0,0,0,0,0,0,0,20,0,0,0,24,0,0,0,20,0,0,0,0,0,0,20,0,0,0,0,24,0,0,0,0,20,0,0,0,0,20,0,0,0,0,0,24,0,0,0,0,0,20,0,0,20,0,0,0,0,0,0,24,0,0,0,0,0,0,20],z=[17,0,0,0,0,0,0,16,0,0,0,0,0,0,15,0,0,17,0,0,0,0,0,16,0,0,0,0,0,15,0,0,0,0,17,0,0,0,0,16,0,0,0,0,15,0,0,0,0,0,0,17,0,0,0,16,0,0,0,15,0,0,0,0,0,0,0,0,17,0,0,16,0,0,15,0,0,0,0,0,0,0,0,0,0,17,0,16,0,15,0,0,0,0,0,0,0,0,0,0,0,0,17,16,15,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,-15,-16,-17,0,0,0,0,0,0,0,0,0,0,0,0,-15,0,-16,0,-17,0,0,0,0,0,0,0,0,0,0,-15,0,0,-16,0,0,-17,0,0,0,0,0,0,0,0,-15,0,0,0,-16,0,0,0,-17,0,0,0,0,0,0,-15,0,0,0,0,-16,0,0,0,0,-17,0,0,0,0,-15,0,0,0,0,0,-16,0,0,0,0,0,-17,0,0,-15,0,0,0,0,0,0,-16,0,0,0,0,0,0,-17],B={p:1,n:2,b:4,r:8,q:16,k:32},V=`pnbrqkPNBRQK`,H=[`n`,`b`,`r`,`q`],U=7,ee=6,W=1,te=0,ne={k:P.KSIDE_CASTLE,q:P.QSIDE_CASTLE},re={w:[{square:F.a1,flag:P.QSIDE_CASTLE},{square:F.h1,flag:P.KSIDE_CASTLE}],b:[{square:F.a8,flag:P.QSIDE_CASTLE},{square:F.h8,flag:P.KSIDE_CASTLE}]},ie={b:W,w:ee},G=[`1-0`,`0-1`,`1/2-1/2`,`*`];function rank(e){return e>>4}function file(e){return e&15}function isDigit(e){return`0123456789`.indexOf(e)!==-1}function algebraic(e){let t=file(e),n=rank(e);return`abcdefgh`.substring(t,t+1)+`87654321`.substring(n,n+1)}function swapColor$1(e){return e===`w`?`b`:`w`}e.a(swapColor$1,`swapColor`);function validateFen(e){let t=e.split(/\s+/);if(t.length!==6)return{ok:!1,error:`Invalid FEN: must contain six space-delimited fields`};let n=parseInt(t[5],10);if(isNaN(n)||n<=0)return{ok:!1,error:`Invalid FEN: move number must be a positive integer`};let r=parseInt(t[4],10);if(isNaN(r)||r<0)return{ok:!1,error:`Invalid FEN: half move counter number must be a non-negative integer`};if(!/^(-|[abcdefgh][36])$/.test(t[3]))return{ok:!1,error:`Invalid FEN: en-passant square is invalid`};if(/[^kKqQ-]/.test(t[2]))return{ok:!1,error:`Invalid FEN: castling availability is invalid`};if(!/^(w|b)$/.test(t[1]))return{ok:!1,error:`Invalid FEN: side-to-move is invalid`};let a=t[0].split(`/`);if(a.length!==8)return{ok:!1,error:`Invalid FEN: piece data does not contain 8 '/'-delimited rows`};for(let e=0;e<a.length;e++){let t=0,n=!1;for(let r=0;r<a[e].length;r++)if(isDigit(a[e][r])){if(n)return{ok:!1,error:`Invalid FEN: piece data is invalid (consecutive number)`};t+=parseInt(a[e][r],10),n=!0}else{if(!/^[prnbqkPRNBQK]$/.test(a[e][r]))return{ok:!1,error:`Invalid FEN: piece data is invalid (invalid piece)`};t+=1,n=!1}if(t!==8)return{ok:!1,error:`Invalid FEN: piece data is invalid (too many squares in rank)`}}if(t[3][1]==`3`&&t[1]==`w`||t[3][1]==`6`&&t[1]==`b`)return{ok:!1,error:`Invalid FEN: illegal en-passant square`};for(let{color:e,regex:n}of[{color:`white`,regex:/K/g},{color:`black`,regex:/k/g}]){if(!n.test(t[0]))return{ok:!1,error:`Invalid FEN: missing ${e} king`};if((t[0].match(n)||[]).length>1)return{ok:!1,error:`Invalid FEN: too many ${e} kings`}}return Array.from(a[0]+a[7]).some(e=>e.toUpperCase()===`P`)?{ok:!1,error:`Invalid FEN: some pawns are on the edge rows`}:{ok:!0}}function getDisambiguator(e,t){let n=e.from,r=e.to,a=e.piece,o=0,c=0,l=0;for(let e=0,u=t.length;e<u;e++){let u=t[e].from,d=t[e].to;a===t[e].piece&&n!==u&&r===d&&(o++,rank(n)===rank(u)&&c++,file(n)===file(u)&&l++)}return o>0?c>0&&l>0?algebraic(n):l>0?algebraic(n).charAt(1):algebraic(n).charAt(0):``}function addMove(e,t,n,r,a,o=void 0,c=P.NORMAL){let l=rank(r);if(a===`p`&&(l===U||l===te))for(let l=0;l<H.length;l++){let u=H[l];e.push({color:t,from:n,to:r,piece:a,captured:o,promotion:u,flags:c|P.PROMOTION})}else e.push({color:t,from:n,to:r,piece:a,captured:o,flags:c})}function inferPieceType(e){let t=e.charAt(0);return t>=`a`&&t<=`h`?e.match(/[a-h]\d.*[a-h]\d/)?void 0:`p`:(t=t.toLowerCase(),t===`o`?`k`:t)}function strippedSan(e){return e.replace(/=/,``).replace(/[+#]?[?!]*$/,``)}function trimFen(e){return e.split(` `).slice(0,4).join(` `)}var Chess=class{_board=Array(128);_turn=`w`;_header={};_kings={w:j,b:j};_epSquare=-1;_halfMoves=0;_moveNumber=0;_history=[];_comments={};_castling={w:0,b:0};_positionCount={};constructor(e=A,{skipValidation:t=!1}={}){this.load(e,{skipValidation:t})}clear({preserveHeaders:e=!1}={}){this._board=Array(128),this._kings={w:j,b:j},this._turn=`w`,this._castling={w:0,b:0},this._epSquare=j,this._halfMoves=0,this._moveNumber=1,this._history=[],this._comments={},this._header=e?this._header:{},this._positionCount={},delete this._header.SetUp,delete this._header.FEN}load(e,{skipValidation:t=!1,preserveHeaders:n=!1}={}){let r=e.split(/\s+/);if(r.length>=2&&r.length<6&&(e=r.concat([`-`,`-`,`0`,`1`].slice(-(6-r.length))).join(` `)),r=e.split(/\s+/),!t){let{ok:t,error:n}=validateFen(e);if(!t)throw Error(n)}let a=r[0],o=0;this.clear({preserveHeaders:n});for(let e=0;e<a.length;e++){let t=a.charAt(e);if(t===`/`)o+=8;else if(isDigit(t))o+=parseInt(t,10);else{let e=t<`a`?`w`:`b`;this._put({type:t.toLowerCase(),color:e},algebraic(o)),o++}}this._turn=r[1],r[2].indexOf(`K`)>-1&&(this._castling.w|=P.KSIDE_CASTLE),r[2].indexOf(`Q`)>-1&&(this._castling.w|=P.QSIDE_CASTLE),r[2].indexOf(`k`)>-1&&(this._castling.b|=P.KSIDE_CASTLE),r[2].indexOf(`q`)>-1&&(this._castling.b|=P.QSIDE_CASTLE),this._epSquare=r[3]===`-`?j:F[r[3]],this._halfMoves=parseInt(r[4],10),this._moveNumber=parseInt(r[5],10),this._updateSetup(e),this._incPositionCount(e)}fen(){let e=0,t=``;for(let n=F.a8;n<=F.h1;n++){if(this._board[n]){e>0&&(t+=e,e=0);let{color:r,type:a}=this._board[n];t+=r===`w`?a.toUpperCase():a.toLowerCase()}else e++;n+1&136&&(e>0&&(t+=e),n!==F.h1&&(t+=`/`),e=0,n+=8)}let n=``;this._castling.w&P.KSIDE_CASTLE&&(n+=`K`),this._castling.w&P.QSIDE_CASTLE&&(n+=`Q`),this._castling.b&P.KSIDE_CASTLE&&(n+=`k`),this._castling.b&P.QSIDE_CASTLE&&(n+=`q`),n||=`-`;let r=`-`;if(this._epSquare!==j){let e=this._epSquare+(this._turn===`w`?16:-16),t=[e+1,e-1];for(let e of t){if(e&136)continue;let t=this._turn;if(this._board[e]?.color===t&&this._board[e]?.type===`p`){this._makeMove({color:t,from:e,to:this._epSquare,piece:`p`,captured:`p`,flags:P.EP_CAPTURE});let n=!this._isKingAttacked(t);if(this._undoMove(),n){r=algebraic(this._epSquare);break}}}}return[t,this._turn,n,r,this._halfMoves,this._moveNumber].join(` `)}_updateSetup(e){this._history.length>0||(e===`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1`?(delete this._header.SetUp,delete this._header.FEN):(this._header.SetUp=`1`,this._header.FEN=e))}reset(){this.load(A)}get(e){return this._board[F[e]]}put({type:e,color:t},n){return this._put({type:e,color:t},n)?(this._updateCastlingRights(),this._updateEnPassantSquare(),this._updateSetup(this.fen()),!0):!1}_put({type:e,color:t},n){if(V.indexOf(e.toLowerCase())===-1||!(n in F))return!1;let r=F[n];if(e==`k`&&!(this._kings[t]==j||this._kings[t]==r))return!1;let a=this._board[r];return a&&a.type===`k`&&(this._kings[a.color]=j),this._board[r]={type:e,color:t},e===`k`&&(this._kings[t]=r),!0}remove(e){let t=this.get(e);return delete this._board[F[e]],t&&t.type===`k`&&(this._kings[t.color]=j),this._updateCastlingRights(),this._updateEnPassantSquare(),this._updateSetup(this.fen()),t}_updateCastlingRights(){let e=this._board[F.e1]?.type===`k`&&this._board[F.e1]?.color===`w`,t=this._board[F.e8]?.type===`k`&&this._board[F.e8]?.color===`b`;(!e||this._board[F.a1]?.type!==`r`||this._board[F.a1]?.color!==`w`)&&(this._castling.w&=~P.QSIDE_CASTLE),(!e||this._board[F.h1]?.type!==`r`||this._board[F.h1]?.color!==`w`)&&(this._castling.w&=~P.KSIDE_CASTLE),(!t||this._board[F.a8]?.type!==`r`||this._board[F.a8]?.color!==`b`)&&(this._castling.b&=~P.QSIDE_CASTLE),(!t||this._board[F.h8]?.type!==`r`||this._board[F.h8]?.color!==`b`)&&(this._castling.b&=~P.KSIDE_CASTLE)}_updateEnPassantSquare(){if(this._epSquare===j)return;let e=this._epSquare+(this._turn===`w`?-16:16),t=this._epSquare+(this._turn===`w`?16:-16),n=[t+1,t-1];if(this._board[e]!==null||this._board[this._epSquare]!==null||this._board[t]?.color!==swapColor$1(this._turn)||this._board[t]?.type!==`p`){this._epSquare=j;return}let canCapture=e=>!(e&136)&&this._board[e]?.color===this._turn&&this._board[e]?.type===`p`;n.some(canCapture)||(this._epSquare=j)}_attacked(e,t,n){let r=[];for(let a=F.a8;a<=F.h1;a++){if(a&136){a+=7;continue}if(this._board[a]===void 0||this._board[a].color!==e)continue;let o=this._board[a],c=a-t;if(c===0)continue;let l=c+119;if(R[l]&B[o.type]){if(o.type===`p`){if(c>0&&o.color===`w`||c<=0&&o.color===`b`)if(n)r.push(algebraic(a));else return!0;continue}if(o.type===`n`||o.type===`k`)if(n){r.push(algebraic(a));continue}else return!0;let e=z[l],u=a+e,d=!1;for(;u!==t;){if(this._board[u]!=null){d=!0;break}u+=e}if(!d)if(n){r.push(algebraic(a));continue}else return!0}}return n?r:!1}attackers(e,t){return t?this._attacked(t,F[e],!0):this._attacked(this._turn,F[e],!0)}_isKingAttacked(e){let t=this._kings[e];return t===-1?!1:this._attacked(swapColor$1(e),t)}isAttacked(e,t){return this._attacked(t,F[e])}isCheck(){return this._isKingAttacked(this._turn)}inCheck(){return this.isCheck()}isCheckmate(){return this.isCheck()&&this._moves().length===0}isStalemate(){return!this.isCheck()&&this._moves().length===0}isInsufficientMaterial(){let e={b:0,n:0,r:0,q:0,k:0,p:0},t=[],n=0,r=0;for(let a=F.a8;a<=F.h1;a++){if(r=(r+1)%2,a&136){a+=7;continue}let o=this._board[a];o&&(e[o.type]=o.type in e?e[o.type]+1:1,o.type===`b`&&t.push(r),n++)}if(n===2||n===3&&(e.b===1||e.n===1))return!0;if(n===e.b+2){let e=0,n=t.length;for(let r=0;r<n;r++)e+=t[r];if(e===0||e===n)return!0}return!1}isThreefoldRepetition(){return this._getPositionCount(this.fen())>=3}isDrawByFiftyMoves(){return this._halfMoves>=100}isDraw(){return this.isDrawByFiftyMoves()||this.isStalemate()||this.isInsufficientMaterial()||this.isThreefoldRepetition()}isGameOver(){return this.isCheckmate()||this.isStalemate()||this.isDraw()}moves({verbose:e=!1,square:t=void 0,piece:n=void 0}={}){let r=this._moves({square:t,piece:n});return e?r.map(e=>new Move(this,e)):r.map(e=>this._moveToSan(e,r))}_moves({legal:e=!0,piece:t=void 0,square:n=void 0}={}){let r=n?n.toLowerCase():void 0,a=t?.toLowerCase(),o=[],c=this._turn,l=swapColor$1(c),u=F.a8,d=F.h1,p=!1;if(r)if(r in F)u=d=F[r],p=!0;else return[];for(let e=u;e<=d;e++){if(e&136){e+=7;continue}if(!this._board[e]||this._board[e].color===l)continue;let{type:t}=this._board[e],n;if(t===`p`){if(a&&a!==t)continue;n=e+I[c][0],this._board[n]||(addMove(o,c,e,n,`p`),n=e+I[c][1],ie[c]===rank(e)&&!this._board[n]&&addMove(o,c,e,n,`p`,void 0,P.BIG_PAWN));for(let t=2;t<4;t++)n=e+I[c][t],!(n&136)&&(this._board[n]?.color===l?addMove(o,c,e,n,`p`,this._board[n].type,P.CAPTURE):n===this._epSquare&&addMove(o,c,e,n,`p`,`p`,P.EP_CAPTURE))}else{if(a&&a!==t)continue;for(let r=0,a=L[t].length;r<a;r++){let a=L[t][r];for(n=e;n+=a,!(n&136);){if(!this._board[n])addMove(o,c,e,n,t);else{if(this._board[n].color===c)break;addMove(o,c,e,n,t,this._board[n].type,P.CAPTURE);break}if(t===`n`||t===`k`)break}}}}if((a===void 0||a===`k`)&&(!p||d===this._kings[c])){if(this._castling[c]&P.KSIDE_CASTLE){let e=this._kings[c],t=e+2;!this._board[e+1]&&!this._board[t]&&!this._attacked(l,this._kings[c])&&!this._attacked(l,e+1)&&!this._attacked(l,t)&&addMove(o,c,this._kings[c],t,`k`,void 0,P.KSIDE_CASTLE)}if(this._castling[c]&P.QSIDE_CASTLE){let e=this._kings[c],t=e-2;!this._board[e-1]&&!this._board[e-2]&&!this._board[e-3]&&!this._attacked(l,this._kings[c])&&!this._attacked(l,e-1)&&!this._attacked(l,t)&&addMove(o,c,this._kings[c],t,`k`,void 0,P.QSIDE_CASTLE)}}if(!e||this._kings[c]===-1)return o;let m=[];for(let e=0,t=o.length;e<t;e++)this._makeMove(o[e]),this._isKingAttacked(c)||m.push(o[e]),this._undoMove();return m}move(e,{strict:t=!1}={}){let n=null;if(typeof e==`string`)n=this._moveFromSan(e,t);else if(typeof e==`object`){let t=this._moves();for(let r=0,a=t.length;r<a;r++)if(e.from===algebraic(t[r].from)&&e.to===algebraic(t[r].to)&&(!(`promotion`in t[r])||e.promotion===t[r].promotion)){n=t[r];break}}if(!n)throw typeof e==`string`?Error(`Invalid move: ${e}`):Error(`Invalid move: ${JSON.stringify(e)}`);let r=new Move(this,n);return this._makeMove(n),this._incPositionCount(r.after),r}_push(e){this._history.push({move:e,kings:{b:this._kings.b,w:this._kings.w},turn:this._turn,castling:{b:this._castling.b,w:this._castling.w},epSquare:this._epSquare,halfMoves:this._halfMoves,moveNumber:this._moveNumber})}_makeMove(e){let t=this._turn,n=swapColor$1(t);if(this._push(e),this._board[e.to]=this._board[e.from],delete this._board[e.from],e.flags&P.EP_CAPTURE&&(this._turn===`b`?delete this._board[e.to-16]:delete this._board[e.to+16]),e.promotion&&(this._board[e.to]={type:e.promotion,color:t}),this._board[e.to].type===`k`){if(this._kings[t]=e.to,e.flags&P.KSIDE_CASTLE){let t=e.to-1,n=e.to+1;this._board[t]=this._board[n],delete this._board[n]}else if(e.flags&P.QSIDE_CASTLE){let t=e.to+1,n=e.to-2;this._board[t]=this._board[n],delete this._board[n]}this._castling[t]=0}if(this._castling[t]){for(let n=0,r=re[t].length;n<r;n++)if(e.from===re[t][n].square&&this._castling[t]&re[t][n].flag){this._castling[t]^=re[t][n].flag;break}}if(this._castling[n]){for(let t=0,r=re[n].length;t<r;t++)if(e.to===re[n][t].square&&this._castling[n]&re[n][t].flag){this._castling[n]^=re[n][t].flag;break}}e.flags&P.BIG_PAWN?t===`b`?this._epSquare=e.to-16:this._epSquare=e.to+16:this._epSquare=j,e.piece===`p`||e.flags&(P.CAPTURE|P.EP_CAPTURE)?this._halfMoves=0:this._halfMoves++,t===`b`&&this._moveNumber++,this._turn=n}undo(){let e=this._undoMove();if(e){let t=new Move(this,e);return this._decPositionCount(t.after),t}return null}_undoMove(){let e=this._history.pop();if(e===void 0)return null;let t=e.move;this._kings=e.kings,this._turn=e.turn,this._castling=e.castling,this._epSquare=e.epSquare,this._halfMoves=e.halfMoves,this._moveNumber=e.moveNumber;let n=this._turn,r=swapColor$1(n);if(this._board[t.from]=this._board[t.to],this._board[t.from].type=t.piece,delete this._board[t.to],t.captured)if(t.flags&P.EP_CAPTURE){let e;e=n===`b`?t.to-16:t.to+16,this._board[e]={type:`p`,color:r}}else this._board[t.to]={type:t.captured,color:r};if(t.flags&(P.KSIDE_CASTLE|P.QSIDE_CASTLE)){let e,n;t.flags&P.KSIDE_CASTLE?(e=t.to+1,n=t.to-1):(e=t.to-2,n=t.to+1),this._board[e]=this._board[n],delete this._board[n]}return t}pgn({newline:e=`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./shapes-DJ-ujuDr.cjs`);let t=require(`vue`),n=require(`@vue-skuilder/common-ui`),r=require(`@vue-skuilder/common`),a=require(`moment`);a=e.o(a);let o=require(`@vue-skuilder/db`);function randomInt(e,t){return Math.floor(Math.random()*(t-e+1))+e}function shuffle(e){let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}function cos(e){return Math.cos(toRadians(e))}function sin(e){return Math.sin(toRadians(e))}function toRadians(e){return e/360*2*Math.PI}function gradeSpellingAttempt(e,t){let n=Array(t.length).fill(`_`),r=e.split(``);console.log(e,t),console.log(`Attempt char codes:`,e.split(``).map(e=>e.charCodeAt(0))),console.log(`Answer char codes:`,t.split(``).map(e=>e.charCodeAt(0)));for(let e=0;e<t.length;e++)e<r.length&&r[e]===t[e]&&(n[e]=r[e],r[e]=``);for(let e=t.length-1;e>=0;e--)if(n[e]===`_`){let a=r.findIndex(n=>n===t[e]);a!==-1&&(n[e]=t[e],r[a]=``)}return console.log(n.join(` `)),n.join(` `)}var c=(0,t.defineComponent)({name:`FillInView`,components:{MarkdownRenderer:(0,t.defineAsyncComponent)(()=>import(`@vue-skuilder/common-ui`).then(e=>e.MarkdownRenderer)),RadioMultipleChoice:n.RadioMultipleChoice,AudioAutoPlayer:n.AudioAutoPlayer},props:{data:{type:Array,required:!0},modifyDifficulty:{type:Number,required:!1,default:0}},setup(e,{emit:r}){let a=(0,n.useViewable)(e,r,`FillInView`),o=(0,n.useQuestionView)(a);o.question.value=new g(e.data);let c=(0,t.ref)(),l=(0,t.computed)(()=>{if(!o.question.value)throw a.logger.error(`Question not initialized`),Error(`Question not initialized`);return o.question.value});(0,t.onMounted)(()=>{try{o.question.value||(o.question.value=new g(e.data)),o.question.value.options&&(c.value=shuffle(getTruncatedList()))}catch(e){a.logger.error(`Failed to initialize question:`,e)}}),(0,t.onUnmounted)(()=>{o.question.value=void 0});let u=(0,t.computed)(()=>c.value??[]),d=(0,t.computed)(()=>!!e.data[0][`image-1`]),p=(0,t.computed)(()=>{if(!d.value)return[``];let t=[],n=1;for(;e.data[0][`image-${n}`];)t.push(URL.createObjectURL(e.data[0][`image-${n}`])),n++;return t}),m=(0,t.computed)(()=>!!e.data[0][`audio-1`]),h=(0,t.computed)(()=>l.value?.mdText||``),_=(0,t.computed)(()=>{if(!m.value)return[``];let t=[],n=1;for(;e.data[0][`audio-${n}`];)t.push(URL.createObjectURL(e.data[0][`audio-${n}`])),n++;return t}),y=(0,t.computed)(()=>{if(l.value.answers)return l.value.answers[Math.floor(l.value.answers.length*Math.random())];throw Error(`No answers provided`)}),b=(0,t.computed)(()=>{let e=y.value;if(console.log(`Prior answers: ${o.priorAnswers.value}`),e&&o.priorAnswers.value[0]?.[0]&&o.priorAnswers.value[0][1]===`UserInputString`)return gradeSpellingAttempt(o.priorAnswers.value[0][0],e);if(console.log(`found no UserInputString`),y.value){let e=``;for(let t=0;t<y.value.length;t++)e+=`_ `;return e}return``}),x=(0,t.computed)(()=>!!(l.value.answers&&l.value.answers.length>0)),getTruncatedList=()=>{if(!l.value?.options)return;if(l.value.options.length<=6)return l.value.options;let t=[];t.push(l.value.answers[Math.floor(Math.random()*l.value.answers.length)]);let n=shuffle(l.value.options.filter(e=>l.value.answers?.indexOf(e)===-1));return e.modifyDifficulty&&(console.log(`Modifying difficulty: ${e.modifyDifficulty}`),n=e.modifyDifficulty<-200?n.slice(0,1):e.modifyDifficulty<-150?n.slice(0,2):e.modifyDifficulty<-100?n.slice(0,3):e.modifyDifficulty<-50?n.slice(0,4):n.slice(0,5)),t.push(...n.slice(0,5)),t},handleNext=()=>{o.submitAnswer(``)};return(0,t.watch)(()=>e.data,e=>{try{o.question.value=new g(e),o.question.value?.options&&(c.value=shuffle(getTruncatedList()))}catch(e){a.logger.error(`Failed to initialize/update question:`,e)}},{deep:!0}),{...a,...o,question:l,truncatedOptions:u,hasImage:d,imageURLs:p,hasAudio:m,audioURL:_,obscuredAnswer:b,someAnswer:y,isQuestion:x,handleNext,markdownText:h}}}),l=e.a((e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},`default`),u={"data-viewable":`FillInView`},d=[`src`],p={key:4,class:`text-center text-h6`},m={key:5,class:`text-center text-h6`};function _sfc_render$25(e,n,r,a,o,c){let l=(0,t.resolveComponent)(`audio-auto-player`),h=(0,t.resolveComponent)(`markdown-renderer`),g=(0,t.resolveComponent)(`radio-multiple-choice`),_=(0,t.resolveComponent)(`v-spacer`),y=(0,t.resolveComponent)(`v-btn`),b=(0,t.resolveComponent)(`v-card-actions`);return(0,t.openBlock)(),(0,t.createElementBlock)(`div`,u,[e.hasAudio?((0,t.openBlock)(),(0,t.createBlock)(l,{key:0,src:e.audioURL},null,8,[`src`])):(0,t.createCommentVNode)(``,!0),e.hasImage?((0,t.openBlock)(!0),(0,t.createElementBlock)(t.Fragment,{key:1},(0,t.renderList)(e.imageURLs,(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`img`,{key:n,src:e},null,8,d))),128)):(0,t.createCommentVNode)(``,!0),e.markdownText?((0,t.openBlock)(),(0,t.createBlock)(h,{key:2,md:e.markdownText},null,8,[`md`])):(0,t.createCommentVNode)(``,!0),e.question?.options?((0,t.openBlock)(),(0,t.createBlock)(g,{key:3,"choice-list":e.truncatedOptions},null,8,[`choice-list`])):e.priorAttempts==1?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,p,[(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(e.obscuredAnswer),1)])):e.priorAttempts==2?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,m,[(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(e.someAnswer),1)])):(0,t.createCommentVNode)(``,!0),e.isQuestion?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createBlock)(b,{key:6},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(_),(0,t.createVNode)(y,{color:`primary`,autofocus:`autofocus`,onClick:e.handleNext},{default:(0,t.withCtx)(()=>n[0]||=[(0,t.createTextVNode)(` Next `)]),_:1},8,[`onClick`])]),_:1}))])}e.a(_sfc_render$25,`_sfc_render`);var h=l(c,[[`render`,_sfc_render$25],[`__scopeId`,`data-v-f91502f8`]]);function splitText(e,t,n){let r=e.split(t),a=r[0],o=r[1].split(n);return{left:a,middle:o[0],right:o[1]}}var g=class BlanksCard extends n.Question{static dataShapes=e.r;static views=[h];mdText=``;answers=null;options=null;splitTextToken(e){if((0,n.containsComponent)(e)){let t=splitText(e.text,`{{`,`}}`),n=splitText(e.raw,`{{`,`}}`),r=[];return n.left.length>0&&r.push({type:`text`,raw:n.left,text:t.left}),n.middle.length>0&&r.push({type:`text`,raw:`{{`+n.middle+`}}`,text:`{{`+t.middle+`}}`}),n.right.length>0&&r.push({type:`text`,raw:n.right,text:t.right}),r}else return[e]}optionsFromString(e){if(!e.startsWith(`{{`)||!e.endsWith(`}}`))throw Error(`string ${e} is not fill-in text - must look like "{{someText}}"`);e=e.substring(2,e.length-2);let t=e.split(`||`);if(t.length>1){let e=t[0].split(`|`).map(e=>e.trim()),n=t[1].split(`|`).map(e=>e.trim()).filter(t=>!e.includes(t));return n.push(e[randomInt(0,e.length-1)]),{answers:e,options:shuffle(n)}}else return{answers:[e.trim()],options:null}}constructor(e){super(e),this.mdText=e[0].Input,this.mdText===void 0&&(this.mdText=``);let t=(0,n.splitByDelimiters)(this.mdText,`{{`,`}}`),r=[];for(let e=0;e<t.length;e++){let a=t[e],o=a.trim();if(o.startsWith(`{{`)&&o.endsWith(`}}`))if((0,n.isInlineComponent)(o.slice(2,-2).trim()))r.push(a);else try{let e=this.optionsFromString(a);this.answers=e.answers,this.options=e.options,this.options?.length?r.push(`{{ || }}`):r.push(`{{ }}`)}catch{r.push(a)}else r.push(a)}this.mdText=r.join(``)}isCorrect(e){if(console.log(`answers:${this.answers}\nuser answer: ${JSON.stringify(e)}`),typeof e==`string`){if(this.answers)return this.answers.includes(e);if(e===``)return!0;throw Error(`Question has no configured answers!`)}else if(Array.isArray(e)){if(this.answers)return e.every(e=>this.answers.includes(e));throw Error(`Question has no configured answers!`)}else return this.isCorrectRadio(e)}dataShapes(){return BlanksCard.dataShapes}views(){return BlanksCard.views}isCorrectRadio(e){return this.answers?this.answers.includes(e.choiceList[e.selection]):!1}},CourseWare=class{get questions(){return this.questionList}get allViews(){let e=[];return this.questionList.forEach(t=>{t.views.forEach(t=>{e.push(t)})}),e}get allViewsMap(){let e={};return this.allViews.forEach(t=>{if(t.name)e[t.name]=t;else throw Error(`View has no name`)}),e}name;questionList;constructor(e,t){this.name=e,this.questionList=t,this.questionList=this.questionList.concat(this.getBaseQTypes())}getQuestion(e){let t=e.replace(/^_/,``).replace(/\d+$/,``),n=this.questionList.map(e=>e.name),r=this.questionList.find(n=>{let r=n.name.replace(/^_/,``).replace(/\d+$/,``);return n.name===e||r===t});if(r)return r.name!==e&&console.debug(`[CourseWare.getQuestion] stripped-exact: "${e}" → "${r.name}" (registered: ${n.join(`, `)})`),r;let a=this.questionList.filter(n=>{let r=n.name.replace(/^_/,``).replace(/\d+$/,``);return n.name.includes(t)||e.includes(r)});if(a.length===0){console.warn(`[CourseWare.getQuestion] NO MATCH: "${e}" (base: "${t}") not found in [${n.join(`, `)}]`);return}a.sort((t,n)=>Math.abs(t.name.length-e.length)-Math.abs(n.name.length-e.length));let o=a[0];return console.warn(`[CourseWare.getQuestion] FUZZY: "${e}" → "${o.name}" (candidates: ${a.map(e=>e.name).join(`, `)}; registered: ${n.join(`, `)})`),o}getBaseQTypes(){return[g]}},_=new CourseWare(`default`,[g]),y=[`cg-white`,`cg-black`],b=[`a`,`b`,`c`,`d`,`e`,`f`,`g`,`h`],x=[`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`],S=[...x].reverse(),C=Array.prototype.concat(...b.map(e=>x.map(t=>e+t))),pos2key=e=>C[8*e[0]+e[1]],key2pos=e=>[e.charCodeAt(0)-97,e.charCodeAt(1)-49],w=C.map(key2pos);function memo(e){let t,ret=()=>(t===void 0&&(t=e()),t);return ret.clear=()=>{t=void 0},ret}var timer=()=>{let e;return{start(){e=performance.now()},cancel(){e=void 0},stop(){if(!e)return 0;let t=performance.now()-e;return e=void 0,t}}},opposite=e=>e===`cg-white`?`cg-black`:`cg-white`,distanceSq=(e,t)=>{let n=e[0]-t[0],r=e[1]-t[1];return n*n+r*r},samePiece=(e,t)=>e.role===t.role&&e.color===t.color,posToTranslate=e=>(t,n)=>[(n?t[0]:7-t[0])*e.width/8,(n?7-t[1]:t[1])*e.height/8],translate=(e,t)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px)`},translateAndScale=(e,t,n=1)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px) scale(${n})`},setVisible=(e,t)=>{e.style.visibility=t?`visible`:`hidden`},eventPosition=e=>{if(e.clientX||e.clientX===0)return[e.clientX,e.clientY];if(e.targetTouches?.[0])return[e.targetTouches[0].clientX,e.targetTouches[0].clientY]},isRightButton=e=>e.button===2,createEl=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};function computeSquareCenter(e,t,n){let r=key2pos(e);return t||(r[0]=7-r[0],r[1]=7-r[1]),[n.left+n.width*r[0]/8+n.width/16,n.top+n.height*(7-r[1])/8+n.height/16]}var diff=(e,t)=>Math.abs(e-t),pawn=e=>(t,n,r,a)=>diff(t,r)<2&&(e===`cg-white`?a===n+1||n<=1&&a===n+2&&t===r:a===n-1||n>=6&&a===n-2&&t===r),knight=(e,t,n,r)=>{let a=diff(e,n),o=diff(t,r);return a===1&&o===2||a===2&&o===1},bishop=(e,t,n,r)=>diff(e,n)===diff(t,r),rook=(e,t,n,r)=>e===n||t===r,queen=(e,t,n,r)=>bishop(e,t,n,r)||rook(e,t,n,r),king=(e,t,n)=>(r,a,o,c)=>diff(r,o)<2&&diff(a,c)<2||n&&a===c&&a===(e===`cg-white`?0:7)&&(r===4&&(o===2&&t.includes(0)||o===6&&t.includes(7))||t.includes(o));function rookFilesOf(e,t){let n=t===`cg-white`?`1`:`8`,r=[];for(let[a,o]of e)a[1]===n&&o.color===t&&o.role===`rook`&&r.push(key2pos(a)[0]);return r}function premove(e,t,n){let r=e.get(t);if(!r)return[];let a=key2pos(t),o=r.role,c=o===`pawn`?pawn(r.color):o===`knight`?knight:o===`bishop`?bishop:o===`rook`?rook:o===`queen`?queen:king(r.color,rookFilesOf(e,r.color),n);return w.filter(e=>(a[0]!==e[0]||a[1]!==e[1])&&c(a[0],a[1],e[0],e[1])).map(pos2key)}function callUserFunction(e,...t){e&&setTimeout(()=>e(...t),1)}function toggleOrientation(e){e.orientation=opposite(e.orientation),e.animation.current=e.draggable.current=e.selected=void 0}function setPieces(e,t){for(let[n,r]of t)r?e.pieces.set(n,r):e.pieces.delete(n)}function setCheck(e,t){if(e.check=void 0,t===!0&&(t=e.turnColor),t)for(let[n,r]of e.pieces)r.role===`king`&&r.color===t&&(e.check=n)}function setPremove(e,t,n,r){unsetPredrop(e),e.premovable.current=[t,n],callUserFunction(e.premovable.events.set,t,n,r)}function unsetPremove(e){e.premovable.current&&(e.premovable.current=void 0,callUserFunction(e.premovable.events.unset))}function setPredrop(e,t,n){unsetPremove(e),e.predroppable.current={role:t,key:n},callUserFunction(e.predroppable.events.set,t,n)}function unsetPredrop(e){let t=e.predroppable;t.current&&(t.current=void 0,callUserFunction(t.events.unset))}function tryAutoCastle(e,t,n){if(!e.autoCastle)return!1;let r=e.pieces.get(t);if(!r||r.role!==`king`)return!1;let a=key2pos(t),o=key2pos(n);if(a[1]!==0&&a[1]!==7||a[1]!==o[1])return!1;a[0]===4&&!e.pieces.has(n)&&(o[0]===6?n=pos2key([7,o[1]]):o[0]===2&&(n=pos2key([0,o[1]])));let c=e.pieces.get(n);return!c||c.color!==r.color||c.role!==`rook`?!1:(e.pieces.delete(t),e.pieces.delete(n),a[0]<o[0]?(e.pieces.set(pos2key([6,o[1]]),r),e.pieces.set(pos2key([5,o[1]]),c)):(e.pieces.set(pos2key([2,o[1]]),r),e.pieces.set(pos2key([3,o[1]]),c)),!0)}function baseMove(e,t,n){let r=e.pieces.get(t),a=e.pieces.get(n);if(t===n||!r)return!1;let o=a&&a.color!==r.color?a:void 0;return n===e.selected&&unselect(e),callUserFunction(e.events.move,t,n,o),tryAutoCastle(e,t,n)||(e.pieces.set(n,r),e.pieces.delete(t)),e.lastMove=[t,n],e.check=void 0,callUserFunction(e.events.change),o||!0}function baseNewPiece(e,t,n,r){if(e.pieces.has(n))if(r)e.pieces.delete(n);else return!1;return callUserFunction(e.events.dropNewPiece,t,n),e.pieces.set(n,t),e.lastMove=[n],e.check=void 0,callUserFunction(e.events.change),e.movable.dests=void 0,e.turnColor=opposite(e.turnColor),!0}function baseUserMove(e,t,n){let r=baseMove(e,t,n);return r&&(e.movable.dests=void 0,e.turnColor=opposite(e.turnColor),e.animation.current=void 0),r}function userMove(e,t,n){if(canMove(e,t,n)){let r=baseUserMove(e,t,n);if(r){let a=e.hold.stop();unselect(e);let o={premove:!1,ctrlKey:e.stats.ctrlKey,holdTime:a};return r!==!0&&(o.captured=r),callUserFunction(e.movable.events.after,t,n,o),!0}}else if(canPremove(e,t,n))return setPremove(e,t,n,{ctrlKey:e.stats.ctrlKey}),unselect(e),!0;return unselect(e),!1}function dropNewPiece(e,t,n,r){let a=e.pieces.get(t);a&&(canDrop(e,t,n)||r)?(e.pieces.delete(t),baseNewPiece(e,a,n,r),callUserFunction(e.movable.events.afterNewPiece,a.role,n,{premove:!1,predrop:!1})):a&&canPredrop(e,t,n)?setPredrop(e,a.role,n):(unsetPremove(e),unsetPredrop(e)),e.pieces.delete(t),unselect(e)}function selectSquare(e,t,n){if(callUserFunction(e.events.select,t),e.selected){if(e.selected===t&&!e.draggable.enabled){unselect(e),e.hold.cancel();return}else if((e.selectable.enabled||n)&&e.selected!==t&&userMove(e,e.selected,t)){e.stats.dragged=!1;return}}(e.selectable.enabled||e.draggable.enabled)&&(isMovable(e,t)||isPremovable(e,t))&&(setSelected(e,t),e.hold.start())}function setSelected(e,t){e.selected=t,isPremovable(e,t)?e.premovable.customDests||(e.premovable.dests=premove(e.pieces,t,e.premovable.castle)):e.premovable.dests=void 0}function unselect(e){e.selected=void 0,e.premovable.dests=void 0,e.hold.cancel()}function isMovable(e,t){let n=e.pieces.get(t);return!!n&&(e.movable.color===`both`||e.movable.color===n.color&&e.turnColor===n.color)}var canMove=(e,t,n)=>t!==n&&isMovable(e,t)&&(e.movable.free||!!e.movable.dests?.get(t)?.includes(n));function canDrop(e,t,n){let r=e.pieces.get(t);return!!r&&(t===n||!e.pieces.has(n))&&(e.movable.color===`both`||e.movable.color===r.color&&e.turnColor===r.color)}function isPremovable(e,t){let n=e.pieces.get(t);return!!n&&e.premovable.enabled&&e.movable.color===n.color&&e.turnColor!==n.color}function canPremove(e,t,n){let r=e.premovable.customDests?.get(t)??premove(e.pieces,t,e.premovable.castle);return t!==n&&isPremovable(e,t)&&r.includes(n)}function canPredrop(e,t,n){let r=e.pieces.get(t),a=e.pieces.get(n);return!!r&&(!a||a.color!==e.movable.color)&&e.predroppable.enabled&&(r.role!==`pawn`||n[1]!==`1`&&n[1]!==`8`)&&e.movable.color===r.color&&e.turnColor!==r.color}function isDraggable(e,t){let n=e.pieces.get(t);return!!n&&e.draggable.enabled&&(e.movable.color===`both`||e.movable.color===n.color&&(e.turnColor===n.color||e.premovable.enabled))}function playPremove(e){let t=e.premovable.current;if(!t)return!1;let n=t[0],r=t[1],a=!1;if(canMove(e,n,r)){let t=baseUserMove(e,n,r);if(t){let o={premove:!0};t!==!0&&(o.captured=t),callUserFunction(e.movable.events.after,n,r,o),a=!0}}return unsetPremove(e),a}function playPredrop(e,t){let n=e.predroppable.current,r=!1;return n?(t(n)&&baseNewPiece(e,{role:n.role,color:e.movable.color},n.key)&&(callUserFunction(e.movable.events.afterNewPiece,n.role,n.key,{premove:!1,predrop:!0}),r=!0),unsetPredrop(e),r):!1}function cancelMove(e){unsetPremove(e),unsetPredrop(e),unselect(e)}function stop(e){e.movable.color=e.movable.dests=e.animation.current=void 0,cancelMove(e)}function getKeyAtDomPos(e,t,n){let r=Math.floor(8*(e[0]-n.left)/n.width);t||(r=7-r);let a=7-Math.floor(8*(e[1]-n.top)/n.height);return t||(a=7-a),r>=0&&r<8&&a>=0&&a<8?pos2key([r,a]):void 0}function getSnappedKeyAtDomPos(e,t,n,r){let a=key2pos(e),o=w.filter(e=>queen(a[0],a[1],e[0],e[1])||knight(a[0],a[1],e[0],e[1])),c=o.map(e=>computeSquareCenter(pos2key(e),n,r)).map(e=>distanceSq(t,e)),[,l]=c.reduce((e,t,n)=>e[0]<t?e:[t,n],[c[0],0]);return pos2key(o[l])}var whitePov=e=>e.orientation===`cg-white`,T=`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR`,E={p:`pawn`,r:`rook`,n:`knight`,b:`bishop`,q:`queen`,k:`king`},D={pawn:`p`,rook:`r`,knight:`n`,bishop:`b`,queen:`q`,king:`k`};function read(e){e===`start`&&(e=T);let t=new Map,n=7,r=0;for(let a of e)switch(a){case` `:case`[`:return t;case`/`:if(--n,n<0)return t;r=0;break;case`~`:{let e=t.get(pos2key([r-1,n]));e&&(e.promoted=!0);break}default:{let e=a.charCodeAt(0);if(e<57)r+=e-48;else{let e=a.toLowerCase();t.set(pos2key([r,n]),{role:E[e],color:a===e?`cg-black`:`cg-white`}),++r}}}return t}function write(e){return S.map(t=>b.map(n=>{let r=e.get(n+t);if(r){let e=D[r.role];return r.color===`cg-white`&&(e=e.toUpperCase()),r.promoted&&(e+=`~`),e}else return`1`}).join(``)).join(`/`).replace(/1{2,}/g,e=>e.length.toString())}function applyAnimation(e,t){t.animation&&(deepMerge(e.animation,t.animation),(e.animation.duration||0)<70&&(e.animation.enabled=!1))}function configure(e,t){if(t.movable?.dests&&(e.movable.dests=void 0),t.drawable?.autoShapes&&(e.drawable.autoShapes=[]),deepMerge(e,t),t.fen&&(e.pieces=read(t.fen),e.drawable.shapes=t.drawable?.shapes||[]),`check`in t&&setCheck(e,t.check||!1),`lastMove`in t&&!t.lastMove?e.lastMove=void 0:t.lastMove&&(e.lastMove=t.lastMove),e.selected&&setSelected(e,e.selected),applyAnimation(e,t),!e.movable.rookCastle&&e.movable.dests){let t=e.movable.color===`cg-white`?`1`:`8`,n=`e`+t,r=e.movable.dests.get(n),a=e.pieces.get(n);if(!r||!a||a.role!==`king`)return;e.movable.dests.set(n,r.filter(e=>!(e===`a`+t&&r.includes(`c`+t))&&!(e===`h`+t&&r.includes(`g`+t))))}}function deepMerge(e,t){for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)&&isPlainObject(e[n])&&isPlainObject(t[n])?deepMerge(e[n],t[n]):e[n]=t[n])}function isPlainObject(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var anim=(e,t)=>t.animation.enabled?animate(e,t):render$2(e,t);function render$2(e,t){let n=e(t);return t.dom.redraw(),n}e.a(render$2,`render`);var makePiece=(e,t)=>({key:e,pos:key2pos(e),piece:t}),closer=(e,t)=>t.sort((t,n)=>distanceSq(e.pos,t.pos)-distanceSq(e.pos,n.pos))[0];function computePlan(e,t){let n=new Map,r=[],a=new Map,o=[],c=[],l=new Map,u,d,p;for(let[t,n]of e)l.set(t,makePiece(t,n));for(let e of C)u=t.pieces.get(e),d=l.get(e),u?d?samePiece(u,d.piece)||(o.push(d),c.push(makePiece(e,u))):c.push(makePiece(e,u)):d&&o.push(d);for(let e of c)d=closer(e,o.filter(t=>samePiece(e.piece,t.piece))),d&&(p=[d.pos[0]-e.pos[0],d.pos[1]-e.pos[1]],n.set(e.key,p.concat(p)),r.push(d.key));for(let e of o)r.includes(e.key)||a.set(e.key,e.piece);return{anims:n,fadings:a}}function step(e,t){let n=e.animation.current;if(n===void 0){e.dom.destroyed||e.dom.redrawNow();return}let r=1-(t-n.start)*n.frequency;if(r<=0)e.animation.current=void 0,e.dom.redrawNow();else{let t=easing(r);for(let e of n.plan.anims.values())e[2]=e[0]*t,e[3]=e[1]*t;e.dom.redrawNow(!0),requestAnimationFrame((t=performance.now())=>step(e,t))}}function animate(e,t){let n=new Map(t.pieces),r=e(t),a=computePlan(n,t);if(a.anims.size||a.fadings.size){let e=t.animation.current&&t.animation.current.start;t.animation.current={start:performance.now(),frequency:1/t.animation.duration,plan:a},e||step(t,performance.now())}else t.dom.redraw();return r}var easing=e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,O=[`green`,`red`,`blue`,`yellow`];function start$2(e,t){if(t.touches&&t.touches.length>1)return;t.stopPropagation(),t.preventDefault(),t.ctrlKey?unselect(e):cancelMove(e);let n=eventPosition(t),r=getKeyAtDomPos(n,whitePov(e),e.dom.bounds());r&&(e.drawable.current={orig:r,pos:n,brush:eventBrush(t),snapToValidMove:e.drawable.defaultSnapToValidMove},processDraw(e))}e.a(start$2,`start`);function processDraw(e){requestAnimationFrame(()=>{let t=e.drawable.current;if(t){let n=getKeyAtDomPos(t.pos,whitePov(e),e.dom.bounds());n||(t.snapToValidMove=!1);let r=t.snapToValidMove?getSnappedKeyAtDomPos(t.orig,t.pos,whitePov(e),e.dom.bounds()):n;r!==t.mouseSq&&(t.mouseSq=r,t.dest=r===t.orig?void 0:r,e.dom.redrawNow()),processDraw(e)}})}function move$1(e,t){e.drawable.current&&(e.drawable.current.pos=eventPosition(t))}e.a(move$1,`move`);function end$1(e){let t=e.drawable.current;t&&(t.mouseSq&&addShape(e.drawable,t),cancel$1(e))}e.a(end$1,`end`);function cancel$1(e){e.drawable.current&&(e.drawable.current=void 0,e.dom.redraw())}e.a(cancel$1,`cancel`);function clear(e){e.drawable.shapes.length&&(e.drawable.shapes=[],e.dom.redraw(),onChange(e.drawable))}function eventBrush(e){let t=(e.shiftKey||e.ctrlKey)&&isRightButton(e),n=e.altKey||e.metaKey||e.getModifierState?.(`AltGraph`);return O[(t?1:0)+(n?2:0)]}function addShape(e,t){let sameShape=e=>e.orig===t.orig&&e.dest===t.dest,n=e.shapes.find(sameShape);n&&(e.shapes=e.shapes.filter(e=>!sameShape(e))),(!n||n.brush!==t.brush)&&e.shapes.push({orig:t.orig,dest:t.dest,brush:t.brush}),onChange(e)}function onChange(e){e.onChange&&e.onChange(e.shapes)}function start$1(e,t){if(!(e.trustAllEvents||t.isTrusted)||t.buttons!==void 0&&t.buttons>1||t.touches&&t.touches.length>1)return;let n=e.dom.bounds(),r=eventPosition(t),a=getKeyAtDomPos(r,whitePov(e),n);if(!a)return;let o=e.pieces.get(a),c=e.selected;if(!c&&e.drawable.enabled&&(e.drawable.eraseOnClick||!o||o.color!==e.turnColor)&&clear(e),t.cancelable!==!1&&(!t.touches||e.blockTouchScroll||o||c||pieceCloseTo(e,r)))t.preventDefault();else if(t.touches)return;let l=!!e.premovable.current,u=!!e.predroppable.current;e.stats.ctrlKey=t.ctrlKey,e.selected&&canMove(e,e.selected,a)?anim(e=>selectSquare(e,a),e):selectSquare(e,a);let d=e.selected===a,p=pieceElementByKey(e,a);if(o&&p&&d&&isDraggable(e,a)){e.draggable.current={orig:a,piece:o,origPos:r,pos:r,started:e.draggable.autoDistance&&e.stats.dragged,element:p,previouslySelected:c,originTarget:t.target,keyHasChanged:!1},p.cgDragging=!0,p.classList.add(`dragging`);let l=e.dom.elements.ghost;l&&(l.className=`ghost ${o.color} ${o.role}`,translate(l,posToTranslate(n)(key2pos(a),whitePov(e))),setVisible(l,!0)),processDrag(e)}else l&&unsetPremove(e),u&&unsetPredrop(e);e.dom.redraw()}e.a(start$1,`start`);function pieceCloseTo(e,t){let n=whitePov(e),r=e.dom.bounds(),a=(r.width/8)**2;for(let o of e.pieces.keys())if(distanceSq(computeSquareCenter(o,n,r),t)<=a)return!0;return!1}function dragNewPiece(e,t,n,r){e.pieces.set(`a0`,t),e.dom.redraw();let a=eventPosition(n);e.draggable.current={orig:`a0`,piece:t,origPos:a,pos:a,started:!0,element:()=>pieceElementByKey(e,`a0`),originTarget:n.target,newPiece:!0,force:!!r,keyHasChanged:!1},processDrag(e)}function processDrag(e){requestAnimationFrame(()=>{let t=e.draggable.current;if(!t)return;e.animation.current?.plan.anims.has(t.orig)&&(e.animation.current=void 0);let n=e.pieces.get(t.orig);if(!n||!samePiece(n,t.piece))cancel(e);else if(!t.started&&distanceSq(t.pos,t.origPos)>=e.draggable.distance**2&&(t.started=!0),t.started){if(typeof t.element==`function`){let e=t.element();if(!e)return;e.cgDragging=!0,e.classList.add(`dragging`),t.element=e}let n=e.dom.bounds();translate(t.element,[t.pos[0]-n.left-n.width/16,t.pos[1]-n.top-n.height/16]),t.keyHasChanged=t.keyHasChanged||t.orig!==getKeyAtDomPos(t.pos,whitePov(e),n)}processDrag(e)})}function move(e,t){e.draggable.current&&(!t.touches||t.touches.length<2)&&(e.draggable.current.pos=eventPosition(t))}function end(e,t){let n=e.draggable.current;if(!n)return;if(t.type===`touchend`&&t.cancelable!==!1&&t.preventDefault(),t.type===`touchend`&&n.originTarget!==t.target&&!n.newPiece){e.draggable.current=void 0;return}unsetPremove(e),unsetPredrop(e);let r=getKeyAtDomPos(eventPosition(t)||n.pos,whitePov(e),e.dom.bounds());r&&n.started&&n.orig!==r?n.newPiece?dropNewPiece(e,n.orig,r,n.force):(e.stats.ctrlKey=t.ctrlKey,userMove(e,n.orig,r)&&(e.stats.dragged=!0)):n.newPiece?e.pieces.delete(n.orig):e.draggable.deleteOnDropOff&&!r&&(e.pieces.delete(n.orig),callUserFunction(e.events.change)),(n.orig===n.previouslySelected||n.keyHasChanged)&&(n.orig===r||!r)?unselect(e):e.selectable.enabled||unselect(e),removeDragElements(e),e.draggable.current=void 0,e.dom.redraw()}function cancel(e){let t=e.draggable.current;t&&(t.newPiece&&e.pieces.delete(t.orig),e.draggable.current=void 0,unselect(e),removeDragElements(e),e.dom.redraw())}function removeDragElements(e){let t=e.dom.elements;t.ghost&&setVisible(t.ghost,!1)}function pieceElementByKey(e,t){let n=e.dom.elements.board.firstChild;for(;n;){if(n.cgKey===t&&n.tagName===`PIECE`)return n;n=n.nextSibling}}function explosion(e,t){e.exploding={stage:1,keys:t},e.dom.redraw(),setTimeout(()=>{setStage(e,2),setTimeout(()=>setStage(e,void 0),120)},120)}function setStage(e,t){e.exploding&&(t?e.exploding.stage=t:e.exploding=void 0,e.dom.redraw())}function start(t,n){function toggleOrientation$1(){toggleOrientation(t),n()}return e.a(toggleOrientation$1,`toggleOrientation`),{set(e){e.orientation&&e.orientation!==t.orientation&&toggleOrientation$1(),applyAnimation(t,e),(e.fen?anim:render$2)(t=>configure(t,e),t)},state:t,getFen:()=>write(t.pieces),toggleOrientation:toggleOrientation$1,setPieces(e){anim(t=>setPieces(t,e),t)},selectSquare(e,n){e?anim(t=>selectSquare(t,e,n),t):t.selected&&(unselect(t),t.dom.redraw())},move(e,n){anim(t=>baseMove(t,e,n),t)},newPiece(e,n){anim(t=>baseNewPiece(t,e,n),t)},playPremove(){if(t.premovable.current){if(anim(playPremove,t))return!0;t.dom.redraw()}return!1},playPredrop(e){if(t.predroppable.current){let n=playPredrop(t,e);return t.dom.redraw(),n}return!1},cancelPremove(){render$2(unsetPremove,t)},cancelPredrop(){render$2(unsetPredrop,t)},cancelMove(){render$2(e=>{cancelMove(e),cancel(e)},t)},stop(){render$2(e=>{stop(e),cancel(e)},t)},explode(e){explosion(t,e)},setAutoShapes(e){render$2(t=>t.drawable.autoShapes=e,t)},setShapes(e){render$2(t=>t.drawable.shapes=e,t)},getKeyAtDomPos(e){return getKeyAtDomPos(e,whitePov(t),t.dom.bounds())},redrawAll:n,dragNewPiece(e,n,r){dragNewPiece(t,e,n,r)},destroy(){stop(t),t.dom.unbind?.(),t.dom.destroyed=!0}}}function defaults(){return{pieces:read(T),orientation:`cg-white`,turnColor:`cg-white`,coordinates:!0,coordinatesOnSquares:!1,ranksPosition:`right`,autoCastle:!0,viewOnly:!1,disableContextMenu:!1,addPieceZIndex:!1,blockTouchScroll:!1,pieceKey:!1,trustAllEvents:!1,highlight:{lastMove:!0,check:!0},animation:{enabled:!0,duration:200},movable:{free:!0,color:`both`,showDests:!0,events:{},rookCastle:!0},premovable:{enabled:!0,showDests:!0,castle:!0,events:{}},predroppable:{enabled:!1,events:{}},draggable:{enabled:!0,distance:3,autoDistance:!0,showGhost:!0,deleteOnDropOff:!1},dropmode:{active:!1},selectable:{enabled:!0},stats:{dragged:!(`ontouchstart`in window)},events:{},drawable:{enabled:!0,visible:!0,defaultSnapToValidMove:!0,eraseOnClick:!0,shapes:[],autoShapes:[],brushes:{green:{key:`g`,color:`#15781B`,opacity:1,lineWidth:10},red:{key:`r`,color:`#882020`,opacity:1,lineWidth:10},blue:{key:`b`,color:`#003088`,opacity:1,lineWidth:10},yellow:{key:`y`,color:`#e68f00`,opacity:1,lineWidth:10},paleBlue:{key:`pb`,color:`#003088`,opacity:.4,lineWidth:15},paleGreen:{key:`pg`,color:`#15781B`,opacity:.4,lineWidth:15},paleRed:{key:`pr`,color:`#882020`,opacity:.4,lineWidth:15},paleGrey:{key:`pgr`,color:`#4a4a4a`,opacity:.35,lineWidth:15},purple:{key:`purple`,color:`#68217a`,opacity:.65,lineWidth:10},pink:{key:`pink`,color:`#ee2080`,opacity:.5,lineWidth:10},white:{key:`white`,color:`white`,opacity:1,lineWidth:10}},prevSvgHash:``},hold:timer()}}var k={hilitePrimary:{key:`hilitePrimary`,color:`#3291ff`,opacity:1,lineWidth:1},hiliteWhite:{key:`hiliteWhite`,color:`#ffffff`,opacity:1,lineWidth:1}};function createDefs(){let e=createElement(`defs`),t=setAttributes(createElement(`filter`),{id:`cg-filter-blur`});return t.appendChild(setAttributes(createElement(`feGaussianBlur`),{stdDeviation:`0.019`})),e.appendChild(t),e}function renderSvg(e,t,n){let r=e.drawable,a=r.current,o=a&&a.mouseSq?a:void 0,c=new Map,l=e.dom.bounds(),u=r.autoShapes.filter(e=>!e.piece);for(let t of r.shapes.concat(u).concat(o?[o]:[])){if(!t.dest)continue;let n=c.get(t.dest)??new Set,r=pos2user(orient(key2pos(t.orig),e.orientation),l),a=pos2user(orient(key2pos(t.dest),e.orientation),l);n.add(moveAngle(r,a)),c.set(t.dest,n)}let d=r.shapes.concat(u).map(e=>({shape:e,current:!1,hash:shapeHash(e,isShort(e.dest,c),!1,l)}));o&&d.push({shape:o,current:!0,hash:shapeHash(o,isShort(o.dest,c),!0,l)});let p=d.map(e=>e.hash).join(`;`);p!==e.drawable.prevSvgHash&&(e.drawable.prevSvgHash=p,syncDefs(r,d,t.querySelector(`defs`)),syncShapes$1(d,t.querySelector(`g`),n.querySelector(`g`),t=>renderShape$1(e,t,r.brushes,c,l)))}function syncDefs(e,t,n){let r=new Map,a;for(let n of t.filter(e=>e.shape.dest&&e.shape.brush))a=makeCustomBrush(e.brushes[n.shape.brush],n.shape.modifiers),n.shape.modifiers?.hilite&&r.set(hilite(a).key,hilite(a)),r.set(a.key,a);let o=new Set,c=n.firstElementChild;for(;c;)o.add(c.getAttribute(`cgKey`)),c=c.nextElementSibling;for(let[e,t]of r.entries())o.has(e)||n.appendChild(renderMarker(t))}function syncShapes$1(e,t,n,r){let a=new Map;for(let t of e)a.set(t.hash,!1);for(let e of[t,n]){let t=[],n=e.firstElementChild,r;for(;n;)r=n.getAttribute(`cgHash`),a.has(r)?a.set(r,!0):t.push(n),n=n.nextElementSibling;for(let n of t)e.removeChild(n)}for(let o of e.filter(e=>!a.get(e.hash)))for(let e of r(o))e.isCustom?n.appendChild(e.el):t.appendChild(e.el)}e.a(syncShapes$1,`syncShapes`);function shapeHash({orig:e,dest:t,brush:n,piece:r,modifiers:a,customSvg:o,label:c},l,u,d){return[d.width,d.height,u,e,t,n,l&&`-`,r&&pieceHash(r),a&&modifiersHash(a),o&&`custom-${textHash(o.html)},${o.center?.[0]??`o`}`,c&&`label-${textHash(c.text)}`].filter(e=>e).join(`,`)}function pieceHash(e){return[e.color,e.role,e.scale].filter(e=>e).join(`,`)}function modifiersHash(e){return[e.lineWidth,e.hilite&&`*`].filter(e=>e).join(`,`)}function textHash(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)>>>0;return t.toString()}function renderShape$1(e,{shape:t,current:n,hash:r},a,o,c){let l=pos2user(orient(key2pos(t.orig),e.orientation),c),u=t.dest?pos2user(orient(key2pos(t.dest),e.orientation),c):l,d=t.brush&&makeCustomBrush(a[t.brush],t.modifiers),p=o.get(t.dest),m=[];if(d){let e=setAttributes(createElement(`g`),{cgHash:r});m.push({el:e}),l[0]!==u[0]||l[1]!==u[1]?e.appendChild(renderArrow(t,d,l,u,n,isShort(t.dest,o))):e.appendChild(renderCircle(a[t.brush],l,n,c))}if(t.label){let e=t.label;e.fill||t.brush&&a[t.brush]&&(e.fill=a[t.brush].color);let n=t.brush?void 0:`tr`;m.push({el:renderLabel(e,r,l,u,p,n),isCustom:!0})}if(t.customSvg){let e=t.customSvg.center??`orig`,[n,a]=e===`label`?labelCoords(l,u,p).map(e=>e-.5):e===`dest`?u:l,o=setAttributes(createElement(`g`),{transform:`translate(${n},${a})`,cgHash:r});o.innerHTML=`<svg width="1" height="1" viewBox="0 0 100 100">${t.customSvg.html}</svg>`,m.push({el:o,isCustom:!0})}return m}e.a(renderShape$1,`renderShape`);function renderCircle(e,t,n,r){let a=circleWidth(),o=(r.width+r.height)/(4*Math.max(r.width,r.height));return setAttributes(createElement(`circle`),{stroke:e.color,"stroke-width":a[n?0:1],fill:`none`,opacity:opacity(e,n),cx:t[0],cy:t[1],r:o-a[1]/2})}function hilite(e){return[`#ffffff`,`#fff`,`white`].includes(e.color)?k.hilitePrimary:k.hiliteWhite}function renderArrow(e,t,n,r,a,o){function renderLine(c){let l=arrowMargin(o&&!a),u=r[0]-n[0],d=r[1]-n[1],p=Math.atan2(d,u),m=Math.cos(p)*l,h=Math.sin(p)*l;return setAttributes(createElement(`line`),{stroke:c?hilite(t).color:t.color,"stroke-width":lineWidth(t,a)+(c?.04:0),"stroke-linecap":`round`,"marker-end":`url(#arrowhead-${c?hilite(t).key:t.key})`,opacity:e.modifiers?.hilite?1:opacity(t,a),x1:n[0],y1:n[1],x2:r[0]-m,y2:r[1]-h})}if(!e.modifiers?.hilite)return renderLine(!1);let c=createElement(`g`),l=setAttributes(createElement(`g`),{filter:`url(#cg-filter-blur)`});return l.appendChild(filterBox(n,r)),l.appendChild(renderLine(!0)),c.appendChild(l),c.appendChild(renderLine(!1)),c}function renderMarker(e){let t=setAttributes(createElement(`marker`),{id:`arrowhead-`+e.key,orient:`auto`,overflow:`visible`,markerWidth:4,markerHeight:4,refX:e.key.startsWith(`hilite`)?1.86:2.05,refY:2});return t.appendChild(setAttributes(createElement(`path`),{d:`M0,0 V4 L3,2 Z`,fill:e.color})),t.setAttribute(`cgKey`,e.key),t}function renderLabel(e,t,n,r,a,o){let c=.4,l=c*.75**e.text.length,u=labelCoords(n,r,a),d=o===`tr`?.4:0,p=setAttributes(createElement(`g`),{transform:`translate(${u[0]+d},${u[1]-d})`,cgHash:t});p.appendChild(setAttributes(createElement(`circle`),{r:c/2,"fill-opacity":o?1:.8,"stroke-opacity":o?1:.7,"stroke-width":.03,fill:e.fill??`#666`,stroke:`white`}));let m=setAttributes(createElement(`text`),{"font-size":l,"font-family":`Noto Sans`,"text-anchor":`middle`,fill:`white`,y:.13*.75**e.text.length});return m.innerHTML=e.text,p.appendChild(m),p}function orient(e,t){return t===`cg-white`?e:[7-e[0],7-e[1]]}function isShort(e,t){return!0===(e&&t.has(e)&&t.get(e).size>1)}function createElement(e){return document.createElementNS(`http://www.w3.org/2000/svg`,e)}function setAttributes(e,t){for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.setAttribute(n,t[n]);return e}function makeCustomBrush(e,t){return t?{color:e.color,opacity:Math.round(e.opacity*10)/10,lineWidth:Math.round(t.lineWidth||e.lineWidth),key:[e.key,t.lineWidth].filter(e=>e).join(``)}:e}function circleWidth(){return[3/64,4/64]}function lineWidth(e,t){return(e.lineWidth||10)*(t?.85:1)/64}function opacity(e,t){return(e.opacity||1)*(t?.9:1)}function arrowMargin(e){return(e?20:10)/64}function pos2user(e,t){let n=Math.min(1,t.width/t.height),r=Math.min(1,t.height/t.width);return[(e[0]-3.5)*n,(3.5-e[1])*r]}function filterBox(e,t){let n={from:[Math.floor(Math.min(e[0],t[0])),Math.floor(Math.min(e[1],t[1]))],to:[Math.ceil(Math.max(e[0],t[0])),Math.ceil(Math.max(e[1],t[1]))]};return setAttributes(createElement(`rect`),{x:n.from[0],y:n.from[1],width:n.to[0]-n.from[0],height:n.to[1]-n.from[1],fill:`none`,stroke:`none`})}function moveAngle(e,t,n=!0){let r=Math.atan2(t[1]-e[1],t[0]-e[0])+Math.PI;return n?(Math.round(r*8/Math.PI)+16)%16:r}function dist(e,t){return Math.sqrt([e[0]-t[0],e[1]-t[1]].reduce((e,t)=>e+t*t,0))}function labelCoords(e,t,n){let r=dist(e,t),a=moveAngle(e,t,!1);if(n&&(r-=33/64,n.size>1)){r-=10/64;let a=moveAngle(e,t);(n.has((a+1)%16)||n.has((a+15)%16))&&a&1&&(r-=.4)}return[e[0]-Math.cos(a)*r,e[1]-Math.sin(a)*r].map(e=>e+.5)}function renderWrap(e,t){e.innerHTML=``,e.classList.add(`cg-wrap`);for(let n of y)e.classList.toggle(`orientation-`+n,t.orientation===n);e.classList.toggle(`manipulable`,!t.viewOnly);let n=createEl(`cg-container`);e.appendChild(n);let r=createEl(`cg-board`);n.appendChild(r);let a,o,c;if(t.drawable.visible&&(a=setAttributes(createElement(`svg`),{class:`cg-shapes`,viewBox:`-4 -4 8 8`,preserveAspectRatio:`xMidYMid slice`}),a.appendChild(createDefs()),a.appendChild(createElement(`g`)),o=setAttributes(createElement(`svg`),{class:`cg-custom-svgs`,viewBox:`-3.5 -3.5 8 8`,preserveAspectRatio:`xMidYMid slice`}),o.appendChild(createElement(`g`)),c=createEl(`cg-auto-pieces`),n.appendChild(a),n.appendChild(o),n.appendChild(c)),t.coordinates){let e=t.orientation===`cg-black`?` black`:``,r=t.ranksPosition===`left`?` left`:``;if(t.coordinatesOnSquares){let a=t.orientation===`cg-white`?e=>e+1:e=>8-e;b.forEach((t,o)=>n.appendChild(renderCoords(x.map(e=>t+e),`squares rank`+a(o)+e+r)))}else n.appendChild(renderCoords(x,`ranks`+e+r)),n.appendChild(renderCoords(b,`files`+e))}let l;return t.draggable.enabled&&t.draggable.showGhost&&(l=createEl(`piece`,`ghost`),setVisible(l,!1),n.appendChild(l)),{board:r,container:n,wrap:e,ghost:l,svg:a,customSvg:o,autoPieces:c}}function renderCoords(e,t){let n=createEl(`coords`,t),r;for(let t of e)r=createEl(`coord`),r.textContent=t,n.appendChild(r);return n}function drop(e,t){if(!e.dropmode.active)return;unsetPremove(e),unsetPredrop(e);let n=e.dropmode.piece;if(n){e.pieces.set(`a0`,n);let r=eventPosition(t),a=r&&getKeyAtDomPos(r,whitePov(e),e.dom.bounds());a&&dropNewPiece(e,`a0`,a)}e.dom.redraw()}function bindBoard(e){let t=e.dom.elements.board;if((e.disableContextMenu||e.drawable.enabled)&&t.addEventListener(`contextmenu`,e=>e.preventDefault()),e.viewOnly)return;let n=startDragOrDraw(e);t.addEventListener(`touchstart`,n,{passive:!1}),t.addEventListener(`mousedown`,n,{passive:!1})}function bindDocument(e,t){let n=[];if(`ResizeObserver`in window||n.push(unbindable(document.body,`chessground.resize`,t)),!e.viewOnly){let t=dragOrDraw(e,move,move$1),r=dragOrDraw(e,end,end$1);for(let e of[`touchmove`,`mousemove`])n.push(unbindable(document,e,t));for(let e of[`touchend`,`mouseup`])n.push(unbindable(document,e,r));let onScroll=()=>e.dom.bounds.clear();n.push(unbindable(document,`scroll`,onScroll,{capture:!0,passive:!0})),n.push(unbindable(window,`resize`,onScroll,{passive:!0}))}return()=>n.forEach(e=>e())}function unbindable(e,t,n,r){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n,r)}var startDragOrDraw=e=>t=>{e.draggable.current?cancel(e):e.drawable.current?cancel$1(e):t.shiftKey||isRightButton(t)?e.drawable.enabled&&start$2(e,t):e.viewOnly||(e.dropmode.active?drop(e,t):start$1(e,t))},dragOrDraw=(e,t,n)=>r=>{e.drawable.current?e.drawable.enabled&&n(e,r):e.viewOnly||t(e,r)};function render$1(e){let t=whitePov(e),n=posToTranslate(e.dom.bounds()),r=e.dom.elements.board,a=e.pieces,o=e.animation.current,c=o?o.plan.anims:new Map,l=o?o.plan.fadings:new Map,u=e.draggable.current,d=computeSquareClasses(e),p=new Set,m=new Set,h=new Map,g=new Map,_,y,b,x,S,C,w,T,E,D;for(y=r.firstChild;y;){if(_=y.cgKey,isPieceNode(y))if(b=a.get(_),S=c.get(_),C=l.get(_),x=y.cgPiece,y.cgDragging&&(!u||u.orig!==_)&&(y.classList.remove(`dragging`),translate(y,n(key2pos(_),t)),y.cgDragging=!1),!C&&y.cgFading&&(y.cgFading=!1,y.classList.remove(`fading`)),b){if(S&&y.cgAnimating&&x===pieceNameOf(b)){let e=key2pos(_);e[0]+=S[2],e[1]+=S[3],y.classList.add(`anim`),translate(y,n(e,t))}else y.cgAnimating&&(y.cgAnimating=!1,y.classList.remove(`anim`),translate(y,n(key2pos(_),t)),e.addPieceZIndex&&(y.style.zIndex=posZIndex(key2pos(_),t)));x===pieceNameOf(b)&&(!C||!y.cgFading)?p.add(_):C&&x===pieceNameOf(C)?(y.classList.add(`fading`),y.cgFading=!0):appendValue(h,x,y)}else appendValue(h,x,y);else if(isSquareNode(y)){let e=y.className;d.get(_)===e?m.add(_):appendValue(g,e,y)}y=y.nextSibling}for(let[e,a]of d)if(!m.has(e)){E=g.get(a),D=E&&E.pop();let o=n(key2pos(e),t);if(D)D.cgKey=e,translate(D,o);else{let t=createEl(`square`,a);t.cgKey=e,translate(t,o),r.insertBefore(t,r.firstChild)}}for(let[o,l]of a)if(S=c.get(o),!p.has(o))if(w=h.get(pieceNameOf(l)),T=w&&w.pop(),T){T.cgKey=o,T.cgFading&&(T.classList.remove(`fading`),T.cgFading=!1);let r=key2pos(o);e.addPieceZIndex&&(T.style.zIndex=posZIndex(r,t)),S&&(T.cgAnimating=!0,T.classList.add(`anim`),r[0]+=S[2],r[1]+=S[3]),translate(T,n(r,t))}else{let a=pieceNameOf(l),c=createEl(`piece`,a),u=key2pos(o);c.cgPiece=a,c.cgKey=o,S&&(c.cgAnimating=!0,u[0]+=S[2],u[1]+=S[3]),translate(c,n(u,t)),e.addPieceZIndex&&(c.style.zIndex=posZIndex(u,t)),r.appendChild(c)}for(let t of h.values())removeNodes(e,t);for(let t of g.values())removeNodes(e,t)}e.a(render$1,`render`);function renderResized$1(e){let t=whitePov(e),n=posToTranslate(e.dom.bounds()),r=e.dom.elements.board.firstChild;for(;r;)(isPieceNode(r)&&!r.cgAnimating||isSquareNode(r))&&translate(r,n(key2pos(r.cgKey),t)),r=r.nextSibling}e.a(renderResized$1,`renderResized`);function updateBounds(e){let t=e.dom.elements.wrap.getBoundingClientRect(),n=e.dom.elements.container,r=t.height/t.width,a=Math.floor(t.width*window.devicePixelRatio/8)*8/window.devicePixelRatio,o=a*r;n.style.width=a+`px`,n.style.height=o+`px`,e.dom.bounds.clear(),e.addDimensionsCssVarsTo?.style.setProperty(`---cg-width`,a+`px`),e.addDimensionsCssVarsTo?.style.setProperty(`---cg-height`,o+`px`)}var isPieceNode=e=>e.tagName===`PIECE`,isSquareNode=e=>e.tagName===`SQUARE`;function removeNodes(e,t){for(let n of t)e.dom.elements.board.removeChild(n)}function posZIndex(e,t){let n=e[1];return`${t?10-n:3+n}`}var pieceNameOf=e=>`${e.color} ${e.role}`;function computeSquareClasses(e){let t=new Map;if(e.lastMove&&e.highlight.lastMove)for(let n of e.lastMove)addSquare(t,n,`last-move`);if(e.check&&e.highlight.check&&addSquare(t,e.check,`check`),e.selected&&(addSquare(t,e.selected,`selected`),e.movable.showDests)){let n=e.movable.dests?.get(e.selected);if(n)for(let r of n)addSquare(t,r,`move-dest`+(e.pieces.has(r)?` oc`:``));let r=e.premovable.customDests?.get(e.selected)??e.premovable.dests;if(r)for(let n of r)addSquare(t,n,`premove-dest`+(e.pieces.has(n)?` oc`:``))}let n=e.premovable.current;if(n)for(let e of n)addSquare(t,e,`current-premove`);else e.predroppable.current&&addSquare(t,e.predroppable.current.key,`current-premove`);let r=e.exploding;if(r)for(let e of r.keys)addSquare(t,e,`exploding`+r.stage);return e.highlight.custom&&e.highlight.custom.forEach((e,n)=>{addSquare(t,n,e)}),t}function addSquare(e,t,n){let r=e.get(t);r?e.set(t,`${r} ${n}`):e.set(t,n)}function appendValue(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function syncShapes(e,t,n){let r=new Map,a=[];for(let t of e)r.set(t.hash,!1);let o=t.firstElementChild,c;for(;o;)c=o.getAttribute(`cgHash`),r.has(c)?r.set(c,!0):a.push(o),o=o.nextElementSibling;for(let e of a)t.removeChild(e);for(let a of e)r.get(a.hash)||t.appendChild(n(a))}function render(e,t){syncShapes(e.drawable.autoShapes.filter(e=>e.piece).map(e=>({shape:e,hash:hash(e),current:!1})),t,t=>renderShape(e,t,e.dom.bounds()))}function renderResized(e){let t=whitePov(e),n=posToTranslate(e.dom.bounds()),r=e.dom.elements.autoPieces?.firstChild;for(;r;)translateAndScale(r,n(key2pos(r.cgKey),t),r.cgScale),r=r.nextSibling}function renderShape(e,{shape:t,hash:n},r){let a=t.orig,o=t.piece?.role,c=t.piece?.color,l=t.piece?.scale,u=createEl(`piece`,`${o} ${c}`);return u.setAttribute(`cgHash`,n),u.cgKey=a,u.cgScale=l,translateAndScale(u,posToTranslate(r)(key2pos(a),whitePov(e)),l),u}var hash=e=>[e.orig,e.piece?.role,e.piece?.color,e.piece?.scale].join(`,`);function Chessground(e,t){let n=defaults();configure(n,t||{});function redrawAll(){let t=`dom`in n?n.dom.unbind:void 0,r=renderWrap(e,n),a=memo(()=>r.board.getBoundingClientRect()),redrawNow=e=>{render$1(o),r.autoPieces&&render(o,r.autoPieces),!e&&r.svg&&renderSvg(o,r.svg,r.customSvg)},onResize=()=>{updateBounds(o),renderResized$1(o),r.autoPieces&&renderResized(o)},o=n;return o.dom={elements:r,bounds:a,redraw:debounceRedraw(redrawNow),redrawNow,unbind:t},o.drawable.prevSvgHash=``,updateBounds(o),redrawNow(!1),bindBoard(o),t||(o.dom.unbind=bindDocument(o,onResize)),o.events.insert?.(r),o}return start(redrawAll(),redrawAll)}function debounceRedraw(e){let t=!1;return()=>{t||(t=!0,requestAnimationFrame(()=>{e(),t=!1}))}}var A=`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1`,Move=class{color;from;to;piece;captured;promotion;flags;san;lan;before;after;constructor(e,t){let{color:n,piece:r,from:a,to:o,flags:c,captured:l,promotion:u}=t,d=algebraic(a),p=algebraic(o);this.color=n,this.piece=r,this.from=d,this.to=p,this.san=e._moveToSan(t,e._moves({legal:!0})),this.lan=d+p,this.before=e.fen(),e._makeMove(t),this.after=e.fen(),e._undoMove(),this.flags=``;for(let e in P)P[e]&c&&(this.flags+=M[e]);l&&(this.captured=l),u&&(this.promotion=u,this.lan+=u)}isCapture(){return this.flags.indexOf(M.CAPTURE)>-1}isPromotion(){return this.flags.indexOf(M.PROMOTION)>-1}isEnPassant(){return this.flags.indexOf(M.EP_CAPTURE)>-1}isKingsideCastle(){return this.flags.indexOf(M.KSIDE_CASTLE)>-1}isQueensideCastle(){return this.flags.indexOf(M.QSIDE_CASTLE)>-1}isBigPawn(){return this.flags.indexOf(M.BIG_PAWN)>-1}},j=-1,M={NORMAL:`n`,CAPTURE:`c`,BIG_PAWN:`b`,EP_CAPTURE:`e`,PROMOTION:`p`,KSIDE_CASTLE:`k`,QSIDE_CASTLE:`q`},N=`a8.b8.c8.d8.e8.f8.g8.h8.a7.b7.c7.d7.e7.f7.g7.h7.a6.b6.c6.d6.e6.f6.g6.h6.a5.b5.c5.d5.e5.f5.g5.h5.a4.b4.c4.d4.e4.f4.g4.h4.a3.b3.c3.d3.e3.f3.g3.h3.a2.b2.c2.d2.e2.f2.g2.h2.a1.b1.c1.d1.e1.f1.g1.h1`.split(`.`),P={NORMAL:1,CAPTURE:2,BIG_PAWN:4,EP_CAPTURE:8,PROMOTION:16,KSIDE_CASTLE:32,QSIDE_CASTLE:64},F={a8:0,b8:1,c8:2,d8:3,e8:4,f8:5,g8:6,h8:7,a7:16,b7:17,c7:18,d7:19,e7:20,f7:21,g7:22,h7:23,a6:32,b6:33,c6:34,d6:35,e6:36,f6:37,g6:38,h6:39,a5:48,b5:49,c5:50,d5:51,e5:52,f5:53,g5:54,h5:55,a4:64,b4:65,c4:66,d4:67,e4:68,f4:69,g4:70,h4:71,a3:80,b3:81,c3:82,d3:83,e3:84,f3:85,g3:86,h3:87,a2:96,b2:97,c2:98,d2:99,e2:100,f2:101,g2:102,h2:103,a1:112,b1:113,c1:114,d1:115,e1:116,f1:117,g1:118,h1:119},I={b:[16,32,17,15],w:[-16,-32,-17,-15]},L={n:[-18,-33,-31,-14,18,33,31,14],b:[-17,-15,17,15],r:[-16,1,16,-1],q:[-17,-16,-15,1,17,16,15,-1],k:[-17,-16,-15,1,17,16,15,-1]},R=[20,0,0,0,0,0,0,24,0,0,0,0,0,0,20,0,0,20,0,0,0,0,0,24,0,0,0,0,0,20,0,0,0,0,20,0,0,0,0,24,0,0,0,0,20,0,0,0,0,0,0,20,0,0,0,24,0,0,0,20,0,0,0,0,0,0,0,0,20,0,0,24,0,0,20,0,0,0,0,0,0,0,0,0,0,20,2,24,2,20,0,0,0,0,0,0,0,0,0,0,0,2,53,56,53,2,0,0,0,0,0,0,24,24,24,24,24,24,56,0,56,24,24,24,24,24,24,0,0,0,0,0,0,2,53,56,53,2,0,0,0,0,0,0,0,0,0,0,0,20,2,24,2,20,0,0,0,0,0,0,0,0,0,0,20,0,0,24,0,0,20,0,0,0,0,0,0,0,0,20,0,0,0,24,0,0,0,20,0,0,0,0,0,0,20,0,0,0,0,24,0,0,0,0,20,0,0,0,0,20,0,0,0,0,0,24,0,0,0,0,0,20,0,0,20,0,0,0,0,0,0,24,0,0,0,0,0,0,20],z=[17,0,0,0,0,0,0,16,0,0,0,0,0,0,15,0,0,17,0,0,0,0,0,16,0,0,0,0,0,15,0,0,0,0,17,0,0,0,0,16,0,0,0,0,15,0,0,0,0,0,0,17,0,0,0,16,0,0,0,15,0,0,0,0,0,0,0,0,17,0,0,16,0,0,15,0,0,0,0,0,0,0,0,0,0,17,0,16,0,15,0,0,0,0,0,0,0,0,0,0,0,0,17,16,15,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,-15,-16,-17,0,0,0,0,0,0,0,0,0,0,0,0,-15,0,-16,0,-17,0,0,0,0,0,0,0,0,0,0,-15,0,0,-16,0,0,-17,0,0,0,0,0,0,0,0,-15,0,0,0,-16,0,0,0,-17,0,0,0,0,0,0,-15,0,0,0,0,-16,0,0,0,0,-17,0,0,0,0,-15,0,0,0,0,0,-16,0,0,0,0,0,-17,0,0,-15,0,0,0,0,0,0,-16,0,0,0,0,0,0,-17],B={p:1,n:2,b:4,r:8,q:16,k:32},V=`pnbrqkPNBRQK`,H=[`n`,`b`,`r`,`q`],U=7,ee=6,W=1,te=0,ne={k:P.KSIDE_CASTLE,q:P.QSIDE_CASTLE},re={w:[{square:F.a1,flag:P.QSIDE_CASTLE},{square:F.h1,flag:P.KSIDE_CASTLE}],b:[{square:F.a8,flag:P.QSIDE_CASTLE},{square:F.h8,flag:P.KSIDE_CASTLE}]},ie={b:W,w:ee},G=[`1-0`,`0-1`,`1/2-1/2`,`*`];function rank(e){return e>>4}function file(e){return e&15}function isDigit(e){return`0123456789`.indexOf(e)!==-1}function algebraic(e){let t=file(e),n=rank(e);return`abcdefgh`.substring(t,t+1)+`87654321`.substring(n,n+1)}function swapColor$1(e){return e===`w`?`b`:`w`}e.a(swapColor$1,`swapColor`);function validateFen(e){let t=e.split(/\s+/);if(t.length!==6)return{ok:!1,error:`Invalid FEN: must contain six space-delimited fields`};let n=parseInt(t[5],10);if(isNaN(n)||n<=0)return{ok:!1,error:`Invalid FEN: move number must be a positive integer`};let r=parseInt(t[4],10);if(isNaN(r)||r<0)return{ok:!1,error:`Invalid FEN: half move counter number must be a non-negative integer`};if(!/^(-|[abcdefgh][36])$/.test(t[3]))return{ok:!1,error:`Invalid FEN: en-passant square is invalid`};if(/[^kKqQ-]/.test(t[2]))return{ok:!1,error:`Invalid FEN: castling availability is invalid`};if(!/^(w|b)$/.test(t[1]))return{ok:!1,error:`Invalid FEN: side-to-move is invalid`};let a=t[0].split(`/`);if(a.length!==8)return{ok:!1,error:`Invalid FEN: piece data does not contain 8 '/'-delimited rows`};for(let e=0;e<a.length;e++){let t=0,n=!1;for(let r=0;r<a[e].length;r++)if(isDigit(a[e][r])){if(n)return{ok:!1,error:`Invalid FEN: piece data is invalid (consecutive number)`};t+=parseInt(a[e][r],10),n=!0}else{if(!/^[prnbqkPRNBQK]$/.test(a[e][r]))return{ok:!1,error:`Invalid FEN: piece data is invalid (invalid piece)`};t+=1,n=!1}if(t!==8)return{ok:!1,error:`Invalid FEN: piece data is invalid (too many squares in rank)`}}if(t[3][1]==`3`&&t[1]==`w`||t[3][1]==`6`&&t[1]==`b`)return{ok:!1,error:`Invalid FEN: illegal en-passant square`};for(let{color:e,regex:n}of[{color:`white`,regex:/K/g},{color:`black`,regex:/k/g}]){if(!n.test(t[0]))return{ok:!1,error:`Invalid FEN: missing ${e} king`};if((t[0].match(n)||[]).length>1)return{ok:!1,error:`Invalid FEN: too many ${e} kings`}}return Array.from(a[0]+a[7]).some(e=>e.toUpperCase()===`P`)?{ok:!1,error:`Invalid FEN: some pawns are on the edge rows`}:{ok:!0}}function getDisambiguator(e,t){let n=e.from,r=e.to,a=e.piece,o=0,c=0,l=0;for(let e=0,u=t.length;e<u;e++){let u=t[e].from,d=t[e].to;a===t[e].piece&&n!==u&&r===d&&(o++,rank(n)===rank(u)&&c++,file(n)===file(u)&&l++)}return o>0?c>0&&l>0?algebraic(n):l>0?algebraic(n).charAt(1):algebraic(n).charAt(0):``}function addMove(e,t,n,r,a,o=void 0,c=P.NORMAL){let l=rank(r);if(a===`p`&&(l===U||l===te))for(let l=0;l<H.length;l++){let u=H[l];e.push({color:t,from:n,to:r,piece:a,captured:o,promotion:u,flags:c|P.PROMOTION})}else e.push({color:t,from:n,to:r,piece:a,captured:o,flags:c})}function inferPieceType(e){let t=e.charAt(0);return t>=`a`&&t<=`h`?e.match(/[a-h]\d.*[a-h]\d/)?void 0:`p`:(t=t.toLowerCase(),t===`o`?`k`:t)}function strippedSan(e){return e.replace(/=/,``).replace(/[+#]?[?!]*$/,``)}function trimFen(e){return e.split(` `).slice(0,4).join(` `)}var Chess=class{_board=Array(128);_turn=`w`;_header={};_kings={w:j,b:j};_epSquare=-1;_halfMoves=0;_moveNumber=0;_history=[];_comments={};_castling={w:0,b:0};_positionCount={};constructor(e=A,{skipValidation:t=!1}={}){this.load(e,{skipValidation:t})}clear({preserveHeaders:e=!1}={}){this._board=Array(128),this._kings={w:j,b:j},this._turn=`w`,this._castling={w:0,b:0},this._epSquare=j,this._halfMoves=0,this._moveNumber=1,this._history=[],this._comments={},this._header=e?this._header:{},this._positionCount={},delete this._header.SetUp,delete this._header.FEN}load(e,{skipValidation:t=!1,preserveHeaders:n=!1}={}){let r=e.split(/\s+/);if(r.length>=2&&r.length<6&&(e=r.concat([`-`,`-`,`0`,`1`].slice(-(6-r.length))).join(` `)),r=e.split(/\s+/),!t){let{ok:t,error:n}=validateFen(e);if(!t)throw Error(n)}let a=r[0],o=0;this.clear({preserveHeaders:n});for(let e=0;e<a.length;e++){let t=a.charAt(e);if(t===`/`)o+=8;else if(isDigit(t))o+=parseInt(t,10);else{let e=t<`a`?`w`:`b`;this._put({type:t.toLowerCase(),color:e},algebraic(o)),o++}}this._turn=r[1],r[2].indexOf(`K`)>-1&&(this._castling.w|=P.KSIDE_CASTLE),r[2].indexOf(`Q`)>-1&&(this._castling.w|=P.QSIDE_CASTLE),r[2].indexOf(`k`)>-1&&(this._castling.b|=P.KSIDE_CASTLE),r[2].indexOf(`q`)>-1&&(this._castling.b|=P.QSIDE_CASTLE),this._epSquare=r[3]===`-`?j:F[r[3]],this._halfMoves=parseInt(r[4],10),this._moveNumber=parseInt(r[5],10),this._updateSetup(e),this._incPositionCount(e)}fen(){let e=0,t=``;for(let n=F.a8;n<=F.h1;n++){if(this._board[n]){e>0&&(t+=e,e=0);let{color:r,type:a}=this._board[n];t+=r===`w`?a.toUpperCase():a.toLowerCase()}else e++;n+1&136&&(e>0&&(t+=e),n!==F.h1&&(t+=`/`),e=0,n+=8)}let n=``;this._castling.w&P.KSIDE_CASTLE&&(n+=`K`),this._castling.w&P.QSIDE_CASTLE&&(n+=`Q`),this._castling.b&P.KSIDE_CASTLE&&(n+=`k`),this._castling.b&P.QSIDE_CASTLE&&(n+=`q`),n||=`-`;let r=`-`;if(this._epSquare!==j){let e=this._epSquare+(this._turn===`w`?16:-16),t=[e+1,e-1];for(let e of t){if(e&136)continue;let t=this._turn;if(this._board[e]?.color===t&&this._board[e]?.type===`p`){this._makeMove({color:t,from:e,to:this._epSquare,piece:`p`,captured:`p`,flags:P.EP_CAPTURE});let n=!this._isKingAttacked(t);if(this._undoMove(),n){r=algebraic(this._epSquare);break}}}}return[t,this._turn,n,r,this._halfMoves,this._moveNumber].join(` `)}_updateSetup(e){this._history.length>0||(e===`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1`?(delete this._header.SetUp,delete this._header.FEN):(this._header.SetUp=`1`,this._header.FEN=e))}reset(){this.load(A)}get(e){return this._board[F[e]]}put({type:e,color:t},n){return this._put({type:e,color:t},n)?(this._updateCastlingRights(),this._updateEnPassantSquare(),this._updateSetup(this.fen()),!0):!1}_put({type:e,color:t},n){if(V.indexOf(e.toLowerCase())===-1||!(n in F))return!1;let r=F[n];if(e==`k`&&!(this._kings[t]==j||this._kings[t]==r))return!1;let a=this._board[r];return a&&a.type===`k`&&(this._kings[a.color]=j),this._board[r]={type:e,color:t},e===`k`&&(this._kings[t]=r),!0}remove(e){let t=this.get(e);return delete this._board[F[e]],t&&t.type===`k`&&(this._kings[t.color]=j),this._updateCastlingRights(),this._updateEnPassantSquare(),this._updateSetup(this.fen()),t}_updateCastlingRights(){let e=this._board[F.e1]?.type===`k`&&this._board[F.e1]?.color===`w`,t=this._board[F.e8]?.type===`k`&&this._board[F.e8]?.color===`b`;(!e||this._board[F.a1]?.type!==`r`||this._board[F.a1]?.color!==`w`)&&(this._castling.w&=~P.QSIDE_CASTLE),(!e||this._board[F.h1]?.type!==`r`||this._board[F.h1]?.color!==`w`)&&(this._castling.w&=~P.KSIDE_CASTLE),(!t||this._board[F.a8]?.type!==`r`||this._board[F.a8]?.color!==`b`)&&(this._castling.b&=~P.QSIDE_CASTLE),(!t||this._board[F.h8]?.type!==`r`||this._board[F.h8]?.color!==`b`)&&(this._castling.b&=~P.KSIDE_CASTLE)}_updateEnPassantSquare(){if(this._epSquare===j)return;let e=this._epSquare+(this._turn===`w`?-16:16),t=this._epSquare+(this._turn===`w`?16:-16),n=[t+1,t-1];if(this._board[e]!==null||this._board[this._epSquare]!==null||this._board[t]?.color!==swapColor$1(this._turn)||this._board[t]?.type!==`p`){this._epSquare=j;return}let canCapture=e=>!(e&136)&&this._board[e]?.color===this._turn&&this._board[e]?.type===`p`;n.some(canCapture)||(this._epSquare=j)}_attacked(e,t,n){let r=[];for(let a=F.a8;a<=F.h1;a++){if(a&136){a+=7;continue}if(this._board[a]===void 0||this._board[a].color!==e)continue;let o=this._board[a],c=a-t;if(c===0)continue;let l=c+119;if(R[l]&B[o.type]){if(o.type===`p`){if(c>0&&o.color===`w`||c<=0&&o.color===`b`)if(n)r.push(algebraic(a));else return!0;continue}if(o.type===`n`||o.type===`k`)if(n){r.push(algebraic(a));continue}else return!0;let e=z[l],u=a+e,d=!1;for(;u!==t;){if(this._board[u]!=null){d=!0;break}u+=e}if(!d)if(n){r.push(algebraic(a));continue}else return!0}}return n?r:!1}attackers(e,t){return t?this._attacked(t,F[e],!0):this._attacked(this._turn,F[e],!0)}_isKingAttacked(e){let t=this._kings[e];return t===-1?!1:this._attacked(swapColor$1(e),t)}isAttacked(e,t){return this._attacked(t,F[e])}isCheck(){return this._isKingAttacked(this._turn)}inCheck(){return this.isCheck()}isCheckmate(){return this.isCheck()&&this._moves().length===0}isStalemate(){return!this.isCheck()&&this._moves().length===0}isInsufficientMaterial(){let e={b:0,n:0,r:0,q:0,k:0,p:0},t=[],n=0,r=0;for(let a=F.a8;a<=F.h1;a++){if(r=(r+1)%2,a&136){a+=7;continue}let o=this._board[a];o&&(e[o.type]=o.type in e?e[o.type]+1:1,o.type===`b`&&t.push(r),n++)}if(n===2||n===3&&(e.b===1||e.n===1))return!0;if(n===e.b+2){let e=0,n=t.length;for(let r=0;r<n;r++)e+=t[r];if(e===0||e===n)return!0}return!1}isThreefoldRepetition(){return this._getPositionCount(this.fen())>=3}isDrawByFiftyMoves(){return this._halfMoves>=100}isDraw(){return this.isDrawByFiftyMoves()||this.isStalemate()||this.isInsufficientMaterial()||this.isThreefoldRepetition()}isGameOver(){return this.isCheckmate()||this.isStalemate()||this.isDraw()}moves({verbose:e=!1,square:t=void 0,piece:n=void 0}={}){let r=this._moves({square:t,piece:n});return e?r.map(e=>new Move(this,e)):r.map(e=>this._moveToSan(e,r))}_moves({legal:e=!0,piece:t=void 0,square:n=void 0}={}){let r=n?n.toLowerCase():void 0,a=t?.toLowerCase(),o=[],c=this._turn,l=swapColor$1(c),u=F.a8,d=F.h1,p=!1;if(r)if(r in F)u=d=F[r],p=!0;else return[];for(let e=u;e<=d;e++){if(e&136){e+=7;continue}if(!this._board[e]||this._board[e].color===l)continue;let{type:t}=this._board[e],n;if(t===`p`){if(a&&a!==t)continue;n=e+I[c][0],this._board[n]||(addMove(o,c,e,n,`p`),n=e+I[c][1],ie[c]===rank(e)&&!this._board[n]&&addMove(o,c,e,n,`p`,void 0,P.BIG_PAWN));for(let t=2;t<4;t++)n=e+I[c][t],!(n&136)&&(this._board[n]?.color===l?addMove(o,c,e,n,`p`,this._board[n].type,P.CAPTURE):n===this._epSquare&&addMove(o,c,e,n,`p`,`p`,P.EP_CAPTURE))}else{if(a&&a!==t)continue;for(let r=0,a=L[t].length;r<a;r++){let a=L[t][r];for(n=e;n+=a,!(n&136);){if(!this._board[n])addMove(o,c,e,n,t);else{if(this._board[n].color===c)break;addMove(o,c,e,n,t,this._board[n].type,P.CAPTURE);break}if(t===`n`||t===`k`)break}}}}if((a===void 0||a===`k`)&&(!p||d===this._kings[c])){if(this._castling[c]&P.KSIDE_CASTLE){let e=this._kings[c],t=e+2;!this._board[e+1]&&!this._board[t]&&!this._attacked(l,this._kings[c])&&!this._attacked(l,e+1)&&!this._attacked(l,t)&&addMove(o,c,this._kings[c],t,`k`,void 0,P.KSIDE_CASTLE)}if(this._castling[c]&P.QSIDE_CASTLE){let e=this._kings[c],t=e-2;!this._board[e-1]&&!this._board[e-2]&&!this._board[e-3]&&!this._attacked(l,this._kings[c])&&!this._attacked(l,e-1)&&!this._attacked(l,t)&&addMove(o,c,this._kings[c],t,`k`,void 0,P.QSIDE_CASTLE)}}if(!e||this._kings[c]===-1)return o;let m=[];for(let e=0,t=o.length;e<t;e++)this._makeMove(o[e]),this._isKingAttacked(c)||m.push(o[e]),this._undoMove();return m}move(e,{strict:t=!1}={}){let n=null;if(typeof e==`string`)n=this._moveFromSan(e,t);else if(typeof e==`object`){let t=this._moves();for(let r=0,a=t.length;r<a;r++)if(e.from===algebraic(t[r].from)&&e.to===algebraic(t[r].to)&&(!(`promotion`in t[r])||e.promotion===t[r].promotion)){n=t[r];break}}if(!n)throw typeof e==`string`?Error(`Invalid move: ${e}`):Error(`Invalid move: ${JSON.stringify(e)}`);let r=new Move(this,n);return this._makeMove(n),this._incPositionCount(r.after),r}_push(e){this._history.push({move:e,kings:{b:this._kings.b,w:this._kings.w},turn:this._turn,castling:{b:this._castling.b,w:this._castling.w},epSquare:this._epSquare,halfMoves:this._halfMoves,moveNumber:this._moveNumber})}_makeMove(e){let t=this._turn,n=swapColor$1(t);if(this._push(e),this._board[e.to]=this._board[e.from],delete this._board[e.from],e.flags&P.EP_CAPTURE&&(this._turn===`b`?delete this._board[e.to-16]:delete this._board[e.to+16]),e.promotion&&(this._board[e.to]={type:e.promotion,color:t}),this._board[e.to].type===`k`){if(this._kings[t]=e.to,e.flags&P.KSIDE_CASTLE){let t=e.to-1,n=e.to+1;this._board[t]=this._board[n],delete this._board[n]}else if(e.flags&P.QSIDE_CASTLE){let t=e.to+1,n=e.to-2;this._board[t]=this._board[n],delete this._board[n]}this._castling[t]=0}if(this._castling[t]){for(let n=0,r=re[t].length;n<r;n++)if(e.from===re[t][n].square&&this._castling[t]&re[t][n].flag){this._castling[t]^=re[t][n].flag;break}}if(this._castling[n]){for(let t=0,r=re[n].length;t<r;t++)if(e.to===re[n][t].square&&this._castling[n]&re[n][t].flag){this._castling[n]^=re[n][t].flag;break}}e.flags&P.BIG_PAWN?t===`b`?this._epSquare=e.to-16:this._epSquare=e.to+16:this._epSquare=j,e.piece===`p`||e.flags&(P.CAPTURE|P.EP_CAPTURE)?this._halfMoves=0:this._halfMoves++,t===`b`&&this._moveNumber++,this._turn=n}undo(){let e=this._undoMove();if(e){let t=new Move(this,e);return this._decPositionCount(t.after),t}return null}_undoMove(){let e=this._history.pop();if(e===void 0)return null;let t=e.move;this._kings=e.kings,this._turn=e.turn,this._castling=e.castling,this._epSquare=e.epSquare,this._halfMoves=e.halfMoves,this._moveNumber=e.moveNumber;let n=this._turn,r=swapColor$1(n);if(this._board[t.from]=this._board[t.to],this._board[t.from].type=t.piece,delete this._board[t.to],t.captured)if(t.flags&P.EP_CAPTURE){let e;e=n===`b`?t.to-16:t.to+16,this._board[e]={type:`p`,color:r}}else this._board[t.to]={type:t.captured,color:r};if(t.flags&(P.KSIDE_CASTLE|P.QSIDE_CASTLE)){let e,n;t.flags&P.KSIDE_CASTLE?(e=t.to+1,n=t.to-1):(e=t.to-2,n=t.to+1),this._board[e]=this._board[n],delete this._board[n]}return t}pgn({newline:e=`
|
|
2
2
|
`,maxWidth:t=0}={}){let n=[],r=!1;for(let t in this._header)n.push(`[`+t+` "`+this._header[t]+`"]`+e),r=!0;r&&this._history.length&&n.push(e);let appendComment=e=>{let t=this._comments[this.fen()];if(t!==void 0){let n=e.length>0?` `:``;e=`${e}${n}{${t}}`}return e},a=[];for(;this._history.length>0;)a.push(this._undoMove());let o=[],c=``;for(a.length===0&&o.push(appendComment(``));a.length>0;){c=appendComment(c);let e=a.pop();if(!e)break;if(!this._history.length&&e.color===`b`){let e=`${this._moveNumber}. ...`;c=c?`${c} ${e}`:e}else e.color===`w`&&(c.length&&o.push(c),c=this._moveNumber+`.`);c=c+` `+this._moveToSan(e,this._moves({legal:!0})),this._makeMove(e)}if(c.length&&o.push(appendComment(c)),this._header.Result!==void 0&&o.push(this._header.Result),t===0)return n.join(``)+o.join(` `);let strip=function(){return n.length>0&&n[n.length-1]===` `?(n.pop(),!0):!1},wrapComment=function(r,a){for(let o of a.split(` `))if(o){if(r+o.length>t){for(;strip();)r--;n.push(e),r=0}n.push(o),r+=o.length,n.push(` `),r++}return strip()&&r--,r},l=0;for(let r=0;r<o.length;r++){if(l+o[r].length>t&&o[r].includes(`{`)){l=wrapComment(l,o[r]);continue}l+o[r].length>t&&r!==0?(n[n.length-1]===` `&&n.pop(),n.push(e),l=0):r!==0&&(n.push(` `),l++),n.push(o[r]),l+=o[r].length}return n.join(``)}header(...e){for(let t=0;t<e.length;t+=2)typeof e[t]==`string`&&typeof e[t+1]==`string`&&(this._header[e[t]]=e[t+1]);return this._header}setHeader(e,t){return this._header[e]=t,this._header}removeHeader(e){return e in this._header?(delete this._header[e],!0):!1}getHeaders(){return this._header}loadPgn(e,{strict:t=!1,newlineChar:n=`\r?
|
|
3
3
|
`}={}){function mask(e){return e.replace(/\\/g,`\\`)}function parsePgnHeader(e){let t={},r=e.split(new RegExp(mask(n))),a=``,o=``;for(let e=0;e<r.length;e++){let n=/^\s*\[\s*([A-Za-z]+)\s*"(.*)"\s*\]\s*$/;a=r[e].replace(n,`$1`),o=r[e].replace(n,`$2`),a.trim().length>0&&(t[a]=o)}return t}e=e.trim();let r=RegExp(`^(\\[((?:`+mask(n)+`)|.)*\\])((?:\\s*`+mask(n)+`){2}|(?:\\s*`+mask(n)+`)*$)`).exec(e),a=r&&r.length>=2?r[1]:``;this.reset();let o=parsePgnHeader(a),c=``;for(let e in o)e.toLowerCase()===`fen`&&(c=o[e]),this.header(e,o[e]);if(!t)c&&this.load(c,{preserveHeaders:!0});else if(o.SetUp===`1`){if(!(`FEN`in o))throw Error(`Invalid PGN: FEN tag must be supplied with SetUp tag`);this.load(o.FEN,{preserveHeaders:!0})}function toHex(e){return Array.from(e).map(function(e){return e.charCodeAt(0)<128?e.charCodeAt(0).toString(16):encodeURIComponent(e).replace(/%/g,``).toLowerCase()}).join(``)}function fromHex(e){return e.length==0?``:decodeURIComponent(`%`+(e.match(/.{1,2}/g)||[]).join(`%`))}let encodeComment=function(e){return e=e.replace(new RegExp(mask(n),`g`),` `),`{${toHex(e.slice(1,e.length-1))}}`},decodeComment=function(e){if(e.startsWith(`{`)&&e.endsWith(`}`))return fromHex(e.slice(1,e.length-1))},l=e.replace(a,``).replace(RegExp(`({[^}]*})+?|;([^${mask(n)}]*)`,`g`),function(e,t,n){return t===void 0?` `+encodeComment(`{${n.slice(1)}}`):encodeComment(t)}).replace(new RegExp(mask(n),`g`),` `),u=/(\([^()]+\))+?/g;for(;u.test(l);)l=l.replace(u,``);l=l.replace(/\d+\.(\.\.)?/g,``),l=l.replace(/\.\.\./g,``),l=l.replace(/\$\d+/g,``);let d=l.trim().split(new RegExp(/\s+/));d=d.filter(e=>e!==``);let p=``;for(let e=0;e<d.length;e++){let n=decodeComment(d[e]);if(n!==void 0){this._comments[this.fen()]=n;continue}let r=this._moveFromSan(d[e],t);if(r==null)if(G.indexOf(d[e])>-1)p=d[e];else throw Error(`Invalid move in PGN: ${d[e]}`);else p=``,this._makeMove(r),this._incPositionCount(this.fen())}p&&Object.keys(this._header).length&&!this._header.Result&&this.header(`Result`,p)}_moveToSan(e,t){let n=``;if(e.flags&P.KSIDE_CASTLE)n=`O-O`;else if(e.flags&P.QSIDE_CASTLE)n=`O-O-O`;else{if(e.piece!==`p`){let r=getDisambiguator(e,t);n+=e.piece.toUpperCase()+r}e.flags&(P.CAPTURE|P.EP_CAPTURE)&&(e.piece===`p`&&(n+=algebraic(e.from)[0]),n+=`x`),n+=algebraic(e.to),e.promotion&&(n+=`=`+e.promotion.toUpperCase())}return this._makeMove(e),this.isCheck()&&(this.isCheckmate()?n+=`#`:n+=`+`),this._undoMove(),n}_moveFromSan(e,t=!1){let n=strippedSan(e),r=inferPieceType(n),a=this._moves({legal:!0,piece:r});for(let e=0,t=a.length;e<t;e++)if(n===strippedSan(this._moveToSan(a[e],a)))return a[e];if(t)return null;let o,c,l,u,d,p=!1;if(c=n.match(/([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/),c?(o=c[1],l=c[2],u=c[3],d=c[4],l.length==1&&(p=!0)):(c=n.match(/([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnQRBN])?/),c&&(o=c[1],l=c[2],u=c[3],d=c[4],l.length==1&&(p=!0))),r=inferPieceType(n),a=this._moves({legal:!0,piece:o||r}),!u)return null;for(let e=0,t=a.length;e<t;e++)if(!l){if(n===strippedSan(this._moveToSan(a[e],a)).replace(`x`,``))return a[e]}else if((!o||o.toLowerCase()==a[e].piece)&&F[l]==a[e].from&&F[u]==a[e].to&&(!d||d.toLowerCase()==a[e].promotion))return a[e];else if(p){let t=algebraic(a[e].from);if((!o||o.toLowerCase()==a[e].piece)&&F[u]==a[e].to&&(l==t[0]||l==t[1])&&(!d||d.toLowerCase()==a[e].promotion))return a[e]}return null}ascii(){let e=` +------------------------+
|
|
4
4
|
`;for(let t=F.a8;t<=F.h1;t++){if(file(t)===0&&(e+=` `+`87654321`[rank(t)]+` |`),this._board[t]){let n=this._board[t].type,r=this._board[t].color===`w`?n.toUpperCase():n.toLowerCase();e+=` `+r+` `}else e+=` . `;t+1&136&&(e+=`|
|