1
0
mirror of https://github.com/exane/not-gwent-online synced 2024-10-31 10:36:53 +00:00

replace socketcluster with socket.io

This commit is contained in:
exane 2015-06-24 18:22:56 +02:00
parent 961fe30da8
commit 03fd73fab2
10 changed files with 242 additions and 113 deletions

View File

@ -1,5 +1,4 @@
/*("http://localhost:16918")*/ var socket = require("socket.io-client");
var socketCluster = require("socketcluster-client");
var Backbone = require("backbone"); var Backbone = require("backbone");
require("./backbone.modal-min"); require("./backbone.modal-min");
var Handlebars = require("handlebars"); var Handlebars = require("handlebars");
@ -21,7 +20,7 @@ var App = Backbone.Router.extend({
Backbone.history.start(); Backbone.history.start();
}, },
connect: function(){ connect: function(){
this.socket = socketCluster.connect(Config.Server); this.socket = socket(Config.Server.hostname + ":" + Config.Server.port);
}, },
receive: function(event, cb){ receive: function(event, cb){
this.socket.on(event, cb); this.socket.on(event, cb);
@ -235,7 +234,7 @@ var BattleView = Backbone.View.extend({
var interval = setInterval(function(){ var interval = setInterval(function(){
if(!user.get("room")) return; if(!user.get("room")) return;
this.setUpBattleEvents(user.get("room")); this.setUpBattleEvents();
this.app.send("request:gameLoaded", {_roomID: user.get("room")}); this.app.send("request:gameLoaded", {_roomID: user.get("room")});
clearInterval(interval); clearInterval(interval);
}.bind(this), 10); }.bind(this), 10);
@ -421,12 +420,50 @@ var BattleView = Backbone.View.extend({
this.app.send("activate:leader") this.app.send("activate:leader")
}, },
setUpBattleEvents: function(channelName){ setUpBattleEvents: function(){
this.battleChannel = this.app.socket.subscribe(channelName);
var self = this; var self = this;
var user = this.user; var user = this.user;
var app = user.get("app");
this.battleChannel.watch(function(d){ app.on("update:hand", function(data) {
if(user.get("roomSide") == data._roomSide){
self.handCards = JSON.parse(data.cards);
self.user.set("handCards", app.handCards);
self.render();
}
})
app.on("update:info", function(data) {
var _side = data._roomSide;
var infoData = data.info;
var leader = data.leader;
var side = self.yourSide;
if(user.get("roomSide") != _side){
side = self.otherSide;
}
side.infoData = infoData;
side.leader = leader;
side.infoData.discard = JSON.parse(side.infoData.discard);
side.render();
})
app.on("update:fields", function(data) {
var _side = data._roomSide;
var side = self.yourSide;
if(user.get("roomSide") != _side){
side = self.otherSide;
}
side.field.close = data.close;
side.field.ranged = data.ranged;
side.field.siege = data.siege;
side.field.weather = data.weather;
side.render();
})
/*this.battleChannel.watch(function(d){
var event = d.event, data = d.data; var event = d.event, data = d.data;
if(event === "update:hand"){ if(event === "update:hand"){
@ -465,7 +502,7 @@ var BattleView = Backbone.View.extend({
side.field.weather = data.weather; side.field.weather = data.weather;
side.render(); side.render();
} }
}) })*/
} }
}); });
@ -525,7 +562,8 @@ var User = Backbone.Model.extend({
}, },
initialize: function(){ initialize: function(){
var self = this; var self = this;
var app = this.get("app"); var user = this;
var app = user.get("app");
this.listenTo(this.attributes, "change:room", this.subscribeRoom); this.listenTo(this.attributes, "change:room", this.subscribeRoom);
@ -592,7 +630,17 @@ var User = Backbone.Model.extend({
self.set("isReDrawing", false); self.set("isReDrawing", false);
}) })
app.on("createRoom", this.createRoom, this); app.receive("update:hand", function(data){
app.trigger("update:hand", data);
})
app.receive("update:fields", function(data){
app.trigger("update:fields", data);
})
app.receive("update:info", function(data){
app.trigger("update:info", data);
})
app.on("startMatchmaking", this.startMatchmaking, this);
app.on("joinRoom", this.joinRoom, this); app.on("joinRoom", this.joinRoom, this);
app.on("setName", this.setName, this); app.on("setName", this.setName, this);
app.on("setDeck", this.setDeck, this); app.on("setDeck", this.setDeck, this);
@ -600,8 +648,8 @@ var User = Backbone.Model.extend({
app.send("request:name", this.get("name") == "unnamed" ? null : {name: this.get("name")}); app.send("request:name", this.get("name") == "unnamed" ? null : {name: this.get("name")});
}, },
createRoom: function(){ startMatchmaking: function(){
this.get("app").send("request:createRoom"); this.get("app").send("request:matchmaking");
}, },
joinRoom: function(){ joinRoom: function(){
this.get("app").send("request:joinRoom"); this.get("app").send("request:joinRoom");
@ -609,7 +657,7 @@ var User = Backbone.Model.extend({
subscribeRoom: function(){ subscribeRoom: function(){
var room = this.get("room"); var room = this.get("room");
var app = this.get("app"); var app = this.get("app");
app.socket.subscribe(room); //app.socket.subscribe(room);
}, },
setName: function(name){ setName: function(name){
this.get("app").send("request:name", {name: name}); this.get("app").send("request:name", {name: name});
@ -636,7 +684,7 @@ var Lobby = Backbone.View.extend({
this.render(); this.render();
}, },
events: { events: {
"click .create-room": "createRoom", "click .startMatchmaking": "startMatchmaking",
"click .join-room": "joinRoom", "click .join-room": "joinRoom",
"blur .name-input": "changeName", "blur .name-input": "changeName",
"change #deckChoice": "setDeck" "change #deckChoice": "setDeck"
@ -646,8 +694,8 @@ var Lobby = Backbone.View.extend({
/*this.$el.find("#deckChoice option[value='" + this.app.user.get("setDeck") + "']").attr("selected", "selected")*/ /*this.$el.find("#deckChoice option[value='" + this.app.user.get("setDeck") + "']").attr("selected", "selected")*/
return this; return this;
}, },
createRoom: function(){ startMatchmaking: function(){
this.app.trigger("createRoom"); this.app.trigger("startMatchmaking");
}, },
joinRoom: function(){ joinRoom: function(){
this.app.trigger("joinRoom"); this.app.trigger("joinRoom");

View File

@ -14,8 +14,8 @@
</div> </div>
<div class="row"> <div class="row">
<div class="col-xs-12"> <div class="col-xs-12">
<button type="button" class="btn btn-primary create-room">Create Room</button> <button type="button" class="btn btn-primary startMatchmaking">Search Opponent</button>
<button type="button" class="btn btn-primary join-room">Join Room</button> <!--<button type="button" class="btn btn-primary join-room">Join Room</button>-->
</div> </div>
</div> </div>
</div> </div>

View File

@ -10,8 +10,8 @@
"minimist": "1.1.0", "minimist": "1.1.0",
"serve-static": "1.8.0", "serve-static": "1.8.0",
"shortid": "^2.2.2", "shortid": "^2.2.2",
"socketcluster": "2.2.x", "socket.io": "^1.3.5",
"socketcluster-client": "2.2.x", "socket.io-client": "^1.3.5",
"underscore": "^1.8.3" "underscore": "^1.8.3"
}, },
"devDependencies": { "devDependencies": {

View File

@ -46,7 +46,7 @@ var Battle = (function(){
this.on("AfterPlace", this.checkAbilityOnAfterPlace)*/ this.on("AfterPlace", this.checkAbilityOnAfterPlace)*/
this.channel = this.socket.subscribe(this._id); //this.channel = this.socket.subscribe(this._id);
this.p1 = Battleside(this._user1.getName(), 0, this, this._user1); this.p1 = Battleside(this._user1.getName(), 0, this, this._user1);
this.p2 = Battleside(this._user2.getName(), 1, this, this._user2); this.p2 = Battleside(this._user2.getName(), 1, this, this._user2);
this.p1.foe = this.p2; this.p1.foe = this.p2;
@ -120,27 +120,33 @@ var Battle = (function(){
this._update(this.p2); this._update(this.p2);
} }
r._update = function(p){ r.updateSelf = function(side) {
this._update(side, true);
}
r._update = function(p, isPrivate){
isPrivate = isPrivate || false;
p.send("update:info", { p.send("update:info", {
info: p.getInfo(), info: p.getInfo(),
leader: p.field[Card.TYPE.LEADER].get()[0] leader: p.field[Card.TYPE.LEADER].get()[0]
}) }, isPrivate)
p.send("update:hand", { p.send("update:hand", {
cards: JSON.stringify(p.hand.getCards()) cards: JSON.stringify(p.hand.getCards())
}); },isPrivate);
p.send("update:fields", { p.send("update:fields", {
close: p.field[Card.TYPE.CLOSE_COMBAT].getInfo(), close: p.field[Card.TYPE.CLOSE_COMBAT].getInfo(),
ranged: p.field[Card.TYPE.RANGED].getInfo(), ranged: p.field[Card.TYPE.RANGED].getInfo(),
siege: p.field[Card.TYPE.SIEGE].getInfo(), siege: p.field[Card.TYPE.SIEGE].getInfo(),
weather: p.field[Card.TYPE.WEATHER].getInfo() weather: p.field[Card.TYPE.WEATHER].getInfo()
}) }, isPrivate);
} }
r.send = function(event, data){ r.send = function(event, data){
this.channel.publish({ /*this.channel.publish({
event: event, event: event,
data: data data: data
}); });*/
io.sockets.in(this._id).emit(event, data);
} }
r.runEvent = function(eventid, ctx, args, uid){ r.runEvent = function(eventid, ctx, args, uid){

View File

@ -620,7 +620,7 @@ Battleside = (function(){
this.send("redraw:cards", null, true); this.send("redraw:cards", null, true);
var h1 = this.receive("redraw:reDrawCard", function(data){ this.receive("redraw:reDrawCard", function(data){
var id = data.cardID; var id = data.cardID;
if(!left) return; if(!left) return;
left--; left--;
@ -633,15 +633,16 @@ Battleside = (function(){
self.send("redraw:close", null, true); self.send("redraw:close", null, true);
console.log("redraw finished"); console.log("redraw finished");
deferred.resolve("done"); deferred.resolve("done");
self.socket.off("redraw:reDrawCard", h1); //self.socket.off("redraw:reDrawCard", h1);
} }
self.update(self); /*self.update(self);*/
self.battle.updateSelf(self);
}) })
var h2 = this.receive("redraw:close_client", function() { this.receive("redraw:close_client", function() {
console.log("redraw finished!"); console.log("redraw finished!");
deferred.resolve("done"); deferred.resolve("done");
self.socket.off("redraw:close_client", h2); //self.socket.off("redraw:close_client", h2);
}) })
return deferred; return deferred;

View File

@ -1,9 +1,9 @@
var Promise = require("promise"); var Promise = require("promise");
var Matchmaker = (function(){ var Matchmaker = (function(){
var Matchmaker = function(connections){ var Matchmaker = function(){
if(!(this instanceof Matchmaker)){ if(!(this instanceof Matchmaker)){
return (new Matchmaker(connections)); return (new Matchmaker());
} }
/** /**
* constructor here * constructor here
@ -23,47 +23,47 @@ var Matchmaker = (function(){
r._queue = null; r._queue = null;
r._connections = null; r._connections = null;
r.findOpponent = function(user){ r.removeFromQueue = function(user){
var self = this; for(var i = 0; i < this._queue.length; i++) {
var u = this._queue[i];
var promise = new Promise(function(resolve){ if(u.getID() === user.getID()) {
self._queue.push(user); user._inQueue = false;
self._checkForOpponent(resolve); return this._queue.splice(i, 1);
});
return promise;
}
r._checkForOpponent = function(resolve){
if(this._queue.length <= 1) return;
console.log(this._queue.length);
if(!this._checkConnections()) return;
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;
p1.send("get:opponent", {socketID: p2.getID()});
p2.send("get:opponent", {socketID: p1.getID()});
p1.joinRoom(roomID);
p2.joinRoom(roomID);
resolve(p1, p2, roomID);
}
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; r.findOpponent = function(user){
var c = connections;
var found = this._checkForOpponent();
if(found){
var room = Room();
c.roomCollection[room.getID()] = room;
room.join(user);
room.join(found);
user._inQueue = false;
found._inQueue = false;
return room;
}
this._getInQueue(user);
}
r._getInQueue = function(user){
console.log(user.getName() + " joined in queue");
this._queue.push(user);
user._inQueue = true;
}
r._checkForOpponent = function(){
if(!this._queue.length) return null;
var foe = this._queue.splice(0, 1)[0];
foe._inQueue = false;
return foe;
} }

View File

@ -2,9 +2,9 @@ var shortid = require("shortid");
var Battle = require("./Battle"); var Battle = require("./Battle");
var Room = (function(){ var Room = (function(){
var Room = function(scServer){ var Room = function(){
if(!(this instanceof Room)){ if(!(this instanceof Room)){
return (new Room(scServer)); return (new Room());
} }
/** /**
* constructor here * constructor here
@ -14,7 +14,7 @@ var Room = (function(){
this._id = shortid.generate(); this._id = shortid.generate();
this._users = []; this._users = [];
this._ready = {}; this._ready = {};
this.socket = scServer.global; //this.socket = scServer.global;
console.log("room created: " + this.getID()); console.log("room created: " + this.getID());
@ -40,6 +40,8 @@ var Room = (function(){
if(this._users.length >= 2) return; if(this._users.length >= 2) return;
this._users.push(user); this._users.push(user);
user.addRoom(this); user.addRoom(this);
user.socket.join(this.getID());
user.send("response:joinRoom", this.getID());
if(!this.isOpen()){ if(!this.isOpen()){
this.initBattle(); this.initBattle();
@ -55,7 +57,7 @@ var Room = (function(){
} }
r.initBattle = function(){ r.initBattle = function(){
this._battle = Battle(this._id, this._users[0], this._users[1], this.socket); this._battle = Battle(this._id, this._users[0], this._users[1], io);
this._users[0].send("init:battle", {side: "p1"}); this._users[0].send("init:battle", {side: "p1"});
this._users[1].send("init:battle", {side: "p2"}); this._users[1].send("init:battle", {side: "p2"});
} }

View File

@ -1,11 +1,8 @@
/* /*var app = require('http').createServer();
var app = require('http').createServer(); global.io = require("socket.io")(app);*/
global.io = require("socket.io")(app); /*var User = require("./User");
var User = require("./User");
var Connections = require("./Connections"); var Connections = require("./Connections");
var Battle = require("./Battle"); var Room = require("./Room");*/
var Npc = require("./Npc");
var Room = require("./Room");
var Socket = (function(){ var Socket = (function(){
@ -13,39 +10,28 @@ var Socket = (function(){
if(!(this instanceof Socket)){ if(!(this instanceof Socket)){
return (new Socket()); return (new Socket());
} }
*/ /**
/**
* constructor here * constructor here
*//* */
this.connections = Connections(); this.connections = Connections();
*/
/*
this.matchmaker = Matchmaker(this.connections);
*//*
this.roomCollection = {}; this.roomCollection = {};
app.listen(this.port); app.listen(this.port);
this.io = io; this.io = io;
this._events(); this._events();
}; };
var r = Socket.prototype; var r = Socket.prototype;
*/ /**
/**
* methods && properties here * methods && properties here
* r.property = null; * r.property = null;
* r.getProperty = function() {...} * r.getProperty = function() {...}
*//* */
r.io = null; r.io = null;
r.port = 16918; r.port = 16918;
r.connections = null; r.connections = null;
r.roomCollection = null; r.roomCollection = null;
*/ /*
/*
r.matchmaker = null; r.matchmaker = null;
*//* */
r._events = function(){ r._events = function(){
var self = this; var self = this;
@ -102,4 +88,4 @@ var Socket = (function(){
return Socket; return Socket;
})(); })();
module.exports = Socket;*/ module.exports = Socket;

View File

@ -12,6 +12,8 @@ var User = (function(){
this._rooms = []; this._rooms = [];
this._id = socket.id; this._id = socket.id;
this.generateName(); this.generateName();
this._events();
}; };
var r = User.prototype; var r = User.prototype;
/** /**
@ -23,7 +25,7 @@ var User = (function(){
r._id = null; r._id = null;
r._name = null; r._name = null;
r._rooms = null; r._rooms = null;
r._searching = false; r._inQueue = false;
r.socket = null; r.socket = null;
r.disconnected = false; r.disconnected = false;
@ -31,13 +33,13 @@ var User = (function(){
return this._id; return this._id;
} }
r.joinRoom = function(roomid){ /*r.joinRoom = function(roomid){
var self = this; var self = this;
/*this.socket.on(roomid, function(d) { *//*this.socket.on(roomid, function(d) {
var event = d.event, data = d.data; var event = d.event, data = d.data;
self.socket.on(event, data); self.socket.on(event, data);
});*/ });*//*
} }*/
r.send = function(event, data, room){ r.send = function(event, data, room){
room = room || null; room = room || null;
@ -45,12 +47,12 @@ var User = (function(){
if(!room){ if(!room){
this.socket.emit(event, data); this.socket.emit(event, data);
} }
else {/* else {
this.socket.to(room).emit(event, data);*/ this.socket.to(room).emit(event, data);
this.socket.global.publish(room, { /*this.socket.global.publish(room, {
event: event, event: event,
data: data data: data
}) })*/
} }
} }
@ -102,6 +104,8 @@ var User = (function(){
var self = this; var self = this;
this.disconnected = true; this.disconnected = true;
matchmaking.removeFromQueue(this);
this._rooms.forEach(function(room) { this._rooms.forEach(function(room) {
room.leave(self); room.leave(self);
if(!room.hasUser()) { if(!room.hasUser()) {
@ -113,6 +117,57 @@ var User = (function(){
this.cleanUp(); this.cleanUp();
} }
r._events = function() {
var socket = this.socket;
var self = this;
socket.on("request:name", function(data){
if(data && data.name){
self.setName(data.name);
}
socket.emit("response:name", {name: self.getName()});
})
/*socket.on("request:createRoom", function(){
var room = Room();
connections.roomCollection[room.getID()] = room;
room.join(self);
console.log("room %s created by %s", room.getID(), self.getName());
self.send("response:createRoom", room.getID());
})
socket.on("request:joinRoom", function(){
console.log("joinroom");
var interval = setInterval(function(){
for(var key in connections.roomCollection) {
var room = connections.roomCollection[key];
if(!room.isOpen()) continue;
room.join(self);
clearInterval(interval);
console.log("user %s joined room %s", self.getName(), room.getID());
self.send("response:joinRoom", room.getID());
}
}, 1000);
})*/
socket.on("request:matchmaking", function() {
if(self._inQueue) return;
matchmaking.findOpponent(self);
});
socket.on("request:gameLoaded", function(data){
console.log(data);
connections.roomCollection[data._roomID].setReady(self);
})
socket.on("set:deck", function(data) {
console.log(data);
if(data && data.deck){
self.setDeck(data.deck);
}
})
}
return User; return User;
})(); })();

View File

@ -1,6 +1,7 @@
var argv = require('minimist')(process.argv.slice(2)); var argv = require('minimist')(process.argv.slice(2));
var SocketCluster = require('socketcluster').SocketCluster; /*var SocketCluster = require('socketcluster').SocketCluster;*/
/*
var socketCluster = new SocketCluster({ var socketCluster = new SocketCluster({
workers: Number(argv.w) || 1, workers: Number(argv.w) || 1,
stores: Number(argv.s) || 1, stores: Number(argv.s) || 1,
@ -10,4 +11,34 @@ var socketCluster = new SocketCluster({
storeController: __dirname + '/store.js', storeController: __dirname + '/store.js',
socketChannelLimit: 100, socketChannelLimit: 100,
rebootWorkerOnCrash: argv['auto-reboot'] != false rebootWorkerOnCrash: argv['auto-reboot'] != false
}); });*/
global.connections = require("./Connections")();
global.matchmaking = require("./Matchmaker")();
global.Room = require("./Room");
global.User = require("./User");
/*global.Socket = require("./Socket");*/
var app = require('http').createServer();
global.io = require("socket.io")(app);
app.listen(16918);
io.on("connection", function(socket) {
var user;
connections.add(user = User(socket));
console.log("new user ", user.getName());
socket.on("disconnect", function() {
connections.remove(user);
user.disconnect();
console.log("user ", user.getName(), " disconnected");
user = null;
})
})