PHP game programming 25 script code

  • 2020-03-31 21:30:17
  • OfStack

Listing 1. A simple die roll
Many games and systems require dice. Let's start with the easy part: rolling a six-sided die. In fact, rolling a six-sided die is picking a random number from 1 to 6. In PHP, this is simple: echo rand(1,6); .
In many cases, this is basically simple. But when dealing with probability games, we need some better implementations. PHP provides a better random number generator: mt_rand (). Without further study of the difference, mt_rand can be considered a faster and better random number generator: echo mt_rand(1,6); . The random number generator works even better if you put it into a function.
Listing 1. Using the mt_rand() random number generator function
 
  function roll () { 
  return mt_rand(1,6); 
  } 
  echo roll(); 

You can then pass the type of die you want to roll as an argument to the function.
Listing 2. Pass the die type as an argument
 
  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 more than one die at a time as needed, returning an array of results; You can also roll several different types of dice at once. But most tasks can use this simple script.
Random name generator
If you're running a game, writing a story, or creating a bunch of characters all at once, you can sometimes get caught up in the constant stream 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 name and one for last name.
Listing 3. Two simple arrays of first and last names
 
  $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 array and extract as needed.
Listing 4. An 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 text files that hold first and last names. If you store a name in each line of a text file, you can easily separate the file contents with a newline character to build an array of source code.
Listing 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')); 

Build or find some good name files (some of which come with the code archive), and we'll never have to worry about names again.
Scene generator
Using the same basic principles used to build the name generator, we can build the scenario generator. This generator is useful not only in role-playing games, but also in situations where a set of pseudo-random environments is needed (for role-playing, improvisation, writing, etc.). One of my favorite games, Paranoia includes "mission blender" in its GM Pack. Task mixers can be used to integrate complete tasks while rolling dice quickly. Let's integrate our own scene 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 barking of nearby dogs and the distinct sounds of enemy searchers. You are cold, trembling, and unarmed. Each sentence in the scenario introduces a specific aspect of the scenario:
"You wake up and find yourself lost in the jungle" - this will set up the setup.
"You know you have to get to New York" -- this will describe the goal.
"You can hear the dog barking" - this will introduce the enemy.
"You are cold, shivering, and unarmed" - this sentence adds complexity.
Just as you create text files for first and last names, you first create text files for Settings, targets, enemies, and complexity, respectively. Sample files are included with the code archive. After you have these files, the code that generates the scenario is basically the same as the code that generates the name.
Listing 6. Generate the scenario
 
  $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 scenario by adding new text files, or we may want to add multiple complexity. The more you add to the base text file, the more the scene changes over time.
Deck builder and shuffler
If you want to play CARDS and work with playing-card-related scripts, 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 CARDS in the same suit and one to hold faces. This gives you great flexibility if you need to add new groups or types of CARDS later on.
Listing 7. Building a standard deck of playing CARDS
 
  $suits = array ( 
  "Spades", "Hearts", "Clubs", "Diamonds" 
  ); 
  $faces = array ( 
  "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", 
  "Nine", "Ten", "Jack", "Queen", "King", "Ace" 
  ); 

Then build an array of CARDS to hold all the card values. You can do this using just a pair of foreach loops.
Listing 8. Building an array of CARDS
 
  $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 shuffle and draw a random card.
Listing 9. Shuffle and draw a random card
 
  shuffle($deck); 
  $card = array_shift($deck); 
  echo $card['face'] . ' of ' . $card['suit']; 

Now we have a shortcut to draw multiple decks or build a multideck shoe.
Calculator: deals
Since the deck of CARDS is built to track the face and suit of each card separately, the deck can be used programmatically to calculate the odds of getting a particular card. First, each hand draws five CARDS.
Listing 10. Draw five CARDS 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 look at the deck to see how many CARDS are left and what is the probability of drawing a particular card. It is easy to view the remaining scores of CARDS. You just count the number of elements contained in the $deck array. To get the probability of drawing a particular card, we need a function to walk through the deck and estimate the remaining CARDS to see if they match.
Listing 11. Calculating the probability of drawing a particular 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 pick the card that you're trying to draw. For simplicity, pass in an array that looks like a certain card. We can look for a particular card.
Listing 12. Find the specified card
 
  $draw = array('face' => 'Ace', 'suit' => 'Spades'); 
  echo implode(" of ", $draw) . ' : ' . calculate_odds($draw, $deck); 

Or you can find CARDS in the specified face or suit.
Listing 13. Find the card for the specified face or suit
 
  $draw = array('face' => '', 'suit' => 'Spades'); 
  $draw = array('face' => 'Ace', 'suit' => ''); 

