Code viewer for World: No Grid Game of Crowns Thi...

// Cloned by Patricija Shalkauskaite on 25 Nov 2022 from World "No Grid Game of Crowns Third Person View" by Mathias Bazin
// Please leave this clone trail here.


// Cloned by Mathias Bazin on 15 Jun 2018 from World "Game of Crowns Third Person View" by Mathias Bazin
// Please leave this clone trail here.


// Cloned by Mathias Bazin on 31 May 2018 from World "Game of Crowns" by Niamh Byrne
// Please leave this clone trail here.

// =============================================================================================
//the idea:
//this game is based on the game of thrones world Winterfall-. snow,castle,queen,fireball
//The queen needs to collect all her crowns
//the queen needs to avoid being trapped by the fireball
//When the queen steps into the crown the crown disappears
//there are 8 crowns to collect
//The user acts as the mind as they control the queen
// =============================================================================================

// =============================================================================================
// Aim:
// Collect all the crowns
// Dont get trapped into a corner by the fireball
// Collect crowns within 200 seconds
//
// =============================================================================================

// ===================================================================
// Season 2 changes :
// Queen and crowns are bigger
// Queen turns to face the direction she is heading
// Changed some raw values into constants
// added some time to collect the crowns (it was hard !)
// ===================================================================

// World must define these:
AB.clockTick           = 30;         // Speed of run: Step every n milliseconds. Default 100.
AB.maxSteps            = 100000;    // 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.
const MAXSTEPS         = 10000000;  // length of a run before final score
const  SCREENSHOT_STEP = 50;
var camera             = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 100);

//---- global constants: -------------------------------------------------------
const gridsize          = 20;                                        // 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        = 225;                                       // size of square in pixels
const MAXPOS            = gridsize * squaresize;		             // length of one side in pixels
const SKYCOLOR 	        =  0xd13636;                                 // a number, not a string
const BLANKCOLOR        = SKYCOLOR ;                                 // make objects this color until texture arrives (from asynchronous file read)
const LIGHTCOLOR 	    = 0xffffff ;
const MODELLENGTH       = 6200;
const SCALEIT           = 2.5;				                         // scale it by this
const SCALEDMODELLENGTH = MODELLENGTH * SCALEIT;

const show3d            = true;						                 // Switch between 3d and 2d view (both using Three.js)
const startRadiusConst  = SCALEDMODELLENGTH * 0.3;
const maxRadiusConst    = SCALEDMODELLENGTH * 2;
const skyboxConst       = MAXPOS * 5 ;		                         // where to put skybox
//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

//--- 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_CROWN    = 3;

//types of camera view
const TPS          = 0;
const CHASE        = 1;
const MOVEDISTANCE = 40;
const TURNAMOUNT   = Math.PI/32;

const CROWNPICKUPFILE = "/uploads/rossfraney3/elevatording.mp3";

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

this.endCondition = false;

var clock = new THREE.Clock(true);
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 ( 5 * gridsize );		// need to keep handles to wall and maze objects so can find them later to paint them
var MAZE 	= new Array ( NOBOXES );

//to hold the crowns
var CROWNS = new Array(8);
var theagent, theagent2, theenemy, thecrown;
var crownMaterial = new THREE.MeshStandardMaterial({color:0xffff00});
// enemy and agent position on squares
var ei, ej, ai, aj, bi, bj, ci,cj;

//Velocity of the player
var badsteps;
var goodsteps;
//variable to stre the crowns
var  step;
var crowns;
var crown;
var self = this;						// needed for private fn to call public fn - see below

var leftInput       =   false;
var rightInput      =   false;
var forwardInput    =   false;
var backwardInput   =   false;

var previousx, previousz;
// 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;
}

//to check if the queen is in a crown square
function nearCrown(i,j)
{
    if ( GRID[i][j] == GRID_CROWN ) 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 translateInv ( x )
{
 return ( x + (squaresize/2) + ( MAXPOS/2 ) ) / squaresize;
}


//--- 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/niamhbyrne/lf.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/niamhbyrne/rt.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/niamhbyrne/up.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/niamhbyrne/dn.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/niamhbyrne/ft.png" ), side: THREE.BackSide } ) ),
 	( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/niamhbyrne/bk.png" ), side: THREE.BackSide } ) )
 	];

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

// This does the file read the old way using loadTexture.
// (todo) Change to asynchronous TextureLoader. A bit complex:
// Make blank skybox. Start 6 asynch file loads to call 6 return functions.
// Each return function checks if all 6 loaded yet. Once all 6 loaded, paint the skybox.
// function createParticleSystem() {

//     // The number of particles in a particle system is not easily changed.
//     var particleCount = 20000;

//     // Particles are just individual vertices in a geometry
//     // Create the geometry that will hold all of the vertices
//     var particles = new THREE.Geometry();

//     // Create the vertices and add them to the particles geometry
//     for (var p = 0; p < particleCount; p++) {

//         // This will create all the vertices in a range of -200 to 200 in all directions
//         var x = Math.random() * 6000 - 3000;
//         var y = Math.random() * 6000 - 3000 ;
//         var z = Math.random() * 6000 - 3000;

//         // Create the vertex
//         var particle = new THREE.Vector3(x, y, z);

//         // Add the vertex to the geometry
//         particles.vertices.push(particle);
//     }

//     // Create the material that will be used to render each vertex of the geometry
//     var particleMaterial = new THREE.PointsMaterial(
//             {//color: BLANKCOLOR ,
//              size: 20,
//              map: THREE.ImageUtils.loadTexture("/uploads/niamhbyrne/snowflake.png"),
//              blending: THREE.AdditiveBlending,
//              transparent: true,
//             });

//     // Create the particle system
//     particleSystem = new THREE.Points(particles, particleMaterial);

//     return particleSystem;
// }


// function animateParticles() {
//     var deltaTime = clock.getDelta();
//     var verts = particleSystem.geometry.vertices;
//     for(var i = 0; i < verts.length; i++) {
//         var vert = verts[i];
//         if (vert.y < -3000) {
//             vert.y = Math.random() * 6000 - 3000;
//         }
//         vert.y = vert.y - (80 * deltaTime);
//     }
//     // particleSystem.geometry.verticesNeedUpdate = true;
// }

// --- asynchronous load textures from file ----------------------------------------
// credits:
// http://commons.wikimedia.org/wiki/File:Old_door_handles.jpg?uselang=en-gb
// 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

// loader return can call private function

function loadTextures()
{   //load the agent
    THREE.Loader.Handlers.add( /.tga$/i, new THREE.TGALoader() );
	var mm = new THREE.MTLLoader();
	mm.setTexturePath ( "/uploads/martind/" );
	mm.setPath        ( "/uploads/martind/" );
	mm.load( "Lion-displacement.mtl", function( materials ) {
		materials.preload();
		var oo = new THREE.OBJLoader();
		oo.setMaterials ( materials );
		oo.setPath ( "/uploads/martind/" );
		oo.load( "Lion-obj.OBJ", function ( object ) {
		    object.scale.multiplyScalar ( 1.2 );
			addparker ( object );

		} );


	} );

    // load castle model OBJ and materials MTL (which reference JPEGs):
// 	var m = new THREE.MTLLoader();
// 	m.setTexturePath ( "/uploads/niamhbyrne/" );
// 	m.setPath        ( "/uploads/niamhbyrne/" );
// 	m.load( "castle.mtl", function( materials ) {

// 		materials.preload();
// 		var o = new THREE.OBJLoader();
// 		o.setMaterials ( materials );
// 		o.setPath ( "/uploads/starter/" );
// 		o.load( "castle.obj", function ( object ) {

// 	        object.scale.multiplyScalar ( SCALEIT );

//         	object.position.x = - ( SCALEDMODELLENGTH * 0.3 );
//         	object.position.z = ( SCALEDMODELLENGTH * 0.15 );
//         	object.position.y = - (squaresize * 0.7);

// //   	        threeworld.scene.add ( object );

// // 		} );
// 	} );

//load in the textures
 var loader1 = new THREE.TextureLoader();
 loader1.load ( '/uploads/niamhbyrne/castle.wall.jpg',		function ( thetexture ) {
		thetexture.minFilter = THREE.LinearFilter;
		paintWalls ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
	} );

//  var loader2 = new THREE.TextureLoader();
//  loader2.load ( '/uploads/niamhbyrne/crown.png',	function ( thetexture ) {
// 		thetexture.minFilter = THREE.LinearFilter;
// 		paintCrown( new THREE.MeshBasicMaterial( { map: thetexture } ));
// 	} );

 var loader3 = new THREE.TextureLoader();
 loader3.load ( '/uploads/martind/cattest.png',	function ( thetexture ) {
		thetexture.minFilter = THREE.LinearFilter;
		theenemy.material =  new THREE.MeshBasicMaterial( { map: thetexture } );
	} );

	 var loader4 = new THREE.TextureLoader();
 loader4.load ( '/uploads/martind/endstone.png',	function ( thetexture ) {
		thetexture.minFilter = THREE.LinearFilter;
		paintMaze( new THREE.MeshBasicMaterial( { map: thetexture } ));
	} );

}
//adds the queen parker
function addparker ( object )
{
	object.scale.multiplyScalar (1.5);
	object.position.y = -150;
	theagent = object;
	theagent2 = object;
//	var tpsCam = new THREE.Mesh(new THREE.BoxGeometry(10,10,10), new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true } ));
    var tpsCam = new THREE.Object3D();
	tpsCam.name = "tps";
//	var chaseCam = new THREE.Mesh(new THREE.BoxGeometry(10,10,10), new THREE.MeshBasicMaterial( { color: 0x1caca1, wireframe: true } ));
    var chaseCam = new THREE.Object3D();
	chaseCam.name = "chase";
	tpsCam.position.set(0,350,-500);
	chaseCam.position.set(0,280,400);
	theagent.add( tpsCam );
	theagent.add( chaseCam );
	threeworld.scene.add( theagent );
	threeworld.scene.add( theagent2 );
}

// --- 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.CylinderGeometry( 30, 30, 80, 6, 4 );
 	 var thecube  = new THREE.Mesh( shape );
	 thecube.material.color.setHex( 0x51565e  );

    	 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 = 10;

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

//randomly places crowns
function initLogicalCrown()
{
 for ( var c=1 ; c <= 8 ; c++ )
 {
  	var i = randomintAtoB(1,gridsize-2);	// inner squares are 1 to gridsize-2
  	var j = randomintAtoB(1,gridsize-2);
    	GRID[i][j] = GRID_CROWN ;
 }
}

//places crowns
function initThreeCrown()
{
 var t = 0;
 for (var i = 0; i < gridsize ; i++)
  for (var j = 0; j < gridsize ; j++)
   if ( GRID[i][j] == GRID_CROWN )
   {
   	// var shape    = new THREE.BoxGeometry( 200,200, 200);
    // thecrown = new THREE.Mesh( shape );
    // thecrown.material.color.setHex( BLANKCOLOR );

    thecrown = createCrown();

    thecrown.position.x = translate ( i * squaresize );
  	thecrown.position.z = translate ( j * squaresize );
  	thecrown.position.y =   0;

 	threeworld.scene.add(thecrown);
	CROWNS[t] = thecrown;		// save it for later
	t++;
   }
}

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.CylinderGeometry( 0, 60, 250, 4, 4 );
  	var thecube  = new THREE.Mesh( shape );
	thecube.material.color.setHex( BLANKCOLOR  );
	thecube.scale.multiplyScalar(2);

  	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 paintCrown ( material )
{
 for ( var i = 0; i < CROWNS.length; i++ )
 {
   if ( CROWNS[i] )  CROWNS[i].material = material;
 }
}

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

//deletes crown when queen picks it up
function replaceShape(f,j)
{

	  for ( var i = 0; i < CROWNS.length; i++ )
    {
        if ( CROWNS[i].position.x == translate ( f * squaresize ) && CROWNS[i].position.z == translate ( j * squaresize ))
                threeworld.scene.remove(CROWNS[i]);
    }

}

// --- enemy functions -----------------------------------
function drawEnemy()	// given ei, ej, draw it
{
  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);
}

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 || ci<ei) 	return (   ACTION_RIGHT 	);
	 if ( ei > ai || ci>ei) 	return (   ACTION_LEFT 		);
 	 return ( ACTION_STAYSTILL );
}

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

function enemyGetAction()
{
    return randomPick ( igetAction(), jgetAction() );
}
function crownGetAction()
{
    return randomPick ( igetAction(), jgetAction() );
}
function initThreeEnemy()
{
 var shape    = new THREE.SphereGeometry( squaresize,  squaresize, squaresize );
 theenemy = new THREE.Mesh( shape );
 theenemy.material.color.setHex( BLANKCOLOR  );
 drawEnemy();
}

function initAgent2()
{
    var shape    = new THREE.SphereGeometry( squaresize,  squaresize, squaresize );
    theagent2 = new THREE.Mesh( shape );
    theagent2.material.color.setHex( BLANKCOLOR  );
}

function moveLogicalEnemy(self)
{
// move towards agent
// put some randomness in so it won't get stuck with barriers

 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 (ai == i && aj == j)
 {
    self.endCondition = true;
	goodsteps = 0;			// you score zero as far as database is concerned
  	if ( true  )
  	{
	//  musicPause();
	//  soundAlarm();
	}
	self.endRun();
 }

 if ( ! occupied(i,j) )  	// if no obstacle then move, else just miss a turn
 {
  ei = i;
  ej = j;
 }
}

const INTERIMROT = 10;

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

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

}

function drawCrown()	// given ai, aj, draw it
{
  var x = translate ( ci * squaresize );
  var z = translate ( cj * squaresize );
  var y =  0;

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

function createCrown()
{
    var shape     = new THREE.CylinderGeometry ( 100, 100, 100, 32, 1, true );
    var material = new THREE.MeshStandardMaterial({color:0xffff00});
    material.side = THREE.DoubleSide

    var ball = new THREE.SphereGeometry ( 10 )
    var ruby = new THREE.MeshStandardMaterial({color:0xff0000});

    var circleShape = new THREE.CylinderGeometry(101,101,10,1,true)
    var circleMaterial = new THREE.MeshStandardMaterial({color: 0xcccc00});

    var crown = new THREE.Mesh(shape, material);
    crown.material.side = THREE.DoubleSide;

    var ball1 = new THREE.Mesh(ball, ruby);
    ball1.position.set(0,-10,100);
    var ball2 = new THREE.Mesh(ball, ruby);
    ball2.position.set(0,-10,-100);
    var ball3 = new THREE.Mesh(ball, ruby);
    ball3.position.set(100,-10,0);
    var ball4 = new THREE.Mesh(ball, ruby);
    ball4.position.set(-100,-10,0);

    var circle = new THREE.Mesh(circleShape, circleMaterial);
    circle.material.side = THREE.DoubleSide;
    circle.position.set(0,0,0);

    crown.add(ball1);
    crown.add(ball2);
    crown.add(ball3);
    crown.add(ball4);
    crown.add(circle);

    return crown;
}

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;
 
 bi = i
 bj = j;
}

//can contol queen using arrow keys
function moveLogicalAgent( a )			// this is called by the infrastructure that gets action a from the Mind
{
    var code = a.keyCode;

    if (code == 37)
    {
        leftInput = true;
        a.preventDefault();
    }   // left

    if (code == 39)
    {
        rightInput = true;
        a.preventDefault();
    }   // right

    if (code == 38){
        forwardInput = true;
        a.preventDefault();
    }   // forward

    if (code == 40){
        backwardInput = true;
        a.preventDefault();
    }   // back
}

function moveAgent()
{
    if (forwardInput)
    {
        theagent.position.x += Math.sin(theagent.rotation.y)*MOVEDISTANCE;
        theagent.position.z += Math.cos(theagent.rotation.y)*MOVEDISTANCE;
    }
    if (rightInput)
    {
        theagent.rotation.y -= TURNAMOUNT;
    }
    if (leftInput)
    {
        theagent.rotation.y += TURNAMOUNT;
    }
    if (backwardInput)
    {
        theagent.position.x -= Math.sin(theagent.rotation.y)*MOVEDISTANCE;
        theagent.position.z -= Math.cos(theagent.rotation.y)*MOVEDISTANCE;

    }
}

function turnAgent(direction)
{
    if (direction == RIGHT)
    {
        if(queenDirection == RIGHT)
        {
            queenDirection = DOWN;
            theagent.rotation.set(0,Math.PI,0);
        }
        else if(queenDirection == DOWN)
        {
            queenDirection = LEFT;
            theagent.rotation.set(0,Math.PI/2,0);
        }
        else if(queenDirection == LEFT)
        {
            queenDirection = UP;
            theagent.rotation.set(0,0,0);
        }
        else if(queenDirection == UP)
        {
            queenDirection = RIGHT;
            theagent.rotation.set(0,-Math.PI/2,0);
        }
    }
    else if (direction == LEFT)
    {
        if(queenDirection == LEFT)
        {
            queenDirection = DOWN;
            theagent.rotation.set(0,Math.PI,0);
        }
        else if(queenDirection == UP)
        {
            queenDirection = LEFT;
            theagent.rotation.set(0,+Math.PI/2,0);
        }
        else if(queenDirection == RIGHT)
        {
            queenDirection = UP;
            theagent.rotation.set(0,0,0);
        }
        else if(queenDirection == DOWN)
        {
            queenDirection = RIGHT;
            theagent.rotation.set(0,-Math.PI/2,0);
        }
    }
    else console.log("error using function turnAgent");

    console.log(queenDirection);
}

function keyUp(e)
{
    rightInput = false;
    leftInput = false;
    forwardInput = false;
    backwardInput = false;
}


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

// --- 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;
}
//checks if crown is picked up
function crownBlocked()
{
    return ( 	nearCrown (ai,aj));
}

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 status = "<font color=brown face=verdana> Welcome to Winterfell.. <br> </font>" + "<font color=brown size=4 face=verdana> <b>Winterfell seconds: </b> </font> " + step ;

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

 var status = "<font color=brown size=4 face=verdana> <b>Crowns collected: </b> </font>" + crowns ;

 $("#user_span4").html( status );


}

function   updateStatusAfter()		// agent and enemy have moved, can calculate score
{


 $("#user_span5").html( status );
 var status = "<font size=4 face=verdana> <b><br> Aim: </b>  <br> Collect all the Crowns, <br> Don't get caught by the fireball, <br> You also must capture the crowns within 500 seconds, <br>Control the Queen with the arrow keys. <br> Good Luck! </font>";

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

function switchToTPS()
{
    view = TPS;
}

function switchToChase()
{
    view = CHASE;
}

//--- public functions / interface / API ----------------------------------------------------------
	this.endCondition;
	this.endC;// 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;
  this.endC = false;
  badsteps = 0;
  goodsteps = 0;
	step = 0;
	crowns=0;


 // for all runs:

 	initGrid();
	initLogicalWalls();
	initLogicalMaze();
	initLogicalCrown();
	initLogicalAgent();
	initAgent2();
	initLogicalEnemy();

 // for graphical runs only:
  if ( true  )
  {
	if ( show3d )
	{
	 BOXHEIGHT = squaresize;
	 threeworld.init3d ( startRadiusConst, maxRadiusConst, SKYCOLOR  );
	 var thelight = new THREE.DirectionalLight ( LIGHTCOLOR, 3 );
    thelight.position.set ( startRadiusConst, startRadiusConst, startRadiusConst );
    threeworld.scene.add(thelight);
	}
	else
	{
	 BOXHEIGHT = 1;
	 threeworld.init2d ( startRadiusConst, maxRadiusConst, SKYCOLOR  );
	}

	initSkybox();
// 	animateParticles()
 	// initMusic();

	// Set up objects first:

	initThreeWalls();
    initThreeMaze();
    initThreeCrown();
	initThreeEnemy();

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

// 	let var7 = "<p>Advanced camera : <button id='tps'>TPS View</p></button>   <button id='chase'>Chase View</p></button>"
// 	$("#user_span7").html( var7 );

	document.addEventListener( 'keydown',  moveLogicalAgent );
	document.addEventListener( 'keyup',  keyUp );
// 	document.getElementById("tps").addEventListener("click", switchToTPS);
// 	document.getElementById("chase").addEventListener("click", switchToChase);

  threeworld.cameraMove();

    var light = new THREE.AmbientLight( 0x404040, 0.7 ); // soft white light
    threeworld.scene.add( light );
  }
};

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



this.nextStep = function()
{
    //   drawAgent();

    previousx = theagent.position.x;
    previousz = theagent.position.z;

    moveAgent();

    ai = Math.trunc(translateInv(theagent.position.x));
    aj = Math.trunc(translateInv(theagent.position.z));



    if (occupied(ai,aj)) //if running into occupied square, set position back to last frame's
    {
        console.log("Collision!");

        //tried to s;ooth out when running into a wall
        let pi = Math.trunc(translateInv(previousx));
        let pj = Math.trunc(translateInv(previousz));

        console.log("pi :", pi, "      pj : ",pj);
        if(occupied(pi,aj)) theagent.position.z = previousz;
        if(occupied(ai,pj)) theagent.position.x = previousx;

        // theagent.position.x = previousx;
        // theagent.position.z = previousz;

        ai = Math.trunc(translateInv(theagent.position.x));
        aj = Math.trunc(translateInv(theagent.position.z));
    }

    console.log("ai :", ai,"//    aj :",aj);

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



   //camera
    threeworld.follow = theagent.getObjectByName('tps').getWorldPosition();
    threeworld.lookat = theagent.position;




    step++;
    var a = 0;
    if ( true  )
    updateStatusBefore(a);			// show status line before moves

     moveLogicalAgent(a);

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










  if(crownBlocked())
  {
      let pickUp = new Audio(CROWNPICKUPFILE);
      pickUp.volume = 0.5;
      pickUp.play();
      crowns++;
      GRID[ai][aj] = GRID_BLANK;
      replaceShape(ai,aj);
      if(crowns == 8)
     {
         this.endCondition = true;
        //  musicPause();
        //  soundClap();
     }
  }
  if ( agentBlocked()|| step == MAXSTEPS)			// if agent blocked in, run over
  {
	this.endCondition = true;
	goodsteps = 0;			// you score zero as far as database is concerned
  	if ( true  )
  	{
	//  musicPause();
	//  soundAlarm();
	}
  }

    // switch(view)
    // {
    //     case TPS:
    //         threeworld.follow = theagent.children[0].position;
    //         threeworld.lookat = theagent.position;
    //         break;
    //     case CHASE:

    //         break;
    //     case OTHER:

    //         break;
    //     default:
    //         console.warn("bug im switch hahajajaaha")
    // }

};

this.endRun = function()
{
 if ( true  )
 {
//   musicPause();
  if ( this.endCondition )
    $("#user_span4").html( " &nbsp; <font color=red size=5 face=verdana> <B> Hard Luck,The Queen is burning in the fireball. </B> </font>   "  );
  if ( this.endC )
    $("#user_span6").html( " &nbsp; <font color=red> <B>  </B> </font>   "  );
  if(step == MAXSTEPS)
  {
     $("#user_span4").html( " &nbsp; <font color=red size=5 face=verdana> <B> Game over, You ran out time!  </B> </font>   "  );
  }
  else if(crowns == 8)
    $("#user_span4").html( " &nbsp; <font color=green size=5 face=verdana> <B> Congratulations! You collected all 8 crowns! </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/niamhbyrne/gameofthronestitlethemesonghddirectripdllink.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/niamhbyrne/explosionsoundeffectpowerpuffgirlsversion.mp3   autoplay  > </audio>";
//   	$("#user_span2").html( x );
// }

// function soundClap()
// {
//  	var x = "<audio    src=/uploads/niamhbyrne/winner.mp3   autoplay  > </audio>";
//   	$("#user_span2").html( x );
// }