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).
Download and install the .NET Core 3.0 Preview.
Blazor Extensions
Download the Blazor Extension.
Install Blazor Extension to work with your Blazor applications.
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.
Click on ASP.NET Core Web Application and click "Next".
Enter your project name and click the "Create" button.
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”.
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.
Select Project and Solutions >> .NET Core.
Check the "Use Previews of the .NET Core SDK" box and click OK.
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".
After creating ASP.NET Core Blazor application, wait for a few seconds. You will see the below structure in the Solution Explorer.
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.
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.
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.
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.
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.
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.
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".
Here, let us give the class name as gameImages.cs and click on "Add".
In the class, declare this property for using in our WEB API Controller and in our client application.
- public class gameImages
- {
- public string id { get; set; }
- public string Image1 { get; set; }
- public string Image2 { get; set; }
- public string Image3 { get; set; }
- public string Image4 { get; set; }
- public string Result { get; set; }
-
- }
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".
Here, we will be creating an empty WEB API controller to get only the image details from the list.
Here, we have given the WEB API controller name as “GameData” and we can see that our new WEB API controller has been created.
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.
-
- [HttpGet("[action]")]
- public IEnumerable<gameImages> AllgameImages()
- {
- List<gameImages> gamedata = new List<gameImages>();
-
- gamedata.Add(new gameImages
- {
- id = "1",
- Image1 = "A1_N.png",
- Image2 = "A2_O.png",
- Image3 = "A3_O.png",
- Image4 = "A4_O.png",
- Result = "1"
- });
- gamedata.Add(new gameImages
- {
- id = "2",
- Image1 = "AN1_O.png",
- Image2 = "AN2_O.png",
- Image3 = "AN3_N.png",
- Image4 = "AN4_O.png",
- Result = "3"
- });
- gamedata.Add(new gameImages
- {
- id = "3",
- Image1 = "C1_O.png",
- Image2 = "C2_N.png",
- Image3 = "C3_O.png",
- Image4 = "C4_O.png",
- Result = "2"
- });
- gamedata.Add(new gameImages
- {
- id = "4",
- Image1 = "F1_O.png",
- Image2 = "F2_O.png",
- Image3 = "F3_N.png",
- Image4 = "F4_O.png",
- Result = "3"
- });
- gamedata.Add(new gameImages
- {
- id = "5",
- Image1 = "G1_N.png",
- Image2 = "G2_O.png",
- Image3 = "G3_O.png",
-
- Image4 = "G4_O.png",
- Result = "1"
- });
- gamedata.Add(new gameImages
- {
- id = "6",
- Image1 = "H1_O.png",
- Image2 = "H2_N.png",
- Image3 = "H3_O.png",
- Image4 = "H4_O.png",
- Result = "2"
- });
- gamedata.Add(new gameImages
- {
- id = "7",
- Image1 = "J1_N.png",
- Image2 = "J2_O.png",
- Image3 = "J3_O.png",
-
- Image4 = "J4_O.png",
- Result = "1"
- });
- gamedata.Add(new gameImages
- {
- id = "9",
- Image1 = "S1_O.png",
- Image2 = "S2_N.png",
- Image3 = "S3_O.png",
-
- Image4 = "S4_O.png",
- Result = "2"
- });
- gamedata.Add(new gameImages
- {
- id = "9",
- Image1 = "N1_N.png",
- Image2 = "N2_O.png",
- Image3 = "N3_O.png",
-
- Image4 = "N4_O.png",
- Result = "1"
- });
- gamedata.Add(new gameImages
- {
- id = "10",
- Image1 = "NW1_O.png",
- Image2 = "NW2_N.png",
- Image3 = "NW3_O.png",
-
- Image4 = "NW4_O.png",
- Result = "2"
- });
- gamedata.Add(new gameImages
- {
- id = "11",
- Image1 = "O1_O.png",
- Image2 = "O2_O.png",
- Image3 = "O3_O.png",
-
- Image4 = "O4_N.png",
- Result = "4"
- });
- gamedata.Add(new gameImages
- {
- id = "12",
- Image1 = "P1_O.png",
- Image2 = "P2_N.png",
- Image3 = "P3_O.png",
-
- Image4 = "P4_O.png",
- Result = "2"
- });
- gamedata.Add(new gameImages
- {
- id = "13",
- Image1 = "SC1_O.png",
- Image2 = "SC2_O.png",
- Image3 = "SC3_O.png",
-
- Image4 = "SC4_N.png",
- Result = "4"
- });
- gamedata.Add(new gameImages
- {
- id = "14",
- Image1 = "T1_N.png",
- Image2 = "T2_O.png",
- Image3 = "T3_O.png",
-
- Image4 = "T4_O.png",
- Result = "1"
- });
- gamedata.Add(new gameImages
- {
- id = "15",
- Image1 = "WA1_O.png",
- Image2 = "WA2_O.png",
- Image3 = "WA3_N.png",
-
- Image4 = "WA4_O.png",
- Result = "3"
- });
- return gamedata.AsEnumerable();
- }
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.
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.
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.
- @page "/games"
- @using ShanuGameBlazor.Shared
- @inject HttpClient Http
Display New Game Message
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.
- @if (showGameStart == true)
- {
-
- <tr>
- <td align="center">
- <h1>
- Shanu Blazor Odd Image Out Game
- </h1>
- <br><br>
- <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>
- <br><br>
-
- Find the Odd Image from the Given four Images. You will be having 5 questions.<br>
- Answer all the 5 Questions.
- <br>Wrong Answer will get -5 points and the correct answer will get 10 Points.<br>
- If the user answers all the 5 Questions correctly, then they are the winner.
-
- </td>
- </tr>
- }
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.
- protected override async Task OnInitAsync()
- {
- gamesimg = await Http.GetJsonAsync<gameImages[]>("api/GameData/AllgameImages");
- }
When user clicks on the "First Question" button, then we hide the Game Start Table row and show the game page table rows.
- void FirstQuestion() {
- showGameStart = false;
- showGame = true;
- showresult = false;
- displayQuestion();
Display New Game Question.
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.
- @if (showGame == true)
- {
- <tr>
- <td align="Center">
- <table class="table">
-
-
- <tr style="background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
- <td align="right" colspan="2">
- <table class="table">
- <tr>
- <td colspan="4" align="center" style="color:#FFFFFF;"><h1> Shanu Blazor Odd Image Out Game </h1></td>
- </tr>
- <tr>
-
- <td style="color:#FFFFFF;font-size:x-large">
- Question : @questionCount
- </td>
- <td style="color:#FFFFFF;font-size:x-large;" colspan="2" align="center">
-
-
- <img src="Images/coin.png" width="48px" height="48px">
-
- </td>
- <td style="color:#FFFFFF;font-size:x-large;">
- Total points : @totalPoints
- </td>
- </tr>
- </table>
- </td>
- </tr>
-
- <tr>
- <td align="center" style=" background-color:#FFFFFF; border: dashed 2px #e44a10; padding:10px;width:50%;">
- <img src="Images/@Image1" width="120px" height="120px" onclick=@(() => findAnswer("1")) />
-
- </td>
- <td align="center" style=" background-color:#FFFFFF; border: dashed 2px #e44a10; padding:10px;width:50%;">
- <img src="Images/@Image2" width="120px" height="120px" onclick=@(() => findAnswer("2")) />
- </td>
- </tr>
- <tr>
- <td align="center" style=" background-color:#FFFFFF; border: dashed 2px #e44a10; padding:10px;width:50%;">
- <img src="Images/@Image3" width="120px" height="120px"
- onclick=@(() => findAnswer("3")) />
- </td>
- <td align="center" style=" background-color:#FFFFFF; border: dashed 2px #e44a10; padding:10px;width:50%;">
- <img src="Images/@Image4" width="120px" height="120px" onclick=@(() => findAnswer("4")) />
- </td>
- </tr>
- </table>
- </td>
- </tr>
- <tr>
- <td align="center">
-
-
- Find the Odd Image from the Given four Images. You will be having 5 questions.<br>
- Answer all the 5 Questions.
- <br>Wrong Answer will get -5 points and the correct answer will get 10 Points.<br>
- If the user answers all the 5 Questions correctly then they are the winner.
-
- </td>
- </tr>
- }
Function Code
- void displayQuestion() {
- questionCount =questionCount +1;
- Random random = new Random();
- int totalcounts = gamesimg.Count();
- randomQuestion=random.Next(1,totalcounts);
- Image1 = gamesimg[randomQuestion].Image1;
- Image2 = gamesimg[randomQuestion].Image2;
- Image3 = gamesimg[randomQuestion].Image3;
- Image4 = gamesimg[randomQuestion].Image4;
- ImageAnswer =gamesimg[randomQuestion].Result;
- }
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.
-
- void findAnswer(string checkvals) {
- if (checkvals == ImageAnswer)
- {
-
- totalPoints = totalPoints + 10;
- }
- else
- {
- totalPoints = totalPoints-5;
- }
- counterval = counterval + 1;
-
-
- if(counterval==5)
- {
-
- displayResult();
- return;
- }
- displayQuestion();
- }
Here, we can see the preview of the working game screen.
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.
- void displayResult() {
-
- if (totalPoints >= 50)
- {
- Resuts = " Wow :) You have answerd all the 5 questions correctly and won the Game.Good Job " ;
- wonImage = "Won.png";
- }
- else
- {
- Resuts = "Sorry You lose the game :( .Your Total points are " + totalPoints + " out of 50 points";
- wonImage = "Lose.png";
- }
- showGameStart = false;
- showGame = false;
- 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.
Lose the Game
If the points are less than 50, then we will display the message as the user loses the game.
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.