コード例 #1
0
ファイル: passenger.py プロジェクト: aterrasa/taxi_simulator
 def send_request(self, content=None):
     """
     Sends an :class:`ACLMessage` to the coordinator to request a taxi.
     It uses the REQUEST_PROTOCOL and the REQUEST_PERFORMATIVE.
     If no content is set a default content with the passenger_id,
     origin and target coordinates is used.
     :param content: Optional content dictionary
     :type content: :class:`dict`
     """
     if content is None or len(content) == 0:
         content = {
             "passenger_id": self.myAgent.agent_id,
             "origin": self.myAgent.current_pos,
             "dest": self.myAgent.dest
         }
     if not self.myAgent.dest:
         self.myAgent.dest = random_position()
     msg = ACLMessage()
     msg.addReceiver(coordinator_aid)
     msg.setProtocol(REQUEST_PROTOCOL)
     msg.setPerformative(REQUEST_PERFORMATIVE)
     msg.setContent(json.dumps(content))
     self.myAgent.send(msg)
     self.logger.debug("Passenger {} asked for a taxi to {}.".format(
         self.myAgent.agent_id, self.myAgent.dest))
コード例 #2
0
ファイル: taxi.py プロジェクト: aterrasa/taxi_simulator
 def move_to(self, dest):
     counter = 5
     path = None
     while counter > 0 and path is None:
         logger.debug("Requesting path from {} to {}".format(
             self.current_pos, dest))
         path, distance, duration = request_path(self.current_pos, dest)
         counter -= 1
     if path is None:
         logger.error(
             "Taxi {} could not get a path to passenger {}.".format(
                 self.agent_id, self.current_passenger.getName()))
         reply = ACLMessage()
         reply.addReceiver(self.current_passenger)
         reply.setProtocol(REQUEST_PROTOCOL)
         reply.setPerformative(CANCEL_PERFORMATIVE)
         reply.setContent("{}")
         logger.debug("Taxi {} sent cancel proposal to passenger {}".format(
             self.agent_id, self.current_passenger.getName()))
         self.send(reply)
     else:
         self.path = path
         self.dest = dest
         self.distances.append(distance)
         self.durations.append(duration)
コード例 #3
0
ファイル: taxi.py プロジェクト: aterrasa/taxi_simulator
 def pick_up_passenger(self, passenger_id, origin, dest):
     """
     Starts a TRAVEL_PROTOCOL to pick up a passenger and get him to his destiny.
     It automatically launches all the graphical process until the passenger is
     delivered.
     :param passenger_id: the id of the passenger
     :type passenger_id: :class:`str`
     :param origin: the coordinates of the current location of the passenger
     :type origin: :class:`list`
     :param dest: the coordinates of the target destiny of the passenger
     :type dest: :class:`list`
     """
     self.logger.info("Taxi {} on route to passenger {}".format(
         self.myAgent.agent_id, passenger_id))
     passenger_aid = build_aid(passenger_id)
     reply = ACLMessage()
     reply.addReceiver(passenger_aid)
     reply.setPerformative(INFORM_PERFORMATIVE)
     reply.setProtocol(TRAVEL_PROTOCOL)
     content = {"status": TAXI_MOVING_TO_PASSENGER}
     reply.setContent(json.dumps(content))
     self.myAgent.status = TAXI_MOVING_TO_PASSENGER
     self.myAgent.current_passenger = passenger_aid
     self.myAgent.current_passenger_orig = origin
     self.myAgent.current_passenger_dest = dest
     self.myAgent.move_to(self.myAgent.current_passenger_orig)
     self.myAgent.send(reply)
     self.myAgent.num_assignments += 1
コード例 #4
0
 def create_agent(self, type_, number=1):
     msg = ACLMessage()
     msg.addReceiver(coordinator_aid)
     msg.setProtocol(CREATE_PROTOCOL)
     msg.setPerformative(REQUEST_PERFORMATIVE)
     content = {"type": type_, "number": number}
     msg.setContent(json.dumps(content))
     self.send(msg)
コード例 #5
0
 def sendPushOrder(self, turtleName, distance):
     msg = ACLMessage()
     msg.setOntology(Vocabulary.PUSH)
     msg.setPerformative(Vocabulary.REQUEST)
     content = Vocabulary.PUSH + "(" + distance + ")"
     msg.setContent(content)
     msg.addReceiver(self.aids[turtleName])
     self.myAgent.send(msg)
コード例 #6
0
    class Booking(Behaviour):
        msg = None

        def _process(self):
            self.msg = self._receive(True)

            if self.msg:
                request = json.loads(self.msg.content)
                if request['request_type'] == 'games':
                    bookie = Bookie()
                    self.send_message(
                        json.dumps({
                            'request_type': 'games',
                            'data': bookie.get_games()
                        }))

                if request['request_type'] == 'bet':
                    bookie = Bookie()
                    data = bookie.make_random_evaluation(
                        request['number_of_teams'])
                    self.send_message(
                        json.dumps({
                            'request_type': 'game_evaluation',
                            'data': data
                        }))

                if request['request_type'] == 'team_selection':
                    bookie = Bookie()
                    data = bookie.make_evaluation(request['teams'])
                    self.send_message(
                        json.dumps({
                            'request_type': 'game_evaluation',
                            'data': data
                        }))

                else:
                    pass

        def stop_agent(self):
            print "Agent is dying..."
            self.kill()
            sys.exit()

        def send_message(self, message):

            client = "[email protected]"
            address = "xmpp://" + client
            receiver = spade.AID.aid(name=client, addresses=[address])

            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("booking")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(receiver)
            self.msg.setContent(message)

            self.myAgent.send(self.msg)
            print "\nMessage sent to: %s !" % client
コード例 #7
0
 def sendMoveOrder(self, turtleName, destinationName):
     msg = ACLMessage()
     msg.setOntology(Vocabulary.TURTLEMOVE)
     msg.setPerformative(Vocabulary.REQUEST)
     content = Vocabulary.GOTO + "(" + destinationName + ")"
     msg.setContent(content)
     msg.addReceiver(self.aids[turtleName])
     self.myAgent.log(msg)
     self.myAgent.send(msg)
コード例 #8
0
 def sendGatherOrder(self):
     msg = ACLMessage()
     msg.setOntology(Vocabulary.TURTLEMOVE)
     msg.setPerformative(Vocabulary.REQUEST)
     msg.setContent(Vocabulary.GATHER + "()")
     turtles = list()
     turtles.extend(self.aids.values())
     turtle = self.aids["samira"]
     self.myAgent.log(turtle.getName(), "GATHER")
     msg.addReceiver(turtle)
     self.myAgent.send(msg)
コード例 #9
0
ファイル: taxi.py プロジェクト: aterrasa/taxi_simulator
 def inform_passenger(self, status, data=None):
     if data is None:
         data = {}
     msg = ACLMessage()
     msg.addReceiver(self.current_passenger)
     msg.setProtocol(TRAVEL_PROTOCOL)
     msg.setPerformative(INFORM_PERFORMATIVE)
     content = {"status": status}
     for k, v in data.items():
         content[k] = v
     msg.setContent(json.dumps(content))
     self.send(msg)
コード例 #10
0
    class Coordinate(Behaviour):

        msg = None
        ready = 0
        selected_number = 0
        requests = []
        won = False

        def _process(self):
            self.msg = self._receive(True)

            if self.msg:
                request = json.loads(self.msg.content)
                if request['request_type'] == 'player_ready':

                    self.ready += 1
                    self.requests.append(request['origin'])

                    if self.ready == 2:
                        self.selected_number = randint(0, 100)
                        print "Number is %d \n" % self.selected_number
                        inform_whisperer = {'request_type': 'new_number', 'number': self.selected_number}
                        self.send_message(inform_whisperer, '[email protected]')

                        for origin in self.requests:
                            inform_player = {'request_type': 'play'}
                            self.send_message(inform_player, origin)

                if request['request_type'] == 'guess':

                    if self.won:
                        inform_whisperer = {'request_type': 'round_result', 'result': 'late'}
                        self.send_message(inform_whisperer, request['origin'])

                    if int(request['number']) == self.selected_number:
                        self.won = True
                        inform_whisperer = {'request_type': 'round_result', 'result': 'win'}
                        self.send_message(inform_whisperer, request['origin'])
                    else:
                        inform_whisperer = {'request_type': 'round_result', 'result': 'no'}
                        self.send_message(inform_whisperer, request['origin'])

        def send_message(self, content, address):

            agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])
            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("game")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(agent)
            self.msg.setContent(json.dumps(content))
            self.myAgent.send(self.msg)
コード例 #11
0
 def process(self):
     print "process send order behaviour: ", self.executors
     self.loadAddressBook()
     msg = ACLMessage()
     msg.setOntology(Vocabulary.TURTLEMOVE)
     msg.setPerformative(Vocabulary.REQUEST)
     content = self.createContent()
     msg.setContent(content)
     for dest in self.executors:
         msg.addReceiver(self.aids[dest])
     #self.myAgent.log(msg)
     self.myAgent.send(msg)
     print "sent message: " + msg.getContent()
コード例 #12
0
ファイル: whisperer.py プロジェクト: lpredova/pyGuessingGame
    class Whisper(Behaviour):

        msg = None
        selected_number = 0

        def _process(self):
            self.msg = self._receive(True)

            if self.msg:
                request = json.loads(self.msg.content)
                if request['request_type'] == 'new_number':
                    self.selected_number = request['number']
                    print "I got it..."

                if request['request_type'] == 'help_request':

                    number = request['number']
                    response = ""

                    if self.myAgent.askBelieve(expr('Vrijednost(gamer2)')):

                        if request['origin'] == "[email protected]":

                            if self.selected_number < int(number):
                                response = "high"
                            if self.selected_number > int(number):
                                response = "low"
                            if self.selected_number == int(number):
                                response = "ok"

                        else:
                            response = "ok"

                    player_help = {'request_type': 'help_response', 'status': response}
                    self.send_message(player_help, request['origin'])
                    print 'I told %s that %i is %s' % (request['origin'], number, response)

        def send_message(self, content, address):

            agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])
            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("game")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(agent)
            self.msg.setContent(json.dumps(content))
            self.myAgent.send(self.msg)
            print '\nMessage %s sent to %s' % (content, address)
コード例 #13
0
ファイル: server.py プロジェクト: lpredova/pybookie
    class Booking(Behaviour):
        msg = None

        def _process(self):
            self.msg = self._receive(True)

            if self.msg:
                request = json.loads(self.msg.content)
                if request['request_type'] == 'games':
                    bookie = Bookie()
                    self.send_message(json.dumps({'request_type': 'games', 'data': bookie.get_games()}))

                if request['request_type'] == 'bet':
                    bookie = Bookie()
                    data = bookie.make_random_evaluation(request['number_of_teams'])
                    self.send_message(json.dumps({'request_type': 'game_evaluation', 'data': data}))

                if request['request_type'] == 'team_selection':
                    bookie = Bookie()
                    data = bookie.make_evaluation(request['teams'])
                    self.send_message(json.dumps({'request_type': 'game_evaluation', 'data': data}))

                else:
                    pass

        def stop_agent(self):
            print "Agent is dying..."
            self.kill()
            sys.exit()

        def send_message(self, message):

            client = "[email protected]"
            address = "xmpp://" + client
            receiver = spade.AID.aid(name=client, addresses=[address])

            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("booking")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(receiver)
            self.msg.setContent(message)

            self.myAgent.send(self.msg)
            print "\nMessage sent to: %s !" % client
コード例 #14
0
ファイル: passenger.py プロジェクト: aterrasa/taxi_simulator
 def refuse_taxi(self, taxi_aid):
     """
     Sends an ACLMessage to a taxi to refuse a travel proposal.
     It uses the REQUEST_PROTOCOL and the REFUSE_PERFORMATIVE.
     :param taxi_aid: The AgentID of the taxi
     :type taxi_aid: :class:`spade.AID.aid`
     """
     reply = ACLMessage()
     reply.addReceiver(taxi_aid)
     reply.setProtocol(REQUEST_PROTOCOL)
     reply.setPerformative(REFUSE_PERFORMATIVE)
     content = {
         "passenger_id": self.myAgent.agent_id,
         "origin": self.myAgent.current_pos,
         "dest": self.myAgent.dest
     }
     reply.setContent(json.dumps(content))
     self.myAgent.send(reply)
     self.logger.debug("Passenger {} refused proposal from taxi {}".format(
         self.myAgent.agent_id, taxi_aid.getName()))
コード例 #15
0
ファイル: taxi.py プロジェクト: aterrasa/taxi_simulator
 def send_proposal(self, passenger_id, content=None):
     """
     Send an :class:`ACLMessage` with a proposal to a passenger to pick up him.
     If the content is empty the proposal is sent without content.
     :param passenger_id: the id of the passenger
     :type passenger_id: :class:`str`
     :param content: the optional content of the message
     :type content: :class:`dict`
     """
     if content is None:
         content = {}
     passenger_aid = build_aid(passenger_id)
     reply = ACLMessage()
     reply.addReceiver(passenger_aid)
     reply.setProtocol(REQUEST_PROTOCOL)
     reply.setPerformative(PROPOSE_PERFORMATIVE)
     reply.setContent(content)
     self.logger.debug("Taxi {} sent proposal to passenger {}".format(
         self.myAgent.agent_id, passenger_id))
     self.myAgent.send(reply)
コード例 #16
0
ファイル: passenger.py プロジェクト: aterrasa/taxi_simulator
 def accept_taxi(self, taxi_aid):
     """
     Sends an :class:`ACLMessage` to a taxi to accept a travel proposal.
     It uses the REQUEST_PROTOCOL and the ACCEPT_PERFORMATIVE.
     :param taxi_aid: The AgentID of the taxi
     :type taxi_aid: :class:`spade.AID.aid`
     """
     reply = ACLMessage()
     reply.addReceiver(taxi_aid)
     reply.setProtocol(REQUEST_PROTOCOL)
     reply.setPerformative(ACCEPT_PERFORMATIVE)
     content = {
         "passenger_id": self.myAgent.agent_id,
         "origin": self.myAgent.current_pos,
         "dest": self.myAgent.dest
     }
     reply.setContent(json.dumps(content))
     self.myAgent.send(reply)
     self.myAgent.taxi_assigned = taxi_aid.getName()
     self.logger.debug("Passenger {} accepted proposal from taxi {}".format(
         self.myAgent.agent_id, taxi_aid.getName()))
     self.myAgent.status = PASSENGER_ASSIGNED
コード例 #17
0
ファイル: playerB.py プロジェクト: lpredova/pyGuessingGame
    class Play(Behaviour):

        msg = None
        initial_guess = randint(0, 100)
        low_state = 0
        high_state = 100
        last_sent = 0

        def _process(self):
            self.msg = self._receive(True)

            if self.msg:
                request = json.loads(self.msg.content)
                if request['request_type'] == 'play':
                    initial_guess = randint(self.low_state, self.high_state)
                    self.last_sent = initial_guess
                    ask_help = {'request_type': 'help_request', 'number': initial_guess, 'origin': '[email protected]'}
                    self.send_message(ask_help, '[email protected]')

                if request['request_type'] == 'help_response':
                    if request['status'] == "high":
                        self.high_state = self.initial_guess
                        new_guess = randint(self.low_state, self.last_sent)
                        self.last_sent = new_guess

                        travel = {'request_type': 'guess', 'origin': '[email protected]', 'number': new_guess}
                        self.send_message(travel, '[email protected]')

                    if request['status'] == "low":
                        new_guess = randint(self.last_sent, self.high_state)
                        self.last_sent = new_guess

                        travel = {'request_type': 'guess', 'origin': '[email protected]', 'number': new_guess}
                        self.send_message(travel, '[email protected]')

                    if request['status'] == "ok":
                        travel = {'request_type': 'guess', 'origin': '[email protected]', 'number': self.last_sent}
                        self.send_message(travel, '[email protected]')

                if request['request_type'] == 'round_result':

                    if request['result'] == "late":
                        print ":(((((((((((((((("
                        return

                    if request['result'] == "win":
                        print "YAAAAY! I won!"
                        return

                    if request['result'] == "no":
                        newest_guess = randint(self.low_state, self.high_state)
                        self.last_sent = newest_guess

                        ask_help = {'request_type': 'help_request', 'number': newest_guess,
                                    'origin': '[email protected]'}
                        self.send_message(ask_help, '[email protected]')

        def say_ready(self):
            travel = {'request_type': 'player_ready', 'origin': '[email protected]'}
            self.send_message(travel, '[email protected]')

        def send_message(self, content, address):

            agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])
            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("game")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(agent)
            self.msg.setContent(json.dumps(content))
            self.myAgent.send(self.msg)
            print '\nMessage %s sent to %s' % (content, address)
コード例 #18
0
ファイル: client.py プロジェクト: lpredova/pybookie
    class BookingSettings(Behaviour):

        dialog_selection = None
        msg = None
        games = None

        # 1 - risky, 2 - sure thing , 3 - I don't know what I'm doing
        mood = random.choice([1, 2, 3])

        def _process(self):
            self.msg = self._receive(True)
            if self.msg:
                request = json.loads(self.msg.content)
                if request['request_type'] == 'games':
                    self.games = request['data']
                    self.show_dialog()
                if request['request_type'] == 'game_evaluation':
                    PrintFormatter.results(request['data'])
                    Evaluator.make_bet(self.mood, request['data'])
                    print "\n********Results********\n"
                    Evaluator.find_result(request['data'])
                    self.show_dialog()

        def show_dialog(self):
            self.dialog_selection = raw_input("\n1) Make a Free bet\n2) Generate bet\n3) Exit\n\nSelect:")
            if self.dialog_selection == '1':
                self.set_free_bet_preferences()

            if self.dialog_selection == '2':
                self.set_bet_preferences()

            if self.dialog_selection == '3':
                self.stop_agent()

        def stop_agent(self):
            print "Agent is dying..."
            self.kill()
            sys.exit()

        def set_bet_preferences(self):
            preferences = None
            number_of_teams = 0

            while number_of_teams == 0 and number_of_teams < 16:
                number_of_teams = raw_input('\nNumber of games:')
                preferences = {'request_type': 'bet', 'number_of_teams': number_of_teams}

            self.send_message(json.dumps(preferences))

        def set_free_bet_preferences(self):
            if self.games:
                PrintFormatter.games(self.games)

            teams = []
            number_of_teams = input("\nNumber of games:")

            for i in range(0, int(number_of_teams)):
                print "GAME %d. \n" % (i + 1)
                team_a = raw_input("\nTeam A id: ")
                team_b = raw_input("\nTeam B id: ")

                teams.append({'teamA': team_a, 'teamB': team_b})

            result = json.dumps({'request_type': 'team_selection', 'teams': teams})
            self.send_message(result)

        def send_message(self, content):
            master_agent = spade.AID.aid(name="[email protected]", addresses=["xmpp://[email protected]"])
            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("booking")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(master_agent)
            self.msg.setContent(content)
            self.myAgent.send(self.msg)
            print 'Message %s sent to master agent' % content
コード例 #19
0
ファイル: client.py プロジェクト: lpredova/pybookie
    class BookingSettings(Behaviour):

        dialog_selection = None
        msg = None
        games = None

        # 1 - risky, 2 - sure thing , 3 - I don't know what I'm doing
        mood = random.choice([1, 2, 3])

        def _process(self):
            self.msg = self._receive(True)
            if self.msg:
                request = json.loads(self.msg.content)
                if request['request_type'] == 'games':
                    self.games = request['data']
                    self.show_dialog()
                if request['request_type'] == 'game_evaluation':
                    PrintFormatter.results(request['data'])
                    Evaluator.make_bet(self.mood, request['data'])
                    print "\n********Results********\n"
                    Evaluator.find_result(request['data'])
                    self.show_dialog()

        def show_dialog(self):
            self.dialog_selection = raw_input(
                "\n1) Make a Free bet\n2) Generate bet\n3) Exit\n\nSelect:")
            if self.dialog_selection == '1':
                self.set_free_bet_preferences()

            if self.dialog_selection == '2':
                self.set_bet_preferences()

            if self.dialog_selection == '3':
                self.stop_agent()

        def stop_agent(self):
            print "Agent is dying..."
            self.kill()
            sys.exit()

        def set_bet_preferences(self):
            preferences = None
            number_of_teams = 0

            while number_of_teams == 0 and number_of_teams < 16:
                number_of_teams = raw_input('\nNumber of games:')
                preferences = {
                    'request_type': 'bet',
                    'number_of_teams': number_of_teams
                }

            self.send_message(json.dumps(preferences))

        def set_free_bet_preferences(self):
            if self.games:
                PrintFormatter.games(self.games)

            teams = []
            number_of_teams = input("\nNumber of games:")

            for i in range(0, int(number_of_teams)):
                print "GAME %d. \n" % (i + 1)
                team_a = raw_input("\nTeam A id: ")
                team_b = raw_input("\nTeam B id: ")

                teams.append({'teamA': team_a, 'teamB': team_b})

            result = json.dumps({
                'request_type': 'team_selection',
                'teams': teams
            })
            self.send_message(result)

        def send_message(self, content):
            master_agent = spade.AID.aid(name="[email protected]",
                                         addresses=["xmpp://[email protected]"])
            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("booking")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(master_agent)
            self.msg.setContent(content)
            self.myAgent.send(self.msg)
            print 'Message %s sent to master agent' % content
    class Pregovaranje(Behaviour):

        brojac_krugova_pregovora = 0
        lokacija = ""
        naziv = ""

        pocetno_vrijeme = ""
        zavrsno_vrijeme = ""
        trajanje_dogadjaja = ""

        izbornik_odabir = "0"
        brojac_odgovora = 0
        odgovori = []

        def _process(self):
            self.msg = None
            self.msg = self._receive(True)

            if self.msg:

                print "\nAgent organizator : " + str(self.brojac_odgovora+1) + " /4 poruka primljeno"
                self.brojac_odgovora += 1
                self.odgovori.append(self.msg.content)

                if self.brojac_odgovora % 4 == 0:

                    for x in range(0, 4):
                        print self.odgovori[x]

                    termin = self.nadjiNajboljiTermin()

                    if termin == "":
                        self.brojac_odgovora = 0
                        del self.odgovori[:]
                        print "\nNe može se odrediti najbolji termin sastanka s tim vremenom." \
                              "\nMolimo predložite novi termin !"
                        self.izbornik()

                    else:
                        print "\nNajbolji termin je : " + termin
                        self.upisiTerminUKalendar(termin)

            else:
                print self.msg
                print "\nAgent organizator : Čekao sam ali nema poruke"
                self.prikaziIzbornik()

        def prikaziIzbornik(self):

            if self.brojac_krugova_pregovora == 10:
                print "\nDogovor nije postignut u 10 krugova pregovora"
                self.zaustaviAgenta()
            self.izbornik()

        def izbornik(self):
                print "\n\n%i. krug pregovora" % (self.brojac_krugova_pregovora + 1)
                self.izbornik_odabir = raw_input(
                    "\n1)Predlozi sastanak\n2)Odustani od pregovaranja\n\nOdabir:")

                if self.izbornik_odabir == "1":
                    self.brojac_odgovora = 0
                    self.brojac_krugova_pregovora += 1
                    self.odgovori = []
                    vrijeme = self.odrediVrijemeSastanka()
                    self.posaljiPorukuAgentima(vrijeme)

                if self.izbornik_odabir == "2":
                    self.zaustaviAgenta()

        def zaustaviAgenta(self):
            print "Agent organizator se gasi..."
            self.posaljiPorukuAgentima("stop")
            self.MyAgent._kill

        def odrediVrijemeSastanka(self):

            self.lokacija = raw_input("\nUnesite lokaciju sastanka:")
            self.naziv = raw_input("Naziv sastanka sastanka:")

            print "Unesi pocetno vrijeme intervala..."
            godina_pocetak = raw_input("pocetna godina (yyyy)   : ")
            mjesec_pocetak = raw_input("pocetni mjesec (mm)     :")
            dan_pocetak = raw_input("pocetni dan (dd)  :")
            sat_pocetak = raw_input("pocetni sat (hh)   : ")
            minute_pocetak = raw_input("pocetne minute (mm)     : ")

            print "\nUnesi zavrsno vrijeme intervala...\n"
            godina_kraj = raw_input("zavrsna godina (yyyy)      : ")
            mjesec_kraj = raw_input("zavrsni mjesec (mm)        :")
            dan_kraj = raw_input("zavrsni dan (dd)      : ")
            sat_kraj = raw_input("zavrsni sat (hh)      : ")
            minute_kraj = raw_input("zavrsne minute (mm)        : ")

            self.trajanje_dogadjaja = raw_input("\ntrajanje događaja (min)        : ")
            self.pocetno_vrijeme = godina_pocetak + "-" + mjesec_pocetak + "-" + dan_pocetak + "T" + sat_pocetak + ":" + minute_pocetak + ":00.000Z"
            self.zavrsno_vrijeme = godina_kraj + "-" + mjesec_kraj + "-" + dan_kraj + "T" + sat_kraj + ":" + minute_kraj + ":00.000Z"
            vremena_sastanka = [self.pocetno_vrijeme, self.zavrsno_vrijeme, self.trajanje_dogadjaja]

            return vremena_sastanka

        def posaljiPorukuAgentima(self, poruka):
            i = 1
            while i < 5:
                time.sleep(0.3)
                i += 1
                klijent = "agent_klijent%[email protected]" %i
                adresa = "xmpp://" + klijent
                primatelj = spade.AID.aid(name=klijent, addresses=[adresa])
                self.msg = ACLMessage()
                self.msg.setPerformative("inform")
                self.msg.setOntology("termin_sastanka")
                self.msg.setLanguage("Hrvatski")
                self.msg.addReceiver(primatelj)
                self.msg.setContent(poruka)
                self.myAgent.send(self.msg)
                print "\nposlao sam poruku agentu klijentu " + klijent + " !"

        def nadjiNajboljiTermin(self):

            rjesenje = False

            for x in range(0, 4):

                element = self.odgovori[x]
                if element == "[]":
                    return ""

                redak = element.translate(None, '[]').split(",")
                for l in range(0, len(redak)):

                    #print "uzeli smo sada : " + redak[l]

                    if "Termin je blokiran" in redak[l]:
                        continue
                    pojava = 0

                    for y in range(0, 4):
                        #print "usporedjujem " + redak[l] + " sa %i"%y + ". tim retkom"
                        el = self.odgovori[y]
                        red = el.translate(None, '[]').split(",")
                        for k in range(0, len(red)):
                            #print "usporedjujem " + redak[l] + " sa " + red[k]

                            if redak[l] == red[k]:
                                pojava += 1
                                #print pojava

                            if pojava == 4:
                                return redak[l]

            if not rjesenje:
                return ""

        def upisiTerminUKalendar(self, termin):

            izbor = 0
            while izbor != 1 or izbor != 2:
                izbor = input("\nŽelite sastanak s terminom %s upisati u kalendar ?"
                              "\n1)Dodaj u kalendar"
                              "\n2)Odustani"
                              "\nodabir:" % termin)
                if izbor == 1:

                    pocetno_vrijeme = termin.split("'")[1]
                    zavrsno_vrijeme = self.izracunajZavrsnoVrijeme(termin);

                    calendar = GoogleCalendar()
                    try:
                        if calendar.upisiTerminUKalendar(pocetno_vrijeme, zavrsno_vrijeme, self.naziv, self.lokacija):
                            print "Događaj je uspješno upisan u kalendar..."
                            self.zaustaviAgenta()
                            self.izbornik()

                    except:
                        print "Dodavanje događaja nije uspjelo !"
                        self.izbornik()

                if izbor == 2:
                    print "Dodavanje događaja otkazano !"
                    self.izbornik_odabir = 0
                    self.izbornik()
                    return

        def izracunajZavrsnoVrijeme(self, pocetno_vrijeme):

            godina = pocetno_vrijeme.split("-")[0].split("'")[1]
            mjesec = pocetno_vrijeme.split("-")[1]
            dan = pocetno_vrijeme.split("-")[2].split("T")[0]
            pocetni_sat = int(pocetno_vrijeme.split("T")[1].split(":")[0])
            pocetne_min = int(pocetno_vrijeme.split("T")[1].split(":")[1]) + int(self.trajanje_dogadjaja)

            if pocetne_min > 60:
                razlika = pocetne_min % 60
                pocetni_sat += pocetne_min / 60
                pocetne_min = razlika

            zavrsno_vrijeme = godina + "-" + mjesec + "-" + dan + "T" + str(pocetni_sat) + ":" + str(pocetne_min) \
                              + ":00.000Z"

            return zavrsno_vrijeme
コード例 #21
0
ファイル: traveler.py プロジェクト: lpredova/pyTA
    class Travel(Behaviour):

        BASE_DIR = os.path.dirname(os.path.dirname(__file__))
        config_file = BASE_DIR + 'agency_config.json'

        msg = None
        agencies_counter = ConfigurationReader.number_of_agencies()
        offer_responses = 0
        offers = []

        ask_discount = random.choice([True, False])

        # Best results in Euro destinations
        destination = random.choice(['Europe', 'Australia', 'Asia', 'America'])

        budget = random.randint(1000, 50000)
        persons = random.randint(1, 5)

        discounts_asked = 0
        discounts_responded = 0
        discounts_responses = []

        def _process(self):
            self.msg = self._receive(True)
            if self.msg:
                request = json.loads(self.msg.content)
                if request['request_type'] == 'offer_response':

                    found_offer = False
                    self.offer_responses += 1
                    self.offers.append(request)

                    if self.offer_responses >= self.agencies_counter:
                        for offer in self.offers:
                            for o in offer["data"]:
                                if o["persons"] >= self.persons and o["price"] <= self.budget:
                                    found_offer = True
                                    if self.ask_discount:
                                        print "\nI asking for discount offer from agency %s" % offer["origin"]
                                        travel = {'request_type': 'discount_request', 'travel_id': o["name"]}

                                        # offer is OK so I'm asking for discount if agent wants discount
                                        self.send_message(json.dumps(travel), offer["origin"])
                                        self.discounts_asked += 1
                                        found_offer = True
                                    else:
                                        # agent doesnt want discount, so he books right away
                                        print "\nI accept offer from agency %s" % offer["origin"]
                                        book = {'request_type': 'make_booking', 'travel_id': o["name"]}
                                        self.send_message(json.dumps(book), offer["origin"])

                        if not found_offer:
                            print "Sorry.There is no offer I'd like to take.\n"
                            travel = {'request_type': 'not_found'}
                            self.send_message_all(json.dumps(travel))
                            sys.exit()

                if request['request_type'] == 'discount_response':

                    self.discounts_responded += 1
                    self.discounts_responses.append(request)
                    got_discount = False

                    discounts_got = []

                    if self.discounts_responded == self.discounts_asked:
                        for discount in self.discounts_responses:

                            if discount["discount_accepted"]:
                                got_discount = True
                                print "YAAY! I got discount %i for %s" % (
                                    discount["discount_amount"], discount["location"])
                                discounts_got.append(discount)

                        if not got_discount:
                            print "Sorry.There is no offer I'd like to take.\n"
                            travel = {'request_type': 'not_found'}
                            self.send_message_all(json.dumps(travel))
                            sys.exit()

                    # if there are multiple discounts got, then choose cheapest one
                    if len(discounts_got) > 0:
                        cheapest = None
                        lowest_price = 0

                        for dis in discounts_got:
                            if dis["discount_amount"] > lowest_price:
                                cheapest = dis

                        book = {'request_type': 'make_booking', 'travel_id': cheapest["location"]}
                        self.send_message(json.dumps(book), cheapest["origin"])

                if request['request_type'] == 'booking_confirmed':
                    print "Great!, I'm traveling to %s" % request['destination']

        def set_preferences(self):
            print "I'd like to go to %s" % self.destination
            print "My budget is  %i $ for %i persons" % (self.budget, self.persons)

            if self.ask_discount:
                print "I like discounts\n\n"
            else:
                print "I don't want discount\n\n"

            travel = {'request_type': 'travel_request', 'destination': self.destination}
            self.send_message_all(json.dumps(travel))

        def send_message_all(self, content):

            agencies_ids = ConfigurationReader.read_agency_id()
            for agency_id in agencies_ids:
                address = "agency%[email protected]" % agency_id
                agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])

                self.msg = ACLMessage()
                self.msg.setPerformative("inform")
                self.msg.setOntology("travel")
                self.msg.setLanguage("eng")
                self.msg.addReceiver(agent)
                self.msg.setContent(content)
                self.myAgent.send(self.msg)
                # print '\nMessage %s sent to %s' % (content, address)

        def send_message(self, content, address):

            agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])
            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("travel")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(agent)
            self.msg.setContent(content)
            self.myAgent.send(self.msg)
    class PrimiTerminSastanka(Behaviour):

        calendar = ""
        ime_agenta = ""
        pocetno_vrijeme = ""
        zavrsno_vrijeme = ""
        trajanje_dogadjaja = ""

        google_client_id = ""
        google_client_secret = ""
        google_client_username = ""

        ne_preferirani_termini = ""

        def setGoogleAccountPodatke(self, id, secret, user, ime, termini):
            self.google_client_id = id
            self.google_client_secret = secret
            self.google_client_username = user
            self.ime_agenta = ime
            self.ne_preferirani_termini = termini

            self.calendar = GoogleCalendar(self.google_client_id, self.google_client_secret,
                                           self.google_client_username)

        def _process(self):
            self.msg = None
            self.msg = self._receive(True)
            if self.msg:
                print "\nAgent " + self.ime_agenta + " : primio sam poruku :  %s " % self.msg.content

                if self.msg.content == "stop":
                    print "Agent " + self.ime_agenta + ": gasim se"
                    self.MyAgent._kill()

                if self.msg.content == "potvrda":
                    print "Agent " + self.ime_agenta + ": Sastanak potvrđen -\tgasim se"
                    self.MyAgent._kill()

                else:
                    vremena = self.msg.content.split("'")

                    self.pocetno_vrijeme = vremena[1]
                    self.zavrsno_vrijeme = vremena[3]
                    self.trajanje_dogadjaja = vremena[5]

                    rezultat = self.evaluirajPrijedlog(self.pocetno_vrijeme, self.zavrsno_vrijeme,
                                                       self.trajanje_dogadjaja)
                    self.posaljiOdgovor(rezultat)
            else:
                print "\nAgent " + self.ime_agenta + " : čekao sam ali nema poruke"
                self.posaljiOdgovor("Nisam primio poruku")

        def evaluirajPrijedlog(self, pocetno_vrijeme, zavrsno_vrijeme, trajanje):
            print "\nAgent " + self.ime_agenta.split(" ")[0] + " : Evaluiram prijedlog za sastankom"

            try:
                pocetak_godina = pocetno_vrijeme.split("-")[0]
                pocetak_mjesec = pocetno_vrijeme.split("-")[1]
                pocetak_dan = pocetno_vrijeme.split("-")[2].split("T")[0]
                zavrsetak_godina = zavrsno_vrijeme.split("-")[0]
                zavrsetak_mjesec = zavrsno_vrijeme.split("-")[1]
                zavrsetak_dan = zavrsno_vrijeme.split("-")[2].split("T")[0]

                slobodni_termini = []
                trajanje_intervala = int(trajanje)

                fiksni_zavrsni_sat = int(zavrsno_vrijeme.split("T")[1].split(":")[0])
                fiksne_zavrsne_min = int(zavrsno_vrijeme.split("T")[1].split(":")[1])

                pocetak_intervala_sati = int(pocetno_vrijeme.split("T")[1].split(":")[0])
                pocetak_intervala_minute = int(pocetno_vrijeme.split("T")[1].split(":")[1])

                pivot_intervala_sati_prednji = pocetak_intervala_sati
                pivot_intervala_minute_prednji = pocetak_intervala_minute

                ne_preferirani_pocetak_sati = int(self.ne_preferirani_termini[0].split(":")[0])
                ne_preferirani_pocetak_minute = int(self.ne_preferirani_termini[0].split(":")[1])
                ne_preferirani_zavrsetak_sati = int(self.ne_preferirani_termini[1].split(":")[0])
                ne_preferirani_zavrsetak_minute = int(self.ne_preferirani_termini[1].split(":")[1])

                while fiksni_zavrsni_sat - 1 >= pivot_intervala_sati_prednji \
                        and fiksne_zavrsne_min <= pivot_intervala_minute_prednji:

                    pivot_intervala_sati_zadnji = pivot_intervala_sati_prednji
                    pivot_intervala_minute_zadnji = pivot_intervala_minute_prednji

                    if ne_preferirani_pocetak_sati == pivot_intervala_sati_prednji \
                            and ne_preferirani_pocetak_minute <= pivot_intervala_minute_prednji:

                        slobodni_termini.append("Termin je blokiran !")
                        pivot_intervala_minute_prednji += trajanje_intervala

                        if pivot_intervala_minute_prednji >= 60:
                            pivot_intervala_sati_prednji += 1
                            pivot_intervala_minute_prednji = 0

                        continue

                    if ne_preferirani_zavrsetak_sati == pivot_intervala_sati_prednji \
                            and ne_preferirani_zavrsetak_minute >= pivot_intervala_minute_prednji:

                        slobodni_termini.append("Termin je blokiran !")
                        pivot_intervala_minute_prednji += trajanje_intervala

                        if pivot_intervala_minute_prednji >= 60:
                            pivot_intervala_sati_prednji += 1
                            pivot_intervala_minute_prednji = 0

                        continue

                    if ne_preferirani_pocetak_sati < pivot_intervala_sati_zadnji \
                            and ne_preferirani_zavrsetak_sati > pivot_intervala_sati_prednji:
                        slobodni_termini.append("Termin je blokiran !")
                        pivot_intervala_minute_prednji += trajanje_intervala

                        if pivot_intervala_minute_prednji >= 60:
                            pivot_intervala_sati_prednji += 1
                            pivot_intervala_minute_prednji = 0

                        continue

                    else:
                        pivot_intervala_minute_prednji += trajanje_intervala
                        if pivot_intervala_minute_prednji >= 60:
                            pivot_intervala_sati_prednji += 1
                            pivot_intervala_minute_prednji = 0

                        if pivot_intervala_sati_zadnji < 10:
                            pocetak_sat = "0%i" % (pivot_intervala_sati_zadnji)
                        else:
                            pocetak_sat = "%i" % (pivot_intervala_sati_zadnji)

                        if pivot_intervala_minute_zadnji < 10:
                            pocetak_minute = "0%i" % (pivot_intervala_minute_zadnji)
                        else:
                            pocetak_minute = "%i" % (pivot_intervala_minute_zadnji)

                        if pivot_intervala_sati_prednji < 10:
                            zavrsetak_sat = "0%i" % (pivot_intervala_sati_prednji )
                        else:
                            zavrsetak_sat = "%i" % (pivot_intervala_sati_prednji )

                        if pivot_intervala_minute_prednji < 10:
                            zavrsetak_minute = "0%i" % pivot_intervala_minute_prednji
                        else:
                            zavrsetak_minute = "%i" % (pivot_intervala_minute_prednji )

                        pocetno_vrijeme = pocetak_godina + "-" + pocetak_mjesec + "-" + pocetak_dan + "T" + \
                                          pocetak_sat + ":" + pocetak_minute + ":00.000Z"
                        zavrsno_vrijeme = zavrsetak_godina + "-" + zavrsetak_mjesec + "-" + str(zavrsetak_dan) + "T" \
                                          + zavrsetak_sat + ":" + zavrsetak_minute + ":00.000Z"

                        # TODO za ux je dobro da ispisuje al bespotrebno
                        print self.name + ": računam slobodno vrijeme..."

                        try:
                            if self.calendar.main(pocetno_vrijeme, zavrsno_vrijeme):
                                slobodni_termini.append(pocetno_vrijeme)
                        except:
                            continue

                return slobodni_termini

            except:
                return "Greska u evaluaciji"

        def posaljiOdgovor(self, odgovor):

            primatelj = spade.AID.aid(name="[email protected]",
                                      addresses=["xmpp://[email protected]"])

            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("povratna_informacija")
            self.msg.setLanguage("Hrvatski")
            self.msg.addReceiver(primatelj)
            self.msg.setContent(odgovor)
            self.myAgent.send(self.msg)

            print  "\nAgent " + self.ime_agenta + " : poslao sam poruku agentu organizatoru %s\n!" % (odgovor)
コード例 #23
0
    class OpenStockExchange(Behaviour):

        ip = None
        msg = None
        brokers = 0
        brokers_total = 5

        round = 0
        evaluation = 0

        stocks = []

        def initialize(self):
            self.ip = self.getName().split(" ")[0]
            self.stocks = self.stock_generate()

            helper.print_yellow("Generated %d stocks...\n" % len(self.stocks))
            for stock in self.stocks:
                print 'ID: %d' % stock['id']
                print 'Name: %s' % stock['name']
                print 'Price per stock: %d' % stock['price']

            helper.print_yellow("============================================")

        # Sends signal that stock exchange is opened for business
        def open_stock_exchange(self):
            msg_sign_in_to_stock_exchange = json.dumps(
                {
                    'uuid': str(uuid.uuid4()),
                    'request_type': 'stock_open',
                    'data': None,
                    'origin': self.ip
                }
            )

            self.broadcast_message(msg_sign_in_to_stock_exchange)

        # Sends stock exchange state to brokers
        def send_stock_exchange_report(self, origin_ip):
            msg_sign_in_to_stock_exchange = json.dumps(
                {
                    'uuid': str(uuid.uuid4()),
                    'request_type': 'stock_report_data',
                    'data': json.dumps(self.stocks),
                    'origin': self.ip
                }
            )

            self.send_message(msg_sign_in_to_stock_exchange, origin_ip)

        # Sends stock exchange state to brokers
        def broadcast_stock_exchange_report(self):
            msg_sign_in_to_stock_exchange = json.dumps(
                {
                    'uuid': str(uuid.uuid4()),
                    'request_type': 'stock_report_data',
                    'data': json.dumps(self.stocks),
                    'origin': self.ip
                }
            )

            self.broadcast_message(msg_sign_in_to_stock_exchange)

        # Informs owner that his stock has changed price
        def inform_owner_change(self, stock, origin_ip):
            msg_owner_share_change = json.dumps(
                {
                    'uuid': str(uuid.uuid4()),
                    'id': stock['id'],
                    'price': stock['price'],
                    'request_type': 'stock_share_change',
                    'data': json.dumps(stock),
                    'origin': self.ip
                }
            )

            self.send_message(msg_owner_share_change, origin_ip)

        def send_buy_confirmation(self, stock, origin_ip, price, amount, transaction):
            msg_owner_buy_confirm = json.dumps(
                {
                    'uuid': str(uuid.uuid4()),
                    'id': stock['id'],
                    'name': stock['name'],
                    'request_type': 'stock_bought',
                    'data': json.dumps(stock),
                    'origin': self.ip,
                    'price': price,
                    'amount': amount,
                    'transactionsId': transaction
                }
            )

            self.send_message(msg_owner_buy_confirm, origin_ip)

        def send_sell_confirmation(self, stock, origin_ip, price):
            msg_owner_sell_confirm = json.dumps(
                {
                    'uuid': str(uuid.uuid4()),
                    'request_type': 'stock_sold',
                    'data': json.dumps(stock),
                    'origin': self.ip,
                    'price': price,
                    'id': stock['id']
                }
            )

            self.send_message(msg_owner_sell_confirm, origin_ip)

        # Closes stock exchange, we have our winner
        def send_close_stock_exchange(self):
            msg_sign_in_to_stock_exchange = json.dumps(
                {
                    'uuid': str(uuid.uuid4()),
                    'request_type': 'stock_close',
                    'data': None,
                    'origin': self.ip
                }
            )

            self.broadcast_message(msg_sign_in_to_stock_exchange)
            self.kill()

        def _process(self):
            self.msg = self._receive(True)

            if self.msg:
                request = json.loads(self.msg.content)

                # Registering brokers to start stock exchange
                if request['request_type'] == 'stock_sign_in':
                    self.brokers += 1
                    print "Broker %s signed in %d/%d" % (request['origin'], self.brokers, self.brokers_total)

                    # All brokers are registrated
                    if self.brokers == self.brokers_total:
                        self.initialize()
                        helper.print_green("Opening stock exchange...")
                        self.open_stock_exchange()

                # Collect round status from agents
                if request['request_type'] == 'evaluation_done':
                    self.evaluation += 1
                    print "Broker %s done with move round %d status: %d/%d" % (
                        request['origin'], self.round + 1, self.evaluation, self.brokers_total)

                    if self.evaluation == self.brokers_total:
                        # Round is over, send new report
                        self.round += 1
                        self.evaluation = 0
                        self.stock_speculate()

                # Get stock report
                if request['request_type'] == 'stock_report':
                    self.send_stock_exchange_report(request['origin'])

                # Buy stock
                if request['request_type'] == 'stock_buy':
                    self.buy_stock(request)

                # Sell stock
                if request['request_type'] == 'stock_sell':
                    self.sell_stock(request)

                # Declare winner and close the stock exchange
                if request['request_type'] == 'stock_win':
                    helper.print_green("Broker %s got rich. Closing stock exchange..." % request['origin'])
                    self.send_close_stock_exchange()

        # Initialize stocks
        @staticmethod
        def stock_generate():
            result = []
            number_of_stocks = random.randint(5, 10)
            for i in range(0, number_of_stocks):
                price = random.randint(10, 1000)
                result.append(
                    {
                        'id': i + 1,
                        'name': ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(3)),
                        'price': price,
                        'numberOfStocks': 10000,
                        'totalValue': 10000 * price,
                        'tendency': random.choice(
                            ['up', 'down', 'stale', 'up fast', 'up slow', 'down fast', 'down slow']),
                        'owners': []
                    }
                )

            return result

        # Method that allows trading certain amounts of stocks
        def buy_stock(self, data):
            price = data['stocksToBuy'] * data['data']['price']
            self.stock_add_owner(data['data'], price, data['stocksToBuy'], data['origin'])
            helper.print_green("Agent %s bought %d shares of:%s for %d$" % (
                data['origin'], data['stocksToBuy'], data['data']['name'], price))

        def sell_stock(self, data):
            price = data['stocksToSell'] * data['data']['price']
            self.stock_remove_owner(data['data'], data['origin'])
            print "%s sold %d shares %s for %d" % (data['origin'], data['stocksToSell'], data['data']['name'], price)

        # Method that changes prices of generated stocks according with tendency
        def stock_speculate(self):
            for stock in self.stocks:
                delta = 0
                if stock['tendency'] == 'up':
                    # % of change
                    change_percentage = random.randint(1, 5) / float(100)
                    delta = stock['price'] * change_percentage
                    stock['price'] += delta

                if stock['tendency'] == 'down':
                    # % of change
                    change_percentage = random.randint(1, 5) / float(100)
                    delta = stock['price'] * change_percentage
                    stock['price'] -= delta

                if stock['tendency'] == 'stale':
                    # % of change
                    change_percentage = random.randint(1, 1) / float(100)
                    delta = stock['price'] * change_percentage
                    stock['price'] += delta

                if stock['tendency'] == 'up slow':
                    # % of change
                    change_percentage = random.randint(5, 10) / float(100)
                    delta = stock['price'] * change_percentage
                    stock['price'] += delta

                if stock['tendency'] == 'up fast':
                    # % of change
                    change_percentage = random.randint(10, 50) / float(100)
                    delta = stock['price'] * change_percentage
                    stock['price'] += delta

                if stock['tendency'] == 'down slow':
                    # % of change
                    change_percentage = random.randint(10, 50) / float(100)
                    delta = stock['price'] * change_percentage
                    stock['price'] -= delta

                if stock['tendency'] == 'down fast':
                    # % of change
                    change_percentage = random.randint(10, 50) / float(100)
                    delta = stock['price'] * change_percentage
                    stock['price'] -= delta

                stock['totalValue'] = stock['numberOfStocks'] * stock['price']
                self.increase_owner_shares(stock, delta)

            helper.print_yellow("Starting new round of trading...")
            time.sleep(0.5)
            self.broadcast_stock_exchange_report()

        def increase_owner_shares(self, stock, delta):

            if len(stock) > 0:
                for owner in stock['owners']:
                    owner['price'] = float(owner['price']) + float(delta)
                    self.inform_owner_change(stock, owner['ip'])

        def stock_add_owner(self, stock, total_price, shares, ip):
            for old_stock in self.stocks:
                if old_stock['id'] == stock['id']:
                    old_stock['numberOfStocks'] -= shares
                    owners = old_stock['owners']
                    transaction = random.randint(1, 100000)
                    owners.append({
                        'id': stock['id'],
                        'name': stock['name'],
                        'transactionId': transaction,
                        'ip': ip,
                        'price': total_price,
                        'shares': shares,
                    })

                    old_stock['owners'] = owners
                    self.send_buy_confirmation(old_stock, ip, total_price, shares, transaction)
                    return transaction

        def stock_remove_owner(self, stock, ip):
            for old_stock in self.stocks:
                if old_stock['id'] == stock['id']:
                    owners = old_stock['owners']
                    new = []

                    for o in owners:
                        if o['ip'] != ip:
                            new.append(o)
                        else:
                            # add to total shares count
                            old_stock['numberOfStocks'] += o['shares']
                            self.send_sell_confirmation(stock, ip, o['price'])

                    old_stock['owners'] = new

        def broadcast_message(self, message):
            for broker in brokers:
                address = "%[email protected]" % broker
                agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])
                self.msg = ACLMessage()
                self.msg.setPerformative("inform")
                self.msg.setOntology("stock")
                self.msg.setLanguage("eng")
                self.msg.addReceiver(agent)
                self.msg.setContent(message)

                self.myAgent.send(self.msg)
                # print '\nMessage %s sent to %s' % (message, address)

        def send_message(self, message, address):
            agent = spade.AID.aid(name=address, addresses=["xmpp://%s" % address])
            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("stock")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(agent)
            self.msg.setContent(message)

            self.myAgent.send(self.msg)
コード例 #24
0
    class Speculate(Behaviour):

        win_threshold = float(100000)
        ip = None
        name = None
        behaviour = None

        msg = None
        budget = None

        myStocks = []

        def initialize(self):
            self.ip = self.getName().split(" ")[0]
            self.name = self.getName().split(" ")[0].split("@")[0]
            self.budget = float(random.randint(10000, 50000))
            self.behaviour = random.choice(['risky', 'passive', 'cautious'])

            print 'Agent %s\nBudget: %d$\nBehaviour: %s' % (
                self.ip, self.budget, self.behaviour)

        def sign_in(self):
            msg_sign_in_to_stock_exchange = json.dumps({
                'uuid':
                str(uuid.uuid4()),
                'request_type':
                'stock_sign_in',
                'data':
                None,
                'origin':
                self.ip
            })
            stared_brokers.append(self.name)
            self.send_message_to_stock(msg_sign_in_to_stock_exchange)

        def evaluation_done(self):
            msg_evaluation_done = json.dumps({
                'uuid': str(uuid.uuid4()),
                'request_type': 'evaluation_done',
                'data': None,
                'origin': self.ip
            })
            self.send_message_to_stock(msg_evaluation_done)

        def ask_for_report(self):
            msg_stock_exchange_report = json.dumps({
                'uuid': str(uuid.uuid4()),
                'request_type': 'stock_report',
                'data': None,
                'origin': self.ip
            })
            self.send_message_to_stock(msg_stock_exchange_report)

        def buy_stock(self, stock, number_of_stocks_to_buy):
            msg_stock_to_buy = json.dumps({
                'uuid':
                str(uuid.uuid4()),
                'request_type':
                'stock_buy',
                'data':
                stock,
                'origin':
                self.ip,
                'stocksToBuy':
                number_of_stocks_to_buy
            })
            self.send_message_to_stock(msg_stock_to_buy)

        def sell_stock(self, stock, number_of_stocks_to_sell):
            msg_stock_to_sell = json.dumps({
                'uuid':
                str(uuid.uuid4()),
                'request_type':
                'stock_sell',
                'data':
                stock,
                'origin':
                self.ip,
                'stocksToSell':
                number_of_stocks_to_sell
            })
            self.send_message_to_stock(msg_stock_to_sell)

        def declare_win(self):
            helper.print_green("\nAgent %s WON! Total sum: %d$" %
                               (self.name, self.get_bank_account()))
            msg_stock_win = json.dumps({
                'uuid': str(uuid.uuid4()),
                'request_type': 'stock_win',
                'data': None,
                'origin': self.ip
            })

            self.send_message_to_stock(msg_stock_win)

        def _process(self):
            if not (self.name in stared_brokers):
                self.initialize()
                self.sign_in()

            self.msg = self._receive(True)
            if self.msg:
                request = json.loads(self.msg.content)

                if request['request_type'] == 'stock_open':
                    self.ask_for_report()

                if request['request_type'] == 'stock_report_data':
                    self.evaluate_stock_state(request['data'])

                if request['request_type'] == 'stock_bought':
                    self.add_to_my_stocks(request)

                if request['request_type'] == 'stock_sold':
                    self.remove_from_my_stocks(request)

                if request['request_type'] == 'stock_share_change':
                    self.adjust_stock_prices(request)

                if request['request_type'] == 'stock_close':
                    print 'Agent %s stopped trading, Won %d$' % (self.ip,
                                                                 self.budget)
                    self.kill()

        def evaluate_stock_state(self, stock_data):
            print '\nAgent %s evaluating stock data...' % self.name
            took_action = False

            if self.get_bank_account() >= self.win_threshold:
                self.declare_win()
                took_action = True

            else:
                stock_data = json.loads(stock_data)
                for stock in stock_data:
                    # buy or wait or sell
                    take_action_odds = random.randint(1, 100)
                    action = random.choice(['buy', 'sell', 'stale'])

                    if self.behaviour == 'risky':
                        # takes action in 80 % of cases
                        if take_action_odds < 80:
                            # spend max 40% of my money on this stock and buy all stocks"
                            if action == 'buy' and not self.check_if_i_own_stock(
                                    stock):
                                self.buy_stock_evaluation(40, stock)
                                took_action = True

                            elif action == 'sell' and self.check_if_i_own_stock(
                                    stock):
                                self.sell_stock_evaluation(stock)
                                took_action = True
                            else:
                                took_action = False

                    elif self.behaviour == 'cautious':
                        # takes action in 40 % of cases
                        if take_action_odds < 40:
                            # spend max 10% of my money on stock and buy only growing or stable"
                            if action == 'buy' \
                                    and not self.check_if_i_own_stock(stock) \
                                    and (stock['tendency'] == 'up'
                                         or stock['tendency'] == 'up fast'
                                         or stock['tendency'] == 'up slow'
                                         or stock['tendency'] == 'stale'):

                                self.buy_stock_evaluation(10, stock)
                                took_action = True

                            elif action == 'sell' \
                                    and self.check_if_i_own_stock(stock) \
                                    and (stock['tendency'] == 'down'
                                         or stock['tendency'] == 'down fast'
                                         or stock['tendency'] == 'down slow'):
                                self.sell_stock_evaluation(stock)
                                took_action = True
                            else:
                                took_action = False

                    elif self.behaviour == 'passive':
                        # takes action in 20 % of cases
                        if take_action_odds < 20:
                            # spend max 10% of my money on stock but rather pass buy all kinds of stocks"
                            if action == 'buy' and not self.check_if_i_own_stock(
                                    stock):

                                self.buy_stock_evaluation(40, stock)
                                took_action = True

                            elif action == 'sell' and self.check_if_i_own_stock(
                                    stock):
                                self.sell_stock_evaluation(stock)
                                took_action = True
                            else:
                                took_action = False

            if not took_action:
                print '\nAgent:%s\tNo action' % self.name

            self.print_money_status()
            self.evaluation_done()

        def buy_stock_evaluation(self, max_percentage, stock):

            if stock['numberOfStocks'] > 0:
                budget_percentage = (random.randint(
                    1, max_percentage)) / float(100)
                money_to_spend = self.budget * budget_percentage
                number_of_stocks = money_to_spend / stock['price']

                if int(number_of_stocks) > 0:
                    print "\nAgent:%s\tTrying to buy %d of %s for %d$" % (
                        self.name, number_of_stocks, stock['name'],
                        money_to_spend)
                    self.buy_stock(stock, int(number_of_stocks))

        def sell_stock_evaluation(self, stock):
            if stock['numberOfStocks'] > 0:
                for s in self.myStocks:
                    if s['id'] == stock['id']:
                        print "\nAgent %s trying to sell %s" % (self.name,
                                                                stock['name'])
                        self.sell_stock(stock, s['number'])

        def check_if_i_own_stock(self, stock):
            if len(self.myStocks) == 0:
                return False

            for myStock in self.myStocks:
                if myStock['id'] == stock['id']:
                    return True

            return False

        def check_if_double_transaction(self, transaction_id):
            for myStock in self.myStocks:

                if myStock['transaction'] == transaction_id:
                    return True

            return False

        def add_to_my_stocks(self, data):
            if not self.check_if_double_transaction(data['transactionsId']):
                self.myStocks.append({
                    'id':
                    data['id'],
                    'transaction':
                    data['transactionsId'],
                    'ip':
                    data['origin'],
                    'price':
                    data['price'],
                    'pricePerShare':
                    data['price'] / float(data['amount']),
                    'number':
                    data['amount'],
                })

                self.budget -= float(data['price'])
                helper.print_red(
                    "\nAgent %s bought %d stock of %s for %d$" %
                    (self.name, data['amount'], data['name'], data['price']))

        def remove_from_my_stocks(self, data):
            clean = []
            for stock in self.myStocks:
                if stock['id'] != data['id']:
                    clean.append(stock)

            self.myStocks = clean
            helper.print_green("Agent:%s\t+%d$ to budget" %
                               (self.name, float(data['price'])))
            self.budget += float(data['price'])
            self.print_money_status()

        def print_money_status(self):
            helper.print_yellow("Agent:%s\tTotal:%d$" %
                                (self.name, self.budget))

        def get_bank_account(self):
            total_money = float(self.budget)

            if len(self.myStocks):
                for stock in self.myStocks:
                    total_money += stock['number'] * stock['pricePerShare']

            return total_money

        def adjust_stock_prices(self, data):
            for stock in self.myStocks:
                if stock['id'] == data['id']:
                    stock['pricePerShare'] = data['price']
                    stock['price'] = stock['number'] * stock['pricePerShare']

        def send_message_to_stock(self, content):
            stock_address = '[email protected]'
            agent = spade.AID.aid(name=stock_address,
                                  addresses=["xmpp://%s" % stock_address])
            self.msg = ACLMessage()
            self.msg.setPerformative("inform")
            self.msg.setOntology("stock")
            self.msg.setLanguage("eng")
            self.msg.addReceiver(agent)
            self.msg.setContent(content)

            self.myAgent.send(self.msg)