I am programming a game of connect 4. The game array is (6,7) and contains 0s in locations where a player has not yet moved. There are 2 players (player 1 and 2). Currently, this is how I check for victory
def check_success(game_array):
assert (np.shape(game_array)==(6,7)), 'Incorrect shape'
for s_r in range(3):
for s_c in range(4):
board=game_array[s_r:s_r+4,s_c:s_c+4]*1
D = np.einsum('ii->i', board)
DP = D != 0
if DP[0] and (D[0] == D).all():
return True, D[0]
L = DP & (D == board).all(0)
I = L.argmax()
if L[I]:
return True, D[I]
L = DP & (D == board.T).all(0)
I = L.argmax()
if L[I]:
return True, D[I]
D = np.einsum('ii->i', board[::-1])
if D[0] and (D[0] == D).all():
return True, D[0]
return False, 0
Can anyone think of a way of handling this without the for loops (or at least fewer iterations)? I looked into numpy.diff and create a for loop to 7 to check rows/columns at the same time (cuts the amount of iterations by 7/12). But I could not come up with an implementation.