Showing posts with label tic tac toe python. Show all posts
Showing posts with label tic tac toe python. Show all posts

Python Tic Tac Toe Game with Source Code

Develop Classic Tic Tac Toe Game in Python 

The shortest competitive mind game ever made is the Tic-Tac-Toe. Make a 3x3 grid and play your game anywhere, anytime. Well, now it's possible to develop this game through python. Let’s find out!



About Tic Tac Toe Project:

The objective of this project is to build the Tic Tac Toe game through python programming. Python has some very cool graphic libraries and APIs like Tkinter for a better user-friendly interface of our game. Defining some conditions based on the rules of the game are enough to develop this game in this project.

 

Project Prerequisites:

The tic tac toe project will be needing a good knowledge of Python and GUI (Graphic User Interface). GUI is a powerful tool in Python for rendering graphics with the help of Tkinter. Also, defining functions and using them in outer scopes and GUI forms a chain to implement the game. We need to install the Tkinter library beforehand to implement it in our project. To install these libraries on PyCharm: 
[ File> Settings> Project> Project Interpreter> + > install the libraries].

Download Tic Tac Toe Python Source Code

Before proceeding ahead, please download the tic-tac-toe project code: Tic Tac Toe Project

Tic Tac Toe Game in Python

Let’s start the development

1. Initializing Game Components:

Code:
from tkinter import *
import tkinter.messagebox
tk = Tk()
tk.title("Tic Tac Toe")

Explanation:
 

a. The message box acts as a notification dialog box, which we will use to notify user 
b. To initialize tkinter, we use Tk() for its usage in the further project.

2. Initializing variables:

Code:
#The variables we require to mention the players:
userA = StringVar()
userB = StringVar()
play1 = StringVar()
play2= StringVar()

#Information of Names to get from the user:
player1_name = Entry(tk, textvariable=play1, bd=7)
player1_name.grid(row=1, column=1, columnspan=9)
player2_name = Entry(tk, textvariable=play2, bd=7)
player2_name.grid(row=2, column=1, columnspan=9)

#Initializing some conditions:
click = True
initial = 0
Explanation: 

a. The user input required to get the names of the players for the game is in StringVar(). 
b. We add the user input spaces in our dialog box for the player names using the above values.
  

3. Defining Functions

Code:
#Initial state of the buttons before clicking:
def disabled():
  gameBtn1.configure(state=DISABLED)
  gameBtn2.configure(state=DISABLED)
  gameBtn3.configure(state=DISABLED)
  gameBtn4.configure(state=DISABLED)
  gameBtn5.configure(state=DISABLED)
  gameBtn6.configure(state=DISABLED)
  gameBtn7.configure(state=DISABLED)
  gameBtn8.configure(state=DISABLED)
  gameBtn9.configure(state=DISABLED)

Explanation:
 

configure() provides an attribute or a state to the designed button. Here, the state is disabled which means the grid buttons would not be responsive. 

Code:
#Defining message box for a particular input:
def btnClick(buttons):
  global click, initial, player2_name, player1_name, userA,userB
  if buttons["text"] == " " and click == True:
    	buttons["text"] = "X"
    	click = False
    	userB = play2.get() + " Wins!"
    	userA = play1.get() + " Wins!"
    	winCondition()
    	initial += 1


  elif buttons["text"] == " " and click == False:
    	buttons["text"] = "O"
    	click = True
    	winCondition()
    	initial += 1
  else:
    	tkinter.messagebox.showinfo("Tic-Tac-Toe", "Button already Pressed!")
Explanation: 

a. We declare some global variables, click, initial, player2_name, player1_name, userA and userB. Global variables can also be used outside the scope. 
b. We have initialized click outside this function to be TRUE, it would print the empty string text to be "X". The next stage it changes to is false for the next user input. 
c. Similarly, if the click is FALSE, it would print the empty string to be “O”. The next stage it changes into is true for the next user input. 
d. Initial increments with the given input of “X” and “O”. 
e. By these button clicks, we check for the winning player by another defined function winCondition() and display the message on the screen. 

Code:
#Defining conditions for winning the game:
def winCondition():
  if (gameBtn1['text'] == 'X' and gameBtn2['text'] == 'X' and gameBtn3['text'] == 'X' or
    	gameBtn4['text'] == 'X' and gameBtn5['text'] == 'X' and gameBtn6['text'] == 'X' or
    	gameBtn7['text'] =='X' and gameBtn8['text'] == 'X' and gameBtn9['text'] == 'X' or
    	gameBtn1['text'] == 'X' and gameBtn5['text'] == 'X' and gameBtn9['text'] == 'X' or
    	gameBtn3['text'] == 'X' and gameBtn5['text'] == 'X' and gameBtn7['text'] == 'X' or
    	gameBtn1['text'] == 'X' and gameBtn2['text'] == 'X' and gameBtn3['text'] == 'X' or
    	gameBtn1['text'] == 'X' and gameBtn4['text'] == 'X' and gameBtn7['text'] == 'X' or
    	gameBtn2['text'] == 'X' and gameBtn5['text'] == 'X' and gameBtn8['text'] == 'X' or
    	gameBtn7['text'] == 'X' and gameBtn6['text'] == 'X' and gameBtn9['text'] == 'X'):
    	disabled()
    	tkinter.messagebox.showinfo("Tic-Tac-Toe", userA)

  elif initial == 8:
    	tkinter.messagebox.showinfo("Tic-Tac-Toe", "It's a Tie")

  elif (gameBtn1['text'] == 'O' and gameBtn2['text'] == 'O' and gameBtn3['text'] == 'O' or
      	gameBtn4['text'] == 'O' and gameBtn5['text'] == 'O' and gameBtn6['text'] == 'O' or
      	gameBtn7['text'] == 'O' and gameBtn8['text'] == 'O' and gameBtn9['text'] == 'O' or
      	gameBtn1['text'] == 'O' and gameBtn5['text'] == 'O' and gameBtn9['text'] == 'O' or
      	gameBtn3['text'] == 'O' and gameBtn5['text'] == 'O' and gameBtn7['text'] == 'O' or
      	gameBtn1['text'] == 'O' and gameBtn2['text'] == 'O' and gameBtn3['text'] == 'O' or
      	gameBtn1['text'] == 'O' and gameBtn4['text'] == 'O' and gameBtn7['text'] == 'O' or
      	gameBtn2['text'] == 'O' and gameBtn5['text'] == 'O' and gameBtn8['text'] == 'O' or
      	gameBtn7['text'] == 'O' and gameBtn6['text'] == 'O' and gameBtn9['text'] == 'O'):
    	disabled()
    	tkinter.messagebox.showinfo("Tic-Tac-Toe", userB)
 
buttons = StringVar()

Explanation: 
The winning conditions are set according to the rules of Tic Tac Toe ie lines matching diagonally or straight 

Code:
#Name of the players:

label = Label( tk, text="Player 1:", font='Arial', bg='white', fg='black', height=1, width=8)
label.grid(row=1, column=0)

label = Label( tk, text="Player 2:", font='Arial', bg='white', fg='black', height=1, width=8)
label.grid(row=2, column=0)

# Styling the Game Buttons:

gameBtn1 = Button(tk, text=" ", font='Arial', bg='black', fg='white', height=5, width=10, command=lambda: btnClick(gameBtn1))
gameBtn1.grid(row=3, column=0)

gameBtn2 = Button(tk, text=' ', font='Arial', bg='black', fg='white', height=5, width=10, command=lambda: btnClick(gameBtn2))
gameBtn2.grid(row=3, column=1)

gameBtn3 = Button(tk, text=' ',font='Arial', bg='black', fg='white', height=5, width=10, command=lambda: btnClick(gameBtn3))
gameBtn3.grid(row=3, column=2)

gameBtn4 = Button(tk, text=' ', font='Arial', bg='black', fg='white', height=5, width=10, command=lambda: btnClick(gameBtn4))
gameBtn4.grid(row=4, column=0)

gameBtn5 = Button(tk, text=' ', font='Arial', bg='black', fg='white', height=5, width=10, command=lambda: btnClick(gameBtn5))
gameBtn5.grid(row=4, column=1)

gameBtn6 = Button(tk, text=' ', font='Arial', bg='black', fg='white', height=5, width=10,command=lambda: btnClick(gameBtn6))
gameBtn6.grid(row=4, column=2)

gameBtn7 = Button(tk, text=' ', font='Arial', bg='black', fg='white', height=5, width=10, command=lambda: btnClick(gameBtn7))
gameBtn7.grid(row=5, column=0)

gameBtn8 = Button(tk, text=' ', font='Arial', bg='black', fg='white', height=5, width=10, command=lambda: btnClick(gameBtn8))
gameBtn8.grid(row=5, column=1)

gameBtn9 = Button(tk, text=' ', font='Arial', bg='black', fg='white', height=5, width=10, command=lambda: btnClick(gameBtn9))
gameBtn9.grid(row=5, column=2)

#To display the created graphic window:

tk.mainloop()

Explanation:
 

We require a grid of 9 buttons to form the game structure for tic tac toe. To operate these buttons, provide them a condition to become active with btnClick().
  

Conclusion

In this article, we have implemented the Tic Tac Toe Game in Python. Tkinter GUI helped in providing a quick and friendly way to make use of the game features.