Search code examples
python-3.xlistconditional-statementstic-tac-toe

How to code win/tie conditions in TicTacToe game in python


I have made the main-game mechanics for the TicTacToe game; however, I don't know a way to code the end-game win conditions, i.e. How to find when someone wins/ties.

I tried using the all() function, but either this did not work, or I used it incorrectly (probably the latter).

Here is the full code, and the list of variables for the code (as there are no comments):

def get_grid():
    r1 = ['-','-','-']
    r2 = ['-','-','-']
    r3 = ['-','-','-']
    return r1, r2, r3

def get_coords():
    x = 0
    y = 0
    while True:
        try:
            x = int(input("x coord : "))
            y = int(input("y coord : "))
        except ValueError:
            print("Must be an integer")
        if x < 0 or x > 3 or y < 0 or y > 3:
            print('Both values must be in the grid!')
        else:
            break
    return x, y

def pgrid(x, y, r1, r2, r3, player):
    rdict = {1:r1, 2:r2, 3:r3}
    if x != 0 and y != 0:
        while True:
            if rdict[y][x-1] == '-':
                rdict[y][x-1] = player
                break
            else:
                print("Invalid Space!")
                x, y = get_coords()
    print('\t1\t2\t3')
    print('  1 |', end = '\t')
    for i in r1:
        print(i, end = '   |   ')
    print()
    print('  2 |', end = '\t')
    for i in r2:
        print(i, end = '   |   ')
    print()
    print('  3 |', end = '\t')
    for i in r3:
        print(i, end = '   |   ')
    print()


def main():
    r1, r2, r3 = get_grid()
    players = ['X', 'O']
    pgrid(0, 0, r1, r2, r3, None)
    win = False
    while win == False:
        for i in players:
            x, y = get_coords()
            pgrid(x, y ,r1 ,r2 , r3, i)

Variables
r1, r2 and r3 are the first, second, and third rows for the board. List
x and y are the coordinates where the 'X' or 'O' is placed. Integer
rdict navigates between the y value entered and the row of the board. Dictionary
player is the player. String players is a List of the players ('X' and 'O')
win is true when a player has won / the game has tied. Boolean

The win variable is what needs to change in answers to this question, I just need the code or at least an idea on how to code it (because I don't have any!).
Thanks in advance!


Solution

  • What's the simplest way to check if three of the same letters are in a row or column? For the first column take r1[0], r2[0] and r3[0] and check if they all contain the same letter:

    if r1[0] == 'X' and r2[0] == 'X' and r3[0] == 'X':
        print('First column meets victory conditions', 'X')
    

    Now it would be a bit cumbersome to do this for all rows and columns and both letters, but fortunately we can just let some for loops do the work for us.

    for letter in 'XO':
        for i in range(3):
            if r1[i] == letter and r2[i] == letter and r3[i] == letter:
                print('Column', i, letter)
    

    For the rows just iterate over (r1, r2, r3) instead of the range(3) and check:

    if row[0] == letter and row[1] == letter ...
    

    And of course you can also use the all function and a list comprehension or generator expression to see if all letters are equal.

    for row in (r1, r2, r3):
        if all(item == letter for item in row):