0% found this document useful (0 votes)
13 views97 pages

File 3

Uploaded by

Anjali Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views97 pages

File 3

Uploaded by

Anjali Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Project Report On

“Web Games Portal”

Submitted to

Himachal Pradesh Technical University,


Hamirpur(H.P)

For the partial fulfillment for the degree

Session : 2023-2025
Under the Supervision of : Submitted by :
Mrs. Shagun Anjali
23015128017

Developed at
Department of Computer Science
H.P.T.U,Hamirpur,Daruhi (H.P)
Certificate - I
This is to certify that the project report entitled “Web Games Portal” submitted to Department
of Computer Science, Himachal Pradesh Technical University,Hamirpur,Daruhi (H.P), in
Partial fulfillment of the requirement for the award of the degree, Master of Computer
Applications’ (M.C.A), is an authentic and original work carried out by Ms. Anjali, with
enrolment number as 23015128017 under my guidance.

Student’s Signature Guide’s Signature

Date : ________________ Mrs. Shagun

Dept. of Computer Science,

Himachal Pradesh Technical


University

Hamirpur ,Daruhi, (H.P)


Certificate - II
Acknowledgement
This is to certify, that the Project Report titled “Web Games Portal” submitted by me (Anjali
Thakur), is an outcome of my independent and original work. I have duly acknowledged all the
sources from which ideas and extracts have been taken. The project is free from any plagiarism
and has not been submitted elsewhere to any other University/Institute for the fulfillment of the
requirements of any course of study.

I would like to express my gratitude towards my guide teacher, Mrs. Shagun and head-of-
department, who gave me the golden opportunity to work on this wonderful project.

Place :Hamirpur Anjali

Date : _______________ 23015128017

MCA 4th Semester

Himachal Pradesh Technical


University

Hamirpur,Daruhi (H.P)
Abstract
The “Web Games Portal” is a web-based gaming web-application which aims to provide users
a convenient and accessible platform to play a variety of mini web games directly through their
web browsers.

Web games have become a popular pastime, offering a vast universe of entertainment, accessible
directly through your web browser. From casual puzzle games to action-packed adventures and
even multiplayer experiences, there's a web game to suit almost any taste and skill level. These
games require no downloads or installations, making them perfect for quick bursts of fun or
extended gaming sessions. With constant innovation and new titles emerging all the time, the
world of web games provides a never-ending source of enjoyment for players around the globe.
Their ease of access and diverse selection make them a perfect choice for casual gamers or those
looking for a quick burst of fun.

This project report details the development of a web-based gaming portal called "Web Games
Portal". This portal is a web development project that aims to provide users with a convenient
and accessible platform to play a variety of mini web games directly through their web browsers.
This project showcases my front-end as well as back-end web-development skills.
Table of Contents

Sr. No Particular Page No. Remarks


1 Project Introduction 1
1.1 Company Profile 2
1.2 Project Introduction 3
1.3 Project Objectives 3
1.4 Key Features 3
1.5 Project Modules 5
1.6 Problems in Existing System 5
1.7 Project Requirements 7
1.8 Software 8

2 System Analysis 10
2.1 Objectives 11
2.2 Feasibility Study 12
2.3 Requirement Gathering 14
2.4 System Architecture 17
2.5 Risk Analysis 19
2.6 SWOT Analysis 21

3 System Design 23
3.1 Introduction 24
3.2 Data Modelling 26
3.3 Process Modelling 30
3.4 Use Case Analysis 31
3.5 User Interface Design 33
Sr. No Particular Page No. Remarks
4 Coding 36
4.1 Technologies and Languages 37
4.2 MVC Architecture 38
4.3 Project Structure 39
4.4 Coding 42

5 Testing 72

6 Result 75

7 Conclusion 87

9 Bibliography 89
Chapter – 1
Project Introduction

1
1.1 | Company Profile
Adress: Plot No. - 218, Industrial Area, Industrial Area Mohali Phase 8B, Sahibzada
Ajit Singh Nagar, Punjab 160062

098153 58800

info@NOVEM CONTROLS.com

www.novemcontrols.com

Novem Controls (India) Private Limited is a professional software and web


development company dedicated to empowering business profiles with a range of
creative, accurate, credible and cost-effective web related solutions and services.

Services Provided
Web Development: Web development is the process of building and maintaining
websites and web applications. It involves a combination of programming, design, and
content management to create functional and interactive websites that can be accessed
through web browsers.

Web designing: Web designing is the process of creating and designing the visual
elements and user interfaces of websites. It involves the combination of various
disciplines, including graphic design, user experience (UX) design, and user interface
(UI) design, to create aesthetically appealing and functional websites that cater to the
needs of the target audience.

App Development: Mobile apps are designed to run on specific operating systems, like
Android or iOS, and offer various functionalities to meet user needs. App development
involves several stages, including planning, design, development, testing, and
deployment, to ensure a successful and user friendly application.

Digital Marketing: It encompasses a wide range of online marketing tactics and


strategies to reach potential customers, build brand awareness, drive website traffic,
generate leads, and ultimately, achieve business goals.

2
1.2 | Project Introduction
Web games have become a popular pastime, offering a vast universe of entertainment,
accessible directly through your web browser. From casual puzzle games to action-
packed adventures and even multiplayer experiences, there's a web game to suit almost
any taste and skill level. These games require no downloads or installations, making them
perfect for quick bursts of fun or extended gaming sessions. With constant innovation and
new titles emerging all the time, the world of web games provides a never-ending source
of enjoyment for players around the globe. Their ease of access and diverse selection
make them a perfect choice for casual gamers or those looking for a quick burst of fun.

This project report details the development of a web-based gaming portal called "Web
Games Portal". This portal is a web development project that aims to provide users with a
convenient and accessible platform to play a variety of mini web games directly through
their web browsers. This project showcases my front-end as well as back-end web-
development skills.

1.3 | Project Objectives


Develop a user-friendly website with a clean and intuitive interface for easy navigation
and game discovery.
Ensure smooth gameplay experience within the web browser, eliminating the need for
downloads or installations.
Implement features to enhance user engagement, such as leader-boards, achievements,
and user accounts (optional).
Maintain a responsive design for optimal viewing across different devices (desktop,
mobile, tablets).

1.4 | Features

➢ Home Page :
Design: Visually appealing layout displaying the carousals for specific game.
Homepage before User Login: Login page becomes homepage, so that only authorized
user can play games.

3
Homepage after User Login: Homepage provides a slider having hyper-images linked to
specific game page and also shows score boards specifying top–five user names and their
highest scores.
Navigation: On header, homepage has navigation links for Signup and Login page.

➢ User Signup Page :


Design: Visually appealing layout for user signup process with input fields and buttons.
Open-Authentication: Provides third-party signup feature (e.g., signup using Facebook,
Google and, so on)
Navigation On header, navigation links for Login and Signup page.

➢ User Login Page :


Design: Visually appealing layout for user login process with input fields and buttons.
Open-Authentication: Provides third-party login feature (e.g., login using Facebook,
Google and, so on)
Navigation On header, navigation links for Signup and Login page.

➢ Word Guess Game Page :


Design: Visually appealing layout having several buttons and input boxes designed for
particular operations.

➢ Tile Matching Game Page :


Design: Visually appealing layout having different modes to play (e.g., 3X4, 4X4 and so
on)

➢ User Accounts :
Registration & Login: Allow users to create accounts for personalized experiences.
Order History: Access to previous orders, tracking information, and status updates.
High Score Tracking: Implement leaderboards to display user high scores and foster
friendly competition.

4
1.5 | Project Modules

Project Initiation and Planning : Define the project’s scope, goals, and
deliverables. Identify key stakeholders, gather requirements, and create a detailed project
plan with timelines and budget estimates to ensure alignment and efficient resource
allocation.

Design and User Experience (UX) : Develop wireframes and high-fidelity


mockups for essential pages such as the homepage and product pages. Create interactive
prototypes to visualize user interactions and finalize the design based on feedback to
ensure a seamless and engaging user experience.

Development : Build the website by implementing front-end and back-end


functionalities. Set up the development environment, create the website’s structure,
integrate e-commerce features, and ensure the site is responsive and compatible across
various devices and browsers.

Integration and Testing : Integrate third-party services like payment gateways and
shipping solutions. Conduct thorough testing, including unit, integration, and user
acceptance testing, to ensure all components work harmoniously and address any bugs or
issues identified during the process.

1.6 | Problems in Existing System

➢ User Experience (UX) Issues : Users may struggle to find or navigate to


separate game pages if the menu and categories are not well-organized.
If the site does not function well on mobile devices or different screen sizes, it can deter
users.
Solutions : Simplify and structure the navigation menu clearly.
Ensure the design is responsive and test across various devices.

5
➢ Client-side Scripting :
Client-side scripts on the user's browser can introduce errors that affect gameplay or user
experience.
Preventing users from modifying client-side code to cheat in games can be difficult.
Solutions : Implement robust error handling on the client-side and consider server-side
validation of game actions.

➢ Game Logic & Multiplayer functionality :


Implementing complex game logic on the server, especially for real-time multiplayer
games, can be challenging.
Solutions : Break down complex game logic into manageable components and utilize
libraries for synchronization if needed.

➢ Performance Issues :
Technical problems or server issues can make the site inaccessible.
The website may struggle to handle high traffic volumes or peak shopping times.
Solutions : Monitor server performance and use reliable hosting services.
Plan for scalability with cloud solutions or load balancing.

➢ SEO and Visibility Challenges : The site may not rank well in search engines,
affecting traffic and sales.
Pages may not be optimized for relevant keywords or user search intent.

Solutions : Implement SEO best practices, like keyword optimization and meta tags.

Regularly update content and ensure that the site is crawl-able by search engines.

➢ Legal and Compliance Issues : Ensure you have the rights to use any game
concepts, artwork, or music within your portal.
Create a clear and concise TOS outlining user expectation and your rights as the
application owner.
Solutions : Consult with a legal professional familiar with technology and intellectual
property law to ensure your application complies with relevant regulations.
Regularly review and update your legal policies (TOS, Privacy Policy) to reflect any
changes in your application or applicable laws.

6
1.7 | Project Requirements

User Registration :
Users should be able to register for an account using an email address or social media
login. Secure login and logout functionality with options for password recovery and
account management.

Platform :
The application must be built using ASP.NET Core 6.0 or later. The front end can utilize
modern HTML5, CSS3, JavaScript (ES6 or later) and jQuery. The backend can utilize C#
and SQL.

Database :
A relational database like SQL Server should be used to store user data, game meta-data,
and other related information. Implement Entity Framework Core for ORM (Object-
Relational Mapping).

Game Library:
The portal must provide a searchable and filterable catalogue of games. Each game must
have a detailed page with descriptions, screenshots, ratings, and reviews. Users should be
able to play games directly on the portal or be redirected to external sites.

Leader-boards and Achievements :


Global and game-specific leader-boards must be implemented. Users should earn
achievements and badges based on their activities and milestones.

Responsive Design :
The portal must be responsive and accessible on various devices (desktop, tablet, mobile).
The UI/UX design should be intuitive and adaptable to different screen sizes.

Security :
Specify security measures to be implemented (e.g., user authentication, input validation,
data encryption). Identity Framework should be implemented for user authorization and
authentication.

Search Engine Optimization (SEO):


The portal should have SEO-friendly URLs and proper meta-tags for better search engine
visibility.

7
1.8 | Software

Visual Studio 2022 is the latest major release of Microsoft’s integrated development
environment (IDE), designed to enhance the productivity of developers working on a
wide range of applications, including web, mobile, and desktop projects. It offers a
powerful and comprehensive platform for building applications across various platforms
and languages. Here’s an overview of its key features and benefits:

➢ Enhanced Performance and Scalability:


64-bit Architecture: Visual Studio 2022 is the first version to support 64-bit architecture,
which allows it to handle larger solutions and projects more efficiently, reducing the
likelihood of performance issues and crashes.
Faster Load Times: Improved start-up and solution load times make it quicker to get into
your development workflow.

➢ Advanced Debugging and Diagnostics:


Enhanced Debugging Tools: Includes powerful debugging features such as enhanced
breakpoints, improved watch windows, and more intuitive debugging experiences,
enabling developers to identify and fix issues faster.
Live Share: Collaboration tools like Live Share allow developers to share their code and
debugging sessions in real time with team members, facilitating better communication
and problem-solving.

➢ Intelligent Code Assistance:


AI-Powered Code Suggestions: Leveraging AI, Visual Studio 2022 provides smart code
completions and recommendations, improving coding efficiency and reducing errors.
Code Refactoring: Advanced refactoring tools help in improving code quality and **10.

➢ Modern Development Features:


Support for Latest Technologies: Includes comprehensive support for the latest .NET
versions, ASP.NET, and other modern frameworks and libraries.
Enhanced Web Development Tools: Updated tools for web development, including
improved support for JavaScript, Typescript, and web frameworks like Angular and
React.

8
➢ User Experience and Interface:
Modern UI: A refreshed and customizable user interface that offers a more streamlined
and intuitive development experience.
Improved Accessibility: Enhanced accessibility features ensure a more inclusive
development environment.

➢ Version Control and Collaboration:


Integrated Git Support: Built-in Git support for version control, with a user-friendly
interface for managing repositories, branches, and commits.
Team Collaboration: Integration with Azure DevOps and other collaboration tools
streamlines team workflows and project management.

➢ Comprehensive Testing Tools:


Unit Testing Frameworks: Support for various unit testing frameworks, including NUnit,
xUnit, and MSTest, to ensure code reliability and quality.
Test Explorer: A unified Test Explorer that provides insights into test results and code
coverage, helping to maintain high code quality.

➢ Extensibility and Customization:


Marketplace Extensions: Access to a wide range of extensions and plugins from the
Visual Studio Marketplace to enhance functionality and tailor the IDE to specific needs.
Custom Workloads: Flexible installation options allowing developers to choose and
install only the components they need for their projects.

➢ Security and Compliance:


Enhanced Security Features: Improved security features to safeguard code and
development environments from vulnerabilities and threats.
Compliance Tools: Tools to help ensure compliance with coding standards and best
practices

9
Chapter – 2
System Analysis

10
2 | Introduction
System Analysis is a critical phase in the development of information systems, software
applications, or any complex system. It involves a systematic study of the current
system's functionality, processes, and requirements to identify areas for improvement or
to design a new system that meets the specific needs of the users and stakeholders. The
primary goal of system analysis is to understand the problems, gather user requirements,
and define the scope of the project before proceeding with system design and
development. System analysis is a crucial step in the System Development Life Cycle
(SDLC), as it lays the foundation for successful system development, ensuring that the
final product aligns with the needs of the users and the organization's objectives.
Effective system analysis saves time, resources, and effort by addressing potential issues
early in the development process and facilitating smooth project implementation.

The "Web Games Portal" is a web-based platform that provides users with access to a
wide range of online games (currently two). Users can browse, search, and play games by
just using a browser and a valid Internet connection. The system also allows game
developers to upload and manage their games on the platform. The goal is to create a
user-friendly platform where users can play a variety of fun and engaging games directly
within their web browsers.

2.1 | Objectives
The objectives of the system analysis for the ASP.NET Core application "Web
Games Portal" are critical for ensuring that the system is designed to meet the needs of
its users, stakeholders, and business goals. These objectives guide the analysis process,
helping to define the system's requirements, identify potential challenges, and design
solutions that are efficient, scalable, and secure.

➢ Define Requirements Clearly :


Functional Requirements: Clearly outline the functionalities the portal should offer,
including game management, user management (optional), gameplay features, and
optional features like leader-boards and social integration.
Non-Functional Requirements: Specify performance expectations, scalability
requirements, security measures, accessibility guidelines, and user interface (UI) design
principles.

11
➢ Identify Stakeholders and Needs :
Primary Stakeholders: Developers, Users.
Secondary Stakeholders: System Administrators and, understand the specific needs and
expectations of each stakeholder group to ensure the portal caters to all involved parties.

➢ Create a Blueprint for Development:


System Architecture: Define the overall architecture using the Model-View-Controller
(MVC) paradigm, separating concerns for efficient development and maintenance.
Data Flow Diagrams (DFDs) : Develop DFDs to illustrate the flow of data within the
system, including user interactions, game logic processing, and data storage (if
applicable).
Technology Stack: Specify the technologies to be used for backend development
(ASP.NET Core, C#), frontend development (HTML, CSS, JavaScript with optional
frameworks), and database management (Microsoft SQL Server).

➢ Mitigate Risks :
Identify potential risks: Security vulnerabilities, performance bottlenecks, game bugs.
Develop mitigation strategies: Secure coding practices, performance optimization
techniques, testing strategies, and bug tracking systems.

➢ Enhance User Experience (UX) :


Focus on creating an intuitive and user-friendly interface that caters to diverse devices
(desktops, tablets, mobiles).
Ensure clear navigation, easy-to-understand controls, and responsive design for optimal
user experience.

➢ Facilitate Scalability and Maintainability :


Choose technologies and design patterns that allow the system to scale efficiently as the
user base grows.
Implement modular code structure and proper documentation for easier maintenance and
future updates.

2.2 | Feasibility Study


This feasibility study assesses the viability of developing a “Web Games Portal” web-
application using ASP.NET Core. It will analyze the project's technical, economic, and
operational feasibility to determine its potential for success. The goal of this study is to
determine whether the project is feasible and to identify potential risks or obstacles.

12
➢ Technical Feasibility :
• Technology Stack :
• Platform : ASP.NET 6 (Core)
• IDLE : Visual Studio 2022
• Front-end : HTML5, CSS3, JavaScript, jQuery
• Back-end : C#
• Database : Microsoft SQL Server, Entity Framework (Object-Relation Mapping)
• Security Tools and Techniques : Identity Framework, OAuth
• Architecture (Design Pattern) : Model-View-Controller(MVC)

• Skills Required :
• Proficiency in frontend and backend technologies
• Knowledge of database management
• Knowledge of RESTful APIs
• Knowledge of open-authentication, Entity and Identity framework
• Experience with cloud hosting and deployment

• Infrastructure :
• Scalable cloud infrastructure
• Secure and reliable payment processing
• Content Delivery Network (CDN) for fast content delivery

➢ Economic Feasibility :
• Development Cost : Estimate the costs for development tools, libraries, server
infrastructure (if not using cloud services), and potential licensing fees for third-party
game assets (if applicable).
• Maintenance Cost : Consider ongoing costs for maintaining the portal, fixing bugs,
adding new features, and keeping up with security updates.
• Budget Alignment : Ensure the project fits within the allocated budget and that
potential benefits outweigh the expenses.

➢ Operational Feasibility :
• Deployment and Hosting : Choose a reliable hosting platform or cloud service that
can handle user traffic and scale effectively.
• Project Management : Develop a clear project plan with timelines, milestones,
resource allocation, and risk management strategies.
• Maintenance and Support : Establish processes for on-going maintenance, bug fixes,
security updates, and potential future feature additions.
• End Users (Players): The portal needs to be user-friendly, providing easy access to a
wide range of games, community features, and personalized experiences. Regular
updates and new content will keep users engaged.

13
➢ Legal Feasibility :
• Compliance with GDPR: The portal must comply with data protection regulations,
such as the General Data Protection Regulation (GDPR) in the EU, which includes
obtaining user consent, providing data access rights, and ensuring data security.
• COPPA Compliance: If the portal targets or is accessible to children, it must comply
with the Children's Online Privacy Protection Act (COPPA) in the United States,
which governs the collection and use of personal information from children under 13.
• Game Content : Ensuring that all games uploaded to the portal are legally owned or
licensed by the developers. The portal should have clear terms and conditions for
content submission.
• Maintenance and Support : Establish processes for on-going maintenance, bug fixes,
security updates, and potential future feature additions.

2.3 | Requirement Gathering


Requirement gathering is a crucial step in the system analysis phase of any software
development project. For an ASP.NET Core Web Application "Web Games Portal," this
process involves understanding the needs and expectations of stakeholders, defining the
scope of the project, identifying and documenting both the functional and non-functional
requirements that will guide the development process.

This process involves understanding stakeholder needs and translating them into
actionable specifications for the development team.

2.3.1 | Requirement Gathering Techniques


Objective: Use various techniques to gather detailed requirements from all stakeholders.

➢ Techniques :
• Interviews: Conduct one-on-one interviews with key stakeholders to understand their
needs and expectations.
• Surveys/Questionnaires: Distribute surveys to potential customers and other
stakeholders to gather quantitative data.
• Workshops: Organize workshops with stakeholders to brainstorm and prioritize
requirements.

14
• Observation: Observe current processes and systems to identify areas for
improvement.
• Document Analysis: Review existing documentation (e.g., business plans, competitor
websites) to gather additional insights.

2.3.2 | User Requirements


• Primary Users: Gamers who will use the portal to play games.
• Game Developers: Contributors who will upload and manage their games on the
portal.
• Target Audience: Identify the primary user base for the portal (e.g., casual gamers,
families, and children). Understanding their demographics, gaming preferences
(genres, difficulty levels), and technical expertise (desktop vs. mobile users) will
guide design decisions.
• User Interface (UI) Requirements: Gather user input on their expectations for the UI.
Consider aspects like:
• Layout and navigation: User-friendly menus, clear organization of games.
• Visual Design: Appealing aesthetics that cater to the target audience.
• Responsiveness: Seamless adaptation to different screen sizes and devices.
• Usability Testing: Conduct usability testing with real users to identify any issues with
the UI and ensure an intuitive experience.

2.3.3 | Functional Requirements


➢ User Registration and Authentication :
• Users must be able to register with the portal using email, social media accounts, or
guest login.
• Implement two-factor authentication for enhanced security.

➢ User Profiles :
• Allow users to create and manage their profiles, including avatars, bio, game
preferences, and gaming history.

➢ Game Management :
• Game developers should have the ability to upload, update, and manage their games.
• Provide tools for managing game versions, screenshots, descriptions, and game
categories.

15
➢ Game Play Interface:
• A responsive, interactive interface where users can browse, search, and play games
directly on the portal.
• Support for various game types (HTML5, Flash, etc.) and integration with third-party
gaming APIs.

➢ Leader-boards and Achievements:


• Implement leaderboards for individual games as well as global rankings.
• Users should be able to earn achievements and badges for various milestones within
the games.

➢ Content Moderation :
• Implement tools for content moderation to filter inappropriate content, manage user
reports, and enforce community guidelines.

➢ Gameplay Features :
• Detail user interaction methods for different game types (touchscreens, keyboards,
mice).
• Specify difficulty level options and how they impact the gameplay experience.
• Determine in-game feedback mechanisms (score displays, health bars, sound effects).

2.3.4 | Non-Functional Requirements

➢ Performance :
• The portal should be able to handle a large number of concurrent users with minimal
latency.
• Ensure fast load times and smooth gameplay experience, even under peak load
conditions.

➢ Scalability :
• The system should be scalable to accommodate future growth in user base, game
library, and feature set.
• Plan for horizontal scaling by using cloud services like Azure for hosting and content
delivery.

➢ Security :
• Implement robust security measures to protect user data, prevent unauthorized access,
and ensure safe transactions.

16
• Regular security audits and compliance with industry standards (e.g., GDPR, PCI-
DSS) should be part of the project’s ongoing maintenance.

➢ Usability :
• The portal should be user-friendly, with intuitive navigation, clear calls to action, and
a responsive design that works well across all devices.
• Conduct usability testing with real users to ensure the portal meets their needs.

➢ Availability :
• Ensure high availability with minimal downtime, possibly using load balancers,
failover mechanisms, and redundant servers.
• Implement a disaster recovery plan to quickly restore services in case of a system
failure.

➢ Compatibility :
• The portal should be compatible with major web browsers (Chrome, Firefox, Edge,
Safari) and mobile devices.
• Ensure that games are playable across different screen sizes and operating systems.

2.4 | System Architecture


The System Architecture for an ASP.NET Core Web Application “Web Games Portal”
will utilize a layered architecture with clear separation of concerns to enhance
maintainability, scalability, testing and security.

It includes the overall design and structure, the technologies and platforms used, and the
interaction between different modules and services.

This architecture will cover key aspects such as the presentation layer, business logic
layer, data access layer, and external integrations.

2.3.1 | Layers of the Architecture

➢ Presentation Layer (Frontend)


• Purpose: The presentation layer is responsible for handling the user interface and the
interaction between the user and the system.

17
❖ Technologies :
❖ ASP.NET Core MVC : For applications that may require a more complex UI
structure with controllers handling requests.
❖ ASP.NET Core Razor Pages : For generating dynamic, server-rendered web pages
with embedded C# code.
❖ C# : For server-side logic and interactivity.
❖ JavaScript : For client-side logic and interactivity.
❖ CSS/Bootstrap/HTML5 : For styling and structuring the user interface.
❖ Features :
❖ Responsive Design: Ensures the portal is accessible on various devices, including
desktops, tablets, and smartphones.
❖ Dynamic Content Rendering: Using Razor syntax for embedding server-side logic
into web pages.
❖ User Interaction: Handling user inputs, form submissions, and interaction with
dynamic elements (e.g., game play, leaderboards).
❖ Routing: Implementing URL routing to map user requests to specific pages or actions
in the portal.

➢ Business Logic Layer (Backend)


❖ Purpose: The business logic layer contains the core functionality of the application,
processing data, applying business rules, and making decisions.
❖ Technologies :
❖ ASP.NET Core: For building the backend API and handling HTTP requests.
❖ Dependency Injection (DI): For managing dependencies and promoting loose
coupling.
❖ C# Language: For writing the core logic, service classes, and business rules.
❖ Components :
❖ Service Layer: Contains services that encapsulate business logic, such as user
management, game processing, and leaderboards.
❖ Domain Models: Define the core entities like Users, Games, Scores, Achievements,
etc.
❖ Validation: Implements input validation and business rules enforcement.

➢ Data Access Layer


❖ Purpose: The data access layer is responsible for interacting with the database or any
other data storage system.
❖ Technologies :
❖ Entity Framework Core : For object-relational mapping (ORM) and managing data
operations.

18
❖ SQL Server : As the primary relational database for storing persistent data.
❖ Components :
❖ Data Models : Define the schema for entities in the database, such as tables for Users,
Games, Scores, etc.
❖ Data Migration : Using EF-Core migrations to manage database schema changes and
updates.

➢ Integration Layer
❖ Purpose : Handles communication with external systems, services, and APIs.
❖ Technologies :
❖ RESTful Web APIs : For integrating with third-party services like payment
gateways, social media platforms, and game APIs.
❖ Components :
❖ External Service Integrations : Handling APIs for user authentication (OAuth).

➢ Security Layer
❖ Purpose : Ensures that the system is secure, protecting data and functionality from
unauthorized access and breaches.
❖ Technologies :
❖ ASP.NET Core Identity : For managing authentication, authorization, and user roles.
❖ OAuth : For integrating third-party
❖ Components :
❖ Authentication/Authorization : Identity framework is used for ensuring that only
authorized users can access certain features.

2.5 | Risk Analysis


A comprehensive risk analysis is crucial for identifying potential challenges that could
hinder the development and success of your ASP.NET Core “Web Games Portal”. This
analysis helps in devising strategies to mitigate or manage these risks.

Here's a breakdown of key risks and mitigation strategies:

➢ Security Risks :
❖ Risk : Security vulnerabilities in the application or database could lead to data
breaches, unauthorized access, or malicious attacks.

19
❖ Mitigation:
❖ Implement secure user authentication and authorization with strong password
hashing.
❖ Conduct regular security audits and penetration testing to identify and address
vulnerabilities.
❖ Stay updated with the latest security patches for ASP.NET Core and other
dependencies.

➢ Performance Bottlenecks :
❖ Risk : The portal might experience slow loading times or lag during gameplay if not
optimized for performance.
❖ Mitigation:
❖ Validate all user input to prevent SQL injection and script attacks.
❖ Encrypt sensitive data (user passwords, game data) at rest and in transit.
❖ Stay updated with the latest security patches for ASP.NET Core and other
dependencies.

➢ Game Bugs and Functionality Issues :


❖ Risk : Bugs in game logic or unexpected user interactions might lead to crashes or
unintended gameplay behavior.
❖ Mitigation:
❖ Implement thorough unit testing for individual game components
❖ Establish a bug tracking system to log, prioritize, and fix bugs efficiently.
❖ Implement a rollback mechanism to revert to a previous functional state if critical
bugs are discovered after deployment.

➢ User Engagement and Retention :


❖ Risk : Users might lose interest in the portal if the game selection is limited, lacks
innovation, or fails to cater to diverse preferences.
❖ Mitigation:
❖ Offer a variety of engaging games across different genres.
❖ Regularly introduce new games or content updates to maintain user interest.
❖ Track user behavior and preferences to inform future game development and content
acquisition decisions.

➢ Project Management Challenges :


❖ Risk : Poor project management can lead to delays, budget overruns, and scope creep.
❖ Mitigation:
❖ Develop a clear project plan with well-defined milestones, timelines, and resource
allocation.

20
❖ Conduct regular project meetings to track progress, identify risks, and make
adjustments as needed.
❖ Utilize project management tools to facilitate communication, task management, and
version control.

➢ User Experience (UX) Risks :


❖ Risk : The portal’s user interface may be difficult to navigate, leading to a poor user
experience.
❖ Mitigation:
❖ Conduct usability testing with real users during development.
❖ Use iterative design processes to refine the UI based on feedback.

➢ Performance and Load Times :


❖ Risk : Slow load times or lag during gameplay could frustrate users and lead to
abandonment.
❖ Mitigation:
❖ Optimize server and client-side performance.
❖ Use CDNs and caching to improve load times.

2.6 | SWOT Analysis


A SWOT analysis provides a comprehensive evaluation of the Strengths, Weaknesses,
Opportunities, and Threats associated with developing a Web Games Portal using
ASP.NET Core.

For this application, this analysis will help in understanding the internal and external
factors that could impact the project's success.

➢ Strengths :
❖ Technology Stack : ASP.NET Core offers a robust and mature framework for
building web applications.
❖ Development Efficiency : Utilizing C# and familiar frontend technologies like
HTML, CSS, and JavaScript can streamline development.
❖ Scalability : The chosen architecture allows for horizontal scaling to accommodate
growing user traffic.

21
❖ Customization : The architecture allows for modular development, enabling
customization and future feature additions.
❖ Security Focus : ASP.NET Core provides various security features, and best practices
can further enhance security.

➢ Weaknesses :
❖ Competition : The web games market is saturated with established competitors
❖ Technical Expertise: Development requires familiarity with ASP.NET Core, game
development practices, and chosen frontend frameworks.
❖ Project Management : Effective project management skills are crucial to avoid scope
creep, delays, and budget overruns.

➢ Opportunities :
❖ Monetization : Explore monetization strategies like in-app purchases (optional) or
advertising.
❖ Mobile Compatibility : A responsive design ensures accessibility on mobile devices,
expanding the user base.
❖ Emerging Technologies : Leverage new technologies like cloud gaming or integration
with other platforms.

➢ Threats :
❖ Security Vulnerabilities : Keeping up with security updates and addressing
vulnerabilities is crucial.
❖ Technology Advancements : Rapid advancements in game development tools and
technologies might necessitate upgrades.
❖ Changing User Preferences : User interest in specific game genres or trends may
evolve over time.
❖ Competition Strategies : Aggressive marketing or innovative features from
established competitors could threaten user acquisition.
❖ Project Management Risks : Poor planning, communication breakdowns, or
underestimating development time can lead to project failures.

22
Chapter – 3
System Design

23
3.1 | Introduction
This detailed system design outlines the architectural components, functionalities, and
data flow within a web-based gaming portal called "Web Games Portal". This portal is
an ASP.NET Core Web Application project that aims to provide users with a convenient
and accessible platform to play a variety of mini web games directly through their web
browsers. This project showcases my front-end as well as back-end web-development
skills.

This system design involves outlining the architecture, components, data flow, and
technologies that will be used to build the application. This design will guide the
development process and ensure that all aspects of the system are well-structured and
optimized for performance, scalability, and maintainability.

➢ Technology Stack:
❖ Front-End (Client-Side) :
❖ HTML5/CSS3/JavaScript : For building responsive user interfaces.
❖ Bootstrap : For responsive design and UI components.
❖ Razor Pages : For server-side rendering of UI components.

❖ Back-End (Server-Side) :
❖ ASP.NET Core MVC : For handling HTTP requests, routing, and application logic.
❖ C# : For server-side business logic development.
❖ Entity Framework Core : For database access and ORM (Object-Relational Mapping).
❖ Identity Framework Core : For authentication and authorization.

❖ Database :
❖ Microsoft SQL Server : For relational database management.
❖ Identity Framework Core : For authentication and authorization.

❖ APIs and Integrations :


❖ RESTful APIs : For communication between front-end and back-end services.

➢ User Interaction Flow :


❖ User visits the portal: The user accesses the web application through their web
browser.
❖ Browsing games: The Presentation Layer displays a list of games categorized by
genre, difficulty, or other criteria.
❖ Game selection: The user selects a game they want to play.

24
❖ Game loading: The Presentation Layer requests the game data from the Business
Logic Layer.Depending on the game complexity, this might involve retrieving game
assets from a storage location or generating dynamic content.
❖ Game play: The user interacts with the game through the user interface elements
provided by the Presentation Layer.
❖ Game progress : User progress (scores, achievements) might be saved in the Data
Access Layer.

➢ Data Flow :
❖ User interactions and requests : The user interacts with the web application's
interface, sending requests to the Presentation Layer.
❖ Data retrieval : The Presentation Layer retrieves necessary data from the Business
Logic Layer, which may obtain data from the Data Access Layer for saved game data,
user data or External APIs for specific functionalities (e.g., user authentication with a
third-party service).
❖ Data updates: The Business Logic Layer may update the Data Access Layer with user
progress (optional), game state changes, or user account information.

➢ System Components :
❖ User Management Module :
❖ User Registration and Login
❖ Profile Management
❖ Authentication and Authorization (using ASP.NET Core Identity)
❖ Social Media Integration (OAuth)

• Game Management Module :


❖ Game Carousal : Links on cards of images for available games.
❖ Leaderboards : Tracking user progress and scores.

➢ Security Considerations:
❖ Secure Login and Authentication : Implement secure user login mechanisms (e.g.,
password hashing).
❖ Input Validation : Sanitize user input to prevent SQL injection and other
vulnerabilities.
❖ HTTPS : Use secure communication protocols to encrypt data transmission.

25
3.2 | Data Modelling
Data modeling is a critical aspect of system design, as it defines how data is stored,
accessed, and managed within the application. The data model defines the structure and
organization of data within the project. The goal is to illustrate the types of data used and
stored within the system, the relationships among these data types, the ways the data can
be grouped and organized, and its formats and attributes For the "Web Games Portal," the
data model will be structured to accommodate various entities such as users, games,
scores obtained and so on.

The following is a detailed data modeling approach for the ASP.NET Core Web
Application "Web Games Portal" :-

➢ Entities and Attributes :


❖ Entity : AppUser
❖ Attributes :
• Id (Primary Key, GUID) : Unique identifier for each user.
• UserName (String, Unique, Required) : User's unique username.
• Email (String, Unique, Required) : User's email address.
• PasswordHash (String, Required) : Hashed password for authentication.

❖ Entity : WordGuessGameHeader
❖ Attributes :
• Id (Primary Key, GUID) : Unique identifier for each game entity.
• AppUserId (String) : Unique identifier for storing AppUser relation’s entity Id.
• AppUser (AppUser, Foreign Key) : Foreign key attribute for setting relationship
between two relations.

❖ Entity : WordGuessGame
❖ Attributes :
• Id (Primary Key, GUID) : Unique identifier for each game entity.
• WordGuessGameHeaderId (Integer) : Unique identifier for storing
WordGuessGameHeader relation’s entity Id.
• WordGuessGameHeader (WordGuessGameHeader, Foreign Key) : Foreign key
attribute for setting relationship between two relations.
• ScoreObtained (Integer) : Attribute to store score obtained.
• TimeTaken (Integer) : Attribute to store time taken for completing task.

26
❖ Entity : TileMatchingGameHeader
❖ Attributes :
• Id (Primary Key, GUID) : Unique identifier for each game entity.
• AppUserId (String) : Unique identifier for storing AppUser relation’s entity Id.
• WordGuessGameHeader : (WordGuessGameHeaderId, Foreign Key) : Foreign key
attribute for setting relationship between two relations.

❖ Entity : TileMatchingGame
❖ Attributes :
• Id (Primary Key, GUID) : Unique identifier for each game entity.
• TileMatchingGameHeaderId (Integer) : Unique identifier for storing
TileMatchingGameHeader relation’s entity Id.
• TileMatchingGameHeader (WordGuessGameHeader, Foreign Key) : Foreign key
attribute for setting relationship between two relations.
• ScoreObtained (Integer) : Attribute to store score obtained.
• TimeTaken (Integer) : Attribute to store time taken for completing task.

➢ Relationships :
• One-to-Many with game session : A game can have multiple sessions associated with
different users.
• One-to-Many with scoreboard : A game can have multiple leaderboards tracking
player scores.
• One-to-Many with achievement : A game can have multiple achievements.
• One-to-Many : One game can have multiple game sessions

➢ ER Diagram (Entity-Relationship Diagram) :

The Entity-Relationship (ER) diagram visually represents the relationships between


entities.

Creating a detailed Entity-Relationship Diagram (ERD) for the ASP.NET Core Web
Application "Web Games Portal" involves representing all the entities, their attributes,
and the relationships between them visually.

27
Start

User

No
No
Signup Login

Yes Yes

Home Page

Word Guess Tile Matching


Game Game

Select Game
Home Page

Exit

Flow Chart

28
UserName PasswordHash

AspNetUsers
Email
Id

AppUserId (FK) AppUserId (FK)

Has

wggheader

tmgheader
Id

Id

Has Has

wggheaderId (FK) Id

tmgheaderId (FK)

Id

wgg

tmg

ScoreObtained TimeTaken

ScoreObtained

TimeTaken

ER Diagram
29
3.3 | Process Modelling
Process modeling is essential in the system design phase as it outlines how the system's
components will interact to accomplish tasks and fulfill the application's objectives.
Process modeling visually depicts the workflows within your ASP.NET Core Web
Games Portal, providing a clear understanding of user interactions, system functionalities,
and data flow. For the "Web Games Portal," process modeling helps visualize the
workflow and the sequence of actions that occur during the interaction between users and
the system.

Here's a detailed process modeling approach for the ASP.NET Core Web Application
"Web Games Portal" :-

➢ User Registration :
• Trigger : User visits the portal and chooses to register for an account.
• Steps :
• User enters username, email (optional), and password.
• System validates user input (e.g., email format, password strength).
• System stores user data securely (hashed password).
• Output : Registered user account.

➢ User Login :
• Trigger : Existing user visits the portal and attempts to log in.
• Steps :
• User enters login credentials (username/email and password).
• Option 1 : Username/Password Login
• System retrieves user data from the database based on username.
• System compares entered password with hashed password (secure comparison).
• Option 2 : Social Login using Open-Authentication
• User logs in using a social media provider (e.g., Google, Facebook).
• System validates the social login token received from the provider.
• System retrieves or creates a user account based on the social login information.
• Output : User enters the portal homepage.

➢ Browse Games :
• Trigger : User visits the games list page.
• Steps :
• System retrieves game data from the database.
• System filters or sorts games based on user selections (genre, difficulty, etc.).

30
• System displays a list of games with details (title, description, image).
• Output : User sees a list of available games.

➢ Play Games :
• Trigger : User selects a game from the list.
• Steps :
• System retrieves game data and assets from storage.
• System initializes the game environment based on game logic.
• System presents the game interface to the user.
• User interacts with the game through the user interface (controls, input).
• Output : User plays the game and interacts with its mechanics.

➢ User Profile Management :


• Trigger : Registered user visits their profile page.
• Steps :
• System retrieves user data from the database.
• System displays user profile information (username, achievements, game progress).
• User can edit their profile information.
• Output: User can view and manage their profile details.

3.3 | Use Case Analysis


A detailed Use Case Analysis for the ASP.NET Core Web Application "Web Games
Portal" involves identifying and describing the various ways in which users interact with
the system. This analysis helps in understanding the system’s functionality from the
user's perspective and serves as a foundation for further development. A use case analysis
identifies and details the interactions between actors (users and external systems) and the
system itself.

Here's a breakdown of key use cases for your ASP.NET Core Web Games Portal:

➢ Use Case : User Registration


• Actors : User
• Description : A user creates a new account on the web portal.
• Pre-conditions : User is not currently logged in.
• Steps :
• System retrieves user data from the database.
• System displays user profile information (username, achievements, game progress).

31
• User can edit their profile information.
• Output: User can view and manage their profile details.

➢ Use Case : User Login


• Actors : User
• Description : A registered user logs in to the web portal.
• Pre-conditions : User account exists.
• Basic Flow (Username/Password Login) :
• User enters username and password.
• System retrieves user data based on username.
• System compares entered password with hashed password (secure comparison).
• System grants access if credentials match.
• Alternative Flows :
• Social login: User logs in using a social media provider (e.g., Google, Facebook).
System validates the social login token and retrieves or creates a user account based
on the information received.
• Login failure: System provides error messages for invalid username or password.
• User can edit their profile information.

➢ Use Case : Browse Games


• Actors : User
• Description : User browses the available games on the portal.
• Pre-conditions : User is logged in.
• Basic Flow :
• System retrieves game data from the database.
• System filters or sorts games based on user selections (genre, difficulty, etc.).
• System displays a list of games with details (title, description, image).
• Alternative Flows :
• User can search for games by name (optional).
• The portal might display featured or popular games prominently.

➢ Use Case : Play Game


• Actors : User
• Description : User selects and plays a game on the portal.
• Pre-conditions : User has browsed games and selected one.
• Basic Flow :
• System retrieves game data and assets from storage.
• System initializes the game environment based on game logic.
• System presents the game interface to the user.
• User interacts with the game through the user interface (controls, input).

32
• System processes user input and updates the game state.
• System renders the updated game state on the user interface.
• Alternative Flows :
• Game might require additional downloads or assets depending on complexity.
• System might track game progress and user achievements.

➢ Use Case : Game Session Management


• Actors : User
• Description : System tracks user progress and data for games requiring session
management.
• Pre-conditions : User is playing a game that requires session tracking.
• Basic Flow :
• System creates a new game session record for the user and game.
• System stores game progress, score, or other relevant data in the session or user
profile.
• System updates the game session record as the user progresses.
• System renders the updated game state on the user interface.
• Alternative Flows :
• Session data might be persisted periodically to avoid data loss in case of
disconnection.

3.4 | User Interface Design


User Interface (UI) design is the process of creating visually appealing, intuitive, and
user-friendly interfaces for software applications, websites, or any digital product that
users interact with. The primary goal of UI design is to enhance the user experience by
ensuring that the interface is easy to use, aesthetically pleasing, and efficient in achieving
the user's goals.

Here are some key principles and considerations in UI design :-


• Place the user at the center of the design process. Understand their needs, preferences,
and pain points through user research, surveys, and usability testing.
• Maintain consistency in the design elements, such as colors, fonts, icons, and layout,
throughout the entire interface.
• Keep the interface simple and avoid clutter. Minimalistic design enhances clarity and
reduces cognitive load for users.
• Ensure that navigation elements, such as menus, buttons, and links, are easily
accessible and intuitive. Users should be able to find what they need quickly.

33
A short introduction to the User Interface (UI) of “Web Games Portal” is as follows :-

➢ Login Page :

➢ Home Page :

34
➢ Word Guess Game Page :

➢ Tile Matching Game Page :

35
Chapter – 4
Coding

36
4.1 | Technologies and Languages
Developing the ASP.NET Core Web Application "Web Games Portal" involves
leveraging various technologies and tools to ensure a robust, scalable, and efficient
solution.

Below is a detailed list of technologies that can be used for this type of project :

Visual Studio 2022: Visual Studio Code serves as the primary Integrated
Development Environment (IDE) for development, debugging, and deployment
of the ASP.NET Core application.

Visual Studio Code : Visual Studio Code serves as the primary Integrated
Development Environment (IDE) for developing and managing the project. Its
robust features and intuitive interface facilitate efficient coding, debugging, and project
management.

ASP.NET Core : ASP.NET Core MVC: The primary framework for building
the application's backend, using the Model-View-Controller (MVC) design
pattern to separate concerns.
• Razor Pages: Simplifies the structure for certain pages, especially for those that
require server-side rendering with minimal logic.

C# : The primary programming language used for writing server-side code in


ASP.NET MVC applications.
• Strongly typed, object-oriented, and commonly used for business logic, data access,
and controller actions.

Microsoft SQL Server : A Relational Database Management System


(RDBMS) used to store and manage application data.
• Provides data storage, querying, and transaction management.

HTML : HTML is the foundation of front-end development. HTML structures


the content of web pages, while CSS is used to style and layout these elements,
ensuring a visually appealing and user-friendly interface.

37
CSS : Cascading Style Sheets used for describing the presentation and
formatting of project.
• It separates the presentation (styling) from the content of a document, allowing for
easier maintenance and providing control over the layout of web pages.

Bootstrap : Bootstrap is a free and open-source front-end framework created


by Twitter that simplifies the development of responsive, mobile-first websites.
• It provides a collection of pre-designed components and utilities built with HTML,
CSS, and optionally JavaScript.

JavaScript : JavaScript is utilized extensively to enhance the interactivity and


functionality to enhance the interactivity and functionality.

• Game logics are merely written in JS.


• jQuery is used specifically for performing AJAX requests, and manipulating the
DOM.

4.2 | MVC Architecture


ASP.NET Core MVC (Model-View-Controller) is an excellent choice for developing
web applications.

The MVC architecture is divided into three main components: Model, View, and
Controller. Here’s a detailed overview of each component:

➢ Model :
• Role: Represents the data and business logic of the application .
• Data Representation: Defines the structure of the data, often using classes that map to
database tables. Models typically include properties that represent the data fields.
• Validation: Can include data validation rules using attributes or custom logic to
ensure data integrity.
• Business Logic: Encapsulates business rules and logic related to the data, such as
calculations or data transformations.
• Data Access: Although not directly responsible for data access, models are often used
in conjunction with repositories or data access layers to interact with the database.

38
➢ View :
• Role: Responsible for displaying data to the user and presenting the user interface
(UI).
• Rendering: Uses HTML, CSS, and JavaScript to render the data provided by the
controller. Views are typically Razor (.cshtml ) files in ASP.NET MVC.
• Presentation Logic: Handles the layout and presentation of data, including user
interaction elements like forms and buttons.
• Data Binding: Receives data from the controller and displays it in a user-friendly
format. Views often use HTML helpers and model binding to render the data.

➢ Controller :
• Role: Manages user input, interacts with the model, and selects the view to render.
• Request Handling: Receives and processes incoming HTTP requests, handles user
interactions, and performs actions based on user input.
• Model Interaction: Retrieves data from the model, performs operations, and passes
the data to the view.
• View Selection: Chooses the appropriate view to display the data or results of
operations. Returns the view to the user, typically using the View() method.

4.3 | Project Structure


The project structure of the “Web Games Portal” web-application, developed using the
MVC (Model-View-Controller) architecture, is organized to ensure modularity,
maintainability, and scalability.

Here is a detailed breakdown of the directory layout and the roles of various folders :

39
MCA_Project_3 css

html
wwwroot
images

js

lib

Data

Migrations

Models ViewModels

Properties

Views Shared

Utility

Project Structure

40
➢ Project Directories and files :
• “MCA_Project_3” is the main project directory which contains important folders like
“wwwroot”, “Areas”, “Data”, “Views”, etc. and files like “appsettings.json”, and
“Program.cs”.
• “wwwroot” directory in an MVC project is designated for serving static files directly
to clients. These static files include CSS, JavaScript, images, and other assets that do
not require server-side processing. This folder is a key component of the ASP.NET
Core project structure and is configured to serve files directly to the client, making
them accessible via URLs.
• “Areas” directory is used to organize related functionality into separate sections,
making the application more modular. Each area contains its own set of Models,
Views, and Controllers, along with an area registration file. This structure is
particularly useful for large applications, enabling better organization and separation
of concerns.
• “Data” directory contains database connection class file i.e. “AppDbContext.cs” and
folder named Migration which stores changes applied to database.
• “AppDbContext.cs” is a class that derives from “DbContext” class from Entity
Framework. It represents the session with the database and is used to manage the
database connections, perform queries, and handle data operations.
• “Migrations” folder is used by Entity Framework to manage database schema
changes. It contains migration files that record changes to the data model, allowing
for version control of the database schema. These migration files enable you to update
the database schema in a consistent and automated way, reflecting changes made in
your code models.
• “Models” directory contains all the models (classes) of our project. A model
represents the data and business logic of the application. It is used to define the
structure of the data and manage the interactions between the data and the
application’s business rules.
• “Utility” directory organizes common functions into a modular package that can be
easily reused across different projects, simplifying code management and updates.
• “appsettings.json” file contains configuration settings for the application, such as
database connections, logging settings, and other application-specific configurations.
• “Program.cs” is the entry point for the application. This file contains the Main method
which runs the web host.

41
4.4 | Coding
Follow the steps to develop an ASP.NET Core Web-App named “Web Games Portal” :

➢ Step-I : Creating Models


• WordGuessGame.cs
namespace MCA_Project_3.Models
{
public class WordGuessGame
{
public int Id { get; set; }
public int WordGuessGameHeaderId { get; set; }
public WordGuessGameHeader WordGuessGameHeader {get; set;}
public int ScoreObtained { get; set; }
public int TimeTaken { get; set; }
}
}

• WordGuessGameHeader.cs
using System.ComponentModel.DataAnnotations.Schema;
namespace MCA_Project_3.Models
{
public class WordGuessGameHeader
{
public int Id { get; set; }
public string AppUserId { get; set; }
[ForeignKey("AppUserId")]
public AppUser AppUser { get; set; }
}
}

• TileMatchingGame.cs
namespace MCA_Project_3.Models
{
public class TileMatchingGame
{
public int Id { get; set; }
public int TileMatchingGameHeaderId { get; set; }
public TileMatchingGameHeader TileMatchingGameHeader { get; set; }
public int ScoreObtained { get; set; }
public int TimeTaken { get; set; }
}
}

42
• TileMatchingGameHeader.cs
using System.ComponentModel.DataAnnotations.Schema;
namespace MCA_Project_3.Models
{
public class TileMatchingGameHeader
{
public int Id { get; set; }
public string AppUserId { get; set; }
[ForeignKey("AppUserId")]
public AppUser AppUser { get; set; }
}
}

➢ Step-II : Creating DbContext class and adding dbsets of models


• AppDbContext.cs
using MCA_Project_3.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace MCA_Project_3.Data
{
public class ApplicationDbContext : IdentityDbContext
{
Public ApplicationDbContext(DbContextOptions
<ApplicationDbContext>options) : base(options) {}
public DbSet<AppUser> appusers { get; set; }
public DbSet<WordGuessGame> wgg { get; set; }
public DbSet<TileMatchingGame> tmg { get; set; }
public DbSet<WordGuessGameHeader> wggheader { get; set; }
public DbSet<TileMatchingGameHeader> tmgheader { get; set;}
}
}

➢ Step-III : Creating connection string inside “appsettings.json”


• appsettings.json
{
"ConnectionStrings": {
"cnx":"Server=(localdb)\\mssqllocaldb;Database=project_mca_db;
Trusted_Connection=True;MultipleActiveResultSets=true"
}
}

➢ Step-IV : Registering “Connection string” and “AppDbContext.cs” in


“Program.cs”
43
• AppDbContext.cs
using MCA_Project_3.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var cnstr = builder.Configuration.GetConnectionString("cnx");
builder.Services.AddDbContext<ApplicationDbContext>
(options => options.UseSqlServer(cnstr));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production
scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{area=Home}/{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
}

➢ Step-V : Add migration and update database using “Package Manager


Console”
Add-migration initLoad
Update-database;

➢ Step-VI : Create “Index” action method and it’s respective razor view
“Index.cshtml” for “HomeController.cs”
• HomeController.cs
using MCA_Project_3.Data;

44
using MCA_Project_3.Models;
using MCA_Project_3.Models.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using System.Security.Claims;
namespace MCA_Project_3.Areas.Home.Controllers
{
[Area("Home")]
[Authorize]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ApplicationDbContext _con;
public HomeController(ILogger<HomeController> logger,
ApplicationDbContext c)
{
_logger = logger;
_con = c;
}
public IActionResult Index()
{
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claims = claimsIdentity.FindFirst
(ClaimTypes.NameIdentifier);
wggVM obj = new wggVM()
{
wggList = _con.wgg.Include("WordGuessGameHeader").
OrderByDescending(wgg => wgg.ScoreObtained)
.Take(5).ToList(),
tmgList = _con.tmg.Include("TileMatchingGameHeader")
.OrderByDescending(tmg => tmg.ScoreObtained)
.Take(5).ToList().ToList(),
appuserList = _con.appusers.ToList()
};
return View(obj);
}

• Index.cshtml
@model MCA_Project_3.Models.ViewModels.wggVM
<div id="mainContainer">
<div id="leftContainer" style="margin-top:6.5pc;
box-shadow:1px 1px 5px aliceblue; color:ghostwhite">
<h4 class="text-center">Top Scores <br />
Word Guess Game<br />(Score w.r.t '5' attempts)

45
</h4>
<table><thead><tr>
<th>Player</th>
<th>Score</th>
<th>Time</th>
</tr></thead>
<tbody>
@if (Model.wggList != null)
{
@foreach (var player in Model.wggList)
{
<tr>
<td>@player.WordGuessGameHeader
.AppUser.UserName.Substring(0,
player.WordGuessGameHeader.
AppUser.UserName.IndexOf('@'))
</td>
<td>@player.ScoreObtained</td>
<td>@player.TimeTaken</td>
</tr>
}
}
else
{
<tr>
<td colspan="3">No Data Found!</td>
</tr>
}
</tbody></table>
</div>
<div class="container" style="width:60pc; margin-top:1pc;
border-radius:9px; box-shadow:1px 1px 5px aliceblue">
<div class="content">
<div class="slideshow">
<button class="slide-btn slide-btn-1"></button>
<button class="slide-btn slide-btn-2"></button>
<button class="slide-btn slide-btn-3"></button>
<button class="slide-btn slide-btn-4"></button>
<div class="slideshow-wrapper">
<div class="slide">
<a asp-area="WordGuessGame" asp-controller="WordGuessGame" asp-action="Index">
<img class="slide-img" src="/images/wgg0.jpg">
</a>
</div>
<div class="slide">

46
<a asp-area="TileMatchingGame" asp-controller="TileMatchingGame" asp-
action="Index">
<img class="slide-img" src="/images/tmg0.jpg">
</a>
</div>
<div class="slide">
<a asp-area="WordGuessGame" asp-controller="WordGuessGame" asp-action="Index">
<img class="slide-img" src="/images/wgg1.JPG">
</a>
</div>
<div class="slide">
<a asp-area="TileMatchingGame" asp-controller="TileMatchingGame" asp-
action="Index">
<img class="slide-img" src="/images/tmg1.png">
</a>
</div></div></div></div></div>
<div id="rightContainer" style="margin-top:6.5pc; box-shadow:1px 1px 5px aliceblue;
color:ghostwhite">
<h4 class="text-center">Top Scores <br /> Tile Matching Game</h4>
<table>
<thead><tr>
<th>Player</th>
<th>Moves</th>
<th>Time</th>
</tr></thead><tbody>
@if (Model.tmgList != null)
{
@foreach (var player in Model.tmgList)
{
<tr>
<td>@player.TileMatchingGameHeader.AppUser.UserName.Substring(0,
player.TileMatchingGameHeader.AppUser.UserName.IndexOf('@'))</td>
<td>@player.ScoreObtained</td>
<td>@player.TimeTaken</td>
</tr>
}
}
else
{
<tr>
<td colspan="3">No Data Found!</td>
</tr>
}
</tbody>
</table>
</div></div>

47
}

