//
// Get the character to the exit point of the Takeshi's Castle inspired Maze.
//Avoid being caught by the Guards if the Maze. The guards can move through the walls so be careful
//Some doors are fake and your character will not be able to go through them
const CLOCKTICK = 300; // speed of run - move things every n milliseconds
const MAXSTEPS = 1000; // length of a run before final score
//---- global constants: -------------------------------------------------------
const gridsize = 71; // number of squares along side of world
const NOBOXES = 0;
// 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 = 0xddffcc ; // 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 * 20 ; // 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_FLOOR = 0;
const GRID_WALL = 1;
const GRID_DOOR = 2;
const GRID_FALSE_DOOR = 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; }
}
//---- 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 = []; // need to keep handles to wall and maze objects so can find them later to paint them
var DOOR = [];
var FALSE_DOOR = [];
var FLOOR = [];
var theagent, theenemy;
// enemy and agent position on squares
var ei, ej, eiTwo, ejTwo, ai, aj;
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_FLOOR ;
}
}
}
function occupied ( i, j ) // is this square occupied
{
if ( ( ei == i ) && ( ej == j ) ) return true;
if ( ( eiTwo == i ) && ( ejTwo == j ) ) return true;
if ( ( ai == i ) && ( aj == j ) ) return true;
if ( GRID[i][j] == GRID_WALL ) return true; // fixed objects
if ( GRID[i][j] == GRID_DOOR) return false;
if ( GRID[i][j] == GRID_FALSE_DOOR) 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
}
// 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.
// --- 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()
{
var loader1 = new THREE.TextureLoader();
loader1.load ( '/uploads/shuntaminaguchi/wall2.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
paintWalls ( new THREE.MeshBasicMaterial( { map: thetexture } ) );
} );
var loader2 = new THREE.TextureLoader();
loader2.load ( '/uploads/shuntaminaguchi/reddoor.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
paintDoor( new THREE.MeshBasicMaterial( { map: thetexture } ) );
} );
var loader3 = new THREE.TextureLoader();
loader3.load ( '/uploads/shuntaminaguchi/j.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
theagent.material = new THREE.MeshBasicMaterial( { map: thetexture } );
} );
var loader4 = new THREE.TextureLoader();
loader4.load ( '/uploads/shuntaminaguchi/tumblr_m9j2jnglpu1qe2g1xo1_250.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
theenemy.material = new THREE.MeshBasicMaterial( { map: thetexture } );
} );
var loader5 = new THREE.TextureLoader();
loader5.load ( '/uploads/shuntaminaguchi/demon1_zpsfiv1ggxf.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
secondEnemy.material = new THREE.MeshBasicMaterial( { map: thetexture } );
} );
var loader6 = new THREE.TextureLoader();
loader6.load ( '/uploads/shuntaminaguchi/reddoor.jpg', function ( thetexture ) {
thetexture.minFilter = THREE.LinearFilter;
paintFalseDoor.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(j === 0 && (i > 10 && i < 20)){}
else if ( ( i=== 20 ) || ( i==gridsize-1 ) || ( j===0 ) || ( j==gridsize-1 ) || (j % 10 === 0) || (i % 10 ===0) )
{
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 = squaresize *2;
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 initLogicalDoor()
{
var j;
for (var i = 10; i < gridsize -10; i = i +10){
j = 14;
while( j < gridsize -10){
GRID[i][j] = GRID_DOOR ;
GRID[j][i] = GRID_DOOR ;
j++;
GRID[i][j] = GRID_DOOR ;
GRID[j][i] = GRID_DOOR ;
j++;
GRID[i][j] = GRID_DOOR ;
GRID[j][i] = GRID_DOOR ;
j = j + 8;
}
}
}
function initThreeDoor()
{
var t = 0;
for (var i = 0; i < gridsize ; i++)
for (var j = 0; j < gridsize ; j++)
if ( GRID[i][j] == GRID_DOOR )
{
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 = squaresize *2 ;
threeworld.scene.add(thecube);
DOOR[t] = thecube; // save it for later
t++;
}
}
function paintDoor ( material )
{
for ( var i = 0; i < DOOR.length; i++ )
{
if ( DOOR[i] ) DOOR[i].material = material;
if ( FALSE_DOOR[i] ) FALSE_DOOR[i].material = material;
}
}
function initLogicalFalseDoor()
{
GRID[54][40] = GRID_FALSE_DOOR;
GRID[55][40] = GRID_FALSE_DOOR;
GRID[56][40] = GRID_FALSE_DOOR;
GRID[34][40] = GRID_FALSE_DOOR;
GRID[35][40] = GRID_FALSE_DOOR;
GRID[36][40] = GRID_FALSE_DOOR;
GRID[30][24] = GRID_FALSE_DOOR;
GRID[30][25] = GRID_FALSE_DOOR;
GRID[30][26] = GRID_FALSE_DOOR;
GRID[30][44] = GRID_FALSE_DOOR;
GRID[30][45] = GRID_FALSE_DOOR;
GRID[30][46] = GRID_FALSE_DOOR;
GRID[14][50] = GRID_FALSE_DOOR;
GRID[15][50] = GRID_FALSE_DOOR;
GRID[16][50] = GRID_FALSE_DOOR;
GRID[34][20] = GRID_FALSE_DOOR;
GRID[35][20] = GRID_FALSE_DOOR;
GRID[36][20] = GRID_FALSE_DOOR;
GRID[40][14] = GRID_FALSE_DOOR;
GRID[40][15] = GRID_FALSE_DOOR;
GRID[40][16] = GRID_FALSE_DOOR;
GRID[10][14] = GRID_FALSE_DOOR;
GRID[10][15] = GRID_FALSE_DOOR;
GRID[10][16] = GRID_FALSE_DOOR;
GRID[10][34] = GRID_FALSE_DOOR;
GRID[10][35] = GRID_FALSE_DOOR;
GRID[10][36] = GRID_FALSE_DOOR;
GRID[30][54] = GRID_FALSE_DOOR;
GRID[30][55] = GRID_FALSE_DOOR;
GRID[30][56] = GRID_FALSE_DOOR;
GRID[20][34] = GRID_FALSE_DOOR;
GRID[20][35] = GRID_FALSE_DOOR;
GRID[20][36] = GRID_FALSE_DOOR;
}
function initThreeFalseDoor()
{
var t = 0;
for (var i = 0; i < gridsize ; i++)
for (var j = 0; j < gridsize ; j++)
if ( GRID[i][j] == GRID_FALSE_DOOR )
{
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 = squaresize *2 ;
threeworld.scene.add(thecube);
FALSE_DOOR[t] = thecube; // save it for later
t++;
}
}
function initThreeFloor() // graphical run only, set up blank boxes, painted later
{
var f = 0;
for (var i = 0; i < gridsize ; i++)
for (var j = 0; j < gridsize ; j++)
if ( GRID[i][j] == GRID_FLOOR )
{
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);
FLOOR[f] = thecube; // save it for later
f++;
}
}
function paintFloor ( material )
{
for ( var i = 0; i < FLOOR.length; i++ )
{
if ( FLOOR[i])
FLOOR[i].material = material;
}
}
// --- enemy functions -----------------------------------
function initLogicalEnemy()
{
// start in random location:
ei = 25;
ej = 5;
}
function drawEnemy() // given ei, ej, draw it
{
var x = translate ( ei * squaresize );
var z = translate ( ej * squaresize );
var y = squaresize;
theenemy.position.x = x;
theenemy.position.y = y;
theenemy.position.z = z;
threeworld.scene.add(theenemy);
// if camera moving, look back at where the enemy is
}
function initThreeEnemy()
{
var shape = new THREE.BoxGeometry( squaresize, BOXHEIGHT/3, squaresize );
theenemy = new THREE.Mesh( shape );
theenemy.material.color.setHex( BLANKCOLOR );
drawEnemy();
}
function moveLogicalEnemy()
{
// 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);
ei = i;
ej = j;
}
// --- Second enemy -------------
function initLogicalEnemy2()
{
eiTwo = 16;
ejTwo= 6;
}
function drawSecondEnemy() // given ei, ej, draw it
{
var x = translate ( eiTwo * squaresize );
var z = translate ( ejTwo * squaresize );
var y = squaresize;
secondEnemy.position.x = x;
secondEnemy.position.y = y;
secondEnemy.position.z = z;
threeworld.scene.add(secondEnemy);
}
function initThreeEnemy2()
{
var shape = new THREE.BoxGeometry( squaresize, BOXHEIGHT/3, squaresize );
secondEnemy = new THREE.Mesh( shape );
secondEnemy.material.color.setHex( BLANKCOLOR );
drawSecondEnemy();
}
function moveLogicalEnemy2()
{
// move towards agent
// put some randomness in so it won't get stuck with barriers
var i, j;
if ( eiTwo < ai ) i = randomintAtoB(eiTwo, eiTwo+1);
if ( eiTwo == ai ) i = eiTwo;
if ( eiTwo > ai ) i = randomintAtoB(eiTwo-1, eiTwo);
if ( ejTwo < aj ) j = randomintAtoB(ejTwo, ejTwo+1);
if ( ejTwo == aj ) j = ejTwo;
if ( ejTwo > aj ) j = randomintAtoB(ejTwo-1, ejTwo);
eiTwo = i;
ejTwo = j;
}
// --- agent functions -----------------------------------
function drawAgent() // given ai, aj, draw it
{
var x = translate ( ai * squaresize );
var z = translate ( aj * squaresize );
var y = squaresize;
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 in specified location:
// ai = 15;
//aj = 9;
ai = 55;
aj = 65;
}
function initThreeAgent()
{
var shape = new THREE.BoxGeometry( squaresize, squaresize, 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 ) {
threeworld.lookat.copy ( theagent.position );
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_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 badstep() // is the enemy within one square of the agent
{
if ( ( Math.abs(ei - ai) < 2 ) && ( Math.abs(ej - aj) < 2 ) ) return true;
else if ( ( Math.abs(eiTwo - ai) < 2 ) && ( Math.abs(ejTwo - aj) < 2 ) ) return true;
else return false;
}
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 x = self.getState();
var status = " Step: <b> " + step + " </b> x = (" + x.toString() + ") 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 = " y = (" + y.toString() + ") <BR> ";
$("#user_span4").html( status );
var score = self.getScore();
var status = " Bad steps: " + badsteps +
" Good steps: " + goodsteps +
" 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();
initLogicalDoor();
initLogicalFalseDoor();
initLogicalAgent();
initLogicalEnemy();
initLogicalEnemy2();
// for graphical runs only:
if ( true )
{
if ( show3d )
{
BOXHEIGHT = 500;
threeworld.init3d ( startRadiusConst, maxRadiusConst, SKYCOLOR );
}
else
{
BOXHEIGHT = 1;
threeworld.init2d ( startRadiusConst, maxRadiusConst, SKYCOLOR );
}
initSkybox();
// Set up objects first:
initThreeWalls();
initThreeDoor();
initThreeFloor();
initThreeAgent();
initThreeEnemy();
initThreeEnemy2();
initThreeFalseDoor();
// 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, eiTwo, ejTwo ];
return ( x );
};
this.takeAction = function ( a )
{
step++;
if ( true )
updateStatusBefore(a); // show status line before moves
// moveLogicalAgent(a);
moveLogicalEnemy();
moveLogicalEnemy2();
if ( badstep() ){
score = 0;
badsteps++;
this.endCondition = true;
}
else
goodsteps++;
if ( true )
{
drawAgent();
drawEnemy();
drawSecondEnemy();
updateStatusAfter(); // show status line after moves
}
if((aj<9) && (ai > 10 && ai < 20))
this.endCondition = true;
};
this.endRun = function()
{
if ( true )
{
musicPause();
if ( this.endCondition )
$("#user_span6").html( " <font color=red> <B> Agent trapped. Final score zero. </B> </font> " );
else
$("#user_span6").html( " <font color=red> <B> Run over. </B> </font> " );
}
};
this.getScore = function()
{
if(goodsteps == step)
return ( ( goodsteps / step ) * 100 );
else return 0;
};
}
//---- end of World class -------------------------------------------------------