r/javahelp • • Jan 11 '20

infinite loop in chess

currently i have a design problem in my chess game, im creating a functionality with means that the king cannot moved onto tiles that are being attacked for example by a rook

so i did program this as following:

0. Lets say the king has a list of 4 valid moves

  1. I create an function(isSafeSpotForKing) that is a condition during the calculating the king moves, to ensure the position is safe

  2. this functions loops through all pieces of the opponent calculates the valid moves from the opponent

  3. Then im comparing ALL the possible moves from the opponent with the possible valid moves of mine (based on x and y coords) 3.0 if compare reach true, the move is not valid ofc 3.1 if compare reach false, the move is valid

but the problem is The opponent has a king aswell, and whenever i trigger the function, it goes to the opponent pieces ( so eventuallly the opponent king (look step 2) so black player king > white player king > black player king > white player king, creating a infinite loop xd which results in a stack overflow error

18 Upvotes

8 comments sorted by

View all comments

2

u/morhp Professional Developer Jan 12 '20

I believe this is less a java problem and more a chess problem.

King proximity works in a way that kings may not enter the 3x3 grid around the other king, it doesn't matter that the other king may not be able to move to one of these squares because of check.

Also this would be much simpler by simulating the move and testing that the king can't be in check after that. Note that this applies to all moves, not just king moves. You can't move a pawn if that would cause the opponent's bishop to gets in "sight" of your king for example.

2

u/jasonthorpe Jan 13 '20

I agree, you can't mix checking for a valid square and checking to see if the move puts you in check in the same function

You need to find all the valid moves, and then see which one places the player in check. Then you can remove those squares from the valid moves list.