Code viewer for World: Assignment Submission - AI...





























// =============================================================================================
// More complex starter World for WWM
// 3d-effect Maze World (really a 2-D problem)
// Mark Humphrys, 2016.
//
// 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.
//
// Scoring on the server side is done by taking average of n runs.
// Runs where you get trapped and score zero can seriously affect this score. 
// =============================================================================================






// World must define these:
 
const	 	CLOCKTICK 	= 100;					// speed of run - move things every n milliseconds
const		MAXSTEPS 	= 300;	
var         enemiesLeft = 5; // length of a run before final score

 
const  SCREENSHOT_STEP = 50;    





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

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

const NOBOXES =  Math.trunc ( (gridsize * gridsize) / 40 );
		// 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 BLANKCOLOR 	= SKYCOLOR ;			// make objects this color until texture arrives (from asynchronous file read)




const show3d = true;						// Switch between 3d and 2d view (both using Three.js) 
 
const startRadiusConst	 	= MAXPOS * 0.8 ;		// distance from centre to start the camera at
const skyboxConst			= MAXPOS * 3 ;		// where to put skybox 
const maxRadiusConst 		= MAXPOS * 10  ;		// maximum distance from camera we will render things  





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




 
// --- some useful random functions  -------------------------------------------


function randomfloatAtoB ( A, B )			 
{
 return ( A + ( Math.random() * (B-A) ) );
}

function randomintAtoB ( A, B )			 
{
 return  ( Math.round ( randomfloatAtoB ( A, B ) ) );
}
  
function randomBoolean()			 
{
 if ( Math.random() < 0.5 ) { return false; }
 else { return true; }
}







//---- start of World class -------------------------------------------------------
 
function World() { 


// most of World can be private 
// regular "var" syntax means private variables:


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 WALLS 	= new Array ( 4 * gridsize );		// need to keep handles to wall and maze objects so can find them later to paint them 
var MAZE 	= new Array ( NOBOXES );
var theenemy,player1,player2;
  

// enemy and agent position on squares
var ei, ej, ai, aj, ci,cj,di,dj,fi,fj,gi,gj;

var badsteps;
var goodsteps;
var  step;

 	var self = this;						// needed for private fn to call public fn - see below  

 


// regular "function" syntax means private functions:


function initGrid()
{
 for (var i = 0; i < gridsize ; i++) 
 {
  GRID[i] = new Array(gridsize);		// each element is an array 

  for (var j = 0; j < gridsize ; j++) 
  {
   GRID[i][j] = GRID_BLANK ;
  }
 }
}

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;
}

 
// 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 ( x ) 
{
 return ( x - ( MAXPOS/2 ) );
}





//--- skybox ----------------------------------------------------------------------------------------------


function initSkybox() 
{

// x,y,z positive and negative faces have to be in certain order in the array 
 
// mountain skybox, credit:
// http://stemkoski.github.io/Three.js/Skybox.html

  
 	
   var materialArray = [
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/starter/dawnmountain-xpos.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/starter/dawnmountain-xneg.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/starter/dawnmountain-ypos.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/starter/dawnmountain-yneg.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/starter/dawnmountain-zpos.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/starter/dawnmountain-zneg.png" ), side: THREE.BackSide } ) )
 	];
 	

  var skyGeometry = new THREE.CubeGeometry ( skyboxConst, skyboxConst, skyboxConst );	
  var skyMaterial = new THREE.MeshFaceMaterial ( materialArray );
  var theskybox = new THREE.Mesh ( skyGeometry, skyMaterial );
  threeworld.scene.add( theskybox );						// We are inside a giant cube
}








