开发者

Node JS Express JS Client / Server game

I'm writing a two player card game, (say it's regular poker for simplicity) in Node.js and Express js. There's a couple of things I'm having trouble with. First, how do I make sure that there are only 2 players that can access an instance of the game, and is it possible to have them reconnect if they lose the connection? Second, how do send a message from the server to the client? I can send it within the "socket.on" listener call, but within the normal scope of the program I can't 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开发者_如何学JAVA', function(){console.log('disconnected');})
  }
  else {
  socket.end;
    }

});

I'm having trouble conceptually what's going on here and how to approach the problem. For example, do I do it all with sockets? Or do I return a web page with the updated state of the game (cards, bets, etc.) every turn?


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

Create an array of instance objects.
When a new player joins either create a new instance and set them as player1, or add them to an existing instance as player two.

var instances = [];

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

Is it possible to have them reconnect if they lose the connection?

If you send each player a UUID when they initially connect you can have them use it to authenticate when they reconnect.

How do I send a message from the server to the client?

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

of if you've saved the client into an object: instances[ 'game1' ].player1.send( data );

I do it all with sockets?

I would deal with 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 wouldn't send html over web sockets. Instead send json and use a client side template to render it.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