-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulator.py
348 lines (305 loc) · 10.6 KB
/
simulator.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
import sys
import random
import signal
import time
import copy
from team42 import Player42 # my bot
from test import player4
class TimedOutExc(Exception):
pass
def handler(signum, frame):
#print 'Signal handler called with signal', signum
raise TimedOutExc()
class Random_Player():
def __init__(self):
pass
def move(self, board, old_move, flag):
#You have to implement the move function with the same signature as this
#Find the list of valid cells allowed
cells = board.find_valid_move_cells(old_move)
return cells[random.randrange(len(cells))]
class Manual_Player:
def __init__(self):
pass
def move(self, board, 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 Board:
def __init__(self):
# board_status is the game board
# block status shows which blocks have been won/drawn and by which player
# initializing 2d arrays using comprehension lists for both board and blocks
self.board_status = [['-' for i in range(16)] for j in range(16)]
self.block_status = [['-' for i in range(4)] for j in range(4)]
# self.board_status[4][4]='o'
# self.board_status[5][4]='o'
# self.board_status[6][4]='o'
# self.board_status[4][5]='x'
# self.board_status[5][5]='x'
#
# self.board_status[9][12]='x'
# self.board_status[9][14]='x'
# self.board_status[9][15]='x'
# self.board_status[10][15]='x'
# self.board_status[10][13]='o'
# self.board_status[10][15]='o'
def print_board(self):
# for printing the state of the board
print '==============Board State=============='
for i in range(16):
if i%4 == 0:
print # this print corresponds to printing a new line
for j in range(16):
if j%4 == 0:
print "", # this print is for printing space between adjacent blocks
print self.board_status[i][j],
print
print
print '==============Block State=============='
for i in range(4):
for j in range(4):
print self.block_status[i][j],
print
print '======================================='
print
print
def find_valid_move_cells(self, old_move):
#returns the valid cells allowed given the last move and the current board state
allowed_cells = []
allowed_block = [old_move[0]%4, old_move[1]%4] #old_move[0] and [1] range from 0 to 15
#checks if the move is a free move or not based on the rules
# old move initialized to (-1,-1) before gameplay
# the below "if condition" checks for "not the first time of play"
if old_move != (-1,-1) and self.block_status[allowed_block[0]][allowed_block[1]] == '-':
for i in range(4*allowed_block[0], 4*allowed_block[0]+4): # after knowing allowed block we are getting the cells of the block by below if conditions
for j in range(4*allowed_block[1], 4*allowed_block[1]+4):
if self.board_status[i][j] == '-':
allowed_cells.append((i,j))
# first time play or allowed block is abandoned
else:
for i in range(16):
for j in range(16):
if self.board_status[i][j] == '-' and self.block_status[i/4][j/4] == '-':
allowed_cells.append((i,j))
return allowed_cells
def find_terminal_state(self):
#checks if the game is over(won or drawn) and returns the player who have won the game or the player who has higher blocks in case of a draw
bs = self.block_status
cntx = 0 # number of blocks won by x
cnto = 0 # number of blocks won by O
cntd = 0 # number of blocks that were a draw
for i in range(4): #counts the blocks won by x, o and drawn blocks
for j in range(4):
if bs[i][j] == 'x': # x has won the block
cntx += 1
if bs[i][j] == 'o': # O has won the block
cnto += 1
if bs[i][j] == 'd': # Match was Draw
cntd += 1
for i in range(4):
row = bs[i] # i'th row
col = [x[i] for x in bs] # i'th column
# checking if i'th row or i'th column has been won or not
if (row[0] =='x' or row[0] == 'o') and (row.count(row[0]) == 4):
return (row[0],'WON')
if (col[0] =='x' or col[0] == 'o') and (col.count(col[0]) == 4):
return (col[0],'WON')
#checking if diagnols have been won or not
if(bs[0][0] == bs[1][1] == bs[2][2] ==bs[3][3]) and (bs[0][0] == 'x' or bs[0][0] == 'o'):
return (bs[0][0],'WON')
if(bs[0][3] == bs[1][2] == bs[2][1] ==bs[3][0]) and (bs[0][3] == 'x' or bs[0][3] == 'o'):
return (bs[0][3],'WON')
if cntx+cnto+cntd <16: #if all blocks have not yet been won or lost or drawn, continue
return ('CONTINUE', '-')
elif cntx+cnto+cntd == 16: #if game is drawn
return ('NONE', 'DRAW')
def check_valid_move(self, old_move, new_move):
#checks if a move is valid or not given the last move
if (len(old_move) != 2) or (len(new_move) != 2):
return False
if (type(old_move[0]) is not int) or (type(old_move[1]) is not int) or (type(new_move[0]) is not int) or (type(new_move[1]) is not int):
return False
if (old_move != (-1,-1)) and (old_move[0] < 0 or old_move[0] > 16 or old_move[1] < 0 or old_move[1] > 16):
return False
cells = self.find_valid_move_cells(old_move)
return new_move in cells # returns 1 if new_move is in cells else returns 0
def update(self, old_move, new_move, ply):
#updating the game board and block status as per the move that has been passed in the arguements
if(self.check_valid_move(old_move, new_move)) == False:
return 'UNSUCCESSFUL'
self.board_status[new_move[0]][new_move[1]] = ply # ply is only X or O
x = new_move[0]/4
y = new_move[1]/4
fl = 0
bs = self.board_status
#checking if a block has been won or drawn or not after the current move
for i in range(4):
#checking for horizontal pattern(i'th row)
if (bs[4*x+i][4*y] == bs[4*x+i][4*y+1] == bs[4*x+i][4*y+2] == bs[4*x+i][4*y+3]) and (bs[4*x+i][4*y] == ply):
self.block_status[x][y] = ply
return 'SUCCESSFUL'
#checking for vertical pattern(i'th column)
if (bs[4*x][4*y+i] == bs[4*x+1][4*y+i] == bs[4*x+2][4*y+i] == bs[4*x+3][4*y+i]) and (bs[4*x][4*y+i] == ply):
self.block_status[x][y] = ply
return 'SUCCESSFUL'
#checking for diagnol pattern
if (bs[4*x][4*y] == bs[4*x+1][4*y+1] == bs[4*x+2][4*y+2] == bs[4*x+3][4*y+3]) and (bs[4*x][4*y] == ply):
self.block_status[x][y] = ply
return 'SUCCESSFUL'
if (bs[4*x+3][4*y] == bs[4*x+2][4*y+1] == bs[4*x+1][4*y+2] == bs[4*x][4*y+3]) and (bs[4*x+3][4*y] == ply):
self.block_status[x][y] = ply
return 'SUCCESSFUL'
#checking if a block has any more cells left or has it been drawn
for i in range(4):
for j in range(4):
if bs[4*x+i][4*y+j] =='-':
return 'SUCCESSFUL' # return successful, just so that it doesn't progrss downwards in the code anymore
self.block_status[x][y] = 'd'
return 'SUCCESSFUL'
def gameplay(obj1, obj2): #game simulator
game_board = Board()
fl1 = 'x'
fl2 = 'o'
old_move = (-1,-1)
WINNER = ''
MESSAGE = ''
TIME = 15 # re initialize to 15
pts1 = 0
pts2 = 0
game_board.print_board()
signal.signal(signal.SIGALRM, handler)
while(1):
#player 1 turn
temp_board_status = copy.deepcopy(game_board.board_status) # entire copy of board status
temp_block_status = copy.deepcopy(game_board.block_status) # entire copy of block status
signal.alarm(TIME)
try: #try to get player 1's move
p1_move = obj1.move(game_board, old_move, fl1)
print "Player 1 move is ",p1_move
except TimedOutExc: #timeout error
WINNER = 'P2'
MESSAGE = 'TIME OUT'
pts2 = 16
break
except Exception as e:
WINNER = 'P2'
MESSAGE = 'INVALID MOVE'
pts2 = 16
break
signal.alarm(0)
#check if board is not modified(the other player hacked the board and plagiarised it) and move returned is valid
if (game_board.block_status != temp_block_status) or (game_board.board_status != temp_board_status):
WINNER = 'P2'
MESSAGE = 'MODIFIED THE BOARD'
pts2 = 16
break
if game_board.update(old_move, p1_move, fl1) == 'UNSUCCESSFUL':
WINNER = 'P2'
MESSAGE = 'INVALID MOVE'
pts2 = 16
break
status = game_board.find_terminal_state() #find if the game has ended and if yes, find the winner
print status
if status[1] == 'WON': #if the game has ended after a player1 move, player 1 would win
pts1 = 16
WINNER = 'P1'
MESSAGE = 'WON'
break
elif status[1] == 'DRAW': #in case of a draw, each player gets points equal to the number of blocks won
WINNER = 'NONE'
MESSAGE = 'DRAW'
break
old_move = p1_move
game_board.print_board()
#do the same thing for player 2
temp_board_status = copy.deepcopy(game_board.board_status)
temp_block_status = copy.deepcopy(game_board.block_status)
signal.alarm(TIME)
try:
p2_move = obj2.move(game_board, old_move, fl2)
print "Player 2 move is ",p2_move
except TimedOutExc:
print "in112"
WINNER = 'P1'
MESSAGE = 'TIME OUT'
pts1 = 16
break
except Exception as e:
print "in1"
print e
WINNER = 'P1'
MESSAGE = 'INVALID MOVE'
pts1 = 16
break
signal.alarm(0)
if (game_board.block_status != temp_block_status) or (game_board.board_status != temp_board_status):
WINNER = 'P1'
MESSAGE = 'MODIFIED THE BOARD'
pts1 = 16
break
if game_board.update(old_move, p2_move, fl2) == 'UNSUCCESSFUL':
print "in2"
print "in3"
WINNER = 'P1'
MESSAGE = 'INVALID MOVE'
pts1 = 16
break
status = game_board.find_terminal_state() #find if the game has ended and if yes, find the winner
print status
if status[1] == 'WON': #if the game has ended after a player move, player 2 would win
pts2 = 16
WINNER = 'P2'
MESSAGE = 'WON'
break
elif status[1] == 'DRAW':
WINNER = 'NONE'
MESSAGE = 'DRAW'
break
game_board.print_board()
old_move = p2_move
game_board.print_board()
print "Winner:", WINNER
print "Message", MESSAGE
x = 0
d = 0
o = 0
for i in range(4):
for j in range(4):
if game_board.block_status[i][j] == 'x':
x += 1
if game_board.block_status[i][j] == 'o':
o += 1
if game_board.block_status[i][j] == 'd':
d += 1
print 'x:', x, ' o:',o,' d:',d
if MESSAGE == 'DRAW':
pts1 = x
pts2 = o
return (pts1,pts2)
if __name__ == '__main__':
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 = Random_Player()
obj2 = Random_Player()
elif option == '2':
obj2 = Player42()
obj1 = player4()
elif option == '3':
obj1 = Manual_Player()
obj2 = Manual_Player()
else:
print 'Invalid option'
sys.exit(1)
x = gameplay(obj1, obj2)
print "Player 1 points:", x[0]
print "Player 2 points:", x[1]