我如何添加玩家并给他们甲板?

时间:2015-12-18 17:05:00

标签: node.js sockets

我试图使用node.js和socket.io构建多人纸牌游戏,我需要添加玩家并给他们一个套牌,我该怎么做

server.js

var player = require("./players");
var nicknames=[];

io.on("connection", function (socket) {  

  socket.on('new user', function(data, callback){
        if (nicknames.indexOf(data) != -1){
            callback(false);
        } else{
            callback(true);
      var aa = {id: nicknames.indexOf(data), name: data};

      var ply = player(aa);

            socket.user = data;
            nicknames.push(socket.user);
            updateNicknames();
        }
    });
  function updateNicknames(){
    io.sockets.emit('usernames', nicknames);
  }

});

players.js

var Player = function(){
    this.data ={

    id : null,
    name : null,
    hand : []
    };
    this.fill = function (info) {
        for(var prop in this.data) { 
            if(this.data[prop] !== 'undefined') {
                this.data[prop] = info[prop]; 
            }
        }
    };  
this.getInformation = function () {
        return this.data;
    };
};

module.exports = function () {

    var instance = new Player();
    return instance;
};

但程序给了我空的玩家对象

1 个答案:

答案 0 :(得分:0)

这对于构造函数来说是个好例子。如果您使用一个,您将要避免导出实例化对象。考虑下面的players.js

var Player = (function() {

  function Player(data) {
    this.data = data;
    var defaults = {
      id: null,
      name: null,
      hand: []
    };

    for (var key in defaults) {
      var val = defaults[key];
      if (this.data[key] == null) {
        this.data[key] = val;
      }
    }
  }

  Player.prototype.getData = function() {
    return this.data;
  };

  return Player;

})();

module.exports = Player;

然后,您可以使用new运算符创建Player类的新实例。

var aa = {id: 0, name: 'test'};
var ply = new Player(aa);
console.log(ply.getData());
>> { id: 0, name: 'test', hand: [] }