-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_engine.py
More file actions
61 lines (53 loc) · 1.88 KB
/
base_engine.py
File metadata and controls
61 lines (53 loc) · 1.88 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
class BaseEngine:
def __init__(self):
self.wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
self.board = [' ' for _ in range(9)]
self.playing_as = 'O'
self.turn = 'X'
self.won = ''
def display(self):
board = self.board
print(f'{board[0]} | {board[1]} | {board[2]}\n'
f'---------\n'
f'{board[3]} | {board[4]} | {board[5]}\n'
f'---------\n'
f'{board[6]} | {board[7]} | {board[8]}')
def check_for_end(self):
for win in self.wins:
line = [self.board[i] for i in win]
if line.count('X') == 3:
self.won = 'X'
break
elif line.count('O') == 3:
self.won = 'O'
break
if self.won == '' and ' ' not in self.board:
self.won = 'Tie!'
def ai_turn(self):
# TODO Implement the AI logic here
move = -1
return move
def player_turn(self):
self.display()
move = -1
while move not in range(9) or self.board[move] != ' ':
try:
move = int(input('Enter a number between 0 and 8: '))
if move not in range(9) or self.board[move] != ' ':
print('Invalid move. Try again.')
except ValueError:
print('Invalid move. Try again.')
return move
def game_turn(self):
if self.turn == self.playing_as:
move = self.ai_turn()
else:
move = self.player_turn()
self.board[move] = self.turn
self.turn = 'O' if self.turn == 'X' else 'X'
self.check_for_end()
if self.won == '':
self.game_turn()
else:
self.display()
print(f'{self.won} won!' if self.won != 'Tie!' else 'It\'s a Tie!')