简体   繁体   中英

How to differentiate between variables passed into function?

I'm working on an automatic (runs until done without user input) blackjack game.

let randomDeal = () => {
  let cardOne = Math.ceil(Math.random() * 10);
  let cardTwo = Math.ceil(Math.random() * 10);
  return cardOne + cardTwo;
}


let player = randomDeal();
let dealer = randomDeal();

console.log("Your hand: " + player);
console.log("Dealer's hand: " + dealer);

let hit = (hand) => {
  if (hand <= 16){
    hand += Math.ceil(Math.random() * 10);
    console.log("Second hand: " + hand);
    if (hand <= 21){
      hand += Math.ceil(Math.random() * 10);
      console.log("Third hand: " + hand);
    }
  }else{
    console.log("Stay: " + hand);
  }
}

hit(player);
hit(dealer);

So far it goes like this:

$ babel-node main.js
Your hand: 6
Dealer's hand: 4
Second hand: 11
Third hand: 19
Second hand: 10
Third hand: 15

I'm confused about how to pass both player and dealer into the hit function and have them return their values back as player and dealer . Right now it is hard to separate them.

IDEAL OUTPUT:

$ babel-node main.js
    Your hand: 6
    Dealer's hand: 4
    Your second hand: 11
    Your third hand: 19
    Dealer's second hand: 10
    Dealer's third hand: 15

Using an object? Start:

let ob = {
  player: 0,
  dealer: 0
}

post function:

ob = {
  player: 18,
  dealer: 19
}

No, a function cannot differentiate between variables (or any other expressions) that were used to compute its arguments. It can only differentiate between values.

For your case, you should consider using a second parameter with the (genitive of the) name of the player:

function hit (hand, prefix) {
  if (hand <= 16) {
    hand += Math.ceil(Math.random() * 10);
    console.log(prefix+" second hand: " + hand);
    if (hand <= 21) {
      hand += Math.ceil(Math.random() * 10);
      console.log(prefix+" third hand: " + hand);
    }
  } else {
    console.log(prefix+" stay: " + hand);
  }
}

hit(player, "Your");
hit(dealer, "Dealer's");

For simplicity could you just return an array of the two items?

return [player, dealer];

Then in the calling function:

result = hit(player, dealer);
player = result[0];
dealer = result[1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM