25 script codes for PHP game programming_PHP tutorial
WBOY
Release: 2016-07-21 15:31:49
Original
1247 people have browsed it
Checklist 1. Simple Dice Roller Many games and gaming systems require dice. Let's start with the easy part: rolling a six-sided die. Essentially, rolling a six-sided die is simply choosing a random number between 1 and 6. In PHP, this is very simple: echo rand(1,6);. In many cases, this is basically simple. But when dealing with games of chance, we need some better implementation. PHP provides a better random number generator: mt_rand(). Without delving too deeply into the differences between the two, mt_rand can be thought of as a faster and better random number generator: echo mt_rand(1,6);. It would be even better if you put this random number generator into a function. Listing 1. Using the mt_rand() random number generator function
Copy the code The code is as follows:
Function roll () { return mt_rand(1,6); } echo roll();
Then you can pass the type of dice that needs to be rolled as a parameter passed to the function. Listing 2. Passing the dice type as a parameter
Copy the code The 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 we can continue to roll as many dice at a time as needed, returning the result Array; it is also possible to roll multiple dice of different types at once. But most tasks can be done using this simple script. Random Name Generator If you are running a game, writing a story, or creating a large number of characters all at once, it can sometimes be overwhelming to deal with the constant flow 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 first names and one for last names. Listing 3. Two simple arrays of first name and last name
> 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, just mix the arrays and extract as needed. Listing 4. Mixed name array
Based on this basic concept, we can create a text file that saves the first and last names. If you store a name on each line of a text file, you can easily separate the file contents with newlines to build an array of source code. $ 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 are included in the code archive) and we'll never have to worry about names again. Scenario Generator Using the same basic principles we used to build the name generator, we can build a scenario generator. This generator is useful not only in role-playing games, but also in situations where you need to use a collection of pseudo-random environments (which can be used for role-playing, improvisation, writing, etc.). One of my favorite games, Paranoia, includes a "mission blender" in its GM Pack. The Mission Mixer can be used to combine complete missions while rolling dice quickly. Let's put together our own scene generator. Consider the following scenario: You wake up and find yourself lost in the jungle. You know you have to get to New York, but you don’t know why. You can hear dogs barking nearby and the distinct sounds of enemy seekers. You're cold, shaking, and unarmed. Each sentence in the scene introduces a specific aspect of the scene: “You wake up and find yourself lost in the jungle” — This sentence will establish the setting. “You know you have to get to New York” — This sentence will describe the goal. “You can hear the dogs barking” — This sentence will introduce the enemy. “You’re cold, shaking, and unarmed” — this sentence will add complexity. Just like you created the text files for First Name and Last Name, first create separate text files for Settings, Objectives, Enemies, and Complexity. Sample files are included in the code archive. Once you have these files, the code to generate the scene is basically the same as the code to generate the name. Listing 6. Generate scene
We can add elements to the scene by adding new text files, and we may wish to add multiple complexities. The more content you add to the basic text file, the more the scene changes over time. Deck builder and gear (shuffler) If you are going to play poker and deal with card-related scripts, we need to integrate a deck builder with the tools in the gear. First, let's build a standard deck of cards. Two arrays need to be constructed - one to hold the group of cards of the same suit, and another to hold the face of the card. This gives you great flexibility if you need to add new decks or card types later. Listing 7. Constructing a standard deck of playing cards
After constructing an array of playing cards, we can easily shuffle the deck and randomly draw a card. Listing 9. Shuffle the deck and randomly draw a card
Now, we have a shortcut to draw multiple decks of cards or build a multideck shoe. Win Odds Calculator: Dealing Cards Because the face and suit of each card are tracked separately when building a deck of cards, the deck can be used programmatically to calculate the odds of getting a specific card. First draw five cards from each hand. List 10. Draw five cards from each hand
Copy the code The 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 specific card. It's easy to see how many cards you have left. Just count the number of elements contained in the $deck array. To get the chance of drawing a specific card, we need a function that goes through the entire deck and estimates the remaining cards to see if they match. Listing 11. Calculate the probability of drawing a specific card
Okay now Choose the card you are trying to draw. To keep things simple, pass in an array that looks like a card. We can look for a specific card. Listing 12. Find a specified card
Simple Poker Dealer Now that we’ve got a deck builder and some tools to help figure out the odds of drawing a specific card, we can put together a really simple card dealer to do that Deal the cards. For the purposes of this example, we will build a card dealer that draws five cards. The card dealer will provide five cards from the entire deck. Numbers are used to specify which cards need to be discarded, and the dealer will replace these cards with other cards from the deck. We are not required to specify licensing restrictions or special rules, but you may find these to be a very beneficial personal experience. Generate and shuffle the deck as shown in the previous section, then hold five cards in each hand. Display the cards by array index so you can specify which cards are returned. You can do this using the checkboxes that indicate which cards you want to replace . Listing 14. Use checkboxes to indicate cards to be replaced
Then, calculate the input array $_POST[ 'card'] to see which cards have been selected for replacement. Listing 15. Calculation input
Copy code The code is as follows:
$i = 0 ; while ($i < 5) { if (isset($_POST['card'][$i])) { $hand[$i] = array_shift($deck); } }
Using this script, you can try to find the best way to deal with a specific set of cards. Hangman Game Hangman is essentially a 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 positions where that letter appears. After a number of incorrect guesses (usually six), you lose the game. To build a crude hangman game, we need to start with a list of words. Now, let's make the word list into a simple array. Listing 16. Create word list
Using the technique described earlier, we can move these words into an external word list text file and then import it 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 track the correct and incorrect guesses every time we make a guess. Just serialize the guess array and pass them on each guess for tracking purposes. If you need to stop people from getting a lucky guess by looking at the page source, you need to do something safer. Construct array to hold letters and correct/wrong guesses. For the correct guess, we will fill the array with letters as keys and periods as values. Listing 17. Construct an array to save letters and guess results
Now I need some Code to evaluate the guess and display the word during the completion of the word guessing game. Listing 18. Evaluate guesses and show progress
In the source code archive you can see how to serialize the guess array and convert the array from One guess is passed into another guess. Crossword Helper I know this is inappropriate, but sometimes when playing crossword puzzles you have to struggle to find a five-letter word that starts with C and ends with T. Using the same word list built for the Hangman game, we can easily search for words that match a pattern. First, find a way to transfer the words. For simplicity, replace missing letters with periods: $guess = "c...t";. Since the regular expression will treat the period as a single character, we can easily iterate through the list of words to find a match. Listing 19. Traverse the word list
Copy the code The 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 guess, we should be able to get a reasonable list of words to use for possible matches. You'll have to decide for yourself whether the answer to the five-letter word for "playing outside the rules" is "chest" or "cheat." Midlibis Midlibis is a word game in which the player is given a short story and replaces the main type of words with different words of the same type, creating a more boring version of the same story New version. 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 replacing word types with other word markers. The opening and closing tags are underlined to prevent unexpected string matches. Listing 20. Replace word types with word tags
Copy code The 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 a few basic word lists. For this example, we won't make it 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');
Text can now be repeatedly evaluated to replace tokens as needed. Listing 22. Evaluate text
Obviously, this is a simple and crude example. The more precise your word list is and the more time you spend on the base text, the better the results will be. We have used text files to create a list of names and a list of basic words. Using the same principles, we can create word lists divided by genre and use these word lists to create more varied Midlibis games. Lotto Machine Picking all six correct Lotto numbers is – to say the least – statistically impossible. Still, many people pay to play, and if you like the numbers, it can be fun to look at the trend graph. Let's build a script that will allow tracking the winning numbers and provide the 6 numbers with the least number of picks in a list. (Disclaimer: This will not help you win Lotto prizes, so please do not spend money on tickets. This is just for fun). Save winning lotto selections to a text file. Separate numbers with commas and put each group of numbers on a separate line. After delimiting the file contents using newlines and commas to separate lines, you get something like Listing 23. Listing 23. Save the selected winning lotto to a text file
Obviously this is not enough to be a basic file for plotting statistics. But it's a start, and sufficient to demonstrate the basic principles. Set a basic array to hold the selection range. For example, if we select a number between 1 and 40 (for example, $numbers = array_fill(1,40,0);), we iterate through our selection, incrementing the corresponding match value. Listing 24. Traverse selections
Copy code The code is as follows:
foreach ($picks as $pick) { foreach ($pick as $number) { $numbers[$number]++; } }
Finally, according to the value Sort the numbers. This operation should put the least selected number at the front of the array. Listing 25. Sort numbers according to value
Long-term trends in number picks can be discovered by regularly adding actual Lotto winning numbers to a text file containing a list of winning numbers. It's interesting to see how often certain numbers appear.
http://www.bkjia.com/PHPjc/322955.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322955.htmlTechArticleListing 1. Simple Dice Roller Many games and gaming systems require dice. Let's start with the easy part: rolling a six-sided die. In fact, rolling a six-sided die starts with...
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn