Home > Mobile >  Update state from the UI
Update state from the UI

Time:10-13

I'm coding a bot in Python that plays tic-tac-toe. The game is a Web app written in React.js and is equipped with an AI of its own that utilizes minimax. The user (which the Python bot simulates) is always X, the AI is always O, and the user always moves first. The AI obviously keeps updated on the state of the board, but the Python bot currently only keeps track of it's own clicked squares and will not select a square that it has already selected, but it does not keep track of the board as such.

How can I update the state of the board in Python through the UI? I'm using Selenium to interact with the Web app through the browser. This is a follow-up to another post: python method not being called.

Edit 1: This is a segment I added to my code to check for squares already filled by either X or O:

    for i in range(1,9):
        if clickedSquares[i] == Tags.exSquare:
            clickedSquares.append(i)
        if clickedSquares[i] == Tags.ohSquare:
            clickedSquares.append(i)

But I get a "list index out of range" error. I think the problem is that I'm trying to do a string comparison on an XPATH. How can I fix this?

CodePudding user response:

        clickedSquares = []

        if not clickedSquares:
            clickedSquares.append(random_square)   
        
        for i in range(1,9):
            if clickedSquares[i] == Tags.exSquare:
                clickedSquares.append(i)
            if clickedSquares[i] == Tags.ohSquare:
                clickedSquares.append(i)

            # What if it is neither X or O?

I think this is the crux of your issue. You initialize an array, add 1 item, then try to iterate through 9 items. Seems out of range to me.

I think its kinda strange that you are manipulating clickedSquares within a loop over essentially the items of clickedSquares. I would probably separate the list into separate lists, or you actually meant to loop over squares instead.

CodePudding user response:

for i in range(x, y)

means we will take a range starting and including x up to but not including y, so I think your range should be (0,9). Also, you're correct about your comparison. If I'm reading your code correctly, it's not clickedSquares[i] you should be using but squares[i].

        for i in range(0,9):
            if squares[i] == Tags.exSquare:
                clickedSquares.append(i)
            if squares[i] == Tags.ohSquare:
                clickedSquares.append(i)

This should work because squares is a list of XPATH variables.

  • Related