Simple Blazor Game Development Using .NET Core 3.0 Preview, Web API, And Visual Studio 2019

ASP.NET Core Blazor simple game development using .Net core 3.0 preview Web API and Visual Studio 2019
 

Introduction

 
Here, we will be creating an “Odd Image Out" game. In this game, a total of 5 questions will be asked. In each question, we will display a set of 4 images where one image will be different from the other three. User has to pick the odd image from the four images. If the user picks the correct one, they will get 10 points. If the user selects a wrong answer, then he/she will get -5 points. After all the 5 questions have been answered by the user, the result will be calculated. If the user gets perfect 50, then he/she wins the game and if the user gets points less than 50, then the user loses the game.

What you should know to create this "Odd Image Out" App using ASP.NET Core Blazor?

You need to have the basic knowledge of the following.

If you are new to Visual Studio 2019, then kindly read my previous article which explains the process of getting started with Visual Studio 2019.

If you are new to ASP.NET Blazor, you can read our previous article which explains the process of working with ASP.NET Core Blazor.

Prerequisites
  • Visual Studio 2019
  • .NET Core 3.0 Preview SDK.
  • Blazor Extensions.

Visual Studio 2019

If you have not yet installed Visual Studio 2019, you can download the Visual Studio 2019 from this link and install it on your computer.

.NET Core 3.0 Preview SDK

Install the .NET Core 3.0 Preview SDK. (You can find all versions from this link).

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Download and install the .NET Core 3.0 Preview.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Blazor Extensions

Download the Blazor Extension.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Install Blazor Extension to work with your Blazor applications.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Odd Image out Game

First, collect all the images needed to be displayed for the question. Each question carries a set of 4 images and in that, one image should be of a different kind. So, collect as many images as possible to make more questions. We will display the questions randomly from the set of questions to avoid repeated question display. So first, we need to make questions for the users to not get bored with the game. After downloading all the images, let's give a proper name to each image. In the image name itself, we have given an answer as O for Ok and N for the wrong image. For the sample of this demo, we have created a total of 15 questions with 15 * 4 images. You can add more questions to make the game more interesting.

Code Part

Step 1 - Create an ASP.NET Core Blazor Application

After installing all the prerequisites listed above and ASP.NET Core Blazor extension, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop. Click New >> Project. 

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Click on ASP.NET Core Web Application and click "Next".

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Enter your project name and click the "Create" button.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Now, we can see that for ASP.NET Core 3.0, only Blazor template has been listed. Even if we create the Blazor project and run, it will show the error as “The current .NET SDK does not support targeting .NET Core 3.0. Either target .NET Core 2.2 or lower, or use a version of the .NET SDK that supports .NET Core 3.0. WebApplication2.Server”.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

To avoid the error and list all the ASP.NET Core templates for .NET Core 3.0 Preview, we need to enable the “Use previews of the .NET Core SDK” option.

For this, let us cancel creating the project and in our Visual Studio 2019, go to Tools >> Options.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Select Project and Solutions >> .NET Core.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Check the "Use Previews of the .NET Core SDK" box and click OK.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Now again, create the ASP.NET Core web project. We can see that now, all the project templates for ASP.NET Core are available for ASP.NET Core 3.0. Let us select Blazor (ASP.NET Core hosted) project and click "Create".

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

After creating ASP.NET Core Blazor application, wait for a few seconds. You will see the below structure in the Solution Explorer.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

When we create our new ASP.NET Core Blazor application, we can see there are 3 projects that will be automatically created in the Solution Explorer.

Client Project

The first project created as a Client Project is our BlazorCore.Client and here, we can see our solution name as “BlazorCore”. This project will mainly focus on all the client-side Views. Here, we will be adding all our page views to be displayed at the client side in the browser.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

We can see a few sample pages already added here and we can also see a shared folder like our MVC application where we will be having the Shared folder and Layout page for the Master page. Here, in Blazor, we have the MainLayout which will be working like the Master page and NavMenu for the left side menu display.

Server Project

As the name indicates, this project will be used as a Server project. This project is mainly used to create all our Controllers and WEB API Controllers to perform all business logic and perform CRUD operation using Web API’s. In our demo application, we will be adding a Web API in this Server project and all the WEB APIs in our client application. This Server project will work like GET/SET the data from the database and from our Client project, we bind or send the result to this server to perform the CRUD operation in the database.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Shared Project

As the name indicates, this project works like a shred project. This project works as a Model for our Server project and for the Client project. The Model declared in this Shared project will be used in both, the Server and the Client project. We also need to install all the packages needed for our project here. For example, to use the Entity Framework, we install all the packages in this Shared project.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Run and test the application

When we run the application, we can see that the left side has navigation and the right side contains the data. We can see that the default sample pages and menus are displayed in our Blazor web site. We can use these pages or remove them and start with our own pages.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Now, let’s see how to add a new page to create our own "Odd Image Out" game.

Adding Images

First, let us add a new folder “Images" inside the wwwroot directory.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

In the newly added Images folder, add all your images which you will be using for the game. Here, we have added 60 sample images for our 15 questions.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Adding Model class

Now, we will create a model class in our shared project for working with WEB API and in our client application, for displaying the questions. Right-click the Shared project and click on "Add New Class".

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Here, let us give the class name as gameImages.cs and click on "Add".

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

In the class, declare this property for using in our WEB API Controller and in our client application.

  1. public class gameImages  
  2.     {  
  3.         public string id { getset; }  
  4.         public string Image1 { getset; }  
  5.         public string Image2 { getset; }  
  6.         public string Image3 { getset; }   
  7.         public string Image4 { getset; }  
  8.         public string Result { getset; }  
  9.   
  10.     }  

Creating Web API for getting the image details for the game

To create the WEB API Controller, let's right-click our Server project Controllers folder. Click "Add New Controller".

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Here, we will be creating an empty WEB API controller to get only the image details from the list.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Here, we have given the WEB API controller name as “GameData” and we can see that our new WEB API controller has been created.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Now, we need to add the below GET method to get all the game images. For this, here, we are not using a database but adding all the image details to a list and return the list as IEnumerable. In our client, we will receive the JSON result and display all the game questions and images.

  1. //api/GameData/AllgameImages  
  2.       [HttpGet("[action]")]  
  3.       public IEnumerable<gameImages> AllgameImages()  
  4.       {  
  5.           List<gameImages> gamedata = new List<gameImages>();   
  6.   
  7.           gamedata.Add(new gameImages  
  8.           {  
  9.               id = "1",  
  10.               Image1 = "A1_N.png",  
  11.               Image2 = "A2_O.png",  
  12.               Image3 = "A3_O.png",  
  13.               Image4 = "A4_O.png",  
  14.               Result = "1"  
  15.           });  
  16.           gamedata.Add(new gameImages  
  17.           {  
  18.               id = "2",  
  19.               Image1 = "AN1_O.png",  
  20.               Image2 = "AN2_O.png",  
  21.               Image3 = "AN3_N.png",  
  22.               Image4 = "AN4_O.png",  
  23.               Result = "3"  
  24.           });  
  25.           gamedata.Add(new gameImages  
  26.           {  
  27.               id = "3",  
  28.               Image1 = "C1_O.png",  
  29.               Image2 = "C2_N.png",  
  30.               Image3 = "C3_O.png",  
  31.               Image4 = "C4_O.png",  
  32.               Result = "2"  
  33.           });  
  34.           gamedata.Add(new gameImages  
  35.           {  
  36.               id = "4",  
  37.               Image1 = "F1_O.png",  
  38.               Image2 = "F2_O.png",  
  39.               Image3 = "F3_N.png",  
  40.               Image4 = "F4_O.png",  
  41.               Result = "3"  
  42.           });  
  43.           gamedata.Add(new gameImages  
  44.           {  
  45.               id = "5",  
  46.               Image1 = "G1_N.png",  
  47.               Image2 = "G2_O.png",  
  48.               Image3 = "G3_O.png",  
  49.   
  50.               Image4 = "G4_O.png",  
  51.               Result = "1"  
  52.           });  
  53.           gamedata.Add(new gameImages  
  54.           {  
  55.               id = "6",  
  56.               Image1 = "H1_O.png",  
  57.               Image2 = "H2_N.png",  
  58.               Image3 = "H3_O.png",  
  59.               Image4 = "H4_O.png",  
  60.               Result = "2"  
  61.           });  
  62.           gamedata.Add(new gameImages  
  63.           {  
  64.               id = "7",  
  65.               Image1 = "J1_N.png",  
  66.               Image2 = "J2_O.png",  
  67.               Image3 = "J3_O.png",  
  68.   
  69.               Image4 = "J4_O.png",  
  70.               Result = "1"  
  71.           });  
  72.           gamedata.Add(new gameImages  
  73.           {  
  74.               id = "9",  
  75.               Image1 = "S1_O.png",  
  76.               Image2 = "S2_N.png",  
  77.               Image3 = "S3_O.png",  
  78.   
  79.               Image4 = "S4_O.png",  
  80.               Result = "2"  
  81.           });  
  82.           gamedata.Add(new gameImages  
  83.           {  
  84.               id = "9",  
  85.               Image1 = "N1_N.png",  
  86.               Image2 = "N2_O.png",  
  87.               Image3 = "N3_O.png",  
  88.   
  89.               Image4 = "N4_O.png",  
  90.               Result = "1"  
  91.           });  
  92.           gamedata.Add(new gameImages  
  93.           {  
  94.               id = "10",  
  95.               Image1 = "NW1_O.png",  
  96.               Image2 = "NW2_N.png",  
  97.               Image3 = "NW3_O.png",  
  98.   
  99.               Image4 = "NW4_O.png",  
  100.               Result = "2"  
  101.           });  
  102.           gamedata.Add(new gameImages  
  103.           {  
  104.               id = "11",  
  105.               Image1 = "O1_O.png",  
  106.               Image2 = "O2_O.png",  
  107.               Image3 = "O3_O.png",  
  108.   
  109.               Image4 = "O4_N.png",  
  110.               Result = "4"  
  111.           });  
  112.           gamedata.Add(new gameImages  
  113.           {  
  114.               id = "12",  
  115.               Image1 = "P1_O.png",  
  116.               Image2 = "P2_N.png",  
  117.               Image3 = "P3_O.png",  
  118.   
  119.               Image4 = "P4_O.png",  
  120.               Result = "2"  
  121.           });  
  122.           gamedata.Add(new gameImages  
  123.           {  
  124.               id = "13",  
  125.               Image1 = "SC1_O.png",  
  126.               Image2 = "SC2_O.png",  
  127.               Image3 = "SC3_O.png",  
  128.   
  129.               Image4 = "SC4_N.png",  
  130.               Result = "4"  
  131.           });  
  132.           gamedata.Add(new gameImages  
  133.           {  
  134.               id = "14",  
  135.               Image1 = "T1_N.png",  
  136.               Image2 = "T2_O.png",  
  137.               Image3 = "T3_O.png",  
  138.   
  139.               Image4 = "T4_O.png",  
  140.               Result = "1"  
  141.           });  
  142.           gamedata.Add(new gameImages  
  143.           {  
  144.               id = "15",  
  145.               Image1 = "WA1_O.png",  
  146.               Image2 = "WA2_O.png",  
  147.               Image3 = "WA3_N.png",  
  148.   
  149.               Image4 = "WA4_O.png",  
  150.               Result = "3"  
  151.           });  
  152.           return gamedata.AsEnumerable();  
  153.       }  

To test the Get method, we can run our project and copy the GET method API path. Here, we can see our API path -api/GameData/AllgameImages/ 

Run the program and paste the API path to test your output.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Working with Client Project

Add a Razor View. To add the Razor View page, right-click the Pages folder from the Client project.

Click on Add >> New Item.

Select Razor View >> Enter your page name. Here, I have given the name as games.razor.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

In Razor View Page, let us add 3 parts of the code. The first is the Import part where we import all the references and models for using in the View. The second part is HTML design and data bind part; and finally, we have the function part to call all the web APIs to bind in our HTML page and also to perform client-side business logic to be displayed in View page for the game.

Import part

First, we import all the needed support files and references in our Razor View page. Here, we have first imported our Model class to be used in our View and also imported HTTPClient for calling the Web API to display the questions and check for the matching answer to calculate the answers.

  1. @page "/games"  
  2. @using ShanuGameBlazor.Shared  
  3. @inject HttpClient Http  

Display New Game Message

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

When a user clicks on the "New Game" button, we will call the FirstQuestion() method, display and hide the relevant table row for displaying the question. And call the displayQuestion() method to display the first question.

  1. @if (showGameStart == true)  
  2.      {  
  3.   
  4.          <tr>  
  5.              <td align="center">  
  6.                  <h1>  
  7.                      Shanu Blazor Odd Image Out Game  
  8.                  </h1>  
  9.                  <br><br>  
  10.                  <button type="submit" class="btn btn-success" onclick=@FirstQuestion style="background-color:#3f9835;color:#FFFFFF;border-color:#f6f803;border-style:dashed;width:220px">Start Game </button>  
  11.                  <br><br>  
  12.   
  13.                  Find the Odd Image from the Given four Images. You will be having 5 questions.<br>  
  14.                  Answer all the 5 Questions.  
  15.                  <br>Wrong Answer will get -5 points and the correct answer will get 10 Points.<br>  
  16.                  If the user answers all the 5 Questions correctly, then they are the winner.  
  17.   
  18.              </td>  
  19.          </tr>  
  20.      }  

In Funciton

In funciotn, first, we have created the OnInitAsync method. In this method, first, we get all the WEB API JSON results and store it in an array for using in our game.

  1. protected override async Task OnInitAsync()  
  2. {  
  3.     gamesimg = await Http.GetJsonAsync<gameImages[]>("api/GameData/AllgameImages");  
  4. }  

When user clicks on the "First Question" button, then we hide the Game Start Table row and show the game page table rows.

  1.   void FirstQuestion() {   
  2. showGameStart = false;  
  3. showGame = true;  
  4. showresult = false;  
  5. displayQuestion();  

Display New Game Question.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

When a user clicks on "New Game", we will call the displayQuestion() method to select the random question from the set of questions which we have created, and display the images in the HTML page.

  1. @if (showGame == true)  
  2.         {  
  3.             <tr>  
  4.                 <td align="Center">  
  5.                     <table class="table">  
  6.   
  7.   
  8.                         <tr style="background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">  
  9.                             <td align="right" colspan="2">  
  10.                                 <table class="table">  
  11.                                     <tr>  
  12.                                         <td colspan="4" align="center" style="color:#FFFFFF;"><h1> Shanu Blazor Odd Image Out Game </h1></td>  
  13.                                     </tr>  
  14.                                     <tr>  
  15.   
  16.                                         <td style="color:#FFFFFF;font-size:x-large">  
  17.                                             Question :  @questionCount  
  18.                                         </td>  
  19.                                         <td style="color:#FFFFFF;font-size:x-large;" colspan="2" align="center">  
  20.   
  21.   
  22.                                             <img src="Images/coin.png" width="48px" height="48px">  
  23.   
  24.                                         </td>  
  25.                                         <td style="color:#FFFFFF;font-size:x-large;">  
  26.                                             Total points :  @totalPoints  
  27.                                         </td>  
  28.                                     </tr>  
  29.                                 </table>  
  30.                             </td>  
  31.                         </tr>  
  32.   
  33.                         <tr>  
  34.                             <td align="center" style=" background-color:#FFFFFF; border: dashed 2px #e44a10; padding:10px;width:50%;">  
  35.                                 <img src="Images/@Image1" width="120px" height="120px" onclick=@(() => findAnswer("1")) />  
  36.   
  37.                             </td>  
  38.                             <td align="center" style=" background-color:#FFFFFF; border: dashed 2px #e44a10; padding:10px;width:50%;">  
  39.                                 <img src="Images/@Image2" width="120px" height="120px" onclick=@(() => findAnswer("2")) />  
  40.                             </td>  
  41.                         </tr>  
  42.                         <tr>  
  43.                             <td align="center" style=" background-color:#FFFFFF; border: dashed 2px #e44a10; padding:10px;width:50%;">  
  44.                                 <img src="Images/@Image3" width="120px" height="120px"  
  45.                                      onclick=@(() => findAnswer("3")) />  
  46.                             </td>  
  47.                             <td align="center" style=" background-color:#FFFFFF; border: dashed 2px #e44a10; padding:10px;width:50%;">  
  48.                                 <img src="Images/@Image4" width="120px" height="120px" onclick=@(() => findAnswer("4")) />  
  49.                             </td>  
  50.                         </tr>  
  51.                     </table>  
  52.                 </td>  
  53.             </tr>  
  54.             <tr>  
  55.                 <td align="center">  
  56.                        
  57.   
  58.                     Find the Odd Image from the Given four Images. You will be having 5 questions.<br>  
  59.                     Answer all the 5 Questions.  
  60.                     <br>Wrong Answer will get -5 points and the correct answer will get 10 Points.<br>  
  61.                     If the user answers all the 5 Questions correctly then they are the winner.  
  62.   
  63.                 </td>  
  64.             </tr>  
  65.         }  

Function Code

  1. void displayQuestion() {  
  2.         questionCount =questionCount +1;  
  3.         Random random = new Random();  
  4.         int totalcounts = gamesimg.Count();  
  5.         randomQuestion=random.Next(1,totalcounts);  
  6.         Image1 = gamesimg[randomQuestion].Image1;  
  7.         Image2 = gamesimg[randomQuestion].Image2;  
  8.         Image3 = gamesimg[randomQuestion].Image3;  
  9.         Image4 = gamesimg[randomQuestion].Image4;  
  10.         ImageAnswer =gamesimg[randomQuestion].Result;  
  11.     }  

Find Answer

Now, we have displayed the question, so what is next. Yes, in each question image click, we need to find the correct answer. In each image click event, we will call the findAnswer(1) method to check for each answer and calculate the result and display the points to the user. Also, we need to display the next question. In this method, we will pass the argument as 1,2,3,4 for each question clicked by order and in each question answer, we will be storing the answers in Number.

We will compare both the user clicked image numbers with each question's answer. If both are matching, then we will add 10 points and if the answer is wrong, then we will subtract 5 points. Finally, we will display the next question for the user to play.
  1. // to find the Answer  
  2. void findAnswer(string checkvals) {  
  3.     if (checkvals == ImageAnswer)  
  4.     {  
  5.   
  6.         totalPoints = totalPoints + 10;  
  7.     }  
  8.     else  
  9.     {  
  10.         totalPoints = totalPoints-5;  
  11.     }  
  12.     counterval = counterval + 1;  
  13.   
  14.   
  15.     if(counterval==5)  
  16.     {  
  17.   
  18.         displayResult();  
  19.         return;  
  20.     }  
  21.     displayQuestion();  
  22. }  

Here, we can see the preview of the working game screen.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

In the meantime, we will check for questions counter value. If the user answers total 5 questions, then we will call the displayResult() method to display the final result to the user.

Display Final result

In this method, we will check for the total points of the user and display the result.

  1. void displayResult() {  
  2.   
  3.     if (totalPoints >= 50)  
  4.     {  
  5.         Resuts = " Wow :) You have answerd all the 5 questions correctly and won the Game.Good Job " ;  
  6.         wonImage = "Won.png";  
  7.     }  
  8.     else  
  9.     {  
  10.         Resuts = "Sorry You lose the game :( .Your Total points are " + totalPoints + " out of 50 points";   
  11.         wonImage = "Lose.png";  
  12.     }     
  13.     showGameStart = false;  
  14.      showGame = false;  
  15.     showresult = true;  

Won the Game

If the points are greater than or equal to 50, then we will display the message as the user won the game.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Lose the Game

If the points are less than 50, then we will display the message as the user loses the game.

ASP.NET Core Blazor simple game development using .Net core 3.0 preview,Web API and Visual Studio 2019

Conclusion

In this article, we have added game details using a static list in Web API with fixed 60 images for 15 questions. You can extend this to load from the database for both questions and images. Hope you all like this article. In the next article, we will see more examples to work with Blazor. It's really very cool and awesome to work with Blazor.