Example #1
0
    def bid(player, bidding, board):
        print("Now bids human player: ", player.position)
        HumanController.showCards(player)
        print("Input: number color")
        try:
            bid_string = str(input()).strip().upper()
            if bid_string == "0":
                return Bid(0, BidColor.PASS)
            bid = Bid.string_to_bid(bid_string)
            if not bid:
                print("There is no such color, input again")
                return HumanController.bid(player, bidding, board)
        except KeyboardInterrupt:
            print("That was not a number. Please insert again.")
            return HumanController.bid(player, bidding, board)
        except ValueError:
            print("That was not a number. Please insert again.")
            return HumanController.bid(player, bidding, board)
        if bid == bidding.highest_bid:
            print("This bidding is equal last highest bid: ", bidding,
                  " you have to bid again")
            return HumanController.bid(player, bidding, board)
        if bid < bidding.highest_bid:
            print("This bidding is lower than last highest bid: ", bidding,
                  " you have to bid again")
            return HumanController.bid(player, bidding, board)

        return bid
Example #2
0
def get_block_from_dict(block):
    if block['bid'] is None:
        b = Block()
        b.nonce = block['nonce']
        return b
    else:
        bid = Bid(base64_decode(block['bid']['user']),
                  base64_decode(block['bid']['value']))
        bid.originalHash = block['bid']['originalHash']
        return Block(bid, block['prev_signature'])
def handleFront(front):
    logging.info('Starting handleFront')
    val_return =[]
    bidXmLNodes = front.getElementsByTagName("Bid")
    for bidXmlNode in bidXmLNodes:
        bid = Bid()
        bid.setFromXmlNode(bidXmlNode)
        val_return.append(bid)
    logging.info('Ending handleFront')
    return val_return
Example #4
0
    def endAuction(self):
        print("end")
        self.live = False

        repoPrivKey = self.repository.getPrivKey()

        if len(self.bids) > 0:
            lastBlock = bytes(self.bids[len(self.bids) - 1])

        else:
            lastBlock = self.iv

        digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
        digest.update(lastBlock)
        checksum = digest.finalize()

        sealBid = Bid({
            "auction":
            self.serialNum,
            "user":
            "",
            "amount":
            str(-1),
            "time":
            datetime.strptime(str(datetime.now()), '%Y-%m-%d %H:%M:%S.%f')
        })

        check_cyphered = repoPrivKey.sign(checksum, padding.PKCS1v15(),
                                          utils.Prehashed(hashes.SHA256()))

        sealBid.addCheckSum(check_cyphered)
        serializedBid = pickle.dumps(sealBid)

        thisIv = checksum[0:16]

        cipher = Cipher(algorithms.AES(self.key),
                        modes.OFB(thisIv),
                        backend=default_backend())
        encryptor = cipher.encryptor()
        ct = encryptor.update(serializedBid) + encryptor.finalize()

        xorValue = []
        for i in range(len(ct)):
            xorValue.append(ct[i] ^ thisIv[i % len(thisIv)])

        self.bids.append(xorValue)

        file = open("repositoryLog.txt", "a")
        file.write("<<BIDCHAIN>> " + str(datetime.now()) + "  --  ")
        file.write(
            json.dumps(self.bids) + " KEY->" +
            base64.b64encode(self.key).decode("utf-8") + " IV->" +
            base64.b64encode(self.iv).decode("utf-8"))
        file.write("\n")
        file.close()
def createCapacitatedBid(strProv, serviceId, delay, price, capacity):
    bid = Bid()
    uuidId = uuid.uuid1()   # make a UUID based on the host ID and current time
    idStr = str(uuidId)
    bid.setValues(idStr, strProv, serviceId)
    bid.setDecisionVariable("1", price)     # Price
    bid.setDecisionVariable("2", delay)  # Delay
    bid.setCapacity(capacity)
    bid.setStatus(Bid.ACTIVE)
    message = bid.to_message()
    return message, idStr
def inactiveBid(bidId, strProv, serviceId, delay, price):
    bid = Bid()
    bid.setValues(bidId, strProv, serviceId)
    bid.setDecisionVariable("1", price)     # Price
    bid.setDecisionVariable("2", delay)  # Delay
    bid.setStatus(Bid.INACTIVE)
    message = bid.to_message()
    return message, bidId
def createBid(strProv, serviceId, delay, price):
    bid = Bid()
    uuidId = uuid.uuid1()	# make a UUID based on the host ID and current time
    idStr = str(uuidId)
    bid.setValues(idStr, strProv, serviceId)
    bid.setDecisionVariable("1", price)     # Price
    bid.setDecisionVariable("2", delay)  # Delay
    bid.setStatus(Bid.ACTIVE)
    message = bid.to_message()
    return message, idStr
Example #8
0
 def takeTurn(self):
     print("Your dice are: " + str(self._diceset))
     choice = ''
     while choice != 'b' and choice != 'c' and choice != 's':
         print("Would you like to make a bid (b), " +
               "call the last bid (c) or " +
               "declare the last bid spot on (s)?")
         choice = input()
     if choice == 'b':
         validBid = False
         while not validBid:
             print("Please make a bid of the form f d where d is the " +
                   "dice face and f is the number facing up.")
             print("For example a bid of three 4s would be 3 4.")
             bid = input()
             if len(bid) == 3:
                 if bid[0].isnumeric() and bid[2].isnumeric():
                     proposedBid = Bid(int(bid[2]), int(bid[0]), self)
                     if self.getGame().getLastBid().isValidBid(proposedBid):
                         self.getGame().makeBid(proposedBid)
                         validBid = True
                     else :
                         print("That's not a valid bid, you must bid " +
                               "a higher dice value, more of the same " +
                               "dice or both.")
     elif choice == 'c':
         self.getGame().callBid(self)
Example #9
0
def runAndPrint(filename):
    print("Loading data from file %s..." % filename)
    count = 0
    slots = []  # slot object array
    bids = []  # bid object array
    with open(filename) as infile:
        for line in infile:
            line = line.strip()
            count += 1
            # read auction term
            if count == 1:
                term = line
            # read click through rate
            if count == 2:
                parts = line.split(' ')
                for ctr in parts:
                    slot = Slot(ctr)
                    slots.append(slot)
            # read bids information
            if count > 2:
                bid = Bid(line)
                bids.append(bid)

    print("\nAuction for \"%s\" with %d slots and %d bidders:" %
          (term, len(slots), len(bids)))
    for slot in slots:
        print("slot: %6.2f %8.2f %8.2f   %s" %
              (float(slot.clickThruRate), float(slot.price), float(
                  slot.profit), slot.bidder))
    print("	<-- click through rates")
    print(" ")

    auction = Auction(term, bids)

    # print bid information
    print "Bids sorted from high to low:"
    for b in auction.bids:
        # 		print ("%s\t%s" % (b.value, b.name))
        print("bid:%6.2f %s" % (float(b.value), b.name))

    auction.executeVCG(slots)

    print(" ")
    print("%12s %8s %8s %8s\n" % ("clicks", "price", "profit", "bidder"))
    # print slots
    for slot in slots:
        print("slot: %6.2f %8.2f %8.2f   %s" %
              (float(slot.clickThruRate), float(slot.price), float(
                  slot.profit), slot.bidder))
    # print sums
    cls = 0
    rev = 0
    val = 0
    for s in slots:
        cls += float(s.clickThruRate)
        rev += float(s.price)
        val += float(s.profit)
    print("sums: %6.2f %8.2f %8.2f\n" % (cls, rev, val))
