Code viewer for World: World 2: World 1 plus code...

// Cloned by Abdelshafa Abdala on 10 Nov 2022 from World "World 2: World 1 plus code to trap the agent" by Gary 
// Please leave this clone trail here.
 
AB.clockTick=50,AB.maxSteps=1e3,AB.screenshotStep=50;const show3d=!0,TEXTURE_WALL="/uploads/gfar97/wall2.jpg",TEXTURE_MAZE="/uploads/gfar97/wall3.jpg",TEXTURE_AGENT="/uploads/gfar97/ship3.jpg",TEXTURE_ENEMY="/uploads/gfar97/enemy.jpg",pathCubeMaterial=new THREE.MeshBasicMaterial({color:65280}),trapCubeMaterial=new THREE.MeshBasicMaterial({color:16750848}),MUSIC_BACK="/uploads/starter/Defense.Line.mp3",SOUND_ALARM="/uploads/starter/air.horn.mp3",gridsize=50,NOBOXES=Math.trunc(gridsize*gridsize/3),squaresize=100,MAXPOS=gridsize*squaresize,SKYCOLOR=14548957,startRadiusConst=.8*MAXPOS,maxRadiusConst=10*MAXPOS;ABHandler.MAXCAMERAPOS=maxRadiusConst,ABHandler.GROUNDZERO=!0;const SKYBOX_ARRAY=["/uploads/gfar97/corona_ft.png","/uploads/gfar97/corona_bk.png","/uploads/gfar97/corona_up.png","/uploads/gfar97/corona_dn.png","/uploads/gfar97/corona_rt.png","/uploads/gfar97/corona_lf.png"],ACTION_LEFT=0,ACTION_RIGHT=1,ACTION_UP=2,ACTION_DOWN=3,ACTION_STAYSTILL=4,GRID_BLANK=0,GRID_WALL=1,GRID_MAZE=2;var BOXHEIGHT,theagent,theenemy,wall_texture,agent_texture,enemy_texture,maze_texture,ei,ej,ai,aj,badsteps,goodsteps,agentLastPosition,lastTrapCube,bestTrap,GRID=new Array(gridsize),spotGrid=new Array(gridsize),cols=gridsize,rows=gridsize,openSet=[],closedSet=[],enemyMoves=[],trapSpots=[];function loadResources(){var e=new THREE.TextureLoader,t=new THREE.TextureLoader,a=new THREE.TextureLoader,o=new THREE.TextureLoader;e.load(TEXTURE_WALL,function(e){e.minFilter=THREE.LinearFilter,wall_texture=e,asynchFinished()&&initScene()}),t.load(TEXTURE_AGENT,function(e){e.minFilter=THREE.LinearFilter,agent_texture=e,asynchFinished()&&initScene()}),a.load(TEXTURE_ENEMY,function(e){e.minFilter=THREE.LinearFilter,enemy_texture=e,asynchFinished()&&initScene()}),o.load(TEXTURE_MAZE,function(e){e.minFilter=THREE.LinearFilter,maze_texture=e,asynchFinished()&&initScene()})}function asynchFinished(){return!!(wall_texture&&agent_texture&&enemy_texture&&maze_texture)}function occupied(e,t){return ei==e&&ej==t||(ai==e&&aj==t||(GRID[e][t]==GRID_WALL||GRID[e][t]==GRID_MAZE))}function translate(e,t){var a=new THREE.Vector3;return a.y=0,a.x=e*squaresize-MAXPOS/2,a.z=t*squaresize-MAXPOS/2,a}function initScene(){var e,t,a,o;for(e=0;e<gridsize;e++)GRID[e]=new Array(gridsize);for(e=0;e<gridsize;e++)for(t=0;t<gridsize;t++)0==e||e==gridsize-1||0==t||t==gridsize-1?(GRID[e][t]=GRID_WALL,a=new THREE.BoxGeometry(squaresize,BOXHEIGHT,squaresize),(o=new THREE.Mesh(a)).material=new THREE.MeshBasicMaterial({map:wall_texture}),o.position.copy(translate(e,t)),ABWorld.scene.add(o)):GRID[e][t]=GRID_BLANK;for(var r=1;r<=NOBOXES;r++)e=AB.randomIntAtoB(1,gridsize-2),t=AB.randomIntAtoB(1,gridsize-2),GRID[e][t]=GRID_MAZE,a=new THREE.BoxGeometry(squaresize,BOXHEIGHT,squaresize),(o=new THREE.Mesh(a)).material=new THREE.MeshBasicMaterial({map:maze_texture}),o.position.copy(translate(e,t)),ABWorld.scene.add(o);do{e=AB.randomIntAtoB(1,gridsize-2),t=AB.randomIntAtoB(1,gridsize-2)}while(occupied(e,t));ei=e,ej=t,ti=ei,tj=ej,a=new THREE.BoxGeometry(squaresize,BOXHEIGHT,squaresize),(theenemy=new THREE.Mesh(a)).material=new THREE.MeshBasicMaterial({map:enemy_texture}),ABWorld.scene.add(theenemy),drawEnemy();do{e=AB.randomIntAtoB(1,gridsize-2),t=AB.randomIntAtoB(1,gridsize-2)}while(occupied(e,t));ai=e,aj=t,a=new THREE.BoxGeometry(squaresize,BOXHEIGHT,squaresize),(theagent=new THREE.Mesh(a)).material=new THREE.MeshBasicMaterial({map:agent_texture}),ABWorld.scene.add(theagent),drawAgent(),setupForAStar(),ABWorld.scene.background=(new THREE.CubeTextureLoader).load(SKYBOX_ARRAY,function(){ABWorld.render(),AB.removeLoading(),AB.runReady=!0})}function drawPath(){for(var e=0;e<enemyMoves.length;e++)shape=new THREE.BoxGeometry(squaresize/2,BOXHEIGHT/2,squaresize/2),pathCube=new THREE.Mesh(shape),pathCube.material=pathCubeMaterial,pathCube.position.copy(translate(enemyMoves[e].x,enemyMoves[e].y)),ABWorld.scene.add(pathCube)}function drawNearestTrap(e){lastTrapCube&&ABWorld.scene.remove(lastTrapCube),shape=new THREE.BoxGeometry(squaresize/2,BOXHEIGHT/2,squaresize/2),pathCube=new THREE.Mesh(shape),pathCube.material=trapCubeMaterial,pathCube.position.copy(translate(e.x,e.y)),ABWorld.scene.add(pathCube),lastTrapCube=pathCube}function drawEnemy(){theenemy.position.copy(translate(ei,ej)),ABWorld.lookat.copy(theenemy.position)}function drawAgent(){theagent.position.copy(translate(ai,aj)),ABWorld.follow.copy(theagent.position)}function moveLogicalEnemy(){var e,t;ei<ai&&(e=AB.randomIntAtoB(ei,ei+1)),ei==ai&&(e=ei),ei>ai&&(e=AB.randomIntAtoB(ei-1,ei)),ej<aj&&(t=AB.randomIntAtoB(ej,ej+1)),ej==aj&&(t=ej),ej>aj&&(t=AB.randomIntAtoB(ej-1,ej)),occupied(e,t)||(ei=e,ej=t)}function moveLogicalAgent(e){var t=ai,a=aj;e==ACTION_LEFT?t--:e==ACTION_RIGHT?t++:e==ACTION_UP?a++:e==ACTION_DOWN&&a--,occupied(t,a)||(ai=t,aj=a)}var OURKEYS=[37,38,39,40];function ourKeys(e){return OURKEYS.includes(e.keyCode)}function keyHandler(e){return!AB.runReady||(!ourKeys(e)||(37==e.keyCode&&moveLogicalAgent(ACTION_LEFT),38==e.keyCode&&moveLogicalAgent(ACTION_DOWN),39==e.keyCode&&moveLogicalAgent(ACTION_RIGHT),40==e.keyCode&&moveLogicalAgent(ACTION_UP),e.stopPropagation(),e.preventDefault(),!1))}function badstep(){return Math.abs(ei-ai)<2&&Math.abs(ej-aj)<2}function agentBlocked(){return occupied(ai-1,aj)&&occupied(ai+1,aj)&&occupied(ai,aj+1)&&occupied(ai,aj-1)}function updateStatusBefore(e){var t=AB.world.getState();AB.msg(" Step: "+AB.step+" &nbsp; x = ("+t.toString()+") &nbsp; a = ("+e+") ")}function updateStatusAfter(){var e=AB.world.getState(),t=goodsteps/AB.step*100;AB.msg(" &nbsp; y = ("+e.toString()+") <br> Bad steps: "+badsteps+" &nbsp; Good steps: "+goodsteps+" &nbsp; Score: "+t.toFixed(2)+"% ",2)}function aStar(){enemyPos=spotGrid[ei][ej],agentPos=spotGrid[ai][aj],pathSpot=new Spot(enemyPos.x,enemyPos.y),enemyMoves.push(pathSpot),bestTrap=nearestTrapToAgent(agentPos);var e=furthestNeighbourFromTrap(agentPos,bestTrap);getDistance(enemyPos,bestTrap)<=getDistance(agentPos,bestTrap)?bestMove=getBestPath(enemyPos,agentPos):bestMove=getBestPath(enemyPos,e),checkTrapped(agentPos)&&(bestMove=getBestPath(enemyPos,agentPos)),sidewaysCheck(agentPos)&&(pushPosition(agentPos,enemyPos)&&(bestMove=getBestPath(enemyPos,pushOutNeighbour(agentPos),!1)),bestMove=getBestPath(enemyPos,agentPos)),ei=bestMove.x,ej=bestMove.y,resetAllDistances()}function getBestPath(e,t,a=!0){for(openMoves=[],closedMoves=[],openMoves.push(e);openMoves.length>0&&s!==t;){for(var o=0,r=0;r<openMoves.length;r++)openMoves[r].totalDistance<openMoves[o].totalDistance&&(o=r);var s=openMoves[o];removeFromArray(openMoves,s),closedMoves.push(s);var n=s.neighbours;for(r=0;r<n.length;r++){var i=n[r];if(!closedMoves.includes(i)&&!i.wall){var u=s.distanceToGetHere+getDistance(i,s),d=!1;openMoves.includes(i)?u<i.distanceToGetHere&&(i.distanceToGetHere=u,d=!0):(i.distanceToGetHere=u,d=!0,openMoves.push(i)),d&&(i.distanceToTarget=getDistance(i,t),i.totalDistance=i.distanceToGetHere+i.distanceToTarget,i.previousSpot=s)}}}var l=s;for(bestPath=[];l.previousSpot;)l=l.previousSpot,bestPath.push(l);return bestPath.length>1?a?bestPath[bestPath.length-2]:bestPath[bestPath.length-1]:l}function getDistance(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function removeFromArray(e,t){for(var a=e.length-1;a>=0;a--)e[a]==t&&e.splice(a,1)}function Spot(e,t){this.x=e,this.y=t,this.totalDistance=0,this.distanceToGetHere=0,this.distanceToTarget=0,this.validNeighbourMoves=0,this.neighbours=[],this.previousSpot=void 0,this.nextSpot=void 0,this.wall=checkIfWall(this.x,this.y),this.addNeighbours=function(e){var t=this.x,a=this.y;t<cols-1&&this.neighbours.push(e[t+1][a]),t>0&&this.neighbours.push(e[t-1][a]),a<rows-1&&this.neighbours.push(e[t][a+1]),a>0&&this.neighbours.push(e[t][a-1])},this.addValidNeighbourMoves=function(){this.x,this.y;if(!this.wall){var e=0;for(neighbourCount=0;neighbourCount<this.neighbours.length;neighbourCount++)this.neighbours[neighbourCount].wall||e++;this.validNeighbourMoves=e}}}function checkIfWall(e,t){return occupied(e,t)}function setupForAStar(){for(xValue=0;xValue<gridsize;xValue++)spotGrid[xValue]=new Array(gridsize);for(xValue=0;xValue<gridsize;xValue++)for(yValue=0;yValue<gridsize;yValue++)spotGrid[xValue][yValue]=new Spot(xValue,yValue);for(xValue=0;xValue<gridsize;xValue++)for(yValue=0;yValue<gridsize;yValue++)spotGrid[xValue][yValue].addNeighbours(spotGrid),spotGrid[xValue][yValue].addValidNeighbourMoves();trapSpots=findTrapSpots()}function resetAllDistances(){for(xValue=0;xValue<gridsize;xValue++)for(yValue=0;yValue<gridsize;yValue++)spotGrid[xValue][yValue].totalDistance=0,spotGrid[xValue][yValue].distanceToGetHere=0,spotGrid[xValue][yValue].distanceToTarget=0,spotGrid[xValue][yValue].previousSpot=void 0}function findTrapSpots(){var e=[];for(xValue=0;xValue<gridsize;xValue++)for(yValue=0;yValue<gridsize;yValue++)1===spotGrid[xValue][yValue].validNeighbourMoves&&e.push(spotGrid[xValue][yValue]);return e}function nearestTrapToAgent(e){for(var t=trapSpots[0],a=0;a<trapSpots.length;a++){trapSpot=trapSpots[a];var o=getDistance(e,trapSpot);getDistance(e,t)>o&&(t=trapSpot)}return t}function furthestNeighbourFromTrap(e,t){for(var a=e,o=0;o<e.neighbours.length;o++)e.neighbours.wall||getDistance(t,e.neighbours[o])>getDistance(t,a)&&(a=e.neighbours[o]);return a}function checkTrapped(e){for(var t=0;t<trapSpots.length;t++)if(0===getDistance(trapSpots[t],e))return console.log("Trapped!!"),!0;return!1}function sidewaysCheck(e){return 2===e.validNeighbourMoves&&(console.log("Sideways"),!0)}function pushPosition(e,t){return getDistance(e,t)<2&&(console.log("Pushing from furthest neighbour"),!0)}function pushOutNeighbour(e){for(var t,a=5,o=0;o<e.neighbours.length;o++)e.neighbours[o].wall||e.neighbours[o].validNeighbourMoves<a&&(a=e.neighbours[o].validNeighbourMoves,t=e.neighbours[o]);return console.log("Pushing from:",enemyPos,"pushing to:",t),t}AB.world.newRun=function(){AB.loadingScreen(),AB.runReady=!1,badsteps=0,goodsteps=0,BOXHEIGHT=squaresize,ABWorld.init3d(startRadiusConst,maxRadiusConst,14548957),loadResources(),document.onkeydown=keyHandler},AB.world.getState=function(){return[ai,aj,ei,ej]},AB.world.takeAction=function(e){updateStatusBefore(e),agentLastPosition=new Spot(ai,aj),moveLogicalAgent(e),AB.step%2==0&&aStar(),drawPath(),bestTrap&&drawNearestTrap(bestTrap),badstep()?badsteps++:goodsteps++,drawAgent(),drawEnemy(),updateStatusAfter(),agentBlocked()&&(AB.abortRun=!0,goodsteps=0)},AB.world.endRun=function(){AB.abortRun?AB.msg(" <br> <font color=red> <B> Agent trapped. Final score zero. </B> </font>   ",3):AB.msg(" <br> <font color=green> <B> Run over. </B> </font>   ",3)},AB.world.getScore=function(){var e=goodsteps/AB.maxSteps*100;return Math.round(100*e)/100};