Click here to Skip to main content
14,664,286 members
Articles » Web Development » ASP.NET » General
Article
Posted 18 Sep 2015

Stats

42.4K views
679 downloads
32 bookmarked

MVC Web API and AngularJS For Are You Genius Game

Rate this:
4.87 (20 votes)
Please Sign up or sign in to vote.
4.87 (20 votes)
4 Oct 2015CPOL
This article shows how to create a Are You Genius game using MVC, AngularJS and Web API 2.

Introduction

Image 1

* Kindly view my Youtube Video Link to learn MVC Web API and AngularJS For Are You Genius Game.

Are you Genius?

This game I have created by the inspiration of the “Who Wants to Be a Millionaire”. It is a world famous TV Show. In India, similar TV Show has been telecasted in Tamil Language as “Neengalum Vellalam Oru Kodi “ and in Hindi language as “Kaun Banega Crorepati”. On the Internet we can see plenty of similar online games and mobile app games mostly created with flash programming. I thought to make things simpler by creating one with MVC using AngularJS and WEB API. I love to make games rather than play games. So to make new games now I have started playing games. I have followed the same rules to make this game and instead of Money ($) I have used Points and named my game as “Are You Genius”. Here is the link of Wikipedia that explains Who Wants to Be a Millionaire: game https://en.wikipedia.org/wiki/Who_Wants_to_Be_a_Millionaire%3F.

Let’s see what is rule to play my game Are You Genius:

Instead of money in my game I have used Points. Total points to win the game is 1 Million..

You will be having 15 Questions, each question will have 30 seconds. You have to answer each question within 30 seconds. For each question you can see 4 choice of answers and you have to pick the correct answer from the question. If you fail to answer within 30 seconds then you will be eliminated from the game. The person who answers all the 15 questions and wins the game is a Genius.

Lifeline: The player will have the following four lifelines:

Note: I will be using Icons in my application. User can click on these icons to use lifeline.

  1. Image 2 Ask to Computer: (If player click this option then computer will display the Answer .Note only 90% of answers will be correct. Remaining 10% might not be correct so Player has to decide as weather he/she can pick the answer or not.)
  2. Image 3 50/50: The 2 non correct answer from the choice will be removed .Player has to select the correct answer from the remaining 2 choices.
  3. Image 4 Ask to Shanu: (If player click this option then SHANU (The Program creator) will display the Answer. Note only 90% of answers will be correct. Remaining 10% might not be correct so Player has to decide as weather he/she can pick the answer or not.)
  4. Image 5Change Question: (Using this option user can change the current question to some other choice of question. If user click change Question then some other random question will be displayed. Note it can be easy or difficult as the random question displaying so player has to think and decide to use this option. It’s tricky one.)

Points for each Question from 1st to 15th question.

Image 6

 Safe Zone: In each 5th question the player will reach the Safe Zone. Here in points we can see in each 5th question I have marked different color. Now for example let’s consider a player is playing this game and he/she answered 5 questions correctly and in 6th question if he picks the wrong answer then he will be getting total 1000 Points. If the player plays a game and he/she answers 3 questions correctly and for the 4th question if he picks the wrong answer then he will get 0 points no matter he answered 3 questions correctly. The player has to pick the correct answer. If he/she picks the wrong answer then he will be getting his last safe zone points. For example, a player answers 12 questions correctly and in 13th question if he picks the wrong answer then he will be getting 32,000 instead of 125,000 Points of 12th question. If the player answers all the 15 questions correctly then he’s the winner and will be a genius.

Walk Away

You can leave the game if you don’t want to lose all your points. For example, now you have answered 3 questions and before each question asked you will be asked to continue or walk away. If you select Walk Away, then you will get the last earned points. For example, now if you have answered 13 questions and if you click Walk Away before answering 14th question, then you will get 250,000 Points.

Timer

Each question will contain 45 second. If the player not pick the answer within 45 second then he will get the last answered point and will be eliminated from the game.

All this game rules logic has been implemented in my MVC application using AngularJS and WEB API. In code part we can see in detail how to implement this logic to make our own game.

Prerequisites

Visual Studio 2015. You can download it from here.
ou can also view my previous articles related to AngularJs using MVC and the WCF Rest Service.

This article will explain in detail how to create an Online Are You Genius Game using MVC, Angular JS and a WEB API 2. This article will explain:

  1.  How to create sample tables and database at SQL Server.
  2. Using Entity Framework connect to database.
  3. Create WEB API controller to get the data and select random 16 result using LINQ query.
  4.  How to install the Angular JS Package into a MVC application.
  5.  How to create our Angular JS application to create our own Are You Genius Game.

Angular JS

We might be familiar with what the Model, View, View Model (MVVM) and what Model, View and Controller (MVC) are. Angular JS is a JavaScript framework that is purely based on HTML, CSS and JavaScript.

The Angular JS Model View Whatever (MVW) pattern is similar to the MVC and MVVM patterns. In our example I have used Model, View and Service. In the code part let's see how to install and create Angular JS in our MVC application.

If you are interested in reading more about Angular JS then kindly go through the following link.

http://www.w3schools.com/angular/default.asp

Using the code

1) Create Database and Table

We will create a QuestionDetails table under the Database ‘GeniusDB.

The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2014.

-- =============================================                          
-- Author      : Shanu                           
-- Create date : 2015-09-17                             
-- Description : To Create Database,Table and Sample Insert Query                            
-- Latest                             
-- Modifier    : Shanu                              
-- Modify date : 2015-09-17                         
-- =============================================
--Script to create DB,Table and sample Insert data

USE MASTER
GO
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'GeniusDB' )
DROP DATABASE GeniusDB
GO

CREATE DATABASE GeniusDB
GO

USE GeniusDB
GO

-- 1) //////////// QuestionDetails table

-- Create Table ItemDetails,This table will be used to store the details like Item Information
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'QuestionDetails' )
DROP TABLE QuestionDetails
GO

CREATE TABLE QuestionDetails
(
   Ques_ID int identity(1,1),
   Question VARCHAR(MAX)  NOT NULL,
   Option1 VARCHAR(500)  NOT NULL,
   Option2 VARCHAR(500)  NOT NULL,
   Option3 VARCHAR(500)  NOT NULL,
   Option4 VARCHAR(500)  NOT NULL,
   Answer VARCHAR(500)  NOT NULL,
CONSTRAINT [PK_QuestionDetails] PRIMARY KEY CLUSTERED  
(  
  Ques_ID ASC   
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]   
) ON [PRIMARY] 
GO

-- Insert the sample records to the ItemDetails Table

Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('What is the Capital of India?','Delhi','OldDelhi','New Delhi','Delhi New','New Delhi')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('How many continent in world?','6','7','8','9','7')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('Seoul is the Capital of which Country?','korea North','Japan','Korea South','China','Korea South')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('Who is the First President of America?','George W. Bush','Barack Obama','George Washington','Abraham Lincoln','George Washington')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('who wrote Thirukural?','Avvaiyar','Thiruvalluvar','William Shakespeare','Kalidasa','Thiruvalluvar')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('what is the name of indian currency?','Won','Rupee','Yen','Renminbi','Rupee')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('How many players are there in a Cricket team?','25','40','11','6','11')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('How many seconds in one hour?','6','3600','36','360','3600')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('Which City located in 2 Continents - Europe and Asia?','Taipei','Ashgabat','Istanbul','Athens','Istanbul')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('What Bird Is Used As A Symbol Of Peace?','Peacock','Owl','Dove','White Cockatoo','Dove')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('who is father of Computer?','Charles Babbage','Antoine Lavoisier','Charles Cabbage','Nikola Tesla ','Charles Babbage')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('Where did Neil Armstrong landed?','SUN','STAR','MOON','SEA','MOON')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('What is the nick name of Wyoming State?','Water State','Sun State','Natural State','Equality State','Equality State')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('Petasos beach is in which country?','Finland','Ireland','Greece','Norway','Greece')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('How many bones does a dog have?','Average of 319','Average of 139','Average of 913','Average of 639','Average of 319')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('What is the Name of South korea President who got the Noble Price for Peace?','Park Geun-hye','Kim Dae-jung','Lee Myung-bak','Roh Moo-hyun','Kim Dae-jung')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('In which year did Sir Chandrasekhara Venkata Raman received the Nobel Prize for Physics?','1930','1979','1913','1989','1930')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('What is the name of supercontinent that existed during the late Paleozoic and early Mesozoic eras?','Laurasia','Gondwana','Pangaea','Pannotia','Pangaea')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('Who are the 4 people who won the Noble Prize 2 times?','Marie Curie,Malala Yousafzai,John Bardeen,Frederick Sanger','Marie Curie,Wolfgang Pauli,John Bardeen,Frederick Sanger','Marie Curie,Linus Pauling,John Bardeen,Frederick Sanger','Marie Curie,Linus Pauling,John Bardeen,Finn E. Kydland','Marie Curie,Linus Pauling,John Bardeen,Frederick Sanger')
Insert into QuestionDetails(Question,Option1,Option2,Option3,Option4,Answer) values('What is the Name of present PANAMA President?','Mireya Moscoso','Juan Carlos Varela','Guillermo Endara','Martín Torrijos','Juan Carlos Varela')

select * from QuestionDetails

2) Create our MVC Web Application in Visual Studio 2015:

After installing our Visual Studio 2015.Click Start -> Programs-> select Visual Studio 2015- Click Visual Studio 2015

Click New -> Project - > Select Web -> ASP.NET Web Application. Select your project location and enter your web application Name.

Image 7

Select MVC and in Add Folders and Core reference for. Select the Web API and click ok.

Image 8

Add Database using ADO.NET Entity Data Model

Right click our project and click Add -> New Item.

Image 9

Select Data->Select ADO.NET Entity Data Model> Give the name for our EF and click Add

Image 10

Select EF Designer from database and click next.

Image 11

Here click New Connection and provide your SQL-Server Server Name and connect to your database.

Image 12

Here we can see I have given my SQL server name, Id and PWD and after it connected I have selected the data base as GeniusDB as we have created the Database using my SQL Script.

Image 13

Click next and select our tables need to be used and click finish.

Image 14

Click Next and select our tables that are needed and click Finish.

Image 15

Here we can see now we have created our GeniusDBModel.

Image 16

Once Entity has been created next step we add WEB API to our controller and write function to select/Insert/Update and Delete.

Steps to add our WEB API Controller.

Right Click Controllers folder-> Click Add-> Click Controller.

Image 17

As we are going to create our WEB API Controller. Select Controller and Add Empty WEB API 2 Controller. Give your Name to Web API controller and click ok. Here for my Web API Controller I have given name as “GeniusController”.

Image 18

As we have created Web API controller, we can see our controller has been inherited ApiController.

 

Image 19

 

As we all know Web API is a simple and easy to build HTTP Services for Browsers and Mobiles

Web API has four methods as Get/Post/Put and Delete where

Get is to request for the data. (Select)

Post is to create a data. (Insert)

Put is to update the data.

Delete is to delete data.

In our example we will use Get method, since we need to get all the Puzzle Question details from database.

Get Method

In our example I have used only Get method as I am using to select data from database to display the Word Puzzle game. We need to create object for our Entity and write our Get Method to perform Select operations.

Select Operation

We use get Method to get all the details of QuestionDetail table using entity object and we return the result as IEnumerable .

Here we can see in get Method I have used the Take method to display only 16 records from the database.To select the random record from the database I have used the Guid.NewGuid().

We use this method in our AngularJS and display the result in MVC HTML page.

public class GeniusController : ApiController
    {
       GeniusDBEntities objAPI = new GeniusDBEntities();     

       //get all Questions

     [HttpGet]
       public IEnumerable<QuestionDetail> Get()
       {
           return objAPI.QuestionDetails.OrderBy(x => Guid.NewGuid()).Take(16).AsEnumerable();                }
}

Creating AngularJs Controller

First create a folder inside the Script Folder and I give the folder name as “MyAngular”

Image 20

Now add your Angular Controller inside the folder.

Right Click the MyAngular Folder and click Add -> New Item -> Select Web -> Select AngularJs Controller and give name to Controller. I have given my AngularJs Controller as “Controller.js”

Image 21

Once the AngularJs Controller is created, we can see by default the controller will have the code with default module definition and all.

Image 22

 

I have change the above code like adding Module and controller like below.

If the Angular JS package is missing then add the package to your project.

Right Click your MVC project and Click-> Manage NuGet Packages. Search for AngularJs and click Install.

Image 23

Steps to Create AngularJs Script Files:

Modules.js : here we add the reference to the Angular.js javascript and create a Angular Module named “RESTClientModule”

/// <reference path="../angular.js" /> 
/// <reference path="../angular.min.js" />  
/// <reference path="../angular-animate.js" />  
/// <reference path="../angular-animate.min.js" />  

var app;
(function () {
    app = angular.module("RESTClientModule", ['ngAnimate']);
})();

Controllers: In Angular JS Controller I have performed all the business logic and return the data from WEB API to our MVC html page.

1) Variable declarations:

First I declared all the local Variable which needs to be used .For each variable I have added the comments.

app.controller("AngularJs_ImageController", function ($scope, $timeout, $rootScope, $window, $http) {   
 //Global Variables
    $scope.date = new Date();
    $scope.MyName = "Shanu";
    $scope.usrName = "";
    $scope.AllQuestions;

    //Game Hidden Table row display
    $scope.showGameStart = true;
    $scope.showGame = false;
    $scope.showresult = false;
    $scope.showlifeline = false;

    //Game Detail Display Variables
    $scope.Question = "";
    $scope.Option1 = "";
    $scope.Option2 = "";
    $scope.Option3 = "";
    $scope.Option4 = "";
    $scope.Answers = "";
    $scope.Resuts = "";
    $scope.ImageAnswer = "won.png";


    //Game variable declared
    $scope.questionCount = 1;
    $scope.totalPoints = 0;
    $scope.rowCount = 0;

    //To Display Game Lifeline Images and Status
    $scope.imgcomputer = "computerE.png";
    $scope.imgcomputerStatus = 0;
    $scope.img50 = "50E.png";
    $scope.img50Status = 0;
    $scope.fiftyElimination = 0;

    $scope.imgShanu = "shanuE.png";
    $scope.imgShanuStatus = 0;

    $scope.imgChange = "changeE.png";
    $scope.imgChangeStatus = 0;
    $scope.showlifelinetext = "";

    //To Display Game Lifeline Images and Status
    $scope.answer1ClickStatus =0;
    $scope.answer2ClickStatus = 0;
    $scope.answer3ClickStatus = 0;
    $scope.answer4ClickStatus = 0;

    //Timer to display the countdown
    $scope.counter = 45;
    var countdownStop;

2) Game Start Function:

By default I will display how to play the game with instruction to the player. Player can enter their name and click to start game button to start the new game

Image 24

In the Start game button Click I call the AngularJs Method startGame to check whether user has  enter the name or not .If user not enter their name I will ask to enter the name to start the game. If user has enter the name then I will call the function to display the first question to the user. Note the Questions are random so every time the first question will not be repeated.The I will call the timerCountDownStart function.In this function I will strart the countdown it will start from 45 and decrease the value by 1 till 0.The player will have 45 second for each question.

$scope.startGame = function () {

    if($scope.usrName=='')
    {
        alert("Enter Your Name to start the game !");
        $scope.showGameStart = true;
        $scope.showGame = false;
        $scope.showresult = false;
    }
    else
    {     
        selectGameDetails();
        $scope.timerCountDownStart();
$scope.showGameStart = false;
        $scope.showGame = true;
        $scope.showresult = false;
        }
    }

selectGameDetails() To display the Each question

Image 25

When user clicks on Start game button I display the Questions No as 1,by using the $http.get('/api/ Genius /') I will get 16 random questions from the database and will store the result data to $scope. Question.For first question the rowcount will be 0 ,I will display the 1st Question information’s with Answer.

//get all Game Details from Database
    function selectGameDetails() {
        $http.get('/api/Genius/').success(function (data) {
            $scope.AllQuestions = data;
            if ($scope.AllQuestions.length > 0) {
                $scope.Question = $scope.AllQuestions[$scope.rowCount].Question;
                $scope.Option1 = $scope.AllQuestions[$scope.rowCount].Option1;
                $scope.Option2 = $scope.AllQuestions[$scope.rowCount].Option2;
                $scope.Option3 = $scope.AllQuestions[$scope.rowCount].Option3;
                $scope.Option4 = $scope.AllQuestions[$scope.rowCount].Option4;
                $scope.Answers = $scope.AllQuestions[$scope.rowCount].Answer;
            }
        })
        .error(function () {
            $scope.error = "An Error has occured while loading posts!";
        });
    }

Timer Countdown:

timerCountDownStart() To start the countdown

Image 26

In this method the countdown will start from 45 and decrease the value by 1 till 0.The player will have 45 second for each question.I will decrement the counter value one by one

$scope.timerCountDownStart = function () {
        countdownStop = $timeout(function () {
            console.log($scope.counter);
            if ($scope.counter >= 1) {
                $scope.counter--;
                $scope.timerCountDownStart();
            }
            else
            {
                $scope.timerCountDownStop();
                $scope.pointsCalculations(1);
                $scope.Resuts = "Sorry Time out " + $scope.usrName + " You lose the game :( .Your Total points are " + $scope.totalPoints;
                  alert($scope.Resuts)
                  $scope.ImageAnswer = "lose.png";
                  $scope.wrongAnswerandLoseGame();
            }       
        }, 1000);
    };
    $scope.timerCountDownStop = function () {
        $timeout.cancel(countdownStop);    
    }

Image 27

.When the counter value is 0 then I will stop the timer and display the alert message as you lose the game and display the players last points value .Here we can see the points as 0 since in my first question I didn’t answer the question within 45 seconds.

Image 28

Lifeline Support:

 Image 29 

As I have already told in this game user has 4 lifeline .user can use all this 4 lifeline in his game to win the Genius Prize.

 Let’s see one by one of this lifeline

Image 30 Ask to Computer: If user don’t know the current question .User can ask the computer to display the Answer. Note the Answer is 90% chance of correct so the player has to decide weather to pick the computer presented answer or not. This Lifeline can be used only one time per game for a player. Here we can see for the below question I don’t know the answer so I have clicked one the Ask to Computer lifeline .Once I click on that the Ask to computer image will be changed to disabled image .user can click and use only one time so think before use this option.

Image 31

Here we can see when I click on the Ask to computer lifeline. The computer will display the answer at the top as “Computer says the correct Answer might be “Average of 319” pick your choice.

//to check the Computer Lifeline already used or not If its not used then change the Computer image to Disabled Image.User can click (use only) one time

    $scope.funComputerLifeline = function () {    

        if($scope.imgcomputerStatus==0)
        {
            $scope.imgcomputer = "computerD.png";
            $scope.imgcomputerStatus = 1;
            $scope.showlifelinetext = "Computer Says the Correct Answer might be   " + $scope.Answers + " Pick Your Choice ";
            alert($scope.showlifelinetext)
            $scope.showlifeline = true;
        }
    }

Image 32 50/50: The 2 non correct answer from the choice will be removed .Player has to select the correct answer from the remaining 2 choices. Player can use this lifeline to remove any 2 non answered choice from the 4 choice of answers. We can see below here for this question I have used the 50/50 lifeline. This lifeline can be used only once.

Image 33

Here we can see when I click on the 50:50 Lifeline. It will remove the 2 non correct answers .Here B and C has been removed now player has 2 choice of A and D .The player need to select the correct answer from A and D. We can also see the countdown will be running here the countdown is 26 and user need to pick the answer with in time. And user can use the 50:50 lifeline only one time .Here we can see the 50:50 lifeline image has been changed to disabled image. In code part we can see I will check for the options with answer and remove 2 unmatched options from the list.

//to check the 50/50 Lifeline already used or not If its not used then change the 50/50 image to Disabled Image.User can click (use only) one time

    $scope.funFiftyLifeline = function () {
        if ($scope.img50Status == 0) {
            if ($scope.Option1 != $scope.Answers) {           
                if ($scope.fiftyElimination <= 1) {
                    $scope.Option1 = "";
                    $scope.fiftyElimination = $scope.fiftyElimination + 1;
                }
            }

            if ($scope.Option2 != $scope.Answers) {
                if ($scope.fiftyElimination <= 1) {
                    $scope.Option2 = "";
                    $scope.fiftyElimination = $scope.fiftyElimination + 1;
                }
            }

            if ($scope.Option3 != $scope.Answers) {
                if ($scope.fiftyElimination <= 1) {
                    $scope.Option3 = "";
                    $scope.fiftyElimination = $scope.fiftyElimination + 1;
                }
            }

            if ($scope.Option4 != $scope.Answers) {
                if ($scope.fiftyElimination <= 1) {
                    $scope.Option4 = "";

                    $scope.fiftyElimination = $scope.fiftyElimination + 1;
                }
            }
            $scope.img50 = "50D.png";
            $scope.img50Status = 1;
        }
    }

Image 34 Ask to Shanu: This is similar to Ask to computer Lifeline. If user don’t know the current question .User can Ask to Shanu for display the Answer. Note the Answer is 90% chance of correct so the player has to decide whether to pick the SHANU presented answer or not. This Lifeline can be used only one time per game for a player. Here we can see for the below question I don’t know the answer so I have clicked one the Ask to Shanu lifeline .Once I click on that the Ask to computer image will be changed to disabled image .user can click and use only one time so think before use this option.

Image 35

Here we can see when I click on the Ask to computer lifeline. The computer will display the answer at the top as “Shanu says the correct Answer might be “Thiruvalluvar” pick your choice.

//to check the Shanu Lifeline already used or not If its not used then change the Shanu image to Disabled Image.User can click (use only) one time

    $scope.funShanuLifeline = function () {
        if ($scope.imgShanuStatus == 0) {
            $scope.imgShanu = "shanuD.png";
            $scope.imgShanuStatus = 1;
            $scope.showlifelinetext = "Shanu Says the Correct Answer might be   " + $scope.Answers + " Pick Your Choice ";
            alert($scope.showlifelinetext)
            $scope.showlifeline = true;
        }
    }

Image 36Change Question: (Using this option user can change the current question to some other choice of question. If user click change Question then some other random question will be displayed. Note it can be easy or difficult as the random question displaying so player has to think and decide to use this option. It’s tricky one.)

Image 37

Here we can see when user click on Change Lifeline I will disable the option and call the NextQuestion Method to display some other random question for the player to play the game.

//to check the Change Question Lifeline already used or not If its not used then change the Change Question image to Disabled Image.User can click (use only) one time

    $scope.funChangeLifeline = function () {
        if ($scope.imgChangeStatus == 0) {
            $scope.imgChange = "changeD.png";
            $scope.imgChangeStatus = 1;
            $scope.NextQuestion(1);
        }
    }

Current Question display: once the player answered the question I will be incrementing QuestionCount to display the next question mean time in  right side of the points and question no display I will dynamically changing the current question Table cell back color to red color. Here we can see after I have answered the 1st question correctly then I will display the 2nd question pointing by red color in right side dynamically.

Image 38

HTML:Here is the sample 2 anser teable cell design of html.here we can see in Table cell using AngularJS ng-class.I will check for current questionCount and display the cell color to red or default color.If the Answer is 2 then I will display the red color by checking the QuestionCount.

<tr>
  <td ng-class="{changeColor: questionCount == '2', actualColor: questionCount != '2'}" align="center">
     <b>2</b>
          </td>
 <td ng-class="{changeColor: questionCount == '2', actualColor: questionCount != '2'}" align="center">
     <b>200 (Points)</b>
    </td>
  </tr>

CSS:In CSS I will be setting the table cell color for actual changeColor for current question color.

.actualColor {
    background-color: #c2cfd8; color:#9F000F ;border: solid 1px #659EC7;cursor: pointer;
}

.changeColor {
    background-color: #ff0000; color:#FFFFFF ;border: solid 1px #659EC7;cursor: pointer;
}

AngularJS : In next question method I will increment the questioncount and display the next question to the user. In Next Question method I will check for the user confirmation as he want to play the game or to walk away from the game with current points.If user click on ok then he wil continue to play the next question.If the player clicks on cancel then he will be walk away (Quit)from the game and he will get the last answer points.

// If answer correctly then display the next Question

    $scope.NextQuestion = function (nextQuestionCount) {     
        if (nextQuestionCount == 1) {         
        }
        else
        {
            if ($scope.questionCount <= 14)
                {
            var strconfirm = confirm("Do you Like to Continue or Walk Away.if you would like to continue the game click YES if you want to Quit game and go with the money then click Cancel?");
            if (strconfirm != true) {
                $scope.pointsCalculations(0);
                $scope.Resuts = "Thank You for Playing   " + $scope.usrName + " Your Total points are " + $scope.totalPoints;
                alert($scope.Resuts)
                $scope.ImageAnswer = "won.png";
                $scope.wrongAnswerandLoseGame();
                return true;
            }
            }

            $scope.questionCount = $scope.questionCount + 1;    
        $scope.timerCountDownStart();
        $scope.counter = 45;
        }

        $scope.rowCount = $scope.rowCount + 1;
        $scope.timerCountDownStop();
        $scope.Question = $scope.AllQuestions[$scope.rowCount].Question;
        $scope.Option1 = $scope.AllQuestions[$scope.rowCount].Option1;
        $scope.Option2 = $scope.AllQuestions[$scope.rowCount].Option2;
        $scope.Option3 = $scope.AllQuestions[$scope.rowCount].Option3;
        $scope.Option4 = $scope.AllQuestions[$scope.rowCount].Option4;
       $scope.Answers = $scope.AllQuestions[$scope.rowCount].Answer;

        $scope.answer1ClickStatus = 0;
        $scope.answer2ClickStatus = 0;
        $scope.answer3ClickStatus = 0;
        $scope.answer4ClickStatus = 0;

        $scope.showlifeline = false;
        $scope.showlifelinetext = "";
    }

Walkaway: Each question before user can continue the game or Walkaway (Quit) the game and get the last answered questions point with him. Here we can see after my 2nd question answer I cancel to continue the game and selected Walkaway and my points was been 200

Image 39

 

Answer: When user clicks on each answer I will check for the user clicked answer with the actual answer. If both answers are correct then I will display the next question.

Image 40

Here we can see I clicked the correct answer and if I click ok then it will display next question to play.

//Answer A Clicked
    $scope.answerAClicked = function () {   

        if ($scope.Option1 == $scope.Answers)
        {
            $scope.answer1ClickStatus = 2;
            if ($scope.questionCount <= 14) {
                $scope.NextQuestion(0);
            }
            else if ($scope.questionCount == 15) {
                $scope.Resuts = "Wow " + $scope.usrName + " :) you won the game .You are the real Genius .Your total points is  1 Million :)";
                alert($scope.Resuts)
                $scope.ImageAnswer = "won.png";
                $scope.wrongAnswerandLoseGame();
            }
        }
        else
        {
            $scope.answer1ClickStatus = 3;
            $scope.wrongAnswerPoints();        

            $scope.Resuts = "Sorry Wrong Answer Dear  " + $scope.usrName + " You lose the game :( .Your Total points are " + $scope.totalPoints;
            alert($scope.Resuts)
            $scope.ImageAnswer = "lose.png";
            $scope.wrongAnswerandLoseGame();         
        } 
    }

 

Wrong Answer:If the  player pick the wrong answer I will display the message with his current points earned.

Image 41

//for calculating wrong answer points
$scope.wrongAnswerPoints = function () {
    if ($scope.questionCount <= 4)
    {
        $scope.totalPoints = "0";
    }
    else if ($scope.questionCount <= 9) {
        $scope.totalPoints = "1,000";
    }
    else if ($scope.questionCount <= 14) {
        $scope.totalPoints = "32,000";
    }
}

Image 42

Genius: If the player answer all the 15 questions then he will be as the Genius. Here we can see that I have answered all the 15 questions and won the 1 Million Points.

Image 43

Points of Interest

Note: you can change the database as per your connection. All of questions and Answers has been displayed from the database. You can add any no of questions and answers in the table Every time I will be filter only 16 random question from the database. If you add more questions and answer that will avoid the repeated questions to the player. Hope you like this game have fun.

Tested Browsers: Chrome and IE 11.

History

shanuAngularJSGenius.zip - 2015-09-18

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
GeneralHI Pin
Member 1003344130-Sep-15 3:42
MemberMember 1003344130-Sep-15 3:42 
Very useful n Nice Article.
GeneralRe: HI Pin
syed shanu30-Sep-15 14:01
mvasyed shanu30-Sep-15 14:01 
GeneralMy vote of 5 Pin
Suvendu Shekhar Giri29-Sep-15 5:00
professionalSuvendu Shekhar Giri29-Sep-15 5:00 
GeneralRe: My vote of 5 Pin
syed shanu29-Sep-15 13:56
mvasyed shanu29-Sep-15 13:56 
AnswerRe: AngularJs Controller Pin
syed shanu24-Sep-15 21:30
mvasyed shanu24-Sep-15 21:30 
GeneralMy vote of 5 Pin
Adil pathan21-Sep-15 8:15
MemberAdil pathan21-Sep-15 8:15 
GeneralRe: My vote of 5 Pin
syed shanu21-Sep-15 14:05
mvasyed shanu21-Sep-15 14:05 
GeneralMy vote of 5 Pin
Santhakumar M19-Sep-15 6:33
professionalSanthakumar M19-Sep-15 6:33 
GeneralRe: My vote of 5 Pin
syed shanu19-Sep-15 13:40
mvasyed shanu19-Sep-15 13:40 
QuestionMy Vote of 5 Pin
aarif moh shaikh18-Sep-15 18:34
professionalaarif moh shaikh18-Sep-15 18:34 
AnswerRe: My Vote of 5 Pin
syed shanu18-Sep-15 18:56
mvasyed shanu18-Sep-15 18:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.