def accept_bid(self, bid): # if hand concluded throw error # if bidding concluded throw error # if it's not the player's turn throw error # if the bid isn't allowed throw error # bid greater than previous # if misere, required threshold of past bids is met if not self.next_player() == bid.player_id: raise OutOfTurnError # make sure new bid is higher than the last one if not bid > self.last_normal_bid(): raise ValueError('New Bid must be higher than previous bid') # if the bid is misere, make sure that a 7 bid has been made if bid == Bid('MISERE') and not self.last_normal_bid() >= Bid( 'SEVEN', 'SPADES'): raise ValueError( 'Misere cannot be bid until a 7 Bid has been made') # the bid is valid self.bids.append(bid) # if this was the last bid, start the first trick if self.bidding_is_concluded(): self.tricks.append(Trick(self.winning_bid().player_id))
def winning_bid(self): # if bidding not concluded throw error # return last non-pass item of self.bids if self.bids.count(Bid('PASS')) == 4: return None return [bid for bid in self.bids if bid != Bid('PASS')][-1]
def trick_is_concluded(self, trick_index): # check length of trick at index # if winning bid is open misere, concluded = len == 3 # else, concluded = len == 4 return len( self.tricks[trick_index].cards) == (3 if self.winning_bid() in { Bid('MISERE'), Bid('OPEN_MISERE') } else 4)
def main(): test_round = Round() print(test_round.nextPlayer()) test_round.addBid(Bid('1H')) print(test_round.nextPlayer()) test_round.addBid(Bid('2S')) print(test_round.nextPlayer()) test_round.addBid(Bid('3H')) try: test_round.addBid(Bid('3C')) raise Exception except ValueError as e: print e print(test_round.nextPlayer()) test_round.addBid(Bid('4H')) print(test_round.nextPlayer()) test_round.addBid(Bid('5N')) print(test_round.nextPlayer()) try: test_round.addBid(Bid('1H')) raise Exception except ValueError as e: print e try: test_round.addBid(Bid('5C')) raise Exception except ValueError as e: print e try: test_round.addBid(Bid('5N')) raise Exception except ValueError as e: print e print(test_round)
def trick_winner(self, trick_index): if len(self.tricks) - 1 > trick_index: raise ValueError(f'Trick {trick_index} does not exist') if not self.trick_is_concluded(trick_index): raise ValueError(f'Trick {trick_index} is not concluded') trick = self.tricks[trick_index] def highest_trump(trump, cards): if Card('JOKER') in cards: return Card('JOKER') # if the Joker was played, then the function has already returned, so we can safely access card.suit trumps = [card for card in cards if card.suit == trump] if not trumps: return None return max(trumps, key=lambda card: card.rank) def highest_non_trump(trump, cards): non_trumps = [ card for card in cards if not card.is_joker() and not card.suit == trump ] return max(non_trumps, key=lambda card: card.rank) bid = self.winning_bid() if bid in {Bid('MISERE'), Bid('OPEN_MISERE') } or bid.suit == 'NO_TRUMPS': trump = None else: trump = bid.suit # time to figure out who won this thing winning_card = highest_trump(trump, trick.cards) or highest_non_trump( trump, trick.cards) winning_index = trick.cards.index(winning_card) # the winning player will be the player who is winning_index places to the left of the trick leader # this means that the winning player will be (number of places between the bid winner and the trick leader + winning_index) to the left of the bid winner if trick_index == 0: trick_leader = self.winning_bid().player_id else: trick_leader = self.trick_winner(trick_index - 1) trick_leader_index = self.hands.keys().index(trick_leader) winning_player = self.hands.keys()[(trick_leader_index + winning_index) % len(self.hands.keys())] return winning_player
def bidding_is_concluded(self): # TODO: remove these notes when everthing is a-ok good to go # yes conditions: # 4 passes # normal bid + 3 passes # hit bidding ceiling (10 no trumps) enough_passes = len( self.bids) == 4 and self.bids.count(Bid('PASS')) >= 3 bid_ceiling = len(self.bids) > 0 and self.bids[-1] == Bid( '10', 'NO_TRUMPS') return enough_passes or bid_ceiling
def card_can_be_played(self, player_id, card): current_trick = self.tricks[-1] if self.next_player() != player_id: return False if len(current_trick.cards ) == 0: # player is leading, so anything can be played return True else: # player is not leading, so we have to check if they're following suit (and at least one edge case rule) led_suit = current_trick.cards[0].suit player_can_follow_suit = len([ card for card in self.hands[player_id] if card.suit == led_suit ]) > 0 # if other team won bidding with misere/open misere, and the player can't follow suit, and the player has the Joker, they must play it if self.winning_bid() in { Bid('MISERE'), BID('OPEN_MISERE') } and not self.are_teammates( self.winning_bid().player_id, player_id) and not player_can_follow_suit and Card( 'JOKER' ) in self.hands[player_id] and not card == Card('JOKER'): return False # make sure the player follows suit if they can return card.suit == led_suit or not player_can_follow_suit
def icnet(self, max_iterations, gauss_stdev): """ICNET""" # init broker self.broker.set_initial_bid(self.estimated_transport_cost) # establish transporters self.set_transporters_initial_bids(gauss_stdev, self.transporters_icnet) nr_transporters_per_bid = random.randrange(1, self.nr_transporters) transporters = [] for iterator in range(nr_transporters_per_bid): transporters.append(random.choice(self.transporters_icnet)) bid_transporters = set(transporters) # establish cargo owner bid_cargo_owner = random.choice(self.cargo_owners) bid_data = Bid(bid_cargo_owner.id, self.estimated_transport_cost) # establishing the winner negotiation_success, list_of_accepting_transporters, nr_iterations = self.negociation( bid_transporters, max_iterations) if negotiation_success == True: winning_transporter, winner_price = self.determine_winning_transporter_icnet( list_of_accepting_transporters) winner_personality = winning_transporter.personality.get_personality( ) bid_data.accepted(winning_transporter.id, winner_personality, winner_price, nr_iterations) self.stats.bids_icnet.append(bid_data) self.personality_updates(bid_transporters, winning_transporter)
def scrape_bid_page(self, bid_id): """Scrapes the Commbuys bid detail page for the given bid id. Relies on the position of information inside the main results table, since the HTML contains no semantically-meaninful ids or classes. Raises ValueError if it encounters unrecoverable parsing errors. """ page = self.scraper.get(self.details_url, params={'bidId': bid_id}) tree = html.fromstring(page.content) bid_id = self._get_next_sibling_text_for(tree, "Bid Number:") description = self._get_next_sibling_text_for(tree, "Description:") department = self._get_next_sibling_text_for(tree, "Department:") organization = self._get_next_sibling_text_for(tree, "Organization:") location = self._get_next_sibling_text_for(tree, "Location:") open_date_str = self._get_next_sibling_text_for( tree, "Bid Opening Date:") open_date = None try: open_date = datetime.strptime(open_date_str, '%m/%d/%Y %I:%M:%S %p') except ValueError: log.warning("Could not parse {} into date".format(open_date_str)) # Discard empty strings from 'items' items = list(filter(None, self._get_siblings_text_for(tree, "Item #"))) return Bid(identifier=bid_id, description=description, department=department, organization=organization, location=location, open_date=open_date, items=items, site=self.get_site().name)
def check(hand): if not hand.has_maj5(): return None if hand.hcp < 10 or hand.hcp > 21: return None if hand.length() + hand.length(1) + hand.hcp < 20: return None return Bid(0, hand.best_major())
def hand_is_concluded(self): # yes conditions: # 4 passes # 10 tricks complete # misere/open misere bidder wins a trick if not self.bidding_is_concluded( ): # this check allows safe usage of self.winning_bid return False four_passes = self.bids.count(Bid('PASS')) == 4 ten_tricks_complete = len(self.tricks) == 10 misere_won_trick = self.winning_bid() in { Bid('MISERE'), BID('OPEN_MISERE') } return four_passes or ten_tricks_complete or misere_won_trick
def eval_move(self, move, challenge_possible=True, reveal_possible=True): parts = move.split(' ') if parts[0] == 'BID': try: bid = Bid(int(parts[1]), int(parts[2])) assert 1 <= bid.value <= 6 assert bid > self.bid assert bid.count <= self.n_dice + 1 except: self.invalid_move(move) return self.bid = bid self.inform_others('PLAYER_BIDS ' + str(self.cp().id) + ' ' + str(bid)) elif parts[0] == 'REVEAL': try: assert reveal_possible assert len(parts) > 1 dice = (int(x) for x in parts[1:]) for die in dice: self.cp().hidden_dice.remove(die) self.cp().revealed_dice.append(die) except: self.invalid_move(move) return self.inform_others('PLAYER_REVEALS ' + str(self.cp().id) + ' ' + ' '.join(parts[1:])) self.cp().roll() self.eval_move(self.cp().play(), False, False) elif parts[0] == 'CHALLENGE': self.finished_round = True if not challenge_possible: self.invalid_move(move) return self.inform_others('PLAYER_CHALLENGES ' + str(self.cp().id)) for i in range(self.n_players): self.inform_others('PLAYER_HAD ' + str(self.cp().id) + ' ' + ' '.join( str(x) for x in self.cp().hidden_dice)) self.shift_cpi() all_dice = [] for p in self.players: all_dice.extend(p.revealed_dice) all_dice.extend(p.hidden_dice) diff = self.bid.count - sum( [1 for die in all_dice if die == self.bid.value or die == 1]) if diff < 0: self.cp().n_dice += diff elif diff > 0: self.players[self.ppi].n_dice -= diff self.cpi = self.ppi else: self.cp().n_dice -= 1 self.players[self.ppi].n_dice += 1 self.check_if_loses() else: self.invalid_move(move)
def addNewBid(self, clientId, bidValue, receipt): previous_hash = -1 if len(self.__list_of_bids) > 0: previous_hash = self.__list_of_bids[-1].previous_hash bid = Bid(int(clientId), self.serialNumber, bidValue, len(self.__list_of_bids), time.time(), previous_hash, receipt) self.__list_of_bids.append(bid)
def check(hand): if hand.in_zone() and hand.hcp >= 10: if hand.sut_length(1) == 6 and hand.sut_qual(1) >= 6: return Bid(1, 1) return None elif not hand.in_zone() and hand.hcp >= 8: if hand.sut_length(1) == 6: return Bid.parse('2d') else: return None else: return None
def check(hand): if hand.in_zone() and hand.hcp >= 10: if hand.sut_length(3) == 6 and hand.sut_qual(3) >= 6: return Bid(1, 3) if hand.sut_length(2) == 6 and hand.sut_qual(2) >= 6: return Bid(1, 2) return None elif not hand.in_zone(): if hand.hcp > 10: if hand.sut_length(3) == 6: return Bid(1, 3) elif hand.sut_length(2) == 6: return Bid(1, 2) else: return None elif hand.hcp > 8: if hand.sut_length(3) == 6 and hand.sut_qual(3) >= 6: return Bid(1, 3) if hand.sut_length(2) == 6 and hand.sut_qual(2) >= 6: return Bid(1, 2) return None else: return None else: return None
def play_round(self): self.finished_round = False self.bid = Bid(0, 6) for i, p in enumerate(self.players): p.write('NEW_ROUND ' + ' '.join(str(p.n_dice) for p in self.players_sorted)) p.revealed_dice = [] p.roll() self.n_dice = sum(p.n_dice for p in self.players) self.eval_move(self.cp().play(), challenge_possible=False) while not self.finished and not self.finished_round: self.shift_cpi() self.eval_move(self.cp().play())
def registerBid(self, bidInputed): print("bid recebido: " + str(bidInputed)) bid = Bid(bidInputed['stockName'], bidInputed['negotiatedPrice'], bidInputed['quantity'], bidInputed['clientId'], bidInputed['type'], BidStatus.PENDING) if bid is None: print("registerBid: Lance inválido recebido") return False presentBid = None theList = None if bid.type == BidType.BUY: theList = self.listOfBuyers elif bid.type == BidType.SELL: theList = self.listOfSellers else: print("registerBid: Lance tem tipo inválido: " + str(bid.type)) return False for b in theList: if b.stockName == bid.stockName: presentBid = b presentBid.quantity = bid.quantity presentBid.negotiatedPrice = bid.negotiatedPrice presentBid.status = bid.status presentBid.type = bid.type self.computeBids() print("registerBid: Lance já existe. Foi atualizado") return True if presentBid is None: presentBid = Bid(bid.stockName, bid.negotiatedPrice, bid.quantity, bid.clientId, bid.type, bid.status) theList.append(presentBid) print("Adicionando lance na lista " + str(theList)) self.computeBids() print("registerBid: Novo lance registrado com sucesso") return True
async def play_round(self): self.finished_round = False self.bid = Bid(0, 6) for i, p in enumerate(self.players): p.revealed_dice = [] p.roll() p.bid = None self.n_dice = sum(p.n_dice for p in self.players) await self.broadcast_state() await self.eval_move(await self.cp().play(), challenge_possible=False) while not self.finished and not self.finished_round: self.shift_cpi() await self.broadcast_state() await self.eval_move(await self.cp().play())
def scrape_bid_page(self, bid_id): """Scrapes the City of Boston bid detail page for the given bid_id. Relies on the position of information inside the main results table, since the HTML contains no semantically-meaninful ids or classes. Raises ValueError if it encounters parsing errors. """ page = self.scraper.get(self.details_url, params={'ID': bid_id}) tree = html.fromstring(page.content) first_center = tree.xpath('//center')[0] start_text_element = first_center.xpath('b')[0] description = start_text_element.text.strip() items = ["".join(first_center.xpath('text()'))] return Bid(identifier=bid_id, description=description, items=items, site=self.get_site().name)
def get_random(self, minut=0, maxut=1): print('Limits', minut, maxut) lower = np.ma.masked_less_equal(self.utility_space[:, -1], maxut).mask upper = np.ma.masked_greater_equal(self.utility_space[:, -1], minut).mask #(all_mask = [i for i, x in enumerate(range(len(lower))) if (lower[i] and upper[i])] mask = (lower == True) & (upper == True) valids = np.where(mask == True)[0] print('valids.size', valids.size) if valids.size == 0: return None index = random.choice(np.arange(valids.size)) return Bid(self.utility_space[valids[index]], self.discount, valids[index])
def __init__(self): dirname = os.path.dirname(__file__) # Script configuration os.environ['FABRIC_URL'] = 'http://localhost:3000/' os.environ['STORAGE_DIR'] = os.path.join(dirname, 'tmp') os.environ['USER_LIST'] = os.path.join(dirname, 'data/user.csv') os.environ['USER_STORAGE'] = os.path.join(os.getenv('STORAGE_DIR'), 'user.csv') os.environ['HOLIDAY_CALENDAR'] = os.path.join( dirname, 'data/thHoliday2563-64.csv') # Import Grouped command self.user = User() self.fabric = Fabric() self.service = Service() self.bid = Bid() self.etl = ETL()
def next_player(self): if self.hand_is_concluded(): return None player_circle = [player_id for player_id in self.hands.keys()] if not self.bidding_is_concluded(): # working this out is more complicated and more manual than I'd like; # there might be a better formulaic method that I didn't come up with player_pointer = 0 for bid in self.bids: if bid == Bid('PASS'): # remove the player who passed from player_circle del player_circle[player_pointer] # if the player_pointer was pointing to the end of the list, it should now point to the beginning if player_pointer == len(player_circle): player_pointer = 0 else: # move the player_pointer around the circle 1 space player_pointer = (player_pointer + i) % len(player_circle) return player_circle[player_pointer] else: current_trick = self.tricks[-1] # next player is at (index of trick leader + number of cards played in current trick) % player count trick_leader_index = player_circle.index( self.tricks[-2].trick_winner()) if len(self.tricks) > 1 else 0 cards_played_this_trick = len(current_trick.cards) return player_circle[len(current_trick.cards) % len(player_circle)]
def filter_data(self, data, customer_bids=False): if (self.printing_mode == True): print("Filter data...") # Error checking variables lens = [] # List of bid_array lengths discovered in the dataset buy_count = 0 # Number of buy bid_arrays sell_count = 0 # Number of sell bid_arrays junk = 0 # Number of bid_arrays not appended to the lists of bids for xx, bid_array in enumerate(data): # If the timestamps were splitted, indices must be changed # To do: Is this done correctly? if (len(bid_array) <= 1): # Some datasets have internal break-lines if (xx <= len(data) - 3): continue # Handling unexpected line at the end of some dataests else: print("breaking at ", xx, bid_array) break elif (len(bid_array) == 3): continue # Vstrip if (bid_array[-1] == "\n"): bid_array = bid_array[:-1] # Error checking if (self.printing_mode == True and len(bid_array) not in lens): lens.append(len(bid_array)) print(xx, len(bid_array), bid_array) # Setup indices based on bid array length if (len(bid_array) == 30): # Indices self.index_of_timestamp = 10 self.index_of_timestamp2 = 13 self.index_of_isBuy = 9 self.index_of_price = 15 self.index_of_volume = 16 self.index_of_order_id = 17 self.index_of_delivery_product = 23 self.index_of_zone = 3 elif (len(bid_array) == 31): # Indices self.index_of_timestamp = 8 self.index_of_timestamp2 = 11 self.index_of_isBuy = 13 self.index_of_price = 16 self.index_of_volume = 17 self.index_of_order_id = 18 self.index_of_delivery_product = 24 self.index_of_zone = 3 elif (len(bid_array) == 22): # Indices self.index_of_timestamp = 8 self.index_of_timestamp2 = 10 self.index_of_isBuy = 9 self.index_of_price = 11 self.index_of_volume = 12 self.index_of_order_id = 13 self.index_of_delivery_product = 18 self.index_of_zone = 3 elif (len(bid_array) == 28): # Indices self.index_of_timestamp = 8 self.index_of_timestamp2 = 11 self.index_of_isBuy = 10 self.index_of_price = 13 self.index_of_volume = 14 self.index_of_order_id = 15 self.index_of_delivery_product = 21 self.index_of_zone = 3 elif (len(bid_array) == 29): # Indices self.index_of_timestamp = 6 self.index_of_timestamp2 = 9 self.index_of_isBuy = 11 self.index_of_price = 14 self.index_of_volume = 15 self.index_of_order_id = 16 self.index_of_delivery_product = 22 self.index_of_zone = 3 # Error checking if (bid_array[self.index_of_isBuy] not in ["0", "1"]): raise ValueError("Not legal bid is buy", bid_array[self.index_of_isBuy], bid_array, "length:", len(bid_array)) # Check the length of bid array if (len(bid_array) not in [22, 28, 29, 30, 31]): raise ValueError( "NBNB: Bid array does not have a supported length.") # Setting the bid features bid_array_timestamp = bid_array[ self.index_of_timestamp] + " " + bid_array[ self.index_of_timestamp + 1] bid_array_timestamp2 = bid_array[ self.index_of_timestamp2] + " " + bid_array[ self.index_of_timestamp2 + 1] bid_array_is_buy = bid_array[self.index_of_isBuy] bid_array_price = float(bid_array[self.index_of_price]) / 100.0 bid_array_volume = float(bid_array[self.index_of_volume]) / 1000.0 bid_array_order_id = bid_array[self.index_of_order_id] bid_array_zone = bid_array[self.index_of_zone] # Based on the bid features, add the bid_array to one of the bid lists if (bid_array_zone not in [ "10YFR-RTE------C", "10YAT-APG------L", "10YCH-SWISSGRIDZ", "10YBE----------2", "10YNL----------L" ]): # Identify and set the bid array delivery product if (len(bid_array[self.index_of_delivery_product]) == 27): bid_array_dp = bid_array[self.index_of_delivery_product] elif (len(bid_array[self.index_of_delivery_product + 1]) == 27): bid_array_dp = bid_array[self.index_of_delivery_product + 1] elif (":" in bid_array[self.index_of_delivery_product + 1]): bid_array_dp = bid_array[ self.index_of_delivery_product] + " " + bid_array[ self.index_of_delivery_product + 1] elif (":" in bid_array[self.index_of_delivery_product]): bid_array_dp = bid_array[ self.index_of_delivery_product - 1] + " " + bid_array[self.index_of_delivery_product] else: raise ValueError( "Don't know where to find delivery product attribute") # Identify and set the bid array timestamp if (len(bid_array[self.index_of_timestamp]) == 27): bid_array_dp = bid_array[self.index_of_timestamp] elif (len(bid_array[self.index_of_timestamp + 1]) == 27): bid_array_dp = bid_array[self.index_of_timestamp + 1] elif (":" in bid_array[self.index_of_timestamp + 1]): bid_array_timestamp = bid_array[ self.index_of_timestamp] + " " + bid_array[ self.index_of_timestamp + 1] elif (":" in bid_array[self.index_of_timestamp]): bid_array_timestamp = bid_array[ self.index_of_timestamp - 1] + " " + bid_array[self.index_of_timestamp] print("Got B", len(bid_array_dp), bid_array_dp, bid_array) elif (":" in bid_array[self.index_of_timestamp + 1]): bid_array_timestamp = bid_array[ self.index_of_timestamp + 1] + " " + bid_array[self.index_of_timestamp + 2] else: raise ValueError( "Don't know where to find timestamp attribute") try: bid_array_dp = dt.strptime( bid_array_dp.split(".")[0], '%Y-%m-%d %H:%M:%S') bid_array_timestamp = dt.strptime( bid_array_timestamp.split(".")[0], '%Y-%m-%d %H:%M:%S') except: bid_array_dp = dt.strptime( bid_array_dp.split(".")[0], '%m/%d/%Y %H:%M:%S') bid_array_timestamp = dt.strptime( bid_array_timestamp.split(".")[0], '%m/%d/%Y %H:%M:%S') if (True or not (float(bid_array_price) > 19899.0 or float(bid_array_price) < -19899.0)): #print(bid_array_is_buy, bid_array_is_buy == "0") if (bid_array_is_buy == "1"): buy_count += 1 # Price Volume Timestamp Timestamp2 isBuy Order ID Placed by Customer self.bidsB.append( Bid(float(bid_array_price), float(bid_array_volume), bid_array_timestamp, bid_array_timestamp2, bid_array_is_buy, bid_array_order_id, customer_bids, bid_array_zone)) elif (bid_array_is_buy == "0"): sell_count += 1 self.bidsS.append( Bid(float(bid_array_price), float(bid_array_volume), bid_array_timestamp, bid_array_timestamp2, bid_array_is_buy, bid_array_order_id, customer_bids, bid_array_zone)) else: raise ValueError("Is buy: " + str(bid_array_is_buy) + str(type(bid_array_is_buy))) else: junk += 1 if (self.printing_mode == True): self.print_elapsed_time(self.start_time) return self.bidsB, self.bidsS
def bid(self, auction, amount): Bid(self, auction, amount)
def filter_data(self, data, customer_bids=False): if (self.printing_mode == True): print("Filter data...") for xx, bid_array in enumerate(data): # If the timestamps were splitted, indices must be changed # To do: Is this done correctly? if (bid_array[-1] == "\n"): bid_array = bid_array[:-1] if (len(bid_array) == 30): # Indices self.index_of_timestamp = 10 self.index_of_timestamp2 = 13 self.index_of_isBuy = 9 self.index_of_price = 15 self.index_of_volume = 16 self.index_of_order_id = 17 self.index_of_delivery_product = 23 self.index_of_zone = 3 elif (len(bid_array) == 31): # Indices self.index_of_timestamp = 8 self.index_of_timestamp2 = 11 self.index_of_isBuy = 13 self.index_of_price = 16 self.index_of_volume = 17 self.index_of_order_id = 18 self.index_of_delivery_product = 24 self.index_of_zone = 3 if (bid_array[self.index_of_isBuy] not in ["0", "1"]): raise ValueError("Not legal bid is buy") # Check the length of bid array if (len(bid_array) != 31 and len(bid_array) != 30): print("NBNB: Bid array does not have a supported length.") print(len(bid_array)) print(bid_array) #print(xx, bid_array) bid_array_timestamp = bid_array[ self.index_of_timestamp] + " " + bid_array[ self.index_of_timestamp + 1] bid_array_timestamp2 = bid_array[ self.index_of_timestamp2] + " " + bid_array[ self.index_of_timestamp2 + 1] bid_array_is_buy = bid_array[self.index_of_isBuy] bid_array_price = float(bid_array[self.index_of_price]) / 100.0 bid_array_volume = float(bid_array[self.index_of_volume]) / 1000.0 bid_array_order_id = bid_array[self.index_of_order_id] bid_array_zone = bid_array[self.index_of_zone] if (bid_array_zone not in [ "10YFR-RTE------C", "10YAT-APG------L", "10YCH-SWISSGRIDZ", "10YBE----------2", "10YNL----------L" ]): if (":" in bid_array[self.index_of_delivery_product + 1]): bid_array_dp = bid_array[ self.index_of_delivery_product] + " " + bid_array[ self.index_of_delivery_product + 1] #print("Got A", len(bid_array_dp), bid_array_dp) elif (":" in bid_array[self.index_of_delivery_product]): bid_array_dp = bid_array[ self.index_of_delivery_product - 1] + " " + bid_array[self.index_of_delivery_product] print("Got B", len(bid_array_dp), bid_array_dp) else: raise ValueError( "Don't know where to find delivery product attribute") if (":" in bid_array[self.index_of_timestamp + 1]): bid_array_timestamp = bid_array[ self.index_of_timestamp] + " " + bid_array[ self.index_of_timestamp + 1] #print("Got A", len(bid_array_dp), bid_array_dp) elif (":" in bid_array[self.index_of_timestamp]): bid_array_timestamp = bid_array[ self.index_of_timestamp - 1] + " " + bid_array[self.index_of_timestamp] print("Got B", len(bid_array_dp), bid_array_dp) elif (":" in bid_array[self.index_of_timestamp + 1]): bid_array_timestamp = bid_array[ self.index_of_timestamp + 1] + " " + bid_array[self.index_of_timestamp + 2] else: print(bid_array) raise ValueError( "Don't know where to find timestamp attribute") try: bid_array_dp = dt.strptime( bid_array_dp.split(".")[0], '%Y-%m-%d %H:%M:%S') bid_array_timestamp = dt.strptime( bid_array_timestamp.split(".")[0], '%Y-%m-%d %H:%M:%S') except: bid_array_dp = dt.strptime( bid_array_dp.split(".")[0], '%m/%d/%Y %H:%M:%S') bid_array_timestamp = dt.strptime( bid_array_timestamp.split(".")[0], '%m/%d/%Y %H:%M:%S') if (True or not (float(bid_array_price) > 19899.0 or float(bid_array_price) < -19899.0)): if (bid_array_is_buy == "1"): # Price Volume Timestamp Timestamp2 isBuy Order ID Placed by Customer self.bidsB.append( Bid(float(bid_array_price), float(bid_array_volume), bid_array_timestamp, bid_array_timestamp2, bid_array_is_buy, bid_array_order_id, customer_bids, bid_array_zone)) elif (bid_array_is_buy == "0"): self.bidsS.append( Bid(float(bid_array_price), float(bid_array_volume), bid_array_timestamp, bid_array_timestamp2, bid_array_is_buy, bid_array_order_id, customer_bids, bid_array_zone)) else: raise ValueError("Is buy: " + str(bid_array_is_buy) + str(type(bid_array_is_buy))) if (False and self.printing_mode): print("Number of buy bids: " + str(len(self.bidsB))) print("Number of sell bids: " + str(len(self.bidsS))) print("Total number of bids: " + str(len(self.bidsS) + (len(self.bidsB)))) if (self.printing_mode == True): self.print_elapsed_time(self.start_time) return self.bidsB, self.bidsS
def place_bid_against(self, bids_against, bidding_price): global TIME new_bid = Bid("AGAINST", bidding_price, TIME, self.ID) heapq.heappush(bids_against, new_bid) TIME += 1 # Increment the time every time a bid/ask is placed
def aicnet(self, max_iterations, gauss_stdev, rank_method, rank_reverse): """AICNET""" # init broker self.broker.set_initial_bid(self.estimated_transport_cost) # establish transporters self.set_transporters_initial_bids(gauss_stdev, self.transporters_icnet) self.set_transporters_initial_bids(gauss_stdev, self.transporters_aicnet) nr_transporters_per_bid = random.randrange(1, self.nr_transporters) # establish transporters aux = [] bid_transporters_ids = [] for iterator in range(nr_transporters_per_bid): aux.append(random.randrange(1, self.nr_transporters)) bid_transporters_ids.extend(list(set(aux))) bid_transporters_icnet = [] bid_transporters_aicnet = [] for transporter in self.transporters_icnet: if transporter.id in bid_transporters_ids: bid_transporters_icnet.append(transporter) for transporter in self.transporters_aicnet: if transporter.id in bid_transporters_ids: bid_transporters_aicnet.append(transporter) # establish cargo owner bid_cargo_owner = random.choice(self.cargo_owners) # establish bid data bid_data_icnet = Bid(bid_cargo_owner.id, self.estimated_transport_cost) bid_data_aicnet = Bid(bid_cargo_owner.id, self.estimated_transport_cost) # establishing the winner and making the necessary personality updates negotiation_success, list_of_accepting_transporters, nr_iterations = self.negociation( bid_transporters_icnet, max_iterations) if negotiation_success == True: winning_transporter_icnet, winner_price = self.determine_winning_transporter_icnet( list_of_accepting_transporters) winner_personality = winning_transporter_icnet.personality.get_personality( ) bid_data_icnet.accepted(winning_transporter_icnet.id, winner_personality, winner_price, nr_iterations) self.stats.bids_icnet.append(bid_data_icnet) self.personality_updates(bid_transporters_icnet, winning_transporter_icnet) # establishing the winner and making the necessary personality updates negotiation_success, list_of_accepting_transporters, nr_iterations = self.negociation( bid_transporters_aicnet, max_iterations) if negotiation_success == True: winning_transporter_aicnet, rank = self.determine_winning_transporter_aicnet( list_of_accepting_transporters, rank_method, rank_reverse) winner_price2 = list_of_accepting_transporters[ winning_transporter_aicnet] winner_personality2 = winning_transporter_aicnet.personality.get_personality( ) bid_data_aicnet.accepted(winning_transporter_aicnet.id, winner_personality2, winner_price2, nr_iterations) self.stats.bids_aicnet.append(bid_data_aicnet) self.personality_updates(bid_transporters_aicnet, winning_transporter_aicnet)
async def eval_move(self, move, challenge_possible=True, reveal_possible=True): parts = move.split(' ') if parts[0] == 'BID': try: bid = Bid(int(parts[1]), int(parts[2])) assert 1 <= bid.number <= 6 assert bid > self.bid assert bid.quantity <= self.n_dice + 1 except: await self.eval_move(await self.invalid_move(move), challenge_possible, reveal_possible) return self.bid = bid self.cp().bid = bid await self.broadcast('PLAYER_BIDS') await self.record('bids ' + str(bid.quantity) + DICE_DICT[bid.number]) elif parts[0] == 'REVEAL': try: assert reveal_possible assert len(parts) > 1 dice = [int(x) for x in parts[1:]] hidden_dice = self.cp().hidden_dice.copy() for die in dice: hidden_dice.remove(die) except: await self.eval_move(await self.invalid_move(move), challenge_possible, reveal_possible) return for die in dice: self.cp().hidden_dice.remove(die) self.cp().revealed_dice.append(die) self.cp().roll() await self.broadcast_state() await self.broadcast('PLAYER_REVEALS') await self.record('reveals ' + ' '.join(DICE_DICT[x] for x in dice)) await self.eval_move(await self.cp().play(), False, False) elif parts[0] == 'CHALLENGE': if not challenge_possible: await self.eval_move(await self.invalid_move(move), challenge_possible, reveal_possible) return self.finished_round = True await self.broadcast_state() dice_table = '<br><pre>' for i in range(self.n_players): dice_table += f'{self.cp().nickname.ljust(12)}{" ".join(DICE_DICT[x] for x in self.cp().revealed_dice + self.cp().hidden_dice)}<br>' self.shift_cpi() dice_table += '</pre><br>' await self.broadcast('PLAYER_CHALLENGES') await self.record('challenges', dice_table) await asyncio.sleep(max(5, 0.7 * self.n_dice)) all_dice = [] for p in self.players: all_dice.extend(p.revealed_dice) all_dice.extend(p.hidden_dice) diff = self.bid.quantity - sum( [1 for die in all_dice if die == self.bid.number or die == 1]) if diff < 0: self.cp().n_dice += diff elif diff > 0: self.players[self.ppi].n_dice -= diff self.cpi = self.ppi else: self.cp().n_dice -= 1 self.players[self.ppi].n_dice += 1 await self.check_if_loses() elif parts[0] == '_BID+1': if self.bid.quantity > self.n_dice: await self.eval_move('_SURRENDER') else: bid = Bid(self.bid.quantity + 1, self.bid.number) self.bid = bid self.cp().bid = bid await self.broadcast('PLAYER_BIDS') await self.record('bids ' + str(bid.quantity) + DICE_DICT[bid.number]) elif parts[0] == '_SURRENDER': self.finished_round = True self.cp().n_dice = 0 await self.record('surrenders') await self.check_if_loses() await asyncio.sleep(4) else: await self.eval_move(await self.invalid_move(move), challenge_possible, reveal_possible)
def get_by_index(self, index): return Bid(self.utility_space[index], self.discount, index)
def place_bid_for(self, bids_for, bidding_price): global TIME new_bid = Bid("FOR", bidding_price, TIME, self.ID) heapq.heappush(bids_for, new_bid) TIME += 1 # Increment the time every time a bid/ask is placed