TypeScript Tutorial: Build a Simple Web-Based Number Guessing Game

Ever wanted to create a fun, interactive game that you can share with anyone, anywhere? In this tutorial, we’ll dive into the world of TypeScript and build a simple yet engaging number guessing game. This project is perfect for beginners and intermediate developers looking to sharpen their TypeScript skills while creating something tangible and enjoyable. We’ll cover everything from setting up your development environment to handling user input and providing feedback, all while exploring the power of TypeScript’s type system.

Why Build a Number Guessing Game?

Creating a number guessing game offers several benefits. Firstly, it’s a fantastic way to grasp fundamental programming concepts like variables, conditional statements, loops, and user interaction. Secondly, it provides a practical context for learning TypeScript’s core features, such as types, interfaces, and functions. Finally, it’s a fun and rewarding project that allows you to see your code come to life in a user-friendly interface. This game serves as an excellent stepping stone for more complex web applications.

Setting Up Your Development Environment

Before we start coding, we need to set up our development environment. Here’s what you’ll need:

  • Node.js and npm (Node Package Manager): TypeScript is a superset of JavaScript, and we’ll use npm to manage our project dependencies. You can download Node.js from nodejs.org.
  • A Code Editor: I recommend Visual Studio Code (VS Code), but you can use any editor you prefer (Sublime Text, Atom, etc.). VS Code has excellent TypeScript support.
  • TypeScript Compiler: We’ll install the TypeScript compiler globally using npm:
npm install -g typescript

This command installs the TypeScript compiler globally on your system, allowing you to compile your TypeScript code into JavaScript from your terminal.

Creating the Project and Initial Setup

Let’s create a new project directory and initialize it with npm:

  1. Open your terminal or command prompt.
  2. Create a new directory for your project:
mkdir number-guessing-game
cd number-guessing-game
  1. Initialize the project with npm:
npm init -y

This command creates a `package.json` file in your project directory, which will hold information about your project and its dependencies. The `-y` flag accepts all default options.

  1. Create a `tsconfig.json` file to configure the TypeScript compiler:
tsc --init

This command generates a `tsconfig.json` file with default settings. You can customize these settings to control how your TypeScript code is compiled. For this tutorial, we’ll keep the default settings, but you can explore the options later.

  1. Create a `src` directory to hold your TypeScript source files:
mkdir src
  1. Create an `index.ts` file inside the `src` directory. This will be the main file for our game.

Writing the TypeScript Code

Now, let’s start writing the code for our number guessing game. Open `src/index.ts` in your code editor. We’ll break down the code into logical sections.

1. Generating a Random Number

First, we need to generate a random number that the user will try to guess. We’ll use the `Math.random()` function and the `Math.floor()` function to achieve this.

// Generate a random number between 1 and 100
const randomNumber = Math.floor(Math.random() * 100) + 1;

Explanation:

  • `Math.random()` generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
  • We multiply this number by 100 to get a number between 0 and 99.
  • `Math.floor()` rounds the number down to the nearest integer.
  • We add 1 to the result to get a number between 1 and 100 (inclusive).

2. Getting User Input

Next, we need to get the user’s guess. We’ll use the `prompt()` function, which displays a dialog box asking the user to enter a value. However, the `prompt()` function is not ideal for larger projects. For more complex web applications, you would typically use HTML input elements and event listeners to capture user input. For simplicity, we’ll use `prompt()` in this tutorial.

// Get user input
function getUserGuess(): number {
  const guess = prompt("Guess a number between 1 and 100:");
  // Handle potential errors (e.g., user cancels the prompt or enters non-numeric input)
  if (guess === null) {
    return -1; // Or handle the cancellation as you see fit.
  }
  const parsedGuess = parseInt(guess, 10);
  if (isNaN(parsedGuess)) {
    alert("Invalid input. Please enter a number.");
    return getUserGuess(); // Recursively call the function to prompt again.
  }
  return parsedGuess;
}

Explanation:

  • `prompt(“Guess a number between 1 and 100:”)` displays a prompt to the user and gets their input as a string.
  • `parseInt(guess, 10)` converts the user’s input (which is a string) to an integer. The second argument, `10`, specifies that we’re using base-10 (decimal) numbers.
  • We include error handling:
    • Check if the user cancelled the prompt (`guess === null`).
    • Check if the parsed value is not a number (`isNaN(parsedGuess)`). If it’s not a number, we display an alert and recursively call `getUserGuess()` to prompt the user again.
  • The function returns the parsed integer if the input is valid or -1 if the prompt was cancelled.

3. Checking the Guess

Now, we need to compare the user’s guess with the random number and provide feedback.

// Check the guess
function checkGuess(guess: number, randomNumber: number): void {
  if (guess === -1) {
    alert("Game cancelled.");
    return;
  }
  if (guess === randomNumber) {
    alert(`Congratulations! You guessed the number ${randomNumber} correctly!`);
  } else if (guess < randomNumber) {
    alert("Too low! Try again.");
  } else {
    alert("Too high! Try again.");
  }
}

Explanation:

  • This function takes the user’s guess and the random number as input.
  • If the guess equals -1 (the user cancelled), the game is aborted.
  • It uses `if/else if/else` statements to compare the guess with the random number.
  • It provides feedback to the user using `alert()` based on whether the guess is too low, too high, or correct.

4. The Main Game Loop

We’ll now create the main game loop that orchestrates the game’s flow.

// Main game function
function playGame(): void {
  const randomNumber = Math.floor(Math.random() * 100) + 1;
  let userGuess: number;
  do {
    userGuess = getUserGuess();
    checkGuess(userGuess, randomNumber);
  } while (userGuess !== randomNumber && userGuess !== -1);
}

// Start the game
playGame();

Explanation:

  • `playGame()` is the main function that runs the game.
  • It generates a new random number at the start of the game.
  • It uses a `do…while` loop to repeatedly prompt the user for a guess and check it until the user guesses correctly or cancels the game.
  • Inside the loop:
    • `getUserGuess()` gets the user’s input.
    • `checkGuess()` checks the guess and provides feedback.
  • The loop continues as long as the user’s guess is not equal to the random number AND the user has not cancelled the game (guess is not -1).
  • `playGame()` is called to start the game.

Compiling and Running the Game

Now that we’ve written the code, let’s compile it and run the game.

  1. Open your terminal or command prompt.
  2. Navigate to your project directory:
cd number-guessing-game
  1. Compile the TypeScript code to JavaScript using the TypeScript compiler:
tsc

This command will create a new file, `index.js`, in your project directory. This file contains the JavaScript code generated from your TypeScript code.

  1. Run the JavaScript file using Node.js:
node index.js

This command will execute the JavaScript code, and the game will start in your terminal. You’ll be prompted to guess a number.

Enhancements and Next Steps

This is a basic number guessing game, but you can enhance it in several ways:

  • Add a Limit to the Number of Guesses: Keep track of the number of guesses the user has made and end the game if they exceed a certain limit.
  • Provide Hints: Give the user hints, such as whether their guess is closer to the number than their previous guess.
  • Implement a User Interface (UI): Instead of using `prompt()` and `alert()`, create an HTML/CSS/JavaScript UI for a more visually appealing and interactive experience. You can use frameworks like React, Angular, or Vue.js to simplify UI development.
  • Add Difficulty Levels: Allow the user to choose the range of numbers (e.g., 1-100, 1-1000).
  • Track Scores: Store the user’s score (number of guesses) and display it after the game.
  • Persistent Storage: Store high scores using local storage or a backend database.

Common Mistakes and How to Fix Them

Here are some common mistakes and how to fix them:

  • Type Errors: TypeScript’s type system can help catch errors. Make sure you declare the types of your variables and function parameters correctly. If you get a type error, read the error message carefully to understand what’s wrong and fix the type mismatch.
  • Incorrect Logic: Carefully review your code’s logic to ensure it behaves as expected. Use `console.log()` statements to debug your code and trace the values of variables.
  • Infinite Loops: Be careful with loops. Make sure your loop conditions are correct and that the loop will eventually terminate.
  • Incorrect User Input Handling: Always validate user input to prevent unexpected behavior. For example, make sure the user enters a valid number.

Key Takeaways

  • TypeScript Basics: This tutorial provided a hands-on introduction to TypeScript fundamentals, including variables, functions, conditional statements, and loops.
  • Error Handling: We learned how to handle potential errors, such as invalid user input.
  • Code Structure: We broke down the code into logical functions, making it easier to understand and maintain.
  • Project Setup: We covered the essential steps for setting up a TypeScript project.
  • Debugging: We discussed common mistakes and how to fix them.

FAQ

  1. Why use TypeScript for a simple game? TypeScript’s type system and features like autocompletion and refactoring can improve code quality, reduce errors, and make development more efficient, even for small projects. TypeScript also helps you scale your projects more easily.
  2. Can I use this game in a web browser? Yes, you can. You’ll need to create an HTML file with a script tag that includes the compiled JavaScript file (`index.js`). Replace the `prompt()` and `alert()` functions with HTML elements and JavaScript for the UI.
  3. How can I add more features to the game? Start by adding a limit to the number of guesses. Then, you can add hints, difficulty levels, and a UI.
  4. What are some good resources for learning more about TypeScript? The official TypeScript documentation (typescriptlang.org/docs/) is an excellent resource. You can also find many tutorials and courses on websites like freeCodeCamp, Udemy, and Coursera.
  5. How do I handle user input in a web browser? You can use HTML input elements (e.g., “) and JavaScript event listeners (e.g., `addEventListener(“click”, …)` for buttons or `addEventListener(“keydown”, …)` for key presses) to capture user input and trigger game logic.

By building this number guessing game, you’ve taken your first steps into the world of TypeScript. You’ve learned how to create a simple game, manage user input, and provide feedback. This project is a foundational building block for your future TypeScript endeavors. Remember to experiment, explore, and continue learning. The skills you’ve gained here will serve you well as you tackle more complex projects and delve deeper into the capabilities of this powerful language. Keep practicing, keep coding, and enjoy the journey!