Build a live leaderboard with Preact
You will need Node 6+ installed on your machine. A basic knowledge of JavaScript (ES6 syntax) will be helpful.
In this article, I’ll show you how to build a leaderboard for a simple game that updates in realtime after every round. You can find the entire source code of the application in this GitHub repository.
Leaderboards are a feature in many online games which is used to improve competition among players since it gives them instant feedback on their rankings which tends to increases gamer satisfaction and keeps them playing for longer.
Prerequisites
To follow through with the tutorial, a basic knowledge of JavaScript (ES6) and React or Preact is required. You also need to have Node.js (v6.x or later) and npm installed on your machine. Installation instructions can be found here.
Getting started
To get started, install preact-cli globally with npm as we’ll be using it shortly to bootstrap a new Preact application.
npm install -g preact-cli
Once the installation completes, the preact
command will become available on your machine. Run the following command in the terminal to create a new Preact app.
preact create simple leaderboard
This command creates a new folder called leaderboard
in your working directory and installs all the necessary dependencies needed to build and run the application.
As soon has the command has finished running, cd
into the leaderboard
directory and run npm run start
to start the development server. The application should be viewable at http://localhost:8080. If port 8080 is not available on your machine, preact
will provide another port for you to use.
Creating our game
The game we will be making is the classic rock-paper-scissors game which is quite popular in many parts of the world. If you’re not familiar with the rules, you can check this Wikipedia entry to get up to speed with how the game works.
In our implementation of the game, the player will get three points for a win, one for a draw and no points for a defeat. The score, as well as the player’s position on the leaderboard, will be updated in realtime.
The first step is to create the frontend of the game with Preact. Open up index.js
in the root of the leaderboard
directory and change its contents to look like this:
// index.js
import './style';
import { Component } from 'preact';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
computerPick: null,
result: null,
leaderboard: [],
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
const { value } = event.target;
fetch(`http://localhost:7777/play?userPick=${value}`)
.then(response => response.json())
.catch(error => console.log(error));
}
render() {
const { leaderboard, computerPick, result } = this.state;
const sortedLeaderboard = leaderboard.sort((a, b) => b.score > a.score);
const tableBody = sortedLeaderboard.map((player, index) => (
<tr>
<td>{index + 1}</td>
<td>{player.name}</td>
<td>{player.score}</td>
</tr>
));
const computerPicked = computerPick ?
<span class="computer-message">The computer chose {computerPick}</span> : null;
let message;
if (result !== null) {
message = result === 1 ?
<span class="message-content">It's a draw</span> :
result === 0 ? <span class="message-content fail">You Lost!</span> :
<span class="message-content success">You won!</span>;
} else {
message = null;
}
return (
<div class="App">
<h1>Rock Paper Scissors</h1>
<div class="button-row">
<button onClick={this.handleClick} value="rock" class="rock">Rock</button>
<button onClick={this.handleClick} value="paper" class="paper">Paper</button>
<button onClick={this.handleClick} value="scissors" class="scissors">Scissors</button>
</div>
<div class="message">
{message}
{computerPicked}
</div>
<div class="leaderboard">
<table>
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{tableBody}
</tbody>
</table>
</div>
</div>
);
}
}
The three buttons allow us to select rock, paper or scissors for a round, while the table below it will contain the top scorers including the current player. We also have a message
section where the winner of a round will be declared (if any).
Next, change up style.css
to look like this:
// style.css
html,
body {
font: 14px/1.21 'Helvetica Neue', arial, sans-serif;
font-weight: 400;
}
.App {
max-width: 500px;
margin: 50px auto;
text-align: center;
}
.button-row,
.scoreboard {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
button {
transition: box-shadow 0.3s;
font-size: 24px;
padding: 20px 25px;
width: 150px;
margin: 0px 10px 0px 10px;
background-color: white;
border: 4px solid rebeccapurple;
border-radius: 3px;
box-shadow: 2px 2px 2px 0px rgba(168,168,168,1);
cursor: pointer;
}
button:hover {
box-shadow: 4px 4px 6px 0px rgba(168,168,168,1);
}
button:focus {
background-color: #222;
color: #fff;
}
.message span {
display: block;
text-align: center;
}
.message-content {
font-weight: bold;
font-size: 20px;
padding: 20px;
background-color: #c0c0c0;
margin-bottom: 20px;
}
.success {
background-color: #0f0;
}
.fail {
background-color: #f00;
}
table {
width: 100%;
}
th,
td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #E1E1E1;
}
th:first-child,
td:first-child {
padding-left: 0;
}
th:last-child,
td:last-child {
padding-right: 0;
}
At this moment, the application should look like this:
Setting up the server
Let’s set up a simple Express server to handle how the score is determined for a round while also broadcasting updates to the frontend.
Run the following command to install the dependencies we’ll be needing:
npm install express cors dotenv pusher
Head over to the Pusher website and to grab the necessary credentials. Once you have signed up, select Channels apps on the sidebar, and hit Create Channels app to create a new app.
You can retrieve your credentials from the API Keys tab, then create a variables.env
file in the root of your project directory and populate it with the following contents:
// variables.env
PORT=7777
PUSHER_APP_ID=<your app id>
PUSHER_APP_KEY=<your app key>
PUSHER_APP_SECRET=<your app secret>
PUSHER_APP_CLUSTER=<your app cluster>
Next, create a new server.js
file in your project directory and change it to look like this:
// server.js
require('dotenv').config({ path: 'variables.env' });
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const Pusher = require('pusher');
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true,
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
We’re going to pretend that we have a leaderboard already with the scores of previous players. Normally, you’d fetch this data from the server, but in this scenario, we’ll hardcode the values in a JSON file.
Create a file called leaderboard.json
in your project directory and update its contents to look like this:
// leaderboard.json
{
"players": [
{
"name": "Mike Koala",
"score": 95
},
{
"name": "Gina Kangaroo",
"score": 92
},
{
"name": "Sally Tortoise",
"score": 86
},
{
"name": "Kim Lobster",
"score": 67
},
{
"name": "Peter Rabbit",
"score": 56
},
{
"name": "Frank Leopard",
"score": 43
},
{
"name": "Mary Hyena",
"score": 34
},
{
"name": "Caroline Bear",
"score": 32
},
{
"name": "Tom Eagle",
"score": 24
},
{
"name": "Jim Unicorn",
"score": 11
},
{
"name": "Player 1",
"score": 0
}
]
}
Display the leaderboard on page load
When our application loads, we need to update the table with the existing leaderboard values as shown in the leaderboard.json
file.
Within index.js
, add the following lifecycle hook that loads the leaderboard when the App
component mounts successfully:
// index.js
componentDidMount() {
fetch('http://localhost:7777/leaderboard')
.then(response => response.json())
.then(data => {
this.setState({
leaderboard: [...data.players],
});
})
.catch(error => console.log(error));
}
Next, let’s add the /leaderboard
route to the server. Hitting this route will simply send the leaderboard.json
file to the client. First add the following under the other require
statements at the top:
// server.js
const leaderboard = require('./leaderboard.json');
Then add the /leaderboard
route as shown below:
// server.js
...
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/leaderboard', (req, res) => {
res.json(leaderboard);
});
...
Game logic
In the index.js
file, we have a handleClick
function that is invoked when each button is clicked. This function sends whatever value is clicked to the server through the /play
endpoint. But this endpoint does not exist on the server yet so we’ll go ahead and create it in the next step.
Before we continue, we need to create a new function that will help us determine the winner of each round or whether it is a draw. Let’s call this function compare
, and create a new compare.js
file to house the function as shown below:
// compare.js
const compare = (choice1, choice2) => {
if (choice1 === choice2) {
return 1;
}
if (choice1 === "rock") {
if (choice2 === "scissors") {
return 3;
} else {
// paper wins
return 0;
}
}
if (choice1 === "paper") {
if (choice2 === "rock") {
return 3;
} else {
return 0;
}
}
if (choice1 === "scissors") {
if (choice2 === "rock") {
return 0;
} else {
return 1;
}
}
};
module.exports = compare;
The compare
function checks what the user plays (choice1
) and compares it with what the computer picks (choice2
) to determine a winner. As explained previously, the user gets three points for a win, one for a draw and zero points for a defeat.
Let’s go ahead and make use of the compare
in the new /play
route. We need to import it first below the other require
statements:
// server.js
const compare = require('./compare');
Then create the /play
route below /leaderboard
as shown below:
app.get('/play', (req, res) => {
const { userPick } = req.query;
const arr = ['rock', 'paper', 'scissors'];
const computerPick = arr[Math.floor(Math.random() * 3)];
const points = compare(userPick, computerPick);
});
The computer picks a random value from the arr
variable anytime this route is hit. This value is then compared with whatever the user selected and the resulting points value for the user is stored in the points
variable.
When the user scores a point, we need to update the leaderboard in realtime so that the player can see his progress in the rankings while playing the game. We’ll be making use of Pusher Channels to achieve this functionality.
Let’s install the Pusher client library through npm. This is how we’ll use Channels in our Preact app.
npm install pusher-js
Then import it at the top of index.js
:
// index.js
import Pusher from 'pusher-js';
Next, we’ll open a connection to Channels within componentDidMount()
and use the subscribe()
method from Pusher to subscribe to a new channel called leaderboard
. Finally, we’ll listen for the update
on the bot
channel using the bind
method and update the application state once we receive a message.
Don’t forget to replace the <your app key>
and <your app cluster>
placeholder with the appropriate values from your Pusher account dashboard.
// index.js
componentDidMount() {
const pusher = new Pusher('<your app key>', {
cluster: '<your app cluster>',
encrypted: true,
});
const channel = pusher.subscribe('leaderboard');
channel.bind('update', data => {
const { leaderboard } = this.state;
const userIndex = leaderboard.findIndex(e => e.name === 'Player 1');
leaderboard[userIndex].score += data.points;
this.setState({
computerPick: data.computerPick,
result: data.points,
leaderboard,
});
});
fetch('http://localhost:7777/leaderboard')
.then(response => response.json())
.then(data => {
this.setState({
leaderboard: [...data.players],
});
})
.catch(error => console.log(error));
}
Finally, we’ll trigger updates from the server when the user’s points for a round have been determined.
Change the /play
route within server.js
to look like this:
// server.js
app.get('/play', (req, res) => {
const { userPick } = req.query;
const arr = ['rock', 'paper', 'scissors'];
const computerPick = arr[Math.floor(Math.random() * 3)];
const points = compare(userPick, computerPick);
pusher.trigger('leaderboard', 'update', {
points,
computerPick,
});
});
You can start the server by running node server.js
in a different terminal window, and test out the game by playing a few rounds. You should see the leaderboard update as you score some points!
Conclusion
I’m sure you’ll agree that setting up Pusher Channels for realtime updates to the game leaderboard was easy enough. There’s so much more you can do with Channels so I recommend digging into the docs to find more about the service and other awesome features it has.
Thanks for reading! Remember that you can find the source code of this app in this GitHub repository.
17 October 2018
by Ayooluwa Isaiah