pythonnumpytic-tac-toe

How do I pick position of tictactoe field by number input (0-8)?


So I'm trying to refine my high school project by trying to restart at making a Tic-Tac-Toe Neural Network. However I can't wrap my head around how to set a cross or a circle at a position in the tic-tac-toe field by inputting 0-8:

class main():
    FIELD = np.zeros((3,3), dtype=int)

    def set(f, pos, type):
        #Line of code, where f is the field array, pos is a number between 0-8 and type is either 1 or -1 
        #(cross or circle) where f looks like this:
        #[0,1,2]
        #[3,4,5]    
        #[6,7,8] 
        return f

    set(FIELD,2,1)
    print(FIELD)
    #Expected Output:
    #[0,0,1]
    #[0,0,0]    
    #[0,0,0] 

Thank you for any answersè :)

So I tried the following line of code:

f[(0 if pos == (0 or 1 or 2) else (1 if pos == (3 or 4 or 5) else (2 if pos == (6 or 7 or 8)))),pos%3] = type

But I think this is rather inefficient and I'm certain there has to be a way without hard-coding this lmao


Solution

  • You can use numpy.unravel_index:

    FIELD = np.zeros((3,3), dtype=int)
    
    position = 5
    FIELD[np.unravel_index(position, FIELD.shape)] = 1
    
    print(FIELD)
    

    Output:

    array([[0, 0, 0],
           [0, 0, 1],
           [0, 0, 0]])