예제 #1
0
def SelectRoomSlot(tcp_sock):
    global room_name, room_window, window
    room_name = room_window.cmb_rooms.currentText()
    window.lbl_room.setText(str("Комната: "+room_name))
    if not room_name:
        QtGui.QMessageBox.about(window, "Информация", "Не выбрана комната.")
    else:
        if not is_main:
            WriteData(tcp_sock, room_name)
            # create tcp-socket-listener-thread
            tcp_sock.setblocking(True)
            thread_listener = threading.Thread(target=ListenTCPSock, args=(tcp_sock,window))
            thread_listener.start()
            LOGGER.print_test("Thread-listener started.")
        else:
            LOGGER.log("I main client", DEF.LOG_FILENAME)
            # Create broadcast-thread
            thread_broadcast = threading.Thread(target=MainServerBroadcast, args=(DEF.SERVER_MESSAGE, DEF.UDP_PORT, udp_sock))
            thread_broadcast.start()
            LOGGER.print_test("Thread-broadcast started.")
            # Create epoll-listener-thread
            tcp_sock.close()
            tcp_sock = CreateTCPSockServer(DEF.TCP_PORT)
            thread_epoll = threading.Thread(target=StartingEpoll, args=(tcp_sock, epoll_sock, window))
            thread_epoll.start()
            LOGGER.print_test("Thread-epoll started.")

        room_window.close()
예제 #2
0
def draw_one_tile(tile, location, background_colour=None, orientation=None):
    location_on_map = Vector(
        location.x * settings.tile_size.width,
        location.y * settings.tile_size.height
    )

    worker = None
    if tile:
        log('draw_one_tile, orientation {}, {}'.format(orientation, tile))
        workers = g.components.filter(on_tile=tile)
        if workers:
            worker = workers[0]
            worker_offset = worker_space_offset(worker.location.space)

    for is_dark, offset in (
            (False, settings.light_map_location),
            (True, settings.dark_map_location)
    ):
        location = location_on_map + offset
        if tile:
            if orientation is None:
                orientation = tile.orientation
            # TODO: Tidy this up
            g.images.images[tile.image_name(is_dark)].draw(
                location=location, orientation=orientation
            )

        if worker and worker.alive is not is_dark:
            draw_circle(location + worker_offset, settings.worker_circle_size, worker.player.colour_code)
예제 #3
0
def get_scores():
    log('Calculating scores')
    workers_scored = set()
    result = {player: player.removed_workers_score for player in g.players}
    for worker in g.components.filter(klass='worker', placed=True):
        if worker in workers_scored:
            continue

        workers_scored.add(worker)

        if worker.location.space == 'G':
            worker_score = score_graveyard(worker)
            if worker_score == 9:
                worker.retire()
                worker.player.removed_workers_score += 9
            else:
                result[worker.player] += worker_score
            continue

        if worker.location.tile.edges[worker.location.space] == 'R':
            workers_on_road = score_road(worker, result)
            for worker_on_road in workers_on_road:
                workers_scored.add(worker_on_road)
            continue

        if worker.location.tile.edges[worker.location.space] == 'C':
            workers_in_city = score_city(worker, result)
            for worker_in_city in workers_in_city:
                workers_scored.add(worker_in_city)
            continue

    return result
예제 #4
0
def draw_next_tile():

    if not g.turn_state.next_tile:
        return

    log('Next tile {}'.format(g.turn_state.next_tile))
    if g.turn_state.next_tile.location:
        orientation = g.turn_state.next_tile_orientation
        draw_one_tile(g.turn_state.next_tile, g.turn_state.next_tile.location, orientation=orientation)

        if g.turn_state.next_worker_space is not None:
            if g.turn_state.next_worker_space == 'G':
                space = g.turn_state.next_worker_space
            else:
                space = (g.turn_state.next_worker_space + g.turn_state.next_tile_orientation) % 4
            worker_offset = worker_space_offset(space)
            location = map_location_to_screen_location(g.turn_state.next_tile.location, not g.turn_state.next_worker.alive) \
                            + worker_offset

            rect = location.to_rect(settings.worker_space_size)
            draw_rectangle(rect, background_colour=g.current_player.colour_code, width=0)

    else:
        g.images.images[g.turn_state.next_tile.image_name(False)].draw(
            location=settings.next_tile_location, orientation=0
        )
예제 #5
0
 def next_tile_orientation(self):
     if not self.next_tile.location:
         log('Tile not placed yet, neutral orientation')
     else:
         log('Next tile, orientation: '.format(
             self.possible_orientations[self.next_tile_orientation_id]))
     return self.possible_orientations[
         self.next_tile_orientation_id] if self.next_tile.location else 0