Example #10
0
    def bidding(self, board):
        """TO DO - zwraca highest bid i ustawia rozgrywającego w boardzie"""
        current_player = self.starting_player
        self.highest_bidder = None
        min_to_start = 12
        while min_to_start > 0:
            if current_player.points < min_to_start:
                current_player = board.players[(current_player.position.value +
                                                1) % 4]
                self.pass_counter += 1
            else:
                self.pass_counter = 0
                break
            if self.pass_counter == 4:
                min_to_start -= 1
                self.pass_counter = 0

        while self.pass_counter != 4:
            bidding = current_player.bid(self, board)
            if bidding == Bid(0, BidColor.PASS):
                print("Player PASSED")
                self.pass_counter += 1
            else:
                self.highest_bidder = current_player
                self.highest_bid = bidding
                self.pass_counter = 0
                friend_player = board.players[
                    (self.highest_bidder.position.value + 2) % 4]
                if bidding.color != BidColor.N:
                    if friend_player.cards_known_amount[bidding.color.value] > 0 \
                            and friend_player.last_bid.color == bidding.color:
                        friend_player.cards_known_amount[
                            bidding.color.
                            value] = bidding.number - friend_player.last_bid.number
                    else:
                        board.players[
                            self.highest_bidder.position.
                            value].cards_known_amount[
                                bidding.color.value] = bidding.number + 4
                current_player.last_bid = bidding
                if self.highest_bidder.position == PlayerPosition.S or self.highest_bidder.position == PlayerPosition.N:
                    current_contractor = self.NS_contractor
                else:
                    current_contractor = self.EW_contractor
                if not current_contractor[bidding.color.value]:
                    current_contractor[
                        bidding.color.value] = self.highest_bidder
            current_player = board.players[(current_player.position.value + 1)
                                           % 4]
            print("Highest bid is now: ", self.highest_bid)
        if self.highest_bidder is None:
            return None, None
        if self.highest_bidder.position == PlayerPosition.S or self.highest_bidder.position == PlayerPosition.N:
            current_contractor = self.NS_contractor
        else:
            current_contractor = self.EW_contractor
        return self.highest_bid, current_contractor[
            self.highest_bid.color.value]
Example #11
0
 def __init__(self, player):
     self.highest_bid = Bid(0, BidColor.PASS)
     self.starting_player = player
     self.counter = 0
     self.pass_counter = 0
     self.highest_bidder = None
     '''Słowniki zawierające kolor jako klucz i player_position jako wartość'''
     self.NS_contractor = [None, None, None, None, None]
     self.EW_contractor = [None, None, None, None, None]
Example #12
0
 def makeFirstBid(self):
     totalDiceInGame = 0
     game = self.getGame()
     for player in game.getPlayers():
         totalDiceInGame += len(player.getDiceSet())
     avgDicePerPlayer = floor(totalDiceInGame / len(game.getPlayers()))
     randomFrequency = random.randint(1, avgDicePerPlayer)
     randomFace = self.getDiceSet().pop()
     self.getDiceSet().add(randomFace)
     self.getGame().makeBid(Bid(randomFace.getTop(), randomFrequency, self))
Example #13
0
    def PlayBidding(self):
        speaker = self.Next(self.dealer)
        self.InformClientsBidStart(speaker)
        biddings = []  # liste de toutes les enchères
        finisher = -1  # compte le nombre de passe à la suite, démare à -1 pour gérer cas particulier du 4 passes à la suite
        bestBid = None  # permet de savoir rapidement si une enchère a été faite et quelle est le joueur qui l'a faite
        while (
                finisher != NBR_PLAYER - 1
        ):  # tant qu'il n'y a pas eu 3 passes ou 4 passes au premier tour
            self.InformClientsCurrentBidder(speaker)
            self.listeClient[speaker].send(BIDORNOT)
            wannaPlay = self.receivedFromPlayer(
                ANSWERINGWANNAPLAY,
                speaker)[1]  # on demande au joueur s'il veut jouer
            if int(wannaPlay):
                bid = Bid(
                )  # il va faire une enchère on crée donc une instance d'enchère
                IsBidValid = False
                while not IsBidValid:  # check s'il a bien le droit de faire l'enchère (obligation de monter)
                    self.listeClient[speaker].send(PROPOSECONTRACT)
                    received = self.receivedFromPlayer(ANSWERINGCONTRACT,
                                                       speaker)[1:]
                    bid.value = int(received[0])
                    bid.color = int(received[1])
                    IsBidValid = self.testBid(biddings, bid)
                bestBid = speaker  # au moment ou le joueur fait une enchère s'est forcément la meilleure
                if bid.value == 9:  # si quelqu'un annonce capot les enchères sont finies (on ne peut pas d'enchere plus haute) on lance le jeu
                    return (bidResult(bid, FROM_NUMBER_TO_TEAM[bestBid]))
                biddings.append(bid)
                finisher = 0  # quelqu'un a fait une enchère on remet le compteur des passes à 0
                self.UpdatePlayersGraphBid(speaker,
                                           bidding_to_string(bid) + " | ")
            else:
                finisher += 1
                self.UpdatePlayersGraphBid(speaker, "pass | ")
            speaker = self.Next(speaker)

        if (bestBid != None):  # s'il y a eu au moins une enchère de faite
            return (
                bidResult(biddings[-1], FROM_NUMBER_TO_TEAM[bestBid])
            )  # on retourne la derniere enchère et le dernier joueur à avoir faite une enchère
        else:
            return None  # aucune enchère n'a été faite
