-
Notifications
You must be signed in to change notification settings - Fork 0
/
ttt.py
78 lines (64 loc) · 2.82 KB
/
ttt.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
class TTT:
board: list[list[int]]
current_player: int
def __init__(self):
self.board = [[0 for _ in range(3)] for _ in range(3)]
self.current_player = 1
def print(self):
for i in range(3):
for j in range(3):
print(self.board[i][j], end=' ')
print()
def move(self, pos):
self.board[pos[0]][pos[1]] = self.current_player
self.current_player = -self.current_player
def player_move(self, pos, player):
self.board[pos[0]][pos[1]] = player
def is_legal(self, pos):
return self.board[pos[0]][pos[1]] == 0
def is_full(self):
return all([self.board[i][j] != 0 for i in range(3) for j in range(3)])
def is_win(self):
return any([all([self.board[0][i] == -self.current_player for i in range(3)]),
all([self.board[1][i] == -self.current_player for i in range(3)]),
all([self.board[2][i] == -self.current_player for i in range(3)]),
all([self.board[i][0] == -self.current_player for i in range(3)]),
all([self.board[i][1] == -self.current_player for i in range(3)]),
all([self.board[i][2] == -self.current_player for i in range(3)]),
all([self.board[i][i] == -self.current_player for i in range(3)]),
all([self.board[i][2 - i] == -self.current_player for i in range(3)])])
def is_player_win(self, player):
return any([all([self.board[0][i] == player for i in range(3)]),
all([self.board[1][i] == player for i in range(3)]),
all([self.board[2][i] == player for i in range(3)]),
all([self.board[i][0] == player for i in range(3)]),
all([self.board[i][1] == player for i in range(3)]),
all([self.board[i][2] == player for i in range(3)]),
all([self.board[i][i] == player for i in range(3)]),
all([self.board[i][2 - i] == player for i in range(3)])])
def is_draw(self):
return self.is_full() and not self.is_win()
def get_legal_moves(self):
if self.is_win():
return []
return [(i, j) for i in range(3) for j in range(3) if self.board[i][j] == 0]
def game_loop(self):
player = 1
while True:
self.print()
print()
while True:
pos = input("Enter position: ")
pos = pos.split(',')
pos = (int(pos[0]), int(pos[1]))
if self.is_legal(pos):
break
print("Illegal move")
self.move(pos)
if self.is_win():
break
player = -player
if __name__ == '__main__':
game = TTT()
# game.print()
game.game_loop()