function loadTextures()
{

 var loader1 = new THREE.TextureLoader();
 loader1.load ( '/uploads/starter/door.jpg',		function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		paintWalls ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
	} ); 

 var loader2 = new THREE.TextureLoader();
 loader2.load ( '/uploads/starter/latin.jpg',		function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		paintMaze ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
 	} ); 


 var loader3 = new THREE.TextureLoader();
 loader3.load ( '/uploads/bouldersoshoulders/on.jpg',	function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		theenemy.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
	} ); 
	
 var loader4 = new THREE.TextureLoader();
 loader4.load ( '/uploads/bouldersoshoulders/capture.jpg',	function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		player1.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
	} ); 

 var loader5 = new THREE.TextureLoader();
 loader5.load ( '/uploads/bouldersoshoulders/capture.jpg',	function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		player2.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
	} ); 
 var loader6 = new THREE.TextureLoader();
 loader6.load ( '/uploads/bouldersoshoulders/capture.jpg',	function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		player3.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
	} ); 
	
 var loader7 = new THREE.TextureLoader();
 loader7.load ( '/uploads/bouldersoshoulders/capture.jpg',	function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		player4.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
	} ); 
	
 var loader8 = new THREE.TextureLoader();
 loader8.load ( '/uploads/bouldersoshoulders/capture.jpg',	function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		player5.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
	} ); 

}


 


// --- add fixed objects ---------------------------------------- 
   
 
function initLogicalWalls()		// set up logical walls in data structure, whether doing graphical run or not	
{
 for (var i = 0; i < gridsize ; i++) 
  for (var j = 0; j < gridsize ; j++) 
   if ( ( i===0 ) || ( i==gridsize-1 ) || ( j===0 ) || ( j==gridsize-1 ) )
   {
    	GRID[i][j] = GRID_WALL ;		 
   }
}


function initThreeWalls()		// graphical run only, set up blank boxes, painted later 	
{
 var t = 0;
 for (var i = 0; i < gridsize ; i++) 
  for (var j = 0; j < gridsize ; j++) 
   if ( GRID[i][j] == GRID_WALL )
   {
 	 var shape    = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );			 
 	 var thecube  = new THREE.Mesh( shape );
	 thecube.material.color.setHex( BLANKCOLOR  );			  
 
    	 thecube.position.x = translate ( i * squaresize );   		// translate my simple (i,j) block-numbering coordinates to three.js (x,y,z) coordinates 
    	 thecube.position.z = translate ( j * squaresize );   	
    	 thecube.position.y =  0;	
 
 	 threeworld.scene.add(thecube);
	 WALLS[t] = thecube;				// save it for later
	 t++; 
   }
}


function paintWalls ( material )		 
{
 for ( var i = 0; i < WALLS.length; i++ )
 { 
   if ( WALLS[i] )  WALLS[i].material = material;
 }
}





function initLogicalMaze()		 
{
 for ( var c=1 ; c <= NOBOXES ; c++ )
 {
  	var i = randomintAtoB(1,gridsize-2);	// inner squares are 1 to gridsize-2
  	var j = randomintAtoB(1,gridsize-2);
    	GRID[i][j] = GRID_MAZE ;		 
 }
}


function initThreeMaze()		  	
{
 var t = 0;
 for (var i = 0; i < gridsize ; i++) 
  for (var j = 0; j < gridsize ; j++) 
   if ( GRID[i][j] == GRID_MAZE )
   {
   	var shape    = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );			 
  	var thecube  = new THREE.Mesh( shape );
	thecube.material.color.setHex( BLANKCOLOR  );			  

  	thecube.position.x = translate ( i * squaresize );   	
  	thecube.position.z = translate ( j * squaresize );   	
  	thecube.position.y =  0;	
 
 	threeworld.scene.add(thecube);
	MAZE[t] = thecube;		// save it for later
	t++; 
   }
}


function paintMaze ( material )		 
{
 for ( var i = 0; i < MAZE.length; i++ )
 { 
   if ( MAZE[i] )  MAZE[i].material = material;
 }
}





// --- Player1 functions -----------------------------------


