1
0
mirror of https://github.com/exane/not-gwent-online synced 2024-11-23 19:36:53 +00:00
not-gwent-online/server/Matchmaker.js

74 lines
1.5 KiB
JavaScript
Raw Normal View History

2015-06-10 16:12:52 +00:00
var Promise = require("promise");
var Matchmaker = (function(){
2015-06-13 07:58:55 +00:00
var Matchmaker = function(connections){
2015-06-10 16:12:52 +00:00
if(!(this instanceof Matchmaker)){
2015-06-13 07:58:55 +00:00
return (new Matchmaker(connections));
2015-06-10 16:12:52 +00:00
}
/**
* constructor here
*/
2015-06-13 07:58:55 +00:00
this._connections = connections;
2015-06-10 16:12:52 +00:00
this._queue = [];
2015-06-13 07:58:55 +00:00
2015-06-10 16:12:52 +00:00
};
var r = Matchmaker.prototype;
/**
* methods && properties here
* r.property = null;
* r.getProperty = function() {...}
*/
r._queue = null;
2015-06-13 07:58:55 +00:00
r._connections = null;
2015-06-10 16:12:52 +00:00
r.findOpponent = function(user){
var self = this;
var promise = new Promise(function(resolve){
self._queue.push(user);
self._checkForOpponent(resolve);
});
return promise;
}
r._checkForOpponent = function(resolve){
if(this._queue.length <= 1) return;
2015-06-13 07:58:55 +00:00
console.log(this._queue.length);
if(!this._checkConnections()) return;
2015-06-10 16:12:52 +00:00
this._match(this._queue[0], this._queue[1], resolve);
}
r._match = function(p1, p2, resolve){
this._queue.splice(0, 2);
var roomID = p1.id + p2.id;
2015-06-13 07:58:55 +00:00
p1.send("get:opponent", {socketID: p2.getID()});
p2.send("get:opponent", {socketID: p1.getID()});
2015-06-10 16:12:52 +00:00
p1.joinRoom(roomID);
p2.joinRoom(roomID);
resolve(p1, p2, roomID);
}
2015-06-13 07:58:55 +00:00
r._checkConnections = function() {
var res = true;
var self = this;
this._queue.forEach(function(user, index) {
if(!self._connections.hasUser(user)) {
self._queue.splice(index, 1);
res = false;
}
});
return res;
}
2015-06-10 16:12:52 +00:00
return Matchmaker;
})();
module.exports = Matchmaker;