File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Game Development and the fly likes Help with a chess program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Game Development
Bookmark "Help with a chess program" Watch "Help with a chess program" New topic

Help with a chess program

Christopher Beech
Ranch Hand

Joined: Feb 08, 2006
Posts: 40
I'm having some trouble with a chess program. My validMove method does not work correctly. It's forcing all the pieces to move like a king. I think it has something to do with the way I'm passing String piece to the function, but everything I have tried to fix it has not worked.

Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Your immediate problem is that you are comparing String values incorrectly. This:

compares to String references to see if they refer to the same object. If instead you want to compare two String references to see if their String objects contain the same sequence of characters -- which they could do even if they are two different String objects -- then do this:

I could go on and suggest that your idea of using Strings to represent your pieces is short-sighted. Instead you could have a Piece class which implements the validMove() method, with subclasses for each of the types of piece each of which implements that method in the appropriate way. But that's perhaps something to do for Version 2 of the game.
Christopher Beech
Ranch Hand

Joined: Feb 08, 2006
Posts: 40
That might help when the correct variable reaches the validMove mehtod. The problem is that the validMove method always gets piece as null. Since it doesn't match any of the strings, it treats the piece as a king.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

Wouldn't that have been a good thing to state at the outset? You really should probably read some of the How to ask Questions. specifically, I'd suggest AvoidRedHerrings, TellTheDetails, and IsolateTheProblem.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: Help with a chess program
It's not a secret anymore!