Using PHP to implement some common functions in the game _php tutorial

Source: Internet
Author: User
Tags shuffle random name generator

Simple Roll-Dice

Many games and game systems require dice. Let's start with a simple section: Throw a six-sided dice. In fact, scrolling a six-sided dice selects a random number from 1 to 6. In PHP, this is very simple: echo rand (1,6);.

In many cases, this is basically simple. But in dealing with odds games, we need some better implementations. PHP provides a better random number generator: Mt_rand (). Without delving into the differences, you can think of Mt_rand as a faster, better random number generator: Echo Mt_rand (1,6);. If you put the random number generator in a function, the effect will be better.

1. Use the Mt_rand () Random number generator function:

function Roll () {return Mt_rand (1,6);} echo Roll ();

You can then pass the dice type that needs to be scrolled as a parameter to the function.

2. Pass the dice type as a parameter:

function Roll ($sides) {return Mt_rand (1, $sides);} echo Roll (6);  Roll a six-sided Dieecho roll (ten);  Roll a ten-sided Dieecho roll ();  Roll a twenty-sided die

From here on, we can continue to roll multiple dice at once, return an array of results, or roll several different types of dice at once. But most tasks can use this simple script.

Random Name Generator

If you're running a game, writing a story, or creating a large number of characters at once, you'll sometimes struggle to cope with new names that are constantly appearing. Let's take a look at a simple random name generator that can be used to solve this problem. First, let's create two simple arrays-one for the first name and one for the last.

3. Two simple arrays of first and last names:

$male = Array ("William", "Henry", "Filbert", "John", "Pat"), $last = Array ("Smith", "Jones", "Winkler", "Cooper", "Cline", );

You can then select a random element from each array: Echo $male [Array_rand ($male)]. ' ' . $last [Array_rand ($last)];. To extract multiple names at once, simply mix the arrays and extract them as needed.

4. Mixed name Array

Shuffle ($male); shuffle ($last); for ($i = 0; $i <= 3; $i + +) {echo $male [$i]. ' ' . $last [$i];}

Based on this basic concept, we can create a text file that holds the first and last names. If you place a name in each line of a text file, you can easily separate the contents of the file with a newline character to build the source code array.

5. Create a text file of the name

$male = Explode (' n ', file_get_contents (' names.female.txt ')); $last = explode (' n ', file_get_contents (' Names.last.txt ') );

Build or find some good name files (some files are included with the Code archive), and then we never have to worry about names anymore.

Scene Builder

Using the same rationale used to build the name generator, we can build the scene generator. This generator is useful not only in role-playing games, but also in situations where pseudo-random environments can be used, such as role-playing, improvisation, writing, and so on. One of my favorite games, paranoia includes the task mixer (mission Blender) in its GM Pack. Task mixer can be used to integrate complete tasks when rolling the dice quickly. Let's integrate our own scene generators.

Consider the following scenario: you wake up and find yourself lost in the jungle. You know you have to rush to New York, but you don't know why. You can hear the barking of nearby dogs and the sound of a clear enemy seeker. You are cold, shivering, and unarmed. Each sentence in the scenario describes a specific aspect of the scene:

    • "You wake up and find yourself lost in the jungle"-this sentence will be set up.
    • "You know you have to go to New York"-This sentence will describe the goal.
    • "You can hear the dog barking"-this sentence will introduce the enemy.
    • "You are cold, shivering, and unarmed"-this sentence adds complexity.

Just like creating a text file of first and last names, create a text file of settings, targets, enemies, and complexity, respectively. Sample files are included with the Code archive. After you have these files, the code that generates the scene is basically the same as the code that generated the name.

6. Generating the scene

$settings = Explode ("n", file_get_contents (' Scenario.settings.txt ')), $objectives = Explode ("n", file_get_contents (' Scenario.objectives.txt '); $antagonists = Explode ("n", file_get_contents (' scenario.antagonists.txt ')); $complicati = Explode ("n", file_get_contents (' scenario.complicati****.txt ')); shuffle ($settings); shuffle ($objectives); Shuffle ($antagonists); shuffle ($complicati); echo $settings [0]. ' ' . $objectives [0]. ' ' . $antagonists [0]. ' '. $complicati ****[0]. "
n ";

We can add elements to the scene by adding new text files, or we might want to add multiple complexities. The more content you add to a basic text file, the more the scene changes over time.

Card Creator (Deck builder) and equipment (Shuffler)

If you want to play Solitaire and want to deal with solitaire-related scripts, we need to integrate a deck builder with the tools in the rig. First, let's build a standard deck of cards. You need to build two arrays-one for holding the same suit, and the other for holding the card. If you later need to add a new deck or card type, this will be a good flexibility.

7. Building a standard poker deck

$suits = Array ("Spades", "Hearts", "Clubs", "Diamonds"), $faces = Array ("n", "three", "four", "Five", "Six", "Seven", " Eight "," Nine "," Ten "," Jack "," Queen "," King "," Ace ");

Then build a deck array to hold all the card values. You can do this with just a couple of foreach loops.

8. Build a deck array

$deck = Array (), foreach ($suits as $suit) {foreach ($faces as $face) {$deck [] = Array ("face" = + $face, "suit" = + $suit) ;}}

After building a deck of poker arrays, we can easily shuffle and randomly draw a card.

9. Shuffle and randomly draw a card

Shuffle ($deck); $card = Array_shift ($deck); Echo $card [' face ']. ' of '. $card [' suit '];

Now, we get a shortcut to draw multiple decks or build multi-layered card boxes (Multideck shoe).

Winning Calculator: Licensing

Since the cards are built to track the face and suit of each card separately, it is possible to use this card programmatically to calculate the probability of getting a particular card. First, five cards are drawn separately for each hand.

10. Draw five cards per hand

$hands = Array (1 = = Array (), 2=>array ()), for ($i = 0; $i < 5; $i + +) {$hands [1][] = implode ("of", Array_shift ($d Eck)); $hands [2][] = implode ("of", Array_shift ($deck));}

You can then look at the deck to see how many cards are left and what the odds are of drawing a particular card. It is easy to see the number of cards remaining. You only need to calculate the number of elements contained in the $deck array.

To get the chance to draw a specific card, we need a function to traverse the entire deck and estimate the remaining cards to see if they match.

11. Calculate the chance to draw a specific card

function Calculate_odds ($draw, $deck) {$remaining = count ($deck), $odds = 0;foreach ($deck as $card) {if (  $draw [' Face '] = = $card [' face '] && $draw [' suit '] = = $card [' suit ']) | | ($draw [' face '] = = ' && $draw [' suit '] = = $card [' suit ']) | | ($draw [' face '] = = $card [' face '] && $draw [' suit '] = = ')) {$odds + +;}} Return $odds. ' In ' $remaining;}

You can now select the cards you are trying to pull out. For the sake of simplicity, pass in an array that looks like a card. We can look for a specific card.

12. Find a specific card

$draw = Array (' face ' = ' Ace ', ' suit ' = ' spades '); Echo implode ("of", $draw). ': '. Calculate_odds ($draw, $deck);

Or you can find a card that specifies a face or suit.

13. Find a card for the specified face or suit

$draw = Array (' face ' + = ', ' suit ' = ' spades '); $draw = Array (' face ' = ' Ace ', ' suit ' + ') ';

A simple poker licensing device

Now that you've got a deck builder and some tools that can help calculate the odds of extracting a particular card, we can integrate a really simple token to do it. For the purposes of this example, we will build a card that can extract five cards. The card will provide five cards from the entire deck. Use numbers to specify which cards need to be discarded, and the card will replace them with other cards in a deck. We don't need to specify licensing restrictions or special rules, but you may find that these are very rewarding personal experiences.

As shown in the previous section, generate and shuffle, then five cards per hand. Displays the cards by array index so that you can specify which cards to return. You can do this by using the check boxes that represent which cards you want to replace.

14. Use a check box to indicate the card you want to replace

foreach ($hand as $index = + $card) {echo "" . $card [' face ']. ' of '. $card [' suit ']. "
";}

Then, calculate the input array $_post[' card ' to see which cards have been selected for replacement.

15. Calculation input

$i = 0;while ($i < 5) {if (Isset ($_post[' card '] [$i]) {$hand [$i] = Array_shift ($deck);}}

With this script, you can try to find the best way to handle a particular set of cards.

Hangman Games

Hangman is essentially a word-guessing game. Given the length of the word, we use a limited number of times to guess the word. If one of the letters that appears in the word is guessed, all occurrences of that letter are populated. After several guesses (usually six times), you lose the game. To build a primitive hangman game, we need to start with the word list. Now, let's make the list of words into a simple array.

16. Create a word list

$words = Array ("Giants", "Triangle", "particle", "birdhouse", "minimum", "flood");

Using the techniques described earlier, we can move these words into an external word list text file and import them as needed.

After you get the list of words, you need to randomly select a word, show each letter empty, and start guessing. We need to track right and wrong guesses every time we make guesses. Tracing can be achieved by simply serializing the guess arrays and passing them each time you guess. If you need to prevent people from guessing the right things by looking at the page source code, you need to do something more secure.

Build the array to hold the letters and correct/false guesses. For the correct guess, we will use the letter as the key and fill the array with a period as the value.

17. Build an array that holds letters and guess results

$letters = Array (' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' x ' , ' y ', ' z '); $right = Array_fill_keys ($letters, '. '); $wrong = Array ();

Now you need some code to evaluate the guesses and display the word in the process of completing the guessing game.

18. Evaluate guesses and show progress

if (Stristr ($word, $guess)) {$show = '; $right [$guess] = $guess; $wordletters = Str_split ($word); foreach ($wordletters as $ Letter) {$show. = $right [$letter];}} else {$show = '; $wrong [$guess] = $guess; if (count ($wrong) = = 6) {$show = $word;} else {foreach ($wordletters as $letter) {$show. = $right [$letter];}}

In the source code archive, you can see how to serialize an array of guesses and pass the array from one guess to another guess.

Crossword Helper

I know it's inappropriate, but sometimes when you're playing crossword puzzles, you have to struggle to find words that start with C and end with a T and contain five letters. Using the same word list built for hangman games, we can easily search for words that match a pattern. First, find a way to transfer words. For simplicity, replace the missing letter with a period: $guess = "c...t";. Because regular expressions will process a period as a single character, we can easily traverse the list of words to find a match.

19. Traversing the word list

foreach ($words as $word) {if (Preg_match ("/^". $_post[' guess '). "$/", $word)) {echo $word. "
n ";}}

Depending on the quality of the word list and the accuracy of the guesses, we should be able to get a reasonable list of words for possible matches. You have to decide for yourself whether "chest" or "cheat" is the answer to the five-letter word that says "do not play by the rules."

Mad Libs

Mad Libs is a word game in which players get a short story and replace major types of words with different words of the same type, creating a more boring new version of the same story. Read the following text: "I was walking in the park when I found a lake." I jumped in and swallowed too much water. I had to go to the hospital. "Begin replacing the word type with another word tag. The start and end tags are underlined to prevent unexpected string matches.

20. Replace word types with Word markers

$text = "I was _verb_ing in the _place_ when I found a _noun_. I _verb_ed in, and _verb_ed too much _noun_.  I had to go to the _place_. ";

Next, create several basic word lists. For this example, we are not going to be too complicated.

21. Create several basic word lists

$verbs = Array (' pump ', ' jump ', ' walk ', ' swallow ', ' crawl ', ' wail ', ' roll '), $places = Array (' Park ', ' Hospital ', ' Arctic ', ' Ocean ', ' grocery ', ' basement ', ' attic ', ' sewer '); $nouns = Array (' Water ', ' lake ', ' spit ', ' foot ', ' worm ', ' dirt ', ' river ', ' Wankel rotary engine ');

You can now evaluate the text repeatedly to replace the tag as needed.

22. Evaluation text

while (Preg_match ("/(_verb_) | ( _place_) | (_noun_)/", $text, $matches)) {switch ($matches [0]) {case ' _verb_ ': Shuffle ($verbs); $text = preg_replace ($matches [0], Current ($verbs), $text, 1); Break;case ' _place_ ': Shuffle ($places); $text = preg_replace ($matches [0], current ($places), $text, 1); Break;case ' _noun_ ': Shuffle ($nouns); $text = preg_replace ($matches [0], current ($nouns), $text, 1); Echo $text;

Obviously, this is a simple and rough example. The more accurate the word list, and the more time it takes to spend on the base text, the better the result. We have used a text file to create a list of names and a list of basic words. Using the same principle, we can create a list of words by type and use these word lists to create more varied Midry games.

Lotto Machine

The six correct numbers of all selected Lotto--step back--are statistically impossible. However, many people still spend money to play, and if you like numbers, it might be interesting to see the trend chart. Let's build a script that will allow you to track the winning number and provide the 6 numbers with the fewest number of choices in the list. (Disclaimer: This will not help you win the lottery, so please do not spend money to buy tickets.) It's just for fun).

Save the winning lotto selection to a text file. Separate the numbers with commas and put each group of numbers on a separate line. After separating the contents of the file with a newline character and separating the lines with commas, you can get something like listing 23.

23. Save the selected win Lotto to a text file

$picks = Array (' 6 ', ' + ', ' + ', ' + ', ' + ', ' + '), Array (' 2 ', ' 8 ', ' + ', ' + ', ' + ', ' a ') ', Array (' 3 ', ' 9 ', ' 14 ', ' 25 ') , ' + ', ' + '), array (' One ', ' n ', ' + ', ' + ', ' + ', ' PNs '), Array (' 4 ', ' 7 ', ' 17 ', ' 26 ', ' 32 ', ' 33 '));

Obviously, this is not enough to be the basic file for drawing statistics. But it's a start, and it's enough to demonstrate the fundamentals.

Set up a basic array to save the selection range. For example, if you select a number from 1 to 40 (for example, $numbers = Array_fill (1,40,0);), then traverse our selection to increment the corresponding matching value.

24. Traverse Selection

foreach ($picks as $pick) {foreach ($pick as $number) {$numbers [$number]++;}}

Finally, the numbers are sorted by value. This operation should place the least selected number in the front of the array.

25. Sort numbers by value

Asort ($numbers); $pick = Array_slice ($numbers, 0,6,true); Echo implode (', ', Array_keys ($pick));

By regularly adding the actual lotto winning numbers to a text file containing a list of winning numbers, you can find the long-term trend of the selection. It is interesting to see how often some numbers appear.

http://www.bkjia.com/PHPjc/752403.html www.bkjia.com true http://www.bkjia.com/PHPjc/752403.html techarticle simple craps many games and game systems require dice. Let's start with a simple section: Throw a six-sided dice. In fact, rolling a six-sided dice is from 1 to 6 ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.