H. Lee
H. Lee

Reputation: 67

Save value of variable after running file in node.js and using "inquirer"

I have a mini game program where I I ask the user to enter a number, and if the number matches the randomly chosen number, I subtract another random number for the opponent variable. Other wise, the opponent damages me. I got the program working with the subtractions, but the problem is, everytime I run my file in node.js (i.e node fileName.js 4), all the variables in my program reset. When the "damage" is subtracted from the "hp" the hp should be saved, but it keeps resetting. mainCharacter and zombie.hp should not be resetting.

var StrawberryCough = require("inquirer");

var mainCharacter = 70;
var zombie = {
    hp: 15,
    num: 0
}

StrawberryCough.prompt([

        {
            type: "input",
            message: "Random Number 1-5: ",
            name: "number"
        }

    ]).then(function(user){

        parseInt(user.number);
        var ranNum = Math.round(Math.random() * (5 - 1) + 1);
        zombie.num = ranNum;

        if(user.number === zombie.num)
        {
            var damage = Math.round(Math.random() * (5 - 1) + 1);
            console.log("Character Damage: ", damage);
            zombie.hp -= damage;
            console.log("zombie hp", zombie.hp);
            if(zombie.hp <= 0)
            {
                console.log("You win!")
                return;
            }
        }
        else if(user.number !== zombie.num)
        {
            var zomDamage = Math.round(Math.random() * (5 - 1) + 1);
            console.log("Zombie Damage: ", zomDamage);
            mainCharacter -= zomDamage;
            console.log("main hp", mainCharacter);
            if(mainCharacter <= 0)
            {
                console.log("You lose!");
                return;
            }
        }
    });

Upvotes: 1

Views: 1991

Answers (1)

isaacdre
isaacdre

Reputation: 892

If you want data to persist, you should look into a key value store, database, saving it to a file... otherwise every time you run the file:

var mainCharacter = 70;
var zombie = {
    hp: 15,
    num: 0
}

Will set the values when the file is loaded as those lines are executed, however that will not permanently store the values and they will cease to exist after the script ends.

It looks like you're looking for the quick and scrappy solution so I would suggest using file system and saving a to something like: gameMemory.json

Contents of gameMemory.json:

{
    "mainCharacter" : 70,
    "zombie" : {
        "hp": 15,
        "num": 0
    }
}

Load the values from gameMemory.js:

fs = require('fs');
//loads the gameMemory into a json object
var gameMemory =JSON.parse(fs.readFileSync('./gameMemory.json', 'utf8'));

Then when you're done manipulating the variables and want them to persist:

fs.writeFileSync('./gameMemory.json', JSON.stringify(gameMemory, null, 2) , 'utf-8');

Upvotes: 1

Related Questions