php decreasing number in database without letting it go below 0

Associate
Joined
11 Oct 2008
Posts
268
Hey guys,
I have some code for a game, which works like this. Theres a little battle on the screen, and when its over. the game awards the charater with some money. It takes this money from the game bank.

at the moment, the money is generated by rand (1,10) and if the bank has less that 1 money stored. It doesn't award the character with anything. However, if there is 3 coins in the bank, and the rand rolls a 5, the bank then goes into -2 coins. Is there a way to make it only deduct a 3 to bring the bank to 0 and not minus. Sorry if I have made a mess of the explanation. Heres the code I have so far.

PHP:
if (($enemyHp <= 0) && ($activeBattle =="yes") && ($gameMoney >=1)) {

    $moneyWon = mt_rand(1, 10);

    $id = 1;
    $sql2 = "UPDATE money SET characterMoney=characterMoney+?, gameMoney=gameMoney-? WHERE id=?";
    $statement = $connect->prepare($sql2);
    $statement->execute(array($money,$moneyWon,$id));
 
Soldato
Joined
18 Jan 2006
Posts
3,111
Location
Norwich
Very easy actually :)
PHP:
if (($enemyHp <= 0) && ($activeBattle =="yes") && ($gameMoney >=1)) {
if($gameMoney <= 10)
{
    $moneyWon = mt_rand(1, 10);
}
else
{
    $moneyWon = mt_rand(1, $gameMoney);
}
    $id = 1;
    $sql2 = "UPDATE money SET characterMoney=characterMoney+?, gameMoney=gameMoney-? WHERE id=?";
    $statement = $connect->prepare($sql2);
    $statement->execute(array($money,$moneyWon,$id));

What I've done there is to add a second check within the function:
If the bank's money is greater than or equal to 10, then use 10 as the maximum in the random number generated, or alternatively use the total money in the bank as the maximum :)

-Leezer-
 
Associate
Joined
21 May 2013
Posts
1,991
Your logic is the wrong way round, should be:

if ($gameMoney >= 10)
...

This is correct.

Currently it uses 10 as the maximum money when the bank's money is LESS THAN or equal to 10. 10 should only be used as the maximum money if the bank's money is MORE THAN or equal to 10, as stated above.
 
Associate
Joined
10 Nov 2013
Posts
1,808
Apologies, misread - I thought $gameMoney was the bank's money :)

EDIT: unless kaku was agreeing with me?! I'm confused! :D
 
Last edited:
Back
Top Bottom