Open In App

Create a Math Sprint Game in HTML CSS & JavaScript

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

The math sprint game presents random math questions with four options. Players click the correct answer, and if correct, it’s acknowledged; otherwise, an incorrect answer message is shown. A 20-second timer adds urgency, ending the game. The score (High Score) is displayed, along with buttons to start or restart the game.

m1

Approach

  • First, we make a folder for our project and create HTML, CSS, and JavaScript files inside it.
  • In the HTML file, we design the layout for Math Sprint Game. We include question, options, two buttons as start and restart.
  • In the CSS file, we style the Math Sprint Game to make them look better. We use conditions like game is not start until we click on start button.
  • In the JavaScript file, we write the main logic of our project. We use it in such a way that when a button is clicked, the mathematical problems come one by one with random numbers.
  • By organizing our project in this way, we can easily manage the code for creating Math Sprint Game

Example: The below code example implements the HTML, CSS and JavaScript to create Math Sprint Game.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        Math Sprint Game
    </title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <h1>
            Math Sprint Game
        </h1>
        <p id="problem"></p>
        <div class="options" id="options"></div>
        <p id="result"></p>
        <p class="score">
            Score: 
            <span id="currentScore">0</span>
        </p>
        <p id="timer">
            Time: 
            <span id="time">20</span> 
            seconds
        </p>
        <button onclick="startGame()">
            Start Game
        </button>
        <button onclick="resetGame()">
            Reset Game
        </button>
        <p id="highScore">
            High Score: 
            <span id="highScoreValue">0</span>
        </p>
    </div>

    <script src="script.js"></script>
</body>

</html>
CSS
body {
    font-family: 'Arial', sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
    background: 
    linear-gradient(to bottom, #ef4444, #f59e0b, #9333ea);
    color: #333;
}

.container {
    text-align: center;
    background-color: rgb(247, 241, 241);
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
    font-size: 36px;
    color: rgb(95, 90, 90);
    font-family: 'Times New Roman', Times, serif;
}

p {
    font-size: 30px;
    margin: 10px 0;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
}

.options {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    font-family: 'Times New Roman', Times, serif;
}

.option {
    margin: 0 10px;
    padding: 10px 20px;
    cursor: pointer;
    background-color: rgb(241, 241, 18);
    color: black;
    border: 1px solid gray;
    border-radius: 5px;
    font-size: 20px;
    transition: background-color 0.3s ease;
}

.option:hover {
    background-color: rgb(248, 248, 42);
}

button {
    margin-top: 20px;
    padding: 10px 25px;
    cursor: pointer;
    background-color: #f39c12;
    color: #fff;
    border: 1px solid gray;
    border-radius: 5px;
    font-weight: bold;
    font-size: 20px;
    transition: background-color 0.3s ease;
}

button:hover {
    background-color: #d35400;
}

.score {
    margin-top: 20px;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
    font-size: 24px;
    color: #27ae60;
}

#timer {
    margin-top: 20px;
    font-size: 20px;
    color: #333;
    background-color: #bdc3c7;
    padding: 10px 5px;
    border-radius: 5px;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
}

#highScore {
    margin-top: 20px;
    font-size: 25px;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
    color: green;
}

#result {
    margin-top: 20px;
    font-size: 24px;
    font-family: 'Times New Roman', Times, serif;
    color: red;

}

.incorrect {
    color: red;
}

.correct {
    color: green;
}

/* Responsive Styles */
@media only screen and (max-width: 600px) {
    .container {
        width: 90%;
    }

    h1 {
        font-size: 28px;
    }

    p {
        font-size: 24px;
    }

    .option {
        font-size: 18px;
        padding: 5px 12px;
    }

    button {
        font-size: 18px;
        padding: 8px 20px;
    }

    .score {
        font-size: 20px;
    }

    #timer {
        font-size: 18px;
    }

    #highScore {
        font-size: 20px;
    }

    #result {
        font-size: 20px;
    }
}
Javascript
let timer;
let time = 20;
let score = 0;
let highScore = 0;

function startGame() {
    resetGame();
    generateProblem();
    generateOptions();
    timer = setInterval(updateTimer, 1000);
    document.getElementById('highScoreValue').
        innerText = highScore;
}

function resetGame() {
    clearInterval(timer);
    time = 20;
    score = 0;
    document.getElementById('time').
        innerText = time;
    document.getElementById('result').
        innerText = '';
    document.getElementById('currentScore').
        innerText = score;
    document.getElementById('options').
        innerHTML = '';
    document.getElementById('problem').
        innerText = '';
    document.getElementById('highScoreValue').
        innerText = '0';
}

function updateTimer() {
    time--;
    document.getElementById('time').innerText = time;
    if (time === 0) {
        endGame();
    }
}

function generateProblem() {
    const num1 = Math.floor(Math.random() * 10);
    const num2 = Math.floor(Math.random() * 10);
    const operation = getRandomOperation();

    let problem;

    switch (operation) {
        case '+':
            problem = `${num1} + ${num2}`;
            break;
        case '-':
            problem = `${num1} - ${num2}`;
            break;
        case '*':
            problem = `${num1} * ${num2}`;
            break;
        case '/':
            // Ensure a non-zero divisor
            const divisor = num2 !== 0 ? num2 : 1;
            const result = (num1 / divisor).toFixed(2);
            problem = `${num1} / ${divisor}`;
            break;
        default:
            // Handle unexpected operations
            problem = '';
    }

    document.getElementById('problem').
        innerText = problem;
}

function getRandomOperation() {
    const operations = ['+', '-', '*', '/'];
    const randomIndex =
        Math.floor(Math.random() *
            operations.length);
    return operations[randomIndex];
}


function generateOptions() {
    const problemText = document.
        getElementById('problem').innerText;
    const correctAnswer = eval(problemText);
    const options = [correctAnswer];

    // Determine if the problem involves 
    // division or multiplication
    const isDivision = problemText.includes('/');
    const isMultiplication = problemText.includes('*');

    while (options.length < 4) {
        let option;
        if (isDivision || isMultiplication) {
            // For division and multiplication, 
            // generate options with 2 decimal places
            option = correctAnswer + (Math.random() * 20 - 10);
            option = parseFloat(option.toFixed(2));
        } else {
            // For other operations, generate options as before
            option = correctAnswer +
                Math.floor(Math.random() * 10) - 5;
        }

        if (!options.includes(option)) {
            options.push(option);
        }
    }

    options.sort(() => Math.random() - 0.5);

    const optionsContainer =
        document.getElementById('options');
    optionsContainer.innerHTML = '';
    options.forEach((option, index) => {
        const button =
            document.createElement('button');
        button.classList.add('option');
        button.innerText = option.toFixed(2);
        button.onclick = () =>
            selectOption(option, correctAnswer);
        optionsContainer.appendChild(button);
    });
}



function selectOption(selectedOption, correctAnswer) {
    if (selectedOption === correctAnswer) {
        document.getElementById('result').innerHTML =
            `<span class="correct">
                Correct!
            </span>`;
        score++;
        document.getElementById('currentScore').
            innerText = score;
        generateProblem();
        generateOptions();
    } else {
        document.getElementById('result').innerHTML = 
            `<span class="incorrect">
                Incorrect. Try again.
            </span>`;
    }

}
function endGame() {
    clearInterval(timer);
    document.getElementById('result').innerText = 
        'Time is up! Game over.';
    document.getElementById('options').innerHTML = '';
    document.getElementById('problem').innerText = '';
    updateHighScore();
}

function updateHighScore() {
    if (score > highScore) {
        highScore = score;
        document.getElementById('highScoreValue').
            innerText = highScore;
    }
}

Output:

web1



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads