DEV Community

Cover image for Making Node CLI(Command Line Interface) quiz app
mimansha-swarup
mimansha-swarup

Posted on

Making Node CLI(Command Line Interface) quiz app

Let's Make a Quiz App which you can share with our family and Friends

Preview
So to make this quiz app we will use Repl.it, you can also use VS Code or any other code editor.

Setting up the enviorment

We will use two node modules

  1. readline-sync: It can take input in various manner from user
  2. chalk: it is an expressive api which adds colors and styling

So if you are using repl you can directly use require function
to include these modules example:

const rs =require('readline-sync');
const chalk = require('chalk');
Enter fullscreen mode Exit fullscreen mode

If you are on VS Code
open the project folder on terminal and use command
npm init -y
this mean to initialize package manager and -y means yes
so after this just run this command to get above mentioned modules
npm install --save readline-sync chalk
now make a JavaScript file and write the require statement mentioned above

Note: In repl you don't need to manually install modules

Figuring out quiz app

  • So we want to make a quiz app which will take input for asked question and check whether the answer is correct or not -For every correct answer we will increment marks by 2 and for incorrect answer we will reduce by 1
  • Also we will have to see if user beat the High score

Planing a bit more precise

  • we will greet the user and ask for the user name
  • We need a global variable to keep account of score
  • We need a function to evaluate whether user answer is correct or not
  • We need a array of questions and answers which can be done by using array of objects with key vale question and answer
  • We need a for loop to iterate this array -At last need to check whether User Defeated High score or not

Coding Part

we have already imported required module and now we have to ask user name and greet as well as create a global variable, ok so it will be like this

// importing
const rs =require('readline-sync');
const chalk = require('chalk');

console.log(chalk.green.bold("Welcome to The Game!!!\n"));

// asking name
var playerName = rs.question("HEy Whats ur Name : ");

//greeting user
console.log(chalk.yellow(`Welcome ${playerName}\n`));


//global variable to keep account of score
var score = 0;
Enter fullscreen mode Exit fullscreen mode
  • rs.question() helps us to take user input from console read this for more info
  • chalk.bold means make the string bold while printing it and chalk.yellow means the printed string should be of color yellow read this for more info

Now we will implement the function which will check user answer is correct or not if answer is correct we will increment the score by 2 and print correct in green color, and if it's not correct then we will print wrong in red color and print the correct answer after conditional statement we will just print some '-' for styling and the updated score of user

// a function to check whether user answer is correct or not
function gamePlay(questions , correctAnswer){

    var answer  = rs.question(chalk.cyanBright
(questions));
    if(answer == correctAnswer){
        console.log(chalk.green('\tcorrect'));    
        score = score+2;
    }
    else{
        console.log(chalk.red('\twrong'));    
        console.log(chalk.greenBright("Correct Answer is: "+correctAnswer));
        score = score-1;

    }
        console.log(chalk.yellowBright('Your score is  :' + score));    
        console.log(chalk.blue('\n----------------\n'));    

} 

Enter fullscreen mode Exit fullscreen mode

now we will create array of objects with key question and answer

qusArray = [
    {
    qus:"What is my name : ",
    ans:"mimansha"
},
{
    qus:"are you reading this : ",
    ans:"yes"
},
 {
    qus:"which year covid widely spread : ",
    ans:"2020"
}

];
Enter fullscreen mode Exit fullscreen mode

Now we will use for loop and iterate through every object and while iterating we will be calling the function ,let's see how it is done and printing final score after for loop cause when this loop will end all qus has been asked and user can't answer any more question

//calling function
for(let i =0 ; i<qusArray.length;i++){
    gamePlay(qusArray[i].qus,qusArray[i].ans);

}
console.log('Final score is  :' + score);    

Enter fullscreen mode Exit fullscreen mode

This might look bit confusing let me explain
gamePlay(qusArray[i].qus,qusArray[i].ans);
see function gameplay has 2 parameter questions and correctAnswer so we are iterating through array by qusarray[i]
if i =0 first object will be accessed now we want the string stored with the key qus example:
console.log(qusArray[0].qus)
output will be What is my name
in same way we are accessing the ans string.

Now we will make Dummy High Score array and printing the high score value also we are checking highest score of our dummy data and storing it inside a variable

//array of highscore
highScore = [
    {
        username: "Naruto",
        point: 2
    },
    {
        username: "MEE6",
        point: 1
    },
    {
        username: "random",
        point: 0
    }
];

//displaying highscore
console.log(chalk.bgYellow(" High Score "));

console.table(highScore);

// getting high score
var max = highScore[0].point;
for (let i = 1; i < highScore.length; ++i) {
  if (highScore[i].point > max) {
    max = highScore[i].point;
  }
}

Enter fullscreen mode Exit fullscreen mode

This is The Last part of quiz app , We have to check if user beat the high score or not and print statement according to that ,let's do it


//checking if user beat the hihg score
if(score>max){
    console.log(chalk.inverse.bold("\n Congrats u beat high score \n"));
}
else{
    console.log(chalk.inverse.bold("\n Better Luck Next Time \n"));

}
Enter fullscreen mode Exit fullscreen mode

so final code will be something like this

const rs =require('readline-sync');
const chalk = require('chalk');

console.log(chalk.green.bold("Welcome to The Game!!!\n"));
// naae input
var playerName = rs.question("HEy Whats ur Name : ");
//greeting user
console.log(chalk.yellow(`Welcome ${playerName}\n`));
//global varibale to keep account of socre
var score = 0;
// a function to check whether user answer is correct or not
function gamePlay(questions , correctAnswer){
    var answer  = rs.question(chalk.cyanBright
(questions));
    if(answer == correctAnswer){
        console.log(chalk.green('\tcorrect'));    
        score = score+2;
    }
    else{
        console.log(chalk.red('\twrong'));    
        console.log(chalk.greenBright("Correct Answer is: "+correctAnswer));
        score = score-1;
    }
        console.log(chalk.yellowBright('Your score is  :' + score));    
        console.log(chalk.blue('\n----------------\n'));    
} 
//creating qus answer  objects
var firstQus = {
    qus:"What is my name : ",
    ans:"mimansha"
};
var secondQus = {
    qus:"are you reading this : ",
    ans:"yes"
};
var thirdQus = {
    qus:"which year covid widely spread : ",
    ans:"2020"
};
// list of all qus answer
qusArray = [firstQus,secondQus,thirdQus];
//calling function
for(let i =0 ; i<qusArray.length;i++){
    gamePlay(qusArray[i].qus,qusArray[i].ans);

}
console.log('Final score is  :' + score);    
//array of highscore
highScore = [
    {
        username: "Naruto",
        point: 2
    },
    {
        username: "MEE6",
        point: 1
    },
    {
        username: "random",
        point: 0
    }
];
//displaying highscore
console.log(chalk.bgYellow(" High Score "));
console.table(highScore);
// getting high score
var max = highScore[0].point;
for (let i = 1; i < highScore.length; ++i) {
  if (highScore[i].point > max) {
    max = highScore[i].point;
  }
}
//checking if user beat the hihg score
if(score>max){
    console.log(chalk.inverse.bold("\n Congrats u beat high score \n"));
}
else{
    console.log(chalk.inverse.bold("\n Better Luck Next Time \n"));

}

Enter fullscreen mode Exit fullscreen mode

When you put all the code and run it output will be like this

Output Window

You can share your Repl with your friends with some changes on link exapmle: https://repl.it/@MimanshaSwarup/cli-app#index.js

by removing file name and add this at ?outputonly=1&lite=true ending of link example: https://repl.it/@MimanshaSwarup/cli-app?outputonly=1&lite=true

Top comments (2)

Collapse
 
vpgmackan profile image
Mackan

You should turn it into an app so you can just type:

npm i quiz-app
npx quiz-app

That would be so fun if you did it! You could also use a randomizer to get random questions from a list.

Collapse
 
mimanshaswarup profile image
mimansha-swarup

Thats great suggestions will surely work on it