Listing 1. Simple Roll Roll Device
Many games and game systems need dice. Let's start with the simple part: roll a six-sided dice. In fact, scrolling a six-sided dice is 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 further study of the difference, Mt_rand is considered to be a faster and 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 Code code as follows:
function Roll () {
Return Mt_rand (1,6);
}
echo Roll ();
You can then pass the dice type that needs to be rolled as a parameter to the function.
Listing 2. Passing the dice type as a parameter
Copy Code code 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, we can continue to scroll multiple dice at once as needed, return an array of results, or scroll through multiple different types of dice at once. But most tasks can use this simple script.
Random Name Builder
If you are running a game, writing a story, or creating a large number of characters at once, you will sometimes be tired of dealing with new names that are constantly appearing. Let's take a look at a simple random name builder 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 name.
Listing 3. Two simple arrays of first and last names
Copy Code code 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 Code code 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 a source code array.
Listing 5. Create a text file with a name
Copy Code code 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 in the Code archive), and then we never need to worry about names.
Scene Builder
Using the same rationale used to build the name builder, we can build the scene builder. This builder is useful not only in role-playing games, but also in situations where you need to use a set of pseudo random environments (for role-playing, improvisation, writing, etc.). One of my favorite games, paranoia included the task Mixer (mission Blender) in its GM Pack. The task mixer can be used to consolidate complete tasks when rolling dice quickly. Let's integrate our own scene builder.
Consider the following scenario: you wake up and find yourself lost in the jungle. You know you have to go 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 scenario:
"You wake up and find yourself lost in the jungle."-this sentence will 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, trembling, and unarmed"-this sentence adds complexity.
Just like creating a text file with a first and last name, create a text file of settings, targets, enemies, and complexity, respectively. A sample file is included in the Code archive. After owning these files, the code that generates the scenario is essentially the same as the code that generated the name.
Listing 6. Generating Scenarios
Copy Code code 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]. "<br/>\n";
We can add elements to the scene by adding a new text file, or we might want to add multiple complexities. The more content you add to the base text file, the more the scene changes over time.
Licensing Group Builder (Deck builder) and equipment (Shuffler)
If you want to play Solitaire and have a card-related script to deal with, we need to integrate a deck builder with the tools in the kit. First, let's build a standard deck of cards. You need to build two arrays-one to hold the same suit, and the other to hold the card. If you later need to add a new group card or type of card, this will be a good flexibility.
Listing 7. Building a standard deck of poker
Copy Code code as follows:
$suits = Array (
"Spades", "Hearts", "clubs", "Diamonds"
);
$faces = Array (
"Two", "Three", "Four", "Five", "Six", "Seven", "eight",
"Nine", "Ten", "Jack", "Queen", "King", "Ace"
);
Then build a deck of cards to hold all the card values. You can do this by using only a pair of foreach loops.
Listing 8. Building a deck of cards
Copy Code code as follows:
$deck = Array ();
foreach ($suits as $suit) {
foreach ($faces as $face) {
$deck [] = Array ("Face" => $face, "Suit" => $suit);
}
}
After building up an array of playing cards, we can easily shuffle and draw a random card.
listing 9. Shuffle and draw a card randomly
Copy Code code as follows:
Shuffle ($deck);
$card = Array_shift ($deck);
echo $card [' face ']. ' of '. $card [' suit '];
Now, we've got a shortcut to pull more than a deck of cards or to build a multi-layer box (Multideck shoe).
Winning Calculator: Licensing
As the cards are built to track the cards and colors of each card, you can use this card programmatically to calculate the probability of getting a particular card. First, draw five cards per hand, respectively.
listing 10. Pull out five cards per hand
Copy Code code 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 and see how many cards are left and what the odds are for a particular card to be drawn. It is easy to see the remaining number of cards. Only the number of elements contained in the $deck array needs to be computed. To get a 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. Calculate the probability of a particular card being drawn
Copy Code code 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;
}
Now you can pick out the cards you're trying to draw. For simplicity, pass in an array that looks like a card. We can look for a specific card.
listing 12. Find a specified card
Copy Code code 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 with a specified face or suit
Copy Code code as follows:
$draw = Array (' Face ' => ', ' suit ' => ' spades ');
$draw = Array (' Face ' => ' Ace ', ' suit ' => ');
Simple Poker Licensing device
Now that we've got the deck builder and some tools that can help you figure out the odds of pulling out a specific card, we can integrate a really simple licensing device to do the licensing. For the purposes of this example, we will build a licensing device that can pull out five cards. The licensing device will provide five cards from the entire deck. Use numbers to specify which cards you want to discard, and the licensing device replaces them with other cards in a deck. We do not need to specify licensing restrictions or special rules, but you may find these to be very useful personal experiences.
As shown in the previous section, generate and shuffle, then five cards per hand. Displays these 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 which cards to replace
Copy Code code as follows:
foreach ($hand as $index => $card) {
echo "<input type= ' checkbox ' Name= ' card[". $index. "] ' >
" . $card [' face ']. ' of '. $card [' suit ']. "<br/>";
}
Then compute the input array $_post[' card ' to see which cards have been selected for replacement.
listing 15. Calculation input
Copy Code code 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 chances to guess the word. If you guess a letter that appears in the word, fill in all the positions that appear in the letter. After guessing several times (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 a simple array of word lists.
listing 16. Create a word list
Copy Code code as follows:
$words = Array (
"Giants",
"Triangle",
"Particle",
"Birdhouse",
"Minimum",
"Flood"
);
Using the techniques described earlier, we can move these words to the external Word list text file and import them as needed.
After you get the word list, you need to randomly select a word, display each letter as empty, and then start guessing. We need to follow the right and wrong guesses every time we make a guess. Tracing can be achieved by simply serializing the guessing array and passing them on each guess. If you need to stop people from looking at the page's source code for a lucky guess, you need to do something more secure.
Build an array to hold the letters and correct/false guesses. For the right guesses, we'll fill the array with a letter as a key and a period as the value.
listing 17. Building an array of letters and guessing results
Copy Code code 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 your guesses and display the word as you complete the crossword puzzle.
listing 18. Evaluate guesses and show progress
Copy Code code 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 the guessing array and pass the array from one guess to another.
Crossword Helper
I know it's not the right thing to do, but sometimes you have to struggle to find a word that starts with C and ends with a T and contains 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 treat a period as a single character, we can easily traverse the word list to find a match.
listing 19. Traversing the list of words
Copy Code code as follows:
foreach ($words as $word) {
if (Preg_match ("/^". $_post[' guess '). "$/", $word)) {
Echo $word. "<br/>\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 must 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 text game in which players get a short story and replace the main type 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 at the park when I found a lake." I jumped in and swallowed too much water. I had to the hospital. "Start replacing word types with other word tags." The start and end tags are underlined to prevent unexpected string matches.
listing 20. Replace the word type with a word mark
Copy Code code as follows:
$text = "I am _verb_ing in the _place_ I found a _noun_."
I _verb_ed in, and _verb_ed too much _noun_. I had to the _place_. "
Next, create a few basic word lists. For this example, we will not be too complicated.
Listing 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 text repeatedly to replace tags as needed.
listing 22. Evaluation text
Copy Code code 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 list of words, and the more time you spend on basic text, the better the result. We have used a text file to create a list of names and basic word lists. Using the same principles, we can create a list of words by type and use these word lists to create more varied Midry games. Lotto Machine
It is statistically impossible to select all six correct numbers for Lotto--to step back. However, many people still spend money to play, and if you like numbers, it can be interesting to see a trend chart. Let's build a script that will allow you to track the winning number and provide a minimum number of 6 numbers in the list.
(Disclaimer: This will not help you win the Lotto award, so please do not pay for the lottery.) It's just for fun).
Save your winning lottery lotto selections to a text file. Separate each number with commas and place each group number on a separate line. You can get something like listing 23 by separating the contents of the file with a newline character and separating the rows with commas.
Listing 23. Save the winning lottery selections to a text file
Copy Code code 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 a basic document for drawing statistical data. But it's a start, and it's enough to demonstrate the fundamentals.
Sets a base array to hold the selection. For example, if you select a number from 1 to 40 (for example, $numbers = Array_fill (1,40,0);), iterate through our selections and increment the corresponding matching value.
listing 24. Traversal Selection
Copy Code code as follows:
foreach ($picks as $pick) {
foreach ($pick as $number) {
$numbers [$number]++;
}
}
Finally, the numbers are sorted by value. This should place the fewest selected numbers in the front of the array.
listing 25. Sorting numbers by value
Copy Code code 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 number selection. It is interesting to see how often some numbers appear.