Have you ever played Wordle? It’s a simple, yet incredibly addictive word game that’s taken the world by storm. The core concept is straightforward: guess a five-letter word in six tries, with clues provided after each guess. But behind that simplicity lies a fascinating interplay of logic, pattern recognition, and a little bit of luck. In this tutorial, we’re going to build our own version of this game using TypeScript, a language that brings structure and clarity to your JavaScript projects. This tutorial is designed for beginners and intermediate developers, so whether you’re new to TypeScript or just looking to sharpen your skills, you’ll find something valuable here.
Why Build a Word Guessing Game?
Building a project like a word guessing game offers several benefits. Firstly, it allows you to practice fundamental programming concepts such as:
- Variables and Data Types
- Functions and Control Flow (if/else, loops)
- Arrays and Strings
- User Input and Output
Secondly, it provides a tangible, engaging project to solidify your understanding of TypeScript. You’ll see how TypeScript’s type system helps you catch errors early, making your code more robust and easier to maintain. Lastly, it’s fun! Creating something you can interact with is a rewarding experience.
Setting Up Your TypeScript Environment
Before we dive into the code, let’s set up our development environment. You’ll need:
- Node.js and npm (Node Package Manager): These are essential for running TypeScript and managing project dependencies. You can download them from nodejs.org.
- A Code Editor: Visual Studio Code (VS Code) is highly recommended due to its excellent TypeScript support, but you can use any editor you prefer.
Once you have these installed, create a new project directory for your game. Open your terminal or command prompt, navigate to your project directory, and initialize a new npm project:
npm init -y
This command creates a package.json file, which will store your project’s metadata and dependencies.
Next, install TypeScript globally or locally. For this project, let’s install it locally:
npm install typescript --save-dev
This command installs TypeScript as a development dependency. Now, create a tsconfig.json file in your project directory. This file configures the TypeScript compiler. You can generate a basic tsconfig.json file using the following command:
npx tsc --init
This command creates a tsconfig.json file with default settings. You can customize these settings to suit your project’s needs. For our game, the default settings will work fine. Finally, create a file named index.ts in your project directory. This is where we’ll write our game’s code.
Laying the Groundwork: Core Game Logic
Let’s start by outlining the core components of our word guessing game:
- Secret Word: The word the player needs to guess.
- Guesses: The player’s attempts to guess the word.
- Feedback: Providing clues after each guess (e.g., correct letters in the correct position, correct letters in the wrong position).
- Game State: Tracking the current state of the game (e.g., ongoing, won, lost).
Here’s how we can represent these components in TypeScript:
// index.ts
const secretWord: string = "HELLO"; // Replace with a randomly selected word later
const maxGuesses: number = 6;
let guessesRemaining: number = maxGuesses;
let gameWon: boolean = false;
// Array to store player's guesses
const guesses: string[] = [];
// Function to check the player's guess
function checkGuess(guess: string): void {
// Implementation to be added later
}
// Function to start the game
function startGame(): void {
// Implementation to be added later
}
startGame();
In this code:
- We declare a
secretWordvariable, which will hold the word to be guessed. For now, we’ve hardcoded it to “HELLO”, but we’ll later replace this with a randomly selected word. maxGuessesstores the maximum number of guesses allowed.guessesRemainingkeeps track of the number of guesses the player has left.gameWonis a boolean flag indicating whether the player has won.guessesis an array to store the player’s guesses.- We define two functions:
checkGuess(which will compare the player’s guess to the secret word and provide feedback) andstartGame(which will handle the game’s initialization and main loop).
Implementing the Guessing Logic
The checkGuess function is the heart of our game. It takes the player’s guess as input and provides feedback. Let’s implement it:
function checkGuess(guess: string): void {
guess = guess.toUpperCase(); // Convert guess to uppercase for case-insensitive comparison
guesses.push(guess);
guessesRemaining--;
const feedback: string[] = [];
for (let i = 0; i < secretWord.length; i++) {
if (guess[i] === secretWord[i]) {
feedback.push("🟩"); // Correct letter and position
} else if (secretWord.includes(guess[i])) {
feedback.push("🟨"); // Correct letter, wrong position
} else {
feedback.push("⬛"); // Letter not in the word
}
}
console.log(feedback.join("")); // Display feedback to the console
if (guess === secretWord) {
gameWon = true;
console.log("Congratulations! You guessed the word!");
} else if (guessesRemaining === 0) {
console.log(`You ran out of guesses. The word was ${secretWord}.`);
}
// Display the guesses made so far
console.log("Guesses:", guesses.join(", "));
}
In this code:
- We convert the player’s guess to uppercase to ensure case-insensitive comparison.
- We add the guess to the
guessesarray and decrementguessesRemaining. - We iterate through each letter of the secret word and compare it to the corresponding letter in the guess.
- We use emojis to provide feedback:
- 🟩: Correct letter and correct position
- 🟨: Correct letter, but in the wrong position
- ⬛: Letter not in the word
- We display the feedback to the console.
- We check if the guess is correct or if the player has run out of guesses, and update the game state accordingly.
- We display the guesses made so far to the console.
User Input and Game Loop
Now, let’s implement the startGame function to handle user input and the game loop. We’ll use the prompt() function to get input from the user in a basic console environment.
import * as readline from 'readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function startGame(): void {
console.log("Welcome to the Word Guessing Game!");
function askForGuess() {
if (guessesRemaining > 0 && !gameWon) {
rl.question("Enter your guess: ", (guess: string) => {
if (guess.length !== secretWord.length) {
console.log(`Guess must be ${secretWord.length} letters long.`);
askForGuess(); // Ask again
} else {
checkGuess(guess);
if (!gameWon && guessesRemaining > 0) {
askForGuess(); // Continue the game
} else {
rl.close(); // End the game
}
}
});
} else {
rl.close(); // End the game if no guesses remaining or game won
}
}
askForGuess();
}
In this code:
- We import the
readlinemodule to handle user input from the console. - We create a
readlineinterface. - The
startGamefunction greets the player. - The
askForGuessfunction usesrl.questionto prompt the user for their guess. - It checks if the guess is the correct length.
- It calls
checkGuessto process the guess. - If the game is still ongoing, it calls
askForGuessagain. - If the game is over (either won or lost), it closes the
readlineinterface.
Adding Word Selection
Currently, our game uses a hardcoded secret word. Let’s enhance it by selecting a random word from a list.
// Add this near the top of index.ts
const wordList: string[] = [
"HELLO", "WORLD", "APPLE", "TRAIN", "CHAIR",
"TABLE", "PHONE", "PIZZA", "WATER", "HOUSE",
"BEACH", "MUSIC", "DANCE", "PLANE", "MOVIE"
];
function getRandomWord(): string {
const randomIndex = Math.floor(Math.random() * wordList.length);
return wordList[randomIndex];
}
// Modify the secretWord declaration
const secretWord: string = getRandomWord();
In this code:
- We create a
wordListarray containing a list of possible secret words. - We define a
getRandomWordfunction to select a random word from thewordList. - We update the
secretWordvariable to use the randomly selected word.
Compiling and Running Your Game
Now that we’ve written our code, let’s compile and run the game. Open your terminal and navigate to your project directory. Then, run the following command:
tsc index.ts
This command compiles your TypeScript code into JavaScript (index.js). Next, run the JavaScript file using Node.js:
node index.js
You should see the game start, prompting you to enter your guesses. Type in a five-letter word and press Enter. The game will provide feedback, and you can continue guessing until you guess the word or run out of attempts.
Common Mistakes and How to Fix Them
When developing this game, you might encounter some common mistakes:
- Incorrect TypeScript Syntax: TypeScript is stricter than JavaScript. Make sure your code follows TypeScript’s syntax rules (e.g., proper type annotations, semicolons). The TypeScript compiler will help you catch these errors.
- Typos: Typos in variable names or function calls can lead to errors. Double-check your code for any typos. Your IDE, like VS Code, can assist you by highlighting potential typos.
- Logic Errors: These are errors in the game’s logic. For example, the feedback might be incorrect, or the game might not recognize a win. Test your game thoroughly and use
console.log()statements to debug your code. - Incorrect Input Handling: If you are not handling the user input properly, the game may behave unexpectedly. Always validate user inputs.
Enhancements and Next Steps
Our word guessing game is functional, but there are many ways to enhance it:
- User Interface: Create a graphical user interface (GUI) using HTML, CSS, and JavaScript. This would provide a much more user-friendly experience than the console-based version.
- Word Lists: Expand the word list to include more words or allow users to select difficulty levels based on word length or frequency.
- Hints: Implement a hint system to provide clues to the player.
- Scoring: Add a scoring system to track the player’s performance.
- Difficulty Levels: Implement levels of difficulty.
Key Takeaways
- TypeScript Fundamentals: You’ve reinforced your understanding of variables, functions, control flow, arrays, and strings.
- Type Safety: You’ve seen how TypeScript’s type system helps catch errors early in the development process.
- Project Structure: You’ve learned how to structure a project with a clear separation of concerns (e.g., game logic, user input).
- Problem-Solving: You’ve practiced breaking down a complex problem (building a game) into smaller, manageable tasks.
FAQ
Here are some frequently asked questions about building a word guessing game in TypeScript:
- Why use TypeScript for this project? TypeScript provides type safety, which helps catch errors early and improves code maintainability. It also makes your code more readable and easier to understand.
- How can I deploy this game online? You can deploy your game online using platforms like GitHub Pages, Netlify, or Vercel. You’ll need to create an HTML file, link your compiled JavaScript file, and style your game using CSS.
- How can I add more words to the word list? Simply add more strings to the
wordListarray. - How can I make the game more challenging? You can increase the word length, limit the number of guesses, or add a time limit.
- Can I use a different IDE? Yes, you can use any code editor you prefer, but VS Code is highly recommended due to its excellent TypeScript support.
Building this word guessing game in TypeScript is a great way to solidify your understanding of the language and practice fundamental programming concepts. By starting with the basics and gradually adding features, you can create a fun and engaging project that showcases your skills. Remember to experiment, iterate, and most importantly, have fun! The beauty of programming lies in the ability to bring your ideas to life, and with TypeScript, you have a powerful tool to do just that. Keep exploring, keep coding, and your skills will continue to grow. This project is just the beginning of your journey into the world of TypeScript and game development. The possibilities are endless, and the only limit is your imagination.
