The adventure of creating… an adventure! Episode 1: Setting up the images [Quick Basic/ QB64 Tutorial]

First Adventure (in QB64)

Introduction

Programming is fun!

What does that have to do with a philosophy portal?

Well… I do not know!

But then again…

What do we know about life or death?

Goal

The goal of this series of tutorials is to show how to create a small (or big?) adventure game with Quick Basic, so as to disseminate programming knowledge. Even if you do not have prior programming knowledge you will be able to follow the series with some additional effort to clear up some programming details we will encounter along the way.

The source code of the program will always be provided at all steps of the tutorial. Reuse of the code is allowed as long as the source is mentioned properly.

Tools needed

To follow the tutorial you just need the Quick Basic in your computer. Just download the latest QB64 from the relative site here for free.

Designing

Before doing any programming one must design what he wants to do. This applies to small as well as big programs.

So what do we want to do?

To create an adventure game!

This game will utilize simple images that we will show to the users as they progress along the game. All the typical adventure game commands will be allowed: Look at, Walk to, Pick up, Use, Talk to, Give, Push, Pull.

The game scenario is something I have not yet thought in its entirety. However I know that the game will start from a room where you are and where you will need to stay alive for at least one day before the rescue team comes and saves you.

The beginning

From where to start from?

Well, from the start (welcome) screen!

To do that we use the PRINT command to print the game title on the screen.

The game will be called…

First Adventure!

Since it is our first adventure.

'Introduction
LOCATE 10, 32: PRINT "First Adventure!"
LOCATE 11, 30: PRINT "Greece, Athens, 2022"
LOCATE 13, 25: PRINT "Seek the moon under the sun…"
SLEEP

The LOCATE commands puts the cursor in a specific line and then we print what we want.

First Adventure – Start image

Setting up the images

Each game takes place in a… place.

To illustrate things we need graphics.

We will use basic graphics in our game, i.e. images we will load into the screen to show things. The first thing is to get the images, right? For the purposes of our tutorial we will use images that are 580×420 pixels in dimension. These images will be shown in a window that is 800×600 in dimensions.

Why these dimensions?

First, for no reason. Just because.

Secondly, I like to have a small window for the program to show small images. You guessed it, the program will not utilize the full screen and will not resize based on the resolution of your screen. Let’s start with the basics and build a bike and we will go to building a spaceship after that…

Images are loaded with the _LOADIMAGE command as it is shown below.

IF GameResolution = 800 THEN
    imgBgrd& = _LOADIMAGE("FA_image_Background_800.png", 32) 'Background image
ELSEIF GameResolution = 1280 THEN
    imgBgrd& = _LOADIMAGE("FA_image_Background_1280.png", 32) 'Background image
END IF

You also guessed it right: We have introduced a variable that indicates the resolution of the game. So when I told you that the game will not take into account the resolution of your computer, I lied a bit. Just a bit. We introduce a variable to indicate the resolution used and we will embed it in the code and… we will see how to use it the future.

For now, let’s set the resolution at 800×600…

CONST GameResolution = 800 'Set for resolution 800x600

We repeat the same loading of images for all images of the game. For now, we only have three images: the background image (that is loaded in the beginning and… stays there for ever) and two more images that we put on the background when he game starts.

First Adventure – Background image

The background

The image I have created for background is a black colour image with a white line. This line will be the border between the upper and the lower part of the screen.

  • In the upper part we will show images that are related to the gameplay, e.g. the photo of a room you are in.
  • In the lower part of the screen we will show to the user the possible commands allowed for the game, his inventory of objects (if and when we add one) and any messages.

Simple enough. Yet, nice and effective.

How are those images put in the screen though?

Well, with the PUTIMAGE command…

IF GameResolution = 800 THEN
    _PUTIMAGE (100, 20)-(680, 440), imgStart&, 0
ELSEIF GameResolution = 1280 THEN
    _PUTIMAGE (80, 20)-(660, 500), imgStart&, 0
END IF

With the PUTIMAGE command you can set where to place your image upper-left corner (100,20) and where the lower-right corner will be (680,440), which image to load (imgStart&) and where to show it (0 denotes the screen). In that way we can put any of the images we have loaded wherever we want.

First Adventure – Start image

Show the initial messages

When the game starts and the background image is loaded, we print the initial messages to the user. We use the LOCATE command and print the messages in the lower part of the screen, as mentioned above…

'Print text to begin the adventure...
LOCATE 33, 1: PRINT "You are in a room... Alone..."
LOCATE 34, 1: PRINT "There is a snow storm raging outside..."
SLEEP

'Show the trees!
_PUTIMAGE (100, 20)-(680, 440), imgTrees1&, 0

LOCATE 33, 1: PRINT "You must survive for one day..."
LOCATE 34, 1: PRINT "Until the rescue party comes to save the day!"
SLEEP

And as you see in the code, we can load new images whenever we want to show new things. In that case we have loaded a trees picture. After all, we are in a snow storm…

Important Notes

  • Guess what the SLEEP command does. Try to remove it and see what happens.
  • Experiment with the coordinates in the PUTIMAGE command to see how that command can be used. (seek some additional examples commented out in the source code provided)

An epilogue and a promise…

We have just set up the scenery for our game. We have the initial screens and we have understood how images are loaded. We will build on this to expand the game and take it to the next level…

APENDIX I – The source code

Please see below for the full source code of the game.

'Declare variables
DIM imgBgrd&
DIM imgStart&
CONST GameResolution = 800 'Set for resolution 800x600
'const GameResolution = 1280 'Set for resolution 1280x720

'Introduction
LOCATE 10, 32: PRINT "First Adventure!"
LOCATE 11, 30: PRINT "Greece, Athens, 2022"
LOCATE 13, 25: PRINT "Seek the moon under the sun..."
SLEEP

'Load the background from an image in a file
'Load different pictures depending on the resolution we want
'(because the image will be used to set the screen)
'imgBgrd& = _LOADIMAGE("FA_image_Background_800.png", 32) 'Background image

IF GameResolution = 800 THEN
    imgBgrd& = _LOADIMAGE("FA_image_Background_800.png", 32) 'Background image
