-
Notifications
You must be signed in to change notification settings - Fork 78
/
tic_tac_toe.py
55 lines (48 loc) · 1.94 KB
/
tic_tac_toe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import tkinter as tk
from tkinter import messagebox
class TicTacToe:
def __init__(self):
self.current_player = "X"
self.board = [["" for _ in range(3)] for _ in range(3)]
self.window = tk.Tk()
self.window.title("Tic Tac Toe")
self.buttons = []
for i in range(3):
row = []
for j in range(3):
button = tk.Button(self.window, text="", width=20, height=10, command=lambda i=i, j=j: self.make_move(i, j))
button.grid(row=i, column=j)
row.append(button)
self.buttons.append(row)
def make_move(self, row, col):
if self.board[row][col] == "":
self.board[row][col] = self.current_player
self.buttons[row][col].config(text=self.current_player)
if self.check_winner(self.current_player):
messagebox.showinfo("Game Over", f"Player {self.current_player} wins!")
self.window.quit()
elif self.is_board_full():
messagebox.showinfo("Game Over", "It's a draw!")
self.window.quit()
else:
self.current_player = "O" if self.current_player == "X" else "X"
def check_winner(self, player):
for i in range(3):
if self.board[i][0] == self.board[i][1] == self.board[i][2] == player:
return True
if self.board[0][i] == self.board[1][i] == self.board[2][i] == player:
return True
if self.board[0][0] == self.board[1][1] == self.board[2][2] == player:
return True
if self.board[0][2] == self.board[1][1] == self.board[2][0] == player:
return True
return False
def is_board_full(self):
for row in self.board:
if "" in row:
return False
return True
def run(self):
self.window.mainloop()
game = TicTacToe()
game.run()