示例#1
0
    def send_command(self, command):
        if self.output is None:
            return

        command_list = CommandList(command)

        self.output.write(command_list.to_json().encode('utf-8'))
示例#2
0
        async def wrapped_issue_command(self):
            res = await issue_command(self)

            if isinstance(res, Command):
                return CommandList(res)

            elif isinstance(res, (list, tuple)):
                return CommandList(*res)

            elif isinstance(res, CommandList):
                return res

            # If no command has been sent, propagate it
            elif res is None:
                return None

            # TODO: stop execution nicely if return value is
            # incompatible with server
            else:
                name = type(self).__name__
                print(f'Return value from {name}.issue_command() '
                      'is incompatible with server. '
                      'Expected Command, tuple or list of Commands, '
                      'or a CommandList.')
                self.loop.stop()
示例#3
0
文件: gamestate.py 项目: quilan1/TM
    def passTurn(self, playerNumber):
        bonusCards = self.bonusCards;
        player = self.players[playerNumber];
        commandPicker = CommandPicker("Pass Turn...");

        if player.bonusCard == BonusCard.Power3Shipping:
            commandPicker.append( Command(["ChangeResources", playerNumber] + Resources(shipping=-1).asList()) );
        commandPicker.append( Command(["ReturnBonusCard", playerNumber, player.bonusCard]) );

        commandOptions = CommandOptions();
        for card,coins in bonusCards.items():
            commandList = CommandList("Take BonusCard: %s (%s)"%(BonusCard.BonusCardList[card], Resources(coins=coins)));
            gainedResources = Resources(coins=coins);
            if card == BonusCard.Power3Shipping: gainedResources.shipping += 1;
            commandList.append( Command(["ChangeResources", playerNumber] + gainedResources.asList()) );
            commandList.append( Command(["TakeBonusCard", playerNumber, card]) );
            commandOptions.append( commandList );
        commandPicker.append( commandOptions );

        commandPicker.append( Command(["PassTurn", playerNumber]) );

        if all( player.hasPassed==False for player in self.players.values() ):
            commandPicker.append( Command(["SetStartingPlayer", playerNumber]) );

        if sum( 1 if player.hasPassed else 0 for player in self.players.values() ) == 1:
            commandPicker.append( Command(["StartTurn", self.currentTurn + 1]) );

        return commandPicker;
示例#4
0
 def __init__(self):
     logging.basicConfig(
         format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
         level=logging.INFO)
     self.config = Config()
     self.updater = Updater(token=self.config.get_config(TOKEN))
     self.dispatcher = self.updater.dispatcher
     self.filter_users = Filters.user(username=Users().get_list_users())
     self.rso = ReportSO()
     self.command_list = CommandList()
示例#5
0
文件: gamestate.py 项目: quilan1/TM
    def upgradeTerraform(self, playerNumber):
        player = self.players[playerNumber];
        if player.resources.terraform >= 2: return Command.Null;

        result, resourcesDelta = player.canMakeResources(workers=2, coins=5, priests=1);
        if result == False: return Command.Null;

        resourcesDelta += Resources(victoryPoints=6, terraform=1);
        commandList = CommandList("Upgrade Terraforming (%s)"%resourcesDelta);
        commandList.append( Command(["ChangeResources", playerNumber]+resourcesDelta.asList()) );
        return commandList;
示例#6
0
文件: gamestate.py 项目: quilan1/TM
    def upgradeShipping(self, playerNumber):
        player = self.players[playerNumber];
        if player.resources.shipping >= 3: return Command.Null;

        result, resourcesDelta = player.canMakeResources(coins=4, priests=1);
        if result == False: return Command.Null;

        resourcesDelta += Resources(victoryPoints=2, shipping=1);
        commandList = CommandList("Upgrade Shipping (%s)"%resourcesDelta);
        commandList.append( Command(["ChangeResources", playerNumber]+resourcesDelta.asList()) );
        return commandList;
示例#7
0
文件: gamestate.py 项目: quilan1/TM
    def iterBonusCardActions(self, playerNumber):
        player = self.players[playerNumber];
        bonusCard = player.bonusCard;

        if bonusCard in self.actionTokens: return Command.Null;

        #TODO: Add More
        if bonusCard == BonusCard.ShovelCoin2:
            commandList = CommandList("BonusCard: Acquire Shovel");
            commandList.append( Command(["ChangeResources", playerNumber] + Resources(shovels=1).asList()) );
            commandList.append( Command(["PerformActionToken", playerNumber, ActionToken.BonusShovel]) );
            return commandList;
        return Command.Null;
示例#8
0
文件: gamestate.py 项目: quilan1/TM
    def iterPowerActions(self, playerNumber):
        player = self.players[playerNumber];
        availActionTokens = set(range(ActionToken.NumberActionTokens)) - self.actionTokens;
        availActionTokens -= { ActionToken.BonusShovel };

        commandOptions = CommandOptions("Perform Power Action...");
        for actionToken in sorted(availActionTokens):
            resourcesGained = Resources();
            if actionToken == ActionToken.PowerBridge:
                powerRequired = 3;
            elif actionToken == ActionToken.PowerPriest:
                powerRequired = 3;
                resourcesGained = Resources(priests=1);
            elif actionToken == ActionToken.PowerWorkers:
                powerRequired = 4;
                resourcesGained = Resources(workers=2);
            elif actionToken == ActionToken.PowerCoins:
                powerRequired = 4;
                resourcesGained = Resources(coins=7);
            elif actionToken == ActionToken.PowerShovel:
                powerRequired = 4;
                resourcesGained = Resources(shovels=1);
            elif actionToken == ActionToken.PowerShovel2:
                powerRequired = 6;
                resourcesGained = Resources(shovels=2);
            else: continue;

            result, resourcesDelta = player.canMakeResources(power=powerRequired);
            if result == False: continue;
            resourcesDelta += resourcesGained;

            commandList = CommandList("%s (%s)"%(ActionToken.ActionTokenList[actionToken], resourcesDelta));
            commandList.append( Command(["ChangeResources", playerNumber]+resourcesDelta.asList()) );
            commandList.append( Command(["PerformActionToken", playerNumber, actionToken]) );
            commandOptions.append( commandList );

        return commandOptions;
示例#9
0
文件: gamestate.py 项目: quilan1/TM
    def iterBuildingPower(self, playerNumber, hex):
        powerAmount = {};
        for neighbor in hex.neighbors:
            key = (neighbor.y, neighbor.x);
            if key not in self.buildings: continue;
            building = self.buildings[key];
            if building.playerNumber == playerNumber: continue;

            if building.buildingType == Building.Dwelling: buildingRank = 1;
            elif building.buildingType == Building.TradingHouse or building.buildingType == Building.Temple: buildingRank = 2;
            else: buildingRank = 3;
            try: powerAmount[building.playerNumber] += buildingRank;
            except: powerAmount[building.playerNumber] = buildingRank;

        commandList = CommandList();
        for playerNumber, power in sorted( powerAmount.items() ):
            resourcesDelta = Resources(power=power,victoryPoints=-(power-1));
            playerName = str(Race(self.players[playerNumber].race));
            commandOptions = CommandOptions(evalAsPlayer=playerNumber);
            description = "Player %s (%s) takes (%s)"%(playerNumber, playerName, resourcesDelta);
            commandOptions.append( Command(["ChangeResources", playerNumber] + resourcesDelta.asList(), description) );
            commandOptions.append( Command.Null );
            commandList.append( commandOptions );
        return commandList;
示例#10
0
class ReportSO:

    def __init__(self):
        self.command_list = CommandList()

    @staticmethod
    def get_return_command(command):
        return_command = Command(command).execute()
        return FormatText(return_command).format()

    def report(self,command,parameters=None):
        name_command = command.lower()
        if self.command_list.is_command_valid(name_command,parameters):
            command_clear = self.command_list.clear_command(name_command)
            return_command = Command(command_clear,parameters=parameters).execute()
            return FormatText(return_command).format()
        else:
            return 'Comando não valido.\nConsulte a ajuda com /help'            

    def get_list_commands(self):
        return self.command_list.get_commands_text()

    def get_list_commands_help(self):
        return self.command_list.get_commands_text_help()
示例#11
0
    def data_received(self, data):
        """Receive commands from the server

        A received command must have the following field:
            command:        JOIN/START/SUCCESSFUL_TRADE/BOOK_EVENT/END_GAME/
                            ERROR

        Optionally, a received command may also contain:
            bot_id:         the unique identifier given by the server
            hand:           the starting hand
            cards:          the cards received from a trade
        """
        try:
            self.received_cmds = CommandList.from_bytes(data)
        except UnicodeDecodeError as e:
            print('Received invalid unicode')
            return
        except JSONDecodeError as e:
            print('Received invalid JSON')
            return

        print(f'RECEIVED {self.received_cmds!r}')

        if Command.JOIN in self.received_cmds:
            self._on_join.set()

        if Command.START in self.received_cmds:
            print('Starting game...')
            self._on_start.set()

        if Command.SUCCESSFUL_TRADE in self.received_cmds:
            pass

        if Command.BOOK_EVENT in self.received_cmds:
            pass

        if Command.END_ROUND in self.received_cmds:
            pass

        if Command.END_GAME in self.received_cmds:
            print('Stopping game...')
            self._on_start.clear()

        if Command.ERROR in self.received_cmds:
            pass
示例#12
0
文件: gamestate.py 项目: quilan1/TM
    def iterUpgradeBuilding(self, playerNumber):
        player = self.players[playerNumber];

        menuPoints = [];
        commandOptions = CommandOptions("Upgrade Building...");
        for (y,x),b in self.buildings.items():
            if b.playerNumber != playerNumber: continue;
            if b.buildingType == Building.Stronghold or b.buildingType == Building.Sanctuary: continue;

            upgradeTo = [];
            if   b.buildingType == Building.Dwelling:     upgradeTo.append(Building.TradingHouse);
            elif b.buildingType == Building.TradingHouse: upgradeTo.append(Building.Stronghold); upgradeTo.append(Building.Temple);
            elif b.buildingType == Building.Temple:       upgradeTo.append(Building.Sanctuary);

            costResult = [];
            for upgradeToType in upgradeTo:
                try:    cost = Building.BuildingCost[player.race][upgradeToType];
                except: cost = Building.BuildingCost[Race.Unknown][upgradeToType];
                result, resourcesDelta = player.canMakeResources(cost);
                if result == False: continue;
                costResult.append( (upgradeToType, resourcesDelta) );
            if len(costResult) == 0: continue;

            for upgradeTo, resourcesDelta in costResult:
                index = len(menuPoints);
                menuPoints.append((y,x));
                if index >= 10: index = chr(ord('a') + index-10);
                indexString = "[%s]"%index;

                if upgradeTo == Building.TradingHouse:
                    neighbors = worldMap.hexes[y][x].neighbors;
                    if any( (h.y,h.x) in self.buildings and self.buildings[h.y,h.x].playerNumber != playerNumber for h in neighbors ):
                        resourcesDelta.coins /= 2;

                commandList = CommandList("Upgrade %s to %s at %s (%s)"%(Building.BuildingList[b.buildingType], Building.BuildingList[upgradeTo], indexString, resourcesDelta));
                commandList.append( Command(["ChangeResources", playerNumber]+resourcesDelta.asList()) );
                commandList.append( Command(["UpgradeBuilding", y, x, upgradeTo]) );
                commandList.append( self.iterBuildingPower(playerNumber, worldMap.hexes[y][x]) );
                commandOptions.append( commandList );

        commandOptions = simplifyCommand( commandOptions );
        for command in commandOptions.commands: command.removeNulls();
        commandOptions.ui = ( UI.DisplayWorld, menuPoints );

        return commandOptions;
示例#13
0
    def __init__(self, loop=None):
        self.transport = None
        self.loop = loop if loop else asyncio.get_event_loop()

        # asynchronous queue
        self.queue = asyncio.Queue()

        # asynchronous methods
        asyncio.ensure_future(self._send_from_queue())
        asyncio.ensure_future(self.join_game())
        asyncio.ensure_future(self.start_game())

        # asynchronous events
        self._on_join = asyncio.Event()
        self._on_start = asyncio.Event()

        # Billionaire bot variables
        self.received_cmds = CommandList()
        self.id = ''
        self.hand = CardLocation()
示例#14
0
    is_admin = database.is_admin(message.from_user.id)
    help_str = ""
    for command in commands:
        if not command.is_admin_command or (command.is_admin_command and is_admin):
            help_str += "/{} - {}\n".format(command.command, command.short_description)
    bot.send_message(message.chat.id, help_str)

help_command = Command("help", "Список доступных команд", do=do_help)


commands = CommandList(start_command,
                       help_command,
                       users_command,
                       set_admin_command,
                       check_photos_command,
                       # Command("get_image_info", "Получить информацию об изображении", do=do_get_image_info,
                       #         need_answer=True,
                       #         echo=answer_get_image_info),
                       # Command("publish", "Опубликовать контент немедленно", do=do_publish, is_admin_command=True),
                       # Command("words", "Список слов", is_admin_command=True, do=do_words),
                       # Command("addword", "Добавить слово вида 'окнО'", do=do_addword, is_admin_command=True,
                       #         need_answer=True, echo=answer_addword),
                       # Command("addwordsfromfile", "Добавить слова из файла", do=do_addwordsfromfile,
                       #         is_admin_command=True, need_answer=True, echo=answer_addwordsfromfile),
                       publish_command,
                       execute_command,
                       remove_keyboard_command
                       # Command("exercise", "Начать тест на ударения", do=do_exercise, need_answer=True,
                       #         echo=answer_exercise)
                       )
示例#15
0
    def on_read(self, source_object, result, *user_data):
        """Receive commands from the server"""
        data = source_object.read_bytes_finish(result).get_data()

        try:
            self.received_cmds = CommandList.from_bytes(data)
        except UnicodeDecodeError as e:
            print('Received invalid unicode')
            return
        except JSONDecodeError as e:
            print('Received invalid JSON')
            print(data)
            return

        print(f'RECEIVED {self.received_cmds!r}')

        # Always parse errors first!
        if Command.ERROR in self.received_cmds:
            error_cmd = self.received_cmds[Command.ERROR]
            self.feed.add_to_feed(Command.ERROR, error_cmd.what)

        if Command.JOIN in self.received_cmds:
            join_cmd = self.received_cmds[Command.JOIN]
            self.id = join_cmd.client_id
            self.feed.add_to_feed(Command.JOIN, f'ID set to {self.id!r}')

        if Command.START in self.received_cmds:
            print('Starting game...')
            start_cmd = self.received_cmds[Command.START]

            hand = CardLocation.from_json(start_cmd.hand)
            self.add_cards_to_gui(hand)
            self.feed.add_to_feed(Command.START, f'Receiving hand...')

        if Command.SUCCESSFUL_TRADE in self.received_cmds:
            trade_cmd = self.received_cmds[Command.SUCCESSFUL_TRADE]

            trade = CardLocation.from_json(trade_cmd.cards)
            partner = trade_cmd.owner_id

            self.offers.data.remove_offer(len(trade))
            self.add_cards_to_gui(trade)

            self.feed.add_to_feed(Command.SUCCESSFUL_TRADE,
                                  f'Traded {len(trade)} cards with {partner}')

        if Command.CANCELLED_OFFER in self.received_cmds:
            cancelled_cmd = self.received_cmds[Command.CANCELLED_OFFER]

            offer = CardLocation.from_json(cancelled_cmd.cards)
            self.add_cards_to_gui(offer)

        if Command.BOOK_EVENT in self.received_cmds:
            book_cmd = self.received_cmds[Command.BOOK_EVENT]

            if book_cmd.event == Command.NEW_OFFER:
                owner = book_cmd.participants[0]
                self.offers.data.add_offer(book_cmd.card_amt, owner)

                self.feed.add_to_feed(
                    Command.BOOK_EVENT, f'New offer of {book_cmd.card_amt} '
                    f'cards from {owner}')

            elif book_cmd.event == Command.CANCELLED_OFFER:
                owner = book_cmd.participants[0]
                self.offers.data.remove_offer(book_cmd.card_amt)

                self.feed.add_to_feed(
                    Command.BOOK_EVENT, f'Offer of {book_cmd.card_amt} '
                    f'cancelled by {owner}')

            elif book_cmd.event == Command.SUCCESSFUL_TRADE:
                active, passive = book_cmd.participants
                self.offers.data.remove_offer(book_cmd.card_amt)

                self.feed.add_to_feed(
                    Command.BOOK_EVENT, f'{active} traded {passive}\'s '
                    f'offer of {book_cmd.card_amt} cards')

        if Command.END_GAME in self.received_cmds:
            self.feed.add_to_feed(Command.END_GAME, 'Stopping game...')
            self.hand.clear_all()
            self.offers.clear_all()

        if Command.BILLIONAIRE in self.received_cmds:
            billionaire_cmd = self.received_cmds[Command.BILLIONAIRE]
            winner = billionaire_cmd.winner_id

            if winner == self.id:
                self.feed.add_to_feed(Command.BILLIONAIRE, 'A winner is you!')
            else:
                self.feed.add_to_feed(Command.BILLIONAIRE,
                                      f'Bad luck, {winner} won.')

        if Command.END_ROUND in self.received_cmds:
            end_round_cmd = self.received_cmds[Command.END_ROUND]
            new_score = end_round_cmd.score

            self.feed.add_to_feed(Command.END_ROUND,
                                  f'Your current score is now {new_score}')

        # Continually add this
        source_object.read_bytes_async(MessagePasser.READ_BYTES,
                                       GLib.PRIORITY_DEFAULT, self.cancellable,
                                       self.on_read)
示例#16
0
文件: gamestate.py 项目: quilan1/TM
    def iterTerraform(self, playerNumber):
        player = self.players[playerNumber];
        raceTerrain = Race.RaceTerrain[player.race];
        points = self.getPointsTerraform(playerNumber);

        menuPoints = [];
        commandOptions = CommandOptions("Terraform / Place Dwelling...");
        for y,x in points:
            hex = worldMap.hexes[y][x];
            hexTerrain = hex.terrain;
            if (y,x) in self.terraform: hexTerrain = self.terraform[y,x];
            shovelsRequired = raceTerrain - hexTerrain;
            shovelsRequired = min(shovelsRequired%7, (7-shovelsRequired)%7);
            if shovelsRequired == 0: continue;

            result, resourcesDelta = player.canMakeResources(shovels=shovelsRequired);
            if result == False: continue;

            index = len(menuPoints);
            menuPoints.append((y,x));
            if index >= 10: index = chr(ord('a') + index-10);
            indexString = "[%s]"%index;

            newPlayer = Player();
            newPlayer.copyPlayer(player);
            newPlayer.changeResources(resourcesDelta);

            commandPicker = CommandPicker();
            if resourcesDelta.isEmpty() == False:
                commandPicker = CommandPicker("Terraform at %s (%s)"%(indexString, resourcesDelta));
                commandList = CommandList();
                commandList.append( Command(["ChangeResources", playerNumber]+resourcesDelta.asList()) );
                commandList.append( Command(["TerraformHex", playerNumber, y, x]) );
                commandPicker.append(commandList);

            result, resourcesDelta = newPlayer.canMakeResources(workers=1, coins=2);
            if result == True:
                del newPlayer;

                buildingOptions = CommandOptions();
                commandList = CommandList("Place Dwelling at %s (%s)"%(indexString, resourcesDelta));
                commandList.append( Command(["ChangeResources", playerNumber]+resourcesDelta.asList()) );
                commandList.append( Command(["PlaceBuilding", playerNumber, y, x, 0]) );
                commandList.append( self.iterBuildingPower(playerNumber, worldMap.hexes[y][x]) );
                buildingOptions.append( commandList );

                buildingOptions.append( Command.Null );
                commandPicker.append( buildingOptions );

            commandOptions.append( commandPicker );

        #We want to make sure all of these are actually actions we can take, not null-sets
        commandOptions = simplifyCommand( commandOptions );
        for command in commandOptions.commands: command.removeNulls();
        commandOptions.ui = ( UI.DisplayWorld, menuPoints );

        return commandOptions;
