30 game scripts you can write in PHP, Part 3
This class can emulate a slot machine. It can emulate pulling the handle discounting the user credits and picking 3 random symbols that will be results. It uses weighted mapping from a virtual reel to a smaller physical reel, emulating real world slots with 3 reels and a center pay line.
Content series:
This content is part # of # in the series: 30 game scripts you can write in PHP, Part 3
This content is part of the series:30 game scripts you can write in PHP, Part 3
Stay tuned for additional content in this series.
In this article, we build an inventory-management system and note-taking scripts for your role-playing games, while working on the interactivity of your PHP scripts. We also build an image-based ID card generator and get your feet wet performing image manipulation with PHP. We will create a poker-hand evaluator, a slot-machine generator, and a casino bank, allowing you to practice some trickier PHP logic. We will take our word-game scripts one step further working with a difficult logic by building a complex anagram generator, a crypto solver, and more.
These scripts are a little harder than the scripts from Part 1 and Part 2 because they accomplish a lot more. The code archive for this article contains the full source code for each script we will discuss.
As in Part 1 and Part 2, we're going to be blazing through these scripts pretty fast. If you haven't run through Parts 1 and 2, you should do so before starting this article.
Basic inventory-management system
Having already put together a script to manage character stats, let's take the script one step further and add some basic inventory management. Using this script, we keep track of spent ammo, burnt torches, and found items (see Listing 1). Rather than try to lay out all the items you might ever find, we create two input fields — one for the name of the item and one for the item count: <input name='newitem' /> <input name='newcount' />
. When the script is submitted, we want to add the new item to an inventory array and save the array along with the character sheet. Then we walk the inventory array and create new input fields to hold the items.
Lisiting 1. Adding some basic inventory management
Those input names may look weird, but by structuring them in this fashion, PHP will create the 'inventory' array automatically, complete with name-value pairs. See the script archive to see how this is all pulled together.
A simple note-taking script
It's helpful when playing an RPG to scribble down some notes. The notes are less helpful when you can't figure out where you wrote down the important parts. Let's put a script together that helps store and find game notes.
Taking a note requires only two form fields: <input name='title' /> <br /> <textarea name='body'> <br />
.
As with the character sheet, the notes are added to an array, serialized, and stored in a text file. As you save the note, you'll analyze the words. The word count is also stored in the same text file. To make this easy, replace anything that isn't a letter or number and lowercase the whole note (only for the analysis): $analyze = preg_replace('/[^0-9a-zs]/', strtolower($_POST['body']));
. Then split on white spaces and push the note ID into the word-count array for each word.
Listing 2. Script that helps easily store and find game notes
You can see how to retrieve individual notes, or notes by keyword, by trying out the test script or looking in the code archive.
ID-card generator
If you're playing a modern-era game, having a physical ID card for your character can impress your friends and add a sense of realism to a game. You're going to put together some PHP image-manipulation code that will allow you to create an ID-card image suitable for lamination. To start, we need a basic image to use as an ID blank. We will use this crude ID blank I pulled together for the example.
Figure 1. Example ID blank
We need a basic form to collect the fields for the ID card (Name, Authorization, Home, Birth date, Hair and Eye color). Then we need to push those values as strings into the image. Some of this takes trial and error to get right, as you determine the right places to start and stop text: imagettftext ( $img , 40 , 0 , 600 , 200 , 0 , 'tarzeau_-_OCR-A', $_POST['name'] );
. If you've done everything correctly, you should be able to fill out the form and get something like Figure 2.
Figure 2. Example ID filled out
The font specified is included in the code archive, and the source image is 300DPI. Getting the font and ID card working can be tricky on some systems, but the source in the script archive calls out the problem areas.
Tile-based map generator
Early computer games used tiles to create game maps. The same basic tile approach is still used today in some circumstances. Let's put together a script to generate a basic map. This map won't be very big, but we can use the same principles to create much larger maps, of varying detail. To start, create a few different terrain types and throw together some really rudimentary map tiles to represent each terrain type.
Figure 3. Basic terrain types
Now that we have basic terrain types, you can imagine what comes next: We create an array of map tiles for each row. But we will get poor results by just picking the terrain types randomly and shoving them into arrays.
Let's make a map that's 20 tiles in size. When picking a terrain type, consider the surrounding tiles when making decisions. Look at the four closest-known tiles: the last tile in the current row and the three tiles directly above the current tile. We can set up complex rules to govern how terrain is generated, but for now, start with something simple: Add the terrain types of the four closest tiles to the array before picking them randomly. The more times we add the previous terrain types, the more likely we will get homogeneous regions. The result is something like Listing 3.
Listing 3. An array of map tiles
Once we have a map array, we iterate through each row and column, including an image for each terrain type. Try out the test script to see what kinds of maps this script will generate. The sky is the limit with this script. We can give individual terrain types different weights by pushing them into the pool multiple times and create more complex rules about what terrain types can touch. Don't be afraid to experiment.
Poker-hand evaluator
We've already written a poker dealer and a blackjack dealer. Let's go one step further and write a hand evaluator for poker. This is more complicated, and working how to sort hands of the same type could take some time to work out. But it's pretty easy to have the script look at five cards and tell you if there is a straight, a flush, etc.
When looking at the cards in the hand, there are several easy rules to apply:
- If the suit of the current card is not the same as the suit of the last card, there is no flush.
- If the face of any card matches the face of any previous card, there is no straight.
- If no cards match, and if the $highcard minus $lowcard is exactly five, there is a straight.
Once these simple rules are in place, apply a simple check to work out the matches:
- If there are five different faces, there are no matches.
- If there are four different faces, there is one pair.
- If there are three different faces, there is either two pair or three of a kind.
- If there are two different faces, there is either a full house or four of a kind.
- If there is only one face, you have cheated.
See how these rules are put in play by reviewing the sample script in the archive.
Slot machine
Modern slot machines are complicated beasts with video screens, multiple paylines, more buttons, and fewer levers to pull. For this example, we simulate a simple three-wheel slot machine with one payline. Let's start by identifying what faces are on the wheel.
Listing 4. Indentifying faces on the wheel
Next, establish what the winning results are. There can be many variations of winning results, but for the example, let's say a winning result is three matching results on the payline. We need to set up some association to the winning result and the payout. You might do something like Listing 5.
Listing 5. Winning results and payouts
When you spin the wheels, the first and third wheels spin in one direction, while the second wheel spins the other direction. With this in mind, let's set up the wheels.
Listing 6. Setting up the wheels
In the code, we reversed the array to set up $wheel2
. We want to keep track of the wheel positions from play to play, but the rest of the exercise is pretty simple. Each wheel must go around at least once, no more than 10 times. Use modulo to simulate rolling the wheel: $result1 = $wheel1[rand(count($wheel1), 10*count($wheel1)) % count($wheel1)];
. Finally, look up the result in $payouts.
Listing 7. Looking up the results in $payouts
Slot Machine Php Jquery Cdn
Please note: This is really rudimentary. Actual slot machines are far more complicated, and balancing the payout is tricky. This is just a learning exercise. Work with the code in the script archive and see if you can tweak the payouts to be something a little more reasonable.
Keno
Keno is a cross between bingo and a lottery. Twenty numbers, from 1 to 80, are selected at random, with players placing bets on which numbers will be drawn (by picking up to 15 numbers). Keno payouts vary widely, but setting up a script to simulate playing Keno is pretty simple, especially since we've already done very similar things in this series. For starters, you need an array of numbers from 1 to 80.
Listing 8. An array of numbers from 1 to 80
Enter your guesses in a single text field, separated by a comma. Then simply slice out 20 numbers from the $balls
array, and check the guesses against the drawn numbers. This is done easily and can be seen in the code archive. The script could be improved by displaying the picks in a Keno-style board. Try this when you are comfortable with the script.
Cryptogram helper
Crypto is a game run in most newspapers, where the goal is to decode a given phrase that has been encoded using a substitution cypher, like the one we wrote in Part 2. Let's write something that uses basic frequency analysis to decode an encoded message. You could use the same approach to help solve Crypto problems.
Frequency analysis is just a fancy way of saying 'counting letters.' Take a sample of unencoded text, count how many times specific letters appear in the text, and sort the letters in order from most to least frequent. Then do the same thing for the encoded text. When done, put the two lists of letters next to each other, and the result is a reasonable guess at a decoding key. This works best with large blocks of text, but the approach can still be used when dealing with shorter phrases. Start with two text boxes: one for unencoded text and one for the Crypto. Count the letters in the unencoded text and sort the array results.
Listing 9. Counting the letters in the unencoded text and sorting the array results
Then, do the same with the encoded text. Once we have the arrays sorted by letter frequency, create a map of letters and use them to try decoding the text. If you're especially lucky, the text will decode the first time, but don't count on it. The result will probably be partially decoded text — a good starting point for working out the puzzle. Check out the script sample for more details. There's plenty of room for improving this script.
Mastermind
Mastermind is a board game (based on an older game) where the player must guess the order and color of pegs set by the codemaker. In this version, the script will be the codemaker, and you will make a series of guesses. The script will tell you how many guesses are the right color, but wrong position, and how many guesses are exactly correct. Mastermind uses six different-colored pegs, and you may repeat colors. Start by establishing the code shown below.
Listing 10. Array of six different-colored pegs
Next, we need something to analyze the guess (see Listing 11). Guesses are entered in a single text field, such as OOGBVR.
Listing 11. Analyzing the guess
See how it is all pulled together in the sample script. This is a fun little game that can be modified in many ways.
Word chains
You have probably played the game before where you take a single word and change just one letter to make a different word. Usually this game is played with the intent to change from one word to another, like from the word BIKE to the word FATE using the following word chain: BIKE, LIKE, LAKE, LATE, FATE. Let's create a script to generate word chains from a single word, using some of the code we created for the crossword helper (see Listing 12). Given a single word, like BIKE, we can create four words with missing letters(.IKE, B.KE, BI.E and BIK.) that can be passed through the crossword helper to find possible matches.
Listing 12. Generating word chains from a single word
Once a match is found, we do the same thing with the match (making sure not to duplicate words). Continue this same logic as long as you keep finding matches. We can even branch the solutions for every possible match. Doing so would be a useful exercise, and a helpful lesson in runaway recursion. Once you're comfortable with the sample script, you should give this a try.
Summary
I hope this '30 game scripts you can write in PHP' series put you on the road to creating interesting game scripts with PHP. Regardless of how you like to play, you can enrich the gaming experience using the simple utilities presented in this series. PHP makes a great language choice for these tasks, and if you've followed along here, you've no doubt improved your PHP programming skills while having fun.
Downloadable resources
- 10 advanced PHP scripts (os-php-gamescripts3.zip | 844KB)
Related topics
- Learn 10 basic scripts you can use in a variety of games in the developerWorks article '30 game scripts you can write in PHP Part 1: 10 fundamental scripts.
- Up the ante with some more complexity that will further develop your PHP programming skills and enhance your status as a game master with Part 2: Developing 10 intermediate scripts.
- Open Font Library is the source of the OCR-A font used in the ID Card Printer (more fonts available).
- Get some basic info on slot machines.
- Learn more about Keno.
- Cryptograms.org has more cryptograms than you could ever want.
- Read 'Apache 2 and PHP 5 (mod_php) on Linux' to find out how to get Apache V2 and PHP V4.x (may also use PHP V5.x) working together on Linux.
- 'Connecting PHP applications to Apache Derby' shows how to install and configure PHP on Windows (some steps are applicable to Linux).
- Read 'Learning PHP, Part 1' to learn about PHP basics. Then read Part 2 to learn how to upload files to non-web accessible locations, using the DOM and SAX. And Part 3 completes the workflow application.
- Check out the PHP Manual to learn more about PHP data objects and their capabilities.
- PHP.net is the central resource for PHP developers.
- Check out the 'Recommended PHP reading list.'
- Browse all the PHP content on developerWorks.
- Expand your PHP skills by checking out IBM developerWorks' PHP project resources.
- Using a database with PHP? Check out the Zend Core for IBM, a seamless, out-of-the-box, easy-to-install PHP development and production environment that supports IBM DB2 V9.
Slot Machine Php Jquery Tutorial
Examples
Overview
Summary
Visitors increasingly want to engage with our sites and brands. This slot machine gives the perfect way for your visitors to do that with little effort or cost to you or your company. On top of that it increases customer loyalty, returning to the site to continue to play! We've seen a huge variety of companies use this to great success. Imagination really is the only limit!
Have your own HTML5, pure Javascript slot machine on your site! In a recent survey, 74% of users said the well finished game contributed “moderately or significantly” to the fun of the site.
Packages provide a license for you to use this slot machine on all your sites. You can mix it up and customize your slot machine with the 5 different pre-set designs provided, or you can very easily make your own.
Written in pure HTML 5, Javascript, jQuery and CSS it is extremely quick and simple to integrate into any new or existing site. Proven to work flawlessly on mobiles and tablet (including Android, iOS and Windows Phone), your visitors can enjoy this feature at any time and there is no use of Flash or Java, so no annoying pop ups to distract your visitors from what you want them to focus on!
Some interesting uses and ideas for your slot machine
These are some of the imaginative uses our customers have given their slot machine. Get your creative juices flowing!
- Encourage spending in your store giving people a chance to win discounts, prizes and promotions.
- Give credits away as virtual game currency, or virtual goods in those games, when users level up, or find a chest, for example.
- Give customers a chance to win a discount at the time of checkout, in your online store.
- Use it together with physical scratchcards to give people prizes in a loyalty program.
- Set up a spot at events with several games to entertain guests.
- Add casino-style games to your site, to increase customer engagement.
- Create a buzz at a convention, letting visitors play and win merchandise items (t-shirts and hats, for example). Change the odds heavily so that almost everyone wins.
Features
- 5 designs included, immediately ready to use.
- Fully customizable. You can very easily change the images, sounds, animations, pay table, and prizes to suit your needs.
- Completely responsive to every resolution and device. Works on every browser.
- You can offer either monetary prizes, or physical gifts like hats, t-shirts, or store credit for your site, to improve your brand and keep customers coming back!
- 100% HTML, CSS3 and Javascript code, based on jQuery. Does not use Java or Flash, ensuring compatibility with all mobile devices.
- Smooth jQuery animation.
- Cheat and fraud prevention measures to avoid getting fraudulent complaints from your customers.
- Over 10 million spins to date, resulting in millions of dollars in profits for the different sites that host it. On a monthly average, there's about one spin every 5 seconds.
Package
The package includes the full source code for the entire slot machine, including HTML, CSS, Javascript and PHP code. It also includes extensive documentation on how to implement the slots in your own site, and how to customize every element of it, in case you want to.
Only a very, very basic knowledge of PHP and CSS is necessary to add this to your site. If you don't have your own programmers, or don't feel comfortable doing it, we can do this for you for a fee.
We also offer a custom-design option for an extra fee, in which we get you in contact with our graphics designer, and you get the design that you need, ready to plug into your site.
Buy this slot machine today, or contact us with any questions.
F.A.Q.
- Can I change the icons to my products / company logo?Open or Close
Yes, all the images you see can be directly replaced for anything you would like, by simply changing the files provided.
- Can I customize the odds of winning / the game's payout / my profit margin?Open or Close
Yes, all the probabilities are 100% configurable when setting up the prizes for the game. This is explained in detail in the documentation, including examples to make it as easy as possible.
- Can I use this slot machine in my Wordpress site?Open or Close
Yes, it's quite easy to integrate this into Wordpress by simply modifying the site templates to add the HTML code, and then adding the extra CSS and JS file. Quick and simple!
- Can anyone implement this?Open or Close
A very minimal knowledge of PHP and CSS is needed to implement this on your site. Any junior programmer can do it. Alternatively, you can hire us to do it for you, for a very small additional fee.
- Is it a one-time payment?Open or Close
Yes, a one time payment of the license fee gives you our full source code, and allows you to use the slot machine in as many sites as you own.
- How can I customize this slot machine?Open or Close
You can very easily change everything that your visitors will see about the slot machine. All images and sounds, the pay table configuration, maximum and minimum bets, payouts, the details of the animation, etc. The package you will buy includes extensive documentation on how to modify all of these, and our support team will also be able to help you and answer all your questions.
- Can I have non-monetary payouts?Open or Close
Yes, several of our customers use their slot machine to give out t-shits, hats, store credit, discount codes and more!
- Can monetary payouts have cents?Open or Close
Yes, you can have your payouts in entire dollars, quarters, cents, even Bitcoin fractions if you want.
- Does it work with Bitcoin / Litecoin / other cryptocurrencies?Open or Close
Yes! Basically, you can integrate this with any payment / credits mechanism you can think of, be it regular money, Bitcoin, tokens, anything!
- Do I get the full source code?Open or Close
You get absolutely everything, in full un-minified, non-obfuscated form. All the PHP, HTML, CSS and Javascript, which you can modify as much as you wish, along with extensive documentation on how to do so.
What our previous customers say
'The customers love it'
We installed the slot machine software on our website about six months ago and could not be happier. It was super smooth and we have not had to return to Daniel even once with any problems - in fact not one of our customers has ever reported a problem with a spin which is amazing for a web based game. The integration was a snap and putting our own custom design into the machine was much easier then expected. We could not be happier with the entire experience and our customers love playing every day.
'Huge increase in customer engagement'
From start to finish Daniel was the perfect man for the job. We were setting up a fun virtual games website and communicated a few game ideas to Daniel. The animations were smooth, the games felt fast, and they were able to handle a large number of users.
Our customers were consistently thrilled with the way the games worked, and the games were a big success immediately after launch. In a recent survey 74% of users said the well finished games he programmed contributed 'moderately or significantly' to the fun of the site.
'Only took me about half an hour to integrate.'
I love your coding style, very organized and well documented. Only took me about half an hour to integrate with our systems, works great and our users are LOVING it!
'I highly recommend Daniel's work.'
I found Daniel to be an extremely knowledgeable and reliable developer who helped us integrate his games into our retail platform. Daniel made himself available for our questions and gave assistance whenever we requested.
I highly recommend Daniel's work to anyone who wishes to be successful the first time out. His insight is invaluable.
'Very easy to customize, works in all browsers'
The slot machine is working really well – we haven't had any reports of problems from players, many of which are using tablets / smartphones.
The documentation was great and the code well laid out and self-explanatory making any customisations easy to add into the code..
'Very professional service'
Daniel is a true professional that provides exceptional value. He kept his word on both pricing and beat his estimated delivery time. I definitely will be working with him on projects in the future.