I am trying to write a program that will return True if the white king on a chess board is in check. The pieces on the board are generated as a string and formatted as such, where the lowercase values are white and the uppercase are black.:
r*x***k****p***P*****Q*****kp****K*****p***Pb****p***PP***X***KR
| | |X| | | |K|R|
| |p| | | |P|P| |
| | | |P|b| | | |
| |K| | | | | |p|
| | | |k|p| | | |
| | | | | |Q| | |
| | | |p| | | |P|
|r| |x| | | |k| |
I understand how to transform the units on the board into x and y coordinates, and the mathematical operations of the pieces on the board (check pawns on +7 and +9, check rooks on ...-2, -1, +1,+2... and ...-16, -8, +8, +16..., but i can't translate this to python, or stop the check if it hits another piece or before it goes "past" the board and loops around again. Here is my code so far, but nothing really working correctly:
def white_check(coded_position):
w_king = coded_position.find("x")
w_king_x = w_king%8
w_king_y = w_king//8
result = False
print(w_king)
# This doesn't work if king is on x = 0 or 8
# Returns true if pawn checks
# if coded_position[w_king+7] == "P" or coded_position[w_king+9] == "P":
#result = True
# try using for loops and going up 1 / 8 at a time and trying each case for rooks / and bishops
# checks right side for rooks
for i in range(w_king,w_king-w_king_x+8):
if coded_position[i] != "*" and coded_position[i] != "K":
result = False
break
if coded_position[i] == "K":
result = True
# checks left side for rooks
for i in range(w_king,w_king-w_king_x,-1):
if coded_position[i] != "*" and coded_position[i] != "K":
result = False
break
if coded_position[i] == "K":
result = True
print(result)
return result
I think I am really over-complicating this, is there anything obvious that I am missing?