Open In App

Design a Calculate Expression Game in Tailwind CSS

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

This project is a “Calculate Expression Game” built using HTML, CSS (with Tailwind CSS for styling) and JavaScript. The game presents arithmetic expressions to the player who must then enter the correct result. The player’s score is tracked, along with number of the correct and incorrect answers. The game has a time limit and the final score is displayed when the time runs out.

a12

Approach:

  • Create an HTML file and include the necessary HTML structure.
  • Add Tailwind CSS for the styling and responsiveness.
  • Write JavaScript code to implement game logic including expression generation user input handling, scoring, timer and feedback.
  • Test the game thoroughly to ensure functionality and usability.

Example: The below code creates an expression calculating game using HTML, TailwindCSS, and JavaScript.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        The Calculate Expression Game
    </title>
    <link rel="stylesheet" href=
</head>
 
<body class="bg-gray-100">
    <div class="flex justify-center items-center h-screen">
        <div class="max-w-md w-full bg-white p-8 rounded-lg
            shadow-lg border-2 border-green-500">
            <h1 class="text-3xl font-bold text-center mb-8">
                Calculate Expression Game
            </h1>
            <div class="game">
                <div class="expression text-4xl text-center mb-4">
                    5 + 3
                </div>
                <input type="text" class="input-field border border-gray-300
                    rounded-md p-2 w-full text-center mb-4"
                    placeholder="Enter your answer" id="answerInput">
                <button class="btn-submit bg-indigo-600 text-white
                    rounded-md px-4 py-2 w-full text-lg mb-4"
                    id="submitButton">Submit</button>
                <div class="timer text-xl font-bold text-center mb-4">
                    Time left:
                    <span id="timer">
                        60
                    </span> seconds
                </div>
                <div class="score text-xl font-bold text-center mb-4">
                    Score:
                    <span id="score">
                        0
                    </span>
                </div>
                <div class="feedback hidden text-xl font-bold text-center mb-4"
                    id="feedback">Correct!</div>
                <div class="result text-center mt-4">
                    <div class="text-xl">
                        Correct:
                        <span id="correctCount" class="font-bold">
                            0
                        </span>
                    </div>
                    <div class="text-xl">
                        Incorrect:
                        <span id="incorrectCount" class="font-bold">
                            0
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
 
</html>


Javascript




document.
        addEventListener("DOMContentLoaded", function () {
            const expressionElement =
                document.querySelector('.expression');
            const answerInput =
                document.getElementById('answerInput');
            const submitButton =
                document.getElementById('submitButton');
            const timerElement =
                document.getElementById('timer');
            const scoreElement =
                document.getElementById('score');
            const feedbackElement =
                document.getElementById('feedback');
            const correctCountElement =
                document.getElementById('correctCount');
            const incorrectCountElement =
                document.getElementById('incorrectCount');
            let score = 0;
            let correctCount = 0;
            let incorrectCount = 0;
            let timeLeft = 60;
            function generateExpression() {
                const operands = ['+', '-', '*', '/'];
                const randomOperand =
                    operands[Math.floor(Math.random() * operands.length)];
                let num1, num2;
                switch (randomOperand) {
                    case '+':
                        num1 = Math.floor(Math.random() * 100);
                        num2 = Math.floor(Math.random() * 100);
                        break;
                    case '-':
                        num1 = Math.floor(Math.random() * 100);
                        num2 = Math.floor(Math.random() * num1);
                        break;
                    case '*':
                        num1 = Math.floor(Math.random() * 20);
                        num2 = Math.floor(Math.random() * 20);
                        break;
                    case '/':
                        num2 = Math.floor(Math.random() * 20) + 1;
                        num1 = num2 * Math.floor(Math.random() * 20);
                        break;
                    default:
                        break;
                }
                expressionElement.textContent =
                    `${num1} ${randomOperand} ${num2}`;
            }
            function updateScore() {
                score++;
                scoreElement.textContent = score;
            }
            function updateCorrectCount() {
                correctCount++;
                correctCountElement.textContent = correctCount;
            }
            function updateIncorrectCount() {
                incorrectCount++;
                incorrectCountElement.textContent = incorrectCount;
            }
            function updateTime() {
                timeLeft--;
                timerElement.textContent = timeLeft;
            }
            function checkAnswer() {
                const userAnswer = answerInput.value.trim();
                if (!userAnswer) {
                    alert("Please enter your answer.");
                    return;
                }
                const expression = expressionElement.textContent;
                const result = eval(expression);
                if (parseInt(userAnswer) === result) {
                    updateScore();
                    updateCorrectCount();
                    feedbackElement.textContent = 'Correct!';
                    feedbackElement.classList.remove('text-red-500');
                    feedbackElement.classList.add('text-green-500');
                } else {
                    updateIncorrectCount();
                    feedbackElement.textContent = 'Incorrect!';
                    feedbackElement.classList.remove('text-green-500');
                    feedbackElement.classList.add('text-red-500');
                }
                feedbackElement.classList.remove('hidden');
                setTimeout(() => {
                    feedbackElement.classList.add('hidden');
                    generateExpression();
                    answerInput.value = '';
                }, 1000);
            }
            generateExpression();
            const timerInterval = setInterval(() => {
                updateTime();
                if (timeLeft === 0) {
                    clearInterval(timerInterval);
                    submitButton.disabled = true;
                    answerInput.disabled = true;
                    feedbackElement.textContent =
                        `Game Over! Final score: ${score}`;
                    feedbackElement.classList.remove('hidden');
                }
            }, 1000);
            submitButton.addEventListener('click', () => {
                checkAnswer();
            });
        });


Output:

calExpGIF



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads