2015-10-20 94 views
-3

試圖創建一個非常簡單的猜數遊戲作爲第一個項目。我希望玩家在失敗之前有5次猜測。簡單的Javascript猜測遊戲程序

我在排除錯誤或編碼錯誤時遇到了困難。

var num = Math.floor((Math.random(1,10) * 10) +1); 
console.log(num); //To check 
var counter = 5; 
while(counter > 0){ 
    function guess(){ 
    counter = counter-1 
    var guess = prompt("You've got " + counter + " tries to guess the number."); 
    if (num == guess){ 
    alert("That's the number!"); 
    }else if (guess != (int){ 
    alert("That's not a number..."); 
    }else{ 
    alert("Nice try"); 
    } 
} 
} 
alert("You lost."); 
+4

什麼錯誤?什麼錯誤?你沒有描述什麼是不工作的。我的第一個猜測是你並不是真的想在一個循環中定義一個函數,而只是調用它。 – csmckelvey

回答

0

工作小提琴:http://jsfiddle.net/0skh4t4r/

var num = Math.floor((Math.random(1, 10) * 10) + 1); 
console.log(num); //To check 
var counter = 5; 

function guess() { 
    var x = prompt("You've got " + counter + " tries to guess the number."); 
    if (!x) return; // cancel the game 
    counter--; 
    if (num === parseInt(x)) { 
    alert("That's the number!"); 
    return; 
    } else if (isNaN(x)) { 
    alert("That's not a number..."); 
    } else { 
    alert("Nice try"); 
    } 
    if(counter === 0) { 
    alert("You lost"); 
    } else { 
    guess(); // next try 
    } 
} 

guess();