Esempio n. 1
0
 def __init__(self, sock):
     self.sock = sock
     self.sock.setblocking(False)
     self.game = Game()
     self.message = self.game.start_message()+"\n"+self.game.board_as_string()
     self.done = False
     self.err_flag = False
Esempio n. 2
0
class Opponent(object):
    def __init__(self, sock):
        self.sock = sock
        self.sock.setblocking(False)
        self.game = Game()
        self.message = self.game.start_message()+"\n"+self.game.board_as_string()
        self.done = False
        self.err_flag = False

    def fileno(self):
        # This method makes Opponent objects act like i/o objects
        # which means they can be handled by select.select.
        # quack quack
        return self.sock.fileno()

    def get_message(self):
        try:
            some_string = self.sock.recv(128)  
            print "move received:", some_string
            move = int(some_string)
            return move
        except socket.error:
            print "socket error"
            self.err_flag = True
        except TypeError:
            print "Parse error"
        except ValueError:
            print "No move received"

    def handle_client_move(self):
        assert self.game.player == 'x'
        client_move = self.get_message() 

        if not type(client_move) == int or not self.game.validate_move(client_move):
            print "Invalid move received on socket %d" % self.fileno()
            self.message = "Not valid.  Try again."
        else:
            self.game.make_move(client_move, self.game.player)
            print "Move made on socket "+str(self.fileno())+":\n", self.game.board_as_string()
            self.game.player = 'o'
Esempio n. 3
0
        return human_move  # pass the move back up the stack


if __name__ == '__main__':
    HOST = sys.argv.pop() if len(sys.argv) == 3 else "127.0.0.1"
    PORT = 1060
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen(1)

    while True:
        print "Listening at", s.getsockname()
        sc, sockname = s.accept()
        print "Accepted connection from", sockname
        print "Socket connects", sc.getsockname(), "and", sc.getpeername()
        g = Game()  # start with human move
        while not g.game_over():
            remote_move = get_valid_remote_move(sc, g)
            g.make_human_move(remote_move)
            if g.game_over():
                end_message = g.end_message(g.winner_if_any())
                sc.sendall(end_message)
                sc.close()
            else:
                g.minimax(g.player)
                g.player = g.next_turn(g.player)
                board_as_string = g.send_as_string()
                sc.sendall(board_as_string)