Slot machine in Javascript

Recently somebody talked to me about creating a slot machine. I looked on the web and could not find any good slot machine implementation in javascript. So I decided to write a quick one. My implementation uses jquery and a couple of jquery plugins for animation. Spritely is a wonderful jquery plugin for background animation. I also used a plugin for animating background-position since jquery does not support it natively.

Lets start building the slot machine. Demo here

First of all we need a sprite for our slot machine. This sprite is basically a reel which in motion simulates a slot. Its preferable to have blurred copy of this reel too, to show the effect of motion. For the purpose of this demo I got the sprite from internet.

The markup is very straightforward. We just need placeholders for 3 slots and a button as controller.

Lets got through the javascript now. First we need a class for a slot. Our 3 slots will be objects of this class.

function Slot(el, max, step) {
    this.speed = 0; //speed of the slot at any point of time
    this.step = step; //speed will increase at this rate
    this.si = null; //holds setInterval object for the given slot
    this.el = el; //dom element of the slot
    this.maxSpeed = max; //max speed this slot can have
}

Why do we need so many paramaters for a slot machine? That’s because each slot of an ideal slot machine should have different acceleration and speed. Also its good to have different max speeds.
Our Slot class will have 4 member functions:

  • start() – starts a slot
  • stop() – stops a slot
  • finalPos() – finds the final position of the slot when its stopped
  • reset() – Resets a slot for another run

How it works?

Initially we create an object for each slot of the slot machine. We pass different values for the max-speed and speed-stepper to the constructor.

var a = new Slot('#slot1', 30, 1),
    b = new Slot('#slot2', 45, 2),
    c = new Slot('#slot3', 70, 3);

When a user presses ‘Start’, start method is called for each slot. This method kicks off the slot and increments the speed at regular intervals. This can be done using setInterval. Code below:

Slot.prototype.start = function() {
    var _this = this;
    $(_this.el).addClass('motion');
    $(_this.el).spStart();
    _this.si = window.setInterval(function() {
        if(_this.speed < _this.maxSpeed) {
            _this.speed += _this.step;
            $(_this.el).spSpeed(_this.speed);
        }
    }, 100);
};

Once all the slots reach their maximum speeds, the ‘Stop’ button is enabled. When the user presses ‘Stop’, the speed of the slots start decrementing.

Slot.prototype.stop = function() {
    var _this = this,
        limit = 30;
    clearInterval(_this.si);
    _this.si = window.setInterval(function() {
        if(_this.speed > limit) {
            _this.speed -= _this.step;
            $(_this.el).spSpeed(_this.speed);
        }
        if(_this.speed <= limit) {
            _this.finalPos(_this.el);
            $(_this.el).spSpeed(0);
            $(_this.el).spStop();
            clearInterval(_this.si);
            $(_this.el).removeClass('motion');
            _this.speed = 0;
        }
    }, 100);
};

Once the speed comes below a certain threshold, the final position is calculated for each of the slots based on their current position and the slots are rotated to reach the final position.

Slot.prototype.finalPos = function() {
    var el = this.el,
        pos,
        posMin = 2000000000,
        best,
        bgPos,
        i,
        j,
        k;
 
    el_id = $(el).attr('id');
    pos = document.getElementById(el_id).style.backgroundPosition;
    pos = pos.split(' ')[1];
    pos = parseInt(pos, 10);
 
    for(i = 0; i < posArr.length; i++) {
        for(j = 0;;j++) {
            k = posArr[i] + (imgHeight * j);
            if(k > pos) {
                if((k - pos) < posMin) {
                    posMin = k - pos;
                    best = k;
                }
                break;
            }
        }
    }
 
    best += imgHeight + 4;
    bgPos = "0 " + best + "px";
    $(el).animate({
        backgroundPosition:"(" + bgPos + ")"
    }, {
        duration: 200
    });
};

Demo
You can see the implementation here.
The full source code can be viewed at my GitHub repository

64 Comments on "Slot machine in Javascript"


  1. hello……I am currently trying to teach myself javascript…or some sort of programming……..I thought this was really cool what you made…..u have any tips of where or how to start….I bought some books so i am currently reading those….and trying to write scripts as i go along
    By the way how long did it take you to write out all the scripting for this page?

    Reply


  2. Hi Saurabh,

    Nice work there, actually I’m planning to use your Javascript Slot Machine but with a bit modification, is it possible to predetermine the winner? I mean I can set when will be the winning combination will occur.

    Like people will have 3 tries to play this but my App will be the one to decide when the winning combination will occur?

    Please provide me an info how to do so and which part of the code need to make some changes as I don’t want to mess up the totality of your work.

    Thanks!

    Reply

    1. Hi Herz and Saurabh,

      did you have found a solution to know the result of the position of each slot beacause i have the same question than Herz.

      thanks

      Reply

  3. Does it ever win though? I played it about 100 times and couldn’t win… 🙁

    Its really cool though – just wish I had a more relevant site to add it to. To the commetor who queried if it worked in Firefox – it worked fine for me every time.

    Reply

    1. I never wrote it as an actual game. My intention was to show a way to implement the slot machine in javascript. So all the combinations of the slots are evenly distributed. You can add some tweaks to increase the chances of winning.

      Reply

      1. Are you (Saurabh Odhyan) available for hire for a simple project?

        If yes email me and I will tell you about it, it should be simpler than your slot machine.

        Reply

  4. Hi Saurabh,
    Awesome script – I would be happy to use it in a small gig I am putting up for a team game for my colleagues – is there a chance you are willing to help me here and provide me with 3 winning scenarios (and one loosing 🙂 ) for some $$$? I wish i had the brains to do it myself but I am sure you are the best man for the job plus I am always happy to donate for open source work 🙂

    Best,
    Ariel

    Reply


  5. Hi Saurabh, Can you please provide a little more details as to how you can increase the odds of winning? Thanks for this tutorial.

    Reply

    1. Decrease the number of images used. I’ve tried seven various images (apples, etc), 1 wild and 1 scatter, for a total of nine, and it keeps the player playing without ‘running out of money’. (unless they are truly ‘unlucky’ 😉

      Reply

      1. Hi Jerry,
        I tried reducing the number of images, but am not having any luck in increasing the chances of winning.,

        Also, when the images reach their final position, I take a look at the elements, and I see things like this:

        My question is – how does the number 10996 relate to the image? My image that shows up with that background position is in the array at 0, 237, 454, 696, 913, and 1157 (as you can see, putting one image in so many spots was my attempt to increase chances of winning, but it seems to make no difference). Any advice from you or Saurabh would be greatly appreciated.

        Reply

        1. Try (google) “Stacked Images”. That is, load 3 or 4 of each image into each slot. Then, randomize a key and sort. At times, one image will be repeated within a/any slot, sometimes 4 in a row. Just remember, if they win, multiple lines will have to be computed.

          Reply


  6. Hi! This is a nice tutorial!
    However I can’t find how to modify the results. Could you please enlighten me on that?
    Thank you.

    Reply

  7. How effective is javascript if we want to develop a facebook social game like farmville,slotomania etc

    We have started a new start up Clipinmedia focused on developing facebook social games for clients.Our next project is to develop a social game like https://apps.facebook.com/slotomania/ ( it’s developed in flash + PHP ) max numbers of games on facebook are made using flash.But as browser games can also be developed using javascript as this slot’s game https://apps.facebook.com/nonstop_casino (is developed using javascript + PHP)

    second game (javascript+php game) is less attractive as far as graphics are concenred but it’s providing almost same gameplay experience as of other flash games.

    Would you like to share your opinion in case we don’t need highly attractive gameplay will this ( Javascript + PHP ) model will work what problems can come into play at later stages.Or javacript will be perfectly fine to work with.

    Reply

  8. Hi,This is a nice tutorial!

    But when you leave machine to roll after some time you will find all slot image is disappear.

    Reply

  9. Can u tell your logic here…?

    Slot.prototype.finalPos = function() {
    var el = this.el,
    pos,
    posMin = 2000000000,
    best,
    bgPos,
    i,
    j,
    k;

    el_id = $(el).attr(‘id’);
    pos = document.getElementById(el_id).style.backgroundPosition;
    pos = pos.split(‘ ‘)[1];
    pos = parseInt(pos, 10);

    for(i = 0; i pos) {
    if((k – pos) < posMin) {
    posMin = k – pos;
    best = k;
    }
    break;
    }
    }
    }

    best += imgHeight + 4;
    bgPos = "0 " + best + "px";
    $(el).animate({
    backgroundPosition:"(" + bgPos + ")"
    }, {
    duration: 200
    });
    };

    Reply

  10. Hi, Saurabh!

    Nice looking slot machine motion.
    Unfortunately, when I try to use your HTML and scripts on my local machine to play around with the code, it does not work: It’s only showing three white squares, no background image at all …

    How can I solve this and get this nice thing running? 🙂

    Thanks

    CK

    Reply

  11. Hello Saurabh,

    I am trying to replace some of the images in the strips of images (normal/blurred) and was wondering if you’d tell me what program/filter you used to get the blurred effect?

    Thanks

    Reply

    1. I used the filter “Motion Blur” in Photoshop, worked perfect. Other software like Gimp or PhotoImpact have this filter, too. 🙂

      Reply

  12. Javascript/CSS based 5 reel slot. My approach was to use the DIV element for the reels. For each spin, randomize x number of images and replace the contents of each reel with the image objects (contained within their own div). Spinning animation was accomplished using a timer (setinterval), and the reels “spun” by inserting the lastChild before the firstChild, and then removing the lastChild. Each reel has a different timer event with a different millisecond setting, and each reel is clearInterval(ed) after each slot replacement. The reels are stopped sequencially left to right by maintaining a “loop count”.

    Works the same in all browsers. I’ll have it up and public soon. I hope this approach stirs some of the fog regarding animation and javascript.

    Reply

  13. anyone figure out how to determine when it wins? like for example win on 3rd pull? please tell how it’s modified to do that.

    Reply

  14. also, how can i make a wild card, or make it so 2 of a kind wins?
    i tried editing the codes and adding more entries to that win array, but the slot machine stopped working.

    when i say wild card, i mean anytime 1 of a certain one appears in any column, then it’s a win. for example, let’s say the number 7 is a wildcard. if a 7 appears once, twice, or three times, then it’s a win.

    Reply

    1. @leo. Therein lies the problem, and it is solved through logic implemented in javascript. You must examine each slot within each reel, one “winning combination” at a time. “lots of code” but very doable. I’m working on one now in order to complete my slot machine, and will post my findings here.
      I’m also trying to implement this blogs solution to achieve a better ‘spinning effect’.
      Lots of good discusstion here. Please keep it going. Animation in Javascript is the only way we will all move away from Flash.

      Reply

      1. so far …
        I grab the image.src to compare those images in the 5reels*3slots view. (note: my machine has only 9 winning lines, but has wild cards and ‘scatter’ wins. 1 wild and 1 scatter per reel. (the difference is wild is wild for all images except scatter. scatter is a win regardless of line or reel.)
        Starting with reel 9 combination, I compare the src of reel1 to reel2, and if there is a match (or a wild), I continue to reel3. If a match is found on reel3, we have a winning line, and I display the line9 graphic, and continue to line4 and line5 to determine the amount won. I then do the same for line 8, through line 1. After that I search for “scatters”. Once the sum of ‘winnings’ is determined, I display the amount and roll it into the players holdings.

        Reply

  15. Hi, Has anyone fixed the problem for Firefox ?! The background iamge simply disapeare at certain point. The problem seems to be in the Spritely plugin here … Help please

    Reply

  16. Saurabh:

    *Excellent* tutorial – this is exactly what I needed for a cute project I was working on for my blog (see the result here: http://unsolicited.elementfx.com/OSM/OSM.html – and, you’re credited 😉

    Unfortunately, I have the same problem as Chaara and Loki – after one spin, the 1st symbol turns “white” and does not display on subsequent spins. While I have some programming experience (sadly, from 1974!), I’m not Javascript savvy: Is there a solution to this?

    Thanks again! The MUSEman

    Reply

  17. Saurabh:

    I think I found the problem: If I start the game before the page loads completely (ie: before every element loads, including ads & trackers) I have the problem. If I wait for the page to completely load, no problem 😉

    Thanks again… well done!

    Reply

  18. Interesting approach. Actual slot machines use virtual reels, and the physical reels you see are just an animation for the shill to look at that displays the final, predetermined result (the virtual reels take the result based on an extremely large random number, and do not necessarily have the same amount of each symbols virtual representation as shown on the physical wheel). You could take an extremely large number, run it against a set of extremely large tables (the virtual reels), then animate it to show the calculated result. More code, but smaller images.

    Reply

  19. Just a completely different answer here:

    Do u need a licence to run this script as a gambling machine ? Imagine that I am not charging user to play it or to join the site, but they can get points if they win, and with those points they can buy images as prizes, or similar .. even more they can upgrade their account if they have x points ?! Otherwise, upgrading costs money ..

    I am just trying to guess the scenario where it could be ilegal!

    Reply

  20. For those puzzled about what is going on in finalPos… I think the nested loops [for(i=0 …] can be replaced with this code (maybe a bit more comprehensive):

    var relativePos = pos % imgHeight;
    var imgBasePos = pos – relativePos;
    for(i=posArr.length-1;i>=0;i–) {
    if(posArr[i] < relativePos) {
    best = imgBasePos + posArr[i];
    this.pos = posArr[i];
    break;
    }
    }

    @Saurabh: Thanks a lot for sharing this cool slot machine script, I really appreciate that… Just a suggestion: the use of more meaningful variable names would be helpful for understanding (or at least additional comments), especially within finalPos (e.g. k, posMin, best).

    Thanks for sharing this!

    Reply

  21. Just found out that posArr is not correctly commented with the symbols. It makes no difference for this example (since the actual symbol does not matter here), but may be confusing when working with the code.

    Changed posArr declaration to:
    posArr = [ // positions on reel image, pixel offset from bottom(!)
    80, // 0 cherry
    165, // 1 banana
    237, // 2 guava
    310, // 3 bar
    378, // 4 number7
    454, // 5 orange
    539, // 6 cherry
    624, // 7 banana
    696, // 8 guava
    769, // 9 bar
    837, // 10 number7
    913, // 11 orange
    1000, // 12 cherry
    1085, // 13 banana
    1157, // 14 guava
    1230, // 15 bar
    1298, // 16 number 7
    1374 // 17 orange
    ];

    btw: I think the guava is rather a pear 😉

    Reply

  22. Firstly Thank you for this excellent Slots Script!

    I am trying to customise it so that this.pos is set to a specific pixel location as not all of my icons are the same (for example s1:’W’, s2:’I’, s3:’N’)

    Your script uses a function to locate the best final position based on how close the icon is.

    this is my modified function:

    for(i = 0; i pos) {
    if((k – pos) < posMin) {
    posMin = k – pos;
    best = k;
    this.pos = winspin[i]; //update the final position of the slot
    }
    break;

    }
    }
    }

    I want each slot to stop at the array positions ie:

    winFifty = new Array(3923, 1878, 436);

    Which equates to

    winFifty = new Array(£, 5, 0);

    Any help you could provide would be greatly appreciated!?

    Kind regards,

    Phil.

    Reply

  23. This is great, your example works beautifully and your explanation is clear. Glad you hosted it at GitHub too. Very helpful.

    Reply

  24. If you don’t want an immediate focused to blurred image, add this to your stylesheet for the .slot div:

    -webkit-transition: background-image 1.7s ease-in-out;
    -moz-transition: background-image 1.7s ease-in-out;
    -ms-transition: background-image 1.7s ease-in-out;
    -o-transition: background-image 1.7s ease-in-out;
    transition: background-image 1.7s ease-in-out;

    Currently, the backround-image doesn’t work on firefox. Progressive enhancement 🙂

    Reply

  25. Hello,
    How do I make the script to always gave the same results, or that I could ask what the script outputs the result?

    Reply

  26. Awesome. I came across this on google as I want to make a slotmachine implementation myself. I tried a few times and I was actually a winner. Great post!

    Reply

  27. Нello there, You have done an incredible jоb.
    I’ll definitely digg it annd persоnally recommend to my friends.
    I’m cojfident they’ll be benefited from this site.

    Reply

  28. Hey there! Do you ҝnow іf tһeү make аny
    plugins tto protect against hackers? I’m kinda рaranoid about losing everything I’ve worked hard on.
    Any recommendations?

    Reply

  29. Hi there! Do you know if they make any plugins to help
    with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not
    seeing very good results. If you know of any please share.
    Kudos!

    Reply

  30. Is there a way to add sound to this? Like when it spins, there will be a spinning sound effect? I’ve tried using the usual JS way to add it but it doesn’t work.

    Reply

Leave a Reply

Your email address will not be published.