Skip to main content

On Sale: GamesAssetsToolsTabletopComics
Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines

I'm stuck - Checking for Check

A topic by sikosis created Apr 19, 2018 Views: 603 Replies: 4
Viewing posts 1 to 5

Looks like I'm stumped ... I've tried a number of methods to work out if the King is in check, but can't nail it down and I've ended up with a bunch of messy code that only half works. I'm half tempted to just leave it up to the players to use the honour system and work it out themselves.

Does anybody have any ideas?

Okay I kept at it and now have something that checks for check properly but nothing to force the player from moving into check. Guess I'll keep at it.

When I've done this in the past, my strategy has been to keep an array of possible moves for each piece. So to see if the king is in check, you just loop through the opponent pieces, checking each of their possible moves. Probably want to calculate the king's moves after all the other pieces. So when checking whether the king can move to a space, if it's a possible move by an opposing piece, don't add it to the array.

There are other benefits to maintaining these arrays too, for showing in the UI, etc.

(1 edit)

For my game Legions at War, checking moves of each piece was to slow so  I cached all the tiles in an array on start. When a piece is moved I update the tiles that, that piece is threatening, then it's as easy as looping through the cache to see if the king was in danger. 

(5 edits)

To check for Check you need to implement a function that checks if a given spot is currently being attacked by the opponent. Basically you loop through all of the opponents pieces, iterate trough all of their possible moves and see if they can attack that spot. Then you execute that function on the spot where the King is to see if the King is in Check.

Checkmate is more difficult. You need to iterate trough all of YOUR possible moves and see if after you perform the move the king is still in Check. As soon as you find one move that works, you can stop checking.

Another challenge is disallowing discovered Checks. So the player can't move into Checking themselves. Basically, if the player wants to move a piece somewhere, try the move real quick and see if the result would make the king be in Check. If yes, undo the move and cancel it.