TypeScript Tutorial: Creating a Simple Number Guessing Game

Ever wanted to create a fun, interactive game that you can play in your browser? How about learning a bit of TypeScript along the way? This tutorial will guide you step-by-step through building a simple number guessing game. It’s a fantastic project for beginners and intermediate developers alike, allowing you to grasp fundamental TypeScript concepts while creating something engaging and playable. We’ll cover everything from setting up your project to handling user input, providing feedback, and managing game logic. By the end, you’ll have a fully functional number guessing game and a solid understanding of how to use TypeScript to build interactive web applications.

Why Build a Number Guessing Game?

Creating a number guessing game is a great way to learn and practice several key programming concepts. Here’s why it’s a valuable project:

  • Fundamental Concepts: You’ll work with variables, data types, conditional statements (if/else), loops (while), functions, and user input – all core programming principles.
  • TypeScript Fundamentals: You’ll get hands-on experience with TypeScript’s type system, which helps catch errors early and improves code maintainability.
  • Interactive Experience: You’ll learn how to build interactive elements that respond to user actions.
  • Problem-Solving: You’ll practice breaking down a problem into smaller, manageable parts and finding solutions.
  • Fun and Engaging: It’s a fun project! You can easily customize and expand upon the game to make it even more interesting.

Setting Up Your TypeScript Project

Before we dive into the code, let’s set up our development environment. We’ll use Visual Studio Code (VS Code) as our code editor, but you can use any editor you prefer. We’ll also need Node.js and npm (Node Package Manager) installed to manage our project dependencies.

Here’s how to get started:

  1. Create a Project Directory: Create a new folder for your project. For example, you could name it “number-guessing-game”.
  2. Initialize npm: Open your terminal or command prompt, navigate to your project directory, and run the following command:
npm init -y

This command creates a `package.json` file, which will store information about your project and its dependencies.

  1. Install TypeScript: Install TypeScript as a development dependency by running:</li
npm install --save-dev typescript
  1. Create a TypeScript Configuration File: Create a `tsconfig.json` file in your project directory. This file tells the TypeScript compiler how to compile your code. You can generate a basic `tsconfig.json` by running:</li
npx tsc --init

This will create a `tsconfig.json` file with a lot of commented-out options. You can customize this file later, but the defaults are a good starting point.

  1. Create your TypeScript file: Create a file named `game.ts` (or any name you prefer) in your project directory. This is where we’ll write our game code.</li

Writing the Game Logic

Now, let’s write the core game logic. We’ll break it down into smaller, manageable steps:

1. Generate 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 to generate a random number between 0 and 1, and then scale it to the desired range (e.g., 1 to 100).

// 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).
  • `Math.random() * 100` scales the number to be between 0 and 99.999…
  • `Math.floor()` rounds the number down to the nearest integer (0 to 99).
  • `+ 1` shifts the range to be between 1 and 100.

2. Get User Input

Next, we need to get the user’s guess. For simplicity, we’ll use the `prompt()` function in the browser, though in a real-world application, you’d likely use HTML input fields and event listeners. However, the logic remains the same.

// Get user input
let userGuess: number | null = null;

while (userGuess === null) {
  const input = prompt("Guess the number (1-100):");

  if (input === null) {
    // User cancelled the prompt
    break; // Exit the loop
  }

  const parsedInput = parseInt(input, 10);

  if (!isNaN(parsedInput) && parsedInput >= 1 && parsedInput <= 100) {
    userGuess = parsedInput;
  } else {
    alert("Invalid input. Please enter a number between 1 and 100.");
  }
}

Explanation:

  • `prompt(“Guess the number (1-100):”)` displays a prompt box to the user and gets their input as a string.
  • `parseInt(input, 10)` attempts to convert the user’s input string to an integer (base 10).
  • `isNaN(parsedInput)` checks if the conversion resulted in a valid number.
  • The `if` statement validates the input to make sure it’s a number between 1 and 100.
  • If the input is invalid, an alert message is shown to the user.

3. Compare the Guess

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


if (userGuess !== null) {
  if (userGuess === randomNumber) {
    alert(`Congratulations! You guessed the number ${randomNumber} correctly!`);
  } else if (userGuess < randomNumber) {
    alert("Too low! Try again.");
  } else {
    alert("Too high! Try again.");
  }
}

Explanation:

  • We check if `userGuess` is not null (meaning the user entered a valid guess).
  • If the guess is correct, a congratulatory message is displayed.
  • If the guess is too low, a “Too low!” message is displayed.
  • If the guess is too high, a “Too high!” message is displayed.

4. Add a Game Loop (Optional but Recommended)

To make the game more engaging, let’s add a game loop so the user can keep guessing until they get it right. We’ll use a `while` loop for this.


// Game loop
let attempts = 0;
const maxAttempts = 10; // You can adjust the number of attempts

while (userGuess !== randomNumber && attempts = 1 && parsedInput <= 100) {
    userGuess = parsedInput;
    if (userGuess === randomNumber) {
      alert(`Congratulations! You guessed the number ${randomNumber} correctly in ${attempts + 1} attempts!`);
    } else if (userGuess < randomNumber) {
      alert("Too low! Try again.");
    } else {
      alert("Too high! Try again.");
    }
  } else {
    alert("Invalid input. Please enter a number between 1 and 100.");
  }
}

if (userGuess !== randomNumber && userGuess !== null) {
  alert(`You ran out of attempts. The number was ${randomNumber}.`);
}

