Classic Tic Tac Toe game made in text version

Posted by Kossanovic on February 26, 2023

Everyone knows it

One of my first projects, done without following tutorials or anything like that.
It createas a "board" onto which players can put their signs.
TicTacToe can be split to nine fields. If you number them between 1-9 and sum up these number you will receive 45.
Since there are only 3 possible combinations of winning you can divide 45 by 3 and that results 15.
Keeping that in mind we can apply this logic onto our board.

points = [2, 7, 6, 9, 5, 1, 4, 3, 8]

To make it more readable let put these numbers on board.


Player can win horizontally, vertically or diagonally. If anything like that happens, sum of numbers in line will 15 as we spoke earlier.
During game, we need to make sure that players' inputs are valid and that they are filling blank fields.

# Check for correct inputs. Prevents signs to be overwritten.
def input_is_not_correct(x):
    if int(x) not in points:
            "Your input is incorrect, try again. It should be 'X'."
            "Range (1-9). "
        return True
    if row[int(x) - 1] != " ":
        print("This spot is already filled. Please choose other one. ")
        return True

def where_to_input_sign(player):
    # Ask for current player's sign:
    x = input(f"Where do you want to put your {player}. Range(1-9): ")
    return x

When the players are in game and filling fields, they are collecting points. But as you can imagine what may happen is that they can collect points over 15 or have exactly 15 points with two numbers, like 9 and 6. Knowing that we need to make sure that:

  • Player have at least 3 signs on board
  • Combination of  exactly 3 numbers in his points list equals exactly 15

At the same time we will also determine if there is a draw if board is filled and none of the players met the conditions.

def check_score(point_list, player):
    if len(point_list) >= 3:
        # Goes through possible combinations of points in threes. 
        # And sums them up to see if they add up to 15. 
        # If they do. Player wins.
        if any(sum(comb) == 15 for comb in combinations(point_list, 3)):
            print(f"Player with {player} won!")
            return True
        # If game is not resolved untill board is filled it is a draw.
        if len(point_list) >= 5:
            print(f"It's a draw!")
            return True