使用随机对象填充对象,并在javascript

时间:2016-07-20 20:46:26

标签: javascript arrays node.js javascript-objects

我正在使用NodeJS和socket.io来创建在线浏览器卡片游戏。

我已经在底部编写了代码,其中一个Object填充了两个玩家(0和1),然后每个玩家获得一个保存套牌的对象,并且在那里,还有两个对象,以对象的形式持卡。

userlists: { // I have more than just "g" in here, but for this part, only "g" is needed
    "g": { // Holds the different game-sessions
        "roomid": { // A Game-Session
            "Players": { // Contains the 2 Opponents
                0: { // Opponent 1
                    "deck": { // The deck of Opponent 1 (note that the different decks are no objects, though if needed, they could be)
                        "onHand": [ // Contains all the Cards "on-Hand"
                            {
                                "Type": "Knight",
                                ... // more properties
                                "position": 0 // The position of the Card on the hand of the Player
                            },
                            ... // more Cards
                        ],
                        "inBlock": [ // Contains all the reserve-Cards
                            ... // as in ["onHand"], but with ["position"]=null
                        ]
                    }
                },
                1: { // Opponent 2
                    ... // same as Opponent 1, just different deck of course
                }
            }
        }
    }
}

但由于这是一个问题,下面的代码实际上并没有产生预期的结果。实际上,它首先会输出所需的数字,但是,此时,它将被发送(function snddcks())到客户端"position"(实际上所有其他属性),得到根据{{​​1}}进行了一些复制,因此所有"Type"都会"Type":"Knight"等等。

这就是问题所在,我无法弄清楚实际发生的原因。

最后,我会快速解释一下这个过程:

  1. 好吧,首先,加入的玩家(它的NR 1,而不是0)在"position":0中创建游戏会话对象(服务器端),其中roomid是随机生成的字符串
  2. NR1,然后告诉NR0他已加入,然后发回" playerhasjoined"到服务器
  3. 在服务器端然后,函数" populateDeck"被调用,然后填充甲板,首先是NR0,然后是NR1
  4. 最后," snddcks"被调用,然后将所有数据发送到两个客户端
  5. 所以在第3步中,所有"位置"和其他属性设置正确,但在第4步中,它们会被覆盖,无论如何。

    这是新代码:

    userlists["g"][roomid]

    这是旧代码:

    function joingid() {
        var roomid = userlists["eo"][socket.username]["gid"];
    
        socket.state = "playing";
        socket.join(roomid);
        socket.leave("lobby");
        socket.leave("searching");
    
        socket.emit("playerfound", {
            gid: roomid
        });
        socket.broadcast.to(roomid).emit('playerjoined', {
            usr: socket.username,
            gid: roomid
        });
    }
    socket.on('playerhasjoined', function(data) {
        socket.state = "playing";
        socket.leave("lobby");
    
        var roomid = userlists["eo"][socket.username]["gid"];
    
        socket.broadcast.to(roomid).emit('otheropponent', {
            usr: socket.username
        });
    
        setTimeout(function() {
            populateDeck2(roomid, data["oppo"]);
        }, 500);
    });
    
    function gRC(roomid, i, i2) {
        userlists["g"][roomid]["Players"][i2]["deck"]["onHand"][i] = standardDeckCards[Math.floor(Math.random() * standardDeckCards.length)];
        userlists["g"][roomid]["Players"][i2]["deck"]["onHand"][i]["CID"] = "CID-"+(Math.floor((Math.random() * 1000) + 1)).toString();
        userlists["g"][roomid]["Players"][i2]["deck"]["onHand"][i]["position"] = i;
    }
    function gRCc(roomid, i, i2) {
        return function() {
            gRC(roomid, i, i2);
        };
    }
    function gRC2(roomid, i, i2) {
        userlists["g"][roomid]["Players"][i2]["deck"]["inBlock"][i] = standardDeckCards[Math.floor(Math.random() * standardDeckCards.length)];
        userlists["g"][roomid]["Players"][i2]["deck"]["inBlock"][i]["CID"] = "CID-"+(Math.floor((Math.random() * 1000) + 1)).toString();
        userlists["g"][roomid]["Players"][i2]["deck"]["inBlock"][i]["position"] = i;
    }
    function gRCc2(roomid, i, i2) {
        return function() {
            gRC2(roomid, i, i2);
        };
    }
    function gRC2_1(roomid, a1i, a2i, card) {
        return function() {
            userlists["g"][roomid]["Players"][a1i]["deck"]["onHand"].push(card);
            userlists["g"][roomid]["Players"][a1i]["deck"]["onHand"][a2i]["CID"] = "CID-"+(Math.floor((Math.random() * 1000) + 1)).toString();
            userlists["g"][roomid]["Players"][a1i]["deck"]["onHand"][a2i]["position"] = a2i;
        };
    }
    function populateDeck2(roomid, oppo) {
        var oppos = [socket.username, oppo];
        userlists["g"][roomid] = {
            "RoomID": roomid,
            "Players": {
                0: {
                    "Player": socket.username,
                    "deck": {
                        "onHand": [],
                        "onField": [],
                        "inBlock": []
                    },
                    "MP-Left": 20
                },
                1: {
                    "Player": oppo,
                    "deck": {
                        "onHand": [],
                        "onField": [],
                        "inBlock": []
                    },
                    "MP-Left": 20
                }
            },
            "Creationdate": Date().toString(),
            "Winner": null,
            "currentPlayer": oppos[Math.floor(Math.random() * oppos.length)],
            "roundNR": 0
        };
        for (var a1 = 0; a1 < 2; a1++) { // plnr
            for (var a2 = 0; a2 < 5; a2++) { // onHand
                (function() {
                    gRCc(roomid, a2, a1)();
                })();
    
                // gRC2_1(roomid, a1, a2, gRC())();
    
                // (function() {
                //     var card1 = gRC();
                //     userlists["g"][roomid]["Players"][a1]["deck"]["onHand"].push(card1);
                //     userlists["g"][roomid]["Players"][a1]["deck"]["onHand"][a2]["CID"] = "CID-"+(Math.floor((Math.random() * 1000) + 1)).toString();
                //     userlists["g"][roomid]["Players"][a1]["deck"]["onHand"][a2]["position"] = a2;
                //     console.log("@"+a1+"::"+a2+" >> "+userlists["g"][roomid]["Players"][a1]["deck"]["onHand"][a2]["CID"]+" AND "+userlists["g"][roomid]["Players"][a1]["deck"]["onHand"][a2]["position"]);
                // })();
            }
            for (var a3 = 0; a3 < 50; a3++) { // inBlock
                (function() {
                    gRCc2(roomid, a3, a1)();
                })();
    
                // (function() {
                //     userlists["g"][roomid]["Players"][a1]["deck"]["inBlock"].push(gRC());
                //     userlists["g"][roomid]["Players"][a1]["deck"]["inBlock"][a3]["CID"] = "CID-"+(Math.floor((Math.random() * 1000) + 1)).toString();
                // })();
            }
            fs.writeFile("userlistsLOG_1.log", "ONE: "+a1+""+Date().toString()+":\n"+JSON.stringify(userlists["g"][roomid]["Players"][a1]["deck"]["onHand"])+"\n\n", {flag:"a"}, function (err) {
                if (err) {
                    console.log('error happened during writing to log')
                    return console.log(err)
                }
            });
        }
        SP("gamepage.html", function FNCr(CALLBACKf) {
            setTimeout(function() {
                $(".gameid").html(roomid);
                $(".opponent").html(opponent);
                $(".giveupbutton").on('click', function() {
                    socket.emit('giveup');
                });
                $(".get_g_button").on('click', function() {
                    socket.emit('get_g', {
                        gid: roomid
                    });
                });
    
                $("#PAGETITLE").html("Da_Cards: VS "+opponent);
                // socket.emit("rcvsrlst");
    
                typeof CALLBACKf === 'function' && CALLBACKf();
            }, 1500);
        }, "aiI", roomid);
        SCL("gamepage loaded", "", "aiI", roomid);
    
        snddcks();
        snddcks(true);
    }
    
    function snddcks(oppo) {
        var oppo = oppo || false;
        var roomid = userlists["eo"][socket.username]["gid"];
        if (oppo === true) {
            socket.broadcast.to(roomid).emit('snddcks', {
                "d0_MP-Left": userlists["g"][roomid]["Players"][1]["MP-Left"],
                "d0_onHand": userlists["g"][roomid]["Players"][1]["deck"]["onHand"],
                "d0_onField": userlists["g"][roomid]["Players"][1]["deck"]["onField"],
                "d0_inBlockC": userlists["g"][roomid]["Players"][1]["deck"]["inBlock"].length,
                "d1_MP-Left": userlists["g"][roomid]["Players"][0]["MP-Left"],
                "d1_onHand": userlists["g"][roomid]["Players"][0]["deck"]["onHand"].length,
                "d1_onField": userlists["g"][roomid]["Players"][0]["deck"]["onField"],
                "d1_inBlockC": userlists["g"][roomid]["Players"][0]["deck"]["inBlock"].length,
            });
            console.log("Sent decks into "+roomid);
            fs.writeFile("userlistsLOG_2.log", "TWO 1: "+Date().toString()+":\n"+JSON.stringify(userlists["g"][roomid]["Players"][1]["deck"]["onHand"])+"\n\n", {flag:"a"}, function (err) {
                if (err) {
                    console.log('error happened during writing to log')
                    return console.log(err)
                }
            });
        } else if (oppo === false) {
            socket.emit('snddcks', {
                "d0_MP-Left": userlists["g"][roomid]["Players"][0]["MP-Left"],
                "d0_onHand": userlists["g"][roomid]["Players"][0]["deck"]["onHand"],
                "d0_onField": userlists["g"][roomid]["Players"][0]["deck"]["onField"],
                "d0_inBlockC": userlists["g"][roomid]["Players"][0]["deck"]["inBlock"].length,
                "d1_MP-Left": userlists["g"][roomid]["Players"][1]["MP-Left"],
                "d1_onHand": userlists["g"][roomid]["Players"][1]["deck"]["onHand"].length,
                "d1_onField": userlists["g"][roomid]["Players"][1]["deck"]["onField"],
                "d1_inBlockC": userlists["g"][roomid]["Players"][1]["deck"]["inBlock"].length,
            });
            console.log("Sent decks to "+socket.username);
            fs.writeFile("userlistsLOG_2.log", "TWO 0: "+Date().toString()+":\n"+JSON.stringify(userlists["g"][roomid]["Players"][0]["deck"]["onHand"])+"\n\n", {flag:"a"}, function (err) {
                if (err) {
                    console.log('error happened during writing to log')
                    return console.log(err)
                }
            });
        }
    
        // setTimeout(function() {
        //     // fs.writeFileSync("userlistsLOG.log", Date().toString()+":\n"+JSON.stringify(userlists["g"][roomid]["Players"][0]["deck"])+"\n\n", {flag:"a"});
        //     // fs.writeFileSync("userlistsLOG.log", Date().toString()+":\n"+JSON.stringify(userlists["g"][roomid]["Players"][1]["deck"])+"\n\n", {flag:"a"});
        // }, 100);
    }
    

1 个答案:

答案 0 :(得分:0)

最后!! 我刚刚解决了我的问题虽然我花了3天时间... 非常感谢@LemmyTauer提供的有用评论:)

这是有趣的代码部分:

function generatedeckthigieandreturn(number) {
    var arr;
    arr = [];
    var fncs;
    fncs = [];
    var ARRAYTHINGIEd = [];

    function gRC() {
        console.log("gRC called");
        return standardDeckCards[Math.floor(Math.random() * standardDeckCards.length)];
    }

    for (var a = 0; a < number; a++) {
        console.log(a);
        fncs[a] = function(b) {
            console.log(a+" called");
            return function() {
                arr[b] = gRC();
                arr[b]["position"] = b;
                arr[b]["CID"] = "CID-"+(Math.floor((Math.random() * 900) + 100)).toString();
                console.log(JSON.stringify(arr[b], null, 4));
                return JSON.stringify(arr[b]);
            }
        };
    }
    for (var c = 0; c < number; c++) {
        ARRAYTHINGIEd.push(JSON.parse(fncs[c](c)()));
    }
    return ARRAYTHINGIEd;
}
for (var xa = 0; xa < 2; xa++) {
    userlists["g"][roomid]["Players"][xa]["deck"]["onHand"] = generatedeckthigieandreturn(5);
    userlists["g"][roomid]["Players"][xa]["deck"]["inBlock"] = generatedeckthigieandreturn(50);
}

所以最后,我使用JSON.stringify()来保存卡片对象,然后使用JSON.parse()将其恢复为&#34;正常&#34;格式。

这是&#34;完整的固定问题&#34; -Code:

function joingid() {
    var roomid = userlists["eo"][socket.username]["gid"];

    socket.state = "playing";
    socket.join(roomid);
    socket.leave("lobby");
    socket.leave("searching");

    socket.emit("playerfound", {
        gid: roomid
    });
    socket.broadcast.to(roomid).emit('playerjoined', {
        usr: socket.username,
        gid: roomid
    });
}
socket.on('playerhasjoined', function(data) {
    socket.state = "playing";
    socket.leave("lobby");

    var roomid = userlists["eo"][socket.username]["gid"];

    socket.broadcast.to(roomid).emit('otheropponent', {
        usr: socket.username
    });

    setTimeout(function() {
        populateDeck2(roomid, data["oppo"]);
    }, 500);
});


function populateDeck2(roomid, oppo) {
    var oppos = [socket.username, oppo];
    userlists["g"][roomid] = {
        "RoomID": roomid,
        "Players": {
            0: {
                "Player": socket.username,
                "deck": {
                    "onHand": [],
                    "onField": [],
                    "inBlock": []
                },
                "MP-Left": 20
            },
            1: {
                "Player": oppo,
                "deck": {
                    "onHand": [],
                    "onField": [],
                    "inBlock": []
                },
                "MP-Left": 20
            }
        },
        "Creationdate": Date().toString(),
        "Winner": null,
        "currentPlayer": oppos[Math.floor(Math.random() * oppos.length)],
        "roundNR": 0
    };

    function generatedeckthigieandreturn(number) {
        var arr;
        arr = [];
        var fncs;
        fncs = [];
        var ARRAYTHINGIEd = [];

        function gRC() {
            console.log("gRC called");
            return standardDeckCards[Math.floor(Math.random() * standardDeckCards.length)];
        }

        for (var a = 0; a < number; a++) {
            console.log(a);
            fncs[a] = function(b) {
                console.log(a+" called");
                return function() {
                    arr[b] = gRC();
                    arr[b]["position"] = b;
                    arr[b]["CID"] = "CID-"+(Math.floor((Math.random() * 900) + 100)).toString();
                    console.log(JSON.stringify(arr[b], null, 4));
                    return JSON.stringify(arr[b]);
                }
            };
        }
        for (var c = 0; c < number; c++) {
            ARRAYTHINGIEd.push(JSON.parse(fncs[c](c)()));
        }
        return ARRAYTHINGIEd;
    }
    for (var xa = 0; xa < 2; xa++) {
        userlists["g"][roomid]["Players"][xa]["deck"]["onHand"] = generatedeckthigieandreturn(5);
        userlists["g"][roomid]["Players"][xa]["deck"]["inBlock"] = generatedeckthigieandreturn(50);
    }

    SP("gamepage.html", function FNCr(CALLBACKf) {
        setTimeout(function() {
            $(".gameid").html(roomid);
            $(".opponent").html(opponent);
            $(".giveupbutton").on('click', function() {
                socket.emit('giveup');
            });
            $(".get_g_button").on('click', function() {
                socket.emit('get_g', {
                    gid: roomid
                });
            });

            $("#PAGETITLE").html("Da_Cards: VS "+opponent);
            // socket.emit("rcvsrlst");

            typeof CALLBACKf === 'function' && CALLBACKf();
        }, 1500);
    }, "aiI", roomid);
    SCL("gamepage loaded", "", "aiI", roomid);

    snddcks();
    snddcks(true);
}

function snddcks(oppo) {
    var oppo = oppo || false;
    var roomid = userlists["eo"][socket.username]["gid"];
    if (oppo === true) {
        socket.broadcast.to(roomid).emit('snddcks', {
            "d0_MP-Left": userlists["g"][roomid]["Players"][1]["MP-Left"],
            "d0_onHand": userlists["g"][roomid]["Players"][1]["deck"]["onHand"],
            "d0_onField": userlists["g"][roomid]["Players"][1]["deck"]["onField"],
            "d0_inBlockC": userlists["g"][roomid]["Players"][1]["deck"]["inBlock"].length,
            "d1_MP-Left": userlists["g"][roomid]["Players"][0]["MP-Left"],
            "d1_onHand": userlists["g"][roomid]["Players"][0]["deck"]["onHand"].length,
            "d1_onField": userlists["g"][roomid]["Players"][0]["deck"]["onField"],
            "d1_inBlockC": userlists["g"][roomid]["Players"][0]["deck"]["inBlock"].length,
        });
        console.log("Sent decks into "+roomid);
        fs.writeFile("userlistsLOG_2.log", "TWO 1: "+Date().toString()+":\n"+JSON.stringify(userlists["g"][roomid]["Players"][1]["deck"]["onHand"])+"\n\n", {flag:"a"}, function (err) {
            if (err) {
                console.log('error happened during writing to log')
                return console.log(err)
            }
        });
    } else if (oppo === false) {
        socket.emit('snddcks', {
            "d0_MP-Left": userlists["g"][roomid]["Players"][0]["MP-Left"],
            "d0_onHand": userlists["g"][roomid]["Players"][0]["deck"]["onHand"],
            "d0_onField": userlists["g"][roomid]["Players"][0]["deck"]["onField"],
            "d0_inBlockC": userlists["g"][roomid]["Players"][0]["deck"]["inBlock"].length,
            "d1_MP-Left": userlists["g"][roomid]["Players"][1]["MP-Left"],
            "d1_onHand": userlists["g"][roomid]["Players"][1]["deck"]["onHand"].length,
            "d1_onField": userlists["g"][roomid]["Players"][1]["deck"]["onField"],
            "d1_inBlockC": userlists["g"][roomid]["Players"][1]["deck"]["inBlock"].length,
        });
        console.log("Sent decks to "+socket.username);
        fs.writeFile("userlistsLOG_2.log", "TWO 0: "+Date().toString()+":\n"+JSON.stringify(userlists["g"][roomid]["Players"][0]["deck"]["onHand"])+"\n\n", {flag:"a"}, function (err) {
            if (err) {
                console.log('error happened during writing to log')
                return console.log(err)
            }
        });
    }