In this blog post, we will explore how to create a simple game using HTML, CSS, and JavaScript. This game will be a basic clicking game where players must click a moving target on the screen as many times as possible within a given timeframe. This project is perfect for beginners looking to practice their web development skills while building something fun and interactive!
First, create a new folder for your project and inside that, create three files: index.html
, styles.css
, and script.js
.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Click Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="game-container"> <div class="target" id="target"></div> <div class="score" id="score">Score: 0</div> <button onclick="startGame()">Start Game</button> </div> <script src="script.js"></script> </body> </html>
styles.css
body, html { height: 100%; margin: 0; display: flex; justify-content: center; align-items: center; background: #f0f0f0; } .game-container { text-align: center; } .target { width: 50px; height: 50px; background-color: red; position: absolute; border-radius: 50%; cursor: pointer; display: none; } .score { margin-bottom: 20px; }
Let's add the functionality with JavaScript now.
script.js
let score = 0; const target = document.getElementById('target'); const scoreDisplay = document.getElementById('score'); function moveTarget() { const x = Math.random() * (window.innerWidth - 50); const y = Math.random() * (window.innerHeight - 50); target.style.left = x + 'px'; target.style.top = y + 'px'; } function startGame() { target.style.display = 'block'; moveTarget(); setInterval(moveTarget, 1000); setTimeout(() => { target.style.display = 'none'; alert('Game Over! Your score is: ' + score); score = 0; scoreDisplay.innerText = 'Score: 0'; }, 10000); } target.addEventListener('click', () => { score++; scoreDisplay.innerText = 'Score: ' + score; });
To play the game, simply open the index.html
file in a browser. Click the "Start Game" button to begin, and try to click the moving target as many times as you can in 10 seconds. The score will update in real-time as you click the target.
You have now created a simple but engaging game using just HTML, CSS, and JavaScript. This project covers concepts such as DOM manipulation, event handling, and animations in web development. As and when you become more comfortable with these technologies, you can add more interesting features like different levels, timers, or even a high score board. Have fun coding and have fun with your new game!
Bonus:
Try the game here: https://thecodeground.in/ground/web/9406584a-3445-4cf3-83b1-6d6236a6f734