示例#17
0
 def __init__(self):
     self.command_list = CommandList()
示例#18
0
class Bot:
    def __init__(self):
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.INFO)
        self.config = Config()
        self.updater = Updater(token=self.config.get_config(TOKEN))
        self.dispatcher = self.updater.dispatcher
        self.filter_users = Filters.user(username=Users().get_list_users())
        self.rso = ReportSO()
        self.command_list = CommandList()

    def start(self, bot, update):
        bot.send_message(chat_id=update.message.chat_id,
                         text=self.config.get_config(WELCOME))

    @staticmethod
    def echo(bot, update):
        bot.send_message(chat_id=update.message.chat_id,
                         text=update.message.text)

    def unknown(self, bot, update):
        bot.send_message(chat_id=update.message.chat_id,
                         text=self.config.get_config(COMMAND_NOT_FOUND))

    def help(self, bot, update):
        bot.send_message(chat_id=update.message.chat_id,
                         text=self.rso.get_list_commands_help())

    def command(self, bot, update, args):
        bot.send_message(chat_id=update.message.chat_id,
                         text=self.rso.get_return_command(' '.join(args)))

    def command_authorized(self, bot, update):
        report = self.rso.report(update.message.text)
        bot.send_message(chat_id=update.message.chat_id, text=report)

    def command_authorized_paramter(self, bot, update, args):
        command = update.message.text.split(' ')[0]
        report = self.rso.report(command, ' '.join(args))
        bot.send_message(chat_id=update.message.chat_id, text=report)

    def main(self):
        start_handler = CommandHandler('start',
                                       self.start,
                                       filters=self.filter_users)
        help_handler = CommandHandler('help',
                                      self.help,
                                      filters=self.filter_users)
        command_handler = CommandHandler('cl',
                                         self.command,
                                         pass_args=True,
                                         filters=self.filter_users)
        command_authorized_handler = CommandHandler(
            self.command_list.get_commands_name_without_parameter(),
            self.command_authorized,
            filters=self.filter_users)
        command_authorized_parameter_handler = CommandHandler(
            self.command_list.get_commands_name_with_parameter(),
            self.command_authorized_paramter,
            pass_args=True,
            filters=self.filter_users)
        echo_handler = MessageHandler(Filters.text, self.echo)
        unknown_handler = MessageHandler(Filters.command, self.unknown)

        self.dispatcher.add_handler(start_handler)
        self.dispatcher.add_handler(help_handler)
        self.dispatcher.add_handler(command_handler)
        self.dispatcher.add_handler(echo_handler)
        self.dispatcher.add_handler(command_authorized_handler)
        self.dispatcher.add_handler(command_authorized_parameter_handler)
        self.dispatcher.add_handler(unknown_handler)

        self.updater.start_polling()