Develop a (chess) program in Visual Studio 2022 (C# NET 6.0) [Huo Chess example]

Huo Chess DV (GUI Edition)

Interested in chess programming? You are interested in philosophy too! What is thinking? Can AI be conscious? What does it mean to do something? Can the AI understand that it does play chess? Explore the AI related articles in Harmonia Philosophica and understand why you are already a philosopher!

Goal

Some years have passed since the latest major update of Huo Chess. The goal of this article is to catch up with the developments of the latest years and show how an application built in previous versions of the Visual Studio can be ported into Visual Studio 2022. We will also show what is new with the newest .NET 6.0 Platform and what are the implications of the latest developments in the tools provided by Microsoft for building applications with C#. We will use the Huo Chess micro-chess engine published in this site as an example to show all the above in a short and concise way.

Important Notes: The new versions of the Huo Chess application in Visual Studio 2022 C# NET 6.0 are called ‘Huo Chess DV’ (from Huo Chess Delta Version).

Overview

Things in computers evolve over time. In the ‘old days’ we had BASIC. Then we had .NET Framework. Now we have .NET Platform (see also here), the latest weapon in the arsenal of Microsoft that allows developers to develop cross-platform applications with a single framework.

.NET frameworks and libraries (source)

And yes, .NET Platform is not the same with .NET Framework. In fact the latter is almost dead, as its support will soon end, whereas .NET is the latest framework (without the word… Framework in its tile, computer world always finds ways to confuse the uninitiated as alchemy used to do in the old days) you should choose. It has been around for some years now and its latest version is .NET 6.0. The .NET platform contains all the necessary tools, drivers and libraries to allow the modern programmer develop their programs.

And just to add more complexity to the already complex landscape, one needs to know that .NET Framework was initially succeeded by .NET Core. It was only after .NET Core 3.1 that it was decided to name the new framework .NET (without the ‘Core’) and that is what we now have .NET. Net (pun intended). [1] [2] [3].

The new .NET Platform allows for easier development of applications for various platforms, from Android to Mac. Details on how this is done is beyond the limited scope of this article.

The purpose of this article is to show how the open source micro-chess engine of Huo Chess was ported into Visual Studio 2022 and .NET 6.0. The next sections will present the problems and obstacles one might face when using the new platform and how they can be used to minimize the size of the application as much as possible.

Tutorials for building a chess program

There are many available tutorials on how to build a chess program. These are all based on Huo Chess open source code and will come in handy when trying to create your own first program. The logic of the program is explained, the functions used and the way the program thinks.

Tutorials on how to develop a chess program include:

This article only covers the porting of Huo Chess into Visual Studio 2022 and .NET 6.0, so in case you are lacking the basic understanding on how to program a chess application please visit these articles first. In any case, you are more than welcomed to continue reading and use the source code provided below as it is. Many times learning to program entails starting directly to… program. That is how I used to learn programming in Commodore and that is always the best way to start. Learning should always go hand in hand with practice.

After all remember: There is no way to learn without experimenting and making mistakes (but keeping a backups is always useful).

Huo Chess source code

The Huo Chess chess program is an open source micro-chess engine specifically designed for simplicity for educational purposes. One can view the code and easily understand the basic structure of a chess engine using Mini-Max algorithm for its thinking process. Reusing the code is allowed by all means (and even encouraged), as long as the source of the code is cited properly.

You can download the latest files for previous Visual Studio versions via the relative sites:

Download the code from the sites above, open them in your local Visual Studio 2022 and… let the fun begin.

In this article, I will describe how the Visual Studio 2019 Huo Chess based on .NET Framework was ported into Visual Studio 2022 and .NET 6.0. In the process I will describe some changes that were necessary and you will be asked to apply those changes to the program you downloaded yourself.

If you are impatient or find that difficult, you can always download the ported (‘fixed’) program from the last chapter at the end of this article.

First things First: Fixing dpi issues

Modern world is different than the world during the Commodore era in many ways. One of them is higher dpis. A modern program should handle that higher dpi of the screens effectively, otherwise it will look blurry. If you try to compile and run the program you already downloaded, you can see that for yourself.

Huo Chess previous version had an issue with how high-dpi screens were handled, making the UI of the chessboard look blurry without the fix. The changes described below are the changes needed to fix the Huo Chess issues for laptops with high dpi [28].

Please do try to apply those changes yourself in the project you already downloaded and see how they can improve the UI look and feel of the program.

Change 1: The application needs to add a compatibility declaration for Windows 10 in the manifest file:

<compatibility xmlns="urn:schemas-microsoft.com:compatibility.v1">
  <application>
    <!-- Windows 10 compatibility -->
    <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
  </application>
</compatibility>

Note: If you cannot find the manifest, add it to the solution.

Change 2: We also need to enable per-monitor DPI awareness in the solution’s app.config:

<System.Windows.Forms.ApplicationConfigurationSection>
  <add key="DpiAwareness" value="PerMonitorV2" />
</System.Windows.Forms.ApplicationConfigurationSection>  

Note: If you cannot find the app.config of your application read here for more.

With these changes, the application will handle high dpi of a modern screen fine. However you will still have a problem: the pieces in the chessboard will look small. Try to figure out how to fix that yourself (if you are impatient, just download the source files at the end of this article).

Tip: Try to change the zoom option in the pictureBoxes in the chessboard.

Porting in Visual Studio 2022…

The first thing to do when developing a new application is of course to download and open the IDE. So go and get the latest Visual Studio, open it and then load the program of Huo Chess. In that way you will load the application and you will also be able to build it and run it.

However, that will not make your application a .NET application. Instead, the existing (old) .NET Framework will still be used.

In order to make your application an application that utlizes the latest .NET Platform, you must create a new project and select to create…

  • Console C# application .NET for the Huo Chess console application (DO NOT select the .NET Framework console application, this is the old framework) [4] [5]
  • WinForms C# NET application for the Huo Chess GUI application (DO NOT select the .NET Framework console application, this is the old framework) [6]

After you create the applications, ‘all’ you need to do is copy the code of the old Huo Chess applications into the new projects. Do it your self and learn something through that process. You will learn that copying is not as simple as it seems. Some times you will forget times, some other times you will see that the new .NET application needs something additional in order to compile.

Follow the Visual Studio Intellisense suggestions to walk your way through the hurdles.

For example, you might be missing a ‘using’ statement in the beginning of the program for elements of the application. If that happens (and it WILL happen since the structure of the application in the new project is somewhat different that the old one), first take some time to understand the problem.

Consider for example the following example…

The problem seems to be with the StreamWriter that is highlighted accordingly. If you hover over the Intellisense lightbulb on the left, you will see some suggestions on how to fix the problem.

We will follow the first suggestion and simply add the missing ‘using’ directive in the beginning of the program. Essentially we were using the StreamWriter function without adding the relevant reference to the library containing that functionality. By simply adding the reference as below, the program compiled successfully.

Hopefully with some effort (depending on your level) you will be able to transfer Huo Chess from previous Visual Studio versions to the latest Visual Studio 2022.

So let’s move to the next and crucial step: Publishing!

Publishing the application

Once we created the application and successfully compiled it, we need to create the executable of our application that we will share with others when distributing our chess program. That is where the new .NET Platform has many options for publishing to various systems.

We will explore the best possible parameters to use so as to achieve the major goal for Huo Chess when it comes to size. And that is only one thing: Minimum size!

In summary, the following parameters are used:

  • Target framework: Net 6.0 – Windows 7.0
  • Deployment mode: Framework dependent
  • Target runtime: win-x86 for the console application / win-x64 for the winForms application
  • Other details: Set to produce a single file with no manifest

So essentially we are publishing for not the latest version of Windows, but we are using the latest framework .NET 6.0.

The publishing is conducted in Framework Dependent mode, meaning that the publishing will generate the minimum needed size of the application that will expect the host system to contain the .NET framework in order to run. Of course that is logical to expect, since the .NET framework is developed to be shared in as many computers as possible so that developers can use it – the was we used to us Java that was again supposed to be installed everywhere.

If we choose the other option to produce a Self-contained application, Visual Studio will publish a huge-sized application (counting in MBs) that will contain all needed .NET libraries for it to run. Useful to make sure your application will run even in a system without the .NET, but not useful for Huo Chess.

It is also important to select a specific target runtime for the publishing to generate code for that specific runtime. Try choosing other runtimes to see how easy it is and check out what will happen.

Last but not least, we choose to publish one single file. Doing so provides us with the true size of the application. There is no point in choosing to publish in multiple files and ‘fool ourselves’ that our application is small just because we choose to look at the size only of the .exe file in the folder…

Application trimming

Because of the changes brought by .NET, the size of the applications is somewhat (or significantly) increased vis-à-vis previous versions of the .NET Framework. Being modern, flexible and cross-platform has a price after all.

For Huo Chess this means that the console edition is now 159 KB (from 44 KB that it used to be) and the GUI edition is now 239 KB (from 96 KB that it used to be).

In order to fix that problem, Microsoft added functionalities to trim the code and optimize its size. There are many articles for application trimming in the References at the end of this article that you can read [17-20] [22] [23].

One basic thing to do in order to reduce the size of your application is to disable the implicit usings. ‘Implicit usings’ essentially tell the Visual Studio to add additional needed references to your project as it sees fit based on your code. Disabling this and selecting on your own the ‘using’ statements to have (like the one for the IO we added above) is the way to go when you need minimum size.

There is also an option to allow application trimming, however this applies only to specific publishing configurations and not to the ones we have selected above for Huo Chess. The trimming options look something like…

<PublishSingleFile>true</PublishSingleFile>
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>Link</TrimMode>

However as already said, you cannot use the trimming options when publishing in Framework dependent mode. If we had selected to publish a Self-contained application these options would greatly reduce the size of our application.

The following file has a nice comparison of the resulting application sizes for Huo Chess console and GUI applications for various publishing and trimming configurations.

Please refer to the references below for trimming in order to read more on that topic.

Huo Chess for Visual Studio 2022 (C# NET 6.0)

As promised in the beginning, here one can download the latest Huo Chess projects for Visual Studio 2022.

Use these projects to learn how to program, to view them as you are reading the relative tutorials available in Harmonia Philosophica, or simple to experiment with your own ideas on how a chess program should look like! Again, re-using the code is free and encouraged, as long as you properly indicate where you found it!

Keep experimenting! Keep coding! And have fun!

References

  1. What is .NET?
  2. Five Things You Should Know About .NET 5
  3. Introduction to .NET
  4. Difference Between .NET and .NET Core
  5. How To Create EXE For .Net Core Console Application
  6. What is the difference between a Windows Forms App and Windows Forms App (.NET Framework)
  7. What’s the difference between .NET Core, .NET Framework, and Xamarin?
  8. MSBuild reference for .NET SDK projects
  9. Libraries Feature Switches
  10. Implicit global using directives for new C# projects only
  11. using directive
  12. An introduction to NuGet
  13. Install and manage packages in Visual Studio using the NuGet Package Manager
  14. Quickstart: Install and use a package using the dotnet CLI
  15. Package versioning
  16. Dependencies
  17. .NET 5.0 App Trimming and Potential for Future Progress
  18. App Trimming in .NET 5: Reduce Your App Sizes Dramatically
  19. How to reduce .Net Core App Size
  20. Reduce the size of your app in .NET Core 3 and above
  21. Remove Unused References
  22. App Trimming in .NET 5
  23. Trim self-contained deployments and executables
  24. Working with Assemblies and the Global Assembly Cache
  25. How to: Remove an Assembly from the Global Assembly Cache
  26. What’s new in Microsoft .NET 6
  27. c# How do I create a manifest file?
  28. winforms – Font blurry in Windows Forms C#

Ultra-fast programming tutorials: How to develop a C# adventure game in one day (without prior programming experience)

Other Related articles

Introduction

Is programming a game difficult?

Don’t be fooled by the title. Yes it is!

However learning the basic principles of programming and making a very simple game is… simple! And the goal of this article is to show how one can learn programming while having fun in just one day.

Yes, you read that right. One day. Do not expect (of course) to be experts. This goes without saying. But you will learn how to create your first program, which will actually do something. This is how I started programming myself. I had bought (my parents actually) a Commodore 16. And there were no games with it. Just a big manual. In which there were the source code of some games I had to type myself into the computer in order to play them! At first I did not know what I typed. But I typed it anyway. And the game was fun.

Next day, I started learning programming.

Because you see, in order to learn something you must LIKE it first! There is absolutely no point in learning programming just by reading big books with incoherent programming exercises which will at the end result in nothing more than code snippets (parts of code) which do nothing important or useful whatsoever. This is how today’s kids learn to hate programming.

The game we will develop is very small and easy: Just an old-times ultra mini text-adventure. Meaning a game with no graphics, which asks for the users to input text commands (e.g. “Open door”) in order to play it.

Sounds fun?

Well, it is!

And most importantly, it is scalable! You can – at your own pace – make it better, more complex, or even add graphics (there will be a lesson for that too). And make it your own super game that will conquer the world! Or at least your friends and parents. 🙂

No more talk. Let us begin!

Setting up the tools

Download Visual Studio from Microsoft. There is a free edition to download. Install it. Figure out how to do that on your own, it is not difficult really – just like installing any other program, just select for now the default configuration suggested by the program.

What you will need is C# to be installed – because there are other languages also supported by Visual Studio (C++, Visual Basic, F# et cetera).

Create the project

Open Visual studio and create a new C# Console Application project.

When first creating the program, Visual Studio will create a lot of code automatically. Your project will look something like the schema below.

This code is the shell of your program. Do not worry about what it does for now. What you need to remember is that the program has a Main class, inside which you should put your code (see the schema above).

Game scenario

What is the scenario of your adventure?

Let us keep it simple: You are a person who have lost his consciousness and is suddenly found inside a locked room. You want to get out. As simple as that. Your goal is to search the room for the key and unlock the outer door!

What will be the solution of the problem?

Again, let us keep it as simple as possible: You search the room. You see a box. You open the box. There is a key inside it. You take the key. You use the key on the door. The door opens. You get out.

It may sound simple – and it is – but this is the basis of a simple game. Remember! You will have time to improve it later on! The point here is to learn the very basics of programming.

The code

Open the newly created project. Now you need to add the code to actually make your game. We will do this by adding the minimum lines of code to make the game. As said above, you will then be able to add additional code and improve the game. What we will show here is the basic principles.

The game has no graphics, so all we need is a way to get user input through text and then present to the user again the results of his action via text.

For a short description of the basic elements of a program (variables, functions etc) check the Huo chess tutorial here.

In short, what we will need is the following programming elements:

Variables: These are elements of different types which hold values. A variable can be an integer variable (which may hold values like 1, 4, 10), a String variable (which may hold values like “key”, “door” etc) or a variable of many other types. We will use the following variables:

  • A variable to hold the command the user has entered. We will call this user_command.
  • A variable to know whether the user has the key or not in his pocket. We will call the variable user_pocket.
  • A variable to determine whether the game must end. We will call this exit_game.

Input/ Output commands: These are the commands we will use to get input from the user (the commands he will issue to do things in the game) and to inform him of the result of his actions with a text message on the screen. There are three major commands we will use for this:

  • Console.Write: This command writes something on the screen, while leaving the cursor at the same line.
  • Console.WriteLine: This command writes a line on the screen and then presses Enter to position the cursor in the next line.
  • Console.ReadLine: This command reads what the user has entered. We will use this command to get the user input and store it in a variable we will call ‘user_command’. Intuitive isn’t it?

All of the above functions are existing functions in C# to process input and output in a program. The fact that they all start with ‘Console.’ simply means that these functions are part of a class called ‘Console’ – look at the class as a large collection of functions. And yes, this is a very simplistic and – to be honest – technically wrong way of putting it. But it will keep your brain from exploding while giving you some time to read in Google what Console is in C#. (remember to check again the basic tutorial for Developing a chess program here, where I have a short description of what a class and a function is)

Decision commands: The program needs to decide what to do when the user does some things. So for example, when the user enters the command “Open door” it needs to be able to decide whether or not the door will open (if the user has the key it will open, if not it will not). We will use the ‘if’ command to perform this kind of operations. The way this command works is very intuitive. You will see in the code how this happens.

The commands the game will accept are the following:

  • Look around
  • Open box
  • Get key
  • Open door
  • Q will exit the game

Loop commands: We need to make the game constantly ask for user input. So after each command the user enters, the program must process it, inform the user of the result of his action and then go back and again ask for input. We will use a do… while look to perform that. With that, every line of code that is within brackets between the ‘do’ and the ‘while’ commands is constantly executed until the condition in the ‘while’ command is met. You will understand when you see the code.

TIP: Google is your friend. Don’t be shy to use it. If you are not sure how a command works just write it into Google search and find out yourself! Not sure how the ‘if’ command works? Google “C# if command” and there you go! (the C# is always needed in the search if you search for C# – but this is rather a tautology and not an advice)

Writing the code

Are you ready to actually write the code?

Well, don’t worry. I have done that for you. Look at code below and write down the program in your own project’s Main method yourself. Go to the static void Main(string[] args) method and write down the below code inside the brackets.

// Declare the variables
String user_command;
String user_pocket = "";
bool exit_game = false;

// Main program loop
do
{
// Ask for user input
Console.Write("What do you want to do? (press Q to exit) ");
user_command = Console.ReadLine();

// Process user input
if ((user_command == "Open door") && (user_pocket == "") )
Console.WriteLine("Door is locked");
else if (user_command == "Look around")
Console.WriteLine("You see a box on a table");
else if (user_command == "Open box")
Console.WriteLine("There is a key inside");
else if (user_command == "Get key")
{   
     Console.WriteLine("You got the key");
     user_pocket = "key";
}
else if ( (user_command == "Open door") && (user_pocket == "key") )
{
     Console.WriteLine("You opened the door! Bravo!");
     user_pocket = "key";
     exit_game = true;
}
else if (user_command == "Q")
     exit_game = true;
else
     Console.WriteLine("Nothing happens");

Console.WriteLine("");
} while (exit_game == false);

There you go!

A game that you wrote!

Your code should look like that.

Important Notes

  • All C# commands end with a semicolon, as you may have noticed. With some exceptions as may have also noticed.
  • The comments are entered after double slash ( // ). They are usually very useful not only for others but mainly for the programmer himself!

Download the code

Ideally you should write the code on your own, so that you practice. However for reference purposes, you can also download the example below.

The file contains the solution as it was developed for this tutorial.

Executing the program

In order to build your code, select Build > Build solution (or Rebuild solution , after you have built it for the first time).

In order to run your program, select Debug > Start without debugging.

The result should look something like this…

That is, if you are smart enough to find the key…

Epilogue

Like when I copied the code from my first Commodore computer manual, you may not know exactly what you write and why. But with what you have read above, you will certainly understand the meaning of the commands and what they do!

You now have a game that you wrote. And potentially a gate to the world of programming. At the end, it is not up to me to teach you anything. It is up to you to learn. As Buddhism says, when the student wants, the teacher appears. I am not your teacher. But I may have instilled in you the desire to search for one…

Happy coding!

APPENDIX – Jurassic Park Adventure Game

When I was a kid, I developed an adventure called “Jussaric Park” based on the known book of Michael Crichton. It was (and still is) a simple yet fun to play text-based adventure writen in QBasic.

You can download the code from below and use your favorite QBasic IDE to view, edit and execute it. The QB64 is a good choice for that.

The user must set the speed when starting the game
Yeap, it is mine!
Graphics are nice… Wait till you hear the crickets…
It’s all Greek to you.
The main screen of the game where you can select the commands
Walk command: Press ‘w’ and simply write where you want to go!
Using the JUPASE (JUrassic PArk Software Emulator)
1 / 6
You made it! You got out of Jurrasic Park!

You can find the code below. Simply copy-paste it into a QBasic editor and execute. The IOURASIO file is the main game. The JUPASE program is called when you reach the Visitors’ Center.

As already mentioned, it is writen in QBasic and it is a playable and enjoyable (at least for those not addicted to ultra-fast 3D graphics) text-based game. It has comments inside the code to help you understand what happens and how it works, so essentially it is an extension of the tutorial you just read.

Note: You will have to update the path in the JUPASE call. (See? Even when having fun, you can alway learn something!)

Have fun!

And keep coding!

Huo Chess (C# micro chess)

Huo Chess DV – GUI edition

Interested in chess programming? You are interested in philosophy too! What is thinking? Can AI be conscious? What does it mean to do something? Can the AI understand that it does play chess? Explore the AI related articles in Harmonia Philosophica and understand why you are already a philosopher!

Latest versions

  • In .NET Framework: Huo Chess 0.9922
  • In .NET: Huo Chess DV [2021-11-10]

Huo Chess News

  • 2021-11-10: Ported Huo Chess in Visual Studio 2022 (C# .NET 6.0) to create the latest Huo Chess DV version. The equivalent version in .NET Framework is the v0.9922 version.
  • 2021-04-07: Re-optimization of CountScore (evaluation of position) function for endgames regarding the pawns evaluation.
  • 2021-04-03: Optimized the CountScore (evaluation of position) function for endgames. Huo Chess v0.9921 beat bot at Chess.com with 1100 ELO rating.
  • 2021-03-20: Added the castling capability also for the computer (up to now, the program only recognize and allowed the castling move for the human opponent).
  • 2021-03-14: Thinking in level 4 and 5 is conducted only if the moves entail the capturing of a piece. Removed redundant code. Improved CountScore function with positional elements for the ending of the game. Introduced the elements of mate and stalemate in the thinking process.
  • 2021-01-06: Fixed initialization of nodes 3 and 4.
  • 2020-09-03: Minor updates.
  • 2020-08-10: Updated the countScore function that evaluates positions to include also qualitative criteria for the position.
  • 2020-08-03: Minor updates to the v0.992 Developers Edition. The trimming rules have been updated to enable deeper thinking.
  • 2019-02-21: The v0.992 has received initial operational capability. The algorithm now works for thinking depth of 5 half-moves, with thinking tree trimming applied.
  • 2019-02-12: Huo Chess version 0.991 published. Now the algorithm performs as planned. Thinking depth limited to 3 half-moves.

Huo Chess Overview

The Huo Chess is one of the smallest open source chess programs in C# (the latest .NET console version is only 159 KB is size, even though it utilizes the latest .NET Platform; while the latest version in .NET Framework is only 44 KB in size). It has heavily commented source code so that it can be used for teaching purposes on how to develop a chess program (or a program in general). It can be easily reused in other applications, e.g. to use it as a chess engine for a robot playing chess (see here).

Feel free to re-use it as you see fit (including changing it or selling it), as long as the source is cited properly. The goal is to spread the knowledge on the basics of chess programming, so sharing is important. Feel free also to contribute to the project, by contacting Harmonia Philosophica with ideas or code that can be used.

Huo Chess sites

You can download the latest files via the relative sites:

Alternatively you can download it below.

Important Notes: The latest version of Huo Chess that is still in development is available only in this site and in GitHub repository. The CodeProject and the MSDN sites still have the v0.992 version.

Huo Chess-based tutorials

Over the years I have written several tutorials on how to develop a chess program based on the Huo Chess.

Tutorials on how to develop a chess program include:

LATEST VERSIONS

DV Version highlights

The latest Huo Chess DV (Delta Version) editions are built in the latest Visual Studio 2022 and use the latest C# .NET 6.0 platform. Remember: along with having the goal of being the smallest chess program for educational purposes, the goal is also to constantly follow all developments in the programming landscape so as to stay relevant!

However being modern and flexible has a price. The new platform had a significant impact on the size of the Huo Chess application: Even after all optimizations, the console edition is now 159 KB (from 44 KB that it used to be) and the GUI edition is now 239 KB (from 96 KB that it used to be). Hopefully the application trimming in the new .NET platform will be improved in the future so these numbers can do down.

Read the Develop a (chess) program in Visual Studio 2022 (C# NET 6.0) article to see how the Huo Chess program was ported into Visual Studio 2022 and .NET 6.0, along with some details on the publishing and trimming settings of the application.

Version 0.9922 highlights

The version 0.9922 is the latest .NET Framework version, i.e. the equivalent to the latest DV Version in .NET. This version has only minor updates regarding logs when compared to v0.9921.

OLDER VERSIONS

Version 0.9921 highlights

The new version of Huo Chess (v0.9921) is even smaller in size than all the previous ones and yet much more capable. This was made possible by optimizing code and removing redundant code as well. The official edition with Windows Forms user interface is 77 KB in size (as opposed to 78 KB of the previous version), the Console application with a chessboard User Interface (UI) edition is 45 KB (as opposed to the 46 KB of version v0.992) and the Console application with text-based chessboard UI edition is 44 KB in size (whereas the previous version was 46 KB in size).

The new version has an updated evaluation function (CountScore) for the endgame, it has improved code for the castling move and also has an optimized deep thinking mechanism.

Huo Chess v0.9921 editions

  • Huo Chess 0.9921 with GUI: This version is the main version with a Windows Forms chessboard User Interface.
  • Huo Chess 0.9921 cs: Console application (text only).
  • Huo Chess 0.9921 cs with graphics: Console application, with minimum text-graphics to depict the chessboard.
  • Huo Chess 0.9921 Developers version: Full developers version with Windows Forms chessboard and logs to show the thinking mechanism. (Attention: Remember to delete the logs when needed, since their size can increase significantly)

Version 0.992 highlights

The v0.992 version of Huo Chess is small in size (as all the previous ones) and much more capable. The official edition with Windows Forms user interface is 78 KB in size, the Console application with a chessboard User Interface (UI) edition is 46 KB and the Console application with text-based chessboard UI edition is 46 KB in size.

Issues with the MiniMax thinking algorithm are fixed and now the computer makes logical moves in every circumstance (at least for the depth of 5 half-moves in which it thinks). Capability of thinking at depth of more half-moves will be added in the future. The program also features an Opening book capability (must have positions in the “Opening Book” folder to use it).

Additional to the above, a Developers Edition has been created, which includes analytic logs of the thinking mechanism for debugging (for teaching purposes). The logs can be easily activated or deactivated. This edition also takes a small step towards showing the variant which the computer thinks to the user interface.

The Opening Book editor is distributed separately. Along with the editor, a library of some sample opening book positions is also included in the distribution files.

Huo Chess editions

There are various Huo Chess editions, each one with slightly different User Interface, plus one for developing purposes.

For the latest Huo Chess DV (Delta Version) there are currently two editions:

  • Huo Chess DV console: The console edition supporting opening functionality and up to 5-ply thinking. Currently using C# .NET 6.0 and standing at 159 KB.
  • Huo Chess DV: The GUI edition supporting opening functionality and up to 5-ply thinking. It also contains logs that can be activated to analyze and debug the thinking algorithm. Currently using C# .NET 6.0 and standing at 239 KB.

Both editions have heavily commented code to allow for using the open source chess engine for educational purposes.

Future versions candidate improvements

There is already a list of potential improvements for the next version of Huo Chess, that can be found below:

  • Add castling capability for the computer to also be able to castle. Also castling should be embedded in the CountScore function.
  • Reduce size by improving ‘peripheral’ functions (like CheckForBlackMate, ElegxosNomimotitas et cetera).
  • Increase efficiency of MiniMax algorithm, by taking into account the average score of each branch. (code already in place, but commented out)
  • Add neural network capability: This will be achieved at a very primitive level by having key points of the MiniMax algorithm (the inequalities at each node level analysis in ComputerMove) being dependent of values stored in external configuration files and by updating those files every time a game is played (increase ‘score’ if the game is a win, decrease if it resulted in defeat). This is still in preliminary stage, but I will try to have a relative Developer edition ready in the next version (without compromising the size).
  • Improve CountScore function, to take into account the position of the chessboard, whether you move the same piece twice in the opening et cetera.

Huo Chess DV distribution files (latest .NET version)

The Huo Chess DV version is the version developed in Visual Studio 2022 and utilizing C# .NET 6.0.

These versions are expected to be updated frequently as the .NET Platform is also updated. Needless to say that these editions render the v0.9921 version the last version utilizing the .NET Framework.

Huo Chess v0.9922 distribution files (latest .NET Framework version)

The version 0.9922 of Huo Chess is the latest version available in .NET Framework. It is the equivalent of the DV version but in the .NET Framework.

Huo Chess v0.9921 distribution files

The version 0.9921 of Huo Chess is currently in development. Take a look at the progress of the project exclusively here at Harmonia Philosophica or directly in the GitHub repository. The code is updated frequently.

HUO CHESS 0.9921 with GUI – Developers edition 2021-04-03 (GitHub)

Note that this is a draft version which is still under development. Also please remember to delete the logs after some moves, or disable them completely if you want to play a full game. The size of the logs of the Developers edition can increase significantly after only some moves.

Di mi se mai fu fatta alcuna cosa
(Tell me if anything was ever done to completion)

~ Leonardo da Vinci

Huo Chess v0.992 distribution files

The version 0.992 of Huo Chess is in development. Take a look at the progress of the project exclusively here at Harmonia Philosophica! The code is updated frequently.

All the files of the v0.992 can be found below. Make sure you download the latest one. The previous versions are kept for historical reference purposes. Also at the end feel free to download the latest v0.9921 version that is still in development

This version is the officially stable version that can also be found in the GitHub repository and the official sites (like CodeProject) which host the Huo Chess code.

Huo Chess v0.991 distribution files

Distribution files for the Huo Chess v0.991 version include the following:

  • Huo Chess 0.992 with GUI
  • Huo Chess 0.992 cs
  • Huo Chess 0.992 cs with graphics
  • Huo Chess 0.992 Developers version
  • Opening Book editor
  • Opening Book

Feel free to contact me for anything regarding the code or the project in general. Remember that the goal is not only to create the smallest chess program but also to create a good basis for educational purposes.

Huo Chess Opening Editor

From the beginning of the Huo Chess project (well, almost from the beginning), an opening functionality was developed. The opening book of Huo Chess is edited with the help of a dedicated tool: the Huo Chess Opening Editor. Simply run the tool, play the moves by selecting “Opening mode” and all the moves will be stored as suggested moves for the computer in its opening book.

There is a C++ (cpp) and a C# (cs) version of the tool, which can be both downloaded below.

The tools generate txt files which hold the positions of the opening book, along with the suggested moves for each position. Note that there must exist a ‘Huo Chess Opening Book‘ folder in the same folder as the application for the latter to store the opening book files.

Make sure you keep checking back in this page for more updates.

Huo Chess Java edition

The Java edition of Huo Chess is also developed in parallel with the C# versions. Currently, only the core engine with text interface with the user is developed in Java. Anyone willing to provide a GUI is more than welcome to do so. (I will try to do that as soon as I have time)

This code can be the basis for an Android Huo Chess application. I am currently working with Visual Studio and Xamarin framework to build it.

Huo Chess QBasic edition

The Huo Chess has been written in QBasic as well. Yes, you read it right! The old friend from the past, BASIC, is still alive and kicking!

You can find the code below. Along with the games’ source code, an opening editor is also distributed. Both work in the same way the C# edition works.

Feel free to write to me for any comments or suggestions.

Instead of epilogue…

The ultimate goal is to go back to where I begun programming and fulfill my child dream: to create a chess program for Commodore 128. The porting of the current Huo Chess version to QBasic is currently in progress and then the road to porting to Commodore BASIC v7.0 is open…

And remember: Huo Chess was not made to be completed. But exactly the opposite: It is here to remind us all the constant struggle to perfection. A struggle so vain as any other human struggle and yet, a struggle so familiar and lovely.

Huo Chess will constantly be upgraded…

By me… By you… By everyone…

And year by year it will constantly be better and smaller…

Until there is nothing left…

Because at the end, the best chess game I will ever play will be that game I played as a child, with my father, trying to learn how to play…

APPENDIX – Huo Chess games

This appendix contains various games played by Huo Chess over the years.

Game 1: Huo Chess v0.9921 vs. Jimmy bot (600 ELO rated) at Chess.com

Huo Chess v0.992 vs. Jimmy Bot @ Chess.com [2021-03-21]

[Site “Chess.com”]
[Date “2021.03.21”]
[Round “?”]
[White “Huo_Chess”]
[Black “Jimmy”]
[Result “1-0”]
[TimeControl “-“]

1. g4 g5 2. Nc3 d5 3. Bh3 Nc6 4. Nf3 h6 5. d4 Qd6 6. Be3 b6 7. Bd2 Nb4 8. Nb5 Qd7 9. Nxa7 Rxa7 10. Bxb4 Nf6 11. Ba3 Ba6 12. c3 Bc4 13. Ne5 Qb5 14. Bg2 Ra4 15. e3 Qa5 16. b4 Ba6 17. bxa5 Rxa5 18. Bb2 Bg7 19. Qf3 Bb7 20. c4 h5 21. gxh5 Ra7 cxd5 Ra6 23. e4 Bh6 24. Bc1 Ra4 25. Be3 O-O 26. Kd1 Ba6 27. Nc6 Kh7 28. Nxe7 Ra5 29. Qxf6 Bd3 30. Nf5 Kg8 31. Nxh6+ Kh7 32. Bxg5 Raa8 33. Nxf7 Rxf7 34. Qxf7+ Kh8 35. Bf6# 1-0 

The game resulted in Huo Chess easily beating the bot within 35 moves.

Game 2: Huo Chess v0.9921 vs. Jimmy bot (600 ELO rated) at Chess.com

Huo Chess v0.992 vs. Jimmy Bot @ Chess.com [2021-03-22]

[Event “vs Computer”]
[Site “Chess.com”]
[Date “2021.03.22”]
[Round “?”]
[White “Huo_Chess”]
[Black “Jimmy”]
[Result “1-0”]
[TimeControl “-“]

1. g4 g5 2. Nc3 e5 3. e4 Ne7 4. Nf3 f6 5. Bb5 Ng8 6. Ba4 Nh6 7. d4 a6 8. dxe5 c6 9. exf6 Kf7 10. Nxg5+ Kg6 11. Ne6 Rg8 12. Nxd8 d6 13. Bxh6 Kxh6 14. Nf7+ Kg6 15. Nxd6 b5 16. Bb3 Bxd6 17. Bxg8 Bc5 18. Qf3 h6 19. Ne2 Bb6 20. Nc1 Bd8 21. c4 Bxf6 22. cxb5 cxb5 23. e5 Bxg4 24. Qxa8 Bxe5 25. Qe4+ Kf6 26. Qxg4 Ke7 27. Qe6+ Kd8 28. Qxe5 Nd7 29. Qd6 h5 30. Be6 Kc8 31. Qxd7+ Kb8 32. Qe8+ Kc7 33. Qxh5 Kb7 34. Bd5+ Ka7 35. Nb3 Kb8 36. Rd1 Kc7 37. Qg6 a5 38. Nxa5 b4 39. Qg4 Kb6 40. Qxb4+ Ka6 41. Nb3 Ka7 42. Qb7# 1-0

Game 3: Huo Chess v0.9921 vs Sven bot @ Chess.com (1100 ELO rated)

[Event “vs Computer”]
[Site “Chess.com”]
[Date “2021.03.26”]
[Round “?”]
[White “Huo_Chess”]
[Black “Sven”]
[Result “1/2-1/2”]
[TimeControl “-“]

Huo Chess v0.9921 vs Sven (1100) [2021-03-26]
1. g4 g6 2. Nc3 d5 3. Bh3 c6 4. d4 Nf6 5. Be3 h6 6. Bd2 Na6 7. Nf3 Nb8 8. Bf4 Nxg4 9. Rg1 h5 10. e4 Be6 11. exd5 cxd5 12. Ng5 Bh6 13. Nxe6 fxe6 14. Bxb8 Rxb8 15. Rh1 Bg7 16. Rb1 Qb6 17. Qd3 Rh6 18. Qd2 Ra8 19. Na4 Qd6 20. Nc5 b5 21. Nb7 Qa6 22. Nc5 Qd6 23. Nb7 Qa6 24. Nc5 Qxa2 25. Rd1 Qc4 26. b3 Qxd4 27. Qxd4 Bxd4 28. Rxd4 e5 29. Rxd5 b4 30. c4 Rh8 31. Ke2 Rh6 32. Kf1 Rh7 33. Ke1 Rf7 34. Nd3 Rg7 35. Nxb4 Kf7 36. Nc6 Kg8 37. Nxe5 Nh6 38. c5 g5 39. Nf3 Kh7 40. Nxg5+ Kg6 41. Ne6 Kf7 42. Nxg7 h4 43. Nh5 Ng8 44. Rd4 Rb8 45. b4 a5 46. bxa5 Rb1+ 47. Rd1 Rb7 48. c6 Rb8 49. Rd4 Rb2 50. Rxh4 e5 51. c7 Rc2 52. c8=Q Rxc8 53. Bxc8 Ke7 54. Ba6 Kd7 55. Re4 Ke6 56. f4 Kf5 57. Rxe5+ Kg6 58. Bd3+ Kf7 59. Bc4+ Kf8 60. Rf5+ Ke7 61. Bxg8 Kd7 62. Rd5+ Kc8 63. Rd1 Kb8 64. Ra1 Kc8 65. f5 Kc7 66. Rd1 Kc8 67. Rd2 Kb7 68. Rd8 Kc7 69. Rd1 Kc8 70. Ra1 Kc7 71. f6 Kd8 72. f7 Ke7 73. Rd1 Ke6 74. Rb1 Ke7 75. Ra1 Kf8 76. Nf4 Kg7 77. Nd3 Kf8 78. Nb2 Ke7 79. Rd1 Ke6 80. Na4 Ke7 81. Nb2 Ke6 82. Ra1 Ke7 83. Na4 Kf8 84. Nb6 Ke7 85. Rd1 Kf8 86. Na4 Ke7 87. Nb2 1/2-1/2

Game 4: Huo Chess v0.9921 vs Sven bot @ Chess.com (1100 ELO rated)

[Event “vs Computer”]
[Site “Chess.com”]
[Date “2021.04.02”]
[Round “?”]
[White “Huo_Chess”]
[Black “Sven”]
[Result “1-0”]
[TimeControl “-“]

Huo Chess v0.9921 vs Sven (1100) [2021-04-02]
1. g4 c6 2. Nc3 h6 3. d4 g6 4. Be3 Qc7 5. Qd2 Bg7 6. Bf4 Qd8 7. e4 Kf8 8. Bc4 Ke8 9. Nge2 Qb6 10. Na4 Qd8 11. Nc5 b6 12. Nb3 d6 13. Rg1 Kf8 14. h4 Qe8 15. Nbc1 Bd7 16. Nd3 a5 17. c3 h5 18. g5 a4 19. Qc1 b5 20. Bxb5 Ra5 21. Bc4 Bg4 22. b4 Ra8 23. Ng3 Qd8 24. Nf1 Bd7 25. Qa3 Bg4 26. Nb2 Rh7 27. Nxa4 Na6 28. Bxa6 Qc7 29. Nb2 Bh3 30. Nd2 Be6 31. Qa4 Ke8 32. Nd1 Qb6 33. b5 Bf8 34. Rh1 Bc8 35. Nc4 Qc7 36. b6 Rxa6 37. Nxd6+ exd6 38. Qxa6 Be7 39. Qa8 Qd7 40. Qb8 Kf8 41. c4 Qd8 42. b7 Bxb7 43. Qxb7 Ke8 44. Qxc6+ Kf8 45. Qa6 Qd7 46. Qa8+ Bd8 47. Qa3 Be7 48. Qa6 Qd8 49. Nb2 Qc7 50. Qa3 Qb6 51. Qa8+ Kg7 52. Rb1 Qxd4 53. Ke2 Qb6 54. Qd5 Rh8 55. Na4 Qc7 56. Ra1 Qc8 57. Qd4+ Kh7 58. Bxd6 Qe6 59. Bb8 Qc6 60. Be5 Ba3 61. Bxh8 Bf8 62. Nb2 Qc7 63. Nd1 Qe7 64. Nc3 Qc7 65. Nb5 Qb7 66. Na7 Qa8 67. Be5 Bb4 68. Rab1 Ba3 69. Rb8 Qxe4+ 70. Qxe4 Bc5 71. Nc6 Ba3 72. Rb7 Nh6 73. Qd3 Ng4 74. Qxa3 Nxf2 75. Rxf7+ Kg8 76. Qf8# 1-0 

Game 5: Huo Chess v0.9921 vs. Sven bot @ Chess.com (1100 ELO rating)

[Event “vs Computer”]
[Site “Chess.com”]
[Date “2021.04.07”]
[Round “?”]
[White “Huo_Chess”]
[Black “Sven”]
[Result “1-0”]
[TimeControl “-“]

1. g4 d5 2. Bg2 Be6 3. Nc3 c5 4. e3 Qd6 5. Qf3 Nf6 6. Bh3 b6 7. Nge2 a6 8. d3 Qe5 9. Nf4 g6 10. d4 cxd4 11. Na4 Nbd7 12. Rb1 Rg8 13. Bd2 b5 14. Nd3 Qe4 15. Qxe4 dxe4 16. Nac5 Nxc5 17. Nxc5 Bxa2 18. Ra1 dxe3 19. Bxe3 Nd7 20. Rxa2 Rd8 21. Rxa6 Nb8 22. Ra5 Nc6 23. Rxb5 Ne5 24. Nxe4 f6 25. Bb6 Ra8 26. Ra5 Rb8 27. Ra6 Bh6 28. Bc7 Rb7 29. Ra8+ Kf7 30. Rxg8 Rxc7 31. Rh8 Rxc2 32. Rxh7+ Bg7 33. Rf1 Rc6 34. Nc3 Rb6 35. Na4 Re6 36. g5 Rc6 37. Rg1 Nf3+ 38. Kf1 f5 39. Rg2 Kg8 40. Rg3 Nd4 41. Rh4 Rc2 42. b4 Be5 43. Re3 Rc1+ 44. Kg2 Nc6 45. Rh6 Bg7 46. Rxg6 Kh8 47. b5 f4 48. Re4 Nd4 49. b6 e5 50. Nb2 Kh7 51. Rd6 Nb3 52. Nc4 Ra1 53. Bf5+ Kg8 54. Nxe5 Nc5 55. Rd8+ Bf8 56. Rxf4 Kg7 57. Ng6 Ra4 58. Rf3 Be7 59. Nxe7 Rh4 60. Rd5 Ne4 61. Rd4 Nxg5 62. Rxh4 Kf7 63. Re3 Kf8 64. Re5 Kf7 65. b7 Nf3 66. Kxf3 Kf8 67. b8=Q+ Kg7 68. Qa8 Kf6 69. Qh8+ Kf7 70. Rh7# 1-0
Huo Chess v0.9921 vs Sven (1100) [2021-04-07]

More games to be uploaded soon with stronger opponents!

How to code a chess program in one day. (C# and Java examples)

Interested in chess programming? You are interested in philosophy too! What is thinking? Can AI be conscious? What does it mean to do something? Can the AI understand that it does play chess? Explore the AI related articles in Harmonia Philosophica and understand why you are already a philosopher!

Introduction

Coding is easy.

Today there are a lot of people learning how to do it.

Why not you?

And you know what is the most difficult step in learning how to code?

TO START LEARNING.

You know there is an old Buddhist saying claiming that “When the student wants, the teacher appears”. So the question is not whether there are tutorials out there to teach you. There are a lot. Here or elsewhere, you can easily find articles showing how to code.

The question is: Are you willing enough?

(And yes, Harmonia Philosophica is mainly a philosophy portal, so feel free to read about philosophy while trying to debug your first chess program)

For this ultra quick training I will use a Java edition of my Huo Chess program. This edition lacks basic functionalities like deep searching, but it can however play chess according to the rules and choose the best move at the current position based on which move earns the most material.

Places to download Huo Chess (source code and executable)

License: You can reuse the code you see here in any way you want, as long as you mention the author and the place where you read it first!

RELATED TUTORIALS:How to program a chess program for Beginners” series will give you a more detailed description of how to create your chess program! Check also the Programming for kids: Developing a chess program in BASIC and the Programming a chess application in QBasic (QB64) tutorials for developing a chess program in BASIC programming language. Check out also the “How to develop an adventure game ultra-fast tutorial” tutorial! You could also find interesting the HUO Writer: A simple AI writer with basic Neural Network capabilities (QB64) article. The How to develop a chess program from scratch (for total beginners) series will help you develop a chess program even though you are a total beginner! Check also our affiliate chess-programming portal!

千里之行,始於足下

(A journey of a thousand miles begins with a single step)

~ Lao Tzu, Tao Te Ching

Step 1: Get a programming interface

This tutorial will show you how to code a demo chess program in one day, even without any prior knowledge of programming. All you need is a programming interface to write and compile (i.e. make an executable program out of your code) the code that you will write. These are also known as Programming IDEs (Integrated Development Interfaces). This could be the Microsoft Visual Studio (the Express edition of which can be downloaded for free) for C# or any Java compiling studio available out there (like NetBeans for example, which again can be downloaded for free).

The tutorial will not cover the details on how to use these programming interfaces. But this is not something hard to learn anyway. Just go to the web (or the page of the tool itself) and you will gain an understanding on how to write a small console program (this is what we are going to do here) in less than an hour. When I refer to a console program I mean a program which does not have graphics but only displays text. We will start with building such a program since writing code for graphics will surely need an additional effort to learn how to do it. And it will be easy to later on add graphics to your program, once you have the AI logic of the chess engine up and ready, don’t you think?

Open the IDE and select to create a new project…
Select to create a simple application…
Your program is created. All you have to do is add the code…

Tools to use for coding your program

  • Microsoft Visual Studio (free edition)
  • Java NetBeans

After you download the IDE, install it in your computer and go to the option New Project. Select to create a simple C# console application (in Visual Studio) or a simple Java program (in NetBeans). Click Create and there you are. You have the shell in which you will add your chess program code!

Step 2: Design the chess program structure

Let’s go into the chess program now.

But wait!

Don’t we need to learn the programming language first?

The answer is simple: NO!

You will learn them as you go.

This is how I (and many others) learned programming in the first place. I opened my Commodore computer and started typing my first program by copying the code from the manual. After I typed it in and spent time to get it right (even copying can be difficult, especially if you are a rookie) I typed RUN and I had my first game! Forget the long chapters of books trying to teach you – after reading 100 pages – how to just print “Hello world” on a screen. Programming is for people who like experimenting and are not afraid to simply start trying things on their machine.

So just go ahead!

You will read here about the basic structure needed for the program, and then you will see the commands required to code that structure into a C# or Java program. The commands are fairly simple and you will understand what they do as you write the program. Do you really need a programming language manual to understand what an “if” command does anyway?

The main structure of the program is depicted in the following schema.

Fairly simple isn’t it?

The story goes like this…

  1. You get input from the user for his move. [EnterMove function]
  2. You check the legality and the validity of the move entered [ElegxosNomimotitas and ElegxosOrthotitas functions, which also utilize the CheckForWhiteCheck and CheckForBlackCheck functions to check if there is a check in the position]
  3. If the move is legal and valid, then do the move. [call drawPosition function to redraw the chessboard; note that the Java edition of the program only prints the chessboard in text]
    • Exercise for you: Add graphics to the application. (use the C# edition ot get some insight on how you could do that)
  4. Call the function which makes the computer think. [ComputerMove function]
  5. Scan the chessboard to find all the pieces of the computer. In the sample code provided for Java, this means that it scans for all the black pieces since the program is made only for the computer to play with black.
    • Exercise for you: Add the ability for the program to play with white as well)
  6. For each piece of the computer, check all possible moves to all possible squares of the chessboard.
  7. If you find a valid move (by invoking the ElegxosNomimotitas and ElegxosOrthotitas functions) then do the move and count the score of the position. [CountScore function: This is one of the most central functions of the program; changing it makes the computer play differently according to the values you assign to pieces or to elements of the chessboard like empty ranks, concentration of the pieces at the center et cetera]
  8. If the score of the move is better than the so far better score, then store this position as the best one. (Note: The program stores the first position analyzed as ‘best’ anyway, so that there is a starting point for the best score)
    • Exercise for you: Change the values in the CountScore function to improve the playing abilities of the computer)
  9. Do the best move found and redraw the chessboard.
  10. Wait for next user input. [call EnterMove function again]

The Java edition of the program does not think in more depth. It just finds the move which earns the more material and makes it. This is not chess isn’t it? Well actually it is. The basis for a good chess program. All you have to do is improve it.

Look at the C# version of “Huo Chess” (search the web for it, there are many repositories where I have uploaded the code, including MSDN Library, CodePlex and Codeproject) to gain a small insight on how the chess program can search into more depth.

Exercise for you: Make the Java edition of the program to think in more depths, by adding more “ComputerMove”-like functions to analyze the next potential moves for the human and the computer. Be careful how you pass over the chessboard between these functions. (yes, Google will be your best friend)

Related resources for C# Huo Chess edition

Step 3 : Write the code

This last section contains the source code of the chess program in Java.

As mentioned above, look for “C# Huo Chess” in the web (See the Recourse listed above) to see the full source code of that Huo Chess edition. This code is also heavily commented to make it easy to read and re-use, while the names of the functions are the same as in the Java edition of the program.

Look also at the “How to program a chess program for Beginners” series here in Harmonia Philosophica, to get some more details on the Huo Chess program. (the tools used in those articles are a bit outdated, but yet the logic is still the same)

Paste that code into the main java file in your NetBeans project and compile it.

Execute your program and enjoy your new chess game.

Epilogue

So there it is. Depending on your copy-paste and reading comprehension skills, you now have a working chess program on your hands and some knowledge on how it could be improved. Everything is up to you now.

Happy coding!

And don’t forget: Keep experimenting!

The worst thing that could happen?

To just ruin your computer…

How to Develop a Chess Program for Beginners

This series of tutorials for dummies will show how one can develop a chess playing program in C# from scratch with no prior knowledge of programming. It will guide the reader step-by-step until the final building of a fully-features chess application in Microsoft Visual Studio. The tutorial is based on the open source Huo Chess software developed by me.

Interested in chess programming? You are interested in philosophy too! What is thinking? Can AI be conscious? What does it mean to do something? Can the AI understand that it does play chess? Explore the AI related articles in Harmonia Philosophica and understand why you are already a philosopher!

Other Related articles

Huo Chess – The program we will code…

Huo Chess is one of the smallest open source chess applications. It is an application that I have personally developed and distribute as fully open source via many channels in the Internet. One can download it for free from the MSDN Code Gallery, Codeplex Huo Chess site or its Codeproject page. In the series I will analyze how one can program the computer to play chess. The final “deliverable” will be the full Huo Chess program as it can be found in the Internet.

Note: An intermediate/ advanced programmer can go directly to the above links and download the Huo Chess source code so as to study it directly. Please contact me for any questions on the code or the algorithm either via email (skakos@hotmail.com) or via comments in this article (Knol). However, even though the source code of my chess is heavily commented, starting looking directly at the full program source code without first reading the lessons I have posted here at Google Knol is not advised for beginner programmers.

Method of teaching

The method I will use for teaching you how to program is by example. The “try to do something and see what happens” may sound like a bad method, but it is actually the best when it comes to computers programming. As long as you have kept a backup of all your valuable files, you must and should try anything with programming if you really want to learn! That is why I will show practical steps you need to follow and I will guide you through every stage of the programming process, without first giving a 100-page lecture on the theory or the basic principles of programming. You will be taught the theory you need to know as we progress through the steps of building the chess game. That method is the method actually used by programmers in the 1980’s. We used to experiment with new things, try new techniques and learn from our mistakes. There is no better way of learning than experimenting and doing mistakes. You will never learn from something you did right in the first place!

The language of choice is C# and the tool we are going to use the Microsoft Visual Studio. However please note that I have created and distributed versions of the “Huo Chess” also in C++ and in Visual Basic. Feel free to search for the free source code in the Internet (I am now trying to create a Commodore version).

Getting started

The first thing you need, is the tool with which you will program. You can download the Microsoft Visual Studio – Express Edition from the respective Microsoft Visual Studio Express Edition site. The “Express” editions of MS Visual Studio are completely free to download and they include all the programming tools and features a novice, intermediate or even an advanced programmer needs. After you download it, installing it is what is keeping you from programming your first game application!

Installing Visual Studio

After you have downloaded the MS Visual Studio – Express Edition, you will have to install it. Installing the Visual Studio is no more complex than the installation of any other program.

You just double-click the file you downloaded and the installation will automatically begin. Normally, the setup will install the Microsoft .NET Framework if it isn’t already installed in your computer (the .NET Framework is required for the Visual Studio to operate – Huo Chess requires .NET Framework 2.0 or above to work) and the Visual Studio. An icon with the characteristic sign of the Visual Studio will appear in your desktop.

Using Visual Studio

Double-click the icon of the Microsoft Visual Studio to begin programming. The Integrated Development Environment (IDE) of the Visual Studio will appear and you are now ready to make your application.

Create a new project

First you need to create a new project. Go to the menu and click File > New > Project.

From there you must choose the language in which you will develop your program. We will write our chess in C# so we must select Visual C# > Windows > Console Application (later we will show how we can also program the same game in C++ or other languages). To create a chess program with a user interface you would need to choose to create a new Windows Forms application. (that would be easy after you have created the code to play chess)

A console application is an application with no graphics. We will start developing our chess game Artificial Intelligence engine as a console application in the beginning and afterwards, when the computer can think and play chess, we will add graphics (that will be the final step in this programming tutorial series). Name the new project “Huo Chess tutorial” and press OK. Visual Studio will do its work and create all the initial things required for you to start developing.

The project is by default saved in a folder with the name you specified, that resides in the My Documents/Visual Studio folder.

Start developing

After you have created your project, you can start programming. The window will initially look like this.

That is a good point to say some things about programming. Programming in one of the modern languages of today entails using three elements:

  • Variables
  • Functions
  • Classes

All programming uses these three elements and if you master them properly then you can do everything. I will try to explain these elements in summary in the lines below.

Variables

The variables used in a program are the elements which store values, that are used in the program. Variables come in many types depending on the type of data they will be used for. For example you can declare an integer variable to store integer values, or a float variable to store numbers with a decimal segment, or a String variable to store text.

The first variable we will use in our program in the variable which will store the color of the human player in the game. In particular, after the human player starts our game he/she should choose the colour with which he (excuse me ladies for using the “he” instead of the “he/she”, but I am a man so I am used to it) will play.

We will declare our variable in the class program by entering the code public static String m_PlayerColor; as seen in the following figure.

Some clarifications are needed here: Every command in C# must end with semicolon (;). Secondly, we declared the variable as public which in short means that it will be visible from every part of our program (the opposite, private variables can be accessed only inside the function/class we declare them in). The static keyword should not concern you at the time (it actually means that only one instance of the variable can be created as the program executes, but we will have more on that later on the tutorial series).

You can then define the value of that variable by hard-coding it in your program. Try to enter m_PlayerColor = “Black”; in the Main function of your program and then print it to screen with the command Console.WriteLine(m_PlayerColor); as seen in the next figure (in fact I have added a Writeline command more as you can see).

Compile the program

The first thing you must do when programming a change in your program is to save your work. Select File > Save All… to save all the changes you made. After you have saved the program, you may want to execute it in order to see what you have done. Before a program is executed, it must first be compiled. Compiling a program means converting the programming language file you just saved to a form readable by the machine (i.e. machine language, which is comprised of 010101’s). Select Build -> Build solution to do that as illustrated in the following figure. If you have followed the steps above, no errors will exist and the compiler will notify you that the solution was successfully built.

Then select Debug > Start without debugging (or simply press Ctrl + F5) to start/ execute your program. The following will show.

You have just created your first program which includes declaring a variable and printing it to screen.

Note about the graphics

The graphics of the chessboard will be added at the final stage of the project. Right now we will focus on developing the chess engine algorithm which is the most difficult part. That is why we started by developing a console application (i.e. an application without graphics). We will worry about the graphics after we have created a fully functional chess AI engine.

Let us now say some things more about functions and classes as promised.

Functions

Functions are code segments which require some input to perform a specific action and produce a specific result. For example you can have a function that adds two numbers called Add_numbers. The code for that function will look something like that (you do not have to code anything in your Huo Chess project now, this is just for theory education purposes):

int Add_numbers(int Number1, int Number2)

int Add_numbers(int Number1, int Number2)

{
      int Result;
      Result = Number1 + Number2;
      return Result;
} 

The code is simple and intuitive, isn’t it? The “int” in the beginning declares that this function will return an integer number as the result of the process it implements. The two integer variables in parenthesis declare the input required for the function to work. That is why when you need to call that function you should call it in a way like the one listed below:

int myAddResult;
myAddResult = Add_numbers(5, 6); 

The above code calls the function Add_numbers by giving it the input of number 5 and 6. The result will be the function to return the value of 11 (= 5 + 6) which we have allocated to variable myAddResult.

Object Oriented Programming

Functions and variables can be used in creating objects. These objects are called classes and are the cornerstone of the Object Oriented Programming (OOP) you may have heard many times before.

Classes

But how do you create and use objects? First, you have to declare the class of the object. For example, if you want to create an object called ‘Blue Calculator’, you must first create and declare a class of objects called Calculator. Define the parameters of that class: the variables it will be using (i.e. the color of the calculator, the numbers which the user will enter in the calculator by pressing the buttons + the result that the calculator will print on its screen) and the methods (or functions) that the calculator will utilize in order to reach the result (i.e. functions for adding numbers, subtracting number etc).

The definition of that class will have the following scheme (independent of what the programming language you use may be):

class Calculator

 class Calculator
          {
               // Variables
               Number_type number1;
               Number_type number2;
               Number_type Result;
               Color_Type Calculator_Color;
               // Methods
               Function Add(number1, number2)
               {
                    Print “The result is:”, (number1 + number2);
               }
               Function Sutract(number1, number2)
               {
                    Print “The result is:”, (number1 – number2);
               }
          } // End of class definition 

The two slash (//) text are comments. Whatever you write after these slashes is not taken into account by the compiler. It is considered best practice to write comments in your code.

After you have properly declared your class of objects, you can create as many objects of that class you like and use them in your program. For example you can create a new blue color calculator by writing a command that could look something like that:

Calculator my_calculator = new Calculator(Blue);

You can then use the member-variables and member-functions of the calculator with commands like:

Integer no1 = 2;
Integer no2 = 7;
Print “Result = ”, my_calculator(Add(no1, no2));
// this should print ‘9’ in the screen
my_calculator.number1 = 20;
Print “Result = ”, my_calculator(Add(my_calculator.number1, no2));          // this should print ‘27’ in the screen

The specific commands again depend on the programming language you use, but you get the meaning. It is all too easy: Declare class => Create new object of that class => Manipulate / define parameters of the new object => Use member functions of that object to generate the result they are designed to generate.

It may be difficult for you to grasp, but ALL programming in ANY language (C++, C#, Visual Basic, Java etc) are based on that logic. What is more, the languages themselves have some ready-made classes that you can use to develop your programs! For example, Visual C++ and C# in the Microsoft Visual Studio has a stored class for Buttons. To add a button to your application, you just write:

Button my_button = new Button();
my_button.color = Blue; 

You don’t have to reinvent the wheel! That simple (and I think you understand what the second command does, without telling you…)! I keep repeating myself, in order for you to stop fearing the unknown realm of programming and just…start programming! The ready-made classes (or even simple functions) are usually stored in packets called ‘libraries’. Add the library you want in your program and them just use any class/ function it contains.

Classes you already use without knowing it

You may think that all the above have nothing to do with the code you just wrote. But you would be wrong. Your program, even at this initial stage, uses many classes without you knowing it! Actually Microsoft has developed some classes that facilitate programming for Windows and you are using these classes with the “using” statements in the beginning of your code. You do not have to know more details about that now, just be aware that you can program your chess because someone else have already developed and implemented a great number of classes in order to help you do that.

A good example of classes you already use if the Console command you wrote in order to print the player’s color. Remember that the command looked something like that:

Console.WriteLine(m_PlayerColor);

The above code actually uses the class Console and calls one of its member-functions: the WriteLine function (that is why the dot is required: to call members of classes as we said above). That functions requires input: the text that you want to display. That is what we write in the parenthesis!

Intellisense

The Visual Studio has embedded features that help you know which are the members of the various classes and how to use them. So when you write “Console” and then enter a dot, the Intellisense of Visual Studio produces a list with all available member variables and functions of that class. You will find yourself more comfortable with the use of Visual Studio and C# only after you have tried to use many of the functions appearing in that list on your own and see what happens. Remember, experimenting and doing mistakes is the only way to learn!

Get user input

In a similar way to printing something to the screen, you can get user input. You will find that very useful when you want the user to enter his/her move for the chess game. In this point, we will require the user to enter his color of choice by using a function similar to Writeline: the Readline. See the figure below on how that can be accomplished.

The code is simple and straightforward. You print instructions to the screen and then read the input from the user. When the user presses “Enter”, the value he entered is allocated to the m_PlayerColor variable which is then printed on the screen.

Next lesson

In the next lesson we will learn how to instantiate the chess board, build the Artificial Intelligence engine of the program and the program’s user interface structure. Until then, try to enter the following code in the program:

 if (m_PlayerColor == “Black”)
               Console.WriteLine(“My first move is: e2 -> e4”);
          else
               Console.WriteLine(“Please enter your first move!”);

Save, compile and run the program. You will see that if the player enters “Black” the program “plays” a first move! Well, actually this is not the way we will use to develop our AI (using “if” statements is not the way to make the machine think), but what I want to note and emphasize here is the simplicity of programming in general. All you need is will to learn!!!

What we have accomplished

In this first lesson, we have accomplished many things which are listed below:

  • Created our first project in MS Visual Studio.
  • Learned how to save, compile and execute the project via Visual Studio.
  • Learned how to print text on the screen.
  • Learned how to use variables and read user input from the user.
  • Gave a look at our first code structure command (“if” command).
  • Learned about functions and classes.
  • Understood the basics of Object Oriented Programming.

Until the next time, happy coding and experimenting!

How to Develop a Chess Series updates

  • Update 2009-06-04: Due to other obligations the next lesson is not going to be published as soon as I expected to. However I am in the process of writting it and it WILL be published as soon as I can.
  • Update 2009-07-30: The new lesson of the series is now published
  • Update 2011-09-29: The third lesson with the chess algorithm analysis is now published!
  • Update 2018-12-02: Refreshed the article. Fixed minor mistakes.
  • Update 2020-03-21: Minor updates and fixes.
Exit mobile version
%%footer%%