Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to check if multiple string indexes match a variable?

I have a tic tac toe game I made for a milestone project, and currently I have a long if/elif statement that checks all 8 possible win states. I’m trying to simplify it.

board = ['PLACEHOLDER', '-', '-', '-', '-', '-', '-', '-', '-', '-']
tag = X

# Vertical win check
if board[7] == tag and board[4] == tag and board[1] == tag:
    endgame()
elif board[8] == tag and board[5] == tag and board[2] == tag:
    endgame()
elif board[9] == tag and board[6] == tag and board[3] == tag:
    endgame()
# Horizontal win check
elif board[7] == tag and board[8] == tag and board[9] == tag:
    endgame()
elif board[4] == tag and board[5] == tag and board[6] == tag:
    endgame()
elif board[1] == tag and board[2] == tag and board[3] == tag:
    endgame()
# Diagonal win check
elif board[7] == tag and board[5] == tag and board[3] == tag:
    endgame()
elif board[1] == tag and board[5] == tag and board[9] == tag:
    endgame()

Is it possible to check multiples indexes in board at once against the tag string? Something like these two, which I already know don’t work:

if board[7, 4, 1] == tag:
    endgame()

if board[7], [4], [1] == tag:
    endgame()

Or is it even worth trying to simplify?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

def endgame():
    print('game end!')


board = ['PLACEHOLDER', '-', '-', '-', '-', '-', '-', '-', '-', '-']
tag = 'X'
idx = [[7, 4, 1], [8, 5, 2], [9, 6, 3], [7, 8, 9], [4, 5, 6], [1, 2, 3], [7, 5, 3], [1, 5, 9]]

for cond in idx:
    if board[cond[0]] == tag and board[cond[1]] == tag and board[cond[2]] == tag:
        endgame()

You could do something like this, which keeps all the win conditions in a list, and iterates over each one, checking if it’s true and ending the game if it’s true.

As khelwood points out, a more clean version of this takes advantage of variable unpacking/destructuring.

for i, j, k in idx:
    if i == tag and j == tag and k == tag:
        endgame()

As Olvin points out, generalizing to dynamic board sizes, with the all() function, we can write this as

for cond in idx:
    if all(board[i] == tag for i in cond):
        endgame()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading