Search code examples
pythonif-statementterminaltic-tac-toe

Simplifying Python If Statements


I am a beginner with python, and I am creating a two player tic tac toe game in terminal. In total, this code takes up 139 lines, (this below being the relevant part of code I am having trouble with), however, this CheckWin function takes up around 40 lines of code, which I think is quite a lot compared to the amount of lines in this code, and considering that it performs a somewhat basic function. Basically, in the game, this function checks whether a row, column, or diagonal, has three X's or three O's, and if it does, it assigns X to the winner and O to the winner. Anyway, here is the code.

X = "X"
O = "O"
empty = " " 
S = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

def CheckWin(S):
    global winner
    winner = ""
    if S[0] == S[1] == S[2] != empty:
        if S[0] == X:
            winner = X
        if S[0] == O:
            winner = O
    if S[3] == S[4] == S[5] != empty:
        if S[3] == X:
            winner = X
        if S[3] == O:
            winner = O
    if S[6] == S[7] == S[8] != empty:
        if S[6] == X:
            winner = X
        if S[6] == O:
            winner = O
    if S[0] == S[3] == S[6] != empty:
        if S[0] == X:
            winner = X
        if S[0] == O:
            winner = O
    if S[1] == S[4] == S[7] != empty:
        if S[1] == X:
            winner = X
        if S[1] == O:
            winner = O
    if S[2] == S[5] == S[8] != empty:
        if S[2] == X:
            winner = X
        if S[2] == O:
            winner = O
    if S[0] == S[4] == S[8] != empty:
        if S[0] == X:
            winner = X
        if S[0] == O:
            winner = O
    if S[2] == S[4] == S[6] != empty:
        if S[2] == X:
            winner = X
        if S[2] == O:
            winner = O

Basically, I need help making the function much much simpler. However, I do not want to eliminate the X, O, and winner variables, nor do I want to eliminate the list index method with the list S. Even though, is there a way to simplify all these If statements, keeping these things? If so, how?


Solution

  • Your code looks for "trios" of positions; you might as well have an object that holds this info:

    trios = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))
    

    Then CheckWin would just loop through every trio, do that check you're doing, and return a winner if the trio matches. This way, CheckWin would be less than 10 lines of code.

    I don't want to give it all away because I'm sure you can do it :)

    Also, you don't need a global variable called "winner" inside CheckWin; just have CheckWin return the winner (or ""), and store the result in a variable outside the function itself.
    I.e.

    winner = CheckWin(S)