MVC Web API and AngularJS For Word Puzzle Game



Word Puzzle Games

A word puzzle game is an interesting game where, for each question there will be 4 Images displayed. The user must find the hidden name of the matching four images together. The game rule is that, for each game there will be 5 questions asked. The question is very simple since each question will be displayed with 4 sets of images, the user must find the matching word for the 4 image combinations and enter the correct answer and click Next to display the next question. Each question will have 20 points. If the user answers the puzzle then he will get 20 points for each of his correct answers. If the user enters the wrong answer then he will get a negative 10 points. That is, he will get -10 points for each wrong answer. If the user gets a total 100 Points for all 5 questions then he or she is a winner of the game. If the user gets less than 100 Points then he or she loses the game and they can try again. Note, each time the questions will be displayed differently since I will display the questions randomly from the database. So kindly check the image well and answer the questions to avoid negative points. I hope you will love this game, have fun. :)

Prerequisites

Visual Studio 2015. You can download it from here.

You can also view my previous articles related to AngularJs using MVC and the WCF Rest Service.

Previous articles related to AngularJs, MVC and the Web API:

This article will explain in detail how to create an online word puzzle game using MVC, AngularJs and a Web API 2. This article will explain:

  1. How to create sample tables and database at SQL Server.
  2. Using Entity Framework to connect to a database.
  3. Create Web API controller to get the data and select random 5 results using a LINQ query.
  4. How to install the AngularJs Package into a MVC application.
  5. How to create our AngularJs application to create our own word puzzle game.

AngularJs

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

The AngularJs 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 AngularJs in our MVC application.

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

Code Part

1. Create a database and table.

We will create a
wordDetails table in the database "wordGameDB".

Table Column Details:

 
 
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 2012.  
  1. USE MASTER  
  2. GO  
  3.   
  4. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB  
  5.   
  6. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'wordGameDB' )  
  7.   
  8. DROP DATABASE wordGameDB  
  9.   
  10. GO  
  11.   
  12.   
  13. CREATE DATABASE wordGameDB  
  14.   
  15. GO  
  16.   
  17.   
  18. USE wordGameDB  
  19.   
  20. GO  
  21.   
  22.   
  23. -- 1) //////////// ItemDetails table  
  24.   
  25. -- Create Table ItemDetails,This table will be used to store the details like Item Information  
  26.   
  27.   
  28. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'wordDetails' )  
  29.   
  30. DROP TABLE wordDetails  
  31.   
  32. GO  
  33.   
  34.   
  35. CREATE TABLE wordDetails  
  36.   
  37. (  
  38.    word_ID int identity(1,1),  
  39.    word_Name VARCHAR(100)  NOT NULL,  
  40.    image1 VARCHAR(100)  NOT NULL,  
  41.    image2 VARCHAR(100)  NOT NULL,  
  42.    image3 VARCHAR(100)  NOT NULL,  
  43.    image4 VARCHAR(100)  NOT NULL,  
  44.    Answer VARCHAR(100)  NOT NULL,  
  45. CONSTRAINT [PK_wordDetails] PRIMARY KEY CLUSTERED     
  46. (     
  47.   word_ID ASC      
  48. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]      
  49. ON [PRIMARY]    
  50.   
  51. GO  
  52.   
  53. -- Insert the sample records to the ItemDetails Table  
  54.   
  55. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Animals','animals-01.png','animals-02.png','animals-03.png','animals-04.png','Animals')  
  56. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Anouncement','Anouncement-01.png','Anouncement-02.png','Anouncement-03.png','Anouncement-04.png','Anouncement')  
  57. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Colors','colors-01.png','colors-02.png','colors-03.png','colors-04.png','Colors')  
  58. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Food','food-01.png','food-02.png','food-03.png','food-04.png','Food')  
  59. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Green','Green-01.png','Green-02.png','Green-03.png','Green-04.png','Green')  
  60. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Horror','horror-01.png','horror-02.png','horror-03.png','horror-04.png','Horror')  
  61. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Java','Java-01.png','Java-02.png','Java-03.png','Java-04.png','Java')  
  62. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Network','Network-01.png','Network-02.png','Network-03.png','Network-04.png','Network')  
  63. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Night','night-01.png','night-02.png','night-03.png','night-04.png','Night')  
  64. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Office','office-01.png','office-02.png','office-03.png','office-04.png','Office')  
  65. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Play','play-01.png','play-02.png','play-03.png','play-04.png','Play')  
  66. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Science','science-01.png','science-02.png','science-03.png','science-04.png','Science')  
  67. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Space','space-01.png','space-02.png','space-03.png','space-04.png','Space')  
  68. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Stone','stone-01.png','stone-02.png','stone-03.png','stone-04.png','Stone')  
  69. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Tree','tree-01.png','tree-02.png','tree-03.png','tree-04.png','Tree')  
  70. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Water','water-01.png','water-02.png','water-03.png','water-04.png','Water')  
  71. Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) values('Weather','Weather-01.png','Weather-02.png','Weather-03.png','Weather-04.png','Weather')  
  72.   
  73. select * from wordDetails  
 2. Create our MVC web application in Visual Studio 2015. After installing our Visual Studio 2015, click Start -> Programs then select Visual Studio 2015 then click Visual Studio 2015.

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



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

 
Add Database using ADO.NET Entity Data Model

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

 

Select Data then select ADO.NET Entity Data Model then provide the name for our EF and click Add.



Select "EF Designer from database" then click Next.

 
Here click New Connection and provide your SQL Server server name and connect to your database.

 
 
Here we can see I have given my SQL Server name, Id and PWD and after it is connected I have selected the database as wordGameDB since we created the database using my SQL Script.
 
 

Click next and select the tables to be used and click Finish.



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


Here we can see now we have created our wordPuzzleModel.




Once the entity has been created the next step is to add Web API to our controller and write the function to select/insert/update and delete.

Procedure to add our Web API Controller

Right-click the Controllers folder then click Add-> Click Controller.



To create the Web API Controller, select Controller and Add Empty Web API 2 Controller. Provide a name for the Web API controller and click OK. Here for my Web API Controller I have given the name “wordGameController”.



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



We all know that the Web API is simple and it is easy to build HTTP Services for browsers and mobiles.


The Web API has the four methods Get/Post/Put and Delete where:
  • Get is to request data (select).
  • Post is to create data (insert).
  • Put is to update data.
  • Delete is to delete data.

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

Get Method

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

Select Operation

We use the get method to get all the details of the wordDetail table using an entity object and we return the result as an IEnumerable.

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

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

  1. public class wordGameController : ApiController  
  2. {  
  3.     wordGameDBEntities objAPI = new wordGameDBEntities();  
  4.   
  5.     //get all Images  
  6.     [HttpGet]  
  7.     public IEnumerable<shanuAngularWordGame.wordDetail> Get()  
  8.     {  
  9.             
  10.         return objAPI.wordDetails.OrderBy(x => Guid.NewGuid()).Take(5).AsEnumerable();  
  11.         //return objAPI.ImageDetails.AsEnumerable().OrderByDescending(item => item.ImageID );    
  12.   
  13.     }  
  14. }  
Creating AngularJs Controller

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




Now add your Angular Controller inside the folder.


Right-click the MyAngular folder and click Add -> New Item then select Web then select AngularJs Controller and provide a name for the controller. I named my AngularJs Controller “Controller.js”.




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

 
I changed the preceding code, like adding a module and controller as in the following.

If the AngularJs 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.


 
Procedure to Create AngularJs Script Files

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

  1. // <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5. var app;  
  6. (function () {  
  7.     app = angular.module("RESTClientModule", ['ngAnimate']);  
  8. })();  
Controllers: In the AngularJs Controller I have done all the business logic and returned the data from the Web API to our MVC HTML page.

1. Variable declarations

First I declared all the local variables that are needed.

  1. app.controller("AngularJs_ImageController"function ($scope, $timeout, $rootScope, $window, $http) {  
  2.   
  3.     //Global Variables  
  4.     $scope.date = new Date();  
  5.     $scope.MyName = "Shanu";  
  6.     $scope.usrName = "";  
  7.     $scope.Images;  
  8.     $scope.txtAnswer="";  
  9.   
  10.   
  11.   
  12.     //Game variable declared  
  13.     //This variable has been declared to display the Question Number,User Total Points on each questions,  
  14.     //Each question Answer Correct Word total character Count for example from the Images display the correct answer is Fire then i will display 4 as total Word Count.  
  15.     //rowCount is used to display the Question one by one.  
  16.     $scope.questionCount = 1;  
  17.     $scope.totalPoints = 0  
  18.     $scope.wordCount = 0;  
  19.     $scope.rowCount = 0;  
  20.   
  21.   
  22.     //Game Detail Display Variables todisplay each 4 images for one question and to store the result to compare with user enterd answer  
  23.   
  24.     $scope.Image1 = "";  
  25.     $scope.Image2 = "";  
  26.     $scope.Image3 = "";  
  27.     $scope.Image4 = "";  
  28.     $scope.ImageAnswer = "won.png";  
  29.     $scope.Answers = "";  
  30.     $scope.Resuts = "";  
  31.   
  32.     //  --  
  33.      
  34.     //Game Hidden Table row display   
  35.     $scope.showGameStart = true;  
  36.     $scope.showGame = false;  
  37.     $scope.showresult = false;  
 2. Game Start Function

By default I will display how to play the game and the rules to play the game and the instructions to start the game. The user can enter their name to start the game. The user cannot start the game without entering their name.

 

In the Start game button click I call the AngularJs method startGame to check whether the user has entered their name. If the user has not entered their name I will ask to enter the name to start the game. If the user has entered their name then I will call the function to display the first question for the user. 
  1. $scope.startGame = function () {  
  2.   
  3.     if($scope.usrName=='')  
  4.     {  
  5.         alert("Enter Your Name to start the game !");  
  6.         $scope.showGameStart = true;  
  7.         $scope.showGame = false;  
  8.         $scope.showresult = false;  
  9.     }  
  10.     else  
  11.     {  
  12.         $scope.questionCount = 1;  
  13.         $scope.totalPoints = 0;  
  14.         $scope.wordCount = 0;  
  15.         $scope.rowCount = 0;  
  16.   
  17.         selectGameDetails();  
  18.         $scope.showGameStart = false;  
  19.         $scope.showGame = true;  
  20.         $scope.showresult = false;  
  21.         }  
  22.     }  
selectGameDetails() To display the Each question.
 
When the user clicks on the Start game button I display questions number 1, the total points as 0 and using the $http.get('/api/wordGame/') I will get 5 random questions from the database and will store the result data to $scope.Images. For the first question the rowcount will be 0, I will display the first question's information with an Answer Word Count.
  1. //get all image Details    
  2. function selectGameDetails() {  
  3.     $http.get('/api/wordGame/').success(function(data) {  
  4.         $scope.Images = data;  
  5.         if ($scope.Images.length > 0) {  
  6.             $scope.Image1 = $scope.Images[$scope.rowCount].image1;  
  7.             $scope.Image2 = $scope.Images[$scope.rowCount].image2;  
  8.             $scope.Image3 = $scope.Images[$scope.rowCount].image3;  
  9.             $scope.Image4 = $scope.Images[$scope.rowCount].image4;  
  10.   
  11.             $scope.Answers = $scope.Images[$scope.rowCount].Answer;  
  12.   
  13.             $scope.wordCount = $scope.Answers.length;  
  14.   
  15.         }  
  16.     })  
  17.         .error(function() {  
  18.         $scope.error = "An Error has occured while loading posts!";  
  19.   
  20.     });  

Question Details

 
 
  • No question: For each question I will display no questions to the user, by default it will be 1.

  • Total Word Count: For each question we can see 4 images. The user must find the matching word for each 4 image combinations. The actual Word Count result I will display as a hint for the user at the top.

  • Total Points: For each questions answered by the user I will display the result of each questions points.

Next Question button Click

In the next button I will check for each answer result entered by the user.

Correct Answer: I will check the user entered answer with the database result answer. If both answers are correct then I will display the result to answer and increment the user total points with 20.

 

Wrong Answer: I will check the user entered answer with the database result answer. If both answers are incorrect then I will display the result to answer and decrement the user total points with 10 (-10).

 
 
 Final Result, the User Losed the Game

When the user has answered all the 5 questions I will check for the result of Total Points for the user and if the points are less than 100 then I will display the message to the user that they have lost the game.

 

When the user clicks on the alert OK button I will display the User Lose the game message and the user can start a new game from here to play again.
 
 
Final Result, the User Won the Game

When the user has answered all 5 questions I will check for the result of Total Points for the user and if the Points are equal to 100 then I will display the message to the user since they have won the game.

 
 
 When the user clicks on the alert OK button I will display the User Won the game message and the user can start the new game from here to play again.
 Here is the AngularJs code to check the user result and display the message.
  1. // to find the Answer    
  2. $scope.findAnswer = function() {  
  3.   
  4.   
  5.     if ($scope.txtAnswer == "") {  
  6.         alert("Enter the Answer");  
  7.         return;  
  8.     }  
  9.   
  10.   
  11.     if ($scope.txtAnswer.toLowerCase() == $scope.Answers.toLowerCase()) {  
  12.         alert("Wow :) You have enter the correct answer and you have got 20 Points for this Answer")  
  13.   
  14.         $scope.totalPoints = $scope.totalPoints + 20;  
  15.   
  16.     } else {  
  17.   
  18.         alert("Sorry :( You have enter the wrong answer and you have got -10 points")  
  19.         $scope.totalPoints = $scope.totalPoints - 10;  
  20.     }  
  21.   
  22.     $scope.txtAnswer = "";  
  23.   
  24.     if ($scope.questionCount == 5) {  
  25.         if ($scope.totalPoints >= 100) {  
  26.             $scope.Resuts = "Wow :) You have won the Game.Good Job " + $scope.usrName;  
  27.             alert($scope.Resuts)  
  28.             $scope.ImageAnswer = "won.png";  
  29.         } else {  
  30.             $scope.Resuts = "Sorry " + $scope.usrName + " You lose the game :( .Your Total points are " + $scope.totalPoints + " out of 100 points"  
  31.   
  32.             alert($scope.Resuts);  
  33.             $scope.ImageAnswer = "lose.png";  
  34.         }  
  35.   
  36.   
  37.         $scope.showGameStart = false;  
  38.         $scope.showGame = false;  
  39.         $scope.showresult = true;  
  40.         return;  
  41.     } else {  
  42.   
  43.         $scope.questionCount = $scope.questionCount + 1;  
  44.   
  45.         $scope.wordCount = 0;  
  46.         $scope.rowCount = $scope.rowCount + 1;  
  47.   
  48.   
  49.         $scope.Image1 = $scope.Images[$scope.rowCount].image1;  
  50.         $scope.Image2 = $scope.Images[$scope.rowCount].image2;  
  51.         $scope.Image3 = $scope.Images[$scope.rowCount].image3;  
  52.         $scope.Image4 = $scope.Images[$scope.rowCount].image4;  
  53.   
  54.   
  55.         $scope.Answers = $scope.Images[$scope.rowCount].Answer;  
  56.   
  57.   
  58.   
  59.         $scope.wordCount = $scope.Answers.length;  
  60.     }  
  61.   

New Game Start method:

After displaying the final result the user can start a new game by clicking the button. In the button click I will call the AngularJs method to start the new game for the user. 

  1. // to Start from New Game  
  2.   
  3.     $scope.NewQuestion = function () {  
  4.         $scope.usrName = "";  
  5.         $scope.questionCount = 1;  
  6.         $scope.totalPoints = 0;  
  7.         $scope.wordCount = 0;  
  8.         $scope.rowCount = 0;  
  9.   
  10.         $scope.showGameStart = true;  
  11.         $scope.showGame = false;  
  12.         $scope.showresult = false;  
  13.     }  
 
 
Note: you can change the database depending on your connection. All of questions and image names have been displayed from the database. If you want to add a new question then kindly add four Images to your application root folder inside the Image folder then provide the same image name in your database image columns. Add the proper answer in your database for the question. There is no static data in my application, so the user can add their own image and answer into the database. I hope you like this game, have fun.

Supported Browsers: Chrome and Firefox.

Up Next
    Ebook Download
    View all
    Learn
    View all