forked from ayan59dutta/Miscellaneous-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonCode_TicTacToe.py
More file actions
52 lines (47 loc) · 1.41 KB
/
PythonCode_TicTacToe.py
File metadata and controls
52 lines (47 loc) · 1.41 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
def tic_tac_toe():
board = [None] + list(range(1, 10))
WIN_COMBINATIONS = [
(1, 2, 3),
(4, 5, 6),
(7, 8, 9),
(1, 4, 7),
(2, 5, 8),
(3, 6, 9),
(1, 5, 9),
(3, 5, 7),
]
def draw():
print(board[1], board[2], board[3])
print(board[4], board[5], board[6])
print(board[7], board[8], board[9])
print()
def choose_number():
while True:
try:
a = int(input())
if a in board:
return a
else:
print("\nInvalid move. Try again")
except ValueError:
print("\nThat's not a number. Try again")
def is_game_over():
for a, b, c in WIN_COMBINATIONS:
if board[a] == board[b] == board[c]:
print("Player {0} wins!\n".format(board[a]))
print("Congratulations!\n")
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
return True
for player in 'XO' * 9:
draw()
if is_game_over():
break
print("Player {0} pick your move".format(player))
board[choose_number()] = player
print()
while True:
tic_tac_toe()
if input("Play again (y/n)\n") != "y":
break