PHP Game Programming 25 script Code _php Tutorial

Source: Internet
Author: User
Tags shuffle random name generator
Listing 1: A simple dice roll
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.
Listing 1: Using the Mt_rand () Random number generator function
Copy CodeThe code is as follows:
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.
Listing 2. Passing the dice type as a parameter
Copy CodeThe code is as follows:
function Roll ($sides) {
Return Mt_rand (1, $sides);
}
echo Roll (6); Roll a six-sided die
echo Roll (10); Roll a ten-sided die
echo Roll (20); 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.
Listing 3. Two simple arrays of first and last names
Copy CodeThe code is as follows:
$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.
Listing 4. Mixed name Array
Copy CodeThe code is as follows:
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.
Listing 5. Creating a text file with a name
Copy CodeThe code is as follows:
$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.
Listing 6. Generating a scene
Copy CodeThe code is as follows:
$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.
Listing 7. Building a standard poker deck
Copy CodeThe code is as follows:
$suits = Array (
"Spades", "Hearts", "Clubs", "Diamonds"
);
$faces = Array (
"The other", "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.
Listing 8. Building a deck array
Copy CodeThe code is as follows:
$deck = Array ();
foreach ($suits as $suit) {
foreach ($faces as $face) {
$deck [] = Array ("face" = = $face, "Suit" and "= $suit");
}
}

After building a deck of poker arrays, we can easily shuffle and randomly draw a card.
listing 9. Shuffle and randomly draw a card
Copy CodeThe code is as follows:
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.
Listing 10: Five cards per hand
Copy CodeThe code is as follows:
$hands = Array (1 = = Array (), 2=>array ());
for ($i = 0; $i < 5; $i + +) {
$hands [1][] = implode ("of", Array_shift ($deck));
$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.
Listing 11: Calculating the probability of a specific card being drawn
Copy CodeThe code is as follows:
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.
listing 12. Finding a specified card
Copy CodeThe code is as follows:
$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.
Listing 13. Find a card for a specified face or suit
Copy CodeThe code is as follows:
$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

listing 14. Use a check box to indicate the card you want to replace
Copy CodeThe code is as follows:
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.
listing 15. Calculation input
Copy CodeThe code is as follows:
$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.
listing 16. Creating a word list
Copy CodeThe code is as follows:
$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. listing 17. Building an array to hold letters and guess results
Copy CodeThe code is as follows:
$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.
Listing 18: Evaluating guesses and showing progress
Copy CodeThe code is as follows:
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.
Listing 19: Traversing the word list
Copy CodeThe code is as follows:
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.
Listing 20: Replacing a word type with a word tag
Copy CodeThe code is as follows:
$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.
listing 21. Creating 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.
listing 22. Evaluation text
Copy CodeThe code is as follows:
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);
Break
}
}
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.
Listing 23. Save the selected win Lotto to a text file
Copy CodeThe code is as follows:
$picks = Array (
Array (' 6 ', ' 10 ', ' 18 ', ' 21 ', ' 34 ', ' 40 '),
Array (' 2 ', ' 8 ', ' 13 ', ' 22 ', ' 30 ', ' 39 '),
Array (' 3 ', ' 9 ', ' 14 ', ' 25 ', ' 31 ', ' 35 '),
Array (' 11 ', ' 12 ', ' 16 ', ' 24 ', ' 36 ', ' 37 '),
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.
listing 24. Traverse Selection
Copy CodeThe code is as follows:
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.
listing 25: Sorting numbers by value
Copy CodeThe code is as follows:
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/322955.html www.bkjia.com true http://www.bkjia.com/PHPjc/322955.html techarticle Listing 1. 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 ...

  • Related Article

    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.