search
HomeBackend DevelopmentPHP Tutorial25 script codes for PHP game programming_PHP tutorial

25 script codes for PHP game programming_PHP tutorial

Jul 21, 2016 pm 03:31 PM
phpcodeanddeviceusgameofSimpleprogrammingScriptneeddice

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
Copy code The code is as follows:

$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, 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 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. $ 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
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 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
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 array to hold 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 the deck 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.
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 $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;
 }

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
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 cards of specified card face or suit
Copy code The code is as follows:

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

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
Copy the code The code is as follows:

 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  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 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
Copy 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 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
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 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
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 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
Copy the code The code is as follows:

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

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.

www.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...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.