-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTikTacToe.py
More file actions
80 lines (69 loc) · 2.18 KB
/
TikTacToe.py
File metadata and controls
80 lines (69 loc) · 2.18 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
board = [['', '', ''],['', '', ''],['', '', '']]
def print_board(board):
print(*board[0], sep=" | ")
print("---------")
print(*board[1], sep=" | ")
print("---------")
print(*board[2], sep=" | ")
def get_markers():
marker1 = input("Player 1 choice(X or O): ").upper()
marker2 = ""
if marker1 == "X":
marker2 = 'O'
return ['X', 'O']
elif marker1 == 'O':
marker2 = 'X'
return ['O', 'X']
else:
print("Invalid Input")
return get_markers()
def get_coordinates():
x,y = list(map(int, input("Enter the coordinates: ").split()))
if x in [0,1,2] and y in [0,1,2]:
return [x,y]
else:
print("Invalid Input")
return get_coordinates()
def check_for_win(board):
for row in board:
if row[0] == row[1] and row[1] == row[2] and row[1] != "":
return True
for i in range(len(board)):
if board[0][i] == board[1][i] and board[1][i] == board[2][i] and board[2][i] != "":
return True
if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[2][2] != "":
return True
if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[2][0] != "":
return True
return False
def update_board(board, chance, marker, x,y):
if chance == True:
board[x][y] = marker
if check_for_win(board):
print("Player 1 wins")
return "game over"
return False
else:
board[x][y] = marker
if check_for_win(board):
print("Player 2 wins")
return "game over"
return True
def play_game():
player1 = 0
player2 = 0
m1, m2 = get_markers()
print(f"player 1: {m1}, player 2: {m2}")
chance = True
while True:
print_board(board)
x, y = get_coordinates()
if chance:
chance = update_board(board, chance, m1, x,y)
if chance == "game over":
break
else:
chance = update_board(board, chance, m2, x, y)
if chance == "game over":
break
play_game()