function drawPlayer1()	// given ei, ej, draw it 
{
  var x = translate ( ai * squaresize );   	
  var z = translate ( aj * squaresize );   	
  var y =  0;	

 player1.position.x = x;
 player1.position.y = y;
 player1.position.z = z;
 threeworld.scene.add(player1);

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


function initLogicalPlayer1()
{
// start in random location:
 var i, j;
 do
 {
  i = randomintAtoB(1,gridsize-2);
  j = randomintAtoB(1,gridsize-2);
 }
 while ( occupied(i,j) );  	  // search for empty square 

 ai = i;
 aj = j;
}


function initThreePlayer1()
{
 var shape    = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );			 
 player1 = new THREE.Mesh( shape );
 player1.material.color.setHex( BLANKCOLOR  );	
 drawPlayer1();		  
}


function moveLogicalPlayer1()
{ 
 var i = ai;
 var j = aj;

 if ( ai > ei ) i = randomintAtoB(ai, ai+1); 
 if ( ai == ei ) i = ei; 
 if ( ai < ei ) i = randomintAtoB(ai-1, ai); 

 if ( aj > ej ) j = randomintAtoB(aj, aj+1); 
 if ( aj == ej ) j = aj; 
 if ( aj < ej ) j = randomintAtoB(aj-1, aj);  
 if ( ! occupied(i,j) )  	// if no obstacle then move, else just miss a turn
 {
  ai = i;
  aj = j;
 }
}


// ------------- player 2 ----------------------------

function drawPlayer2()	// given ei, ej, draw it 
{
  var x = translate ( ci * squaresize );   	
  var z = translate ( cj * squaresize );   	
  var y =  0;	

 player2.position.x = x;
 player2.position.y = y;
 player2.position.z = z;
 threeworld.scene.add(player2);

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


function initLogicalPlayer2()
{
 var i, j;
 do
 {
  i = randomintAtoB(1,gridsize-2);
  j = randomintAtoB(1,gridsize-2);
 }
 while ( occupied(i,j) );  	  // search for empty square 

 ci = i;
 cj = j;
}


function initThreePlayer2()
{
 var shape    = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );			 
 player2 = new THREE.Mesh( shape );
 player2.material.color.setHex( BLANKCOLOR  );	
 drawPlayer2();		  
}


function moveLogicalPlayer2()
{ 

 var i = ci;
 var j = cj;


 if ( ci > ei ) i = randomintAtoB(ci, ci+1); 
 if ( ci == ei ) i = ei; 
 if ( ci < ei ) i = randomintAtoB(ci-1, ci); 

 if ( cj > ej ) j = randomintAtoB(cj, cj+1); 
 if ( cj == ej ) j = cj; 
 if ( cj < ej ) j = randomintAtoB(cj-1, cj); 
 if ( ! occupied(i,j) )  	// if no obstacle then move, else just miss a turn
 {
  ci = i;
  cj = j;
 }
}






//-------------- player 3 --------------
function drawPlayer3()	// given ei, ej, draw it 
{
  var x = translate ( di * squaresize );   	
  var z = translate ( dj * squaresize );   	
  var y =  0;	

 player3.position.x = x;
 player3.position.y = y;
 player3.position.z = z;
 threeworld.scene.add(player3);

 threeworld.lookat.copy ( player3.position );	  
}


function initLogicalPlayer3()
{
 var i, j;
 do
 {
  i = randomintAtoB(1,gridsize-2);
  j = randomintAtoB(1,gridsize-2);
 }
 while ( occupied(i,j) );  	  // search for empty square 

 di = i;
 dj = j;
}


function initThreePlayer3()
{
 var shape    = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );			 
 player3 = new THREE.Mesh( shape );
 player3.material.color.setHex( BLANKCOLOR  );	
 drawPlayer3();		  
}


function moveLogicalPlayer3()
{ 
 var i = di;
 var j = dj;

 if ( di > ei ) i = randomintAtoB(di, di+1); 
 if ( di == ei ) i = ei; 
 if ( di < ei ) i = randomintAtoB(di-1, di); 

 if ( dj > ej ) j = randomintAtoB(dj, dj+1); 
 if ( dj == ej ) j = dj; 
 if ( dj < ej ) j = randomintAtoB(dj-1, dj);  
 if ( ! occupied(i,j) )  	// if no obstacle then move, else just miss a turn
 {
  di = i;
  dj = j;
 }
}


//-------------- player 4 -----------------------------
function drawPlayer4()	
{
  var x = translate ( fi * squaresize );   	
  var z = translate ( fj * squaresize );   	
  var y =  0;	

 player4.position.x = x;
 player4.position.y = y;
 player4.position.z = z;
 threeworld.scene.add(player4);

 threeworld.lookat.copy ( player4.position );	
}


function initLogicalPlayer4()
{
 var i, j;
 do
 {
  i = randomintAtoB(1,gridsize-2);
  j = randomintAtoB(1,gridsize-2);
 }
 while ( occupied(i,j) );  	  // search for empty square 

 fi = i;
 fj = j;
}


function initThreePlayer4()
{
 var shape    = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );			 
 player4 = new THREE.Mesh( shape );
 player4.material.color.setHex( BLANKCOLOR  );	
 drawPlayer4();		  
}


function moveLogicalPlayer4()
{ 

 var i = fi;
 var j = fj;

 if ( fi > ei ) i = randomintAtoB(fi, fi+1); 
 if ( fi == ei ) i = ei; 
 if ( fi < ei ) i = randomintAtoB(fi-1, fi); 

 if ( fj > ej ) j = randomintAtoB(fj, fj+1); 
 if ( fj == ej ) j = fj; 
 if ( fj < ej ) j = randomintAtoB(fj-1, fj);  
 if ( ! occupied(i,j) )  	// if no obstacle then move, else just miss a turn
 {
  fi = i;
  fj = j;
 }
}

// ------------- player 5 -------------------
function drawPlayer5()
{
  var x = translate ( gi * squaresize );   	
  var z = translate ( gj * squaresize );   	
  var y =  0;	

 player5.position.x = x;
 player5.position.y = y;
 player5.position.z = z;
 threeworld.scene.add(player5);

 threeworld.lookat.copy ( player5.position );	  
}


function initLogicalPlayer5()
{
 var i, j;
 do
 {
  i = randomintAtoB(1,gridsize-2);
  j = randomintAtoB(1,gridsize-2);
 }
 while ( occupied(i,j) );  	  // search for empty square 

 gi = i;
 gj = j;
}


function initThreePlayer5()
{
 var shape    = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );			 
 player5 = new THREE.Mesh( shape );
 player5.material.color.setHex( BLANKCOLOR  );	
 drawPlayer5();		  
}


function moveLogicalPlayer5()
{ 
 var i = gi;
 var j = gj;

 if ( gi > ei ) i = randomintAtoB(gi, gi+1); 
 if ( gi == ei ) i = ei; 
 if ( gi < ei ) i = randomintAtoB(gi-1, gi); 

 if ( gj > ej ) j = randomintAtoB(gj, gj+1); 
 if ( gj == ej ) j = gj; 
 if ( gj < ej ) j = randomintAtoB(gj-1, j);  
 
 if ( ! occupied(i,j) )  	// if no obstacle then move, else just miss a turn
 {
  gi = i;
  gj = j;
 }
}





// --- enemy functions -----------------------------------


function drawEnemy()
{
  var x = translate ( ei * squaresize );   	
  var z = translate ( ej * squaresize );   	
  var y =  0;	

 theenemy.position.x = x;
 theenemy.position.y = y;
 theenemy.position.z = z;
 threeworld.scene.add(theenemy);

 threeworld.lookat.copy ( theenemy.position );		
}


function initLogicalEnemy()
{
 var i, j;
 do
 {
  i = randomintAtoB(1,gridsize-2);
  j = randomintAtoB(1,gridsize-2);
 }
 while ( occupied(i,j) );  	  // search for empty square 

 ei = i;
 ej = j;
}