예제 #6
0
    def fits(self, location):
        for edge in range(4):
            if g.map[location].edges[
                    edge] and g.map[location].edges[edge] != self.edges[edge]:
                log('{}, {} fit in {} at {}? No'.format(
                    self.id, self.edges, g.map[location].edges, location))
                return False

        log('{}, {} fit in {} at {}? Yes'.format(self.id, self.edges,
                                                 g.map[location].edges,
                                                 location))
        return True
예제 #7
0
def SendBroadcast(msg, _port, fd):
    """
    Make one broadcast message with text msg
    """
    try:
        fd.sendto(msg.encode('utf-8'), ("255.255.255.255", _port))
    except error as e:
        LOGGER.log("Sendto failed. Function:" + SendBroadcast.__name__ + "\nError:" + str(e), DEF.LOG_FILENAME)
        if "Errno 101" in str(e):
            global window
            QtGui.QMessageBox.about(window, "Информация", "Нет соединения с интернетом.")
            sys.exit(-1)
예제 #8
0
def CreateTCPSockClient(_port):
    """
    This function creates TCP socket for client.
    """
    try:
        sock = socket(AF_INET, SOCK_STREAM)

    except error as e:
        LOGGER.log("Can't' create socket. Function:" + CreateTCPSockClient().__name__+"\nError:" + str(e), DEF.LOG_FILENAME)
        sys.exit(-1)

    return sock
예제 #9
0
 def orientated_copy(self, orientation):
     tile = Tile(id=self.id,
                 starting=self.starting,
                 roads=rotate(self.roads, orientation),
                 cities=rotate(self.cities, orientation),
                 graveyard=self.graveyard)
     if self.roads:
         log('Rotated roads {} by {} to get {}'.format(
             self.roads, orientation, rotate(self.roads, orientation)))
     if self.cities:
         log('Rotated cities {} by {} to get {}'.format(
             self.cities, orientation, rotate(self.cities, orientation)))
     tile.orientation = orientation
     return tile
예제 #10
0
def CreateTCPSockServer(_port):
    """
    This function creates TCP socket for server.
    """
    try:
        sock = socket(AF_INET, SOCK_STREAM)
        sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        sock.bind(("", _port))
        sock.listen(DEF.MAX_LISTEN_COUNT)

    except error as e:
        LOGGER.log("Can't create socket. Function:" + CreateTCPSockServer.__name__ + "\nError:" + str(e), DEF.LOG_FILENAME)
        sys.exit(-1)

    return sock
예제 #11
0
def CreateUDPSock():
    """
    This function creates UDP socket.
    """
    try:
        sock = socket(AF_INET, SOCK_DGRAM)
        #sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
        sock.setsockopt(SOL_SOCKET, SO_BROADCAST,1)

    except error as e:
        LOGGER.log("Can not create socket. Function:" + CreateUDPSock.__name__+"\nError:" + str(e), DEF.LOG_FILENAME)
        sys.exit(-1)

    return sock
예제 #12
0
def OnDeadProgram():
    """
    It is destructor for program.
    """
    try:
        global connections, tcp_sock, udp_sock, epoll_sock, server_addr, rooms
        udp_sock.close()
        tcp_sock.shutdown(1)
        tcp_sock.close()
        epoll_sock.close()
        del connections, rooms, udp_sock, tcp_sock, epoll_sock
        LOGGER.log("Bye-bye...", DEF.LOG_FILENAME)
        LOGGER.print_test("Cleaning finished.")
        exit(0)
    except error as e:
        LOGGER.log("Warning in function " + OnDeadProgram.__name__+"\nWarning:"+str(e),DEF.LOG_FILENAME)
예제 #13
0
def WriteData(fd, msg):
    """
    Write data into socket fd. If server is dead, functions returns False,
    else - True.
    """
    try:
        msg = CheckString(msg)
        while len(msg)>0:
            written = fd.send(msg.encode('utf-8'))
            msg = msg[written:]
    except error as e:
        LOGGER.print_test("Can't send data to server")
        LOGGER.log("Can't send data to server'. Function:" + WriteData.__name__ + "\nError:" + str(e), DEF.LOG_FILENAME)
        return False

    return True
예제 #14
0
    def __init__(self,config=None,use_dicosverer=False,target=None,modules=[],assume=[],inject=[]):
        print('--> building class OsaQyery')
        simple_logger.log()
        simple_logger.logger.setLevel(logging.ERROR)

        self.target = target
        self.modules = modules
        self.assume = assume
        self.inject = inject


        if use_dicosverer == True:
            try:
                c = discover_docker.DDOSAWorkerContainer()

                self.data_server_url = c.data_server_url
                self.dataserver_cache = c.dataserver_cache
                print("===>managed to read from docker:")



            except Exception as e:
                raise RuntimeError("failed to read from docker", e)

        elif config is not None:
            try:
                # config=ConfigEnv.from_conf_file(config_file)
                self.data_server_url = config.dataserver_url
                self.dataserver_cache = config.dataserver_cache

            except Exception as e:
                #print(e)

                print ("ERROR->")
                e.display()
                raise RuntimeError("failed to use config ", e)

        else:
            self.config()





        print("dataserver_cache:", self.data_server_url)
        print("dataserver_cache:", self.dataserver_cache)
        print('--> done')
예제 #15
0
def ListenUdpPort(_port):
    """
    This funcion listen port _port and return old post.
    """
    try:
        sock = CreateUDPSock()
        sock.bind(("", _port))
        sock.settimeout(DEF.BROADCAST_TIMEOUT)

        (msg, addr) = sock.recvfrom(1024)
        lst = [msg.decode('utf-8'), addr]
        sock.close()

        return lst

    except error as e:
        LOGGER.log("Warning in function " + ListenUdpPort.__name__ + ".\nWarning:" + str(e), DEF.LOG_FILENAME)
예제 #16
0
    def possible_worker_spaces(self):
        result = []
        tile = self.next_tile
        # tile.place(tile.location, self.next_tile_orientation)

        if tile.graveyard:
            result.append('G')

        for edge in range(4):
            if not tile.edges[edge] or tile.edges[edge] is 'B':
                continue
            # if worker_space_is_valid(tile, edge, self.current_player):
            #     log('Can place on |{}| at {}'.format(tile.edges[edge], edge))
            result.append(edge)

        # tile.unplace()

        log('Worker spaces: {}'.format(result))
        return result
예제 #17
0
def GetListOfRooms(fd):
    """
    This function for client.
    Reading list available rooms from fd.
    """
    try:
        reading_data = ReadData(fd)
        lst = []
        if reading_data == DEF.ROOMS_LIST_SEND_MESSAGE:
            while True:
                reading_data = ReadData(fd)
                if not reading_data or reading_data == DEF.ROOMS_LIST_SEND_MESSAGE+"-END":
                    break
                else:
                    lst.append(reading_data)

        return lst

    except error as e:
        LOGGER.log("Error in function" + GetListOfRooms.__name__, "\nError:"+str(e), DEF.LOG_FILENAME)
예제 #18
0
    def unplace(self):
        location = self.location
        orientation = self.orientation

        g.map[location].edges = {e: '' for e in range(4)}
        for l in location.neighbours:
            g.map[l].has_neighbours -= 1

        not_blank = []

        for cities in self.cities:
            for c in cities:
                not_blank.append(c)
                l = g.map[location].neighbour_at_edge(c)
                if l and not g.map[l].edges[flip_edge(c)]:
                    g.map[l].edges[flip_edge(c)] = ''

        for roads in self.roads:
            for r in roads:
                not_blank.append(r)
                l = g.map[location].neighbour_at_edge(r)
                if l and g.map[l].tile is None and not g.map[l].edges[
                        flip_edge(r)]:
                    g.map[l].edges[flip_edge(r)] = ''

        for s in range(4):
            if s not in not_blank:
                l = g.map[location].neighbour_at_edge(s)
                if l and g.map[l].tile is None and not g.map[l].edges[
                        flip_edge(s)]:
                    g.map[l].edges[flip_edge(s)] = ''

        self.cities = rotate(self.cities, -orientation)
        self.roads = rotate(self.roads, -orientation)
        self.edges = get_edges(self.roads, self.cities)

        # self.location = None
        # self.orientation = 0
        g.map[location].tile = None

        log('Just unplaced {}'.format(self))
예제 #19
0
 def take_move(self):
     locations = g.map.available_locations()
     possible_fits = []
     while not possible_fits:
         next_tile = draw_random_tile()
         possible_fits = suitable_locations_and_orientations(next_tile)
     next_location = choice(possible_fits)
     log("Placing tile {}, orientation {} at {}".format(
         next_tile.id, next_location[1], next_location[0]))
     next_tile.place(next_location[0], next_location[1])
     # if next_tile.worker_spaces:
     #     next_worker = get_worker(self.player)
     #     if next_worker:
     #         worker_space = choice(next_tile.worker_spaces)
     #         # if worker_space != 'G':
     #         #     worker_space = (worker_space + next_location[1]) % 4
     #         next_worker.place(next_tile, worker_space)
     #         log("Placing worker {} at {}".format(next_worker, worker_space))
     draw_all()
     sleep(1)
     g.turn_state.next_player()
예제 #20
0
def ListenTCPSock(fd, window):
    """
    This function listen tcp socket fd and return old post.
    """
    global tcp_sock, user_exit, udp_sock
    while not user_exit:
        reading_data = ReadData(fd)

        if reading_data:
            CheckBuf(reading_data)
        else:
            if not user_exit:
                LOGGER.log("Server is dead. Function:"+ListenTCPSock.__name__, DEF.LOG_FILENAME)
                LOGGER.print_test("Server is dead.")
            break

    # if here - server is died
    if not user_exit:
        CaptureOfPower(DEF.UDP_PORT, udp_sock, window)
    else:
        LOGGER.print_test("Thread-listener stopped.")
예제 #21
0
    def place(self, location, orientation):
        self.cities = rotate(self.cities, orientation)
        self.roads = rotate(self.roads, orientation)
        self.edges = get_edges(self.roads, self.cities)

        g.map[location].edges = {e: '' for e in range(4)}
        g.map[location].tile = self
        self.location = location
        self.orientation = orientation
        for l in location.neighbours:
            g.map[l].has_neighbours += 1

        not_blank = []

        log('Just placed {}'.format(self))

        for cities in self.cities:
            for c in cities:
                not_blank.append(c)
                g.map[location].edges[c] = 'C'
                l = g.map[location].neighbour_at_edge(c)
                if l and not g.map[l].edges[flip_edge(c)]:
                    g.map[l].edges[flip_edge(c)] = 'C'

        for roads in self.roads:
            for r in roads:
                not_blank.append(r)
                g.map[location].edges[r] = 'R'
                l = g.map[location].neighbour_at_edge(r)
                if l and g.map[l].tile is None and not g.map[l].edges[
                        flip_edge(r)]:
                    g.map[l].edges[flip_edge(r)] = 'R'

        for s in range(4):
            if s not in not_blank:
                l = g.map[location].neighbour_at_edge(s)
                if l and g.map[l].tile is None and not g.map[l].edges[
                        flip_edge(s)]:
                    g.map[l].edges[flip_edge(s)] = 'B'
예제 #22
0
def CheckWhoMainServer(_port, fd):
    """
    If main client is there then connect to them.
    Else it will be main client.
    """
    try:
        global server_addr, tcp_sock, room_name
        stop_at = time.time() + DEF.BROADCAST_TIMEOUT
        while time.time() < stop_at:
            SendBroadcast(DEF.MESSAGE_FROM_RUNNING, _port, fd)
            lst = ListenUdpPort(_port)
            if lst and lst[0]==DEF.SERVER_MESSAGE:
                server_addr = lst[1]
                tcp_sock.connect((server_addr[0], DEF.TCP_PORT))
                rooms_lst = GetListOfRooms(tcp_sock) # this function get list of rooms from server
                AddToRoomWindow(rooms_lst)
                return False

    except error as e:
        LOGGER.log("Can't connect socket. Function:" + CheckWhoMainServer.__name__+"\nError:" + str(e), DEF.LOG_FILENAME)
        sys.exit(-1)

    return True
예제 #23
0
def ReadData(fd):
    """
    Read data from socket fd.
    """
    global static_str
    try:
        result = ""
        index = -1
        if static_str:
            index = GetEndOfMessage(static_str)
            if index != -1:
                result = static_str[:index].replace('\0\0','\0')
                static_str = static_str[index+1:]
                return result
            else:
                result = static_str

        stop = False
        while not stop:
            tmp_str = fd.recv(256).decode('utf-8')
            if not tmp_str:
                stop = True
            else:
                index = GetEndOfMessage(tmp_str)
                if index != -1:
                    result += tmp_str[:index].replace('\0\0','\0')
                    static_str = tmp_str[index+1:]
                    stop = True
                else:
                    result += tmp_str.replace('\0\0', '\0')

    except error as e:
        LOGGER.log("Can't read data from server. Function:" + ReadData.__name__ + "\nError:" + str(e), DEF.LOG_FILENAME)
        return ""

    return result
예제 #24
0
def MassMailing(message, room):
    """
    This function sends message for all clients.
    """
    if not message:
        LOGGER.log ("Message is empty. Function:" +MassMailing.__name__, DEF.LOG_FILENAME)
    else:
        global connections, rooms
        for key in connections.keys():
            if room == rooms[key]:
                if not WriteData(connections[key], message):
                    LOGGER.log("Bad WriteData into sock with fd "+str(key), DEF.LOG_FILENAME)

        LOGGER.log ("Sending message complete. Function:" + MassMailing.__name__, DEF.LOG_FILENAME)
예제 #25
0
def StartingEpoll(server, epoll_sock, window):
    """
    This function creates epoll and monitoring all socket in epoll +
    adds new sockets + removes dead sockets.
    """
    epoll_sock.register(server.fileno(), select.EPOLLIN)

    try:
        global connections, is_main, rooms, room_name
        rooms[server.fileno()] = room_name
        while is_main:
            if not epoll_sock:
                break
            events = epoll_sock.poll(1)
            for fileno, event in events:
                if fileno == server.fileno():
                    conn, addr = server.accept()
                    conn.setblocking(True)
                    epoll_sock.register(conn.fileno(), select.EPOLLIN)
                    connections[conn.fileno()] = conn
                    # send list of rooms to client
                    SendListRooms(rooms, conn)
                    # reading room-name here
                    reading_data = ReadData(conn)
                    rooms[conn.fileno()] = reading_data.strip()
                    LOGGER.log("Add client. Function:"+StartingEpoll.__name__, DEF.LOG_FILENAME)

                elif event & select.EPOLLIN:
                    reading_data = ReadData(connections[fileno])
                    if not reading_data:
                        epoll_sock.unregister(fileno)
                        if fileno in list(connections.keys()):
                            LOGGER.print_test("Cleaning after disconnecting.")
                            connections[fileno].close()
                            del connections[fileno]
                        if fileno in list(rooms.keys()):
                            del rooms[fileno]
                        LOGGER.log("One client is disconnected. Function:" + StartingEpoll.__name__, DEF.LOG_FILENAME)
                        continue
                    # if room client and your room is equal
                    if rooms[server.fileno()] == rooms[fileno]:
                        CheckBuf(reading_data)
                    MassMailing(reading_data, rooms[fileno])

    except error as e:
        LOGGER.log("There are errors. Function:" + StartingEpoll.__name__+"\nError:" + str(e), DEF.LOG_FILENAME)
    finally:
        LOGGER.print_test("Thread-epoll stopped.")
예제 #26
0
    connections = {}
    rooms = {}
    server_addr = ()
    udp_sock = CreateUDPSock()
    tcp_sock = CreateTCPSockClient(DEF.TCP_PORT)
    epoll_sock = select.epoll()
    user_exit = False
    date_of_starting = GetStartingTime()
    is_main = False
    room_name = ""
    user_name = ""
    status = DEF.STATUS_FREE
    message_buf = []
    ####################################################################
    try:
        LOGGER.log("Now i kill you!", DEF.LOG_FILENAME)
        os.remove(DEF.LOG_FILENAME)

        # create ui here
        app = QtGui.QApplication(sys.argv)
        tray = QtGui.QSystemTrayIcon(QtGui.QIcon("chat.bmp"), app)
        tray.show()
        window = uic.loadUi("gui.ui") # main window of application
        window.setWindowIcon(QtGui.QIcon("chat.bmp"))
        pixmap = QtGui.QPixmap("status_ok.png")
        status = DEF.STATUS_FREE
        scaledPixmap = pixmap.scaled(window.lbl_color.width(), window.lbl_color.height(), QtCore.Qt.KeepAspectRatio)
        window.lbl_color.setPixmap(scaledPixmap);

        window.edt_chat.setReadOnly(True)
        window.edt_msg.setFocus()
예제 #27
0
 def rotate_next_tile(self):
     old_rotation_id = self.next_tile_orientation_id
     self.next_tile_orientation_id = (self.next_tile_orientation_id +
                                      1) % len(self.possible_orientations)
     log('Rotated from id {} to {}'.format(old_rotation_id,
                                           self.next_tile_orientation_id))
예제 #28
0
    def start_human_move(self):
        log('Started human move')

        self.next_tile, self.possible_fits = self.pick_next()
        self.next_tile_orientation_id = 0
