Commits

Anonymous committed b8e738a

check for winning moves and block or win

Comments (0)

Files changed (1)

tic-tac-toe/server/tttserv.py

 class EchoWebSocket(tornado.websocket.WebSocketHandler):
     def open(self):
         logging.info('Connection established from %s' % self.request.remote_ip)
-        self.receive_message(self.on_message)
 
     def on_message(self, message):
         logging.info('Message received: %s' % message)
         new_board = json.loads(self.response.body)
         self.failIf(new_board == body)
 
+#given a row # return all of the index into elements in the row
+def indexes_for_row(i):
+    return ((i,0),(i,1),(i,2))
+
+#given a col # return all of the index into elements in the col
+def indexes_for_col(i):
+    return ((0,i),(1,i),(2,i))
+
+def diagnols():
+    return (((0,0),(1,1),(2,2)),((0,2),(1,1),(2,0)))
+
+def other_player(player):
+    if player == -1:
+        return 1
+    elif player == 1:
+        return -1
+    else:
+        raise Exception("Unknown Player")
+
+def winning_move(board, player):
+    #two in a row
+    for i in range(len(board)):
+        row = [board[r][c] for r,c in indexes_for_row(i)]
+        for r,c in indexes_for_row(i):
+            if board[r][c] == 0 and row.count(player) == len(board)-1:
+                return (r,c)
+    #two in a column
+    for i in range(len(board[0])):
+        col = [board[r][c] for r,c in indexes_for_col(i)]
+        for r,c in indexes_for_col(i):
+            if board[r][c] == 0 and col.count(player) == len(board[0])-1:
+                return (r,c)
+    #two in a diagnol
+    for d in diagnols():
+        diag = [board[r][c] for r,c in d]
+        for r,c in d:
+            if board[r][c] == 0 and diag.count(player) == len(diag)-1:
+                return (r,c)
+    return None
+
 def move(board):
-    import random
-    while True:
-        row = random.choice(range(len(board)))
-        col = random.choice(range(len(board[0])))
-        if board[row][col] not in (-1, 1):
-            board[row][col] = -1
-            return board
-    # new_options = [-1,0,1]
-    # new_options.remove(board[row][col])
-    # board[row][col] = -1
+    #can win?
+    if winning_move(board, -1):
+        r,c = winning_move(board, -1)
+        board[r][c] = -1
+        return board
+    #can block a win?
+    if winning_move(board, 1):
+        r,c = winning_move(board, 1)
+        board[r][c] = -1
+        return board
     return board
 
 class MainHandler(tornado.web.RequestHandler):
     http_server.listen(options.port)
 
     if options.test:
-        sys.argv.remove('--test')
+        sys.argv.remove('--test') #don't mess with unittest
         unittest.main()
     else:
         tornado.ioloop.IOLoop.instance().start()