我正在Node.js和Express js中写一个双人纸牌游戏(说它是简单的普通扑克).我遇到了一些问题.首先,我如何确保只有2个玩家可以访问游戏实例,如果他们失去连接,是否可以让他们重新连接?第二,如何从服务器向客户端发送消息?我可以在“socket.on”监听器调用中发送它,但是在程序的正常范围内我无法使其工作.
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;
}
});
我在概念上遇到了麻烦,这里发生了什么以及如何解决问题.例如,我是否使用套接字完成所有操作?或者我每回合都会返回一个包含更新游戏状态(卡片,赌注等)的网页?
最佳答案
First, how do I make sure that there
are only 2 players that can access an
instance of the game?
创建实例对象数组.
当新玩家加入时,要么创建新实例并将其设置为player1,要么将它们作为玩家二添加到现有实例.
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?
如果您在最初连接时向每个播放器发送UUID,您可以让它们在重新连接时使用它进行身份验证.
How do I send a message from the
server to the client?
client.send({gameState:gameState()});
如果您已将客户端保存到对象中:instances [‘game1’] .player1.send(data);
I do it all with sockets?
我会处理与Web套接字的所有动态交互.
Do I return a web page with the updated state of the game (cards, bets, etc.) every turn?
我不会通过网络套接字发送HTML.而是发送json并使用客户端模板来呈现它.