Example #14
0
 def makeFirstBid(self):
     print("Your dice are: " + str(self._diceset))
     validBid = False
     while not validBid:
         print("Please make a bid of the form f d where d is the " +
                 "dice face and f is the number facing up.")
         print("For example a bid of three 4s would be 3 4.")
         bid = input()
         splitbid = bid.split(' ')
         if len(splitbid) == 2:
             if splitbid[0].isnumeric() and splitbid[1].isnumeric():
                 proposedBid = Bid(int(splitbid[1]), int(splitbid[0]), self)
                 if Bid(1, 0, self).isValidBid(proposedBid):
                     self.getGame().makeBid(proposedBid)
                     validBid = True
                 else :
                     print("That's not a valid bid, you must bid " +
                             "a higher dice value, more of the same " +
                             "dice or both.")
Example #15
0
def runAndPrint(filename):
    print("loading Auction from file %s" % filename)
    count = 0
    slots = []
    bids = []
    with open(filename) as infile:
        for line in infile:
            line = line.strip()
            count += 1
            if count == 1:
                term = line
            if count == 2:
                parts = line.split(' ')
                for ctr in parts:
                    slot = Slot(ctr)
                    slots.append(slot)
            if count > 2:
                bid = Bid(line)
                bids.append(bid)

    print("Auction for \"%s\" with %d slots and %d bidders" %
          (term, len(slots), len(bids)))

    for slot in slots:
        print("slot: %6.2f %8.2f %8.2f   %s" %
              (float(slot.clickThruRate), float(slot.price), float(
                  slot.profit), slot.bidder))
    print("  <-- click through rates")
    print(" ")

    auction = Auction(term, bids)
    for b in auction.bids:
        # print ("%s\t%s"%(b.value,b.name))
        print("bid:%6.2f %s" % (float(b.value), b.name))

    auction.executeVCG(slots)
    print(" ")
    print("%12s %8s %8s %8s\n" % ("clicks", "price", "profit", "bidder"))
    for slot in slots:
        print("slot: %6.2f %8.3f %8.3f   %s" %
              (float(slot.clickThruRate), float(slot.price), float(
                  slot.profit), slot.bidder))
    cls = 0
    rev = 0
    val = 0
    for s in slots:
        cls += float(s.clickThruRate)
        rev += float(s.price)
        val += float(s.profit)
    print("sums: %6.2f %8.3f %8.3f\n" % (cls, rev, val))
Example #16
0
    def bid(player, bidding, board):
        print("Now bids computer player:", player.position)
        max = bidding.highest_bid.number
        color = bidding.highest_bid.color
        my_color = None
        if color == BidColor.PASS:
            # first bidding of this player when no one bid before
            for i, count in enumerate(player.cards_amount):
                if count >= 5:
                    my_color = BidColor(i)
            if not my_color:
                return Bid(0, BidColor.PASS)
            else:
                return Bid(1, my_color)
        elif color == BidColor.N:
            # if a human player gives no color -> just pass
            return Bid(0, BidColor.PASS)
        else:
            eq_color = None
            # color you can raise when bidding number is equal
            co_player_known_cards = board.players[(player.position.value + 2) %
                                                  4].cards_known_amount

            for i in range(color.value + 1, 4):
                if player.cards_amount[i] + co_player_known_cards[i] == max + 4:
                    print("My cards: ", player.cards_amount[i],
                          " my co_player: ", co_player_known_cards[i])
                    eq_color = BidColor(i)
                elif player.cards_amount[i] + co_player_known_cards[
                        i] > max + 4:
                    # if on i-color we can gain more points
                    my_color = BidColor(i)
            if not my_color:
                if not eq_color:
                    if player.cards_amount[
                            color.value] + co_player_known_cards[
                                color.value] < max + 5:
                        return Bid(0, BidColor.PASS)
                    else:
                        return Bid(max + 1, color)
                else:
                    return Bid(max, eq_color)
            else:
                return Bid(max + 1, my_color)
Example #17
0
        async def run(self):
            for auctionElement in self.agent.auctions:

                if auctionElement.auctionStart < datetime.now():
                    if auctionElement.auctionEnd > datetime.now():

                        if len(auctionElement.buyers) > 0:
                            for buyer in auctionElement.buyers:
                                bid = Bid(auctionElement.auctionId,
                                          auctionElement.bidIncrement,
                                          auctionElement.winner,
                                          auctionElement.endPrice)
                                bidJson = jsonpickle.encode(bid)
                                msgNotify = Message(to=buyer,
                                                    body=bidJson,
                                                    metadata={
                                                        "ontology": "aukcija",
                                                        "language": "hrvatski",
                                                        "intent":
                                                        "bidajakooces"
                                                    })
                                await self.send(msgNotify)
                        else:
                            print(
                                f"AUKCIJA {auctionElement.auctionId} NEMA SUDIONIKA"
                            )

                        if auctionElement.winner != None:
                            print(
                                f"AUKCIJU VODI AGENT {auctionElement.winner} -> {auctionElement.endPrice}"
                            )

                    else:
                        if auctionElement.active == True:
                            if auctionElement.winner != None:
                                print(
                                    f"AUKCIJU VODI AGENT {auctionElement.winner} -> {auctionElement.endPrice}"
                                )

                                update = EndAuctionRequestModel(
                                    auctionElement.auctionId,
                                    auctionElement.endPrice,
                                    auctionElement.winner)
                                updateJson = jsonpickle.encode(update)
                                apiUrl = "https://localhost:44388/api/auction/finish"
                                headers = {'Content-Type': 'application/json'}
                                requests.put(url=apiUrl,
                                             data=updateJson,
                                             headers=headers,
                                             timeout=10,
                                             verify=False)

                            if len(auctionElement.buyers) > 0:
                                for buyer in auctionElement.buyers:
                                    win = Winner(auctionElement.auctionId,
                                                 auctionElement.winner,
                                                 auctionElement.endPrice)
                                    winJson = jsonpickle.encode(win)
                                    msgNotify = Message(to=buyer,
                                                        body=winJson,
                                                        metadata={
                                                            "ontology":
                                                            "aukcija",
                                                            "language":
                                                            "hrvatski",
                                                            "intent":
                                                            "aukcijagotova"
                                                        })
                                    await self.send(msgNotify)

                            else:
                                print(
                                    f"AUKCIJA {auctionElement.auctionId} NEMA SUDIONIKA"
                                )

                            print("ZAVRSAVAM AUKCIJU ZA OVAJ PREDMET")
                            auctionElement.active = False
