Declaring an "unassigned" integer variable

Declaring an "unassigned" integer variable
0.0 0

#1

Hello everyone!

My siblings and I created a fun card game, and I thought it would be fun, and rather convenient, to code a small scoring system for it. However, I am running into one major problem. The scoring code is in function() format, and everything gets added the way I intended. The problem I am having is I cannot figure out how to create variables for the players’ scores (e.g. var player1 = 0, player2 = 0, player3 = 0 etc.) without them resetting to 0 every time I run the code. I’m sure the way to do this isn’t that complicated, but I Googled for around 30 minutes but came across nothing to help me out. I want to declare integer variables that aren’t assigned to something every time I run the code. I’ve tried doing var player1; var player2; var player3; etc, but when I add numbers to them the result is NaN. Does anyone know of a way of doing this efficiently?

Thanks!

~ Myth


#2

Is there any way you can share your code, or at least the function in question? As I understand it, one solution could be to use short circuit assignment, which will initialize a variable only if its not given a truthy value. Example:

function setPlayerScores(p1, p2) {
  var player1 = p1 || 0;
  var player2 = p2 || 0;
  return "player1 has a score of " + player1 + " and player2 has a score of " + player2;
}

This function doesn’t do anything at all, so it’s not a drop in replacement for whatever you’re doing, but notice that it’s going to set each value to zero iff (if and only if) it isn’t given a different number.

setPlayerScores(1, 2); // "player1 has a score of 1 and player2 has a score of 2"
setPlayerScores(undefined, 444); // "player1 has a score of 0 and player2 has a score of 444"
setPlayerScores(); //"player1 has a score of 0 and player2 has a score of 0"

#3

So you’re saying you want to be able to add up the score but keep that score for the future in case you want to add some more?

Seems like a simple scoping issue.

The most basic solution is to create a global variable, but that’s not entirely recommended.

Either way, you have to separate the initialization of the variable outside of that function. You could do this by turning the function into an object and the turning the addition function into a method.

var game = {
  score1: 0,
  score2: 0,
  addScore: function(toAdd1, toAdd2){
    game.score1 += toAdd1;
    game.score2 += toAdd2;
  }
}

game.addScore(5, 6);
game.addScore(10, 11);
console.log("Player 1: " + game.score1); //"Player 1: 15"
console.log("Player 2: " + game.score2); //"Player 2: 17"

#4

Thank you for your response! However, while this does help a ton with some organization issues, it does not fix the main issue I am having. I think it was a bit unclear on what I needed. I have to rerun the code every time I need to add score, which resets all of the scores to 0 when I run it again. Here is my code to explain what I mean:

    var game = {
    	i: 0,
    	c: 0,
    	g: 0,
    	e: 0,
    	addScore: function(add1, add2, add3, add4) {
    		game.i += add1;
    		game.c += add2;
    		game.g += add3;
    		game.e += add4;
    	}
    };

    function scoring(stats) {
    	switch (stats[0]) {
    		case "ian":
    			switch (stats[1]) {
    				case "win":
    					game.addScore(500,0,0,0);
    					break;
    				case "dealer":
    					if (i - 2000 >= 0) {
    						game.addScore(-2000,0,0,0);
    					}
    					break;
    				case "magician":
    					if (i - 5000 >= 0) {
    						game.addScore(-5000,0,0,0);
    					}
    					break;
    			}
    			break;
    		case "caden":
    			switch (stats[1]) {
    				case "win":
    					game.addScore(0,500,0,0);
    					break;
    				case "dealer":
    					if (c - 2000 >= 0) {
    						game.addScore(0,-2000,0,0);
    					}
    					break;
    				case "magician":
    					if (c - 5000 >= 0) {
    						game.addScore(0,-5000,0,0);
    					}
    					break;
    			}
    			break;
    		case "grace":
    			switch (stats[1]) {
    				case "win":
    					game.addScore(0,0,500,0);
    					break;
    				case "dealer":
    					if (g - 2000 >= 0) {
    						game.addScore(0,0,-2000,0);
    					}
    					break;
    				case "magician":
    					if (g - 5000 >= 0) {
    						game.addScore(0,0,-5000,0);
    					}
    					break;
    			}
    			break;
    		case "evan":
    			switch (stats[1]) {
    				case "win":
    					game.addScore(0,0,0,500);
    					break;
    				case "dealer":
    					if (e - 2000 >= 0) {
    						game.addScore(0,0,0,-2000);
    					}
    					break;
    				case "magician":
    					if (e - 5000 >= 0) {
    						game.addScore(0,0,0,-5000);
    					}
    					break;
    			}
    			break;
    	}
    	console.log("Ian: "+game.i+"\nCaden: "+game.c+"\nGrace: "+game.g+"\nEvan: "+game.e);
    }
    var stats = [];
    stats.push(prompt("Enter a name"));
    stats.push(prompt("Enter scoring type (kit name or win)"));
    scoring(stats);

