pxt-core
Version:
Microsoft MakeCode provides Blocks / JavaScript / Python tools and editors
1 lines • 189 kB
JavaScript
var pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim,pxsim;!function(e){!function(t){let n,s=!1;function i(e){const t=window.navigator&&/Mac/i.test(window.navigator.platform)?e.metaKey:e.ctrlKey;return"Escape"===e.key?(e.preventDefault(),"escape"):"/"===e.key&&t?(e.preventDefault(),"togglekeyboardcontrolshelp"):"b"===e.key&&t?(e.preventDefault(),"toggleareamenu"):null}t.makeFocusable=function(e){e.setAttribute("focusable","true"),e.setAttribute("tabindex","0")},t.getGlobalAction=i,t.postKeyboardEvent=function(){s||(s=!0,document.addEventListener("keydown",(t=>{const n=i(t);if(n){const t={type:"action",action:n};e.Runtime.postMessage(t)}})))},t.enableKeyboardInteraction=function(e,t,n){t&&e.addEventListener("keydown",(e=>{const n="number"==typeof e.which?e.which:e.keyCode;32!==n&&13!==n||t()})),n&&e.addEventListener("keyup",(e=>{const t="number"==typeof e.which?e.which:e.keyCode;32!==t&&13!==t||n()}))},t.setAria=function(e,t,n){t&&!e.hasAttribute("role")&&e.setAttribute("role",t),n&&!e.hasAttribute("aria-label")&&e.setAttribute("aria-label",n)},t.setLiveContent=function(e){if(!n){let e="position: absolute !important;display: block;visibility: visible;overflow: hidden;width: 1px;height: 1px;margin: -1px;border: 0;padding: 0;clip: rect(0 0 0 0);";n=document.createElement("div"),n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.setAttribute("aria-hidden","false"),n.setAttribute("style",e),document.body.appendChild(n)}n.textContent!==e&&(n.textContent=e)}}(e.accessibility||(e.accessibility={}))}(pxsim||(pxsim={})),function(e){const t="blue",n="red",s="orange";const i=e=>(e=>e.reduce(((e,t)=>e+(t?1:0)),0))(e)>0;function r(e,t){let n={};for(let t in e)n[t]=e[t];for(let e in t)n[e]=t[e];return n}function o(t){e.U.assert(!!t,"Invalid pin: "+t);const n=/^(\w+)\.\s*(?:[a-z]*)?([A-Z][A-Z\d_]+)$/.exec(t);return n?n[2]:void 0}function a(e){return"-Z"===e.orientation&&"male"===e.style}e.readPin=o;class l{constructor(t){this.availablePowerPins={top:{fiveVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(26,51).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(26,51).map((e=>({type:"breadboard",row:"-",col:`${e}`})))},bottom:{fiveVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),threeVolt:e.mkRange(1,26).map((e=>({type:"breadboard",row:"+",col:`${e}`}))),ground:e.mkRange(1,26).map((e=>({type:"breadboard",row:"-",col:`${e}`})))}},this.opts=t}allocPartIRs(t,n,s){let i=[];const r=(t,n,i,r)=>{let o=[];for(let n=0;n<t.numberOfPins;n++){let r,a=t.pinDefinitions[n];if("string"==typeof a.target)r=a.target;else{let t=a.target.pinInstantiationIdx;if(!i||void 0===i[t])return void e.log(`error: parts no pin found for PinInstantiationIdx: ${t}. (Is the part missing an ArgumentRole or "trackArgs=" annotations?)`);r=i[t]}let l=t.visual.pinLocations[n],u=s.yOffset+l.y,c=Math.round(u/t.visual.pinDistance),h=u-c*t.visual.pinDistance,d=s.xOffset+l.x,p=Math.round(d/t.visual.pinDistance),m={partRelativeRowIdx:c,partRelativeColIdx:p,xOffset:d-p*t.visual.pinDistance,yOffset:h};o.push({def:a,loc:l,target:r,bbFit:m})}return{name:n,def:t,pins:o,partParams:r||{},bbFit:s}},a=t.instantiations||[];return t.instantiation&&a.push(t.instantiation),a.forEach((s=>{if("singleton"===s.kind)i.push(r(t,n));else if("function"===s.kind){let a=s,l=a.fullyQualifiedName.split(","),u={};l.forEach((e=>{this.opts.fnArgs[e]&&this.opts.fnArgs[e].forEach((e=>{u[e]=1}))}));let c=Object.keys(u);if(!c||!c.length)return void e.log(`error: parts failed to read pin(s) from callsite for: ${l}`);c.forEach((s=>{const u=s.split(",");if(u.length!=a.argumentRoles.length)return void e.log(`error: parts mismatch between number of arguments at callsite (function name: ${l}) vs number of argument roles in part definition (part: ${n}).`);let c=[],h={};u.forEach(((e,t)=>{let n=a.argumentRoles[t];if(void 0!==n.partParameter&&(h[n.partParameter]=e),void 0!==n.pinInstantiationIdx){let t=n.pinInstantiationIdx,s=o(e);c[t]=s}})),i.push(r(t,n,c,h))}))}})),i.filter((e=>!!e))}computePartDimensions(t,n){let s=t.visual.pinLocations,i=t.pinDefinitions,o=t.numberOfPins;e.U.assert(s.length===o,`Mismatch between "numberOfPins" and length of "visual.pinLocations" for "${n}"`),e.U.assert(i.length===o,`Mismatch between "numberOfPins" and length of "pinDefinitions" for "${n}"`),e.U.assert(o>0,`Part "${n}" has no pins`);let a,l,u,c,h=s.map(((e,t)=>{return n={idx:t},s=e,o=i[t],r(r(n,s),o);var n,s,o})).filter((e=>"-Z"===e.orientation)),d=h.length>0,p=t.visual.pinDistance;if(d){let e=h[0],n=Math.ceil(e.x/p),s=Math.ceil(e.y/p);a=n*p-e.x,l=s*p-e.y,u=Math.ceil((a+t.visual.width)/p)+1,c=Math.ceil((l+t.visual.height)/p)+1}else u=Math.ceil(t.visual.width/p),c=Math.ceil(t.visual.height/p),a=u*p-t.visual.width,l=c*p-t.visual.height;return{xOffset:a,yOffset:l,rowCount:c,colCount:u}}allocColumns(t){let n=t.length;let s=e.visuals.BREADBOARD_MID_COLS-t.map((e=>e.colCount)).reduce(((e,t)=>e+t),0);s<=0&&e.log("Not enough breadboard space!");let i=Math.floor(s/(n-1+2)),r=s-i*(n-1),o=Math.floor(r/2),a=(Math.ceil(r/2),1+o);return t.map((e=>{let t=a;return a+=e.colCount+i,t}))}placeParts(t){const n=e.visuals.BREADBOARD_MID_ROWS+2;let s=this.allocColumns(t.map((e=>e.bbFit))),i=t.map((e=>{let t=n-e.bbFit.rowCount,s=Math.floor(t/2);return s>4&&(s=4),s<1&&(s=1),s}));return t.map(((e,t)=>{let n=i[t];return r({startColumnIdx:s[t],startRowIdx:n},e)}))}nextColor(){return(!this.availableWireColors||this.availableWireColors.length<=0)&&(this.availableWireColors=e.visuals.GPIO_WIRE_COLORS.map((e=>e))),this.availableWireColors.pop()}allocWireIRs(i){let o=[],l=i.pins.map(((r,l)=>{let u,c,h=r.target,d=i.startColumnIdx+r.bbFit.partRelativeColIdx,p=e.visuals.getColumnName(d),m=i.startRowIdx+r.bbFit.partRelativeRowIdx;if(m>=7&&(m-=2),a(r.def)){u={type:"breadboard",row:m<5?"j":"a",col:p,style:r.def.style}}else{u={type:"breadboard",row:e.visuals.getRowName(m),col:p,xOffset:r.bbFit.xOffset/i.def.visual.pinDistance,yOffset:r.bbFit.yOffset/i.def.visual.pinDistance,style:r.def.style}}return c="ground"===h?t:"threeVolt"===h?n:"fiveVolt"===h?s:"number"==typeof r.def.colorGroup?o[r.def.colorGroup]?o[r.def.colorGroup]:o[r.def.colorGroup]=this.nextColor():this.nextColor(),{start:u,end:h,color:c,pinIdx:l}}));return r(i,{wires:l})}allocLocation(t,n){if("ground"===t||"threeVolt"===t||"fiveVolt"==t){if("ground"===t&&this.powerUsage.singleGround){return{type:"dalboard",pin:this.getBoardGroundPin()}}if("threeVolt"===t&&this.powerUsage.singleThreeVolt){return{type:"dalboard",pin:this.getBoardThreeVoltPin()}}if("fiveVolt"===t&&this.powerUsage.singleFiveVolt){return{type:"dalboard",pin:this.getBoardFiveVoltPin()}}e.U.assert(!!n.referenceBBPin);let s=this.opts.getBBCoord(n.referenceBBPin),i=[this.availablePowerPins.top.ground[0]||this.availablePowerPins.top.threeVolt[0],this.availablePowerPins.bottom.ground[0]||this.availablePowerPins.bottom.threeVolt[0]].map((e=>this.opts.getBBCoord(e)));i[0]&&i[1]||e.debug(`No more available "${t}" locations!`);let r,o=0==e.visuals.findClosestCoordIdx(s,i);o?"ground"===t?r=this.availablePowerPins.top.ground:"threeVolt"===t?r=this.availablePowerPins.top.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.top.fiveVolt):"ground"===t?r=this.availablePowerPins.bottom.ground:"threeVolt"===t?r=this.availablePowerPins.bottom.threeVolt:"fiveVolt"===t&&(r=this.availablePowerPins.bottom.fiveVolt);let a=r.map((e=>this.opts.getBBCoord(e))),l=e.visuals.findClosestCoordIdx(s,a),u=r[l];return o?(this.availablePowerPins.top.ground.splice(l,1),this.availablePowerPins.top.threeVolt.splice(l,1)):(this.availablePowerPins.bottom.ground.splice(l,1),this.availablePowerPins.bottom.threeVolt.splice(l,1)),u}if("breadboard"===t.type)return t;if("MOSI"===t||"MISO"===t||"SCK"===t){return this.opts.boardDef.spiPins||e.debug("No SPI pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.spiPins[t]}}if("SDA"===t||"SCL"===t){return this.opts.boardDef.i2cPins||e.debug("No I2C pin mappings found!"),{type:"dalboard",pin:this.opts.boardDef.i2cPins[t]}}{e.U.assert("string"==typeof t,"Unknown location type: "+t);let n=t,s=this.opts.boardDef.gpioPinMap[n]||n;return s?{type:"dalboard",pin:s}:void e.debug(`unknown pin location for ${n}`)}}getBoardGroundPin(){let t=this.opts.boardDef.groundPins&&this.opts.boardDef.groundPins[0]||null;return t||e.debug("No available ground pin on board!"),t}getBoardThreeVoltPin(){let t=this.opts.boardDef.threeVoltPins&&this.opts.boardDef.threeVoltPins[0]||null;return t||e.debug("No available 3.3V pin on board!"),t}getBoardFiveVoltPin(){let t=this.opts.boardDef.fiveVoltPins&&this.opts.boardDef.fiveVoltPins[0]||null;return t||e.debug("No available 5V pin on board!"),t}allocPowerWires(e){let i=this.getBoardGroundPin(),r=this.getBoardThreeVoltPin(),o=this.getBoardFiveVoltPin();const a={type:"breadboard",row:"-",col:"26"},l={type:"breadboard",row:"-",col:"1"},u={type:"breadboard",row:"-",col:"50"},c={type:"breadboard",row:"-",col:"25"};let h,d;this.opts.boardDef.attachPowerOnRight?(h=u,d=c):(h=a,d=l);let p=[],m=[],f=[];e.bottomGround&&e.topGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:this.allocLocation("ground",{referenceBBPin:d}),color:t}),e.topGround?p.push({start:this.allocLocation("ground",{referenceBBPin:h}),end:{type:"dalboard",pin:i},color:t}):e.bottomGround&&p.push({start:this.allocLocation("ground",{referenceBBPin:d}),end:{type:"dalboard",pin:i},color:t}),e.bottomThreeVolt&&e.bottomGround?m.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:this.allocLocation("threeVolt",{referenceBBPin:d}),color:n}):e.bottomFiveVolt&&e.bottomGround&&f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:this.allocLocation("fiveVolt",{referenceBBPin:d}),color:s}),e.topThreeVolt?m.push({start:this.allocLocation("threeVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:r},color:n}):e.bottomThreeVolt&&m.push({start:this.allocLocation("threeVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:r},color:s}),e.topFiveVolt&&!e.topThreeVolt?f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:h}),end:{type:"dalboard",pin:o},color:n}):e.bottomFiveVolt&&!e.bottomThreeVolt&&f.push({start:this.allocLocation("fiveVolt",{referenceBBPin:d}),end:{type:"dalboard",pin:o},color:s});let g=[];p.length>0&&g.push({wireIndices:p.map(((e,t)=>t))});let b=p.length;return m.length>0&&g.push({wireIndices:m.map(((e,t)=>t+b))}),f.length>0&&g.push({wireIndices:m.map(((e,t)=>t+b+m.length))}),{wires:p.concat(m).concat(f),assembly:g}}allocWire(e){const t=[e.start,e.end],n=t.map((e=>"ground"===e||"threeVolt"===e||"fiveVolt"===e));let s=t.map(((e,t)=>n[t]?void 0:this.allocLocation(e,{})));if(s=s.map(((e,n)=>{if(e)return e;const i=s[1-n];return this.allocLocation(t[n],{referenceBBPin:i})})),s[0]&&s[1])return{start:s[0],end:s[1],color:e.color}}allocPart(t){let n=t.pins.filter((e=>a(e.def))).map((n=>{let s=t.startRowIdx+n.bbFit.partRelativeRowIdx;s>=7&&(s-=2);let i=e.visuals.getRowName(s),r=t.startColumnIdx+n.bbFit.partRelativeColIdx;return{type:"breadboard",row:i,col:e.visuals.getColumnName(r)}}));return{name:t.name,visual:t.def.visual,bbFit:t.bbFit,startColumnIdx:t.startColumnIdx,startRowIdx:t.startRowIdx,breadboardConnections:n,params:t.partParams,simulationBehavior:t.def.simulationBehavior}}allocAll(){let e=this.opts.partsList.map((e=>({name:e,def:this.opts.partDefs[e]}))).filter((e=>!!e.def));if(e.length>0){let t=e.map((e=>this.computePartDimensions(e.def,e.name))),n=[];e.forEach(((e,s)=>{let i=t[s],r=this.allocPartIRs(e.def,e.name,i);n=n.concat(r)}));const s=this.placeParts(n).map((e=>this.allocWireIRs(e))),r=s.map((e=>e.wires)).reduce(((e,t)=>e.concat(t)),[]).map((e=>function(e){let t=[e.start,e.end],n=t.map((e=>"ground"===e)),s=t.map((e=>"threeVolt"===e)),r=t.map((e=>"fiveVolt"===e)),o=t.map((e=>function(e){let t=!1;if("string"!=typeof e&&"breadboard"===e.type){let n=e.row;t=0<=["a","b","c","d","e"].indexOf(n)}return t}(e))),a=i(n),l=i(s),u=i(r),c=i(o);return{topGround:a&&!c,topThreeVolt:l&&!c,topFiveVolt:u&&!c,bottomGround:a&&c,bottomThreeVolt:l&&c,bottomFiveVolt:u&&c,singleGround:a,singleThreeVolt:l,singleFiveVolt:u}}(e)));this.powerUsage=function(e){const t=e.reduce(((e,t)=>({topGround:e.topGround||t.topGround,topThreeVolt:e.topThreeVolt||t.topThreeVolt,topFiveVolt:e.topFiveVolt||t.topFiveVolt,bottomGround:e.bottomGround||t.bottomGround,bottomThreeVolt:e.bottomThreeVolt||t.bottomThreeVolt,bottomFiveVolt:e.bottomFiveVolt||t.bottomFiveVolt,singleGround:t.singleGround?null===e.singleGround:e.singleGround,singleThreeVolt:t.singleThreeVolt?null===e.singleThreeVolt:e.singleThreeVolt,singleFiveVolt:t.singleFiveVolt?null===e.singleFiveVolt:e.singleFiveVolt})),{topGround:!1,topThreeVolt:!1,topFiveVolt:!1,bottomGround:!1,bottomThreeVolt:!1,bottomFiveVolt:!1,singleGround:null,singleThreeVolt:null,singleFiveVolt:null});return t.singleGround&&(t.topGround=t.bottomGround=!1),t.singleThreeVolt&&(t.topThreeVolt=t.bottomThreeVolt=!1),t.singleFiveVolt&&(t.topFiveVolt=t.bottomFiveVolt=!1),t}(r);const o=this.allocPowerWires(this.powerUsage),a=s.map(((e,t)=>{const n=this.allocPart(e),s=e.wires.map((e=>this.allocWire(e)));if(s.some((e=>!e)))return;const i=[];e.wires.forEach(((e,t)=>{i[e.pinIdx]=t}));return{part:n,wires:s,assembly:e.def.assembly.map((e=>({part:e.part,wireIndices:(e.pinIndices||[]).map((e=>i[e]))})))}})).filter((e=>!!e)),l=[o].concat(a).filter((e=>e.assembly&&e.assembly.length)),u=!l.some((e=>e.part&&e.part.breadboardConnections&&e.part.breadboardConnections.length>0||e.wires&&e.wires.some((e=>"breadboard"==e.end.type&&"croc"!=e.end.style||"breadboard"==e.start.type&&"croc"!=e.start.style))));return{partsAndWires:l,wires:[],parts:[],hideBreadboard:u}}return{partsAndWires:[],wires:[],parts:[]}}}e.allocateDefinitions=function(e){return new l(e).allocAll()}}(pxsim||(pxsim={})),function(e){!function(t){class n{constructor(e){this.seq=0,this.type=e}}t.Message=n;t.Response=class extends n{constructor(e,t){super("response"),this.request_seq=e.seq,this.command=e.command,t?(this.success=!1,this.message=t):this.success=!0}};class s extends n{constructor(e,t){super("event"),this.event=e,t&&(this.body=t)}}t.Event=s;t.Source=class{constructor(e,t,n=0,s,i){this.name=e,this.path=t,this.sourceReference=n,s&&(this.origin=s),i&&(this.adapterData=i)}};t.Scope=class{constructor(e,t,n=!1){this.name=e,this.variablesReference=t,this.expensive=n}};t.StackFrame=class{constructor(e,t,n,s=0,i=0){this.id=e,this.source=n,this.line=s,this.column=i,this.name=t}};t.Thread=class{constructor(e,t){this.id=e,this.name=t||"Thread #"+e}};t.Variable=class{constructor(e,t,n=0,s,i){this.name=e,this.value=t,this.variablesReference=n,"number"==typeof i&&(this.namedVariables=i),"number"==typeof s&&(this.indexedVariables=s)}};t.Breakpoint=class{constructor(e,t,n,s){this.verified=e;const i=this;"number"==typeof t&&(i.line=t),"number"==typeof n&&(i.column=n),s&&(i.source=s)}};t.Module=class{constructor(e,t){this.id=e,this.name=t}};t.CompletionItem=class{constructor(e,t,n=0){this.label=e,this.start=t,this.length=n}};t.StoppedEvent=class extends s{constructor(e,t,n=null){if(super("stopped"),this.body={reason:e,threadId:t},n){this.body.text=n}}};t.ContinuedEvent=class extends s{constructor(e,t){super("continued"),this.body={threadId:e},"boolean"==typeof t&&(this.body.allThreadsContinued=t)}};t.InitializedEvent=class extends s{constructor(){super("initialized")}};t.TerminatedEvent=class extends s{constructor(e){if(super("terminated"),"boolean"==typeof e){this.body={restart:e}}}};t.OutputEvent=class extends s{constructor(e,t="console",n){super("output"),this.body={category:t,output:e},void 0!==n&&(this.body.data=n)}};t.ThreadEvent=class extends s{constructor(e,t){super("thread"),this.body={reason:e,threadId:t}}};t.BreakpointEvent=class extends s{constructor(e,t){super("breakpoint"),this.body={reason:e,breakpoint:t}}};t.ModuleEvent=class extends s{constructor(e,t){super("module"),this.body={reason:e,module:t}}};class i{constructor(){this._pendingRequests={}}start(e){this._sequence=1,this.host=e,this.host.onData((e=>{if("request"===e.type)this.dispatchRequest(e);else if("response"===e.type){const t=e,n=this._pendingRequests[t.seq];n&&(delete this._pendingRequests[t.seq],n(t))}}))}stop(){this.host&&this.host.close()}sendEvent(e){this.send("event",e)}sendResponse(t){t.seq>0?e.error(`attempt to send more than one response for command ${t.command}`):this.send("response",t)}sendRequest(e,n,s,i){const r={command:e};if(n&&Object.keys(n).length>0&&(r.arguments=n),this.send("request",r),i){this._pendingRequests[r.seq]=i;const e=setTimeout((()=>{clearTimeout(e);const n=this._pendingRequests[r.seq];n&&(delete this._pendingRequests[r.seq],n(new t.Response(r,"timeout")))}),s)}}send(e,t){if(t.type=e,t.seq=this._sequence++,this.host){const e=JSON.stringify(t);this.host.send(e)}}dispatchRequest(e){}}t.ProtocolServer=i;class r extends i{constructor(){super(...arguments),this._debuggerLinesStartAt1=!1,this._debuggerColumnsStartAt1=!1,this._clientLinesStartAt1=!0,this._clientColumnsStartAt1=!0}shutdown(){}dispatchRequest(e){const n=new t.Response(e);try{if("initialize"===e.command){let t=e.arguments;if("boolean"==typeof t.linesStartAt1&&(this._clientLinesStartAt1=t.linesStartAt1),"boolean"==typeof t.columnsStartAt1&&(this._clientColumnsStartAt1=t.columnsStartAt1),"path"!==t.pathFormat)this.sendErrorResponse(n,2018,"debug adapter only supports native paths",null);else{const e=n;e.body={},this.initializeRequest(e,t)}}else"launch"===e.command?this.launchRequest(n,e.arguments):"attach"===e.command?this.attachRequest(n,e.arguments):"disconnect"===e.command?this.disconnectRequest(n,e.arguments):"setBreakpoints"===e.command?this.setBreakPointsRequest(n,e.arguments):"setFunctionBreakpoints"===e.command?this.setFunctionBreakPointsRequest(n,e.arguments):"setExceptionBreakpoints"===e.command?this.setExceptionBreakPointsRequest(n,e.arguments):"configurationDone"===e.command?this.configurationDoneRequest(n,e.arguments):"continue"===e.command?this.continueRequest(n,e.arguments):"next"===e.command?this.nextRequest(n,e.arguments):"stepIn"===e.command?this.stepInRequest(n,e.arguments):"stepOut"===e.command?this.stepOutRequest(n,e.arguments):"stepBack"===e.command?this.stepBackRequest(n,e.arguments):"restartFrame"===e.command?this.restartFrameRequest(n,e.arguments):"goto"===e.command?this.gotoRequest(n,e.arguments):"pause"===e.command?this.pauseRequest(n,e.arguments):"stackTrace"===e.command?this.stackTraceRequest(n,e.arguments):"scopes"===e.command?this.scopesRequest(n,e.arguments):"variables"===e.command?this.variablesRequest(n,e.arguments):"setVariable"===e.command?this.setVariableRequest(n,e.arguments):"source"===e.command?this.sourceRequest(n,e.arguments):"threads"===e.command?this.threadsRequest(n):"evaluate"===e.command?this.evaluateRequest(n,e.arguments):"stepInTargets"===e.command?this.stepInTargetsRequest(n,e.arguments):"gotoTargets"===e.command?this.gotoTargetsRequest(n,e.arguments):"completions"===e.command?this.completionsRequest(n,e.arguments):this.customRequest(e.command,n,e.arguments)}catch(e){this.sendErrorResponse(n,1104,"{_stack}",{_exception:e.message,_stack:e.stack})}}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsConfigurationDoneRequest=!0,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(e,t){this.sendResponse(e)}attachRequest(e,t){this.sendResponse(e)}setBreakPointsRequest(e,t){this.sendResponse(e)}setFunctionBreakPointsRequest(e,t){this.sendResponse(e)}setExceptionBreakPointsRequest(e,t){this.sendResponse(e)}configurationDoneRequest(e,t){this.sendResponse(e)}continueRequest(e,t){this.sendResponse(e)}nextRequest(e,t){this.sendResponse(e)}stepInRequest(e,t){this.sendResponse(e)}stepOutRequest(e,t){this.sendResponse(e)}stepBackRequest(e,t){this.sendResponse(e)}restartFrameRequest(e,t){this.sendResponse(e)}gotoRequest(e,t){this.sendResponse(e)}pauseRequest(e,t){this.sendResponse(e)}sourceRequest(e,t){this.sendResponse(e)}threadsRequest(e){this.sendResponse(e)}stackTraceRequest(e,t){this.sendResponse(e)}scopesRequest(e,t){this.sendResponse(e)}variablesRequest(e,t){this.sendResponse(e)}setVariableRequest(e,t){this.sendResponse(e)}evaluateRequest(e,t){this.sendResponse(e)}stepInTargetsRequest(e,t){this.sendResponse(e)}gotoTargetsRequest(e,t){this.sendResponse(e)}completionsRequest(e,t){this.sendResponse(e)}customRequest(e,t,n){this.sendErrorResponse(t,1014,"unrecognized request",null)}sendErrorResponse(e,t,n,s){let i;"number"==typeof t?(i={id:t,format:n},s&&(i.variables=s),i.showUser=!0):i=t,e.success=!1,r.formatPII(i.format,!0,i.variables),e.body||(e.body={}),e.body.error=i,this.sendResponse(e)}convertClientLineToDebugger(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e+1:this._clientLinesStartAt1?e-1:e}convertDebuggerLineToClient(e){return this._debuggerLinesStartAt1?this._clientLinesStartAt1?e:e-1:this._clientLinesStartAt1?e+1:e}convertClientColumnToDebugger(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e+1:this._clientColumnsStartAt1?e-1:e}convertDebuggerColumnToClient(e){return this._debuggerColumnsStartAt1?this._clientColumnsStartAt1?e:e-1:this._clientColumnsStartAt1?e+1:e}convertClientPathToDebugger(e){return this._clientPathsAreURIs!=this._debuggerPathsAreURIs?this._clientPathsAreURIs?r.uri2path(e):r.path2uri(e):e}convertDebuggerPathToClient(e){return this._debuggerPathsAreURIs!=this._clientPathsAreURIs?this._debuggerPathsAreURIs?r.uri2path(e):r.path2uri(e):e}static path2uri(e){let t=e.replace(/\\/g,"/");return"/"!==t[0]&&(t="/"+t),encodeURI("file://"+t)}static uri2path(e){return e}static formatPII(e,t,n){return e.replace(r._formatPIIRegexp,(function(e,s){return t&&s.length>0&&"_"!==s[0]?e:n[s]&&n.hasOwnProperty(s)?n[s]:e}))}}r._formatPIIRegexp=/{([^}]+)}/g,t.DebugSession=r}(e.protocol||(e.protocol={}))}(pxsim||(pxsim={})),function(e){!function(e){e.injectPolyphils=function(){String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(e,t){return void 0!==e&&null!=e&&(t=!t||t<0?0:+t,this.substring(t,t+e.length)===e)}}),Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError("this is null or not defined");let t=Object(this),n=t.length>>>0,s=arguments[1],i=s>>0,r=i<0?Math.max(n+i,0):Math.min(i,n),o=arguments[2],a=void 0===o?n:o>>0,l=a<0?Math.max(n+a,0):Math.min(a,n);for(;r<l;)t[r]=e,r++;return t}}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{writable:!0,enumerable:!0,value:function(e){if(null==this)throw new TypeError('"this" is null or not defined');let t=Object(this);const n=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");const s=arguments[1];let i=0;for(;i<n;){const n=t[i];if(e.call(s,n,i,t))return n;i++}}}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint16Array.prototype.slice||Object.defineProperty(Uint16Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint32Array.prototype.slice||Object.defineProperty(Uint32Array.prototype,"slice",{value:Array.prototype.slice,writable:!0,enumerable:!0}),Uint8Array.prototype.fill||Object.defineProperty(Uint8Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint16Array.prototype.fill||Object.defineProperty(Uint16Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint32Array.prototype.fill||Object.defineProperty(Uint32Array.prototype,"fill",{value:Array.prototype.fill,writable:!0,enumerable:!0}),Uint8Array.prototype.some||Object.defineProperty(Uint8Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint16Array.prototype.some||Object.defineProperty(Uint16Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint32Array.prototype.some||Object.defineProperty(Uint32Array.prototype,"some",{value:Array.prototype.some,writable:!0,enumerable:!0}),Uint8Array.prototype.reverse||Object.defineProperty(Uint8Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint16Array.prototype.reverse||Object.defineProperty(Uint16Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Uint32Array.prototype.reverse||Object.defineProperty(Uint32Array.prototype,"reverse",{value:Array.prototype.reverse,writable:!0,enumerable:!0}),Math.imul||(Math.imul=function(e,t){const n=65535&e,s=65535&t;return n*s+((e>>>16&65535)*s+n*(t>>>16&65535)<<16>>>0)|0}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){"use strict";if(null==e)throw new TypeError("Cannot convert undefined or null to object");let n=Object(e);for(let e=1;e<arguments.length;e++){let t=arguments[e];if(null!=t)for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])}return n},writable:!0,configurable:!0}),Promise.prototype.finally||(Promise.prototype.finally=Promise.prototype.finally||{finally(e){const t=t=>Promise.resolve(e()).then(t);return this.then((e=>t((()=>e))),(e=>t((()=>Promise.reject(e)))))}}.finally)};function t(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():e&&"."!==e&&t.push(e)})),t}e.Lazy=class{constructor(e){this._func=e,this._evaluated=!1}get value(){return this._evaluated||(this._value=this._func(),this._evaluated=!0),this._value}},e.getNormalizedParts=t,e.normalizePath=function(e){return t(e).join("/")},e.relativePath=function(e,n){const s=t(e),i=t(n);let r=0;for(;s[r]===i[r]&&(r++,r!==s.length&&r!==i.length););const o=s.slice(r),a=i.slice(r);for(let e=0;e<o.length;e++)a.unshift("..");return a.join("/")},e.pathJoin=function(...e){let t="";return e.forEach((e=>{e.replace(/\\/g,"/"),e.lastIndexOf("/")===e.length-1&&(e=e.slice(0,e.length-1)),t+="/"+e})),t},e.toArray=function(e){if(Array.isArray(e))return e;let t=[];for(let n=0;n<e.length;++n)t.push(e[n]);return t}}(e.util||(e.util={}))}(pxsim||(pxsim={})),function(e){e.getWarningMessage=function(t){let n={type:"debugger",subtype:"warning",breakpointIds:[],message:t},s=e.runtime.currFrame;for(;null!=s;)n.breakpointIds.push(s.lastBrkId),s=s.parent;return n};function t(t,n){switch(typeof t){case"string":case"number":case"boolean":return t;case"function":return{text:"(function)",type:"function"};case"undefined":return null;case"object":if(!t)return null;if(t instanceof e.RefObject){n&&(n[t.id]=t);let s=e.RefObject.toDebugString(t),i=s.startsWith("[")?"array":s;return{id:t.id,preview:s,hasFields:null!==t.fields||s.startsWith("["),type:i}}return t._width&&t._height?{text:t._width+"x"+t._height,type:"image"}:{text:"(object)",type:"object"};default:throw new Error}}function n(n,i,r,o,a=!1){return function(n,r){const l={};for(let e of Object.keys(n))/^__/.test(e)||!/___\d+$/.test(e)||o&&-1===o.indexOf(e)||(l[e]=t(n[e],i));if(n.fields&&r)for(let e of r)e=e.substring(e.lastIndexOf(".")+1),l[e]=t(s(n.vtable.iface[e],n),i);if(n.fields)for(let e of Object.keys(n.fields).filter((e=>a||!e.startsWith("_"))))l[e]=t(n.fields[e],i);else if(n instanceof e.RefMap)for(const e of n.data)l[e.key]=t(e.val,i);else Array.isArray(n.data)?n.data.forEach(((e,n)=>{l[n]=t(e,i)})):void 0!==n._width&&void 0!==n._height&&(l.width=n._width,l.height=n._height,a&&void 0!==n._bpp&&(l.isMono=1===n._bpp));return l}(n,r)}function s(e,t){let n={pc:0,arg0:t,fn:e,parent:{}};for(;n.fn;)n=n.fn(n);return n.retval}function i(e,s){let i=e.fn?e.fn.info:null;if(i){let r={thisParam:t(e.argL,s),params:[]};if(i.argumentNames){const n=i.argumentNames;r.params=n.map(((n,i)=>({name:n,value:t(e["arg"+i],s)})))}return{locals:n(e,s),funcInfo:i,breakpointId:e.lastBrkId,callLocationId:e.callLocIdx,arguments:r}}}e.BreakpointMap=class{constructor(e){this.fileMap={},this.idMap={},e.forEach((e=>{const[t,n]=e;this.fileMap[n.source.path]||(this.fileMap[n.source.path]=[]),this.fileMap[n.source.path].push(e),this.idMap[t]=n}));for(const e in this.fileMap){const t=this.fileMap[e];this.fileMap[e]=t.sort((([,e],[,t])=>e.line===t.line?t.endLine===e.endLine?e.column-t.column:t.endLine-e.endLine:e.line-t.line))}}getById(e){return this.idMap[e]}verifyBreakpoint(e,t){const n=this.fileMap[e];let s;if(n)for(const[e,i]of n)i.line<=t.line&&i.endLine>=t.line&&(s=[e,i]);return s?(s[1].verified=!0,s):[-1,{verified:!1}]}},e.dumpHeap=n,e.injectEnvironmentGlobals=function(n,s){const i=e.runtime.environmentGlobals;if(!Object.keys(i).length)return;const r=n.environmentGlobals={};Object.keys(i).forEach((n=>r[n]=t(e.runtime.environmentGlobals[n],s)))},e.getBreakpointMsg=function(t,s,r){const o={},a={type:"debugger",subtype:"breakpoint",breakpointId:s,globals:n(e.runtime.globals,o,void 0,r),stackframes:[]};for(;null!=t;){let e=i(t,o);e&&a.stackframes.push(e),t=t.parent}return{msg:a,heap:o}};class r extends e.protocol.DebugSession{constructor(t){super();let n={onDebuggerBreakpoint:e=>this.onDebuggerBreakpoint(e),onDebuggerWarning:e=>this.onDebuggerWarning(e),onDebuggerResume:()=>this.onDebuggerResume(),onStateChanged:e=>this.onStateChanged(e)};this.driver=new e.SimulatorDriver(t,n)}runCode(t,n,s,i,r){this.breakpoints=i,this.projectDir&&this.fixBreakpoints(),this.sendEvent(new e.protocol.InitializedEvent),this.driver.run(t,{parts:n,fnArgs:s,boardDefinition:r})}stopSimulator(e=!1){this.driver.stop(e)}initializeRequest(e,t){e.body.supportsConditionalBreakpoints=!1,e.body.supportsHitConditionalBreakpoints=!1,e.body.supportsFunctionBreakpoints=!1,e.body.supportsEvaluateForHovers=!1,e.body.supportsStepBack=!1,e.body.supportsSetVariable=!1,e.body.supportsRestartFrame=!1,e.body.supportsStepInTargetsRequest=!1,e.body.supportsGotoTargetsRequest=!1,e.body.supportsCompletionsRequest=!1,e.body.supportsConfigurationDoneRequest=!0,this.sendResponse(e)}disconnectRequest(e,t){this.sendResponse(e),this.shutdown()}launchRequest(t,n){this.projectDir||(this.projectDir=e.util.normalizePath(n.projectDir),this.breakpoints&&this.fixBreakpoints()),this.sendResponse(t)}setBreakPointsRequest(t,n){t.body={breakpoints:[]};const s=[];n.breakpoints.forEach((i=>{if(this.breakpoints){const[r,o]=this.breakpoints.verifyBreakpoint(e.util.relativePath(this.projectDir,n.source.path),i);t.body.breakpoints.push(o),o.verified&&s.push(r)}else t.body.breakpoints.push({verified:!1})})),this.driver.setBreakpoints(s),this.sendResponse(t)}continueRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Resume),this.sendResponse(t)}nextRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOver),this.sendResponse(t)}stepInRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepInto),this.sendResponse(t)}stepOutRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.StepOut),this.sendResponse(t)}pauseRequest(t,n){this.driver.resume(e.SimulatorDebuggerCommand.Pause),this.sendResponse(t)}threadsRequest(e){e.body={threads:[{id:r.THREAD_ID,name:"main"}]},this.sendResponse(e)}stackTraceRequest(e,t){if(this.lastBreak){const t=this.state.getFrames();e.body={stackFrames:t}}this.sendResponse(e)}scopesRequest(e,t){this.state&&(e.body={scopes:this.state.getScopes(t.frameId)}),this.sendResponse(e)}variablesRequest(e,t){this.state&&(e.body={variables:this.state.getVariables(t.variablesReference)}),this.sendResponse(e)}onDebuggerBreakpoint(t){if(this.lastBreak=t,this.state=new o(this.lastBreak,this.breakpoints,this.projectDir),t.exceptionMessage){const n=t.exceptionMessage.replace(/___\d+/g,"");this.sendEvent(new e.protocol.StoppedEvent("exception",r.THREAD_ID,n))}else this.sendEvent(new e.protocol.StoppedEvent("breakpoint",r.THREAD_ID))}onDebuggerWarning(e){}onDebuggerResume(){this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0))}onStateChanged(t){switch(t){case e.SimulatorState.Paused:break;case e.SimulatorState.Running:this.sendEvent(new e.protocol.ContinuedEvent(r.THREAD_ID,!0));break;case e.SimulatorState.Stopped:this.sendEvent(new e.protocol.TerminatedEvent)}}fixBreakpoints(){for(const t in this.breakpoints.idMap){const n=this.breakpoints.idMap[t];n.source.path=e.util.pathJoin(this.projectDir,n.source.path),n.line=this.convertDebuggerLineToClient(n.line),n.endLine=this.convertDebuggerLineToClient(n.endLine),n.column=this.convertDebuggerColumnToClient(n.column),n.endColumn=this.convertDebuggerColumnToClient(n.endColumn)}}}r.THREAD_ID=1,e.SimDebugSession=r;class o{constructor(e,t,n){this._message=e,this._map=t,this._dir=n,this._currentId=1,this._frames={},this._vars={};const s=this.nextId();this._vars[s]=this.getVariableValues(this._message.globals),this._globalScope={name:"Globals",variablesReference:s,expensive:!1}}getFrames(){return this._message.stackframes.map(((e,t)=>{const n=this._map.getById(e.breakpointId);if(n)return this._frames[e.breakpointId]=e,{id:e.breakpointId,name:e.funcInfo?e.funcInfo.functionName:0===t?"main":"anonymous",line:n.line,column:n.column,endLine:n.endLine,endColumn:n.endLine,source:n.source}})).filter((e=>!!e))}getScopes(e){const t=this._frames[e];if(t){const e=this.nextId();return this._vars[e]=this.getVariableValues(t.locals),[{name:"Locals",variablesReference:e,expensive:!1},this._globalScope]}return[this._globalScope]}getVariables(e){const t=this._vars[e];return t&&t.value||[]}getVariableValues(t){return new e.util.Lazy((()=>{const e=[];for(const n in t){const s=t[n];let i,r=0;null===s?i="null":void 0===s?i="undefined":"object"==typeof s?(i="(object)",r=this.nextId(),this._vars[r]=this.getVariableValues(s)):i=s.toString();const o=n.substr(0,n.lastIndexOf("___"));e.push({name:o,value:i,variablesReference:r})}return e}))}nextId(){return this._currentId++}}}(pxsim||(pxsim={})),function(e){let t,n;function s(e=0){function t(){try{window.print()}catch(e){}}e?setTimeout(t,e):t()}function i(e,t){r({type:"pxtsim",action:"event",tick:e,data:t})}function r(e){"undefined"!=typeof window&&window.parent&&window.parent!==window&&window.parent.postMessage(e,"*")}function o(){setInterval((()=>{e.Runtime.postMessage({type:"simulator",command:"reload"})}),3e3)}!function(e){let t;!function(e){e[e.Player=0]="Player",e[e.Reaction=1]="Reaction"}(t=e.IconType||(e.IconType={}))}(t=e.multiplayer||(e.multiplayer={})),e.print=s,function(t){function n(t){t.origin;let n=t.data||{},o=n.type;if(o)switch(o){case"run":l(n);break;case"instructions":e.instructions.renderInstructions(n);break;case"stop":a();break;case"mute":u(n.mute);break;case"stopsound":e.AudioContextManager.stopAll();break;case"print":s();break;case"recorder":!function(e){if(!r)return;switch(e.action){case"start":r.startRecording(e.width);break;case"stop":r.stopRecording()}}(n);break;case"screenshot":e.Runtime.postScreenshotAsync(n);break;case"custom":e.handleCustomMessage&&e.handleCustomMessage(n);break;case"pxteditor":break;case"debugger":r&&r.handleDebuggerMsg(n);break;case"simulator":let t=n;switch(t.command){case"focus":i("simulator.focus",{timestamp:t.timestamp});break;case"blur":i("simulator.blur",{timestamp:t.timestamp})}default:!function(e){if(!r||r.dead)return;r.board.receiveMessage(e)}(n)}}let r;function a(){r&&(r.kill(),r.board&&r.board.kill())}function l(t){a(),t.mute&&u(t.mute),t.localizedStrings&&e.localization.setLocalizedStrings(t.localizedStrings);const n=new e.Runtime(t);r=n,n.board.initAsync(t).then((()=>{n===r&&n.run((t=>{e.dumpLivePointers(),e.Runtime.postMessage({type:"toplevelcodefinished"})}))}))}function u(t){e.AudioContextManager.mute(t)}t.start=function(){window.addEventListener("message",n,!1),t.frameid=window.location.hash.slice(1),function(){if("serviceWorker"in navigator&&-1!==window.location.href.indexOf("---simulator")&&!e.U.isLocalHost()){const t=window.location.pathname,n=t.substring(1,t.indexOf("---"));navigator.serviceWorker.controller&&navigator.serviceWorker.addEventListener("message",(e=>{const t=e.data;t&&"serviceworker"===t.type&&"activated"===t.state&&t.ref===n&&o()}));const s=window.location.href.replace(/---simulator.*$/,"---simserviceworker");navigator.serviceWorker.register(s).then((function(t){e.log("Simulator ServiceWorker registration successful with scope: ",t.scope)}),(function(t){e.log("Simulator ServiceWorker registration failed: ",t)}))}}(),e.Runtime.postMessage({type:"ready",frameid:t.frameid})},t.stop=a,t.run=l}(n=e.Embed||(e.Embed={})),e.tickEvent=i,e.reportError=function(e,t,n){r({type:"pxtsim",action:"event",tick:"error",category:e,message:t,data:n})},e.reload=o}(pxsim||(pxsim={})),pxsim.util.injectPolyphils(),"undefined"!=typeof window&&window.addEventListener("load",(function(e){pxsim.Embed.start()})),function(e){!function(t){const n=e=>`${e}x`,s=.95,[i,r]=[816*s,1056*s],o=i-86.4,a=r-86.4,[l,u]=[1,1],c=24,h=o/u-48*u,d=`\n .instr-panel {\n margin: 20px;\n padding: 24px;\n border-width: 4px;\n border-color: gray;\n border-style: solid;\n border-radius: 20px;\n display: inline-block;\n width: ${h}px;\n height: ${a/l-48*l}px;\n position: relative;\n overflow: hidden;\n page-break-inside: avoid;\n }\n .board-svg {\n margin: 0 auto;\n display: block;\n position: absolute;\n bottom: 24px;\n left: ${(h-465)/2+c}px;\n }\n .panel-num-outer {\n position: absolute;\n left: -4px;\n top: -4px;\n width: 120px;\n height: 120px;\n border-width: 4px;\n border-style: solid;\n border-color: gray;\n border-radius: 20px 0 20px 0;\n }\n .panel-num {\n margin: 10px 0;\n text-align: center;\n font-size: 80px;\n }\n .cmp-div {\n display: inline-block;\n }\n .reqs-div {\n margin-left: 144px;\n margin-top: 5px;\n }\n .partslist-wire,\n .partslist-cmp {\n margin: 10px;\n }\n .partslist-wire {\n display: inline-block;\n }\n `;function p(t,n){let s=document.createElementNS("http://www.w3.org/2000/svg","svg"),i={l:0,t:0,w:0,h:0},r=document.createElementNS("http://www.w3.org/2000/svg","svg");s.appendChild(r),r.appendChild(t.el);let o={viewBox:`${t.x} ${t.y} ${t.w} ${t.h}`,preserveAspectRatio:"xMidYMid"};i.w=t.w,i.h=t.h;let a=e=>{i.h*=e,i.w*=e,o.width=i.w,o.height=i.h};n.cmpScale&&a(n.cmpScale),n.cmpWidth&&n.cmpWidth<i.w?a(n.cmpWidth/i.w):n.cmpHeight&&n.cmpHeight<i.h&&a(n.cmpHeight/i.h),e.svg.hydrate(r,o);let l=i.l,u=i.t,c=i.w,h=i.h,d=e=>{if(e<i.l){let t=i.l-e;i.l=e,i.w+=t}},p=e=>{let t=i.l+i.w;if(t<e){let n=e-t;i.w+=n}},m=e=>{if(e<i.t){let t=i.t-e;i.t=e,i.h+=t}},f=e=>{let t=i.t+i.h;if(t<e){let n=e-t;i.h+=n}},[g,b]=[-.3,.3];const v=[1.4,1];if(n&&n.top){let t=n.topSize,i=t/v[0],r=t/v[1],[o,a]=[l+c/2,u-3-r/2],h=e.visuals.mkTxt(o,a,t,0,n.top,g,b);e.U.addClass(h,"cmp-lbl"),s.appendChild(h);let f=i*n.top.length;m(a-r/2),d(o-f/2),p(o+f/2)}if(n&&n.bot){let t=n.botSize,i=t/v[0],r=t/v[1],[o,a]=[l+c/2,u+h+3+r/2],m=e.visuals.mkTxt(o,a,t,0,n.bot,g,b);e.U.addClass(m,"cmp-lbl"),s.appendChild(m);let y=i*n.bot.length;f(a+r/2),d(o-y/2),p(o+y/2)}if(n&&n.right){let t=n.rightSize,i=t/v[1],r=t/v[0]*n.right.length,[o,a]=[l+c+5+r/2,u+h/2],d=e.visuals.mkTxt(o,a,t,0,n.right,g,b);e.U.addClass(d,"cmp-lbl"),s.appendChild(d),m(a-i/2),p(o+r/2),f(a+i/2)}if(n&&n.left){let t=n.leftSize,i=t/v[1],r=t/v[0]*n.left.length,[o,a]=[l-5-r/2,u+h/2],c=e.visuals.mkTxt(o,a,t,0,n.left,g,b);e.U.addClass(c,"cmp-lbl"),s.appendChild(c),m(a-i/2),d(o-r/2),f(a+i/2)}let y={viewBox:`${i.l} ${i.t} ${i.w} ${i.h}`,width:1.7*i.w,height:1.7*i.h,preserveAspectRatio:"xMidYMid"};e.svg.hydrate(s,y);let w=document.createElement("div");return w.appendChild(s),w}function m(t,n){let s,i=e.runtime.board;if("wire"==t)s=e.visuals.mkWirePart([0,0],n.wireClr||"red",n.crocClips);else{let n=t;if("string"==typeof n.builtIn){s=(0,i.builtinPartVisuals[n.builtIn])([0,0])}else s=e.visuals.mkGenericPartSVG(n)}return p(s,n)}function f(t,n,s=!1){const i={state:e.runtime.board,boardDef:t.boardDef,forceBreadboardLayout:!0,forceBreadboardRender:t.allAlloc.requiresBreadboard,partDefs:t.cmpDefs,maxWidth:`${n}px`,fnArgs:t.fnArgs,wireframe:s,partsList:[]};let r=new e.visuals.BoardHost(e.visuals.mkBoardView({visual:i.boardDef.visual,boardDef:i.boardDef,wireframe:i.wireframe}),i),o=r.getView();return e.U.addClass(o,"board-svg"),r}function g(){let t=document.createElement("div");return e.U.addClass(t,"instr-panel"),t}function b(t){let s=g();var i;let r=p((i=t.boardDef,e.visuals.mkBoardView({visual:i.visual,boardDef:i}).getView()),{left:n(1),leftSize:30,cmpScale:.17});s.appendChild(r);let o=p(new e.visuals.Breadboard({}).getSVGAndSize(),{left:n(1),leftSize:30,cmpScale:.25});return s.appendChild(o),t.allCmps.forEach((t=>{let i=1;"buttonpair"===t.visual.builtIn&&(i=2);let r=m(t.visual,{left:n(i),leftSize:30,cmpScale:.3});e.U.addClass(r,"partslist-cmp"),s.appendChild(r)})),t.allWireColors.forEach((i=>{let r=t.colorToWires[i].length,o=t.boardDef.pinStyles[i]||"female",a=m("wire",{left:n(r),leftSize:20,wireClr:i,cmpScale:.23,crocClips:"croc"==o});e.U.addClass(a,"partslist-wire"),s.appendChild(a)})),s}function v(t,n){let s=g(),i=f(n,465,!0);!function(t,n,s){let i=t.getView();n>0&&e.U.addClass(i,"grayed");for(let i=0;i<=n;i++){let r=s.stepToCmps[i];r&&r.forEach((s=>{let r=t.addPart(s);i===n&&(s.breadboardConnections.forEach((e=>t.highlightBreadboardPin(e))),e.U.addClass(r.element,"notgrayed"))}));let o=s.stepToWires[i];o&&o.forEach((e=>{let s=t.addWire(e);s&&i===n&&("breadboard"==e.start.type?t.highlightBreadboardPin(e.start):t.highlightBoardPin(e.start.pin),"breadboard"==e.end.type?t.highlightBreadboardPin(e.end):t.highlightBoardPin(e.end.pin),t.highlightWire(s))}))}}(i,t,n),s.appendChild(i.getView());let r=document.createElement("div");e.U.addClass(r,"panel-num-outer"),e.U.addClass(r,"noselect"),s.appendChild(r);let o=document.createElement("div");e.U.addClass(o,"panel-num"),o.textContent=t+1+"",r.appendChild(o);let a=document.createElement("div");e.U.addClass(a,"reqs-div"),s.appendChild(a);let l=n.stepToWires[t]||[],u=e=>{if("breadboard"===e.type){let{row:t,col:n}=e;return`(${t},${n})`}return e.pin};return l.forEach((t=>{let s=!1;"dalboard"==t.end.type&&(s="croc"==n.boardDef.pinStyles[t.end.pin]);let i=m("wire",{top:u(t.end),topSize:10,bot:u(t.start),botSize:10,wireClr:t.color,cmpHeight:40,crocClips:s});e.U.addClass(i,"cmp-div"),a.appendChild(i)})),(n.stepToCmps[t]||[]).forEach((t=>{let n;n="buttonpair"===t.visual.builtIn?[t.breadboardConnections[0],t.breadboardConnections[2]]:[t.breadboardConnections[0]],n.forEach(((n,s)=>{let i;if(n){let{row:e,col:t}=n;i=`(${e},${t})`}else i="";let r=1.5;"buttonpair"===t.visual.builtIn&&(r*=.5);let o=m(t.visual,{top:i,topSize:10,cmpHeight:50,cmpScale:r});e.U.addClass(o,"cmp-div"),a.appendChild(o)}))})),s}function y(t,n){n.boardDef.pinStyles||(n.boardDef.pinStyles={}),n.configData&&e.setConfigData(n.configData.cfg,n.configData.cfgKey);const s={type:"run",code:"",boardDefinition:n.boardDef,partDefinitions:n.partDefinitions};e.runtime=new e.Runtime(s),e.runtime.board=null,e.initCurrentRuntime(s);let i=document.createElement("style");i.textContent+=d,document.head.appendChild(i);const r=n.partDefinitions;let o=new e.visuals.Breadboard({}),a=function(t){let n=e.allocateDefinitions(t),s=[],i=[],r=1;n.partsAndWires.forEach((e=>{let t=e.part,n=e.wires;e.assembly.forEach(((e,o)=>{e.part&&t&&(i[r+o]=[t]),e.wireIndices&&e.wireIndices.length>0&&n&&(s[r+o]=e.wireIndices.map((e=>n[e])))})),r+=e.assembly.length}));let o=r-1,a=n.partsAndWires.map((e=>e.part)).filter((e=>!!e)),l=n.partsAndWires.map((e=>e.wires||[])).reduce(((e,t)=>e.concat(t)),[]),u={},c=[];return l.forEach((e=>{u[e.color]||(u[e.color]=[],c.push(e.color)),u[e.color].push(e)})),{boardDef:t.boardDef,cmpDefs:t.partDefs,fnArgs:t.fnArgs,allAlloc:n,stepToWires:s,stepToCmps:i,allWires:l,allCmps:a,lastStep:o,colorToWires:u,allWireColors:c}}({boardDef:n.boardDef,partDefs:r,partsList:n.parts,fnArgs:n.fnArgs,getBBCoord:o.getCoord.bind(o)});a.allAlloc.requiresBreadboard=!0;!function(e){let t=document.getElementById("front-panel"),n=f(e,400,!1);n.addAll(e.allAlloc),t.appendChild(n.getView())}(a);let l=b(a);t.appendChild(l);for(let e=0;e<=a.lastStep;e++){let n=v(e,a);t.appendChild(n)}n.print&&e.print(2e3)}t.renderParts=y,t.renderInstructions=function(e){document.getElementById("proj-title").innerText=e.options.name||"",y(document.body,e.options)}}(e.instructions||(e.instructions={}))}(pxsim||(pxsim={})),function(e){function t(e,t="sim: check failed"){if(!e)throw new Error(t)}e.quiet=!1,e.check=t,e.title="";let n,s,i,r,o,a={},l={};e.getConfig=function(e){return l.hasOwnProperty(e+"")?l[e+""]:null},e.getConfigKey=function(e){return a.hasOwnProperty(e)?a[e]:null},e.getAllConfigKeys=function(){return Object.keys(a)},e.setConfigKey=function(e,t){a[e]=t},e.setConfig=function(e,t){l[e]=t},e.setConfigData=function(e,t){l=e,a=t},e.getConfigData=function(){return{cfg:l,cfgKey:a}},e.setTitle=function(t){e.title=t};class u{constructor(){e.runtime?this.id=e.runtime.registerLiveObject(this):this.id=0}destroy(){}scan(t){throw e.U.userError("scan not implemented")}gcKey(){throw e.U.userError("gcKey not implemented")}gcSize(){throw e.U.userError("gcSize not implemented")}gcIsStatic(){return!1}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefObject id:${this.id}`)}toDebugString(){return"(object)"}static toAny(e){return e&&e.toAny?e.toAny():e}static fromAny(t){return t?t instanceof u?t:Array.isArray(t)?e.RefCollection.fromAny(t):"object"==typeof t?h.fromAny(t):t:t}static toDebugString(e){return null===e?"null":void 0===e?"undefined;":e.vtable&&e.vtable.name?"_Map"===e.vtable.name&&e instanceof m?"(object)":e.vtable.name:e.toDebugString?e.toDebugString():e.vtable&&e.vtable.name?e.vtable.name:"string"==typeof e?JSON.stringify(e):e.toString()}}e.RefObject=u;class c{constructor(e,t,n){this.func=e,this.caps=t,this.args=n}}e.FnWrapper=c;class h extends u{constructor(){super(...arguments),this.fields={}}scan(e){for(let t of Object.keys(this.fields))e(t,this.fields[t])}gcKey(){return this.vtable.name}gcSize(){return this.vtable.numFields+1}destroy(){this.fields=null,this.vtable=null}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefRecord id:${this.id} (${this.vtable.name})`)}toDebugString(){let e="RefRecord: {";const t=Object.keys(this.fields);for(let n=0;n<t.length;++n)n>0&&(e+=", "),e+=t[n]+": "+u.toDebugString(this.fields[t[n]]);return e+"}"}toAny(){const e={};for(let t of Object.keys(this.fields))e[t]=u.toAny(this.fields[t]);return e}static fromAny(e){const t=new h;for(let n of Object.keys(e))t.fields[n]=u.fromAny(e[n]);return t}}e.RefRecord=h;class d extends u{constructor(){super(...arguments),this.fields=[]}scan(e){for(let t=0;t<this.fields.length;++t)e("_cap"+t,this.fields[t])}gcKey(){return e.functionName(this.func)}gcSize(){return this.fields.length+3}isRef(e){return t(0<=e&&e<this.fields.length),e<this.len}ldclo(e){return t(0<=(e>>=2)&&e<this.fields.length),this.fields[e]}destroy(){this.fields=null,this.func=null}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefAction id:${this.id} len:${this.fields.length}`)}}e.RefAction=d,function(t){t.seedAddRandom=function(e){},t.mkAction=function(e,t){let n=new d;n.len=e,n.func=t;for(let t=0;t<e;++t)n.fields.push(null);return n},t.runAction=function(t,n){let s=e.getResume();s(t instanceof d?new c(t.func,t.fields,n):new c(t,null,n))};let n={};t.dumpPerfCounters=function(){if(!e.runtime||!e.runtime.perfCounters)return;let t="calls,us,name\n";for(let n of e.runtime.perfCounters){n.lastFew.sort();const e=n.lastFew[n.lastFew.length>>1];t+=`${n.numstops},${n.value},${n.name},${e}\n`}!function(t){let s="";const i=(e,t)=>{s+=e.length>=t?e:(" "+e).slice(-t)},r=e=>i(""+Math.round(e),6),o=(e,t)=>{i(Math.round(t)+"",8),s+=" /",r(e),s+=" =",r(t/e)};for(let e of t.split(/\n/)){if(!e)continue;if(!/^\d/.test(e))continue;const t=e.split(/,/);let i=n[t[2]];i||(n[t[2]]=i={stops:0,us:0,meds:[]}),a=t[2],l=25,s+=a.length>=l?a:(a+" ").slice(0,l);const u=parseInt(t[0]),c=parseInt(t[1]);o(u,c),s+=" |",o(u-i.stops,c-i.us),s+=" ~";const h=parseInt(t[3]);r(h),i.meds.length>10&&i.meds.shift(),i.meds.push(h);const d=i.meds.slice();d.sort(((e,t)=>e-t));const p=d[d.length>>1];s+=" ~~",r(p),i.stops=u,i.us=c,s+="\n"}var a,l;e.log(s)}(t)}}(n=e.pxtcore||(e.pxtcore={}));class p extends u{constructor(){super(...arguments),this.v=void 0}scan(e){e("*",this.v)}gcKey(){return"LOC"}gcSize(){return 2}destroy(){}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefRefLocal id:${this.id} v:${this.v}`)}}e.RefRefLocal=p;class m extends u{constructor(){super(...arguments),this.vtable=e.mkMapVTable(),this.data=[]}scan(e){for(let t of this.data)e(t.key,t.val)}gcKey(){return"{...}"}gcSize(){return 2*this.data.length+4}findIdx(e){e+="";for(let t=0;t<this.data.length;++t)if(this.data[t].key==e)return t;return-1}destroy(){super.destroy();for(let e=0;e<this.data.length;++e)this.data[e].val=0;this.data=[]}print(){e.runtime&&e.runtime.refCountingDebug&&e.log(`RefMap id:${this.id} size:${this.data.length}`)}toDebugString(){let e="RefMap: {";for(let t=0;t<this.data.length;++t)t>0&&(e+=", "),e+=this.data[t].key+": "+u.toDebugString(this.data[t].val);return e+"}"}toA