socket.io多人游戏玩家的观点

我对nodejs和socket.io很陌生。 我正试图创build一个简单的多人纸牌游戏实时。 我现在的问题是我不能从玩家的angular度让玩家的观点显示在正确的div上。 例如,我希望我的比赛场地显示在底部框中,我的对手要显示在顶部框中,同样也与我的对手的观众一起显示。 他会在底部看到自己,看到我在顶部的div。 你如何得到这个效果?

客户

 <div class='top'></div> <div class='bottom></div> <script> var socket = io(); socket.on('playerinfo', function(data){ $('.top').html(data[0]); $('.bottom')html(data[1]); }); </script> 

服务器

 var players = []; io.on('connection', function(socket){ //player is given 'P' with random number when connection is made to represent username socket.name = "P" + Math.floor(Math.random() * (20000)); players.push(socket.name); io.emit('playerinfo', players); } 

如果你能指向我的教程或博客相关,这将是很好的。 谢谢。

你是通过一些独特的权利来区分自我和其他用户,比如唯一性就是用户的电子邮件地址或者用户标识。

解决scheme1:

在进行套接字连接时,还要发送用户标识/电子邮件,并且可以将其存储为套接字对象本身的一部分。 所以,当玩家1做了一些动作,在发送发送ID以及你发送的任何数据。

解决scheme2:

当player1做了一些动作的时候,你会发送数据给服务器,在发送数据的同时,也发送用户的id / email。 并在服务器再次与用户ID一起发出。

在客户端,你可以检查 – 如果id是self,那么在底部更新。 如果id不是self,那么更新顶部。 注意:如果你有多个对手球员,你仍然可以处理这个。

例:

在客户端:

 <script> var socket = io(); var selfId; socket.on('playerinfo', function(data){ selfId = data.name; playerInfo = data.players; $('.top').html(playerInfo); $('.bottom')html(selfId); }); socket.on('move', function(data){ if(data.uid == selfId) { $('.top').html(data.card); } else { $('.bottom')html(data.card); } }); socket.emit('move', {card:A, uid:56836480193347838764}); </script> 

在服务器中:

 var players = []; io.on('connection', function(socket){ //player is given 'P' with random number when connection is made to represent username socket.name = "P" + Math.floor(Math.random() * (20000)); // Here may be you can assign the position also where the user is sitting along with the user name. //players will be an array of object which holds username and their position //So that in client you can decide where the user will sit. players.push(socket.name); io.emit('playerinfo', {'players':players, 'name':socket.name); socket.on('move', function (data) { socket.emit('move', data); }); } 

你需要给每个客户端一些id,告诉每个客户端连接时,他们的id是什么。 当一个客户端连接时,为他们生成一个随机的唯一ID,然后发回给他们,让他们知道他们的ID。 当你发回其他玩家的数据时,客户端可以根据id找出他们的数据,并将其显示在正确的区域。