Listing 1. Simple throttling
Many games and game systems require dice. Let's start with the simple part: throw a six-sided dice. In fact, rolling a six-sided dice means selecting a random number from 1 to 6. In PHP, this is very simple: echo rand );.
In many cases, this is basically simple. However, when dealing with probability games, we need some better implementations. PHP provides a better random number generator: mt_rand (). Without in-depth research on the differences between the two, mt_rand can be considered as a faster and better random number generator: echo mt_rand );. If the random number generator is put into the 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 ();
Then, you can pass the dice type to be rolled to the function as a parameter.
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
Starting from here, we can continue to scroll multiple dice at a time as needed and return an array of results. We can also scroll multiple different types of dice at a time. However, most tasks can use this simple script.
Random name Generator
If you are running a game, writing a story, or creating a large number of characters at a time, you may sometimes get tired of new names. 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 the other for the last name.
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 ",
);
Then you can select a random element from each array: echo $ male [array_rand ($ male)]. ''. $ last [array_rand ($ last)];. To extract multiple names at a time, you only need to mix the array and extract the names 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 saves the first and last names. If you store a name in each line of a text file, you can easily use line breaks to separate the file content to build an array of source code.
Listing 5. Create a text file with the name Copy codeCode: $ male = explode ('\ n', file_get_contents('names.female.txt '));
$ Last = explode ('\ n', file_get_contents('names.last.txt '));
After building or searching for some good name files (some files are included in the Code archive), we will never need to worry about names.
Scenario Generator
With the same basic principles used to build a name generator, we can build a scenario generator. This generator is useful not only in role-playing games, but also in scenarios where a pseudo-random environment set (can be used for role-playing, impromptu creation, and writing) is required. One of my favorite games, Paranoia included "mission blender" in its GM Pack )". The task mixer can be used to integrate a complete task when rolling the dice quickly. Let's integrate our scenario generator.
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 sounds of dogs nearby and clear enemy searches. You are cold, trembling, and have no weapons. Each sentence in this scenario describes specific aspects of the scenario:
"You wake up and find yourself lost in the jungle"-setting will be set up.
"You know you have to go to New York"-this sentence will describe the target.
"You can hear the call of a dog"-This sentence introduces the enemy.
"You are cold, trembling, and have no weapons"-This sentence adds complexity.
Just like creating a text file with the first name and last name, create a text file with the settings, target, enemy, and complexity respectively. The sample file is included in the Code archive. After you have these files, the generated scenario code is basically the same as the generated name code.
Listing 6. Generation scenarios
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]. "<br/> \ n ";
You can add elements to a scenario by adding a new text file, or you may want to add multiple complexity levels. The more content you add to a basic text file, the more scenarios change over time.
Card group creator (Deck builder) and equipment (shuffler)
If you want to play cards and process card-related scripts, we need to integrate a deck builder with tools in the equipment. First, let's build a pair of standard cards. You need to construct two Arrays-one to save the cards of the same color, and the other to save the cards. If you need to add a new group card or card type later, doing so will provide great flexibility.
Listing 7. Building a pair of standard playing cards Copy codeThe Code is as follows: $ suits = array (
"Spades", "Hearts", "Clubs", "Diamonds"
);
$ Faces = array (
"Two", "Three", "Four", "Five", "Six", "Seven", "Eight ",
"Nine", "Ten", "Jack", "Queen", "King", "Ace"
);
Create a deck array to save all card values. You only need to use a pair of foreach loops to complete this operation.
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" => $ suit );
}
}
After building an array of playing cards, we can easily shuffles and randomly draw a card.
Listing 9. Shuffling and randomly picking a card Copy codeThe Code is as follows: shuffle ($ deck );
$ Card = array_shift ($ deck );
Echo $ card ['face']. 'of'. $ card ['suit'];
Now, we have achieved a shortcut to extract multiple deck cards or build a multi-layer card box (multideck shoe.
Winning rate calculator: Licensing
Since the cards and colors of each card are tracked separately when building cards, you can use this card in programming to calculate the probability of a specific card. First, five cards are drawn for each hand.
Listing 10. Five cards for each 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 ));
}
Then you can check the deck to see how many cards are left and the probability of getting a specific card. It is easy to view the remaining number of cards. 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. calculate the probability of winning a specific card 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;
}
Now you can select the cards to be pulled. For simplicity, input an array that looks like a card. We can find a specific card.
Listing 12. Search for a specified card Copy codeThe Code is as follows: $ draw = array ('face' => 'ace', 'suit' => 'spades ');
Echo implode ("of", $ draw). ':'. calculate_odds ($ draw, $ deck );
Alternatively, you can find a card with a specified card surface or color.
Listing 13. Search for a card with a specified card surface or colorCopy codeThe Code is as follows: $ draw = array ('face' => '', 'suit' => 'spades ');
$ Draw = array ('face' => 'ace', 'suit' => '');
Simple poker poster
Now we have obtained the card group builder and some tools to help calculate the probability of getting a specific card. We can integrate a truly simple card Generator for licensing. For the purpose of this example, we will build a poster that can draw five cards. The poster provides five cards from the entire deck. Use a number to specify which cards need to be abandoned, and the poster will replace these cards with other cards in one deck. We do not need to specify licensing restrictions or special rules, but you may find these are very useful personal experiences.
As shown in the previous section, generate and shuffles five cards for each hand. Display these cards by array index so that you can specify which cards are returned. You can use the check boxes indicating which cards to replace to complete this operation.
.
Listing 14. Use the check box to indicate the cards to be replaced Copy codeThe Code is as follows: foreach ($ hand as $ index => $ card ){
Echo "<input type = 'checkbox' name = 'Card [". $ index. "] '>
". $ Card ['face']. 'of'. $ card ['suit']." <br/> ";
}
Then, enter array $ _ POST ['Card '] to check 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 process a specific group of cards.
Hangman games
Hangman is essentially a word game. Given the length of a word, we use a limited number of chances to guess the word. If you have guessed a letter that appears in the word, fill in all the locations where the letter appears. After several guesses (usually six times), you lose. To build a simple hangman game, we need to start with the word list. Now, let's make the word list 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 technology described above, we can move these words to an external word list text file and then import them as needed.
After obtaining the word list, you need to randomly select a word, empty each letter, and start to guess. We need to track the correct and wrong guesses every time we make a guess. You only need to serialize the guess array and pass them each time you guess to achieve the tracking purpose. If you want to prevent people from making guesses by viewing the page source code, you need to perform some safer operations.
Construct an array to save letters and correct/wrong guesses. For correct guesses, we will use letters as keys and periods as values to fill the array.Listing 17. Building an array that saves letters and guesses
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 your guess and display it when you complete the game.
Listing 18. Evaluating guesses and displaying 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 the guess array and pass the array from one guess to another.
Crossword riddle Assistant
I know this is not suitable, but sometimes you have to struggle to find words that start with C and end with T and contain five letters when playing crossword puzzles. Using the same word list built for the Hangman game, we can easily search for words that match a certain pattern. First, find a method for transferring words. For simplicity, replace the missing letter with a period: $ guess = "c... t ";. Because regular expressions process periods as a single character, we can easily traverse the word list to find matching.
Listing 19. traverse the word list Copy codeThe Code is as follows: foreach ($ words as $ word ){
If (preg_match ("/^". $ _ POST ['Guess ']. "$/", $ word )){
Echo $ word. "<br/> \ n ";
}
}
Based on the quality of the word list and the accuracy of prediction, we should be able to obtain a reasonable word list for possible matching. You must decide whether "chest" or "cheat" is the answer to the question "a word consisting of five letters indicating not playing by rules ".
Meilibice
Meilibice is a text game where players get a short story and replace the main types of words with different words of the same type, to create a new boring 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. start to replace the word type with other word tags. The start and end tags are underlined to prevent unexpected string matching.
Listing 20. Replace the word type with the word mark Copy codeThe Code is as follows: $ text = "I was _ VERB_ing in the _ PLACE _ when I found a _ n _.
I _ VERB_ed in, and _ VERB_ed too much _ n _. I had to go to the _ PLACE _.";
Next, create several basic word lists. For this example, we will not do too complicated.
Listing 21. Creating a list of several basic words
$ Verbs = array ('pump ', 'jump', 'walk ', 'swallow', 'crawl', 'wail ', 'roll ');
$ Places = array ('Park ', 'hospath', 'arctic', 'oceance', 'grocery', 'basement ',
'Attic', 'sewer ');
$ Nouns = array ('water', 'Lake ', 'spit', 'foot', 'worm ',
'Did', 'river', 'wankel rotary engine ');
Now you can repeat the evaluation text 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 '_ n _':
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 basic text, the better the result. We have used a text file to create a name list and a basic word list. With the same principle, we can create a list of words by type and use these word lists to create a more varied and more varied meilibice game. Lotto host
Select all the six correct phone numbers of lotto, which are not statistically possible. However, many people still spend money to play, and if you like numbers, it may be interesting to view the trend chart. Let's build a script that will allow you to track the winning numbers and provide the six numbers with the minimum number selected in the list.
(Disclaimer: this will not help you win lotto prizes. Therefore, please do not spend any money to purchase coupons. This is just for entertainment ).
Save the lottery winner to a text file. Separate the numbers with commas (,) and place each group of numbers in a single row. After you use line breaks to separate file content and use commas to separate rows, you can get content similar to listing 23.
Listing 23. Save the lottery winner 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 a basic file for drawing statistics. But it is the beginning and is sufficient to demonstrate the basic principles.
Set a basic array to save the selection range. For example, if you select a number between 1 and 40 (for example, $ numbers = array_fill (, 0);), traverse our selection and increase the matching value.
Listing 24. traversal Selection Copy codeThe Code is as follows: foreach ($ picks as $ pick ){
Foreach ($ pick as $ number ){
$ Numbers [$ number] ++;
}
}
Finally, the numbers are sorted by values. This operation should place the least selected number in the front of the array.
List 25. sort numbers by value
Copy codeThe Code is as follows: asort ($ numbers );
$ Pick = array_slice ($ numbers, 0, 6, true );
Echo implode (',', array_keys ($ pick ));
By adding an actual lotto winning number to a text file containing the winning number list regularly, you can find the long-term trend of the number selection. It is very interesting to see how often some numbers appear.