ELSEIF GameResolution = 1280 THEN
    imgBgrd& = _LOADIMAGE("FA_image_Background_1280.png", 32) 'Background image
END IF

'imgStart& = _LOADIMAGE("FA_image_Start_800.png", 32)

'Load images of the game from files
'Images for resolution 800x600 are 580x420
'Images for resolution 1280x720 are 640x480
'Image Start
IF GameResolution = 800 THEN
    imgStart& = _LOADIMAGE("FA_image_Start_800.png", 32)
ELSEIF GameResolution = 1280 THEN
    imgStart& = _LOADIMAGE("FA_image_Start_1280.png", 32)
END IF
'Image trees
imgTrees1& = _LOADIMAGE("FA_trees1.png", 32)

'Set the image as destination
'_DEST img1&

'Set the screen mode based on the background image (800x600 png image)
'SCREEN 12
'SCREEN _NEWIMAGE(800, 600, 32)
SCREEN imgBgrd&

'Set background colour to gray
'CLS , _RGB32(127, 127, 127)

'Present the first image of the game on the black screen
'(i.e. put the image2 on top of image1, which is the background loaded initially)

'_PUTIMAGE (10, 10)-(650, 490), imgStart&, 0
'_PUTIMAGE (200, 200)-(400, 400), img2&, 0, (0, 0)-(400, 400)

IF GameResolution = 800 THEN
    _PUTIMAGE (100, 20)-(680, 440), imgStart&, 0
ELSEIF GameResolution = 1280 THEN
    _PUTIMAGE (80, 20)-(660, 500), imgStart&, 0
END IF

'Set text colour
'COLOR 7, 5

'Print text to begin the adventure...
LOCATE 33, 1: PRINT "You are in a room... Alone..."
LOCATE 34, 1: PRINT "There is a snow storm raging outside..."
SLEEP

'Show the trees!
_PUTIMAGE (100, 20)-(680, 440), imgTrees1&, 0

LOCATE 33, 1: PRINT "You must survive for one day..."
LOCATE 34, 1: PRINT "Until the rescue party comes to save the day!"
SLEEP

Copy this code in your QB64 IDE and try it out.

In order to use it you must also have the images the program loads in the same folder as the QB64.exe program.

APPENDIX II – The images

Please fine here the images used by the program.

APPENDIX III – Useful resources

One can find many things in the Internet. Information about programming is one of these things. Seek help in the relative QB64 web site or in relevant programming sites to understand how various Quick Basic commands work.

Below I list some resources related to the commands we used.

Feel free to seek knowledge from where you can!

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

Huo Chess DV (GUI Edition)

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

Goal

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

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

Overview

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

.NET frameworks and libraries (source)

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

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

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

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

Tutorials for building a chess program

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

Tutorials on how to develop a chess program include:

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

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

Huo Chess source code

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

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

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

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

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

First things First: Fixing dpi issues

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

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

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

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

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

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

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

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

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

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

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

Porting in Visual Studio 2022…

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

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

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

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

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

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

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

Consider for example the following example…

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

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

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

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

Publishing the application

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

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

In summary, the following parameters are used:

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

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

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

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

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

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

Application trimming

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

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

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

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

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

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

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

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

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

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

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

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

Keep experimenting! Keep coding! And have fun!

References

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

Programming a chess application in QBasic (QB64)

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

Other Related articles

News

  • 2022-05-06: Huo Chess v0.7 in QBasic with graphics is released. The version addresses Out of Memory issues with the logs of the application.
  • 2021-11-14: Created a GitHub repository of the Huo Chess Quick Basic edition.
  • 2021-03-14: Updated thinking in levels 4 and 5; now extra analysis at these levels only happens if the move entails the capturing of a piece. Updated CountScore to include positional elements in the evaluation. Introduced the notions of mate and stalemate in the thinking process.
  • 2020-12-16: Fixed issue with en passant move.

This is an article on how one can develop a chess program in QBasic.

