I am working on a replica of an old game I played in High School called Drug Wars. I have global variables that hold the qty of each drug owned. Originally I just used a different function for each buy and sell operation for each drug. Trying to save myself some code and provide for some scale ability I wanted to change it to one function for buying, passing the drugqty, drugprice(done by a different function), and the drugname.
The part I am stuck with is trying to update the drugqty (used locally in the function) to the global variable.
function buy(drugqty, drugprice, drugname)
{
if (money < drugprice)
{
window.alert("You do not have enough money to do that!")
}
else if(money >= drugprice)
{
var maxdrug = money/drugprice;
var addtoqty;
addtoqty=prompt("How many would you like to purchase? They are $" + drugprice +" a unit. You can afford " + Math.floor(maxdrug) + "." );
if((addtoqty*drugprice)>money)
{
window.alert("Nice try you need more money to do that!")
}
else {
drugqty = parseInt(drugqty, 10) + parseInt(addtoqty, 10);
money = money - (drugprice*addtoqty);
document.getElementById(drugname+"qty").innerHTML=drugqty;
document.getElementById("money").innerHTML=money;
}
}
}
Below is my buy button for one particular drug.
<td><center><button onclick="buy(cocaineqty, cocaine, 'cocaine')">Buy</center></button></center></td>
When the button is pressed it calls the function and executes correctly.
I just need to figure out how to update the global variable cocaineqty with what the local function drugqty creates.
I tried things like
drugname+"qty"=drugqty;
My two thoughts were to parse that information again from where it is displayed or somehow update the global variable in the function(again using it for more than one drug in the future so it can be done dynamically)
<td id="cocaineqty" align="center">0</td>
My first post here but I am more than willing to make changes or correct any mistakes with the post. Thanks for your time!
edit: Updated my code for the correct information based on the checked answer
function buy(drugqty, drugprice, drugname)
{
if (money < drugprice)
{
window.alert("You do not have enough money to do that!")
}
else if(money >= drugprice)
{
var maxdrug = money/drugprice;
var addtoqty;
addtoqty=prompt("How many would you like to purchase? They are $" + drugprice +" a unit. You can afford " + Math.floor(maxdrug) + "." );
if((addtoqty*drugprice)>money)
{
window.alert("Nice try you need more money to do that!")
}
else {
drugqty = parseInt(drugqty, 10) + parseInt(addtoqty, 10);
money = money - (drugprice*addtoqty);
document.getElementById(drugname+"qty").innerHTML=drugqty;
document.getElementById("money").innerHTML=money;
window[drugname+"qty"]=drugqty;
}
}
Thanks again for all of your assistance!