0

I apologize in advance if there are several things wrong with my code; I'm still very new to this.

I made a simple little RNG betting game, which follows:

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;
    }
}

The code deals with losing (i.e. subtraction) just fine, but can't seem to handle the addition part. If you bet, say, 50 and win, you'll wind up with 10050. Aside from never seeking out a job as a gambling software programmer, what should I do?

1 Answer 1

7

prompt returns a string. Adding a number to a string results in a string:

> "12" + 13
"1213"

While subtraction results in an integer, as only string concatenation is done with a plus sign:

> "12" - 13
-1

You need to convert your user's input into an integer:

 var bet = parseInt(prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign."), 10);
Sign up to request clarification or add additional context in comments.

1 Comment

this would also explain why subtraction works; the - operator is not overloaded like the + one is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.