Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

This PR is the solution to the 'js-basics #3 #84

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
26 changes: 26 additions & 0 deletions 3-typing-game/typing-game-solution/assignment/assignment.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typing Quiz Game</title>
<link rel="stylesheet" href="assignment_style.css">
<script src="assignment_script.js" defer></script>
</head>
<body>
<h1>Typing Quiz Game</h1>
<p>Type the correct answer. One mistake and it's game over!</p>
<button id="start">Start game</button>

<div id="container">
<p id="question"></p>
<input type="text" id="answer" placeholder="Type your answer here...">
<button id="submit">Submit</button>
<button id="restart" class="hidden">Restart Quiz</button>

<p id="score">Score: 0 | High Score: <span id="high-score">0</span></p>
<p id="timer"></p>
<p id="game-over" class="hidden">Game Over! Press Restart to try again.</p>
</div>
</body>
</html>
109 changes: 109 additions & 0 deletions 3-typing-game/typing-game-solution/assignment/assignment_script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
let questions = [
{ question: "What year did the Soviet Union dissolve?", answer: "1991" },
{ question: "Who was the first person to win two Nobel Prizes?", answer: "Marie Curie" },
{ question: "What year did the Berlin Wall fall?", answer: "1989" },
{ question: "What element has the highest melting point?", answer: "Tungsten" },
{ question: "Unicorn is the national animal of which country?", answer: "Scotland" },
{ question: "Which Indian state has the longest coastline?", answer: "Gujarat" },
{ question: "What was the first country to leave the Soviet Union?", answer: "Lithuania" },
{ question: "Which country built the first high-speed rail system?", answer: "Japan" },
{ question: "What is the longest bone in the human body?", answer: "Femur" },
{ question: "What is the largest cryptocurrency by market cap?", answer: "Bitcoin" },
{ question: "Which country has the most number of time zones?", answer: "France" },
{ question: "What is the only sport to have been played on the moon?", answer: "Golf" },
{ question: "Which country was formerly known as Persia?", answer: "Iran" },
{ question: "The Library of Alexandria was located in which modern-day country?", answer: "Egypt" }
];

let score = 0;
let timer;
const timeLimit=30;
let timeLeft;

let highScore = localStorage.getItem("topscore") || 0;
document.getElementById("high-score").innerText = highScore;

let currentQuestionIndex = -1;
let usedQuestions = [];

function getRandomQuestion() {
if (usedQuestions.length == questions.length) {
document.getElementById("question").innerText = "You won! Refresh or restart to play again.";
document.getElementById("submit").disabled = true;
document.getElementById("answer").disabled = true;
return;
}

let randomIndex;
do {
randomIndex = Math.floor(Math.random() * questions.length);
} while (usedQuestions.includes(randomIndex));

usedQuestions.push(randomIndex);
currentQuestionIndex = randomIndex;
document.getElementById("question").innerText = questions[currentQuestionIndex].question;
displayTimer();
}

const timerElement=document.getElementById("timer");
function displayTimer(){
timeLeft=timeLimit;
timerElement.innerText=`Time left: ${timeLeft}`;
timer=setInterval(()=>{
if (timeLeft==0){
clearInterval(timer);
endGame();
}
else{
timerElement.innerText = `Time left: ${timeLeft}s`;
timeLeft--;
}
},1000)
}

const startButton=document.getElementById("start");
const container=document.getElementById("container");
container.style.display="none";
startButton.addEventListener("click", function () {
startButton.style.display = "none";
container.style.display = "block";
getRandomQuestion();
});

document.getElementById("submit").addEventListener("click", function () {
const userAnswer = document.getElementById("answer").value.trim();
if (userAnswer.toLowerCase() === questions[currentQuestionIndex].answer.toLowerCase()) {
score++;
document.getElementById("score").innerText = `Score: ${score} | High Score: ${highScore}`;
document.getElementById("answer").value = "";
getRandomQuestion();
} else {
endGame();
}});

function endGame(){
document.getElementById("game-over").classList.remove("hidden");
document.getElementById("restart").classList.remove("hidden");

if (score > highScore) {
localStorage.setItem("topscore", score);
document.getElementById("high-score").innerText = score;
}

document.getElementById("submit").disabled = true;
document.getElementById("answer").disabled = true;
}

document.getElementById("restart").addEventListener("click", function () {
score = 0;
usedQuestions = [];
document.getElementById("score").innerText = `Score: 0 | High Score: ${highScore}`;
document.getElementById("game-over").classList.add("hidden");
document.getElementById("restart").classList.add("hidden");
document.getElementById("submit").disabled = false;
document.getElementById("answer").disabled = false;
document.getElementById("answer").value = "";
getRandomQuestion();
});

getRandomQuestion();
96 changes: 96 additions & 0 deletions 3-typing-game/typing-game-solution/assignment/assignment_style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}


h1 {
margin-top: 20px;
font-size: 28px;
color: #333;
}


p {
font-size: 18px;
color: #555;
}


#question {
font-size: 22px;
font-weight: bold;
margin: 20px 0;
color: #222;
}


input {
padding: 10px;
font-size: 18px;
border: 2px solid #007bff;
border-radius: 5px;
width: 60%;
text-align: center;
outline: none;
transition: 0.3s;
}

input:focus {
border-color: #0056b3;
box-shadow: 0px 0px 10px rgba(0, 91, 187, 0.5);
}


button {
margin-top: 10px;
padding: 10px 20px;
font-size: 18px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}


button:hover {
background-color: #0056b3;
}


#score {
margin-top: 20px;
font-size: 20px;
font-weight: bold;
}


#game-over {
font-size: 22px;
font-weight: bold;
color: red;
margin-top: 15px;
}


.hidden {
display: none;
}


#restart {
background-color: #28a745;
margin-left: 10px;
}


#restart:hover {
background-color: #218838;
}


27 changes: 27 additions & 0 deletions 3-typing-game/typing-game-solution/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<html>
<head>
<title>Typing game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Typing game!</h1>
<p>Practice your typing skills with a quote from Sherlock Holmes. Click **start** to begin!</p>
<p id="highScoreDisplay">Best Time: -- seconds</p>
<p id="quote"></p>
<p id="message"></p>
<div>
<input type="text" aria-label="current word" id="typed-value" />
<button type="button" id="start">Start</button>
</div>
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2>Congratulations!</h2>

<p id="modal-message"></p>
</div>
</div>

<script src="script.js"></script>
</body>
</html>
83 changes: 83 additions & 0 deletions 3-typing-game/typing-game-solution/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
const quotes = [
'When you have eliminated the impossible, whatever remains, however improbable, must be the truth.',
'There is nothing more deceptive than an obvious fact.',
'I ought to know by this time that when a fact appears to be opposed to a long train of deductions it invariably proves to be capable of bearing some other interpretation.',
'I never make exceptions. An exception disproves the rule.',
'What one man can invent another can discover.',
'Nothing clears up a case so much as stating it to another person.',
'Education never ends, Watson. It is a series of lessons, with the greatest for the last.',
];

let words = [];
let wordIndex = 0;
let startTime = Date.now();

const quoteElement = document.getElementById('quote');
const messageElement = document.getElementById('message');
const typedValueElement = document.getElementById('typed-value');
const highScoreElement = document.getElementById('highScoreDisplay'); // High Score Display

let highScore = localStorage.getItem("highScore") || null;
if (highScore) {
highScoreElement.textContent = `Best Time: ${highScore} seconds`;
}

function startGame() {
const quoteIndex = Math.floor(Math.random() * quotes.length);
const quote = quotes[quoteIndex];

typedValueElement.disabled = false;
words = quote.split(' ');
wordIndex = 0;

const spanWords = words.map(word => `<span>${word} </span>`);
quoteElement.innerHTML = spanWords.join('');
quoteElement.childNodes[0].className = 'highlight';

messageElement.innerText = '';
typedValueElement.value = '';
typedValueElement.focus();

startTime = new Date().getTime();
}

document.getElementById('start').addEventListener('click', startGame);

typedValueElement.addEventListener('input', () => {
const currentWord = words[wordIndex];
const typedValue = typedValueElement.value;

if (typedValue === currentWord && wordIndex === words.length - 1) {
const elapsedTime = (new Date().getTime() - startTime) / 1000;
const message = `You finished in ${elapsedTime} seconds.`;


if (!highScore || elapsedTime < highScore) {
highScore = elapsedTime;
localStorage.setItem("highScore", highScore);
highScoreElement.textContent = `Best Time: ${highScore} seconds`;
}

document.getElementById("modal-message").innerText = message;
document.getElementById("modal").style.display = "block";

typedValueElement.removeEventListener('input', startGame);
typedValueElement.value = '';
typedValueElement.disabled = true;
} else if (typedValue.endsWith(' ') && typedValue.trim() === currentWord) {
typedValueElement.value = '';
wordIndex++;
for (const wordElement of quoteElement.childNodes) {
wordElement.className = '';
}
quoteElement.childNodes[wordIndex].className = 'highlight';
} else if (currentWord.startsWith(typedValue)) {
typedValueElement.className = '';
} else {
typedValueElement.className = 'error';
}
});

document.querySelector(".close").addEventListener("click", function() {
document.getElementById("modal").style.display = "none";
});
16 changes: 16 additions & 0 deletions 3-typing-game/typing-game-solution/solution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Challenge

* 1. Disabled the `input` event listener using `removeEventListener`and when the button is clicked, it is added again using `addEventListener`

* 2. The textbox is disabled when the game ends using the `disabled` property which is set to `true`.

* 3. First, I created a `div` in index.html to display the modal box. The modal box is not displayed when we start as the `display` property in CSS is set to `none`. After we complete the game, the modal box will popup as the `display` property is changed to `block` and will show you the congratulatory message.

* 4. The high score is stored and retrieved using id `highScore`. We us `localstorage.getItem` method for it.

# Assignment

For my assignment, I made a quiz game. A question will be displayed on the screen and you have to answer it within the specified time. If you answer it incorrectly or fail to answer it within the time limit, the game will end. The questions are displayed randomly by generating an index and then pushing it to the `usedQuestions` array. When generating an index, it will make sure that the index is not in usedQuetions. When length of the `usedQuestions` becomes equal to the length of `questions` array (where our questions and answers are stored), the game will end and the modal box will pop up, congradulating you.



Loading