def printEstadoMina(s, url, bien): html = s.post(url) levels = re.search(r'"resourceLevel":"(\d+)","tradegoodLevel":"(\d+)"', html) if bien == 'Aserradero': lv = levels.group(1) else: lv = levels.group(2) infoMina = re.search(r':<\\/h4>\\n\s*<ul\sclass=\\"resources\\">\\n\s*<li\sclass=\\"wood\\">([\d,]+)<[\s\S]*?:<\\/h4>\\n\s*<ul\sclass=\\"resources\\">\\n\s*<li\sclass=\\"wood\\">([\d,]+)<', html) if infoMina is not None: donado = infoMina.group(2) porDonar = infoMina.group(1) donado = int(donado.replace(',', '')) porDonar = int(porDonar.replace(',', '')) print('{} lv:{}'.format(bien, lv)) print('{} / {} {}%'.format(addPuntos(donado), addPuntos(porDonar), addPuntos(int((100 * donado) / porDonar)))) else: print('{}: Está ampliando al nivel {:d}\n'.format(bien, int(lv) + 1)) return infoMina is not None
def donar(s): bienes = {'1': 'Viñedo', '2': 'Cantera', '3': 'Mina de cristal', '4': 'Mina de azufre'} banner() ciudad = elegirCiudad(s) html = ciudad['html'] banner() madera = getRecursosDisponibles(html)[0] almacenamiento = getCapacidadDeAlmacenamiento(html) idIsla = ciudad['islandId'] html = s.get(urlIsla + idIsla) isla = getIsla(html) tipo = re.search(r'"tradegood":"(\d)"', html).group(1) bien = bienes[tipo] urlAserradero = 'view=resource&type=resource&islandId={0}&backgroundView=island¤tIslandId={0}&actionRequest={1}&ajax=1'.format(idIsla, s.token()) aserraderoOk = printEstadoMina(s, urlAserradero, 'Aserradero') urlBien = 'view=tradegood&type={0}&islandId={1}&backgroundView=island¤tIslandId={1}&actionRequest={2}&ajax=1'.format(tipo, idIsla, s.token()) bienOk = printEstadoMina(s, urlBien, bien) tipo = ['resource', 'tradegood'] print('Madera disopnible:{} / {}\n'.format(addPuntos(madera), addPuntos(almacenamiento))) if aserraderoOk is True and bienOk is True: msg = 'Aserradero(1) o ' + bien + '(2)?:' tipoDonacion = read(msg=msg, min=1, max=2) elif aserraderoOk is True and bienOk is False: tipoDonacion = 1 print('Aserradero:\n') elif aserraderoOk is False and bienOk is True: tipoDonacion = 2 print('{}:\n'.format(bien)) else: print('No se puede donar\n') return tipo = tipo[tipoDonacion - 1] cantidad = read(min=0, max=int(madera), msg='Cantidad:') s.post(payloadPost={'islandId': idIsla, 'type': tipo, 'action': 'IslandScreen', 'function': 'donate', 'donation': cantidad, 'backgroundView': 'island', 'templateView': 'resource', 'actionRequest': s.token(), 'ajax': '1'})
def buy(s, ciudad, oferta, cantidad): barcos = int(math.ceil((Decimal(cantidad) / Decimal(500)))) data_dict = { 'action': 'transportOperations', 'function': 'buyGoodsAtAnotherBranchOffice', 'cityId': oferta['cityId'], 'destinationCityId': oferta['destinationCityId'], 'oldView': 'branchOffice', 'position': ciudad['pos'], 'avatar2Name': oferta['jugadorAComprar'], 'city2Name': oferta['ciudadDestino'], 'type': int(oferta['type']), 'activeTab': 'bargain', 'transportDisplayPrice': 0, 'premiumTransporter': 0, 'capacity': 5, 'max_capacity': 5, 'jetPropulsion': 0, 'transporters': barcos, 'backgroundView': 'city', 'currentCityId': oferta['cityId'], 'templateView': 'takeOffer', 'currentTab': 'bargain', 'actionRequest': s.token(), 'ajax': 1 } url = 'view=takeOffer&destinationCityId={}&oldView=branchOffice&activeTab=bargain&cityId={}&position={}&type={}&resource={}&backgroundView=city¤tCityId={}&templateView=branchOffice&actionRequest={}&ajax=1'.format( oferta['destinationCityId'], oferta['cityId'], oferta['position'], oferta['type'], oferta['resource'], oferta['cityId'], s.token()) data = s.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 = oferta['resource'] if resource == 'resource': data_dict['cargo_resource'] = cantidad else: data_dict['cargo_tradegood{}'.format(resource)] = cantidad s.post(payloadPost=data_dict) msg = _('Compro {} a {} de {}').format(addPuntos(cantidad), oferta['ciudadDestino'], oferta['jugadorAComprar']) sendToBotDebug(msg, debugON_comprarRecursos)
def menuRutaComercial(s): rutas = [] while True: banner() print('Ciudad de origen:') try: ciudadO = elegirCiudad(s) except KeyboardInterrupt: if rutas: print('¿Enviar viajes? [Y/n]') rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() != 'n': break return html = ciudadO['html'] max = getRecursosDisponibles(html) total = list(map(int, max)) banner() print('Ciudad de destino') ciudadD = elegirCiudad(s, ajenas=True) idIsla = ciudadD['islandId'] if ciudadO['id'] == ciudadD['id']: continue if ciudadD['propia']: html = ciudadD['html'] mad, vin, mar, cri, azu = getRecursosDisponibles(html, num=True) capacidad = getCapacidadDeAlmacenamiento(html) capacidad = int(capacidad) mad = capacidad - mad vin = capacidad - vin mar = capacidad - mar cri = capacidad - cri azu = capacidad - azu resto = total for ruta in rutas: (origen, destino, _, md, vn, mr, cr, az) = ruta if origen['id'] == ciudadO['id']: resto = (resto[0] - md, resto[1] - vn, resto[2] - mr, resto[3] - cr, resto[4] - az) if ciudadD['propia'] and destino['id'] == ciudadD['id']: mad = mad - md vin = vin - vn mar = mar - mr cri = cri - cr azu = azu - az banner() if ciudadD['propia']: msg = '' if resto[0] > mad: msg += '{} más de madera\n'.format(addPuntos(mad)) if resto[1] > vin: msg += '{} más de vino\n'.format(addPuntos(vin)) if resto[2] > mar: msg += '{} más de marmol\n'.format(addPuntos(mar)) if resto[3] > cri: msg += '{} más de cristal\n'.format(addPuntos(cri)) if resto[4] > azu: msg += '{} más de azufre\n'.format(addPuntos(azu)) if msg: print('Solo puede almacenar:\n' + msg) print('Disponible:') print('Madera {} Vino {} Marmol {} Cristal {} Azufre {}'.format( addPuntos(resto[0]), addPuntos(resto[1]), addPuntos(resto[2]), addPuntos(resto[3]), addPuntos(resto[4]))) print('Enviar:') try: md = pedirValor(' Madera:', resto[0]) vn = pedirValor(' Vino:', resto[1]) mr = pedirValor(' Marmol:', resto[2]) cr = pedirValor('Cristal:', resto[3]) az = pedirValor(' Azufre:', resto[4]) except KeyboardInterrupt: continue if md + vn + mr + cr + az == 0: continue banner() print('Por enviar de {} a {}'.format(ciudadO['cityName'], ciudadD['cityName'])) enviado = '' if md: enviado += 'Madera:{} '.format(addPuntos(md)) if vn: enviado += 'Vino:{} '.format(addPuntos(vn)) if mr: enviado += 'Marmol:{} '.format(addPuntos(mr)) if cr: enviado += 'Cristal:{} '.format(addPuntos(cr)) if az: enviado += 'Azufre:{}'.format(addPuntos(az)) print(enviado) print('¿Proceder? [Y/n]') rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() != 'n': ruta = (ciudadO, ciudadD, idIsla, md, vn, mr, cr, az) rutas.append(ruta) print('¿Realizar otro envio? [y/N]') rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() != 'y': break forkear(s) if s.padre is True: return info = '\nRuta comercial\n' for ruta in rutas: (ciudadO, ciudadD, idIsla, md, vn, mr, cr, az) = ruta info = info + '{} -> {}\nMadera: {} Vino: {} Marmol: {} Cristal: {} Azufre: {}\n'.format( ciudadO['cityName'], ciudadD['cityName'], addPuntos(md), addPuntos(vn), addPuntos(mr), addPuntos(cr), addPuntos(az)) setInfoSignal(s, info) try: msg = 'Comienzo a enviar recursos:\n' msg += info sendToBotDebug(msg, debugON_menuRutaComercial) planearViajes(s, rutas) msg = 'Termino de enviar recursos:\n' msg += info sendToBotDebug(msg, debugON_menuRutaComercial) except: msg = 'Error en:\n{}\nCausa:\n{}'.format(info, traceback.format_exc()) sendToBot(msg) finally: s.logout()
def entrenarTropas(s): banner() print(_('¿En qué ciudad quiere entrenar las tropas?')) ciudad = elegirCiudad(s) banner() for i in range(len(ciudad['position'])): if ciudad['position'][i]['building'] == 'barracks': ciudad['pos'] = str(i) break data = getCuartelInfo(s, ciudad) unidades_info = data[2][1] unidades = generateTroops(unidades_info) maxSize = 0 for unidad in unidades: if maxSize < len(unidad['local_name']): maxSize = len(unidad['local_name']) entrenamientos = [] while True: unidades = generateTroops(unidades_info) print(_('Entrenar:')) for unidad in unidades: cantidad = read(msg='{}{}:'.format( ' ' * (maxSize - len(unidad['local_name'])), unidad['local_name']), min=0, empty=True) if cantidad == '': cantidad = 0 unidad['cantidad'] = cantidad print(_('\nCosto total:')) costo = { 'madera': 0, 'vino': 0, 'marmol': 0, 'cristal': 0, 'azufre': 0, 'ciudadanos': 0, 'manuntencion': 0, 'tiempo': 0 } for unidad in unidades: if 'wood' in unidad['costs']: costo['madera'] += unidad['costs']['wood'] * unidad['cantidad'] if 'wine' in unidad['costs']: costo['vino'] += unidad['costs']['wine'] * unidad['cantidad'] if 'marble' in unidad['costs']: costo[ 'marmol'] += unidad['costs']['marble'] * unidad['cantidad'] if 'cristal' in unidad['costs']: costo['cristal'] += unidad['costs']['cristal'] * unidad[ 'cantidad'] if 'sulfur' in unidad['costs']: costo[ 'azufre'] += unidad['costs']['sulfur'] * unidad['cantidad'] if 'citizens' in unidad['costs']: costo['ciudadanos'] += unidad['costs']['citizens'] * unidad[ 'cantidad'] if 'upkeep' in unidad['costs']: costo['manuntencion'] += unidad['costs']['upkeep'] * unidad[ 'cantidad'] if 'completiontime' in unidad['costs']: costo['tiempo'] += unidad['costs']['completiontime'] * unidad[ 'cantidad'] if costo['madera']: print(_(' Madera: {}').format(addPuntos(costo['madera']))) if costo['vino']: print(_(' Vino: {}').format(addPuntos(costo['vino']))) if costo['marmol']: print(_(' Marmol: {}').format(addPuntos(costo['marmol']))) if costo['cristal']: print(_(' Cristal: {}').format(addPuntos(costo['cristal']))) if costo['azufre']: print(_(' Azufre: {}').format(addPuntos(costo['azufre']))) if costo['ciudadanos']: print(_(' Ciudadanos: {}').format(addPuntos(costo['ciudadanos']))) if costo['manuntencion']: print( _('Manutención: {}').format(addPuntos(costo['manuntencion']))) if costo['tiempo']: print( _(' Duración: {}').format( diasHorasMinutos(int(costo['tiempo'])))) print(_('\nProceder? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': return entrenamientos.append(unidades) print(_('\n¿Quiere entrenar más tropas al terminar? [y/N]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'y': banner() continue else: break recursos = getRecursosDisponibles(ciudad['html'], num=True) ciudadanos = getCiudadanosDisponibles(ciudad['html']) sobrante = {} sobrante['madera'] = recursos[0] sobrante['vino'] = recursos[1] sobrante['marmol'] = recursos[2] sobrante['cristal'] = recursos[3] sobrante['azufre'] = recursos[4] sobrante['ciudadanos'] = ciudadanos for entrenamiento in entrenamientos: for unidad in entrenamiento: if 'wood' in unidad['costs']: sobrante[ 'madera'] -= unidad['costs']['wood'] * unidad['cantidad'] if 'wine' in unidad['costs']: sobrante[ 'vino'] -= unidad['costs']['wine'] * unidad['cantidad'] if 'marble' in unidad['costs']: sobrante[ 'marmol'] -= unidad['costs']['marble'] * unidad['cantidad'] if 'cristal' in unidad['costs']: sobrante['cristal'] -= unidad['costs']['cristal'] * unidad[ 'cantidad'] if 'sulfur' in unidad['costs']: sobrante[ 'azufre'] -= unidad['costs']['sulfur'] * unidad['cantidad'] if 'citizens' in unidad['costs']: sobrante['ciudadanos'] -= unidad['costs']['citizens'] * unidad[ 'cantidad'] falta = [elem for elem in sobrante if sobrante[elem] < 0] != [] if falta: print(_('\nNo hay suficientes recursos:')) if sobrante['madera'] < 0: print( _(' Madera:{}').format(addPuntos(sobrante['madera'] * -1))) if sobrante['vino'] < 0: print(_(' Vino:{}').format(addPuntos(sobrante['vino'] * -1))) if sobrante['marmol'] < 0: print( _(' Marmol:{}').format(addPuntos(sobrante['marmol'] * -1))) if sobrante['cristal'] < 0: print( _(' Cristal:{}').format(addPuntos(sobrante['cristal'] * -1))) if sobrante['azufre'] < 0: print( _(' Azufre:{}').format(addPuntos(sobrante['azufre'] * -1))) if sobrante['ciudadanos'] < 0: print( _('Ciudadanos:{}').format( addPuntos(sobrante['ciudadanos'] * -1))) print(_('\n¿Proceder de todos modos? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': return print(_('\nSe entrenarán las tropas seleccionadas.')) enter() forkear(s) if s.padre is True: return info = _('\nEntreno tropas en {}\n').format(ciudad['cityName']) setInfoSignal(s, info) try: planearEntrenamientos(s, ciudad, entrenamientos) except: msg = _('Error en:\n{}\nCausa:\n{}').format(info, traceback.format_exc()) sendToBot(msg) finally: s.logout()
def enviarVino(s): banner() vinoTotal = 0 dict_idVino_diponible = {} (idsCiudades, ciudades) = getIdsDeCiudades(s) ciudadesVino = {} for idCiudad in idsCiudades: esVino = ciudades[idCiudad]['tradegood'] == '1' if esVino: html = s.get(urlCiudad + idCiudad) ciudad = getCiudad(html) recursos = getRecursosDisponibles(html) disponible = int(recursos[1]) - 1000 # dejo 1000 por las dudas ciudad['disponible'] = disponible if disponible > 0 else 0 vinoTotal += ciudad['disponible'] ciudadesVino[idCiudad] = ciudad aEnviar = len(ciudades) - len(ciudadesVino) vinoXciudad = int(vinoTotal / aEnviar) maximo = addPuntos(vinoXciudad) if vinoXciudad > 100000: maximo = maximo[:-6] + '00.000' elif vinoXciudad > 10000: maximo = maximo[:-5] + '0.000' elif vinoXciudad > 1000: maximo = maximo[:-3] + '000' elif vinoXciudad > 100: maximo = maximo[:-2] + '00' elif vinoXciudad > 10: maximo = maximo[:-1] + '0' print('Se puede enviar como máximo {} a cada ciudad'.format(maximo)) cantidad = read(msg='¿Cuanto vino enviar a cada ciudad?:', min=0, max=vinoXciudad) print('\nPor enviar {} de vino a cada ciudad'.format(addPuntos(cantidad))) print('¿Proceder? [Y/n]') rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': return forkear(s) if s.padre is True: return rutas = [] for idCiudadDestino in idsCiudades: if idCiudadDestino not in ciudadesVino: htmlD = s.get(urlCiudad + idCiudadDestino) ciudadD = getCiudad(htmlD) idIsla = ciudadD['islandId'] faltante = cantidad for idCiudadOrigen in ciudadesVino: if faltante == 0: break ciudadO = ciudadesVino[idCiudadOrigen] vinoDisponible = ciudadO['disponible'] for ruta in rutas: (origen, _, _, _, vn, _, _, _) = ruta if origen['id'] == idCiudadOrigen: vinoDisponible -= vn enviar = faltante if vinoDisponible > faltante else vinoDisponible faltante -= enviar ruta = (ciudadO, ciudadD, idIsla, 0, enviar, 0, 0, 0) rutas.append(ruta) info = '\nEnviar vino\n' for ruta in rutas: (ciudadO, ciudadD, idIsla, md, vn, mr, cr, az) = ruta info = info + '{} -> {}\nVino: {}\n'.format( ciudadO['cityName'], ciudadD['cityName'], addPuntos(vn)) setInfoSignal(s, info) try: planearViajes(s, rutas) except: msg = 'Error en:\n{}\nCausa:\n{}'.format(info, traceback.format_exc()) sendToBot(msg) finally: s.logout()
def repartirRecurso(s): banner() print(_('¿Qué recurso quiere repartir?')) print(_('(1) Vino')) print(_('(2) Marmol')) print(_('(3) Cristal')) print(_('(4) Azufre')) recurso = read(min=1, max=4) recursoTotal = 0 dict_idVino_diponible = {} (idsCiudades, ciudades) = getIdsDeCiudades(s) ciudadesOrigen = {} for idCiudad in idsCiudades: esTarget = ciudades[idCiudad]['tradegood'] == str(recurso) if esTarget: html = s.get(urlCiudad + idCiudad) ciudad = getCiudad(html) recursos = getRecursosDisponibles(html) disponible = int( recursos[recurso]) - 1000 # dejo 1000 por las dudas ciudad['disponible'] = disponible if disponible > 0 else 0 recursoTotal += ciudad['disponible'] ciudadesOrigen[idCiudad] = ciudad aEnviar = len(ciudades) - len(ciudadesOrigen) recursoXciudad = int(recursoTotal / aEnviar) maximo = addPuntos(recursoXciudad) if recursoXciudad > 1000: maximo = maximo[:-3] + '000' print(_('Se puede enviar como máximo {} a cada ciudad').format(maximo)) cantidad = read(msg=_('¿Cuanto enviar a cada ciudad?:'), min=0, max=recursoXciudad) if cantidad == 0: return print(_('\nPor enviar {} a cada ciudad').format(addPuntos(cantidad))) print(_('¿Proceder? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': return forkear(s) if s.padre is True: return rutas = [] for idCiudadDestino in [ idCity for idCity in idsCiudades if idCity not in ciudadesOrigen ]: htmlD = s.get(urlCiudad + idCiudadDestino) ciudadD = getCiudad(htmlD) idIsla = ciudadD['islandId'] faltante = cantidad for idCiudadOrigen in ciudadesOrigen: if faltante == 0: break ciudadO = ciudadesOrigen[idCiudadOrigen] recursoDisponible = ciudadO['disponible'] for ruta in rutas: origen = ruta[0] rec = ruta[recurso + 3] if origen['id'] == idCiudadOrigen: recursoDisponible -= rec enviar = faltante if recursoDisponible > faltante else recursoDisponible ocupado = getRecursosDisponibles(ciudadD['html'], num=True)[recurso] capacidad = getCapacidadDeAlmacenamiento(ciudadD['html'], num=True) disponible = capacidad - ocupado if disponible < enviar: faltante = 0 enviar = disponible else: faltante -= enviar if recurso == 1: ruta = (ciudadO, ciudadD, idIsla, 0, enviar, 0, 0, 0) elif recurso == 2: ruta = (ciudadO, ciudadD, idIsla, 0, 0, enviar, 0, 0) elif recurso == 3: ruta = (ciudadO, ciudadD, idIsla, 0, 0, 0, enviar, 0) else: ruta = (ciudadO, ciudadD, idIsla, 0, 0, 0, 0, enviar) rutas.append(ruta) info = _('\nRepartir recurso\n') for ruta in rutas: (ciudadO, ciudadD, idIsla, md, vn, mr, cr, az) = ruta rec = ruta[recurso + 3] info = info + _('{} -> {}\n{}: {}\n').format( ciudadO['cityName'], ciudadD['cityName'], tipoDeBien[recurso], addPuntos(rec)) setInfoSignal(s, info) try: planearViajes(s, rutas) except: msg = _('Error en:\n{}\nCausa:\n{}').format(info, traceback.format_exc()) sendToBot(msg) finally: s.logout()
def comprarRecursos(s): banner() ciudades_comerciales = getCiudadesComerciales(s) if len(ciudades_comerciales) == 0: print(_('No hay una Tienda contruida')) enter() return ciudad = ciudades_comerciales[0] # por ahora solo uso la primera ciudad numRecurso, recurso = asignarRecursoBuscado(s, ciudad) banner() ofertas = obtenerOfertas(s, ciudad) if len(ofertas) == 0: print(_('No se encontraron ofertas.')) return precio_total = 0 cantidad_total = 0 for oferta in ofertas: cantidad = oferta['cantidadDisponible'] unidad = oferta['precio'] costo = cantidad * unidad print(_('cantidad :{}').format(addPuntos(cantidad))) print(_('precio :{:d}').format(unidad)) print(_('costo :{}').format(addPuntos(costo))) print('') precio_total += costo cantidad_total += cantidad ocupado = getRecursosDisponibles(ciudad['html'], num=True)[numRecurso - 1] capacidad = getCapacidadDeAlmacenamiento(ciudad['html'], num=True) disponible = capacidad - ocupado print( _('Total disponible para comprar: {}, por {}').format( addPuntos(cantidad_total), addPuntos(precio_total))) if disponible < cantidad_total: print( _('Solo se puede comprar {} por falta de almacenamiento.').format( addPuntos(disponible))) cantidad_total = disponible print('') cantidadAComprar = read(msg=_('¿Cuánta cantidad comprar? '), min=0, max=cantidad_total) if cantidadAComprar == 0: return oro = getOro(s, ciudad) costoTotal = calcularCosto(ofertas, cantidadAComprar) print( _('\nOro actual : {}.\nCosto total: {}.\nOro final : {}.').format( addPuntos(oro), addPuntos(costoTotal), addPuntos(oro - costoTotal))) print(_('¿Proceder? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': return print(_('Se comprará {}').format(addPuntos(cantidadAComprar))) enter() forkear(s) if s.padre is True: return info = _('\nCompro {} de {} para {}\n').format(addPuntos(cantidadAComprar), tipoDeBien[numRecurso - 1], ciudad['cityName']) setInfoSignal(s, info) try: do_it(s, ciudad, ofertas, cantidadAComprar) except: msg = _('Error en:\n{}\nCausa:\n{}').format(info, traceback.format_exc()) sendToBot(msg) finally: s.logout()