我似乎不知道我应该如何让我的垂直移动工作,我的面板是一个嵌套列表,由6个列表组成,每个列表中有6个元素。
我已经能够计算出我的水平以及我的对角线获胜条件。但是我不能把我的头放在垂直的那个
例如,这是我的水平条件
#the list itself
board = [
[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
]
def hor_condition(board, player):
"""the hor_condition checks whether the list contains necessary amount of checkers in order to call it a win"""
for row in board:
for cell in row:
if row.index(cell) < 2:
check_list = [row[row.index(cell)],
row[row.index(cell) + 1],
row[row.index(cell) + 2],
row[row.index(cell) + 3]
]
if check_list[0] == player and\
check_list[1] == player and \
check_list[2] == player and \
check_list[3] == player:
return True这里检查玩家在同一行中是否有4个相同的元素,以便将其称为胜利。我期望垂直条件所做的是检查在同一列中是否有4个相同的棋子
这可能看起来很痛苦,但请记住,我刚刚开始使用python,我开始理解基础知识。
我并不是真的要求在白代码上写黑字,而是在正确的方向上推动。
如果需要的话,我很乐意提供任何进一步的信息!提前谢谢你!
编辑:这有点晚了,但我想帮助其他和我有同样问题的人。我最终解决了以下问题:
def vert_condition(board, player):
"""The vert_condition iterates over the board and checks whether 4 vertical slots contain the same player input by
with the help of a nested loop"""
for row in range(3):
for col in range(6):
if (board[row][col] == \
board[row + 1][col] == \
board[row + 2][col] == \
board[row + 3][col] == player):
return True发布于 2018-11-17 02:26:28
您可以使用类似于for col in board的方式进行迭代:
for col_index in range(6):
col = [row[col_index] for row in board]
for i in range(len(col) - 4 + 1):
if all(col[i + j] == player for j in range(4)):
return True因为您不能直接迭代行,所以使用索引计数器迭代-在本例中是range(6) -并每次取出每行的第n个元素来构造列。
我还建议对你的代码做一个小的修改:
在你一直写row.index(cell)的地方,这是一个繁重的计算,所以计算一次并存储在一个变量中,这样你就可以重用结果,而不是在你可以很容易地存储它的时候不断地重新计算它。
为了让它更好,使用内置的all,您提供了一个迭代器,如果所有元素都为真,则返回true。
此外,您只需要检查6-4+1 (=3)次,因为....
在那之后就没有了,因为在行(和列)中没有第7个单元格。我在代码中包含的计算是:
len(row) - len(what’s being checked) + 1https://stackoverflow.com/questions/53343309
复制相似问题