Esempio n. 1
0
    def run(self):
        """The main loop of the bot."""
        logger.info("Running bot '%s'", self.get_name())

        while True:
            data = yield from self.messages.get()
            if isinstance(data, Status):
                for cell in data.cells:
                    self.cells[cell.id] = cell
                for cell in data.dissapears:
                    if cell.id in self.cells:
                        del self.cells[cell.id]
                for eats in data.eat:
                    if eats.eatee == self.player_id:
                        self.alive = False
                    if eats.eatee in self.cells:
                        del self.cells[eats.eatee]
            elif isinstance(data, PlayerCell):
                self.player_id = data.cell.id
                self.alive = True
            elif isinstance(data, ScreenAndCamera):
                self.screen = data.screen
            else:
                pass

            if not self.alive:
                yield from self.client.spawn()
            yield from self.do_move()
Esempio n. 2
0
    def create_party(self):
        """Create a new party."""
        logger.info("Creating a new party.")
        region = b":".join((self.region.encode('ascii'), b"party"))
        data = b"\n".join((region, INIT_TOKEN.encode('ascii')))
        res = requests.post('https://m.agar.io/',
                            data=data,
                            headers={'Origin': 'http://agar.io',
                                     'User-Agent': USER_AGENT,
                                     'Referer': 'http://agar.io/'})

        self.server, self.token, _ = res.text.split('\n')
        logger.debug("Server: %s", self.server)
        logger.info("Party Token: %s", self.token)
Esempio n. 3
0
    def connect(self):
        """Connects to the server."""
        if self.server is None:
            self.get_server()

        logger.info("Connecting to server %s", self.server)
        self.ws = yield from websockets.connect("ws://" + self.server,
                                                origin='http://agar.io')
        yield from self.ws.send(struct.pack("<BI", 254, PROTO_VERSION))
        yield from self.ws.send(struct.pack("<BI", 255, int(INIT_TOKEN)))

        # Send token
        msg = struct.pack("B" + ("B" * len(self.token)),
                          80, *[ord(c) for c in self.token])

        yield from self.ws.send(msg)
        logger.debug("Connected!")
        self.connected.set()
Esempio n. 4
0
def pyagar(argv=None):
    """pyagar cli interface."""
    from pyagar.client import Client
    from pyagar.log import logger
    from pyagar.utils import hub, GameplaySaver, GameReplay
    from pyagar.visual import Visualizer

    args = pyagar_parser().parse_args(argv)
    if args.command is None:
        logger.error("No subcommand present. To play execute: 'pyagar play'")
        sys.exit(1)

    coros = []
    dsts = []

    if args.debug is not None:
        logger.setLevel(logging.DEBUG)

        if args.debug > 1:
            from pyagar.utils import Output
            output = Output()
            coros.append(output.run())
            dsts.append(output)
    else:
        logger.setLevel(logging.INFO)

    logger.info("Starting pyagar!")
    if VERSION:
        logger.info("Version %s", VERSION)

    if args.command == "replay":
        visualizer = Visualizer(
            None,
            view_only=True,
            hardware=not args.disable_hw)
        dsts.append(visualizer)
        
        replayer = GameReplay(args.gameplay_file[0])

        coros.append(replayer.run())
        coros.append(visualizer.run())
        coros.append(hub(replayer, *dsts))

    else:
        party = args.create_party or args.join_party or False
        client = Client(args.nick, region=args.region, party=party)
        coros.append(client.read())

        visualizer = Visualizer(
            client,
            view_only=args.command != "play",
            hardware=not args.disable_hw)
        coros.append(visualizer.run())
        dsts.append(visualizer)

        if args.command == "list-regions":
            from pyagar.utils import print_regions
            print_regions(client.get_regions())
            sys.exit(0)
        elif args.command == "bot":
            if args.list_types:
                print("Available bot types:\n")
                from pyagar.control import Controller
                for cls in Controller.__subclasses__():
                    doc = cls.__doc__ if cls.__doc__ else '**Not documented**'
                    dedented_text = textwrap.dedent(doc).strip()
                    name = ' * %s: ' % cls.__name__
                    msg = textwrap.fill(
                        dedented_text,
                        initial_indent=name,
                        subsequent_indent='    ')
                    print(msg)
                sys.exit(0)
            elif args.type:
                from pyagar import control
                if not hasattr(control, args.type):
                    print("Unknown bot type")
                    sys.exit(1)
                else:
                    bot = getattr(control, args.type)
                    if (not issubclass(bot, control.Controller) or
                            bot is control.Controller):
                        print("Invalid bot type.")
                        sys.exit(1)
                    else:
                        controller = bot(client)
                        coros.append(controller.run())
                        dsts.append(controller)
            elif args.from_file:
                from pyagar.control import Controller
                module = imp.load_source('botmodule', args.from_file)
                if (not hasattr(module, 'UserBot') or
                        not issubclass(module.UserBot, Controller)):
                    print("Invalid bot.")
                else:
                    controller = module.UserBot(client)
                    coros.append(controller.run())
                    dsts.append(controller)

        if args.save is not None:
            saver = GameplaySaver(args.save)
            coros.append(saver.run())
            dsts.append(saver)

        coros.append(hub(client, *dsts))

        LOOP.run_until_complete(client.connect())

        if args.command == "spectate":
            LOOP.run_until_complete(client.spectate())

    game = asyncio.wait(coros, return_when=asyncio.FIRST_COMPLETED)
    done, _ = LOOP.run_until_complete(game)
    for coro in done:
        try:
            coro.result()
        except:
            logger.exception("Exception running coroutine.")

    logger.info("Bye!")