Hangman (json_response demo)





Check out the live demo…^

This happened just because I wanted to make a little challenge for myself — create a simple game without altering my existing JavaScript or CSS. I did end up adding a new rule to my CSS (button:disabled), but that really isn't specific to this and I should have had a rule like that to begin with.

This works entirely because of my existing JavaScript, however. A rather small set of it in fact that is designed to perform actions set by my json_response class.

So, how does this work?

First, the HTML contains an inline <svg> with a couple of <button>s.

Each <button> has a data-request attribute, which I already pick up with Mutation Observers. Clicking on one of them makes an AJAX request, which the server responds to.

When you click New Game, I set a phrase in $_SESSION, along with counters for how many guesses were correct and how many were wrong. It then removes the disabled attribute from all of the buttons for the keyboard and displays the phrase with all characters replaced with <u>&nbsp;&nbsp;</u>. The phrase only exists in $_SESSION, and is never sent to the browser (unless you've lost).

When you make a guess by clicking on the onscreen keyboard, I use preg_match() to determine if it is in the phrase. If it is found, I get all positions of the character and use

$resp->text(
"#hangman_phrase > u:nth-of-type({$pos})",
$index[0] //from preg_match_all()
);

to update the dislpay in the browser. If the number of correct characters is also the number of unique characters in the phrase, you've won.

If your guess is incorrect, however, I increment a different $_SESSION variable and change the opacity of one of the <path>s from 0 to 1 to make it visible. When the number of wrong guesses reaches its maximum, you've lost and I update the displayed phrase to the one in $_SESSION.