def get_command_list(self):
     prepared_commands = []
     for offset, column in {
             1:
         (Constant.CELL_DELIMITER_SIZE + Constant.CELL_TOTAL_SIZE * 0,
          Constant.CELL_TOTAL_SIZE * 1),
             -1:
         (Constant.CELL_DELIMITER_SIZE + Constant.CELL_TOTAL_SIZE * 2,
          Constant.CELL_TOTAL_SIZE * 3)
     }.items():
         f = Formation(self._all_vehicles,
                       self._me,
                       ownership=Ownership.ALLY,
                       column=column)
         from_topleft, from_bottomright = f.find_topleft(
         ), f.find_bottomright()
         to_topleft, to_bottomright = (from_topleft[0], from_topleft[1] + offset * Constant.CELL_TOTAL_SIZE), \
                                      (from_bottomright[0], from_bottomright[1] + offset * Constant.CELL_TOTAL_SIZE)
         speed_factor = self._terrain_map.get_minimum_speed_factor_on_path(
             from_topleft, from_bottomright, to_topleft, to_bottomright)
         prepared_commands.append(
             Action.clear_and_select(topleft=f.find_topleft(),
                                     bottomright=f.find_bottomright()))
         prepared_commands.append(
             Action.move(offset * Constant.CELL_TOTAL_SIZE, 0,
                         0.3 * speed_factor))
     return prepared_commands
    def get_command_list(self):
        optimal_position = self.__generate_optimal_position()
        ground_force_commands = self.__build_commands(
            optimal_position, Constant.GROUND_FORCE_TYPES)
        air_force_commands = self.__build_commands(optimal_position,
                                                   Constant.AIR_FORCE_TYPES)
        commands = ground_force_commands + air_force_commands
        prepared_commands = []
        for command in commands:
            if command is not None:
                topleft = [
                    c * Constant.CELL_TOTAL_SIZE + Constant.CELL_DELIMITER_SIZE
                    for c in command['current']
                ]
                bottomright = [(c + 1) * Constant.CELL_TOTAL_SIZE
                               for c in command['current']]
                diff = [d * Constant.CELL_TOTAL_SIZE for d in command['diff']]
                target_topleft = (topleft[0] + diff[0], topleft[1] + diff[1])
                target_bottomright = (bottomright[0] + diff[0],
                                      bottomright[1] + diff[1])

                base_speed = Constant.MAX_SPEED[command['type']]
                characteristic_map = self._weather_map if command[
                    'type'] in Constant.AIR_FORCE_TYPES else self._terrain_map
                speed_factor = characteristic_map.get_minimum_speed_factor_on_path(
                    topleft, bottomright, target_topleft, target_bottomright)

                prepared_commands.append(
                    Action.clear_and_select(topleft, bottomright,
                                            command['type']))
                prepared_commands.append(
                    Action.move(diff[1], diff[0], base_speed * speed_factor))
        return prepared_commands
Exemplo n.º 3
0
    def execute(self, event=None):
        Action.execute(self)
        #making sure filename isn't "" and that it doesnt have commas
        if (len(self.filename) == 0):
            _ = Error("File must have a name")
            return
        if ("," in self.filename):
            _ = Error("Cannot use commas in filename when saving")
            return

        #saving items into the file
        fullfilename = os.getcwd() + '/' + self.filename + '.txt'
        self.filename = fullfilename
        f = open(os.path.expanduser(self.filename), "w+")
        for i, subj in enumerate(self.ScheduleList, 1):
            f.write(str(i) + "\t")
            lectext = subj.cd + ',' + subj.dy + ',' + subj.stH + ',' + subj.stM + ',' + subj.enH + ',' + subj.enM
            f.write(lectext)
            f.write("\t")
            if not (subj.SubObj.link == None):
                tuttext = subj.dy1 + ',' + subj.stH1 + ',' + subj.stM1 + ',' + subj.enH1 + ',' + subj.enM1
                f.write(tuttext)
            else:
                f.write("None")
            f.write("\n")

        f.close()
        self.filename = ""
        self.wind.destroy()
Exemplo n.º 4
0
 def __init__(self):
     self.action = None
     self.name = None
     self.actions = [Action("rock"), Action("paper"), Action("scissor")]
     self.op_actions = []  # opponent's choice of action in each game
     self.results = []  # points gotten in each game
     self.current_win_rates = []
Exemplo n.º 5
0
	def consequences(self, atackingOrganism):
		result = []
		if self.power > atackingOrganism.power:
			result.append(Action(ActionEnum.A_REMOVE, Position(xPosition=-1, yPosition=-1), 0, atackingOrganism))
		else:
			result.append(Action(ActionEnum.A_REMOVE, Position(xPosition=-1, yPosition=-1), 0, self))
		return result
Exemplo n.º 6
0
    def successor(self, state: []) -> '[ActionStatePair]':

        possible_actions = deepcopy(self.actions)
        possible_action_state_pair = []

        blank_loc = ()
        for i in range(len(state)):
            for j in range(len(state)):
                if state[i][j] == 0:
                    blank_loc = (i, j)
                    break

        if blank_loc[1] == 0:
            possible_actions.remove(Action("left"))
        if blank_loc[1] == 3:
            possible_actions.remove(Action("right"))
        if blank_loc[0] == 0:
            possible_actions.remove(Action("up"))
        if blank_loc[0] == 3:
            possible_actions.remove(Action("down"))

        for action in possible_actions:
            current_state = deepcopy(state)
            possible_action_state_pair.append(
                ActionStatePair(action=action,
                                state=self.perform_action(
                                    current_state, action)))

        return possible_action_state_pair
Exemplo n.º 7
0
def load_params(mud):
    """

    :type mud: Mud
    """
    bases = []
    ships = []
    space = []
    events = []
    try:
        with open(SAVE_FILE) as json_file:
            data = json.load(json_file)
    except OSError:
        print("Starting a new game!  Enter 'help' for commands.")
        return Action(mud)
    mud.ore = int(data['ore'])
    mud.bmat = int(data['bmat'])
    mud.fuel = int(data['fuel'])
    for b in data['bases']:
        bases.append(b)
    mud.bases = bases
    for s in data['ships']:
        ships.append(Ship.load(s))
    mud.ships = ships
    for s in data['space']:
        space.append(Ship.load(s))
    mud.space = space
    for e in data['events']:
        eve = MyEvent.load(e)
        events.append(eve)
    mud.events = events
    return Action(mud)
Exemplo n.º 8
0
    def place_down_corner(color1, color2):

        down_corner = Solver.find_cubelet(Face.White, color1, color2)
        index_of_cubelet = Solver.cube.cubelets.index(down_corner)

        # In the bottom layer
        if index_of_cubelet > 17:

            count = 0

            while index_of_cubelet != 26:
                Action.D()
                count += 1
                index_of_cubelet = Solver.cube.cubelets.index(down_corner)

            Solver.place_down_corner_algorithm()

            for i in range(count):
                Action.Di()

            Solver.place_down_corner_algorithm()

            return

        # In the top layer
        count = 0
        while index_of_cubelet != 8:
            Action.U()
            count += 1
            index_of_cubelet = Solver.cube.cubelets.index(down_corner)

        Solver.place_down_corner_algorithm()
Exemplo n.º 9
0
    def turn_cube_ccw():

        Action.Ui()
        Solver.cube.rotate_face_ccw(Solver.cube.get_up_middle(),
                                    Cubelet.turn_u_ccw,
                                    Solver.cube.set_up_middle)
        Action.D()
Exemplo n.º 10
0
    def orient_up_cross():

        counter = 0

        while True:
            while Solver.cube.cubelets[1].sides[3] != Face.Green:
                Action.U()

            cross_edges = [
                Solver.cube.cubelets[1].sides[3],
                Solver.cube.cubelets[3].sides[4],
                Solver.cube.cubelets[7].sides[1],
                Solver.cube.cubelets[5].sides[2]
            ]
            if cross_edges == [Face.Green, Face.Orange, Face.Blue, Face.Red]:
                break

            index_blue = cross_edges.index(Face.Blue)

            # Vertical line
            if cross_edges[(index_blue + 2) % 4] == Face.Green:
                Solver.orient_up_cross_algorithm()

            if cross_edges[0] == ((cross_edges[1].value + 1) % 4 + 1):
                Action.Ui()
            elif cross_edges[0] == ((cross_edges[1].value + 1) % 4 + 1):
                Action.U()

            if counter == 3:
                counter = 0
                Action.U()

            Solver.orient_up_cross_algorithm()

            counter += 1
Exemplo n.º 11
0
    def position_side_edge(color1, color2):

        edge_cubelet = Solver.find_cubelet(color1, color2)
        index_of_cubelet = Solver.cube.cubelets.index(edge_cubelet)

        if 8 < index_of_cubelet < 18:
            count = 0
            while index_of_cubelet != 17:
                Action.Yi()
                index_of_cubelet = Solver.cube.cubelets.index(edge_cubelet)
                count += 1
            Solver.position_side_edge_algorithm()
            for i in range(count):
                Action.Y()

        index_of_cubelet = Solver.cube.cubelets.index(edge_cubelet)

        if index_of_cubelet < 9:
            while index_of_cubelet != 5:
                Action.U()
                index_of_cubelet = Solver.cube.cubelets.index(edge_cubelet)

            Solver.position_side_edge_algorithm()

        if edge_cubelet.sides[1] != color1:
            # re-orient
            Solver.position_side_edge_algorithm()
            Action.U()
            Action.U()
            Solver.position_side_edge_algorithm()
Exemplo n.º 12
0
    def position_up_corners():

        while True:
            while Solver.cube.cubelets[7].sides[1] != Face.Blue:
                Action.U()

            YBR = Solver.find_cubelet(Face.Yellow, Face.Blue, Face.Red)
            YGR = Solver.find_cubelet(Face.Yellow, Face.Green, Face.Red)
            YGO = Solver.find_cubelet(Face.Yellow, Face.Green, Face.Orange)
            YBO = Solver.find_cubelet(Face.Yellow, Face.Blue, Face.Orange)

            if (Solver.cube.cubelets.index(YBR) == 8
                    and Solver.cube.cubelets.index(YGR) == 2
                    and Solver.cube.cubelets.index(YGO) == 0
                    and Solver.cube.cubelets.index(YBO) == 6):
                break

            if Solver.cube.cubelets.index(YGR) == 2:
                Action.Ui()
            elif Solver.cube.cubelets.index(YGO) == 0:
                Action.U()
                Action.U()
            elif Solver.cube.cubelets.index(YBO) == 6:
                Action.U()

            Solver.position_up_corners_algorithm()
Exemplo n.º 13
0
 def get_opening_bet_action(self, request, game, hand_state):
     """Get Action in response to open bet request"""
     self.display_hand_state(request, game, hand_state)
     user_selection = self._newUserSelection()
     user_selection.add_option("c", "check", Action.new_check())
     user_selection.add_option("b", "bet", Action.new_bet(request.amount))
     return user_selection.get_user_selection()