Example #18
0
        async def run(self):
            try:
                msg = await self.receive(timeout=100)
                if msg:
                    intent = msg.get_metadata("intent")

                    #register buyer
                    if intent == "registerbuyer":
                        #check if user is in registeredUser array
                        if msg.body not in self.agent.registeredUsers:
                            self.agent.registeredUsers.append(msg.body)
                            print(f"User {msg.body} registered")
                        else:
                            print(f"User {msg.body} already added")

                        #filter list with available auction items
                        tempAuctions = []
                        for auctionItem in self.agent.auctions:
                            if auctionItem.auctionStart > datetime.now():
                                tempAuctions.append(auctionItem)

                        #create spade message instance for registration
                        content = jsonpickle.encode(self.agent.auctions)
                        msg = Message(to=msg.body,
                                      body=content,
                                      metadata={
                                          "ontology": "aukcija",
                                          "language": "hrvatski",
                                          "intent": "auctionitems"
                                      })
                        await self.send(msg)
                        print("ORGANIZATOR: Poruka aukcija poslana")

                    #register buyer auctions
                    if intent == "auctionitemsreg":
                        temp = jsonpickle.decode(msg.body)
                        temp.__class__ = ItemRegistration
                        for auction in self.agent.auctions:
                            for registeredAuction in temp.auctionItems:
                                if auction.auctionId == registeredAuction:
                                    print(
                                        f"Korisnik {temp.agentId} prijavljen na aukciju {auction.auctionId}"
                                    )
                                    auction.buyers.append(temp.agentId)

                                    update = AddBuyerRequest(
                                        auction.auctionId, temp.agentId)
                                    updateJson = jsonpickle.encode(update)
                                    apiUrl = "https://localhost:44388/api/auction/buyer"
                                    headers = {
                                        'Content-Type': 'application/json'
                                    }
                                    requests.put(url=apiUrl,
                                                 data=updateJson,
                                                 headers=headers,
                                                 timeout=10,
                                                 verify=False)

                    #biding
                    if intent == "bid":
                        bider = jsonpickle.decode(msg.body)
                        bider.__class__ = NewBid
                        for auction in self.agent.auctions:
                            if auction.auctionId == bider.auctionId:
                                if auction.endPrice < bider.agentPrice:
                                    auction.endPrice = bider.agentPrice
                                    auction.winner = bider.agentId

                                    update = EndAuctionRequestModel(
                                        auction.auctionId, auction.endPrice,
                                        auction.winner)
                                    updateJson = jsonpickle.encode(update)
                                    apiUrl = "https://localhost:44388/api/auction/newprice"
                                    headers = {
                                        'Content-Type': 'application/json'
                                    }
                                    requests.put(url=apiUrl,
                                                 data=updateJson,
                                                 headers=headers,
                                                 timeout=10,
                                                 verify=False)
                                else:
                                    bid = Bid(auction.auctionId,
                                              auction.bidIncrement,
                                              auction.winner, auction.endPrice)
                                    bidJson = jsonpickle.encode(bid)
                                    msgNotify = Message(to=bider.agentId,
                                                        body=bidJson,
                                                        metadata={
                                                            "ontology":
                                                            "aukcija",
                                                            "language":
                                                            "hrvatski",
                                                            "intent":
                                                            "bidajakooces"
                                                        })
                                    await self.send(msgNotify)

            except Exception:
                traceback.print_exc()
Example #19
0
    async def makeBid(self, bid, client_key, c=0):
        if c == 0:
            try:
                client_key.verify(base64.b64decode(bid["signature"]),
                                  bytes(bid["user"], "utf-8"),
                                  padding.PKCS1v15(), hashes.SHA1())
            except:
                return '{"status":1, "error":"Invalid Signature."}'
        bid = Bid(bid, client_key)
        if await self.repository.validateBid(bid):
            if self.live:
                if bid.amount < self.lowestBidValue and self.lowestBidValue - bid.amount < self.marginValue and bid.amount > self.minimumValue:
                    self.lowestBidValue = bid.amount
                    self.lowestBidUser = bid.user

                    if len(self.bids) == 0:
                        bid.addCheckSum(self.iv)
                        serializedBid = pickle.dumps(bid)

                        cipher = Cipher(algorithms.AES(self.key),
                                        modes.OFB(self.iv),
                                        backend=default_backend())
                        encryptor = cipher.encryptor()
                        ct = encryptor.update(
                            serializedBid) + encryptor.finalize()

                        xorValue = []
                        for i in range(len(ct)):
                            xorValue.append(ct[i] ^ self.iv[i % len(self.iv)])

                    else:
                        digest = hashes.Hash(hashes.SHA256(),
                                             backend=default_backend())
                        digest.update(bytes(self.bids[len(self.bids) - 1]))
                        checksum = digest.finalize()

                        bid.addCheckSum(checksum)

                        serializedBid = pickle.dumps(bid)
                        print(serializedBid)

                        thisIv = checksum[0:16]
                        cipher = Cipher(algorithms.AES(self.key),
                                        modes.OFB(thisIv),
                                        backend=default_backend())
                        encryptor = cipher.encryptor()
                        ct = encryptor.update(
                            serializedBid) + encryptor.finalize()
                        xorValue = []
                        for i in range(len(ct)):
                            xorValue.append(ct[i] ^ thisIv[i % len(thisIv)])

                    #self.bids.append(bid)1
                    self.bids.append(xorValue)

                    #repo signature
                    privkey = self.repository.getPrivKey()
                    signature = bytes(
                        privkey.sign(bytes(bid.user, "utf-8"),
                                     padding.PKCS1v15(), hashes.SHA1()))
                    sgn = base64.b64encode(signature).decode("utf-8")

                    return '{"user":"******","signature":"' + sgn + '","amount":' + str(
                        bid.amount) + ',"auction":' + str(
                            bid.auction) + ',"evidence":"' + base64.b64encode(
                                bytes(xorValue)).decode("utf-8") + '"}'
                return '{"status":1, "error":"Unable to complete bid. Your value does not follow the auction\'s rules."}'
            return '{"status":1, "error":"Unable to complete bid. Auction is already closed."}'
        return '{"status":1, "error":"Bid did not pass the validation process."}'
Example #20
0
    def sIA_function(self):
        # This function represents The Simple Itareted Auction algorithm. It provides
        # list of tasks that need to be assigned to the agents. After it recieves bids from
        # the agents it calls choose_bid function that decides which bids are accepted and which
        # are not.

        self.Tauc = []
        self.bids = []
        TaucMsg = []

        self.sort_Tasks()

        self.define_Tauc()

        print(f'Tasks TF on auction: {self.Tauc}\n')

        while self.Tauc:
            TaucMsg.clear()
            control = False
            for task in self.Tauc:
                TaucMsg.append(task.to_msg())

            for name in self.ns:
                rospy.wait_for_service(f'/{name}/provide_tauc')
                try:
                    self.resp1 = ProvideTaucResponse()
                    provide_tauc = rospy.ServiceProxy(f'/{name}/provide_tauc',
                                                      ProvideTauc)
                    self.resp1 = provide_tauc(TaucMsg)
                    if self.resp1.time != 0:
                        self.bids.append(
                            Bid(Task.to_task(self.resp1.bid), self.resp1.time,
                                self.resp1.robot_name))
                except rospy.ServiceException as exc:
                    print("Service did not process request: " + str(exc))

                if self.resp1.time != 0:
                    control = True
                    print("Bidder name: {0}".format(self.resp1.robot_name),
                          end='\n')
                    print("Bid: {0}".format(self.resp1.bid.name), end='\n')
                    print("Time: {0} seconds\n".format(self.resp1.time))
                else:
                    print(
                        f"{self.resp1.robot_name} couldn't bid for any task at this moment.\n"
                    )

            if not control:
                print("No one could bid for rest of tasks on auction :(\n")
                print(
                    "Auctioneer is going to remove those tasks from auction.")
                self.Tauc.clear()

            self.choose_bid()

            if self.Tauc:
                print(f"=========================================\n")
                print(f"Tasks still left on auction: {self.Tauc}\n")
            elif self.TL and self.TH and not self.Tauc:
                for name in self.ns:
                    rospy.wait_for_service(f'/{name}/tighten_schedule')
                    try:
                        tighten_schedule = rospy.ServiceProxy(
                            f'/{name}/tighten_schedule', TightenSchedule)
                        tighten_schedule(True)
                    except rospy.ServiceException as exc:
                        print(end='')

                self.define_Tauc()

                print(f"=========================================\n")
                print(f"Tasks TL on auction: {self.Tauc}\n")
            elif self.TH and not self.Tauc:
                for name in self.ns:
                    rospy.wait_for_service(f'/{name}/tighten_schedule')
                    try:
                        tighten_schedule = rospy.ServiceProxy(
                            f'/{name}/tighten_schedule', TightenSchedule)
                        tighten_schedule(True)
                    except rospy.ServiceException as exc:
                        print(end='')

                self.define_Tauc()

                print(f"=========================================\n")
                print(f"Tasks TH on auction: {self.Tauc}\n")

        print("=========================================\n")
        for name in self.ns:
            rospy.wait_for_service(f'/{name}/declare_end')
            try:
                self.resp2 = DeclareEndResponse()
                declare_end = rospy.ServiceProxy(f'/{name}/declare_end',
                                                 DeclareEnd)
                self.resp2 = declare_end(True)
                for r_name in self.robot_name_location:
                    if r_name == name.capitalize():
                        for tsk in self.resp2.schedule:
                            t = Task.to_task(tsk)
                            self.robot_name_location[r_name][0].append(
                                float(t.location_X))
                            self.robot_name_location[r_name][1].append(
                                float(t.location_Y))
            except rospy.ServiceException as exc:
                print(end='')
