+local rowDirs = {-1, -1, -1, 0, 0, 1, 1, 1}
+local colDirs = {-1, 0, 1, -1, 1, -1, 0, 1}
+
+local bishopThreats = {true, false, true, false, false, true, false, true}
+local rookThreats = {false, true, false, true, true, false, true, false}
+local queenThreats = {true, true, true, true, true, true, true, true}
+local kingThreats = {true, true, true, true, true, true, true, true}
+
+local function king_attack(color, idx, inv)
+ local threatDetected = false
+ local kill = color == "white"
+ local pawnThreats = {kill, false, kill, false, false, not kill, false, not kill}
+
+ for dir = 1, 8 do
+ if not threatDetected then
+ local col, row = index_to_xy(idx)
+ col, row = col + 1, row + 1
+
+ for step = 1, 8 do
+ row = row + rowDirs[dir]
+ col = col + colDirs[dir]
+
+ if row >= 1 and row <= 8 and col >= 1 and col <= 8 then
+ local square = get_square(row, col)
+ local square_name = inv:get_stack("board", square):get_name()
+ local piece, pieceColor = square_name:match(":(%w+)_(%w+)")
+
+ if piece then
+ if pieceColor ~= color then
+ if piece == "bishop" and bishopThreats[dir] then
+ threatDetected = true
+ elseif piece == "rook" and rookThreats[dir] then
+ threatDetected = true
+ elseif piece == "queen" and queenThreats[dir] then
+ threatDetected = true
+ else
+ if step == 1 then
+ if piece == "pawn" and pawnThreats[dir] then
+ threatDetected = true
+ end
+ if piece == "king" and kingThreats[dir] then
+ threatDetected = true
+ end
+ end
+ end
+ end
+ break
+ end
+ end
+ end
+ end
+ end
+
+ return threatDetected
+end
+
+local function locate_kings(inv)
+ local Bidx, Widx
+ for i = 1, 64 do
+ local piece, color = inv:get_stack("board", i):get_name():match(":(%w+)_(%w+)")
+ if piece == "king" then
+ if color == "black" then
+ Bidx = i
+ else
+ Widx = i
+ end
+ end
+ end
+
+ return Bidx, Widx
+end
+