Search⌘ K
AI Features

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:

Javascript (babel-node)
const urlSearchParams = new URLSearchParams(window.location.search);
const playerName = urlSearchParams.get("playerName");
const mainHeadingTemplate = document.querySelector(
"#main-heading-template"
).innerHTML;
const welcomeHeadingHTML = Handlebars.compile(mainHeadingTemplate);
document.querySelector("main").insertAdjacentHTML(
"afterBegin",
welcomeHeadingHTML({
playerName,
})
);

Let’s break down the syntax above:

  • Line 1: Extract the playerName from 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.html file.

  • 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 welcomeHeadingHTML function, passing in the playerName data that will be used to render the heading. ...