Wednesday, January 2, 2019

codingdirectional: Solving tic tac toe problem with python

Hello again, today we are going to continue exploring py.checkio.org site by solving this tic tac toe question with python, this question requires us to find out which player has won the tic tac toe game by returning ‘X’ if X wins, returning ‘Y’ if Y wins or ‘D’ if it is a draw. After solving this question I think I will create a tic tac toe game with python later on since I already have the solution for the game mechanism so better don’t waste this wonderful resource! Below is the entire solution to the above tic tac toe question. I have thought of making the solution shorter by introducing a few functions to replace the long solution but for now, we will stick to this one.

The solution below might not be the best so do comment under this article and tell me what do you think about the below solution.

def checkio(game_result):

    first = game_result[0]
    second = game_result[1]
    third = game_result[2]

    if(first[0] == first[1] == first[2] and first[0] != '.'):
        if(first[0] == 'X'):
            return 'X'
        elif(first[0] == 'O'):
            return 'O'
    elif(second[0] == second[1] == second[2] and second[1] != '.'):
        if(second[0] == 'X'):
            return 'X'
        elif(second[0] == 'O'):
            return 'O'
    elif(third[0] == third[1] == third[2] and third[0] != '.'):
        if(third[0] == 'X'):
            return 'X'
        elif(third[0] == 'O'):
            return 'O'
    elif(first[0] == second[0] == third[0] and third[0] != '.'):
        if(third[0] == 'X'):
            return 'X'
        elif(third[0] == 'O'):
            return 'O'
    elif(first[1] == second[1] == third[1] and second[1] != '.'):
        if(third[1] == 'X'):
            return 'X'
        elif(third[1] == 'O'):
            return 'O'
    elif(first[2] == second[2] == third[2] and second[2] != '.'):
        if(third[2] == 'X'):
            return 'X'
        elif(third[2] == 'O'):
            return 'O'
    elif(first[0] == second[1] == third[2] and second[1] != '.'):
        if(third[2] == 'X'):
            return 'X'
        elif(third[2] == 'O'):
            return 'O'
    elif(first[2] == second[1] == third[0] and third[0] != '.'):
        if(third[0] == 'X'):
            return 'X'
        elif(third[0] == 'O'):
            return 'O'
    else:
        return 'D'

The solution above will serve as a framework for those who want to develop your own tic tac toe game. I will continue to explore this site and see what it actually does by solving more python related problems in the coming articles.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...