如何给玩家一副牌

How to gives players a deck of cards?

本文关键字:一副 玩家      更新时间:2023-09-26

我正在尝试使用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);
  }
});

要回答您的问题,每次用户连接时,您都会创建一个新的牌组(即一个完整的牌组),然后发放前13张牌。你需要创建一副牌,可能是在创建游戏时,然后从中抽取(如果你喜欢这类东西,可以随机抽取)——当你抽取一张牌时,你会将其从牌组中移除。

server.js

var deck = crd.createDeck();
socket.on('new user', function(...) {
    player.hand = // draw randomly from deck and remove