P5 Js Slot Machine

Slot machine using p5.js - Duration: 0:20. Eric Gee 355 views. How to create slot game 3x5 all lines Modern Suits Slot Asset for Unity Asset Store - Duration: 10:44.

by Allison Parrish

This tutorial will take you through the steps necessary to create your firstp5.js sketch and upload it to the Internet.

What is p5.js?

p5.js is a library and set of tools that make it easy to use the JavaScriptprogramming language for creative coding. It’s based onProcessing, a creative coding environment originallydeveloped by Ben Fry and Casey Reas. One of the primary goals of Processing(and projects based on Processing) is to make it as easy as possible forbeginners to learn how to program interactive, graphical applications (whilealso providing powerful tools for experts).

The advantage of using the JavaScript programming language is its broadavailability and ubiquitous support: every web browser has a JavaScriptinterpreter built-in, which means that p5.js programs can (generally) run inany web browser. Additionally, the JavaScript language is defined by aninternational standard and mostJavaScript interpreters (including those that run inside of web browsers), areopen-source and freely available. No one “owns” JavaScript, and anyone can useit for free.

Another important idea from Processing is that it should be easy forprogrammers to create software prototypes very quickly, to try out a new ideaor see if something works. For this reason, Processing (and p5.js) programs aregenerally referred to as “sketches.” We’ll use this nomenclature in this class.

What software to use

There are a number of ways to write p5.js sketches. Because p5.js is just aJavaScript library under the hood, you can include it in any regular web page,and even use it in conjunction with other JavaScript libraries. The officialtutorial suggests downloading a separate texteditor (like Brackets or Atom)and working with your p5.js source code just like any other programminglanguage. Which is fine!

In this class, however, we’re going to use the p5.jsweb editor, a web-based programming environmentspecifically built for p5.js. It should work in nearly any web browser!

Anatomy of the web editor

When you load the web editor, you can get started right away. But I recommendmaking an account, which will allow you to save your work and share it withother people. Here’s what the web editor looks like and an explanation of theimportant moving parts. (There are other features of the web editor interfacethat we’ll discuss later. Also note that as of this writing the web editor isunder heavy development and the way it looks when you read this might bedifferent from how it looks in the image below.)

  1. The “code” pane. This is where you type your p5.js code.
  2. The “console” pane. This is where error messages from your code show up. youcan also use the console.log() function to make text appear here whileyour program is running. (This is helpful for debugging purposes, and we’lldiscuss it more later!)
  3. The “preview” pane. Your sketch will show up here!
  4. Controls. Press the “Play” button (▶) to “run” your sketch. Press “Stop”(⬛︎) to terminate the sketch.
  5. The name of your sketch. Click the little pencil icon to the right of thename to edit it. (When you create a new sketch, a random name is generatedfor you. The web editor uses this library to generate thenames, if you’recurious!)

Your first sketch

Okay, the preliminaries are out of the way! Let’s get a-programmin’. Copy thesource code from the example below (on the left-hand side) and paste it intoyour p5.js editor. Press the “Play” button; a window will open, and you shouldsee something that looks like what you see on the right-hand side below.

Congratulations! You’ve made a simple computer program.

So what’s going on here?

You made a computer program, but what exactly happened? Here’s a littlebreakdown (simplifying a little):

  • ellipse(50, 50, 60, 60); is an example of a function call. p5.js comeswith several dozen built-in “functions” that perform various tasks, likedrawing shapes to the screen or calculating values using mathematicalformulas. Learning how to program in p5.js is mostly about learning thesecommands and what they do. The ellipse function, in case you hadn’tguessed, draws an ellipse to the screen.
  • ellipse is the function’s name. Functions are always followed by a pairof parentheses; inside these parentheses are a comma-separated list ofvalues. These values are called the function’s parameters. Every functionuses its parameters in a slightly different way, and part of learning afunction is learning what its parameters mean.
  • In the case of ellipse, the first parameter is the X coordinate of theellipse, the second parameter is the Y coordinate, the third parameter is thewidth of the ellipse and the last parameter is the height of the ellipse.
  • The function call ends with the semicolon (;). You should put a semicolonat the end of every function call.
  • You can put as many function calls as you want in between the line that readsfunction draw() { and the } that follows it. (We won’t talk about whatfunction draw() means for now, or what the curly braces mean. Just knowthat you can put more stuff in between those curly braces if you want morestuff to happen.)

You can find a big list of p5.js functions in the p5.jsreference. For now, we’re going to focus just onthe most simple functions for drawing shapes to the screen. As the courseprogresses, we’ll learn about other functions that do more interesting things.

Add another shape

This is pretty boring so far. Let’s give our ellipse a friend to play with.

P5 Js Slot Machine Machines

► run sketch◼ stop sketch

The rect() function draws a rectangle to the screen. The parameters to therectangle function have the following meanings:

  • parameter 1: the X position of the rectangle’s upper left-hand corner
  • parameter 2: the Y position of the rectangle’s upper left-hand corner
  • parameter 3: the rectangle’s width
  • parameter 4: the rectangle’s height

Notice that the functions are called in the same order as they’re drawn. Thatmeans that the rectangle gets drawn on top of the ellipse. If you reversedthe order of the commands, the ellipse would be drawn on top instead:

► run sketch◼ stop sketch

Background color

The background() function sets the background color for the entire sketch.Call it first in the draw() block, like so:

► run sketch◼ stop sketch

The background function takes a single parameter, which is a value from 0 to

  1. The value determines the shade of grey that the background will appear. 0means black, and 255 means white; other values refer to all of the interveningshades of grey. For example, use 50 for a nice slate color:
► run sketch◼ stop sketch

Or 240 for a smoky light grey:

► run sketch◼ stop sketch

If you call the background function with three values, you can set thebackground to a color of your choice (not just a shade of grey). The threeparameters correspond to the red, green and blue components of the givencolor. (See the Processing colortutorial for an explanation ofwhy the color is specified with red, green and blue, and why the numbers rangefrom zero to 255.)

A good place to look for color values is Wikipedia’s list ofcolors. Click on anycolor, like Cornflower blue,and you’ll find (in the infoboxes on the right-hand side) the RGB values forthat color. The infobox says that the RGB value for Cornflower blue is (100,149, 237); let’s use those values to make the background of our sketchCornflower blue:

► run sketch◼ stop sketch

Coordinates

By now you’re asking yourself: now that I can set the background of mysketches, they seem awful… small. Can I made it any bigger? Also, thosenumbers in a call to ellipse or rect specify positions and dimensions. Butwhat are the units? If 50 is some shape’s X position, what’s the unit?Meters? Furlongs? Lachters?Spats?No! Distances in Processing are measured in pixels.

Nearly all digital displays are broken up into tiny squares called pixels.Normally, each pixel is itself an actual, tiny, physical device that candisplay a color. The screen on your device right now likely has hundreds ofthousands if not millions of these tiny devices. Each one is exactly the samesize, and together they form a “grid.”

Every p5.js sketch has a size in pixels—the number of pixels wide it is, andthe number of pixels tall. By default, the sketch is 100 pixels by 100 pixels.(Time was that this was a fair number of pixels. The original GameBoy’s display, for example, was160x144 pixels. But in this contemporary era of “retina” displays, it’s notmuch.)

The pixel in the far upper left-hand corner is designated as the pixel atcoordinate 0, 0. As you move further left, the X coordinate increases.As you move further down, the Y coordinate increases, so that the coordinateof the middle of the sketch is 50, 50 and the coordinate at the lowerright-hand corner is 100, 100. (If you’re used to Cartesian coordinates, thisseems weird, since normally the Y value decreases as you move down. Butyou’ll just have to get used to the way Processing does it for the purposes ofthis class.)

For more information and diagrams, see the Processing coordinate systemtutorial.

Change the size of your sketch

Up until now we haven’t talked about that strange function setup() { thing upat the top of the sketch’s source code. Well, let’s talk about it now!There’s one special function that you can put inside of there, calledcreateCanvas(). This function sets the size (in pixels) of your sketch.Let’s take the example above and give it some room to breathe:

► run sketch◼ stop sketch

(Ignore the call to fill(); we’ll discuss it further below.)

Slot

The first parameter to the createCanvas() function specifies the width ofthe sketch, and the second specifies its height (again, in number of pixels).

Now that our canvas is bigger, let’s spread our shapes out a little bit!

► run sketch◼ stop sketch

Fill and stroke

p5.js lets you control not just the shapes that you draw but also two criticalaspects of those shapes’ appearance: what color they are, and what color theiroutline is. You can set the color of a shape with the fill() function.Just as with background(), you can call fill with either one parameter toset its greyscale color, like so:

► run sketch◼ stop sketch

Or you can call it with three values, to set the color using RGB values. Let’stry a nice shade of carmine:

► run sketch◼ stop sketch

Notice that the color in the fill() command applies to every shape that getsdrawn after it’s called. To change the color for subsequent shapes, include asecond call to fill() right before you call the function for the shape whosecolor you want to be different:

► run sketch◼ stop sketch

You can change the color of the outline of the shapes using the stroke()command. Again, like background() and fill(), you can use stroke() eitherto set the greyscale value, or to set an RGB color. Also like fill(), a callto stroke() sets the stroke color for all shapes that follow, unless you callthe stroke() function again:

► run sketch◼ stop sketch

There’s also a function called strokeWeight() which allows you to set thewidth of the stroke. The width is measured in pixels, and like fill() andstroke() it applies to every function called after it:

► run sketch◼ stop sketch

Here’s an example that puts it all together!

► run sketch◼ stop sketch

(Color scheme generated automatically with Coolors. Idon’t advocate this site, it was just the first result when I googled “colorscheme generator”)

Other shapes

Here are some other functions that draw shapes. Each of them works a little bitdifferently from the next, so consult the reference page for information andinstructions.

When something goes wrong

Programming is persnickety work, and it’s easy to get the syntax wrong. (Easyfor beginners especially, since you haven’t quite learned yet how to reasonabout how the syntax works.) If something goes wrong, you’ll get an errormessage. The error message will appear in that little box beneath the sourcecode editing area, called the “console.”

If you can’t find where the problem is, don’t fret! The error message willgive you some hints. The number at the beginning of the errortells you the number of the line that p5.js thinks the problem is on.(Sometimes it’ll be off by a line or two, so you’ll have to hunt around.) Themessage gives you some idea of what the problem is, although the description isfiltered through the weird language of programming language parsers.

This error message shows that there’s a problem on line 2: I accidentallyspelled it crateCanvas instead of createCanvas, and JavaScript is helpfullyinforming me that it has no idea what crateCanvas is. (When JavaScript sayssomething “is not defined,” that’s what it means. JavaScript only knows aboutbuilt-in objects, variables and functions you’ve defined, and variables andfunctions in the libraries you’re using, like those you’re learning about inp5.js.)

Sharing your work

You can share your work right from the web editor. In the web editor’s Filemenu, select Share. You’ll see a dialog box with three different boxes whosecontents you can use to share what you’ve made with other people. Here’s howthey work:

  • Embed: If your blogging software supports it, you can just copy this code andpaste it right into your blog post. (The code is an iframe, which is anHTML tag that tells a browser to show the content from another site in themiddle of whatever page the code occurs in.)
  • Fullscreen: This URL leads to a version of your sketch that only displays theoutput (what we’ve been calling the “preview pane”). The word “fullscreen” issort of a misnomer, since it doesn’t actually take up the full screen unlessyou use your browser’s “Enter Full Screen” function.
  • Edit: This links to your sketch in the web editor. Use this when you want toshare your code with other people.

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'

P5 Js Slot Machine Jackpots

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.

P5 Js Slot Machine Slot

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.'

P5 Slot Machine

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!

P5 Js Slot Machines

'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.