Have you ever wondered if you could build your own chess game and play it with an AI engine on the browser? If you do, then you might enjoy reading this article.

Photo by Felix Mittermeier on Unsplash
Photo by Felix Mittermeier on Unsplash

It is no wonder that chess is the most popular intellectual game in the world. We can trace this game to the 6th century, which has stuck because of its complex and challenging nature until these days.

The first “chess machine” was invented by the Hungarian Wolfgang Von Kempelen (Kempelen Farkas) in 1770, known as the Mechanical Turk. The inventor claimed that the machine was fully automatic. Moreover, its elaborate mechanism and the fact that it had defeated even chess masters convinced many people. But did a successful chess machine already exist in the late 18th century? The answer is no. The truth was that Wolfgang von Kempelen had hired several chess masters and hid them inside the machine. The hidden players then controlled the mechanical arms of the Turk manually. As a result, the chess machine has traveled worldwide, impressed people everywhere, and inspired them to create their own.

In the last century, the concern became creating a machine with human-like intelligence. The mathematician and computer scientist Alan Turing was amongst the first to start laying down the principles of chess AI algorithms. Many are familiar with his name thanks to the recent movie “The Imitation Game,” about how he helped crack the German ciphers encoded with the Enigma machine [4]. However, his work on artificial intelligence led him toward chess, specifically the theory of using computers to play chess.

Around 1948, he and his colleague David Gawen Champerowne wrote the first computer chess program, called Turochamp, using the following basic principles that each piece on the board was assigned a value: pawn = 1, knight = 3, bishop = 3.5, rook = 5, queen = 10, and king = 1000. The algorithm foresaw two moves to calculate every possible combination of moves and then chose the most rewarding one. He tested his algorithm by challenging one of his friends, Alick Glennie. Since computers at the time were not up to heavy computing calculations, Turing calculated the moves on paper by hand (which took him more than 30 minutes on the average per move). Unfortunately, Turing and his algorithm lost the match. Nevertheless, he constructed the earliest known computer chess program.

So now, what about you? Are you ready to build your chessboard on a webpage?

Building the chessboardIn this section, we will teach you how to build a simple chessboard using html and javascript (no css styling needed). The method used may not be the best, yet it is easy to understand.

Let us break it into simple steps and statements:

a) Creating the canvas: to draw the chessboard, we brought a white canvas element in html with a specific height and width to stick the pieces on it later. The code in html is as simple as:

b) Drawing the squares: Since we have a white canvas, we chose to draw the squares and pieces using functions in JavaScript. The squares are created by slicing the canvas into 64 identical squares alternating between black and white. The code for this is as follows:

Note: dimension = 8 is the number of files/ ranks in the chessboard and the context.globalAlpha is set to 1 to make the canvas rendering fully opaque.

c) Drawing the pieces: The pieces are of a complex shape; therefore, images of them are easier to insert and use. You may get the images from any source and import them into your js code. Then we can organize them into a list to put them in a loop. You can see here that we used the instance game_state to place each piece in its correct initial position. Nevertheless, it is better explained later in the article.

Now that we have all the drawing elements, how do we link them all together?

We link the html body with an initiating function that defines the canvas elements and events.

So in html, we add the following in the body tag:

Then in the js code:

The view of our chessboard on the page after building the html
The view of our chessboard on the page after building the html

Basic functionality of a chess gameTo create a real chess game, we must move the piece and keep track of their positions at all times. However, this is not as simple as it sounds in programming. Let’s say we want to create a class that defines the game and let’s call it game_state. It needs to state the initial board position and the offset of each piece and move it accordingly while logging the new board position. For example, this snippet code shows the board representation and then the knight offset.

Moving the pieces: There are different types of moves in chess. Any move could be a start, end, board move, capturing a piece, promotion move, en-passant move, or castle move. Each of them should be defined. For example, an en-passant move can be made with:

By now, the piece could move, but what if the move was illegal?

Each move needs to be validated. If the move is illegal, then the piece should be retracted automatically. Yet, suppose you want to make it easier for the player to commit legal moves only. In that case, you can define all the valid moves of a piece and highlight them when the player touches (clicks on) any piece to move. For example, you may check all the possible moves of a piece with a code similar to this:

Did you make a move and regret it or make a mistake? Then you need to introduce the undo button to your game.

It is easily implemented in HTML by adding the following:

In js code, you may create the undo function as a method of the game_state, which allows you to edit other attributes in game-tracking, such as making a move and game-over status. Check it below:

In concept, the undo method is purely popping the last move out of the log. Nevertheless, what if the move was a promotion or en-passant? Then we need to define more conditions that cover all possibilities. Let’s look at the code snippet below. It checks the move type as promotion and takes multiple actions to revoke it, including the return of the captured piece during the move.

Now we have all bases covered to start playing.

But do you want to play alone? Absolutely not. Let’s create an

AI opponent## . The first thing that you need to build an AI opponent is data. Let’s put it as you feed the model some inputs to teach it how to digest them and generate the specific output. For chess, these data are recorded games between real players. These recorded games are formed as Portable Game Notation (PGN) files. Fortunately, many PGN databases are available online for free, and you may use any. Yet keep in your mind that these notation files need to be parsed. Our recommendation is to use chess.pgn in Python.

So let’s consider that you already have parsed the database and are ready to use it; thus, it’s time to build our AI model. We can create a sequential model out of multiple layers using TensorFlow and Keras. As you may see below, the model consists of 2 layers of 2D Convolutional Neural Networks (CNN), Flatten, 2 layers of Dense Neural Networks (DNN), and a softmax layer. You can notice that we used the Adam optimizer and binary loss entropy function to optimize the training process.

Note: after building the model and training it in Python, you can convert it into Javascript code.

After training the model, you need a function that will enable the AI engine to move a piece based on predicting the best valid move possible at a specific game state. In other words, you need to link the AI prediction with the chess functions provided earlier in the Javascript code. For example, selecting the best move will be as the following:

Don’t forget to add the button and link it with a function to enable the AI feature.

Are you wondering how to link all the files together? Well, module bundling is the solution to that.

Here we reach the end of this story. We provided tutorial-like instructions and discussion to build your own chess game on a webpage, define your desired rules, and program your ultimate opponent. Nevertheless, our description was brief in some points, but we hope our article encouraged you to go and search further.

What is your next move?

For the full code to build your own game, please check our repository on

GitHub## . If you are interested in playing against our AI engine, please visit the page under Demos## .

Related Posts

Empowering Business Growth with Custom Software Development

Empowering Business Growth with Custom Software Development


Smart Marketing, Smarter Solutions: AI-Marketing & Use Cases

Smart Marketing, Smarter Solutions: AI-Marketing & Use Cases


The AI Revolution in Manufacturing

The AI Revolution in Manufacturing


AI in Sales: Boosting Efficiency and Driving Growth

AI in Sales: Boosting Efficiency and Driving Growth


AI in Digital Arts

AI in Digital Arts


AI-Powered Smart Lighting Solutions

AI-Powered Smart Lighting Solutions


Making Your Home Smarter with a Little Help from AI

Making Your Home Smarter with a Little Help from AI


MLOps vs. DevOps - Key Distinctions Explained

MLOps vs. DevOps - Key Distinctions Explained


AI in Biomechanics: From Creating Cosmetic Prosthetics to Rehabilitation & Making Metahumans!

AI in Biomechanics: From Creating Cosmetic Prosthetics to Rehabilitation & Making Metahumans!


Maximising AI Application Development with MLOps

Maximising AI Application Development with MLOps


Introduction to MLOps (4/04/2024)
How can AI tools improve customer service and satisfaction? (3/04/2024)
Breaking Boundaries in Smart Communication with AI Technologies (1/04/2024)
Exploring Virtual Museums and the Digital Past with AI and AR VR (28/03/2024)
The Impact of AI on Smart Lighting Solutions (27/03/2024)
The Impact of AI in the Supply Chain and Logistics (26/03/2024)
Scoring Big with AI: Innovations in Sports Technology (25/03/2024)
Eat Right for Your Body with AI-Driven Nutritional and Supplement Guidance (22/03/2024)
Exploring AI's Role in Smart Solutions for Traffic, Transportation, and Parking (21/03/2024)
The Benefits of AI-Integrated Fitness Programs (20/03/2024)
Detecting and Canceling Signal Noise with AI (19/03/2024)
Transformative Role of AI in Supply Chain Management (18/03/2024)
The Future of Cities Lies in AI and Smart Urban Design (14/03/2024)
AI's Role in Lottery Predictions: Facts and Insights (13/03/2024)
Augmented Reality in the Beauty and Cosmetics Industry (12/03/2024)
Exploring the Possibilities of Artificial Intelligence in Real Estate (11/03/2024)
The Impact of AI in the Aviation Industry (7/03/2024)
What is augmented reality (AR) and where is it applied? (6/03/2024)
5 Practical NLP Applications to Improve Customer Service (5/03/2024)
Exploring Outer Space with the Help of AI Innovations (4/03/2024)
Latest Advancements in AI Image Generation (1/03/2024)
What are the biggest problems Virtual Reality can solve? (29/02/2024)
Maximising Social Media Insights with Deep Learning Analytics (28/02/2024)
AI in Customer Service: Efficiency and Personalisation (27/02/2024)
Can Machines Make You a Millionaire? AI in Fintech (26/02/2024)
How can artificial intelligence replace virtual assistants? (23/02/2024)
How can smart cities really make a difference? (22/02/2024)
Why is it so hard to create an artificial general intelligence? (21/02/2024)
Banking Beyond Boundaries with AI's Magical Shot (20/02/2024)
What is applied and general artificial intelligence? (19/02/2024)
Innovative AI Solutions for Maritime Transportation Systems (16/02/2024)
Can computers play chess as well as humans? (15/02/2024)
Applications of AI and Deep Learning Solutions by TechnoLynx (13/02/2024)
Why do businesses need Generative AI? (9/02/2024)
Microsoft's AI Journey from Bing to Copilot (8/02/2024)
Use AI to Beat Climate Change Risks for Insurance (6/02/2024)
The Future of Insurance: Exploring the Influence of AI (4/02/2024)
Chrome Gets an AI Makeover: Boost Your Business with Tab Magic (2/02/2024)
AI's Role in Electrical and Mechanical Design (1/02/2024)
How the Food Industry is Reshaped by AI and Edge Computing - on Medium (31/01/2024)
Read more at TechnoLynx Blog!