Code viewer for World: Complex World (clone by Re...

// Cloned by Reeve Barreto on 25 Oct 2023 from World "Complex World" by Starter user 
// Please leave this clone trail here.
 



// ==== Starter World =================================================================================================
// This code is designed for use on the Ancient Brain site.
// This code may be freely copied and edited by anyone on the Ancient Brain site.
// To include a working run of this program on another site, see the "Embed code" links provided on Ancient Brain.
// ====================================================================================================================



// =============================================================================================
// More complex starter World 
// 3d-effect Maze World (really a 2-D problem)
// Movement is on a semi-visible grid of squares 
//
// This more complex World shows:
// - Skybox
// - Internal maze (randomly drawn each time)
// - Enemy actively chases agent
// - Music/audio
// - 2D world (clone this and set show3d = false)
// - User keyboard control (clone this and comment out Mind actions to see)
// =============================================================================================


// =============================================================================================
// Scoring:
// Bad steps = steps where enemy is within one step of agent.
// Good steps = steps where enemy is further away. 
// Score = good steps as percentage of all steps.
//
// There are situations where agent is trapped and cannot move.
// If this happens, you score zero.
// =============================================================================================


 





// ===================================================================================================================
// === Start of tweaker's box ======================================================================================== 
// ===================================================================================================================

// The easiest things to modify are in this box.
// You should be able to change things in this box without being a JavaScript programmer.
// Go ahead and change some of these. What's the worst that could happen?


AB.clockTick       = 300;    

	// Speed of run: Step every n milliseconds. Default 100.
	
AB.maxSteps        = 1000;    

	// Length of run: Maximum length of run in steps. Default 1000.

AB.screenshotStep  = 50;   
  
	// Take screenshot on this step. (All resources should have finished loading.) Default 50.



//---- global constants: -------------------------------------------------------

	const show3d = true;						// Switch between 3d and 2d view (both using Three.js) 


 const TEXTURE_WALL 	= '/uploads/reeve/water.png' ;
 const TEXTURE_MAZE 	= '/uploads/reeve/land.png' ;
 const TEXTURE_AGENT 	= '/uploads/reeve/caterpie.png' ;
 const TEXTURE_ENEMY 	= '/uploads/reeve/ash.png' ;

// credits:
// http://commons.wikimedia.org/wiki/File:Old_door_handles.jpg
// https://commons.wikimedia.org/wiki/Category:Pac-Man_icons
// https://commons.wikimedia.org/wiki/Category:Skull_and_crossbone_icons
// http://en.wikipedia.org/wiki/File:Inscription_displaying_apices_(from_the_shrine_of_the_Augustales_at_Herculaneum).jpg

 
	const MUSIC_BACK  = '/uploads/reeve/pokemonbattle.mp3' ;
	const SOUND_ALARM = '/uploads/reeve/pokemoncaptured.mp3' ;

// credits:
// http://www.dl-sounds.com/royalty-free/defense-line/
// http://soundbible.com/1542-Air-Horn.html 

	
	
const gridsize = 40;						// number of squares along side of world	   

const NOBOXES = Math.trunc ( (gridsize * gridsize) / 3);
		// density of maze - number of internal boxes
		// (bug) use trunc or can get a non-integer 

const squaresize = 100;					// size of square in pixels

const MAXPOS = gridsize * squaresize;		// length of one side in pixels 
	
const SKYCOLOR 	= 0xddffdd;				// a number, not a string 

 
const startRadiusConst	 	= MAXPOS * 0.8 ;		// distance from centre to start the camera at
const maxRadiusConst 		= MAXPOS * 10  ;		// maximum distance from camera we will render things  



//--- change ABWorld defaults: -------------------------------

ABHandler.MAXCAMERAPOS 	= maxRadiusConst ;

ABHandler.GROUNDZERO		= true;						// "ground" exists at altitude zero



//--- skybox: -------------------------------
// skybox is a collection of 6 files 
// x,y,z positive and negative faces have to be in certain order in the array 
// https://threejs.org/docs/#api/en/loaders/CubeTextureLoader 
                
const SKYBOX_ARRAY = [										 
                "/uploads/reeve/xp.png",
                "/uploads/reeve/xn.png",
                "/uploads/reeve/yp.png",
                "/uploads/reeve/yn.png",
                "/uploads/reeve/zp.png",
                "/uploads/reeve/zn.png"
                ];


// ===================================================================================================================
// === End of tweaker's box ==========================================================================================
// ===================================================================================================================


// You will need to be some sort of JavaScript programmer to change things below the tweaker's box.









//--- Mind can pick one of these actions -----------------

const ACTION_LEFT 			= 0;		   
const ACTION_RIGHT 			= 1;
const ACTION_UP 			= 2;		 
const ACTION_DOWN 			= 3;
const ACTION_STAYSTILL 		= 4;

// in initial view, (smaller-larger) on i axis is aligned with (left-right)
// in initial view, (smaller-larger) on j axis is aligned with (away from you - towards you)


// contents of a grid square

const GRID_BLANK 	= 0;
const GRID_WALL 	= 1;
const GRID_MAZE 	= 2;
 
 
 
 

var BOXHEIGHT;		// 3d or 2d box height 

var GRID 	= new Array(gridsize);			// can query GRID about whether squares are occupied, will in fact be initialised as a 2D array   

var theagent, theenemy;
  
var wall_texture, agent_texture, enemy_texture, maze_texture; 


// enemy and agent position on squares
var ei, ej, ai, aj;

var badsteps;
var goodsteps;
	
function loadResources()		// asynchronous file loads - call initScene() when all finished 
{
	var loader1 = new THREE.TextureLoader();
	var loader2 = new THREE.TextureLoader();
	var loader3 = new THREE.TextureLoader();
	var loader4 = new THREE.TextureLoader();
	
	loader1.load ( TEXTURE_WALL, function ( thetexture )  		
	{
		thetexture.minFilter  = THREE.LinearFilter;
		wall_texture = thetexture;
		if ( asynchFinished() )	initScene();		// if all file loads have returned 
	});
		
	loader2.load ( TEXTURE_AGENT, function ( thetexture )  	 
	{
		thetexture.minFilter  = THREE.LinearFilter;
		agent_texture = thetexture;
		if ( asynchFinished() )	initScene();		 
	});	
	
	loader3.load ( TEXTURE_ENEMY, function ( thetexture )  
	{
		thetexture.minFilter  = THREE.LinearFilter;
		enemy_texture = thetexture;
		if ( asynchFinished() )	initScene();		 
	});
	
	loader4.load ( TEXTURE_MAZE, function ( thetexture )  
	{
		thetexture.minFilter  = THREE.LinearFilter;
		maze_texture = thetexture;
		if ( asynchFinished() )	initScene();		 
	});
	
}


function asynchFinished()		 // all file loads returned 
{
	if ( wall_texture && agent_texture && enemy_texture && maze_texture )   return true; 
	else return false;
}	
	
	
 

//--- grid system -------------------------------------------------------------------------------
// my numbering is 0 to gridsize-1

	
function occupied ( i, j )		// is this square occupied
{
 if ( ( ei == i ) && ( ej == j ) ) return true;		// variable objects 
 if ( ( ai == i ) && ( aj == j ) ) return true;

 if ( GRID[i][j] == GRID_WALL ) return true;		// fixed objects	 
 if ( GRID[i][j] == GRID_MAZE ) return true;		 
	 
 return false;
}

 
// translate my (i,j) grid coordinates to three.js (x,y,z) coordinates
// logically, coordinates are: y=0, x and z all positive (no negative)    
// logically my dimensions are all positive 0 to MAXPOS
// to centre everything on origin, subtract (MAXPOS/2) from all dimensions 

function translate ( i, j )			
{
	var v = new THREE.Vector3();
	
	v.y = 0;	
	v.x = ( i * squaresize ) - ( MAXPOS/2 );   		 
	v.z = ( j * squaresize ) - ( MAXPOS/2 );   	
	
	return v;
}



	
function initScene()		// all file loads have returned 
{
	 var i,j, shape, thecube;
	 
	// set up GRID as 2D array
	 
	 for ( i = 0; i < gridsize ; i++ ) 
		GRID[i] = new Array(gridsize);		 


	// set up walls
	 
	 for ( i = 0; i < gridsize ; i++ ) 
	  for ( j = 0; j < gridsize ; j++ ) 
		if ( ( i==0 ) || ( i==gridsize-1 ) || ( j==0 ) || ( j==gridsize-1 ) )
		{
			GRID[i][j] = GRID_WALL;		 
			shape    = new THREE.BoxGeometry ( squaresize, BOXHEIGHT, squaresize );			 
			thecube  = new THREE.Mesh( shape );
			thecube.material = new THREE.MeshBasicMaterial( { map: wall_texture } );
			
			thecube.position.copy ( translate(i,j) ); 		  	// translate my (i,j) grid coordinates to three.js (x,y,z) coordinates 
			ABWorld.scene.add(thecube);
		}
		else 
   			GRID[i][j] = GRID_BLANK;

		
   // set up maze 
    for ( var c=0 ; c < NOBOXES ; c++ )
	{
		i = AB.randomIntAtoB(1,gridsize-2);		// inner squares are 1 to gridsize-2
		j = AB.randomIntAtoB(1,gridsize-2);
        
        // static maze
//         const arri = [22,9,26,16,27,3,12,30,22,2,27,10,7,13,29,28,11,36,18,22,11,9,4,13,6,2,28,14,4,13,26,9,37,25,32,9,15,7,21,11,5,32,12,8,34,17,31,14,16,7,19,22,32,1,9,23,2,32,26,24,38,21,13,15,27,29,28,33,19,30,5,32,36,19,36,11,16,37,4,38,7,5,31,11,10,25,2,11,27,8,21,18,15,3,21,37,12,5,16,16,18,28,13,4,4,23,9,26,31,31,5,18,12,18,36,19,3,6,10,33,16,28,1,18,26,23,25,8,24,38,9,19,7,10,10,30,10,16,7,23,31,28,23,26,2,1,36,4,11,32,3,10,2,6,12,37,38,20,28,29,9,32,9,35,8,31,22,34,12,28,11,16,21,34,29,11,25,37,22,24,21,13,7,29,9,3,25,4,15,17,14,36,37,19,21,4,8,35,17,30,37,9,30,20,32,35,1,17,33,2,3,15,15,18,24,3,22,21,3,16,3,1,19,27,8,32,14,33,20,7,24,15,24,28,10,5,14,13,28,28,20,16,31,10,30,33,15,32,23,37,11,37,22,26,32,8,16,27,14,15,19,1,7,9,20,28,27,36,38,33,8,14,17,11,27,8,27,18,7,35,9,10,2,29,10,36,27,35,2,31,12,10,13,36,2,21,21,26,22,9,11,13,3,12,27,23,23,17,21,12,18,16,11,15,30,22,18,28,22,17,16,31,14,24,31,6,37,22,22,19,21,31,28,25,23,26,21,1,6,20,28,12,18,32,27,36,8,36,11,6,24,15,5,6,31,14,27,36,15,17,10,33,19,18,22,20,37,5,12,31,8,6,11,13,36,3,36,20,21,8,24,22,6,31,12,22,9,36,5,29,38,5,9,16,6,14,38,9,19,21,28,23,9,11,34,37,12,19,12,20,29,6,16,11,12,9,11,26,24,25,9,37,31,8,25,7,16,33,1,13,22,12,36,1,6,6,31,19,1,31,38,24,28,23,22,33,28,32,32,14,32,29,16,21,37,13,33,17,20,16,11,4,8,31,21,3,6,7,25,24,34,16,1,20,2,11,23,11,38,28,24,22,16,19,19,33,37,13,28,8,38,12,33,36,10,33,34,25,34,29,38,9,37,34,30,31,29,17,2,6,21,5,37,7,35,32,9,36,5,9,3,24,12,13,30,7,18,16,33,27,3,13,19];
//         const arrj = [10,4,7,8,4,18,36,38,21,24,38,5,8,33,23,21,19,21,18,1,10,22,2,34,3,19,14,21,9,31,15,12,21,28,27,11,35,6,30,18,31,31,7,27,30,3,33,37,15,14,19,13,28,35,25,3,30,9,30,11,24,8,23,7,13,34,15,24,4,34,21,10,30,25,30,37,23,11,18,3,36,34,23,37,25,19,7,8,3,4,31,29,10,36,10,34,33,19,20,29,13,1,5,26,8,24,5,20,1,14,3,29,37,32,37,27,14,3,18,2,2,19,36,20,21,28,14,37,13,38,25,4,9,6,1,19,7,18,27,6,9,5,22,18,18,10,24,21,33,24,8,12,30,23,3,3,7,6,28,11,29,34,22,23,21,14,11,3,7,11,27,3,17,8,1,34,8,24,23,22,23,10,5,2,3,31,28,3,11,29,31,29,2,35,37,8,16,12,11,9,8,32,28,8,9,5,18,20,13,2,36,14,12,3,16,24,25,22,35,8,17,25,6,9,22,20,9,3,12,10,2,33,20,24,27,12,8,8,6,1,25,27,11,13,28,22,25,1,35,30,30,27,6,10,32,3,23,29,10,12,23,25,13,35,11,28,14,18,17,37,18,32,9,3,7,24,21,27,22,7,29,3,5,14,37,8,36,20,37,7,12,25,3,37,1,6,30,3,5,19,26,3,25,38,27,2,15,8,37,10,29,22,34,18,33,20,29,19,24,21,32,11,9,1,38,12,17,28,36,30,28,24,22,37,2,34,19,18,37,11,2,4,31,7,31,30,19,18,35,21,12,4,3,22,31,2,15,4,34,34,10,8,24,27,17,11,34,21,11,6,12,36,10,29,28,28,20,15,6,22,31,27,35,16,17,16,31,21,31,36,7,22,3,9,33,7,27,30,35,36,23,14,7,22,19,10,28,3,20,7,20,6,29,7,29,27,33,11,14,31,14,4,22,12,29,36,12,4,10,13,9,3,14,22,38,7,17,19,9,21,37,24,8,1,22,25,27,13,21,38,26,5,17,33,8,38,11,33,36,15,9,17,25,16,34,23,16,5,28,31,36,1,31,20,1,23,29,19,15,33,9,19,30,5,33,5,22,11,23,4,26,7,21,27,15,8,34,4,27,7,38,3,25,26,17,27,18,6,25,33,34,19,4,35,4,10,15,23,19,10,11,23,29,12,34,17,11,34,18,35,33,29,27];
        
// 		i = arri[c];
// 		j = arrj[c];
		
		GRID[i][j] = GRID_MAZE ;
		
		shape    = new THREE.BoxGeometry ( squaresize, BOXHEIGHT, squaresize );			 
		thecube  = new THREE.Mesh( shape );
		thecube.material = new THREE.MeshBasicMaterial( { map: maze_texture } );		  

		thecube.position.copy ( translate(i,j) ); 		  	// translate my (i,j) grid coordinates to three.js (x,y,z) coordinates 
		ABWorld.scene.add(thecube);		
	}

   
	// set up enemy 
	// start in random location
	
	 do
	 {
	  i = AB.randomIntAtoB(1,gridsize-2);
	  j = AB.randomIntAtoB(1,gridsize-2);
	 }
	 while ( occupied(i,j) );  	  // search for empty square 
	 
	 ei = i;
	 ej = j;
	 
	 shape    = new THREE.BoxGeometry ( squaresize, BOXHEIGHT, squaresize );			 
	 theenemy = new THREE.Mesh( shape );
 	 theenemy.material =  new THREE.MeshBasicMaterial( { map: enemy_texture } );
	 ABWorld.scene.add(theenemy);
	 drawEnemy();

	 
	
	// set up agent 
	// start in random location
	
	 do
	 {
	  i = AB.randomIntAtoB(1,gridsize-2);
	  j = AB.randomIntAtoB(1,gridsize-2);
	 }
	 while ( occupied(i,j) );  	  // search for empty square 
 
     ai = i;
	 aj = j;
 
	 shape    = new THREE.BoxGeometry ( squaresize, BOXHEIGHT, squaresize );			 
	 theagent = new THREE.Mesh( shape );
	 theagent.material =  new THREE.MeshBasicMaterial( { map: agent_texture } );
	 ABWorld.scene.add(theagent);
	 drawAgent();

  // finally skybox 
  // setting up skybox is simple 
  // just pass it array of 6 URLs and it does the asych load 
  
  	 ABWorld.scene.background = new THREE.CubeTextureLoader().load ( SKYBOX_ARRAY, 	function() 
	 { 
		ABWorld.render(); 
	 
		AB.removeLoading();
	
		AB.runReady = true; 		// start the run loop
	 });
 		
}
 
 
 


// --- draw moving objects -----------------------------------


function drawEnemy()		// given ei, ej, draw it 
{
	theenemy.position.copy ( translate(ei,ej) ); 		  	// translate my (i,j) grid coordinates to three.js (x,y,z) coordinates 

	ABWorld.lookat.copy ( theenemy.position );	 		// if camera moving, look back at where the enemy is  
}


function drawAgent()		// given ai, aj, draw it 
{
	theagent.position.copy ( translate(ai,aj) ); 		  	// translate my (i,j) grid coordinates to three.js (x,y,z) coordinates 

	ABWorld.follow.copy ( theagent.position );			// follow vector = agent position (for camera following agent)
}

// --- take actions -----------------------------------

function moveLogicalEnemy()
{ 
    let start = new Node(ei, ej);
    let target = new Node(ai, aj);
    
    AStar(start, target);
    // BFS(start, target);
    
}


function moveLogicalAgent( a )			// this is called by the infrastructure that gets action a from the Mind 
{ 
 var i = ai;
 var j = aj;		 

      if ( a == ACTION_LEFT ) 	i--;
 else if ( a == ACTION_RIGHT ) 	i++;
 else if ( a == ACTION_UP ) 		j++;
 else if ( a == ACTION_DOWN ) 	j--;

 if ( ! occupied(i,j) ) 
 {
  ai = i;
  aj = j;
 }
}




// --- key handling --------------------------------------------------------------------------------------
// This is hard to see while the Mind is also moving the agent:
// AB.mind.getAction() and AB.world.takeAction() are constantly running in a loop at the same time 
// have to turn off Mind actions to really see user key control 

// we will handle these keys: 

var OURKEYS = [ 37, 38, 39, 40 ];

function ourKeys ( event ) { return ( OURKEYS.includes ( event.keyCode ) ); }
	

function keyHandler ( event )		
{
	if ( ! AB.runReady ) return true; 		// not ready yet 

   // if not one of our special keys, send it to default key handling:
	
	if ( ! ourKeys ( event ) ) return true;
	
	// else handle key and prevent default handling:
	
	if ( event.keyCode == 37 )   moveLogicalAgent ( ACTION_LEFT 	);   
    if ( event.keyCode == 38 )   moveLogicalAgent ( ACTION_DOWN  	); 	 
    if ( event.keyCode == 39 )   moveLogicalAgent ( ACTION_RIGHT 	); 	 
    if ( event.keyCode == 40 )   moveLogicalAgent ( ACTION_UP		);   
	
	// when the World is embedded in an iframe in a page, we want arrow key events handled by World and not passed up to parent 

	event.stopPropagation(); event.preventDefault(); return false;
}





// --- score: -----------------------------------


function badstep()			// is the enemy within one square of the agent
{
 if ( ( Math.abs(ei - ai) < 2 ) && ( Math.abs(ej - aj) < 2 ) ) return true;
 else return false;
}


function agentBlocked()			// agent is blocked on all sides, run over
{
 return ( 	occupied (ai-1,aj) 		&& 
		occupied (ai+1,aj)		&&
		occupied (  ai,aj+1)		&&
		occupied (  ai,aj-1) 	);		
} 


function updateStatusBefore(a)
// this is called before anyone has moved on this step, agent has just proposed an action
// update status to show old state and proposed move 
{
 var x 		= AB.world.getState();
 AB.msg ( " Step: " + AB.step + " &nbsp; x = (" + x.toString() + ") &nbsp; a = (" + a + ") " ); 
}


function   updateStatusAfter()		// agent and enemy have moved, can calculate score
{
 // new state after both have moved
 
 var y 		= AB.world.getState();
 var score = ( goodsteps / AB.step ) * 100; 

 AB.msg ( " &nbsp; y = (" + y.toString() + ") <br>" +
// 		" Bad steps: " + badsteps + 
		"States Searched: " + TSS +
		" &nbsp; Good steps: " + goodsteps + 
		" &nbsp; Score: " + score.toFixed(2) + "% ", 2 ); 
}





AB.world.newRun = function() 
{
	AB.loadingScreen();

	AB.runReady = false;  

	badsteps = 0;	
	goodsteps = 0;

	
	if ( show3d )
	{
	 BOXHEIGHT = squaresize;
	 ABWorld.init3d ( startRadiusConst, maxRadiusConst, SKYCOLOR  ); 	
	}	     
	else
	{
	 BOXHEIGHT = 1;
	 ABWorld.init2d ( startRadiusConst, maxRadiusConst, SKYCOLOR  ); 		     
	}
	
	
	loadResources();		// aynch file loads		
							// calls initScene() when it returns 

	document.onkeydown = keyHandler;	
		 
};



AB.world.getState = function()
{
 var x = [ ai, aj, ei, ej ];
  return ( x );  
};



AB.world.takeAction = function ( a )
{
  updateStatusBefore(a);			// show status line before moves 

  moveLogicalAgent(a);

//   if ( ( AB.step % 2 ) == 0 )		// slow the enemy down to every nth step
    moveLogicalEnemy();


  if ( badstep() )  badsteps++;
  else   			goodsteps++;

   drawAgent();
   drawEnemy();
   updateStatusAfter();			// show status line after moves  


  if ( agentBlocked() )			// if agent blocked in, run over 
  {
    gameOverMessage = "Cateripe can't move"
	AB.abortRun = true;
	goodsteps = 0;			// you score zero as far as database is concerned 			 
	musicPause();
	soundAlarm();
  }

};



AB.world.endRun = function()
{
  musicPause(); 
  if ( AB.abortRun ) AB.msg ( " <br> <font color=green> <B>" + gameOverMessage + "</B> </font>   ", 3  );
  else    				AB.msg ( " <br> <font color=red> <B> Run over. </B> </font>   ", 3  );
};

 
AB.world.getScore = function()
{
    // only called at end - do not use AB.step because it may have just incremented past AB.maxSteps
    
    var s = ( goodsteps / AB.maxSteps ) * 100;   // float like 93.4372778 
    var x = Math.round (s * 100);                // 9344
    return ( x / 100 );                          // 93.44
};


 




// --- music and sound effects ----------------------------------------

var backmusic = AB.backgroundMusic ( MUSIC_BACK );

function musicPlay()   { backmusic.play();  }
function musicPause()  { backmusic.pause(); }

											 
function soundAlarm()
{
	var alarm = new Audio ( SOUND_ALARM );
	alarm.play();							// play once, no loop 
}

// -----------------My Code -------------------------------
  
class Node {
    constructor (i, j) {
        this.i = i;
        this.j = j;
        this.f = null;
        this.g = null;
        this.h = null;
        this.neighbours = null;
        this.parent = null;
    }
}

let pathline;
let dots = new Set();
let gameOverMessage = null;

let TSS = 0; // total states searched

function isWallOrMaze(i, j) {
    return GRID[i][j] == GRID_WALL || GRID[i][j] == GRID_MAZE;
}

function getNeighboursOfNode(node) {
    const neighbours = new Set();
    
    // Define the potential moves
    const moves = [
        { i: node.i - 1, j: node.j },
        { i: node.i + 1, j: node.j },
        { i: node.i, j: node.j - 1 },
        { i: node.i, j: node.j + 1 },
    ];

    // Check if each move is valid and not a wall or maze
    for (const move of moves) {
        const { i, j } = move;
        if (!isWallOrMaze(i, j)) {
            neighbours.add(new Node(i, j));
        }
    }

    return neighbours;
}

function hCost (a, b) {
    // Return the Manhattan Distance between a & b
    return Math.abs(a.i - b.i) + Math.abs(a.j - b.j);
}

function makeNextMove(node) {
    // Initialise the path list
    const path = []
    
    // Through backwards propogation make the path
    while (node) {
        path.push(node);
        node = node.parent;
    }
    
    // Second to last element in path is the next move
    let nextMove = path[path.length - 2]
    
    // Check if next move will capture the agent
    if (nextMove.i == ai && nextMove.j == aj) 
        return gameOver("You caught a Caterpie!");
    
    // Clear the old path from the world
    if (pathline) {
        ABWorld.scene.remove(pathline);
        pathline = null;
    }
    
    // Move our guy
    ei = nextMove.i;
    ej = nextMove.j;
    
    // Draw the path between our guy and agent
    path.pop();
    drawPath(path);
}

function drawPath(path) {
    // Create a line with the path vertices
    const lineGeometry = new THREE.BufferGeometry();
    const lineVertices = [];

    // Add the vertices of the line based on the path
    for (const node of path) {
        const position = translate(node.i, node.j);
        lineVertices.push(position.x, position.y + BOXHEIGHT / 2, position.z); 
    }

    lineGeometry.setAttribute('position', new THREE.Float32BufferAttribute(lineVertices, 3));
    const lineMaterial = new THREE.LineBasicMaterial({ color: 0x0000ff }); 

    const line = new THREE.Line(lineGeometry, lineMaterial);

    ABWorld.scene.add(line);
    
    // For reference when clearing 
    pathline = line;
}

function drawDots(points, color) {
    // Create a sphere for each point and add to the world
    for (const point of points) {
        const sphereGeometry = new THREE.SphereGeometry(squaresize / 4, 10, 10); // Adjust size and resolution as needed
        const sphereMaterial = new THREE.MeshBasicMaterial({ color }); // Specify color
    
        const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        const {x, y, z} = translate(point.i, point.j);
        sphere.position.set(x, y, z); // Set the position of the sphere
    
        // Add the dot to the scene
        ABWorld.scene.add(sphere);
        
        // Add the dot to the set for reference 
        dots.add(sphere);
    }
}

function clearDots() {
    // For remove each value in dots set from the world
    for (const dot of dots) {
        ABWorld.scene.remove(dot);
        dots.delete(dot);
    }
}

function gameOver (msg) {
    // Set the game over messasge
	gameOverMessage = msg;
	
    AB.abortRun = true;
	goodsteps = 0;
	musicPause();
	soundAlarm();
}

function AStar(start, target) {
    // Initialise the open and closed list
    let open = [];
    let closed = [];
    
    // Push the start node to open
    open.push(start);
    
    // Repeat until open list empty or found target
    while (open.length > 0) {
        let current = null;
        
        // set current to the node with lowest f
        for (const node of open) 
            if (!current || node.f < current.f) 
                current = node;
                
        // Remove current from open
        open.splice(open.indexOf(current), 1);   
        
        // If current is equal to the target then target found! Make next move
        if (current.i == target.i && current.j == target.j) {
            // Clear previous dots before drawing new Dots
            clearDots();
            drawDots(open, 0x00ff00);
            drawDots(closed, 0xff0000);
            
            TSS += closed.length;
            
            return makeNextMove(current);
        }
        
        // Push current to closed
        closed.push(current);  // add current to closed
        
        // Fetch the neighbours of current
        current.neighbours = getNeighboursOfNode(current);
        
        // For each neighbour of current
        for (const neighbour of current.neighbours) {
            // Skip if neighbour is already in closed set
            if (closed.find((val) => val.i == neighbour.i && val.j == neighbour.j))  
                continue;
            
            // Calculate g for the neighbour    
            let g = current.g + 1;
            
            // If new g is less than old g or neighbour is not in open set
            if (g < neighbour.g || !open.find((val) => val.i == neighbour.i && val.j == neighbour.j)) {
                neighbour.parent = current;
                neighbour.g = g
                neighbour.h = hCost(neighbour, target);
                neighbour.f = neighbour.g + neighbour.h;
                open.push(neighbour);
            }
        }
    }
    
    // If no solution
    return gameOver("Sighs.. no way to the caterpie");
}
		
function BFS(start, target) {
    // Initialise the queue and visited list
    const queue = [];
    const visited = [];
    
    // Push the start node to queue
    queue.push(start);
    
    // Repeat uptil queue is empty or target found
    while(queue.length > 0) {
        // Pop the next value from the queue to current
        const current = queue.shift();
        
        // If current is equal to the target then target found! Make next move
        if (current.i == target.i && current.j == target.j) {
            // Clear previous dots before drawing new Dots
            clearDots();
            drawDots(queue, 0x00ff00);
            drawDots(visited, 0xff0000);
            
            TSS += visited.length;
            
            return makeNextMove(current);
        }
        
        // Check if current is not in visited list
        if (!visited.find((val) => val.i == current.i && val.j == current.j)) {
            // Fetch the neighbours of current
            current.neighbours = getNeighboursOfNode(current);
            
            // Push current to visited
            visited.push(current);
            
            // For each neighbour of current
            for (const neighbour of current.neighbours) {
                // Push neighbours to queue if they don't exist
                if (!visited.find((val) => val.i == neighbour.i && val.j == neighbour.j)) {
                    neighbour.parent = current;
                    queue.push(neighbour);
                }
            }
        }
    }
    
    // If no solution
    return gameOver("Sighs.. no way to the caterpie");
}