Thibault J
Thibault J

Reputation: 31

Most efficient method to check victory in a tictactoe game

I've made two TicTacToe games and I've tried some ways to check victory within my array. At the moment, I've kept the following ones. Could you help me find out which is the most efficient ?

The first one :

def check_victory(self, board, mark):
    for i in board:
        if np.array_equal(i, [mark]*3):
            return True

    for i in range (0, 3):
        if (board[0][i] == board[1][i] == board[2][i] == mark):
            return True

    if (board [0][0] == board [1][1] == board [2][2] == mark) or (board [0][2] == board [1][1] == board [2][0] == mark):
        return True
    return False

The second one :

def check_victory(self, table):
    for j in range(3) :
        if (sum(table[j][i] for i in range(3)))**2 == 9 or (sum(table[i][j] for i in range(3)))**2 ==9:
            return -self.active_player

    if (sum(table[i][i] for i in range(3)))**2 == 9 or (sum(table[i][2-i] for i in range(3)))**2 == 9:
        return -self.active_player

    for i in range(3) :
        for j in range(3) :
            if table[i][j]==0 :
                return None
    return 0

Upvotes: 1

Views: 809

Answers (2)

Prune
Prune

Reputation: 77837

Use a timing function. Build a series of the 8 possible wins, and run a loop to evaluate the entire series many times (enough to make overhead costs insignificant).

Also, you can do better in the second case. Instead of checking

if x**2 == 9

Try

if abs(x) == 3

The exponentiation, even as a multiply, is slower than letting the hardware operations invert a negative integer.

Even better, don't check the whole board: instead, check only the 2-4 combinations involving the most recent move. Best of all, after the second move, simply maintain a list of winning moves. When you are able to make one of those, there's no check needed.

One way to do this more easily is to number the squares internally as a 3x3 magic square:

8 3 4
1 5 9
6 7 2

Now, you have a win iff you played three numbers that add up to 15.

Upvotes: 2

user5807384
user5807384

Reputation:

I use this algo:

def algo(symbols, x, y):
    """Check if someone wins with this move
    0,0  0,1  0,2
    1,0  1,1  1,2
    2,0  2,1  2,2

    2 straight checks: [0][y] & [x][0]
    2 diagonal checks, if x = y or x = 2 - y
    """
    return (symbols[0 * 3 + y] == symbols[1 * 3 + y] == symbols[2 * 3 + y] or
            symbols[x * 3 + 0] == symbols[x * 3 + 1] == symbols[x * 3 + 2] or
            (x == y and symbols[0] == symbols[4] == symbols[8]) or
            (x == 2 - y and symbols[2] == symbols[4] == symbols[6]))

It automatically return True or False

Upvotes: 0

Related Questions