Code viewer for World: Run Spider Run
// About the world:
//You play as the spider and try to get to your web before the hand comes and squishes you
//When you reach your web you move on to the next level, where the grid increases in size

// Known Bugs:
//Run does not finish when hand comes into contact with spider
//Fails to load http://ab.computing.dcu.ie/uploads/dean95/C:/Users/Textures/Black%20widow%20back%20red.jpg even though I dont ask to load this file
//Does not end run and move to next level when on web


// Credits:
//Spider MTL and OBJ
//https://www.cgtrader.com/free-3d-models/animals/insect/spider-black-widow-free

//hand OBJ and JPG
//http://tf3dm.com/download-page.php?url=freerealsichand-85561

//skybox
//http://opengameart.org/content/forest-skyboxes

//shrubs (maze)
//http://images.meredith.com/content/dam/bhg/Images/2009/11/101128116.jpg.rendition.largest.jpg

//thorns (walls)
//http://teshuvaministries.net/wp-content/uploads/2014/02/thorn.jpg

//web
//http://www.patternpictures.com/wp-content/uploads/2014/10/PP56511112-Spider-Web-on-Monotone-Green-Background.jpg

// music credit
// https://www.youtube.com/watch?v=Bbl2u7FzS3Y



 
const	 	CLOCKTICK 	= 150;				// 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 = 30;					// number of squares along side of world	   
const squaresize = 100;					// size of square in pixels
const MAXPOS = gridsize * squaresize;		// length of one side in pixels 
	
const NOBOXES =  Math.trunc ( (gridsize * gridsize) / 15 );


const SKYCOLOR 	= 0xffffcc;				// a number, not a string 
const BLANKCOLOR 	= SKYCOLOR ;			// make objects this color until texture arrives (from asynchronous file read)

const  LIGHTCOLOR 	= 0xffffff ;



const startRadiusConst	 	= MAXPOS * 1 ;		// distance from centre to start the camera at
const skyboxConst			= MAXPOS * 3 ;		// where to put skybox 
const maxRadiusConst 			= MAXPOS * 5 ;		// 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;

 


// contents of a grid square

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


 


 
// --- 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 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 handle to each wall block object so can find it later to paint it 
var MAZE 	= new Array ( NOBOXES );
var WEB     = new Array ( 1 );
var theagent, theenemy;		  


var agentRotation = 0;
var enemyRotation = 0;		  // with 3D models, current rotation away from default orientation


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

var ci, cj;

var badsteps;
var goodsteps;
var  step;
var level;

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





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


 
function translate ( x ) 
{
 return ( x - ( MAXPOS/2 ) );
}





// --- asynch load textures from file ----------------------------------------
  

function loadTextures()
{
	var manager = new THREE.LoadingManager();		
	var loader = new THREE.OBJLoader( manager );
			
 loader.load( "/uploads/dean95/hand.obj", buildenemy );


// load OBJ plus MTL (plus TGA files) 
	THREE.Loader.Handlers.add( /.tga$/i, new THREE.TGALoader() );
	var m = new THREE.MTLLoader();
	m.setTexturePath ( "/uploads/dean95/" );
	m.setPath        ( "/uploads/dean95/" );
	m.load( "blackwidow4.mtl", function( materials ) {
 
		materials.preload();
		var o = new THREE.OBJLoader();
		o.setMaterials ( materials );
		o.setPath ( "/uploads/dean95/" );
		o.load( "blackwidow4.obj", function ( object ) {
			addspider ( object );
		} );
	} );




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

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

 var loader3 = new THREE.TextureLoader();
 loader3.load ( '/uploads/dean95/web.jpg',		function ( thetexture ) {			 
		thetexture.minFilter = THREE.LinearFilter;
		paintWeb ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
 	} );
}

 
 
function buildenemy ( object ) 
{ 
	object.scale.multiplyScalar ( 50 );    	  // make 3d object n times bigger 
	object.traverse( paintEnemy );
	theenemy = object;
	threeworld.scene.add( theenemy ); 
}

function paintEnemy ( child ) 
{
	if ( child instanceof THREE.Mesh ) 
	{
      	child.material.map = THREE.ImageUtils.loadTexture( "/uploads/dean95/hand_mapnew.jpg" );
	}
}


function addspider ( object )
{
	object.scale.multiplyScalar ( 150 );    //150 scales well in proportion to hand	   
	theagent = object;
	threeworld.scene.add( theagent ); 
}





function initSkybox() 
{

   var materialArray = [
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/dean95/posx.jpg" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/dean95/negx.jpg" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/dean95/posy.jpg" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/dean95/negy.jpg" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/dean95/posz.jpg" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/dean95/negz.jpg" ), 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 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, squaresize, 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 )		// paint blank boxes  
{
 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(2,gridsize-3);	// inner squares are 1 to gridsize-2
  	var j = randomintAtoB(2,gridsize-3);
    	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, squaresize, 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;
 }
}

function initLogicalWeb()
{
 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;
 	GRID[i][j] = GRID_WEB ;
}

function initThreeWeb()
{

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

  	thecube.position.x = translate ( ci * squaresize );   	
  	thecube.position.z = translate ( cj * squaresize );   	
  	thecube.position.y = 0;	
 
 	threeworld.scene.add(thecube);
 	WEB[0] = thecube;
}

function paintWeb( material )
{
    WEB[0].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(1,gridsize-2);
  j = randomintAtoB(1,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 
{
if ( theagent )
{
  var x = translate ( ai * squaresize );   	
  var z = translate ( aj * squaresize );   	
  var y =   ( 0 * 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 );     // put camera higher up
}
}


function initLogicalAgent()
{
// 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 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;
 }
}






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_UP 	);
    if (e.keyCode == 38)  moveLogicalAgent ( ACTION_LEFT  	);
    if (e.keyCode == 39)  moveLogicalAgent ( ACTION_DOWN 	);
    if (e.keyCode == 40)  moveLogicalAgent ( ACTION_RIGHT	);
}


 


// --- score: -----------------------------------     //do i need a score?


 
function   updateStatus()		 
{
    var score = self.getScore();
    var status =  "Score:    " + score + ". Get the spider to the web using the arrow keys to progress to the next level!"; 

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






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


// must have this public variable:

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

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




this.newRun = function() 
{
  this.endCondition = false;


  // define logical data structure for the World, even if no graphical representation:

 	initGrid();
	initLogicalWalls(); 
	initLogicalMaze();
	initLogicalWeb();

	initLogicalAgent();
	initLogicalEnemy();


  if ( true  )
  {
	  threeworld.init3d ( startRadiusConst, maxRadiusConst, SKYCOLOR  ); 


		// light
    		var ambient = new THREE.AmbientLight();
    		threeworld.scene.add( ambient );

		
	   	 var thelight = new THREE.DirectionalLight ( LIGHTCOLOR, 3 );
	  	 thelight.position.set ( startRadiusConst, startRadiusConst, startRadiusConst );
	   	 threeworld.scene.add(thelight);
		


		// music
  		var x = "<audio  id=theaudio  src=/uploads/dean95/theflashtheme.mp3   autoplay loop> </audio>" ;
  		$("#user_span2").html( x );

		// music credit
		// https://www.youtube.com/watch?v=Bbl2u7FzS3Y



        	initSkybox();
	    	initThreeWalls();
	    	initThreeMaze();
	    	initThreeWeb();

	  loadTextures();			// will return sometime later, but can go ahead and render now	
	  
	  document.onkeydown = keyHandler;
  }		
};



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



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

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

  if ( true  )
  {
   drawAgent();
   drawEnemy();
   updateStatus();
   
  }

};



this.endRun = function() //if spider gets squished
{
    //if enemy comes into contact with agent
   if (  ei == ai && ej == aj )
   {
        return true;
         $("#user_span6").html( " &nbsp; <font color=red> <B> YOU WEREN'T FAST ENOUGH YOU GOT SQUISHED </B> </font>   "  );
   }
        else return false;
};

this.nextLevel = function()
{
    if ( ci == ai && cj == aj )
    {
        this.endCondition = true;
        gridsize * 2;
        level++; 
        return newRun();
    }
        
}

this.getScore = function()
{
 return level;
};


}

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