Exemplo n.º 14
0
    def getAction(self, number: int) -> "Action Object":
        ########################################################################
        #							YOUR CODE BEGINS						   #
        ########################################################################
        self.__tileNumState = number
        self.__updateGame()

        if not self.__isGameOver:
            self.__findSafeMoves(self.__lastX, self.__lastY)
            if (len(self.__safeMoves)):
                action = AI.Action.UNCOVER
                x, y = self.__getMove()
                self.__finishedMoves.add((x, y))
                return Action(action, x, y)

            self.__findBomb()
            if (len(self.__flagCoor)):
                action = AI.Action.FLAG
                x, y = self.__getMove()
                self.__visited.add((x, y))
                self.__finishedMoves.add((x, y))
                # self.__board.totalMines -= 1
                return Action(action, x, y)
            else:
                self.__lastX, self.__lastY = self.__getMoveProb()
                action = AI.Action.UNCOVER
                return Action(action, self.__lastX, self.__lastY)

        else:
            action = AI.Action.LEAVE
            return Action(action)
Exemplo n.º 15
0
def test_updatestate():
    gs = HackingState("TestReflectionString",
                      "Il Pentest sta verificando se la stringa è riflessa",
                      False)
    gs.setAction(
        Action(
            "NameRequest",
            "Invia la richiesta con una testNTT, controlla tutte le pagine per verificare se la stringa è riflessa"
        ))
    observation1 = Observation("ReflectionString", "La stringa e' riflessa")
    observation2 = Observation("NotReflectionString",
                               "La stringa non e' riflessa")
    newHS = HackingState("TestReflectionType",
                         "Il Pentest sta verificando il tipo di riflessione",
                         False)
    actionToAnalyze = Action("CheckReflectionType",
                             "Analizza la riflessione dove è avvenuta")
    newHS.setAction(actionToAnalyze)
    failState = HackingState("NoXSS", "No xss found", False)
    gs.addObservationState(observation1, newHS)
    gs.addObservationState(observation2, failState)
    hg = HackingGoal("xss", "goal", gs)
    currentObservation = Observation("ReflectionString",
                                     "La stringa e' riflessa")
    hg.acquireObservation(currentObservation)
    theActionToDo = hg.suggestAction()
    assert theActionToDo == actionToAnalyze
def getClassLabel(c_):

	global frameCount, setLabel

	if setLabel != c_:
		frameCount = 0
	setLabel = c_

	if c_ == 0:
		frameCount = (frameCount + 1)
		if frameCount > threshold:
			return "One Finger Only"
	if c_ == 1:
		frameCount = (frameCount + 1)
		if frameCount > threshold:
			return "Victory"
	if c_ == 2:
		frameCount = (frameCount + 1)
		if frameCount > threshold:
			Action.play()
			return "Fist"
	if c_ == 3:
		frameCount = (frameCount + 1)
		if frameCount > threshold:
			Action.pause()
			return "Wait"
	if c_ == 4:
		if frameCount > 20:
			return "Nothing There"
Exemplo n.º 17
0
	def __init__(self, say=None, play=None, finishOnKey=None, maxLength=None, timeout=None, trimSilence=None, playBeep=None, callbackUrl=None):
		children = []
		attributes ={}
		if say is not None:
			children.append(say)
		if play is not None:
			children.append(play)
		if maxLength is not None:
			maxLength = '"' + maxLength + '"'
			attributes['maxLength'] = maxLength
		if timeout is not None:
			timeout = '"' + timeout + '"'
			attributes['timeout'] = timeout
		if finishOnKey is not None:
			finishOnKey = '"' + finishOnKey + '"'
			attributes['finishOnKey'] = finishOnKey
		if callbackUrl is not None:
			callbackUrl = '"' + callbackUrl + '"'
			attributes['callBackUrl'] = callbackUrl
		if playBeep is not None:
			playBeep = '"' + playBeep + '"'
			attributes['playBeep'] = playBeep
		if trimSilence is not None:
			trimSilence = '"' + trimSilence + '"'
			attributes['trimSilence'] = trimSilence

		Action.__init__(self, tag="Record", children=children, attributes=attributes)
Exemplo n.º 18
0
    def execute(self, event=None):
        Action.execute(self)
        self.generate_dict()
        self.generate_schedule()

        #checking that the user enters a name

        if (len(self.filename) == 0):
            _ = Error("File must have a name")
            return

        # Opens file and prints Schedules inside it
        fullfilename = os.getcwd() + '/' + self.filename + '.txt'
        self.filename = fullfilename
        f = open(os.path.expanduser(self.filename), "w+")
        for i, Sched in enumerate(self.ScheduleList, 1):
            f.write('-' * 25 + ' Schedule ( ' + str(i) + ' ) ' + '-' * 25)
            f.write("\n")
            for key, val in Sched.days.items():
                line = key + " : " + str(val)
                f.write(line)
                f.write("\n")

        self.filename = ""
        f.close()

        self.wind.destroy()
Exemplo n.º 19
0
    def getPossibleActions(self, state):

        r = state.m_agentPos.row
        c = state.m_agentPos.col
        action = None

        l = []

        oponent_color = -1
        if self.m_color == 0:  # white pawn
            oponent_color = 1
        elif self.m_color == 1:  # black pawn
            oponent_color = 1

        if state.m_board[r + 1][c] == Utils.empty:  # standard pawn move
            l.append(Action(state.m_agentPos, Position(r + 1, c)))
        if r == 1 and (state.m_board[r + 2][c]
                       == Utils.empty):  # starting pawn move
            l.append(Action(state.m_agentPos, Position(r + 2, c)))
        if c > 0 and (state.m_board[r + 1][c - 1] != Utils.empty) and (
                Utils.getColorPiece(
                    state.m_board[r + 1][c - 1]) == oponent_color):  # capture
            l.append(Action(state.m_agentPos, Position(r + 1, c - 1)))
        if c < (state.m_boardSize - 1) and (
                state.m_board[r + 1][c + 1] !=
                Utils.empty) and (Utils.getColorPiece(
                    state.m_board[r + 1][c + 1]) == oponent_color):  # capture
            l.append(Action(state.m_agentPos, Position(r + 1, c + 1)))

        return l
Exemplo n.º 20
0
        def guessAccum(self, finalLocationz):
                #finalLocationz = findAllUnopen()
                theMaxPlace = tuple()
                theMinPlace = tuple()
                theMax = 0
                theMin = 0
                bombTogether = False
                for f in finalLocationz:
                        openAdjTiles = list()
                        tempValue = 0
                        openAdjTiles = self.openAdjacent(f[0],f[1], self.matrix)

                        for o in openAdjTiles:
                                val = self.checkBoard(o[0],o[1], self.matrix)
                                if val == -1:
                                        difX = f[0] - o[0]
                                        difY = f[1] - o[1]
                                        if difX == 0 and difY != 0:
                                                if self.bombsNext(f[0]+1, f[1], o[1], "Y") or self.bombsNext(f[0]-1, f[1], o[1], "Y"):
                                                        bombTogether = True
                                                        break
                                        elif difX != -1 and difY == 0:
                                                if self.bombsNext(f[0], f[1]+1, o[0], "X") or self.bombsNext(f[0], f[1]-1, o[0], "X"):
                                                        bombTogether = True
                                                        break
                                tempValue += val

                        if bombTogether:
                                self.actionLocation = f
                                return Action(AI.Action.UNCOVER, self.actionLocation[0], self.actionLocation[1])


                #safety measure
                self.actionLocation = finalLocationz[0]
                return Action(AI.Action.UNCOVER, self.actionLocation[0], self.actionLocation[1])
 def get_command_list(self):
     f = Formation(self._all_vehicles, self._me, ownership=Ownership.ALLY)
     base_y = f.find_topleft()[0]
     group_height = Constant.SANDWICH_HORIZONTAL_GROUP_INDEX * (
         2 * Constant.UNIT_RADIUS + Constant.UNIT_INITIAL_DISTANCE)
     central_column = (Constant.CELL_DELIMITER_SIZE +
                       Constant.CELL_TOTAL_SIZE * 1,
                       Constant.CELL_TOTAL_SIZE * 2)
     prepared_commands = []
     for i in range(Constant.SANDWICH_GROUP_COUNT):
         top_y = base_y + i * group_height
         bottom_y = base_y + (i + 1) * group_height
         offset = (Constant.CELL_SIZE + Constant.UNIT_INITIAL_DISTANCE) * (
             1 - i % Constant.SANDWICH_HORIZONTAL_GROUP_INDEX)
         base_speed = min(Constant.MAX_SPEED)
         speed_factor = self._terrain_map.get_minimum_speed_factor_on_path(
             (top_y, central_column[0]), (bottom_y, central_column[1]),
             (top_y, central_column[0] + offset),
             (bottom_y, central_column[1] + offset))
         prepared_commands.append(
             Action.clear_and_select((top_y, central_column[0]),
                                     (bottom_y, central_column[1])))
         prepared_commands.append(Action.assign(i + 1))
         if offset == 0 or i == Constant.INITIAL_FORMATION_UNITS_COUNT - 1:
             continue
         prepared_commands.append(
             Action.move(offset, 0, base_speed * speed_factor))
     return prepared_commands
Exemplo n.º 22
0
	def solve(self) -> None:
		# when new statement is found, search again
		found_new_statement = True
		while found_new_statement:
			found_new_statement = False
			# for each pair of statements, try generate new statement using the two
			new_stmt_list = []
			for stmt in self.statement_list:
				for other_stmt in self.statement_list:
					if stmt!=other_stmt:
						new_stmt = self.minus(stmt, other_stmt)
						if new_stmt!=None:	# new statement is valid
							if self.is_solveable(new_stmt):
								if new_stmt not in self.infer_result:
									self.infer_result.append(new_stmt)
							else:
								if (new_stmt not in self.statement_list) and (new_stmt not in new_stmt_list):
									new_stmt_list.append(new_stmt)
									found_new_statement = True
			self.statement_list.extend(new_stmt_list)
			#print(len(new_stmt_list))

		# add the solvables found to list
		for stmt in self.infer_result:
			if stmt["mine_cnt"]==0:
				for tile in stmt["tile_list"]:
					self.solvable.append(Action(AI.Action.UNCOVER,tile.x,tile.y))
			elif len(stmt["tile_list"])==stmt["mine_cnt"]:
				for tile in stmt["tile_list"]:
					self.solvable.append(Action(AI.Action.FLAG,tile.x,tile.y))
Exemplo n.º 23
0
    def __init__(self):
        goal1 = Goal("Health", 4)
        goal2 = Goal("Have fun!", 3)
        self.goals = [goal1, goal2]
        self.action_index = -1

        game_state = self

        # actions
        action1 = Action("Go out for dinner", [{
            "goal": goal1,
            "insistance_change": -4
        }], -3)
        action2 = Action("Party!!", [{
            "goal": goal2,
            "insistance_change": -2
        }], -3)
        action3 = Action("Eat at home", [{
            "goal": goal1,
            "insistance_change": -2
        }], -2)
        self.base_action = Action("No action", [], 0)

        self.actions = [action1, action2, action3]
        self.money = 5
    def select_action(self):
        if len(self.__opponent_actions) <= self.__remember:
            return Action.get_random_action(self)

        last_opponent_actions = self.__opponent_actions.copy()[-1 * self.__remember :]
        historical_next_actions = []

        for i in range(0, len(self.__opponent_actions) - 1):
            if i < self.__remember - 1:
                continue
            sub_sequence = []
            next_action = self.__opponent_actions[i + 1]
            for j in range(0, self.__remember):
                sub_sequence.append(self.__opponent_actions[i - j].get_weapon())
            sub_sequence.reverse()

            matches = True
            for k in range(0, self.__remember):
                if last_opponent_actions[k].get_weapon() != sub_sequence[k]:
                    matches = False
            if matches:
                historical_next_actions.append(next_action)

        if len(historical_next_actions) == 0:
            return Action.get_random_action(self)

        most_probable_action = Action(self.__most_frequent(historical_next_actions))

        return Action.get_counter_action(self, most_probable_action)
Exemplo n.º 25
0
    def __init__(self):
        goal1 = Goal("Eat", 4)
        goal2 = Goal("Sleep", 3)
        self.goals = [goal1, goal2]
        self.action_index = -1

        game_state = self

        # actions
        action1 = Action("Get raw food", [{
            "goal": goal1,
            "insistance_change": -4
        }], -3)
        action2 = Action("Sleep in bed", [{
            "goal": goal2,
            "insistance_change": -2
        }], -3)
        action3 = Action("Get snack", [{
            "goal": goal1,
            "insistance_change": -2
        }], -2)
        self.base_action = Action("No action", [], 0)

        self.actions = [action1, action2, action3]
        self.strength = 5
 def possible_moves(self, board: Board):
     if self.player == 2 and not self.is_king:
         nearby_coords = [(self.x + 1, self.y + 1),
                          (self.x - 1, self.y + 1)]
     elif self.player == 1 and not self.is_king:
         nearby_coords = [(self.x + 1, self.y - 1),
                          (self.x - 1, self.y - 1)]
     else:
         nearby_coords = [
             (self.x + 1, self.y + 1), (self.x - 1, self.y + 1),
             (self.x - 1, self.y - 1), (self.x + 1, self.y - 1)
         ]
     possible_moves = []
     jump_moves = []
     state = board.get_board()
     for x, y in nearby_coords:
         if 0 <= x < len(state) and 0 <= y < len(state[0]):
             if state[x][y] == 0:
                 possible_moves.append(
                     Action(x, y, CheckersPawn(self.x, self.y, self.color)))
             elif state[x][y] != state[self.x][self.y]:
                 projectory_x, projectory_y = (x - self.x) + x, (y -
                                                                 self.y) + y
                 if 0 <= projectory_x < len(state) and 0 <= projectory_y < len(state[0]) \
                         and state[projectory_x, projectory_y] == 0:
                     jump_moves.append(
                         Action(projectory_x, projectory_y,
                                CheckersPawn(self.x, self.y, self.color)))
     return possible_moves, jump_moves
 def select_action(self):
     last_weapon = self.__get_last_weapon().get_weapon()
     if last_weapon == "rock":
         return Action("paper")
     if last_weapon == "paper":
         return Action("scissors")
     return Action("rock")
Exemplo n.º 28
0
	def __init__(self, nodeName, imageName, node, newText):
		Action.__init__(self, node.documentOwner)
		self.nodeName = nodeName
		self.imageName = imageName
		self.node = node
		self.newText = newText
		self.oldText = self.node.GetText()
Exemplo n.º 29
0
  def makeMove(self):
    possibleActions = []
    # add possible PLAYs, DISCARDs
    for cardPos in range(0, len(self.agentStates[self].getCards())):
      possibleActions.append(Action.createPlayAction(self,cardPos))
      possibleActions.append(Action.createDiscardAction(self,cardPos))
    # add possible HINTs
    if self.gameState.getHintsRemaining():
      for key in self.agentStates:
        # can't hint myself
        if self is key:
          continue
        else:
          objectAgent = key
          colors = {}
          numbers = {}
          for cardPos in range(0, self.agentStates[key].getNumCards()):
            card = self.agentStates[key].getCard(cardPos)
            color = card.getColor()
            if not color in colors:
              colors[color] = []
            colors[color].append(cardPos)
            number = card.getNumber()
            if not number in numbers:
              numbers[number] = []
            numbers[number].append(cardPos)
          for key in colors:
            possibleActions.append(Action.createHintAction(self,objectAgent,Hint.createColorHint(colors[key],key)))
          for key in numbers:
            possibleActions.append(Action.createHintAction(self,objectAgent,Hint.createNumberHint(numbers[key],key)))

    move = random.choice(possibleActions)
    return move
Exemplo n.º 30
0
	def __init__(self, rowDimension, colDimension, totalMines, startX, startY):
		self.rows = colDimension
		self.cols = rowDimension
		#print("max row & col:",self.rows,self.cols)
		self.tot_mine = totalMines
		self.board = \
			[
				[
					block(row, col, self.rows, self.cols) for col in range(self.cols)
				]
				for row in range(self.rows)
			]

		self.last_move = Action(AI.Action.UNCOVER,startX,startY)
		self.first_step = (startX,startY)

		self.solved = [] 		# List of Block Object , where everything around such block is a number or a flag
		self.solvable = [] 		# List of Action Object, to be uncovered or flaged
		self.outer_edge = []	# List of Block Object , blocks uncovered but has surrounded blocks untouched.

		#self.last_x = startX
		#self.last_y = startY
		########################################################################
		#							YOUR CODE BEGINS						   #
		########################################################################
		pass
Exemplo n.º 31
0
def findGreedyPolicy(values, gridWorld, gameLogic, gamma = 1):
    # create a greedy policy based on the values param
    stateGen = StateGenerator()
    greedyPolicy = [Action(Actions.NONE)] * len(values)
    for (i, cell) in enumerate(gridWorld.getCells()):
        gridWorld.setActor(cell)
        if not cell.canBeEntered():
            continue
        maxPair = (Actions.NONE, -np.inf)
        for actionType in Actions:
            if actionType == Actions.NONE:
                continue
            proposedCell = gridWorld.proposeMove(actionType)
            if proposedCell is None:
                # action is nonsensical in this state
                continue
            Q = 0.0 # action-value function
            proposedStates = stateGen.generateState(gridWorld, actionType, cell)
            for proposedState in proposedStates:
                actorPos = proposedState.getIndex()
                transitionProb = gameLogic.getTransitionProbability(cell, proposedState, actionType, gridWorld)
                reward = gameLogic.R(cell, proposedState, actionType)
                expectedValue = transitionProb * (reward + gamma * values[actorPos])
                Q += expectedValue
            if Q > maxPair[1]:
                maxPair = (actionType, Q)
        gridWorld.unsetActor(cell) # reset state
        greedyPolicy[i] = Action(maxPair[0])
    return greedyPolicy
 def test_steal_from_bottom_of_stack(self):
     self.game_state.saved_dice = [6, 6, 5, 5, 2]
     self.game_state.is_roll_resolved = True
     potential_actions = self.game_state.get_next_actions()
     self.assertEqual(len(potential_actions), 2)
     self.assertIn(Action(Action.ACTION_ROLL_DICE), potential_actions)
     self.assertIn(Action(Action.ACTION_TAKE_DOMINO, (21, 1)),
                   potential_actions)
Exemplo n.º 33
0
	def addToStillIn(self, stmts):
		for s in stmts:
			if s[0] == 0:
				for tile in s[0]:
					self.stillInTiles.append( Action(AI.Action.UNCOVER, tile.X, tile.Y) )
			elif len(s[0]) == s[1]:
				for tile in s[0]:
					self.stillInTiles.append( Action(AI.Action.FLAG, tile.X, tile.Y) )
Exemplo n.º 34
0
    def __init__(self, **kwargs):
        Action.__init__(self, **kwargs)

        # Push Bullet settings -- set up in site.cfg, or override in local-site.cfg
        self.access_token = kwargs.get('access_token', "XXX")
        self.triggers = json.loads(kwargs.get('triggers',"[]"))
        print "Got Triggers: ",self.triggers
        self.start()
Exemplo n.º 35
0
 def __init__ (self, command, *matchers):
     """
     Command: command to execute
     matchers: string(s) to match
     """
     self.matchers = []
     for m in matchers:
         self.matchers.append(m.lower())
     Action.__init__(self, command)
Exemplo n.º 36
0
    def __init__(self, target, lookAt = None):
        Action.__init__(self)
        self.command = commands.Attack
        self.target = target

        self.params['description'] = 'Attack'

        if lookAt is not None:
            self.params['lookAt'] = lookAt
Exemplo n.º 37
0
 def get_opening_bet_action(self, request, game, hand_state):
     """Get Action in response to opening bet request"""
     # No bet required, check 75%, bet 25%
     random_number = random.random()
     if random_number < .75:
         action = Action.new_check()
     else:
         action = Action.new_bet(min(request.amount, self.stack),
                                 all_in=request.amount >= self.stack)
     return action
Exemplo n.º 38
0
def drawCard(agent, deck, gameState, agentStates):
  card = deck.pop()
  agentStates[agent].addCard(card)
  gameState.cardMinus()
  agent.observeEvent(GameEvent(Action.createDrawAction(agent), Card.blank()))
  for key in agentStates:
    if key is agent:
      continue
    key.observeEvent(GameEvent(Action.createDrawAction(agent), card)) 
  if printer.verbose: print str(agent) + " draws " + str(card)
Exemplo n.º 39
0
    def __init__(self, **kwargs):
        Action.__init__(self, **kwargs)

        # settings for XBee radio connect -- set up in site.cfg, or override in local-site.cfg
        self.port = kwargs.get('port', "/dev/tty.usbmodem1431")
        self.baud = int(kwargs.get('baud', 9600))
        self.start_mute = int(kwargs.get('start_mute', 0)) # HHMM
        self.end_mute = int(kwargs.get('end_mute', 0)) # HHMM
        self.start()
        self.timezone = kwargs.get('timezone', 'America/Los_Angeles')
Exemplo n.º 40
0
 def addNewTask(self,taskName):
     #this creates a new topic with no inputs or outputs. As subtasks are put under it the number of inputs and outputs should increase
     if taskName not in [x.name for x in self.tree]:
         newTask=Action(taskName) #add this task with no inputs and outputs
         newTask.inputs=[]
         newTask.outputs=[]
         self.tree.append(newTask)
         self.currentSubtask=len(self.tree)-1 #change current task to this new task
         return True
     else:
         return False
Exemplo n.º 41
0
    def __init__(self, target):
        Action.__init__(self)

        #Command
        self.command = commands.Defend

        #Facing direction
        self.target = target

        #Parametres supplementaires
        self.params['description'] = 'Defend'
Exemplo n.º 42
0
 def get_option_action(self, request, game, hand_state):
     """Get Action in request to option request"""
     self.display_hand_state(request, game, hand_state)
     user_selection = self._newUserSelection()
     user_selection.add_option("c",
                               "check",
                               Action.new_check())
     user_selection.add_option("r",
                               "raise {}".format(request.raise_amount),
                               Action.new_raise(request.raise_amount))
     return user_selection.get_user_selection()
Exemplo n.º 43
0
 def get_option_action(self, request, game, hand_state):
     """Get Action in request to option request"""
     # Calls in front of us, raise 25%, check 75%
     random_number = random.random()
     if (random_number < .25) and \
             (self.stack > 0):
         action = Action.new_raise(min(request.raise_amount, self.stack),
                                   all_in=request.raise_amount >= self.stack)
     else:
         action = Action.new_check()
     return action
Exemplo n.º 44
0
    def __init__(self, **kwargs):
        Action.__init__(self, **kwargs)

        # clock settings -- set up in site.cfg, or override in local-site.cfg
        self.ring_quarters = parse_bool(kwargs.get('ring_quarters', False))
        self.xmas_mode = parse_bool(kwargs.get('xmas_mode', False))
        self.timezone = kwargs.get('timezone', 'America/Los_Angeles')
        self.chimes = json.loads(kwargs.get('chimes',"{}"))
        self.xmas_hours =  json.loads(kwargs.get('xmas_hours',"[]"))
        print "Got chimes", self.chimes
        print "Got xmas_hours", self.xmas_hours

        self.start()
Exemplo n.º 45
0
	def build_action(self, response):
		i = 0; A = None
		while i <response.size():
			if response.get(i).asString() == "Action":
				if A != None:
					A.connect("abstract_signal", self.abstract_action)
					self.bootstrap_action(A); A = None
				A =  Action()
				A.name = response.get(i+1).asString()
				i +=2; continue
			else:
				p = response.get(i).asString()
				try:
					ps = response.get(i+1).asDouble()
				except:
					try:
						ps = response.get(i+1).asInt()
					except:
						ps = response.get(i+1).asString()

				if type(ps)==type(str()) and ps[0] == "$":
					A.props_var[p] = response.get(i+1).asString()
					A.props[p] = None
				else:
					A.props[p] = ps; A.props_var[p] = None
				i +=2; continue
		A.connect("abstract_signal", self.abstract_action)
		self.bootstrap_action(A)
Exemplo n.º 46
0
 def blinds(self, hand_state):
     """Handle blinds."""
     # XXX What if # blinds < # players?
     blinds = self.structure.get_blinds()
     betting = hand_state.get_current_betting_round()
     for blind in blinds:
         player = betting.get_action_player()
         if player.stack < blind:
             action = Action.new_blind(player.stack,
                                       all_in=True)
         else:
             action = Action.new_blind(blind)
         betting.process_action(action)
         self.report_action(player, action)
Exemplo n.º 47
0
 def get_call_action(self, request, game, hand_state):
     """Get Action in response to call request"""
     self.display_hand_state(request, game, hand_state)
     user_selection = self._newUserSelection()
     user_selection.add_option("c",
                               "call {}".format(request.amount),
                               Action.new_call(request.amount))
     user_selection.add_option("f", "fold", Action.new_fold())
     if request.raise_amount != None:
         user_selection.add_option(\
             "r",
             "raise to {}".format(request.raise_amount),
             Action.new_raise(request.raise_amount))
     return user_selection.get_user_selection()
Exemplo n.º 48
0
 def get_call_action(self, request, game, hand_state):
     """Get Action in response to call request"""
     # Bet in front of us, fold 50%, call 35%, raise 15% (if allowed)
     random_number = random.random()
     if (random_number < .15) and \
             (request.raise_amount is not None) and \
             (self.stack > request.amount):
         action = Action.new_raise(min(request.raise_amount, self.stack),
                                   all_in=request.raise_amount >= self.stack)
     elif random_number < .50:
         action = Action.new_call(min(request.amount, self.stack),
                                  all_in=request.amount >= self.stack)
     else:
         action = Action.new_fold()
     return action
Exemplo n.º 49
0
 def __init__(self,sx,sy, level):
 
     self.level=level
 
     self.current_state["standing"]=True
     self.current_state["crouching"]=False
     self.current_state["walking"]=False
     self.current_state["jumping"]=False
     self.current_state["wandswish"]=False
     self.current_state["falling"]=False
 
     self.x=sx
     self.y=sy
     
     self.startx=sx
     self.starty=sy
     
     self.AG_walk=ActionGroup()
     self.AG_walk.append("wobble",Action(func=self.wobble,max=5,cycle=True,min=-5,reverseloop=True,init_tick=0))
     self.AG_walk.append("footR",Action(func=self.footR,max=13,cycle=True,min=0))
     self.AG_walk.append("footL",Action(func=self.footL,max=13,cycle=True,min=0,init_tick=6))
     
     self.AG_jump=ActionGroup()        
     self.AG_jump.append("jump_displacement",Action(func=self.jump_displacement,max=10,min=0))        
     self.AG_jump.action("jump_displacement").callback=self.end_jump
      
     
      
     self.AG_walk.speed_scale(2) 
      
     self.A_wandswish=Action(func=self.swish,min=-7,max=-1,cycle=False,reverseloop=False,init_tick=-7)
Exemplo n.º 50
0
class Brain:
    def __init__(self):
        self.luis = Luis()
        self.luis.initialize()
        self.acter = Action()
        self.state_manager = StateCollection()
        self.state_manager.load('states.json')
        self.current_state_name = self.state_manager.starting_state_name()
        with open('txt/intro.txt', 'r') as f:
            self.help_message = f.read()

    def step(self):
        result = self.acter.act_state(self.current_state_name)
        self.current_state_name = self.state_manager.next_state(self.current_state_name, result)

    # def intent_to_state(self, intent):
    #     self.current_state = self.current_state.next_state(intent)
    #
    # def intent_to_action(self, intent):
    #     if intent.lower() == 'learn':
    #         return ActionList.Clarify
    #
    #     if intent.lower() == 'quit':
    #         return ActionList.Quit
    #
    #     return ActionList.DidNotUnderstand

    def Chat(self):
        keep_chatting = True
        print self.help_message
        while keep_chatting:
            self.step()
            if self.current_state_name == 'quit':
                keep_chatting = False
