Making the Game Interactive

Introduction: Making the Game Interactive

Welcome to the next step in building your Word Play Game! So far, you have created the main HTML structure and styled your game using code. Now, it’s time to make your game interactive.

In this lesson, you will learn how your code connects the static page to the game logic. By the end, you will understand how the game responds to user actions, updates the page, and communicates with the backend to keep the game running smoothly.

Quick Recall: Connecting Frontend and Backend

Let’s quickly remind ourselves of what you have already built:

  • Your page structure sets up the game, including buttons, input fields, and areas to display information.
  • Your styling code makes the game look nice and organized.

Now, your code will be the “bridge” that listens for user actions (like button clicks), updates the page, and communicates with the backend server to get or send game data.

Managing Game State and Starting the Game

To make the game work, we need to keep track of what’s happening as the player plays. This is called the game state. We use variables to remember things like which word we’re on, the player’s score, and whether the game has started.

Here’s how the game state is set up:

let words = []
let breakpoints = []
let currentWord = 0
let scoreSum = 0
let gameStarted = false
let guessHistory = []
  • words will hold the list of words for the game.
  • breakpoints tell us where the player should make a guess.
  • currentWord keeps track of which word we’re showing.
  • scoreSum is the player’s total score.
  • gameStarted helps us know if the game has started.
  • guessHistory will store all the guesses the player has made.

To start the game, we need to get the game data from the backend. This is done with the startGame function:

async function startGame() {
  const res = await fetch('/game')
  const data = await res.json()

  document.getElementById('llm-model').textContent = data.prompt.llm
  document.getElementById('system-prompt').textContent = data.prompt.systemPrompt
  document.getElementById('user-question').textContent = data.prompt.userQuestion

  words = data.words
  breakpoints = data.breakpoints
  showNextWord()
}
  • fetch('/game') asks the backend for the game data.
  • The response is turned into an object with await res.json().
  • The game’s prompt and question are shown on the page.
  • The list of words and breakpoints is saved for use in the game.
  • Finally, showNextWord() is called to start showing the words.

Displaying Words and Handling Guesses

Now, let’s see how the game shows words and waits for the player’s guess.

The showNextWord function is responsible for displaying each word one at a time:

function showNextWord() {
  const responseDiv = document.getElementById('response')
  const guessBlock = document.getElementById('guess-block')

  if (currentWord >= words.length) {
    guessBlock.classList.add('hidden')
    document.getElementById('result').classList.remove('hidden')
    document.getElementById('final-score').textContent = scoreSum
    return
  }

  if (breakpoints.includes(currentWord)) {
    guessBlock.classList.remove('hidden')
    document.getElementById('guess-input').value = ''
    return
  }

  const span = document.createElement('span')
  span.textContent = words[currentWord]
  responseDiv.appendChild(span)
  currentWord++
  setTimeout(showNextWord, 600)
}

Let’s break this down:

  • If we’ve shown all the words, the game ends and the final score is displayed.
  • If we reach a breakpoint, the game shows the guess input box and waits for the player to enter a guess.
  • Otherwise, the next word is shown on the page, and after a short pause (600 milliseconds), the function is executed again.

When the player makes a guess and clicks the submit button, this code runs:

document.getElementById('submit-guess').addEventListener('click', async () => {
  const guess = document.getElementById('guess-input').value.trim()
  const correct = words[currentWord]
  if (!guess) return

  const res = await fetch('/submit_guess', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ guess, correct })
  })
  const data = await res.json()
  const rounded = Math.round(data.score)
  scoreSum += rounded

  guessHistory.push({ guess, correct, score: data.score })
  updateGuessTable(guess, correct, rounded)

  const span = document.createElement('span')
  span.textContent = correct
  span.style.fontWeight = 'bold'
  document.getElementById('response').appendChild(span)

  document.getElementById('guess-block').classList.add('hidden')
  currentWord++
  setTimeout(showNextWord, 600)
})

Here’s what happens:

  • The player’s guess is read from the input box.
  • The correct word is found from the words list.
  • If the guess is empty, nothing happens.
  • The guess and correct word are sent to the backend for scoring.
  • The score is updated, and the guess is added to the history.
  • The correct word is shown in bold.
  • The guess input is hidden, and the game continues.

Let’s look more closely at how the words are shown one after another using setTimeout inside the showNextWord function.

When showNextWord() is called, it displays the current word, then uses this line:

setTimeout(showNextWord, 600)

This means: after 600 milliseconds (0.6 seconds), call showNextWord() again. This creates a loop where each word is shown, then the function waits a short time before showing the next word. This pattern is called a recursive setTimeout, because the function keeps calling itself with a delay, instead of using a regular loop. This is useful for creating timed sequences in web pages, like showing words one at a time.

So, each time showNextWord() runs, it:

  1. Shows the next word.
  2. Waits 600ms.
  3. Calls itself again to show the next word.

This continues until all words are shown or a breakpoint is reached.

Updating the Score and Showing Results

Updating the Page

Throughout the game, your code is used to show or hide different parts of the page and update the content. Here are some examples:

  • To hide or show a block, use classList.add('hidden') or classList.remove('hidden').
  • To update text, use element.textContent = ....
  • To add new elements, use document.createElement() and appendChild().

For example, when the game starts, we hide the start block and show the game info:

document.getElementById('start-button').addEventListener('click', () => {
  if (!gameStarted) {
    gameStarted = true
    document.getElementById('start-block').classList.add('hidden')
    document.getElementById('info').classList.remove('hidden')
    startGame()
  }
})

This makes the game feel dynamic and responsive to the player’s actions.

Summary and What’s Next

In this lesson, you learned how your code brings your Word Play Game to life by:

  • Managing the game state with variables.
  • Fetching game data from the backend and starting the game.
  • Displaying words and handling player guesses.
  • Updating the score and showing results.
  • Dynamically updating the page as the game progresses.

You are now ready to practice these skills in the next set of exercises. You’ll get hands-on experience writing and modifying code to control the game’s flow and make your web app interactive. Good luck!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal