How to Develop a Chess Program for Beginners

Related articles

e3062ae1-7433-445c-a652-58dd979c837d
Huo Chess – The program we will use

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.

39 responses to “How to Develop a Chess Program for Beginners”

  1. Are you happy with page views to your knol portfolio? — A Survey.Do we as authors need to do something?Results will be reported in http://knol.google.com/k/narayana-rao-k-v-s-s/knol-author-news-september-2010/2utb2lsm2k7a/2910?collectionId=2utb2lsm2k7a.2981#and in a separate Knol.Regards

    Like

  2. Wonderful Tuto. — Dear Spiros,This is amazing. My son is very fond of this, hope this tutorial will help him to understand more on this line. Oh! good the second session also is available now, thanks spiros for your effort keep it up. I am saving it.BestPhilips

    Like

    1. Untitled — Thanks Ariel!

      Like

  3. Great work — I always wanted to write a chess program myself. Although I am a doctor by profession, I love computer programming. I once made a replica of “Paranoid” in pascal. Waiting for your next lesson !Hope this wins the “How-to contest”. All the best

    Like

    1. Untitled — The second lesson in the series is now available at http://knol.google.com/k/spiros-kakos/how-to-develop-a-chess-program-for/2jszrulazj6wq/41#.

      Like

    2. Untitled — Thanks a lot for the comments! I will post the next lesson soon. In the meantime please let me know if you have any problems or questions. I will be happy to answer them.

      Like

  4. very good — i have write a p about it http://www.fromxian.com

    Like

    1. Untitled — The second lesson in the series is now available at http://knol.google.com/k/spiros-kakos/how-to-develop-a-chess-program-for/2jszrulazj6wq/41#.

      Like

    2. Untitled — Thanks!

      Like

  5. Thanks for the info — Thank you for all the info and knowledge that you posted and shared here. That rocks.Sat Nam, ~(-_-)~Piper

    Like

    1. Untitled — The second lesson in the series is now available at http://knol.google.com/k/spiros-kakos/how-to-develop-a-chess-program-for/2jszrulazj6wq/41#.

      Like

    2. Untitled — Thanks! I will post more in the next lesson…

      Like

  6. Excellent Lesson! — I love this, I just found out about Knol, and this is just what I need to get over my intimidation of Microsoft’s VS!

    Like

    1. Untitled — The second lesson in the series is now available at http://knol.google.com/k/spiros-kakos/how-to-develop-a-chess-program-for/2jszrulazj6wq/41#.

      Like

    2. Untitled — Thanks! Next lesson will be posted soon!

      Like

  7. Im Stuck!!! — im really interested in trying this, But i cant get the ‘Microsoft Visual Studio Express Edition’ downloaded, everytime i click on download, i get that… Internet Explorer cannot display the webpage Not Cool :(Please tell me where, or how i can download itThanks

    Like

    1. Untitled — The second lesson in the series is now available at http://knol.google.com/k/spiros-kakos/how-to-develop-a-chess-program-for/2jszrulazj6wq/41#.

      Like

    2. Untitled — cool, ive been reading up on c# alot, and wow, this stuff i complicated, can u recommend other projects i can start trying out?

      Like

    3. Untitled — Great! Next lesson will be probably released within the next month (depending on my time schedule).

      Like

    4. Untitled — i did it :OCant wait for next lesson!

      Like

    5. Untitled — Please tell me which link you use so that I can test it or give you another one.

      Like

    6. Untitled — Does your IE has problems in general or only with that site? Are you attempting to download from http://www.microsoft.com/Express/ ? Usually problems with the IE can be fixed if you open it and update it (open the Internet Explorer and try Tools => Windows Update). If this does not work, you can always download Firefox (at http://www.mozilla.com/firefox/) or Opera or Chrome. One of them should do the job. Tell me if you made it.

      Like

  8. I’m voting for this knol, too — Along with The Price of Liberty (by yours truly) and Earth At The Center of the Universe? by you. Keep up the good work!

    Like

    1. Untitled — The second lesson in the series is now available at http://knol.google.com/k/spiros-kakos/how-to-develop-a-chess-program-for/2jszrulazj6wq/41#.

      Like

  9. Lesson 2 is now available — Dear all,The second lesson in the series is now available at http://knol.google.com/k/spiros-kakos/how-to-develop-a-chess-program-for/2jszrulazj6wq/41#.

    Like

  10. […] also at the “How to program a chess program for dummies” series here in Harmonia Philosophica, to get some more details on the Huo Chess program. […]

    Like

  11. […] How to develop a chess program for dummies series […]

    Like

  12. […] learning programming. So we will use it here. (Not in the mood for BASIC? Search for the Java and C# relevant tutorials in Harmonia […]

    Like

  13. […] learning programming. So we will use it here. (Not in the mood for BASIC? Search for the Java and C# relevant tutorials in Harmonia […]

    Like

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

    Like

  15. […] How to Develop a Chess Program for Dummies […]

    Like

  16. […] How to develop a chess program for dummies series […]

    Like

  17. […] How to Develop a Chess Program for Dummies […]

    Like

  18. […] How to develop a chess program for dummies series […]

    Like

  19. […] How to Develop a Chess program for Dummies Series. […]

    Like