➢ Step-VIII : Create an MVC Area “WordGuessGame” inside “Areas”


directory and in the “Controllers” directory of this area, create an MVC
Controller “WordGuessGameController.cs” and create its Index action
method and it’s respective razor view “Index.cshtml”.
• WordGuessGameController.cs
using MCA_Project_3.Data;
using MCA_Project_3.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
namespace MCA_Project_3.Areas.WordGuessGame.Controllers
{
[Area("WordGuessGame")]
public class WordGuessGameController : Controller
{
private readonly ApplicationDbContext _con;
[BindProperty]
public Models.WordGuessGame wggObj { get; set; }
[BindProperty]
public WordGuessGameHeader wggHeaderObj { get; set; }
public WordGuessGameController(ApplicationDbContext con)
{
_con = con;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult returnData(string score, string time)
{
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claims = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
wggHeaderObj = new Models.WordGuessGameHeader()
{
AppUser = _con.appusers.FirstOrDefault(au => au.Id == claims.Value)
};

48
if (! _con.wggheader.Any(wh => wh.AppUserId == claims.Value))
{
_con.wggheader.Add(wggHeaderObj);
_con.SaveChanges();
}
wggObj = new Models.WordGuessGame()
{
WordGuessGameHeader = _con.wggheader.FirstOrDefault(wh => wh.AppUserId ==
claims.Value),
ScoreObtained = Convert.ToInt32(score),
TimeTaken = Convert.ToInt32(time)
};
_con.wgg.Add(wggObj);
_con.SaveChanges();
return RedirectToAction("Index");
}
}
}

• Index.cshtml
@model MCA_Project_3.Models.AppUser
<form method="post" asp-controller="WordGuessGame" asp-action="returnData">
<div class="centerdiv">
<div id='titlep'>
<p>
Guess The Word
</p>
</div>
<input type="button" name="ngbtn" id="ngbtn" onclick="newgameFunc()" value="New
Game">
<input type="hidden" id="score" name="score">
<input type="hidden" id="time" name="time">
<input type="submit" name="stopbtn" id="stopbtn" value="Stop Game">
<p id="timer">00:00</p>
<center>
<div class="hintcontainer">
<p id="hintp">Hint Goes Here!</p>
</div>
</center>
<div class="inputs">
<input type="text" name="letter" id="letter1" maxlength=1
onkeypress="moveCursor(this)" />
<input type="text" name="letter" id="letter2" maxlength=1
onkeypress="moveCursor(this)" />
<input type="text" name="letter" id="letter3" maxlength=1
onkeypress="moveCursor(this)" />

49
<input type="text" name="letter" id="letter4" maxlength=1
onkeypress="moveCursor(this)" />
<input type="text" name="letter" id="letter5" maxlength=1
onkeypress="moveCursor(this)" />
</div>
<input type="button" name="cbtn" id="cbtn" onclick="clearFunc()" value="Clear
Word">
<input type="button" name="sbtn" id="sbtn" onclick="submitFunc()" value="Submit">
<input type="button" name="nwbtn" id="nwbtn" onclick="nextwordFunc()"
value="Next Word">
<div id="resultdiv">
<p id="result">
Current Score = &nbsp;
<p id='scorespan'>0</p>
</p>
</div>
</div>
</form>

➢ Step-IX : Create an MVC Area “TileMatchingGame” inside “Areas”


directory and in the “Controllers” directory of this area, create an MVC
Controller “TileMatchingGameController.cs” and create its Index action
method and it’s respective razor view “Index.cshtml”.
• TileMatchingGame Controller.cs
using MCA_Project_3.Data;
using MCA_Project_3.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using static System.Formats.Asn1.AsnWriter;
namespace MCA_Project_3.Areas.TileMatchingGame.Controllers
{
[Area("TileMatchingGame")]
public class TileMatchingGameController : Controller
{
private readonly ApplicationDbContext _con;
public TileMatchingGameController(ApplicationDbContext con)
{
_con = con;
}
[BindProperty]
public Models.TileMatchingGame tmgObj { get; set; }
[BindProperty]
public Models.TileMatchingGameHeader tmgHeaderObj { get; set; }
public IActionResult Index()

50
{
return View();
}
[HttpPost]
public IActionResult returnData(string moves, int time)
{
// Info of user logged in
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claims = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
// adding moves and time
tmgHeaderObj = new Models.TileMatchingGameHeader()
{
AppUser = _con.appusers.FirstOrDefault(au => au.Id == claims.Value)
};
if (!_con.tmgheader.Any(wh => wh.AppUserId == claims.Value))
{
_con.tmgheader.Add(tmgHeaderObj);
_con.SaveChanges();
}
tmgObj = new Models.TileMatchingGame()
{
TileMatchingGameHeader = _con.tmgheader.FirstOrDefault(th => th.AppUserId ==
claims.Value),
ScoreObtained = Convert.ToInt32(moves),
TimeTaken = Convert.ToInt32(time)
};
tmgObj.TileMatchingGameHeaderId = tmgObj.TileMatchingGameHeader.Id;
_con.tmg.Add(tmgObj);
_con.SaveChanges();
return RedirectToAction("Index");
}
}
}

➢ Step-X : In “Shared” folder of “Views” folder of root directory, create


Partial Views which will be used as layout template for all razor views of
specific controller.
• “_Layout_Home.cshtml” for “HomeController.cs”
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Games</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

51
<!-- CSS -->
<link rel="shortcut icon" href="/images/fevicon.png" />
<link rel="stylesheet" href="/css/styles_home.css">
</head>
<body>
<header id="navContainer">
<div>
<p id="logo">Web Games Portal</p>
</div>
<div>
<partial name="_LoginPartial" />
</div>
</header>
<div id="marquee">
<marquee style="color:#1699bd; text-shadow:1px 1px 1px #000">
Welcome to Web Games Portal ! Click on Tiles to play games
</marquee>
</div>

<main>
@RenderBody()
</main>
<footer>
<p>
&copy;All Rights Reserved | [email protected] | Kullu, Himachal Pradesh,
India
</p>
</footer>
<!-- Scripts -->
<script src="/home_script.js"> </script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

• “_Layout_WGG.cshtml” for “WordGuessGameController.cs”


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Object Matching Game</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--CSS Stylesheet-->

52
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU
" crossorigin="anonymous">
<link rel="stylesheet" href="/css/styles_tmg.css">
<!--Favicon-->
<link rel="shortcut icon" href="images/fevicon.png" />
<!--Google Fonts-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Patrick+Hand&display=swap"
rel="stylesheet">
<!-- Javascript -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"> </script>
</head>
<body>
<header id="navContainer">
<div>
<a asp-area="Home" asp-controller="Home" asp-action="Index" id="logo">Web Games
Portal</a>
</div>
</header>
<div id="ol"></div>
<div style="height: 8px;"></div>
<div id="title">
<h3>OBJECT MATCHING GAME</h3>
</div>
<div id="title" style="height: 40px;">
<span id="moves"></span>
<span id="time"></span>
</div>
<center>
<table cellspacing="0"></table>
</center>
@RenderBody()
<footer>
<p>
&copy;All Rights Reserved | [email protected] | Kullu, Himachal Pradesh,
India
</p>
</footer>
<script src="/js/script_tmg.js"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

53
• “_Layout_TMG.cshtml” for “TileMatchingGameController.cs”
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tile Matching Game</title>
<link rel="stylesheet" href="/css/styles_tmg.css">
<!--Favicon-->
<link rel="shortcut icon" href="images/fevicon.png" />
</head>
<body>
<header id="navContainer">
<div>
<a asp-area="Home" asp-controller="Home" asp-action="Index" id="logo">Web Games
Portal</a>
</div>
</header>
<div id="ol"></div>
<div style="height: 8px;"></div>
<div id="title">
<h3>TILE MATCHING GAME</h3>
</div>
<div id="title" style="height: 40px;">
<span id="moves"></span>
<span id="time"></span>
</div>
<center>
<table cellspacing="0"></table>
</center>
@RenderBody()
<footer>
<p>
&copy;All Rights Reserved | [email protected] | Kullu, Himachal Pradesh,
India
</p>
</footer>
<script src="/js/script_tmg.js"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

➢ Step-XI : In “css” folder of “wwwroot” folder of root directory, create


external stylesheets for specific controller.
• styles_home.css
*{
margin: 0;

54
padding: 0;
box-sizing: border-box;
}
#loginContainer {
display: none;
justify-content: center;
align-items: center;
position: fixed;
z-index: 2;
text-align: center;
padding: 8pc;
margin: 4vh 34vw;
background-color: #1699bd;
backdrop-filter: blur(30px);
}
form > h2 {
padding-bottom: 3pc;
font-family: 'Montserrat', sans-serif;
}
#loginPartialContainer {
display: flex;
justify-content: center;
align-items: center;
/*background-color: beige;*/
position: relative;
left: 16vw;
}
#loginPartialContainer > div {
/*background-color: aliceblue;*/
display: flex;
padding: 0.4pc 0.8pc;
margin: 1pc;
justify-content: flex-end;
text-align: right;
border: 2px solid #1699bd;
border-radius: 50px;
}
#innerLoginPartialContainer > div {
padding: 0.5pc 1pc;
margin: 0.2pc;
justify-content: flex-end;
text-align: right;
border: 1px black double;
border-radius: 50px;
}
.nav-link {

55
color: black;
text-decoration: none;
}
body {
font-family: 'Montserrat', sans-serif;
margin: 0;
padding: 0;
background-color: #1687A7;
}
#marquee {
display: flex;
justify-content: center;
align-items: center;
background-color: #dfdfdf8c;
color: rgb(14, 11, 11);
height: 3pc;
margin-top: 1pc;
font-size: 20px;
font-weight: bold;
}
#navContainer {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100px;
background-color: #dfdfdf8c;
position: relative;
top: 0;
}
#logo {
text-align: center;
font-size: 26px;
font-weight: bolder;
color: rgba(255, 255, 255, 0.705);
text-shadow: 1px 1px 22px #012f58;
width: max-content;
background-color: #1687A7;
margin: 2pc 2pc;
margin-left: 22pc;
padding: 0.5pc 1pc;
border-radius: 12pc;
font-size: 34px;
}
#logo:hover {
padding: 0.8pc 0.2pc;

56
letter-spacing: 1px;
font-size: 2.2em;
}
.title {
background-color: aquamarine;
}
.title > h2 {
background-color: aquamarine;
}
#mainContainer {
display: flex;
justify-content:center;
text-align:center;
}
#leftContainer {
margin: 2.2pc;
padding-top:8px;
width: 20%;
height: 50%;
border: 2px solid black;
}
#rightContainer {
margin: 2.2pc;
padding-top: 8px;
width: 20%;
height: 50%;
border: 2px solid black
}
table, thead, th, tr, tbody, td{
border : 1px solid black;
border-radius:46px;
border-collapse:collapse;
width:100%;
padding:13px;
margin-top : 7px;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.carousel-content {
position: absolute;
top: 50%;
left: 50%;

57
transform: translate(-50%, -50%);
text-align: center;
z-index: 50;
}
.slideshow {
height: 100%;
overflow: hidden;
position: relative;
border-radius: 1pc;
}
footer {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 92vh;
width: 100%;
height: 8vh;
background-color: #dfdfdf8c;
font-size: 16px;
font-weight: bold;
letter-spacing: 0.4px;
}

➢ Step-XII : In “js” folder of “wwwroot” folder of root directory, create


JavaScript files which will contain client-side logic for specific controller.
• “script_home.js” for “HomeController.cs”
function displayLogin()
{
document.getElementById("loginContainer").style.display = "block";
}
const buttons = document.querySelectorAll("[data-carousel-button]");
buttons.forEach(button =>
{
button.addEventListener("click", () =>
{
const offset = button.dataset.carouselButton === "next" ? 1 : -1;
const slides = button.closest("[data-carousel]").querySelector("[data-slides]");
const activeSlide = slides.querySelector("[data-active]");
let newIndex = [...slides.children].indexOf(activeSlide) + offset;
if (newIndex < 0) newIndex = slides.children.length – 1;
if (newIndex >= slides.children.length) newIndex = 0;
slides.children[newIndex].dataset.active = true;
delete activeSlide.dataset.active;

58
})
})

• “script_wgg.js” for “WordGuessGameController.cs”


const obj = {
'hello': 'Word or greeting when we meet any person',
'eager': 'Keen to know everything',
'faces': 'Front part of a person\'s head',
'kabab': 'A dish of roasted or grilled meat or vegetables',
'price': 'A term for money required for trade of an item',
'happy': 'Emotion of joy',
'erase': 'To remove or rub out something written or recorded',
'event': 'An occassion or thing of importance that takes place',
'alert': 'A term used to give warning',
'eagle': 'Bird flying on very high altitudes'
};

const wordArr = ['hello', 'eager', 'faces', 'kabab', 'price', 'happy', 'erase', 'event', 'alert',
'eagle'];
score = 0;
randomIndex = 0;
tempWord = 0;
hintVar = 0;
[char1, char2, char3, char4, char5] = '';
[input1, input2, input3, input4, input5] = '';
totalTime = 10;
currTime = 0;
tempTime = 0;
totalTimeTaken = 0;
newGameToggle = 1;
// driver function
function newgameFunc() {
if (newGameToggle) {
document.getElementById('ngbtn').value = 'Restart Game';
document.getElementById('ngbtn').style.width = '10pc';
document.getElementById('stopbtn').style.display = 'inline-block';
}
document.getElementById('scorespan').innerHTML = score;
document.getElementById('scorespan').style.color = 'white';
document.getElementById('sbtn').style.display = 'none';
nextwordFunc();
}
function nextwordFunc() {
removeStyleInputFields();
clearFunc();

59
document.getElementById('cbtn').style.display = 'inline';
document.getElementById('sbtn').style.display = 'inline';
document.getElementById('nwbtn').style.display = 'none';
currTime = 0;
timer();
randomIndex = Math.floor(Math.random() * 10);
tempWord = wordArr[randomIndex];
// creating hint var
hintVar = document.getElementById('hintp');
hintVar.innerHTML = obj[wordArr[randomIndex]];
[char1, char2, char3, char4, char5] = [tempWord[0], tempWord[1], tempWord[2],
tempWord[3], tempWord[4]];
input1 = document.getElementById('letter1');
input2 = document.getElementById('letter2');
input3 = document.getElementById('letter3');
input4 = document.getElementById('letter4');
input5 = document.getElementById('letter5');
}
function clearFunc() {
document.getElementById('letter1').value = '';
document.getElementById('letter2').value = '';
document.getElementById('letter3').value = '';
document.getElementById('letter4').value = '';
document.getElementById('letter5').value = '';
}
function submitFunc() {
document.getElementById('cbtn').style.display = 'none';
document.getElementById('sbtn').style.display = 'none';
document.getElementById('nwbtn').style.display = 'inline';
if ((input1.value == char1) && (input2.value == char2) && (input3.value == char3) &&
(input4.value == char4) && (input5.value == char5)) {
correctInputFields();
score += 10;
document.getElementById("score").value = score;
tTime = document.getElementById("timer").innerHTML.substring(3);
totalTimeTaken += parseInt(tTime);
document.getElementById("time").value = totalTimeTaken;
currTime = 21;
tempTime = 0;
}
else if ((input1.value == '') && (input2.value == '') && (input3.value == '') &&
(input4.value == '') && (input5.value == '')) {
document.getElementById('cbtn').style.display = 'inline';
document.getElementById('sbtn').style.display = 'inline';
document.getElementById('nwbtn').style.display = 'none';
alert('Enter the word first!!!')

60
}
else if (tempTime > 0) {
showAnswer();
score -= 5;
document.getElementById('scorespan').innerHTML = score;
document.getElementById("score").value = score;
tTime = document.getElementById("timer").innerHTML.substring(3);
totalTimeTaken += parseInt(tTime);
document.getElementById("time").value = totalTimeTaken;
wrongInputFields();
currTime = 21;
}
else {
console.log('Error');
}
scoreObj = document.getElementById('scorespan').innerHTML = score;
}
function timer() {
let timer = setInterval(func, 1000);
function func() {
tempTime = totalTime - currTime;
if (currTime <= totalTime) {
if (tempTime >= 10) {
document.getElementById('timer').innerHTML = '00:' + tempTime;
currTime++;
}
else {
document.getElementById('timer').innerHTML = '00:0' + tempTime;
currTime++;
}
}
else if (currTime == 21) {
showAnswer();
currTime = 0;
document.getElementById('scorespan').innerHTML = score;
clarInterval(timer);
document.getElementById('sbtn').style.display = 'none';
document.getElementById('nwbtn').style.display = 'inline';
}
else {
document.getElementById('sbtn').style.display = 'none';
document.getElementById('nwbtn').style.display = 'inline';
clearInterval(timer);
score -= 5;
currTime = 0;
// document.getElementById('scorespan').style.color = 'red';

61
document.getElementById('scorespan').innerHTML = score;
showAnswer();
}
}
}
function correctInputFields() {
document.getElementById('letter1').style.border = '3px solid green';
document.getElementById('letter2').style.border = '3px solid green';
document.getElementById('letter3').style.border = '3px solid green';
document.getElementById('letter4').style.border = '3px solid green';
document.getElementById('letter5').style.border = '3px solid green';
}
function wrongInputFields() {
document.getElementById('letter1').style.border = '3px solid red';
document.getElementById('letter2').style.border = '3px solid red';
document.getElementById('letter3').style.border = '3px solid red';
document.getElementById('letter4').style.border = '3px solid red';
document.getElementById('letter5').style.border = '3px solid red';
showAnswer();
}
function showAnswer() {
setTimeout(() => {
document.getElementById('letter1').value = char1;
document.getElementById('letter1').style.color = 'green';
}, 600);
setTimeout(() => {
document.getElementById('letter2').value = char2;
document.getElementById('letter2').style.color = 'green';
}, 800);
setTimeout(() => {
document.getElementById('letter3').value = char3;
document.getElementById('letter3').style.color = 'green';
}, 1000);
setTimeout(() => {
document.getElementById('letter4').value = char4;
document.getElementById('letter4').style.color = 'green';
}, 1200);
setTimeout(() => {
document.getElementById('letter5').value = char5;
document.getElementById('letter5').style.color = 'green';
}, 1400);
}
function removeStyleInputFields() {
document.getElementById('letter1').style.border = '1px solid cornflowerblue';
document.getElementById('letter2').style.border = '1px solid cornflowerblue';
document.getElementById('letter3').style.border = '1px solid cornflowerblue';

62
document.getElementById('letter4').style.border = '1px solid cornflowerblue';
document.getElementById('letter5').style.border = '1px solid cornflowerblue';
document.getElementById('letter1').style.color = 'black';
document.getElementById('letter2').style.color = 'black';
document.getElementById('letter3').style.color = 'black';
document.getElementById('letter4').style.color = 'black';
document.getElementById('letter5').style.color = 'black';
}

• “script_tmgg.js” for “TileMatchingGameController.cs”


var tmp, c, p = em.length;
if(p) while(--p) {
c = Math.floor(Math.random() * (p + 1));
tmp = em[c];
em[c] = em[p];
em[p] = tmp;
}
var pre="", pID, ppID=0, turn=0, t="transform", flip="rotateY(180deg)",
flipBack="rotateY(0deg)", time, mode;
window.onload = function() {
$("#ol").html(`
<center>
<div id="inst">
<h3 class = "game-title">
Match The Cards !</h3>
<br/>
<h4>Instructions For Game - </h4>
<br/>
<div id="div_li">
<li>Make pairs of similiar blocks by flipping them.</li>
<li>To flip a block you can click on it.</li>
<li>If two blocks you clicked are not similar, they will be flipped
back.</li><li>Complete the game, comment your score and challenge your friends
too.</li>
</div>
<p style = "font-size: 25px; font-weight: 400; margin-top: 90px;">Click one of the
following mode to start the game.</p>
<button class = "btn btn-outline-light btn-lg modes" onclick="start(3, 4)">3 x 4</button>
<button class = "btn btn-outline-light btn-lg modes" onclick="start(4, 4)" style="w">4 x
4</button>
<button class = "btn btn-outline-light btn-lg modes" onclick="start(4, 5)">4 x 5</button>
<button class = "btn btn-outline-light btn-lg modes" onclick="start(5, 6)">5 x 6</button>
<button class = "btn btn-outline-light btn-lg modes" onclick="start(6, 6)">6 x 6</button>
</div>
</center>`);
}

63
function start(r,l)
{
//Timer and moves
min=0, sec=0, moves=0;
$("#time").html("Time: 00:00");
$("#moves").html("Moves: 0");
time = setInterval(function() {
sec++;
if(sec==60) {
min++; sec=0;
}
if(sec<10)
$("#time").html("Time: 0"+min+":0"+sec);
else
$("#time").html("Time: 0"+min+":"+sec);
}, 1000);
rem=r*l/2, noItems=rem;
mode = r+"x"+l;
//Generating item array and shuffling it
var items = [];
for (var i=0;i<noItems;i++)
items.push(em[i]);
for (var i=0;i<noItems;i++)
items.push(em[i]);
var tmp, c, p = items.length;
if(p) while(--p) {
c = Math.floor(Math.random() * (p + 1));
tmp = items[c];
items[c] = items[p];
items[p] = tmp;
}
$("table").html("");
var n=1;
for (var i = 1;i<=r;i++) {
$("table").append("<tr>");
for (var j = 1;j<=l;j++) {
$("table").append(`<td id='${n}' onclick="change(${n})"><div class='inner'><div
class='front'></div><div class='back'><p>${items[n-1]}</p></div></div></td>`);
n++;
}
$("table").append("</tr>");
}
$("#ol").fadeOut(500);
}
function change(x)
{

64
let i = "#"+x+" .inner";
let f = "#"+x+" .inner .front";
let b = "#"+x+" .inner .back";
if (turn==2 || $(i).attr("flip")=="block" || ppID==x) {}
else {
$(i).css(t, flip);
if (turn==1)
{
turn=2;
if (pre!=$(b).text()) {
setTimeout(function() {
$(pID).css(t, flipBack);
$(i).css(t, flipBack);
ppID=0;
},1000);
}
else {
rem--;
$(i).attr("flip", "block");
$(pID).attr("flip", "block");
}
setTimeout(function() {
turn=0;
//Increase moves
moves++;
$("#moves").html("Moves: "+moves);
},1150);
}
else {
pre = $(b).text();
ppID = x;
pID = "#"+x+" .inner";
turn=1;
}
if (rem == 0) {
clearInterval(time);
if (min == 0) {
time = `${sec} seconds`;
$.ajax({
url: "/TileMatchingGame/TileMatchingGame/returnData",
type: "post",
data: {
moves: moves,
time: time.substring(0, 2)
}
});

65
}
else {
time = `${min} minute(s) and ${sec} second(s)`;
tTime = (min * 60) + sec;
$.ajax({
url: "/TileMatchingGame/TileMatchingGame/returnData",
type: "post",
data: {
moves: moves,
time: tTime
}
});
}
setTimeout(function()
{
(function () {
});
document.getElementById("moves").value = moves;
document.getElementById("time").value = time;
$("#ol").html(`
<center>
<div id="iol">
<h2>Congrats!</h2>
<p style="font-size:23px;">
You completed the ${mode} mode in ${moves} moves. It took you ${time}.
</p>
<p style="font-size:18px">
Comment Your Score!<br/>Wanna Play Again ?
</p>
<button class = "btn btn-outline-light btn-lg modes2" onclick="start(3, 4)">3 x
4</button>
&nbsp;
<button class = "btn btn-outline-light btn-lg modes2" onclick="start(4, 4)" style="w">4 x
4</button>
&nbsp;
<button class = "btn btn-outline-light btn-lg modes2" onclick="start(4, 5)">4 x
5</button>
&nbsp;
<button class = "btn btn-outline-light btn-lg modes2" onclick="start(5, 6)">5 x
6</button>
&nbsp;
<button class = "btn btn-outline-light btn-lg modes2" onclick="start(6, 6)">6 x
6</button></div></center>`);
$("#ol").fadeIn(450);
}, 1000);
}

66
}
}

➢ Step-XIII : In “Account” folder “Pages” folder of “Identity” area of


“Areas” folder, modify code for “Register.cshtml” razor page.
• Register.cshtml.cs
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using MCA_Project_3.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
namespace MCA_Project_3.Areas.Identity.Pages.Account
{
public class RegisterModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly IUserStore<IdentityUser> _userStore;
private readonly IUserEmailStore<IdentityUser> _emailStore;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterModel(
UserManager<IdentityUser> userManager,
IUserStore<IdentityUser> userStore,
SignInManager<IdentityUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_userStore = userStore;
_emailStore = GetEmailStore();
_signInManager = signInManager;
_logger = logger;
67
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1}
characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do
not match.")]
public string ConfirmPassword { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
ExternalLogins = (await
_signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await
_signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new AppUser()
{
UserName = Input.Email,
Email = Input.Email
};
await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)

68
{
_logger.LogInformation("User created a new account with password.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl =
returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return Page();
}
private IdentityUser CreateUser()
{
try
{
return Activator.CreateInstance<IdentityUser>();
}
catch
{
throw new InvalidOperationException($"Can't create an instance of
'{nameof(IdentityUser)}'. " +
$"Ensure that '{nameof(IdentityUser)}' is not an abstract class and has a parameterless
constructor, or alternatively " +
$"override the register page in /Areas/Identity/Pages/Account/Register.cshtml");
}
}
private IUserEmailStore<IdentityUser> GetEmailStore()
{
if (!_userManager.SupportsUserEmail)
{
throw new NotSupportedException("The default UI requires a user store with email
support.");
}
return (IUserEmailStore<IdentityUser>)_userStore;
}
}
}

69
➢ Step-XIV : In “Account” folder “Pages” folder of “Identity” area of
“Areas” folder, modify code for “Login.cshtml” razor page.
• Login.cshtml.cs
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using MCA_Project_3.Models;
namespace MCA_Project_3.Areas.Identity.Pages.Account
{
public class LoginModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<LoginModel> _logger;

public LoginModel(SignInManager<IdentityUser> signInManager,


ILogger<LoginModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
70
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
returnUrl ??= Url.Content("~/");
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await
_signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await
_signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password,
Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe =
Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
return Page();
}

71
}
}

Chapter – 5
Testing

72
5.1 | Testing

73
74
Chapter – 6
Result

75
6.1 | Result

➢ Login Page
• Objective :
• Login page is displayed when application starts.
• Existing user signs-up using e-mail address and password.
• New user has to register for accessing the portal by clicking on “Register” hyperlink.
• New as well as existing users can use third-party authentication providers (Facebook,
Google, Github, and so on) to register or login to portal.
• User sign-in is mandatory for accessing portal.

➢ Registration Page
• Objective :
• On clicking “Register” link, user registration (sign-up) page gets displayed.
• New user registers for user account by providing e-mail address and password.
• On clicking “Register” button, user account with specified credentials is created and
redirected homepage.

76
• Users can use third-party authentication providers (Facebook, Google, Github, and so
on) for registration to portal.

➢ Home Page
• Objective :
• After authorization process, user enters into portal’s homepage.
• A carousal (dynamic slide of static images) containing graphical links to specific
games are displayed.
• User clicks on image to land on game page.
• On both sides of carousal, a table is displayed containing top five scores of players
with details as shown in above image.
• On header, there are two buttons, one showing username of logged-in user and
another button for logging-out.

77
➢ Word Guess Game Page
• Objective :
• On clicking on either 1st or 3rd graphical links (images containing “Word Guess”
keywords), user lands on “Word Guess Game” page.
• User has to guess the word within a time interval of 30 seconds, after which correct
answer is displayed within input boxes and 5 points gets deducted from current total
score.

• Following are steps how user interacts with game.


• User clicks on “New Game” button and a statement (hint) justifying the word is
displayed.

78
• Then, user inputs character by character the word he/she guesses and then clicks on
“Submit” button to submit the word.
• “Clear Word” button will be clicked to empty input boxes.
• If the entered word is correct, then the color of characters entered by user and the
input boxes, changes to “green” character-by-character.
• “Next Word” button is clicked to continue with next word.
• “Below “Next Word” button, user’s current score is displayed.
• On correct guess, user gets 10 points.

• If the entered word is incorrect, then the color of characters entered by user are
replaced by characters of correct word with “green” color while, the color of input
boxes changes to “red” character-by-character.
• “Next Word” button is clicked to continue with next word.
• On wrong guess, 5 points gets deducted from total score.

79
• User can stop the game by clicking on “Stop Game” button and can continue a new
game by clicking on “New Game Button”.

• User can redirect back to homepage by clicking on “Web Games Portal” link on
header.
80
➢ Tile Matching Game Page
• Objective :
• On clicking either 2nd or 4th graphical links (images containing “Tile Matching”
keywords), user lands on “Tile Matching Game” page.
• User has to match the object displayed on one tile with another tile.
• When two consecutive tiles are matched, they are remains flipped while if not
matched, both selected tiles are flipped back.
• Selecting (flipping) two tiles counts 1 move and user has to flip all tiles with
minimum moves and time taken.

• Following are steps how user interacts with game.


• User lands on “Tile Matching Game” page having directions to play the game.

81
• At bottom, there are displayed 5 modes (grid of rows and columns) in which user can
play the game like 3X4, 4X4, 4X5, 5X6 and 6X6.
• To start game, user has to click on one mode.

• When user selects 4X4 mode, following page is displayed.


• Total 12 tiles are there and user has to flip two tiles consecutively.

82
• If matched object on two tiles gets matched, flipped tiles remain flipped.

• If matched object on two tiles doesn’t get matched, flipped tiles are flipped back to
their original position.

• When all tiles are flipped, a popup is displayed displaying moves and time taken by
user
• User can restart new game by clicking on a specific mode given.

83
• User can go back to homepage to play another game by clicking on “Web Games
Portal” link on header.

• If user has scored highest points then the top 5 scorers, then his/her score gets
displayed in the table of respective game on homepage.
• User can continue to play another game by following same steps.

84
➢ User Profile Button
• Objective :
• On clicking the button having user name on header, “User Profile” page is displayed
which helps user to access profile data.
• “Profile” button provides an input box having user’s username which can be changed
by clicking on “Save” button from this page.

• “Personal Score” button displays two tables containing all scores obtained by user
having most current score on top of table record.

85
• “Password” button displays input boxes to change user password.

• “Logout” button on header is used to end user session or simply logout the current
user and displays login page as new user can login in.
• In same steps, new and existing users can play games using portal.

• Here’s the end of User Interface (UI) used to interact with “Web Games Portal”.

86
Chapter – 7
Conclusion

87
7.1 | Conclusion
The development of the "Web Games Portal" using ASP.NET Core represents a
significant achievement in creating a modern, scalable, and feature-rich online gaming
platform. This project demonstrates the potential of ASP.NET Core as a powerful
framework for building web applications that can meet the demands of both users and
developers in today’s fast-paced digital environment.

In conclusion, the ASP.NET Core "Web Games Portal" stands as a comprehensive and
innovative platform that leverages the full potential of modern web development
technologies. It successfully addresses the needs of a dynamic and growing online
gaming community, offering a secure, scalable, and enjoyable environment for gamers
worldwide. The development process has been guided by best practices in software
engineering, ensuring that the portal is not only functional and efficient today but also
well-prepared to evolve with the demands of tomorrow's digital landscape.

The successful implementation of this project showcases the effectiveness of ASP.NET


Core in building complex, high-performance web applications and serves as a solid
foundation for future developments in the online gaming industry.

88
Chapter – 8
Bibliography

89
8.1 | Bibliography
• “Pro ASP.NET Core MVC 2” by “Adam Freeman”
• “Head First HTML, CSS, and JavaScript” by “Eric Freeman and Elisabeth Robson”
• “JavaScript: The Definitive Guide” by “David Flanagan”
• https://dotnet.microsoft.com/en-us/apps/aspnet/
• https://www.w3schools.com/
• https://www.geeksforgeeks.org/
• https://www.youtube.com/@Csharp-video-tutorialsBlogspot – “ASP.NET core
tutorial for beginners” by “kudvenkat”
• https://www.youtube.com/watch?v=cpoXLj24BDY&t=39927s - “JavaScript
Complete Course (2024)” by “KG Coding by Prashant Sir”

90

You might also like