Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web

MVC Web API and AngularJS for Image Puzzle Game

4.86/5 (27 votes)
3 Sep 2015CPOL10 min read 51.5K   909  
How to use MVC, AngularJS and Web API 2 and create a word puzzle game
This article shows how to create a word puzzle game using MVC, AngularJS and Web API 2.

Image 1

Introduction

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 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 Angular JS,MVC and 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 this link.

Using the Code

1. Create a database and table.

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

Table Column Details

Image 2

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.

SQL
-- =============================================                             
-- Author      : Shanu                           
-- Create date : 2015-08-13                             
-- Description : To Create Database,Table and Sample Insert Query                            
-- Latest                             
-- Modifier    : Shanu                              
-- Modify date : 2015-03-13                          
-- =============================================
--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] = 'wordGameDB' )
DROP DATABASE wordGameDB

GO

CREATE DATABASE wordGameDB
GO

USE wordGameDB
GO

-- 1) //////////// ItemDetails 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] = 'wordDetails' )
DROP TABLE wordDetails
GO

CREATE TABLE wordDetails
(
   word_ID int identity(1,1),
   word_Name VARCHAR(100)  NOT NULL,
   image1 VARCHAR(100)  NOT NULL,
   image2 VARCHAR(100)  NOT NULL,
   image3 VARCHAR(100)  NOT NULL,
   image4 VARCHAR(100)  NOT NULL,
   Answer VARCHAR(100)  NOT NULL,
CONSTRAINT [PK_wordDetails] PRIMARY KEY CLUSTERED  
(  
  word_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 wordDetails(word_Name,image1,image2,image3,image4,Answer) _
values('Animals','animals-01.png','animals-02.png',_
'animals-03.png','animals-04.png','Animals')

Insert into wordDetails(word_Name,image1,image2,image3,image4,Answer) _
values('Announcement','Anouncement-01.png','Anouncement-02.png',_
'Anouncement-03.png','Anouncement-04.png','Announcement')

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')

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')

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')

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')

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')

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')

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')

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')

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')

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')

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')

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')

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')

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')

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')

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.

Image 3

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

Image 4

Add Database using ADO.NET Entity Data Model

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

Image 5

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

Image 6

Select "EF Designer from database", then click Next.

Image 7

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

Image 8

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.

Image 9

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

Image 10

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

Image 11

Here, we can see now we have created our wordPuzzleModel.

Image 12

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.

Image 13

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”.

Image 14

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

Image 15

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 that 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.

C#
public class wordGameController : ApiController
    {
        wordGameDBEntities objAPI = new wordGameDBEntities();

        //get all Images
    [HttpGet]
    public IEnumerable<shanuAngularWordGame.wordDetail> Get()
        { 
            return objAPI.wordDetails.OrderBy(x => Guid.NewGuid()).Take(5).AsEnumerable();
        }
    }

Creating AngularJs Controller

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

Image 16

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”.

Image 17

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

Image 18

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.

Image 19

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”.

JavaScript
// <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 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.

JavaScript
app.controller("AngularJs_ImageController", 
function ($scope, $timeout, $rootScope, $window, $http) {

    //Global Variables
    $scope.date = new Date();
    $scope.MyName = "Shanu";
    $scope.usrName = "";
    $scope.Images;
    $scope.txtAnswer="";

    //Game variable declared
    //This variable has been declared to display the Question Number,
    User Total Points on each questions    //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.
    //rowCount is used to display the Question one by one.
    $scope.questionCount = 1;
    $scope.totalPoints = 0
    $scope.wordCount = 0;
    $scope.rowCount = 0;

    //Game Detail Display Variables todisplay each 4 images for 
    //one question and to store the result to compare with user enterd answer
    $scope.Image1 = "";
    $scope.Image2 = "";
    $scope.Image3 = "";
    $scope.Image4 = "";
    $scope.ImageAnswer = "won.png";
    $scope.Answers = "";
    $scope.Resuts = "";

    //  --  

    //Game Hidden Table row display
    $scope.showGameStart = true;
    $scope.showGame = false;
    $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.

Image 20

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.

JavaScript
$scope.startGame = function () {
    if($scope.usrName=='')
    {
        alert("Enter Your Name to start the game !");
        $scope.showGameStart = true;
        $scope.showGame = false;
        $scope.showresult = false;
    }
    else
    {
        $scope.questionCount = 1;
        $scope.totalPoints = 0;
        $scope.wordCount = 0;
        $scope.rowCount = 0;
        selectGameDetails();
        $scope.showGameStart = false;
        $scope.showGame = true;
        $scope.showresult = false;
        }
    }

selectGameDetails() - To display the Each question.

Image 21

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.

JavaScript
//get all image Details
    function selectGameDetails() {
    $http.get('/api/wordGame/').success(function (data) {
        $scope.Images = data;    
        if ($scope.Images.length > 0) {         
            $scope.Image1 = $scope.Images[$scope.rowCount].image1;
            $scope.Image2 = $scope.Images[$scope.rowCount].image2;
            $scope.Image3 = $scope.Images[$scope.rowCount].image3;
            $scope.Image4 = $scope.Images[$scope.rowCount].image4;
 
            $scope.Answers = $scope.Images[$scope.rowCount].Answer;         
            $scope.wordCount = $scope.Answers.length; 
        }
    })
    .error(function () {
        $scope.error = "An Error has occurred while loading posts!";
    });
    }

Question Details

Image 22

  • 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.

Image 23

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).

Image 24

Final Result, the User Lost 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.

Image 25

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.

Image 26

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.

Image 27

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.

Image 28

Here is the AngularJs code to check the user result and display the message.

JavaScript
// to find the Answer
    $scope.findAnswer = function () {
     
        if ($scope.txtAnswer == "")
        {
            alert("Enter the Answer");
            return;
        }

        if ($scope.txtAnswer.toLowerCase() == $scope.Answers.toLowerCase())
        {
        alert("Wow :) You have enter the correct answer and 
               you have got 20 Points for this Answer")
            $scope.totalPoints = $scope.totalPoints + 20;     
        }
        else
        {
            alert("Sorry :( You have enter the wrong answer and you have got -10 points")
            $scope.totalPoints = $scope.totalPoints-10;
        }

        $scope.txtAnswer = "";
        if ($scope.questionCount == 5)
        {
            if ($scope.totalPoints >= 100)
            {
                $scope.Resuts = "Wow :) You have won the Game.Good Job " + $scope.usrName;
                alert($scope.Resuts)
                $scope.ImageAnswer = "won.png";
            }
            else
            {
                $scope.Resuts = "Sorry " + $scope.usrName + " 
                You lose the game :( .Your Total points are " + 
                $scope.totalPoints +" out of 100 points"

                alert($scope.Resuts);
                $scope.ImageAnswer = "lose.png";
            }              

            $scope.showGameStart = false;
            $scope.showGame = false;
            $scope.showresult = true;
            return;
        }
        else
            {
        $scope.questionCount = $scope.questionCount + 1;
        $scope.wordCount = 0;
        $scope.rowCount = $scope.rowCount + 1;

        $scope.Image1 = $scope.Images[$scope.rowCount].image1;
        $scope.Image2 = $scope.Images[$scope.rowCount].image2;
        $scope.Image3 = $scope.Images[$scope.rowCount].image3;
        $scope.Image4 = $scope.Images[$scope.rowCount].image4;
       $scope.Answers = $scope.Images[$scope.rowCount].Answer;
       $scope.wordCount = $scope.Answers.length;
        }
    }

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.

JavaScript
// to Start from New Game
    $scope.NewQuestion = function () {
        $scope.usrName = "";
        $scope.questionCount = 1;
        $scope.totalPoints = 0;
        $scope.wordCount = 0;
        $scope.rowCount = 0;

        $scope.showGameStart = true;
        $scope.showGame = false;
        $scope.showresult = false;
    }

Image 29

Points of Interest

Note: You can change the database depending on your connection. All 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

History

  • 17th August, 2015: Initial version

License

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