예제 #29
0
def CaptureOfPower(_port, fd, window):
    """
    Client will be call this function if server died.
    fd - udp socket. _port - udp port.
    """
    try:
        stop_at = time.time() + DEF.BROADCAST_TIMEOUT
        global date_of_starting, tcp_sock, epoll_sock, is_main, server_addr, room_name
        tcp_sock.shutdown(1)
        tcp_sock.close()
        msg = DEF.CANDIDATE_MESSAGE+"MY_TIME="+date_of_starting
        is_not_main = False
        count_trying = DEF.MAX_TRYING_COUNT

        while count_trying > 0:
            # Trying to become the main client
            while time.time() < stop_at:
                SendBroadcast(msg, _port, fd)
                lst = ListenUdpPort(_port)
                if lst and DEF.CANDIDATE_MESSAGE in lst[0]:
                        date = GetDateStructFromMessage(lst[0], "MY_TIME=", "#")
                        # if it is younger
                        if not CompareDates(date_of_starting, date):
                            LOGGER.print_test("Main client found.")
                            is_not_main = True
                            break
            # expect the main client
            if is_not_main:
                count_trying -= 1
                stop_at = time.time() + DEF.BROADCAST_TIMEOUT
                while time.time() < stop_at:
                    lst = ListenUdpPort(_port)
                    if lst and lst[0] == DEF.SERVER_MESSAGE:
                        server_addr = lst[1]
                        tcp_sock = CreateTCPSockClient(DEF.TCP_PORT)
                        tcp_sock.setblocking(True)
                        tcp_sock.connect((server_addr[0], DEF.TCP_PORT))
                        rooms_lst = GetListOfRooms(tcp_sock) # this function get list of rooms from server
                        AddToRoomWindow(rooms_lst)
                        WriteData(tcp_sock, room_name)
                        thread_listener = threading.Thread(target=ListenTCPSock, args=(tcp_sock, window))
                        thread_listener.start()
                        LOGGER.print_test("Thread-listener started.")
                        return False
            else:
                break

        if count_trying <= 0:
            LOGGER.log("Two or more clients have equal data of starting.", DEF.LOG_FILENAME)
            OnDeadProgram()

        # if here - you the main client
        is_main = True
        tcp_sock = CreateTCPSockServer(DEF.TCP_PORT)
        LOGGER.log("I main client", DEF.LOG_FILENAME)
        # Create broadcast-thread
        thread_broadcast = threading.Thread(target=MainServerBroadcast, args=(DEF.SERVER_MESSAGE, _port, fd))
        thread_broadcast.start()
        LOGGER.print_test("Thread-broadcast started.")
        # Create epoll-listener-thread
        thread_epoll = threading.Thread(target=StartingEpoll, args=(tcp_sock, epoll_sock, window))
        thread_epoll.start()
        LOGGER.print_test("Thread-epoll started.")

    except error as e:
        LOGGER.log("Error in function " + CaptureOfPower.__name__ + ".\nError:" + str(e), DEF.LOG_FILENAME)
예제 #30
0
    def __init__(self,
                 config=None,
                 task=None,
                 param_dict=None,
                 instrument=None):
        print('--> building class PolarDispatcher', instrument, config)

        simple_logger.log()
        simple_logger.logger.setLevel(logging.ERROR)

        self.task = task

        self.param_dict = param_dict

        #print ('TEST')
        #for k in instrument.data_server_conf_dict.keys():
        #   print ('dict:',k,instrument.data_server_conf_dict[k ])

        config = DataServerConf(
            data_server_url=instrument.
            data_server_conf_dict['data_server_url'],
            data_server_port=instrument.
            data_server_conf_dict['data_server_port'],
            data_server_remote_cache=instrument.
            data_server_conf_dict['data_server_cache'],
            dispatcher_mnt_point=instrument.
            data_server_conf_dict['dispatcher_mnt_point'],
            dummy_cache=instrument.data_server_conf_dict['dummy_cache'])
        #for v in vars(config):
        #   print('attr:', v, getattr(config, v))

        print('--> config passed to init', config)

        if config is not None:

            pass

        elif instrument is not None and hasattr(instrument,
                                                'data_server_conf_dict'):

            print('--> from data_server_conf_dict')
            try:
                #config = DataServerConf(data_server_url=instrument.data_server_conf_dict['data_server_url'],
                #                        data_server_port=instrument.data_server_conf_dict['data_server_port'])

                config = DataServerConf(
                    data_server_url=instrument.
                    data_server_conf_dict['data_server_url'],
                    data_server_port=instrument.
                    data_server_conf_dict['data_server_port'])
                # data_server_remote_cache=instrument.data_server_conf_dict['data_server_cache'],
                # dispatcher_mnt_point=instrument.data_server_conf_dict['dispatcher_mnt_point'],
                #s dummy_cache=instrument.data_server_conf_dict['dummy_cache'])

                print('config', config)
                for v in vars(config):
                    print('attr:', v, getattr(config, v))

            except Exception as e:
                #    #print(e)

                print("ERROR->")
                raise RuntimeError("failed to use config ", e)

        elif instrument is not None:
            try:
                print('--> plugin_conf_file', plugin_conf_file)
                config = instrument.from_conf_file(plugin_conf_file)

            except Exception as e:
                #    #print(e)

                print("ERROR->")
                raise RuntimeError("failed to use config ", e)

        else:

            raise PolarException(
                message='instrument cannot be None',
                debug_message=
                'instrument se to None in PolarDispatcher __init__')

        try:
            _data_server_url = config.data_server_url
            _data_server_port = config.data_server_port

        except Exception as e:
            #    #print(e)

            print("ERROR->")
            raise RuntimeError("failed to use config ", e)

        self.config(_data_server_url, _data_server_port)

        print("data_server_url:", self.data_server_url)
        #print("dataserver_cache:", self.dataserver_cache)
        print("dataserver_port:", self.data_server_port)
        print('--> done')
예제 #31
0
    def __init__(self, config=None, param_dict=None, instrument=None):
        print('--> building class SpiacsDispatcher', instrument, config)

        simple_logger.log()
        simple_logger.logger.setLevel(logging.ERROR)

        self.param_dict = param_dict

        #resp = urlopen("http://isdc.unige.ch/~savchenk/spiacs-online/spiacs.pl",
        #           urlencode({"requeststring": utc, 'submit': "Submit", 'generate': 'ipnlc'})).read()

        config = DataServerConf(
            data_server_url=instrument.
            data_server_conf_dict['data_server_url'],
            data_server_port=instrument.
            data_server_conf_dict['data_server_port'],
            data_server_remote_cache=instrument.
            data_server_conf_dict['data_server_cache'],
            dispatcher_mnt_point=instrument.
            data_server_conf_dict['dispatcher_mnt_point'],
            dummy_cache=instrument.data_server_conf_dict['dummy_cache'])
        #for v in vars(config):
        #   print('attr:', v, getattr(config, v))

        print('--> config passed to init', config)

        if config is not None:

            pass

        elif instrument is not None and hasattr(instrument,
                                                'data_server_conf_dict'):

            print('--> from data_server_conf_dict')
            try:
                #config = DataServerConf(data_server_url=instrument.data_server_conf_dict['data_server_url'],
                #                        data_server_port=instrument.data_server_conf_dict['data_server_port'])

                config = DataServerConf(
                    data_server_url=instrument.
                    data_server_conf_dict['data_server_url'],
                    data_server_port=instrument.
                    data_server_conf_dict['data_server_port'])
                # data_server_remote_cache=instrument.data_server_conf_dict['data_server_cache'],
                # dispatcher_mnt_point=instrument.data_server_conf_dict['dispatcher_mnt_point'],
                #s dummy_cache=instrument.data_server_conf_dict['dummy_cache'])

                print('config', config)
                for v in vars(config):
                    print('attr:', v, getattr(config, v))

            except Exception as e:
                #    #print(e)

                print("ERROR->")
                raise RuntimeError("failed to use config ", e)

        elif instrument is not None:
            try:
                print('--> plugin_conf_file', plugin_conf_file)
                config = instrument.from_conf_file(plugin_conf_file)

            except Exception as e:
                #    #print(e)

                print("ERROR->")
                raise RuntimeError("failed to use config ", e)

        else:

            raise SpiacsException(
                message='instrument cannot be None',
                debug_message=
                'instrument se to None in SpiacsDispatcher __init__')

        try:
            _data_server_url = config.data_server_url
            _data_server_port = config.data_server_port

        except Exception as e:
            #    #print(e)

            print("ERROR->")
            raise RuntimeError("failed to use config ", e)

        self.config(_data_server_url, _data_server_port)

        print("data_server_url:", self.data_server_url)
        #print("dataserver_cache:", self.dataserver_cache)
        print("dataserver_port:", self.data_server_port)
        print('--> done')
예제 #32
0
def find_road_segment(worker_location, backwards=False):
    log('find_road_segment, starting at {}'.format(worker_location))
    # Return a list of WorkerLocation's
    result = []

    # For the first tile we should ignore anything 'before' the starting location
    first_step = True

    # Start from worker_location
    current_location = worker_location

    # Loop until we've hit the end
    while True:
        tile, space = current_location.tile, current_location.space
        log('At {}, {}'.format(tile, space))

        # Find which road the space is on
        # And make a copy of it, so that if we reverse it, it doesn't change the original
        road = [r for r in tile.roads if space in r][0][:]
        log('Which is on road: {}'.format(road))

        # If the road is only 1 long, it means we've reached a start/end segment
        # Add this to the list, then stop
        # For the first tile we still need to check the neighbours - but only in one direction
        if len(road) == 1:
            if first_step:
                if not backwards:
                    # First step, going forwards, we're done
                    log('Road of length 1, first step, going forwards - done')
                    result.append(WorkerLocation(tile, road[0]))
                    return True, result
                else:
                    # First step, going backwards, keep going
                    log('Road of length 1, first step, going backwards so keep going'
                        )
            else:
                log('Road of length 1, not the first step - done')
                result.append(WorkerLocation(tile, road[0]))
                return True, result

        # If necessary, follow the road in reverse
        if first_step:
            # If this is our first step, and we should be going backwards, reverse the road
            if backwards:
                log("First step and backwards, reversing the road")
                road.reverse()
                log("Reversed road: {}".format(road))
        else:
            # If we just came from another tile, make sure the road is orientated correctly,
            # The start of the road should be our current space
            if road[0] != current_location.space:
                log('Entry space not the start of the road, reversing the road'
                    )
                road.reverse()
                log('Reversed road: {}'.format(road))

        # For the first tile we should ignore anything 'before' the starting location
        if first_step:
            i = road.index(current_location.space)
            road = road[i:]
            log('First step, so ignore rest of the road. New road: {}'.format(
                road))
            first_step = False

        # Add all of the road's edges to the results list
        for s in road:
            result.append(WorkerLocation(tile, s))

        # Find the neighbour at the edge at the end of the road
        neighbour_location = g.map[tile.location].neighbour_at_edge(road[-1])
        log('Neighbour location at edge {}: {}'.format(road[-1],
                                                       neighbour_location))

        # If the neighbour is off the map or an empty space
        if neighbour_location is None or not g.map[neighbour_location].tile:
            log('No neighbour found or off the map - done')
            return False, result

        # Move to the neighbour, ready to start again
        current_location = WorkerLocation(g.map[neighbour_location].tile,
                                          flip_edge(road[-1]))
        log('Moved to the neighbour {}'.format(current_location))
예제 #33
0
def find_road_tiles(worker_location):
    log('Getting details for left segment')
    left_segment_complete, left_segment = find_road_segment(
        worker_location, True)
    if left_segment_complete:
        log('left segment done: ')
    else:
        log('left segment in progress')

    for l in left_segment:
        log(l)

    log('')

    log('Getting details for right segment')
    right_segment_complete, right_segment = find_road_segment(
        worker_location, False)
    if right_segment_complete:
        log('right segment done: ')
    else:
        log('right segment in progress')

    for l in right_segment:
        log(l)

    log('')

    # There may be an overlap between the left and right segment, but that doesn't matter in the counting
    return left_segment_complete and right_segment_complete, left_segment + right_segment
예제 #34
0
def draw_random_tile():
    log('Draw random tile from {} possible tiles'.format(
        len(g.components.filter(klass='tile', placed=False))))
    return choice(g.components.filter(klass='tile', placed=False)) if settings.random \
        else g.components.filter(klass='tile', placed=False)[0]
예제 #35
0
def score_feature_tiles(feature_complete, feature_locations, scores):
    log('Feature found:')
    tiles, workers = set(), set()
    for l in feature_locations:
        tiles.add(l.tile)
        for worker in g.components.filter(on_tile=l.tile):
            if worker.location.space == l.space:
                workers.add(worker)
        log(l)
    log('')

    # TODO: Use a Counter for this?
    workers_by_player = defaultdict(int)
    for worker in workers:
        workers_by_player[worker.player] += 1

    max_workers_for_player = max(c for c in workers_by_player.values())
    log('Highest number of workers: {}'.format(max_workers_for_player))
    score = 2 * len(tiles) if feature_complete else len(tiles)
    for player, workers_for_player in workers_by_player.items():
        if workers_for_player != max_workers_for_player:
            continue

        log('{} points for player {}'.format(score, player))
        if feature_complete:
            player.removed_workers_score += score
        else:
            scores[player] += score

    if feature_complete:
        log('Feature complete, returning all workers')
        for worker in workers:
            worker.retire()

    return workers