Home Backend Development PHP Tutorial 25 good PHP game programming script code sharing (1)_PHP tutorial

25 good PHP game programming script code sharing (1)_PHP tutorial

Jul 22, 2016 am 09:02 AM
php code share and device game of Simple programming Script need dice

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

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> roll () {  </span></span></li>
<li>
<span class="keyword">return</span><span> mt_rand(1,6);  </span>
</li>
<li class="alt"><span>}  </span></li>
<li>
<span class="func">echo</span><span> roll(); </span>
</li>
</ol>
Copy after login

Then you can pass the type of dice to be rolled as a parameter to the function.

Listing 2. Passing the dice type as a parameter

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> roll (</span><span class="vars">$sides</span><span>) {  </span></span></li>
<li>
<span class="keyword">return</span><span> mt_rand(1,</span><span class="vars">$sides</span><span>);  </span>
</li>
<li class="alt"><span>}  </span></li>
<li>
<span class="func">echo</span><span> roll(6);  </span><span class="comment">// roll a six-sided die </span><span> </span>
</li>
<li class="alt">
<span class="func">echo</span><span> roll(10);  </span><span class="comment">// roll a ten-sided die </span><span> </span>
</li>
<li>
<span class="func">echo</span><span> roll(20);  </span><span class="comment">// roll a twenty-sided die</span><span> </span>
</li>
</ol>
Copy after login

From here, we can continue to roll as many dice at once as needed, returning an array of results; we can also roll multiple dice of different types at once. But most tasks can be done using this simple script.

Random Name Generator

If you're running a game, writing a story, or creating a large number of characters at once, it can sometimes be overwhelming to deal with 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 names and one for last names.

Listing 3. Two simple arrays of first name and last name

<ol class="dp-c">
<li class="alt"><span><span class="vars">$male</span><span> = </span><span class="keyword">array</span><span>(  </span></span></li>
<li>
<span class="string">"William"</span><span>,  </span>
</li>
<li class="alt">
<span class="string">"Henry"</span><span>,  </span>
</li>
<li>
<span class="string">"Filbert"</span><span>,  </span>
</li>
<li class="alt">
<span class="string">"John"</span><span>,  </span>
</li>
<li>
<span class="string">"Pat"</span><span>,  </span>
</li>
<li class="alt"><span>);  </span></li>
<li>
<span class="vars">$last</span><span> = </span><span class="keyword">array</span><span>(  </span>
</li>
<li class="alt">
<span class="string">"Smith"</span><span>,  </span>
</li>
<li>
<span class="string">"Jones"</span><span>,  </span>
</li>
<li class="alt">
<span class="string">"Winkler"</span><span>,  </span>
</li>
<li>
<span class="string">"Cooper"</span><span>,  </span>
</li>
<li class="alt">
<span class="string">"Cline"</span><span>,  </span>
</li>
<li><span>); </span></li>
</ol>
Copy after login

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

<ol class="dp-c">
<li class="alt"><span><span>shuffle(</span><span class="vars">$male</span><span>);  </span></span></li>
<li>
<span>shuffle(</span><span class="vars">$last</span><span>);  </span>
</li>
<li class="alt">
<span class="keyword">for</span><span> (</span><span class="vars">$i</span><span> = 0; </span><span class="vars">$i</span><span> <span class="vars">$i</span><span>++) {  </span></span>
</li>
<li>
<span class="func">echo</span><span> </span><span class="vars">$male</span><span>[</span><span class="vars">$i</span><span>] . </span><span class="string">' '</span><span> . </span><span class="vars">$last</span><span>[</span><span class="vars">$i</span><span>];  </span>
</li>
<li class="alt"><span>} </span></li>
</ol>
Copy after login

Based on this basic concept, we can create a text file that holds 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

<ol class="dp-c">
<li class="alt"><span><span class="vars">$male</span><span> = </span><span class="func">explode</span><span>(</span><span class="string">'n'</span><span>, </span><span class="func">file_get_contents</span><span>(</span><span class="string">'names.female.txt'</span><span>));  </span></span></li>
<li>
<span class="vars">$last</span><span> = </span><span class="func">explode</span><span>(</span><span class="string">'n'</span><span>, </span><span class="func">file_get_contents</span><span>(</span><span class="string">'names.last.txt'</span><span>)); </span>
</li>
</ol>
Copy after login

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

Utilizing the same basic principles we used to build name generators, we can build scenario generators. 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 the 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 text files for Settings, Objectives, Enemies, and Complexity respectively. 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. Generating the scene

<ol class="dp-c">
<li class="alt"><span><span class="vars">$settings</span><span> = </span><span class="func">explode</span><span>(</span><span class="string">"n"</span><span>, </span><span class="func">file_get_contents</span><span>(</span><span class="string">'scenario.settings.txt'</span><span>));  </span></span></li>
<li>
<span class="vars">$objectives</span><span> = </span><span class="func">explode</span><span>(</span><span class="string">"n"</span><span>, </span><span class="func">file_get_contents</span><span>(</span><span class="string">'scenario.objectives.txt'</span><span>));  </span>
</li>
<li class="alt">
<span class="vars">$antagonists</span><span> = </span><span class="func">explode</span><span>(</span><span class="string">"n"</span><span>, </span><span class="func">file_get_contents</span><span>(</span><span class="string">'scenario.antagonists.txt'</span><span>));  </span>
</li>
<li>
<span class="vars">$complicati</span><span>**** = </span><span class="func">explode</span><span>(</span><span class="string">"n"</span><span>, </span><span class="func">file_get_contents</span><span>(</span><span class="string">'scenario.complicati****.txt'</span><span>));  </span>
</li>
<li class="alt">
<span>shuffle(</span><span class="vars">$settings</span><span>);  </span>
</li>
<li>
<span>shuffle(</span><span class="vars">$objectives</span><span>);  </span>
</li>
<li class="alt">
<span>shuffle(</span><span class="vars">$antagonists</span><span>);  </span>
</li>
<li>
<span>shuffle(</span><span class="vars">$complicati</span><span>****);  </span>
</li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="vars">$settings</span><span>[0] . </span><span class="string">' '</span><span> . </span><span class="vars">$objectives</span><span>[0] . </span><span class="string">' '</span><span> . </span><span class="vars">$antagonists</span><span>[0] . </span><span class="string">' '</span><span> </span>
</li>
<li>
<span>. </span><span class="vars">$complicati</span><span>****[0] . </span><span class="string">"<br>n"</span><span>; </span>
</li>
</ol>
Copy after login

We can add elements to the scene by adding new text files, and we may wish to add multiple levels of complexity. 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. Build a standard deck of playing cards

<ol class="dp-c">
<li class="alt"><span><span class="vars">$suits</span><span> = </span><span class="keyword">array</span><span> (  </span></span></li>
<li>
<span class="string">"Spades"</span><span>, </span><span class="string">"Hearts"</span><span>, </span><span class="string">"Clubs"</span><span>, </span><span class="string">"Diamonds"</span><span> </span>
</li>
<li class="alt"><span>);  </span></li>
<li>
<span class="vars">$faces</span><span> = </span><span class="keyword">array</span><span> (  </span>
</li>
<li class="alt">
<span class="string">"Two"</span><span>, </span><span class="string">"Three"</span><span>, </span><span class="string">"Four"</span><span>, </span><span class="string">"Five"</span><span>, </span><span class="string">"Six"</span><span>, </span><span class="string">"Seven"</span><span>, </span><span class="string">"Eight"</span><span>,  </span>
</li>
<li>
<span class="string">"Nine"</span><span>, </span><span class="string">"Ten"</span><span>, </span><span class="string">"Jack"</span><span>, </span><span class="string">"Queen"</span><span>, </span><span class="string">"King"</span><span>, </span><span class="string">"Ace"</span><span> </span>
</li>
<li class="alt"><span>); </span></li>
</ol>
Copy after login

Then build a deck array to hold all card values. This can be done simply using a pair of foreach loops.

Listing 8. Constructing an array of playing cards

<ol class="dp-c">
<li class="alt"><span><span class="vars">$deck</span><span> = </span><span class="keyword">array</span><span>();  </span></span></li>
<li>
<span class="keyword">foreach</span><span> (</span><span class="vars">$suits</span><span> </span><span class="keyword">as</span><span> </span><span class="vars">$suit</span><span>) {  </span>
</li>
<li class="alt">
<span class="keyword">foreach</span><span> (</span><span class="vars">$faces</span><span> </span><span class="keyword">as</span><span> </span><span class="vars">$face</span><span>) {  </span>
</li>
<li>
<span class="vars">$deck</span><span>[] = </span><span class="keyword">array</span><span> (</span><span class="string">"face"</span><span>=></span><span class="vars">$face</span><span>, </span><span class="string">"suit"</span><span>=></span><span class="vars">$suit</span><span>);  </span>
</li>
<li class="alt"><span>}  </span></li>
<li><span>} </span></li>
</ol>
Copy after login

After constructing an array of playing cards, we can easily shuffle the deck and randomly draw a card.

List 9. Shuffle the deck and randomly draw a card

<ol class="dp-c">
<li class="alt"><span><span>shuffle(</span><span class="vars">$deck</span><span>);  </span></span></li>
<li>
<span class="vars">$card</span><span> = </span><span class="func">array_shift</span><span>(</span><span class="vars">$deck</span><span>);  </span>
</li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="vars">$card</span><span>[</span><span class="string">'face'</span><span>] . </span><span class="string">' of '</span><span> . </span><span class="vars">$card</span><span>[</span><span class="string">'suit'</span><span>]; </span>
</li>
</ol>
Copy after login

Now we have a shortcut to draw multiple decks of cards or build a multideck shoe.

Win Odds Calculator: Dealing Cards

Since the face and suit of each card are tracked separately when building a poker deck, the deck can be used programmatically to calculate the odds of getting a specific card. First draw five cards from each hand.

清单 10. 每只手抽出五张牌

<ol class="dp-c">
<li class="alt"><span><span class="vars">$hands</span><span> = </span><span class="keyword">array</span><span>(1 => </span><span class="keyword">array</span><span>(), 2=></span><span class="keyword">array</span><span>());  </span></span></li>
<li>
<span class="keyword">for</span><span> (</span><span class="vars">$i</span><span> = 0; </span><span class="vars">$i</span><span> <span class="vars">$i</span><span>++) {  </span></span>
</li>
<li class="alt">
<span class="vars">$hands</span><span>[1][] = implode(</span><span class="string">" of "</span><span>, </span><span class="func">array_shift</span><span>(</span><span class="vars">$deck</span><span>));  </span>
</li>
<li>
<span class="vars">$hands</span><span>[2][] = implode(</span><span class="string">" of "</span><span>, </span><span class="func">array_shift</span><span>(</span><span class="vars">$deck</span><span>));  </span>
</li>
<li class="alt"><span>} </span></li>
</ol>
Copy after login

然后可以查看这副牌,看看剩余多少张牌以及抽到特定牌的机率是多少。查看剩余的牌数十分简单。只需要计算 $deck 数组中包含的元素数。要获得抽到特定牌的机率,我们需要一个函数来遍历整副牌并估算其余牌以查看是否匹配。

清单 11. 计算抽到特定牌的几率

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> calculate_odds(</span><span class="vars">$draw</span><span>, </span><span class="vars">$deck</span><span>) {  </span></span></li>
<li>
<span class="vars">$remaining</span><span> = </span><span class="func">count</span><span>(</span><span class="vars">$deck</span><span>);  </span>
</li>
<li class="alt">
<span class="vars">$odds</span><span> = 0;  </span>
</li>
<li>
<span class="keyword">foreach</span><span> (</span><span class="vars">$deck</span><span> </span><span class="keyword">as</span><span> </span><span class="vars">$card</span><span>) {  </span>
</li>
<li class="alt">
<span class="keyword">if</span><span> (  (</span><span class="vars">$draw</span><span>[</span><span class="string">'face'</span><span>] == </span><span class="vars">$card</span><span>[</span><span class="string">'face'</span><span>] && </span><span class="vars">$draw</span><span>[</span><span class="string">'suit'</span><span>] ==  </span>
</li>
<li>
<span class="vars">$card</span><span>[</span><span class="string">'suit'</span><span>] ) ||  </span>
</li>
<li class="alt">
<span>(</span><span class="vars">$draw</span><span>[</span><span class="string">'face'</span><span>] == </span><span class="string">''</span><span> && </span><span class="vars">$draw</span><span>[</span><span class="string">'suit'</span><span>] == </span><span class="vars">$card</span><span>[</span><span class="string">'suit'</span><span>] ) ||  </span>
</li>
<li>
<span>(</span><span class="vars">$draw</span><span>[</span><span class="string">'face'</span><span>] == </span><span class="vars">$card</span><span>[</span><span class="string">'face'</span><span>] && </span><span class="vars">$draw</span><span>[</span><span class="string">'suit'</span><span>] == </span><span class="string">''</span><span> ) ) {  </span>
</li>
<li class="alt">
<span class="vars">$odds</span><span>++;  </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span>}  </span></li>
<li>
<span class="keyword">return</span><span> </span><span class="vars">$odds</span><span> . </span><span class="string">' in '</span><span> </span><span class="vars">$remaining</span><span>;  </span>
</li>
<li class="alt"><span>} </span></li>
</ol>
Copy after login

现在可以选出尝试抽出的牌。为了简单起见,传入看上去类似某张牌的数组。我们可以查找特定的一张牌。

清单 12. 查找指定的一张牌

<ol class="dp-c">
<li class="alt"><span><span class="vars">$draw</span><span> = </span><span class="keyword">array</span><span>(</span><span class="string">'face'</span><span> => </span><span class="string">'Ace'</span><span>, </span><span class="string">'suit'</span><span> => </span><span class="string">'Spades'</span><span>);  </span></span></li>
<li>
<span class="func">echo</span><span> implode(</span><span class="string">" of "</span><span>, </span><span class="vars">$draw</span><span>) . </span><span class="string">' : '</span><span> . calculate_odds(</span><span class="vars">$draw</span><span>, </span><span class="vars">$deck</span><span>); </span>
</li>
</ol>
Copy after login

或者可以查找指定牌面或花色的牌。

清单 13. 查找指定牌面或花色的牌

<ol class="dp-c">
<li class="alt"><span><span class="vars">$draw</span><span> = </span><span class="keyword">array</span><span>(</span><span class="string">'face'</span><span> => </span><span class="string">''</span><span>, </span><span class="string">'suit'</span><span> => </span><span class="string">'Spades'</span><span>);  </span></span></li>
<li>
<span class="vars">$draw</span><span> = </span><span class="keyword">array</span><span>(</span><span class="string">'face'</span><span> => </span><span class="string">'Ace'</span><span>, </span><span class="string">'suit'</span><span> => </span><span class="string">''</span><span>); </span>
</li>
</ol>
Copy after login

1

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445840.htmlTechArticle简单的掷骰器 许多游戏和游戏系统都需要骰子。让我们先从简单的部分入手:掷一个六面骰子。实际上,滚动一个六面骰子就是从 1 到 6...
Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles