Code viewer for World: Ch.7. Websocket functional...

// Ch.7
// Adding Websocket functionality  
// Click on opponent grid (a guess) is sent to opponent browser, where it sinks ships or misses.
// Opponent browser reports back what happened.


// The data to be sent is of two types:
//  my current guess: i,j
//  result of your last guess: i,j, (hit or miss)
 
 
 

// === start of code ===========================================================================================================

const gridsize 		= 10;							  	   
const squaresize 	= 100;							 
const MAXPOS 		= gridsize * squaresize;	  

const startRadiusConst	 	= MAXPOS * 2 ;		      
const maxRadiusConst 		= MAXPOS * 10 ;			   
	
const SKYCOLOR 		= 'lightyellow';			      

AB.maxSteps                 = 1000000;         
AB.drawRunControls          = false;
ABWorld.drawCameraControls  = false;          


 const TEXTURE_WALL 	= '/uploads/chapters/stone.png' ;
 const TEXTURE_SHIP 	= '/uploads/chapters/ship.png' ;
 const TEXTURE_FIRE 	= '/uploads/chapters/fire.png' ;
 
// credit:
// https://commons.wikimedia.org/wiki/File:Square_stone_brick_Texture.jpg
// https://commons.wikimedia.org/wiki/File:Regina_Maris.JPG
// https://commons.wikimedia.org/wiki/File:FIRE_01.JPG

var wall_texture, ship_texture, fire_texture; 
var thesea;       


var GRID1  = new Array(gridsize);	    // my grid
var GRID2  = new Array(gridsize);	    // my (initially blank) map of opponent grid 

const GRID_EMPTY = 0;
const GRID_WALL  = 1;
const GRID_SHIP  = 2;
const GRID_BURNT = 3;
const GRID_FAIL  = 4;




	ABWorld.init3d ( startRadiusConst, maxRadiusConst, SKYCOLOR  ); 

	loadTextures();		 	 
							
    
    
	
function loadTextures()		  // now has 3 textures to load 
{
	var loader1 = new THREE.TextureLoader();
	var loader2 = new THREE.TextureLoader();
	var loader3 = new THREE.TextureLoader();
		
	loader1.load ( TEXTURE_SHIP, function ( texture )  	 
	{
		ship_texture = texture;                  
		if ( ship_texture && wall_texture && fire_texture )	makeEverything();		// if all textures loaded from files  
	});	

	loader2.load ( TEXTURE_WALL, function ( texture )  		
	{
		wall_texture = texture;                  
		if ( ship_texture && wall_texture && fire_texture )	makeEverything();		  
	});	
	
	loader3.load ( TEXTURE_FIRE, function ( texture )  		
	{
		fire_texture = texture;                  
		if ( ship_texture && wall_texture && fire_texture )	makeEverything();		  
	});	
}




//--- two 2D grids  -------------------------------------------------------------------------------

function translateMy ( i, j )			 
// the absolute 3D position of an (i,j) square on my grid is:           
//  width x = (i * squaresize)      
// height y = 0                                
//  depth z = (j * squaresize) 
{
	var v = new THREE.Vector3();
	
	v.x = (i * squaresize) ;   		 
	v.y = 0 ;	
	v.z = (j * squaresize) ;   	
	
	return v;
}


function translateOpponent ( i, j )		
// put 2nd grid beside the 1st grid, offset on the x dimension 
{
	var v = new THREE.Vector3();

	v.x = (i * squaresize) + MAXPOS ;   		 
	v.y = 0 ;	
	v.z = (j * squaresize) ;   	

	return v;
}



//--- translate 3D point to a square in opponent's grid ----------------------------------
// all explained previously 

const minOpponentX = MAXPOS +            (1 * squaresize) - squaresize/2;
const maxOpponentX = MAXPOS + ((gridsize-2) * squaresize) + squaresize/2;

const minOpponentZ =                     (1 * squaresize) - squaresize/2;
const maxOpponentZ =          ((gridsize-2) * squaresize) + squaresize/2;


function point2address ( p )
{
    if ( p.x < minOpponentX ) return null;
    if ( p.x > maxOpponentX ) return null;
    if ( p.z < minOpponentZ ) return null;
    if ( p.z > maxOpponentZ ) return null;
    
    // else we are within the non-wall part of the opponent's grid 
    var i = ( p.x - MAXPOS ) / squaresize;
    var j = p.z / squaresize;
    
    i =  Math.round ( i );
    j =  Math.round ( j );
    return ( new THREE.Vector2 ( i, j ) );
}



	
function makeEverything()		 
{
    makeGrids();
    makeSea();
    makeShips();
    
    // start socket for this World
    // see "Websockets" in Docs 
    // or just select the line below and click "Code Help"

    AB.socketStart();
}


function makeGrids()
{
	var i,j, shape, thecube,   position, lookat;
	shape    = new THREE.BoxGeometry ( squaresize, squaresize, squaresize );			 

	for ( i = 0; i < gridsize ; i++ )  
	{
	  GRID1[i] = new Array(gridsize);		// make each element an array of size "gridsize"
	  GRID2[i] = new Array(gridsize);
	  
	  for ( j = 0; j < gridsize ; j++ ) 
	  {
		if ( ( i==0 ) || ( i==gridsize-1 ) || ( j==0 ) || ( j==gridsize-1 ) )         
		{
		    GRID1[i][j] = GRID_WALL;
		    GRID2[i][j] = GRID_WALL;
		    
			thecube = new THREE.Mesh( shape );
			thecube.material = new THREE.MeshBasicMaterial( { map: wall_texture } );
			position = translateMy(i,j);                
			thecube.position.copy ( position ); 		
			ABWorld.scene.add(thecube);
			
			thecube = new THREE.Mesh( shape );
			thecube.material = new THREE.MeshBasicMaterial( { map: wall_texture } );
			position = translateOpponent(i,j);                
			thecube.position.copy ( position ); 		
			ABWorld.scene.add(thecube);
		}
		else 
		{
		    GRID1[i][j] = GRID_EMPTY;
		    GRID2[i][j] = GRID_EMPTY;
		}
	  }
	}

// position and "lookat" of camera explained previously:

    position = new THREE.Vector3 ( MAXPOS,   MAXPOS * 1.2,   MAXPOS * 1.3 );
    lookat   = translateMy ( gridsize,  gridsize/2  );
    ABWorld.cameraCustom ( position, lookat );         
}

 
function makeSea()      
{
  var shape = new THREE.PlaneGeometry ( MAXPOS * 2,  MAXPOS  );      // make a "sea" plane for 2 grids side by side   
  thesea = new THREE.Mesh ( shape );
  thesea.material    = new THREE.MeshBasicMaterial ( { color: 'lightblue', side: THREE.DoubleSide } );
  thesea.rotation.set ( Math.PI / 2, 0, 0 );        // rotate it 90 degrees   
  
  // "position" of sea explained previously
  thesea.position.set ( MAXPOS - squaresize/2,      - squaresize * 0.4 ,      MAXPOS/2 - squaresize/2 );  

  ABWorld.scene.add ( thesea );
}

 
function makeShips()    
// make randomised ships in my grid
{
	 var  p, i, j, shape, thecube, position;
	 shape = new THREE.BoxGeometry ( squaresize, squaresize, squaresize );	
	 
	 for ( p = 1; p <=5 ; p++ )    
	 {
    	 thecube = new THREE.Mesh( shape );
     	 thecube.material =  new THREE.MeshBasicMaterial( { map: ship_texture } );
     	 i = AB.randomIntAtoB ( 1, gridsize-2 );    // positions 0 and (gridsize-1) are walls 
     	 j = AB.randomIntAtoB ( 1, gridsize-2 ); 
     	 position = translateMy ( i, j );        
     	 thecube.position.copy ( position ); 
    	 ABWorld.scene.add(thecube);

		 GRID1[i][j] = GRID_SHIP;
	 }
}
 


