1

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

tryg
  • 13
  • 4
  • Note that `pos == (0 or 1 or 2)` is not doing what you think. `(0 or 1 or 2)` evaluates to `1` as `0` is falsy and `1` truthy. You would need `pos in {0, 1, 2}`. – mozway Jun 09 '23 at 12:14

2 Answers2

0

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]])
mozway
  • 194,879
  • 13
  • 39
  • 75
0

This implementation of set() should work.

def set(f, pos, type):
    row = pos // 3  # Calculate the row index
    col = type % 3  # Calculate the column index
    f[row][col] = 1
    return f