Skip to content

Instantly share code, notes, and snippets.

@ToeJamson
Last active October 19, 2017 00:43
Show Gist options
  • Save ToeJamson/31eeb0c4eaa263f70c04 to your computer and use it in GitHub Desktop.
Save ToeJamson/31eeb0c4eaa263f70c04 to your computer and use it in GitHub Desktop.
Random Matchmaking (MemeWarz 5)
pubnub.subscribe({
channel: channel,
state: {
skill: 2
}
});
pubnub.here_now({
channel: channel,
state: true,
callback: function(data) {}
});
{
"uuids": [
{
"state": {
"skill": 2
},
"uuid": "fuchsia_whale"
},
{
"state": {
"skill": 3
},
"uuid": "lime_impala"
}
],
"occupancy": 2
}
var my_skill = Math.floor(Math.random() * 3) + 1;
$('#my_skill').text(my_skill);
<a href="#">
You are <strong id="whoami"></strong>
<span id="my_skill" class="badge"></span>
</a>
pubnub.subscribe({
channel: channel,
state: {
skill: my_skill
},
message: function(data) {},
presence: function(data) { }
});
pubnub.here_now({
channel: channel,
state: true,
callback: function(data) {}
});
$('#find-match').click(function(){
pubnub.here_now({
channel: channel,
state: true,
callback: function(data) {
var users = data.uuids;
var matches = [];
for(var i = users.length - 1; i >= 0; i--) {
if(users[i].uuid !== me && users[i].state.skill == my_skill) {
matches.push(users[i])
}
}
if(!matches.length) {
alert('Nobody is online with the same skill level.');
} else {
var opponent = matches[Math.floor(Math.random() * matches.length)];
alert('Opponent Found: ' + opponent.uuid + ' with skill level ' + opponent.state.skill);
}
}
});
});
pubnub.subscribe({
channel: channel,
state: {
skill: my_skill
},
message: function(data) { },
presence: function(data) {
if(data.action == "join") {
var $new_user = $('<li id="' + data.uuid + '" class="list-group-item"><span class="badge">' + data.data.skill + '</span>' + data.uuid + '</li>')
$('#online-users').append($new_user);
}
// ...
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment