65.9K
CodeProject 正在变化。 阅读更多。
Home

MVC Web API 和 AngularJS 图像拼图游戏

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (26投票s)

2015 年 8 月 17 日

CPOL

10分钟阅读

viewsIcon

52784

downloadIcon

950

如何使用 MVC、AngularJS 和 Web API 2 创建一个单词益智游戏

引言

单词益智游戏

单词益智游戏是一个有趣的游戏,每道题都会显示4张图片。用户必须找到这四张图片共同隐藏的名称。游戏规则是,每局游戏会提出5个问题。问题非常简单,因为每个问题都会显示4组图片,用户必须找到4张图片组合对应的单词,并输入正确答案,然后点击下一步以显示下一个问题。每个问题有20分。如果用户回答了谜题,那么每答对一个问题将获得20分。如果用户输入了错误的答案,那么他将获得负10分。也就是说,每答错一个问题将获得-10分。如果用户在所有5个问题中总共获得100分,那么他或她就是游戏的赢家。如果用户获得少于100分,那么他或她就输掉了游戏,并且可以再试一次。注意,每次问题会显示不同,因为我会从数据库中随机显示问题。所以请仔细查看图片并回答问题,以避免负分。我希望你会喜欢这个游戏,玩得开心。:)

必备组件

Visual Studio 2015。您可以从这里下载。

您还可以查看我之前关于使用 MVC 和 WCF REST 服务进行 AngularJs 的文章。

与 Angular JS、MVC 和 WEB API 相关的往期文章

本文将详细解释如何使用 MVC、AngularJs 和 Web API 2 创建一个在线单词益智游戏。本文将解释

  1. 如何在 SQL Server 中创建示例表和数据库
  2. 使用 Entity Framework 连接数据库
  3. 创建 Web API 控制器以获取数据并使用 LINQ 查询选择随机的5个结果
  4. 如何将 AngularJs 包安装到 MVC 应用程序中
  5. 如何创建我们的 AngularJs 应用程序以制作我们自己的单词益智游戏

AngularJs

我们可能熟悉什么是模型-视图-视图模型 (MVVM) 以及什么是模型-视图-控制器 (MVC)。AngularJs 是一个纯粹基于 HTML、CSS 和 JavaScript 的 JavaScript 框架。

AngularJs 的模型-视图-任何 (MVW) 模式类似于 MVC 和 MVVM 模式。在我们的示例中,我使用了模型、视图和服务。在代码部分,让我们看看如何在我们的 MVC 应用程序中安装和创建 AngularJs。

如果您有兴趣阅读更多关于 AngularJs 的内容,请查阅此链接

Using the Code

1. 创建数据库和表。

我们将在数据库“wordGameDB”中创建一张名为“wordDetails”的表。

表列详情

以下是创建数据库、表和示例insert查询的脚本。在您的 SQL Server 中运行此脚本。我使用的是 SQL Server 2012。

-- =============================================                             
-- 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. 在 Visual Studio 2015 中创建我们的 MVC Web 应用程序。安装 Visual Studio 2015 后,点击开始 -> 程序,然后选择Visual Studio 2015,然后点击Visual Studio 2015

点击新建 -> 项目,然后选择Web -> ASP.NET Web 应用程序。选择您的项目位置并输入您的 Web 应用程序名称。

选择 MVC 并在“添加文件夹和核心引用”中选择 Web API,然后点击 确定

使用 ADO.NET 实体数据模型添加数据库

右键单击我们的项目,然后点击添加 -> 新建项

选择数据,然后选择ADO.NET 实体数据模型,然后为我们的 EF 提供名称并点击添加

选择“来自数据库的 EF 设计器”,然后点击下一步

在这里,点击新建连接并提供您的 SQL Server 服务器名称并连接到您的数据库。

在这里,我们可以看到我输入了我的 SQL Server 名称、ID 和密码,连接后,我选择了数据库为wordGameDB,因为我们是使用我的 SQL 脚本创建的数据库。

点击下一步并选择要使用的表,然后点击完成

点击下一步并选择我们需要的表,然后点击完成

现在我们可以看到我们已经创建了wordPuzzleModel

创建实体后,下一步是向控制器添加 Web API 并编写select/insert/updatedelete函数。

添加 Web API 控制器的过程

右键单击Controllers文件夹,然后点击添加->点击控制器

要创建 Web API 控制器,选择 Controller 并添加空白 Web API 2 控制器。为 Web API 控制器提供一个名称,然后点击 OK。这里,我为我的 Web API 控制器命名为 “wordGameController”。

由于我们已经创建了一个 Web API 控制器,我们可以看到我们的控制器已经继承了ApiController

我们都知道 Web API 简单易用,可以为浏览器和移动设备构建 HTTP 服务。

Web API 有四种方法:Get/Post/PutDelete,其中

  • Get 用于请求数据(select
  • Post 用于创建数据(insert
  • Put 用于更新数据
  • Delete 用于删除数据

在我们的例子中,我们将使用 Get 方法,因为我们需要从数据库中获取所有谜题问题详情。

Get 方法

在我们的示例中,我只使用了Get方法,因为我是从数据库中选择数据来显示单词益智游戏。我们需要为我们的实体创建一个对象,并编写Get方法来执行Select操作。

查询操作

我们使用get方法,通过实体对象获取wordDetail表的所有详情,并以IEnumerable形式返回结果。

在这里,我们可以在get方法中看到我使用了Take方法来只显示数据库中的5条记录。为了从数据库中随机选择记录,我使用了Guid.NewGuid()

我们将在 AngularJs 中使用此方法,并在 MVC HTML 页面中显示结果。

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();
        }
    }

创建 AngularJs Controller

首先,在Script文件夹内创建一个文件夹,我将文件夹命名为“MyAngular”。

现在,将您的 Angular 控制器添加到该文件夹中。

右键单击MyAngular文件夹,然后点击添加 -> 新建项,然后选择Web,然后选择AngularJs控制器并为控制器提供名称。我将我的AngularJs控制器命名为“Controller.js”。

一旦创建了 AngularJs 控制器,我们可以看到默认情况下控制器将包含带有默认模块定义及所有内容的完整代码。

我修改了前面的代码,添加了一个模块和控制器,如下所示。

如果 AngularJs 包丢失,请将该包添加到您的项目中。

右键单击您的 MVC 项目,然后单击管理 NuGet 程序包。搜索 AngularJs,然后单击安装

创建 AngularJs 脚本文件的过程

Modules.js:在这里,我们添加了 Angular.js JavaScript 的引用,并创建了一个名为 “RESTClientModule” 的 Angular 模块。

// <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']);
})();

控制器:在 AngularJs 控制器中,我完成了所有业务逻辑,并将数据从 Web API 返回到我们的 MVC HTML 页面。

1. 变量声明

首先,我声明了所有需要的局部变量。

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. 游戏开始功能

默认情况下,我将显示游戏玩法、游戏规则和开始游戏的说明。用户可以输入他们的名字来开始游戏。用户必须输入名字才能开始游戏。

开始游戏按钮点击时,我调用 AngularJs 方法startGame来检查用户是否输入了名字。如果用户没有输入名字,我将要求输入名字来开始游戏。如果用户输入了名字,那么我将调用函数来显示用户的第一个问题。

$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() - 用于显示每个问题。

当用户点击开始游戏按钮时,我显示第1个问题,总分显示为0,并使用$http.get('/api/wordGame/')从数据库中获取5个随机问题,并将结果数据存储到$scope.Images中。对于第一个问题,rowcount将为0,我将显示第一个问题的信息以及答案单词数量。

//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!";
    });
    }

问题详情

  • 问题编号:对于每个问题,我将向用户显示问题编号,默认情况下为1
  • 总字数:每个问题有4张图片。用户必须找出每4张图片组合对应的单词。我将在顶部显示实际的单词数量作为用户的提示。
  • 总得分:对于用户回答的每个问题,我将显示每个问题的得分结果。

下一个问题按钮点击

在下一个按钮中,我将检查用户输入的每个答案结果。

正确答案:我将把用户输入的答案与数据库中的结果答案进行比较。如果两个答案都正确,我将显示答案结果,并将用户总分增加20。

错误答案:我将检查用户输入的答案与数据库结果答案。如果两个答案都不正确,那么我将显示答案结果,并将用户总分减少10分(-10)。

最终结果,用户输掉游戏

当用户回答完所有5个问题后,我将检查用户的总分数结果,如果分数小于100,我将向用户显示他们输掉游戏的消息。

当用户点击警告确定按钮后,我将显示“用户输掉游戏”的消息,用户可以从这里开始新游戏再次玩。

最终结果,用户赢得游戏

当用户回答完所有5个问题后,我将检查用户的总分数结果,如果分数等于100,那么我将向用户显示他们赢得了游戏的消息。

当用户点击警告确定按钮后,我将显示“用户赢得游戏”的消息,用户可以从这里开始新游戏再次玩。

这是检查用户结果并显示消息的 AngularJs 代码。

// 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;
        }
    }

新游戏开始方法

显示最终结果后,用户可以通过点击按钮开始新游戏。在按钮点击时,我将调用 AngularJs 方法为用户开始新游戏。

// 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文件夹中添加四张图片,然后在您的数据库图片列中提供相同的图片名称。在您的数据库中为问题添加正确的答案。我的应用程序中没有静态数据,因此用户可以将自己的图片和答案添加到数据库中。希望您喜欢这个游戏,玩得开心。

支持的浏览器:Chrome 和 Firefox

历史

  • 2015年8月17日:初始版本
© . All rights reserved.