Code viewer for World: Egg Stealer
//---- NOTE ABOUT THE WORLD -------------------------------------------------------
// This world was orignally cloned from jame's humphry's Snow World
// and altered to fit a Bomberman style game. 
// Boxes are added to the maze as obstacles. The agent has to place and detonate
// bombs next to them in order to clear a path.
// The monster is in the way of the agent, guarding the egg.
// If the monster gets to the agent (within one block), the agent fails the mission
// If the agent detonates a bomb near the monster, the monster is killed.
// The agent gets the egg by getting on the same square.
//---- -------------------- -------------------------------------------------------


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

const  SCREENSHOT_STEP = 50;    




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

const gridsize = 25 ;					

const NOBOXES =  Math.trunc ( (gridsize * gridsize) / 2);

const squaresize = 30;					// 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;
const GRID_BLOCK    = 3;
const GRID_GEM      = 4;
 
 




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




function randomPick ( a, b )
{
 if ( randomBoolean() ) 
  return a;
 else
  return b;
}




//---- 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 BLOCKS  = new Array(NOBOXES);
var theagent, theenemy, thegem, thebomb;        // additions of thegem = egg and thebomb for gameplay
  

var agentRotation = 0;
var enemyRotation = 0;

// enemy and agent position on squares
var ei, ej, ai, aj, gi, gj, bi, bj;


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;		 
    if ( GRID[i][j] == GRID_BLOCK ) return true;
    if ( GRID[i][j] == GRID_GEM ) 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 ) );
}

function initFloor() {
    var floorTexture = new THREE.ImageUtils.loadTexture('/uploads/inapo/floor.jpg');
	floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping; 
	floorTexture.repeat.set( 10, 10 );
	var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
	var floorGeometry = new THREE.PlaneGeometry(850, 850, 10, 10);
	var floor = new THREE.Mesh(floorGeometry, floorMaterial);
	floor.position.y = -20;
	floor.rotation.x = Math.PI / 2;
	threeworld.scene.add(floor);    

}


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


function initSkybox() 
{

// x,y,z positive and negative faces have to be in certain order in the array 
 
// mountain skybox, credit:
// http://www.custommapmakers.org/skyboxes.php

  var materialArray = [
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/inapo/darkskies_ft.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/inapo/darkskies_bk.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/inapo/darkskies_up.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/inapo/darkskies_dn.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/inapo/darkskies_rt.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/inapo/darkskies_lf.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
}

// TEXTURES & MODELS CREDITS
// walls : http://webtreats.mysitemyway.com/8-tileable-metal-textures/
// black : http://wallpaperfolder.com/wallpapers/dark+metal
// skin : http://www.123rf.com/stock-photo/animal_skin.html
// sphere : http://blog.mastermaps.com/2014/01/photo-spheres-with-threejs.html
// agent : http://tf3dm.com/3d-model/muhammer-30214.html
// monster : http://tf3dm.com/3d-model/rage-9769.html


function loadTextures()
{

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

     var loader2 = new THREE.TextureLoader();
     loader2.load ( '/uploads/inapo/walls.jpg',		function ( thetexture ) {			 
    		thetexture.minFilter = THREE.LinearFilter;
    		paintMaze ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
     	} ); 
     	
     var loader3 = new THREE.TextureLoader();
     loader3.load ( '/uploads/inapo/skin.jpg',		function ( thetexture ) {			 
    		thetexture.minFilter = THREE.LinearFilter;
    		thebomb = new THREE.MeshBasicMaterial( { map: thetexture } );
     	} );
    
     var loader4 = new THREE.TextureLoader();
     loader4.load ( '/uploads/inapo/sphere.jpg',	function ( thetexture ) {			 
    		thetexture.minFilter = THREE.LinearFilter;
    		thegem.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
    	} ); 
    
     var loader5 = new THREE.TextureLoader();
     loader4.load ( '/uploads/inapo/wood.jpg',	function ( thetexture ) {			 
    		thetexture.minFilter = THREE.LinearFilter;
    		paintBlocks ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
    	} ); 
    	
    //NOTE: THE TEXTURES FOR THE MODELS:
    // They don't show up in the world due to the references in the MTL file
    // referring to a blend file that cannot be uploaded to this server due 
    // to file size and file type
    
    // load OBJ plus MTL (plus TGA files) 
	THREE.Loader.Handlers.add( /.tga$/i, new THREE.TGALoader() );
	var m = new THREE.MTLLoader();
	m.setTexturePath ( "/uploads/inapo/" );
	m.setPath        ( "/uploads/inapo/" );
	m.load( "rage.mtl", function( materials ) {
 
		materials.preload();
		var o = new THREE.OBJLoader();
		o.setMaterials ( materials );
		o.setPath ( "/uploads/inapo/" );
		o.load( "rage.obj", function ( object ) {
		    object.position.y = 5;
			addenemy ( object );
		} );
	} );
	
	// load OBJ plus MTL (plus TGA files) 
	THREE.Loader.Handlers.add( /.tga$/i, new THREE.TGALoader() );
	var m = new THREE.MTLLoader();
	m.setTexturePath ( "/uploads/inapo/" );
	m.setPath        ( "/uploads/inapo/" );
	m.load( "muhammer2.mtl", function( materials ) {
 
		materials.preload();
		var o = new THREE.OBJLoader();
		o.setMaterials ( materials );
		o.setPath ( "/uploads/inapo/" );
		o.load( "muhammer.obj", function ( object ) {
		    object.position.y = -50;
			addagent ( object );
		} );
	} );
}

function addenemy ( object )
{
	object.scale.multiplyScalar (8);
	theenemy = object;
	threeworld.scene.add( theenemy ); 
}

function addagent ( object )
{
	object.scale.multiplyScalar (20);
	theagent = object;
	threeworld.scene.add( theagent ); 
}




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


// Blocks are the boxes that can be destroyed by a bomb 
// in order to clear a path to the egg
function initLogicalBlocks()		 
{
    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);
    	if(i == 1 && j == 1 ){
    	    GRID[i][j] = GRID_BLANK;
    	} else if (i == 1 && j == 2) {
    	    GRID[i][j] = GRID_BLANK;
    	} else if (i == 2 && j == 1) {
    	    GRID[i][j] = GRID_BLANK;
    	} else if (i == 23 && j == 23) {
    	    GRID[i][j] = GRID_BLANK;
    	} else {
        	GRID[i][j] = GRID_BLOCK ;  
    	}
    }
    
}


function initThreeBlocks()		  	
{
 var t = 0;
 for (var i = 0; i < gridsize ; i++) 
  for (var j = 0; j < gridsize ; j++) 
   if ( GRID[i][j] == GRID_BLOCK )
   {
   	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);
	BLOCKS[t] = {coordi: i, coordj: j, cube: thecube};		// save it for later
	t++; 
   }
}


function paintBlocks ( material )		 
{
 for ( var i = 0; i < BLOCKS.length; i++ )
 { 
   if ( BLOCKS[i] )  BLOCKS[i].cube.material = material;
 }
}




function initLogicalMaze()		 
{
  	for(var i = 2; i < gridsize - 2; i = i + 2){
  	    for(var j = 2; j < gridsize -2; j = j + 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;
 }
}





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


function drawEnemy()		// given ei, ej, draw it 
{
if ( theenemy )
{
  var x = translate ( ei * squaresize );   	
  var z = translate ( ej * squaresize );   	
  var y =   ( -1 * squaresize );   	

 theenemy.position.x = x;
 theenemy.position.y = y;
 theenemy.position.z = z;
 
 threeworld.lookat.copy ( theenemy.position );		// if camera moving, look back at where the enemy is  
 threeworld.lookat.y = ( squaresize * 1.5 );     // point camera higher up
}
}



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

 ei = i;
 ej = j;
}


