Code viewer for World: Experiment - join other World



// ==== Starter World =================================================================================================
// This code is designed for use on the Ancient Brain site.
// This code may be freely copied and edited by anyone on the Ancient Brain site.
// To include a working run of this program on another site, see the "Embed code" links provided on Ancient Brain.
// ====================================================================================================================



// Demo of Ancient Brain Websockets functionality. 
// Click button and it changes colour in all clients. 

const yellow 	= "#ffffcc";
const grey		= "#eeeeee";


// default body is margin 0 and padding 0 

  $('body').css( "margin", "20px" );
  $('body').css( "padding", "20px" );

 
document.write ( `

<h1> Websockets test </h1>

Run this on two different devices.
<p>
Click button to  set background color  in all runs on all devices:
<p>

 <button onclick="setYellow();"   class=ab-largenormbutton > Yellow </button> 
 <button onclick="setGrey();"     class=ab-largenormbutton > Grey </button> 

` );




// fake other World

AB.worldid = "4592716058";    // World X

// (subtle bug): if you make this a number, 
// then Websockets room id is the number 
// which is different from the other room, whose id is a string 

// start socket for this World

AB.socketStart();

// no matter what the code is in World X 
// you can just wrote code here in a different World 
// and change AB.worldid
// and join the socket for World X





// --- When I click, set the color and send info to server ----------------------------------------------------------------

function setYellow()
{
  document.body.style.background = yellow;
  sendtoServer(yellow);
}

function setGrey()
{
  document.body.style.background = grey;
  sendtoServer(grey);
}

function sendtoServer ( thecolor )
{  
  var data = 
  {
   color: thecolor
  };
  
  AB.socketOut ( data );        // server gets this, and sends the data to all clients running this World
}



// --- When someone else clicks, server will send me a message and I can set the color -------------------------------------
// define what to do when we get incoming data on the socket: 

AB.socketIn = function(data)
{
    document.body.style.background = data.color;
};