mikyjet06
mikyjet06

Reputation: 5

Is there a way to check if all of the variables contain a variable

I wanted to build a tic tac toe game but something is wrong with my win function

def check_if_gameover(d):

    if d[1] and d[4] and d[7] == 'X' or 'O':
        return True
    elif d[1] and d[5] and d[9] == 'X' or 'O':
        return True
    elif d[1] and d[2] and d[3] == 'X' or 'O':
        return True
    elif d[7] and d[8] and d[9] == 'X' or 'O':
        return True
    elif d[4] and d[5] and d[6] == 'X' or 'O':
        return True
    elif d[9] and d[6] and d[3] == 'X' or 'O':
        return True
    elif d[8] and d[5] and d[2] == 'X' or 'O':
        return True
    elif d[7] and d[5] and d[3] == 'X' or 'O':
        return True
    else:
        return False

the d stands for dictionary and i wanted to check for example the first statement if X or O is in d[1], d[4] and in d[7] at the same time but instead when there was one of them == to X or O it returned True. If you understand my question please reply. Thanks

Upvotes: 0

Views: 40

Answers (2)

N Chauhan
N Chauhan

Reputation: 3515

An easier way is to store the indexes to check in a list of tuples and compare to a tuple:

checks = [
    (1, 4, 7),
    (1, 5, 9),
    ...
]

def check_if_gameover(d):
    for a, b, c in checks:
        if ((d[a], d[b], d[c]) == ('X', 'X', 'X')
            or (d[a], d[b], d[c]) == ('O', 'O', 'O')):
            return True

Upvotes: 1

BeastCoder
BeastCoder

Reputation: 2741

Your problem is that or “0” returns true. As long as “0” is not the None value (which it isn’t it will return true).

I would recommend formatting it like this:

if (d[1] == “0” or d[1] == “X”) and (d[4] == “0” or d[4] == “X”) and (d[7] == “0” or d[7] == “X”):
return True

Then I would put this into a function so that you don’t have to make this too repetitive, or you don’t have to.

Upvotes: 0

Related Questions