Code viewer for World: Banana Island
//Author: Adeyemi Adebanjo, Adeyemi.adebanjo2@mail.dcu.ie, 20215012, MCM1

// Cloned by Rock on 9 Nov 2020 from World "Complex World" by Starter user 
// Please leave this clone trail here.
 


// =============================================================================================
// 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.
// =============================================================================================


AB.clockTick       = 100;    

	// 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/rock20/Bricktile.jpg' ;
 const TEXTURE_MAZE 	= '/uploads/rock20/Box_wood.jpg' ;
 const TEXTURE_AGENT 	= '/uploads/starter/pacman.jpg' ;
 const TEXTURE_ENEMY 	= '/uploads/starter/ghost.3.png' ;
 const TEXTURE_FLOOR 	= '/uploads/rock20/floorwood.jpg' ;    //Author: Adeyemi Adebanjo
 const TEXTURE_BRAIN	= '/uploads/rock20/brain.jpg' ;        //Author: Adeyemi Adebanjo

// 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/starter/Defense.Line.mp3' ;
	const SOUND_ALARM = '/uploads/starter/air.horn.mp3' ;

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

	
const gridsize = 50;						// number of squares along side of world	//Author: Adeyemi Adebanjo   

const guidenum = gridsize * gridsize;       // number of guides objects that exist that we can manipulate to show the path. //Author: Adeyemi Adebanjo 

const NOBOXES =  Math.trunc ( (gridsize * gridsize) / 3 );   //Author: Adeyemi Adebanjo 
		// density of maze - number of internal boxes
		

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 

// mountain skybox, credit:
// http://stemkoski.github.io/Three.js/Skybox.html

/*
 const SKYBOX_ARRAY = [										 
                "/uploads/starter/dawnmountain-xpos.png",
                "/uploads/starter/dawnmountain-xneg.png",
                "/uploads/starter/dawnmountain-ypos.png",
                "/uploads/starter/dawnmountain-yneg.png",
                "/uploads/starter/dawnmountain-zpos.png",
                "/uploads/starter/dawnmountain-zneg.png"
                ];
*/

// space skybox, credit:
// http://en.spaceengine.org/forum/21-514-1
// x,y,z labelled differently

/*
 const SKYBOX_ARRAY = [										 
                "/uploads/starter/sky_pos_z.jpg",
                "/uploads/starter/sky_neg_z.jpg",
                "/uploads/starter/sky_pos_y.jpg",
                "/uploads/starter/sky_neg_y.jpg",
                "/uploads/starter/sky_pos_x.jpg",
                "/uploads/starter/sky_neg_x.jpg"
                ];
			*/


// urban photographic skyboxes, credit:
// http://opengameart.org/content/urban-skyboxes


 const SKYBOX_ARRAY = [										 
                "/uploads/starter/posx.jpg",
                "/uploads/starter/negx.jpg",
                "/uploads/starter/posy.jpg",
                "/uploads/starter/negy.jpg",
                "/uploads/starter/posz.jpg",
                "/uploads/starter/negz.jpg"
                ];




// ===================================================================================================================
// === End of 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 guideObjects = []; // the guide objects  //Author: Adeyemi Adebanjo 

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


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

var badsteps;
var goodsteps;

// The last position of the agent, used to determine if its stuck. //Author: Adeyemi Adebanjo 
var last_ai = 0;
var last_aj = 0;
var playerStuckCounter = 0;  // How many steps the agent has been in the same place

	
function loadResources()		// asynchronous file loads - call initScene() when all finished. //Author: Adeyemi Adebanjo
{
	var loader1 = new THREE.TextureLoader();
	var loader2 = new THREE.TextureLoader();
	var loader3 = new THREE.TextureLoader();
	var loader4 = new THREE.TextureLoader();
	var loader5 = new THREE.TextureLoader();
	var loader6 = 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();		 
	});
	
    loader5.load ( TEXTURE_FLOOR, function ( thetexture )  
	{
		thetexture.minFilter  = THREE.LinearFilter;
		floor_texture = thetexture;
		if ( asynchFinished() )	initScene();		 
	});
	
	loader6.load ( TEXTURE_BRAIN, function ( thetexture )  
	{
		thetexture.minFilter  = THREE.LinearFilter;
		brain_texture = thetexture;
		if ( asynchFinished() )	initScene();		 
	});
	
}

