我正在为连接4的游戏编程。游戏数组为(6,7),并且在玩家尚未移动的位置包含0。有2位玩家(玩家1和2)。目前,这就是我检查胜利的方式
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
谁能想到一种无需for循环(或至少减少迭代次数)的处理方式?我查看了numpy.diff并创建了一个到7的for循环以同时检查行/列(将迭代次数减少了7/12)。但是我无法提出实现方案。
答案 0 :(得分:0)
基于Checkio - Xs and Os solution和that answer的解决方案:
def check_success(field):
rows = field.tolist()
cols = field.T.tolist()
diags = [field[::-1,:].diagonal(i)
for i in range(-field.shape[0] + 1, field.shape[1])]
diags.extend(field.diagonal(i)
for i in range(field.shape[1] - 1, -field.shape[0], -1))
lines = diags + cols + rows
for line in lines:
if "2, 2, 2, 2" in repr(line):
return "2 wins"
elif "1, 1, 1, 1" in repr(line):
return "1 wins"
return "no winner"
它提高了可读性,而不是效率。但是,对于6 x 7
字段,效率并不是至关重要的。