forked from mosh-hamedani/python-projects-for-beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtic_tac_toe.py
More file actions
98 lines (69 loc) · 1.8 KB
/
tic_tac_toe.py
File metadata and controls
98 lines (69 loc) · 1.8 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
from termcolor import colored
X = 'X'
O = 'O'
board = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
def cell(mark):
color = 'red' if mark == X else 'green'
return colored(mark, color)
def print_board(board):
line = '---+---+---'
print(line)
for row in board:
print(f' {cell(row[0])} | {cell(row[1])} | {cell(row[2])}')
print(line)
def check_winner(board):
# Check rows
for row in board: # [' ', ' ', ' ']
if row[0] == row[1] == row[2] != ' ':
return True
# Check columns
for column in range(3):
if board[0][column] == board[1][column] == board[2][column] != ' ':
return True
# Check diagonals
if board[0][0] == board[1][1] == board[2][2] != ' ' or \
board[0][2] == board[1][1] == board[2][0] != ' ':
return True
return False
def is_full(board):
for row in board:
if ' ' in row:
return False
return True
def get_position(prompt):
while True:
try:
position = int(input(prompt))
if position < 0 or position > 2:
raise ValueError
return position
except ValueError:
print('Invalid input!')
def get_move(current_player):
print(f"Player {current_player}'s turn")
while True:
row = get_position('Enter row (0-2): ')
column = get_position('Enter column (0-2): ')
if board[row][column] == ' ':
board[row][column] = current_player
break
print('This spot is already taken')
def main():
print_board(board)
current_player = X
while True:
get_move(current_player)
print_board(board)
if check_winner(board):
print(f'Player {current_player} wins!')
break
if is_full(board):
print(f'Board is full')
break
current_player = O if current_player == X else X
if __name__ == '__main__':
main()