function initThreeEnemy()
{
 var shape    = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );			 
 theenemy = new THREE.Mesh( shape );
 theenemy.material.color.setHex( BLANKCOLOR  );	
 drawEnemy();		  
}

function returnClosesti()
{
    var closi = ai;
    var closj = aj;
    var distance = Math.sqrt( (ei-ai)*(ei-ai) + (ej-aj)*(ej-aj));
     
    if(distance > Math.sqrt( (ei-ci)*(ei-ci) + (ej-cj)*(ej-cj)))
    {
        distance = Math.sqrt( (ei-ci)*(ei-ci) + (ej-cj)*(ej-cj))
        closi = ci;
        closj = cj;
    }
    
    if(distance > Math.sqrt( (ei-di)*(ei-di) + (ej-dj)*(ej-dj)))
    {
        distance = Math.sqrt( (ei-di)*(ei-di) + (ej-dj)*(ej-dj))
        closi = di;
        closj = dj;
    }
    
    if(distance > Math.sqrt( (ei-gi)*(ei-gi) + (ej-gj)*(ej-gj)))
    {
        distance = Math.sqrt( (ei-gi)*(ei-gi) + (ej-gj)*(ej-gj))
        closi = gi;
        closj = gj;
    }
    
    if(distance > Math.sqrt( (ei-fi)*(ei-fi) + (ej-fj)*(ej-fj)))
    {
        distance = Math.sqrt( (ei-fi)*(ei-fi) + (ej-fj)*(ej-fj))
        closi = fi;
        closj = fj;
    }
    return closi;
}
function returnClosestj()
{
    var closi = ai;
    var closj = aj;
    var distance = Math.sqrt( (ei-ai)*(ei-ai) + (ej-aj)*(ej-aj));
     
    if(distance > Math.sqrt( (ei-ci)*(ei-ci) + (ej-cj)*(ej-cj)))
    {
        distance = Math.sqrt( (ei-ci)*(ei-ci) + (ej-cj)*(ej-cj))
        closi = ci;
        closj = cj;
    }
    
    if(distance > Math.sqrt( (ei-di)*(ei-di) + (ej-dj)*(ej-dj)))
    {
        distance = Math.sqrt( (ei-di)*(ei-di) + (ej-dj)*(ej-dj))
        closi = di;
        closj = dj;
    }
    
    if(distance > Math.sqrt( (ei-gi)*(ei-gi) + (ej-gj)*(ej-gj)))
    {
        distance = Math.sqrt( (ei-gi)*(ei-gi) + (ej-gj)*(ej-gj))
        closi = gi;
        closj = gj;
    }
    
    if(distance > Math.sqrt( (ei-fi)*(ei-fi) + (ej-fj)*(ej-fj)))
    {
        distance = Math.sqrt( (ei-fi)*(ei-fi) + (ej-fj)*(ej-fj))
        closi = fi;
        closj = fj;
    }
    return closj;
}

function moveLogicalEnemy()
{ 

 const pi = returnClosesti();
 const pj = returnClosestj();
 console.log(pi + " = i    " + pj + " = j")
 var i =ei;
 var j = ej;
  if (i < pi && j < pj) 
  {
      j++;
      i++;
  }
   if (i < pi && j > pj) 
  {
      j--;
      i++;
  }
   if (i > pi && j < pj) 
  {
      j++;
      i--;
  }
  if (i > pi && j > pj) 
  {
      j--;
      i--;
  }
  if (i == pi && j < pj) 
  {
      j++;
  }
  if (i == pi && j > pj) 
  {
      j--;
  }
   if (i < pi && j == pj) 
  {
      i++;
  }
   if (i > pi && j == pj) 
  {
      i--;
  }

 /*var i, j;
 if ( ei < ai ) i = randomintAtoB(ei, ei+1); 
 if ( ei == ai ) i = ei; 
 if ( ei > ai ) i = randomintAtoB(ei-1, ei); 

 if ( ej < aj ) j = randomintAtoB(ej, ej+1); 
 if ( ej == aj ) j = ej; 
 if ( ej > aj ) j = randomintAtoB(ej-1, ej); 
 */

 /*if (occupied(i,j))
 {
  if()
  
 }*/ 

 if ( occupied(i,j) &&  !GRID[i][j] == GRID_WALL )
 {
  ei = i;
  ej = j;
 }
 if ( !occupied(i,j))
 {
  ei = i;
  ej = j;
 }
 if(occupied(i,j))
 {
    
    if(ei == i && ej < j)
    {
        if(!occupied(ei-1,ej))
            i = ei -1;
        else if(!occupied(ei+1,ej))
            i = ei + 1;

    }
    if(ei < i && ej == j)
    {
        if(!occupied(ei,ej-1))
            j = ej - 1;
        else if(!occupied(ei,ej+1))
            j = ej + 1; 
    }
    if(ei == i && ej > j)
    {
        if(!occupied(ei-1,ej))
            i = ei -1;
        else if(!occupied(ei+1,ej))
            i = ei + 1; 
    }
    if(ei > i && ej == j)
    {
        if(!occupied(ei,ej-1))
            j = ei -1;
        else if(!occupied(ei,ej+1))
            j = ei + 1;
    }
    
    if(ei < i && ej > j)
    {
        if(!occupied(ei,ej-1))
            j = ej-1;
        else if(!occupied(ei+1,ej))
            i = ei +1;

    }
    if(ei > i && ej > j)
    {
        if(!occupied(ei,ej+1))
            j = ej+1;
        else if(!occupied(ei+1,ej))
            i = ei+1;
    }
    if(ei> i && ej< j)
    {
        if(!occupied(ei-1,ej))
            i = ei-1;
        else if(!occupied(ei,ej+1))
            j = ej+1;
    }
    if(ei < i && ej < j)
    {
        if(!occupied(ei+1,ej))
            i = ei+1;
        else if(!occupied(ei,ej+1))
            j = ej + 1;
    }
    ei = i;
    ej = j;
    

     
 }
}





// --- agent functions -----------------------------------




// --- 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 caught()
{
    if(ei == gi && ej == gj)
    {
        gi = 100;
        gj = 100;
        enemiesLeft--;
    }
    if(ei == ai && ej == aj)
    {
        ai = 100;
        aj = 100;
        enemiesLeft--;
    }
    if(ei == ci && ej == cj)
    {
        ci = 100;
        cj = 100;
        enemiesLeft--;
    }
    if(ei == di && ej == dj)
    {
        di = 100;
        dj = 100;
        enemiesLeft--;
    }
    if(ei == fi && ej == fj)
    {
        fi = 100;
        fj = 100;
        enemiesLeft--;
    }
}


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 = self.getState();
 var status = " Step: <b> " + step + " </b> &nbsp; x = (" + x.toString() + ") &nbsp; a = (" + a + ") "; 

 $("#user_span3").html( status );
}


function   updateStatusAfter()		// agent and enemy have moved, can calculate score
{
 // new state after both have moved
 var y = self.getState();
 var status = " &nbsp; y = (" + y.toString() + ") <BR> "; 
 $("#user_span4").html( status );

 var score = self.getScore();

 var status = "   Bad steps: " + badsteps + 
		" &nbsp; Good steps: " + goodsteps + 
		" &nbsp; Score: " + score.toFixed(2) + "% "; 

 $("#user_span5").html( status );
}






//--- public functions / interface / API ----------------------------------------------------------


	this.endCondition;			// If set to true, run will end. 



