-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
238 lines (193 loc) · 6.28 KB
/
main.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import sys
import numpy as np
import random
from random import choice
import time
import TicTacToe
sys.dont_write_bytecode = True
COMP = +1
HUMAN = -1
def run_code(tic_tac_toe, test_case, grid_size, player_1=None, player_2=None):
# Loops until there are empty spaces available on the grid for more inputs
player_1_val = +1
player_2_val = -1
itr = 0
while len(tic_tac_toe.emptyGrid()) > 0 and not tic_tac_toe.isGameOver():
# Get user input 1: "X"
success = False
while not success and len(tic_tac_toe.emptyGrid()):
try:
# use user inputs
tic_tac_toe.clean()
tic_tac_toe.initialGridDisplay()
tic_tac_toe.printGrid(player_1, player_2)
user_input_x = int(input("\nX: Choose between 0-{}: ".format(grid_size*grid_size)))
except Exception as e:
# the input is invalid
print("Invalid input. Please try again.")
continue
j = user_input_x % grid_size
i = user_input_x // grid_size
success = tic_tac_toe.updateGrid(i, j, player_1_val)
if success:
itr += 1
# Check if X is a winner
result = tic_tac_toe.isWinner(player_1_val)
if result:
tic_tac_toe.clean()
tic_tac_toe.printGrid(player_1, player_2)
print("Player 1 is the winner")
sys.exit()
break
# Get user input 2: "O"
success = False
while not success and len(tic_tac_toe.emptyGrid()):
try:
# use user inputs
tic_tac_toe.clean()
tic_tac_toe.initialGridDisplay()
tic_tac_toe.printGrid(player_1, player_2)
user_input_y = int(input("\n0: Choose between 0-{}: ".format(grid_size*grid_size)))
except Exception as e:
# the input is invalid
print("Invalid input. Please try again.")
continue
j = user_input_y % grid_size
i = user_input_y // grid_size
success = tic_tac_toe.updateGrid(i, j, player_2_val)
if success:
itr += 1
# Check if Y is a winner
result = tic_tac_toe.isWinner(player_2_val)
if result:
tic_tac_toe.clean()
tic_tac_toe.printGrid(player_1, player_2)
print("Player 2 is the winner")
sys.exit()
break
print("DRAW!")
def computer_turn(tic_tac_toe, grid_size, human_choice, computer_choice):
game_depth = len(tic_tac_toe.emptyGrid())
if game_depth == 0 or tic_tac_toe.isGameOver():
return
tic_tac_toe.clean()
print(f'Computer turn [{computer_choice}]')
tic_tac_toe.initialGridDisplay()
tic_tac_toe.printGrid(computer_choice, human_choice)
if game_depth == (grid_size*grid_size):
x = np.random.randint(0, grid_size, 1)[0]
y = np.random.randint(0, grid_size, 1)[0]
else:
move = tic_tac_toe.minimaxAlgorithm(game_depth, COMP)
x, y = move[0], move[1]
tic_tac_toe.updateGrid(x, y, COMP)
time.sleep(1)
def human_turn(tic_tac_toe, grid_size, human_choice, computer_choice):
game_depth = len(tic_tac_toe.emptyGrid())
if game_depth == 0 or tic_tac_toe.isGameOver():
return
tic_tac_toe.clean()
print(f'Human turn [{human_choice}]')
tic_tac_toe.initialGridDisplay()
tic_tac_toe.printGrid(computer_choice, human_choice)
grid_no = -1
while grid_no <= 0 or grid_no > (grid_size*grid_size):
try:
grid_no = int(input('Use numpad (0..{}): '.format(grid_size*grid_size)))
j = grid_no % grid_size
i = grid_no // grid_size
can_move = tic_tac_toe.updateGrid(i, j, HUMAN)
if not can_move:
print('Bad move')
grid_no = -1
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')
def main():
print("============")
print("TIC-TAC-TOE")
print("============")
grid_size = int(input('Choose the game size: '))
# grid_size = 3
print('Initializing a Game (' + str(grid_size) + 'x' + str(grid_size) + ')')
tic_tac_toe = TicTacToe.TicTacToe(grid_size=grid_size, board=np.zeros((grid_size, grid_size)))
print("--------------------------")
human_choice = ''
computer_choice = ''
is_player_computer = ''
first_player = ''
second_player = ''
# let's human choose if he wants to play with another human or computer
while is_player_computer != 'y' and is_player_computer != 'n':
try:
is_player_computer = input("Do you want to play vs the computer?(y/n):\nChoice: ").lower()
print("--------------------------")
except:
print("Bad Choice")
if is_player_computer =='y':
print("Human VS Computer")
print("--------------------------")
# let's human choose to be X or 0
while human_choice != '0' and human_choice != 'X':
try:
human_choice = input("Choose X or O\nChoice: ",).upper()
print("--------------------------")
except Error as e:
print(e)
except(Keyerror, ValueError):
print("Bad Choice! Please try again")
# assigning computer a choice/label
if human_choice == 'X':
computer_choice = '0'
else:
computer_choice = 'X'
while first_player != 'Y' and first_player != 'N':
try:
first_player = input('Do you want to start first?[y/n]: ').upper()
print("--------------------------")
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')
tic_tac_toe.clean()
# main loop
while len(tic_tac_toe.emptyGrid()) > 0 and not tic_tac_toe.isGameOver():
if first_player == 'N':
computer_turn(tic_tac_toe, grid_size, human_choice, computer_choice)
first_player = ''
human_turn(tic_tac_toe, grid_size, human_choice, computer_choice)
if tic_tac_toe.isWinner(HUMAN):
tic_tac_toe.clean()
tic_tac_toe.printGrid(computer_choice, human_choice)
print('YOU WIN!')
sys.exit()
# print("Execute computer")
computer_turn(tic_tac_toe, grid_size, human_choice, computer_choice)
if tic_tac_toe.isWinner(COMP):
tic_tac_toe.clean()
tic_tac_toe.printGrid(computer_choice, human_choice)
print('YOU LOOSE!')
sys.exit()
tic_tac_toe.printGrid(computer_choice, human_choice)
print('DRAW!')
else:
print("Human VS Human")
print("--------------------------")
while human_choice != '0' and human_choice != 'X':
try:
human_choice = input("Choose X or O\nChoice: ",).upper()
print("--------------------------")
except Error as e:
print(e)
except(Keyerror, ValueError):
print("Bad Choice! Please try again")
if human_choice == 'X':
computer_choice = '0'
else:
computer_choice = 'X'
run_code(tic_tac_toe, None, grid_size, human_choice, computer_choice)
if __name__ == '__main__':
main()