In the get_score function from Example 18-5, what do the constants HIT, MISS, and CLOSE represent, and how are they used to build the result string?
HIT, MISS, and CLOSE are constants equal to the characters "H", "M", and "C". In get_score, HIT means the guessed letter is correct and in the correct position, MISS means it is not in the hidden word, and CLOSE means it is in the word but at another position. The score string is built by starting a list with MISS for every letter, replacing exact matches with HIT, then replacing remaining eligible letters with CLOSE, and finally joining the list into a string.
In Example 18-5, HIT, MISS, and CLOSE define the three possible results for each letter of a guess. HIT is "H", MISS is "M", and CLOSE is "C". The get_score function first verifies that the guess has the same length as the actual word. It then creates a result list of MISS characters, one for each letter. Next, it loops over the guess: wherever a guess letter exactly equals the actual letter at that position, it sets that result position to HIT and increments a counter for that letter. After that, it loops again over the guess, skipping positions already marked HIT. For each remaining position, it increments the counter for that guessed letter and, if the letter occurs in the actual word and the guessed count so far is within the actual letter's count, it changes the result position to CLOSE. Finally, it joins all the single-character results into one string, which the client uses with CSS classes to display green, yellow, or gray cells.
Key points
- HIT = "H" means the guessed letter is in the correct position.
- MISS = "M" means the guessed letter is not in the hidden word.
- CLOSE = "C" means the guessed letter is in the word but in another position.
- The result starts as a list of MISS characters, then exact matches are changed to HIT.
- A second loop changes eligible non-hit positions to CLOSE, using letter counts to avoid marking too many repeated letters.
- The list is joined into a string where each character corresponds to one guessed letter.
Related questions
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.