#!/usr/bin/env pythyon3
from tkinter import *
from tkinter import messagebox
import random as r

# Button function: function to define a button
def button(frame):
    b=Button(frame,padx=1,bg="indianred4",activebackground="tomato3",
    width=3,text="  ",font=('arial',60,'bold'), relief="sunken",bd=10)
    return b

# Change function: change operand for next player (X or O)
def change_a():
    global a
    for i in ['O','X']:
        if not (i==a):
            a=i
            break

# Reset function: reset game (reset buttons to normal & clear text)
def reset():
    global a
    for i in range(3):
        for j in range(3):
            b[i][j]["text"]="  "
            b[i][j]["state"]=NORMAL

# Check function: checks for Victory or Draw
def check():
    for i in range(3):
        # left/right/up/down
        if(b[i][0]["text"]==b[i][1]["text"]==b[i][2]["text"]==a or
        b[0][i]["text"]==b[1][i]["text"]==b[2][i]["text"]==\
        b[2][i]["text"]==a):
            messagebox.showinfo("Congrats!!","'"+a+"' has won")
            reset()
    # diagnols
    if(b[0][0]["text"]==b[1][1]["text"]==b[2][2]["text"]==a or
    b[0][2]["text"]==b[1][1]["text"]==b[2][0]["text"]==a):
        messagebox.showinfo("Congrats!!","'"+a+"' has won")
        reset()
    elif(b[0][0]["state"]==b[0][1]["state"]==b[0][2]["state"]==\
    b[1][0]["state"]==b[1][1]["state"]==b[1][2]["state"]==\
    b[2][0]["state"]==b[2][1]["state"]==b[2][2]["state"]==DISABLED):
        messagebox.showinfo("Tied!!","The match ended in a draw")
        reset()

# Click function: handle clicks on board
def click(row,col):
    b[row][col].config(text=a,state=DISABLED,disabledforeground=color[a])
    check()
    change_a()
    label.config(text=a+"'s Chance")
##############   Main Program  ##########################################
root=Tk()  #Window defined
root.title("Tic-Tac-Toe")  # Title given
a=r.choice(['O','X'])  # 2 operators (operands) defined
color={'O':"deep sky blue",'X':"lawn green"}
b=[[],[],[]]
for i in range(3):
    for j in range(3):
        b[i].append(button(root))
        b[i][j].config(command= lambda row=i,col=j:click(row,col))
        b[i][j].grid(row=i,column=j)
label=Label(text=a+"'s Chance",font=('arial',20,'bold'),bg="rosy brown")
label.grid(row=3,column=0,columnspan=3,sticky="nsew")
root.mainloop()