Search code examples
pythonoptimizationtic-tac-toe

Optimize tic tac toe checks


For a project of mine, I have to do a tic-tac-toe solver, and I would like to just ask for some help optimizing some code.

Task: Depending on the winner( x or o) , return the appropriate result

How I did It: I checked Horizontal, vertical, and diagonal strategies for the result

What I need help with : I am mostly repeating the same code, but different if statement for each case, and I am just wondering if there is a more universal method to do this.

Current Code: (Diagonal win)

 if diagcounter==size and (board[0][0]=="x") :
        print("Win Diagonally")
        return "X has won"
    elif diagcounter==size and (board[0][0]=="o"):
        print("Win Diagonally")

Horizontal win:

 if vertcounter==size and board[0][x]=="x":
            print("Win vertically")
            return "X has won"
        elif vertcounter==size and board[0][x]=="o":
            print("Win vertically")
            return "O has won"

As you can see, they are almost the same, but since I need to check the letter at the spot, I don`t know how to optimize it.


Solution

  • You could hold a list of the indices for each row/column/diagonal. So for example, the first row should be sequence_indices = [(0, 0), (0, 1), (0, 2)]. The main diagonal should be sequence_indices = [(0, 0), (1, 1), (2, 2)].

    Now whenever you write in your code vertcounter or diagcounter use a function counter(sequence_indices), and instead of board[0][x] or board[0][0], use

    first_i, first_j = sequence_indices[0]
    board[first_i][first_j]
    

    Another way to optimize this is to use board like so:

    If a cell contains x, then board in that cell should hold the number 1. If the cell contains o, board in that cell should hold the number -1, and if the cell is empty it should be 0.

    Now to calculate rowcounter or whatever-counter just sum over these cells and compare them to +size (x wins), or to -size (o wins).