How do you permanently save the last value of a variable using Math.random(), so it can be added to another variable?

Sorry, if the question sounds weird, but I’m basically trying to code the “21 card game,” and these are the instructions:

21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total.

The game is won by the player whose chosen number causes the running total to reach exactly 21.

The running total starts at zero. One player will be the computer.

Players alternate supplying a number to be added to the running total.

Task

Write a computer program that will:

  • do the prompting (or provide a button menu),
  • check for errors and display appropriate error messages,
  • do the additions (add a chosen number to the running total),
  • display the running total,
  • provide a mechanism for the player to quit/exit/halt/stop/close the program,
  • issue a notification when there is a winner, and
  • determine who goes first (maybe a random or user choice, or can be specified when the game begins).
const player = choiceNumber => {
const playerTotal = choiceNumber;
return playerTotal;

}

let runningTotal = player(2);

const computer = computerChoice => {
const computerValue = computerChoice;
console.log(`Computer chooses: ${computerValue}`);

switch(computerValue) {
  case 1:
  runningTotal += 1;
  break;
  case 2:
  runningTotal += 2;
  break;
  case 3:
  runningTotal += 3;
  break;
}
}
computer(Math.floor(Math.random() * 4));


console.log(`Running total: ${runningTotal}`);

I’m programming the computer portion of this project, and my goal is for the computer to randomly choose either 1, 2, or 3 and add that value to let runningTotal = player(2); . I figured out how to make the computer randomize the three numbers, and add it to let runningTotal = player(2);, but I’m not sure how to get the last random value of const computerValue = computerChoice; to permanently add to runningTotal, and then have a new random value permanently add on top of that. Thank you!

what do you mean with “permanently add to runningTotal”?
Because every time you run computer, the value is added to runningTotal

(You also don’t need the switch — why don’t yoi just runningTotal += computerValue?)

Basically like if the runningTotal started at 0, then the computer function randomly chose the value 1 to be added to the running total, runningTotal would permanetly equal 1 (ie the new valhe of runningTotal would be 3) while the computer function randomly finds a new number to add to runningTotal (lets say computer finds 2, then runningTotal would equal 5)

you need to call computer again then

1 Like

Ah okay, thank you! I’ll give that a go

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.