Showing posts with label python. Show all posts
Showing posts with label 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.

Python Project - Text Editor with python and Tkinter

Python text editor is a standalone deployable application that is used as an alternative to Notepad. It uses python and the Tkinter python GUI library to provide one with the basic tools and functions needed to keep a record.


python project text editor


Setting up the necessary dependencies

Text editor or notepad works on python 3 and thus it requires python 3 installed. For installing python 3, visit official python website and download the latest stable release and proceed further.

Once python 3 is installed and the path is set up in the environment variables, we can verify the installation by running python -V in the command line. Successful installing would show a version number while unsuccessful installation will trigger an error.

Before getting started it is important to note that the python version running is 3.x. and not python2. The project is built on python3 and hence the code won’t work with the python2.

The next library required for Python Text editor project to work is the Tkinter library. To install Tkinter, open up the command line and type the following command:

pip install tk

Start the development of text editor project in Python


Download Python Text Editor Source Code


Before proceeding ahead, please download the source code of Python Text Editor Project: Text Editor Project in Python

1. Import dependencies

from tkinter import *
import tkinter.scrolledtext as ScrolledText
import tkinter.filedialog as FileDialog
import tkinter.messagebox as MessageBox
import tkinter.simpledialog as SimpleDialog
import os
from tkinter import font

2. Set up working window

#Creating base for the main working window
base = Tk(className = ' TechnologyMania Text Editor')
textArea = ScrolledText.ScrolledText(base, width = 160, height = 50)

3. Code for menu bar

#Creating cascade menu and menu options
menu = Menu(base)
base.config(menu = menu)

fileMenu = Menu(menu)
menu.add_cascade(label = "File", menu = fileMenu)
fileMenu.add_command(label = 'New', command = newFile)
fileMenu.add_command(label = 'Open', command = openFile)
fileMenu.add_command(label = 'Save', command = saveFile)
fileMenu.add_separator()
fileMenu.add_command(label = "Exit", command = exiteditor)

editmenu = Menu(menu)
menu.add_cascade(label = 'Edit', menu = editmenu)
editmenu.add_command(label = 'Change Font', command = changeFont)

textArea.pack()

#Making the window remain open
base.mainloop()

4. New file option

#New File Function
def newFile():

    #if content present
    if len(textArea.get('1.0' , END)) > 0:
        if MessageBox.askyesno("Save?" , "Do you wish to save the file"):
            saveFile()
            textArea.delete('1.0', END)
            base.title("TechnologyMania Text Editor")

        else:
            textArea.delete('1.0', END)
            base.title("TechnologyMania Text Editor")

5. Open file option

#Open File Function
def openFile():

    file = FileDialog.askopenfile(parent = base, title = 'Select a file', filetype = (("Text file" , "*.txt"),("All files" , "*.*")))

    base.title(os.path.basename(file.name) + "  - TechnologyMania Text Editor")

    if file != None:
        contents = file.read()
        textArea.delete('1.0', END)
        textArea.insert('1.0', contents)
        file.close()

6. Save file option

#Save File Function
def saveFile():

    file = FileDialog.asksaveasfile(mode = 'w', defaultextension = ".txt", filetype = (("Text file" , "*.txt"),("All files" , "*.*")))

    if file != None:
        data = textArea.get('1.0' , END)
        file.write(data)
        base.title(os.path.basename(file.name) + "  - TechnologyMania Text Editor")
        file.close()

7. Exit Option

#Exit function        
def exiteditor():

    if len(textArea.get('1.0' , END+'-1c')) > 0:
        
        if MessageBox.askyesno("Save?" , "Do you wish to save the file before closing"):
            saveFile()
            base.destroy()

        else:
            base.destroy()
    
    else:

        if MessageBox.askyesno("Quit", "Are you sure you want to quit ?"):
            base.destroy()

8. Change Font Option

def changeFont():

    #creating new window
    fontbase = Tk(className = 'Choose your Font')
    fontbase.minsize(height = 600, width = 600)

    #defining font selection dropdown and label
    font_label = Label(fontbase, text = "Choose Font", font = ("Helvetica", 14))
    font_options = list(font.families())
    font_options.sort()
    font_variable = StringVar(fontbase)
    font_variable.set(font_options[0])
    font_menu = OptionMenu(fontbase, font_variable, *font_options)
    font_menu.pack()
    font_menu.place(x = 50, y = 100)
    font_label.place(x = 35, y = 70)

    #defining style selection dropdown and label
    style_label = Label(fontbase, text = "Choose Style", font = ("Helvetica", 14))
    style_options = ['Normal', 'Bold', "Italic" , "Bold and Italic"]
    style_variable = StringVar(fontbase)
    style_variable.set(style_options[0])
    style_menu = OptionMenu(fontbase, style_variable, *style_options)
    style_menu.pack()
    style_menu.place(x = 250 , y = 100)
    style_label.place(x = 230, y = 70)

    #defining size selection dropdown and label
    size_label = Label(fontbase, text = "Choose Size", font = ("Helvetica", 14))
    size_options = ['6','8','10','12','14','16','20','24','30','32','36','40','46','52','60','72','80']
    size_variable = StringVar(fontbase)
    size_variable.set('10')
    size_menu = OptionMenu(fontbase, size_variable, *size_options)
    size_menu.pack()
    size_menu.place(x = 450, y = 100)
    size_label.place(x = 425, y = 70)

    #confirm funtion
    def confirm():
        f_C = font_variable.get()
        s_C = style_variable.get()
        si_C = int(size_variable.get())

        if(s_C == 'Bold'):
            textArea.configure(font=("f_C", si_C, "bold"))

        if(s_C == 'Normal'):
            textArea.configure(font=("f_C", si_C, "normal"))

        if(s_C == 'Italic'):
            textArea.configure(font=("f_C", si_C, "italic"))

        if(s_C == "Bold and Italic"):
            textArea.configure(font=("f_C", si_C, 'bold', "italic"))

        fontbase.destroy()

    #cancel function
    def cancel():
        fontbase.destroy()

    #creating and placing the buttons    
    confirm_btn = Button(fontbase, text = "Confirm", command = confirm)
    cancel_btn = Button(fontbase, text = "Cancel", command = cancel)    

    confirm_btn.place(x = 400, y = 530)
    cancel_btn.place(x = 500, y = 530)
    
    fontbase.mainloop()

Summary

In this python project, we created a text editor or notepad with Tkinter. This is a good python project for beginners to brush up python skills.

If you like this project, please rate Technology Mania on Facebook