lundi 30 novembre 2015

Randomly select from array then assign selection to a variable

I have a function that randomly selects a monster from an object. Here's the function:

var travel = function(direction) {
        var newRoom = rooms[currentRoom.paths[direction]];
        if (!newRoom) {
            $("<p>You can't go that way.</p>").properDisplay();
        }
        else {
            currentRoom = newRoom;
            $("<p>You are now in the " + currentRoom.name + " Room.</p>").properDisplay();
                if (currentRoom.hasMonsters) {
                    function pickRand() {
                        var monsterArray = Object.keys(monsters);   
                        var randomKey = Math.floor(Math.random() * monsterArray.length);
                        return $("<p>Holy Crap!  There's a " + monsterArray[randomKey] + " in here!</p>").properDisplay();  
                    }
                    pickRand();

                }
        }
    };

Here's the object:

var monsters = {
    zombie:  {
        hitPoints: 10,
        loot: "magic knife"
    },
    skeleton: {
        hitPoints: 15,
        loot: "magic shield"
    },
    ghoul:  {
        hitPoints: 12,
        loot: "magic helm"
    }
};  

It's set up to randomly select "Zombie", "Skeleton", or "Ghoul." Everything works fine. How do I take whatever was randomly selected and save it to a variable?

I've tried a couple things like:

var beast = pickRand();

and

var beast = monsterArray;

But no luck. What am I missing?




Aucun commentaire:

Enregistrer un commentaire