简体   繁体   English

如何遍历矩阵并找到匹配值

[英]How to iterate over matrix and find matching value

def is_win(self, player):
    for x,y,z in [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ]:

    if x == player and y == player and z == player:
         return True

I am trying to form a win condition on Tic Tac toe.我正在尝试在井字游戏中形成获胜条件。 But this will not match.但这不会匹配。 I have a update_board function that checks if is_win after updating a players move.我有一个 update_board 函数,可以在更新玩家移动后检查 is_win 是否。

You should set your player to contain a set of positions.您应该将播放器设置为包含一组位置。 Then, you check if any row in your matrix is in the player's positions.然后,您检查矩阵中的任何行是否在玩家的位置。

# assuming player.positions is a set()
def is_win(self,player):
    win_matrix = [set([0, 1, 2]),set([3, 4, 5]),set([6, 7, 8]),set([0, 3, 6]),\
                 set([1, 4, 7]),set([2, 5, 8]),set([0, 4, 8]),set([2, 4, 6])]
    for w in win_matrix:
        if(w.issubset(player.positions)):
            return True
    return False
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM