Check if column or diagonal in matrix = x (Without Numpy)

后端 未结 2 1424
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 10:10

I can use this code to check if a row in a matrix = x:

q = [[1,2,1],[1,2,1],[2,1,2]]
answer = [sum(row) for row in q]
for i in range(0, len(q)):
    if answe         


        
2条回答
  •  情话喂你
    2021-01-07 10:47

    Well you could translate your enumeration of winning conditions into a tuple, of tuple of pairs ... not to much work in a 3x3 board world.

    Something like below (taking your sample board) and resulting in a tie should get you started in further learning Python:

    #! /usr/bin/env python
    """Check in snaive 3x3 game board world for diagonal,
    column, or row all ocupied by one player."""
    from __future__ import print_function
    
    players = (1, 2)  # Code for the players
    board = [[1, 2, 1],  # Board interpreted as 3 lists rows
             [1, 2, 1],
             [2, 1, 2]]
    winning_configs = (  # outer-inner-index pairs that win:
        ((0, 0), (1, 1), (2, 2)),  # TL to BR diagonal
        ((0, 2), (1, 1), (2, 0)),  # TR to BL diagonal
        ((0, 0), (1, 0), (2, 0)),  # L column
        ((0, 1), (1, 1), (2, 1)),  # M column
        ((0, 2), (1, 2), (2, 2)),  # R column
        ((0, 0), (0, 1), (0, 2)),  # L row
        ((1, 0), (1, 1), (1, 2)),  # M row
        ((2, 0), (2, 1), (2, 2)),  # R row
    )
    
    
    def and_the_winner_is(players, board, winning_configs):
        """First one matching rules is returned as winner,
        otherwise None to indicate a tie."""
        for player in players:
            for cfg in winning_configs:
                if all([board[i][j] == player for i, j in cfg]):
                    return player
        else:
            return None
    
    
    def main():
        """Determine the result from board."""
        winner = and_the_winner_is(players, board, winning_configs)
    
        if winner in players:
            print('Winner is Player({})'.format(winner))
        else:
            print('A tie')
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题