Honesty Rocks! truth rules.

Random With Functions?

HOME      >>       Programming

Feelay

Hey!

Is it possible to use a random script on functions.
Lets say I have created three functions (Items that a user will win if he defeates a monster).

One function is a function named shield() and another function is named sword() and a third function is named helmet().
Now when a player defeates a monster, he must be awarded. So.. How can I randomize what item he should get? something like

rand(sheild(), sword(), helmet());

or?

Thanks //Feelay

turbopowerdmaxsteel

You can only use the rand function to generate a random number. However, this number can be used to call any of those functions randomly. This can be easily accomplished using a switch - case statement.

switch(rand(1, 3)){ case 1: sheild(); break; case 2: sword(); break; case 3: helmet(); break;}


Feelay

oh my :) Never wanted to learn how to use that switch case thing :) Well.. I think I will have to learn then.. Thank You ^-^//Feelay


TavoxPeru

I agree with turbopowerdmaxsteel, that's the way to do that in my opinion, but, another way to do the same thing is by using a series of IF and ELSEIF statements on the same expression, for example the following code is another way to write the same thing:

 

<?php$i=rand(1, 3);if ($i == 1) { sheild();} elseif ($i == 2) { sword();} elseif ($i == 3) { helmet();}?>
Don't forget to always include a break statement at the end of every case, because the switch statement executes line by line and if you don't include it PHP will continue executing the next code until it finds a break statement or the end of the switch block. Also, it is recommended to include a default case that will be executed in case anything match.

 

A special case is the default case. This case matches anything that wasn't matched by the other cases, and should be the last case statement.

For more information go to PHP: switch - Manual.

 

Best regards,


Jared

Yes you may find at some point through editing that the amount of rewards may change. So it is always wise to have as much error checking in your script as possible:

$rewards_num = 3;$reward = rand (1, $rewards_num); // for now, there are 3 options.switch ($reward) { case 1: helmet (); break; case 2: sword (); break; case 3: helmet (); break; default: wrong_reward (); break; // this would be a function containing a returned value from the rand () that is invalid}

And as the previous poster mentioned, check out that link for more info on the switch.