예제 #1
0
    def attaque1(self):

        s = SuperState(self.state, self.id_team, self.id_player)
        a = Actions(self.state, self.id_team, self.id_player)

        if s.poscoequippier.distance(
                s.ball
        ) < PLAYER_RADIUS + BALL_RADIUS:  #SI le coequippier a la balle

            return a.deplacement(s.pointcampeurgauche)

        elif s.player.distance(s.ball) < PLAYER_RADIUS + BALL_RADIUS:
            if s.player.distance(s.poscoequippier) < PLAYER_RADIUS * 25:
                if s.coepdevant == 1:
                    return a.tircoequippier
            elif s.player.distance(s.goaladverse) < (
                    PLAYER_RADIUS *
                    15):  #Si il est dans la surface de tir : shoot
                return a.shootbut
            elif s.playeradverse.distance(s.player) < (PLAYER_RADIUS * 8):
                return a.dr2
            else:

                return a.avanceravecballe
        else:

            return a.deplacement(s.ball)
예제 #2
0
파일: game.py 프로젝트: NoYzE1/cRPG
 def main():
     action = input("\nChoose an action: (status, move, save, rest, exit) ")
     if action == "status":
         Playerinfo.status()
         Game.main()
     elif action == "move" or action == "m":
         Actions.move()
         if Player.isAlive:
             Game.main()
         else:
             IO.death()
             Game.start()
     elif action == "rest" or action == "r":
         Actions.rest()
         Game.main()
     elif action == "save":
         IO.save()
         print("Game saved!")
         Game.main()
     elif action == "exit" or action == "q" or action == "quit":
         answer = input("Are you sure you want to quit? (y/n) ")
         if answer == "y":
             IO.save()
             IO.quit()
         else:
             Game.main()
     else:
         print("\nTry again!")
         Game.main()
예제 #3
0
class Character():
    def __init__(self, dict_info):
        self.name = dict_info['name']
        self.hp = dict_info['hp']
        self.mp = dict_info['mp']
        self.offense = dict_info['offense']
        self.defense = dict_info['defense']
        self.speed = dict_info['speed']
        self.wise = dict_info['wise']

        action_ids = dict_info['actions'].split(':')
        self.actions = Actions()
        self.actions.construct(action_ids)

    def decide_action(self):
        action = None
        if len(self.actions.list) > 0:
            action = self.actions.list[randint(0, len(self.actions.list))]

        return action

    def show_info(self):
        print(f'{self.name}')
        print(f'    HP    :{self.hp}')
        print(f'    MP    :{self.mp}')
        print(f'    攻撃力  :{self.offense}')
        print(f'    防御力  :{self.defense}')
        print(f'    素早さ  :{self.speed}')
        print(f'    賢さ   :{self.wise}')
        self.actions.show_info()
예제 #4
0
파일: util.py 프로젝트: ramroll/pacman
def closestNFood(pos, food, walls, n, ghosts):
    """
    closestFood -- this is similar to the function that we have
    worked on in the search project; here its all in one place
    """
    fringe = [(pos[0], pos[1])]
    expanded = set()
    gset = set()
    for g in ghosts:
        nbrs = Actions.getLegalNeighbors(g.pos, walls)
        for p in nbrs:
            gset.add(p)

    nfoods = []
    while fringe and len(nfoods) < n:
        pos_x, pos_y = fringe.pop(0)
        if (pos_x, pos_y) in expanded:
            continue
        expanded.add((pos_x, pos_y))
        # if we find a food at this location then exit
        if food[pos_x][pos_y] and not (pos_x, pos_y) in gset:
            nfoods.append((pos_x, pos_y))
            continue
        # otherwise spread out from the location to its neighbours
        nbrs = Actions.getLegalNeighbors((pos_x, pos_y), walls)
        for nbr_x, nbr_y in nbrs:
            fringe.append((nbr_x, nbr_y))
    return nfoods
예제 #5
0
파일: state.py 프로젝트: ramroll/pacman
 def next(self, player, action):
     # 检查是否合法
     Actions.checkLegal(player.pos, action, self.layout.walls)
     # 更新坐标
     (player.pos, player.dir) = Actions.getSuccessor(player.pos, action)
     # 更新分数和生死状态
     self.calculateScore(player)
예제 #6
0
    def compute_strategy(self, state, id_team, id_player):

        s = Strategies(state, id_team, id_player)
        v = SuperState(state, id_team, id_player)
        a = Actions(state, id_team, id_player)

        if v.player.distance(v.ball) < PLAYER_RADIUS + BALL_RADIUS:
            if id_team == 1:

                tir = (Vector2D(GAME_WIDTH * 3 / 8,
                                GAME_HEIGHT / 2)) - v.player
                return SoccerAction(shoot=tir.normalize() * 3)
            else:

                tir = (Vector2D(GAME_WIDTH * 5 / 8,
                                GAME_HEIGHT / 2)) - v.player
                return SoccerAction(shoot=tir.normalize() * 3)

        else:
            if v.ballecampadverse == 0:
                if id_team == 1:
                    return a.deplacement(
                        Vector2D((GAME_WIDTH / 2) - 5, v.ball.y))
                else:
                    return a.deplacement(
                        Vector2D((GAME_WIDTH / 2) + 5, v.ball.y))
            elif v.player.distance(v.ball) < PLAYER_RADIUS * 10:
                return a.deplacement(v.ball)
예제 #7
0
파일: loaders.py 프로젝트: AHAPX/test-rest
 def get_actions(self, actions, params):
     result = Actions()
     for action in actions:
         name, data = action.popitem()
         steps = self.get_steps(data.get('steps'), self.get_block(data, **params))
         result.add_action(Action(steps, name))
     return result
예제 #8
0
 def __init__(self):
     Board.__init__(self)
     Actions.__init__(self)
     Rules.__init__(self)
     self.players = {}
     self.turn = 0
     self.game_over = True
예제 #9
0
    def __init__(self):
        self.state = State.Init
        self.config = {
            'hover_height':
            1.0,

            # States for which movement.fix_hover() will NOT be called (to make sure the drone is at `hover_height`)
            'exclude_from_fix_hover': [
                State.Init,
                State.Takeoff,
                State.Land,
                State.Done,
            ],

            # Radius in meters around a blacklisted goal that the robot will ignore
            'blacklisted_goal_radius':
            2.0
        }

        self.store = DataStore()
        self.movement = MovementHandler(core=self, datastore=self.store)
        self.actions = Actions(core=self,
                               datastore=self.store,
                               movement_handler=self.movement)
        self.planner = Planner(core=self,
                               datastore=self.store,
                               movement_handler=self.movement)

        # Aux files
        self.temp_data = {}
        self.last_goal = None
예제 #10
0
class Controller:
    def __init__(self):
        config = configparser.ConfigParser()
        config_file = os.path.join(os.path.dirname(__file__), 'config.ini')
        config.read(config_file)
        client = InfluxDBClient.from_config_file(config_file)
        self.query_api = client.query_api()
        self.bucket = config['ha']['influx_bucket']
        self.actions = Actions()

    def get_last_record(self, measurement, tag_key, tag_value, field_key):
        # https://v2.docs.influxdata.com/v2.0/query-data/get-started/query-influxdb/
        query = '''
        from(bucket:"{}")
        |> range(start: -10d)
        |> filter(fn:(r) => r._measurement == "{}")
        |> filter(fn: (r) => r.{} == "{}")
        |> filter(fn:(r) => r._field == "{}")
        |> last()
        '''.format(self.bucket, measurement, tag_key, tag_value, field_key)

        result = self.query_api.query(query=query)
        return result[0].records[0]

    def run(self):

        while True:

            last_value = self.get_last_record('sensor', 'location', 'home',
                                              'dummy0')['_value']
            if last_value > 80000:
                self.actions.do_action1()
            if last_value < 60000:
                self.actions.do_action2()
예제 #11
0
    def getValidActions(self, gameState):
        """
        Get valid actions based on gamestate
        input: gameState of hand
        returns: list of valid actions the player can take
        """
        validActions = []
        # Player may have split and have multiple hands, get current one
        # from the gameState
        try:
            playerHand = gameState.getCurrentPlayableHand()
        except IndexError as e:
            return []

        if playerHand.isBlackjack():
            return [Actions.STAND]

        if Actions.isHitValid(playerHand):
            validActions.append(Actions.HIT)

        if Actions.isStandValid(playerHand):
            validActions.append(Actions.STAND)

        if Actions.isDoubleDownValid(playerHand, gameState):
            validActions.append(Actions.DOUBLE_DOWN)

        if Actions.isSplitValid(playerHand, gameState):
            validActions.append(Actions.SPLIT)

        return validActions
예제 #12
0
    def processEvent(self, event):
        """Pretty prints events.
        Prints all events that occur with two spaces between each new
        conversation and a single space between turns of a conversation.
        Args:
            event(event.Event): The current event to process.
        """
        print(event)
        Actions.status_text.set(str(event.type)[10:])

        # chat update
        if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
            Actions.inp = event.args["text"]
            Actions.otp = ""
            Actions.text_text.set(Actions.inp)
            self.customAction(event.args)


        if event.type == EventType.ON_RENDER_RESPONSE:
            Actions.otp = event.args["text"]

        if event.type == EventType.ON_CONVERSATION_TURN_FINISHED:
            Actions.text_text.set("")
            # Actions.chatUpdate('', 0)
            Actions.chatUpdate(Actions.inp, 1)  # You:
            Actions.chatUpdate(Actions.otp, 2)  # UAssist:

        if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
            self.can_start_conversation = False
            subprocess.Popen(["aplay", "{}/resource/audio/todon.wav".format(Actions.ROOT_PATH)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        if event.type == EventType.ON_DEVICE_ACTION:
            for command, params in event.actions:
                print('Do command', command, 'with params', str(params))
예제 #13
0
    def choose_discard(self, drawn_card, game_state):
        """
        Decides which card in its hand to exchange with the drawn_card or whether to discard it.
        If there are any cards in the hand that score more than the drawn card, then the first card that scores more is exchanged.
        If the drawn card scores more than all visible cards in the hand, then it chooses from the remaining legal moves randomly.
        This random decision is made using pythons random choice method.        
        The decision is returned as an instance of the Actions IntEnum class.
        Args:
            drawn_card (Card): The card that has been drawn by the player.
            game_state ([int]): Not used.
        Returns: An Actions object corresponding to the card being discarded.
        """
        v, _ = drawn_card.get_val_suit()
        for i in range(6):
            #Exchanges the drawn card with the first card that scores more
            if self.hand[i].hidden == False and Golf.card_score(
                    v) < Golf.card_score(self.hand[i].get_val_suit()[0]):
                return Actions(i)

        disc_options = [i for i in range(6) if self.hand[i].hidden == True]
        #Prevents the player discarding a card drawn from the discard pile
        if game_state[Golf.get_card_index(drawn_card)] != -2:
            disc_options += [8]
        #If no card scores more, choose from remaining legal moves randomly
        return Actions(random.choice(disc_options))
예제 #14
0
    def attaquedroit(self):  #essai

        s = SuperState(self.state, self.id_team, self.id_player)
        a = Actions(self.state, self.id_team, self.id_player)

        if s.poscoequippier.distance(
                a.directionball
        ) < PLAYER_RADIUS + BALL_RADIUS:  #SI le coequippier a la balle

            return a.deplacement(s.pointcampeurdroit)

        elif s.player.distance(s.ball) < PLAYER_RADIUS + BALL_RADIUS:
            if s.opposantsplusproche[1].distance(
                    s.player) < PLAYER_RADIUS * 10:

                #if s.player.distance(s.poscoequippier) < PLAYER_RADIUS*25 :
                if s.coepdevant == 1:
                    print("DDDDD")
                    return a.tircoequippier + a.deplacement(
                        s.pointattaquantdroit)

            elif s.playeradverse.distance(s.player) < (PLAYER_RADIUS * 15):
                return a.tircoequippier

            elif s.player.distance(s.goaladverse) < (
                    PLAYER_RADIUS *
                    20):  #Si il est dans la surface de tir : shoot
                return a.shootbut

            else:

                return a.avanceravecballe
        else:

            return a.deplacement(a.directionball)
예제 #15
0
def generate(proxy_file, result_dir) -> bool:
    copyfile(manifest_src, result_dir + r'\manifest.json')

    # f=open(os.getcwd()+r'\proxy.txt','r')
    i = 0
    with open(proxy_file) as proxyf:
        for proxy in proxyf:
            i += 1
            print('-------------' + proxy + '------------')
            # Генерим ZIP архив для текущего прокси
            # proxy = proxyf.readline()
            ip = proxy[proxy.find('@') + 1:proxy.find(':443')]
            with open(os.getcwd() + r'\Proxy\background.js',
                      'r') as background, open(os.getcwd() + r'\Proxy\rez.js',
                                               'a') as rez:
                for line in background:
                    # Генерим ZIP архив для текущего прокси
                    index = line.find(r'host:')
                    if index > -1:
                        line = line[0:index + 6] + '"' + ip + '"' + ','
                    rez.write(line)
            rez.close()
            os.replace(os.getcwd() + r'\Proxy\rez.js',
                       os.getcwd() + r'\Proxy\newproxies\background.js')
            Actions.compressfiles([
                os.getcwd() + r'\Proxy\newproxies\background.js',
                os.getcwd() + r'\Proxy\newproxies\manifest.json'
            ],
                                  os.getcwd() + '\\Proxy\\newproxies\\' + ip +
                                  '.zip')

    print('Обработано проксей ' + str(i))
예제 #16
0
 def addAction(self, code, amount):
     act = Actions()
     act.code = code
     act.amount = amount
     self.actions.append(act)
 
 # def toJSON(self):
 #     return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
예제 #17
0
def listen_attached_player_death(gs, changes, gameState, l):
    if gs['attach_target'] is not '':
        p_alive = gs['players'][gs['attach_target']]['alive']
        p_changes_alive = changes['players'][gs['attach_target']]['alive']
        if gs['is_attached'] is False and p_alive is False and changes['is_attached'] is True and p_changes_alive is True:
            Actions.move_click(gameState.nexus_pos)
            GameLoop.old_time = time.time()
            return 'flee'
예제 #18
0
 def __init__(self):
     config = configparser.ConfigParser()
     config_file = os.path.join(os.path.dirname(__file__), 'config.ini')
     config.read(config_file)
     client = InfluxDBClient.from_config_file(config_file)
     self.query_api = client.query_api()
     self.bucket = config['ha']['influx_bucket']
     self.actions = Actions()
예제 #19
0
def predict():
    predict_loss = []
    predict_accuracy = []
    predict_dice = []
    model = Actions(sess, configure())
    loss, acc, dice = model.predict()
    predict_loss.append(loss)
    predict_accuracy.append(acc)
    predict_dice.append(dice)
예제 #20
0
def auto_heal(gs, changes, gameState, l):
    #print( self._is_attached, ' ', self.attach_target, ' ', self.auto_heal_enabled )
    if gs['is_attached'] is True and gs['attach_target'] is not '' and gs['auto_heal_enabled'] is True:
        print('auto heal firing')
        if gs['players'][gs['attach_target']]['hp'] < 0.60:
            Actions.press_and_release_key('e')
            
        if gs['players'][gs['attach_target']]['hp'] < 0.18:
            Actions.press_and_release_key('d')
예제 #21
0
    def __init__(self, catalog=None):
        Cmd.__init__(self)

        self.intro = f'\n [{catalog["name"]}] Work with book CLI'
        self.prompt = "Book > "
        self.doc_header = "Book commands (type help <topic>):"
        print(catalog['id'])
        self.actions = Actions(catalog['id'])
        self.search = Search(catalog['id'])
예제 #22
0
    def __init__(self,
                 icon=None,
                 tunableDict=json.loads(
                     json.dumps({
                         "windowX": 20,
                         "windowY": 50,
                         "windowWidth": 500,
                         "windowHeight": 500,
                         "volume": 50
                     })),
                 title="Window"):
        """
        Initializing the UI for Forge

        Args:\n
            icon (string, optional): File path to the icon(.ico file) for the top left of the window. Defaults to None.
            tunableDict (JSON, optional): The tunable variables class for saving the windows position on close.
                                          Defaults to {"windowX": 10, "windowY": 10, "windowWidth": 500, "windowHeight": 500}.
            title (str, optional): The name of the window. Defaults to "Window".
        """

        stylesheet = open(utilities.resource_path("QTPie Style\\style.css"),
                          "r")
        styling = stylesheet.read()
        stylesheet.close()

        self.actions = Actions()

        self.tunableDict = tunableDict

        self.app = QtWidgets.QApplication(sys.argv)
        self.app.setStyleSheet(styling)
        self.app.aboutToQuit.connect(
            lambda: self.actions.onWindowClose(self.mainWindow))

        if icon:
            appIcon = PyQt5.QtGui.QIcon()
            appIcon.addFile(utilities.resource_path("icon.png"))
            self.app.setWindowIcon(appIcon)

        self.grid = QtWidgets.QGridLayout()
        self.gridCount = 0
        self.grid.setSpacing(0)
        self.grid.setContentsMargins(0, 0, 0, 0)
        self.space = self.addLabel([1, 1, 1, 1], txt="", name="Spacer")

        self.window = QTPieWidget()
        self.window.setLayout(self.grid)

        self.mainWindow = QTPieWindow()
        self.mainWindow.setGeometry(self.tunableDict["windowX"],
                                    self.tunableDict["windowY"],
                                    self.tunableDict["windowWidth"],
                                    self.tunableDict["windowHeight"])
        self.mainWindow.setWindowTitle(title)
        self.mainWindow.setCentralWidget(self.window)
예제 #23
0
 def __init__(self):
     self.nlg = NLG(user_name=self.my_name)
     self.speech = Speech(launch_phrase=self.launch_phrase,
                          debugger_enabled=self.debugger_enabled)
     self.actions = Actions(self.location)
     if os.path.isfile('unknown_commands.csv') == False:
         with open('unknown_commands.csv', 'w') as csvfile:
             writer = csv.DictWriter(csvfile,
                                     fieldnames=self.unknown_fieldnames)
             writer.writeheader()
예제 #24
0
    def __init__(self, players_turn, feature_length, label_length):
        self.players_turn = players_turn
        self.game_over = False
        self.user = Player('user')
        self.opponent = Player('opponent')

        self.game_actions = Actions()

        self.player_training_data = Data(feature_length, label_length)
        self.opponent_training_data = Data(feature_length, label_length)
예제 #25
0
class Main:
    """
    kwargs: {
        argv: expected sys.argv
            Tries breaking into arguments of flags and key flags
            flags are just texts like python script.py flag1 flag2 --flag3
            key flags have equal sign python script.py this=that --other_flag=that-one
            Not the best solution and doesn't work for spacer, easier for me to format

            flags:
                "wsl": Assume this is running on WSL Arch, changes one dependency (fakeroot -> fakeroot-tcp)
                "onego": Calls yay for installing ALL packages at once listed on requirements
    }
    """
    def __init__(self, **kwargs):
        debug_prefix = "[Main.__init__]"

        # Argv from shell
        self.argv = kwargs["argv"]

        # Empty list of flags and kflags
        self.flags = []
        self.kflags = {}

        if self.argv is not None:

            # Iterate in all args
            for arg in self.argv[1:]:

                # Is a kwarg
                if "=" in arg:
                    arg = arg.split("=")
                    self.kflags[arg[0]] = arg[1]

                # Is a flag
                else:
                    self.flags.append(arg)

        # Print user flags from the terminal
        print(debug_prefix, "Flags are:", self.flags)
        print(debug_prefix, "Keyword flags are:", self.kflags)

        # Create classes
        self.utils = Utils(self)
        self.subprocess_utils = SubprocessUtils(self)
        self.pacman = Pacman(self)
        self.directories = Directories(self)
        self.download = Download(self)
        self.actions = Actions(self)

        # Runs every action
        self.actions.run()

    def get_subprocess_utils(self):
        return copy.deepcopy(self.subprocess_utils)
예제 #26
0
class World():
    def __init__(self, N, M, r, specials, p1, p2, possibleActions):
        self.buildMap(N, M, r, specials)
        self.p1 = p1
        self.p2 = p2

        self.actions = Actions(possibleActions)

    def buildMap(self, N, M, r, specials):
        self.rewards = [[r for x in range(N)] for y in range(M)]  # [y][x]
        self.terminals = []

        for s in specials:
            self.rewards[s[1]][s[0]] = specials[s][1]
            if specials[s][0] == "F":
                self.rewards[s[1]][s[0]] = None
            elif specials[s][0] == "G":
                self.terminals.append(s)
            elif specials[s][0] == "S":
                self.start = s

    def getY(self):
        return len(self.rewards)

    def getX(self):
        return len(self.rewards[0])

    # state : tuple(x,y)
    def getReward(self, state):
        return self.rewards[state[1]][state[0]]

    def getActions(self, state):
        return self.actions.getActions() if state not in self.terminals else [
            self.actions.terminalAction
        ]

    def bellmanOperator(self, state, action):
        if self.actions.isTerminalAction(action):
            return [(0, state)]  #state is reachable for sure
        else:
            possibleAct = self.actions.getOtherPossibleActionsActions(action)
            probState = [
                (self.p2, self.getNewState(state, pa)) for pa in possibleAct
            ] + [(self.p1, self.getNewState(state, action))]
            return [s for s in probState if self.isStateReachable(s[1])]

    def getNewState(self, state, action):
        x = state[0] + action['x']
        y = state[1] + action['y']
        if x in range(self.getX()) and y in range(self.getY()):
            return x, y
        return state

    def isStateReachable(self, state):
        return True if self.rewards[state[1]][state[0]] is not None else False
예제 #27
0
    def __init__(self, config, encoder_output_dim , action_dict, ent_dict, tri_dict, arg_dict):
        self.config = config
        self.model = pm.global_collection()

        self.multi_task = MultiTask(config, encoder_output_dim , action_dict, ent_dict, tri_dict, arg_dict)
        self.arg_null_id = arg_dict[Vocab.NULL]

        bi_rnn_dim = encoder_output_dim  # config['rnn_dim'] * 2 #+ config['edge_embed_dim']
        lmda_dim = config['lmda_rnn_dim']
        part_ent_dim = config['part_ent_rnn_dim']

        self.lmda_dim = lmda_dim
        self.bi_rnn_dim = bi_rnn_dim
        self.lambda_var = nn.LambdaVar(lmda_dim)

        dp_state = config['dp_state']
        dp_state_h = config['dp_state_h']


        self.sigma_rnn = nn.StackLSTM(lmda_dim, lmda_dim, dp_state, dp_state_h)  # stack
        self.delta_rnn = nn.StackLSTM(lmda_dim, lmda_dim, dp_state, dp_state_h)   # will be pushed back

        self.part_ent_rnn = nn.StackLSTM(bi_rnn_dim, part_ent_dim, dp_state, dp_state_h)
        #self.beta = []  # buffer, unprocessed words
        self.actions_rnn = nn.StackLSTM(config['action_embed_dim'], config['action_rnn_dim'], dp_state, dp_state_h)
        self.out_rnn = nn.StackLSTM(bi_rnn_dim, config['out_rnn_dim'], dp_state, dp_state_h)

        self.act_table = nn.Embedding(len(action_dict), config['action_embed_dim'])
        self.ent_table = nn.Embedding(len(ent_dict), config['entity_embed_dim'])
        self.tri_table = nn.Embedding(len(tri_dict), config['trigger_embed_dim'])

        self.act= Actions(action_dict, ent_dict, tri_dict, arg_dict)

        hidden_input_dim = bi_rnn_dim + lmda_dim * 3 + part_ent_dim \
                           + config['action_rnn_dim'] + config['out_rnn_dim']

        self.hidden_linear = nn.Linear(hidden_input_dim, config['output_hidden_dim'], activation='tanh')
        self.output_linear = nn.Linear(config['output_hidden_dim'], len(action_dict))
        entity_embed_dim = config['entity_embed_dim']
        trigger_embed_dim = config['trigger_embed_dim']

        ent_to_lmda_dim = config['part_ent_rnn_dim'] + entity_embed_dim #+ config['sent_vec_dim'] * 4
        self.ent_to_lmda = nn.Linear(ent_to_lmda_dim, lmda_dim, activation='tanh')
        tri_to_lmda_dim = bi_rnn_dim + trigger_embed_dim #+ config['sent_vec_dim']
        self.tri_to_lmda = nn.Linear(tri_to_lmda_dim, lmda_dim, activation='tanh')

        self.hidden_arg = nn.Linear(lmda_dim * 2 + self.bi_rnn_dim, config['output_hidden_dim'],
                                    activation='tanh')
        self.output_arg = nn.Linear(config['output_hidden_dim'], len(arg_dict))
        self.empty_buffer_emb = self.model.add_parameters((bi_rnn_dim,), name='bufferGuardEmb')

        self.event_cons = EventConstraint(ent_dict, tri_dict, arg_dict)
        #self.cached_valid_args = self.cache_valid_args(ent_dict, tri_dict)

        self.empty_times = 0
예제 #28
0
    def run(self):
        self.logger.info("daemon running")

        actions = Actions(self.logger)
        
        try:
            actions.createSessionBus()
            actions.createManager()
            actions.wireEventHandlers()
            actions.openManager()
            
            # MAIN LOOP
            # ---------        
            while True:
                #self.logger.info("start loop")
                
                try:
                    signal.pause()
                    #time.sleep(0.1)
                    #sys.stdin.read()
                except Exception,e:
                    exc=str(e)
                    self.logger.error("error_untrapped", exc=exc)
                    
                #self.logger.info("tail loop")
                
        except Exception,e:
            exc=str(e)
            self.logger.error("error_untrapped", exc=exc)
예제 #29
0
 def __init__(self, config, gestures, el, *args, **kwarg):
     """
     :param config: string containing the path to the action configuration
     :param gestures: string containing the path to the gestures configuration
     """
     super(EventDispatcher, self).__init__(*args, **kwarg)
     self._event_loop = el
     self._gdb = GestureDatabase()
     self._actions = Actions(config, gestures)
     self.update_devices()
     self._multitouches = []
예제 #30
0
    def auto_heal(self):
        #print( self._is_attached, ' ', self.attach_target, ' ', self.auto_heal_enabled )
        if self._is_attached is True and self.attach_target is not '' and self.auto_heal_enabled is True:
            print('auto heal firing')
            if self.players[self.attach_target].get_hp() < 0.60:
                print('heal cast')
                Actions.press_and_release_key('e')

            if self.players[self.attach_target].get_hp() < 0.15:
                print('summoenr heal')
                Actions.press_and_release_key('d')
 def getRobotSuccessors(self, pos):
     possible = []
     possible = Actions.possibleActions(pos, self.robot.world)
     if possible == [Actions.STOP]:
         possible = Actions.possibleActions(pos, self.robot.world)
     successor = []
     for direction in possible:
         x = pos[0] + direction[0]
         y = pos[1] + direction[1]
         successor.append(Node([x,y]))
     return successor
예제 #32
0
    def compute_strategy(self, state, id_team, id_player):

        s = Strategies(state, id_team, id_player)
        v = SuperState(state, id_team, id_player)
        a = Actions(state, id_team, id_player)

        if v.player.distance(v.ball) < PLAYER_RADIUS + BALL_RADIUS:
            shoot = v.playeradverse - v.player
            return SoccerAction(shoot=shoot.normalize() * 3)
        else:
            return a.deplacement(v.ball)
예제 #33
0
파일: main.py 프로젝트: moliqingcha/DACN
def predict(): 
    predict_loss = []
    predict_accuracy = []
    predict_m_iou = []
    model = Actions(sess, configure())
    loss,acc,m_iou = model.predict()
    predict_loss.append(loss)
    predict_accuracy.append(acc)
    predict_m_iou.append(m_iou)
    print('predict_loss',predict_loss)
    print('predict_accuracy',predict_accuracy)
    print('predict_m_iou',predict_m_iou)
예제 #34
0
class TPBattStat():
  def __init__(self, mode, forceDelay=None, forceIconSize=None):
    self.mode = mode
    self.forceDelay = forceDelay

    self.prefs = Prefs()
    self.battStatus = BattStatus(self.prefs)
    self.actions = Actions(self.prefs, self.battStatus)
    if self.mode == "gtk" or self.mode == "prefs":
      self.gui = Gui(self.prefs, self.battStatus)
    elif self.mode == "json" or self.mode == "dzen":
      self.guiMarkupPrinter = GuiMarkupPrinter(
        self.prefs, self.battStatus, forceIconSize)
      
  def getGui(self):
    return self.gui
  def startUpdate(self):
    self.curDelay = -1
    self.update()
  def update(self):
    try:
      self.prefs.update()
    except Exception as e:
      print 'ignoring prefs'
      print e.message
    if self.forceDelay != None:
      self.prefs['delay'] = self.forceDelay
    self.battStatus.update(self.prefs)

    self.actions.performActions()
    if self.mode == "gtk":
      self.gui.update()
    elif self.mode == "json" or self.mode == "dzen":
      try:
        if self.mode == "json":
          markup = self.guiMarkupPrinter.getMarkupJson()
        elif self.mode == "dzen":
          markup = self.guiMarkupPrinter.getMarkupDzen()
        print markup
        sys.stdout.flush()
      except IOError, e:
        print >> sys.stderr, "STDOUT is broken, assuming external gui is dead"
        sys.exit(1)

    if self.prefs['delay'] != self.curDelay:
      self.curDelay = self.prefs['delay']
      if self.curDelay <= 0:
        self.curDelay = 1000
      gobject.timeout_add(self.curDelay, self.update)
      return False
    else:
      return True
예제 #35
0
파일: listener.py 프로젝트: guyzmo/kitt
class Listener(EventDispatcher):
    """
    listener function that queries kivy for touch events, builds the gesture
    and dispatch it through the actions singleton.
    """
    def __init__(self, config, gestures, el, *args, **kwarg):
        """
        :param config: string containing the path to the action configuration
        :param gestures: string containing the path to the gestures configuration
        """
        super(EventDispatcher, self).__init__(*args, **kwarg)
        self._event_loop = el
        self._gdb = GestureDatabase()
        self._actions = Actions(config, gestures)
        self.update_devices()
        self._multitouches = []

    def update_devices(self):
        log.debug('update_devices()')
        context = pyudev.Context()
        for device in context.list_devices(subsystem='input', ID_INPUT_MOUSE=True):
            if device.sys_name.startswith('event'):
                if 'PRODUCT' in device.parent.keys():
                    self._actions.update_gestures(device.parent['PRODUCT'])
        for gest_n, gest_r in self._actions.get_gestures().iteritems():
            for g in gest_r:
                g = self._gdb.str_to_gesture(g)
                g.normalize()
                g.name = gest_n
                self._gdb.add_gesture(g)

    def on_touch_down(self, touch):
        """
        listening function executed at begining of touch event
        builds the gesture
        """
        self._multitouches.append(touch)
        touch.ud['line'] = Line(points=(touch.sx, touch.sy))
        return True

    def on_touch_move(self, touch):
        """
        listening function executed during touch event
        store points of the gesture
        """
        # store points of the touch movement
        try:
            touch.ud['line'].points += [touch.sx, touch.sy]
            return True
        except (KeyError), e:
            pass
예제 #36
0
파일: game_rules.py 프로젝트: Gin93/111
    def apply_action(state, action):
        """ Edits the state to reflect the results of the action.
            (State, str) -> None
        """
        if action not in BlackBirdRules.get_legal_actions(state):
            raise Exception("Illegal action " + str(action))
        state.score_change = 0

        next_pos = Actions.get_successor(state.black_bird_position, action)
        state.black_bird_position = next_pos
#        if next_pos == state.red_bird_position :
#            print( "Black moving into Red's position" )


        if next_pos in state.yellow_birds:
            state.score_change -= state.current_yellow_bird_score
            state.yellow_birds = tuple([yb for yb in state.yellow_birds if yb != next_pos])
            state._yellow_bird_eaten = next_pos
            if not state.yellow_birds:
                print("All Birds Eaten")
                state.terminal = True
        if state.red_bird_position == state.black_bird_position :
            state.red_bird_dead = True # Black eats Red
            print("Black EATS Red!")
            state.score_change -= 250
        if state.black_bird_position is not None:
            state.current_yellow_bird_score *= 0.99
        if state.current_yellow_bird_score < 0.5 :
            print("Game Over - All the Yellow Birds Have Flown Away!")
예제 #37
0
파일: game_rules.py 프로젝트: Gin93/111
    def apply_action(state, action):
        """ Edits the state to reflect the results of the action.
            (State, str) -> None
        """
        if action not in RedBirdRules.get_legal_actions(state):
            raise Exception("Illegal action " + str(action))
        state.score_change = 0

        next_pos = Actions.get_successor(state.red_bird_position, action)
        state.red_bird_position = next_pos
#        if next_pos == state.black_bird_position :
#            print( "Red moving into Black's position" )

        if next_pos in state.yellow_birds:
            state.score_change += state.current_yellow_bird_score
            state.yellow_birds = tuple([yb for yb in state.yellow_birds if yb != next_pos])
            state._yellow_bird_eaten = next_pos
            if not state.yellow_birds:
                print("All Birds EATEN")
                state.terminal = True
        if state.red_bird_position == state.black_bird_position :
            state.black_bird_dead = True # Red eats Black
            print("Red EATS Black!")
            state.terminal = True
            state.score_change += 250
        if state.black_bird_position is not None:
            state.current_yellow_bird_score *= 0.99
        if state.current_yellow_bird_score < 0.5 :
            print("Game Over - All the Yellow Birds Have Flown Away!")


        #There is only a time penalty if we do not have an adversary
        if state.get_black_bird_position() is None:
            state.score_change -= TIME_PENALTY
예제 #38
0
파일: gui.py 프로젝트: charky/chyfy
class GUI:
    
    def __init__(self):
       self.wsControlLabels = []
       self.wsControlLabels.append(settings.wireless_switch["ws_1_name"] + " On")
       self.wsControlLabels.append(settings.wireless_switch["ws_1_name"] + " Off")
       self.wsControlLabels.append(settings.wireless_switch["ws_2_name"] + " On")
       self.wsControlLabels.append(settings.wireless_switch["ws_2_name"] + " Off")
       self.wsControlLabels.append(settings.wireless_switch["ws_3_name"] + " On")
       self.wsControlLabels.append(settings.wireless_switch["ws_3_name"] + " Off")
       self.wsControlLabels.append("- - -")
       self.wsControlLabels.append("Toggle Service on/off")
       self.actions = Actions()
     
    def toggleService(self):
        settings.update_general()
        if settings.general["service_enabled"]:
            settings.set("service_enabled", "false")
        else:
            settings.set("service_enabled", "true")
        settings.update_general()    
       
    def show(self):    
        ## main loop ##
        while True:
            if settings.general["service_enabled"]:
                self.wsControlLabels[7] = "Disable Service"
            else:
                self.wsControlLabels[7] = "Enable Service"
                
            idx = Dialog().select(addonname, self.wsControlLabels)
            xbmc.log(msg=self.wsControlLabels[idx], level=xbmc.LOGDEBUG)  
            if idx >= 0 and idx <= 5:
                wsID = str(idx / 2 + 1)
                powerState = "0"
                if idx % 2 == 0:
                    powerState = "1"
                self.actions.ws_control(wsID,powerState)
            elif idx == 7:
                self.toggleService()
            elif idx == 8:
                self.actions.start_settings_server()
            elif idx == -1:
                break
            else:
                break   
        sys.modules.clear()
예제 #39
0
파일: service.py 프로젝트: charky/chyfy
 def __init__(self):
     self.monitor = CE_Monitor(self)
     self.player = xbmc.Player()
     self.actions = Actions()
     self.blue = Bluetooth()
     self.lightIsON=False
     self.deviceFound=False
     self.discoveryIsOn=False
     self.delayToggle = 0
예제 #40
0
    def __init__(self):
        self.prevGraph = None

        self.actions = Actions(sendToLiveClients)

        self.rulesN3 = "(not read yet)"
        self.inferred = Graph() # gets replaced in each graphChanged call

        self.inputGraph = InputGraph([], self.graphChanged)      
        self.inputGraph.updateFileData()
예제 #41
0
파일: listener.py 프로젝트: guyzmo/kitt
 def __init__(self, config, gestures, el, *args, **kwarg):
     """
     :param config: string containing the path to the action configuration
     :param gestures: string containing the path to the gestures configuration
     """
     super(EventDispatcher, self).__init__(*args, **kwarg)
     self._event_loop = el
     self._gdb = GestureDatabase()
     self._actions = Actions(config, gestures)
     self.update_devices()
     self._multitouches = []
예제 #42
0
파일: gui.py 프로젝트: charky/chyfy
 def __init__(self):
    self.wsControlLabels = []
    self.wsControlLabels.append(settings.wireless_switch["ws_1_name"] + " On")
    self.wsControlLabels.append(settings.wireless_switch["ws_1_name"] + " Off")
    self.wsControlLabels.append(settings.wireless_switch["ws_2_name"] + " On")
    self.wsControlLabels.append(settings.wireless_switch["ws_2_name"] + " Off")
    self.wsControlLabels.append(settings.wireless_switch["ws_3_name"] + " On")
    self.wsControlLabels.append(settings.wireless_switch["ws_3_name"] + " Off")
    self.wsControlLabels.append("- - -")
    self.wsControlLabels.append("Toggle Service on/off")
    self.actions = Actions()
예제 #43
0
파일: jail.py 프로젝트: rhertzog/lcs
 def __init__(self, name, backend="auto"):
     self.__name = name
     self.__queue = Queue.Queue()
     self.__filter = None
     if backend == "polling":
         self.__initPoller()
     else:
         try:
             self.__initGamin()
         except ImportError:
             self.__initPoller()
     self.__action = Actions(self)
예제 #44
0
  def __init__(self, mode, forceDelay=None, forceIconSize=None):
    self.mode = mode
    self.forceDelay = forceDelay

    self.prefs = Prefs()
    self.battStatus = BattStatus(self.prefs)
    self.actions = Actions(self.prefs, self.battStatus)
    if self.mode == "gtk" or self.mode == "prefs":
      self.gui = Gui(self.prefs, self.battStatus)
    elif self.mode == "json" or self.mode == "dzen":
      self.guiMarkupPrinter = GuiMarkupPrinter(
        self.prefs, self.battStatus, forceIconSize)
예제 #45
0
파일: jail.py 프로젝트: lchiquitto/fail2ban
	def __init__(self, name, backend = "auto"):
		self.__name = name
		self.__queue = Queue.Queue()
		self.__filter = None
		logSys.info("Creating new jail '%s'" % self.__name)
		if backend == "polling":
			self.__initPoller()
		else:
			try:
				self.__initGamin()
			except ImportError:
				self.__initPoller()
		self.__action = Actions(self)
예제 #46
0
파일: universe.py 프로젝트: mphair/abstrat
 def DoTimeStep(self):
     self.actions.DoGather()
     #transfer
     self.actions.DoSplit()
     self.actions.DoDiscover()
     self.actions.DoTeach()
     #unlearn
     self.actions.DoLeach()
     self.actions.DoMove()
     self.actions.DoSubsist()
     self.actions = Actions(self)
     self.__teamsAccountedFor = set()
     self.t+=1
예제 #47
0
 def on_scan_finished(self, scanner):
     # GLib.idle_add(self._on_scan_finished)
     if self.progreso_dialog is not None:
         self.progreso_dialog.destroy()
         self.progreso_dialog = None
     md = Gtk.MessageDialog(parent=self)
     md.set_title('Antiviral')
     md.set_property('message_type', Gtk.MessageType.INFO)
     md.add_button(Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT)
     md.set_property('text', _('Antiviral'))
     if len(self.infected) > 0:
         md.format_secondary_text(
             _('What a pity!, In this machine there are viruses!'))
         md.run()
         md.destroy()
         actions = Actions(self, self.infected)
         actions.run()
         actions.destroy()
     else:
         md.format_secondary_text(_('Congratulations!!, no viruses found'))
         md.run()
         md.destroy()
예제 #48
0
파일: universe.py 프로젝트: mphair/abstrat
 def LoadFromConfig(self):
     # none of these vary during the game:
     self.energyTypes = self.config.GetEnergyTypes()
     self.cells = self.config.GetInitialCells()
     self.subsistEnergyRequirements = self.config.GetSubsistEnergyRequirements()
     self.moveEnergyRequirements = self.config.GetMoveEnergyRequirements()
     self.__DefaultGatherEfficencies = self.config.GetDefaultGatherEfficencies()
     self.__DefaultMovementRate = self.config.GetDefaultMovementRate()
     self.__DefaultTeachingMultiplier = self.config.GetDefaultTeachingMultiplier()
     self.__DefaultLeachingTargetRate = self.config.GetDefaultLeachingTargetRate()
     self.__DefaultLeachingPowers = self.config.GetDefaultLeachingPowers()
     self.__DefaultLeachingDefenses = self.config.GetDefaultLeachingDefenses()
     self.__DefaultLeachingEfficencies = self.config.GetDefaultLeachingEfficencies()
     self.Advancements = self.config.GetAdvancements()
     self.actions = Actions(self)
예제 #49
0
    def apply_action(state, action):
        """ Edits the state to reflect the results of the action.
            (State, str) -> None
        """
        if action not in BlackBirdRules.get_legal_actions(state):
            raise Exception("Illegal action " + str(action))
        state.score_change = 0
        
        next_pos = Actions.get_successor(state.black_bird_position, action)
        state.black_bird_position = next_pos

        if next_pos in state.yellow_birds:
            state.score_change -= state.current_yellow_bird_score
            state.yellow_birds = tuple([yb for yb in state.yellow_birds if yb != next_pos])
            state._yellow_bird_eaten = next_pos
            if state.black_bird_position is not None:
                state.current_yellow_bird_score = max(1, state.current_yellow_bird_score - 1)   
            if not state.yellow_birds:
                state.terminal = True
예제 #50
0
 def initialize(self):
     """
         Use this function to setup your bot before the game starts.
     """
     self.verbose = True #display the command descriptions next to the bot.
     #Get the important game data to represent the current state.
     self.gameData = GameData(self.game, self.level) 
     #Get important data for each bot to represent the current state.
     self.bots = [BotData(name, self.game, self.level) for name in\
                  [bot.name for bot in self.game.team.members]]
     self.actions = Actions(self.game, self.level, self)
     #Set up reinforcement learning.
     self.agent = CTFAgent() 
     self.env = CTFEnvironment(self.actions.returnFunctions(), self.gameData, 
                               self.bots, [bot for bot in self.game.team.members]) 
     self.rl = RLinterface(self.agent, self.env)
     self.checkForPastLearning() #Check for previous learning.
     self.rl.RL_start() #Start episode.
     self.tc = 0 #Count until reinforcement learning begins. Get bots out of spawn...       
     print 'Finished Commander Initialization...'
예제 #51
0
    def apply_action(state, action):
        """ Edits the state to reflect the results of the action.
            (State, str) -> None
        """
        if action not in RedBirdRules.get_legal_actions(state):
            raise Exception("Illegal action " + str(action))
        state.score_change = 0
        
        next_pos = Actions.get_successor(state.red_bird_position, action)
        state.red_bird_position = next_pos

        if next_pos in state.yellow_birds:
            state.score_change += state.current_yellow_bird_score#YELLOW_BIRD_SCORE
            state.yellow_birds = tuple([yb for yb in state.yellow_birds if yb != next_pos])
            state._yellow_bird_eaten = next_pos
            if state.black_bird_position is not None:
                state.current_yellow_bird_score = max(1, state.current_yellow_bird_score - 1)
            if not state.yellow_birds:
                state.terminal = True
        
        #There is only a time penalty if we do not have an adversary
        if state.get_black_bird_position() is None:
            state.score_change -= TIME_PENALTY
예제 #52
0
    def __init__(self, fileName=None, parent=None):
        super(Editor, self).__init__(parent)
        
        self.setWindowIcon(QIcon(':/images/logo.png'))
        self.setToolButtonStyle(Qt.ToolButtonFollowStyle)
        
        self.textEdit = QTextEdit(self)
        self.commands = Actions(parent=self)
        
        # Setup Menu and Toolbar
        self.setupFileActions()
        self.setupEditActions()
        self.setupFormatActions()
        self.setupI18nActions()
        self.setupHelpActions()
        self.setupNavDock()
        
        self.commands.init()
        
        self.setCentralWidget(self.textEdit)
        self.setWindowModified(self.textEdit.document().isModified())

        QApplication.clipboard().dataChanged.connect(
                self.commands.clipboardDataChanged)
        
        i18n = QSettings()
        if i18n.value("lang").toString() == "zh_CN":
            self.actionChinese.setChecked(True)
        else:
            self.actionEnglish.setChecked(True)

        if fileName is None:
            fileName = ':/example.html'

        if not self.commands.load(fileName):
            self.commands.fileNew()
예제 #53
0
 def get_legal_actions(state):
     """ Black birds can move in the same way as red birds.
     """
     return Actions.get_legal_actions(state.black_bird_position,
         state.layout.walls, state.red_bird_position)
예제 #54
0
파일: universe.py 프로젝트: mphair/abstrat
class Universe:
    DEBUG_MOVE = False
    DEBUG_SUBSIST = False
    DEBUG_ENERGY = False
    DEBUG_DISCOVER = False
    DEBUG_LEARN = False
    DEBUG_TEACH = False
    DEBUG_LEACH = False

    def LoadFromConfig(self):
        # none of these vary during the game:
        self.energyTypes = self.config.GetEnergyTypes()
        self.cells = self.config.GetInitialCells()
        self.subsistEnergyRequirements = self.config.GetSubsistEnergyRequirements()
        self.moveEnergyRequirements = self.config.GetMoveEnergyRequirements()
        self.__DefaultGatherEfficencies = self.config.GetDefaultGatherEfficencies()
        self.__DefaultMovementRate = self.config.GetDefaultMovementRate()
        self.__DefaultTeachingMultiplier = self.config.GetDefaultTeachingMultiplier()
        self.__DefaultLeachingTargetRate = self.config.GetDefaultLeachingTargetRate()
        self.__DefaultLeachingPowers = self.config.GetDefaultLeachingPowers()
        self.__DefaultLeachingDefenses = self.config.GetDefaultLeachingDefenses()
        self.__DefaultLeachingEfficencies = self.config.GetDefaultLeachingEfficencies()
        self.Advancements = self.config.GetAdvancements()
        self.actions = Actions(self)

    def LoadNew(self, configFileName):
        f = open(configFileName)
        jsonString = f.read()
        f.close()
        self.config = Config.FromJson(jsonString, self)
        self.LoadFromConfig()
        # the following vary during the game:
        self.entities = self.config.GetInitialEntities(self.cells)
        self.t = 1
        self.__initTeams()

    def ToJson(self):
        return json.dumps({
            'config': self.config.ToJson(),
            'entities': [entity.ToJson() for entity in self.entities],
            't': self.t})
    @staticmethod
    def FromJson(jsonString):
        universe = Universe()
        universe.ReinitFromJson(jsonString)
        return universe

    def __initTeams(self):
        self.__teams = set()
        for entity in self.entities:
            self.__teams.add(entity.Team.lower())
        self.__teamsAccountedFor = set()

    def ReinitFromJson(self, jsonString):
        d = json.loads(jsonString)
        self.config = Config.FromJson(d['config'], self)
        self.LoadFromConfig()

        cellDict = dict()
        for cell in self.cells:
            cellDict[cell.Name] = cell
        self.entities = [Entity.FromJson(jsonString, self, cellDict) for jsonString in d['entities']]

        self.t = d['t']
        self.__initTeams()
        
    def GetDefaultGatherEfficencies(self):
        return copy.deepcopy(self.__DefaultGatherEfficencies)

    def GetDefaultMovementRate(self):
        return copy.deepcopy(self.__DefaultMovementRate)

    def GetDefaultTeachingMultiplier(self):
        return self.__DefaultTeachingMultiplier

    def GetDefaultLeachingTargetRate(self):
        return self.__DefaultLeachingTargetRate
    def GetDefaultLeachingPowers(self):
        return copy.deepcopy(self.__DefaultLeachingPowers)
    def GetDefaultLeachingDefenses(self):
        return copy.deepcopy(self.__DefaultLeachingDefenses)
    def GetDefaultLeachingEfficencies(self):
        return copy.deepcopy(self.__DefaultLeachingEfficencies)

    def DoTimeStep(self):
        self.actions.DoGather()
        #transfer
        self.actions.DoSplit()
        self.actions.DoDiscover()
        self.actions.DoTeach()
        #unlearn
        self.actions.DoLeach()
        self.actions.DoMove()
        self.actions.DoSubsist()
        self.actions = Actions(self)
        self.__teamsAccountedFor = set()
        self.t+=1
        
    def ActTryTimestep(self, actions, team):
        self.actions.extend(actions)
        self.__AccountFor(team)
        if self.__AllAccountedFor():
            self.DoTimeStep()
            return True
        return False
        
    def __AccountFor(self, team):
        if team not in self.__teams:
            raise "Team " + str(team) + " unknown."
        self.__teamsAccountedFor.add(team)

    def AccountedFor(self, team):
        return (team in self.__teamsAccountedFor)
    def __AllAccountedFor(self):
        return all([self.AccountedFor(team) for team in self.__teams])
        
    def RunTests(self):
        self.LoadNew("basic.config")
        self.DoTimeStep()
        print self.entities
        print "now move"
        self.actions.PendingMoves.append((self.entities[0],self.entities[0].PresentInCell.Neighbors[2]))
        self.actions.PendingMoves.append((self.entities[1],self.entities[1].PresentInCell.Neighbors[0]))
        self.DoTimeStep()
        print self.entities
        print "now just sit"
        self.DoTimeStep()
        print self.entities
        print "now split"
        self.actions.PendingSplits.append((self.entities[0],self.entities[0].PresentInCell.Neighbors[2]))
        self.actions.PendingSplits.append((self.entities[1],self.entities[1].PresentInCell.Neighbors[0]))
        self.DoTimeStep()
        print self.entities
        print "now A:1 and B:1 move too much and die"
        self.entities[2].MovementRate = 4 # hack to allow too much movement
        self.entities[3].MovementRate = 4 # hack to allow too much movement
        next = [self.entities[2].PresentInCell.Neighbors[0], self.entities[3].PresentInCell.Neighbors[0]]
        for x in range(4):
            for n in range(2):
                print "->", next[n].Name
                self.actions.PendingMoves.append((self.entities[n+2],next[n]))
                next[n] = next[n].Neighbors[0]
        self.DoTimeStep()
        print self.entities
#        self.DEBUG_DISCOVER = True
#        self.DEBUG_LEARN = True
#        self.DEBUG_ENERGY = True
        print "try to discover ahead of schedule"
        self.actions.PendingDiscoveries.append((self.entities[0],u"movement+2",((u"n1",2),)))
        self.DoTimeStep()
        print self.entities
        print "now discover prereq"
        self.actions.PendingDiscoveries.append((self.entities[0],u"movement+1",((u"n1",2),)))
        self.DoTimeStep()
        print self.entities
        print "now discover again"
        self.actions.PendingDiscoveries.append((self.entities[0],u"movement+2",((u"n1",0),)))
        self.DoTimeStep()
        print self.entities
        print "teach"
        self.actions.PendingTeachings.append((self.entities[0],u'movement+1',((u'n1',1),),self.entities[1]))
        self.DoTimeStep()
        print self.entities
예제 #55
0
 parser.add_argument('--range', dest='range')
 parser.add_argument('--nmap_options', dest='nmap_options')
 args = parser.parse_args()
 db = args.db
 filters = args.filters
 criteria = args.criteria
 if criteria == None:
     criteria = ''
 geoloc = args.geoloc
 if geoloc == None:
     geoloc = ''
 collection = args.collection
 attr = args.attr
 msg = db + ' ' + ' ' + args.action + ' ' + criteria
 h.register(msg)
 act = Actions(db)
 if args.action == 'reset':
     act.reset()
 elif args.action == 'metasearch':
     if criteria and scriptsJS and db and geoloc:
         criteria = criteria.split(',')
         act.metasearch(criteria, scriptsJS, geoloc)
 elif args.action == 'search_ip':
     act.search_ip(geoloc, scriptsJS, args.range)
 elif args.action == 'create_network':
     act.create_network()
 elif args.action == 'metadata':
     act.metadata_exctract()
 elif args.action == 'create_result':
     if not criteria and not db:
         parser.print_help()
예제 #56
0
파일: tests.py 프로젝트: AHAPX/test-rest
 def test_Actions_run(self, run):
     actions = Actions([Action(), Action()])
     actions.run()
     self.assertEqual(run.call_count, 2)
예제 #57
0
    INSERT  = 1
    OBSERVE = 2
    VISUAL  = 3
    VISUAL_BATCH = 4

if '__main__' == __name__:
    mode = Mode.COMMAND
    pygame.init()
    running = True
    snapgrid = False
    width, height = 400, 400
    observer = Point( width / 2, height / 2, 100 )
    model   = Model( ( width, height ), observer )
    screen  = pygame.display.set_mode( ( width, height + 40 ) )
    objects = [ ]
    actions = Actions()
    leftClick = rightClick = False
    while running:
        for event in pygame.event.get():
            if QUIT == event.type:
                running = False
            elif KEYUP == event.type:
                if K_g == event.key:
                    model = model.update_position( Point( 0, 0, 0 ) )
                elif K_i == event.key:
                    mode = Mode.INSERT
                elif K_u == event.key:
                    if actions.can_undo():
                        actions.undo()
                elif K_r == event.key:
                    if actions.can_redo():
예제 #58
0
class RLCommander(Commander):
    """
        Rename and modify this class to create your own commander and add 
        mycmd.Placeholder to the execution command you use to run the 
        competition.
    """
    
    
    #LEARNING_PATH = '/media/jayden/Storage/Linux/AIGameDev/CaptureTheFlag/aisbx-0.20.6.linux-x86_64/' 
    LEARNING_PATH = '/home/jayden/AIGameDev/CaptureTheFlag/aisbx-0.20.5.linux-x86_64/'


    def initialize(self):
        """
            Use this function to setup your bot before the game starts.
        """
        self.verbose = True #display the command descriptions next to the bot.
        #Get the important game data to represent the current state.
        self.gameData = GameData(self.game, self.level) 
        #Get important data for each bot to represent the current state.
        self.bots = [BotData(name, self.game, self.level) for name in\
                     [bot.name for bot in self.game.team.members]]
        self.actions = Actions(self.game, self.level, self)
        #Set up reinforcement learning.
        self.agent = CTFAgent() 
        self.env = CTFEnvironment(self.actions.returnFunctions(), self.gameData, 
                                  self.bots, [bot for bot in self.game.team.members]) 
        self.rl = RLinterface(self.agent, self.env)
        self.checkForPastLearning() #Check for previous learning.
        self.rl.RL_start() #Start episode.
        self.tc = 0 #Count until reinforcement learning begins. Get bots out of spawn...       
        print 'Finished Commander Initialization...'


    def tick(self):
        """
            Override this function for your own bots.  
            Here you can access all the information in self.game,
            which includes game information, and self.level which includes 
            information about the level.
        """
        #if self.tc % 10 == 0:
        self.updateGameState()
        #self.gameData.printProperties()
        #print '\n\n\n'
        self.runRL()
        self.tc += 1


    def shutdown(self):
        """
            Use this function to teardown your bot after the game is over, 
            or perform an analysis of the data accumulated during the game.
        """
        print 'Writing out State Action Values...'
        self.agent.sendToFile_QValues()
        #self.agent.sendToFile_ActionValues()
        print 'Fin.'



    
    ######################################################################
    #Utility
    ######################################################################  

    def printStars(self):
        """
            Print stars for formatting output nicely.
        """
        print '*' * 80

    
    def updateGameState(self):
        """
            Update the data structures with the new information.
        """
        self.gameData.updateGameState(self.game)
        for bot in self.bots:
            bot.updateGameState(self.game, self.level)
 

    def printStateProperties(self):
        """
            Print the value of all the properties of our state.
        """
        self.printStars()
        print 'Game Properties'
        self.printStars()
        self.gameData.printProperties()
        self.printStars()
        print 'Bot Properties'
        for bot in self.bots:
            self.printStars()
            bot.printProperties()
            self.printStars()
        print '\n\n\n'


    def checkForPastLearning(self):
        """
            Checks whether learning has occured before and if so
            reads in this information and passes it to the agent.
        """
        print 'Checking for previous learning...'
        if os.path.exists(RLCommander.LEARNING_PATH) and \
        os.path.isfile(os.path.join(RLCommander.LEARNING_PATH, 'data.pkl')):
           print 'Found previous learning. Reading in data.'
           self.agent.readFromFile_QValues()
        else:
            print 'No previous learning. Starting with defaults.'


    def runRL(self):
        """
            Iterate through the bots on the team
            and run one step.
        """
        if self.tc > 0:
            for bot in self.game.team.members:
                self.rl.RL_step_two()
                #Update the botData and bot references.
                botData = [b for b in self.bots if b.botName == bot.name][0]
                self.env.botUpdate(bot, botData)
                self.rl.RL_step_one()
        else:
            print 'Taking a step - First tick iteration.'
            for bot in self.game.team.members:
                botData = [b for b in self.bots if b.botName == bot.name][0]
                self.env.botUpdate(bot, botData)
                self.rl.RL_step_one()
            print 'First tick iteration ending.'
예제 #59
0
파일: jail.py 프로젝트: rhertzog/lcs
class Jail:
    def __init__(self, name, backend="auto"):
        self.__name = name
        self.__queue = Queue.Queue()
        self.__filter = None
        if backend == "polling":
            self.__initPoller()
        else:
            try:
                self.__initGamin()
            except ImportError:
                self.__initPoller()
        self.__action = Actions(self)

    def __initPoller(self):
        logSys.info("Using poller")
        from filterpoll import FilterPoll

        self.__filter = FilterPoll(self)

    def __initGamin(self):
        # Try to import gamin
        import gamin

        logSys.info("Using Gamin")
        from filtergamin import FilterGamin

        self.__filter = FilterGamin(self)

    def setName(self, name):
        self.__name = name

    def getName(self):
        return self.__name

    def getFilter(self):
        return self.__filter

    def getAction(self):
        return self.__action

    def putFailTicket(self, ticket):
        self.__queue.put(ticket)

    def getFailTicket(self):
        try:
            return self.__queue.get(False)
        except Queue.Empty:
            return False

    def start(self):
        self.__filter.start()
        self.__action.start()

    def stop(self):
        self.__filter.stop()
        self.__action.stop()
        self.__filter.join()
        self.__action.join()

    def isAlive(self):
        isAlive0 = self.__filter.isAlive()
        isAlive1 = self.__action.isAlive()
        return isAlive0 or isAlive1

    def setIdle(self, value):
        self.__filter.setIdle(value)
        self.__action.setIdle(value)

    def getIdle(self):
        return self.__filter.getIdle() or self.__action.getIdle()

    def getStatus(self):
        fStatus = self.__filter.status()
        aStatus = self.__action.status()
        ret = [("filter", fStatus), ("action", aStatus)]
        return ret