tic tac toe python project pdf code example

Example 1: tic tac toe python easy

def tic_tac_toe():
    board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    end = False
    win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))

    def draw():
        print(board[0], board[1], board[2])
        print(board[3], board[4], board[5])
        print(board[6], board[7], board[8])
        print()

    def p1():
        n = choose_number()
        if board[n] == "X" or board[n] == "O":
            print("\nYou can't go there. Try again")
            p1()
        else:

             board[n] = "X"
           
    def p2():
        n = choose_number()
        if board[n] == "X" or board[n] == "O":
            print("\nYou can't go there. Try again")
            p2()
        else:
            board[n] = "O"

    def choose_number():
        while True:
            while True:
                a = input()
                try:
                    a  = int(a)
                    a -= 1
                    if a in range(0, 9):
                        return a
                    else:
                        print("\nThat's not on the board. Try again")
                        continue
                except ValueError:
                   print("\nThat's not a number. Try again")
                   continue

    def check_board():
        count = 0
        for a in win_commbinations:
            if board[a[0]] == board[a[1]] == board[a[2]] == "X":
                print("Player 1 Wins!\n")
                print("Congratulations!\n")
                return True

            if board[a[0]] == board[a[1]] == board[a[2]] == "O":
                print("Player 2 Wins!\n")
                print("Congratulations!\n")
                return True
        for a in range(9):
            if board[a] == "X" or board[a] == "O":
                count += 1
            if count == 9:
                print("The game ends in a Tie\n")
                return True

    while not end:
        draw()
        end = check_board()
        if end == True:
            break
        print("Player 1 choose where to place a cross")
        p1()
        print()
        draw()
        end = check_board()
        if end == True:
            break
        print("Player 2 choose where to place a nought")
        p2()
        print()

    if input("Play again (y/n)\n") == "y":
        print()
        tic_tac_toe()

tic_tac_toe()

Example 2: how to make tic tac toe in python

# Python Program for simple Tic Tac Toe

board = ["-", "-", "-",
         "-", "-", "-",
         "-", "-", "-"]

game_still_going = True

winner = None

current_player = "X"

def play_game():

    display_board()

    while game_still_going:
        handle_turn(current_player)
        check_if_game_over()
        flip_player()
    if winner == "X" or winner == "O":
        print(winner + " won.")
    elif winner is None:
        print("Tie.")

def display_board():
    print("\n")
    print(board[0] + " | " + board[1] + " | " + board[2] + "     1 | 2 | 3")
    print(board[3] + " | " + board[4] + " | " + board[5] + "     4 | 5 | 6")
    print(board[6] + " | " + board[7] + " | " + board[8] + "     7 | 8 | 9")
    print("\n")

def handle_turn(player):
    print(player + "'s turn.")
    position = input("Choose a position from 1-9: ")


    valid = False
    while not valid:
        while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
            position = input("Choose a position from 1-9: ")
        position = int(position) - 1
        if board[position] == "-":
            valid = True
        else:
            print("You can't go there. Go again.")
    board[position] = player
    display_board()

def check_if_game_over():
    check_for_winner()
    check_for_tie()

def check_for_winner():
    global winner
    row_winner = check_rows()
    column_winner = check_columns()
    diagonal_winner = check_diagonals()
    if row_winner:
        winner = row_winner
    elif column_winner:
        winner = column_winner
    elif diagonal_winner:
        winner = diagonal_winner
    else:
        winner = None

def check_rows():
    global game_still_going
    row_1 = board[0] == board[1] == board[2] != "-"
    row_2 = board[3] == board[4] == board[5] != "-"
    row_3 = board[6] == board[7] == board[8] != "-"
    if row_1 or row_2 or row_3:
        game_still_going = False
    if row_1:
        return board[0]
    elif row_2:
        return board[3]
    elif row_3:
        return board[6]
    else:
        return None

def check_columns():
    global game_still_going
    column_1 = board[0] == board[3] == board[6] != "-"
    column_2 = board[1] == board[4] == board[7] != "-"
    column_3 = board[2] == board[5] == board[8] != "-"
    if column_1 or column_2 or column_3:
        game_still_going = False
    if column_1:
        return board[0]
    elif column_2:
        return board[1]
    elif column_3:
        return board[2]
    else:
        return None

def check_diagonals():
    global game_still_going
    diagonal_1 = board[0] == board[4] == board[8] != "-"
    diagonal_2 = board[2] == board[4] == board[6] != "-"
    if diagonal_1 or diagonal_2:
        game_still_going = False
    if diagonal_1:
        return board[0]
    elif diagonal_2:
        return board[2]
    else:
        return None

def check_for_tie():
    global game_still_going
    if "-" not in board:
        game_still_going = False
        return True
    else:
        return False

def flip_player():
    global current_player
    if current_player == "X":
        current_player = "O"
    elif current_player == "O":
        current_player = "X"
play_game()

Example 3: tic tac toe in python

import time
import sys

TITLES = "    A   B   C\n"
INIT_BOARD = "| / | / | / |\n"
A, B, C = 4, 8, 12
# creates the game board
board = [f"{x} {INIT_BOARD}" for x in range(3)]
user_turn = ""
taken = True
winner = False
turn_number = 0
# keeps the score and determines what symbols will be used
SYMBOLS = ["x", "o"]
winner_save = [list(x * 3) for x in SYMBOLS]
score = {symbol: 0 for symbol in SYMBOLS}

# does all the logic to the game
class logic:
    def __init__(self, ctx, turn, win_template):
        self.ctx = ctx
        self.turn = turn
        self.template = win_template

    # check if 3 of the same symbols are in a line
    def winner_check(self):
        # initializes the list containing the rows. rows 0, 1, and 2 are created
        win_check = [
            [board[c][x] for x in range(4, len(board[c])) if x % 4 == 0]
            for c in range(3)
        ]
        # adds the values for every possible row to the list
        for x in range(3):
            win_check.append([win_check[c][x] for c in range(3)])
        win_check.append([win_check[x][x] for x in range(3)])
        win_check.append([win_check[x][c] for x, c in zip(range(3)[::-1], range(3))])
        # determines if someone has won
        for x in win_check:
            if x in self.template:
                print(f"{self.turn} wins!")
                keep = True
                break
            keep = False
        return keep

    # updates the spot value of the given input. ex: input = A1, spot A1 will be occupied by the player
    def take_spot(self):
        append_board = board[int(user[1])]
        append_board = "".join(
            [
                append_board[x] if x != eval(user[0]) else self.turn
                for x in range(len(append_board))
            ]
        )
        return append_board

    # checks to see if a spot on the board is already occupied
    def spot_taken(self):
        board_ctx = board[int(self.ctx[1])][eval(self.ctx[0])]
        check_spot = True if board_ctx in ["o", "x"] else False
        if check_spot == True:
            print("spot already taken :/ try again")
        return check_spot


# takes the location input and checks if it exists
def input_check():
    slow_print("location- \n")
    ctx = input().upper()
    all_input = [x + str(c) for x in ["A", "B", "C"] for c in range(3)]
    if ctx in all_input:
        pass
    else:
        while ctx not in all_input:
            slow_print("invalid location, try again\n")
            slow_print("location- \n")
            ctx = input().upper()
    return list(ctx)


# takes an input and prints it smoothly to the console
def slow_print(inpt):
    for x in inpt:
        sys.stdout.write(x)
        time.sleep(0.01)


slow_print(TITLES + "".join(board))

# determines what symbol will go first
while True:
    slow_print(f"{SYMBOLS[0]}'s or {SYMBOLS[1]}'s?- \n")
    user_turn = input()
    if user_turn in [SYMBOLS[0], SYMBOLS[1]]:
        slow_print(f"{user_turn}'s first!\n")
        break
    else:
        slow_print("incorrent input try again!")

# brings all the functions and logic together
while True:
    outcome = "None"
    while winner == False:
        # keeps track of the amount of turns to determine if the outcome is a tie
        turn_number += 1
        if turn_number == 10:
            slow_print("Tie!\n")
            outcome = None
            break
        # takes spot input and brings the spot_taken logic together to determines==
        # whether a spot is already occupied
        while taken == True:
            user = input_check()
            init = logic(user, user_turn, winner_save)
            taken = init.spot_taken()
        ctx_board = init.take_spot()
        board[int(user[1])] = ctx_board
        slow_print(TITLES + "".join(board))
        user_turn = SYMBOLS[0] if user_turn != SYMBOLS[0] else SYMBOLS[1]
        taken = True
        winner = init.winner_check()
    # makes sure the point is given to the winner by inverting the current user_turn
    if outcome == None:
        pass
    else:
        score[SYMBOLS[0] if user_turn == SYMBOLS[1] else SYMBOLS[1]] += 1
    slow_print(
        f"Scores: {SYMBOLS[0]}-{score[SYMBOLS[0]]}, {SYMBOLS[1]}-{score[SYMBOLS[1]]}\n"
    )
    slow_print("Would you like to play another (Y/N)?- \n")
    repeat = input().upper()
    if repeat == "Y":
        winner = False
        board = [f"{x} {INIT_BOARD}" for x in range(3)]
        turn_number = 0
        continue
    else:
        break