Tallying incorrect answers for Javascript game - javascript

So I am trying to make a javascript game for my geography class but I have run into some trouble, I can ask the questions and tell you if you're wrong or not but I would like to be able to keep track of the wrongs answers. I want to keep track using for loops but I'm not good at them, some help would be greatly appreciated!
This is the basis of what every question looks like, it's just that && is where I need to add a single mark to the incorrect tally which I am sure I need to use for loops for.
var y = "You are correct!!!"
var n = "You are incorrect!!!"
alert("Chapter 1, Human Cultural Connections. 1-10")
//==================================================
var Q1 = prompt("Demographers identify three different stages of life.
They are children, working adults, and older adults. What is the age
range for children? 0-13, 0-15, 0-18")
if (Q1 === "0-13")
{
alert(y)
}
else
{
alert(n) //&& add 1 tally to incorrect list
}
If someone could help me out with this it would be sooo helpful, and don't worry this is past do anyways but I still want to know how to do it for future projects!
p.s. I already have the script HTML so I don't need help with that.

var correct = [], // well store the index of the correctly answered questions here
wrong = [], // well store the index of the incorrectly answered questions here
questions = [
{
"question": "Demographers identify three different stages of life. They are children, working adults, and older adults. What is the age range for children?",
"answers": ["0-13", "0-15", "0-18"],
"correct": 0 // correct answer is item of index 0 in property "answers" (0-13)
},
{
"question": "whats your favorite color?",
"answers": ["red", "yellow", "blue", "purple"],
"correct": 2 // blue
}
];
for (var i in questions){
var answer = prompt(questions[i].question + questions[i].answers.join(','));
if (answer == questions[i].answers[questions[i].correct]){
correct.push(i);
}else{
wrong.push(i);
}
}
alert('wrong number of answers: ' + wrong.length);
alert('correct number of answers: ' + correct.length);
alert('first wrong question: ' + questions[wrong[0]].question);
I know this is practically overwngineering what you asked for but it might give you better flexibility and knowledge as to how js for loops work. Hope it helps.

Add a variable to keep track of incorrect answers:
var y = "You are correct!!!"
var n = "You are incorrect!!!"
var incorrectCount = 0;
alert("Chapter 1, Human Cultural Connections. 1-10")
//==================================================
var Q1 = prompt("Demographers identify three different stages of life.
They are children, working adults, and older adults. What is the age
range for children? 0-13, 0-15, 0-18")
if (Q1 === "0-13")
{
alert(y)
}
else
{
alert(n) //&& add 1 tally to incorrect list
incorrectCount++;
}

Related

I want the "YOU ENTERED LEVEL X" message to be displayed only once. Please read the full question to understand it better

I need help for this code. Let me tell what the problem is. For example, after running the program , if the score is 4, as soon as user scores 4, it will be printed Congratulations!! You entered level 1 of the game and the same goes for level 2 and level 3 for the score 7 and 9 respectively. Now, the problem is- if user scores 4, then the line will be printed for Level 1 and if user fails to answer the next question, then again this line will be printed. What I want is that the line to be printed only once the user enters the score. I don't want it to be printed again and again if the user fails to pass the score for which the message is written. I hope I am able to explain the problem properly. If you don't get what I am trying to say, please tell me. I'll try to explain my problem more elaborately. Thank You. Below is the code
var readlineSync = require('readline-sync');
var userName = readlineSync.question("May we know your name please? ");
console.log("Hello " + userName + " to the neog.camp fun quiz game!!\n");
console.log("Please answer 4 questions correctly to reach Level 1 of the game,7 to reach Level 2 of the game, and 9 to reach Level 3 of the game.\nALL THE BEST :) \n\n");
var currentScore = 0;
var highScores =
{
azhar: 10,
bhargav: 7
};
function ask(question, answer) {
var userAnswer = readlineSync.question(question);
if (userAnswer === answer) {
console.log("Correct!!");
currentScore++;
console.log("score: ", currentScore);
}
else {
console.log("Wrong!!");
console.log("score: ", currentScore);
}
if(currentScore>=4 && currentScore<5)
{
console.log("Congrats!! You entered LEVEL 1 of the game!!")
}
if(currentScore>=7 && currentScore<8)
{
console.log("Congrats!! You entered LEVEL 2 of the game!!")
}
if(currentScore>=9 && currentScore<10)
{
console.log("Congrats!! You entered LEVEL 3 of the game!! Yippeee ;) ")
}
}
var questions =
[
{
question: "What is the capital of INDIA? ",
answer: "New Delhi"
},
{
question: "What is the full name of MS Dhoni? ",
answer: "Mahendra Singh Dhoni"
},
{
question: "Who founded Amazon ?",
answer: "Jeff Bezos"
},
{
question: "Which is the largest country in Asia? ",
answer: "China"
},
{
question: "How many sides does a quadrilateral have? ",
answer: "4"
},
{
question: "Which Indian Cricketer did hit six sixes in six balls against England in 2007? ",
answer: "Yuvraj Singh"
},
{
question: "What is the full form of CS GO? ",
answer: "Counter Strike Global Offensive"
},
{
question: "How many players are there in a football team excluding the goal keeper? ",
answer: "10"
},
{
question: "Which language is called the mother of all programming languages?",
answer: "C"
},
{
question: "What is the name of the highest mountain in the world? ",
answer: "Mount Everest"
}
];
for (var i = 0; i < questions.length; i++) {
var currentQuestion = questions[i];
ask(currentQuestion.question, currentQuestion.answer);
}
console.log("\nYour final score is : ", currentScore);
if (currentScore >= highScores.azhar) {
console.log("Congratulations!! You are the new highest scorer!! \t Kindly send the screenshot of the score to us.\nThank You")
}
else {
console.log("Oops!! You failed to beat the highest scorer!!\nBetter Luck Next Time")
console.log("High Scores :- \n" + "Azhar : " + highScores.azhar + "\nBhargav : " + highScores.bhargav);
}
The reason why your program outputs the string when the user fails, is because your program will check the score and print the string, regardless of whether the answer is correct or not.
In order to change this you must specify an exit condition in the case where the answer is wrong
function ask(question, answer) {
var userAnswer = readlineSync.question(question);
if (userAnswer === answer) {
console.log("Correct!!");
currentScore++;
console.log("score: ", currentScore);
}
else {
console.log("Wrong!!");
console.log("score: ", currentScore);
return
Unrelated to your question, but still an existing bug is the way you use userName inside console.log. Presently it will output "username" as a string, rather than the value of the variable. This needs to be re-written using backticks as follows:
console.log(`Hello ${userName} to the neog.camp fun quiz game!!\n`);
Looks like you're looking for something that stores the "state" (I will be murdered by frontend devs for calling it this) of the level.
Storing something like that could be as simple as
let currentLevel = 0 // or 1, depending on where you want them to start
With the current code, you would only need to add in an if statement which checks the level
if(currentScore>=4 && currentScore<5 && !currentLevel === 1)
{
console.log("Congrats!! You entered LEVEL 1 of the game!!")
currentLevel = 1
}
I think adding a return statement in the ask function after they have entered a wrong answer will do the trick.
else {
console.log("Wrong!!");
console.log("score: ", currentScore);
return; //<-- this line
}
It stops further execution of the ask function.
If you would like to refactor that function a bit more, you can do an early return check like this. You won't need the else statement, because your function returns early when the answer is wrong.
You can return whatever you like since you are not doing anything with the return value, in this example an undefined is returned.
//...
if (userAnswer !== answer) {
console.log("Wrong!!");
console.log("score: ", currentScore);
return;
}
console.log("Correct!!");
currentScore++;
console.log("score: ", currentScore);

Why is submitting the google form with response in "Others" option in checkbox not reflecting in individual response?

I am trying to submit the responses in a google sheet to google form. I found the script and made some changes to it.
There are some checkbox fields with "Other" as an option. In the google sheets, there are some responses with values for the "Other" field in some of the questions.
I can see the "Other" responses in the summary. But I cannot see those answers in individual responses.
I've used the method showOtherOption as well, but I couldn't get the solution.
Here is the script I am using:
function readSpreadsheet() {
var sheet = SpreadsheetApp.openById("123456");
var range = sheet.getDataRange();
var numRows = range.getNumRows();
var values = range.getValues();
var form = FormApp.getActiveForm();
var items = form.getItems();
for (var i = 2; i < numRows; i++) {
var value = values[i];
var formResponse = form.createResponse();
var k = 1;
for (var j = 0; j < items.length; j++) {
var item;
switch (items[j].getType()) {
case FormApp.ItemType.LIST:
item = items[j].asListItem();
formResponse.withItemResponse(item.createResponse(value[k++]));
break;
case FormApp.ItemType.MULTIPLE_CHOICE:
item = items[j].asMultipleChoiceItem();
var aa = value[k++];
formResponse.withItemResponse(item.createResponse(aa));
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
item = items[j].asParagraphTextItem();
formResponse.withItemResponse(item.createResponse(value[k++]));
break;
case FormApp.ItemType.TEXT:
item = items[j].asTextItem();
formResponse.withItemResponse(item.createResponse(value[k++]));
break;
case FormApp.ItemType.CHECKBOX:
item = items[j].asCheckboxItem();
var checkboxValue = value[k++];
if (typeof checkboxValue !== 'string') {
checkboxValue = checkboxValue.join(',');
}
var checkboxValueArr = checkboxValue.toString().split(/ *, */);
var choices = item.getChoices();
var foundElem = [];
var notFoundElem = [];
checkboxValueArr.forEach((elem) => {
if(choices.map((choice) => choice.getValue()).indexOf(elem) != -1) {
foundElem.push(elem);
} else {
notFoundElem.push(elem);
}
});
if(notFoundElem.length > 0) {
foundElem.push(notFoundElem.join(","));
}
item.showOtherOption(true);
formResponse.withItemResponse(item.createResponse(foundElem));
break;
default:
Logger.log("#" + (i + 1) + ":Do nothing for item " + j + " of type " + items[j].getType());
continue;
}
if(j==0){
Logger.log("This item is the FORM NUMBER");
};
}
formResponse.submit();
break;
}
}
Is there any other way I can get those options to be visible in individual responses ?
Edit: Here is the example format of the data.
Timestamp,Your name,Email ID,How old are you ?,Do you have any sources of income ?,How do you manage the money you earn ?,"Whom do you consult to manage your money apart from necessary expenses like rent, bills, etc ?",How well do you know about the ways you can save taxes ?,Can you share the reasons behind no knowledge or basic knowledge about taxes ?,Whom do you consult to invest your money ?,"In case you invest, what are challenges you've faced while trying learn and do it ?","In case you do not invest, what are the reasons you not to invest your money ?",Would you like to learn managing personal finances ?,Would you like to share your feedback on managing your own personal finances ?
7/3/2021 0:17:20,Name1,Email1,23-30 Years old,Yes,Pay the bills and rent and keep remaining in savings accounts,Nobody. I don't manage the money I earn,"I have basic knowledge. Example, 80C","Difficulty to understand the rules, I don't have enough time to learn about it, I don't know where to learn about saving taxes",Nobody. I don't invest money,Not applicable for me,"Lack of knowledge, I find the concepts difficult to understand, I find it risky, I don't know where to start",Yes,I wish to learn about financial literacy
7/3/2021 0:17:22,Name2,Email2,23-30 Years old,Yes,Pay the bills and rent and keep remaining in savings accounts,Friends/family,"I have basic knowledge. Example, 80C","Difficulty to understand the rules, Less reliable sources of information,lack of awareness",Friends/Family,"Lack of relavant and structured material to study, I did not have anyone to discuss with about investments, I found too many options for investment confusing, Lack of reliable source of information,scams make someone lose interest in investing","Lack of knowledge, I/My friends/relatives lost their money made me doubtful about investing, I find the concepts difficult to understand, I find it risky, I don't know where to start",Yes,
7/3/2021 0:17:24,Name3,Email3,23-30 Years old,Yes,"Pay the bills and rent and keep remaining in savings accounts, Invest in fixed deposit, Invest in mutual funds, Invest in stock market",Myself,Very well,,I manage it on my own,Lack of relavant and structured material to study,Not applicable for me,No,
7/3/2021 0:17:26,Name4,Email4,23-30 Years old,Yes,"Invest in fixed deposit, Invest in mutual funds, Invest in stock market, Invest in Tax saving schemes",Myself,"I have basic knowledge. Example, 80C",I think I know the question there is no such option,I manage it on my own,A lot of time required to study a particular stock.,Not applicable for me,Yes,no
It seems this is an issue as answered by Iamblichus.
There are 2 workarounds:
Method A: fetch the response with prefilled url
entry.XXX=__other_option__&entry.XXX.other_option_response=answer
Method B: add a question for the 'other' answer through Google Apps Script
Insert a section and a text question (i.e. itemOther) with blank title for 'other' answer right after your original question (i.e. item)
Jump the section created in 1. to hide it from UI submission
Show form questions based on answers
You may like to skip the (a) page break item and (b) 'other' question in your items loop
(a) add FormApp.ItemType.PAGE_BREAK to you switch argument
case FormApp.ItemType.PAGE_BREAK:
break;
(b) add a if statement before the switch argument
if (items[j].getTitle === '') continue;
Modify the code to handle 'other' answer
let included = false;
for (const choice of item.getChoices()) {
if (value[k++] === choice.getValue()) {
included = true;
break;
}
}
if (included) {
formResponse.withItemResponse(item.createResponse(value[k++]));
}
else {
formResponse.withItemResponse(item.createResponse('__other_option__'));
formResponse.withItemResponse(itemOther.createResponse(value[k++]));
}
showOtherOption(true) is used to enable 'other' option when you add or edit the question

I am trying to scrape amazon, and stop at a specific number

So this is my code
if (body.included != null && body.included.length > 0) {
let genres = '';
for(let i = 0; i < body.included.length; i++) {
genres += body.included[i].attributes.title;
if(i != body.included.length - 1) {genres += ', ';}
}
embed.addField('GENRES', [`${genres}`,], true);
}
this is the results whenever i search anything with this it gives me this:
Comedy, Kids, Fantasy, Fantasy World, Erotic Torture, Loli, Nudity, Bdsm, Bondage, Sex, Past, Plot Continuity, Violence, Military, Mecha, Historical, Action, Romance, Science Fiction, World War II, Japan, Asia, Piloted Robot, Alternative Past, Steampunk, Gunfights, Alien, War, Robot, Adventure, Space Travel, Cyborg, Crime, Other Planet, Humanoid Alien, Future, Space, Contemporary Fantasy, Vampire, Slice of Life, Detective, Bounty Hunter, Magic, Present, Demon, Super Power, Drama, Anime Influenced, Earth, Love Polygon, Angst, High School, School Life
Has this a example because other types searches comes with 1 or 2 or decent amount of genres where it doesn't have like 40 of them
like this one
Ninja, Fantasy World, Adventure, Action, Comedy, Martial Arts, Super Power, Romance, Disaster, Shounen, Love Polygon, Angst, Plot Continuity, Parallel Universe, Fantasy
So what i need help is how do i make it stop in a certain number where it wont give me 40 of them instead 10 or less
You could change the loop condition but still need to watch out for the length of the body.included array for cases where it has fewer than 10 elements. Try the following:
const MAX_GENRES = 10;
if (body.included && body.included.length) {
const max = Math.min(MAX_GENRES, body.included.length);
const genres = [];
let i = 0;
while (i < max) {
genres.push(body.included[i].attributes.title);
i += 1;
}
embed.addField('GENRES', [genres.join(',')], true);
}
This should achieve what you're after. I don't know the signature for embed.addField() but are you certain that the second argument should be a single-element array containing a string? Could be but seems weird. If the function calls for an array of strings use:
embed.addField('GENRES', genres, true);

Using text input by the user to access an array of that name?

As part of an assignment for uni i've been asked to write a question worth 10 marks and then write a solution and marking scheme for said question.
This is my question;
Write a program that will store the top ranking fighters of 3 weight divisions in the UFC (using the following data);
-Featherweight; Connor McGregor, Jose Aldo, Frankie Edgar, Max Holloway, Anthony Pettis.
-Lightweight; Connor McGregor, Khabib Nurmagomedov, Tony Ferguson, Eddie Alvarez, Rafael dos Anjos.
-Light heavyweight; Daniel Cormier, Anthony Johnson, Alexander Gustafsson, Ryan Bader, Glover Teixiera.
Prompt the user to enter the name of a weight division in the UFC and return the ranking the the format;
Current Champion is ….
1st contender is …..
2nd contender is ……
Etc.
So far in my solution for the questioni have had the user enter the name of a weight division, however i now have the problem of trying to use that specific variable in a loop.
This is my code so far;
//Declaration of the arrays to store the ranking of the weight divisions;
var featherweight = ["Connor McGregor", "Jose Aldo", "Frankie Edgar", "Max Holloway", "Anthony Pettis"];
var lightweight = ["Connor McGregor", "Khabib Nurmagomedov", "Tony Ferguson", "Eddie Alarez", "Rafael dos Anjos"];
var lightHeavyweight = ["Daniel Cormier", "Anthony Johnson", "Alexander Gustafsson", "Ryan Bader", "Glovier Teixiera"];
//Declaring the output variable to store and add to what will be output before it is displayed;
var output = "";
//Variable to store the user input and a prompt to recieve the users input;
var userInput = prompt("Please enter the name of a weight devision you would like to see the rankings off. \n Options are; \n - featherweight \n - lightweight \n - lightHeavyweight");
//loop that will continue adding items to the output for the length of the array that the user has asked to see.;
for (var i = 0; i < )
Help is greatly appreciated, and thanks in advance!
Before the loop you should have chained if statements:
var chosenArray;
if (input === "x")
{
chosenArray = xArray;
}
elseif (input === "y")
{
chosenArray = yArray;
}
...
else
{
// should print that the input is unknown
}
// should use chosenArray for loop

Break up a string in JS

I have a script built to grab a quote from an array at random, and display it.
I'm trying to format it so it would split the quote and the author like so:
"Insert quote"
Name of person saying Quote
I've tried using split with \n and <br /> and nothing works, even in an alert.
here is my code:
//Initalize the array
var quotes = [];
//Insert data into the array
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
quotes[1] = "Video games are bad for you? That's what they said about rock n' roll." + "Shigeru Miyamoto";
quotes[2] = "I'd like to be known as the person who saw things from a different point of view to others." + "Shigeru Miyamoto";
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
quotes[4] = "The future was uncertain, absolutely, and there were many hurdles, twists, and turns to come, but as long as I kept moving forward, one foot in front of the other, the voices of fear and shame, the messages from those who wanted me to believe that I wasn't good enough, would be stilled." + "Chris Gardner";
quotes[5] = "Running a start-up is like eating glass. You just start to like the taste of your own blood." + "Sean Parker";
quotes[6] = "I used to drink cristal, the muh'fucker's racist. So I switched gold bottles on to that Spade shit" + "Shawn Carter (Jay Z)";
quotes[7] = "I think it's better to let my work do the talking" + "Shigeru Miyamoto.";
quotes[8] = "Success is a lousy teacher. It seduces smart people into thinking they can't lose." + "Bill Gates";
quotes[9] = "We need to reengineer companies to focus on figuring out who the customer is, what's the market and what kind of product you should build." + "Eric Ries";
quotes[10] = "I have no friends and no enemies - only competitors." + "Aristole Onassis";
quotes[11] = "Working 24 hours a day isn't enough anymore. You have to be willing to sacrifice everything to be successful, including your personal life, your family life, maybe more. If people think it's any less, they're wrong, and they will fail." + "Kevin O'Leary";
quotes[12] = "My hope is to the see the benefits of my labour spread out in the community." + "W. Brett Wilson";
quotes[13] = "I'm not here to make friends; I'm here to make money." + "Kevin O'Leary";
quotes[14] = "Good artists copy, great artists steal" + "Pablo Picasso";
quotes[15] = "Welcome ladies and gentlemen to the eighth wonder of the world. The flow of the century, always timeless; HOV!" + "Shawn Carter (Jay Z)";
quotes[16] = "Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel";
quotes[17] = "I believe life is an intelligent thing: that things aren't random." + "Steve Jobs";
quotes[18] = "Pretty? You mean like rainbows, unicorns, and sparkles?" + "Michelle Brown";
quotes[19] = ".....and for that reason, I'm OUT!" + "Mark Cuban";
//Splits the quote into two pieces, the quote and the person.
var quoteSplit = function (quotes) {
var split = quotes.split("+").replace("\n");
}
//Displays a quote from the array at random.
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote);
//END
When you're building your array, you are concatenating the quote with the author. So this:
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
Ends up with this string being set to quotes[0]
It doesn't matter how many times you have failed, you only have to be right once.Mark Cuban
And your split statement will not work, because the + is not included in the string. This isn't a great way of setting up your array, though. What happens if your quote contains the + symbol, for example?
A better way would be to create an object for each item:
quotes[0] = {
text: "It doesn't matter how many times you have failed, you only have to be right once.",
author: "Mark Cuban"
}
Then you can do:
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote.text + '<br>' + displayQuote.author);
It's seems that + sign is not in your string. The following code:
console.log("Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel");
will return to you string
Today’s “best practices” lead to dead ends; the best paths are new and untried.Peter Thiel;
So, you just have to include + sig in your strings like that:
"Today’s “best practices” lead to dead ends; the best paths are new and untried.+Peter Thiel"
As Daniel A. White said in the comments section. You are considering + to be part of the string but you are in fact concatenating 2 strings on each index.
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
should be:
quotes[3] = "Stay hungry, stay foolish, stay crazy.+Steve Jobs";
Or you could use regex ( Unfortunately I can't provide a regex example right now ) but those are two of your possible options.
If you output any element of your array, you'll see that each entry is a single string with quote and person. Ex.
console.log(quotes[3]);
Stay hungry, stay foolish, stay crazy.Steve Jobs
That's because + concatenates when applied to strings.
As suggested in the comments, you could use split on punctuation marks, although that would break some of your quotes.
You could do something like
quotes[3]=["Stay hungry, stay foolish, stay crazy.","Steve Jobs"];
and output each element separately.
Try this:
var quotes = {
1: {
quote: 'Hello world.',
author: 'Test test'
},
2: {
quote: 'Hello world 2.',
author: 'Test test 2'
},
};
// Display random quote
function displayQuote(){
var key = Math.floor(Math.random() * Object.keys(quotes).length + 1);
return quotes[key].quote + ' ' + quotes[key].author;
};
document.write(displayQuote());

Categories