It is based on Huo Chess that was developed by me and is available as open source in multiple programming languages (C#, Java, older versions in C++ and Visual Basic).

Parts of the article have been posted as separate tutorials (check here). They are all gathered here in a unique article that can provide an overall understanding of the chess programming complexity.

The tutorial is at the point at a very simple/ high level but it will be enriched as time passes by. The initial goal was to have at least a starting point for someone who needs to delve into the chess programming cosmos and this I believe I have managed to achieve.

Why in QBasic?

Well, BASIC is simple and fun!

Do you need more reasons?

Well…

Here is another one:

10 PRINT "Why not?!"
20 GOTO 10

That’s what happens when you mess with BASIC. Seriously now, at the end, the goal here is to present the algorithm. The specific language of the implementation does not play a particular role. When you are at a level to develop the next Stockfish be sure to remember that it was here from where you started your journey…

The tutorial should be read in conjunction with the source code of Huo Chess offered here. The code itself is written in a simple and structured way and it is heavily commented so that even without any prior knowledge one can easily understand how thw algorithm works.

Let’s not waste any more time!

Happy coding!

I. Beginning

Let us begin from the… beginning. And one step at a time, try to see how we can develop our chess program.

Important Notes

  • Refer to QB64 site for questions regarding how QBasic commands work. Essentially they are simple, but in case your are stuck with an error you cannot resolve, this is the place where you will find your answers.
  • Always have the source code open in a separate window. Although the tutorial only goes throug portions of the code to explain how it works, it is always beneficial to have the whole source code of the working program in front of you.
  • A note about the source code versions: Chapter I to IV refer to the version 0.3 of the code. Chapter V refers to the version 0.6 of the code.
  • The Huo Chess Quick Basic edition is available for download either from here or from the relevant Huo Chess QB64 GitHub repository.

And don’t forget: Coding is about experimenting!

Do not wait everything from this tutorial or from any other tutorial! Just open the QBasic editor and write code! Change things! See what they do! At the end it is YOU who is learning, not me teaching you!

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-Z
OPTION BASE 1 'Make tables dimensions start from 1
DIM SHARED chessboard$(8, 8)
COMMON SHARED startingRank, startingColumn
COMMON SHARED finishingRank, finishingColumn
COMMON 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.

II. Check legality of a move

In the previous chapter we managed to create our program in BASIC (QB64) and write the first lines of code to ask for input from the user for his move.

Now we will perform the next and one of the most important steps in a chess program: Checking the legality and validity of a move!

Remember that we asked from the user his move by the command…

INPUT "Enter your move: ", Move$

With this command the computer asks for input by the user and then stores what the user entered (after he presses Enter) into the Move$ variable. As we said in the previous lesson, the $ sign in a variable name denotes that the variable stores a string (text) value and not a number.

Now that we have the move into a single text variable, we should first of all “break it down” into four specific elements:

  • Starting column
  • Starting rank
  • Finishing column
  • Finishing rank

In that way we will have the starting and finishing coordinates of the user’s move, which we will use for the checking of the legality of the move later on.

How do we “break up” the text? By using the MID$ built-in function of BASIC which returns a specific character from a text. So if the user entered the move “g2g4” (which is Grob opening by the way, one of my favorites), then the command…

MID$(Move$, 2, 1)

will return the character “2”, since it will start from character 2 of the Move$ variable and will get 1 character.

Without further delay, here is the code which breaks up the move the user entered into the four numbers we are looking for.

INPUT "Enter your move: ", Move$
startingColumnText$ = MID$(Move$, 1, 1)
startingRankText$ = MID$(Move$, 2, 1)
finishingColumnText$ = MID$(Move$, 3, 1)
finishingRankText$ = MID$(Move$, 4, 1)
SELECT CASE startingRankText$
CASE "1"
startingRank = 1
CASE "2"
startingRank = 2
CASE "3"
startingRank = 3
CASE "4"
startingRank = 4
CASE "5"
startingRank = 5
CASE "6"
startingRank = 6
CASE "7"
startingRank = 7
CASE "8"
startingRank = 8
END SELECT
SELECT CASE finishingRankText$
CASE "1"
finishingRank = 1
CASE "2"
finishingRank = 2
CASE "3"
finishingRank = 3
CASE "4"
finishingRank = 4
CASE "5"
finishingRank = 5
CASE "6"
finishingRank = 6
CASE "7"
finishingRank = 7
CASE "8"
finishingRank = 8
END SELECT
SELECT CASE startingColumnText$
CASE "A", "a"
startingColumn = 1
CASE "B", "b"
startingColumn = 2
CASE "C", "c"
startingColumn = 3
CASE "D", "d"
startingColumn = 4
CASE "E", "e"
startingColumn = 5
CASE "F", "f"
startingColumn = 6
CASE "G", "g"
startingColumn = 7
CASE "H", "h"
startingColumn = 8
END SELECT
SELECT CASE finishingColumnText$
CASE "A", "a"
finishingColumn = 1
CASE "B", "b"
finishingColumn = 2
CASE "C", "c"
finishingColumn = 3
CASE "D", "d"
finishingColumn = 4
CASE "E", "e"
finishingColumn = 5
CASE "F", "f"
finishingColumn = 6
CASE "G", "g"
finishingColumn = 7
CASE "H", "h"
finishingColumn = 8
END SELECT

The above code breaks up the Move$ into the above-mentioned four numbers and you would have noticed that the break up has two steps which we didn’t quite mention before: First we break up the text and then we ‘translate’ the four text values into numbers. This is done with the SELECT CASE commands, which essentially select different numeric value for each possible value of the columns and ranks. And yes, the text “8” needs to be translated to the number 8. As far as the computer is concerned they are completely different monsters altogether.

So now we have what we need. The starting column and rank and the finishing ones. How do we check the legality and validity of the move? Well, there is no “magic” way. We just have to write code to do that.

For clarity purposes we will gather all the code performing the check of the legality in one function (= set of code) which we will call ElegxosNomimotitas (= Check of Legality, in Greek). We will define the call parameters of the function (i.e. what parameters we need to pass over the function for it to do its job) and then write the code inside it.

What would be the input parameters?

The starting and end column and ranks of course. And we will also send the Moving Piece in a separate variable because this is a crucial part of the function. Different pieces move in a different way, right?

The function declaration would be something like…

DECLARE SUB ElegxosNomimotitas(ENSkakiera() AS STRING, startColumn AS INTEGER, startRank AS INTEGER, finishColumn AS INTEGER, finishRank AS INTEGER, MovingPieceEN AS STRING)

The ENSkakiera (=Elegxos Nomimotitas Skakiera = Check Legality Chessboard in Greek) is the array of the chessboard (= Skakiera in Greek) we will need to pass. The function will check the legality of a move not in general, but in the context of a specific chessboard of course. Then beyond the chessboard we pass over the start and end columns and ranks and the Moving piece as mentioned above.

Now we are in the function which checks the legality of the move. We will show how to do this for one piece, the rook. Then the logic is similar (not exactly, but you will get the meaning) for the other pieces.

Without further delay, here is the code…

IF (MovingPieceEN$ = "wrook" OR MovingPieceEN$ = "brook") THEN

    IF debugMode = 1 THEN PRINT "Nomimotita = " + STR$(NomimotitaEN)

    'Check correctness of move (Rook only moves in lines)

    IF ((startColumn <> finishColumn) AND (startRank <> finishRank)) THEN NomimotitaEN = 0

    IF debugMode = 1 AND NomimotitaEN = 0 THEN PRINT "Checkpoint ROOK-0"

    'Check if the Rook moves beyond the limits of the chessboard

    IF ((finishColumn < 1) OR (finishRank < 1)) THEN NomimotitaEN = 0
    IF ((finishColumn > 8) OR (finishRank > 8)) THEN NomimotitaEN = 0


    'Check if another piece is between the current and the target square

    'Horizontal movement

    IF (startColumn > finishColumn) AND (startRank = finishRank) THEN
        FOR J = startColumn TO finishColumn STEP -1
            IF (J <> startColumn) AND (J <> finishColumn) AND ENSkakiera(J, startRank) <> "" THEN NomimotitaEN = 0
        NEXT J
    END IF

    IF (startColumn < finishColumn) AND (startRank = finishRank) THEN
        FOR J = startColumn TO finishColumn
            IF (J <> startColumn) AND (J <> finishColumn) AND ENSkakiera(J, startRank) <> "" THEN NomimotitaEN = 0
        NEXT J
    END IF

    'Vertical movement

    IF (startColumn = finishColumn) AND (startRank > finishRank) THEN
        FOR J = startRank TO finishRank STEP -1
            IF (J <> startRank) AND (J <> finishRank) AND ENSkakiera(startColumn, J) <> "" THEN NomimotitaEN = 0
        NEXT J
    END IF

    IF (startColumn = finishColumn) AND (startRank < finishRank) THEN
        FOR J = startRank TO finishRank
            IF (J <> startRank) AND (J <> finishRank) AND ENSkakiera(startColumn, J) <> "" THEN NomimotitaEN = 0
        NEXT J
    END IF

    'If the start square is the same as the destination...
    IF startColumn = finishColumn AND startRank = finishRank THEN NomimotitaEN = 0

    'Check if a piece of the same colour is at the destination square
    IF MID$(ENSkakiera$(finishColumn, finishRank), 1, 1) = MID$(ENSkakiera$(startColumn, startRank), 1, 1) THEN NomimotitaEN = 0

    IF debugMode = 1 AND NomimotitaEN = 0 THEN PRINT "Checkpoint ROOK-5": 'INPUT a$

END IF

This code checks for many things:

  • If the rook moves in rows or columns
  • If the rook moved beyond the limits of the chessboard
  • If the rook is blocked by another piece before he reaches the destination square
  • If there is a piece of the same colour at the destination square.

If any of the above validations fail, then the Nomimotita (legality in Greek) variable is set to false (0). If not, the Nomimotita is 1 (= true). Note that we use an integer variable to indicate the Nomimotita (which takes values 0 or 1) instead of a text variable (which would take the values “True” or “False”) to use less memory. But we could anyway use a text variable with the same result.

Note: The “IF debugMode = 1” lines of code are used to print to the screen messages for debugging.

It may look complicated, but at the end it is not. The code is simple and self explanatory, with comments. Take for example the first validation: A rook must move in columns or ranks. How is this translated in the code?

    IF ((startRank = finishRank) AND (startColumn <> finishColumn)) THEN NomimotitaEN = 0
IF ((startColumn = finishColumn) AND (startRank <> finishRank)) THEN NomimotitaEN = 0
IF ((startColumn <> finishColumn) AND (startRank <> finishRank)) THEN NomimotitaEN = 0

Read the code at your own pace.

At the end it is just… English. 🙂

After making sure that the move entered is valid, then all we have to do is… make it and present it to the screen.

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

    IF debugMode = 1 THEN
        PRINT "Now we will redraw the chessboard"
    END IF

    'Do the move
    chessboard$(finishingColumn, finishingRank) = chessboard$(startingColumn, startingRank)
    chessboard$(startingColumn, startingRank) = ""
    CLS
    CALL drawBoard

END IF

Go on and check the program source code (check at the end of the tutorial to find it), which contains all the other move validity checks for all the other pieces. You will find it pretty easy to read and understand. It contains comments within the code to support you in your lesson. Copy and paste the code in your QBasic interpreter/ compiler to see it and compile it.

III. Chess thinking algorithm

In the previous chapter we managed to create the function that 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!

IV. Advanced concepts (Part 1)

The last chapters (Advanced concepts Part 1 and 2) will touch-base on some more advanced concepts in chess programming:

  • Thinking for more moves ahead in the game
  • Improving the position evaluation
  • Selecting the best move (miniMax concept introduction)

Up to now the program we have developed (see the previous lessons, where you can download the program) can think in one (1) move depth. This means that it simply (well, not ‘simply’ – we have gone a long way to make this happen) scans all the possible moves and then selects the one with the highest score.

This has just gave us an insight of the way a computer may think for chess, but a very limited one. The basic thing for thinking for chess is thinking in depth. Everybody would agree that thinking in more depth makes someone a better player.

How can we make that happen?

Simple!

We will copy-and-paste (sort of speak) the main computerMove SUB (Move depth 1 – Existing) two times more, so that the computer also thinks two moves more in depth. In essence, there will be two additional ‘thinking SUB-routines’: One which thinks of the potential human moves (Move depth 2) and another that thinks of the reactions of the computer to those moves (Move depth 3).

After that we will have the following structure:

DEPTH 1: computerMove: This routine thinks of the potential moves of the computer at the first level of thinking. If the thinkingDepth is not reached (i.e. if it is not set to 1, but e.g. 3) then the HumanMove1 SUB is called.

IF Move = thinkingDepth THEN
   '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

IF Move < thinkingDepth THEN CALL HumanMove1(chessboard$())

DEPTH 2: HumanMove1: This routine is scanning for all the possible answers of the human opponent. For each of those movements, the next thinking depth routine is called.

DEPTH 3: ComputerMove2: The last routine. Searches for possible moves at depth 3 (i.e. 3 half-moves). The move which ends up with the position with the best score at the end, is the one chosen.

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

With these you will have the program think in depth of 3 half-moves (i.e. a move of the computer, a move of the human opponent and a last move by the computer).

We have been slowly progressing.

Yet, there is a lot more way to go…

V. Advanced concepts (Part 2): Improving the computer thinking with MiniMax

The algorithm described above is simple and does make the computer think in depth. When using the code below, you will see an obvious latency in computer’s thinking vis-a-vis the time needed by the previous version which thinks in depth of only 1 move.

When using the code however one can see that it does not make good moves! Simply by checking the score of the positions at the end, does not lead to wise decisions. The computer thinks, but not very well.

Yet.

What is needed for that to happen?

First improvement: Improvement of the position evaluation.

Now we are just counting the material in the final position.

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

But material is not everything.

For example in the initial position all moves seem to result in the same material score, however it is known that in the chess opening the good player always moves hies pieces near the center of the chess board, avoid unnecessary movements of the king and the queen and avoids to move the same piece twice.

EXERCISE: Try to improve the countScore SUB to cater for the above. You might need to also introduce a new variable which will count the number of moves we are in the game, so that the computer knows if we are at the opening, the middle of the final stage of the game.

Second improvement: Apply the MiniMax algorithm

Improving the CountScore SUB does not solve our problems.

The thinking mechanism of the program we have desribed is inefficient. One could say that it is inherently flawed.

The program searches for the best score at the end of 3 half-moves, but does not cater at all for the fact that the human opponent moves (at move depth 2) will not be the ones which maximize the score for the computer, but the ones maximizing the score for the human opponent.

In other words: The variants (set of moves) which include completely stupid human opponent moves end up in high scores in favor of the computer and that is why, those variants will at the end be chosen.

But in real life the human opponent will never play his worst moves, but quite the opposite: He will play his best moves so as to win the computer!

The following example will better illustrate the problem.

Imagine we are at the following position…

Important note: The Huo Chess program was developed with simple text-like ‘graphics’. There is also a graphics-version based on Deep Basic chess program (by Thomas McBurney), which you can also download.

An initial version of Huo Chess which simply thought in terms of the best score at the end of 3-half-moves, would play… Qf7+ in this position.

But this is a bad move! Why does it play that?

Simple.

The computer assumes that at the next move human will play something stupid and then it will be able to capture the king of the opponent. The set of moves “1. Qf7+ [something stupid] 2. Qxe8” results in the best (highest) score for the computer, so this move is selected.

The algorithm did not even think that human after Qf7+ will simply play KxQf7 and take the queen, simply because this move results in low score for the computer.

But how do you take into account the best moves for the human opponent (MAXimize value) and at the same time the worst possible variants for the computer (MINImize value)? In other words, at the end, how can the computer play its best move taking into account the worst scenario, which we will have only if the human opponent plays his best move?

EXERCISE: Try to think of the above on your own, WITHOUT reading online about the MiniMax algorithm. First of all – who knows? – you might think of something better! Secondly, one only masters knowledge when he has tried on his own and failed to acquire it. Having things ready for you simply does not lead to wisdom.

The solution to the above problem is the MinMax algorithm. The current version of Huo Chess utilizes it, so you can read there how it works. However note that you can never learn anything by simply copying the program of someone else. Unless you write the program on your own, make mistakes, spend countless nights and days pondering upon them, you will never truly develop anything.

In the MinMax algorithm, we start from the lower level nodes and go up to the beginning of the tree, like in the schema that follows:

MinMax algorithm [Source: Wikipedia]

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 half-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. (source)

In simpler words: It is not enough to calculate the best end-score of a node! Because this might be the result of a combination of good computer moves and bad human moves. The human will not make stupid moves (or at least this will have to be our assumption). So in the level that the computer plays, we must maximize the score (the computer makes the best possible move), but in the levels the human opponent plays we must minimize the score of the computer (i.e. the human plays the best move for him, so the worst move for the computer).

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.

Make sure you check the relevant Huo Chess C# tutorials or the page in Codeproject which refer in more depth to the algorithm (which stays the same regardless of the programming language you use of course).

More updates coming soon!

Download Source Code

This section contains the source code of the Huo Chess QBasic application. Make sure to check here frequently for the latest updates.

Huo Chess source

The Huo Chess source code can be found below. Copy and paste the code in your QBasic interpreter/ compiler to see it and compile it.

One can also download a version with more elaborate graphics for the chessboard, where I have re-used the graphics from the Deep Chess program (by Thomas McBurney). Note that all the code is the same as the Huo Chess above, only the graphics are added – so if you need to study the engine the Huo Chess edition without these more elaborate graphics will perfectly fit your needs.

Important Note: For it to work, copy the PIECES.EGA file you will find in the Deep Chess site to the same folder as your program (this file contains the images of the pieces).

For historical purposes I have added previous versions of the code. You do not have to worry about those. Simply choose the latest one. Make sure you keep on coming to this page for updates of the code.

Important Notes

  • The “HUO Chess with graphics v0.6” needs a lot of memory for the logs so in some systems it may throw an Out of Memory exception. In those cases, please use the “Huo Chess v0.7” which has reduced memory needs instead.

Opening Book Editor

The latest versions (v0.6) of the code have an opening book functionality. In order to generate the files of the opening book you can use the Opening Book Editor found below.

Simply run the program, play the moves you want to store in the opening book and they will all be stored in separate txt files. These files must then be places in the same folder as the Huo Chess executable for the latter to utilize them.

As with Huo Chess, make sure you visit this page again to check for any updates or improvements in the code!

Other Huo Chess resources

Other Huo Chess related resources are listed in this section.

Feel free to write for any comments or suggestions for the program.

Until we meet again…

Happy coding!

HUO Writer: A simple AI writer with basic Neural Network capabilities (QB64)

News

  • 2021-02-14: Updated phrases the AI uses. Added more comments to make the code more readable and easier to configure new phrases.

Goal

The goal of Huo Writer is to be a program that thinks philosophically. By getting user input on a specific topic, it can generate phrases with deep philosphical meaning so as to trigger thoughts on the human user.

The goal of the article is to serve as a simple tutorial on how to build a program that can have a conversation with a human, for people with limited or no programming skills.

An Appendix describes how the program can be enhanced with neural network capabilities, by showing a totally primitive way of helping the program improve its responses based on human feedback.

Go directly at the end to get the code of the program.

Other programming tutorials

Introduction

Programming is easy. And difficult.

It is easy in the sense that all you have to do in order to do it, is… do it! As in all things. There is no magic words to use, no secret key, no hidden doors to unlock. Simply open your computer and start programming. As simple as getting up in the morning and making coffee.

Of course, you must know how to make coffee.

That is the difficult part of programming. But do not worry. As in all other programming tutorials in our portal, we will try to keep it simple.

First of all, we will use the simplest high-level language for our tutorial, i.e. QBasic (and in particular, the 64-bit version which can run in any modern Operating System, QB64). BASIC is, as the name implies, basic. Very easy to learn. There are tons of resources in the Internet on the language; be sure to search for QB64 (QBasic 64 bit) mainly, so as to make sure you search for the right thing.

Secondly, the program itself is ultra-simple. The code is based on a very limited set of commands (mainly PRINT, IF, CASE, INPUT, RANDOMIZE) which you can easily learn. And even if you don’t you are able to understand what they do by reading this article!

Huo Writer on faith, problems, helping…

Yet and despite the above, the actual result is very good! The program actually does sound like a philosopher and writes deep stochastic phrases which will trouble you and invoke thoughts.

Look at the text below…

Never do faith supports us.
Would faith exist without you?
Ignorant men.
Others create reality.
Don’t you remember?
Stop thinking. And you will see…

~ HUO Writer, 2020-09-01

It was written by the program when discussing about the tags faith, helping, problems. Taking into account how simple and ultra-light the program is, it is really good! Don’t you agree? (Note the small gramatical errors, these are still part of the problems still to be solved)

Is it Artificial Intelligence though?

Well, surely it wasn’t created on its own, so yes it is artificial. And it does include some very basic rules to randomly generate what it says. Last but not least, the result seems like it is intelligent, so that is the greatest argument in favor of answering yes to this question. After all, how to I know that you are not robot?

I. How the program works

The program works in the following simple steps:

  1. Ask input from the user: The program needs from the user to enter some tags related to topic of discussion. For each tag, the gender (male, female, neutral, adjective, indifferent) and the number (plural, single, indifferent) must be defined. Note that some of the values are not exactly ‘correct’, for example the ‘adjective’ is not a gender. The values entered are then used by the program to properly formulate the phrases it will generate to speak with the human.
  2. Generate the phrases to say, by not-fully randomly combining the tags provided by the user with specific words and phrases in the database of the program.

Simple huh?

Well, it is!

The most difficult part is to enter meaningful and cleverly selected words and phrases in the database so that the phrases generated by the program can sound as philosophical and meaningful. As in any other thing, the ‘Garbage in-Garbage out’ principle stands strong.

II. Step 1: Get user input

Getting user input is as simple as using the… INPUT command in QBasic and ask from the user the input.

Just see the code below on how the program asks from that input.

PRINT "What is our theme of discussion to-day?"
PRINT ""
INPUT "Number of tags: ", tagsNo
PRINT "Thank you"
SLEEP 2
PRINT "": PRINT "Now…": PRINT ""
SLEEP 2
PRINT "Please enter related tags one by one…"
SLEEP 2
PRINT "One word only per tag please. All in small letters."
PRINT "Enter Bye or just press Enter to exit."
'Read related tags for the subject of discussion
FOR I = 1 TO tagsNo

PRINT ""
INPUT "Enter Tag: ", Tags$(I, 1)
IF Tags$(I, 1) = "Bye" OR Tags$(I, 1) = "" THEN END

TagGender:
INPUT "ENTER THE TAG'S GENDER (m, f, n, a, i) : ", Tags$(I, 2)
IF Tags$(I, 2) <> "m" AND Tags$(I, 2) <> "f" AND Tags$(I, 2) <> "n" AND Tags$(I, 2) <> "a" AND Tags$(I, 2) <> "i" THEN GOTO TagGender

TagNumber:
INPUT "ENTER THE NUMBER OF THE TAG (s, p, i) : ", Tags$(I, 3)
IF Tags$(I, 3) <> "s" AND Tags$(I, 3) <> "p" AND Tags$(I, 3) <> "i" THEN GOTO TagNumber

NEXT I

Initially the program asks for the number of the tags to be entered and then, for each tag (hence the FOR… NEXT loop), the user is asked to enter the parameters (gender, number) of the tag.

As you can see, all the tags entered as placed inside the Tags$ table. This table will be then used to generate the phrases.

The tag itself is stored in dimension 1 of the table, while the parameters of the tag are stored in the dimensions 2 and 3 of the table.

Tags table dimentions

  • Dimension 1: The tag itself
  • Dimension 2: This stores the gender
  • Dimension 3: This stores the number

These parameters will be used later on in validation rules necessary for the correct creation of the phrases.

III. Step 2: Generating the phrases

Based on the input of the user, the program combines the tags with specific phrases or words in the database of the program.

The program generates the following phrases:

  1. Phrase H.1: The first phrase, combining phrases from tables H1$, H2$, one of the tags and a phrase from table H3$.
  2. Phrase H.2: The second phrase, combining a phrase from table H4$, one of the tags and a phrase from table H5$.
  3. Intermediate phrase 1: A connecting phrase, which includes a phrase from table I1$.
  4. Phrase K: The third phrase, combining phrases from tables K1$, K2$ and K3$.
  5. Intermediate phrase 2: A connecting phrase, which includes a phrase from table I2$.
  6. Terminating phrase: The closing phrase, which includes a phrase from table T$.

As mentioned, the elements used for each phrase as documented in the program’s database. By ‘database’ we do not refer to a relational database, but to tables (e.g. tables H1$, H2$, H3$ used for the first phrase) which are populated with data with the code of the program.

These rables are filled in as follows…

'PHRASE 3 (Phrase K)
'Set Variables for third phrase (Phrase K) generation
'----------------------------------------------------
K1$(1, 1) = "Death": K1$(1, 2) = "i": K1$(1, 3) = "i"
K1$(2, 1) = "Life": K1$(2, 2) = "i": K1$(2, 3) = "i"
K1$(3, 1) = "Self": K1$(3, 2) = "i": K1$(3, 3) = "i"
K1$(4, 1) = "God": K1$(4, 2) = "i": K1$(4, 3) = "i"
K1$(5, 1) = "Existence": K1$(5, 2) = "i": K1$(5, 3) = "i"
K1$(6, 1) = "Being": K1$(6, 2) = "i": K1$(6, 3) = "i"
K1$(7, 1) = "Reality": K1$(7, 2) = "i": K1$(7, 3) = "i"
K1$(8, 1) = "Others": K1$(8, 2) = "i": K1$(8, 3) = "p"
K1$(9, 1) = "Thought": K1$(9, 2) = "i": K1$(9, 3) = "i"
K1$(10, 1) = "Knowledge": K1$(10, 2) = "i": K1$(10, 3) = "i"
'-----------------------------------------------------
K2$(1, 1) = " defines ": K2$(1, 2) = "i": K2$(1, 3) = "s"
K2$(2, 1) = " is defined by ": K2$(2, 2) = "i": K2$(2, 3) = "s"
K2$(3, 1) = " creates ": K2$(3, 2) = "i": K2$(3, 3) = "s"
K2$(4, 1) = " is created by ": K2$(4, 2) = "i": K2$(4, 3) = "s"
K2$(5, 1) = " define ": K2$(5, 2) = "i": K2$(5, 3) = "p"
K2$(6, 1) = " are defined by ": K2$(6, 2) = "i": K2$(6, 3) = "p"
K2$(7, 1) = " create ": K2$(7, 2) = "i": K2$(7, 3) = "p"
K2$(8, 1) = " are created by ": K2$(8, 2) = "i": K2$(8, 3) = "p"
'------------------------------------------------
K3$(1, 1) = "death.": K3$(1, 2) = "i": K3$(1, 3) = "i"
K3$(2, 1) = "life.": K3$(2, 2) = "i": K3$(2, 3) = "i"
K3$(3, 1) = "self.": K3$(3, 2) = "i": K3$(3, 3) = "i"
K3$(4, 1) = "being.": K3$(4, 2) = "i": K3$(4, 3) = "i"
K3$(5, 1) = "others.": K3$(5, 2) = "i": K3$(5, 3) = "i"
K3$(6, 1) = "existence.": K3$(6, 2) = "i": K3$(6, 3) = "i"
K3$(7, 1) = "reality.": K3$(7, 2) = "i": K3$(7, 3) = "i"
K3$(8, 1) = "God.": K3$(8, 2) = "i": K3$(8, 3) = "i"
K3$(9, 1) = "thought.": K3$(9, 2) = "i": K3$(9, 3) = "i"
K3$(10, 1) = "knowledge.": K3$(10, 2) = "i": K3$(10, 3) = "i"

As you can see, as with tags, dimensions 2 and 3 are used to store the gender and the number of the elements.

The tables documented above are for the creation of the K Phrase (i.e. the third phrase). The program randomly selects an element from each table and finally creates the phrase to show to the use.

The phrases are generated, by generating random number and then using these numbers to get the relevant entries from the tables defined above.

An example of the code used to get random numbers and create the phrases (the example is from Phrase K) is depicted below.

'----------------------
'Generate third phrase
'----------------------
PhraseK:
RANDOMIZE TIMER
A = INT(RND * 9) + 1: B = INT(RND * 7) + 1: C = INT(RND * 9) + 1
IF C = A THEN GOTO PhraseK
'If number is not equal (plural with plural, single with single) or the number of the next element is not indifferent, then generate phrase again
IF K1$(A, 3) <> K2$(B, 3) AND K2$(B, 3) <> "i" THEN GOTO PhraseK

As said before, the code is simple. In most cases it is. It is the idea that could be complex either in percieving it, implementing it or both. (or selling it I would say, but that is part of another bigger discussion)

Phrases generation rules

There are some basic validation rules applied for the phrases generation. As the program progresses, these rules will be amended and improved.

One rule for example is the following: the number of an element must match with the number of the tag combined with that element. The code below does exactly that thing: If the number (i.e. the 3rd dimension) of the first and the second element do not match, then the program is instructed to go back and generate the phrase again.

IF K1$(A, 3) <> K2$(B, 3) AND K2$(B, 3) <> "i" THEN GOTO PhraseK

If the validation fails, then the program generates a new phrase.

Printing the phrase

After the phrases are generated, they are printied on the screen. With what else than the… PRINT command.

Voila!

A philospher at your own hands!

APPENDIX I – Neural Network

Neural networks are all about having a program learn from its mistakes. Usually this happens with feedback from its user, while the most advanced programs have the ability to learn also on their own. I attempted to start implementing a primitive type of neural network capability.

If the user activates the Learning Mode, the program asks for input after each phrase it produces. If the input is negative (i.e. the user says that he did not like the phrase generated) then the program stores the combination in a table storing ‘bad’ combinations with the code below.

PRINT "": PRINT "Was this sentence a good one? (y/n)"
e$ = ""
DO
    DO
        hyn$ = INKEY$
    LOOP WHILE hyn$ = ""
    SELECT CASE hyn$
        CASE "y", "Y"
            e$ = ""
        CASE "n", "N"
            BadCombinationsK(Kcounter, 1) = A
            BadCombinationsK(Kcounter, 2) = B
            BadCombinationsK(Kcounter, 3) = C
        CASE ELSE
            e$ = "A"
    END SELECT
LOOP WHILE e$ <> ""
PRINT "Thank you for your input.": PRINT ""

The next time the program speaks with the user, the bad combinations are not used in the phrase generation. In that sense, the program learns from the human input. One can visualize the nodes and their combinations are human brain neurons – the neurons which are not used often are gradually disabled while the neurons which are used often are strengthened. Now the program only has the capability to totally ‘delete’ one set of nodes from the possible responses, but future enhancements could see it behave in a more elaborate way.

An example of the code doing that is depicted below.

'Neural network: Check if the combination selected was discarded by human previously. If yes, generate a different one!
FOR I = 1 TO Kcounter
IF BadCombinationsK(I, 1) = A AND BadCombinationsK(I, 2) = B AND BadCombinationsK(I, 3) = C THEN GOTO PhraseK
NEXT I

As mentioned above, this is the simplest form of a neural network: The program ‘learns’ from human interaction and adjusts the ‘nodes’ (elements used for the phrases) inside its ‘brain’ (tables holding the elements used for the phrases) accordingly.

Note that this works only inside the same instance of the program. Whenever you restart the program the ‘bad nodes’ are forgotten, since they are not stored permanently anywhere.

Improvements that are coming soon

  • Make the learning not only disable nodes (0 or 1), but also decrease the likelihood of a node being used (with probability values between 0 and 1).
  • Store what the program has learned into a txt file, so that the next time you execute it, it still ‘remembers’ what it has learnt.

APPENDIX II – The source code

You can click at the link below to get the source code.

Simply copy-paste it into a QBasic editor and execute.

APPENDIX III – How to configure the program

The program is easy to configure. And that is why it is so fun! I have added phrases which are related to my personality and the way I am thinking. You can alter them to reflect yours!

You can also add new elements for the phrases! Simple go and add new elements in the relative tables. When doing that, rememeber to also define the gender and number of the element.

After having added the new element, do not forget to increase the relative constant which defines the size of the table! The constants defining the size of the elements’ tables can be found in the beginning of the program.

Programming for kids: Developing a chess program in BASIC – Part 4: Advanced concepts

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

Hello again!

After having published various tutorials on basic chess programming, it is time to move on to more advanced concepts.

Programming for kids – How to program a chess program in BASIC

Existing chess tutorials

Huo Chess resources

This article will touch-base on some more advanced concepts in chess programming:

  • Thinking for more moves ahead in the game
  • Improving the position evaluation
  • Selecting the best move (miniMax concept introduction)

Up to now the program we have developed (see the previous lessons, where you can download the program) can think in one (1) move depth. This means that it simply (well, not ‘simply’ – we have gone a long way to make this happen) scans all the possible moves and then selects the one with the highest score.

This has just gave us an insight of the way a computer may think for chess, but a very limited one. The basic thing for thinking for chess is thinking in depth. Everybody would agree that thinking in more depth makes someone a better player.

How can we make that happen?

Simple!

We will copy-and-paste (sort of speak) the main computerMove SUB (Move depth 1 – Existing) two times more, so that the computer also thinks two moves more in depth. In essence, there will be two additional ‘thinking SUB-routines’: One which thinks of the potential human moves (Move depth 2) and another that thinks of the reactions of the computer to those moves (Move depth 3).

After that we will have the following structure:

DEPTH 1: computerMove: This routine thinks of the potential moves of the computer at the first level of thinking. If the thinkingDepth is not reached (i.e. if it is not set to 1, but e.g. 3) then the HumanMove1 SUB is called.

IF Move = thinkingDepth THEN
   '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

IF Move < thinkingDepth THEN CALL HumanMove1(chessboard$())

DEPTH 2: HumanMove1: This routine is scanning for all the possible answers of the human opponent. For each of those movements, the next thinking depth routine is called.

DEPTH 3: ComputerMove2: The last routine. Searches for possible moves at depth 3 (i.e. 3 half-moves). The move which ends up with the position with the best score at the end, is the one chosen.

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

With these you will have the program think in depth of 3 half-moves (i.e. a move of the computer, a move of the human opponent and a last move by the computer).

You can download the program below.

Download Source Code

Simply copy and paste the code in your QBasic editor and try it out!

One can also download a graphics version, where I have added the graphics engine by Deep Chess (by Thomas McBurney).

Important: For it to work, copy the PIECES.EGA file you will find in the Deep Chess site to the same folder as your program (this file contains the images of the pieces).

Make sure you keep on coming to this page for updates of the code.

Opening Book Editor

The latest versions (v0.6) of the code have an opening book functionality. In order to generate the files of the opening book you can use the Opening Book Editor found below.

Simply run the program, play the moves you want to store in the opening book and they will all be stored in separate txt files. These files must then be places in the same folder as the Huo Chess executable for the latter to utilize them.

As with Huo Chess, make sure you visit this page again to check for any updates or improvements in the code!

Advanced concepts: Improving the computer thinking

The algorithm described above is simple and does make the computer think in depth. When using the code below, you will see an obvious latency in computer’s thinking vis-a-vis the time needed by the previous version which thinks in depth of only 1 move.

However it does not make good moves!

What is needed for that to happen?

First improvement: Improvement of the position evaluation.

Now we are just counting the material in the final position.

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

But material is not everything.

For example in the initial position all moves seem to result in the same material score, however it is known that in the chess opening the good player always moves hies pieces near the center of the chess board, avoid unnecessary movements of the king and the queen and avoids to move the same piece twice.

Make sure to check the latest version of Huo Chess uploaded, to see how qualitative criteria were added in the countScore SUB!

EXERCISE: Try to improve the countScore SUB to cater for the above. You might need to also introduce a new variable which will count the number of moves we are in the game, so that the computer knows if we are at the opening, the middle of the final stage of the game.

Second improvement: Apply the MiniMax algorithm

The thinking mechanism of the program we have desribed is inefficient. One could say that it is inherently flawed.

The program searches for the best score at the end of 3 half-moves, but does not cater at all for the fact that the human opponent moves (at move depth 2) will not be the ones which maximize the score for the computer, but the ones maximizing the score for the human opponent.

In other words: The variants (set of moves) which include completely stupid human opponent moves end up in high scores in favor of the computer and that is why, those variants will at the end be chosen.

But in real life the human opponent will never play his worst moves, but quite the opposite: He will play his best moves so as to win the computer!

The following example will better illustrate the problem.

Imagine we are at the following position…

Important note: The Huo Chess program was developed with simple text-like ‘graphics’. There is also a graphics-version based on Deep Basic chess program (by Thomas McBurney), which you can also download.

An initial version of Huo Chess which simply thought in terms of the best score at the end of 3-half-moves, would play… Qf7+ in this position.

But this is a bad move! Why does it play that?

Simple.

The computer assumes that at the next move human will play something stupid and then it will be able to capture the king of the opponent. The set of moves “1. Qf7+ [something stupid] 2. Qxe8” results in the best (highest) score for the computer, so this move is selected.

The algorithm did not even think that human after Qf7+ will simply play KxQf7 and take the queen, simply because this move results in low score for the computer.

But how do you take into account the best moves for the human opponent (MAXimize value) and at the same time the worst possible variants for the computer (MINImize value)? In other words, at the end, how can the computer play its best move taking into account the worst scenario, which we will have only if the human opponent plays his best move?

EXERCISE: Try to think of the above on your own, WITHOUT reading online about the MiniMax algorithm. First of all – who knows? – you might think of something better! Secondly, one only masters knowledge when he has tried on his own and failed to acquire it. Having things ready for you simply does not lead to wisdom.

The solution to the above problem is the MinMax algorithm. The current version of Huo Chess utilizes it, so you can read there how it works. However note that you can never learn anything by simply copying the program of someone else. Unless you write the program on your own, make mistakes, spend countless nights and days pondering upon them, you will never truly develop anything.

Make sure you check the relevant Huo Chess C# tutorials which refer in more depth to the algorithm (which stays the same regardless of the programming language you use of course).

More updates coming soon!

Until next time…

Happy coding!

Exit mobile version
%%footer%%