// =============================================================================================
// 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)
// =============================================================================================
// =============================================================================================
// Help Dr. Mark Humphrys get out of the Worlds Hardest Maze
// You have 200 steps to help him escape or else he'll be stuck forever
//
// This is a complex hedge maze and is difficult to complete in one attempt
// =============================================================================================
// =============================================================================================
// How to improve
// 1. It was quite difficult to find errors in my code or to figure out where I went wrong when the
// world wouldn't load
// 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
//---- global constants: -------------------------------------------------------
const gridsize = 33; // number of squares along side of world
const NOBOXES = Math.trunc ( (gridsize * gridsize) / 10 );
// 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_BLOCK = 1;
// --- 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
//Creation of the Maze - 2d Array
var GRID = [
[1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1],
[1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,0,1],
[1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,1],
[1,0,1,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1,1,1,0,1,0,1,0,1,1,0,1,0,1,0,1],
[1,0,1,0,1,0,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,1,0,1,0,1,1,0,1,0,1,0,1],
[1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,1,0,1,0,1],
[1,0,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1,0,0,1,0,1,0,1,0,1,0,0,0,0,1,0,1],
[1,1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,0,1,0,1,0,1,1,0,1,0,1],
[1,0,1,0,0,0,0,0,1,1,1,1,0,1,1,0,1,0,0,1,1,1,1,1,0,0,0,0,1,0,1,0,1],
[1,0,1,1,1,0,1,1,1,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,0,1,1,0,1,0,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,1,1,1,0,0,1,0,1,0,1],
[1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,0,1,0,1,0,1,0,1,1,1,1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],
[1,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1],
[1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,0,1,0,1,1,1,1,0,0,0,0,0,0,0,1],
[1,0,0,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,0,1,1,1],
[1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1],
]; // 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 theagent;
// enemy and agent position on squares
var ai, aj;
var step = 0;
var self = this; // needed for private fn to call public fn - see below
function occupied ( i, j ) // is this square occupied
{ // variable objects
if ( ( ai == i ) && ( aj == j ) ) return true;
if ( GRID[i][j] == GRID_BLOCK ) return true; // fixed objects
if ( GRID[i][j] == GRID_BLOCK ) 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()
{
//Garden Skybox - 360 photo cut into 4
var materialArray = [
( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/jordanm/garden1.jpg" ), side: THREE.BackSide } ) ),
( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/jordanm/garden3.jpg" ), side: THREE.BackSide } ) ),
( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/jordanm/sky.jpg" ), 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/jordanm/garden4.jpg" ), side: THREE.BackSide } ) ),
( new THREE.MeshBasicMaterial ( { map: THREE.ImageUtils.loadTexture( "/uploads/jordanm/garden2.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 loadTextures()
{
// The hedge/blocks texture
var loader1 = new THREE.TextureLoader();
loader1.load ( '/uploads/jordanm/hedge.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
paintWalls ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
} );
var loader2 = new THREE.TextureLoader();
loader2.load ( '/uploads/jordanm/hedge.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
paintMaze ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
} );
// The texture for our agent (Dr. Mark Humphrys) - Credit to http://computing.dcu.ie/~humphrys/
var loader3 = new THREE.TextureLoader();
loader3.load ( '/uploads/jordanm/mark.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
theagent.material = new THREE.MeshBasicMaterial( { map: thetexture } );
} );
}
// --- add fixed objects ----------------------------------------
function initLogicalBlocks() // set up logical Blocks in data structure, whether doing graphical run or not
{
for (var i = 0; i < gridsize ; i++)
for (var j = 0; j < gridsize ; j++)
if ( GRID[i][j] == 1 )
{
GRID[i][j] = GRID_BLOCK ;
}
}
function initThreeBlocks() // 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_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 ); // 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;
}
}
// --- agent functions -----------------------------------
function drawAgent() // given ai, aj, draw it
{
var x = translate ( ai * squaresize );
var z = translate ( aj * squaresize );
var y = 0;
theagent.position.x = x;
theagent.position.y = y;
theagent.position.z = z;
threeworld.scene.add(theagent);
threeworld.follow.copy ( theagent.position ); // follow vector = agent position (for camera following agent)
}
function initLogicalAgent()
{
// start at 0,1
var i, j;
do
{
i = 0;
j = 1;
}
while ( occupied(i,j) ); // search for empty square
ai = i;
aj = j;
}
function initThreeAgent()
{
var shape = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );
theagent = new THREE.Mesh( shape );
theagent.material.color.setHex( BLANKCOLOR );
drawAgent();
}
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.
{
//To count how many steps taken
step++;
if (e.keyCode == 37)
{
moveLogicalAgent ( ACTION_LEFT );
threeworld.lookat.copy ( theagent.position );
}
if (e.keyCode == 38)
{
moveLogicalAgent ( ACTION_DOWN );
threeworld.lookat.copy ( theagent.position );
}
if (e.keyCode == 39)
{
moveLogicalAgent ( ACTION_RIGHT );
threeworld.lookat.copy ( theagent.position );
}
if (e.keyCode == 40)
{
moveLogicalAgent ( ACTION_UP );
threeworld.lookat.copy ( theagent.position );
}
}
// --- score: -----------------------------------
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
{
//Display number of steps
var x = self.getState();
var status = " Step: <b> " + step + " </b> x = (" + x.toString() + ") ";
$("#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 = " y = (" + y.toString() + ") <BR> ";
$("#user_span4").html( status );
//Display number of steps left
var stepsL = " Your have " + self.stepsLeft() + " steps left <BR> ";
$("#user_span5").html( stepsL );
}
//--- public functions / interface / API ----------------------------------------------------------
this.endCondition; // If set to true, run will end.
this.completed; // If set to true, will have completed the Maze
this.fail; // If set to true, will have failed to complete the Maze
this.newRun = function()
{
// (subtle bug) must reset variables like these inside newRun (in case do multiple runs)
this.endCondition = false;
this.completed = false;
this.fail = false;
step = 0;
// for all runs:
initLogicalBlocks();
initLogicalAgent();
// 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:
initThreeBlocks();
initThreeAgent();
// 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];
return ( x );
};
this.takeAction = function ( a )
{
if ( true )
updateStatusBefore(a); // show status line before moves
if ( true )
{
drawAgent();
updateStatusAfter(); // show status line after moves
}
if(ai > 31 && aj > 30) // if at end of Maze
{
this.endCondition = true;
this.completed = true;
if ( true )
{
musicPause();
soundAlarm();
}
}
if(step > 199) // Ran out of steps
{
this.endCondition = true;
this.fail = true;
if ( true )
{
musicPause();
soundAlarm2();
}
}
};
this.endRun = function()
{
if ( true )
{
musicPause();
if ( this.endCondition )
{
//show3d = false;
if(this.completed)
$("#user_span6").html( " <font color=red> <B> You completed the Maze!! </B> </font> " );
if(this.fail)
$("#user_span6").html( " <font color=red> <B> Game over..loser :) </B> </font> " );
}
}
};
//To display steps left
this.stepsLeft = function()
{
return ( 200 - step );
};
}
//---- end of World class -------------------------------------------------------
function initMusic()
{
// Background music
var x = "<audio id=theaudio src=/uploads/jordanm/background2.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();
}
// Winners music
function soundAlarm()
{
var x = "<audio src=/uploads/jordanm/win.mp3 autoplay > </audio>";
$("#user_span2").html( x );
}
// Losers music
function soundAlarm2()
{
var x = "<audio src=/uploads/jordanm/lose.mp3 autoplay > </audio>";
$("#user_span2").html( x );
}