Showing posts with label chess. Show all posts
Showing posts with label chess. Show all posts

Saturday, March 15, 2014

Philosophy Wire: Chess, ants, goals...


Philosophy Wire by Spiros Kakos [2014-03-15]: Ants solving chess problems! [1] Or so it seems. You see even the most efficient complicated system must have goals set. By someone...

(c) Philosophy WIRES - Commenting world news from philosophy's perspective…

Monday, February 13, 2012

How to Develop a Chess Program for Dummies 3

Introduction

This lesson will describe the Artificial Intelligence algorithm that one has to implement in order to have the chess program play chess.

How to read this lesson

In order to understand what is mentioned in this lesson, you must have downloaded the latest version of Huo Chess (currently v0.93). You should have the MS Visual Studio open with Huo Chess, while you read so that you can understand the article. Please contact me for any issues or questions at skakos@hotmail.com.
Places to download Huo Chess (source code and executable):

The article that follows can also be found in the Codeproject site of Huo Chess.

I. Chess Algorithm Analysis

The algorithm used in this program for the implementation of the computer thinking is the MiniMax algorithm for the latest version (C# 0.93) and the "Brute Force Algorithm" for the older C++ / VB / C# version. Huo Chess plays with the material in mind, while its code has some hints of positional strategic playing embedded (e.g. it is good to have your Knights closer to the center of the chessboard in the beginning). More analytically: When the program starts thinking, it scans the chessboard to find where its pieces are (see ComputerMove function) and then tries all possible moves it can make. It analyzes these moves up to the thinking depth I have defined (via the ComputerMove => ComputerMove2 => ComputerMove3 => ComputerMove4 => ComputerMove5 path), measures the score (see CountScore function) of the final position reached from all possible move variants and – finally – chooses the move that leads to the most promising (from a score point of view) position (ComputerMove function).

C# v0.93 Kakos-Minimax algorithm summary



A high-level example of the progress of the main algorithm for versions 0.84 and older is as follows:
  1. ComputerMove: Scans the chessboard and makes all possible moves
  2. CheckMove: Checks the legality and correctness of these possible moves
  3. (if thinking depth not reached) => call HumanMove
  4. HumanMove: Checks and finds the best answer of the human opponent
  5. ComputerMove2: Scans the chessboard and makes all possible moves at the next thinking level
  6. CheckMove: Checks the legality and correctness of these possible moves
  7. (if thinking depth not reached) => call HumanMove
  8. HumanMove: Checks and finds all possible answers of the human opponent (Note: Previous (v0.84 and older) versions found only the best answer of the human opponent (by finding with which move the human earns more)
  9. ComputerMove4 /ComputerMove6 / ... ComputerMove20: Scans the chessboard and makes all possible moves at the next thinking level
  10. CheckMove: Checks the legality and correctness of these possible moves
  11. (if thinking depth reached) => record the score of the final position in the Nodes of the MiniMax algorithm
  12. The algorithm continues until all possible moves are scanned
  13. The MiniMax algorithm is finally used to calculate the best move via the analysis of the thinking tree Nodes
You can SET huo_debug to TRUE to see live the progress of the computer thought while the computer thinks. Just press a key to move step-by-step into the Huo Chess inner mechanism… You can also uncomment the code lines that record the time the program requires to think its move, so as to have an idea of the time required by the processor to complete the thinking process.



II. Huo Chess Thought Flow (v0.93 Simple-Minimax algorithm)

Below, I analyze the thought flow of the chess program. I will describe only the main steps and code segments, so as to show the way the computer scans the chessboard, conducts all possible moves and finally finds the better one. The function names appear in bold, i.e. ComputerMove - Start indicates the beginning of the ComputerMove() function. Be aware that some code segments may be slightly different from the code in the distributed ZIP file since I continuously change the program. As it appears, the "constant beta" state is the trend nowadays. ComputerMove – Start When the computer thinking starts, the first thing to do is to initialize all the variables and store the initial chessboard position in an array.

// store the initial position in the chessboard 
for (int iii1 = 0; iii1 <= 7; iii1++)
{
    for (int jjj1 = 0; jjj1 <= 7; jjj1++)
    {
        Skakiera_Thinking_init[(iii1), (jjj1)] = Skakiera_Thinking[iii1, jjj1];
    }
}

Call: CheckMove

ComputerMove – Dangerous Squares filter

The program then scans the chessboard and analyzes it in order to find the Dangerous Squares. These squares are the squares where the computer cannot move its pieces to, since they are protected by pieces of the other side. These Dangerous Squares analysis is conducted for every level of thinking and serves as a “filter”, so as to reduce the number of moves analyzed (this helps to the program speed) and make sure both sides do not “make” stupid moves.
DangerousSquares(Skakiera_Thinking, "ComputerMove0", m_PlayerColor);

ComputerMove – Main Thinking
  • Scan the chessboard ® find any possible move (MoveFilter makes a pre-scanning of valid moves so as to increase the thinking speed).
  • Make the move temporarily
(Versions 0.82 and earlier called CheckHumanMove to find the move of the human which wins more material – However newer versions analyze all possible moves of the human with MiniMax algorithm)
  • Call ComputerMove2 [Chessboard with the move analyzed applied, is passed over as an argument]
ComputerMove_2(Skakiera_Thinking);

CheckHumanMove2 / CheckHumanMove 3 / CheckHumanMove 4...

Deeper thinking is implemented by respective thinking functions. Each one has as input the chessboard array from the previous one.

CountScore

Every move score is measured (if the move is legal and correct). These scores are stored in the NodesAnalysis array (see below). The scoring function is the heart of the program. It currently takes into account mainly material values, with some positional considerations for the opening phase of the game (i.e. if Move < 11 it is not good to move your Queen or else a small “scoring penalty” is imposed). The optimization of that function is key to the increasing of the computer play strength.

Thinking Depth - End

When we have reached the thinking depth (i.e. when we have reached the ComputerMove function which we have defined as the last one in the chain of analysis), we store the chessboard scores of the thinking tree nodes for every thinking depth level (applies for version 0.93 and newer). These nodes are then going to be used in the MiniMax algorithm to find the best move.

// Record the node in the Nodes Analysis array (to use with MiniMax algorithm)
NodesAnalysis[NodeLevel_1_count, 1, 0] = Temp_Score_Human_before_2;
NodesAnalysis[NodeLevel_2_count, 2, 0] = Temp_Score_Human_after_2;
NodesAnalysis[NodeLevel_3_count, 3, 0] = Temp_Score_Human_before_4;
NodesAnalysis[NodeLevel_4_count, 4, 0] = Temp_Score_Human_after_4;
NodesAnalysis[NodeLevel_5_count, 5, 0] = Temp_Score_Human_before_6;
NodesAnalysis[NodeLevel_6_count, 6, 0] = Temp_Score_Human_after_6;
For every node, we also store the number of the parent node:
// Store the parents (number of the node of the upper level)
NodesAnalysis[NodeLevel_1_count, 1, 1] = 0;
NodesAnalysis[NodeLevel_2_count, 2, 1] = NodeLevel_1_count;
NodesAnalysis[NodeLevel_3_count, 3, 1] = NodeLevel_2_count;
NodesAnalysis[NodeLevel_4_count, 4, 1] = NodeLevel_3_count;
NodesAnalysis[NodeLevel_5_count, 5, 1] = NodeLevel_4_count;

MiniMax algorithm

This is required for the MiniMax algorithm implementation (see http://en.wikipedia.org/wiki/Minimax on how this algorithm works): We start from the lower level nodes and go up to the beginning of the tree, like in the schema that follows:

 

Suppose the game being played only has a maximum of two possible moves per player each turn. The algorithm generates the tree shown in the figure above, where the circles represent the moves of the computer AI running the algorithm (maximizing player), and squares represent the moves of the human opponent (minimizing player). For the example’s needs, the tree is limited to a look-ahead of 4 moves. The algorithm evaluates each leaf node using the CountScore evaluation functions, obtaining the values shown. The moves where the maximizing player wins are assigned with positive infinity, while the moves that lead to a win of the minimizing player are assigned with negative infinity (this is again for illustration purposes only – infinity will not happen in the game as it is currently developed). At level 3, the algorithm will choose, for each node, the smallest of the child node values, and assign it to that same node (e.g. the node on the left will choose the minimum between "10" and "+8", therefore assigning the value "10" to itself). The next step, in level 2, consists of choosing for each node the largest of the child node values. Once again, the values are assigned to each parent node. The algorithm continues evaluating the maximum and minimum values of the child nodes alternately until it reaches the root node, where it chooses the move with the largest value (represented in the figure with a blue arrow). This is the move that the player should make in order to minimize the maximum possible loss. In order for the program to calculate the best move, a number of “for loops” are applied so as to make the abovementioned backwards computation possible.

for (counter7 = 1; counter7 <= NodeLevel_7_count; counter7++)
{ for (counter8 = 1; counter8 <= NodeLevel_8_count; counter8++)
{ if (NodesAnalysis[counter8, 8, 1] == counter7)
{ if (counter8 == 1)
                        NodesAnalysis[counter7, 7, 0] = NodesAnalysis[counter8, 8, 0];
                    if (counter8 > 1)
                        if (NodesAnalysis[counter8, 8, 0] < NodesAnalysis[counter7, 7, 0]) NodesAnalysis[counter7, 7, 0] = NodesAnalysis[counter8, 8, 0];
 }
}
}

After the algorithm has reached the root node, the move with the best score is selected. ComputerMove[Maximum thinking depth] – End

III. Huo Chess Thought Flow (v0.93 Kakos-Minimax)

In this section, I analyze the thinking algorithm for version 0.93 (Kakos-Minimax edition) or for versions 0.84 and older. Below, I illustrate the step-by-step process of the computer's thought for a thinking depth of 2. Let's see the "step" boxes to understand the way the program is structured. Scenario Details
  • Computer Level: Maitre (ThinkingDepth = 2)
ComputerMove - Start

Step 1

START

Move_Analyzed = 0

1. If the first time called -> store initial chessboard position.
2. if( Move_Analyzed >Thinking_Depth )
3. Stop_Analyzing = true;
4. if( Stop_Analyzing = false)
5. Scan chessboard. for iii, jjj
6. Scan chessboard, find a piece of the HY , conduct move, check correctness and legality of move, and if all is OK, then call CheckMove to measure the score of the move.

Call: CheckMove CheckMove - Start
  1. Number of moves analyzed ++.
  2. Check correctness and legality of move.
  3. Check if there is a mate on the chessboard.
  4. If the move is correct and legal, then do it.
  5. Check if there is a pawn to be promoted.
  6. Store move to ***_HY variables because, after many calls of ComputerMove and CheckMove functions, the initial values of the move analyzed will be lost.
  7. If this is the first move analyzed, then record it as the correct "best" move, no matter how bad it is.
Step 2

IF result: FALSE Move_Analyzed = 0
  1. if(Move_Analyzed = Thinking_Depth)
  2. Measure the score of the move and record it as "best" move if it is larger than the score of the so-far best move score.
Step 3

IF result: TRUE Move_Analyzed = 1
  1. if (Move_Analyzed < Thinking_Depth)
HumanMove - Start [HumanMove_Template for v0.93]

Step 4

Find the best answer of the Human (Move_Analyzed = 1). Version 0.93: Find ALL possible human moves
  • Scan the chessboard -> find any possible move.
  • Call CheckHumanMove. [redundant in v0.93]
Store the chessboard score before and after the human move.

CheckHumanMove - Start

voidCheckHumanMove(array<String^, 2>^ CMSkakiera_Human_Thinking)
Count the score of the move and record it as "best" if its score is better than the so-far best move.

In v0.93 and newer: Record the score before and after the human opponents makes his move. Those scores are recorded in the Nodes Analysis array and will be used for the MiniMax algorithm at the end (to evaluate the best move).

CheckHumanMove - End

Conduct the best move of the human [conduct all possible human moves in v0.93].

Move_Analyzed = Move_Analyzed + 1; Who_Is_Analyzed = "HY";
for(i = 0; i <= 7;i++)
{
    for(j = 0; j <= 7; j++)
    {
        Skakiera_Move_After[(i),(j)]=Skakiera_Human_Thinking[(i),(j)];
    }
}

Step 5

Move_Analyzed = 2

Step 6

CALL next ComputerMove function for next-level move analysis.

Move_Analyzed = 2 if(Move_Analyzed == 2)
this->ComputerMove2(Skakiera_Move_After);
else if(Move_Analyzed == 4)
this->ComputerMove4(Skakiera_Move_After);
else if(Move_Analyzed == 6)
this->ComputerMove6(Skakiera_Move_After);
else if( Move_Analyzed == 8 )
this->ComputerMove8(Skakiera_Move_After);
// Call ComputerMove2 to find the best next move of the HY (deeper thinking)

Step 7

Scan the chessboard and find the best move for the computer.

Move_Analyzed = 2 voidComputerMove2(array<STRING^, />^ Skakiera_Thinking_2)
{
// Same as…ComputerMove if(Move_Analyzed has not reached thinking depth) {
// Same as…ComputerMove: Call CheckMove -> HumanMove -> next ComputerMove etc
// (If we haven't reached the desired level of analysis, then the HumanMove
// will be called again, then again the ComputerMove function etc.)
}

Step 8

Return to a previous ComputerMove (i.e. ComputerMove4 calls ComputerMove2) function to continue the analysis. Move_Analyzed = 2 (at the end of the analysis this variable will be equal to 0, see Step 9).

// Return to the ComputerMove function of the 'previous' thinking
// level to continue the analysis
Move_Analyzed = Move_Analyzed - 2;
Who_Is_Analyzed = "HY";
for(i = 0; i <= 7; i++)
{
    for(j = 0; j <= 7; j++)
    {
        Skakiera_Thinking[i,j] = Skakiera_Move_0[i,j];
    }
}
ComputerMove2 - End HumanMove - End CheckMove - End
// close for iii, jjj loop// close if( Stop_Analyzing = false ) segment

If no legal move is found -> we have MATE!

Step 9

Version 0.93: Apply the MiniMax algorithm to reach to the best move. Play the move with the highest score. Now it is the Human's turn to play.

if (move_analyzed==0){
  1. Check if it is good to conduct castling.
  2. "Redraw" the chessboard with the best move found.
  3. Move the rook next to the king, if castling occurred.
  4. Check if a pawn is promoted (at the current version computer always promotes a pawn to queen).
  5. Now it is the turn of the other player (human) to play!
}
else
{
    Move_Analyzed = Move_Analyzed - 2;
    Who_Is_Analyzed = "HY";
    for(i = 0; i <= 7; i++)
    {
        for(j = 0; j <= 7;j++)
        {
            Skakiera_Thinking[i,j] = Skakiera_Move_0[i,j];
        }
    }
}
ComputerMove – End

Other resources

One can find the same article published in Codeproject at http://www.codeproject.com/KB/game/cpp_microchess.aspx. Next Lessons In the next lesson, I will analyze a little bit more the MiniMax algorithm.

How to Develop a Chess Program for Dummies 2


In the previous (first) lesson we learned about how to create a new project in Microsoft Visual Studio environment. We also learned the basics about object oriented programming - i.e. variables, functions and classes. I demonstrated how one can get user input from the keyboard and store it in a variable, how to create new functions and how to create new classes.

 Huo Chess - The program we will code
In this second lesson we will learn how to develop the game's structure (i.e. the loop structure that reads/waits for user input) and the chess engine of our chess program (i.e. the Artificial Intelligence of the application). We will set the starting position of the chessboard, get user input for the human opponent's move and then start scanning the chessboard to find the best possible move. We will also show how to use the debugging mode to help us look inside the mechanism of the program and how it works.

Method of Teaching

The method of teaching will be as follows: I will analyze in small chapters every aspect of the full chess program, explain in simple words its purpose and how it works and I will show a characteristic part of the C# source code that implement it. With all that you will be able to go to the respective function which implements that aspect in "Huo Chess" and understand how it works in high level.
In that way after this lesson you will be able to read the whole source code of the complete Huo Chess game and at least be able to understand how it works and what every command in it does. Hopefully much more than you ever imagined to do after just two lessons...!!! This will give you access to the depth of programming as no other tutorial is able to give you. You will not spend weeks after weeks so as to understand how to write a "Hello World" program, but you will be able to experiment on your own and test your own hypothesis on the real "thing".The commands used in the program are simple and you shouldn't have a problem with them. I mostly use "if" and "for" commands, which we have analyzed in the previous lesson. Don't hesitate to contact me for any clarifications you may need. However you must understand that this lesson will not explain how every function works in full detail. This is the subject of lessons to come. A program like that is complicated and even though you may understand what a function does in general and know all the commands used, you may not be able to grasp the full detail at this stage you are now. Patience is the only good advice I can give you...

Important Note - Learning material

In order to follow the lesson you must download the Huo Chess application source code. You can download it for free from Codeplex at http://huochess.codeplex.com/ (the downloaded file contains all versions of Huo Chess, so be sure you use the C# version - it is tagged as 'cs' version in the folder you download) or from MSDN at http://code.msdn.microsoft.com/cshuochess.
In every chapter below I will note explicitly which Huo Chess part is the part I am describing. Look for the "Huo Chess Point" tag to find where in the Huo Chess source code is the thing we talk about.

Our progress so far

The program we have developed so far justs initiates a screen and asks the user to enter his/her preferred colour. In this lesson I will demonstrate how to build on the knowledge earned inthe previous lessons and develop a complete and fully functional game application.

The main program loop

Any game has a main loop which continually "looks" for user input. In case the user presses a key (or in our case, makes a move), it does "something" (in our case it thinks for the best move to make). You have to program that never-ending loop on your own. In our case we will design a never-ending loop that will continuously check for user input and call the computer chess engine in case the user enters a move. When the user enters a move, the program will stop from checking for input and start thinking its answer. As soon as the computers stops thinking and makes a move in the chessboard, the application will once again start waiting for new user input. The code will be as simple as that:

bool exit = false;
do { 
[check for user input]
if user enters move 
{ [check user move validity] 
[if move entered is valid => call computer chess engine to answer] 
[if move entered is not valid => prompt for error and do nothing!] 

}while(exit == false);

What does that code do? It is based on a do...while loop which continues to loop until the condition inside the parenthesis next to "while" is set to false. It is a rather intuitve set of commands. Until the condition in the "while" (at the bottom of the code segment) becomes true, the set of commands inside the do...while block will continue to execute. So practically the program will continually be in that loop and will exit only when the user enters a move (we will see in details how that is performed).

Huo Chess Point: You can see the respective loop in Huo Chess at the Main(string[] args) function. The Main function of a C# program is the funtion which is loaded when the program starts. So this is the best place to enter that loop which reads user input.

Setting the chessboard

In order for the game to begin, we must set up the chessboard. The best way to store the chessboard into memory is by using a new kind of variable called "array". You can visualize an array as a "table" of values. An array can have as many dimentions as we wish. As you may have thought already, in our chess program we need a 2-dimentions table that will represent the chessboard.The two dimensions array which the program uses as a virtual representation of the chessboard is declared with the following command:

public static String[,] Skakiera = new String[8,8];

We then use function Starting_position()to fill in that table with the values of the chess pieces. The values are quire straightforward. I enter "White Rook" to represent a white rook, "Black Bishop" to represent a black bishop and so on. In order to note a move (either from the human player of from the computer) you just have to change the initial chessboard square value and the destination chessboard square value.Huo Chess Point: You can see the source code which sets the chessboard starting position in the Starting_position() function.

Human plays a move
When the human enters a move, this move is recorded in the following way:

////////////////////////////
// Human enters his move
////////////////////////////
Console.WriteLine("");
Console.Write("Starting column (A to H)...");
m_StartingColumn = Console.ReadLine().ToUpper();
Console.Write("Starting rank (1 to 8).....");
m_StartingRank = Int32.Parse(Console.ReadLine());
Console.Write("Finishing column (A to H)...");
m_FinishingColumn = Console.ReadLine().ToUpper();
Console.Write("Finishing rank (1 to 8).....");
m_FinishingRank = Int32.Parse(Console.ReadLine());
// show the move entered
String huoMove = String.Concat("Your move: ", m_StartingColumn, m_StartingRank.ToString(), " -> " ); huoMove = String.Concat( huoMove, m_FinishingColumn, m_FinishingRank.ToString() );
Console.WriteLine( huoMove );

We use the ReadLine command to read user input from the keyboard. The input (in this case the move parameters) is stored in the variable we will enter in the left side of the operation in the command. The .ToUpper();function converts the text entered by the user to uppercase letters. This is required because we have only uppercase letters in some "if" statements later in the program.We then use the WriteLine commandto show that move on the screen, as a verification that it has been entered and processed by the program.In summary, the program uses the following variables:
  • Variable MovingPiece records the piece that is being moved.
  • Variable StartingColumn records the column of the starting square
  • Variable StartingRank records the rank of the starting square
  • Variable FinishingColumn records the column of the destination square
  • Variable FinishingRank records the rank of the destination square
These variables are then used in the validation checks (see next chapter). Huo Chess point: Look at the Enter_move()function to see how the program stores the parameters of the move the human player enters.

How to use Debug Mode - Part 1

You can have a look at how the program stores values in the abovementioned variables by debugging the program. Debugging is the process of analyzing how the program actually works while it is executed, so as to fix any possible bugs. In order to do that you must follow the following steps:

1. Set Breakpoints: Breakpoints are points in the program where you want the debugger to stop execution and let you see what is happening inside your code. You usually set breakpoints at places you expect to have errors or at places you want to examine more closely if they work correctly. Go to line 461 and left-click on the margin at the left of the code window to set a breakpoint as in the following figure.

Set a new breakpoint by clicking on the left margin of the source code window [click on image to enlarge]

2. Run the application in debugging mode: Start the program in debugging mode by pressing F5.



3. The application will execute. Choose white colour as human and enter a move. The program will start flling in the values of the move you entered in the respective variables we mentioned. Because you have a breakpoint it will stop executing exactly after it has stored these values. You will then see the code screen on your monitor.


4. You can now see the values stored in each of these variables and understand more on how the program works. Just hover with your mouse above the name of the variables in the source code window and you will see the value attached to each variable! Easy huh?

See values stored in variables during debugging by hovering over the variable [click on image to enlarge]


Press F5 to continue executing the program or choose Stop Debugging to exit debugging mode.

Human move validation checks

When the human player enters his/her move the computer must first check of the move is valid. The program makes two kind of validation checks for a move:1. Checks the legality of the move(this is performed by the ElegxosNomimotitas function - where 'Elegxos' stands for 'Check' in Greek and 'Nomimotita' stands for 'Legality' in Greek): This check is related to the kind of move performed. A bishop can move only in diagonals, so if the human player attempts to move a bishop in a horizontal way, the move is not "legal".2. Checks the correctness of the move (this is performed by the ElegxosOrthotitas function - where 'Elegxos' stands for 'Check' in Greek and 'Orthotita' stands for 'Correctness' in Greek): If the player attempts to move a piece to a square that is already taken by another piece of the same colour, then the move is not "correct". In the same way, if the player attempts to move to a square but another piece exsts in the way towards that square, then the move again is not "correct".We will analyze how these functions work in the next lesson. They are rather "simple" functions that use only the "if" and the "for" commands. For now, just consider them as "black boxes" which you can feed with the variables mentioned above and they return a true-false value that you can use to determine legality and correctness of move. The program calls these functions with the following commands:

// Check correctness of move entered
m_OrthotitaKinisis = ElegxosOrthotitas(Skakiera);
// check legality of move entered
// (only if it is correct - so as to save time!)
if( m_OrthotitaKinisis == true )
       m_NomimotitaKinisis = ElegxosNomimotitas(Skakiera);
else
       m_NomimotitaKinisis = false;

These commands are a normal call to a function (as we showed in the previous lesson) and stored the legality / correctness of the move (true / false) in the NomimotitaKinisis / OrthotitaKinisis variables. You should have noticed that the program does not bother to call the function ElegxosNomimotitasif the correctness of the move is found to be false in the previous validation check. This is for performance purposes only: there is no need to make more validation checks for legality if the move is not correct.


Huo Chess Point: You can see the respective functions in the program at the Enter_move() function.

How to use Debug Mode - Part 2

You can have a look at how the program analyzes the legality of a move entered by using debugging mode, as we did in the previous chapter:First, enter a breakpoint inline 4065 of the application, where the ElegxosOrthotitas function is called. Then enter a second breakpoint at line 4070 where the result of the legality check is stored in the NomimotitaKinisis variable.


Set breakpoints where legality and correctness validation checks are performed [click on image to enlarge]


Now run the program in debugging mode by pressing F5. Choose white as your colour and try to enter e2 => d3 as your first move. This is obviously a wrong move. You will see that the program stops at the first breakpointyou have set. Press F5 to go to the second breakpoint. There you will see the legality of the move being stored in the NomimotitaKinisis variable.Hover your mouse over that variable's name in the source code window and you will see the value of the variable appearing. So you have now verified that your program conducts the correct legality checks. That check is crucial because you might have the move rejected as illegal not due to legality issue but due to a correctness issue (see above for the difference between the two). This is the only way to see under the hood and verify that everything is indeed working the way you want them to.


Computer Thinking Process


After the human opponent plays a move and the computer accepts it, it is now the turn of the AI to initiate so as to find the best answer. The logic of the program is simple:

  1. It scans the chess board to find where its pieces are.
  2. Then the computer makes all possible moves in the chessboard.
  3. It searches and finds the best human answer to each of the moves found in the previous step.
  4. It continues thinking in more depth by applying steps 2 and 3 over and over again.
Let's start analyzing each step slowly, one at a time.

A. Scanning the chessboard

A simple nested "for" (nested = a for loop inside another for loop) loop is used for the scanning of the chessboard, so as to find where all the pieces of the compute are. You can see that full loop here (I have removed some sections which do not matter right now, leaving just the commands which conduct the main work in the chess engine):


  for (iii = 0; iii <= 7; iii++)
 {
  for (jjj = 0; jjj <= 7; jjj++)
 {

  if (((Who_Is_Analyzed.CompareTo("HY") == 0) && ((((Skakiera_Thinking[(iii), (jjj)].CompareTo("White King") == 0) || (Skakiera_Thinking[(iii), || ......... (Skakiera_Thinking[(iii), (jjj)].CompareTo("Black Pawn") == 0)) && (m_PlayerColor.CompareTo("Black") == 0)))))
 {
for (int w = 0; w <= 7; w++)
{
for (int r = 0; r <= 7; r++)
{
                            // Changed in version 0.5
                           Danger_penalty = false;
                           Attackers_penalty = false;
                           Defenders_value_penalty = false;
                           MovingPiece = Skakiera_Thinking[(iii), (jjj)];
                           m_StartingColumnNumber = iii + 1;
                           m_FinishingColumnNumber = w + 1;
                           m_StartingRank = jjj + 1;
                           m_FinishingRank = r + 1;
                           Moving_Piece_Value = 0;
                           Destination_Piece_Value = 0;


                          // Calculate the value (total value) of the moving piece
                         .........


                         // Find the value of the piece in the destination square
                           .........


                        CheckMove(Skakiera_Thinking); 

                 }
 }
 }
 }
 }

The "if" statement checks whether the piece detected is a piece of the same colour as the colour of the computer. If yes, the program proceeds with the next steps of the thinking process (after some checks about the dangerousness of the destination square, which I have ommited here for clarity purposes).Huo Chess point: Look at lines 2583-2700 of ComputerMove(string[,] Skakiera_Thinking_init) function for the abovementioned main chess engine loop. This loop is reffered to in the followin steps as well.

B. Finding all possible moves

The first thing to do in order to find the best move, is to find all the possible moves that the computer can make in the current chessboard position. Huo Chess uses a very simple and brute way to find all possible moves: it actually attempts to move every piece in every possible square of the chessboard and then checks the legality and the correctness of these moves. Every move that has legality=true and correctness=true is a valid move worth analyzing!


The code that performs the moving of all pieces to all possible directions is:

for (int w = 0; w <= 7; w++)
 {
  for (int r = 0; r <= 7; r++)
 {
                                   MovingPiece = Skakiera_Thinking[(iii), (jjj)]; 
                                   m_StartingColumnNumber = iii + 1;
                                   m_FinishingColumnNumber = w + 1;
                                   m_StartingRank = jjj + 1;
                                   m_FinishingRank = r + 1;
                                   .........
                                  CheckMove(Skakiera_Thinking);
 }
 }

In particular, this nested "for" loop stores every possible value as destination square parameters (in the m_FinishingColumnNumber and m_FinishingRankvariables respectively). The computer "makes" the moves in the 2-dimensions tables (virtual chessboards) we use to represent the chessboard in the computer memory. "Making" the move actually means that the program stores the starting and destination square parameters in the respetive variables.The code then calls the CheckMove(Skakiera_Thinking) function to see if that move is valid or not and - if yes - the same function (CheckMove(Skakiera_Thinking)) rates the move to see how good it is. This function is another key ingredient of the game: it is the functions which performs the analysis of the move and rates it. We will have a separate lesson for the function only in the future lessons. For now you need to know that this function rates all moves, after it has reached the thinking depth we have set.

The code in CheckMove(Skakiera_Thinking) checks the legality and correctness of every possible move by using the ElegxosNomimotitas and ElegxosOrthotitas functions that we mentioned above (see lines 1743-1746 in the CheckMove(string[,]  CMSkakiera) function).

Every move that passes the legality and correctness checks is conducted by the program so as to find the best of them (see next steps right below).

C. Rating each move analyzed

Each possible move must be analyzed and rated. After all possible moves have been analyzed and rated, the computer simply chooses the best move (i.e. the move with the best rating). The rating of each move is calculated by the program with the help of the CountScore(string[,] CSSkakiera) function. After the computer has reached the thinking depth we have set, it sends the final position it has reached to the CountScore function and the latter calculates the score of that position.

You can see part of the CountScore function here:

 if (CSSkakiera[(i), (j)].CompareTo("White Pawn") == 0) Current_Move_Score = Current_Move_Score + 1; else if (CSSkakiera[(i), (j)].CompareTo("White Rook") == 0)
{
       ......... Current_Move_Score = Current_Move_Score + 5;
 } 
......... .........
else if (CSSkakiera[(i), (j)].CompareTo("Black Rook") == 0)
{
.........
Current_Move_Score = Current_Move_Score - 5;
}

As you can see the way it works is very simple: It just scans the chessboard with a nested for statement and adds points when if finds white pieces and subtracts points when it finds black pieces. The final score is then a clear indication of who wins the game at the current position.

Huo Chess point: Look at lines 2880 for the CountScore(string[,] CSSkakiera)function.

D. Deciding on the best move

The final decision of which move to play is conducted in the CheckMove function with the following set of commands:


// DO THE BEST MOVE FOUND
if (Move_Analyzed == 0)
{
  // Επαναφορά της τιμής της Stop_Analyzing (βλ. πιο πάνω)
Stop_Analyzing = false;

//////////////////////////////////////////////////////////////////////////////////////
// REDRAW THE CHESSBOARD
//////////////////////////////////////////////////////////////////////////////////////

// erase the initial square
for (iii = 0; iii <= 7; iii++)
 {
      for (jjj = 0; jjj <= 7; jjj++)
     {
         Skakiera[(iii), (jjj)] = Skakiera_Move_0[(iii), (jjj)]; } } MovingPiece =
         Skakiera[(Best_Move_StartingColumnNumber - 1), (Best_Move_StartingRank - 1)];
         Skakiera[(Best_Move_StartingColumnNumber - 1), (Best_Move_StartingRank - 1)] = "";
           .........
         // position piece to the square of destination
         Skakiera[(Best_Move_FinishingColumnNumber - 1), (Best_Move_FinishingRank - 1)] = MovingPiece;


These commands tell the computer to use the parameters of the Best Move (where the best move that has so far been found is stored) and then make the move.

Next lesson

In the next lesson we will analyze deeper the chess engine algorithm that is used to make the computer think and actually play chess.

What we have accomplished

In this second lesson, we have accomplished the following not-so-trivial tasks:
  • Understood how the game loop is used to read input from the game's user.
  • Outlined the thinking process of the computer.
  • Understood what each function used in the AI process does at high level.
  • Had a look inside some functions of the program.
  • Looked at how we can use the debugging mode to see the mechanisms of the program.
Until the next time, happy coding and experimenting!

How to Develop a Chess Series updates
  • Update 2011-09-29: The third lesson with the chess algorithm analysis is now published!

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