2013-06-10 3 views
0

내 코드에 몇 가지 문제가있는 경우 사전에 사과드립니다. 나는 아직도 이것에 아주 새롭다.Javascript While 루프 이상한 결과 반환

나는 다음과 간단한 작은 RNG 도박 게임, 제작 : (즉, 뺄셈) 잘을 잃고

var funds = 100; 
var betting = true; 


function roll_dice() { 
    var player = Math.floor(Math.random() * 100); 
    var com = Math.floor(Math.random() * 100); 
    var bet = prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign."); 
    if (player === com) { 
     alert("tie."); 
    } 
    else if (bet > funds) { 
    alert("You don't have that much money. Please try again"); 
    roll_dice(); 
    } 
    else if (player > com) { 
     funds += bet; 
     alert("Your roll wins by " + (player - com) + " points. You get $" + bet + " and have a total of $" + funds + "."); 
    } 
    else { 
     funds -= bet; 
     alert("Computer's roll wins by " + (com - player) + " points. You lose $" + bet + " and have a total of $" + funds + "."); 
    } 
} 

while (betting) { 
    var play = prompt("Do you wish to bet? Yes or no?"); 
    if (funds <= 0) { 
     alert("You have run out of money."); 
     betting = false; 
    } 
    else if (play === "yes") { 
     roll_dice(); 
    } 
    else { 
     alert("Game over."); 
     betting = false; 
    } 
} 

코드 거래를하지만, 추가 부분을 처리 할 수없는 것. 당신이 내기하고, 말하자면, 50 점을 얻고, 이기면, 10050을 얻게 될 것입니다. 도박 소프트웨어 프로그래머로서 직업을 찾는 것을 제외하고, 어떻게해야합니까?

답변

7

prompt은 문자열을 반환합니다. 문자열에서 문자열 결과에 번호를 추가 :

> "12" + 13 
"1213" 

에만 문자열 연결로 정수의 뺄셈 결과, 더하기 기호 수행하는 동안 :

> "12" - 13 
-1 

당신은 사용자의 입력을 변환해야 정수로 :

var bet = parseInt(prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign."), 10); 
+1

이것은 또한 빼기가 작동하는 이유를 설명합니다. '-' 연산자는'+'처럼 오버로드되지 않습니다. –