python - How to make a function determining the winner of Tic-Tac-Toe more concise -


i'm writing python script supposed allow human , computer players play tic tac toe. represent board, i'm using 3x3 numpy array 1 , 0 marks of players (instead of "x" , "o"). i've written following function determine winner:

import numpy np  class board():     def __init__(self, grid = np.ones((3,3))*np.nan):         self.grid = grid      def winner(self):         rows = [self.grid[i,:] in range(3)]         cols = [self.grid[:,j] j in range(3)]         diag = [np.array([self.grid[i,i] in range(3)])]         cross_diag = [np.array([self.grid[2-i,i] in range(3)])]          lanes = np.concatenate((rows, cols, diag, cross_diag))          if any([np.array_equal(lane, np.ones(3)) lane in lanes]):             return 1         elif any([np.array_equal(lane, np.zeros(3)) lane in lanes]):             return 0 

so example, if execute

board = board() board.grid = np.diag(np.ones(3)) print board.winner() 

i result 1. bothers me repetition of any statements. think there more concise, dry way of coding this. (i thinking of switch/case in matlab doesn't exist in python). suggestions?

another option check sum of lanes.

    s = np.sum(lanes, axis=1)     if 3 in s:         return 1     elif 0 in s:         return 0 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -