0

如果我的代码有几个问题,我提前道歉;我对此还是很陌生。

我做了一个简单的小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。除了永远不找一份赌博软件程序员的工作,我该怎么办?

4

1 回答 1

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);
于 2013-06-10T01:25:14.063 回答