-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogic.py
More file actions
76 lines (62 loc) · 1.82 KB
/
Copy pathlogic.py
File metadata and controls
76 lines (62 loc) · 1.82 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
def empty_board():
return [
[None, None, None],
[None, None, None],
[None, None, None],
]
def get_board_filled_num(board):
num = 0
for i in range(3):
for j in range(3):
if board[i][j] is not None:
num += 1
return num
def get_winner(board):
"""Determines the winner of the given board.
Returns 'X', 'O', or None."""
# If a player wants to win Tic-Tac-Toe,
# these are all possible combinations
# for a player to win the game.
wins = [
[(0, 0), (0, 1), (0, 2)],
[(1, 0), (1, 1), (1, 2)],
[(2, 0), (2, 1), (2, 2)],
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
[(0, 0), (1, 1), (2, 2)],
[(0, 2), (1, 1), (2, 0)],
]
def check_win(S) -> bool:
"""
Check if a set of a player's pieces leads to win.
:param S: a set
:return: True if the set can lead to win otherwise False
"""
for win in wins:
flag = True
for pos in win:
if pos not in S:
flag = False
break
if flag:
return True
return False
x_set, o_set = set(), set()
for i in range(3):
for j in range(3):
if board[i][j] == "X":
x_set.add((i, j))
if check_win(x_set):
return "X"
elif board[i][j] == "O":
o_set.add((i, j))
if check_win(o_set):
return "O"
# Otherwise let the game continue
return None if get_board_filled_num(board) != 9 else "DRAW"
def other_player(player):
"""
Return the other player for the given player.
"""
return "O" if player == "X" else "X"