2015-12-18 47 views
0

我正在尝试使用node.js和socket.io构建一个多人纸牌游戏,并且我创建了一个包含52张纸牌的纸牌,并且我需要为每个玩家分配13张纸牌,问题在于该程序首先给每个人13张牌 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 (info) { 
    var instance = new Player(); 

    instance.fill(info); 

    return instance; 
}; 

card.js

var Card = function() { 

    this.data = { 
     suits : ["H", "C", "S", "D"], 
     pack : [] 
    }; 

    this.createPack = function(){ 

    this.data.pack = []; 
    this.count = 0; 

    for(i = 0; i < 4; i++){ 
     for(j = 1; j <14; j++){ 

      this.data.pack[this.count++] = j + this.data.suits[i]; 
     } 
    } 
    return this.data.pack; 
    }; 

    this.draw = function(pack, amount, hand, initial) { 
    var cards = new Array(); 
    cards = pack.slice(0, amount); 
    pack.splice(0, amount); 

    if (!initial) { 
     hand.push.apply(hand, cards); 
    } 
    return cards; 
    }; 
} 
    module.exports = function() { 

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

server.js

var nicknames=[]; 

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

var crd = card(); 

    socket.on('new user', function(data, callback){ 
     if (nicknames.indexOf(data) != -1){ 
      callback(false); 
     } else{ 
      callback(true); 
      socket.user = data; 
      nicknames.push(socket.user); 
      updateNicknames(); 

      var aa = { 
       id: nicknames.indexOf(data), 
       name: socket.user, 
       hand: crd.draw(crd.createPack(), 13, '', true) 
      }; 

     var pl = player(aa); 

     console.log(pl.getInformation()); 
     } 
    }); 
    function updateNicknames(){ 
    io.sockets.emit('usernames', nicknames); 
    } 
}); 

回答

1

要回答你的questio n,每次用户连接时,您都会创建一个新的套牌(即完整的套牌),然后处理前13张牌。你需要创建一个套牌,可能是在创建一个游戏时,然后从中抽取(如果你是这样的话,随机抽取) - 当你画一张牌时,将其从套牌中移除。

server.js

var deck = crd.createDeck(); 

socket.on('new user', function(...) { 
    player.hand = // draw randomly from deck and remove 
+0

仍然是相同的probleme。 – user3514348