spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / javachess / 3

Senior Consultant/Information Security - permanent position (TX)
Next Step Systems
US-TX-Irving

Justtechjobs.com Post A Job | Post A Resume
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

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.

home / programming / javascript / javachess / 3

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Symantec Whitepaper: Converging System and Data Protection for Complete Disaster Recovery
Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
  PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Symantec Whitepaper: Comprehensive Backup and Recovery of VMware Virtual Infrastructure
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Fixing MySQL Replication · Firewall Guide: First Steps to Securing the Enterprise · VoxOx Tames the Tumultuous Communications Tangle

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

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