2015-10-20 59 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();