By Vijay Pancholi | Simple Game Based on HTML CSS JQUERY Based - Catch the Square
by Vijay Pancholi
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Catch the Square Game</title>
</head>
<body>
<h1>🎯 Catch the Square!</h1>
<div id="score">Score: 0</div>
<div id="timer">Time Left: 30s</div>
<button id="start-btn">Start Game</button>
<div id="game-box">
<div class="square" id="square"></div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>
CSS
body {
font-family: Arial, sans-serif;
text-align: center;
background: #f4f4f4;
}
#game-box {
width: 400px;
height: 400px;
border: 4px solid #333;
margin: 40px auto;
position: relative;
background-color: #fff;
}
.square {
width: 50px;
height: 50px;
background-color: crimson;
position: absolute;
display: none;
cursor: pointer;
border-radius: 5px;
}
#score, #timer {
font-size: 24px;
margin: 10px;
}
#start-btn {
padding: 10px 20px;
font-size: 18px;
background-color: teal;
color: white;
border: none;
cursor: pointer;
}
#start-btn:hover {
background-color: darkcyan;
}
JavaScript
let score = 0;
let timeLeft = 30;
let timerInterval;
let moveInterval;
function randomPosition() {
let box = $("#game-box");
let square = $("#square");
let maxX = box.width() - square.width();
let maxY = box.height() - square.height();
let randX = Math.floor(Math.random() * maxX);
let randY = Math.floor(Math.random() * maxY);
square.css({ top: randY + "px", left: randX + "px" });
}
function startGame() {
score = 0;
timeLeft = 30;
$("#score").text("Score: " + score);
$("#timer").text("Time Left: " + timeLeft + "s");
$("#start-btn").hide();
moveSquare();
timerInterval = setInterval(() => {
timeLeft--;
$("#timer").text("Time Left: " + timeLeft + "s");
if (timeLeft <= 0) {
endGame();
}
}, 1000);
}
function moveSquare() {
moveInterval = setInterval(() => {
$("#square").fadeOut(100, () => {
randomPosition();
$("#square").fadeIn(100);
});
}, 1000);
}
function endGame() {
clearInterval(timerInterval);
clearInterval(moveInterval);
$("#square").hide();
$("#start-btn").show().text("Play Again");
alert("Game Over! Your final score is: " + score);
}
$(document).ready(function () {
$("#start-btn").click(startGame);
$("#square").click(function () {
score++;
$("#score").text("Score: " + score);
$(this).hide(); // disappear on click
});
});