Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading