0

I'm making tic-tac-toe in python. I have a board, and each of the squares corresponds to a number (0-8) and to help with win conditions, I have this list:

wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]

Whenever one of the players puts down a letter, wherever they placed the letter gets put into a list, so at the end of the game one of their lists might look like this:

player1 = [0, 1, 4, 5, 6]

How do I check if all of the elements of one of the nested lists are in player1 (regardless of order, if possible)?

SirDurtle
  • 5
  • 3
  • `any(all(position in player1 for position in win) for win in wins)`, checks if there is `any` win condition for which `all` actions (positions) are in `player1`. Also see [this](https://stackoverflow.com/questions/35964155/checking-if-list-is-a-sublist) post for checking sublists. – Thymen Mar 15 '21 at 14:57

2 Answers2

0

You can use the all function which checks if a list is a subset of another list. See the docs here.

For example:

def check_for_win():
    for win in wins:
        if all(x in player1 for x in win):
            return True
    return False
Julian Fock
  • 98
  • 10
0

If you simply want to check if any of the possible winning square lists is equivalent to player1's selected square list, you can do

any([set(w) == set(player1) for w in wins])

However, it seems to me that it would make more sense to check if any of the winning square lists are contained within player1's moves, meaning not necessarily all of the elements are in player1. You can do this by simply doing

any([set(w).issubset(set(player1)) for w in wins])
v0rtex20k
  • 1,041
  • 10
  • 20