我正在编写一个tic tac toe游戏,我陷入了代码应该检查玩家是否已赢得垂直的步骤,我知道c ++的朋友告诉我先通过COLUMNS迭代然后ROWS来制作流程更轻松。不确定它在python中是如何工作的。
所以例如玩家进入4x4表,过了一会儿这是他的结果。
[0,1,0,0]
[0,1,0,0]
[0,1,0,0]
[0,1,0,0]
他说如果我首先通过列迭代然后再行,那么它就像是:
CHECK,1,0,0
CHECK,1,0,0
CHECK,1,0,0
CHECK,1,0,0
然后列索引更改为1
0,CHECK,0,0
0,CHECK,0,0
0,CHECK,0,0
0,CHECK,0,0
抱歉说不好......
答案 0 :(得分:0)
这样的事情?
In [22]: import numpy as np
In [23]: a=np.array(range(15)).reshape(3,5)
In [24]: a
Out[24]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
In [25]: [ [x[i] for x in a] for i in range(a.shape[1])]
Out[25]: [[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14]]
答案 1 :(得分:0)
您可以使用内置all()功能检查所有元素是否为True,
和Row-to-Column Transposition
zip(*table)
符号
mytable1 = [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]]
mytable2 = [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]]
mytable3 = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
mytable4 = [[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable5 = [[0,1,0,0],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable6 = [[2,1,0,0],[2,0,1,0],[2,1,0,0],[2,0,1,0]]
mytable7 = [[2,1,0,0],[0,2,1,0],[0,1,2,0],[0,0,1,2]]
def hasWon(table,player_no):
#check rows
for row in table:
if all([e==player_no for e in row]):
return True
#check columns
for column in zip(*table):
if all([e==player_no for e in column]):
return True
#check diagonals
if all([table[i][i]==player_no for i in range(len(table)) ]):
return True
if all([table[-i-1][i]==player_no for i in range(len(table))]):
return True
return False
print(hasWon(mytable1,1))
print(hasWon(mytable2,1))
print(hasWon(mytable3,1))
print(hasWon(mytable4,1))
print(hasWon(mytable5,1))
print(hasWon(mytable6,2))
print(hasWon(mytable7,2))
输出:
True
True
True
True
False
True
True