Javascript Chess Program, Pt. 3 - Web | WebReference

Javascript Chess Program, Pt. 3 - Web

Javascript Chess Simulator: Pt. 3

In this final section, I am going to create a few tweaks to the application that we created in the previous two sections. Here, we'll focus on validating the Move Lists and we'll create some enhancements for the User Interface.

Validation

In general, most of the functionality in this application is internal, and the same applies to the majortiy of the data used. Therefore, the application can be considered reasonsably robust, but the weakest link is the list of moves which drive the rest of the application.

Validation of this can be broken down into several distinct validation requirements (as follows):

As mentioned in the last section we're going to use the Algebraic Notation format, which provides us with a clear definition of how any given move can be recorded, from which we can deduce a series of validators to check our data. There are many ways that we can check (and validate) user data , but we'll use Regular Expressions. Let's take each component of the move, build a Regular Expression to support it and then combine them at the end.

Let's begin with a normal move; the from location is either two or three characters, e.g. Ra8, c4, Bc5 etc. Converting this to a Regular Expression we get [R,N,B,K,Q]?[a-h][1-8]. The next character indicates the type of move, either a dash for a normal move or a cross for a capture, so we have [-]|[x]. Then we have the 'move to' part, which is identical to the move from. Next, we have some indicators of what the move was, such as (ep) for en Passant, check or checkmate, converting these gives us \(ep\)?([+]{1,2})?. The only other non-standard moves we haven't covered is castling, which we can represent with the following syntax 0-0|0-0-0. If a player Resigns or a Draw is agreed, we'll use the upper case version giving us (DRAW)|(RESIGN).

After combining the elements we're left with a single RE which validates that the move is "synatically" valid and correct :

/^((([R,N,B,K,Q]?[a-h][1-8]([-]|[x])[R,N,B,Q]?[a-h][1-8](\(ep\))?)|0-0|0-0-0)([+]{1,2})?)|(DRAW)|(RESIGN)$/

Now that we have our function, we need to decide how to achieve it.. Since we built the components of the application (the board and the move list) separately, I'm going to implement this as a seperate function, and use it in the moveList function, so it validates the moves before it displays the list. The amended code can be found in this listing; the changes to the original moveList function can be found in red.

Although we can validate that the move elements are 'valid' (as defined in our rules of notation format), it doesn't tell us if the move is actually valid . For example, Kh1-e3 would be passed as valid by our Regular Expression, but is actually an invalid move.

Note: Validation of this kind is quite complex, and beyond of the scope of this article.

User Interface Enhancements

There are several enhancements we could make to the user interface, such as integrating it with an existing website or to use a pre-defined color scheme. A useful addtion would be highlighting the current move in the move list (using DHTML). Since we've already created an ID reference for each cell in the moveList function, we can add some logic into the updateDisplay function, so as the display panel is updated, we also unhighlight the last move and highlight the current move.

The logic in this section revolves around finding the pair of cells involved - i.e. the cell which needs to go from colored to uncolored and the one that needs to go from uncolored to colored. However, for the first move of the game, there will only be one cell involved. Once we've determined which cells to use, we use DHTML to change their cell background colors (a red background to highlight the current move and a white background for the rest). The changes are shown in this listing with the additions marked in red, and the results can be seen in this demonstration.

Using XML Datafiles

Up until now, all our move lists have been in the format of Javascript arrays - arr_whiteMoves and arr_blackMoves. However, we could also use XML files to store the move information and load those into our application.

To allow us to use an XML file, we will need to detect that an XML file is part of the input to the application and then load and process the XML file. Looking at our existing functionality, we need to implement this enhancement before the move lists are actually used. Thus, we're going to create a separate function to perform the tasks and we'll call this as the very first line in the moveList function.

We'll use an attribute in the Query String part of the URL to indicate that we wish to load an XML file and then if present, we'ill use some standard Javascript to process the file and populate our arrays so they can be used by the application. For our XML file we'll need to define a format so that others can create XML files to fit our format. All we need to store is the players names and their moves, so we'll use the following format :

<movelist>
    <players>
        <white>A N Other</white>
        <black>John Smith</black>
    </players>
    <move moveNo="1">
        <white>e2-e3</white>
        <black>e7-e6</black>
    </move>
    <move moveNo="2">
        <white>Nb1-c3</white>
        <black>d7-d5</black>
    </move>
    <move moveNo="3">
        <white>Bf1-c4</white>
        <black>Ng8-h6</black>
    </move>
</movelist>

To implement this, we'll need to get the name of the XML file out of the Querystring - not the easiest thing to do in Javascript - then read and process it, placing the results into the strings that hold the players names and the arrays that store their moves. Once completed, we run the standard functions over the move lists, so they are validated and presented to the user in the same way as a hardcoded set of moves. Our XML handler function is shown in this listing, and we can see an example of using an XML file in this demonstration.

Conclusion

We now have a complete working Chess application, which will allow visitors to a website to play through any Chess game (where the moves have been programmed into the site). These could be your games, or the games of a great player such as Karpov or Spasky. In the text accompanying the page we refer to any position in the game and we can provide a link that will reconfigure the board until it shows the required position.

There is still room for enhancing the offerings outlined here. Some of the possibilities are:

Hopefully, this series of articles has provided enough to get you started and perhaps interested in playing Chess.

In the process of preparing this series, I've encountered some useful websites which are available for your interest:

I'm sure there are many more useful sites on the internet, if you know of any I'd like to hear about them.

A complete working demo containing all of the code used in this series of articles is available here.

About the Author

Greg Griffiths is a lead developer for a US corporation. Currently based in the UK, he spends the bulk of his time working (in several languages) on all aspects of the life cycle of enterprise web based applications. His Chess experience comes from several years spent at Castell Nedd club in South Wales, UK, where he had a successful career at local, regional and county level as a player and team captain. A regular on IT related mailing lists, forums and newsgroups, he's been involved with books and web articles for Wrox, Builder.Com, CNet, etc. You can contact him through his web site at: http://www.greggriffiths.org.

Created: March 7, 2003
Revised: October 30, 2003

URL: http://webreference.com/programming/professional/javascript/javachess/3/index.html