-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulation.py~
461 lines (373 loc) · 14.4 KB
/
simulation.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import sys
import random
import signal
#Timer handler, helper function
class TimedOutExc(Exception):
pass
def handler(signum, frame):
#print 'Signal handler called with signal', signum
raise TimedOutExc()
class Manual_player:
def __init__(self):
pass
def move(self, temp_board, temp_block, old_move, flag):
print 'Enter your move: <format:row column> (you\'re playing with', flag + ")"
mvp = raw_input()
mvp = mvp.split()
return (int(mvp[0]), int(mvp[1]))
from team33_final import Player33 as Player1
from team31_final import Player31 as Player2
class Player12:
def __init__(self):
pass
def move(self,temp_board,temp_block,old_move,flag):
for_corner = [0,2,3,5,6,8]
#List of permitted blocks, based on old move.
blocks_allowed = []
if old_move[0] % 3 == 0 and old_move[1] % 3 == 0:
blocks_allowed = [1,3]
elif old_move[0] % 3 == 0 and old_move[1] % 3 == 2:
blocks_allowed = [1,5]
elif old_move[0] % 3 == 2 and old_move[1] % 3 == 0:
blocks_allowed = [3,7]
elif old_move[0] % 3 == 2 and old_move[1] % 3 == 2:
blocks_allowed = [5,7]
elif old_move[0] % 3 == 0 and old_move[1] % 3 == 1:
blocks_allowed = [0,2]
elif old_move[0] % 3 == 1 and old_move[1] % 3 == 0:
blocks_allowed = [0,6]
elif old_move[0] % 3 == 2 and old_move[1] % 3 == 1:
blocks_allowed = [6,8]
elif old_move[0] % 3 == 1 and old_move[1] % 3 == 2:
blocks_allowed = [2,8]
elif old_move[0] % 3 == 1 and old_move[1] % 3 == 1:
blocks_allowed = [4]
else:
print "SOMETHING REALLY WEIRD HAPPENED!"
sys.exit(1)
for i in reversed(blocks_allowed):
if temp_block[i] != '-':
blocks_allowed.remove(i)
# We get all the empty cells in allowed blocks. If they're all full, we get all the empty cells in the entire board.
cells = get_empty_out_of(temp_board,blocks_allowed,temp_block)
return cells[random.randrange(len(cells))]
#Initializes the game
def get_init_board_and_blockstatus():
board = []
for i in range(9):
row = ['-']*9
board.append(row)
block_stat = ['-']*9
return board, block_stat
# Checks if player has messed with the board. Don't mess with the board that is passed to your move function.
def verification_fails_board(board_game, temp_board_state):
return board_game == temp_board_state
# Checks if player has messed with the block. Don't mess with the block array that is passed to your move function.
def verification_fails_block(block_stat, temp_block_stat):
return block_stat == temp_block_stat
#Gets empty cells from the list of possible blocks. Hence gets valid moves.
def get_empty_out_of(gameb, blal,block_stat):
cells = [] # it will be list of tuples
#Iterate over possible blocks and get empty cells
for idb in blal:
id1 = idb/3
id2 = idb%3
for i in range(id1*3,id1*3+3):
for j in range(id2*3,id2*3+3):
if gameb[i][j] == '-':
cells.append((i,j))
# If all the possible blocks are full, you can move anywhere
if cells == []:
for i in range(9):
for j in range(9):
no = (i/3)*3
no += (j/3)
if gameb[i][j] == '-' and block_stat[no] == '-':
cells.append((i,j))
return cells
# Note that even if someone has won a block, it is not abandoned. But then, there's no point winning it again!
# Returns True if move is valid
def check_valid_move(game_board,block_stat, current_move, old_move):
# first we need to check whether current_move is tuple of not
# old_move is guaranteed to be correct
if type(current_move) is not tuple:
return False
if len(current_move) != 2:
return False
a = current_move[0]
b = current_move[1]
if type(a) is not int or type(b) is not int:
return False
if a < 0 or a > 8 or b < 0 or b > 8:
return False
#Special case at start of game, any move is okay!
if old_move[0] == -1 and old_move[1] == -1:
return True
for_corner = [0,2,3,5,6,8]
#List of permitted blocks, based on old move.
blocks_allowed = []
if old_move[0] % 3 == 0 and old_move[1] % 3 == 0:
blocks_allowed = [1,3]
elif old_move[0] % 3 == 0 and old_move[1] % 3 == 2:
blocks_allowed = [1,5]
elif old_move[0] % 3 == 2 and old_move[1] % 3 == 0:
blocks_allowed = [3,7]
elif old_move[0] % 3 == 2 and old_move[1] % 3 == 2:
blocks_allowed = [5,7]
elif old_move[0] % 3 == 0 and old_move[1] % 3 == 1:
blocks_allowed = [0,2]
elif old_move[0] % 3 == 1 and old_move[1] % 3 == 0:
blocks_allowed = [0,6]
elif old_move[0] % 3 == 2 and old_move[1] % 3 == 1:
blocks_allowed = [6,8]
elif old_move[0] % 3 == 1 and old_move[1] % 3 == 2:
blocks_allowed = [2,8]
elif old_move[0] % 3 == 1 and old_move[1] % 3 == 1:
blocks_allowed = [4]
else:
print "SOMETHING REALLY WEIRD HAPPENED!"
sys.exit(1)
#Check if the block is won, or completed. If so you cannot move there.
for i in reversed(blocks_allowed):
if block_stat[i] != '-':
blocks_allowed.remove(i)
# We get all the empty cells in allowed blocks. If they're all full, we get all the empty cells in the entire board.
cells = get_empty_out_of(game_board, blocks_allowed,block_stat)
#Checks if you made a valid move.
if current_move in cells:
return True
else:
return False
def update_lists(game_board, block_stat, move_ret, fl):
#move_ret has the move to be made, so we modify the game_board, and then check if we need to modify block_stat
game_board[move_ret[0]][move_ret[1]] = fl
block_no = (move_ret[0]/3)*3 + move_ret[1]/3
id1 = block_no/3
id2 = block_no%3
mg = 0
mflg = 0
if block_stat[block_no] == '-':
if game_board[id1*3][id2*3] == game_board[id1*3+1][id2*3+1] and game_board[id1*3+1][id2*3+1] == game_board[id1*3+2][id2*3+2] and game_board[id1*3+1][id2*3+1] != '-':
mflg=1
if game_board[id1*3+2][id2*3] == game_board[id1*3+1][id2*3+1] and game_board[id1*3+1][id2*3+1] == game_board[id1*3][id2*3 + 2] and game_board[id1*3+1][id2*3+1] != '-':
mflg=1
if mflg != 1:
for i in range(id2*3,id2*3+3):
if game_board[id1*3][i]==game_board[id1*3+1][i] and game_board[id1*3+1][i] == game_board[id1*3+2][i] and game_board[id1*3][i] != '-':
mflg = 1
break
### row-wise
if mflg != 1:
for i in range(id1*3,id1*3+3):
if game_board[i][id2*3]==game_board[i][id2*3+1] and game_board[i][id2*3+1] == game_board[i][id2*3+2] and game_board[i][id2*3] != '-':
mflg = 1
break
if mflg == 1:
block_stat[block_no] = fl
#check for draw on the block.
id1 = block_no/3
id2 = block_no%3
cells = []
for i in range(id1*3,id1*3+3):
for j in range(id2*3,id2*3+3):
if game_board[i][j] == '-':
cells.append((i,j))
if cells == [] and mflg!=1:
block_stat[block_no] = 'd' #Draw
return
def terminal_state_reached(game_board, block_stat):
#Check if game is won!
bs = block_stat
## Row win
if (bs[0] == bs[1] and bs[1] == bs[2] and bs[1]!='-' and bs[1]!='d') or (bs[3]!='d' and bs[3]!='-' and bs[3] == bs[4] and bs[4] == bs[5]) or (bs[6]!='d' and bs[6]!='-' and bs[6] == bs[7] and bs[7] == bs[8]):
print block_stat
return True, 'W'
## Col win
elif (bs[0]!='d' and bs[0] == bs[3] and bs[3] == bs[6] and bs[0]!='-') or (bs[1]!='d'and bs[1] == bs[4] and bs[4] == bs[7] and bs[4]!='-') or (bs[2]!='d' and bs[2] == bs[5] and bs[5] == bs[8] and bs[5]!='-'):
print block_stat
return True, 'W'
## Diag win
elif (bs[0] == bs[4] and bs[4] == bs[8] and bs[0]!='-' and bs[0]!='d') or (bs[2] == bs[4] and bs[4] == bs[6] and bs[2]!='-' and bs[2]!='d'):
print block_stat
return True, 'W'
else:
smfl = 0
for i in range(9):
for j in range(9):
if game_board[i][j] == '-' and block_stat[(i/3)*3+(j/3)] == '-':
smfl = 1
break
if smfl == 1:
#Game is still on!
return False, 'Continue'
else:
#Changed scoring mechanism
# 1. If there is a tie, player with more boxes won, wins.
# 2. If no of boxes won is the same, player with more corner move, wins.
point1 = 0
point2 = 0
for i in block_stat:
if i == 'x':
point1+=1
elif i=='o':
point2+=1
if point1>point2:
return True, 'P1'
elif point2>point1:
return True, 'P2'
else:
point1 = 0
point2 = 0
for i in range(len(game_board)):
for j in range(len(game_board[i])):
if i%3!=1 and j%3!=1:
if game_board[i][j] == 'x':
point1+=1
elif game_board[i][j]=='o':
point2+=1
if point1>point2:
return True, 'P1'
elif point2>point1:
return True, 'P2'
else:
return True, 'D'
def decide_winner_and_get_message(player,status, message):
if player == 'P1' and status == 'L':
return ('P2',message)
elif player == 'P1' and status == 'W':
return ('P1',message)
elif player == 'P2' and status == 'L':
return ('P1',message)
elif player == 'P2' and status == 'W':
return ('P2',message)
else:
return ('NO ONE','DRAW')
return
def print_lists(gb, bs):
print '=========== Game Board ==========='
for i in range(9):
if i > 0 and i % 3 == 0:
print
for j in range(9):
if j > 0 and j % 3 == 0:
print " " + gb[i][j],
else:
print gb[i][j],
print
print "=================================="
print "=========== Block Status ========="
for i in range(0, 9, 3):
print bs[i] + " " + bs[i+1] + " " + bs[i+2]
print "=================================="
print
def simulate(obj1,obj2):
# Game board is a 9x9 list, block_stat is a 1D list of 9 elements
game_board, block_stat = get_init_board_and_blockstatus()
pl1 = obj1
pl2 = obj2
### basically, player with flag 'x' will start the game
pl1_fl = 'x'
pl2_fl = 'o'
old_move = (-1, -1) # For the first move
WINNER = ''
MESSAGE = ''
TIMEALLOWED = 12
print_lists(game_board, block_stat)
while(1):
# Player1 will move
temp_board_state = game_board[:]
temp_block_stat = block_stat[:]
signal.signal(signal.SIGALRM, handler)
signal.alarm(TIMEALLOWED)
# Player1 to complete in TIMEALLOWED secs.
try:
ret_move_pl1 = pl1.move(temp_board_state, temp_block_stat, old_move, pl1_fl)
except TimedOutExc as e:
WINNER, MESSAGE = decide_winner_and_get_message('P1', 'L', 'TIMED OUT')
break
signal.alarm(0)
#Checking if list hasn't been modified! Note: Do not make changes in the lists passed in move function!
if not (verification_fails_board(game_board, temp_board_state) and verification_fails_block(block_stat, temp_block_stat)):
#Player1 loses - he modified something
WINNER, MESSAGE = decide_winner_and_get_message('P1', 'L', 'MODIFIED CONTENTS OF LISTS')
break
# Check if the move made is valid
if not check_valid_move(game_board, block_stat,ret_move_pl1, old_move):
## player1 loses - he made the wrong move.
WINNER, MESSAGE = decide_winner_and_get_message('P1', 'L', 'MADE AN INVALID MOVE')
break
print "Player 1 made the move:", ret_move_pl1, 'with', pl1_fl
#So if the move is valid, we update the 'game_board' and 'block_stat' lists with move of pl1
update_lists(game_board, block_stat, ret_move_pl1, pl1_fl)
# Checking if the last move resulted in a terminal state
gamestatus, mesg = terminal_state_reached(game_board, block_stat)
if gamestatus == True:
print_lists(game_board, block_stat)
WINNER, MESSAGE = decide_winner_and_get_message('P1', mesg, 'COMPLETE')
break
old_move = ret_move_pl1
print_lists(game_board, block_stat)
# Now player2 plays
temp_board_state = game_board[:]
temp_block_stat = block_stat[:]
signal.signal(signal.SIGALRM, handler)
signal.alarm(TIMEALLOWED)
try:
ret_move_pl2 = pl2.move(temp_board_state, temp_block_stat, old_move, pl2_fl)
except TimedOutExc as e:
WINNER, MESSAGE = decide_winner_and_get_message('P2', 'L', 'TIMED OUT')
break
signal.alarm(0)
if not (verification_fails_board(game_board, temp_board_state) and verification_fails_block(block_stat, temp_block_stat)):
WINNER, MESSAGE = decide_winner_and_get_message('P2', 'L', 'MODIFIED CONTENTS OF LISTS')
break
if not check_valid_move(game_board, block_stat,ret_move_pl2, old_move):
WINNER, MESSAGE = decide_winner_and_get_message('P2', 'L', 'MADE AN INVALID MOVE')
break
print "Player 2 made the move:", ret_move_pl2, 'with', pl2_fl
update_lists(game_board, block_stat, ret_move_pl2, pl2_fl)
gamestatus, mesg = terminal_state_reached(game_board, block_stat)
if gamestatus == True:
print_lists(game_board, block_stat)
WINNER, MESSAGE = decide_winner_and_get_message('P2', mesg, 'COMPLETE' )
break
old_move = ret_move_pl2
print_lists(game_board, block_stat)
print WINNER + " won!"
print MESSAGE
if __name__ == '__main__':
## get game playing objects
if len(sys.argv) != 2:
print 'Usage: python simulator.py <option>'
print '<option> can be 1 => Random player vs. Random player'
print ' 2 => Human vs. Random Player'
print ' 3 => Human vs. Human'
sys.exit(1)
obj1 = ''
obj2 = ''
option = sys.argv[1]
if option == '1':
obj1 = Player1()
obj2 = Player2()
elif option == '2':
obj1 = Player1()
obj2 = Manual_player()
elif option == '3':
obj1 = Manual_player()
obj2 = Manual_player()
# O_token = 1
# simulate(obj2, obj1)
# Deciding player1 / player2 after a coin toss
# However, in the tournament, each player will get a chance to go 1st.
num = random.uniform(0,1)
flag = 0
if num > 0.5:
flag = 1
simulate(obj1, obj2)
else:
flag =2
simulate(obj1, obj2)
if (flag == 1):
print "You are P2"
else:
print "You are P1"