diff options
| -rw-r--r-- | examples/jarvis.js | 65 | 
1 files changed, 40 insertions, 25 deletions
diff --git a/examples/jarvis.js b/examples/jarvis.js index 433d2b0..065100d 100644 --- a/examples/jarvis.js +++ b/examples/jarvis.js @@ -10,62 +10,77 @@ const Search = require('../tools/search');  const Queue = require('../tools/queue');  const ri = require('../utils/rectintersect'); +//// Basic handling on open and close of the socket  var main = new Socket(); -main.on('open', ()=>{ // Tries to identify itself with a cursor movement +main.on('open', open); +main.on('close', deinit); + +//// tileUpdates require knowledge of the prog's identity (sender) +var sender; +main.on('tileUpdate', tileHandler); + +//// Configurable helpers for utilities +function init(send){ +  sender = send; +  writes.enable(); +} + +function deinit(){ +  writes.disable(); +} + +function initOnce(){ +  timect(); +} + +var funcs = [protectArea, detectPrompt]; + +//// Management utilities +// "Pings" the server with a cursor location which is then detected +function open(){    console.log('socket opened');    let coords = [Math.floor(Math.random()*100000+16),Math.floor(Math.random()*100000+16)];    main.cursor(coords); -  main.on('cursor',detect); +  main.once('cursor', detect);    function detect(pos, send){      if (vec.equals(pos[0],coords)){        main.off('cursor', detect);        identity(send);      }    } -}); - -main.on('close', ()=>{ -  writes.disable() -}); - -var sender; // Global variable that holds identity()'s `send` for tileHandler -var initialized = false; +} +// identity records the identity discovered from the cursor and calls configurable init and initOnce functions +var initialized = false; //"Initialize once" strategy  function identity(send){ -  sender = send;    console.log('identity activated');    if (! initialized){      initialized = true;      initOnce();    } -  init(); -  main.on('tileUpdate', tileHandler); -} - -function init(){ -  writes.enable(); -} - -function initOnce(){ -  timect(); +  init(send);  } +// When a tile changes, processes data into usable form and runs every function in `funcs` w/ that data. +// Note that functions can edit inputs  function tileHandler(send, source, tiles){    if (send == sender) return;    let locs = tilekeys(tiles);    let tilespaces = {}; -  for (let i=0; i<locs.length; i++){ -    let loc = locs[i]; +  for (loc of locs){      tilespaces[loc] = new Space();      tilespaces[loc].fromfetch(tiles, [loc, loc], conform=false);    } -  [protectArea, detectPrompt].forEach(func => { +  funcs.forEach(func => {      func(send, tilespaces, locs);    });  } -notifsrc = '\ +//// "userspace" functions for responses, like to tileUpdates +var writes = new Queue(1000, 200, (elems) => main.write(elems)); + +var notifsrc = '\                             \n\    For a node.js YWOT api:                    \n\  &   http://github.com/feynmansfedora/ywot-clean \n\  | 
