Gamification is more than just a buzzword—it’s a proven strategy that works. Whether you're building a mobile app or website, everyone and their grandma uses this gamification magic, and your competitors are in on the secret, too. So, what does gamification do, and how do I apply it to your application?
First, gamification can be applied anywhere, even in the real world. Whether hosting an event live, a sports streaming feature, or creating an interactive app, live engagement tools like fan chat, live reaction, trivia, and loyalty points will incentivize users to return for an engaging experience.
So Why Does Gamification Work?
According to the Oxford Online Dictionary:
“Gamification is the practice of making activities more like games to make them more interesting or enjoyable.”
In other terms, gamification uses the concepts of video games and applies them to non-game contexts to render experiences more engaging and rewarding to create more interactive content.
Gamification techniques are everywhere, even in the physical world, to increase user interactions and retention. Examples of gamified apps: If you're a Starbucks customer and you earn "stars" toward a free meal or drink, you're playing a game designed to get you to purchase more. Another great example is Duolingo, where points, streaks, and badges are awarded for daily language learning—turning the learning experience or learning process into an addictive one by making you feel a sense of accomplishment.
The Power of Real-time Interactivity
Developing these real-time experiences isn't merely a matter of including a real-time leaderboard or some kind of interactive quest in your application—it's about real-time engagement that forms user incentives and brings them back to your app.
These gamified features only work if they are done in real-time. Slowed-down interactions destroy momentum, increasing the churn rate and ruining your user experience. Worry not—PubNub is here for your app development!
Building a Real-time Gamified Experience
Now that you understand the importance of adding gamified elements to your app, let’s explore how to build these features. Whether you want to implement live chat, reactions, polls, or a rewards program, you will need a system that can effectively handle real-time updates.
So, let’s add gamification elements to our app using our PubNub SDKs.
Setting Up The Communication Layer
We will need a real-time messaging layer to handle instant updates. This ensures that all interactions, such as poll votes, chat messages, or reward notifications, reach all users immediately.
This is the most critical stage—it provides the foundation for a smooth and immersive gamified experience. With no real-time updates, the interactions are no longer exciting, and people lose interest.
JavaScript (Web)
Install Dependencies
npm install pubnub
Initialize the Messaging Client
import PubNub from 'pubnub';
const pubnub = new PubNub({
publishKey: 'your-publish-key',
subscribeKey: 'your-subscribe-key',
userId: 'user-unique-id',
});
Kotlin (Android)
If you are creating an application in Kotlin, choose which dependency installation makes sense for your project.
Use Gradle (Android Studio Projects)
implementation 'com.pubnub:pubnub-kotlin:10.4.1'
Initialize the Messaging Client
import com.pubnub.api.v2.PNConfiguration
import com.pubnub.api.PubNub
import com.pubnub.api.UserId
val config = PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "your-publish-key"
subscribeKey = "your-subscribe-key"
}.build()
val pubnub = PubNub(config)
Swift (IOS)
If you are creating an application in Swift, choose which dependency installation makes sense for your project.
Use Swift Package Manager In your Package.swift file, add the following dependency:
import com.pubnub.api.v2.PNConfiguration
import com.pubnub.api.PubNub
import com.pubnub.api.UserId
val config = PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "your-publish-key"
subscribeKey = "your-subscribe-key"
}.build()
val pubnub = PubNub(config)
Use CocoaPods Ensure you have the latest CocoaPods installed:
gem install cocoapods
gem update cocoapods
Add PubNub to your Podfile:
pod 'PubNubSwift', '~> 8.3.1'
Use Carthage Add the following to your Cartfile:
github "pubnub/swift" ~> 8.3.1
Initialize Messaging Client (Swift) Import & configure PubNub in AppDelegate (Check implementation below for multiple scenes, IOS 13+)
import UIKit
import PubNub
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var pubnub: PubNub!
var window: UIWindow?
func application(
_ application: UIApplication,
willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
) -> Bool {
let config = PubNubConfiguration(
publishKey: "your-publish-key",
subscribeKey: "your-subscribe-key",
userId: "userId"
)
pubnub = PubNub(configuration: config)
return true
}
}
Initialize Messaging Client For Multiple Scenes (IOS 13+) Modify SceneDelegate.swift to pass PubNub to the view controllers:
import UIKit
import PubNub
@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var pubnub: PubNub?
func scene(
_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions
) {
let config = PubNubConfiguration(
publishKey: "your-publish-key",
subscribeKey: "your-subscribe-key",
userId: "userId"
)
pubnub = PubNub(configuration: config)
}
}
Bringing Gamification to Life
Where gamification is involved, you have a lot of freedom, and with PubNub, we get to let these ideas run wild. The game elements you choose to include in your application don’t necessarily have to feel like games. For instance, gamification can be as simple as an onboarding procedure that walks you through a progress indicator and a reward, such as access to more features in your application.
In this blog, we will walk you through one example of gamification: creating a live leaderboard that lets users track their high scores. The use case will be in a live event application where users answer trivia questions about their favourite sports team. The leaderboard will rank who got the most questions right, and users will receive live updates about their independent scores and rewards for participating in the trivia.
How it will work: Users will earn points by answering questions during a game or live event. Scores update instantly, ensuring everyone sees changes as they happen The leaderboard dynamically ranks players, motivating them to stay engaged
Let’s break it down step-by-step.
Step 1: Broadcasting Score Updates in Real Time
The first thing in creating a live leaderboard is to ensure that every time a player gains points, his or her score gets updated and streamed in real-time to other users on your application.
We achieve this by publishing messages to the “leaderboard” channel, which we will subscribe to using a PubNub Function later in the blog.
How It Works: Each time a user earns points, we publish an updated score request The message published will contain the user’s ID and their new score
async function updateScore(userId, newScore) {
try {
const response = await pubnub.publish({
message: { username: userId, score: newScore },
channel: "leaderboard",
storeInHistory: true,
});
console.log("Score published:", response);
} catch (error) {
console.error("Error publishing score:", error);
}
}
// Example: A player earns 50 points
updateScore("player123", 50);
Every score update is broadcast to every User / PubNub Function who is subscribed to the “leaderboard” channel.
Step 2: Subscribing to Leaderboard Updates
To ensure real-time rankings, all users should dynamically listen for new scores, and the UI should reflect that. To do this, we’ll create a subscriptionset that will allow us to handle multiple event types that PubNub supports efficiently.
Below, I will include all the different event types that PubNub supports. For this demo, we will utilize the OnMessage to deliver the leaderboard ranks as a “Message.” For another example of gamification, you might use PubNub Signals (for smaller messages), utilizing the OnSignal event listener for live reactions.
JavaScript (Web)
Let leaderboard = [];
const subscriptionSet = pubnub.subscriptionSet({
channels: ["leaderboard_scores"]
});
subscriptionSet.subscribe();
subscriptionSet.onMessage = (event) => {
try {
leaderboard = event.message.username.map((user, index) => ({
userId: user,
steps: parseFloat(event.message.score[index]) || 0
}));
} catch (e) {
console.error("Error processing leaderboard update:", e);
}
updateLeaderboard();
}
Check out other listeners that might be helpful for your application below.
subscriptionSet.onPresence = (presenceEvent) => {
console.log("Presence event: ", presenceEvent);
};
subscriptionSet.onSignal = (signalEvent) => {
console.log("Signal event: ", signalEvent);
};
subscriptionSet.onObjects = (objectsEvent) => {
console.log("Objects event: ", objectsEvent);
};
subscriptionSet.onMessageAction = (messageActionEvent) => {
console.log("Message Reaction event: ", messageActionEvent);
};
subscriptionSet.onFile = (fileEvent) => {
console.log("File event: ", fileEvent);
};
Step 3: Storing Scores with PubNub Functions
A leaderboard in real-time is wonderful, but what happens when users reload or close the application? We need a way of persisting scores. Instead of using App Context, we can cache scores using PubNub Functions via KV Store to dynamically update player scores.
We will use PubNub Functions with the KV Store to keep the leaderboard data persistent. This will allow us to dynamically store, retrieve and update a user's score without relying on an external database.
Create a PubNub Function
Navigate to the PubNub Admin Portal
Go to Functions → Select “Create Package”
Name the Function and select the event type “Before Publish on Fire”
Name the channel you would want the function to watch for events (messages) on. In this case, we will use the channel “leaderboard”
Copy and paste the code shown below in the Functions editor
Click “Deploy” Function and specify the keyset you would like to deploy your function under
Add KV Store for Persistent Storage
Use db.get(“leaderboard”) to retrieve stored scores
Use db.set(“leaderboard”, updated data) to persist new scores
export default async (request) => {
const db = require("kvstore");
const pubnub = require("pubnub");
const { username, score } = request.message;
// Fetch existing leaderboard or initialize an empty one
// db.removeItem("leaderboard");
let leaderboard = await db.get("leaderboard") || { username: [], score: [] };
// Ensure leaderboard structure is correct
if (!Array.isArray(leaderboard.username) || !Array.isArray(leaderboard.score)) {
leaderboard = { username: [], score: [] };
}
// If username is null or undefined, just publish the existing leaderboard
if (!username) {
await pubnub.publish({
channel: "leaderboard_scores",
message: leaderboard
});
return request.ok();
}
const newScore = parseFloat(score);
// Insert new score in sorted order
for (let i = 0; i <= leaderboard.score.length; i++) {
if (i === leaderboard.score.length || newScore > parseFloat(leaderboard.score[i])) {
leaderboard.score.splice(i, 0, score);
leaderboard.username.splice(i, 0, username);
break;
}
}
// Trim leaderboard to top 10 entries
leaderboard.score = leaderboard.score.slice(0, 10);
leaderboard.username = leaderboard.username.slice(0, 10);
await db.set("leaderboard", leaderboard);
await pubnub.publish({
channel: "leaderboard_scores",
message: leaderboard
});
return request.ok();
};
Step 4: Displayer the Live Leaderboard
Now that we’ve successfully set up real-time score broadcasting, subscription handling, and persistent storage with PubNub Functions, the final step is to fetch the initial leaderboard.
To achieve this, we can publish a message to the PubNub Function, which will publish a message back on “leaderboard_scores”. Above, we have created a “subscriptionset” subscribing to channel “leaderboard_scores” to receive the leaderboard data.
async function fetchInitialLeaderboard() {
try {
await pubnub.publish({
channel: "leaderboard",
message: {
score: [0]
}
});
} catch (error) {
console.error("Error fetching initial leaderboard:", error);
}
}
Enhancing Gamification with AppContext
We have built a real-time leaderboard with PubNub Functions utilizing the KV store for persistent storage. What if we wanted to take gamification even further? This is where AppContext come into play.
Using AppContext for Persistent Player Storage
While the KV Store is ideal for storing and updating data like leaderboard ranks, App Context is designed to store player metadata across sessions.
For example, instead of only showing the highest leaderboard scores, you could personalize your application to display a player’s all-time ranking, achievements, and progress toward the next reward level. Personalization through player profiles creates a good customer experience as users are motivated and engaged even if they are not ranked on the leaderboard. In other words, think of AppContext as storing and retrieving player profiles instead of the highest scores of all players, as that is what we used the KV store for.
So what does this look like?
First, we need to enable App Context on our keyset like such:
We can now make a new function to save your score to a profile that can be retrieved later, utilizing App Context.
// Function to upload user's score to App Context
async function uploadUserScore(userId, score) {
try {
await pubnub.objects.setUUIDMetadata({
uuid: userId, // Set the user's UUID as their name
data: {
name: userId,
custom: {score}
}
});
console.log(`Successfully updated steps for ${userId}: ${score}`);
} catch (error) {
console.error("Error uploading user score to App Context:", error);
}
}
To retrieve the initial score, we can use the function “getUUIDMetadata ” specifying a uuid for the user for which we want to retrieve a score for. When we navigate to BizOps Workspace, the management console for AppContext, we should now see the score or, in this case, steps uploaded.
Repurposing PubNub Demos for Gamification
PubNub offers many demos that are very quickly supported in the context of gamifying your sports media & entertainment app. Whether you are working on fan engagement, financial awards, or interactive leaderboards, these demos provide a solution to integrate real-time gamification features.
Demo
Use Case for Gamification
Fan chat for sports, concerts, or esports events, complete with live reactions and polls.
Instant updates on leaderboard changes, reward system.
In-game chat with team-based interactions, challenges, and real-time engagement to boost social interaction.
Gamify financial apps with loyalty rewards, spending challenges, and cashback leaderboards.
Ready to Gamify Your App?
Gamification isn’t just a trend—it’s a powerful tool that works. By incorporating game design, game mechanics, and game-like elements, you can create interactive experiences that captivate user engagement, creating user motivation for them to keep coming back. Whether you are building a live event, sports, or interactive website, leveraging real-time interactivity ensures users stay engaged, charged, and immersed in the experience. Combining active rewards, challenges, and competition turns passive interaction into an interactive experience that builds a stronger connection between your application and your users.
By leveraging PubNub’s real-time capabilities, whether with our SDKs, PubNub Functions, and AppContext, you can add features such as live leaderboards, rewards, real-time chat, or interactive challenges without worrying about infrastructure or scale.
Get Started Today
How can PubNub help you?
This article was originally published on PubNub.com
Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.
The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.
Experience PubNub
Check out Live Tour to understand the essential concepts behind every PubNub-powered app in less than 5 minutes
Get Setup
Sign up for a PubNub account for immediate access to PubNub keys for free
Get Started
The PubNub docs will get you up and running, regardless of your use case or SDK
Top comments (0)