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

Advertisements
Huo Chess DV (GUI Edition)

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#

How to code a chess program in one day. (C# and Java examples)

Advertisements

Introduction

Coding is easy.

Today there are a lot of people learning how to do it.

Why not you?

And you know what is the most difficult step in learning how to code?

TO START LEARNING.

You know there is an old Buddhist saying claiming that “When the student wants, the teacher appears”. So the question is not whether there are tutorials out there to teach you. There are a lot. Here or elsewhere, you can easily find articles showing how to code.

The question is: Are you willing enough?

(And yes, Harmonia Philosophica is mainly a philosophy portal, so feel free to read about philosophy while trying to debug your first chess program)

For this ultra quick training I will use a Java edition of my Huo Chess program. This edition lacks basic functionalities like deep searching, but it can however play chess according to the rules and choose the best move at the current position based on which move earns the most material.

Places to download Huo Chess (source code and executable)

License: You can reuse the code you see here in any way you want, as long as you mention the author and the place where you read it first!

RELATED TUTORIALS:How to program a chess program for dummies” series will give you a more detailed description of how to create your chess program! Check also the Programming for kids: Developing a chess program in BASIC and the Programming a chess application in QBasic (QB64) tutorials for developing a chess program in BASIC programming language. Check out also the “How to develop an adventure game ultra-fast tutorial” tutorial! You could also find interesting the HUO Writer: A simple AI writer with basic Neural Network capabilities (QB64) article.

千里之行,始於足下

(A journey of a thousand miles begins with a single step)

~ Lao Tzu, Tao Te Ching

Step 1: Get a programming interface

This tutorial will show you how to code a demo chess program in one day, even without any prior knowledge of programming. All you need is a programming interface to write and compile (i.e. make an executable program out of your code) the code that you will write. These are also known as Programming IDEs (Integrated Development Interfaces). This could be the Microsoft Visual Studio (the Express edition of which can be downloaded for free) for C# or any Java compiling studio available out there (like NetBeans for example, which again can be downloaded for free).

The tutorial will not cover the details on how to use these programming interfaces. But this is not something hard to learn anyway. Just go to the web (or the page of the tool itself) and you will gain an understanding on how to write a small console program (this is what we are going to do here) in less than an hour. When I refer to a console program I mean a program which does not have graphics but only displays text. We will start with building such a program since writing code for graphics will surely need an additional effort to learn how to do it. And it will be easy to later on add graphics to your program, once you have the AI logic of the chess engine up and ready, don’t you think?

Open the IDE and select to create a new project…
Select to create a simple application…
Your program is created. All you have to do is add the code…

Tools to use for coding your program

  • Microsoft Visual Studio (free edition)
  • Java NetBeans

After you download the IDE, install it in your computer and go to the option New Project. Select to create a simple C# console application (in Visual Studio) or a simple Java program (in NetBeans). Click Create and there you are. You have the shell in which you will add your chess program code!

Step 2: Design the chess program structure

Let’s go into the chess program now.

But wait!

Don’t we need to learn the programming language first?

The answer is simple: NO!

You will learn them as you go.

This is how I (and many others) learned programming in the first place. I opened my Commodore computer and started typing my first program by copying the code from the manual. After I typed it in and spent time to get it right (even copying can be difficult, especially if you are a rookie) I typed RUN and I had my first game! Forget the long chapters of books trying to teach you – after reading 100 pages – how to just print “Hello world” on a screen. Programming is for people who like experimenting and are not afraid to simply start trying things on their machine.

So just go ahead!

You will read here about the basic structure needed for the program, and then you will see the commands required to code that structure into a C# or Java program. The commands are fairly simple and you will understand what they do as you write the program. Do you really need a programming language manual to understand what an “if” command does anyway?

The main structure of the program is depicted in the following schema.

Fairly simple isn’t it?

The story goes like this…

  1. You get input from the user for his move. [EnterMove function]
  2. You check the legality and the validity of the move entered [ElegxosNomimotitas and ElegxosOrthotitas functions, which also utilize the CheckForWhiteCheck and CheckForBlackCheck functions to check if there is a check in the position]
  3. If the move is legal and valid, then do the move. [call drawPosition function to redraw the chessboard; note that the Java edition of the program only prints the chessboard in text]
    • Exercise for you: Add graphics to the application. (use the C# edition ot get some insight on how you could do that)
  4. Call the function which makes the computer think. [ComputerMove function]
  5. Scan the chessboard to find all the pieces of the computer. In the sample code provided for Java, this means that it scans for all the black pieces since the program is made only for the computer to play with black.
    • Exercise for you: Add the ability for the program to play with white as well)
  6. For each piece of the computer, check all possible moves to all possible squares of the chessboard.
  7. If you find a valid move (by invoking the ElegxosNomimotitas and ElegxosOrthotitas functions) then do the move and count the score of the position. [CountScore function: This is one of the most central functions of the program; changing it makes the computer play differently according to the values you assign to pieces or to elements of the chessboard like empty ranks, concentration of the pieces at the center et cetera]
  8. If the score of the move is better than the so far better score, then store this position as the best one. (Note: The program stores the first position analyzed as ‘best’ anyway, so that there is a starting point for the best score)
    • Exercise for you: Change the values in the CountScore function to improve the playing abilities of the computer)
  9. Do the best move found and redraw the chessboard.
  10. Wait for next user input. [call EnterMove function again]

The Java edition of the program does not think in more depth. It just finds the move which earns the more material and makes it. This is not chess isn’t it? Well actually it is. The basis for a good chess program. All you have to do is improve it.

Look at the C# version of “Huo Chess” (search the web for it, there are many repositories where I have uploaded the code, including MSDN Library, CodePlex and Codeproject) to gain a small insight on how the chess program can search into more depth.

Exercise for you: Make the Java edition of the program to think in more depths, by adding more “ComputerMove”-like functions to analyze the next potential moves for the human and the computer. Be careful how you pass over the chessboard between these functions. (yes, Google will be your best friend)

Related resources for C# Huo Chess edition

Step 3 : Write the code

This last section contains the source code of the chess program in Java.

As mentioned above, look for “C# Huo Chess” in the web (See the Recourse listed above) to see the full source code of that Huo Chess edition. This code is also heavily commented to make it easy to read and re-use, while the names of the functions are the same as in the Java edition of the program.

Look also at the “How to program a chess program for dummies” series here in Harmonia Philosophica, to get some more details on the Huo Chess program. (the tools used in those articles are a bit outdated, but yet the logic is still the same)

Paste that code into the main java file in your NetBeans project and compile it.

Execute your program and enjoy your new chess game.

Epilogue

So there it is. Depending on your copy-paste and reading comprehension skills, you now have a working chess program on your hands and some knowledge on how it could be improved. Everything is up to you now.

Happy coding!

And don’t forget: Keep experimenting!

The worst thing that could happen?

To just ruin your computer…

How to Develop a Chess Program for Dummies

This series of tutorials for dummies will show how one can develop a chess playing program in C# from scratch with no prior knowledge of programming. It will guide the reader step-by-step until the final building of a fully-features chess application in Microsoft Visual Studio. The tutorial is based on the open source Huo Chess software developed by me.

Advertisements

Other Related articles

Huo Chess – The program we will code…

Huo Chess is one of the smallest open source chess applications. It is an application that I have personally developed and distribute as fully open source via many channels in the Internet. One can download it for free from the MSDN Code Gallery, Codeplex Huo Chess site or its Codeproject page. In the series I will analyze how one can program the computer to play chess. The final “deliverable” will be the full Huo Chess program as it can be found in the Internet.

Note: An intermediate/ advanced programmer can go directly to the above links and download the Huo Chess source code so as to study it directly. Please contact me for any questions on the code or the algorithm either via email (skakos@hotmail.com) or via comments in this article (Knol). However, even though the source code of my chess is heavily commented, starting looking directly at the full program source code without first reading the lessons I have posted here at Google Knol is not advised for beginner programmers.

