Node JS Express JS Client / Server

I am writing a two-player card game (say, regular poker for simplicity) in Node.js and Express js. There are a couple of things that I came across. Firstly, how can I make sure that there are only 2 players who can access the instance of the game, and is it possible for them to reconnect if they lose the connection? Secondly, how to send a message from the server to the client? I can send it in a listener call to "socket.on", but within the normal program area, I cannot get it to work.

var socket = io.listen(app); socket.on('connection', function(client){ player++; if(player <= 2) { var messageout = "player " + player + " connected"; client.broadcast(messageout); client.on('message', function(data){console.log(data); }) client.on('disconnect', function(){console.log('disconnected');}) } else { socket.end; } }); 

I am having problems with the concept of what is happening here and how to approach the problem. For example, am I doing all this with sockets? Or am I returning a web page with the updated state of the game (cards, bets, etc.) at every step?

+4
source share
2 answers

First of all, how can I make sure that there are only 2 players who can access an instance of the game?

Create an array of instance objects.
When a new player joins, either creates a new instance, or sets them as player1, or adds them to the existing instance as a second player.

 var instances = []; function Instance () { return { name = 'game' + instances.length + 1, gameVariables = defaults, player1 = null, player2 = null, player1UUID = UUID(), player2UUID = UUID() } } 

Is it possible for them to reconnect if they lose their connection?

If you send each player a UUID on the first connection, you can use it to authenticate when reconnecting.

How to send a message from server to client?

client.send ({gameState: gameState ()});

if you saved the client in the object: instances[ 'game1' ].player1.send( data );

Am I doing all this with sockets?

I would consider all dynamic interactions with web sockets.

Do I return a web page with the updated state of the game (cards, bets, etc.) every turn?

I would not send html via web sockets. Instead, send json and use the client-side template to display it.

+2
source

Try now .

 // server var nowjs = require("now") var everyone = nowjs.initialize(app); everyone.connected(function() { if (users.length < 2) { users.push(this); } }); everyone.now.sendMessage = function(message, cb) { gameLogic(message); users.forEach(function(user) { user.update(gameLogic.getState()); }); }; //client $("#action").click(function() { now.sendMessage($(this).data("action")); }); now.update = function(data) { // update UI }; 
0
source

All Articles