0

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

DJSchaffner
  • 562
  • 7
  • 22
mikyjet06
  • 5
  • 1
  • Looks to me like you are checking for something toally wrong. Meaning, you check the first 2 for !false, the third for equals 'X' and then 'O' != false. The first thing that comes to mind for me would write a function that check its 3 params for the same content (X) or (O) and call that for each of your rows. However that seems a bit cumbersome and theres probably an easier solution – DJSchaffner Jan 15 '20 at 19:24
  • Your conditions will always return true. See here: [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – N Chauhan Jan 15 '20 at 19:30

2 Answers2

1

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
N Chauhan
  • 3,407
  • 2
  • 7
  • 21
  • 1
    I really liked your approach and did a full implementation: https://repl.it/repls/ResponsibleLeanRoutine just in case someone is interested :D I dont want to submit a seperate answer for this – DJSchaffner Jan 15 '20 at 20:05
  • Thank you for your help – mikyjet06 Jan 15 '20 at 20:45
0

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.

BeastCoder
  • 2,391
  • 3
  • 15
  • 26