-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulator1.py
565 lines (452 loc) · 17.2 KB
/
simulator1.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import sys
import random
import signal
from Submission import Player as Player1
#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]))
'''
class Player1:
def __init__(self):
pass
def move(self,temp_board,temp_block,old_move,flag):
# while(1):
# pass
for_corner = [0,2,3,5,6,8]
#List of permitted blocks, based on old move.
blocks_allowed = []
if old_move[0] in for_corner and old_move[1] in for_corner:
## we will have 3 representative blocks, to choose from
if old_move[0] % 3 == 0 and old_move[1] % 3 == 0:
## top left 3 blocks are allowed
blocks_allowed = [0, 1, 3]
elif old_move[0] % 3 == 0 and old_move[1] in [2, 5, 8]:
## top right 3 blocks are allowed
blocks_allowed = [1,2,5]
elif old_move[0] in [2,5, 8] ad old_move[1] % 3 == 0:
## bottom left 3 blocks are allowed
blocks_allowed = [3,6,7]
elif old_move[0] in [2,5,8] and old_move[1] in [2,5,8]:
### bottom right 3 blocks are allowed
blocks_allowed = [5,7,8]
else:
print "SOMETHING REALLY WEIRD HAPPENED!"
sys.exit(1)
else:
#### we will have only 1 block to choose from (or maybe NONE of them, which calls for a free move)
if old_move[0] % 3 == 0 and old_move[1] in [1,4,7]:
## upper-center block
blocks_allowed = [1]
elif old_move[0] in [1,4,7] and old_move[1] % 3 == 0:
## middle-left block
blocks_allowed = [3]
elif old_move[0] in [2,5,8] and old_move[1] in [1,4,7]:
## lower-center block
blocks_allowed = [7]
elif old_move[0] in [1,4,7] and old_move[1] in [2,5,8]:
## middle-right block
blocks_allowed = [5]
elif old_move[0] in [1,4,7] and old_move[1] in [1,4,7]:
blocks_allowed = [4]
# 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)
return cells[random.randrange(len(cells))]
'''
class Player2:
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] in for_corner and old_move[1] in for_corner:
## we will have 3 representative blocks, to choose from
if old_move[0] % 3 == 0 and old_move[1] % 3 == 0:
## top left 3 blocks are allowed
blocks_allowed = [0, 1, 3]
elif old_move[0] % 3 == 0 and old_move[1] in [2, 5, 8]:
## top right 3 blocks are allowed
blocks_allowed = [1,2,5]
elif old_move[0] in [2,5, 8] and old_move[1] % 3 == 0:
## bottom left 3 blocks are allowed
blocks_allowed = [3,6,7]
elif old_move[0] in [2,5,8] and old_move[1] in [2,5,8]:
### bottom right 3 blocks are allowed
blocks_allowed = [5,7,8]
else:
print "SOMETHING REALLY WEIRD HAPPENED!"
sys.exit(1)
else:
#### we will have only 1 block to choose from (or maybe NONE of them, which calls for a free move)
if old_move[0] % 3 == 0 and old_move[1] in [1,4,7]:
## upper-center block
blocks_allowed = [1]
elif old_move[0] in [1,4,7] and old_move[1] % 3 == 0:
## middle-left block
blocks_allowed = [3]
elif old_move[0] in [2,5,8] and old_move[1] in [1,4,7]:
## lower-center block
blocks_allowed = [7]
elif old_move[0] in [1,4,7] and old_move[1] in [2,5,8]:
## middle-right block
blocks_allowed = [5]
elif old_move[0] in [1,4,7] and old_move[1] in [1,4,7]:
blocks_allowed = [4]
# 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)
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):
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):
if gameb[i][j] == '-':
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, 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] in for_corner and old_move[1] in for_corner:
## we will have 3 representative blocks, to choose from
if old_move[0] % 3 == 0 and old_move[1] % 3 == 0:
## top left 3 blocks are allowed
blocks_allowed = [0, 1, 3]
elif old_move[0] % 3 == 0 and old_move[1] in [2, 5, 8]:
## top right 3 blocks are allowed
blocks_allowed = [1,2,5]
elif old_move[0] in [2,5, 8] and old_move[1] % 3 == 0:
## bottom left 3 blocks are allowed
blocks_allowed = [3,6,7]
elif old_move[0] in [2,5,8] and old_move[1] in [2,5,8]:
### bottom right 3 blocks are allowed
blocks_allowed = [5,7,8]
else:
print "SOMETHING REALLY WEIRD HAPPENED!"
sys.exit(1)
else:
#### we will have only 1 block to choose from (or maybe NONE of them, which calls for a free move)
if old_move[0] % 3 == 0 and old_move[1] in [1,4,7]:
## upper-center block
blocks_allowed = [1]
elif old_move[0] in [1,4,7] and old_move[1] % 3 == 0:
## middle-left block
blocks_allowed = [3]
elif old_move[0] in [2,5,8] and old_move[1] in [1,4,7]:
## lower-center block
blocks_allowed = [7]
elif old_move[0] in [1,4,7] and old_move[1] in [2,5,8]:
## middle-right block
blocks_allowed = [5]
elif old_move[0] in [1,4,7] and old_move[1] in [1,4,7]:
blocks_allowed = [4]
# 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)
#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
#print "@@@@@@@@@@@@@@@@@"
#print block_stat
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] == '-':
### now for diagonals
## D1
# ^
# ^
# ^
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
mg=1
#print "SEG: D1 found"
## D2
# ^
# ^
# ^
############ MODIFICATION HERE, in second condition -> gb[id1*3][id2*3+2]
# 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+2][id2*3] and game_board[id1*3+1][id2*3+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
mg=1
#print "SEG: D2 found"
### col-wise
if mflg != 1:
for i in range(id2*3,id2*3+3):
#### MODIFICATION HERE, [i] was missing previously
# if game_board[id1*3]==game_board[id1*3+1] and game_board[id1*3+1] == game_board[id1*3+2] and game_board[id1*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
#print "SEG: Col found"
break
### row-wise
if mflg != 1:
for i in range(id1*3,id1*3+3):
### MODIFICATION HERE, [i] was missing previously
#if game_board[id2*3]==game_board[id2*3+1] and game_board[id2*3+1] == game_board[id2*3+2] and game_board[id2*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
#print "SEG: Row found"
break
if mflg == 1:
block_stat[block_no] = fl
#print
#print block_stat
#print "@@@@@@@@@@@@@@@@@@@@@@@"
return mg
#Check win
def terminal_state_reached(game_board, block_stat,point1,point2):
### we are now concerned only with block_stat
bs = block_stat
## Row win
if (bs[0] == bs[1] and bs[1] == bs[2] and bs[1]!='-') or (bs[3]!='-' and bs[3] == bs[4] and bs[4] == bs[5]) or (bs[6]!='-' and bs[6] == bs[7] and bs[7] == bs[8]):
print block_stat
return True, 'W'
## Col win
elif (bs[0] == bs[3] and bs[3] == bs[6] and bs[0]!='-') or (bs[1] == bs[4] and bs[4] == bs[7] and bs[4]!='-') or (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]!='-') or (bs[2] == bs[4] and bs[4] == bs[6] and bs[2]!='-'):
print block_stat
return True, 'W'
else:
smfl = 0
for i in range(9):
for j in range(9):
if game_board[i][j] == '-':
smfl = 1
break
if smfl == 1:
return False, 'Continue'
else:
##### check of number of DIAGONALs
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 status == 'P1':
return ('P1', 'MORE DIAGONALS')
elif status == 'P2':
return ('P2', 'MORE DIAGONALS')
elif 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 ('NONE','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()
#########
# deciding player1 / player2 after a coin toss
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 = 60
### These points will not keep track of the total points of both the players.
### Instead, these variables will keep track of only the blocks won by DIAGONALS, and these points will be used only in cases of DRAW....
p1_pts=0
p2_pts=0
#### printing
print_lists(game_board, block_stat)
while(1):
######################################
########### firstly pl1 will move
######################################
## just for checking that the player1 does not modify the contents of the 2 lists
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
### MODIFICATION!!
signal.alarm(0)
#### check if both lists are the same!!
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
### now check if the returned move is valid
if not check_valid_move(game_board, 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
p1_pts += update_lists(game_board, block_stat, ret_move_pl1, pl1_fl)
### now check if the last move resulted in a terminal state
gamestatus, mesg = terminal_state_reached(game_board, block_stat,p1_pts,p2_pts)
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
###########################################
## just for checking that the player2 does not modify the contents of the 2 lists
temp_board_state = game_board[:]
temp_block_stat = block_stat[:]
signal.signal(signal.SIGALRM, handler)
signal.alarm(TIMEALLOWED)
# Player2 to complete in TIMEALLOWED secs.
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)
#### check if both lists are the same!!
if not (verification_fails_board(game_board, temp_board_state) and verification_fails_block(block_stat, temp_block_stat)):
##player2 loses - he modified something
WINNER, MESSAGE = decide_winner_and_get_message('P2', 'L', 'MODIFIED CONTENTS OF LISTS')
break
### now check if the returned move is valid
if not check_valid_move(game_board, ret_move_pl2, old_move):
## player2 loses - he made the wrong 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
######## So if the move is valid, we update the 'game_board' and 'block_stat' lists with the move of P2
p2_pts += update_lists(game_board, block_stat, ret_move_pl2, pl2_fl)
### now check if the last move resulted in a terminal state
gamestatus, mesg = terminal_state_reached(game_board, block_stat,p1_pts,p2_pts)
if gamestatus == True:
print_lists(game_board, block_stat)
WINNER, MESSAGE = decide_winner_and_get_message('P2', mesg, 'COMPLETE' )
break
### otherwise CONTINUE
old_move = ret_move_pl2
print_lists(game_board, block_stat)
######### THESE ARE NOT THE TOTAL points, these are just the diagonal points, (refer to the part before the while(1) loop
####### These will be used only in cases of DRAW
print p1_pts
print p2_pts
print WINNER
print MESSAGE
# return WINNER, MESSAGE, p1_pt2, p2_pt2
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()
#########
# deciding player1 / player2 after a coin toss
num = random.uniform(0,1)
interchange = 0
if num > 0.5:
interchange = 1
simulate(obj2, obj1)
else:
simulate(obj1, obj2)