r/javahelp • u/poepstinktvies • 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
I create an function(isSafeSpotForKing) that is a condition during the calculating the king moves, to ensure the position is safe
this functions loops through all pieces of the opponent calculates the valid moves from the opponent
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
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.
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.
1
u/[deleted] Jan 11 '20
Maybe post your code(?)