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

60 comments

  1. Tushar says:

    very cool!

  2. 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?

  3. [...] machine ที่ผมจะนำมาเสนอ ผมเอาของ Saurabh Odhyan’s Blog มา Implement [...]

  4. Kartik Rao says:

    Just brilliant! Thanks.

  5. Herz says:

    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!

  6. Loki says:

    I found out an error on firefox there, after start for awhile all 3 slot turn into blanks slot.

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

    • Saurabh says:

      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.

  8. Ariel says:

    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

  9. [...] Slot machine in Javascript Our Slot class will have 4 member functions: start() – starts a slot 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. [...]

  10. Chris says:

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

    • Jerry says:

      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’ ;)

      • Mark says:

        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.

  11. LUCAS says:

    Hi, I invite you to play my slot beer game: http://www.cervejadasorte.com.br !!! just login facebook, it’s all FREE !

  12. [...] use of TypeKit (font used in the logo).  The spinning effect is based on a blog post I found by Saurabh Odhyan.  He basically pans an image across a div using JQuery.spritely.  Once the speed increases, the [...]

  13. sh1981 says:

    This whole casino is javascript I think
    http://www.social-casino.co.uk

  14. minoaye says:

    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.

  15. james constantino says:

    im using your slots program in my facebook app. kudos!

  16. Aaron says:

    has anyone tried making 5 reels instead of 3?

  17. Mohit says:

    Hi,This is a nice tutorial!

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

  18. Mohit says:

    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
    });
    };

  19. Hey there! I understand this is somewhat off-topic but I had to ask. Does running a well-established website like yours require a large amount of work? I’m completely new to operating a blog but I do write in my diary everyday. I’d like to start a blog so I can easily share my own experience and views online. Please let me know if you have any kind of recommendations or tips for brand new aspiring blog owners. Thankyou!

  20. F*ckin’ awesome issues here. I’m very glad to see your article. Thanks a lot and i am taking a look ahead to contact you. Will you kindly drop me a e-mail?

  21. CK says:

    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

  22. cvr says:

    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

  23. Appreciate it for helping out, fantastic information.

  24. Jerry says:

    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.

  25. leo says:

    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.

  26. leo says:

    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.

    • Jerry says:

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

      • Jerry says:

        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.

  27. Chaara says:

    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

  28. donna says:

    Hi is it possible to stop the slot automatically? Thanks! :)

  29. The MUSEman says:

    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

  30. The MUSEman says:

    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!

  31. OCBujinkan says:

    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.

  32. jobag says:

    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!

  33. I was studying some of your articles on this internet site and I think this web site is rattling informative! Retain putting up.

  34. I delight in, result in I found exactly what I was looking for. You’ve ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  35. Pete says:

    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!

  36. Pete says:

    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 ;-)

  37. mohamed says:

    Hello,
    How to set this to work with new version of jquery like 1.8.2 ?

  38. Vishal Tarkar says:

    How to set all image on same align ? when they stop ?

  39. Phil Glen says:

    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.

Post a comment

Copyright © Saurabh Odhyan's Blog

Built on Notes Blog Core
Powered by WordPress