// Cloned by James Humphrys on 8 Jan 2020 from World "Stay in the box!" by Liam Nunez
// Please leave this clone trail here.
//Stay in the Box! - By Liam Nunez
//This is the world and mind I'm submitting for grading
//Uses the complex world template
// =============================================================================================
// Scoring:
// Steps - the amount of steps survived until the box is inevitably touched by the agent.
// The box will move faster after 500 steps and 5000 steps.
// Each step is 10ms.
// 1 million steps maximum.
// =============================================================================================
// World must define these:
const CLOCKTICK = 1; // speed of run - move things every n milliseconds
const MAXSTEPS = 1000000; // length of a run before final score
const SCREENSHOT_STEP = 1;
//---- global constants: -------------------------------------------------------
const gridsize = 40; // 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 BLUECOLOR = 0x3498db; //extra colors
const BLACKCOLOR = 0x000000;
const GREENCOLOR = 0x27ae60;
const REDCOLOR = 0xff0000;
const BLANKCOLOR = SKYCOLOR ; // make objects this color until texture arrives (from asynchronous file read)
const show3d = false; // 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_ENEMY = 3; //Enemy = the moving box in this game
// --- 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 = 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, theenemy;
// enemy and agent position on squares
var ei, ej, 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_BLANK ;
}
}
}
// 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 ) );
}
// --- add fixed objects ----------------------------------------
var enemyPosX = 10;
var enemyPosY = 7;
//enemyPos is the inital starting point for the centre of the box
var enemyCubes = 20;
var containerSide = 6;
//container side is how many squares the box will have on each side
var containers = new Array(containerSide*4);
//containers is the array which holds every border square in the box
var directionX = 1, directionY = 1;
//this is the direction the box is travelling in for x and y positions. can only be 1 or -1.
//Randomizes the starting points and direction for each game to make it more interesting
function randomizeStartingValues(){
enemyPosX = randomintAtoB(containerSide + 1, gridsize - containerSide - 1);
enemyPosY = randomintAtoB(containerSide + 1, gridsize - containerSide - 1);
if (randomBoolean())
directionX = 1;
else directionX = - 1;
if (randomBoolean())
directionY = 1;
else directionY = - 1;
}
function initLogicalContainer(){
for (var i = 0; i < gridsize ; i++)
for (var j = 0; j < gridsize ; j++)
if (GRID[i][j] == GRID_ENEMY)
GRID[i][j] = GRID_BLANK;
for ( i = 0; i < containerSide + 1; i++) {
GRID[enemyPosX - 3 + i][enemyPosY + 3] = GRID_ENEMY;
}
for ( i = 0; i < containerSide; i++) {
GRID[enemyPosX + 3][enemyPosY - 3 + i] = GRID_ENEMY;
}
for ( i = 0; i < containerSide; i++) {
GRID[enemyPosX - 3 + i][enemyPosY - 3] = GRID_ENEMY;
}
for ( i = 0; i < containerSide; i++) {
GRID[enemyPosX - 3][enemyPosY - 3 + i] = GRID_ENEMY;
}
}
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( GREENCOLOR );
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 initThreeContainer()
{
var t = 0;
for (var i = 0; i < gridsize ; i++)
for (var j = 0; j < gridsize ; j++)
if ( GRID[i][j] == GRID_ENEMY )
{
var shape = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );
containers[t] = new THREE.Mesh( shape );
containers[t].material.color.setHex( BLUECOLOR );
containers[t].position.x = translate ( i * squaresize );
containers[t].position.z = translate ( j * squaresize );
containers[t].position.y = 0;
threeworld.scene.add(containers[t]);
t++;
}
}
function drawContainer(){
var t = 0;
for (var i = 0; i < gridsize ; i++)
for (var j = 0; j < gridsize ; j++)
if ( GRID[i][j] == GRID_ENEMY )
{
containers[t].position.x = translate ( i * squaresize );
containers[t].position.z = translate ( j * squaresize );
containers[t].position.y = 0;
threeworld.scene.add(containers[t]);
t++;
}
}
//This function does exactly what it says
function isAgentAndContainerColliding(){
if (GRID[ai][aj] == GRID_ENEMY) {
return true;
}
return false;
}
function moveContainer() //moves the container based on its centre square
{
enemyPosX += directionX;
enemyPosY += directionY;
if (enemyPosX + 3 >= (gridsize - 1) || enemyPosX - 3 <= 0)
directionX = -directionX;
if (enemyPosY + 3 >= (gridsize - 1) || enemyPosY - 3 <= 0)
directionY = -directionY;
}
// --- 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 initMyAgent()
{
ai = enemyPosX;
aj = enemyPosY;
}
function initThreeAgent()
{
var shape = new THREE.BoxGeometry( squaresize, BOXHEIGHT, squaresize );
theagent = new THREE.Mesh( shape );
theagent.material.color.setHex( REDCOLOR );
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--;
ai = i;
aj = j;
}
function updateStatus(){
var status1 = " Step: <b> " + step + " </b>";
var status2 = "<font color=green> Stay in the box as long as you can! (the box will move faster the longer you stay) </font> <BR>";
$("#user_span3").html( status1 );
$("#user_span5").html( status2 );
}
//--- 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();
randomizeStartingValues();
initLogicalContainer();
initMyAgent();
// for graphical runs only:
if ( true )
{
if ( show3d )
{
BOXHEIGHT = squaresize;
threeworld.init3d ( startRadiusConst, maxRadiusConst, BLACKCOLOR );
}
else
{
BOXHEIGHT = 1;
threeworld.init2d ( startRadiusConst, maxRadiusConst, BLACKCOLOR);
}
initMusic();
// Set up objects first:
initThreeWalls();
initThreeContainer();
initThreeAgent();
}
};
this.getState = function()
{
var x = [ GRID, ai, aj,];
return ( x );
};
var containerFlag = 0; // the box only will move when this variable is equal to the one below. this variable will increase once per step and reset to 0 each time the box moves.
var moveContainerAction = 30;
this.takeAction = function ( a )
{
step++;
//move agent based on action from the mind:
moveLogicalAgent(a);
//speed up the moving box at these 2 steps:
if (step == 5 || step == 50)
moveContainerAction -= 10;
//after the needed amount of steps, the box can finally move
if (containerFlag == moveContainerAction){
initLogicalContainer();
moveContainer();
}
if ( true )
{
drawAgent();
if (containerFlag == moveContainerAction)
drawContainer();
updateStatus();
}
if (isAgentAndContainerColliding()) {
this.endCondition = true;
goodsteps = step;
}
if (containerFlag < moveContainerAction)
containerFlag++;
else
containerFlag = 0;
};
this.endRun = function()
{
if ( true )
{
musicPause();
if ( this.endCondition ) {
var endmsg = " <font color=red> <B> You touched the box. Final score: " + step + ". </B> </font> ";
$("#user_span6").html( endmsg );
}
else {
goodsteps = step;
$("#user_span6").html( " <font color=red> <B> You've survived 1,000,000 steps somehow... I guess you win! </B> </font> " );
}
}
};
this.getScore = function()
{
return step;
};
}
//---- 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/starter/Defense.Line.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 );
}