Random With Functions?

free web hosting
Free Web Hosting > Computers & Tech > Programming > Scripting > PHP

Random With Functions?

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
CODE
rand(sheild(), sword(), helmet());

or?

Thanks //Feelay

Reply

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.

CODE
switch(rand(1, 3))
{
    case 1:
           sheild();
        break;

    case 2:
        sword();
        break;

    case 3:
        helmet();
        break;
}

Reply

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

//Feelay

Reply

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:

CODE
<?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.

QUOTE
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,

 

 

 


Reply

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:

CODE
$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.

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Similar Topics

Keywords : random, functions,

  1. String Library Functions
    A few questions (4)
  2. Php: Lesson #3;functions
    PHP. (0)
    Well, the last lesson was on If...Else statements, this one will be on Functions. Things you need
    to know 1.Basic PHP(Lesson 1) 2.I only speak English, sorry. So, everything will be in English
    terms. 3.I only put the stuff in quotes to be more organized. xD Lesson #3; Functions!
    Questions & Answers Q1.What is a function? A1.A function is code that we can access at any time,
    such as the e-mail function; mailto(email@something.com). Q2.Why use functions? A2.Would you rather
    use CODE <?php lots and lots of code more code more and more code ?&#....
  3. Php Random Selector
    whats the code (2)
    Is there a PHP script that randomly selects a string from a list? example, the list is: 1-Pie
    2-Balls 3-eggs The script would view a random
    word from those 3 every time i run it. Also is there a function that gives a random number between
    0 and a number i select?....
  4. Using Regular Expressions To Parse Functions
    (5)
    I have a hierarchy of functions represented as something like:-
    @BeforeText(@AfterText(@ReadURL('http://www.quotationspage.com/quote/1.html')@,'
    ',True)@,' ',True)@ Each of the functions follow the format @FunctionName( )@. The
    ParamString itself can be composed of a string, a number or a boolean value. For example:-
    @AfterText('String', "st", True)@ - This function returns the portion of text following the
    specified substring. It is composed of three parameters. First one is the string being worked on,
    second is the substring being sou....
  5. Creating Dll With Delphi
    show how to pass functions and procedures in DELPHI (0)
    First of all, I'd like to apologise because my English is not tha good. Well, It's a very
    popular doubt. like How can I use a DLL? How can I create one? What is it for? So, DLL or Dynamic
    Link Libraries, allows a set of functions developed in one especific programmer language to be used
    for softwares developed in other language. For example, you can create a DLL in DELPHI and use it
    with a software developed in C++ for example. So, let's get started: Select the Item NEW in the
    menu FILE to show the dialog box NEW ITEMS. Now select DLL and OK to generate ....
  6. C# Tutorial : Lesson 8 - Functions/methods
    (0)
    The programming model has gone through many refinements, each change improving upon the model. One
    of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these
    are fragments of code within a program. They offer the following advantages:- Reduction of code
    duplication by offering re-usability Simplifying program logic by decomposing the program into
    smaller blocks Improving readability of the program Why do we need functions?
    Consider the following program:- CODE using System; namespace ConsoleApplication1 { ....
  7. Javascript Show / Hide Functions
    need some fine-tuning (3)
    Searching before posting my topic, i found this very helpful post. Javascript show + hide
    However, I'm still muddling around trying to fine tune it, and since i'm no good at coding,
    I'd appreciate any help. Using that example, how do I get the div text to be hidden on loading,
    rather than showing it all at page load. Also, is there a way to have the text change when clicked?
    so that for example, it would say "expand" when it's the small amount of text, and "collapse"
    when it's the full text? ....
  8. Writing Functions In PHP
    Turn Your PHP Script Into A Reusable PHP Function (6)
    Well, it has been a while since I offered a tutorial here at AstaHost. Most of my creativity has
    gone toward my new website, Handy PHP . The website is just getting started and it is hard to post
    potential content for my website here instead of there. The purpose of this tutorial is to show you
    how to convert a standard PHP script into a reusable PHP function. It is funny, because this
    tutorial is very similar in nature to the very first tutorial I wrote here. Rapid HTML code
    generation using simple PHP would be a good topic to read with this tutorial. Before we....
  9. C++: Basic Classes
    classes, objects, access labels, members, inline functions (5)
    This tutorial assumes that you have a basic knowledge of C++. You know how to use built-in types,
    like ints, doubles, chars, etc. You should know some types that are part of the STL, like vector,
    etc. Those types that come in the STL are just C++; you can create your own types just like
    those! Non built-in types are referred to as classes . To create a class, you just use the
    keyword class , the name of the class, and curly brackets. CODE //A class named MyClass class
    MyClass { }; In fact, that is all we need to create variables, pointers, or references ....
  10. How To Get The Random.h Header
    (4)
    Hi, I'm currently looking for a header file I really need. It's a random.h header file. Is
    there a way that someone can send it to me? I know there is a rand() function in stdlib.h but I
    prefer to use the random.h one because it's being used for my school.....
  11. Random Name Generator
    For a fantasy RPG forum (2)
    Well, I did this particular piece of coding a few days back, and I forgot to display it to you all
    here at AstaHost. I have just started a fantasy RPG forum. The naming rules are pretty strict
    because it has to be based on a construted langage called Pasen. No matter how much I explained, I
    thought, it would be hard for a newbie to understand the syllable formation constraints. Hence, I
    wrote a script and put it at my Drupal powered site, that generates random names for the four races
    for both genders. http://www.WiseTome.com/name-generator-for-chaos-and-order I ....
  12. Google Image Labeler
    A new feature of Google Image Search that allows you to label random i (11)
    A new feature of Google Image Search that allows you to label random images to help improve the
    quality of Google's image search results. How does it work? You'll be randomly
    paired with a partner who's online and using the feature. Over a 90-second period, you and your
    partner will be shown the same set of images and asked to provide as many labels as possible to
    describe each image you see. When your label matches your partner's label, you'll earn some
    points and move on to the next image until time runs out. After time expires, you can exp....
  13. Script For Viewing A Random Image Needed
    (3)
    While browsing the web, I bumped into a script that I could really use, since it's different
    from everything that I saw. Most scripts that view a random image contain a code that chooses an
    image, and then puts the part into the page itself. However, on the www.greenplastic.com web
    site (dedicated to Radiohead), in the top left corner there is a random image module. If you look at
    the code, here's what is used: CODE <img
    src="http://www.greenplastic.com/images/v75/random/random.php" width="125"
    height="125" /> Now,....
  14. Lesson #3 - Basic Math Operators And Random #s
    Lesson #3 - Basic Math Operators and Random #s (0)
    In this lesson I will cover how to use basic math operations, well addition really but you can also
    use subtraction , division and multiplication . I would also like to note that when doing
    division, if variabes of int type are used you will not get any remainders (i.e. n.345984). To be
    able to work with real numbers, numbers with decimals, you can use float. Below is a way to declare
    a float and assign it a value: float floatNumber; float Number = 28.47f; Aside from
    generating random numbers and basic math operations, we will also incorporate an if statement a....
  15. Calling Of Functions Between Mulitple External Javascript Files
    How do I use an external script to call a function from another script (2)
    I have a page that requires many Javascript functions. In order to make the coding easier to read
    and edit, I decided to seperate them into 3 Javascript files. Two files will each do a specific job.
    One file will have the shared functions that both other 2 files will need to use. They are all
    linked to a page using three <script> tags. The difficult part is that after the page calls a
    function in one of the special code files, that Javascript file will need to call the functions
    located in the common Javascript file. The file will call several functions, and it will....
  16. Rather Random Question
    (2)
    yes i know this is a very random question, but it has been bugging me for about 2 hours now!
    does anyone remember having a quiz sent to them via email, but the sender got the results? i need to
    find that, dont ask me why, but its got to the stage were im rly getting anoyed? ive been searching
    on google for about an hour! /dry.gif" style="vertical-align:middle" emoid=" ....
  17. Blingo Search Engine
    A SE that gives away random prizes (3)
    A friend told me about a search engine that brings back Google results, however the owners of the
    Engine have the site set up to give random prizes away depending on what "turn" you are to search.
    They pick a bunch of random winning times, and if you search at the right time, you win a gift
    certificate, or other prize. The theory is, that if you DO happen to hit your search on one of
    these "winning times", instead of being redirected to your search results, you are notified that you
    have won, and they send you your gift somehow... I have never won on this thing and I ....
  18. Google Adsense's Functions
    How does Pay per Click works? (1)
    I wanna know how the Pay-per-Click works. This is because I have put the ads up on my website. There
    are queries from the Google Search but no cash. My Google ads also have not generated money. It
    states another confusing thing: Cost-per-1000 impressions. What is that????....
  19. A Few Random Thoughts..
    Just something I wrote out in class (0)
    I just needed a decent place to post this... And I didn't think it'd fit into any of the
    other forums here... Unfortunately, cause it probably woulda done nicely for my hosting credits
    Anyway QUOTE Freedom. People seem to think that this is something to go after. They seem to
    think that this thing called 'freedom' is better than other ways of life. Ways of life that
    don't have you quite as liberated to act or think as we please. At least, that's what they
    seem to believe. They spoke about about being bound, about being scared, frightenned. ....
  20. PHP And Texts: Need Help With PHP String Functions
    (5)
    Hey people! I'm pretty new with PHP and MySQL. I wanna have all the text on my site in
    MySQL. But i'm having trouble with the inputing from HTML-forms, like . How to i do it? Can i
    use PHP or is it better to use javascript and sorta add htmltags into the tag? I wanna make a
    texteditor where i can use bold, italic and that kinda stuff. I'm thankful for any help...
    /Jens....
  21. Multibyte-string Functions
    since server shift (1)
    Hello, I use multibyte functions to split a string by letter and I was wondering if you could turn
    them on again, because they were on before the server shift (and they are in PHP by default) and now
    I get fatal errors, when trying to use them. In the Phpinfo they don't appear at all.. I've
    been waiting for quite some time now and it is only a basic PHP-integrated feature.. Thanks, Ruben....
  22. Random MySQL Entry
    (1)
    I am tring to figure this out and I can't. When you set a primary key. Say something_id and it
    is defined as a int (12) auto_inc. I go and fill it up with 10 entries, meaning it is now set to be
    something_id entry 10, but say I go and delete entry 5. Why doesn't it take that 5 for the next
    number, but instead it does a 11 and leaves 5 blank. How might I get it to where it fill's up
    the 5 instead of going to the next number or is that just one of the bad thing's of having a sql
    entry auto_inc ? Also, the random part. The reason I ask this is I take the....
  23. Random Chuck Norris Facts
    Funny. Check it out (2)
    QUOTE In his spare time, Chuck Norris breeds thoroughbred horses by manually inseminating the
    females with his own semen. Ask not what Chuck Norris will do for a Klondike bar, ask what the
    Klondike bar will do for Chuck Norris. Chuck Norris ruins the endings of Harry Potter books for
    children who just bought one for the hell of it. When they start crying Chuck Norris calmly says,
    "I'll give you something to cry about," and roundhouse kicks them in the face. Chuck Norris has
    every copy of National Geographic in his basement. He also has the ability to lift ever....
  24. Php: Write Random Text As Image
    Having problems, help needed! (3)
    I'm trying to create a script that writes text to an image. CODE
    header("Content-type: image/png"); $_phrases = array( "Test
    1", "Test 2", "Test 3", "Test 4", "etc." );
    $_rand_phrase = $_phrases[rand(0,count($_phrases)-1)];
    $_image = imagecreatefrompng("gmail.png"); $_user_width =
    imaagettfbbox(9,0,"tahoma.ttf",$_rand_phrase); $_x_value =
    (200-($user_width[2] + 113));....
  25. Php : Variables Included Dont Work In Functions
    Variables from Included files dont work (4)
    Today, I came up with this strange PHP behaviour. Just wanted to know if anyone has any
    suggestions! I make a common variable/function file called config.php. I put in my generally
    used functions in it. Suppose this is my file // -----VARIABLES --- // $a=10,$b....
    // -----FUCTIONS--- // function doit() { print "A value is " . $a; } ?> Here, suppose we
    execute this file directly. Since A has a global scope, it does work perfectly. But if this same
    file is imported in another file say, mainfile.php // -----VARIABLES --- // $c,$....
  26. Pre-installed Cgi
    Random HTML not working (0)
    I'm trying to use the pre-installed HTML Code Rotator in cPanel (Preinstalled Scripts / CGI
    Center / Random HTML), I've put some code into it and added the given line into the .SHTML file
    I'm using. But, when I go to the file, it doesn't work. Where the code should be, its
    completely blank. /sad.gif' border='0' style='vertical-align:middle' alt='sad.gif' /> Has
    anyone else had a problem like this? Any ideas? Thanks in advance, saxsux....
  27. Random Images On Eacht Pageload And Refresh.
    best in plain htlm or javascript (6)
    Im looking for somethin that puts a diffrent image for each pageload/refresh. And it should be
    something that dosent need any super server technolgys like php and mysql and all that stuff.
    something that is enough just on the page and finished.....
  28. Visual Basic: Random Strings!
    (10)
    This article will teach you how to get random strings for output to a label caption, or anywhere you
    want it to go. 1. First we need to declare our string names: CODE Private
    RndString(2) This declaration says there will be an array of strings called RndString,
    and there will be 2 strings in that array. 2. Then, we need to create a function that will
    generate a random number. CODE Private Function RandomNumber(rUpper As Integer, Optional
    rLower As Integer) As Integer ' Generate random number between upper and lower bound values
      ....
  29. Coppermine Random Image Script
    (6)
    hi i need a script to display random image of coppermine on my index....
  30. Photoshop Tutorial: Abstract Background I
    How to make a random backgrounds (1)
    Firstly, there are varying tutorials like this but this is one way in which you can achieve the
    simple effect. Program: Photoshop Elements or Higher Note: Reset your template colours to B/W
    (press D). Also, instead of screening blend, try Overlay. 1) Create a 500 X 500 pixel picture with
    Transparency 2) Go to Filters -> Render -> Cloud. (Repeat until a desirable cloud is shown) 3) Go to
    Filters -> Render -> Difference Cloud. 4) Invert the picture (Ctrl + I) 5) Make the levels equal.
    (Shift+Ctrl+L) Now comes the fun parts /laugh.gif' border='0' style='vertical-alig....

    1. Looking for random, functions,

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for random, functions,
Similar
String Library Functions - A few questions
Php: Lesson #3;functions - PHP.
Php Random Selector - whats the code
Using Regular Expressions To Parse Functions
Creating Dll With Delphi - show how to pass functions and procedures in DELPHI
C# Tutorial : Lesson 8 - Functions/methods
Javascript Show / Hide Functions - need some fine-tuning
Writing Functions In PHP - Turn Your PHP Script Into A Reusable PHP Function
C++: Basic Classes - classes, objects, access labels, members, inline functions
How To Get The Random.h Header
Random Name Generator - For a fantasy RPG forum
Google Image Labeler - A new feature of Google Image Search that allows you to label random i
Script For Viewing A Random Image Needed
Lesson #3 - Basic Math Operators And Random #s - Lesson #3 - Basic Math Operators and Random #s
Calling Of Functions Between Mulitple External Javascript Files - How do I use an external script to call a function from another script
Rather Random Question
Blingo Search Engine - A SE that gives away random prizes
Google Adsense's Functions - How does Pay per Click works?
A Few Random Thoughts.. - Just something I wrote out in class
PHP And Texts: Need Help With PHP String Functions
Multibyte-string Functions - since server shift
Random MySQL Entry
Random Chuck Norris Facts - Funny. Check it out
Php: Write Random Text As Image - Having problems, help needed!
Php : Variables Included Dont Work In Functions - Variables from Included files dont work
Pre-installed Cgi - Random HTML not working
Random Images On Eacht Pageload And Refresh. - best in plain htlm or javascript
Visual Basic: Random Strings!
Coppermine Random Image Script
Photoshop Tutorial: Abstract Background I - How to make a random backgrounds
advertisement




Random With Functions?



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE