[go: up one dir, main page]

0% found this document useful (0 votes)
18 views2 pages

Self Self Self: Tictactoe - Init

Uploaded by

resume.dbcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views2 pages

Self Self Self: Tictactoe - Init

Uploaded by

resume.dbcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

10/30/23, 9:14 AM Tic Tac Toe with GUI - Jupyter Notebook

In [2]: import tkinter as tk


from tkinter import messagebox

class TicTacToe:
def __init__(self, root):
self.root = root
self.root.title("Tic-Tac-Toe")

# Create buttons for the game board


self.buttons = [[None, None, None] for _ in range(3)]
for i in range(3):
for j in range(3):
self.buttons[i][j] = tk.Button(root, text='', font=('normal', 20), width=5, height=2,
command=lambda row=i, col=j: self.make_move(row, col))
self.buttons[i][j].grid(row=i, column=j)

self.current_player = 'X'
self.moves = 0

def make_move(self, row, col):
if self.buttons[row][col]['text'] == '' and not self.check_winner():
self.buttons[row][col]['text'] = self.current_player
self.moves += 1

if self.check_winner():
messagebox.showinfo("Tic-Tac-Toe", f"Player {self.current_player} wins!")
self.reset_board()
elif self.moves == 9:
messagebox.showinfo("Tic-Tac-Toe", "It's a tie!")
self.reset_board()
else:
self.current_player = 'O' if self.current_player == 'X' else 'X'

def check_winner(self):
for i in range(3):
if self.buttons[i][0]['text'] == self.buttons[i][1]['text'] == self.buttons[i][2]['text'] != '':
return True
if self.buttons[0][i]['text'] == self.buttons[1][i]['text'] == self.buttons[2][i]['text'] != '':
return True
if self.buttons[0][0]['text'] == self.buttons[1][1]['text'] == self.buttons[2][2]['text'] != '':
return True

localhost:8888/notebooks/00 Practice UB/Tic Tac Toe with GUI.ipynb 3/4


10/30/23, 9:14 AM Tic Tac Toe with GUI - Jupyter Notebook
if self.buttons[0][2]['text'] == self.buttons[1][1]['text'] == self.buttons[2][0]['text'] != '':
return True
return False

def reset_board(self):
for i in range(3):
for j in range(3):
self.buttons[i][j]['text'] = ''
self.current_player = 'X'
self.moves = 0

if __name__ == '__main__':
root = tk.Tk()
game = TicTacToe(root)

root.mainloop()

In [ ]: ​

localhost:8888/notebooks/00 Practice UB/Tic Tac Toe with GUI.ipynb 4/4

You might also like