In this article I will outline how I built a hangman game with Vanilla JavaScript, and more importantly, how I made it accessible for players who navigate with their keyboard or with a screen reader.

My hangman game

Concept

Hangman is a simple word guessing game that can be played by one or two people. The goal of this project was to practice building a fun app using Vanilla JavaScript only, no frameworks or libraries. Players can choose to play with two people or solo. For the one-player game, categories and words are preloaded in an array and randomly generated for the player to guess. For two players, the first person creates a category/word and the second person has to guess the word. Each letter guessed correctly is displayed on the page. For each incorrect guess, a body part is added to the hangman image. If the hangman image is completed before the player can guess the word, they lose the game. To guess a letter, players type it into a text input.

Setup

After creating a namespace for the app, one of the first things I did was create an array of questions (words and categories) for the one-player game. In the near future, I would like to build a REST API that can replace this array and also be shared with other people who are interested in building a word game. For now, this is what I started with:

Namespace and array of questions for my hangman app

The next order of business was making sure that every time someone plays the game, one of these words is selected randomly, and displayed in the proper format. I created one variable to select a random question, and another to split the word into its individual letters:

Variable to select random question and variable to split word into individual letters

For guess input, one option would be to provide onscreen buttons as a virtual keyboard for guessing each letter, but I decided to use a text input instead so that players can use their own keyboard, touch screen, or other input method of choice. To that end, I created an array to hold each guess and a simple regular expression to make sure that players can only input letters (no numbers or special characters):

Array to hold user guess and regex to allow only letters input

Game functionality (one player)

Time to start the game! When a player clicks the One Player button, the button itself disappears, the guess form appears, the word category appears at the top of the page, and blank spaces indicate how many letters the word has. As usual with Vanilla JavaScript, this involves a lot of query selectors and class toggling:

Function to start the game

#javascript #game-development #accessibility #games #web-development #programming

How to Build an Accessible Hangman Game with Vanilla JavaScript
62.45 GEEK