Ejemplo n.º 1
0
def createOffer(session, my_offering_market_city, resource_type, event):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	my_offering_market_city : dict
	resource_type : int
	event : multiprocessing.Event
	"""
    banner()

    html = getMarketInfo(session, my_offering_market_city)
    sell_market_capacity = storageCapacityOfMarket(html)
    total_available_amount_of_resource = my_offering_market_city['recursos'][
        resource_type]

    print(
        _('How much do you want to sell? [max = {}]').format(
            addDot(total_available_amount_of_resource)))
    amount_to_sell = read(min=0, max=total_available_amount_of_resource)
    if amount_to_sell == 0:
        event.set()
        return

    price_max, price_min = re.findall(r'\'upper\': (\d+),\s*\'lower\': (\d+)',
                                      html)[resource_type]
    price_max = int(price_max)
    price_min = int(price_min)
    print(
        _('\nAt what price? [min = {:d}, max = {:d}]').format(
            price_min, price_max))
    price = read(min=price_min, max=price_max)

    print(
        _('\nI will sell {} of {} at {}: {}').format(
            addDot(amount_to_sell), materials_names[resource_type],
            addDot(price), addDot(price * amount_to_sell)))
    print(_('\nProceed? [Y/n]'))
    rta = read(values=['y', 'Y', 'n', 'N', ''])
    if rta.lower() == 'n':
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI sell {} of {} in {}\n').format(
        addDot(amount_to_sell), materials_names[resource_type],
        my_offering_market_city['name'])
    setInfoSignal(session, info)
    try:
        do_it2(session, amount_to_sell, price, resource_type,
               sell_market_capacity, my_offering_market_city)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Ejemplo n.º 2
0
def createOffer(s, city, resource, e):
    banner()

    html = getStoreInfo(s, city)
    sell_store_capacity = storageCapacityOfStore(html)
    recurso_disp = city['recursos'][resource]

    print(
        _('How much do you want to sell? [max = {}]').format(
            addDot(recurso_disp)))
    amount_to_sell = read(min=0, max=recurso_disp)
    if amount_to_sell == 0:
        e.set()
        return

    price_max, price_min = re.findall(r'\'upper\': (\d+),\s*\'lower\': (\d+)',
                                      html)[resource]
    price_max = int(price_max)
    price_min = int(price_min)
    print(
        _('\nAt what price? [min = {:d}, max = {:d}]').format(
            price_min, price_max))
    price = read(min=price_min, max=price_max)

    print(
        _('\nI will sell {} of {} at {}: {}').format(
            addDot(amount_to_sell), materials_names[resource], addDot(price),
            addDot(price * amount_to_sell)))
    print(_('\nProceed? [Y/n]'))
    rta = read(values=['y', 'Y', 'n', 'N', ''])
    if rta.lower() == 'n':
        e.set()
        return

    set_child_mode(s)
    e.set()

    info = _('\nI sell {} of {} in {}\n').format(addDot(amount_to_sell),
                                                 materials_names[resource],
                                                 city['name'])
    setInfoSignal(s, info)
    try:
        do_it2(s, amount_to_sell, price, resource, sell_store_capacity, city)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(s, msg)
    finally:
        s.logout()
Ejemplo n.º 3
0
def buy(session, city, offer, amount_to_buy):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	city : dict
	offer : dict
	amount_to_buy : int
	"""
    ships = int(math.ceil((Decimal(amount_to_buy) / Decimal(500))))
    data_dict = {
        'action': 'transportOperations',
        'function': 'buyGoodsAtAnotherBranchOffice',
        'cityId': offer['cityId'],
        'destinationCityId': offer['destinationCityId'],
        'oldView': 'branchOffice',
        'position': city['pos'],
        'avatar2Name': offer['jugadorAComprar'],
        'city2Name': offer['ciudadDestino'],
        'type': int(offer['type']),
        'activeTab': 'bargain',
        'transportDisplayPrice': 0,
        'premiumTransporter': 0,
        'capacity': 5,
        'max_capacity': 5,
        'jetPropulsion': 0,
        'transporters': ships,
        'backgroundView': 'city',
        'currentCityId': offer['cityId'],
        'templateView': 'takeOffer',
        'currentTab': 'bargain',
        'actionRequest': actionRequest,
        'ajax': 1
    }
    url = 'view=takeOffer&destinationCityId={}&oldView=branchOffice&activeTab=bargain&cityId={}&position={}&type={}&resource={}&backgroundView=city&currentCityId={}&templateView=branchOffice&actionRequest={}&ajax=1'.format(
        offer['destinationCityId'], offer['cityId'], offer['position'],
        offer['type'], offer['resource'], offer['cityId'], actionRequest)
    data = session.post(url)
    html = json.loads(data, strict=False)[1][1][1]
    hits = re.findall(r'"tradegood(\d)Price"\s*value="(\d+)', html)
    for hit in hits:
        data_dict['tradegood{}Price'.format(hit[0])] = int(hit[1])
        data_dict['cargo_tradegood{}'.format(hit[0])] = 0
    hit = re.search(r'"resourcePrice"\s*value="(\d+)', html)
    if hit:
        data_dict['resourcePrice'] = int(hit.group(1))
        data_dict['cargo_resource'] = 0
    resource = offer['resource']
    if resource == 'resource':
        data_dict['cargo_resource'] = amount_to_buy
    else:
        data_dict['cargo_tradegood{}'.format(resource)] = amount_to_buy
    session.post(payloadPost=data_dict)
    msg = _('I buy {} to {} from {}').format(addDot(amount_to_buy),
                                             offer['ciudadDestino'],
                                             offer['jugadorAComprar'])
    sendToBotDebug(session, msg, debugON_buyResources)
Ejemplo n.º 4
0
def buyResources(session, event, stdin_fd):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	event : multiprocessing.Event
	stdin_fd: int
	"""
    sys.stdin = os.fdopen(stdin_fd)
    try:
        banner()

        # get all the cities with a store
        commercial_cities = getCommercialCities(session)
        if len(commercial_cities) == 0:
            print(_('There is no store build'))
            enter()
            event.set()
            return

        # choose which city to buy from
        if len(commercial_cities) == 1:
            city = commercial_cities[0]
        else:
            city = chooseCommertialCity(commercial_cities)
            banner()

        # choose resource to buy
        resource = chooseResource(session, city)
        banner()

        # get all the offers of the chosen resource from the chosen city
        offers = getOffers(session, city)
        if len(offers) == 0:
            print(_('There are no offers available.'))
            event.set()
            return

        # display offers to the user
        total_price = 0
        total_amount = 0
        for offer in offers:
            amount = offer['amountAvailable']
            price = offer['precio']
            cost = amount * price
            print(_('amount:{}').format(addDot(amount)))
            print(_('price :{:d}').format(price))
            print(_('cost  :{}').format(addDot(cost)))
            print('')
            total_price += cost
            total_amount += amount

        # ask how much to buy
        print(
            _('Total amount available to purchase: {}, for {}').format(
                addDot(total_amount), addDot(total_price)))
        available = city['freeSpaceForResources'][resource]
        if available < total_amount:
            print(
                _('You just can buy {} due to storing capacity').format(
                    addDot(available)))
            total_amount = available
        print('')
        amount_to_buy = read(msg=_('How much do you want to buy?: '),
                             min=0,
                             max=total_amount)
        if amount_to_buy == 0:
            event.set()
            return

        # calculate the total cost
        gold = getGold(session, city)
        total_cost = calculateCost(offers, amount_to_buy)

        print(
            _('\nCurrent gold: {}.\nTotal cost  : {}.\nFinal gold  : {}.'
              ).format(addDot(gold), addDot(total_cost),
                       addDot(gold - total_cost)))
        print(_('Proceed? [Y/n]'))
        rta = read(values=['y', 'Y', 'n', 'N', ''])
        if rta.lower() == 'n':
            event.set()
            return

        print(_('It will be purchased {}').format(addDot(amount_to_buy)))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI will buy {} from {} to {}\n').format(
        addDot(amount_to_buy), materials_names[resource], city['cityName'])
    setInfoSignal(session, info)
    try:
        do_it(session, city, offers, amount_to_buy)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Ejemplo n.º 5
0
def do_it2(session, amount_to_sell, price, resource_type, sell_market_capacity,
           city):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	amount_to_sell : int
	price : int
	resource_type : int
	sell_market_capacity : int
	city : dict
	"""
    initial_amount_to_sell = amount_to_sell
    html = getMarketInfo(session, city)
    previous_on_sell = onSellInMarket(html)[resource_type]
    while True:
        html = getMarketInfo(session, city)
        currently_on_sell = onSellInMarket(html)[resource_type]
        # if there is space in the store
        if currently_on_sell < storageCapacityOfMarket(html):
            # add our new offer to the free space
            free_space = sell_market_capacity - currently_on_sell
            offer = min(amount_to_sell, free_space)
            amount_to_sell -= offer
            new_offer = currently_on_sell + offer

            payloadPost = {
                'cityId': city['id'],
                'position': city['pos'],
                'action': 'CityScreen',
                'function': 'updateOffers',
                'resourceTradeType': '444',
                'resource': '0',
                'resourcePrice': '10',
                'tradegood1TradeType': '444',
                'tradegood1': '0',
                'tradegood1Price': '11',
                'tradegood2TradeType': '444',
                'tradegood2': '0',
                'tradegood2Price': '12',
                'tradegood3TradeType': '444',
                'tradegood3': '0',
                'tradegood3Price': '17',
                'tradegood4TradeType': '444',
                'tradegood4': '0',
                'tradegood4Price': '5',
                'backgroundView': 'city',
                'currentCityId': city['id'],
                'templateView': 'branchOfficeOwnOffers',
                'currentTab': 'tab_branchOfficeOwnOffers',
                'actionRequest': actionRequest,
                'ajax': '1'
            }
            if resource_type == 0:
                payloadPost['resource'] = new_offer
                payloadPost['resourcePrice'] = price
            else:
                payloadPost['tradegood{:d}'.format(resource_type)] = new_offer
                payloadPost['tradegood{:d}Price'.format(resource_type)] = price
            session.post(payloadPost=payloadPost)

            # if we don't have any more to add to the offer, leave the loop
            if amount_to_sell == 0:
                break

        # sleep for 2 hours
        wait(60 * 60 * 2)

    # wait until the last of our offer is actualy bought, and let the user know
    while True:
        html = getMarketInfo(session, city)
        currently_on_sell = onSellInMarket(html)[resource_type]
        if currently_on_sell <= previous_on_sell:
            msg = _('{} of {} was sold at {:d}').format(
                addDot(initial_amount_to_sell), materials_names[resource_type],
                price)
            sendToBot(session, msg)
            return

        # sleep for 2 hours
        wait(60 * 60 * 2)
Ejemplo n.º 6
0
def sellToOffers(session, city_to_buy_from, resource_type, event):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	city_to_buy_from : dict
	resource_type : int
	event : multiprocessing.Event
	"""
    banner()

    offers = getOffers(session, city_to_buy_from, resource_type)

    if len(offers) == 0:
        print(_('No offers available.'))
        enter()
        event.set()
        return

    print(_('Which offers do you want to sell to?\n'))

    chosen_offers = []
    total_amount = 0
    profit = 0
    for offer in offers:
        cityname, username, amount, price, dist, destination_city_id = offer
        cityname = cityname.strip()
        amount = amount.replace(',', '').replace('.', '')
        amount = int(amount)
        price = int(price)
        msg = _('{} ({}): {} at {:d} each ({} in total) [Y/n]').format(
            cityname, username, addDot(amount), price, addDot(price * amount))
        rta = read(msg=msg, values=['y', 'Y', 'n', 'N', ''])
        if rta.lower() == 'n':
            continue
        chosen_offers.append(offer)
        total_amount += amount
        profit += amount * price

    if len(chosen_offers) == 0:
        event.set()
        return

    available = city_to_buy_from['recursos'][resource_type]
    amount_to_sell = min(available, total_amount)

    banner()
    print(
        _('\nHow much do you want to sell? [max = {}]').format(
            addDot(amount_to_sell)))
    amount_to_sell = read(min=0, max=amount_to_sell)
    if amount_to_sell == 0:
        event.set()
        return

    left_to_sell = amount_to_sell
    profit = 0
    for offer in chosen_offers:
        cityname, username, amount, price, dist, destination_city_id = offer
        cityname = cityname.strip()
        amount = amount.replace(',', '').replace('.', '')
        amount = int(amount)
        price = int(price)
        sell = min(amount, left_to_sell)
        left_to_sell -= sell
        profit += sell * price
    print(
        _('\nSell {} of {} for a total of {}? [Y/n]').format(
            addDot(amount_to_sell), materials_names[resource_type],
            addDot(profit)))
    rta = read(values=['y', 'Y', 'n', 'N', ''])
    if rta.lower() == 'n':
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI sell {} of {} in {}\n').format(
        addDot(amount_to_sell), materials_names[resource_type],
        city_to_buy_from['name'])
    setInfoSignal(session, info)
    try:
        do_it1(session, amount_to_sell, chosen_offers, resource_type,
               city_to_buy_from)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Ejemplo n.º 7
0
def trainArmy(s, e, fd):
    sys.stdin = os.fdopen(fd)
    try:
        banner()

        print(_('Do you want to train troops (1) or ships (2)?'))
        rta = read(min=1, max=2)
        trainTroops = rta == 1
        banner()

        if trainTroops:
            print(_('In what city do you want to train the troops?'))
        else:
            print(_('In what city do you want to train the fleet?'))
        city = chooseCity(s)
        banner()

        lookfor = 'barracks' if trainTroops else 'shipyard'
        for i in range(len(city['position'])):
            if city['position'][i]['building'] == lookfor:
                city['pos'] = str(i)
                break
        else:
            if trainTroops:
                print(_('Barracks not built.'))
            else:
                print(_('Shipyard not built.'))
            enter()
            e.set()
            return

        data = getBuildingInfo(s, city, trainTroops)

        units_info = data[2][1]
        units = generateArmyData(units_info)

        maxSize = max([len(unit['local_name']) for unit in units])

        tranings = []
        while True:
            units = generateArmyData(units_info)
            print(_('Train:'))
            for unit in units:
                pad = ' ' * (maxSize - len(unit['local_name']))
                amount = read(msg='{}{}:'.format(pad, unit['local_name']),
                              min=0,
                              empty=True)
                if amount == '':
                    amount = 0
                unit['cantidad'] = amount

            # calculate costs
            cost = [0] * (len(materials_names_english) + 3)
            for unit in units:
                for i in range(len(materials_names_english)):
                    material_name = materials_names_english[i].lower()
                    if material_name in unit['costs']:
                        cost[i] += unit['costs'][material_name] * unit[
                            'cantidad']

                if 'citizens' in unit['costs']:
                    cost[len(materials_names_english) +
                         0] += unit['costs']['citizens'] * unit['cantidad']
                if 'upkeep' in unit['costs']:
                    cost[len(materials_names_english) +
                         1] += unit['costs']['upkeep'] * unit['cantidad']
                if 'completiontime' in unit['costs']:
                    cost[len(materials_names_english) + 2] += unit['costs'][
                        'completiontime'] * unit['cantidad']

            print(_('\nTotal cost:'))
            for i in range(len(materials_names_english)):
                if cost[i] > 0:
                    print('{}: {}'.format(materials_names_english[i],
                                          addDot(cost[i])))
            if cost[len(materials_names_english) + 0] > 0:
                print(
                    _('Citizens: {}').format(
                        addDot(cost[len(materials_names_english) + 0])))
            if cost[len(materials_names_english) + 1] > 0:
                print(
                    _('Maintenance: {}').format(
                        addDot(cost[len(materials_names_english) + 1])))
            if cost[len(materials_names_english) + 2] > 0:
                print(
                    _('Duration: {}').format(
                        daysHoursMinutes(
                            int(cost[len(materials_names_english) + 2]))))

            print(_('\nProceed? [Y/n]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'n':
                e.set()
                return

            tranings.append(units)

            if trainTroops:
                print(
                    _('\nDo you want to train more troops when you finish? [y/N]'
                      ))
            else:
                print(
                    _('\nDo you want to train more fleets when you finish? [y/N]'
                      ))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'y':
                banner()
                continue
            else:
                break

        # calculate if the city has enough resources
        resourcesAvailable = city['recursos'].copy()
        resourcesAvailable.append(city['ciudadanosDisp'])

        for training in tranings:
            for unit in training:

                for i in range(len(materials_names_english)):
                    material_name = materials_names_english[i].lower()
                    if material_name in unit['costs']:
                        resourcesAvailable[i] -= unit['costs'][
                            material_name] * unit['cantidad']

                if 'citizens' in unit['costs']:
                    resourcesAvailable[
                        len(materials_names_english
                            )] -= unit['costs']['citizens'] * unit['cantidad']

        not_enough = [elem for elem in resourcesAvailable if elem < 0] != []

        if not_enough:
            print(_('\nThere are not enough resources:'))
            for i in range(len(materials_names_english)):
                if resourcesAvailable[i] < 0:
                    print('{}:{}'.format(materials_names[i],
                                         addDot(resourcesAvailable[i] * -1)))

            if resourcesAvailable[len(materials_names_english)] < 0:
                print(
                    _('Citizens:{}').format(
                        addDot(
                            resourcesAvailable[len(materials_names_english)] *
                            -1)))

            print(_('\nProceed anyway? [Y/n]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'n':
                e.set()
                return

        if trainTroops:
            print(_('\nThe selected troops will be trained.'))
        else:
            print(_('\nThe selected fleet will be trained.'))
        enter()
    except KeyboardInterrupt:
        e.set()
        return

    set_child_mode(s)
    e.set()

    if trainTroops:
        info = _('\nI train troops in {}\n').format(city['cityName'])
    else:
        info = _('\nI train fleets in {}\n').format(city['cityName'])
    setInfoSignal(s, info)
    try:
        planTrainings(s, city, tranings, trainTroops)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(s, msg)
    finally:
        s.logout()
Ejemplo n.º 8
0
def sendResources(s, e, fd):
    sys.stdin = os.fdopen(fd)
    try:
        routes = []
        while True:

            banner()
            print(_('Origin city:'))
            try:
                cityO = chooseCity(s)
            except KeyboardInterrupt:
                if routes:
                    print(_('Send shipment? [Y/n]'))
                    rta = read(values=['y', 'Y', 'n', 'N', ''])
                    if rta.lower() != 'n':
                        break
                e.set()
                return

            banner()
            print(_('Destination city'))
            cityD = chooseCity(s, foreign=True)
            idIsland = cityD['islandId']

            if cityO['id'] == cityD['id']:
                continue

            resources_left = cityO['recursos']
            for route in routes:
                (origin_city, destination_city, __, *toSend) = route
                if origin_city['id'] == cityO['id']:
                    for i in range(len(materials_names)):
                        resources_left[i] -= toSend[i]

                # the destination city might be from another player
                if cityD['propia'] and destination_city['id'] == cityD['id']:
                    for i in range(len(materials_names)):
                        cityD['freeSpaceForResources'][i] -= toSend[i]

            banner()
            # the destination city might be from another player
            if cityD['propia']:
                msg = ''
                for i in range(len(materials_names)):
                    if resources_left[i] > cityD['freeSpaceForResources'][i]:
                        msg += '{} more {}\n'.format(
                            addDot(cityD['freeSpaceForResources'][i]),
                            materials_names[i].lower())

                if len(msg) > 0:
                    print(_('You can store just:\n{}').format(msg))

            print(_('Available:'))
            for i in range(len(materials_names)):
                print('{}:{} '.format(materials_names[i],
                                      addDot(resources_left[i])),
                      end='')
            print('')

            print(_('Send:'))
            try:
                max_name = max([len(material) for material in materials_names])
                send = []
                for i in range(len(materials_names)):
                    material_name = materials_names[i]
                    pad = ' ' * (max_name - len(material_name))
                    val = askForValue(_('{}{}:'.format(pad, material_name)),
                                      resources_left[i])
                    send.append(val)
            except KeyboardInterrupt:
                continue
            if sum(send) == 0:
                continue

            banner()
            print(
                _('About to send from {} to {}').format(
                    cityO['cityName'], cityD['cityName']))
            for i in range(len(materials_names)):
                if send[i] > 0:
                    print('{}:{} '.format(materials_names[i], addDot(send[i])),
                          end='')
            print('')

            print(_('Proceed? [Y/n]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() != 'n':
                route = (cityO, cityD, idIsland, *send)
                routes.append(route)
                print(_('Create another shipment? [y/N]'))
                rta = read(values=['y', 'Y', 'n', 'N', ''])
                if rta.lower() != 'y':
                    break
    except KeyboardInterrupt:
        e.set()
        return

    set_child_mode(s)
    e.set()

    info = _('\nSend resources\n')

    setInfoSignal(s, info)
    try:
        executeRoutes(s, routes)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(s, msg)
    finally:
        s.logout()