function asynchFinished()		 // all file loads returned. //Author: Adeyemi Adebanjo 
{
	if ( wall_texture && agent_texture && enemy_texture && maze_texture && floor_texture && brain_texture)   return true; 
	else return false;
}	

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

	
function occupied ( i, j )		// is this square occupied by obstacles, or enitites  //Author: Adeyemi Adebanjo 
{
    if ( ( ei == i ) && ( ej == j ) ) return true;		// variable objects 
    if ( ( ai == i ) && ( aj == j ) ) return true;
    
    return occupiedByWall(i, j);
}

function occupiedByWall(i, j)   // is this square occupied by maze walls     //Author: Adeyemi Adebanjo 
{
    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  //Author: Adeyemi Adebanjo 
{
	 var i,j, shape, thecube, material;
	 
	 // set up GRID as 2D array
	 for ( i = 0; i < gridsize ; i++ )
	 {
		GRID[i] = new Array(gridsize);
	 }
	 
	 // Create lights
	 
	 // Create a white ambient light
	var color = 0xFFFFFF;
    var intensity = 0.4;
    var light = new THREE.AmbientLight(color, intensity);
    ABWorld.scene.add(light);
    
    // Create a white directional light
    // Enable shadows for the light.
    // The position is important as this is where the shadow map camera will be placed
    // I used the shadows in the skybox to roughly determine the direction of the light
    intensity = 0.8;
    light = new THREE.DirectionalLight(color, intensity);
    light.position.set(0, 1000, 2000);
    light.target.position.set(0, 0, 0);
    light.castShadow = true;
    ABWorld.scene.add(light);
    ABWorld.scene.add(light.target);
    
    // Set up shadowmap texture size
    light.shadow.mapSize.width = 1024;
    light.shadow.mapSize.height = 1024;
    
    // Shadow camera frustum values
    // We need these to be big enough to cover the objects in the scene
    light.shadow.camera.left = -2500;
    light.shadow.camera.right = 2500;
    light.shadow.camera.top = 2500;
    light.shadow.camera.bottom = -2500;
    light.shadow.camera.near = 0.5;
    light.shadow.camera.far = 5000;
    ABWorld.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    ABWorld.renderer.shadowMap.enabled = true;

    // Only create box geometry once, not for every single onbject
	shape = new THREE.BoxGeometry ( squaresize, BOXHEIGHT, squaresize );
    material = new THREE.MeshPhongMaterial({ map: wall_texture } );
	// 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;
			thecube  = new THREE.Mesh( shape, material );
			thecube.castShadow = true;
			thecube.receiveShadow = true;
			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
		}

		
    // Only create the shape and material once, not for each box
    material = new THREE.MeshPhongMaterial({ map: maze_texture } );
			
   // set up maze 
    for ( var c=1 ; c <= NOBOXES ; c++ )
	{
		i = AB.randomIntAtoB(1,gridsize-2);		// inner squares are 1 to gridsize-2
		j = AB.randomIntAtoB(1,gridsize-2);
			
		GRID[i][j] = GRID_MAZE ;
		
		thecube  = new THREE.Mesh( shape,  material);
		thecube.castShadow = true;
        thecube.receiveShadow = true;
		thecube.position.copy ( translate(i,j) ); 		  	// translate my (i,j) grid coordinates to three.js (x,y,z) coordinates 
		ABWorld.scene.add(thecube);
	}
	
	
	shape = new THREE.SphereGeometry( 10, 12, 12 );
	
	// set up guide objects
	// As I dont know how many will be used to draw the path,
	// I create an array so that stores a number of the guide objects.
	// We set them all to invisible and then just use what we need
	for ( var g = 0; g < guidenum; g++ ) 
	{
	    			 
		var guide  = new THREE.Mesh( shape );
		
		guide.material = new THREE.MeshBasicMaterial({
            color: 0x00FF00,
            opacity: 0.5,
            transparent: true,
          });
          
		guide.position.copy ( translate(0, 0) ); 		  	// translate my (i,j) grid coordinates to three.js (x,y,z) coordinates
		guide.scale.x = 1.0;
		guide.scale.y = 1.0;
		guide.scale.z = 1.0;

		guide.visible = false;
		guideObjects.push(guide);
		ABWorld.scene.add(guide);
	}
	
	shape  = new THREE.BoxGeometry ( squaresize, BOXHEIGHT, squaresize );
   
	// 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;
	 
	 theenemy = new THREE.Mesh( shape );
 	 theenemy.material =  new THREE.MeshPhongMaterial( { map: brain_texture, } );
 	 theenemy.receiveShadow = true;
 	 theenemy.castShadow = true;
	 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;
 
	 theagent = new THREE.Mesh( shape );
	 theagent.material =  new THREE.MeshPhongMaterial( { map: agent_texture } );
	 theagent.receiveShadow = true;
	 theagent.castShadow = true;
	 ABWorld.scene.add(theagent);
	 drawAgent(); 
	 
	// Create floor
	shape    = new THREE.PlaneGeometry ( squaresize * gridsize, squaresize * gridsize, 1 );			 
	thefloor  = new THREE.Mesh( shape );
	thefloor.material = new THREE.MeshPhongMaterial( { map: floor_texture } );
    thefloor.receiveShadow = true;                  // The floor should receive shadows
	thefloor.rotation.x = -Math.PI / 2;             // Rotate 90 degrees so it faces upward
	thefloor.position.x = -squaresize/2;
	thefloor.position.z = -squaresize/2;
	thefloor.position.y = -BOXHEIGHT/2;
	ABWorld.scene.add(thefloor);
	
	// We want the texture to tile accross the floor, not be stretched, so 
	// we set the texture wrapping to use RepeatWrapping and set the repeat to be a large number
	floor_texture.wrapS = THREE.RepeatWrapping;
    floor_texture.wrapT = THREE.RepeatWrapping;
    floor_texture.repeat.set( gridsize / 2, gridsize / 2 ); // Using the grid size to determine the wrapping means it will work when someone edits the grid

  // 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 -----------------------------------

// Draws the guide path to show the A* algorithm working
function drawPath(path)    //Author: Adeyemi Adebanjo 
{
    // Set all the guide objects to invisible
    for(var g = 0; g < guideObjects.length; g++)
    {
       guideObjects[g].visible = false;
    }
    
    var guideIndex = 0;
    
    for(var i = 0; i < path.length; i++)
    {
        if(i + 1 < path.length)
        {
            // Get the position of the current node, and the next node
            var position1 = translate(path[i].i, path[i].j);
            var position2 = translate(path[i+1].i, path[i+1].j);
            
            // Create a direction vector that points from position 1 to position 2
            var direction = new THREE.Vector3(position2.x - position1.x, position2.y - position1.y, position2.z - position1.z);
            var guidePosition = new THREE.Vector3();
            
            // Draw several boxes in between the positions, so it looks like a line
            for(var c = 0; c < 10; c++)
            {
                // Only use the guide objects we have. We should have enough,
                // but just want to check to be sure. 
                if(guideIndex < guideObjects.length)
                {
                    guideObjects[guideIndex].visible = true;
                    guidePosition.x = position1.x + (direction.x * (c / 10));
                    guidePosition.y = BOXHEIGHT - 45;
                    guidePosition.z = position1.z + (direction.z * (c / 10));
                    guideObjects[guideIndex].position.copy ( guidePosition ); 
                    guideIndex++;
                }
            }
        }
    }
}

function drawEnemy()		// given ei, ej, draw the enemy
{
	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 that returns true if the position is next to the player
// Diagonals are included
function isNextToPlayer(i, j)     //Author: Adeyemi Adebanjo
{
    if(Math.abs(i - ai) <= 1 && Math.abs(j - aj) <= 1)
    {
        return true;
    }
    
    return false;
}

// Array containing the offsets needed for the 8 surrounding tiles of a tile.    //Author: Adeyemi Adebanjo 
var neighborPositions = [{i:-1, j:-1}, {i:1, j:-1}, {i:1, j:1}, {i:-1, j:1}, {i:0, j:1}, {i:0, j:-1}, {i:1, j:0}, {i:-1, j:0}];

// Randomly moves the enemy towards the agent.  //Author: Adeyemi Adebanjo 
function moveLogicalEnemy()    
{ 
    // Use A* to find the best path towards the player
    var path = createAStarPath(ei, ej, ai, aj);

    // If the path length is larger than 0 and the first step isnt the agents position, move the enemy there
    // (We do this because we dont want to move the enemy onto the players square)
    if(path.length > 0 && !(path[0].i == ai && path[0].j == aj))
    {
        ei = path[0].i;
        ej = path[0].j;
    }
    else
    {
        // The enemy has essentially reached the target (a space next to player) and isnt 'stuck' yet
        // The enemy can wait for the player to move, but as the goal of the enemy is to block the player in,
        // I found it works better if the enemy moves to squares next to the player. This seems to help us block the player in, 
        // or force something to happen. What square we check first is set to be random, so the enemy doesnt always choose the same spot
        // If a square cant be found next to the player that isnt occupied, the enemy will just stay in its current position
        var testedPositionNum = 0;
        var enemyMoved = false;
        
        // Generate a random number between 0 and 7
        var index = Math.floor(Math.random() * 8);
    
        while(!enemyMoved && testedPositionNum != 7)
        {
            // Get the position to test near the enemy
            var ei_test = ei + neighborPositions[index].i;
            var ej_test = ej + neighborPositions[index].j;
            
            // Only move to an nearby square if its not occupied and the square is next to the player
            if(!occupied(ei_test, ej_test) && isNextToPlayer(ei_test, ej_test))
            {
                ei = ei_test;
                ej = ej_test;
                enemyMoved = true; // Just so we dont make more than one move per turn
            }
            
            // Keep track of how many positions weve tested
            testedPositionNum++;
            
            // Increase index to look at next position
            index++;
            if(index > 7)
            {
                index = 0;
            }
        }
        
        // Check if the player has been stuck in the same position for a while
        // This may indicate the player and enemy are in a state where the enemy is just moving to neaby tiles and not allowing the player to do anything
        // This is rare but when it happens it just means the game will come to a halt and time out until the step limit is hit
        // In order to force something to happen, it would be beneficial in this case to move the enemy away from the player
        // We only check if the player has been stuck when the enemy is touching it, as it can easily get stuck when we are moving towards it.
        
        if(isNextToPlayer(ei, ej))
        {
            if(ai == ai_last && aj == aj_last)
            {
                playerStuckCounter++;
            }
            else 
            {
                playerStuckCounter = 0;
            }
            
            
            // If there has been 10 steps where the player has been in the same place while the enemy is on an adjacent tile, I consider it stuck.
            if(playerStuckCounter > 10)
            {
                console.log("STUCK");
                // Try to move enemy to square thats not touching the player
                // The first square we check is random so that we add some unpredictability into the enemy
                
                // Generate a random number between 0 and 7
                var index = Math.floor(Math.random() * 8);
                var enemyMoved = false;
            
                while(!enemyMoved && testedPositionNum != 7)
                {
                    // Get the position to test near the enemy
                    var ei_test = ei + neighborPositions[index].i;;
                    var ej_test = ej + neighborPositions[index].j;
                    
                    // Only move to an nearby square if its not occupied and the square is next to the player
                    if(!occupied(ei_test, ej_test) && !isNextToPlayer(ei_test, ej_test))
                    {
                        ei = ei_test;
                        ej = ej_test;
                        enemyMoved = true; // Just so we dont make more than one move per turn
                    }
                    
                    // Keep track of how many positions we've tested
                    testedPositionNum++;
                    
                    // Increase index to look at next position
                    index++;
                    if(index > 7)
                    {
                        index = 0;
                    }
                }
            }
            
            // Set player stuck counter to 0, so enemy doensnt keep moving away
            playerStuckCounter = 0;
        }

        // Create guide path
        // As we are right next to the player, we just need to draw a line from the enemy to the player.
        path = [];
        path.push({i: ei, j: ej});
        path.push({i: ai, j: aj});
    }
    
    drawPath(path);
}


//Author: Adeyemi Adebanjo 
// Function that creates a node for use in the A* algorithm
// i: i grid position
// j: j grid position
// g: the g value used for the A* algorithm
// h: the heuristic value used for the A* algorithm
// parent: the parent node of the created node
function createNode(i, j, g, h, parent)
{
    var node = {};
    node.i = i;
    node.j = j;
    node.g = g;
    node.h = h;
    node.f = g + h;
    node.parent = parent;
    return node;
}


//Author: Adeyemi Adebanjo 
// Function that returns true if a node is at a specific position
function isNodeAtPosition(node, di, dj)
{
    if(node.i == di && node.j == dj)
    {
        return true;
    }
    else
    {
        return false;
    }
}


//Author: Adeyemi Adebanjo
// Gets the index of a node in the specified list
// The nodes position is used for comparison
function getIndexOfNodeInList(node, list)
{
    for(var i = 0; i < list.length; i++)
    {
        if(list[i].i == node.i && list[i].j == node.j)
        {
            return i;
        }
    }
    
    return -1;
}


//Author: Adeyemi Adebanjo 
// Removes a node from the specified list
function removeNodeFromList(node, list)
{
    var index = getIndexOfNodeInList(node, list);
    if(index != -1)
    {
        list.splice(index, 1);
    }
}


//Author: Adeyemi Adebanjo 
// Calculates the H value of a node for the A* algorithm
// Uses the euclidean distance
function calculateHValue(i, j, destinationI, destinationJ)
{
    return Math.sqrt((i - destinationI) * (i - destinationI) + (j - destinationJ) * (j - destinationJ));
}


//Author: Adeyemi Adebanjo 
// Creates a path from the node passed in
// Iterates over the nodes and their parents and creates an array of points that
// make up the path to get from the start destination to the end destination.
function createPathFromEndNode(node)
{
    var nodeList = [];
    var nextNode = node;
    while(nextNode.parent !== null)
    {
        nodeList.push({i: nextNode.i, j: nextNode.j});
        nextNode = nextNode.parent;
    }
    
    // Reverse array (as we started at end node and worked backwards)
    // This way our path will be from start location to destination.
    nodeList.reverse();
    return nodeList;
}


//Author: Adeyemi Adebanjo 
// Function that uses the A* algorithm to determine the best path from a start location
// to a destination.
function createAStarPath(startI, startJ, destinationI, destinationJ)
{ 
    // Create the open and closed list to keep track of what nodes have been processed/awaiting processing
    var openlist = [];   // Contains nodes that need to be processed
    var closedlist = []; // Contains nodes that have been processed
    
    // Create the start node and add it to the open list with a F score of 0
    var startNode = createNode(startI, startJ, 0, 0, null);
    openlist.push(startNode);
    
    // Iterate through the open list
    // If no nodes are left in the openlist, then a path could not be found
    while(openlist.length > 0)
    {
        // Get the node with the lowest f from the open list
        var currentNode = openlist[0];
        for (var i = 0; i < openlist.length; i++)
        {
            if(openlist[i].f < currentNode.f)
            {
                currentNode = openlist[i];
            }
        }
        
        // Check if this node is our destination node
        if(isNodeAtPosition(currentNode, destinationI, destinationJ))
        {
            // Reached the destination, create a path and return it
            return createPathFromEndNode(currentNode);
        }
        else
        {
            // Remove the current node from open list
            removeNodeFromList(currentNode, openlist);

            // Put the current node in the closed list
            // Then check the neighbor nodes
            closedlist.push(currentNode);
            
            // Create the neighbor nodes
            var neighbors = [];
            for(var x = -1; x <= 1; x++)
            {
                for(var y = -1; y <= 1; y++)
                {
                    // We dont want to create a node for 0,0 because this will be the same position as the current node
                    if((x === 0 && y === 0) === false) 
                    {
                        var neighborNode = createNode(currentNode.i + x, currentNode.j + y, currentNode.g + 1, calculateHValue(currentNode.i + x, currentNode.j + y, destinationI, destinationJ), currentNode);
                        neighbors.push(neighborNode);
                    }
                }
            }
            
            // Iterate through the neighbor nodes
            for(var n = 0; n < neighbors.length; n++)
            {
                var closedlistIndex = getIndexOfNodeInList(neighbors[n], closedlist);
                var openlistIndex = getIndexOfNodeInList(neighbors[n], openlist);
                    
                // Only process this neighbor node if is not an obstacle and not on the closed list
                if(occupiedByWall(neighbors[n].i, neighbors[n].j) || closedlistIndex != -1)
                {
                    continue;
                }
                
                // If this neighbor node is not on the open list, add it to the open list so it will be processed
                if(openlistIndex == -1)
                {
                    openlist.push(neighbors[n]);
                }
                else
                {
                    // A node with this position already exists in the open list and is waiting to be processed
                    // Check to see if g is lower, as this indicates a better path
                    // If it is, we should update the node in the open list with the new G value, and set its parent to be the current node.
                    if(neighbors[n].g < openlist[openlistIndex].g)
                    {
                        // update the node in the open list with the new value of g, and set its parent to be the current node
                        openlist[openlistIndex].g = neighbors[n].g;
                        openlist[openlistIndex].f = openlist[openlistIndex].g + openlist[openlistIndex].h;
                        openlist[openlistIndex].parent = currentNode;
                    }
                }
            }
        }
    }
    
    // We didnt find a path, so just return an empty one
    return [];
}

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;
 }
 
 //Author: Adeyemi Adebanjo 
 ai_last = ai;
 aj_last = aj;
}



// --- 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 + 
		" &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 
  {
	AB.abortRun = true;
	goodsteps = 0;
	musicPause();
	soundAlarm();
  }

};


AB.world.endRun = function()
{
  musicPause(); 
  if ( AB.abortRun )
  {
      if(agentBlocked())
      {
          AB.msg ( " <br> <font color=red> <B> Agent trapped by Enemy. Final score zero. </B> </font>   ", 3  );
      }

  }
  else 
  {
      AB.msg ( " <br> <font color=green> <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 
}