2

Tic Tac Toe GUI based game in python Tkinter

tic tac toe using python tkinter module gui based

topic – tic toe game in python tkinter

Learning Outcomes

  • Implement Tkinter GUI Python Application
  • Implement and utilize widgets
  • Develop logic

Program Overview – tic toe game in python tkinter

Your task is to build the game Tic Tac Toe in a GUI application. The form consists of 9 buttons that each player takes turns clicking trying to mark 3 in a row. Player 1 goes first and will mark a button with an X. Next Player 2 takes a turn marking a button with an O. The winner is the first to get 3 marks in a row, column, or diagonal. If all 9 buttons are marked and no winner, declare a message which is a tie. After a game (win or tie), reset the board and start over with player 1’s turn.

It is recommended to use functions to keep your code to a minimum.

tic tac toe python code for beginners continue…

Functionality Requirements

Your game should:

  1. Create a GUI that has 9 buttons. Consider ways to store the buttons in a way that allow you to access them and modify the buttonObject.config(text=’X or O’) field to Mark the button for player 1 or 2. If you were to store all button in a structure that has an index of some kind you could easily determine which button is being clicked. You’ll need some way to know the button that was clicked was the upper left which is index 0 (this is an example).
  2. Create a function to link the click event for all buttons. This event handler must be invoked when any of the 9 buttons are clicked and I suggest using a lambda to allow you the ability to pass data to indicate which button was pressed similar to how you did the calculator. Follow the provided psuedo-code to complete the code. Declare variables for the needed information. The process of the game is players alternate turns clicking a button (player 1 goes first and marks X while player 2 marks O). Each button click is the exact same logic which follows:
    • Determine which player is taking a turn (clicking the button)
      • If player 1, change the button text to X and state to DISABLED
      • If player 2, change the button text to O and state to DISABLED
    • Change Players alternating players each turn
    • Keep a count of the number of turns taken place because only 9 turns are possible at which point you have a cats game or tie.
  3. Create a function check_for_winner. Complete the following:
    • Create a decision to check for all possible winning combinations.
    • Things to consider to perform this operation:
      • Which player are we checking won?
      • Which buttons has this player selected? You could check all buttons for their mark (X or O), or maybe you stored this players marks in a data structure saving a number to specify the button location.
      • Know the winning combinations. Example I could create a number system for the game board like below:
        • 012
        • 345
        • 678
        • So combos are: 012, 036, 048, etc.

Now, does the player your checking have any of these combos, but if you find 1 the game is over.

Note: After each user moves, the program needs to check if the user has won or not. There are 8 ways a user can win. He or she can complete any one of the 3 rows, or the 3 columns, or the 2 diagonals. If the game has been won, as determined by this method, clear_board() and reset the game data to the beginning.

CODE – tic toe game in python tkinter:

import tkinter as tk


player1Color = "tomato"
player2Color = "sea green"
textColorPlayer1 = "sea green"
textColorPlayer2 = "tomato"
labelColor = "orange"
labelTextColor = "blue"
btnResetColor = "black"
btnResetTextColor = "grey"


'''This function will be called when user
click on RESET button
This function will clear all the text on
button and set color to default
outer loop is for rows and while inner loop
is for columns it will reset all 9 buttons'''
def reset():
for i in range(3):
for j in range(3):
board[i][j].configure(text='',
bg="SystemButtonFace")


'''This function will be called when ever user
played any move,it will check if any of
condition is fullfilled or not
if condition is fullfilled then return 1
if still no one has won it will return
0 and if the games draw it will return -1'''
def isWin():
for i in range(3):
if board[i][0]['text'] == board[i][1]['text'] \
== board[i][2]['text'] != '':
return 1
for j in range(3):
if board[0][j]['text'] == board[1][j]['text'] \
== board[2][j]['text'] != '':
return 1
if board[0][0]['text'] == board[1][1]['text'] \
== board[2][2]['text'] != '':
return 1
elif board[0][2]['text'] == board[1][1]['text'] \
== board[2][0]['text'] != '':
return 1
elif EmptyCells() == []:
return 0
else:
return -1


#this function will return empty list of all
# the buttons which are stilled on used by player
def EmptyCells():
h=[]
for i in range(3):
for j in range(3):
#it will check if button has not any text on it
if board[i][j]['text'] == '':
h.append((i,j))
return h

#for first run first player will be given
# character 'O'
player = 'O'

#here's the main flow of game
def main_gameflow(r,c):
#global variable player to
# store currentplayer
#it is global because global
# variable can be access from any where in program
global player
#if current button on board is empty the
# it will add respected text on button i.e: O or X and after move checks if anyone wins

if board[r][c]['text'] == '' and isWin() == -1:
if player == 'O':
board[r][c].configure(text='O',bg = player1Color, fg= textColorPlayer1)
if isWin() == -1:
player = 'X'
winAndTurnLabel.configure(text=("It's X's turn"))
elif isWin() == 1:
winAndTurnLabel.configure(text=("O win"))
elif isWin() == 0:
winAndTurnLabel.configure(text="Draw!")
elif player == 'X':
board[r][c].configure(text='X',bg = player2Color, fg= textColorPlayer2)
if isWin() == -1:
player = 'O'
winAndTurnLabel.configure(text=("It's O's turn"))
elif isWin() == 1:
winAndTurnLabel.configure(text=("X win"))
elif isWin() == 0:
winAndTurnLabel.configure(text="Draw!")

#making Tkinter object
screen=tk.Tk()
#setting screen title
screen.title('Tic Tac Toe')
#creating 3 * 3 matrix
board=[[0,0,0],[0,0,0],[0,0,0]]
#generating buttons with 3 rows and 3 columns and
#each row and columns will contain 3 buttons
for i in range(3):
for j in range(3):
#creating button where command takes an lambda funtion
#means lambda is any funtion which will be exexuted whenever any button is clicked
board[i][j]=tk.Button(text='',font=('normal',60,'normal'),width=4,height=1,command=lambda row = i,col = j: main_gameflow(row,col))
#placing button in grid so their will be no space between buttons
board[i][j].grid(row=i,column=j)

#generating label to tell which player turn and who wins / Draw
winAndTurnLabel=tk.Label(text="It's O's turn",font=('normal',22,'bold')
,bg = labelColor,fg = labelTextColor)
winAndTurnLabel.grid(row=3,column=1)
#Generating Reset button to reset game / board
ResetButton=tk.Button(text='RESET',font=('Courier',18,'bold')
,fg=btnResetTextColor,bg = btnResetColor,command=reset)
ResetButton.grid(row=4,column=1)
screen.mainloop()

DEMO

Tags :

tic toe game in python Tkinter
tic tac toe python tkinter
2 player tic tac toe python beginner

keep visiting : shaadcoding

shaad

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *