我正在尝试使用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);
}
});
答案 0 :(得分:1)
要回答您的问题,每次用户连接时,您都会创建一个新的牌组(即完整牌组),然后处理前13张牌。你需要创建一个牌组,可能是在创建游戏时,然后从中抽取(随机,如果你进入那种事情) - 当你画一张牌时,你将其从牌组中删除。
server.js
var deck = crd.createDeck();
socket.on('new user', function(...) {
player.hand = // draw randomly from deck and remove