userNaN
userNaN

Reputation: 526

Javascript While Loop Returning Strange Results

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?

Upvotes: 0

Views: 120

Answers (1)

Blender
Blender

Reputation: 298176

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

Upvotes: 7

Related Questions