Monday, February 13, 2012

How to Develop a Chess Program for Dummies

Share/Bookmark


Programming is a simple thing, despite of what you may have heard. However many people feel intimidated by modern computer technology and do not even consider trying to program an application of their own because they are afraid it requires too much knowledge. The truth is that the only things required for you to program is the will to work and learn and a structured way of thinking. No quantum mechanics, no nuclear physics, no relativity theory or advanced mathematics required... Great programmers are people who just like to experiment. Great programmers are people who just try different new things on their computers until they find what "works" (and then have other people treat them as "gods" because they know it). This is the first article of a series of articles showing how to program a full-featured chess program in a modern programming language. Chess programs some of the most complicated applications existing and developing one can be intimidating to many experienced programmers. This article will show that this is NOT the case. The basis for this Programming a Chess Program for Dummies tutorials is the "Huo Chess" program. The final deliverable will be something like the program shown in the following figure.

 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 channes in the Internet. One can dowload it for free from the MSDN Code GalleryCodeplex 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 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 lern! 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 pronciples 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 seach 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 2008 - 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 donwload 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 Developement 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).


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 entailes 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 wll 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.

ou 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 (we will use the XNA Framework, but you don't need to know anything about it at this point). 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 exaple 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 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 funtion 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
          {
               // 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 beggining 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 helo 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 VStudio 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 accomplised.
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!

Related Posts Plugin for WordPress, Blogger...