SalesforceBlue

Feel the rhythm of Salesforce

Goodies

Create Multi-Player TIC TAC TOE Game In LWC Using Platform Events

Hey Rockstar, Hope you are doing well.

In this post, we would be creating a real-time multi-player Tic Tac Toe game using LWC and Platform Events. If you are familiar with the lightning/empApi module in LWC and platform events, proceed ahead. Otherwise will request you to do a quick walkthrough of these items – Platform Event Basics, Using Lightning Emp Api Module In LWC

Alright, let’s proceed to create our Tic Tac Toe game.

Platform events provide fantastic flexibility to communicate with your running lightning component asynchronously via apex. We are going to leverage this behavior in building this app.

Let’s view the LWC component structure for this as shown below:

ComponentDescription
c-ttt-wrapperWrapper component holding c-ttt-lobby and c-ttt-playing-area
c-ttt-lobbyThis component will add the logged-in user to the lobby area and later to the game area
c-ttt-playing-areaThis component will be the actual playing area which will hold the tic tac toe board and necessary game engine
c-ttt-user-infoThis component will display the player’s information

Here is the object structure we have created for the same:

ObjectDescription
Game Lobby This object will hold the players as soon as they open this application and will be redirected to the playing area.
Game AreaThis object will store the reference of a running game and its respective players

We have created two platform events for this app one is responsible for starting the game and another one is responsible to communicate across the player’s current move.

Platform EventsDescription
TTT_Game_Start__eThis platform event is responsible for notifying the respective lightning components that the game has started
TTT_Game_Moves__eThis platform event is responsible for notifying the respective lightning component about current player moves

Below flow chart captures the game start flow:


Below flow chart captures the player moves and their propagation:


Here is the repo link where the action is happening 🙂 – TIC TAC TOE

Feel free to install it in your dev org and further explore.

Thus, we covered how lightning components can subscribe to platform events, allowing a mechanism for Apex Code to communicate asynchronously with running lightning components.

On the project do consider the governor limits considerations while choosing platform events for any implementations. Here is the reference from the official docs.

Below is the user experience captured for the entire gameplay:

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂



Leave a Reply

Your email address will not be published. Required fields are marked *