|
var updateHunter, updateList, connectHandler, errorHandler; |
|
|
|
addItem = function(itemName) { |
|
SWARM.send({ item: itemName, found: false }) |
|
} |
|
|
|
connectHandler = function() { |
|
console.log('connected'); |
|
}; |
|
|
|
errorHandler = function(response) { |
|
console.log('Error:'); |
|
console.log(response); |
|
}; |
|
|
|
// alert to new or eaten hunters, and keep a list of current hunters |
|
updateHunter = function(response) { |
|
presence = JSON.parse(response).presence; |
|
// Filter out swarm presence messages, which do not contain the 'type' field |
|
if(presence.type) { |
|
var who = presence.from.resource; |
|
var alive = (presence.type === "available"); |
|
|
|
if (alive) { |
|
alert('' + who + ' just joined the hunt!'); |
|
$('#hunters').append("<li id='" + who + "'>" + who + '</li>'); |
|
} else { |
|
alert('' + who + ' was just eaten by the ravenous bugblatter beast of trall!'); |
|
$('#' + who).remove(); |
|
// if a hunter is eaten all their items are dropped |
|
$('.' + who).prop('disabled', false); |
|
$('.' + who).prop('checked', false); |
|
} |
|
} |
|
}; |
|
|
|
// keep an list of what items need to be gathered or have already been gathered |
|
// we use class to determine who requested the item |
|
updateList = function(response) { |
|
message = JSON.parse(response).message; |
|
var who = message.from.resource; |
|
var what = message.payload; |
|
|
|
var dom_item = $('#' + what.item); |
|
if (what.found && dom_item[0]) { |
|
alert('' + who + ' found ' + what.item); |
|
// Track who is carrying the item using class |
|
dom_item.addClass(who); |
|
// No other hunter needs these items now |
|
dom_item.prop('checked', true); |
|
dom_item.prop('disabled', true); |
|
} else if (what.item && !(dom_item[0])) { |
|
what.found = true; |
|
alert('' + who + ' needs ' + what.item); |
|
$('#items').append(' ' + |
|
"<input type='checkbox' id='" + what.item + "' />" |
|
+ "<label for='" + what.item + "'>" + what.item + '</label>' |
|
+ '<br>'); |
|
|
|
$('#' + who.item).click(function() { SWARM.send({found: true, item: what.item})}); |
|
} |
|
}; |
|
|
|
// Join the swarm |
|
// All callbacks must be defined before calling SWARM.connect for it to work |
|
// The apikey, swarm and resource was setup beforehand. Replace with your own! |
|
SWARM.connect({ apikey: '' |
|
, swarms: '' |
|
, resource: '' |
|
, onmessage: updateList |
|
, onpresence: updateHunter |
|
, onconnect: connectHandler |
|
, onerror: errorHandler |
|
}); |