【问题标题】:JS game Crowns and Anchors: error in outcomeJS 游戏 Crowns and Anchors:结果错误
【发布时间】:2017-03-05 20:22:46
【问题描述】:

在 Ethan Brown 的“Learning JavaScript”一书的帮助下开发的游戏的结果难以理解。

代码如下:

//helper functions for randomizing
function rand(x,y){
  return x + Math.floor((y-x+1)*Math.random());
}

function getFace(){ return ['crown','heart','spade','club','diamond','anchor'][rand(0,5)]; }

//the game
function crownsAndAnchors(){
  console.log('Let\'s play Crowns and Anchors!');
  let rounds = 0;
  let funds = 50;
  while( funds > 1 && funds < 100 ){
    rounds ++;
    console.log(`Round: ${rounds}`);
    let totalBet = 7;
    let bets = { crown: 0, heart: 0, spade:0, club:0, diamond:0, anchor:0 };
    if (totalBet == 7){
      totalBet = funds;
      console.log('You pulled out 7p, your lucky number! Bet all on heart');
      bets.heart = totalBet;
    }else{
       //distribute totalBet randomly
    }
    funds = funds - totalBet;
    console.log('\tBets: ' + Object.keys(bets).map(face => `${face} ${bets[face]}p`).join(' || ') + `  (total: ${totalBet} pence)`);
    const hand = [];
     // roll the dice
    console.log("_______________rolling the dice ____________")
    for (let i = 0; i < 3; i++) {
      hand.push(getFace());
    }
    console.log(`\tHand: ${hand.join(', ')}`);
    //check for winnings
    let wins = 0;
    for (let i = 0; i < hand.length; i++) {
      let face = hand[i];
      if (bets[face] > 0) wins = wins + bets[face];
    }
    funds = funds + wins;
    console.log(`\tWinnings: ${wins}`);
  }
  console.log(`\nEnding Funds: ${funds}`);
}

crownsAndAnchors();

我将变量 totalBet 硬编码为 7,以便轻松监控最终结果。例如,如果三分之二的骰子结果是heart,那么期末资金应该是150,对吗?

但是,当我运行代码(节点v7.6.0)时,我返回的是:

Let's play Crowns and Anchors!

Round: 1
You pulled out 7p, your lucky number! Bet all on heart
        Bets: crown: 0p || heart: 50p || spade: 0p || club: 0p || diamond: 0p || anchor: 0p  (total: 50 pence)
_______________rolling the dice ____________
        Hand: heart, heart, club
        Winnings: 100

Ending funds: 100

我知道我以某种方式错误地更新了funds,我只是不知道为什么。

提前谢谢你!!!

【问题讨论】:

    标签: javascript iteration addition


    【解决方案1】:

    线 资金=资金-totalBet; 正在将资金设置为 0,然后您将获得 50 的两场胜利,然后将其添加为 100。

    如果您消除资金 = 资金 - totalBet 的那条线,那么您将得到预期的 150。

    或者将那条线移到掷骰子之后,只有在你没有赢得任何东西的情况下才执行它。

    【讨论】:

    • 好眼光,拉里!我继续删除该行并添加到//检查奖金的底部for loop块语句if (!wins) { funds = funds - totalBet; } 它似乎正在根据统计概率工作,现在!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2022-07-08
    相关资源
    最近更新 更多