Home  >  Article  >  Backend Development  >  25 Game Scripts Written in PHP_PHP Tutorial

25 Game Scripts Written in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:46:351270browse

Whether you're playing a simple paper-and-pen game by yourself, a complex tabletop role-playing game with a group, or any type of online game, this series has something for you. Each article in the "30 Game Scripts You Can Write in PHP" series will introduce 10 scripts in less than 300 words (3d10 means "roll three 10-sided dice"), and these introductory words even It's simple enough for novice developers and useful for experienced gamers. The goal of this series is to give you something you can modify to suit your needs so you can impress your friends and fellow gamers by showing off your notebook at your next gaming meetup.
Before You Begin
As a game expert/designer and developer, I often find myself running, planning, and playing games with very little in the way of writing useful utilities and scripts. Sometimes I need to come up with ideas quickly. Other times, I just have to make up a bunch of Non-Player Character (NPC) names. Occasionally, I also need to crunch numbers, handle some exceptions, or integrate some wordplay into the game. These tasks can be better managed with just a little scripting work beforehand.
This article will explore 10 basic scripts that can be used in a variety of games. The code zip contains the complete source code for each script discussed, and the scripts can be viewed in action at chaoticneutral.
We will quickly introduce these scripts. There is no introduction to how to find a host or set up a server. There are many web hosting companies that offer PHP, and if you need to install your own PHP, the XAMPP installer is simple to use. We won't spend a lot of time talking about PHP best practices or game design techniques. The scripts described in this article are easy to understand, simple to use, and quick to master.
Simple Dice Roller
Many games and game 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 and return 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 at once, sometimes it can 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
Copy code The 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 once, just mix the arrays and extract as needed.
Listing 4. Mixed name array
Copy code The 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 on each line of a text file, you can easily separate the file contents with newlines to build an array of source code.
Listing 5. Creating a text file of names
$male = explode('n', file_get_contents('names.female.txt'));
$last = explode(' n', file_get_contents('names.last.txt'));
Build or find some good names 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 a 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 are 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
Copy code The 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, 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 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 shuffler. 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
Copy the code The 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"
 );

Then build a deck of card arrays to save all card values. This can be done simply using a pair of foreach loops.
Listing 8. Constructing a deck of cards array
Copy the code The code is as follows:

 $ deck = array();
foreach ($suits as $suit) {
foreach ($faces as $face) {
$deck[] = array ("face"=>$face, " suit"=>$suit);
 }
 }
After constructing an array of playing cards, we can easily shuffle the deck and randomly draw a card.
Listing 9. Shuffle and randomly draw a card
Copy the code The code is as follows:

shuffle($deck);
$card = array_shift($deck);
echo $card['face'] . ' of ' . $card['suit'];

Now, we have a shortcut to draw multiple decks of cards or build a multideck shoe.
Winning 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.
Listing 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
Copy the code The 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 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
Copy the code The code is as follows:

$draw = array('face' => 'Ace', 'suit' => 'Spades');
echo implode(" of ", $draw) . ' : ' . calculate_odds($draw, $ deck);

Or you can search for cards with a specified face or suit.
Listing 13. Find the card of the specified card face or suit
Copy the code The code is as follows:

$draw = array('face' => '', 'suit' => 'Spades');
$draw = array('face' => 'Ace', 'suit' => ; '');

A Simple Poker Dealer
Now that we have a deck builder and some tools to help figure out the odds of drawing a particular card, we can put together a really simple A card dealer is used to deal 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.
As shown in the previous section, generate and shuffle the deck, then have five cards in each hand. Display the cards by array index so you can specify which cards are returned. You do this using checkboxes indicating which cards you want to replace.
Listing 14. Use checkboxes to indicate cards to be replaced
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 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
Copy code The code is as follows:

$words = array (
"giants",
"triangle",
"particle",
"birdhouse",
"minimum",
"flood"
);

Using the technique described earlier, we can move these words into an external word list text file and then import it as needed.
After getting 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 an 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
Copy the code The 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 guess and display the word while completing the word guessing game.
Listing 18. Evaluate guesses and show progress
Copy code The 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 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 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."
Midribis
Midribis 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, thereby 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. Replacing word types with word tags
$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
Copy the code The code is as follows:

$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 evaluated repeatedly to replace tokens as needed.
Listing 22. Evaluate text
Copy code The 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 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
Copy the code The 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 plotting statistics. But it's a start, and sufficient to demonstrate the basic principles.
Set up 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, sort the numbers according to their values. This operation should put the least selected number at the front of the array.
Listing 25. Sort numbers according to value
Copy code The code is as follows:

asort ($numbers);
$pick = array_slice($numbers,0,6,true);
echo implode(',', array_keys($pick));

Pass Long-term trends in number selection can be discovered by regularly adding actual winning Lotto numbers to a text file containing a list of winning numbers. It's interesting to see how often certain numbers appear.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320130.htmlTechArticleWhether one is playing a simple game using pen and paper, or the same group is playing a complex tabletop role-playing game Games, or any type of online games, this series provides something suitable for you...
Statement:
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