Пример #1
0
    def _process_request(self, msg):
        print("msg.cmd:  ", msg.cmd)
        # cadastra o S.S
        if msg.cmd == Commands.LOGIN:
            if self.jogo.registra_jogador(msg.address, msg.data):
                print(msg.data)
                info = {'status': 200, 'info': 'logado'}
                self._send_status(info, msg.address)
                print("Login de ", msg.data, " efetuado com sucesso")
            else:
                info = {'status': 400, 'info': 'nao foi possivel logar'}
                self._send_status(info, msg.address)

        # autoriza ou nao o movimento de um jogador
        elif msg.cmd == Commands.MOVE_TO:
            if self.jogo.move_jogador(msg.address, msg.data):
                # info = {'status': 200, 'info': 'OK'}
                # self._send_status(info, msg.address)
                self._update_map()
            else:
                info = {'status': 400, 'info': 'posicao invalida ou ja ocupada'}
                self._send_status(info, msg.address)

        # valida ou nao uma caca, caso seja validada, envia a todos a nova lista de cacas
        # atualiza placar tb
        elif msg.cmd == Commands.GET_FLAG:
            # self._process_flag(msg)
            self._process_flag_thread(msg)

        elif msg.cmd == Commands.GET_IP:
            ip = self.jogo.get_player_ip(msg.data)
            rep = Message(cmd=Commands.GET_IP, data=ip)
            self._router_socket.send_multipart([msg.address, rep.serialize()])
        else:
            pass
Пример #2
0
 def _update_flags(self):
     # atualiza as cacas
     msg = Message(cmd=Commands.UPDATE_FLAGS, data=self.jogo.lista_de_cacas)
     self._publish_socket.send(msg.serialize())
     if self.jogo.lista_de_cacas:
         print("Bandeiras ", self.jogo.lista_de_cacas)
     else:
         print("\n\n\n FIM DE JOGO \n\n\n")
Пример #3
0
 def set_mode(self, mode):
     """Manual = TRUE
        Automatico = False """
     self.jogo.manual = mode
     msg = Message(cmd=Commands.MODE, data=mode)
     self._publish_socket.send(msg.serialize())
     if mode: print("modo manual")
     else: print("modo automatico")
Пример #4
0
 def get_flag(self, coord):
     """ Envia mensagem que obteve uma bandeira """
     req = Message(cmd=Commands.GET_FLAG, data=coord)
     self.dealer_socket.send(req.serialize())
     if self.supervisor.jogo.manual:
         Thread(target=self._wait_flag_status, daemon=False).start()
     else:
         self._wait_flag_status()
Пример #5
0
 def direita(self):
     self._mover(dir=Robo.RIGHT)
     self.current_pos = int(
         self.current_pos[0]), int(self.current_pos[1]) + 1
     print(self.current_pos)
     if not self.manual:
         msg = Message(cmd=Mover.DIREITA)
         self.connection.send(msg.serialize())
         time.sleep(Automatico.SLEEP_TIME)
Пример #6
0
 def esquerda(self):
     self._mover(dir=Robo.LEFT)
     self.current_pos = int(
         self.current_pos[0]), int(self.current_pos[1]) - 1
     print(self.current_pos)
     if not self.manual:
         msg = Message(cmd=Mover.ESQUERDA)
         self.connection.send(msg.serialize())
         time.sleep(Automatico.SLEEP_TIME)
Пример #7
0
 def frente(self):
     self._mover(dir=Robo.FRONT)
     self.current_pos = int(self.current_pos[0]) + 1, int(
         self.current_pos[1])
     print(self.current_pos)
     if not self.manual:
         msg = Message(cmd=Mover.FRENTE)
         self.connection.send(msg.serialize())
         time.sleep(Automatico.SLEEP_TIME)
Пример #8
0
    def _connect_to_supervisor(self, ip):
        # conecta ao respectivo S.S
        self._dealer_socket = self.context.socket(zmq.DEALER)
        self._dealer_socket.connect("tcp://%s:%d" %
                                    (ip, Supervisor.SUPERVISOR_PORT))

        # envia uma mensagem pro ss (so pra testar msm)
        msg = Message(cmd=Commands.CONNECT_TO_SS)
        self._dealer_socket.send(msg.serialize())
Пример #9
0
 def tras(self):
     self._mover(dir=Robo.BACK)
     self.current_pos = int(self.current_pos[0]) - 1, int(
         self.current_pos[1])
     print(self.current_pos)
     if not self.manual:
         msg = Message(cmd=Mover.TRAS)
         self.connection.send(msg.serialize())
         time.sleep(Automatico.SLEEP_TIME)
Пример #10
0
    def stop_game(self):
        """Termina a partida, imprime o placar, informa aos supervisores o fim da mesma """
        msg = Message(cmd=Commands.STOP)
        self._publish_socket.send(msg.serialize())
        placar = self.jogo.stop()
        print("o jogo terminou")
        for player in placar:
            print("o jogador ", player, " obteve ", placar[player])

        self.jogo_started = False
Пример #11
0
 def _sorteia_cacas(self):
     # Sorteia e envia as bandeiras
     self.cacas = self.jogo.sorteia_cacas()
     print(self.cacas)
     ##msg = Message(cmd=Commands.MODE, data=mode)
     #self._publish_socket.send(msg.serialize())
     #self.cacas = [(0,1),(1,2),(2,3),(3,4),(1,1)]
     msg = Message(cmd=Commands.START, data=self.cacas)
     print("Bandeiras: ", self.cacas)
     self._publish_socket.send(msg.serialize())
Пример #12
0
 def move(self, coord):
     """Envia ao robo a ordem para se mover para coord"""
     info = {
         "status": 200,
         "data": coord
     }
     msg = Message(cmd=Commands.MOVE_TO, data=info)
     self.router_socket.send_multipart([self.robot_address, msg.serialize()])
     self.current_pos = coord
     print("as coord sao", self.current_pos)
Пример #13
0
 def login(self):
     '''Metodo  para o Login no jogo, envia a ID do robo'''
     dados = {
         Commands.ID: self.id,
         Commands.IP: self.my_ip,
         Commands.INITIAL_POS: self.supervisor.current_pos
     }  # Commands.ID = string 'id', Commands.IP = 'ip', Commands.INITIAL_POS = 'initial_pos'
     req = Message(cmd=Commands.LOGIN, data=dados)
     self.dealer_socket.send(req.serialize())
     self._read_rep()
Пример #14
0
 def direita(self):
     try:
         self.motor.direita()
     except Exception as e:
         pass
     self.current_pos = int(self.current_pos[0]), int(self.current_pos[1]) + 1
     print(self.current_pos)
     if not self.manual:
         msg = Message(cmd=Mover.DIREITA)
         self.connection.send(msg.serialize())
         time.sleep(Automatico.SLEEP_TIME)
Пример #15
0
 def esquerda(self):
     try:
         self.motor.esquerda()
     except Exception as e:
         pass
     self.current_pos = int(self.current_pos[0]), int(self.current_pos[1]) - 1
     print(self.current_pos)
     if not self.manual:
         msg = Message(cmd=Mover.ESQUERDA)
         self.connection.send(msg.serialize())
         time.sleep(Automatico.SLEEP_TIME)
Пример #16
0
 def tras(self):
     try:
         self.motor.tras()
     except Exception as e:
         pass
     self.current_pos = int(self.current_pos[0]) - 1, int(self.current_pos[1])
     print(self.current_pos)
     if not self.manual:
         msg = Message(cmd=Mover.TRAS)
         self.connection.send(msg.serialize())
         time.sleep(Automatico.SLEEP_TIME)
Пример #17
0
 def _sorteia_cacas(self):
     # Sorteia e envia as bandeiras
     try:
         if debug:
             self.cacas = def_flags
             print("Modo de debug")
     except:
         self.cacas = self.jogo.sorteia_cacas()
     msg = Message(cmd=Commands.START, data=self.cacas)
     print("Bandeiras: ", self.cacas)
     self._publish_socket.send(msg.serialize())
Пример #18
0
 def frente(self):
     try:
         self.motor.move(Mover.FRENTE)
     except Exception as e:
         pass
     self.current_pos = int(self.current_pos[0]) + 1, int(self.current_pos[1])
     print(self.current_pos)
     if not self.manual:
         while not self.motor.moveu: pass
         msg = Message(cmd=Mover.FRENTE)
         self.connection.send(msg.serialize())
         time.sleep(Automatico.SLEEP_TIME)
Пример #19
0
    def connect(self, player_id):
        # cria um socket temporario, envia a solicitacao pro servidor
        socket = self.context.socket(zmq.DEALER)
        socket.connect("tcp://%s:%d" % (self.SA_ip, self.port + 1))
        msg = Message(cmd=Commands.GET_IP, data=player_id)
        socket.send(msg.serialize())

        # recebe a resposta do servidor
        rep = socket.recv()
        rep = Message(0, rep)
        # self.SS_ip = rep.data
        self.connect_to_supervisor(rep.data)
        print(rep.data)
Пример #20
0
    def _process_flag(self, msg):
        self._blocked = True
        coord = tuple(msg.data)
        print("get_flag", coord)
        status = 400

        if coord in self.jogo.lista_de_cacas:
            print("a caca eh valida, digite ok pra continuar ")
            while user_input != 'ok':
                pass  # n faz nada ate o cabra digitar ok
            self.jogo.jogadores_dict[msg.address].increase_score()
            self.jogo.remove_bandeira(coord)
            self._update_flags()
            print("O jogador", self.jogo.jogadores_dict[msg.address].id,
                  "obteve a caca em ", coord, " sua pontuacao eh ",
                  self.jogo.jogadores_dict[msg.address].score)
            status = 200
        else:
            print("caca invalida, digite ok pra continuar")
            while user_input != 'ok':
                pass

        self._router_socket.send_multipart([
            msg.address,
            Message(cmd=Commands.STATUS_GET_FLAG, data=status).serialize()
        ])
        print("status de valida caca enviado")
        self._blocked = False
Пример #21
0
 def _handle(self):
     while self.run_flag:
         events = dict(self.poller.poll())
         for event in events:
             address, req = self.router_socket.recv_multipart()
             msg = Message(address, req)
             self._process_cmd(msg)
Пример #22
0
 def _listen(self):
     while True:
         try:
             msg = self._socket.recv(2048)
             msg = Message(None, msg)
             self._handle(msg)
         except Exception as e:
             pass
Пример #23
0
 def _handle(self):
     while self.thread_run_flag:
         events = dict(self._poller.poll(timeout=None))  # dicionario = {SOCKET : EVENTO}
         for event in events:
             address, req = self._router_socket.recv_multipart()
             print(req)
             msg = Message(address, req)
             self._process_request(msg)
Пример #24
0
 def _handle(self):
     while True:
         try:
             msg = self.connection.recv(2048)
             print(msg, file=sys.stderr)
             msg = Message(None, msg)
             self._process_data(msg)
         except Exception as e:
             print(e.with_traceback)
Пример #25
0
 def tras(self):
     # anda pra tras e decrementa 1 em X
     self.current_pos = int(self.current_pos[0]) - 1, int(
         self.current_pos[1])
     try:
         self._socket.send(Message(cmd=Mover.TRAS).serialize())
     except Exception as e:
         pass
     if not self.manual:
         while not self._socket.recv(256):
             pass
     print("posicao atual eh: ", self.current_pos)
     return self.current_pos[0], self.current_pos[1]
Пример #26
0
    def esquerda(self):
        # anda pra esquerda e decrementa 1 em Y
        self.current_pos = int(
            self.current_pos[0]), int(self.current_pos[1]) - 1
        try:

            self._socket.send(Message(cmd=Mover.ESQUERDA).serialize())
        except Exception as e:
            pass
        if not self.manual:
            while not self._socket.recv(256):
                pass
        print("posicao atual eh: ", self.current_pos)
        return self.current_pos[0], self.current_pos[1]
Пример #27
0
    def _wait_flag_status(self):

        ## bloqueia tanto interface de jogo quanto supervisor
        self.supervisor.jogo.block()
        self.supervisor.block()

        while True:
            resp = self.dealer_socket.recv()
            resp = Message(0, resp)
            if resp.cmd == Commands.STATUS_GET_FLAG:
                break
        # desbloqueia ambos
        self.supervisor.unblock()
        self.supervisor.jogo.unblock()
Пример #28
0
    def direita(self):
        # anda pra direita e incrementa 1 em Y
        self.current_pos = int(
            self.current_pos[0]), int(self.current_pos[1]) + 1
        try:
            self._socket.send(Message(cmd=Mover.DIREITA).serialize())
        except Exception as e:
            pass
        if not self.manual:
            while not self._socket.recv(256):
                pass

        print("posicao atual eh: ", self.current_pos)
        return self.current_pos[0], self.current_pos[1]
Пример #29
0
    def _process_cmd(self, msg):
        address = msg.address
        # recebe mensagem de obtem bandeira
        if msg.cmd == Commands.GET_FLAG:
            self.comunica_com_sa.get_flag(msg.data)
            while self.is_blocked(): pass
            # o robo n precisa saber o status, so o supervisor
            self.router_socket.send_multipart([self.robot_address, Message(cmd=Commands.STATUS_GET_FLAG).serialize()])

        # robo informa ao supervisor que quer ir para X,Y posicao
        elif msg.cmd == Commands.MOVE_TO:
            self.current_pos = msg.data
            self.comunica_com_sa.try_move(msg.data)


        # robo estabelece conexao com o seu respectivo supervisor
        elif msg.cmd == Commands.CONNECT_TO_SS:
            print("Robo Conectado")
            self.robot_address = address
            msg = Message(cmd=Commands.INITIAL_POS, data=self.begin_pos)
            self._send_reply(address, msg.serialize())

        else:
            pass
Пример #30
0
    def frente(self):
        # anda pra frente e incrementa 1 em X
        self.current_pos = int(self.current_pos[0]) + 1, int(
            self.current_pos[1])
        try:  # envia uma mensagem para o robo para se mover
            self._socket.send(Message(cmd=Mover.FRENTE).serialize())
        except Exception as e:
            print("falhou ao mover", e)

        # fica bloqeuado ate receber a resposta do robo
        if not self.manual:
            while not self._socket.recv(256):
                pass
        print("posicao atual eh: ", self.current_pos)

        return self.current_pos[0], self.current_pos[1]