You can do it like this:
def Checker(g,what):
"""Checks if any index combination inside Winner has all X"""
Winning = [[0, 1, 2], [0,3,6], ] # you need to add all other 6 wind conditions here
return any( all( g[a]==what for a in x) for x in Winning)
win = ['X', 'X', 'X', 3, 4, 5, 6, 7, 8]
win2 = ['X', 2, 3, 'X', 4, 5, 'X', 7, 8]
loose = ['X', 'X', 'o', 3, 4, 5, 6, 7, 8]
print (win, Checker(win,'X'))
print (win2, Checker(win2,'X'))
print (loose, Checker(loose,'X'))
Output:
['X', 'X', 'X', 3, 4, 5, 6, 7, 8] True
['X', 2, 3, 'X', 4, 5, 'X', 7, 8] True
['X', 'X', 'o', 3, 4, 5, 6, 7, 8] False
- all() checks if the test if valid for all elements of an iterable
- any() checks if any element of an iterable statisfies a condition
Example to understand any()
/all()
t = [2,4,6]
print( all( x % 2 == 0 for x in t) ) # are all elements of t even?
print( any( x // 3 == 2 for x in t) ) # is any element of t divided by 3 == 2 ?
print( any( x % 2 == 1 for x in t) ) # is any element in t odd?
Output:
True
True
False
The line
return any( all( g[a]==what for a in x) for x in Winning)
simply checks if any element of your Winning
(either [0,1,2]
or [0,3,6]
- 6 more conditions to be added by yourself) has all grid-indexes g[..]
(as given in this condition) with a value given by what
- so you can check for X
or O
- either one might win.