xonecas.io
373
Ti

tictactoe / commit 978bf4d

Initial commit

xonecas2020-08-12 978bf4d1e2438ed3660a9a7399de92286052db87

1 file changed

tic_tac_tow.py+111−0
@@ -0,0 +1,111 @@
1+#!/usr/bin/env python3
2+
3+import random
4+
5+
6+class TicTacToe():
7+
8+ class NoPlayableRoom(Exception):
9+ """Error for when the AI has no valid moves"""
10+ pass
11+
12+ class InvalidPlay(Exception):
13+ """Error for when the Player chooses an invalid move"""
14+ pass
15+
16+ AI = 1
17+ PLAYER = 2
18+ SYMBOLS = {0: '-', 1: 'O', 2: 'X', }
19+
20+ def __init__(self):
21+ self.board = self.makeBoard()
22+ # Simple heads or tails, under 5.0 goes the player
23+ self.who_next = self.PLAYER if random.random() >= 0.5 else self.AI
24+
25+ def makeBoard(self):
26+ return [[0] * 3 for i in [0] * 3]
27+
28+ def printBoard(self):
29+ symbols_to_print = ''
30+ for i, n in enumerate(self.board):
31+ for j, m in enumerate(n):
32+ symbols_to_print = symbols_to_print + self.SYMBOLS[m]
33+ if j < 2:
34+ symbols_to_print = symbols_to_print + '|'
35+ else:
36+ symbols_to_print = symbols_to_print + '\n'
37+ print('\n' + symbols_to_print + '\n')
38+
39+ def checkForRoom(self):
40+ foundRoom = False
41+ coords = None
42+
43+ for i, _ in enumerate(self.board):
44+ for j, m in enumerate(self.board[i]):
45+ if m == 0:
46+ foundRoom = True
47+ coords = (i, j)
48+ break
49+ if foundRoom:
50+ break
51+
52+ return foundRoom, coords
53+
54+ def AIPlay(self):
55+ isThereRoom = self.checkForRoom()
56+
57+ if isThereRoom[0]:
58+ print('AI is making their move...')
59+ i = isThereRoom[1][0]
60+ j = isThereRoom[1][1]
61+ self.board[i][j] = self.AI
62+ else:
63+ raise self.NoPlayableRoom()
64+
65+ def PlayerPlay(self):
66+ isThereRoom = self.checkForRoom()
67+
68+ if isThereRoom[0]:
69+ player_coords_input = (
70+ input('\nEnter a row and column, separeted by a comma\n\n'))
71+ i, j = [int(s) - 1 for s in player_coords_input.split(',')]
72+ allowed_indexes = (0, 1, 2)
73+
74+ if (i in allowed_indexes and j in allowed_indexes and
75+ self.board[i][j] == 0):
76+ self.board[i][j] = self.PLAYER
77+ else:
78+ raise self.InvalidPlay()
79+ else:
80+ raise self.NoPlayableRoom()
81+
82+ def makePlay(self):
83+ if self.who_next == self.PLAYER:
84+ self.PlayerPlay()
85+ else:
86+ self.AIPlay()
87+
88+ def choose_next_move(self):
89+ self.who_next = self.PLAYER if self.who_next == self.AI else self.AI
90+
91+ def loop(self):
92+ game_running = True
93+
94+ while(game_running):
95+ self.printBoard()
96+
97+ try:
98+ self.makePlay()
99+ except self.NoPlayableRoom:
100+ print('\nGame over')
101+ game_running = False
102+ except self.InvalidPlay:
103+ print('\nInvalid coordenates, please choose a valid spot\n\n')
104+ self.loop()
105+
106+ self.choose_next_move()
107+
108+
109+if __name__ == '__main__':
110+ game = TicTacToe()
111+ game.loop()