IN THIS ARTICLE
Subscribe to Our Newsletter
We love games at PubNub. So when I was presented with the opportunity to make whatever I wanted at the PubNub Hackathon, I knew I wanted to make a fun game with a single input. Inspired by the “boring” Android game Toilet Paper Man, I wanted my game to be both multiplayer and dead simple. As a result, TrackPad Destroyer was born. The game is simple. Two players scroll their trackpads as fast as possible before the timer counts down to zero. Whoever scrolls more pixels wins.
That’s it. You’ll soon find out that your trackpad isn’t the only thing that’ll get destroyed:
You can check out the Github Repository here, and I’ll walk you through the code below.
clearTimeout to implement the countdown timer. There are two variables to record the time left.
seconds represents seconds left and
millisec represents tenths of seconds left. The frequency of the update is a tenth of a second, so I set the 100 milliseconds interval to
setTimeout. One thing to mention is that the callback of
setTimeout will only execute once, which means that you need to call
setTimeout inside your callback to keep it working. The callback here is
display(). It updates time left and pixels scrolled by both you and your opponent. When time is due,
clearTimeout is called to stop the timer and pixels scrolled are compared to check who won.
join(‘’’) to concatenate into a string and then render.
On Your Mark, Get Set, Go!
window.scrollTop() to get the offset to the top of the window, and use an anonymous function that updates pixels scrolled as the scroll event handler.
So how do we make it multiplayer and keep both screens synchronized? Use PubNub! Here’s how:
First, initialize pubnub with pub_key and sub_key. You’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub keys in the PubNub Developer Portal. Once you have, clone the GitHub repository, and enter your unique PubNub keys on the PubNub initialization, for example:
publish to publish messages to channel. Here, I publish the pixels scrolled.
subscribe to receive pixels scrolled by your competitors.
That’s it. Now we have a multiplayer game with dead simple input. Have fun!