0
我無法理解我在Ethan Brown的書「Learning JavaScript」幫助下開發的遊戲的結果。JS遊戲Crowns and Anchors:結果錯誤
下面是代碼:
//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
錯誤我只是想不通爲什麼。
非常感謝你提前!
好眼,拉里!我繼續前進並刪除該行,並將其添加到_ //底部查詢winnings_' for loop'語句 'if(!wins){funds = funds - totalBet; }' 它現在好像按照統計概率工作!謝謝 –