aboutsummaryrefslogtreecommitdiff
path: root/examples/jarvis.js
blob: 9b428e83882ef6892244ffd3b0d05259251fb96f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// A bot which responds to `jarvis` with a box

const Space = require('../space');
const Socket = require('../socket');
const tilekeys = require('../utils/tilekeys');
const Search = require('../tools/search');
const Queue = require('../tools/queue');

var main = new Socket();

function equals(arg1,arg2){ // Just takes the specific case argument of each being an int pair
  return arg1[0] == arg2[0] && arg1[1] == arg2[1]
}

main.on('open', ()=>{ // Tries to identify itself with a cursor movement
  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);
  function detect(pos, send){
    if (equals(pos[0],coords)){
      main.off('cursor', detect);
      identity(send);
    }
  }
})

function identity(sender){

  console.log('identity activated');
  
  var search = new Space();
  search.adhoc('jarvis'); // The search space is the word jarvis, so whenever that's caught, a relevant function can be called.
  var read = new Search(search);
  var expire = {};

  main.on('tileUpdate', tileHandler);
}

function tileHandler(send, source, tiles){
  if (send == sender) return; //this may lead to issues later, but for now is used to count its own updates
  let locs = tilekeys(tiles);

  for (let i=0; i<locs.length; i++){
    let loc = locs[i];
    if (read.has(loc)){
      clearTimeout(expire[loc]);
      delete expire[loc];
      read.del(loc);
    }
    let locspace = new Space();
    locspace.fromfetch(tiles, [loc, loc], conform=false);
    let results = read.add(loc, locspace);
    if (results.length > 0) respond(results);
    expire[loc] = setTimeout(() => {read.del(loc)}, 30000);
  }
}

let response = new Space();
response.adhoc('yes, my liege');

let writes = new Queue(1000, 200, (elems) => main.write(elems));

function respond(coord){
  console.log('called at', coord);
  response.loc = coord;
  writes.enqueue(...response.towrite());
}