20+ Python Tic Tac Toe Examples

This post contains a total of 20+ Hand-Picked Python Tic Tac Toe Examples with Source Code. All the Tic Tac Toe programs are made using Python Programming language.

You can use the source code of these programs for educational purpose with credits to the original owner.

Related Posts

Click a Code to Copy it.

1. By Supersebi3

Made by Supersebi3. Multiplayer Tic Tac Toe game made using python. ( Source )

"""
This is multiplayer Tic Tac Toe. Copy it into your IDE to play it.
"""

field = """{}|{}|{}
-+-+-
{}|{}|{}
-+-+-
{}|{}|{}"""

fields = [i for i in range(10)]

ended = False
turn = 1
winner = None
symbols = (None, "X", "O")
wincombos = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7))

while not ended:
    print(field.format(fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], fields[7], fields[8], fields[9]))
    if not any([i in range(1,10) for i in fields]):
        ended = True
        print("It's a draw.        ")
        break
    while True:
        try:
            inp = int(input("Player {}'s turn: ".format(turn)))
            if inp not in range(1, 10) or fields[inp] != inp:
                print("\33[2A")
                continue
            break
        except ValueError:
            print("\33[2A")
    fields[inp] = symbols[turn]
    for i in wincombos:
        for j in i:
            if fields[j] != symbols[turn]:
                break
        else:
            winner = int(turn)
    if winner is not None:
        ended = True
        print("\33[7A")
        print(field.format(fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], fields[7], fields[8], fields[9]))
        print("Player {} won!       ".format(winner))
        break
    turn = int(not bool(turn-1)) + 1
    print("\33[7A")

2. By Harry Patlow

Made by Harry Patlow. Simple Python Tic Tac Toe game. ( Source )

x,y,z= input().split(),input().split(),input().split()
xwin,owin = 0,0
#Horizontal Wins Check
for i in x: 
	if x.count(i)==3 and i == 'X':
	   print('Player X')
	   xwin=1
	   break
	elif x.count(i)==3 and i == 'O':
	   print('Player O')
	   owin = 1
	   break
for i in y: 
	if y.count(i)==3 and i == 'X':
	   print('Player X')
	   xwin=1
	   break
	elif y.count(i)==3 and i == 'O':
	   print('Player O')
	   owin = 1
	   break
for i in z: 
	if z.count(i)==3 and i == 'X':
	   print('Player X')
	   xwin=1
	   break
	elif z.count(i)==3 and i == 'O':
	   print('Player O')
	   owin = 1
	   break
#Vertical Wins Check
vx = list(x[0]+y[0]+z[0])
vy = list(x[1]+y[1]+z[1])
vz = list(x[2]+y[2]+z[2])

if xwin ==0 and owin ==0:
   for i in vx: 
	  if vx.count(i)==3 and i == 'X':
		 print('Player X')
		 xwin=1
		 break
	  elif vx.count(i)==3 and i == 'O':
		 print('Player O')
		 owin = 1
		 break
   for i in vy: 
	  if vy.count(i)==3 and i == 'X':
		 print('Player X')
		 xwin=1
		 break
	  elif vy.count(i)==3 and i == 'O':
		 print('Player O')
		 owin = 1
		 break
   for i in vz: 
	  if vz.count(i)==3 and i == 'X':
		 print('Player X')
		 xwin=1
		 break
	  elif vz.count(i)==3 and i == 'O':
		 print('Player O')
		 owin = 1
		 break
#Diagonal Wins Check

dx = list(x[0]+ y[1]+z[2])
dy = list(x[2]+ y[1] + z[0])
if xwin ==0 and owin ==0:
   for i in dx:
	   if dx.count(i) == 3 and i=='X':
		 print('Player X')
		 xwin = 1
		 break
	   elif dx.count(i)==3 and i == 'O':
		 print('Player O')
		 owin = 1
		 break
   for i in dy: 
	  if dy.count(i)==3 and i == 'X':
		 print('Player X')
		 xwin=1
		 break
	  elif dy.count(i)==3 and i == 'O':
		 print('Player O')
		 owin = 1
		 break
if xwin ==0 and owin==0:
   print('Tie')
	   

3. By Eliya Ben Baruch

Made by Eliya Ben Baruch. AI Tic tac Toe game using Python. ( Source )

"""This code is 1V1 if you want to play againts the computer use the code below."""
class Game:
    def __init__(self, player1, player2):
        self.board = Board()
        self.players = [player1, player2]
        self.turn = False
        self.play()
    def play(self):
        while True:
            current_player = self.players[int(self.turn)]
            print(self.board.to_string())
            move = current_player.make_move(self.board)
            is_winning = self.board.place_mark(current_player.marker, move)
            if is_winning or self.board.is_draw():
                break
            self.turn = not self.turn
        if self.board.is_draw():
            print(self.board.to_string())
            print ('It\'s a draw!')
            again = input("Do you wanna play again?(y\\n)?\n")
            if again == 'y' or again == 'Y':
                Game(Player(input("Enter your name for X marker:\n"), 'X', 'O'), Player(input("Enter your name for Y marker:\n", 'O', 'X')))
            elif again == 'n' or again == 'N':
                exit()
        else:
            print (self.board.to_string())
            print(f'Congratulations {current_player.name}, you win!')
            again = input("Do you wanna play again?(y\\n)?\n")
            if again == 'y' or again == 'Y':
                Game(Player(input("Enter your name for X marker:\n"), 'X', 'O'), Computer("Computer", 'O', 'X'))
            elif again == 'n' or again == 'N':
                exit()
class Board:
    def __init__(self, from_board = None):
        self.board = (from_board or list('012345678')).copy()
    def clone(self):
        return Board(self.board)
    def to_string(self):
        return '{}|{}|{}\n-----\n{}|{}|{}\n-----\n{}|{}|{}\n'.format(*self.board)
    def place_mark(self, marker, place):
        if self.board[int(place)] not in '012345678' or int(place) < 0 or int(place) > 8:
            raise ValueError()
        self.board[int(place)] = marker
        return self.is_winner(marker)
    def legal_move(self, i):
        return self.board[int(i)] in '012345678'
    def is_winner(self, marker):
        winning_positions = [
            [0,1,2],
            [3,4,5],
            [6,7,8],
            [0,3,6],
            [1,4,7],
            [2,5,8],
            [0,4,8],
            [2,4,6]
            ]
        return any([sum([self.board[i] == marker for i in pos]) == 3 for pos in winning_positions])
    def is_draw(self):
        return all(str(i) not in self.board for i in range(9))
class Player:
    def __init__(self, name, marker, opponent_marker):
        self.name = name
        self.marker = marker
        self.opponent_marker = opponent_marker
        while self.name == '' or self.name == ' ':
            self.name = input(f"Illegal name, please enter a name again for {self.marker}:\n")
    def make_move(self, board):
        move = input(f'This is the current board, {self.name} please make a move.\n')
        while True:
            if board.legal_move(move):
                return move
            else:
                move = int(input('Illegal move, please try again.\n'))
Game(Player(input("Enter your name for Y marker:\n"), 'O', 'X'), Player(input("Enter your name for X marker:\n"), 'X', 'O'))






""" This code is playing by artificial intelligence.
Sololearn has out time error, so run it on your computer."""
class Game:
    def __init__(self, player1, player2):
        self.board = Board()
        self.players = [player1, player2]
        self.turn = False
        self.play()
    def play(self):
        while True:
            current_player = self.players[int(self.turn)]
            print(self.board.to_string())
            move = current_player.make_move(self.board)
            is_winning = self.board.place_mark(current_player.marker, move)
            if is_winning or self.board.is_draw():
                break
            self.turn = not self.turn
        if self.board.is_draw():
            print(self.board.to_string())
            print ('It\'s a draw!')
            again = input("Do you wanna play again?(y\\n)?\n")
            if again == 'y' or again == 'Y':
                Game(Player(input("Enter your name for X marker:\n"), 'X', 'O'), Computer("Computer", 'O', 'X'))
            elif again == 'n' or again == 'N':
                exit()
        else:
            print (self.board.to_string())
            print(f'Congratulations {current_player.name}, you win!')
            again = input("Do you wanna play again?(y\\n)?\n")
            if again == 'y' or again == 'Y':
                Game(Player(input("Enter your name for X marker:\n"), 'X', 'O'), Computer("Computer", 'O', 'X'))
            elif again == 'n' or again == 'N':
                exit()
class Board:
    def __init__(self, from_board = None):
        self.board = (from_board or list('012345678')).copy()
    def clone(self):
        return Board(self.board)
    def to_string(self):
        return '{}|{}|{}\n-----\n{}|{}|{}\n-----\n{}|{}|{}\n'.format(*self.board)
    def place_mark(self, marker, place):
        if self.board[int(place)] not in '012345678' or int(place) < 0 or int(place) > 8:
            raise ValueError()
        self.board[int(place)] = marker
        return self.is_winner(marker)
    def legal_move(self, i):
        return self.board[int(i)] in '012345678'
    def is_winner(self, marker):
        winning_positions = [
            [0,1,2],
            [3,4,5],
            [6,7,8],
            [0,3,6],
            [1,4,7],
            [2,5,8],
            [0,4,8],
            [2,4,6]
            ]
        return any([sum([self.board[i] == marker for i in pos]) == 3 for pos in winning_positions])
    def is_draw(self):
        return all(str(i) not in self.board for i in range(9))
class Player:
    def __init__(self, name, marker, opponent_marker):
        self.name = name
        self.marker = marker
        self.opponent_marker = opponent_marker
        while self.name == '' or self.name == ' ':
            self.name = input(f"Illegal name, please enter a name again for {self.marker}:\n")
    def make_move(self, board):
        move = input(f'This is the current board, {self.name} please make a move.\n')
        while True:
            if board.legal_move(move):
                return move
            else:
                move = int(input('Illegal move, please try again.\n'))
class Computer(Player):
    def score_move(self, board, i, turn = True):
        new_board = board.clone()
        try:
            new_board.place_mark(self.marker if turn else self.opponent_marker, i)
        except ValueError:
            return None
        if new_board.is_winner(self.marker):
            return 1
        elif new_board.is_winner(self.opponent_marker):
            return -1
        elif new_board.is_draw():
            return 0
        else:
            all_options = 0
            n_options = 0
            for x in range(9):
                if new_board.legal_move(x):
                    test = self.score_move(new_board, x, not turn)
                    all_options += test or 0
                    n_options += 1 if test is not None else 0
            return all_options / n_options
    def make_move(self, board):
        new_board = board.clone()
        moves = []
        best_moves = []
        move = 9
        for i in range(9):
            if board.legal_move(i):
                moves.append((self.score_move(board, i), i))
        moves = sorted(moves)
        best_moves.append(moves[-1][-1])
        for i in moves:
            if i[0] == moves[-1][0] and i != moves[-1][1]:
                best_moves.append(i[-1])
        for i in best_moves:
            try:
                new_board.place_mark(self.opponent_marker, i)
            except Exception as E:
                print (E)
            if new_board.is_winner(self.opponent_marker):
                move = i
            elif move == 9:
                move = moves[-1][1]
            new_board = board.clone()
        return move
Game(Computer("Computer", 'O', 'X'), Player(input("Enter your name for X marker:\n"), 'X', 'O'))"""

4. By Spidey K๐Ÿ’šK๐Ÿ’š๐Ÿ˜‰

Made by Spidey K๐Ÿ’šK๐Ÿ’š๐Ÿ˜‰. Only works on Python IDLE. ( Source )

from __future__ import print_function

print('thanks for seeing my code but there is only a draw back.this code will work only on python3 IDLE. so you want to copy this code and paste this code on new maked python IDLE.')

choices=[]

for X in range (0, 9) :
    choices.append(str(X + 1))

playeroneTurn = True
winner = False

def printBoard()  :
    print( '\n -----')
    print( '|' + choices[0] + '|' + choices[1] + '|' + choices[2] + '|')
    print( ' -----')
    print( '|' + choices[3] + '|' + choices[4] + '|' + choices[5] + '|')
    print( ' -----')
    print( '|' + choices[6] + '|' + choices[7] + '|' + choices[8] + '|')
    print( ' -----\n')

while not winner :
    printBoard()

    if playeroneTurn :
        print('player 1:')
    else :
        print('player 2:')

    try:
        choice = int (input('>> '))
    except:
        print('please enter a valid field')
        continue 
    if choices[choice - 1] == 'X' or choices [choice-1] == 'o':
        print('illegle move,please try again')
        continue 

    if playeroneTurn :
        choices[choice - 1] = 'X'
    else :
        choices[choice - 1] = 'o'

    playeroneTurn  = not playeroneTurn  


    for X in range (1,3) :
        y = X * 3
        if (choices[y] == choices[(y + 1)] and choices[y] == choices[(y + 2)]) :
         winner = True
        printBoard()
    if (choices[X] == choices[(X + 3)] and choices[X] == choices[(X + 1)]) :
        winner = True 
        printBoard()
        
    if((choices[1] == choices[4] and choices[1] == choices[8]) or
       (choices[2] == choices[4] and choices[4] == choices[6])) :
       printBoard()
       
print ('player' + str(int(playeroneTurn + 1)) + ' wins!\n')

5. By Dhritiman Roy

Made by Dhritiman Roy. Simple Tic Tac Toe game. ( Source )

# Tic Tac Toe game
# Date: 19/11/2017

# SUGGESTED: Copy the code and run in your own IDE. Then it will be more comprehensive and effective.

print ("TIC TAC TOE GAME")

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

board_print = " " + board[6] + " | " + board[7] + " | " + board[8] + "\n" + "-----------" + "\n" + " " + board[3] + " | " + board[4] + " | " + board[5] + "\n" + "-----------" + "\n" + " " + board[0] + " | " + board[1] + " | "+ board[2]
board_print_default = " " + "7" + " | " + "8" + " | " + "9" + "\n" + "-----------" + "\n" + " " + "4" + " | " + "5" + " | " + "6" + "\n" + "-----------" + "\n" + " " + "1" + " | " + "2" + " | "+ "3"

print ("")
print (board_print_default)

def p1_input():
    for i in range(10):
        if i == p_in:
            board[i-1] = "X"
            board_print = " " + board[6] + " | " + board[7] + " | " + board[8] + "\n" + "-----------" + "\n" + " " + board[3] + " | " + board[4] + " | " + board[5] + "\n" + "-----------" + "\n" + " " + board[0] + " | " + board[1] + " | " + board[2]
            print (board_print)

def p2_input():
    for i in range(10):
        if i == p_in:
            board[i-1] = "O"
            board_print = " " + board[6] + " | " + board[7] + " | " + board[8] + "\n" + "-----------" + "\n" + " " + board[3] + " | " + board[4] + " | " + board[5] + "\n" + "-----------" + "\n" + " " + board[0] + " | " + board[1] + " | " + board[2]
            print (board_print)

def win_check_p1():

    # Check all the horizontal boxes.
    if board[0] == "X" and board[1] == "X" and board[2] == "X":
        return True

    elif board[3] == "X" and board[4] == "X" and board[5] == "X":
        return True

    elif board[6] == "X" and board[7] == "X" and board[8] == "X":
        return True

    # Check all the vertical boxes.
    elif board[0] == "X" and board[3] == "X" and board[6] == "X":
        return True

    elif board[1] == "X" and board[4] == "X" and board[7] == "X":
        return True

    elif board[2] == "X" and board[5] == "X" and board[8] == "X":
        return True

    # Check all the diagonal boxes.
    elif board[6] == "X" and board[4] == "X" and board[2] == "X":
        return True

    elif board[8] == "X" and board[4] == "X" and board[0] == "X":
        return True

def win_check_p2():

    # Check all the horizontal boxes.
    if board[0] == "O" and board[1] == "O" and board[2] == "O":
        return True

    if board[3] == "O" and board[4] == "O" and board[5] == "O":
        return True

    if board[6] == "O" and board[7] == "O" and board[8] == "O":
        return True

    # Check all the vertical boxes.
    if board[0] == "O" and board[3] == "O" and board[6] == "O":
        return True

    if board[1] == "O" and board[4] == "O" and board[7] == "O":
        return True

    if board[2] == "O" and board[5] == "O" and board[8] == "O":
        return True

    # Check all the diagonal boxes.
    if board[6] == "O" and board[4] == "O" and board[2] == "O":
        return True

    if board[8] == "O" and board[4] == "O" and board[0] == "O":
        return True

def check_draw():
    pass

s = 0
p_in = 0 # Player input.
t = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]    # A variable to check if the given value of p_in is not same.
i = 0
draw_var = 0 # This is the var that is used to check if the match is draw or not.
while s!= 9:
    print ("")

    t[i] = p_in
    p_in = int(input("> "))
    print ("")

    if (p_in == t[0] or p_in == t[1] or p_in == t[2] or p_in == t[3] or p_in == t[4] or p_in == t[5] or p_in == t[6] or p_in == t[7] or p_in == t[8] or p_in == t[9] or p_in == t[10] or p_in == t[11] or p_in == t[12] or p_in == t[13]) or p_in < 1 or p_in > 9:
        print ("Input not accepted. Try again.\n")
    else:
        if s % 2 == 0:
            p1_input()
            win_check_p1()

            if win_check_p1():
                print ("")
                print ("Player 1 has won.")
                draw_var = 1
                break
        elif s % 2 != 0:
            p2_input()
            win_check_p2()

            if win_check_p2():
                print ("")
                print ("Player 2 has won.")
                draw_var = 1
                break
            
        s += 1
    i += 1
    if i == 14:
        print ("Multiple invalid inputs. Please re-start the game.")
        break

if draw_var == 0:
    print ("")
    print ("Draw.")
    

6. By Programmer Raja

Made by Programmer Raja. Tic Tac Toe using oops. ( Source )

class tictac:
    a=[" " for i in range(9)]
    position=[i for i in range(9)]
    def display(s):
      print "|",s.a[0], "|",s.a[1],"|",s.a[2],"|"
      print "-------------"
      print "|",s.a[3], "|",s.a[4],"|",s.a[5],"|"
      print "-------------"
      print "|", s.a[6], "|",s.a[7],"|",s.a[8],"|"
      print "-------------\n\n"
    def check(s):
        ways=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6,))
        for i in ways:
           if  (s.a[i[0]]=="X" and s.a[i[1]]=="X" and s.a[i[2]]=="X") or (s.a[i[0]]=="O" and s.a[i[1]]=="O" and s.a[i[2]]=="O") :
              return True
        else:
            c=1
            for i in range(len(s.a)):
                if s.a[i]=="X" or s.a[i]=="O":
                    c+=1
                    if c==10:
                        print "match draw"
                        return "draw"
        return False
        
class players(tictac):
    def __init__(s):
        
        s.player=input("enter the player name")
        s.weapon=input("choose your weapon(X/O)").upper()
    def move(player1,player2):
        player1_postion=int(input("enter the postion%s"%player1.player))
        if player1_postion in tictac.position:
            if tictac.a[player1_postion]==" ":
                tictac.a[player1_postion]=player1.weapon
                player1.display()
                if player1.check()=="draw":
                     return 
                if player1.check():
                    
                    print ("you are the winner",player1.player)
                    
                else:
                    player2.move(player1)
            else:
                print"postion is already occupied"
                player1 .move(player2)
                
        
        else:
             print "enter a valid postion"
             player1.move(player2)
             
board=tictac()
board.display()
player1=players()
player2=players()
player1.move(player2)
        

7. By Manoj kale

Made by Manoj kale. You get to first enter your name, after that you get to choose your symbol and start the game. ( Source )

import numpy as np
import random
import time
start = '----------  Tic Tac Toe  ----------------'
for i in start:
    print(i,end="",flush=True)
    time.sleep(.05)
print()
time.sleep(2)
Player_name=input("Enter Your Name: ")
entry_list = [1,2,3,4,5,6,7,8,9]
game_display = np.array([['*','*','*'],['*','*','*'],['*','*','*']])
while(True):
    player = input("Select your Sign [+ 0] :")
    if(player!='*' and player!='@'):
        break
    else:
        time.sleep(1)
        print("Please, choose another sign\n")

def display():
    for i in range(3):
        for j in range(3):
            print(game_display[i][j],end=' ')
        print(" ")
display()
filled_pos = []
def add_pos(choise,player1):
    if(choise==1):
        game_display[0][0]=player1
    elif(choise==2):
        game_display[0][1]=player1
    elif(choise==3):
        game_display[0][2]=player1
    elif(choise==4):
        game_display[1][0]=player1
    elif(choise==5):
        game_display[1][1]=player1
    elif(choise==6):
        game_display[1][2]=player1
    elif(choise==7):
        game_display[2][0]=player1
    elif(choise==8):
        game_display[2][1]=player1
    elif(choise==9):
        game_display[2][2]=player1
    else:
        print("not found" + str(choise))

def computer(entry_list):
    if(entry_list==[]):
        print("Match Draw\n")
        return 0
    num=random.sample(entry_list,1)
    entry_list.remove(num[0])
    return num

def winner_is(winner_sign):
    global Player_name
    if(winner_sign=='@'):
        winner='Computer'
    else:
        winner=Player_name
    print("Winner is :" + winner)


def cheak_winner(game_display):
    time.sleep(1)
    for i in range(3):
        for j in range(1):
            if(game_display[i][j]==game_display[i][j+1] and game_display[i][j+2]==game_display[i][j+1] and game_display[i][j]!='*'):
                winner=game_display[i][j]
                winner_is(winner)
                # print("Winner is : " + str(winner))
                display()
                return 1
            elif(game_display[j][i]==game_display[j+1][i] and game_display[j+1][i]==game_display[j+2][i] and game_display[j][i]!='*'):
                winner=game_display[j][i]
                # print("Winner is : " + str(winner))
                winner_is(winner)
                display()
                return 1
            elif(game_display[0][0]==game_display[1][1] and game_display[0][0]==game_display[2][2] and game_display[0][0]!='*'):
                winner=game_display[0][0]
                winner_is(winner)
                # print("Winner is : " + str(winner))
                display()
                return 1
            elif(game_display[0][2]==game_display[1][1] and game_display[0][2]==game_display[2][0] and game_display[0][2]!='*'):
                winner=game_display[0][2]
                # print("Winner is : " + str(winner))
                winner_is(winner)
                display()
                return 1                            
    display()
    return 0
win=0
while(win!=1):
    time.sleep(1)
    choise = int(input("Select the Position : [1-9] :"))
    if(choise not in entry_list):
        print("Postion is occupied\n")
        continue
    else:
        entry_list.remove(choise)
    add_pos(choise,player)
    win=cheak_winner(game_display)
    print("-----------")
    if(win==1):
        break
    player2 = computer(entry_list)    
    if(player2==0):
        break
    add_pos(player2[0],'@')
    win=cheak_winner(game_display)
    
# Creater: Manoj Kale

8. By Tolulope Soneye

Made by Tolulope Soneye. ( Source )

# Global Variables


# Game Board
board = ["-", "-", "-",
         "-", "-", "-",
         "-", "-", "-"]
# If game is going
game_still_going = True

# Who won? Or tie?
winner = None

# Who's turn is it
current_player = "X"


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


def play_game():

    # Display initial board
    display_board()

    while game_still_going:

        handle_turn(current_player)

        check_if_game_over()

        # Flip to the other player
        flip_player()

        # The game has ended
    if winner == "X" or winner == "O":
        print(winner + " won.")
    elif winner == None:
        print("Tie.")


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("Invalid 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_if_tie()


def check_for_winner():

    global winner

    # check rows
    row_winner = check_rows()
    # check columns
    column_winner = check_columns()
    # check diagonals
    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
    return


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]
    return


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]
    return


def check_diagonals():
    global game_still_going

    diagonals_1 = board[0] == board[4] == board[8] != "-"
    diagonals_2 = board[6] == board[4] == board[2] != "-"

    if diagonals_1 or diagonals_2:
        game_still_going = False
    if diagonals_1:
        return board[0]
    elif diagonals_2:
        return board[6]
    return


def check_if_tie():
    global game_still_going
    if "-" not in board:
        game_still_going = False
    return


def flip_player():
    global current_player

    if current_player == "X":
        current_player = "O"
    elif current_player == "O":
        current_player = "X"
    return


play_game()

9. By Feuerstein

Made by Feuerstein. A simple, but logically demanding Tic-Tac-Toe game. ( Source )

# Run it on your IDLE as this code requires multiple inputs over time.
# Fully working.

# Available Commands | the Board to visualize & run the program.
theBoard = {'top-l': ' ', 'top-m': ' ', 'top-r': ' ', 'mid-l': ' ', 'mid-m': ' ', 'mid-r': ' ', 'low-l': ' ', 'low-m': ' ', 'low-r': ' '}


# Printing the board to the table when the function is called.
def printBoard(board):
    
    print(board['top-l'] + '|' + board['top-m'] + '|' + board['top-r'])
    print('-+-+-')
    print(board['mid-l'] + '|' + board['mid-m'] + '|' + board['mid-r'])
    print('-+-+-')
    print(board['low-l'] + '|' + board['low-m'] + '|' + board['low-r'])
    print('\n')
    

# Checking if the game is finished by determining the win or draw.
def checkBoard(board):

    result = 0 # Stands for a draw
    winner = '' # X or O
    
    currentStats = list(board.values())
    # List Comprehension to separate the list into three sub-lists with a width of 3.
    currentStats = [currentStats[i:i+3] for i in range(0, 9, 3)]
    
    
    # The main code for checking.
    for i in range(3):
        # Checking Vertically.
        if currentStats[0][i] == currentStats[1][i] and currentStats[1][i] == currentStats[2][i] and currentStats[0][i] != ' ':
            winner = currentStats[0][i]
            result = 1
            break
            
        # Checking Horizontally.
        elif currentStats[i][0] == currentStats[i][1] and currentStats[i][1] == currentStats[i][2] and currentStats[i][0] != ' ':
            winner = currentStats[i][0]
            result = 1
            break
        
        # Checking diagonally from left to right.
        elif currentStats[0][0] == currentStats[1][1] and currentStats[2][2] == currentStats[1][1] and currentStats[0][0] != ' ':
            winner = currentStats[0][0]
            result = 1
            break

        # Checking diagonally from right to left.
        elif currentStats[0][2] == currentStats[1][1] and currentStats[2][0] == currentStats[1][1] and currentStats[0][2] != ' ':
            winner = currentStats[0][2]
            result = 1
            break
      
            
    return [result, winner]    


# Function to validate input positions.
def validInput(position):
    if position in theBoard.keys():
        return True
        
    return False
  
    
# Function to check if the position is already occupied.
def validSquare(square):
    if theBoard[square] == ' ':
        return True
        
    return False

# Main Code.
turn = 'X'
for i in range(10):
    printBoard(theBoard)
    
    print(f'Turn for {turn}. Move on which space?')
    move = input().lower()
    
    
    # Validating input.
    if validInput(move):
        pass
    else:
        print('Please, enter only the allowed positions.')
        if i == 9:
            print('You did not enter any available positions. Reload to play again.')
        continue
    
    
    # Validating Squares
    if validSquare(move):
        theBoard[move] = turn
    else:
        print(f'{move} is already occupied!')
        if i == 9:
            print('You entered occupied positions too much. Reload to play again.')
            continue
    
    
    # Getting the results of the game.
    check = checkBoard(theBoard)
    
    # Checking to finish the game.
    # check[0] - result. If either 'X' and '0' is 3 lines long, the result is set to 1.
    if check[0] == 1:
        print(f'Congratulations. {check[1]} has won!')
        break
    
    # if the game continues, we need to take turns.
    else:
        if turn == 'X':
            turn = '0'
        else:
            turn = 'X'
    
    # At the end of the game, if no  one wins, then this message is displayed.
    if i == 9:
        if check[0] == 0:
            print('It is a draw. Thank you for playing')
    

# Running
printBoard(theBoard)
            

10. By eldio

Made by eldio. You can press space to restart the game. ( Source )

import pygame
import sys

def check_win(mas, sign):
    zeroes = 0
    for row in mas:
        zeroes += row.count(0)
        if row.count(sign) == 3:
            return sign
    for col in range(3):
        if mas[0][col] == sign and mas[1][col] == sign and mas[2][col] == sign:
            return sign
        if mas[0][0] == sign and mas[1][1] == sign and mas[2][2] == sign:
            return sign
    if mas[0][0] == sign and mas[1][1] == sign and mas[2][2] == sign:
        return sign
    if mas[0][2] == sign and mas[1][1] == sign and mas[2][0] == sign:
        return sign
    if zeroes == 0:
        return 'Piece'
    return False


pygame.init()
size_block = 100
margin = 15
width = height = size_block * 3 + margin * 4

size_window = (width, height)
screen = pygame.display.set_mode(size_window)
pygame.display.set_caption("XO")

black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
mas = [[0] * 3 for i in range(3)]
query = 0  # 1 2 3 4 5 6 7
game_over = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)
        elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            x_mouse, y_mouse = pygame.mouse.get_pos()
            col = x_mouse // (size_block + margin)
            row = y_mouse // (size_block + margin)
            if mas[row][col] == 0:
                if query % 2 == 0:
                    mas[row][col] = 'x'
                else:
                    mas[row][col] = 'o'
                query += 1
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            game_over = False
            mas = [[0] * 3 for i in range(3)]
            query = 0
            screen.fill(black)
    if not game_over:
        for row in range(3):
            for col in range(3):
                if mas[row][col] == 'x':
                    color = red
                elif mas[row][col] == 'o':
                    color = blue
                else:
                    color = white
                x = col * size_block + (col + 1) * margin
                y = row * size_block + (row + 1) * margin
                pygame.draw.rect(screen, color, (x, y, size_block, size_block))
                if color == red:
                    pygame.draw.line(screen, white, (x + 5, y + 5), (x + size_block - 5, y + size_block - 5), 3)
                    pygame.draw.line(screen, white, (x + size_block - 5, y + 5), (x + 5, y + size_block - 5), 3)
                elif color == blue:
                    pygame.draw.circle(screen, white, (x + size_block // 2, y + size_block // 2), size_block // 2 - 3,
                                       3)
    if (query - 1) % 2 == 0:  # x
        game_over = check_win(mas, 'x')
    else:
        game_over = check_win(mas, 'o')

    if game_over:
        screen.fill(black)
        font = pygame.font.SysFont('stxingkai', 80)
        text1 = font.render(game_over, True, white)
        text_rect = text1.get_rect()
        text_x = screen.get_width() / 2 - text_rect.width / 2
        text_y = screen.get_height() / 2 - text_rect.height / 2
        screen.blit(text1, [text_x, text_y])
    pygame.display.update()
Input()

11. By Anshu Khanra

Made by Anshu Khanra. If you have an offline coding playground, like PyCharm, Go to the terminal and type “pip install pygame”. ( Source )


import pygame as pg

from pygame.locals import *

import time


# Initialize Global Variables
XO = 'x'
winner = None
draw = False
width = 400
height = 400
white = (255, 255, 255)
line_color = (10, 10, 10)

# TicTacToe 3x3 board
TTT = [[None]*3, [None]*3, [None]*3]

# Initializing Pygame Window
pg.init()
fps = 30
CLOCK = pg.time.Clock()
screen = pg.display.set_mode((width, height + 100), 0, 32)
pg.display.set_caption("Tic Tac Toe")

# Loading The Images
opening = pg.image.load("C:/Users/Bishwajit/Desktop/tic tac opening.png")
x_img = pg.image.load("C:/Users/Bishwajit/Downloads/x.png")
o_img = pg.image.load("C:/Users/Bishwajit/Desktop/o.png")


# Resizing Images
x_img = pg.transform.scale(x_img, (80,80))
o_img = pg.transform.scale(o_img, (80,80))
opening = pg.transform.scale(opening, (width, height+100))

def game_opening():
    screen.blit(opening,(0,0))
    pg.display.update()
    time.sleep(1)
    screen.fill(white)
    # Drawing vertical lines
    pg.draw.line(screen, line_color, (width/3, 0), (width/3, height), 7)
    pg.draw.line(screen, line_color, (width/3*2, 0), (width/3*2, height), 7)
    # Drawing horizontal lines
    pg.draw.line(screen, line_color, (0, height/3), (width, height/3), 7)
    pg.draw.line(screen, line_color, (0, height/3*2), (width, height/3*2), 7)
    draw_status()

def draw_status():
    global draw
    if winner is None:
        message = XO.upper() + "'s Turn"
    else:
        message = winner.upper() + " won!"
    if draw:
        message = 'Game Draw!'
    font = pg.font.Font(None, 30)
    text = font.render(message, 1, (255, 255, 255))
    # copy the rendered message onto the board
    screen.fill ((0, 0, 0), (0, 400, 500, 100))
    text_rect = text.get_rect(center=(width/2, 500-50))
    screen.blit(text, text_rect)
    pg.display.update()

def check_win():
    global TTT, winner,draw
    # check for winning rows
    for row in range (0,3):
        if ((TTT [row][0] == TTT[row][1] == TTT[row][2]) and(TTT [row][0] is not None)):
            # this row won
            winner = TTT[row][0]
            pg.draw.line(screen, (250,0,0), (0, (row + 1)*height/3 -height/6),\
                              (width, (row + 1)*height/3 - height/6 ), 4)
            break
    # check for winning columns
    for col in range (0, 3):
        if (TTT[0][col] == TTT[1][col] == TTT[2][col]) and (TTT[0][col] is not None):
            # this column won
            winner = TTT[0][col]
            #draw winning line
            pg.draw.line (screen, (250,0,0),((col + 1)* width/3 - width/6, 0),\
                          ((col + 1)* width/3 - width/6, height), 4)
            break
    # check for diagonal winners
    if (TTT[0][0] == TTT[1][1] == TTT[2][2]) and (TTT[0][0] is not None):
        # game won diagonally left to right
        winner = TTT[0][0]
        pg.draw.line (screen, (250,70,70), (50, 50), (350, 350), 4)
    if (TTT[0][2] == TTT[1][1] == TTT[2][0]) and (TTT[0][2] is not None):
        # game won diagonally right to left
        winner = TTT[0][2]
        pg.draw.line (screen, (250,70,70), (350, 50), (50, 350), 4)
    if(all([all(row) for row in TTT]) and winner is None ):
        draw = True
    draw_status()

def drawXO(row,col):
    global TTT,XO
    if row==1:
        posx = 30
    if row==2:
        posx = width/3 + 30
    if row==3:
        posx = width/3*2 + 30
    if col==1:
        posy = 30
    if col==2:
        posy = height/3 + 30
    if col==3:
        posy = height/3*2 + 30
    TTT[row-1][col-1] = XO
    if(XO == 'x'):
        screen.blit(x_img,(posy,posx))
        XO= 'o'
    else:
        screen.blit(o_img,(posy,posx))
        XO= 'x'
    pg.display.update()
    #print(posx,posy)
    #print(TTT)

def userClick():
    #get coordinates of mouse click
    x,y = pg.mouse.get_pos()
    #get column of mouse click (1-3)
    if(x<width/3):
        col = 1
    elif (x<width/3*2):
        col = 2
    elif(x<width):
        col = 3
    else:
        col = None
    #get row of mouse click (1-3)
    if(y<height/3):
        row = 1
    elif (y<height/3*2):
        row = 2
    elif(y<height):
        row = 3
    else:
        row = None
    #print(row,col)
    if(row and col and TTT[row-1][col-1] is None):
        global XO
        #draw the x or o on screen
        drawXO(row,col)
        check_win()

def reset_game():
    global TTT, winner,XO, draw
    time.sleep(3)
    XO = 'x'
    draw = False
    game_opening()
    winner=None
    TTT = [[None]*3,[None]*3,[None]*3]

game_opening()

# Run for the game loop forever
while(True):
    for event in pg.event.get():
        if event.type == QUIT:
            pg.quit()
        elif event.type == MOUSEBUTTONDOWN:
            # The user clicked; place an x or o
            userClick()
            if(winner or draw):
                reset_game()
    pg.display.update()
    CLOCK.tick(fps)

12. By Alon Schwarzblatt

Made by Alon Schwarzblatt. ( Source )



list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print ("the board of the game is: \n|", list[0], "|", list[1], "|", list[2], "|")
print ("|", list[3], "|", list[4], "|", list[5], "|")
print ("|", list[6], "|", list[7], "|", list[8], "|")
print ("try to beat your friend in tic-tac-toe")
print ("every time enter the number of place you want to put your X")
while not list[0]==list[1]==list[2] and not list[0]==list[3]==list[6] and not list[0]==list[4]==list[8] and not list[1]==list[4]==list[7] and not list[3]==list[4]==list[5] and not list[6]==list[7]==list[8]and not list[2]==list[5]==list[8] and not list[2]==list[4]==list[6]:
	Turn = int(input("enter the number of the place you want to put your X   "))
	if list[list.index(Turn)]!="X" or list[list.index(Turn)]!="O" :
		list[list.index(Turn)] = "X"
	else:
		print ("eror, try again.")
	print ("the board of the game now is: \n|", list[0], "|", list[1], "|", list[2], "|")
	print ("|", list[3], "|", list[4], "|", list[5], "|")
	print ("|", list[6], "|", list[7], "|", list[8], "|")
	if  list[0]==list[1]==list[2] or list[0]==list[3]==list[6] or list[0]==list[4]==list[8] or list[1]==list[4]==list[7] or list[3]==list[4]==list[5] or list[6]==list[7]==list[8]or list[2]==list[5]==list[8] or list[2]==list[4]==list[6]:
		break
	else:
		Turn = int(input("enter the number of the place you want to put your O   "))
		if list[list.index(Turn)]!="X" or list[list.index(Turn)]!="O" :
			list[list.index(Turn)] = "O"
		else:
			print ("eror, try again.")
		print (")the board of the game now is: \n|", list[0], "|", list[1], "|", list[2], "|")
		print ("|", list[3], "|", list[4], "|", list[5], "|")
		print ("|", list[6], "|", list[7], "|", list[8], "|")
if list[0]==list[1]==list[2]=="X" or list[0]==list[3]==list[6]=="X" or list[0]==list[4]==list[8]=="X" or list[1]==list[4]==list[7]=="X" or list[3]==list[4]==list[5]=="X" or list[6]==list[7]==list[8]=="X" or list[2]==list[5]==list[8]=="X" or list[2]==list[4]==list[6]=="X":
	print ("player X is the winner!!")
else :
	print ("player O is the winner!")



13. By Dexent Hamza

Made by Dexent Hamza. Tic Tac Toe made using Python tkinter. ( Source )

from tkinter import *

import tkinter.messagebox

tk = Tk()
tk . title("Tic Tac Toe")

click = True

def checker (buttons):
    global Click
    if buttons["text"] ==" " and click == True:
        buttons["text"] = "X"
        click = False

    elif buttons["text"] ==" " and click == False:
        buttons["text"] = "O"
        click = True

    elif(button1["text"] =="X" and button2["text"]  =="X" and button3["text"] =="X" or
        button4["text"] =="X" and button5["text"]  =="X" and button6["text"] =="X" or
        button7["text"] =="X" and button8["text"]  =="X" and button9["text"] =="X" or
        button3["text"] =="X" and button5["text"]  =="X" and button7["text"] =="X" or
        button1["text"] =="X" and button5["text"]  =="X" and button9["text"] =="X" or
        button1["text"] =="X" and button4["text"]  =="X" and button7["text"] =="X" or
        button2["text"] =="X" and button5["text"]  =="X" and button8["text"] =="X" or
        button3["text"] =="X" and button6["text"]  =="X" and button9["text"] =="X"):
         tkinter.messegebox.showinfo("Winner X", "You have just won a game")


    elif(button1["text"] =="O" and button2["text"]  =="O" and button3["text"] =="O" or
        button4["text"] =="O" and button5["text"]  =="O" and button6["text"] =="O" or
        button7["text"] =="O" and button8["text"]  =="O" and button9["text"] =="O" or
        button3["text"] =="O" and button5["text"]  =="O" and button7["text"] =="O" or
        button1["text"] =="O" and button5["text"]  =="O" and button9["text"] =="O" or
        button1["text"] =="O" and button4["text"]  =="O" and button7["text"] =="O" or
        button2["text"] =="O" and button5["text"]  =="O" and button8["text"] =="O" or
        button3["text"] =="O" and button6["text"]  =="O" and button9["text"] =="O" ):
         tkinter.messegebox.showinfo("Winner O", "You have just won a game")

buttons=StringVar()

button1 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button1))
button1.grid(row=1 , column=0,sticky = S+N+E+W)

button2 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button2))
button2.grid(row=1 , column=1,sticky = S+N+E+W)

button3 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button3))
button3.grid(row=1 , column=2,sticky = S+N+E+W)

button4 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button4))
button4.grid(row=2 , column=0,sticky = S+N+E+W)

button5 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button5))
button5.grid(row=2 , column=1,sticky = S+N+E+W)

button6 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button6))
button6.grid(row=2 , column=2,sticky = S+N+E+W)

button7 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button7))
button7.grid(row=3 , column=0,sticky = S+N+E+W)

button8 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button8))
button8.grid(row=3 , column=1,sticky = S+N+E+W)

button9 = Button(tk,text=" ",font=('Tiems 26 bold'), height = 4 , width = 8, command=lambda:checker(button9))
button9.grid(row=3 , column=2,sticky = S+N+E+W)


tk.mainloop()




        

14. By vishnu sangem

Made by vishnu sangem. ( Source )

def who_is_the_winner():
    m = 0
    for i in range(3):
        k=0
        l=0
        for j in range(3):
            if(j!=2 and table[i][j] != '*'):
                if(table[i][j] == table[i][j+1]):
                    k+=1
                    if(k == 2):
                        if(table[i][j] == '@'):
                            return 0;
                        else:
                            return 1;
                    if(k == 2):
                        break;
                    
            if(j!=2 and table[j][i] != '*'):
                if(table[j][i] == table[j+1][i]):
                    l+=1
                    if(l == 2):
                        if(table[j][i] == '@'):
                            return 0;
                        else:
                            return 1;
                    if(l == 2):
                        break;
            if(i == j and table[i][j] != '*'):
                if(j != 2):
                    if(table[i][j] == table[i+1][j+1]):
                        m+=1
                        if(m == 2):
                            if(table[i][j] == '@'):
                                return 0;
                            else:
                                return 1;
                        if(m == 2):
                            break;            
                
def show_table():
    for j in range(3):
        print("\t--------------------")
        for k in range(3):
            print("\t",table[j][k],end='  |  ')
        print("\n")
    print("\t--------------------")
def filling(n):
    squares.remove(n)
    filled_squares.append(n)
    show_table()
    opt=who_is_the_winner()
    if(opt == 1):
        print("YoU LoST")
    elif(opt == 0):
        print(" YoU WoN ")
    elif(len(squares) == 0):
        print("match tied")
import random
table = [['*','*','*'],['*','*','*'],['*','*','*']]
squares = [0,1,2,3,4,5,6,7,8]
filled_squares = [10]
sys_input = 10

while( len(squares) != 0):
    if sys_input in filled_squares:
        sys_input = random.choice(squares)
    else:
        row = sys_input//3
        col = sys_input%3
        table[row][col] = "X"
        print("system turn ->")
        filling(sys_input)
        print("your\'s turn->",end='')
        row, col = input().strip().split(' ')
        row, col = [int(row), int(col)]
        table[row][col] = '@'
        row = row*3
        filling(row+col)
        opt=who_is_the_winner()
        if(opt == 0 or opt ==1):
            break;

15. By Javed Ullah

Made by Javed Ullah. You can select your choice of symbol before starting the game. ( Source )

#only observe what you have read so far! The if, elif and else statements and see how many conditions i have linked up in each statement!
#i think this code will not work here in the playground, because it aquires many inputs. Though it is working fine with me




Wel_Hello = "Hello!"
Game_Name = "Welcome to the TIC TAC TOE Game!"

print('\33[1m')
print(Wel_Hello.center(len(Game_Name)+28, '-') + '\n')
print(Game_Name.center(len(Game_Name)+28, '~'))
print('\33[0m')
print('\n')


#dictionary of the places in the board
the_board = {'top_L' : ' ', 'top_M' : ' ', 'top_R' : ' ', 'mid_L' : ' ', 'mid_M' : ' ', 'mid_R' : ' ', 'low_L' : ' ', 'low_M' : ' ', 'low_R' : ' '}

#printing the board
def board(board):
    print("\t\t\t" + board['top_L'] + '|' + board['top_M'] + '|' + board['top_R'])
    print('\t\t\t-+-+-')
    print("\t\t\t" + board['mid_L'] + '|' + board['mid_M'] + '|' + board['mid_R'])
    print('\t\t\t-+-+-')
    print("\t\t\t" + board['low_L'] + '|' + board['low_M'] + '|' + board['low_R'])

#selecting the player
turn = input("type 'X' or 'O' as your choice:\t").upper()
print("\n")

#making condition, if player select other than O and X
player = turn
while player !='X' or player !='O':
    if player == 'X':
        break
    elif player == 'O':
        break
    else:
        player = input("You have chose a wrong player name! In this game we have only player 'X' and player 'O'. So choose between anyone of them!\nEnter again:\n").upper()

turn = player
check_list = []

#taking input from player, where to move
for i in range(9):
    board(the_board)
    print('\n\nTurn for ' + turn + ' which place to move?')
    move1 = input("Enter 'mid', 'top' or 'low': ").lower()
    
    #condition, if player write a wrong place name, which is even not on the board
    while move1 != 'top' or move1 != 'mid' or move1 != 'low':
        if move1 == 'top':
            break
        elif move1 == 'mid':
            break
        elif move1 == 'low':
            break
        else:
            move1 = input("Oops! You have entered something wrong ๐Ÿ™„! Enter again either 'top' or 'mid' or 'low':\n").lower()
    move2 = input("Enter 'L', 'M', or 'R': ").upper()
    print("\n")
    
    while move2 != 'L' or move2 != 'M' or move2 != 'R':
        if move2 == 'M':
            break
        elif move2 == 'R':
            break
        elif move2 == 'L':
            break
        else:
            move2 = input("\nOops! You have entered something wrong ๐Ÿ™„! Enter again either 'L' or 'M' or 'R':\n").upper()
                
    move = move1 + '_' + move2    
    
    #condition for, if player select a place, which is already covered by the opposing player
    if move in check_list:
        print("\nThat place is already covered by your opposite player!\nSelect a new place please!\n")
    else:
        the_board[move] = turn
        
        if turn == 'X':
            turn = 'O'
        else:
            turn ='X'
        check_list.append(move)
        print("\n")
        
        #condition, if a player wins!    
        if (the_board['top_L'] == 'X' and the_board['top_M'] == 'X' and the_board['top_R'] == 'X') or (the_board['top_L'] == 'O' and the_board['top_M'] == 'O' and the_board['top_R'] == 'O') or (the_board['mid_L'] == 'X' and the_board['mid_M'] == 'X' and the_board['mid_R'] == 'X') or (the_board['mid_L'] == 'O' and the_board['mid_M'] == 'O' and the_board['mid_R'] == 'O') or (the_board['low_L'] == 'X' and the_board['low_M'] == 'X' and the_board['low_R'] == 'X') or (the_board['low_L'] == 'O' and the_board['low_M'] == 'O' and the_board['low_R'] == 'O') or (the_board['top_L'] == 'X' and the_board['mid_M'] == 'X' and the_board['low_R'] == 'X') or (the_board['top_L'] == 'O' and the_board['mid_M'] == 'O' and the_board['low_R'] == 'O') or (the_board['top_R'] == 'X' and the_board['mid_M'] == 'X' and the_board['low_L'] == 'X') or (the_board['top_R'] == 'O' and the_board['mid_M'] == 'O' and the_board['low_L'] == 'O') or (the_board['top_L'] == 'X' and the_board['mid_L'] == 'X' and the_board['low_L'] == 'X') or (the_board['top_L'] == 'O' and the_board['mid_L'] == 'O' and the_board['low_L'] == 'O') or (the_board['top_M'] == 'X' and the_board['mid_M'] == 'X' and the_board['low_M'] == 'X') or (the_board['top_M'] == 'O' and the_board['mid_M'] == 'O' and the_board['low_M'] == 'O') or (the_board['top_R'] == 'X' and the_board['mid_R'] == 'X' and the_board['low_R'] == 'X') or (the_board['top_R'] == 'O' and the_board['mid_R'] == 'O' and the_board['low_R'] == 'O'):        
            break        

board(the_board)

#condition, which player won and what to print
if (the_board['top_L'] == 'X' and the_board['top_M'] == 'X' and the_board['top_R'] == 'X') or (the_board['mid_L'] == 'X' and the_board['mid_M'] == 'X' and the_board['mid_R'] == 'X') or (the_board['low_L'] == 'X' and the_board['low_M'] == 'X' and the_board['low_R'] == 'X') or (the_board['top_L'] == 'X' and the_board['mid_M'] == 'X' and the_board['low_R'] == 'X') or (the_board['top_R'] == 'X' and the_board['mid_M'] == 'X' and the_board['low_L'] == 'X') or (the_board['top_L'] == 'X' and the_board['mid_L'] == 'X' and the_board['low_L'] == 'X') or (the_board['top_M'] == 'X' and the_board['mid_M'] == 'X' and the_board['low_M'] == 'X') or (the_board['top_R'] == 'X' and the_board['mid_R'] == 'X' and the_board['low_R'] == 'X'):
    player1 = 'X'
    player2 = 'O'
    print(f'\nCongratulations {player1}, You have won the tic-tac-toe game.')
    print(f'Better luck next time player {player2}')

#if the other player wins!    
elif (the_board['top_L'] == 'O' and the_board['top_M'] == 'O' and the_board['top_R'] == 'O') or (the_board['mid_L'] == 'O' and the_board['mid_M'] == 'O' and the_board['mid_R'] == 'O') or (the_board['low_L'] == 'O' and the_board['low_M'] == 'O' and the_board['low_R'] == 'O') or (the_board['top_L'] == 'O' and the_board['mid_M'] == 'O' and the_board['low_R'] == 'O') or (the_board['top_R'] == 'O' and the_board['mid_M'] == 'O' and the_board['low_L'] == 'O') or (the_board['top_L'] == 'O' and the_board['mid_L'] == 'O' and the_board['low_L'] == 'O') or (the_board['top_M'] == 'O' and the_board['mid_M'] == 'O' and the_board['low_M'] == 'O') or (the_board['top_R'] == 'O' and the_board['mid_R'] == 'O' and the_board['low_R'] == 'O'):
    player1 = 'O'
    player2 = 'X'
    print(f'\nCongratulations {player1}, You have won the tic-tac-toe game.')
    print(f'Better luck next time player {player2}')

#if no one wins
else:
    print("The game is a draw, though it was a hard fought game! You both are great players.\nGood luck ๐Ÿคž for your future games!")

16. By Oluwaseyi Temitope

Made by Oluwaseyi Temitope. Note: You are to input three input, One: which side do u want X or O Two: You are to Enter Yes to begin the game Three: Choose the place you want to input either 1 to 9. ( Source )


def display_board(board):

    print('   |   |')
    print(' ' + board[7] + ' ' + '| ' + board[8] + ' ' + '| ' + board[9])
    print('   |   |')
    print(' ---------')
    print('   |   |')
    print(' ' + board[4] + ' ' + '| ' + board[5] + ' ' + '| ' +board[6])
    print('   |   |')
    print(' ---------')
    print('   |   |')
    print(' ' + board[1] + ' ' + '| ' + board[2] + ' ' + '| ' + board[3])
    print('   |   |')


test_board = ['#','X','O','X','O','X','O','X','O','X']
def player_input():
    marker = ''

    while not (marker == 'X' or marker == 'O'):
        marker = input('Player 1, Do you want to be X or O: ').upper()

        if marker == 'X':
            return ('X', 'O')
        else:
            return ('O', 'X')

def place_marker(board,marker,position):
    board[position] = marker

#print(place_marker(test_board,'$',8))

#print(display_board(test_board))

def win_check(board,mark):
    return ((board[4] == mark and board[5] == mark and board[6] == mark) or
            (board[1] == mark and board[2] == mark and board[3] == mark) or
            (board[7] == mark and board[8] == mark and board[9] == mark) or
            (board[1] == mark and board[4] == mark and board[7] == mark) or
            (board[2] == mark and board[5] == mark and board[8] == mark) or
            (board[3] == mark and board[6] == mark and board[9] == mark) or
            (board[1] == mark and board[5] == mark and board[9] == mark) or
            (board[3] == mark and board[5] == mark and board[7] == mark))

#print(win_check(test_board, 'X'))

import random
def choose_first():
    if random.randint(0,1) == 0:
        return 'Player 2'
    else:
        return 'Player 1'

def space_check(board,position):
    return board[position] == ' '

def full_board_check(board):
    for i in range(1,10):
        if space_check(board, i):
            return False
    return True

def player_choice(board):
    position = 0

    while position not in [range(1,10)] or not space_check(board,position):
        position = int(input('Choose your next position(1-9): '))


    return position

def replay():
    return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')

print('Welcome to Tic Tac Toe')
game_on = True

while game_on:
    the_board = [' '] * 10
    player1_marker, player2_marker = player_input()
    turn = choose_first()
    print(turn + ' will go first')

    play_game = input('Are you ready to start the game? Enter Yes or No: ')
    if play_game.lower()[0] == 'y':
        game_on = True
    else:
        game_on = False

    while game_on:
        # Player1 turn

        if turn == 'Player1':
            display_board(the_board)
            position = player_choice(the_board)
            place_marker(the_board,player1_marker,position)

            if win_check(the_board,player1_marker):
                display_board(the_board)
                print('Congratulations!, You have won the game')
                game_on = False
            else:
                if full_board_check(the_board):
                    display_board(the_board)
                    print('The game is a draw!!')
                    break
                else:
                    turn = 'Player 2'

        else:

            display_board(the_board)
            position = player_choice(the_board)
            place_marker(the_board, player2_marker, position)

            if win_check(the_board,player2_marker):
                display_board(the_board)
                print('Player 2 won the game!!')
                game_on = False
            else:
                if full_board_check(the_board):
                    display_board(the_board)
                    print('The game is a tie!!')
                    break
                else:
                    turn = 'Player 1'

    if not replay():
        break

17. By OkomoJacob

Made by OkomoJacob. Python Tic Tac Toe game made using Tkinter. ( Source )

from tkinter import *
from tkinter import Button
from tkinter.messagebox import showinfo

# Define a function to display whether player 1(X) or player 2(O) is playing
from typing import List, Any

y = ""  # Initialised as null Will store whether the value playing is X or O
x = 2  # Is maximised to 2 Will store the integer value of the number of the current player whether 1 or 2
player_1 = []  # is a list to store the number of buttons in them and it is initialised as empty
player_2: List[Any] = []


def define_sign(number):  # This is what the lambda function sends if the button 1 is pressed then the number 1 is sent
    global x, y
    global player_1, player_2

    """
    NOW PERMUTATION STARTS HERE TO DETERMINE WHICH PLAYER WINS
    """

    from itertools import permutations
    # We are iterating through all the possible win combinations.(Either raws, columns or even diagonals.
    # E.g ([3, 5, 7]) means third, 5th and 7th buttons respectively.

    set1 = permutations([1, 2, 3])
    set2 = permutations([3, 5, 7])
    set3 = permutations([1, 5, 9])
    set4 = permutations([3, 6, 9])
    set5 = permutations([1, 4, 7])
    set6 = permutations([4, 5, 6])
    set7 = permutations([7, 8, 9])
    set8 = permutations([2, 5, 8])

    # We are now creating a for loop to extract each set from the above set
    for i in set1, set2, set3, set4, set5, set6, set7, set8:
        # now we are iterating in the above set for each value
        for j in list(i):
            # We are extracting elements in player_1 and
            # checking whether all the elements of j of the permuted list is present in player 1list or not
            # An dif it is present, then player 1 becomes True
            """
            Example:
            >>> a = [1, 2, 3, 4, 5]
            >>> b = [2, 4, 5]
            >>> all(elem in a for elem in b)
            True
            """
            plyr_1: bool = all(elem in player_1 for elem in j)
            plyr_2 = all(elem in player_2 for elem in j)
            # So this loop will check if all j elements are present in the player list and if so is true then:

            if plyr_1:  # I.e player 1 has satisfied all the conditions and thus won
                print("Player 1 has Won")
                showinfo("Game results", "Player 2 has lost!")

            # Winning conditions for player 2
            elif plyr_2:  # I.e player 1 has satisfied all the conditions and thus won
                print("Player 2 has Won")
                showinfo("Game results", "Player 1 has lost")
                # We need to break any loop of course
                break
            # If there is no winner, we pass
            else:
                pass

    # If player 1 is playing
    if number == 1:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b1.config(text=y)
        x = x + 1

        # If player 1 is playing
    if number == 2:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b2.config(text=y)
        x = x + 1

        # If player 1 is playing
    if number == 3:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b3.config(text=y)
        x = x + 1

        # If player 1 is playing
    if number == 4:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b4.config(text=y)
        x = x + 1

        # If player 1 is playing
    if number == 5:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b5.config(text=y)
        x = x + 1

        # If player 1 is playing
    if number == 6:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b6.config(text=y)
        x = x + 1

        # If player 1 is playing
    if number == 7:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b7.config(text=y)
        x = x + 1

        # If player 1 is playing
    if number == 8:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b8.config(text=y)
        x = x + 1

        # If player 1 is playing
    if number == 9:  # and x % 2 == 0:
        if x % 2 == 0:  # This tells us that player 1 is playing and thus the empty string is filed with the X value
            y = 'X'
            assert isinstance(player_1, object)
            player_1.append(number)
            print(player_1)

        # If player 2 is now playing
        elif 0 != x % 2:

            # This tells us that player 2 is playing and thus the empty string is filed with the O value
            y = 'O'
            assert isinstance(player_2, object)
            player_2.append(number)
            print(player_2)

        b9.config(text=y)
        x = x + 1


root = Tk()
root.title('Tic Tac Toe')

# labels:
l1 = Label(root, text='Player 1: X', font="times 15")
l1.grid(row=0, column=1)

l2 = Label(root, text='Player 2 : O', font="times 15")
l2.grid(row=0, column=3)

# Creating the 9 buttons


b1: Button = Button(root, width=20, height=10, command=lambda: define_sign(1))
b1.grid(row=1, column=1)

b2: Button = Button(root, width=20, height=10, command=lambda: define_sign(2))
b2.grid(row=1, column=2)

b3 = Button(root, width=20, height=10, command=lambda: define_sign(3))
b3.grid(row=1, column=3)

b4: Button = Button(root, width=20, height=10, command=lambda: define_sign(4))
b4.grid(row=4, column=1)

b5: Button = Button(root, width=20, height=10, command=lambda: define_sign(5))
b5.grid(row=4, column=2)

b6 = Button(root, width=20, height=10, command=lambda: define_sign(6))
b6.grid(row=4, column=3)

b7: Button = Button(root, width=20, height=10, command=lambda: define_sign(7))
b7.grid(row=8, column=1)

b8 = Button(root, width=20, height=10, command=lambda: define_sign(8))
b8.grid(row=8, column=2)

b9 = Button(root, width=20, height=10, command=lambda: define_sign(9))
b9.grid(row=8, column=3)

"""
After the end of our buttons, we need to close our mainloop
"""

if __name__ == '__main__':
    root.mainloop()

18. By Amir

Made by Amir. ( Source )

'''object oriented tic-tac-toe'''
class TableBoard():
    table=[' ' for i in range(9) ]
    def __init__(self ):
        pass
    def is_valid(self, move):
        if __class__.table[move]==' ':
            return True
    def is_winner(self):
        b= self.__class__.__base__.table
        mark=self.n
        return (b[0]==b[1]==b[2]==mark) or (b[3]==b[4]==b[5]==mark) or (b[6]==b[7]==b[8]==mark)\
            or (b[0]==b[3]==b[6]==mark) or (b[2]==b[5]==b[8]==mark) or (b[1]==b[4]==b[7]==mark) \
                or (b[0]==b[4]==b[8]==mark) or (b[2]==b[4]==b[6]==mark)
                    
    def __repr__(self):
        b = __class__.table
        output = f'{b[0]}|{b[1]}|{b[2]}\n++++++\n{b[3]}|{b[4]}|{b[5]}\n++++++\n{b[6]}|{b[7]}|{b[8]}\n\n'
        return output

class player_O(TableBoard):
    def __init__(self):
        self.n='O'
    def move(self,number):
        self.__class__.__base__.table[number]='O'

class player_X(TableBoard): 
    def __init__(self):
        self.n='X' 
    def move(self,number):
        self.__class__.__base__.table[number]='X'
board=TableBoard() 
player1=player_X()
player2=player_O()
while True:
    print(board)
    print(f'It is the turn of player {player1.n}.')
    move=int(input('input number cell 1-9\n'))-1
    if board.is_valid(move):
        player1.move(move)
    else:
        print('This cell is full. Choose another cell')
        continue
    fill=[1 for cell in board.table if cell=='X' or cell=='O']
    if len(fill)==9:
        print('The game was tied')
        break
    if player1.is_winner():
        print(f'player {player1.n} is winner')
        print(board)
        break
    player1,player2=player2,player1

19. By abo hussein

Made by abo hussein. ( Source )

from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from random import randint
ActivePlyer=1 # set ActivePlyer 
p1=[] # What player 1 selected
p2=[] # What player 2 selected
style=style()
style.them_use('classic')

root=TK()
root.title("tic tac toy : player 1")
bu1=ttk.button(root,text='')
bu1.grid(row=0,column=0,sticky='snew',ipadx=40,ipady=40)
bu1.config(command=lambda : BuClick(1))


bu2=ttk.button(root,text='')
bu2.grid(row=0,column=1,sticky='snew',ipadx=40,ipady=40)
bu2.config(command=lambda : BuClick(2))


bu3=ttk.button(root,text='')
bu3.grid(row=0,column=2,sticky='snew',ipadx=40,ipady=40)
bu3.config(command=lambda : BuClick(3))



bu4=ttk.button(root,text='')
bu4.grid(row=1,column=0,sticky='snew',ipadx=40,ipady=40)
bu4.config(command=lambda : BuClick(4))

bu5=ttk.button(root,text='')
bu5.grid(row=1,column=1,sticky='snew',ipadx=40,ipady=40)
bu5.config(command=lambda : BuClick(5))

bu6=ttk.button(root,text='')
bu6.grid(row=1,column=2,sticky='snew',ipadx=40,ipady=40)
bu6.config(command=lambda : BuClick(6))


bu7=ttk.button(root,text='')
bu7.grid(row=2,column=0,sticky='snew',ipadx=40,ipady=40)
bu7.config(command=lambda : BuClick(7))



bu8=ttk.button(root,text='')
bu8.grid(row=2,column=1,sticky='snew',ipadx=40,ipady=40)
bu8.config(command=lambda : BuClick(8))


bu9=ttk.button(root,text='')
bu9.grid(row=2,column=2,sticky='snew',ipadx=40,ipady=40)
bu9.config(command=lambda : BuClick(9))


def BuClick(id):
    global ActivePlyer 
    global p1
    global p2
    if(ActivePlyer==1):
        SetLayout(id,'X')
        p1.append(id)
        root.title('tic tak toy : player 2')
        ActivePlyer=2
        print('p1:{}.format(p1)')
        AutoPlay()
    elif(ActivePlyer==2):
        SetLayout(id,'O')
        p2.append(id)
        root.title('tic tak toy : player 1')
        ActivePlyer=1
        print('p2:{}.format(p2)')

        
def SetLayout(id,text):
    if (id==1):
        bu1.config(text=text)
        bu1.state(['disable'])
    elif (id==2):
        bu2.config(text=text)
        bu2.state(['disable'])
    elif (id==3):
        bu3.config(text=text)
        bu3.state(['disable'])
    elif (id==4):
        bu4.config(text=text)
        bu4.state(['disable'])
    elif (id==5):
        bu5.config(text=text)
        bu5.state(['disable'])
    elif (id==6):
        bu6.config(text=text)
        bu6.state(['disable'])
    elif (id==7):
        bu7.config(text=text)
        bu7.state(['disable'])
    elif (id==8):
        bu8.config(text=text)
        bu8.state(['disable'])
    elif (id==9):
        bu9.config(text=text)
        bu9.state(['disable'])
        
        
def CheakWiner():
    Winer=-1
    if ( (1 in p1) and (2 in p1) and (3 in p1)):
        Winer=1 
    if ( (1 in p2) and (2 in p2) and (3 in p2)):
        Winer=2
    if ( (4 in p1) and (5 in p1) and (6 in p1)):
        Winer=1 
    if ( (4 in p2) and (5 in p2) and (6 in p2)):
        Winer=2
    if ( (7 in p1) and (8 in p1) and (9 in p1)):
        Winer=1 
    if ( (7 in p2) and (8 in p2) and (9 in p2)):
        Winer=2
    if ( (1 in p1) and (4 in p1) and (7 in p1)):
        Winer=1 
    if ( (1 in p2) and (4 in p2) and (7 in p2)):
        Winer=2
    if ( (2 in p1) and (5 in p1) and (8 in p1)):
        Winer=1 
    if ( (1 in p2) and (5 in p2) and (8 in p2)):
        Winer=2
    if ( (3 in p1) and (6 in p1) and (9 in p1)):
        Winer=1 
    if ( (3 in p2) and (6 in p2) and (9 in p2)):
        Winer=2
    if Winer==1:
                        messagebox.showinfo(title='cong.',message='player 1 is winer')
    if Winer==2:
            messagebox.showinfo(title='cong.',message='player 2 is winer')
         
def AutoPlay():
    global p1
    global  p2
    EmptyCell=[]
    for cell in range(9):
        if(  not((cell+1 in p1) or(cell+1 in p2))):
            EmptyCell.append(cell+1)
            
RandIndex=randint(0,len(EmptyCell)-1)
BuClic(EmptyCell[RandIndex])      
root.mainloop()

20. By Shubhank Gupta

Made by Shubhank Gupta. ( Source )


# THE BOARD
board = [ '-', '-', '-',
          '-', '-', '-',
          '-', '-', '-',]

# DISPLAYING THE BOAR
game_still_going = True

current_player = 'X'

valid_input = True

def display_board():
    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()
    

# THE GAME AND IT'S FUNCTIONS 

def game():
    
    global game_still_going
    display_board()
    while game_still_going :
        manage_turn()
        flip_player()
        check_if_game_over()
        
    print('The winning player is :' ,winner)
    

# MANAGING THE TURN 
def manage_turn ():
    global valid_input 
    position = int(input('Please enter a number from 1 to 9 : '))- 1
    if board[position] == '-' and 0 <= position <= 8 :
        board[position] = current_player
        display_board()
        valid_input = True
    else :
        valid_input = False
        
# TO CHECK IF THE GAME WILL CONTINUE

def check_if_game_over():
    global game_still_going
    if_win()
                
def if_win():
    global game_still_going
    global winner 
    winner = 'Both played equally good ! FAIR AND SQUARE '
    rows() 
    column()
    diagonal()
    if '-' not in board and game_still_going == True :
        game_still_going = False
        print('Its a draw !')
                
def rows():
    global winner
    global game_still_going
    if board[0] == board[1] == board[2] != '-':
        game_still_going = False
        winner = board[0]
    elif board[3] == board[4] == board[5] != '-':
        game_still_going = False
        winner = board[3]
    elif board[6] == board[7] == board[8] != '-':
        game_still_going = False
        winner = board[6]

def column():
    global winner
    global game_still_going
    if board[0] == board[3] == board[6] != '-':
        game_still_going = False
        winner = board[0]
    elif board[1] == board[4] == board[7] != '-':
        game_still_going = False
        winner = board[3]
    elif board[2] == board[5] == board[8] != '-':
        game_still_going = False
        winner = board[2]

def diagonal():
    global winner
    global game_still_going
    if board[0] == board[4] == board[8] != '-':
        game_still_going = False
        winner = board[0]
    elif board[2] == board[4] == board[6] != '-':
        game_still_going = False
        winner = board[2]
    
def flip_player():
    global valid_input
    global current_player 
    if current_player == 'X' and valid_input == True:
        current_player = 'O'
    elif current_player == 'O' and valid_input == True :
        current_player = 'X'
    else :
        print('\n' , 'Sorry you can\'t enter a field twice' , '\n')
        
game()

21. By Joseph

Made by Joseph. ( Source )

import time
import os
import platform
moves={'A1':' ', 'A2':' ', 'A3':' ', 'B1': ' ', 'B2': ' ', 'B3': ' ', 'C1': ' ', 'C2': ' ', 'C3': ' '}
p1=1
p2=0
print("\n-How to Play: Write (For Example)  A1 X  or  a1 x  to display it on the following board.\n ")
print("      1  2  3\n\n A   {} | {} | {} \n     ---------\n B   {} | {} | {}\n     ---------\n C   {} | {} | {}\n\n".format(moves['A1'],moves['A2'],moves['A3'],moves['B1'],moves['B2'],moves['B3'],moves['C1'],moves['C2'],moves['C3']))
position=0
def whoWon():
    if moves['A1'] == moves['A2'] == moves['A3'] == 'O' or moves['A1'] == moves['A2'] == moves['A3'] == 'X':
        print(moves['A1'] + " Has won!\n\nExiting in 5 seconds...")
        time.sleep(5)
        exit()
    if moves['B1'] == moves['B2'] == moves['B3'] == 'O' or moves['B1'] == moves['B2'] == moves['B3'] == 'X':
        print(moves['B1'] + " Has won!\n\nExiting in 5 seconds...")
        time.sleep(5)
        exit()
    if moves['C1'] == moves['C2'] == moves['C3'] == 'O' or moves['C1'] == moves['C2'] == moves['C3'] == 'X':
        print(moves['C1'] + " Has won!\n\nExiting in 5 seconds...")
        time.sleep(5)
        exit()
    if moves['A1'] == moves['B1'] == moves['C1'] == 'O' or moves['A1'] == moves['B1'] == moves['C1'] == 'X':
        print(moves['A1'] + " Has won!\n\nExiting in 5 seconds...")
        time.sleep(5)
        exit()
    if moves['A2'] == moves['B2'] == moves['C2'] == 'O' or moves['A2'] == moves['B2'] == moves['C2'] == 'X':
        print(moves['A1'] + " Has won!\n\nExiting in 5 seconds...")
        time.sleep(5)
        exit()
    if moves['A3'] == moves['B3'] == moves['C3'] == 'O' or moves['A3'] == moves['B3'] == moves['C3'] == 'X':
        print(moves['A1'] + " Has won!\n\nExiting in 5 seconds...")
        time.sleep(5)
        exit()
    if moves['A1'] == moves['B2'] == moves['C3'] == 'O' or moves['A1'] == moves['B2'] == moves['C3'] == 'X':
        print(moves['A1'] + " Has won!\n\nExiting in 5 seconds...")
        time.sleep(5)
        exit()
    if moves['A3'] == moves['B2'] == moves['C1'] == 'O' or moves['A3'] == moves['B2'] == moves['C1'] == 'X':
        print(moves['A3'] + " Has won!\n\nExiting in 5 seconds...")
        time.sleep(5)
        exit()
def play1():
    position = input("Player 1: ")
    position = position.split()
    if moves[position[0].upper()] != ' ':
        print("Player 1, the box already taken, you blew your chance.")
    else:
        if platform.system() == "Windows":
           os.system('cls')
        else:
            os.system('clear')
        moves[position[0].upper()]=position[1].upper()
        print("\n      1  2  3\n\n A   {}| {} |{} \n    ---------\n B   {}| {} |{}\n    ---------\n C   {}| {} | {}\n\n".format(moves['A1'], moves['A2'], moves['A3'], moves['B1'], moves['B2'], moves['B3'], moves['C1'], moves['C2'],moves['C3']))
def play2():
    position = input("Player 2: ")
    position = position.split()
    if moves[position[0].upper()] != ' ':
        print("Player 2, the box already taken, you blew your chance.")
    else:
        if platform.system() == "Windows":
           os.system('cls')
        else:
            os.system('clear')
        moves[position[0].upper()]=position[1].upper()
        print("\n      1  2  3\n\n A   {}| {} |{} \n    ---------\n B   {}| {} |{}\n    ---------\n C   {}| {} |{}\n\n".format(moves['A1'], moves['A2'], moves['A3'], moves['B1'], moves['B2'], moves['B3'], moves['C1'], moves['C2'],moves['C3']))
for goon in range(9):
    if p1 == 1:
        p1=0
        play1()
    else:
        p1=1
    if p2 == 1:
        p2=0
        play2()
    else:
        p2=1

    whoWon()
print(" Draw\n Exiting in 5 seconds....")
time.sleep(5)