function igetAction()
{
	 if ( ei < ai ) 	return (   ACTION_RIGHT 	); 
	 if ( ei > ai ) 	return (   ACTION_LEFT 		); 
 	 return ( ACTION_STAYSTILL );
}

function jgetAction()
{
    if ( ej < aj ) 	return (   ACTION_UP  	); 
	if ( ej > aj ) 	return (   ACTION_DOWN  ); 
  	return ( ACTION_STAYSTILL );
}

function enemyGetAction()
{
    return randomPick ( igetAction(), jgetAction() );
}


function moveLogicalEnemy()
{ 
     var a = enemyGetAction();
     var i = ei;
     var j = ej;		 
    
          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) ) 
     {
      if ( true  )
      {
    	      if ( a == ACTION_LEFT ) 	{  rotateEnemyTowards ( 3 * (Math.PI / 2) ); }
    	 else if ( a == ACTION_RIGHT ) 	{  rotateEnemyTowards ( 1 * (Math.PI / 2) ); }
    	 else if ( a == ACTION_UP ) 	{  rotateEnemyTowards ( 0 * (Math.PI / 2) ); }
    	 else if ( a == ACTION_DOWN ) 	{  rotateEnemyTowards ( 2 * (Math.PI / 2) ); }
      }
      ei = i;
      ej = j;
     }
}


function rotateEnemyTowards ( newRotation )		
{
     if ( enemyRotation == newRotation ) return;
     // else 
     var x = ( enemyRotation + newRotation ) / 2; 
     theenemy.rotation.set ( 0, x, 0 );
     enemyRotation = x;	
}



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


function drawAgent()	// given ai, aj, draw it 
{
  var x = translate ( ai * squaresize );   	
  var z = translate ( aj * squaresize );   	
  var y =  ( -1 * squaresize );	

 theagent.position.x = x;
 theagent.position.y = y;
 theagent.position.z = z;

 threeworld.follow.copy ( theagent.position );		// follow vector = agent position (for camera following agent)
 threeworld.follow.y = ( squaresize * 1.5 );  
}


function initLogicalAgent()
{
    ai = 1;
    aj = 1;
}



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) ) 
 {
  if ( true  )
  {
	// if going to actually move, then turn body towards move
	// rotate by some amount of radians from the normal position 
	// in degrees: +0, +90, +180, +270

	      if ( a == ACTION_LEFT ) 	{  rotateAgentTowards ( 3 * (Math.PI / 2) ); }
	 else if ( a == ACTION_RIGHT ) 	{  rotateAgentTowards ( 1 * (Math.PI / 2) ); }
	 else if ( a == ACTION_UP ) 		{  rotateAgentTowards ( 0 * (Math.PI / 2) ); }
	 else if ( a == ACTION_DOWN ) 	{  rotateAgentTowards ( 2 * (Math.PI / 2) ); }
  }
  ai = i;
  aj = j;
 }
}



function rotateAgentTowards ( newRotation )		
{
 if ( agentRotation == newRotation ) return;
 // else 
 var x = ( agentRotation + newRotation ) / 2; 
 theagent.rotation.set ( 0, x, 0 );
 agentRotation = x;	
}


// gem stuff ---------------------------------------

function initLogicalGem() {
    gi = 23;
    gj = 23;
}

function drawGem()	// given ai, aj, draw it 
{
  var x = translate ( gi * squaresize );   	
  var z = translate ( gj * squaresize );   	
  var y = 10;	

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

}

function initThreeGem() {
    var shape    = new THREE.SphereGeometry( 10, 10, 10 );			 
    thegem = new THREE.Mesh( shape );
    thegem.material.color.setHex( BLANKCOLOR  );	
    drawGem();
}


// bomb stuff -------------------------------------------------------
var bombPlaced = false;
function initThreeBomb() {
    bi = ai;
    bj = aj;
    var shape = new THREE.SphereGeometry( 15, 15, 15 );			 
    thebomb = new THREE.Mesh( shape );
    thebomb.material.color.setHex( BLANKCOLOR  );
    drawBomb();
}

function drawBomb()	// given ai, aj, draw it 
{
    var x = translate ( ai * squaresize );   	
    var z = translate ( aj * squaresize );   	
    var y =  ( -1 * squaresize );	
    
    thebomb.position.x = x;
    thebomb.position.y = y + 25;
    thebomb.position.z = z;
 

    threeworld.scene.add(thebomb);
    bombCountdown();
    bombPlaced = true;
    console.log("Bomb added");
 
}

function bombCountdown() {
    var count = 4;
    // Countdown function using built-in javascript
    // function that sets an interval for the execution
    // of a certain piece of code by miliseconds.
    var countdown = setInterval(function(){
            count--;
            if(count > 0){
                console.log(count);
            } else {
                detonateBomb();
                clearInterval(countdown);
                eraseBomb(); 
            }
    }, 1000);
    
}

// removes the bomb from the scene graphicallly
function eraseBomb() {
    threeworld.scene.remove(thebomb);
}

// clears surrounding area adjacent to the bomb
// will delete all boxes on square away
// will kill agent if too close
// will kill monster if too close
function detonateBomb(){
    if(GRID[bi + 1][bj] == GRID_BLOCK) {
        for(var x = 0; x < BLOCKS.length; x++){
            if(BLOCKS[x].coordi == (bi + 1) && BLOCKS[x].coordj == bj){
                threeworld.scene.remove(BLOCKS[x].cube);
                eraseBomb(); 
                GRID[bi + 1][bj] = GRID_BLANK;
                bombPlaced = false;
            }
        }
        
    }
    
    if(GRID[bi][bj + 1] == GRID_BLOCK) {
        for(var x = 0; x < BLOCKS.length; x++){
            if(BLOCKS[x].coordi == bi && BLOCKS[x].coordj == (bj + 1)){
                threeworld.scene.remove(BLOCKS[x].cube);
                eraseBomb(); 
                GRID[bi][bj + 1] = GRID_BLANK;
                bombPlaced = false;
            }
        }
        
    }
    
    if(GRID[bi - 1][bj] == GRID_BLOCK) {
        for(var x = 0; x < BLOCKS.length; x++){
            if(BLOCKS[x].coordi == (bi - 1) && BLOCKS[x].coordj == bj){
                threeworld.scene.remove(BLOCKS[x].cube);
                eraseBomb(); 
                GRID[bi - 1][bj] = GRID_BLANK;
                bombPlaced = false;
            }
        }
        
    }
    
    if(GRID[bi][bj - 1] == GRID_BLOCK) {
        for(var x = 0; x < BLOCKS.length; x++){
            if(BLOCKS[x].coordi == bi && BLOCKS[x].coordj == (bj - 1)){
                threeworld.scene.remove(BLOCKS[x].cube);
                eraseBomb(); 
                GRID[bi][bj - 1] = GRID_BLANK;
                bombPlaced = false;
            }
        }
        
    }
    
    soundExplosion();
    
    if(ai == (bi + 1) && (aj == bj)) {agentKilled = true;}
    if(ai == (bi - 1) && (aj == bj)) {agentKilled = true;}
    if((ai == bi) && (aj == bj + 1)) {agentKilled = true;}
    if((ai == bi) && (aj == bj - 1)) {agentKilled = true;}
    
    if(ei == (bi + 1) && (ej == bj)) {
        monsterKilled = true; 
        threeworld.scene.remove(theenemy);
    }
    if(ei == (bi - 1) && (ej == bj)) {
        monsterKilled = true; 
        threeworld.scene.remove(theenemy);
    }
    if((ei == bi) && (ej == bj + 1)) {
        monsterKilled = true; 
        threeworld.scene.remove(theenemy);
    }
    if((ei == bi) && (ej == bj - 1)) {
        monsterKilled = true; 
        threeworld.scene.remove(theenemy);
    }
    
    
}


function keyHandler(e)		
// user control 
// Note that this.takeAction(a) is constantly running at same time, redrawing the screen.
{
    if (e.keyCode == 37)  moveLogicalAgent ( ACTION_LEFT 	);
    if (e.keyCode == 38)  moveLogicalAgent ( ACTION_DOWN  	);
    if (e.keyCode == 39)  moveLogicalAgent ( ACTION_RIGHT 	);
    if (e.keyCode == 40)  moveLogicalAgent ( ACTION_UP	);
    if (e.keyCode == 32)  {
        if(!bombPlaced){
            initThreeBomb();
        }
    }
}





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

var agentKilled = false;
var monsterKilled = false;

function agentHasGem()	
{
    return ( 	ai == gi && aj == gj 	);		
} 

function agentCaught() {
    if(ai == (ei + 1) && (aj == ej)) {return true;}
    if(ai == (ei - 1) && (aj == ej)) {return true;}
    if((ai == ei) && (aj == ej + 1)) {return true;}
    if((ai == ei) && (aj == ej - 1)) {return true;}
    
    return false;
    
}



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 = "Steal the egg before the monster gets to you. <br/> Use the arrow keys to move. Press the spacebar to drop a bomb."; 

 $("#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 = ""; 
 $("#user_span4").html( status );

 var score = self.getScore();

 var status = ""; 

 $("#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(); 
	initLogicalBlocks();
	initLogicalMaze();
	initLogicalAgent();
	initLogicalEnemy();
	initLogicalGem();

 // for graphical runs only:

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

	initSkybox();
	initFloor();
 	initMusic();

	// Set up objects first:

	initThreeWalls(); 
	initThreeBlocks();
	initThreeMaze();
	initThreeGem();

	// 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();	
	document.onkeydown = keyHandler;	
  }

};




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



this.nextStep = function()		 
{
 var a = 4;

  step++;

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

  moveLogicalAgent(a);

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

  if ( true  )
  {
   drawAgent();
   drawEnemy();
   updateStatusAfter();			// show status line after moves  
  }


  if ( agentHasGem() )			// if agent blocked in, game over
  {
	this.endCondition = true; 			 
  	if ( true  )
  	{
	    musicPause();
	    soundAlarm();
	}
  }
  
  if(agentCaught()) {
    this.endCondition = true;
    if ( true  )
    {
        musicPause();
        soundAlarm();
    }
  }
  
  if(agentKilled) {
      this.endCondition = true;
      if ( true  )
    {
        musicPause();
        soundAlarm();
    }
  }

};



this.endRun = function()
{
    if ( true  )
    {
        musicPause(); 
        if ( this.endCondition ) {
            if(agentHasGem()) {
                $("#user_span6").html( " &nbsp; <font color=red> <B> You got the egg! You win! </B> </font>   "  );
            } else if (agentCaught()){
                $("#user_span6").html( " &nbsp; <font color=red> <B> You got caught by the monster!</B> </font>   "  );
            } else if (agentKilled){
                 $("#user_span6").html( " &nbsp; <font color=red> <B> You died of your own bomb</B> </font>   "  );
            }
        } 
    }
};


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


}

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








// --- music and sound effects ----------------------------------------
// credits:
// Bomb sound effect : https://www.youtube.com/watch?v=QzOTZpxBmAk
// http://soundbible.com/1542-Air-Horn.html 
// Main BG music : Bomberman soundtrack (original)


 

function initMusic()
{
	// put music element in one of the spans
  	var x = "<audio  id=theaudio  src=/uploads/inapo/bgmusic.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 );
}


function soundExplosion()
{
 	var x = "<audio    src=/uploads/inapo/explosion.mp3   autoplay  > </audio>";
  	$("#user_span2").html( x );
}