forked from ronitraj74/python-Learning-code
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPROJECT_3_Game_of_Tic-Tac-Toe.PY
More file actions
56 lines (43 loc) · 1.57 KB
/
PROJECT_3_Game_of_Tic-Tac-Toe.PY
File metadata and controls
56 lines (43 loc) · 1.57 KB
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
56
import tkinter as tk
from tkinter import messagebox
def check_winner():
global winner
for combo in [[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]]:
if buttons[combo[0]]["text"] == buttons[combo[1]]["text"] == buttons[combo[2]]["text"] != "":
# highlight winner
for i in combo:
buttons[i].config(bg="green")
messagebox.showinfo("Tic-Tac-Toe", f"Player {buttons[combo[0]]['text']} wins!")
winner = True
# disable all buttons
for b in buttons:
b.config(state="disabled")
def button_click(index):
if buttons[index]["text"] == "" and not winner:
buttons[index]["text"] = current_player
check_winner()
if not winner:
toggle_player()
def toggle_player():
global current_player
current_player = "X" if current_player == "O" else "O"
label.config(text=f"Player {current_player}'s turn")
# main window
root = tk.Tk()
root.title("Tic-Tac-Toe")
buttons = [
tk.Button(root, text="", font=("normal",25),
width=6, height=2,
command=lambda i=i: button_click(i))
for i in range(9)
]
# grid layout
for i, button in enumerate(buttons):
button.grid(row=i // 3, column=i % 3)
current_player = "X"
winner = False
label = tk.Label(root, text=f"Player {current_player}'s turn", font=("normal",16))
label.grid(row=3, column=0, columnspan=3)
root.mainloop()