0

I am making a basic dice game, the object is to have the person roll the dice, if they get a 7 they get $4 added to their bet, other wise they lose $1.

For some reason, instead of adding $4 to the already established amount, it will physically add the 4 in, so if the person has $5 and rolls a 7 instead of adding 4 to 5 to make 9, it simply adds the 4 on to make 54, any suggestions?

here is my fiddle

  <script>


        function rollDice(){
        var userInput = document.getElementById("bet").value;
        document.getElementById("bet").value = userInput; 
        var d1 = Math.floor(Math.random() * 6) + 1;
        var d2 = Math.floor(Math.random() * 6) + 1;
        var diceTotal = d1 + d2;
        do {
            if(diceTotal === 7) {
                alert("your rolled a " +d1+ " and a " +d2+ " for a total of                      " +diceTotal +"! You win $4");
                document.getElementById("bet").value = userInput + 4;
                 break; 
            } else {
                alert("your rolled a " +d1+ " and a " +d2+ " for a total of " +diceTotal +"! You lose $1");
                document.getElementById("bet").value = userInput - 1;
                break;  
            }
        } while (userInput >= 0);
        }
    </script>
</head>
<body>          
    <div class="container-fluid">
        <div class="page-head"> 
            <h1 align="center">Lucky Sevens</h1>
        </div>
    </div>  
    <div class="container" align="center"> 
        <table style="border: 1px solid black"> 
            <tr>
                <th><h3 align="center">Lucky Sevens</h3></th>
            </tr>
            <tr>
                <td>
                    <form>
                        Starting Bet: 
                        <input id="bet" type="text"/>
                    </form>
                </td>   
            </tr>
            <tr>
                <td align="center">
                    <button onclick="rollDice()">Play</button>
                </td>
            </tr>
        </table>
    </div> 
davejal
  • 6,009
  • 10
  • 39
  • 82
johnster
  • 63
  • 2
  • 8
  • You need to `parseInt()` the numbers – Mark Eriksson Jan 27 '16 at 02:15
  • Thanks Mark. Where would I add the paseInt? – johnster Jan 27 '16 at 03:26
  • sorry I'm on my phone atm. Wrap it about userInput. So for example, `document.getElementById("bet").value = parseInt(userInput) + 4;` you'll need to do the same for the other line too that does `userInput - 1;` – Mark Eriksson Jan 27 '16 at 03:30
  • Never-mind Mark, that worked! Thanks a million! – johnster Jan 27 '16 at 03:33
  • no worries. The reason that works is because the way you were doing it, it thinks `userInput` is a string, so it literally tries to add the number 4 on to it, so you need to parse `userInput` as an integer (whole number) for it to be able to do maths – Mark Eriksson Jan 27 '16 at 03:34

0 Answers0