Learning how to code isn’t just about understanding algorithms or memorizing syntax. Sometimes, the best way to absorb concepts is by creating something practical—and fun! In this blog, we’ll walk through how to build a simple yet engaging Click-the-Button Game in JavaScript, covering essential coding concepts like event handling, DOM manipulation, and adding game logic.
By the end of this project, you’ll have a deeper understanding of JavaScript fundamentals and how they come together to create interactive web applications.
The Goal of Our Game
In this game, the player will:
- Click a button as many times as possible within a set time limit (10 seconds).
- Earn bonus points for fast clicks.
- See the button move randomly and shrink in size, increasing the difficulty.
Setting the Stage: HTML and CSS
We start with a basic HTML structure for the game interface. Here’s the code that sets up the game environment:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Click the Button Game - Enhanced</title>
<style>
body {
text-align: center;
font-family: Arial, sans-serif;
}
#clickButton {
padding: 20px;
font-size: 20px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<h1>Click the Button Game</h1>
<p>Score: <span id="score">0</span></p>
<p>High Score: <span id="highScore">0</span></p>
<p>Time left: <span id="time">10</span> seconds</p>
<button id="clickButton">Click me!</button>
<script src="game.js"></script>
</body>
</html>
What’s Happening Here?
- HTML: Sets up the structure for the game—a button to click, displays for the score, and time left.
- CSS: Ensures the button is centered and styled for readability.
This skeleton doesn’t do much yet, but it gives us a solid foundation for adding interactivity with JavaScript.
Let’s Add Interactivity: JavaScript Basics
Now we get to the fun part: writing JavaScript to add the game mechanics.
Game Logic & Event Handling
JavaScript is what makes the button clickable and responsive. The idea is to track how many times the button is clicked and how long the game lasts. We’ll also randomize the button’s position to keep the player engaged.
Here’s the full JavaScript code for the game:
let score = 0;
let highScore = 0;
let timeLeft = 10;
let gameRunning = false;
let buttonSize = 100; // Initial button size
let clickTime = 0;
let shrinkRate = 5; // Initial shrink rate
// Select elements from the DOM
const scoreDisplay = document.getElementById('score');
const highScoreDisplay = document.getElementById('highScore');
const timeDisplay = document.getElementById('time');
const clickButton = document.getElementById('clickButton');
// Function to start the game
function startGame() {
if (gameRunning) return;
gameRunning = true;
score = 0;
timeLeft = 10;
buttonSize = 100; // Reset the button size
shrinkRate = 5; // Reset shrink rate
scoreDisplay.textContent = score;
timeDisplay.textContent = timeLeft;
clickButton.textContent = 'Click me!';
clickButton.style.width = `${buttonSize}px`;
clickButton.style.height = `${buttonSize}px`;
// 3-second countdown before game starts
let countdown = 3;
clickButton.textContent = `Starting in ${countdown}`;
const countdownInterval = setInterval(() => {
countdown--;
clickButton.textContent = `Starting in ${countdown}`;
if (countdown === 0) {
clearInterval(countdownInterval);
clickButton.textContent = 'Click me!';
// Start the game timer
const timer = setInterval(() => {
timeLeft--;
timeDisplay.textContent = timeLeft;
// Increase difficulty: shrink faster over time
if (timeLeft < 5) {
shrinkRate = 8; // Button shrinks faster in the last 5 seconds
}
if (timeLeft === 0) {
clearInterval(timer);
gameRunning = false;
// Check if the player achieved a new high score
if (score > highScore) {
highScore = score;
highScoreDisplay.textContent = highScore;
}
clickButton.textContent = 'Game Over! Click to restart.';
}
}, 1000);
}
}, 1000);
}
// Function to move button to a random position
function moveButton() {
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const randomX = Math.floor(Math.random() * (windowWidth - buttonSize));
const randomY = Math.floor(Math.random() * (windowHeight - buttonSize));
clickButton.style.left = `${randomX}px`;
clickButton.style.top = `${randomY}px`;
}
// Function to decrease button size based on shrink rate
function shrinkButton() {
if (buttonSize > 30) {
buttonSize -= shrinkRate;
clickButton.style.width = `${buttonSize}px`;
clickButton.style.height = `${buttonSize}px`;
}
}
// Function to add bonus points for fast clicking
function addBonus() {
const currentTime = new Date().getTime();
if (currentTime - clickTime <= 500) { // Bonus if clicked within 0.5 seconds
score += 2; // Add bonus points
}
clickTime = currentTime;
}
// Function to handle button clicks
clickButton.addEventListener('click', () => {
if (!gameRunning) {
startGame(); // Start the game if it's not running
} else {
score++;
addBonus(); // Check if bonus points should be awarded
scoreDisplay.textContent = score;
moveButton(); // Move the button to a new random position
shrinkButton(); // Shrink the button each time it's clicked
}
});
Breaking Down Key Concepts
1. Event Listeners & DOM Manipulation
JavaScript interacts with HTML through the Document Object Model (DOM). Using the addEventListener()
function, we can listen for user events (like clicks) and update the game accordingly.
Example:
clickButton.addEventListener('click', () => {
// Handle button click logic here
});
This is the core of our game’s interactivity. When the button is clicked, we:
- Increase the score.
- Move the button to a new random position.
- Decrease its size to make the game harder.
2. Game Loops & Timers
We use setInterval()
to handle both the game’s countdown and the game-over timer. This function allows us to run a block of code at a regular time interval, updating the remaining time every second.
Example:
const timer = setInterval(() => {
timeLeft--;
timeDisplay.textContent = timeLeft;
}, 1000);
The timer decreases by one second every 1000 milliseconds (1 second). Once the time hits zero, the game ends.
3. Randomized Movement
To keep the player engaged, we move the button to random positions after each click. This is done using the Math.random()
function to calculate random x
and y
positions within the screen’s width and height.
Example:
const randomX = Math.floor(Math.random() * (windowWidth - buttonSize));
const randomY = Math.floor(Math.random() * (windowHeight - buttonSize));
clickButton.style.left = `${randomX}px`;
clickButton.style.top = `${randomY}px`;
4. Increasing Difficulty
The button gets smaller with each click. Initially, it shrinks by 5 pixels, but after the game hits the halfway point (5 seconds), it shrinks faster to make the game harder.
Example:
buttonSize -= shrinkRate;
clickButton.style.width = `${buttonSize}px`;
clickButton.style.height = `${buttonSize}px`;
5. Bonus Points for Quick Clicks
To reward fast reactions, we implement a simple bonus point system. If the player clicks the button within 0.5 seconds of its last movement, they earn 2 extra points.
Example:
if (currentTime - clickTime <= 500) {
score += 2; // Add bonus points
}
6. High Score Tracking
A key part of any game is keeping track of the player’s high score. We store the high score in a variable and update it whenever the player’s current score exceeds the previous high score.
Example:
if (score > highScore) {
highScore = score;
highScoreDisplay.textContent = highScore;
}
Bringing It All Together
We’ve now built a fun, interactive game that demonstrates fundamental JavaScript concepts in action. From DOM manipulation and event listeners to game loops, we’ve touched on several topics that are essential to web development.
Final Thoughts
By building this game, you’ve taken a significant step toward understanding JavaScript and how it can be used to create dynamic, engaging experiences on the web. Whether you’re just starting your journey in computer science or looking to expand your skills, these concepts will serve you well in future projects.
Ready for more? You can expand this game by:
- Adding levels or new challenges.
- Implementing sound effects.
- Storing the high score in the browser’s localStorage for long-term tracking.
Let me know how you plan to enhance your version of the game, or if you have any questions about the code. Happy coding!