// Mouse click all explained previously:

ABHandler.initMouseDrag = function ( x, y )  
{ 
    trySquare ( x, y );      
    ABHandler.initCameraDrag ( x, y );  
};


function trySquare ( x, y )
{
    if ( ABWorld.hitsObject ( x, y, thesea ) )
    {
        var p = ABWorld.hitsObjectPoint ( x, y, thesea );  
        var a = point2address ( p );
        
        if ( a )
        {
            // we have a valid click 
            // send "a" to opponent as our guess 
            sendGuess ( a );    
        }
    }
}



//--- Websockets functions --------------------------------------------------------------------------------

function sendGuess ( a )
// send my guess (a 2D point) to the other player 
{
  var data = 
  {
    guess: a
  };
  
  AB.socketOut ( data );   
}  
  

function sendReply ( i, j, hit )
// tell the other player if their guess i,j was a hit or not 
{
  var data = 
  {
    reply: [ i, j, hit ]        // send an array of the 3 pieces of data 
  };
  
  AB.socketOut ( data );   
}



// receive data on Websocket

AB.socketIn = function(data)
{
    var i,j, shape, position, thecube, hit;
	
	// two types of incoming data - opponent guess and reply to my last guess
	// in both cases we will be making a cube at some location 
	shape = new THREE.BoxGeometry ( squaresize, squaresize, squaresize );	
    thecube = new THREE.Mesh( shape );
	
    if ( data.guess )     // if this field exists  
    {
        i = data.guess.x;   
        j = data.guess.y;   
        
        if ( ( GRID1[i][j] == GRID_SHIP ) || ( GRID1[i][j] == GRID_BURNT ) )    // if ship or burnt (already burnt this spot)
        {
            GRID1[i][j] = GRID_BURNT;       // opponent success
            // make a square of fire at that location 
         	thecube.material = new THREE.MeshBasicMaterial( { map: fire_texture } );
            position = translateMy ( i, j );        // cube goes onto my grid 
         	sendReply ( i, j, true );               // tell the opponent what happened
        }        
        else
        {
            GRID1[i][j] = GRID_FAIL;       // opponent failure 
            // make a failure square at that location 
         	thecube.material = new THREE.MeshBasicMaterial ( { color: 'navy' } );
            position = translateMy ( i, j );          
         	sendReply ( i, j, false );
        }
    }
    
    if ( data.reply )     // if this field exists  
    {
        i = data.reply[0];   
        j = data.reply[1];
        hit = data.reply[2]; 
        
        if ( hit )
        {
            GRID2[i][j] = GRID_BURNT;       // my success
            // make a square of fire at that location 
         	thecube.material = new THREE.MeshBasicMaterial( { map: fire_texture } );
            position = translateOpponent ( i, j );        // cube goes onto my map of opponent grid 
        }        
        else
        {
            GRID2[i][j] = GRID_FAIL;       // my failure 
            // make a failure square at that location 
         	thecube.material = new THREE.MeshBasicMaterial ( { color: 'navy' } );
            position = translateOpponent ( i, j );          
        }        
    }
    
    // now the cube is ready to be put in the scene     
    thecube.position.copy ( position ); 
    ABWorld.scene.add(thecube);            
};  
  
  
// === end of code ===========================================================================================================




// To have a 2 player game:
// Both players must run the same World.
// (Give the URL to the other player.)
 
 
// This game is a bit chaotic.
// You can just fire off clicks to the other user. 
// Also more than 2 users can join.
// We will fix this in the next chapter.


// Exercises:
// Change the number of ships.
// Make ships always be 2 or 3 squares in a row.
// Keep track of score.  
// Declare a winner at end.

 
// Outcomes: Student can:
// Learn how to make a multi-user web game.
// Learn how users on web browsers in different places can talk to each other using Websockets.
// Get introduced to the problem of synchronising code on two different web browsers.