-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtictactoe.py
93 lines (73 loc) · 1.8 KB
/
tictactoe.py
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
"""
Tic Tac Toe Player
"""
import math
X = "X"
O = "O"
board = [[None, None, None], [None, None, None], [None, None, None]]
turn = X
def initial_state():
"""
Returns starting state of the board.
"""
return [[None, None, None],
[None, None, None],
[None, None, None]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
if turn == 'X':
turn = 'O'
else:
turn = "X"
def result(board, action):
"""
updates board with new move
"""
i = action[0]
j = action[1]
if board[i][j] != None:
raise Exception
board[i][j] = player(board)
return board
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
# check colums
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] and board[i][0] != None:
return board[i][0]
# check rows
for i in range(3):
if board[0][i] == board[1][i] == board[2][i] and board[0][i] != None:
return board[0][i]
# check diagonal
if board[0][0] == board[1][1] == board[2][2] or board[2][0] == board[1][1] == board[0][2] and board[1][1] != None:
return board[1][1]
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if winner(board) is not None:
return True
if sum(j.count(None) for j in board) == 0:
return True
return False
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board) == "X":
return 1
if winner(board) == "O":
return -1
else:
return 0
def player(board):
if sum(j.count(None) for j in board) % 2 == 1:
return "X"
else:
return "O"