{"id":216,"date":"2011-05-23T20:06:00","date_gmt":"2011-05-23T14:36:00","guid":{"rendered":"http:\/\/odhyan.com\/blog\/?p=216"},"modified":"2017-04-04T15:28:54","modified_gmt":"2017-04-04T09:58:54","slug":"slot-machine-in-javascript","status":"publish","type":"post","link":"https:\/\/odhyan.com\/blog\/2011\/05\/slot-machine-in-javascript\/","title":{"rendered":"Slot machine in Javascript"},"content":{"rendered":"<p>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. <a href=\"http:\/\/www.spritely.net\/\">Spritely<\/a> is a wonderful jquery plugin for background animation. I also used a <a href=\"http:\/\/www.protofunc.com\/scripts\/jquery\/backgroundPosition\/\">plugin for animating background-position<\/a> since jquery does not support it natively. <\/p>\n<p>Lets start building the slot machine. <a href=\"http:\/\/odhyan.com\/slot\/\">Demo here<\/a><\/p>\n<p>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.<\/p>\n<p>The markup is very straightforward. We just need placeholders for 3 slots and a button as controller.<\/p>\n<p>Lets got through the javascript now. First we need a class for a slot. Our 3 slots will be objects of this class.<\/p>\n<pre lang=\"javascript\">\r\nfunction Slot(el, max, step) {\r\n    this.speed = 0; \/\/speed of the slot at any point of time\r\n    this.step = step; \/\/speed will increase at this rate\r\n    this.si = null; \/\/holds setInterval object for the given slot\r\n    this.el = el; \/\/dom element of the slot\r\n    this.maxSpeed = max; \/\/max speed this slot can have\r\n}\r\n<\/pre>\n<p>Why do we need so many paramaters for a slot machine? That&#8217;s because each slot of an ideal slot machine should have different acceleration and speed. Also its good to have different max speeds.<br \/>\nOur Slot class will have 4 member functions: <\/p>\n<ul>\n<li>start() &#8211; starts a slot<\/li>\n<li>stop() &#8211; stops a slot<\/li>\n<li>finalPos() &#8211; finds the final position of the slot when its stopped<\/li>\n<li>reset() &#8211; Resets a slot for another run<\/li>\n<\/ul>\n<p><strong>How it works?<\/strong><\/p>\n<p>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.<\/p>\n<pre lang=\"javascript\">\r\nvar a = new Slot('#slot1', 30, 1),\r\n    b = new Slot('#slot2', 45, 2),\r\n    c = new Slot('#slot3', 70, 3);\r\n<\/pre>\n<p>When a user presses &#8216;Start&#8217;, 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:<\/p>\n<pre lang=\"javascript\">\r\nSlot.prototype.start = function() {\r\n    var _this = this;\r\n    $(_this.el).addClass('motion');\r\n    $(_this.el).spStart();\r\n    _this.si = window.setInterval(function() {\r\n        if(_this.speed < _this.maxSpeed) {\r\n            _this.speed += _this.step;\r\n            $(_this.el).spSpeed(_this.speed);\r\n        }\r\n    }, 100);\r\n};\r\n<\/pre>\n<p>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.<\/p>\n<pre lang=\"javascript\">\r\nSlot.prototype.stop = function() {\r\n    var _this = this,\r\n        limit = 30;\r\n    clearInterval(_this.si);\r\n    _this.si = window.setInterval(function() {\r\n        if(_this.speed > limit) {\r\n            _this.speed -= _this.step;\r\n            $(_this.el).spSpeed(_this.speed);\r\n        }\r\n        if(_this.speed <= limit) {\r\n            _this.finalPos(_this.el);\r\n            $(_this.el).spSpeed(0);\r\n            $(_this.el).spStop();\r\n            clearInterval(_this.si);\r\n            $(_this.el).removeClass('motion');\r\n            _this.speed = 0;\r\n        }\r\n    }, 100);\r\n};\r\n<\/pre>\n<p> 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.<\/p>\n<pre lang=\"javascript\">\r\nSlot.prototype.finalPos = function() {\r\n    var el = this.el,\r\n        pos,\r\n        posMin = 2000000000,\r\n        best,\r\n        bgPos,\r\n        i,\r\n        j,\r\n        k;\r\n\r\n    el_id = $(el).attr('id');\r\n    pos = document.getElementById(el_id).style.backgroundPosition;\r\n    pos = pos.split(' ')[1];\r\n    pos = parseInt(pos, 10);\r\n\r\n    for(i = 0; i < posArr.length; i++) {\r\n        for(j = 0;;j++) {\r\n            k = posArr[i] + (imgHeight * j);\r\n            if(k > pos) {\r\n                if((k - pos) < posMin) {\r\n                    posMin = k - pos;\r\n                    best = k;\r\n                }\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    best += imgHeight + 4;\r\n    bgPos = \"0 \" + best + \"px\";\r\n    $(el).animate({\r\n        backgroundPosition:\"(\" + bgPos + \")\"\r\n    }, {\r\n        duration: 200\r\n    });\r\n};\r\n<\/pre>\n<p><strong>Demo<\/strong><br \/>\n<a href= \"http:\/\/odhyan.com\/slot\/\">You can see the implementation here.<\/a><br \/>\nThe full source code can be viewed at <a href=\"https:\/\/github.com\/odhyan\/slot\">my GitHub repository<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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.&hellip;<\/p>\n <a href=\"https:\/\/odhyan.com\/blog\/2011\/05\/slot-machine-in-javascript\/\" title=\"Slot machine in Javascript\" class=\"entry-more-link\"><span>Read More<\/span> <span class=\"screen-reader-text\">Slot machine in Javascript<\/span><\/a>","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[18,10,21],"class_list":["entry","author-saurabh","post-216","post","type-post","status-publish","format-standard","category-programming","tag-games","tag-javascript","tag-jquery"],"_links":{"self":[{"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/posts\/216","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/comments?post=216"}],"version-history":[{"count":35,"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/posts\/216\/revisions"}],"predecessor-version":[{"id":401,"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/posts\/216\/revisions\/401"}],"wp:attachment":[{"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/media?parent=216"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/categories?post=216"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/odhyan.com\/blog\/wp-json\/wp\/v2\/tags?post=216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}