AskReference
ProcessIntermediate

How does the `show_score` function in the game's JavaScript determine the color of each letter cell?

The show_score function creates a table row and one cell per guessed letter. For each letter, it sets the cell text to guess[i] and adds the corresponding character from score[i] as a CSS class. The characters are H, C, and M, which the stylesheet colors green, yellow, and gray, respectively.

In template/game.html, show_score(guess, score) receives the player's guess string and a score string returned by the server. It inserts a new row into the guesses table, then loops through each character of the guess. For position i, it inserts a cell, assigns the guessed letter to cell.innerHTML, and runs cell.classList.add(score[i]). Because the server returns a score string made of 'H' for a correct-position letter, 'C' for a letter present elsewhere, and 'M' for a miss, those characters act as CSS class names. The stylesheet defines .H with a green background, .C with a yellow background, and .M with a gray background, so the class addition is what makes each letter cell appear green, yellow, or gray.

Key points

  • show_score builds a new table row and a cell for each guessed letter.
  • It sets each cell's text to the guessed letter at that position.
  • It adds score[i] as a CSS class on the cell.
  • Score characters H, C, and M map to green, yellow, and gray backgrounds in the stylesheet.
Source:FastAPI: Modern Python Web Development· Games· p. 251–262

Related questions

Cover of FastAPI: Modern Python Web Development

FastAPI: Modern Python Web Development

Bill Lubanovic;

First Edition · O'Reilly Media, Inc.

View this ebook