Explanation:

  • `attempts` keeps track of the number of guesses.
  • `maxAttempts` sets the maximum number of guesses allowed.
  • The `while` loop continues as long as the guess is incorrect and the user has attempts remaining.
  • Inside the loop, the user is prompted to guess again, and the `attempts` counter is incremented.
  • The loop also checks if the user cancels the prompt or runs out of attempts, and it provides appropriate feedback.

Complete Code

Here’s the complete code for the number guessing game:


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

// Game loop
let userGuess: number | null = null;
let attempts = 0;
const maxAttempts = 10; // You can adjust the number of attempts

while (userGuess !== randomNumber && attempts = 1 && parsedInput <= 100) {
    userGuess = parsedInput;
    if (userGuess === randomNumber) {
      alert(`Congratulations! You guessed the number ${randomNumber} correctly in ${attempts + 1} attempts!`);
    } else if (userGuess < randomNumber) {
      alert("Too low! Try again.");
    } else {
      alert("Too high! Try again.");
    }
  } else {
    alert("Invalid input. Please enter a number between 1 and 100.");
  }
}

if (userGuess !== randomNumber && userGuess !== null) {
  alert(`You ran out of attempts. The number was ${randomNumber}.`);
}

Running the Game

To run the game, you’ll need to compile your TypeScript code into JavaScript and then run the JavaScript code in a web browser. Here’s how:

  1. Compile TypeScript: Open your terminal in the project directory and run the following command to compile your TypeScript code into JavaScript:
tsc game.ts

This will create a `game.js` file in your project directory.

  1. Create an HTML File: Create an HTML file (e.g., `index.html`) in your project directory. This file will load your JavaScript code and display the game in the browser. The HTML file should look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Number Guessing Game</title>
</head>
<body>
    <script src="game.js"></script>
</body>
</html>
  1. Open in Browser: Open the `index.html` file in your web browser. You should see the prompt to guess the number. Follow the prompts to play the game!</li

Common Mistakes and How to Fix Them

Here are some common mistakes beginners make when building this type of game and how to address them:

  • Incorrect Input Handling: Forgetting to validate the user’s input can lead to errors. Always check if the input is a valid number and within the expected range. Use `isNaN()` to check if the input is a number.
  • Off-by-One Errors: When generating random numbers, be careful about the inclusive/exclusive nature of the range. Make sure the range matches your game’s requirements (e.g., 1-100). Double-check your use of `Math.floor()` and `Math.random()`.
  • Infinite Loops: If you don’t handle user input correctly or have a flawed loop condition, you might end up with an infinite loop. Always make sure your loop has a clear exit condition, such as the user guessing the correct number or running out of attempts.
  • Missing or Incorrect Type Annotations: TypeScript relies on type annotations to catch errors. Make sure you’re properly annotating your variables, function parameters, and return types. This can save you a lot of debugging time.
  • Scope Issues: Be mindful of variable scope. Variables declared inside a function are only accessible within that function. If you need to access a variable from multiple parts of your code, declare it in a wider scope.

Enhancements and Next Steps

Once you’ve built the basic game, you can add several enhancements to make it more interesting and feature-rich:

  • GUI (Graphical User Interface): Instead of using `prompt()` and `alert()`, create a proper HTML user interface with input fields, buttons, and visual feedback.
  • Difficulty Levels: Add difficulty levels (e.g., easy, medium, hard) that change the range of the random number or the number of attempts.
  • High Scores: Store and display high scores using local storage or a database.
  • Hints: Provide hints to the user, such as whether their guess is closer to the correct number than their previous guess.
  • Play Again Button: Add a button to easily restart the game.
  • Limit Input Attempts: Add a counter to limit the number of attempts the player has.

Key Takeaways

This tutorial has provided a practical introduction to building a number guessing game with TypeScript. You’ve learned about generating random numbers, handling user input, providing feedback, and using loops. Moreover, you’ve gained experience with essential TypeScript concepts, such as variables, data types, conditional statements, and functions. This simple project serves as a solid foundation for more complex web development projects. Remember that practice is key. The more you code, the better you’ll become!

FAQ

  1. What is TypeScript? TypeScript is a superset of JavaScript that adds static typing. It helps catch errors early and improves code maintainability.
  2. Why use TypeScript for a simple game? Using TypeScript, even for a simple project, helps you learn the language, practice type annotations, and understand how TypeScript can improve your code quality.
  3. How can I deploy this game online? You can deploy your game online by hosting the HTML, JavaScript, and any other assets on a web server or using a platform like GitHub Pages or Netlify.
  4. Can I use this game as a starting point for a larger project? Absolutely! This game can be a stepping stone for more complex projects. You can add more features, create different game modes, and expand its functionality as you learn more about web development.
  5. Where can I learn more about TypeScript? The official TypeScript documentation ([https://www.typescriptlang.org/](https://www.typescriptlang.org/)) is an excellent resource. There are also many online tutorials, courses, and books available.

Building a number guessing game with TypeScript is an excellent way to solidify your understanding of core programming concepts and to start exploring the power of TypeScript. This project provides a clear, concise introduction to the language, and the step-by-step instructions make it easy to follow along. From generating random numbers to handling user input and providing feedback, you’ve now experienced the key elements of creating an interactive web application. The ability to customize and extend the game with your own ideas is a testament to the power of the project. Happy coding!