From 526ff0f8a9e57b4a0090a3ee02209b64e6af6f28 Mon Sep 17 00:00:00 2001 From: Holden Rohrer Date: Wed, 8 Jan 2020 18:06:16 -0500 Subject: cleaned up jarvis --- examples/jarvis.js | 65 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 40 insertions(+), 25 deletions(-) (limited to 'examples') 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 { + 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\ -- cgit