Exemplo n.º 51
0
 def __init__(self):
     self.luis = Luis()
     self.luis.initialize()
     self.acter = Action()
     self.state_manager = StateCollection()
     self.state_manager.load('states.json')
     self.current_state_name = self.state_manager.starting_state_name()
     with open('txt/intro.txt', 'r') as f:
         self.help_message = f.read()
Exemplo n.º 52
0
    def testDiffByPred( self ):
        self.a4.addPredecessor( self.a3 )

        self.a4.computePreview().returns( "4" ).isOptional()
        self.a3.computePreview().returns( "3" ).isOptional()
        self.b4.computePreview().returns( "4" ).isOptional()

        self.m.startTest()
        self.assertFalse( Action.areSame( self.a4, self.b4 ) )
Exemplo n.º 53
0
 def makeMove(self):
    productiveActions = []
    for cardPos in range(0, len(self.agentStates[self].getCards())):
      card = self.agentStates[self].getCards()[cardPos]
      if self.isProductivePlay(card):
        productiveActions.append(Action.createPlayAction(self,cardPos))
    
    if productiveActions:
      return random.choice(productiveActions)
    else:
      return super(ObviousMoveOrRandomAgent, self).makeMove()
Exemplo n.º 54
0
    def testTwoWayDiffByPredPreview( self ):
        self.makeTwoWay()
        
        with self.m.unorderedGroup():
            self.a3.computePreview().returns( "3" )
            self.a1.computePreview().returns( "1" )
            self.a2.computePreview().returns( "2" )
            self.b3.computePreview().returns( "3" )
            self.b2.computePreview().returns( "2" )
            self.b1.computePreview().returns( "one" )

        self.m.startTest()
        self.assertFalse( Action.areSame( self.a3, self.b3 ) )
Exemplo n.º 55
0
    def testDeepEqual( self ):
        self.makeDeep()
        
        self.a4.computePreview().returns( "4" )
        self.a3.computePreview().returns( "3" )
        self.a2.computePreview().returns( "2" )
        self.a1.computePreview().returns( "1" )
        self.b4.computePreview().returns( "4" )
        self.b3.computePreview().returns( "3" )
        self.b2.computePreview().returns( "2" )
        self.b1.computePreview().returns( "1" )

        self.m.startTest()
        self.assertTrue( Action.areSame( self.a4, self.b4 ) )
Exemplo n.º 56
0
    def testDeepDiffByPredPreview( self ):
        self.makeDeep()
        
        self.a4.computePreview().returns( "4" )
        self.a3.computePreview().returns( "3" )
        self.a2.computePreview().returns( "2" )
        self.a1.computePreview().returns( "1" )
        self.b4.computePreview().returns( "4" )
        self.b3.computePreview().returns( "three" )
        self.b2.computePreview().returns( "2" )
        self.b1.computePreview().returns( "1" )

        self.m.startTest()
        self.assertFalse( Action.areSame( self.a4, self.b4 ) )
Exemplo n.º 57
0
    def testWideDiffByPredPreview( self ):
        self.makeWide()
        
        self.a4.computePreview().returns( "4" )
        with self.m.unorderedGroup():
            self.a3.computePreview().returns( "3" ).isOptional()
            self.a2.computePreview().returns( "2" )
            self.a1.computePreview().returns( "1" ).isOptional()
        self.b4.computePreview().returns( "4" )
        with self.m.unorderedGroup():
            self.b3.computePreview().returns( "3" ).isOptional()
            self.b2.computePreview().returns( "two" )
            self.b1.computePreview().returns( "1" ).isOptional()

        self.m.startTest()
        self.assertFalse( Action.areSame( self.a4, self.b4 ) )
Exemplo n.º 58
0
    def testWideEqualInDifferentOrder( self ):
        self.makeWide()
        
        self.a4.computePreview().returns( "4" )
        with self.m.unorderedGroup():
            self.a3.computePreview().returns( "3" )
            self.a2.computePreview().returns( "2" )
            self.a1.computePreview().returns( "1" )
        self.b4.computePreview().returns( "4" )
        with self.m.unorderedGroup():
            self.b3.computePreview().returns( "2" )
            self.b2.computePreview().returns( "3" )
            self.b1.computePreview().returns( "1" )

        self.m.startTest()
        self.assertTrue( Action.areSame( self.a4, self.b4 ) )
Exemplo n.º 59
0
 def get_user_action(self):
     entry = input(self.prompt)
     action = Action()
     action.command = Action.translate   # Default action
     action.parameter = entry
     if entry.lower() in self._breaking_seq:
         action.command = self._breaking_seq[entry.lower()]
     if entry in sorted(self.howto_descriptions_dict.keys()):
         action.command = Action.display_howto
         action.parameter = self.howto_descriptions_dict[entry]
     return action
Exemplo n.º 60
0
	def __init__(self, mem):
		self.mem = mem
		self.preconditions = WorldState()
		self.postconditions =  WorldState()
		self.associated_observations = WorldState()
		self.associated_preconditions = WorldState()
		self.disappeared_observations = WorldState()
		self.action = Action()
		self.id  = -1
		self.generalised = False
		self.successes = 0.0
		self.excitation = 0.0
		self.activations = 0.0
		self.parent_schemas = []
		self.child_schemas = []
		self.added_ID = 0
		self.execution_ID = []
		self.failed_schemas = []