this.newRun = function() 
{

// (subtle bug) must reset variables like these inside newRun (in case do multiple runs)

  this.endCondition = false;
  badsteps = 0;	
  goodsteps = 0;
	step = 0;


 // for all runs:

 	initGrid();
	initLogicalWalls(); 
	initLogicalMaze();
	initLogicalEnemy();
	initLogicalPlayer1();
    initLogicalPlayer2();
	initLogicalPlayer3();
    initLogicalPlayer4();
    initLogicalPlayer5();




 // for graphical runs only:

  if ( true  )
  {
	if ( show3d )
	{
	 BOXHEIGHT = squaresize;
	 threeworld.init3d ( startRadiusConst, maxRadiusConst, SKYCOLOR  ); 	
	}	     
	else
	{
	 BOXHEIGHT = 1;
	 threeworld.init2d ( startRadiusConst, maxRadiusConst, SKYCOLOR  ); 		     
	}

	initSkybox();
 	//initMusic();

	// Set up objects first:

	initThreeWalls(); 
	initThreeMaze();
	initThreeEnemy();
	initThreePlayer1();
	initThreePlayer2();
	initThreePlayer3();
	initThreePlayer4();
	initThreePlayer5();



	// Then paint them with textures - asynchronous load of textures from files. 
	// The texture file loads return at some unknown future time in some unknown order.
	// Because of the unknown order, it is probably best to make objects first and later paint them, rather than have the objects made when the file reads return.
	// It is safe to paint objects in random order, but might not be safe to create objects in random order. 

	loadTextures();	

  }

};




this.getState = function()
{
 var x = [ ai, aj, ei, ej, ci, cj, di, dj, gi, gj, fi, fj];
  return ( x );  
};


	
       


this.takeAction = function ( a )
{
  step++;

  if ( true  )
   updateStatusBefore(a);			// show status line before moves 


  if ( ( step % 3 ) == 0 )		// slow the enemy down to every nth step
    moveLogicalEnemy();
    
  if ( ( step % 2 ) == 0 )		// slow the enemy down to every nth step
    moveLogicalPlayer1();
  if ( ( step % 2 ) == 0 )		// slow the enemy down to every nth step
    moveLogicalPlayer2();
  if ( ( step % 2 ) == 0 )		// slow the enemy down to every nth step
    moveLogicalPlayer3();
      if ( ( step % 2 ) == 0 )		// slow the enemy down to every nth step
    moveLogicalPlayer4();
  if ( ( step % 2 ) == 0 )		// slow the enemy down to every nth step
    moveLogicalPlayer5();
    



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

  if ( true  )
  {
   drawEnemy();
   drawPlayer1();
   drawPlayer2();
   drawPlayer3();
   drawPlayer4();
   drawPlayer5();
   updateStatusAfter();			// show status line after moves  
  }



  if(caught())
  {
    var loader9 = new THREE.TextureLoader();
    loader9.load ( '/uploads/bouldersoshoulders/on.jpg',	function ( thetexture ) {			 
	thetexture.minFilter = THREE.LinearFilter;
	player4.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
	} ); 
  }
  if(enemiesLeft == 0)
  {
    updateStatusBefore(a);
    this.endCondition= true;
  }

};



this.endRun = function()
{
 if ( true  )
 {
  musicPause(); 
  if ( this.endCondition )
    $("#user_span6").html( " &nbsp; <font color=red> <B> Enemy has caaught all players. Winner Winner Chicken Dinner."  );
  else
    $("#user_span6").html( " &nbsp; <font color=red> <B> All opponents not caught, enemy loses. </B> </font>   "  );
    
 }
};


this.getScore = function()
{
 return ( ( goodsteps / step ) * 100 );
};


}

//---- end of World class -------------------------------------------------------








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



function initMusic()
{
	// put music element in one of the spans
  	var x = "<audio  id=theaudio  src=/uploads/starter/Defense.Line.mp3   autoplay loop> </audio>" ;
  	$("#user_span1").html( x );
} 
 

function musicPlay()  
{
	// jQuery does not seem to parse pause() etc. so find the element the old way:
 	document.getElementById('theaudio').play();
}


function musicPause() 
{
 	document.getElementById('theaudio').pause();
}


function soundAlarm()
{
 	var x = "<audio    src=/uploads/starter/air.horn.mp3   autoplay  > </audio>";
  	$("#user_span2").html( x );
}