Have you ever wanted to build your own game? Something simple, engaging, and fun? In this tutorial, we’ll dive into the world of TypeScript and create a classic number guessing game right in your web browser. This project is perfect for beginners and intermediate developers looking to sharpen their TypeScript skills while building something tangible.
Why Build a Number Guessing Game?
Creating a number guessing game is an excellent way to:
- Learn and practice fundamental programming concepts.
- Understand how to interact with the Document Object Model (DOM) in a web browser.
- Gain experience with event handling.
- Apply TypeScript’s type safety and features in a practical context.
Plus, it’s a fun project that you can easily share with friends and family!
Setting Up Your Development Environment
Before we start coding, let’s set up our development environment. You’ll need:
- A code editor (like Visual Studio Code, Sublime Text, or Atom).
- Node.js and npm (Node Package Manager) installed on your machine.
- A basic understanding of HTML, CSS, and JavaScript is helpful but not strictly required.
Once you have these installed, create a new project directory and navigate into it using your terminal. Initialize a new npm project by running:
npm init -y
This command creates a package.json file, which will manage our project dependencies.
Next, install TypeScript globally or locally (recommended):
npm install --save-dev typescript
Now, let’s create a tsconfig.json file to configure TypeScript. Run the following command in your terminal:
npx tsc --init
This command generates a tsconfig.json file with default settings. You can customize these settings to fit your project’s needs. For our game, the default settings will work fine, but you might want to uncomment and modify the following lines in your tsconfig.json file to enable stricter type checking and more modern JavaScript features:
{
"compilerOptions": {
"target": "ES2015",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
Now, create a directory named src and a file named index.ts inside it. This is where we’ll write our TypeScript code.
Building the Game Logic in TypeScript
Let’s start by defining the core game logic. Open src/index.ts and add the following code:
// Generate a random number between 1 and 100
const secretNumber: number = Math.floor(Math.random() * 100) + 1;
let attemptsLeft: number = 10;
// Function to check the user's guess
function checkGuess(): void {
const guessInput = document.getElementById('guessInput') as HTMLInputElement;
const guess = parseInt(guessInput.value, 10);
if (isNaN(guess) || guess 100) {
setMessage('Please enter a valid number between 1 and 100.');
return;
}
attemptsLeft--;
if (guess === secretNumber) {
setMessage(`Congratulations! You guessed the number ${secretNumber} in ${10 - attemptsLeft} attempts.`);
disableInputAndButton();
} else if (attemptsLeft === 0) {
setMessage(`Game over! The number was ${secretNumber}.`);
disableInputAndButton();
} else if (guess < secretNumber) {
setMessage(`Too low! Attempts left: ${attemptsLeft}`);
} else {
setMessage(`Too high! Attempts left: ${attemptsLeft}`);
}
clearInput();
}
// Function to set the message on the screen
function setMessage(message: string): void {
const messageElement = document.getElementById('message') as HTMLParagraphElement;
messageElement.textContent = message;
}
// Function to clear the input field
function clearInput(): void {
const guessInput = document.getElementById('guessInput') as HTMLInputElement;
guessInput.value = '';
}
// Function to disable the input field and guess button
function disableInputAndButton(): void {
const guessInput = document.getElementById('guessInput') as HTMLInputElement;
const guessButton = document.getElementById('guessButton') as HTMLButtonElement;
guessInput.disabled = true;
guessButton.disabled = true;
}
// Add event listener to the guess button
const guessButton = document.getElementById('guessButton') as HTMLButtonElement;
if (guessButton) {
guessButton.addEventListener('click', checkGuess);
}
// Initial message
setMessage('Guess a number between 1 and 100.');
Let’s break down this code:
secretNumber: A randomly generated number that the player needs to guess.attemptsLeft: The number of attempts the player has to guess the number.checkGuess(): This function is triggered when the player clicks the
