예제 #1
0
 def __init__(self, exit_on_game_over=False):
     self.actions = ActionFactory(self)
     self.deck1 = []
     self.deck2 = []
     self.players = []
     self.sides = [[], []]
     self.active_player = 0
     self.exit_on_game_over = exit_on_game_over
     self.winner = None
예제 #2
0
    def load_config(self, xml_document):
        """Parses the XML config file"""
        try:
            root = ET.fromstring(xml_document)
        except UnicodeEncodeError:
            root = ET.fromstring(xml_document.encode('utf-8'))

        #
        # Find organization node
        #
        self.organization = (root.findall('organization') + [None])[0]

        #
        # Find (first) deviceconfig node
        #
        self.devicecfg = root.find('configurations/deviceConfiguration')

        #
        # Read reporting config and initialize reporter
        #
        try:
            reporting = next(
                iter(
                    filter(
                        lambda n: int(n.get('type', '0')) ==
                        SW2_PALADIN_REPORT_HANDLER_CLOUD,
                        self.devicecfg.findall('reporting/handlers/handler'))))
        except StopIteration:
            reporting = None

        self.reporter = PaladinCloudReporter(reporting, self.devicecfg,
                                             self.organization)
        self.resources = load_resources(
            self.devicecfg.findall('customization/resources/resource'))

        #
        # Create actions
        #
        factory = ActionFactory(self)
        self.actions = [
            factory.create(a) for a in self.devicecfg.findall('actions/action')
        ]
예제 #3
0
 def parse(self,stream):
     self.actions = []
     while stream.peek('uintle:8') != 0:
         action_code = datatypes.UI8(stream)
         action_length = 0
         if action_code > 0x7F:
             action_length = datatypes.UI16(stream)
         action_stream = stream.read('bits:{0}'.format(action_length*8))
         self.actions.append(ActionFactory.new_action(action_stream,
                                                      action_code,
                                                      action_length))        
예제 #4
0
 def parse(self,stream):
     self.sprite_id = stream.read('uintle:16')
     self.actions = []
     while stream.peek('uintle:8') != 0:
         action_code = stream.read('uintle:8')
         action_length = 0
         if action_code > 0x7F:
             action_length = stream.read('uintle:16')
         action_stream = stream.read('bits:{0}'.format(action_length*8))
         self.actions.append(ActionFactory.new_action(action_stream,
                                                      action_code,
                                                      action_length))        
예제 #5
0
class Game:
    player = Player()
    computer = Player()
    scanner = Scanner()
    rounds = 0
    actionFactory = ActionFactory()

    def run(self):
        self.rounds = self.scanner.readRoundNumber()

        if self.rounds == False:
            self.run()
            return False

        i = 0
        while i < int(self.rounds):
            print("Make your choice for round " + str(i) + ": ")

            action = self.scanner.readActionName()

            if action != False:
                self.player.currentAction = self.actionFactory.createAction(
                    action)

                self.computer.currentAction = self.actionFactory.getRandomAction(
                )

                result = self.player.currentAction.attack(
                    self.player.currentAction, self.computer.currentAction)

                if result == True:
                    self.player.score += 1
                if result == False:
                    self.computer.score += 1
                i += 1

        self.showResults()

    def showResults(self):
        if self.player.score > self.computer.score:
            print("Result: You won " + str(self.player.score) +
                  " time(s), your opponent won " + str(self.computer.score) +
                  " time(s). You win!")
        if self.player.score < self.computer.score:
            print("Result: You won " + str(self.player.score) +
                  " time(s), your opponent won " + str(self.computer.score) +
                  " time(s). Your oponnent wins!")
        if self.player.score == self.computer.score:
            print("Result: You won " + str(self.player.score) +
                  " time(s), your opponent won " + str(self.computer.score) +
                  " time(s). It's a tie!")
예제 #6
0
 def __init__(self,stream,swf_version):
     self.event_flags = ClipEventFlags(stream,swf_version)
     self.action_record_size = stream.read('uintle:32')
     initial_bytepos = stream.bytepos
     if hasattr(self.event_flags,"clip_event_key_press") and self.event_flags.clip_event_key_press == True:
         self.key_code = stream.read('uintle:8')
     self.actions = []
     while stream.bytepos < initial_bytepos + self.action_record_size:
         action_code = stream.read('uintle:8')
         action_length = 0
         if action_code > 0x7F:
             action_length = stream.read('uintle:16')
         action_stream = stream.read('bits:{0}'.format(action_length*8))
         self.actions.append(ActionFactory.new_action(action_stream,
                                                      action_code,
                                                      action_length) )
예제 #7
0
class Board:
    def __init__(self, exit_on_game_over=False):
        self.actions = ActionFactory(self)
        self.deck1 = []
        self.deck2 = []
        self.players = []
        self.sides = [[], []]
        self.active_player = 0
        self.exit_on_game_over = exit_on_game_over
        self.winner = None

    def initialize_game(self):
        initializer = DeckInitializer()
        self.deck1 = initializer.make_std_deck()
        self.deck2 = initializer.make_std_deck()
        p1_starts = self._player1_starts()
        self.active_player = 0 if p1_starts else 1 
        self.players = [
            Player(id=1, deck=self.deck1, hand=Hand(self.deck1), starts=p1_starts),
            Player(id=2, deck=self.deck2, hand=Hand(self.deck2), starts=not p1_starts)
        ]
        self.sides = [[initializer.create_hero('jaina')], [initializer.create_hero('jaina')]]

    def _player1_starts(self):
        return random() < 0.5

    def play_minion(self, index):
        self.execute_action(self.actions.play_minion(index))

    def cast_spell(self, card_idx, target_idx, safe=False):
        self.execute_action(self.actions.cast_spell(card_idx, target_idx, safe))

    def end_turn(self, safe=False):
        self.execute_action(self.actions.end_turn(safe))

    def active_draw_card(self, card_idx):
        self.execute_action(self.actions.draw(card_idx))

    def attack(self, atk_idx, def_idx, safe=False):
        self.execute_action(self.actions.attack(atk_idx, def_idx, safe))

    def execute_action(self, action):
        action.execute()

    def change_active_player(self):
        self.active_player = self.get_other_idx()

    def get_active_hand(self):
        return self.get_active_player().hand

    def get_other_hand(self):
        return self.get_other_player().hand

    def get_active_deck(self):
        return self.get_active_player().deck

    def get_other_deck(self):
        return self.get_other_player().deck

    def get_active_idx(self):
        return self.active_player

    def get_other_idx(self):
        return 1 if self.active_player == 0 else 0

    def get_active_side(self):
        return self.sides[self.get_active_idx()]

    def get_other_side(self):
        return self.sides[self.get_other_idx()]

    def get_active_player(self):
        return self.players[self.get_active_idx()]

    def get_other_player(self):
        return self.players[self.get_other_idx()]

    def game_loop(self):
        pass

    def game_over(self, active):
        self.winner = active+1        
        if self.exit_on_game_over:
            print(str(self))
            print('Player #{} won!'.format(active+1))
            sys.exit(self.winner)

    def is_game_over(self):
        return self.winner is not None

    def __str__(self):
        board_str = ''
        for player in self.players:
            board_str += str(player) + '\n'
        i = 1
        board_str += '\n\n'
        for side in self.sides:
            board_str += 'SIDE OF PLAYER #{}:\n'.format(i)
            i += 1
            for card in side:
                board_str += '{}\n'.format(card)
        return board_str
예제 #8
0

# A class that prints A 'x' times
class PrintA(Aktion):
    def __init__(self):
        super().__init__()

    def __act__(self, times):
        print("A".join(['' for i in range(times + 1)]))


# A class that prints B 'x' times
class PrintB(Aktion):
    def __init__(self):
        super().__init__()
        self.retryin = []

    def __act__(self, times):
        print("B".join(['' for i in range(times + 1)]))


if __name__ == "__main__":

    factory = ActionFactory()
    factory.register(PrintA)
    factory.register(PrintB)

    plan = ExecutionPlan("simple_actions.json")

    plan.run()
import json
import boto3
import re
from actions import ActionFactory
from actions import Action
from utils import Utils
from decision_node import decision_node
from decision_tree import decision_tree
from decision_tree_map import decision_tree_map
from bot_init import BotInitialize

dynamodb = boto3.client('dynamodb')
d_tree_map_by_file_name = {}
actionFactory = ActionFactory()


def get_decision_node(root, path):
    d2 = Utils().get_decision_node(root, path, 0)
    return d2


def update_call_status(callId, callStatus):
    keyRequest = {"callId": {'N': str(callId)}}
    updateExpression = "SET callStatus=:statusValue"
    expressionAttributes = {':statusValue': {'S': callStatus}}
    dynamodb.update_item(TableName='callTriggerTable',
                         Key=keyRequest,
                         ExpressionAttributeValues=expressionAttributes,
                         UpdateExpression=updateExpression)

예제 #10
0
class GenerateB(Aktion):

    def __init__(self):
        super().__init__()
        self.retryin = []

    def __act__(self, times):
        return "B".join(['' for i in range(times+1)])


class ConcatSrt(Aktion):

    def __init__(self):
        super().__init__()

    def __act__(self, items, times=1):
        result = "".join([i for i in items])
        result = result.join(['' for i in range(times+1)])
        print(result)


if __name__ == "__main__":

    factory = ActionFactory()
    factory.register(GenerateA)
    factory.register(GenerateB)
    factory.register(ConcatSrt)

    plan = ExecutionPlan(r"chain_actions.json")
    plan.run()
예제 #11
0
 def on_event(self, event, extension):
     _LOGGER_.debug("KeywordQueryEventListener executing")
     arguments_or_empty: str = event.get_query().get_argument() or ""
     arguments: list = arguments_or_empty.split()
     return RenderResultListAction(
         ActionFactory(arguments, extension.db).create().execute())
예제 #12
0
 def __init__(self, board):
     self.board = board
     self.actions = ActionFactory(board)
     self.reviewer = BoardReviewer(board)
예제 #13
0
class Analyzer:
    def __init__(self, board):
        self.board = board
        self.actions = ActionFactory(board)
        self.reviewer = BoardReviewer(board)

    def generate_actions(self):
        if self.board.is_game_over():
            return []
        all_actions = []
        all_actions.extend(self.generate_playing_minions())
        all_actions.extend(self.generate_attacks())
        all_actions.extend(self.generate_casting_spells())
        all_actions.extend(self.generate_ending_turn())
        # all_actions.extend(self.generate_card_draw())
        return all_actions

    def grade_board(self):
        return self.reviewer.grade_board()

    def generate_playing_minions(self):
        player = self.board.get_active_player()
        active_side = self.board.get_active_side()
        actions = []
        for idx, card in enumerate(player.hand.cards):
            if card.cost <= player.mana:
                if card.type == 'minion':
                    if len(active_side) < 7:
                        actions.append(self.actions.play_minion(idx))
        return actions

    def generate_ending_turn(self):
        return [self.actions.end_turn()]

    def generate_attacks(self):
        active_side = self.board.get_active_side()
        other_side = self.board.get_other_side()
        actions = []
        for idx, minion in enumerate(active_side):
            # Skip the hero
            if idx == 0: continue
            if minion.can_attack:
                taunts = [c for c in other_side if c.taunt]
                for enemyidx, enemy in enumerate(other_side):
                    if taunts:
                        if enemy.taunt:
                            actions.append(self.actions.attack(idx, enemyidx))
                    else:
                        actions.append(self.actions.attack(idx, enemyidx))
        return actions

    def generate_casting_spells(self):
        active_player = self.board.get_active_player()
        other_side = self.board.get_other_side()
        actions = []
        for cardidx, card in enumerate(active_player.hand.cards):
            if card.type != 'spell': continue
            if card.cost > active_player.mana: continue
            for enemyidx, _ in enumerate(other_side):
                actions.append(self.actions.cast_spell(cardidx, enemyidx))
        return actions

    def generate_card_draw(self):
        deck = self.board.get_active_deck()
        card_scores = [self.reviewer.grade_card(c) for c in deck.cards]
        max_score_idx = card_scores.index(max(card_scores))
        return [self.actions.draw(max_score_idx)]