forked from USPCodeLabSanca/onboarding_tic-tac-toe_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtictactoe.py
113 lines (97 loc) · 3.08 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
class TicTacToe:
def __init__(self):
self.board = [[' ' for i in range (3)] for j in range(3)]
self.symbols = {
'x' : 'x',
'o' : 'o'
}
self.count_moves = 0
self.game_end = False
def __position_is_valid(self, x, y):
return x >= 0 and x < 3 and y >= 0 and y < 3 and self.board[x][y] == ' '
def update_game(self, x, y, mark):
message = None
if (self.game_end):
raise Exception('O jogo acabou')
if (mark == 'x' or mark == 'o'):
if (self.__position_is_valid(x, y)):
self.board[x][y] = self.symbols[mark]
self.count_moves+=1
else:
raise Exception('Posição Inválida ou Já Preenchida')
else:
raise Exception('Símbolo Inválido. Digite \'x\' ou \'o\'')
if (self.__check_game(x, y, mark)):
#message = f"O jogador com {self.symbols[mark]} ganhou!!"
message = self.symbols[mark]
self.game_end = True
elif (self.count_moves == 9):
#message = "Os jogadores empataram!!"
message = '-1'
self.game_end = True
return message
def set_symbol(self, mark, symbol):
if (symbol not in self.symbols.values()):
self.symbols[mark] = symbol
else:
raise Exception('Este símbolo já foi cadastrado')
def __check_game(self, x, y, mark):
i = j = 0
#verifying the vertical orientation
while (i < 3):
if (self.board[i][y] != self.symbols[mark]):
break
i+=1
else:
return True
#verifying the horizontal orientation
while (j < 3):
if (self.board[x][j] != self.symbols[mark]):
break
j+=1
else:
return True
i = j = 0
#verifying the right diagonal
while (i < 3):
if (self.board[i][j] != self.symbols[mark]):
break
i+=1
j+=1
else:
return True
i = 0
j = 2
#verifying the left diagonal
while (i < 3):
if (self.board[i][j] != self.symbols[mark]):
break
i+=1
j-=1
else:
return True
return False
def show_board(self):
for i in range (3):
print("|", end = '')
for j in range (3):
print ("{value}".format(value = self.board[i][j]), end='|')
print()
print()
def main():
game = TicTacToe()
game.update_game(1, 1, 'x')
game.update_game(1, 2, 'o')
game.update_game(0, 1, 'x')
game.update_game(2, 1, 'o')
game.update_game(0,0, 'o')
game.update_game(0,2,'x')
game.update_game(1,0,'x')
game.update_game(2,0,'x')
game.show_board()
new_game = TicTacToe()
new_game.set_symbol('x', 'Y')
new_game.update_game(1, 1, 'x')
new_game.show_board()
if __name__ == "__main__":
main()