Method of teaching

The method I will use for teaching you how to program is by example. The “try to do something and see what happens” may sound like a bad method, but it is actually the best when it comes to computers programming. As long as you have kept a backup of all your valuable files, you must and should try anything with programming if you really want to learn! That is why I will show practical steps you need to follow and I will guide you through every stage of the programming process, without first giving a 100-page lecture on the theory or the basic principles of programming. You will be taught the theory you need to know as we progress through the steps of building the chess game. That method is the method actually used by programmers in the 1980’s. We used to experiment with new things, try new techniques and learn from our mistakes. There is no better way of learning than experimenting and doing mistakes. You will never learn from something you did right in the first place!

The language of choice is C# and the tool we are going to use the Microsoft Visual Studio. However please note that I have created and distributed versions of the “Huo Chess” also in C++ and in Visual Basic. Feel free to search for the free source code in the Internet (I am now trying to create a Commodore version).

Getting started

The first thing you need, is the tool with which you will program. You can download the Microsoft Visual Studio – Express Edition from the respective Microsoft Visual Studio Express Edition site. The “Express” editions of MS Visual Studio are completely free to download and they include all the programming tools and features a novice, intermediate or even an advanced programmer needs. After you download it, installing it is what is keeping you from programming your first game application!

Installing Visual Studio

After you have downloaded the MS Visual Studio – Express Edition, you will have to install it. Installing the Visual Studio is no more complex than the installation of any other program.

You just double-click the file you downloaded and the installation will automatically begin. Normally, the setup will install the Microsoft .NET Framework if it isn’t already installed in your computer (the .NET Framework is required for the Visual Studio to operate – Huo Chess requires .NET Framework 2.0 or above to work) and the Visual Studio. An icon with the characteristic sign of the Visual Studio will appear in your desktop.

Using Visual Studio

Double-click the icon of the Microsoft Visual Studio to begin programming. The Integrated Development Environment (IDE) of the Visual Studio will appear and you are now ready to make your application.

Create a new project

First you need to create a new project. Go to the menu and click File > New > Project.

From there you must choose the language in which you will develop your program. We will write our chess in C# so we must select Visual C# > Windows > Console Application (later we will show how we can also program the same game in C++ or other languages). To create a chess program with a user interface you would need to choose to create a new Windows Forms application. (that would be easy after you have created the code to play chess)

A console application is an application with no graphics. We will start developing our chess game Artificial Intelligence engine as a console application in the beginning and afterwards, when the computer can think and play chess, we will add graphics (that will be the final step in this programming tutorial series). Name the new project “Huo Chess tutorial” and press OK. Visual Studio will do its work and create all the initial things required for you to start developing.

The project is by default saved in a folder with the name you specified, that resides in the My Documents/Visual Studio folder.

Start developing

After you have created your project, you can start programming. The window will initially look like this.

That is a good point to say some things about programming. Programming in one of the modern languages of today entails using three elements:

  • Variables
  • Functions
  • Classes

All programming uses these three elements and if you master them properly then you can do everything. I will try to explain these elements in summary in the lines below.

Variables

The variables used in a program are the elements which store values, that are used in the program. Variables come in many types depending on the type of data they will be used for. For example you can declare an integer variable to store integer values, or a float variable to store numbers with a decimal segment, or a String variable to store text.

The first variable we will use in our program in the variable which will store the color of the human player in the game. In particular, after the human player starts our game he/she should choose the colour with which he (excuse me ladies for using the “he” instead of the “he/she”, but I am a man so I am used to it) will play.

We will declare our variable in the class program by entering the code public static String m_PlayerColor; as seen in the following figure.

Some clarifications are needed here: Every command in C# must end with semicolon (;). Secondly, we declared the variable as public which in short means that it will be visible from every part of our program (the opposite, private variables can be accessed only inside the function/class we declare them in). The static keyword should not concern you at the time (it actually means that only one instance of the variable can be created as the program executes, but we will have more on that later on the tutorial series).

You can then define the value of that variable by hard-coding it in your program. Try to enter m_PlayerColor = “Black”; in the Main function of your program and then print it to screen with the command Console.WriteLine(m_PlayerColor); as seen in the next figure (in fact I have added a Writeline command more as you can see).

Compile the program

The first thing you must do when programming a change in your program is to save your work. Select File > Save All… to save all the changes you made. After you have saved the program, you may want to execute it in order to see what you have done. Before a program is executed, it must first be compiled. Compiling a program means converting the programming language file you just saved to a form readable by the machine (i.e. machine language, which is comprised of 010101’s). Select Build -> Build solution to do that as illustrated in the following figure. If you have followed the steps above, no errors will exist and the compiler will notify you that the solution was successfully built.

Then select Debug > Start without debugging (or simply press Ctrl + F5) to start/ execute your program. The following will show.

You have just created your first program which includes declaring a variable and printing it to screen.

Note about the graphics

The graphics of the chessboard will be added at the final stage of the project. Right now we will focus on developing the chess engine algorithm which is the most difficult part. That is why we started by developing a console application (i.e. an application without graphics). We will worry about the graphics after we have created a fully functional chess AI engine.

Let us now say some things more about functions and classes as promised.

Functions

Functions are code segments which require some input to perform a specific action and produce a specific result. For example you can have a function that adds two numbers called Add_numbers. The code for that function will look something like that (you do not have to code anything in your Huo Chess project now, this is just for theory education purposes):

int Add_numbers(int Number1, int Number2)

int Add_numbers(int Number1, int Number2)

{
      int Result;
      Result = Number1 + Number2;
      return Result;
} 

The code is simple and intuitive, isn’t it? The “int” in the beginning declares that this function will return an integer number as the result of the process it implements. The two integer variables in parenthesis declare the input required for the function to work. That is why when you need to call that function you should call it in a way like the one listed below:

int myAddResult;
myAddResult = Add_numbers(5, 6); 

The above code calls the function Add_numbers by giving it the input of number 5 and 6. The result will be the function to return the value of 11 (= 5 + 6) which we have allocated to variable myAddResult.

Object Oriented Programming

Functions and variables can be used in creating objects. These objects are called classes and are the cornerstone of the Object Oriented Programming (OOP) you may have heard many times before.

Classes

But how do you create and use objects? First, you have to declare the class of the object. For example, if you want to create an object called ‘Blue Calculator’, you must first create and declare a class of objects called Calculator. Define the parameters of that class: the variables it will be using (i.e. the color of the calculator, the numbers which the user will enter in the calculator by pressing the buttons + the result that the calculator will print on its screen) and the methods (or functions) that the calculator will utilize in order to reach the result (i.e. functions for adding numbers, subtracting number etc).

The definition of that class will have the following scheme (independent of what the programming language you use may be):

class Calculator

 class Calculator
          {
               // Variables
               Number_type number1;
               Number_type number2;
               Number_type Result;
               Color_Type Calculator_Color;
               // Methods
               Function Add(number1, number2)
               {
                    Print “The result is:”, (number1 + number2);
               }
               Function Sutract(number1, number2)
               {
                    Print “The result is:”, (number1 – number2);
               }
          } // End of class definition 

The two slash (//) text are comments. Whatever you write after these slashes is not taken into account by the compiler. It is considered best practice to write comments in your code.

After you have properly declared your class of objects, you can create as many objects of that class you like and use them in your program. For example you can create a new blue color calculator by writing a command that could look something like that:

Calculator my_calculator = new Calculator(Blue);

You can then use the member-variables and member-functions of the calculator with commands like:

Integer no1 = 2;
Integer no2 = 7;
Print “Result = ”, my_calculator(Add(no1, no2));
// this should print ‘9’ in the screen
my_calculator.number1 = 20;
Print “Result = ”, my_calculator(Add(my_calculator.number1, no2));          // this should print ‘27’ in the screen

The specific commands again depend on the programming language you use, but you get the meaning. It is all too easy: Declare class => Create new object of that class => Manipulate / define parameters of the new object => Use member functions of that object to generate the result they are designed to generate.

It may be difficult for you to grasp, but ALL programming in ANY language (C++, C#, Visual Basic, Java etc) are based on that logic. What is more, the languages themselves have some ready-made classes that you can use to develop your programs! For example, Visual C++ and C# in the Microsoft Visual Studio has a stored class for Buttons. To add a button to your application, you just write:

Button my_button = new Button();
my_button.color = Blue; 

You don’t have to reinvent the wheel! That simple (and I think you understand what the second command does, without telling you…)! I keep repeating myself, in order for you to stop fearing the unknown realm of programming and just…start programming! The ready-made classes (or even simple functions) are usually stored in packets called ‘libraries’. Add the library you want in your program and them just use any class/ function it contains.

Classes you already use without knowing it

You may think that all the above have nothing to do with the code you just wrote. But you would be wrong. Your program, even at this initial stage, uses many classes without you knowing it! Actually Microsoft has developed some classes that facilitate programming for Windows and you are using these classes with the “using” statements in the beginning of your code. You do not have to know more details about that now, just be aware that you can program your chess because someone else have already developed and implemented a great number of classes in order to help you do that.

A good example of classes you already use if the Console command you wrote in order to print the player’s color. Remember that the command looked something like that:

Console.WriteLine(m_PlayerColor);

The above code actually uses the class Console and calls one of its member-functions: the WriteLine function (that is why the dot is required: to call members of classes as we said above). That functions requires input: the text that you want to display. That is what we write in the parenthesis!

Intellisense

The Visual Studio has embedded features that help you know which are the members of the various classes and how to use them. So when you write “Console” and then enter a dot, the Intellisense of Visual Studio produces a list with all available member variables and functions of that class. You will find yourself more comfortable with the use of Visual Studio and C# only after you have tried to use many of the functions appearing in that list on your own and see what happens. Remember, experimenting and doing mistakes is the only way to learn!

Get user input

In a similar way to printing something to the screen, you can get user input. You will find that very useful when you want the user to enter his/her move for the chess game. In this point, we will require the user to enter his color of choice by using a function similar to Writeline: the Readline. See the figure below on how that can be accomplished.

The code is simple and straightforward. You print instructions to the screen and then read the input from the user. When the user presses “Enter”, the value he entered is allocated to the m_PlayerColor variable which is then printed on the screen.

Next lesson

In the next lesson we will learn how to instantiate the chess board, build the Artificial Intelligence engine of the program and the program’s user interface structure. Until then, try to enter the following code in the program:

 if (m_PlayerColor == “Black”)
               Console.WriteLine(“My first move is: e2 -> e4”);
          else
               Console.WriteLine(“Please enter your first move!”);

Save, compile and run the program. You will see that if the player enters “Black” the program “plays” a first move! Well, actually this is not the way we will use to develop our AI (using “if” statements is not the way to make the machine think), but what I want to note and emphasize here is the simplicity of programming in general. All you need is will to learn!!!

What we have accomplished

In this first lesson, we have accomplished many things which are listed below:

  • Created our first project in MS Visual Studio.
  • Learned how to save, compile and execute the project via Visual Studio.
  • Learned how to print text on the screen.
  • Learned how to use variables and read user input from the user.
  • Gave a look at our first code structure command (“if” command).
  • Learned about functions and classes.
  • Understood the basics of Object Oriented Programming.

Until the next time, happy coding and experimenting!

How to Develop a Chess Series updates

  • Update 2009-06-04: Due to other obligations the next lesson is not going to be published as soon as I expected to. However I am in the process of writting it and it WILL be published as soon as I can.
  • Update 2009-07-30: The new lesson of the series is now published
  • Update 2011-09-29: The third lesson with the chess algorithm analysis is now published!
  • Update 2018-12-02: Refreshed the article. Fixed minor mistakes.
  • Update 2020-03-21: Minor updates and fixes.
Exit mobile version
%%footer%%