## Other Related articles

In the previous lesson we managed to create the function which checks the legality of a move. With that we managed to check the move entered by the user and present it to the screen.

What is next?

To make the computer think of an answer!

In essence this is easy! (the difficult part is to make the computer think of a really good move, that we will tackle later on)

What we will need besides the SUB which checks the legality of the move (ElegxosNomimotitas) is a SUB which counts the score of any given position in the chessboard. This will allow us to evaluate all the possible moves, so that the computer can select the best one.

This is done by the code below, which simply scans the chessboard for pieces and adds or subtracts the value of each piece it founds from the total score of the chessboard.

SUB countScore

```positionScore = 0

FOR I = 1 TO 8
FOR J = 1 TO 8

IF chessboard\$(I, J) = "wpawn" THEN positionScore = positionScore + 1
IF chessboard\$(I, J) = "wrook" THEN positionScore = positionScore + 5
IF chessboard\$(I, J) = "wknight" THEN positionScore = positionScore + 3
IF chessboard\$(I, J) = "wbishop" THEN positionScore = positionScore + 3
IF chessboard\$(I, J) = "wqueen" THEN positionScore = positionScore + 9
IF chessboard\$(I, J) = "wking" THEN positionScore = positionScore + 100

IF chessboard\$(I, J) = "bpawn" THEN positionScore = positionScore - 1
IF chessboard\$(I, J) = "brook" THEN positionScore = positionScore - 5
IF chessboard\$(I, J) = "bknight" THEN positionScore = positionScore - 3
IF chessboard\$(I, J) = "bbishop" THEN positionScore = positionScore - 3
IF chessboard\$(I, J) = "bqueen" THEN positionScore = positionScore - 9
IF chessboard\$(I, J) = "bking" THEN positionScore = positionScore - 100

NEXT J
NEXT I```

END SUB

Easy? Pretty much. All that is needed is a nested FOR loop (read in QB64 here how that works). Nothing more.

Now that we have that, let’s move on to the main course.

The ComputerMove SUB, which – you guessed right – makes the computer perform a move!

In essence, the steps needed are pretty simple:

Scan the chessboard.

If you find a piece of the computer, then…

Scan all possible moves of that piece to all squares of the chessboard.

For every possible move, check the legality of that move.

If the move is legal, then make it!

Check the score of the move.

If the score is best than the current best move (in the beginning there obviously no current best move), then this is the current best move!

After you have examined all the possible moves, do the current best move

Simple isn’t it?

How is the scanning of the chessboard and the checking of all possible moves performed? With four nested FOR loops.

Check the code below. It simple scans all the chessboard with the FOR loops of I and J and then, if it finds a piece which belongs to the computer, it scans all possible destination squares with the FOR loops of ii and jj.

How do we determine is the piece we found is one of the computer’s pieces? We compare the first letter of the piece (which would be ‘w’ or ‘b’ for white and black pieces) with the color of the player. If for example the color of the player is ‘w’ (for white) and we encounter a piece ‘brook’, then this is a piece of the computer since it is black – i.e. opposite than the color of the player.

```'Scan the chessboard...
FOR I = 1 TO 8
FOR J = 1 TO 8

'If you find a piece of the computer...
IF ((MID\$(chessboard\$(I, J), 1, 1) = "w" AND playerColor\$ = "b") OR (MID\$(chessboard\$(I, J), 1, 1) = "b" AND playerColor\$ = "w")) THEN

'Scan all possible destination squares...
FOR ii = 1 TO 8
FOR jj = 1 TO 8

startingColumn = I
startingRank = J
finishingColumn = ii
finishingRank = jj

MovingPiece\$ = chessboard\$(I, J)
ProsorinoKommati\$ = chessboard\$(ii, jj)

'Check legality of the move entered
CALL ElegxosNomimotitas(chessboard\$(), 0, startingColumn, startingRank, finishingColumn, finishingRank, MovingPiece\$)

'If move is legal, then do the move and present it in the chessbooard
IF Nomimotita = 1 THEN

'Do the move
chessboard\$(finishingColumn, finishingRank) = chessboard\$(startingColumn, startingRank)
chessboard\$(startingColumn, startingRank) = ""

'Count the score of the move
CALL countScore

'If the score is better than the existing best score, then this is the best move now (and the best score)
IF ((playerColor\$ = "b" AND positionScore >= bestPositionScore) OR (playerColor\$ = "w" AND positionScore <= bestPositionScore)) THEN
bestStartingRank = startingRank
bestStartingColumn = startingColumn
bestFinishingRank = finishingRank
bestFinishingColumn = finishingColumn
bestPositionScore = positionScore
END IF

END IF

'Undo the move
chessboard\$(startingColumn, startingRank) = MovingPiece\$
chessboard\$(finishingColumn, finishingRank) = ProsorinoKommati\$

NEXT jj
NEXT ii

END IF

NEXT J
NEXT I```

If the move analyzed is legal (the ElegxosNomimotitas SUB is called to determine that) then the move is performed. The score of the position resulting after that is counted (the CountScore SUB is called for that). If the score is better than the current ‘best score’ (the initial best score is zero of course) then this move is registered as best move.

After the scanning is complete, we simply perform the best move!

```'Do the best move found
chessboard\$(bestFinishingColumn, bestFinishingRank) = chessboard\$(bestStartingColumn, bestStartingRank)
chessboard\$(bestStartingColumn, bestStartingRank) = ""
CLS
CALL drawBoard```

Easy? Yes!

Happy coding!

Read the full program here. Copy and paste the code in your QBasic interpreter/ compiler to see it and compile it.

IMPORTANT NOTES

• The code is draft and errors might exist. Make sure to also check Huo Chess in C# (can be found in Harmonia Philosophica here).

Next lesson: How to improve the game of the computer.

## Other Related articles

Programming is fun.

Want to learn? Why not start now?

And what better way there is than to develop an advanced program that makes the computer “think” how to play chess?! Forget about those silly beginners’ example programs which print “Hello world”. Who in his right mind ever spends time to write a program which prints “Hello world” on the screen?

BASIC is fun.

A very easy language for kids to start learning programming. So we will use it here. (Not in the mood for BASIC? Search for the Java and C# relevant tutorials in Harmonia Philosophica!)

And in one day, you will have learnt the basic of how to program a chess program in BASIC! The actual implementation could take a bit longer but in general in some days you will have the knowledge of how the program works, thus being in a position to improve it or write your own!

The BASIC programming language is one of the simplest ones. Especially designed for simplicity, it uses simple commands to perform operations. The commands are easy to learn and use, since they are utilizing English language words which are easily recognizable. Want to print something on the screen? Use the command PRINT! Want to determine what will happen if something else happens? Use the command IF! See what I mean?

`IF YOU_UNDERSTAND = "Yes" THEN PRINT "Yes I understand!"`

Did you understand the above command? Great!

The only thing that might trouble you if you are new to programming is the notion of variables. A variable is an element which holds values. This element is used in various places of the program. The values could be of different types – the ones we will use are integers (1, 4, 10…) and strings/ characters (e.g. “white pawn”).

Variables could be stored also in arrays. An array is a collection of variables in one or more dimensions. It is also known as a “table”. And yes, you guessed right: we will use an array (table) to store the chessboard. Could you guess the dimensions of that table? Spot on again.

`DIM SHARED chessboard\$(8, 8)`

The command DIM defines a variable. We do all the variable declarations in the beginning of the program. The above command declares an 8×8 array which holds the… you guessed it right: The chessboard!

By the way, we are using QBasic64, a version of Quick Basic that is available for free and pretty popular as well. Check https://www.qb64.org/portal/ to get it. The site also contains excellent tutorials and training material. You will have it as a reference throughout the whole process, so make sure you create a bookmark out of it.

After you download QBasic64 from the site, just click on the QB64.exe file and execute it. You will be presented with the IDE (programming interface) of QBasic where you will write your program. I do not need to explain the “Create new”, “Save” or “Save as” functions…

Just start writing the commands and then press “Save as”. Executing the program is easy as well. Just select Run > Start.

As said above, what is the first thing to do? (Besides the “Create new program” part and saving it in a folder of your choosing with a name of your choosing as well)

Some of the first things to do we already mentioned.

First, declare the variables. BASIC is really simple in the sense that it is not so strict in requiring you to declare all the variables before using them, in contrast to other high level languages like C#. However this is also a downside of the language. Leaving the programmer with some slack makes the programmer careless.

So we will declare all the variables we use…

`DEFINT A-ZOPTION BASE 1 'Make tables dimensions start from 1`
`DIM SHARED chessboard\$(8, 8)COMMON SHARED startingRank, startingColumnCOMMON SHARED finishingRank, finishingColumnCOMMON SHARED startingRankText\$, startingColumnText\$COMMON SHARED finishingRankText\$, finishingColumnText\$COMMON SHARED Move\$COMMON SHARED MovingPiece\$COMMON SHARED debugMode`

There you go. (Read the QB64 Wiki for what DEFINT A-Z and OPTION BASE 1 commands do – Remember, learning entails the process of… learning)

What is next?

What else?

Ask the user for input!

And what else to ask than his first move! For simplicity purposes we will present the main command which tells the user to put his move. The drawing of the board on the screen will be done by the drawBoard() function. A function is an independent set of code that you can call to perform an action. In our case we call the drawBoard function (with the command… CALL DRAWBOARD – I told you it was simple). For the time being forget how the function works. (Even though reading through it and trying to understand how it works would be a lesson on its own…)

So how would you ask for the user input?

Simple by the command… INPUT!

There you go:

`INPUT "Enter your move: ", Move\$`

This command tells the computer to wait for the user to enter something and press Enter. When this happens, the text entered by the user is saved in the Move\$ variable. The dollar sign (\$) indicates that the variable is a string (text) and not a number.

Let’s stay there.

For now you have learnt how to…

• Create a new program.
• Declare the variables you will use (including the chessboard).
• Ask from the user to enter his first move.

You have also been acquainted with the notions of variables and functions and with some basic BASIC (get the joke?) commands, like IF… THEN or INPUT and PRINT. Don’t worry if you don’t get everything yet. You will as you program more and more every day.

Next lessons will include the next logical steps:

• Validate that the user move is valid and legal.
• Redraw the chessboard with the move of the user.
• Make the computer think of an answer.

You would be surprised how the last part (the thinking of the computer) is a rather simple one. In essence the computer thinks of all possible moves, validates them (in the same way we will validate the move entered by the user) and then for the valid ones it will calculate a score of the position. The move with the best score will be the move of the computer.

Until next time…

Happy coding!

Next lesson: How to check the legality of the move entered! Check here.

{{#pages}} {{/pages}}
%%footer%%