2015-02-09 34 views
0

我正在嘗試做一個非常基本的骰子游戲(新的Javascript)。在頁面加載時,「骰子」會被「滾動」三次,並顯示結果,並顯示一條消息,說明您是否設置了滾動條6。我試圖提出一個有關贏得了多少遊戲的永久消息 - 問題是,如果你看看下面的代碼,那麼每次贏得勝利時,我爲這個「勝利」使用的變量都會增加,但是它實際上只顯示兩個值:0,如果用戶剛剛輸了,1,如果是贏。無論骰子擲出多少次,它都不會達到更高的數字。想知道是否有人有解決方案/解釋?Javascript中的非常基本的骰子游戲 - 試圖記錄'贏'變量

代碼:

console.log("Dice game. You have 3 tries to roll a 6 - go"); 
var rolls = 0; 
var wins = 0; 

function rollDice() { 
    var dice = Math.random(); 
    if (dice <= .17) { 
     dice = 1; 
    } 
    else if (dice <= .33) { 
     dice = 2; 
    } 
    else if (dice <= .50) { 
     dice = 3; 
    } 
    else if (dice <= .67) { 
     dice = 4; 
    } 
    else if (dice <= .84) { 
     dice = 5; 
    } 
    else if (dice <= 1) { 
     dice = 6; 
    } 
    return dice; 
} 

function diceGame() { 
    do { 
     var dice = rollDice(); 
     console.log(dice); 
     rolls++; 
     if (dice === 6) { 
      console.log("You won!"); 
      wins++; 
      if (rolls === 1) { 
       console.log("It took " + rolls + " try"); 
      } 
      else { 
       console.log("It took " + rolls + " tries"); 
      } 
      break; 
     } 
    } 
    while (rolls <= 2); 
    if (dice !== 6) { 
     console.log("You lost"); 
    } 
} 

diceGame(); 
console.log("Times won: " + wins); 
+0

頁面必須刷新/重新加載才能再次擲骰子? – Sufian 2015-02-09 07:34:08

+0

當你贏了,你正在做'break',而不是'繼續;' – Krzysiek 2015-02-09 07:36:06

+0

只要刪除「break」運算符 – Dart 2015-02-09 07:57:07

回答

0

你是如何運行的代碼?每次運行時,它都會將wins變量重置爲0.您需要使用按鈕或其他函數調用該函數,否則無需刷新代碼塊以再次運行。

0

一些改進;)

  1. 呼叫繼續,而不是突破MDN continue
  2. 變化rollDice功能Random number from range
  3. 匿名函數用於創建命名空間

 
    // namespace for our variables 
    (function(){

console.log("Dice game. You have 3 tries to roll a 6 - go"); var rolls = 0; var wins = 0; function rollDice() { // simple random from range (https://stackoverflow.com/a/1527820/2746472) return Math.floor(Math.random()*6)+1; } function diceGame() { do { var dice = rollDice(); console.log(dice); rolls++; if (dice === 6) { console.log("You won!"); wins++; if (rolls === 1) { console.log("It took " + rolls + " try"); } else { console.log("It took " + rolls + " tries"); } continue; //instead of break! } } while (rolls <= 2); if (dice !== 6) { console.log("You lost"); } } diceGame(); console.log("Times won: " + wins); })();
+0

感謝您的建議。我已經實現了它們,雖然我的代碼確實很整潔,但問題還沒有解決。有什麼建議麼?另外,'繼續'似乎會導致遊戲在贏得勝利之後發揮作用,直到我嘗試避免三次嘗試。 – Avariel 2015-02-10 01:55:02

+0

適用於我:'骰子游戲。你有3次嘗試推出6 - 去你贏了! 花了1次嘗試你贏了! 花了2次嘗試贏得了次數:2'。也許你想要別的東西。描述你的目標;) – Krzysiek 2015-02-10 07:06:15

-1

rollDice功能,可簡化的1行。

var dice = Math.floor(Math.random() * 6) + 1; 
+0

這是範圍0-6,並且具有非均勻分佈。 – Krzysiek 2015-02-09 07:44:42

+0

0的可能性極小。所以你永遠不會看到它發生! – Kerndog73 2015-02-09 07:47:21

+0

但它是!「一般情況下,我們隨機選擇特定範圍內的數字,0--向俄羅斯發送核彈,但不太可能發生,不要打擾這個。」 – Krzysiek 2015-02-09 07:49:45

-1

這是因爲如果你贏了,你就休息一下,因此在第一場勝利後退出循環。