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

1

u/thomasjjc Jan 12 '20

Maybe you should let the move that captures the king happen. It's a hyptothetical move only anyway. But then when the search algorithm makes the score for the resulting board, you should treat it as a win for the opposing player. That way that move should never be considered as a good move (and if all possible moves result in a win for the opposing player, your AI can give up an tell your player that he won).

That's how I did it in my Java chess engine.

1

u/morhp Professional Developer Jan 12 '20

I believe OP wants to create a chess game (with complete rules), not just an ai/engine. For an engine, your approach night be fine, but you should handle the case than the AI tries to make an illegal move.