To practice coding, I am making a virtual casino, with a roulette wheel. For simplicity's sake, the wheel currently has only 4 sections, instead of the usual 37. I'm trying to have a "money" variable that adjusts every time the player spins the roulette wheel. IE if the player bets $10 on number 4 and loses, they will now have $190 instead of $200. The problem is, the "money" variable does not seem to change, even though its a global variable.
Here's a piece of my code. What is the problem?
var money = 200;
function spin(){
var landing = Math.floor(Math.random() * 4) + 1;
var nsvalue = parseInt(document.regular_roulette.num_select.value);
var betvalue = parseInt(document.regular_roulette.bet.value);
if (landing === nsvalue) {
alert("You win $" + betvalue * 3);
money = money + (betvalue * 3);
} else {
alert("You lose $" + betvalue);
money = money - betvalue;
}
}
document.write("You currently have $" + money);
Normally you might put this in some input fields, check those values (check for not a number) and output to some element on the page. Here I use a spin button click for the spin action. Example.
var money = 200; function spin() { var landing = Math.floor(Math.random() * 4) + 1; var nsvalue = parseInt(document.getElementById("num_select").value); var betvalue = parseInt(document.getElementById("bet").value); if(!isNaN(nsvalue)&& !isNaN(betvalue)) if (landing === nsvalue) { document.getElementById("action").innerText =("You win $" + betvalue * 3); money = money + (betvalue * 3); } else { document.getElementById("action").innerText =("You lose $" + betvalue); money = money - betvalue; } //something here to show spin value perhaps? } document.getElementById("spinme").onclick = function(event) { spin(); document.getElementById("results").innerText = ("You currently have $" + money); }
<div id="results"> empty </div> <div id="regular_roulette"> <label>Choice <input id="num_select"> </label> <label>Bet <input id="bet"> </label> </div> <button id="spinme"> Spin! </button> <div id="action"> </div>
Instead of using a global variable. you can try to pass it to the function and return it and reassign it.
var money = 200;
function spin(m){
var landing = Math.floor(Math.random() * 4) + 1;
var nsvalue = parseInt(document.regular_roulette.num_select.value);
var betvalue = parseInt(document.regular_roulette.bet.value);
if (landing === nsvalue)
{
alert("You win $" + betvalue * 3);
m = m + (betvalue * 3);
}
else
{
alert("You lose $" + betvalue);
m = m - betvalue;
}
return m;
}
money = spin(m);
document.write("You currently have $" + money);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.