JavaScript Tutorial: Code Two Classic Word Games
Word games are a fun and effective way to engage your mind, expand your vocabulary, and test your knowledge. They‘re also an excellent learning project for beginning JavaScript developers looking to practice core programming concepts in a hands-on manner.
In this comprehensive tutorial, we‘ll walk through how to code two classic word games from scratch using vanilla JavaScript: a Jeopardy-style trivia game and a word association game. By the end, you‘ll have built two fully-functional interactive games while solidifying your understanding of essential JavaScript techniques.
Why Build Word Games to Learn JavaScript?
Coding simple games provides immediate, concrete practice with the fundamentals of JavaScript in a way that‘s engaging and rewarding. According to a survey by Stack Overflow, JavaScript is the most commonly used programming language, employed by over 68% of professional developers. Gaining proficiency in JavaScript and its related tools and frameworks can open up a wide range of opportunities, from front-end web development to full-stack engineering.
Building word games in particular allows you to practice working with several key JavaScript concepts:
- Arrays and Objects: Storing and accessing word lists, questions and answers, and game state
- Functions: Organizing reusable blocks of code to handle game logic and user interactions
- Loops: Iterating over arrays to dynamically generate HTML elements and process game data
- DOM Manipulation: Selecting, creating, and updating HTML elements to reflect game state
- Event Listeners: Responding to user interactions like button clicks to control game flow
- Conditionals: Checking user input against game data and updating scores and displays accordingly
A study published in the Journal of Educational Psychology found that students who practiced programming concepts through game-based learning showed significantly higher levels of engagement and motivation compared to those who used traditional study methods. By applying JavaScript skills to build fun and challenging word games, you‘re more likely to stay focused and driven to continue improving.
Game 1: Jeopardy Trivia
Let‘s start by building a basic Jeopardy-style trivia game, where players are presented with clues in the form of answers and must respond with the correct question. Here‘s a step-by-step breakdown of how to implement this in JavaScript.
Defining Clue Data
First, we‘ll create an array of objects to store our clues, categories, and point values:
const clues = [
{
category: "Science & Nature",
question: "The speed of light in a vacuum is about 186,000 miles per one of these units",
answer: "second",
value: 200
},
{
category: "Mythology",
question: "This Greek goddess of wisdom is said to have sprung fully-grown from the head of Zeus",
answer: "Athena",
value: 400
},
// Additional clues...
];
Each object in the clues
array contains category
, question
, answer
, and value
properties to fully define each trivia item.
Setting Up the Game Board
Next, we‘ll create references to the necessary HTML elements for displaying the game board and score:
const board = document.getElementById("board");
const scoreDisplay = document.getElementById("score");
To dynamically generate the Jeopardy board from our clues
array, we‘ll use a function that creates an HTML element for each clue and attaches a click event listener:
function initBoard() {
// Create a new row element
let row = document.createElement("div");
row.className = "row";
// Loop through the clues array
clues.forEach(clue => {
// Create a new box element for each clue
let box = document.createElement("div");
box.className = "box";
// Set the box text to the clue‘s point value
box.textContent = clue.value;
// Attach a click event listener to handle selecting the clue
box.addEventListener("click", handleClick.bind(null, clue));
// Add the box to the row
row.appendChild(box);
});
// Add the row to the board
board.appendChild(row);
}
This initBoard
function loops through the clues
array, creating a new div
element for each clue, setting its text content to the clue‘s point value, and adding a click
event listener to handle selecting the clue. The generated HTML structure will look something like:
<div id="board">
<div class="row">
<div class="box">200</div>
<div class="box">400</div>
...
</div>
</div>
Handling Clue Selection
When a clue box is clicked, the handleClick
function will be called with the corresponding clue object as an argument:
let score = 0;
function handleClick(clue, event) {
// Mark the clicked box as used
event.target.classList.add("used");
// Remove the click event listener from the used box
event.target.removeEventListener("click", handleClick);
// Prompt the user for their response to the clue
let userAnswer = prompt(clue.question);
// Check if the user‘s response matches the correct answer
if (userAnswer.toLowerCase() === clue.answer.toLowerCase()) {
// If correct, add the clue‘s value to the score
score += clue.value;
} else {
// If incorrect, subtract the clue‘s value from the score
score -= clue.value;
}
// Update the displayed score
scoreDisplay.textContent = score;
}
This function first marks the clicked clue box as used by adding a used
class and removing the click
event listener to prevent re-selection. It then prompts the user to input their response to the clue and checks if it matches the correct answer. The score is updated accordingly, adding the clue‘s value for a correct response and subtracting it for an incorrect one. Finally, the displayed score is updated to reflect the change.
To kick off the game, we simply call the initBoard
function:
initBoard();
With that, our basic Jeopardy game is complete! Players can select clues by clicking on the point values, input their responses, and see their score tallied based on their performance.
Expanding the Game
To take this simple implementation further, consider adding some of the following features:
- Support for multiple categories and rounds (like the classic Jeopardy "Double Jeopardy" round)
- A final "Final Jeopardy" clue with customizable wager amounts
- A more polished UI with graphics, animations, and sound effects
- Multi-player support with a buzzer system to determine who can respond first
- A leaderboard to keep track of high scores across games
While adding these enhancements will require more advanced JavaScript techniques, the core concepts of dynamically rendering HTML elements, managing game state, and handling user input with event listeners will remain central to the implementation.
Game 2: Word Associations
For our second game, we‘ll create a simple word association challenge where players are presented with a target word and must select other related words from a list of options.
Implementing the Word List
We‘ll start by defining our word list as an array of strings:
const words = [
"cat",
"dog",
"bird",
"fish",
"hamster",
"turtle",
"rabbit",
// More words...
];
Setting Up Game State
Next, we‘ll create variables to track the essential game state, including the target word, the player‘s selected words, and their score:
let targetWord;
let userWords;
let score;
function startGame() {
// Select a random word from the array as the target
targetWord = words[Math.floor(Math.random() * words.length)];
// Reset the user‘s selected words
userWords = [];
// Reset the score
score = 0;
// Update the UI to reflect the new game state
updateUI();
}
The startGame
function initializes a new game by selecting a random word from the words
array as the target, resetting the userWords
array and score
variable, and calling an updateUI
function (defined later) to reflect the new game state.
Rendering Word Options
To present the word options to the player, we‘ll generate button elements for each word dynamically:
const wordButtons = document.getElementById("word-buttons");
function renderWordButtons() {
// Clear any existing word buttons
wordButtons.innerHTML = "";
// Loop through the words array
for (let word of words) {
// Skip the target word and any words the user has already selected
if (word !== targetWord && !userWords.includes(word)) {
// Create a new button element for the word
let button = document.createElement("button");
button.textContent = word;
// Attach a click event listener to handle selecting the word
button.addEventListener("click", handleGuess.bind(null, word));
// Add the button to the word buttons container
wordButtons.appendChild(button);
}
}
}
The renderWordButtons
function first clears any existing buttons from the wordButtons
container. It then loops through the words
array, skipping the target word and any words the player has already selected. For each remaining word, a new button
element is created with the word as its text content and a click
event listener attached to handle selecting the word. The button is then added to the wordButtons
container.
Handling Word Selection
When a word button is clicked, the handleGuess
function is called with the selected word as an argument:
function handleGuess(word) {
// Add the selected word to the user‘s words array
userWords.push(word);
// Check if the selected word is associated with the target word
if (isAssociated(targetWord, word)) {
// If associated, increment the score
score++;
} else {
// If not associated, decrement the score
score--;
}
// Check if the user has selected all possible words
if (userWords.length === words.length - 1) {
// If all words have been selected, end the game and display the final results
alert(`Game over! Your score is ${score}. The target word was "${targetWord}".`);
// Start a new game
startGame();
} else {
// If words remain, update the word buttons and UI
renderWordButtons();
updateUI();
}
}
This function first adds the selected word to the userWords
array. It then checks if the selected word is associated with the target word using a helper function called isAssociated
(implementation discussed later). If the words are associated, the score is incremented; if not, the score is decremented.
Next, the function checks if the player has selected all possible words by comparing the length of the userWords
array to the length of the words
array minus one (to account for the target word). If all words have been selected, the game ends, the final score is displayed, and a new game is started. If words remain, the word buttons and UI are updated to reflect the new game state.
Checking Word Associations
The isAssociated
helper function is responsible for determining if two given words are related. A simple implementation could use a hard-coded object to store word associations:
const associations = {
cat: ["dog", "mouse", "yarn"],
dog: ["cat", "bone", "leash"],
bird: ["feather", "nest", "worm"],
// More associations...
};
function isAssociated(word1, word2) {
// Check if word2 is in the associations array for word1
return associations[word1].includes(word2);
}
In this example, the associations
object maps each word to an array of associated words. The isAssociated
function simply checks if word2
is included in the associations
array for word1
.
For a more robust solution, consider integrating with a thesaurus API or using natural language processing techniques to determine word relations based on semantic similarity or frequency of co-occurrence in text corpora.
Updating the UI
Finally, the updateUI
function is responsible for updating the displayed target word, score, and other game elements:
const targetWordDisplay = document.getElementById("target-word");
const scoreDisplay = document.getElementById("score");
function updateUI() {
// Update the displayed target word
targetWordDisplay.textContent = targetWord;
// Update the displayed score
scoreDisplay.textContent = score;
// Render the updated word buttons
renderWordButtons();
}
To put it all together, the final HTML for the word association game might look something like:
<p>Select words related to: <span id="target-word"></span></p>
<div id="word-buttons"></div>
<p>Score: <span id="score">0</span></p>
And the JavaScript to initialize the game:
startGame();
With that, our basic word association game is complete! The player is presented with a target word and a set of buttons for other words. Clicking a word button updates the score based on whether the word is associated with the target. The game ends when all words have been selected, and a new game begins with a new target word.
Expanding the Game
Some ideas for enhancing the word association game:
- Add a timer to limit the amount of time players have to make their selections
- Implement difficulty levels with more obscure or challenging word associations
- Provide hints or definitions for the target word
- Track high scores across multiple plays and display a leaderboard
- Allow players to create and share their own word association sets
Conclusion
In this tutorial, we‘ve walked through the process of building two classic word games using vanilla JavaScript. Along the way, we‘ve explored essential programming concepts and techniques, including:
- Storing and manipulating data with arrays and objects
- Dynamically generating HTML elements based on data
- Handling user interactions with click events
- Updating the DOM to reflect changes in game state
- Organizing code with functions and variables
- Implementing game logic with conditionals and loops
To deepen your understanding, I encourage you to customize and expand upon the provided examples. Experiment with different data structures, add new features and game mechanics, and refactor the code to improve performance and maintainability.
Coding word games is just one example of the kind of fun, engaging projects you can build with JavaScript. As you continue to develop your skills, consider exploring libraries and frameworks like Phaser or Babylon.js that provide powerful tools and abstractions for game development.
With practice and dedication, the techniques you‘ve learned here will serve as a foundation for creating increasingly sophisticated interactive experiences on the web. Keep coding, stay curious, and most importantly – have fun!