2015-12-18 74 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