Skip to content

Solution to Typing game #3 #73

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

Open
wants to merge 3 commits 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
105 changes: 105 additions & 0 deletions 1-js-basics/solution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@

# 1.Variables and Data Types

## Assignment
> For making a shopping cart I would first use String,int data types mainly.I might use array for some rare cases like including multiple items under one bigger group. Then would use boolean to know wheter the item is bought or no.
## Challenge
> Here when age=1; and Age=2; the java script treats both the variables as two different variable and returns false because both are different variables and 1!=2
### Gotchas
> 1. Another coommon type of gotcha is "==" vs "===" in cases like 12 == '12' it return true as javascript coerces them to same data type and compares the value but '===' strictly compares both the value and data type so in 12 === '12' it returns false
> 2. If we add a number to string then we end with string ,example 1+'1' then output would be like '11'.
> 3. NaN(Not a Number) is not equal to itself and if we use isNaN("") or isNaN([]) then javascript coerces them into number data type and then return true.
> 4. When new array is created it is created with empty items so we need to manually intialize it.
> 5. 0.1+0.2 !==0.3 as java using floating-point arithemetic so leads to precision errors.


# 2.functions-methods

## Assignment
> Function with no return:
```
function name(){
console.log("Sathvik");
}
name();
```
> Function with return:
```
function name(s){
return s;
}
name("Sathvik");
```
> Function with mixed parameters

```
function Details(name,age=0){
return {age,name};
}
Details("Sathvik");
Output:
Object { age: 0, name: "Sathvik" }
```
# 3.Making-decision

## Assingment

> Function performs set of tasks but method performs a set of tasks that are associated with an object.
```
const allStudents = [
'A',
'B-',
1,
4,
5,
2
]

let studentsWhoPass = [];
function pass(s){
if(typeof s =="number" && s>2){
studentsWhoPass.push(s);
}
else if(typeof s == "string" && s!== 'C-'){
studentsWhoPass.push(s)
}
}
allStudents.forEach(pass);
console.log(studentsWhoPass);
```
### Challenge
> Function with if .. else:
```
function check(s){
if(s === 200){
return 1
}
else{
return 0
}
}
check(150)
```
>Function with ternary operator
```
let a=200
const c = a === 200 ? 1:0;
console.log(c);
```
# 4.Arrays-loops

### Assignment
```

let arr=[]
for(let i=1;i<20;i++){
if(i%3 === 0){
arr.push(i);
}…
```
### Challenge

```
let arr=[1,23,4,45,6,7,8];
arr.forEach((element)=>console.log(element));
```
3 changes: 3 additions & 0 deletions typing-game-solution/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"liveServer.settings.port": 5501
}
Binary file added typing-game-solution/chrome.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions typing-game-solution/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!-- inside index.html -->
<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="quote"></p> <!-- This will display our quote -->
<p id="message"></p> <!-- This will display any status messages -->
<div>
<input type="text" aria-label="current word" id="typed-value" /> <!-- The textbox for typing -->
<button type="button" id="start">Start</button> <!-- To start the game -->
</div>
<script src="script.js"></script>
</body>
</html>
Binary file added typing-game-solution/mozilla.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
107 changes: 107 additions & 0 deletions typing-game-solution/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// inside script.js
// all of our quotes
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.',
];
// store the list of words and the index of the word the player is currently typing
let words = [];
let wordIndex = 0;
// the starting time
let startTime = Date.now();
// page elements

const quoteElement = document.getElementById('quote');
const messageElement = document.getElementById('message');
const typedValueElement = document.getElementById('typed-value');
// at the end of script.js
let best_time=parseFloat(localStorage.getItem("best_time")) || 10000000.0;

document.getElementById('start').addEventListener('click', () => {
// get a quote
const quoteIndex = Math.floor(Math.random() * quotes.length);
const quote = quotes[quoteIndex];
// Put the quote into an array of words
words = quote.split(' ');
// reset the word index for tracking
wordIndex = 0;

// UI updates
// Create an array of span elements so we can set a class
const spanWords = words.map(function(word) { return `<span>${word} </span>`});
// Convert into string and set as innerHTML on quote display
quoteElement.innerHTML = spanWords.join('');
// Highlight the first word
quoteElement.childNodes[0].className = 'highlight';
// Clear any prior messages
messageElement.innerText = '';

// Setup the textbox
// Clear the textbox
typedValueElement.value = '';
// set focus
typedValueElement.focus();
// set the event handler

// Start the timer
startTime = new Date().getTime();
able();
});
// at the end of script.js
typedValueElement.addEventListener('input', function runn() {
// Get the current word
const currentWord = words[wordIndex];
// get the current value
const typedValue = typedValueElement.value;

if (typedValue === currentWord && wordIndex === words.length - 1 ) {
// end of sentence
// Display success

const elapsedTime = new Date().getTime() - startTime;
if (elapsedTime<best_time){
best_time=elapsedTime/1000
localStorage.setItem("best_time",best_time)
}
const message = `CONGRATULATIONS! You finished in ${elapsedTime / 1000} seconds.
All time high score: ${localStorage.getItem("best_time")}`;
messageElement.innerText = message;
alert("Well Done!")
disable();
} else if (typedValue.endsWith(' ') && typedValue.trim() === currentWord) {
// end of word
// clear the typedValueElement for the new word
typedValueElement.value = '';
// move to the next word
wordIndex++;
// reset the class name for all elements in quote
for (const wordElement of quoteElement.childNodes) {
wordElement.className = '';
}
// highlight the new word
quoteElement.childNodes[wordIndex].className = 'highlight';
} else if (currentWord.startsWith(typedValue)) {
// currently correct
// highlight the next word
typedValueElement.className = '';
} else {
// error state
typedValueElement.className = 'error';
}

});
function disable(){
typedValueElement.disabled = true;
typedValueElement.removeEventListener("input",runn)


}
function able(){
typedValueElement.addEventListener("input",runn)
typedValueElement.disabled = false;
}
9 changes: 9 additions & 0 deletions typing-game-solution/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* inside style.css */
.highlight {
background-color: yellow;
}

.error {
background-color: lightcoral;
border: red;
}
16 changes: 16 additions & 0 deletions typing-game-solution/typing-game/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Guess-the-char</title>
</head>
<body>
<h1>GUESS THE CHARACTER!</h1>
<img id="char-img">
<p id="final"></p>
<input type="text" label="usrvalue" id="typed"/>
<button type="button" id="strt">START</button>

<script src="script.js"></script>
</body>
</html>
61 changes: 61 additions & 0 deletions typing-game-solution/typing-game/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const imageElemnt = document.getElementById("char-img")
const messageElement = document.getElementById("final")
const typedElement = document.getElementById("typed")
const url = "https://api.jikan.moe/v4/random/characters"
let char_name = ''
let max_attempts = 10


function stt() {
if (attempts >= max_attempts) {
messageElement.innerText = `Game Over! Your Score: ${score}/${max_attempts}`;
return;
}

typedElement.value = ''
messageElement.innerHTML = ''
typedElement.focus()

fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
imageElemnt.src = data.data.images.jpg.image_url
char_name = data.data.name
console.log(char_name)
})
.catch(error => console.error("Error fetching character:", error));
}

function check(event) {
if (event.key === "Enter") {
const typedVal = typedElement.value.trim().toLowerCase();

if (typedVal === char_name.toLowerCase()) {
score++;
messageElement.innerText = "Correct!"
} else {
messageElement.innerText = `Wrong! Correct answer: ${char_name}`
}

attempts++;

if (attempts < max_attempts) {
setTimeout(stt, 2000)
} else {
messageElement.innerText = `Game Over! Your Score: ${score}/${max_attempts}`;
}
}
}

document.getElementById("strt").addEventListener("click", () => {
attempts = 0;
score = 0;
stt();
});

typedElement.addEventListener("keydown", check);
28 changes: 28 additions & 0 deletions typing-game-solution/typing-game/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
body{
background-color: rgb(238, 169, 84);
text-align: center
;

}
h1{
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
color: aqua;
}
img{

border: 3px;
border-color: aqua;
}
#typed{
background-color: aqua;
color: rgb(238, 169, 84);
box-shadow: 1px

}
button{
background-color: aquamarine;
color: rgb(238, 169, 84);
box-shadow: transparent;
text-shadow: 1px;

}