The advent of the PC and the internet has redefined the term “entertainment” and the means by which it can be obtained. While a console or some special hardware would have been required to play games in the past, games are only a click away in today's world of technology.
In this tutorial, we will create a realtime tic-tac-toe game using Python and Pusher Channels. Here’s a demo of how the game will look and behave upon creation:
This multiplayer game will allow a player to connect using their preferred username (or generate a random username where a player doesn’t connect with a username) and choose to play with another player from a list of other online players.
The game itself follows the conventional principles of the popular tic-tac-toe game. The “online player(s)” feature is powered by Pusher presence channels and the realtime updates of a player’s move across multiple windows is powered by Pusher private channels. The source code for this tutorial is available here GitHub.
Let’s get started.
To follow along, a basic knowledge of Python, Flask, JavaScript (ES6 syntax) and Vue is required. You will also need the following installed on your machine:
Virtualenv is great for creating isolated Python environments, so we can install dependencies in an isolated environment without polluting our global packages directory.
We will create the project folder and activate a virtual environment within it:
1$ mkdir python-pusher-mutiplayer-game 2 $ cd python-pusher-mutiplayer-game 3 $ virtualenv .venv 4 $ source .venv/bin/activate # Linux based systems 5 $ \path\to\env\Scripts\activate # Windows users
We will install Flask using this command:
$ pip install flask
To integrate Pusher into the multiplayer game, we need to create a Pusher Channels application. To get started with Pusher Channels, sign up or sign in and then go to the dashboard to create the Channels app.
To enable client events, click on App settings and scroll to the bottom of the page then select the option that says Enable client events, and update the App settings.
Back in the project directory, let’s install the Python Pusher library with this command:
$ pip install pusher
We will create a new file and call it app.py
, this is where we will write all the code for the Flask backend server. We will also create a folder and call it templates
, this folder will hold the markup files for this application.
Let’s write some code to register the endpoints for the game and serve the view, open the app.py
file and paste the following code:
1// File: ./app.py 2 from flask import Flask, render_template, request, jsonify, make_response, json 3 from pusher import pusher 4 5 app = Flask(__name__) 6 7 pusher = pusher_client = pusher.Pusher( 8 app_id='PUSHER_APP_ID', 9 key='PUSHER_APP_KEY', 10 secret='PUSHER_APP_SECRET', 11 cluster='PUSHER_APP_CLUSTER', 12 ssl=True 13 ) 14 15 name = '' 16 17 @app.route('/') 18 def index(): 19 return render_template('index.html') 20 21 @app.route('/play') 22 def play(): 23 global name 24 name = request.args.get('username') 25 return render_template('play.html') 26 27 @app.route("/pusher/auth", methods=['POST']) 28 def pusher_authentication(): 29 auth = pusher.authenticate( 30 channel=request.form['channel_name'], 31 socket_id=request.form['socket_id'], 32 custom_data={ 33 u'user_id': name, 34 u'user_info': { 35 u'role': u'player' 36 } 37 } 38 ) 39 return json.dumps(auth) 40 41 if __name__ == '__main__': 42 app.run(host='0.0.0.0', port=5000, debug=True) 43 44 name = ''
NOTE: Replace the
PUSHER_APP_*
keys with the values on your Pusher dashboard.
In the code above, we defined three endpoints, here’s what they do:
/
- renders the front page that asks a player to connect with a username./play
- renders the game view./pusher/auth
- authenticates Pusher’s presence and private channels for connected players.In the templates
folder, we will create two files:
index.html
play.html
The index.html
file will render the connection page, so open the templates/index.html
file and paste the following code:
1<!-- File: ./templates/index.html --> 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="utf-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 7 <meta name="description" content=""> 8 <meta name="author" content="Neo Ighodaro"> 9 <title>TIC-TAC-TOE</title> 10 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> 11 <style> 12 :root { 13 --input-padding-x: .75rem; 14 --input-padding-y: .75rem; 15 } 16 html, 17 body, body > div { 18 height: 100%; 19 } 20 body > div { 21 display: -ms-flexbox; 22 display: flex; 23 -ms-flex-align: center; 24 align-items: center; 25 padding-top: 40px; 26 padding-bottom: 40px; 27 background-color: #f5f5f5; 28 } 29 .form-signin { 30 width: 100%; 31 max-width: 420px; 32 padding: 15px; 33 margin: auto; 34 } 35 .form-label-group { 36 position: relative; 37 margin-bottom: 1rem; 38 } 39 .form-label-group > input, 40 .form-label-group > label { 41 padding: var(--input-padding-y) var(--input-padding-x); 42 } 43 .form-label-group > label { 44 position: absolute; 45 top: 0; 46 left: 0; 47 display: block; 48 width: 100%; 49 margin-bottom: 0; /* Override default `<label>` margin */ 50 line-height: 1.5; 51 color: #495057; 52 cursor: text; /* Match the input under the label */ 53 border: 1px solid transparent; 54 border-radius: .25rem; 55 transition: all .1s ease-in-out; 56 } 57 .form-label-group input::-webkit-input-placeholder { 58 color: transparent; 59 } 60 .form-label-group input:-ms-input-placeholder { 61 color: transparent; 62 } 63 .form-label-group input::-ms-input-placeholder { 64 color: transparent; 65 } 66 .form-label-group input::-moz-placeholder { 67 color: transparent; 68 } 69 .form-label-group input::placeholder { 70 color: transparent; 71 } 72 .form-label-group input:not(:placeholder-shown) { 73 padding-top: calc(var(--input-padding-y) + var(--input-padding-y) * (2 / 3)); 74 padding-bottom: calc(var(--input-padding-y) / 3); 75 } 76 .form-label-group input:not(:placeholder-shown) ~ label { 77 padding-top: calc(var(--input-padding-y) / 3); 78 padding-bottom: calc(var(--input-padding-y) / 3); 79 font-size: 12px; 80 color: #777; 81 } 82 </style> 83 </head> 84 <body> 85 <div id="app"> 86 <form class="form-signin"> 87 <div class="text-center mb-4"> 88 <img class="mb-4" src="https://thestore.gameops.com/v/vspfiles/photos/Tic-Tac-Go-14.gif" alt="" width="72" height="72"> 89 <h1 class="h3 mb-3 font-weight-normal">TIC-TAC-TOE</h1> 90 <p>PUT IN YOUR DETAILS TO PLAY</p> 91 </div> 92 <div class="form-label-group"> 93 <input type="name" id="inputUsername" ref="username" class="form-control" placeholder="Username" required="" autofocus=""> 94 <label for="inputUsername">Username</label> 95 </div> 96 <div class="form-label-group"> 97 <input type="email" id="inputEmail" ref="email" class="form-control" placeholder="Email address" autofocus="" required> 98 <label for="inputEmail">Email address</label> 99 </div> 100 <button class="btn btn-lg btn-primary btn-block" type="submit" @click.prevent="login">Connect</button> 101 <p class="mt-5 mb-3 text-muted text-center">© 2017-2018</p> 102 </form> 103 </div> 104 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 105 <script> 106 var app = new Vue({ 107 el: '#app', 108 methods: { 109 login: function () { 110 let username = this.$refs.username.value 111 let email = this.$refs.email.value 112 window.location.replace(`/play?username=${username}&email=${email}`); 113 } 114 } 115 }) 116 </script> 117 </body> 118 </html>
When a player visits the connection page and puts in a username and email, the browser window will be redirected to the game view.
Let’s write the markup for the game view. Open the play.html
file and paste the following code:
1<!-- file: ./templates/play.html --> 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="utf-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 7 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> 8 <title>TIC-TAC-TOE</title> 9 </head> 10 <body> 11 <div id="app" class="container-fluid"> 12 <div class="container-fluid clearfix mb-3 shadow"> 13 <img class="float-left my-3" src="https://thestore.gameops.com/v/vspfiles/photos/Tic-Tac-Go-14.gif" height="62px" width="62px" 14 /> 15 <div class="float-right w-25 py-3"> 16 <img class="my-3 mx-3 rounded-circle border" src="http://dfsanonymous.club/wp-content/uploads/2017/11/DFSAnonymous-NewLogo.png" 17 height="62px" width="62px" /> 18 <p class="d-inline"> {% raw %} {{ username }} {% endraw %} </p> 19 </div> 20 </div> 21 <div class="row mx-5" style="height: 50vh"> 22 <div class="col-8 h-50 align-self-center"> 23 <div class="row border rounded invisible h-50 w-75 m-auto" style="font-size: 3.6rem" ref="gameboard" @click="playerAction"> 24 <div class="h-100 pr-2 col border border-dark" data-id="1" ref="1"></div> 25 <div class="col pr-2 border border-dark" data-id="2" ref="2"></div> 26 <div class="col pr-2 border border-dark" data-id="3" ref="3"></div> 27 <div class="w-100"></div> 28 <div class="h-100 pr-2 col border border-dark" data-id="4" ref="4"></div> 29 <div class="col pr-2 border border-dark" data-id="5" ref="5"></div> 30 <div class="col pr-2 border border-dark" data-id="6" ref="6"></div> 31 <div class="w-100"></div> 32 <div class="h-100 pr-2 col border border-dark" data-id="7" ref="7"></div> 33 <div class="col pr-2 border border-dark" data-id="8" ref="8"></div> 34 <div class="col pr-2 border border-dark" data-id="9" ref="9"></div> 35 </div> 36 </div> 37 <div class="col-4 pl-3"> 38 <div class="row h-100"> 39 <div class="col border h-75 text-center" style="background: rgb(114, 230, 147);"> 40 <p class="my-3"> {% raw %} {{ players }} {% endraw %} online player(s) </p> 41 <hr/> 42 <li class="m-auto py-3 text-dark" style="cursor: pointer;" v-for="member in connectedPlayers" @click="choosePlayer"> 43 {% raw %} {{ member }} {% endraw %} 44 </li> 45 </div> 46 <div class="w-100"></div> 47 <div class="col text-center py-3 border h-25" style="background: #b6c0ca; font-size: 1em; font-weight: bold"> 48 {% raw %} {{ status }} {% endraw %} 49 </div> 50 </div> 51 </div> 52 </div> 53 </div> 54 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 55 <script src="https://js.pusher.com/4.2/pusher.min.js"></script> 56 <script> 57 58 </script> 59 </body> 60 </html>
The code above defines the layout of the game view but does not contain any interactivity or realtime features. In the scripts section, before the closing body
tag, we included the Vue and Pusher libraries because they are required for the game to work.
Let’s include the JavaScript code that will drive the entire game process and define its logic.
In the same file, add the code below in between the script
tag that is just before the closing body
tag:
1var app = new Vue({ 2 el: '#app', 3 4 data: { 5 username: '', 6 players: 0, 7 connectedPlayers: [], 8 status: '', 9 pusher: new Pusher('PUSHER_APP_KEY', { 10 authEndpoint: '/pusher/auth', 11 cluster: 'PUSHER_APP_CLUSTER', 12 encrypted: true 13 }), 14 otherPlayerName: '', 15 mychannel: {}, 16 otherPlayerChannel: {}, 17 firstPlayer: 0, 18 turn: 0, 19 boxes: [0, 0, 0, 0, 0, 0, 0, 0, 0] 20 }, 21 22 created () { 23 let url = new URL(window.location.href); 24 let name = url.searchParams.get("username"); 25 26 if (name) { 27 this.username = name 28 this.subscribe(); 29 this.listeners(); 30 } else { 31 this.username = this.generateRandomName(); 32 location.assign("/play?username=" + this.username); 33 } 34 }, 35 36 methods: { 37 // We will add methods here 38 } 39 });
NOTE: Replace the
PUSHER_APP_*
keys with the keys on your Pusher dashboard.
Above, we create a new instance of Vue and we target the #app
selector. We define all the defaults in the data
object and then in the create()
function which is called automatically when the Vue component is created, we check for a user and assign the user to the username if one was supplied.
We also make calls to the subscribe
and listeners
methods. Let’s define those inside the methods
object. Inside the methods
object, paste the following functions:
1// [...] 2 3 subscribe: function () { 4 let channel = this.pusher.subscribe('presence-channel'); 5 this.myChannel = this.pusher.subscribe('private-' + this.username) 6 7 channel.bind('pusher:subscription_succeeded', (player) => { 8 this.players = player.count - 1 9 player.each((player) => { 10 if (player.id != this.username) 11 this.connectedPlayers.push(player.id) 12 }); 13 }); 14 15 channel.bind('pusher:member_added', (player) => { 16 this.players++; 17 this.connectedPlayers.push(player.id) 18 }); 19 20 channel.bind('pusher:member_removed', (player) => { 21 this.players--; 22 var index = this.connectedPlayers.indexOf(player.id); 23 if (index > -1) { 24 this.connectedPlayers.splice(index, 1) 25 } 26 }); 27 }, 28 29 listeners: function () { 30 this.pusher.bind('client-' + this.username, (message) => { 31 if (confirm('Do you want to start a game of Tic Tac Toe with ' + message)) { 32 this.otherPlayerName = message 33 this.otherPlayerChannel = this.pusher.subscribe('private-' + this.otherPlayerName) 34 this.otherPlayerChannel.bind('pusher:subscription_succeeded', () => { 35 this.otherPlayerChannel.trigger('client-game-started', this.username) 36 }) 37 this.startGame(message) 38 } else { 39 this.otherPlayerChannel = this.pusher.subscribe('private-' + message) 40 this.otherPlayerChannel.bind('pusher:subscription_succeeded', () => { 41 this.otherPlayerChannel.trigger('client-game-declined', "") 42 }) 43 this.gameDeclined() 44 } 45 }), 46 47 this.myChannel.bind('client-game-started', (message) => { 48 this.status = "Game started with " + message 49 this.$refs.gameboard.classList.remove('invisible'); 50 this.firstPlayer = 1; 51 this.turn = 1; 52 }) 53 54 this.myChannel.bind('client-game-declined', () => { 55 this.status = "Game declined" 56 }) 57 58 this.myChannel.bind('client-new-move', (position) => { 59 this.$refs[position].innerText = this.firstPlayer ? 'O' : 'X' 60 }) 61 62 this.myChannel.bind('client-your-turn', () => { 63 this.turn = 1; 64 }) 65 66 this.myChannel.bind('client-box-update', (update) => { 67 this.boxes = update; 68 }) 69 70 this.myChannel.bind('client-you-lost', () => { 71 this.gameLost(); 72 }) 73 }, 74 75 // [...]
In the subscribe
method, we subscribe to our Pusher presence channel, and then subscribe to the private channel for the current user. In the listeners
method we register the listeners for all the events we are expecting to be triggered on the private channel we subscribed to.
Next, we will add other helper methods to our methods class. Inside the methods class, add the following functions to the bottom after the listeners
method:
1// Generates a random string we use as a name for a guest user 2 generateRandomName: function () { 3 let text = ''; 4 let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; 5 for (var i = 0; i < 6; i++) { 6 text += possible.charAt(Math.floor(Math.random() * possible.length)); 7 } 8 return text; 9 }, 10 11 // Lets you choose a player to play as. 12 choosePlayer: function (e) { 13 this.otherPlayerName = e.target.innerText 14 this.otherPlayerChannel = this.pusher.subscribe('private-' + this.otherPlayerName) 15 this.otherPlayerChannel.bind('pusher:subscription_succeeded', () => { 16 this.otherPlayerChannel.trigger('client-' + this.otherPlayerName, this.username) 17 }); 18 }, 19 20 // Begins the game 21 startGame: function (name) { 22 this.status = "Game started with " + name 23 this.$refs.gameboard.classList.remove('invisible'); 24 }, 25 26 // User declined to play 27 gameDeclined: function () { 28 this.status = "Game declined" 29 }, 30 31 // Game has ended with current user winning 32 gameWon: function () { 33 this.status = "You WON!" 34 this.$refs.gameboard.classList.add('invisible'); 35 this.restartGame() 36 }, 37 38 // Game has ended with current user losing 39 gameLost: function () { 40 this.turn = 1; 41 this.boxes = [0, 0, 0, 0, 0, 0, 0, 0, 0] 42 this.status = "You LOST!" 43 this.$refs.gameboard.classList.add('invisible'); 44 this.restartGame() 45 }, 46 47 // Restarts a game 48 restartGame: function () { 49 for (i = 1; i < 10; i++) { 50 this.$refs[i].innerText = "" 51 } 52 this.$refs.gameboard.classList.remove('invisible'); 53 }, 54 55 // Checks tiles to see if the tiles passed are a match 56 compare: function () { 57 for (var i = 1; i < arguments.length; i++) { 58 if (arguments[i] === 0 || arguments[i] !== arguments[i - 1]) { 59 return false 60 } 61 } 62 63 return true; 64 }, 65 66 // Checks the tiles and returns true if theres a winning play 67 theresAMatch: function () { 68 return this.compare(this.boxes[0], this.boxes[1], this.boxes[2]) || 69 this.compare(this.boxes[3], this.boxes[4], this.boxes[5]) || 70 this.compare(this.boxes[6], this.boxes[7], this.boxes[8]) || 71 this.compare(this.boxes[0], this.boxes[3], this.boxes[6]) || 72 this.compare(this.boxes[1], this.boxes[4], this.boxes[7]) || 73 this.compare(this.boxes[2], this.boxes[5], this.boxes[8]) || 74 this.compare(this.boxes[2], this.boxes[4], this.boxes[6]) || 75 this.compare(this.boxes[0], this.boxes[4], this.boxes[8]) 76 }, 77 78 // Checks to see if the play was a winning play 79 playerAction: function (e) { 80 let index = e.target.dataset.id - 1 81 let tile = this.firstPlayer ? 'X' : 'O' 82 83 if (this.turn && this.boxes[index] == 0) { 84 this.turn = 0 85 this.boxes[index] = tile 86 e.target.innerText = tile 87 88 this.otherPlayerChannel.trigger('client-your-turn', "") 89 this.otherPlayerChannel.trigger('client-box-update', this.boxes) 90 this.otherPlayerChannel.trigger('client-new-move', e.target.dataset.id) 91 92 if (this.theresAMatch()) { 93 this.gameWon() 94 this.boxes = [0, 0, 0, 0, 0, 0, 0, 0, 0] 95 this.otherPlayerChannel.trigger('client-you-lost', '') 96 } 97 } 98 },
Above, we have added several helper methods that the game needs to function properly and before each method, we have added a comment to show what the method does.
Let’s test the game now.
We can test the game by running this command:
$ flask run
Now if we visit localhost:5000, we should see the connection page and test the game:
In this tutorial, we have learned how to leverage the Pusher SDK in creating an online multiplayer game powered by a Python backend server.
The source code for this tutorial is available on GitHub