Simple poker dealer
Now that we have the deck builder and some tools to help figure out the probability of pulling a particular card, we can put together a really simple dealer to deal. For the purposes of this example, we will build a dealer that can draw five CARDS. The dealer will supply five CARDS from the deck. Use Numbers to specify which CARDS to discard, and the dealer will replace them with other CARDS in a deck. We do not need to specify licensing restrictions or special rules, but you may find these very useful personal experiences.
As shown in the previous section, generate and shuffle the CARDS, and then five CARDS per hand. The CARDS are displayed as an array index so that you can specify which CARDS are returned. You can do this by using a check box that indicates which CARDS to replace
.
Listing 14. Use the checkbox to indicate the card to replace
 
  foreach ($hand as $index =>$card) { 
  echo "<input type='checkbox' name='card[" . $index . "]'> 
  " . $card['face'] . ' of ' . $card['suit'] . "<br />"; 
  } 

Then, calculate the input array $_POST['card'] to see which CARDS have been selected for substitution.
Listing 15. Calculate the input
 
  $i = 0; 
  while ($i < 5) { 
  if (isset($_POST['card'][$i])) { 
  $hand[$i] = array_shift($deck); 
  } 
  } 

Using this script, you can try to figure out the best way to handle a particular set of CARDS.
Hangman
Hangman is essentially a crossword game. Given the length of a word, we have a limited number of guesses. If you guess a letter that appears in the word, fill in all the places where the letter appears. After guessing wrong a number of times (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 list of words into a simple array.
Listing 16. Creating a list of words
 
  $words = array ( 
  "giants", 
  "triangle", 
  "particle", 
  "birdhouse", 
  "minimum", 
  "flood" 
  ); 

Using the techniques described earlier, we can move these words to an external word list text file and import them as needed.
Once you have a list of words, you need to pick one word at random, leave each letter blank, and start guessing. We need to keep track of right and wrong guesses every time we make a guess. You can do this by serializing the guess array and passing it along each time you make a guess. If you need to prevent people from getting lucky by looking at the source code of the page, you need to do something safer.
Build an array to hold letters and correct/wrong guesses. For good guesses, we'll fill the array with letters as keys and periods as values. Listing 17. Building an array to hold the letters and the guesses
 
  $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 guesses and display the word during the crossword puzzle.
Listing 18. Evaluate guesses and show 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 archive, you can see how to serialize a guess array and pass it from guess to guess.
Crossword helper
I know this isn't appropriate, but sometimes in crossword puzzles you have to struggle to find five-letter words that begin with C and end with T. Using the same list of words built for the Hangman game, we can easily search for words that fit a pattern. First, find a way to transfer words. For simplicity, replace the missing letter with a period: $guess = "c... T "; . Because the regular expression treats the period as a single character, we can easily traverse the list of words to find a match.
Listing 19. Walking through the list of words
 
  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 guess, we should be able to get a reasonable list of words for possible matches. You have to decide for yourself whether the answer to the five-letter word for 'not playing by the rules' is' chest' or 'cheat'.
midribis
Midribis is a word game in which players get a short story and replace the main type of words with different words of the same type to create a new, more 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." with other words the tag type. The start and end tags are underlined to prevent unexpected string matches.
Listing 20. Replace the word type with a word tag
 
  $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 get too complicated.
Listing 21. Create a few 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', 'the spit', 'foot' and 'worm',
'dirt', 'river', 'wankel rotary engine');

You can now evaluate the text repeatedly to replace the markup as needed.
Listing 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 crude example. The more accurate the word list, and the more time spent on the basic text, the better the result. We have used a text file to create a list of names and a list of basic words. Using the same principles, we can create lists of words by type and use those lists to create more varied midribis games. The lottery machine
Picking all six correct Numbers in the lottery 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 chart. Let's build a script that will allow you to keep track of winning Numbers and provide the list of the least selected six Numbers.
(disclaimer: this won't help you win the lottery, so please don't spend money on raffle tickets. It's just for fun.
Save the winning lottery selections to a text file. Separate Numbers with commas and put each group on a separate line. After separating the contents of the file with a newline character and separating the lines with a comma, you get something like listing 23.
Listing 23. Save the selected winning lottery 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's a start, and it's enough to demonstrate the fundamentals.
Sets a base array to hold the selection range. For example, if you select between 1 and 40 (for example, $Numbers = array_fill(1,40,0);) The number of, then traverses our selection and increments the corresponding matching value.
Listing 24. Traversing the selection
 
  foreach ($picks as $pick) { 
  foreach ($pick as $number) { 
  $numbers[$number]++; 
  } 
  } 

Finally, sort the Numbers by value. This operation should place the least selected number at the front of the array.
Listing 25. Sort Numbers by value
 
  asort($numbers); 
  $pick = array_slice($numbers,0,6,true); 
  echo implode(',', array_keys($pick)); 

Long-term trends can be found by regularly adding actual lottery Numbers to a text file containing a list of winning Numbers. It's interesting to see how often certain Numbers appear.

Related articles: