Add Game Logic to Our Application
Explore how to implement core game logic for a live trivia game by dynamically generating welcome headers with Handlebars and handling real-time events with Socket.IO. Learn to manage player data on the server and update the game interface interactively. By the end, you'll understand how to send and receive events, format messages with timestamps, and create an engaging multiplayer experience.
Task 5: Create the welcome header
The welcome header is currently missing, so let’s add that. In the completed game, the header greets the player by the name that they provide on the registration page. We can use Handlebars to generate the header dynamically in the client.
Create the welcome header. Add the following code in the public/js/trivia.js file:
Let’s break down the syntax above:
-
Line 1: Extract the
playerNamefrom the URL search parameters. The player provided this on the registration page. -
Line 4: Here, target the template that’s embedded as a script tag in the
public/trivia.htmlfile. -
Line 8: Compile the template into HTML by calling
Handlebars.compile(), which returns a function. -
Line 10: Insert welcomeHeadingHTML right after the opening
<main>tag -
Line 12: Invoke the
welcomeHeadingHTMLfunction, passing in theplayerNamedata that will be used to render the heading. ...