示例#1
0
 def __init__(self, universe, username, password, server, delay=60, gap=60):
     self.ogame = OGame(universe, username, password, server)
     self.planet_ids = self.ogame.get_planet_ids()
     self.delay = delay
     self.gap = gap
     self.resources = {}
     self.resources_buildings = {}
     self.research = {}
示例#2
0
文件: ogi.py 项目: adi2004/pyogame
    def login(self, universe, user, password):
        pc.yellow("Logging in with %s" % user, end=" ")

        try:
            self.ogame = OGame(universe, user, password)
        except Exception as e:
            pp.red("Failed to login %s. Exception: " % user + str(e))
        else:
            if self.ogame.is_logged():
                pc.green("Success!")
                for p in self.planets:
                    p.ogame = self.ogame
示例#3
0
def login():
    try:
        arg = request.get_json()
        global empire
        empire = OGame(**arg)
        return {'login': '******'}
    except:
        return {'login': '******'}, 400
示例#4
0
文件: ogi.py 项目: adi2004/pyogame
    def get_resources(self, building_str="", level_diff=1):
        """Calculates the resources needed to build new building higher with level_diff then the current level"""
        res = self.data["resources"]

        cost = {}
        if building_str == "":
            cost['metal'] = 0
            cost['crystal'] = 0
            cost['deuterium'] = 0
        else:
            building_lvl = self.data["buildings"][building_str] + level_diff
            cost = OGame.calc_building_cost(building_str, building_lvl)

        missing = dict()
        missing['metal'] = max(0, cost['metal'] - res['metal'])
        missing['crystal'] = max(0, cost['crystal'] - res['crystal'])
        missing['deuterium'] = max(0, cost['deuterium'] - res['deuterium'])

        return missing
示例#5
0
def log_in():
    return OGame('Indus', '*****@*****.**', '1101982.Password')
示例#6
0
from ogame import OGame
from ogame.constants import Ships, Speed, Missions, Buildings, Research, Defense, Facilities

ogame = OGame("Indus", "*****@*****.**", "1101982.Ogame")


def check_energy(planet_name):
    return (ogame.get_resources(
        ogame.get_planet_by_name(planet_name)))["energy"] < 0


def building_in_construction(planet_name):
    return ogame.get_overview(
        ogame.get_planet_by_name(planet_name))["buildings"] != ""


def build_resources(planet_name):
    """Checking first if needed energy and try to build energy resources, and after,
        trying for building other resources"""
    if check_energy(planet_name):
        print("Trying to create more energy for the planet %s" % planet_name)
        for i in ["SolarPlant", "FusionReactor"]:
            ogame.build_building(ogame.get_planet_by_name(planet_name),
                                 Buildings[i])
            if len(ogame.get_overview(planet_name)["buildings"]) != 0:
                break
    else:
        print("Trying build resources for the planet %s" % planet_name)
        for k in [
                "CrystalMine",
                "MetalMine",
示例#7
0
文件: ogame_try.py 项目: lbun/og_lz
from ogame import OGame
from ogame.constants import Ships, Speed, Missions, Buildings, Research, Defense, Facilities

ogame = OGame("Indus", "*****@*****.**", "1101982.Password")


def deploy_fleet_to_moon_Milan(planet_name='Milan'):
    ships = [(Ships['LightFighter'], 999), (Ships['Cruiser'], 999),
             (Ships['Recycler'], 999), (Ships['Battleship'], 999),
             (Ships['Bomber'], 999), (Ships['Destroyer'], 999),
             (Ships['Battlecruiser'], 999)]
    speed = Speed["100%"]
    where = {'galaxy': 2, 'system': 335, 'position': 4, 'type': 3}
    mission = Missions["Park"]
    resources = {"metal": 99, "crystal": 99, "deuterium": 9999}
    ogame.send_fleet(ogame.get_planet_by_name(planet_name), ships, speed,
                     where, mission, resources)


def deploy_fleet_to_moon_Rome(planet_name='Rome'):
    ships = [(Ships['LightFighter'], 999), (Ships['Cruiser'], 999),
             (Ships['Recycler'], 999), (Ships['Battleship'], 999),
             (Ships['Bomber'], 999), (Ships['Destroyer'], 999),
             (Ships['Battlecruiser'], 999)]
    speed = Speed["100%"]
    where = {'galaxy': 3, 'system': 498, 'position': 6, 'type': 3}
    mission = Missions["Park"]
    resources = {"metal": 99, "crystal": 99, "deuterium": 9999}
    ogame.send_fleet(ogame.get_planet_by_name(planet_name), ships, speed,
                     where, mission, resources)
示例#8
0
        config = load_config(args.config)
        client_params = parse_client_config(config)
        bot_params = parse_bot_config(config)
        listeners = parse_listener_config(config)
        expeditions = parse_expedition_config(config)

        logging.debug('Loaded config from %s', args.config)

        # Scheduler notifies Cruiser about any new events
        #  (e.g. when it's time to defend a planet!).
        scheduler = Scheduler()

        # Client controls the account. It provides an interface to
        #  download and parse information from the OGame server as well as
        #  send commands to the servers.
        client = OGame(**client_params)

        # Cruiser makes the decisions. It receives events from the scheduler
        #  and acts accordingly. It's decision making is based on the
        #  information the client provides.
        bot = OGameBot(client, scheduler, **bot_params)

        # Add listeners (e.g. Telegram) that will notify users about
        #  important events (e.g. planet under attack).
        for listener in listeners:
            bot.add_listener(listener)
            logging.debug('Added listener: %s', type(listener).__name__)

        # Schedule expeditions if they were defined.
        for expedition in expeditions:
            scheduler.push(
示例#9
0
def log_in():
    return OGame('Indus', '*****@*****.**', '1101982.Ogame')
示例#10
0
def login():
    return OGame('Yildun', '*****@*****.**', 'trolona')
示例#11
0
文件: ogi.py 项目: adi2004/pyogame
class Account:
    """The bot contains an instance to the main page of the app"""

    # ogame logic
    ogame = None

    # data dictionary
    data = {}

    # array of planets and moons
    planets = []

    # persistance file
    file = "ogame.json"

    def __init__(self):
        print("Account.__init__")

    def login(self, universe, user, password):
        pc.yellow("Logging in with %s" % user, end=" ")

        try:
            self.ogame = OGame(universe, user, password)
        except Exception as e:
            pp.red("Failed to login %s. Exception: " % user + str(e))
        else:
            if self.ogame.is_logged():
                pc.green("Success!")
                for p in self.planets:
                    p.ogame = self.ogame

    #
    # Fetching functions (they display only status messages, not the data fetched)
    #

    def fetch_general(self):
        pc.yellow("Updating general user info")
        self.ogame.general_get_user_infos()

    def fetch_planets(self):
        if self.ogame is None:
            pp.red("Not logged in")
            return

        # read from the server
        pc.yellow("Updating all planet ids...")
        planets = self.ogame.get_planet_ids() + self.ogame.get_moon_ids()

        # convert to dict and save in data
        planets_dict = {}
        for p in planets:
            pc.yellow("Reading " + p, end="")
            planet_overview = self.ogame.get_planet_infos(p)
            planets_dict[planet_overview["planet_name"]] = planet_overview
            pc.green(" OK for " + planet_overview["planet_name"])

        # update the class member
        if "planets" not in self.data:
            self.data["planets"] = {}

        self.data["planets"].update(planets_dict)

    def fetch_account(self):
        #TODO: implement this
        if self.ogame is None:
            pp.red("Not logged in")
            return

    #
    # Print general account informations (rank, name, research queue, messages)
    #

    def pp(self):
        for planet in self.planets:
            planet.pp()

    #
    # Persistance functions
    #

    def load(self, file_name=None):
        """Reads the data from a json file"""
        if file_name is not None and self.file != file_name:
            print("Setting file to %s" % file_name)
            self.file = file_name
        file_name = self.file
        pc.bold("Loading %s" % file_name, end=" ")
        try:
            f = open(file_name, "r")
            data = f.read()
            f.close()
            # data = '{"planet": {"mines": "none"}, "moon": {"produciton": "tbd"}}'
            self.data = json.loads(data)
        except Exception as e:
            pp.red("JSON format error: " + str(e))
        else:
            self.init_planets()
            pc.green("Done.")

    def save(self, file_name=None):
        if file_name is not None and self.file != file_name:
            pp("Setting file to %s", file_name)
        file_name = self.file
        pc.bold("Saving to %s" % file_name, end=" ")

        # updated data
        for p in self.planets:
            if p.name() not in self.data["planets"]:
                self.data["planets"][p.name()] = {}
            self.data["planets"][p.name()].update(p.data)

        # write to file
        try:
            f = open(file_name, "w")
            f.write(json.dumps(self.data, indent=4))
            f.close()
        except Exception as e:
            pp.red("Something went wrong: " + str(e))
        else:
            pc.green("Done.")

    #
    # Data manipulation
    #

    def planet_data(self, planet_id):
        """Given an ID returns the planet data source (aka data)"""
        for planet in self.planets:
            if planet.id() == planet_id:
                return planet.data

    def init_planets(self):
        """Given an existing data, gets the `planets` key and creates attributes on the `Account` class"""
        if 'planets' not in self.data:
            pc.red(
                "Unable to initialize `planets`. No `planets` key found in `self.data`"
            )
        self.planets = []
        for k, v in self.data['planets'].items():
            planet = Planet(self, v)
            self.planets.append(planet)
            self.__setattr__(k.lower(), planet)
示例#12
0
import sys
from decouple import config
from ogame import OGame
from ogame.constants import Ships, Speed, Missions, Buildings, Research, Defense

ogame = OGame(config('UNIVERSE'), config('USERNAME'), config('PASSWORD'))


def farm(origin, destination):
    ships = [(Ships['SmallCargo'], 100)]

    ogame.send_fleet(origin['id'], ships, Speed['100%'],
                     destination['coordinates'], Missions['Attack'], {})
    print(ships, destination)


def fleet(origin, destination):
    availableShips = ogame.get_ships(origin['id'])
    availableResources = ogame.get_resources(origin['id'])

    smallCargoes = largeCargoes = 0
    resources = {'metal': 0, 'crystal': 0, 'deuterium': 0}

    # Prioritize deuterim, then crystal and then metal
    for resource in ['deuterium', 'crystal', 'metal']:
        for i in range(availableShips['small_cargo']):
            if (availableResources[resource] > 0
                    and availableShips['small_cargo'] > 0):
                amount = min(10000, availableResources[resource])
                resources[resource] += amount
                availableResources[resource] -= amount
示例#13
0
    response = empire.session.get('https://gf{}.geo.gfsrv.net/{}/{}'.format(
        nr, dir, res)).content
    return send_file(BytesIO(response), attachment_filename=res)


@barakis.route('/bot_settings', methods=['POST'])
def set_settings():
    new_settings = dict(request.form)
    for setting in bot_settings:
        bot_settings[setting] = ''
    for setting, value in new_settings.items():
        bot_settings[setting] = value
    Thread(target=bot.start_tasks, args=(empire, )).start()
    return redirect('/')


if universum == '' or username == '' or password == '':
    print('PLS input User Info')
    universum = input('Universum: ')
    username = input('Usernameor Email: ')
    password = input('Password: '******'Bad Login')
worker = Thread(target=bot.worker, args=(empire, ))
worker.start()
proxy = WSGIServer((ip_adress, 5000), barakis)
print('Visit: http://{}:5000'.format(ip_adress))
proxy.serve_forever()
示例#14
0
class BOT:
    def __init__(self, universe, username, password, server, delay=60, gap=60):
        self.ogame = OGame(universe, username, password, server)
        self.planet_ids = self.ogame.get_planet_ids()
        self.delay = delay
        self.gap = gap
        self.resources = {}
        self.resources_buildings = {}
        self.research = {}

    @staticmethod
    def pretty_dict(name, d):
        print "  " + "\033[91m" + name + "\033[0m"
        for key, value in d.iteritems():
            print "  {}: {}".format(key, value)

    def pretty_info(self):
        for planet_id in planet_ids:
            print '\033[92m' + str(datetime.datetime.now()) + '\033[0m'
            self.pretty_dict("resource", self.resources[planet_id])
            self.pretty_dict("resource level",
                             self.resources_buildings[planet_id])
            self.pretty_dict("research", self.research)

    def get_info(self, planet_id):
        for planet_id in self.planet_ids:
            self.resources[planet_id] = self.ogame.get_resources(planet_id)
            self.resources_buildings[
                planet_id] = self.ogame.get_resources_buildings(planet_id)
            self.research = self.ogame.get_research()

    def auto_escape(self):
        if not self.ogame.is_under_attack(): return
        print '\033[31m' + "under attack!! auto escape on!!" + '\033[0m'
        ships = []
        where = {'galaxy': 1, 'system': 161, 'position': 16}
        resources = {
            'metal': 10000000,
            'crystal': 10000000,
            'deuterium': 10000000
        }
        for value in Ships.values():
            ships.append((value, 10000))
        fleet_id = self.ogame.send_fleet(self.planet_ids[0], ships,
                                         Speed['100%'], where,
                                         Missions['Expedition'], resources)
        if fleet_id:
            print '\033[31m' + "successfully depart away from battle field!!" + '\033[0m'

    def auto_merge_resources(self, where):
        ships = []
        resources = {
            'metal': 10000000,
            'crystal': 10000000,
            'deuterium': 10000000
        }
        for value in Ships.values():
            ships.append((value, 10000))
        # assume mother planet at the first planet
        for planet_id in self.planet_ids[1:]:
            fleet_id = self.ogame.send_fleet(planet_id, ships, Speed['100%'],
                                             where, Missions['Transport'],
                                             resources)
            if fleet_id:
                print '\033[36m' + "send fleet from " + str(
                    planet_id) + '\033[0m'

    def auto_upgrade(self, positive_energy=True):
        if positive_energy and resource["energy"] < 0:
            ogame.build(planet_id, Buildings["SolarPlant"])
            ogame.build(planet_id, Buildings["FusionReactor"])
            if resource["energy"] < -60:
                ogame.build(planet_id, (Ships["SolarSatellite"], 1))
        else:
            for value in Buildings.values():
                ogame.build(planet_id, value)
            for value in Facilities.values():
                ogame.build(planet_id, value)
            for value in Research.values():
                ogame.build(planet_id, value)

    def run(self):
        while True:
            self.get_info()
            self.pretty_info()
            self.auto_escape()
            self.auto_merge_resources()
            time.sleep(random.randint(self.delay, self.delay + self.gap))