Example #21
0
    def process_bidding_round(self):
        self.state = GameState.BIDDING_ROUND
        logging.info("Starting bidding round")
        first_bidder = self.starting_player
        next_bidder = first_bidder

        # logging.info("Object json: {}\n".format(self.json))
        # Assume bids are legal because the UI should handle this bit
        # If we do do AI players we might as well enforce they follow rules too right?
        logging.info(
            "Getting a first bid from {}, and enforcing a minimum 28 bid".
            format(self.players[self.starting_player].name))
        bid_amount = self.players[first_bidder].make_bid(enforce_bid=True)
        self.bid_history.append(Bid(self.players[first_bidder], bid_amount))
        winning_bid = Bid(self.players[first_bidder], bid_amount)
        self.push_bid_info(winning_bid)
        # logging.info("Continuing bidding round after first bid")
        done = False
        last_nminus1_bids = []
        while not done:
            next_bidder = (next_bidder + 1) % self.num_players
            bid_amount = self.players[next_bidder].make_bid()
            bid = Bid(self.players[next_bidder], bid_amount)
            self.bid_history.append(bid)
            # logging.info("Bid history json: {}".format(self.get_bid_json()))
            # TODO: Implement bidding rules
            # Second condition _should_ be redundant because we should assume they play by the rules
            # Actually should be redundant because of the UI preventing this?
            if bid_amount > 0 and bid_amount > winning_bid.bid_amount:
                logging.info("Updating winning bid : {} bid {}".format(
                    self.players[next_bidder].name, bid_amount))
                winning_bid = Bid(self.players[next_bidder], bid_amount)
            else:
                logging.info("{} opted to pass".format(
                    self.players[next_bidder].name))
            self.push_bid_info(bid)
            # Check termination
            if len(last_nminus1_bids) < self.num_players - 1:
                last_nminus1_bids.append(bid_amount)
            else:
                # Should use an array (questionable) but lol
                last_nminus1_bids.pop(0)
                last_nminus1_bids.append(bid_amount)
            # If n-1 people pass in a row
            if len(last_nminus1_bids) == self.num_players - 1 and sum(
                    last_nminus1_bids) == 0:
                logging.info(
                    "Last {} bids were passes, ending bidding round".format(
                        self.num_players - 1))
                # logging.info("Object json: {}\n".format(self.json))
                done = True

        self.game_bid = winning_bid
        logging.info("Asking winning bidder to select a trump to hide")
        self.state = GameState.HIDE_TRUMP_REQUEST
        self.hidden_trump_card = winning_bid.player.select_trump()
        self.bidder_index = winning_bid.player.number
        # Remove the card from their hand, and place it face down on the table
        # Note that this card is not available to play until trump is requested
        self.player_hands[self.bidder_index].remove(self.hidden_trump_card)
        logging.info("{} chose to hide {}".format(winning_bid.player.name,
                                                  str(self.hidden_trump_card)))
        # Use this to make sure the player doesn't start a round with that suit
        # (unless they have no choice but code that too)
        self.trump_suit = self.hidden_trump_card.suit