Using PHP to implement some common functions in the game

Source: Internet
Author: User
Tags random name generator

Simple flipper

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.

1. Use the mt_rand () random number generator function:

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.

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(10);  // roll a ten-sided dieecho 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.

3. Two simple arrays of first and last names:

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

4. array of mixed names

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.

5. Create a text file with the name

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

6. Generation scenarios

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

7. Build a pair of standard playing cards

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

8. Build a deck Array

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

9. Shuffling and randomly picking a card

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.

10. Five cards are drawn from each hand

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

11. calculate the probability of winning 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;}

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.

12. Search for a specified card

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

13. Search for a card of the specified card surface or color

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

14. Use the check box to indicate the card to be replaced

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.

15. Computing 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 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.

16. Create a word list

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

17. Construct an array for saving letters and guessing 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 your guess and display it when you complete the game.

18. Evaluate the guess and display the 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 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.

19. traverse the word list

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.

20. Replace the word type with the word mark

$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 will not do 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');

Now you can repeat the evaluation text 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);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.

23. Save the lottery winner to a text file.

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

24. Traverse Selection

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.

25. sort numbers by value

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.

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.