The format for scoring is in the form of a function, and I cannot figure out how to loop it so I don’t have to rerun the code every time. Is there a way for me to do that, or possibly a way to remove the function but keep the way it works?


#5

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

Are you running this in the console or in a browser? If it’s in the browser, you have lots of options for persisting data as long as you want. If it’s in the console, you’ll need to use a while loop

while(true) {
   // application logic...
   if(input === "q") { break; } // quits the app when the user types 'q'
}

#6

Thanks for cleaning up my code haha. I wasn’t sure how to do that. :slight_smile:
And I am creating this using repl.it, so it is similar to a browser console. Should I remove the break; lines in the code to prevent the code from stopping, therefore, if I have the while loop in, it will keep going? Or will that mess up the logic of the code and prevent it from working properly?

EDIT: I have figured out that I do not need to remove the break; statements, I just need to log the score to the prompts :smiley:


#7

By “console”, I essentially meant Node. repl.it, codepen, or anything else in the browser runs… in the browser. Don’t use an infinite loop in that case.

A scorekeeper would be a really great React project, by the way.


#8

Ah, I see now. By “rerunning the code” what you’re really doing is refreshing the whole thing.

I personally would use HTML and event handlers to determine when the appropriate code runs. It’s been a while since I’ve used a console strictly so I can’t be certain that the following is the best solution. What you can do is have the two functions call each other recursively, and add a timeout between the cycle so your browser doesn’t crash. I’ve added another case for names called “end” that will stop the cycle so it doesn’t run infinitely.

var game = {
  i: 0,
  c: 0,
  g: 0,
  e: 0,
  addScore: function(add1, add2, add3, add4) {
    game.i += add1;
    game.c += add2;
    game.g += add3;
    game.e += add4;
  },
  runStats: function() {
    var stats = [];
    stats.push(prompt("Enter a name"));
    stats.push(prompt("Enter scoring type (kit name or win)"));
    scoring(stats);
    console.log(
      "Ian: " +
        game.i +
        "\nCaden: " +
        game.c +
        "\nGrace: " +
        game.g +
        "\nEvan: " +
        game.e
    );
  }
};

function scoring(stats) {
  switch (stats[0]) {
    case "ian":
      switch (stats[1]) {
        case "win":
          game.addScore(500, 0, 0, 0);
          break;
        case "dealer":
          if (i - 2000 >= 0) {
            game.addScore(-2000, 0, 0, 0);
          }
          break;
        case "magician":
          if (i - 5000 >= 0) {
            game.addScore(-5000, 0, 0, 0);
          }
          break;
      }
      break;
    case "caden":
      switch (stats[1]) {
        case "win":
          game.addScore(0, 500, 0, 0);
          break;
        case "dealer":
          if (c - 2000 >= 0) {
            game.addScore(0, -2000, 0, 0);
          }
          break;
        case "magician":
          if (c - 5000 >= 0) {
            game.addScore(0, -5000, 0, 0);
          }
          break;
      }
      break;
    case "grace":
      switch (stats[1]) {
        case "win":
          game.addScore(0, 0, 500, 0);
          break;
        case "dealer":
          if (g - 2000 >= 0) {
            game.addScore(0, 0, -2000, 0);
          }
          break;
        case "magician":
          if (g - 5000 >= 0) {
            game.addScore(0, 0, -5000, 0);
          }
          break;
      }
      break;
    case "evan":
      switch (stats[1]) {
        case "win":
          game.addScore(0, 0, 0, 500);
          break;
        case "dealer":
          if (e - 2000 >= 0) {
            game.addScore(0, 0, 0, -2000);
          }
          break;
        case "magician":
          if (e - 5000 >= 0) {
            game.addScore(0, 0, 0, -5000);
          }
          break;
      }
      break;
    case "end": ///enter "end" during first prompt to stop cycle
      return;
  }
  setTimeout(game.runStats, 3000); ////wait 3 seconds before looping
}

game.runStats();


#9

Thank you so much, it worked perfectly! I was unaware of the setTimeout(); function. Thank you for introducing me to that! :smiley: