-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathtictactoe.py
More file actions
100 lines (88 loc) · 3.14 KB
/
tictactoe.py
File metadata and controls
100 lines (88 loc) · 3.14 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
board = [[' ' for _ in range(3)] for _ in range(3)]
def checkwinner(a):
if (board[0][0] == a and board[1][0] == a and board[2][0] == a or
board[0][1] == a and board[1][1] == a and board[2][1] == a or
board[0][2] == a and board[1][2] == a and board[2][2] == a):
return 1
elif (board[0][0] == a and board[0][1] == a and board[0][2] == a or
board[1][0] == a and board[1][1] == a and board[1][2] == a or
board[2][0] == a and board[2][1] == a and board[2][2] == a):
return 1
elif (board[0][0] == a and board[1][1] == a and board[2][2] == a or
board[0][2] == a and board[1][1] == a and board[2][0] == a):
return 1
else:
return 0
def fill():
for i in range(3):
for j in range(3):
board[i][j] = ' '
def play(box, a):
row = (box - 1) // 3
col = (box - 1) % 3
if board[row][col] != ' ':
return 1
else:
board[row][col] = a
return 0
def display():
print(f"\n {board[0][0]} | {board[0][1]} | {board[0][2]} ")
print("---|---|---")
print(f" {board[1][0]} | {board[1][1]} | {board[1][2]} ")
print("---|---|---")
print(f" {board[2][0]} | {board[2][1]} | {board[2][2]} ")
print("\nWelcome to Tic Tac Toe\n")
print(" 1 | 2 | 3 ")
print("---|---|---")
print(" 4 | 5 | 6 ")
print("---|---|---")
print(" 7 | 8 | 9 ")
while True:
fill()
instruction = input("\n\n1. Press Enter to start a new game.\n2. Press E to exit.\n-->")
if instruction == "":
count = 0
result = 0
while not result and count < 9:
if count % 2 == 0:
cell = int(input("\n\nEnter the number to mark (O): "))
if 1 <= cell <= 9:
if play(cell, 'O'):
print("\nBlock already filled")
continue
else:
play(cell, 'O')
display()
count += 1
if checkwinner('O'):
print("\n\nCongratulations O won!!!\n")
result = 1
else:
continue
else:
print("\nInvalid Input")
continue
else:
cell = int(input("\n\nEnter the number to mark (X): "))
if 1 <= cell <= 9:
if play(cell, 'X'):
print("\nBlock already filled")
continue
else:
play(cell, 'X')
display()
count += 1
if checkwinner('X'):
print("\n\nCongratulations X won!!!\n")
result = 1
else:
continue
else:
print("\nInvalid Input")
continue
if not result and count == 9:
print("\n\nIt is a DRAW!!")
elif instruction.lower() == 'e':
print("\nThanks for Playing!")
print("------------------------------")
break