Example #1
0
def plan_push(state: State, start: Pos, goal: Pos) -> Optional[List[Move]]:
    """Plan how to push box from start to goal position. Planning is done using
	A* planning, taking the players movements into account. We also have to keep
	track of the actual game state, updating the original state. Positioning of
	the player is done using the basic movement planning algorithm.
	"""
    queue = [(start.dist(goal), start, state.player, [])]
    visited = set()

    while queue:
        _, box, player, path = heapq.heappop(queue)
        if box == goal:
            return path

        if (box, player) in visited:
            continue
        visited.add((box, player))

        # update state with new player and box positions, expand neighbor states
        # (temporarily modifying the original state is _not_ faster, I tried)
        state2 = State(state.level, state.boxes - {start} | {box}, player)
        for m in MOVES_P:
            box2 = box.add(m)
            if state2.is_free(box2) and box2 not in state.level.deadends:
                positioning = find_path(state2, box.add(m.inv()))
                if positioning is not None:
                    path2 = path + positioning + [m]
                    heapq.heappush(
                        queue,
                        (len(path2) + box2.dist(goal), box2, box, path2))
    # no push-path found
    return None
Example #2
0
def setstate():
    try:
        user_key = request.headers.get("X-SecondLife-Owner-Key")
        user = get_user(user_key)
        state = request.args.get("state")
        course_id = request.args.get("courseid")

        course = Course.get(Key(course_id))

        s = State(parent=user, course=course, state=state, started=datetime.now())
        s.put()
        memcache.set(key="state-%s" % user_key, value=serialize_entities(s), time=CACHE_TIME)
        return Response()
    except db.Timeout:
        msg = "\nState was not saved. The database timed out."
        logging.error(msg)
        return Response(msg, status=500)
    except CapabilityDisabledError:
        msg = "\nState was not saved. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "\nState was not saved. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        if DEBUG:
            print_exc()
        logging.error(str(e))
        return Response("\nState was not saved. %s." % e, status=500)
Example #3
0
def find_path(state: State, goal: Pos) -> Optional[List[Move]]:
    """Try to find a path for the player to the goal in the given state.
	This is also used for the push-planning algorithm below for checking whether
	the player can be repositioned for attacking the box from a different side.
	This is using a simple Breadth First Search; I also tried A* some time ago
	(like for push-planning), but it was not any faster here.
	"""
    if not state.is_free(goal):
        return None
    if state.player == goal:
        return []

    queue = collections.deque([(state.player, [])])
    visited = set()

    while queue:
        p, path = queue.popleft()
        if p == goal:
            return path

        for m in MOVES:
            p2 = p.add(m)
            if state.is_free(p2) and p2 not in visited:
                queue.append((p2, path + [m]))
                visited.add(p2)
    # no path found
    return None
Example #4
0
    def _expand(self, node: Node, state: State):
        action = random.sample(node.actions, 1)[0]
        state.transition(action)
        node.actions.remove(action)

        new = Node(state, action)
        new.parent = node
        node.children.append(new)
        return new
Example #5
0
 def __connect(self):
     self.state = State(self.gui.ip, self.gui.is_simulation)
     self.gui.set_connection_state(self.state.connected)
     if self.state.connected:
         inform("Connection Succeeded!")
         self.__set_function_slots()
     else:
         warn("Connection Failed!")
         self.__disable_function_slots()
Example #6
0
 def __init__(self):
     self.gui = Main()
     self.state = State(self.gui.ip, self.gui.is_simulation)
     self.gui.slide.set_value(self.brightness)
     self.gui.set_connection_state(self.state.connected)
     self.__set_slots()
     if self.state.connected:
         self.__set_function_slots()
     else:
         self.__disable_function_slots()
Example #7
0
    def _tree_policy(self, node: Node, state: State):
        current = node

        while not state.is_terminal():
            if current.actions:
                return self._expand(current, state)
            else:
                current = current.best_child()
                state.transition(current.action)

        return current
Example #8
0
def add_state():
    session = dbconnect()
    request_dict = request.get_json()
    try:
        state_instance = State()
        state_instance.state_name = request_dict["State"]
        session.add(state_instance)
        session.commit()
        return jsonify(state_instance.id)
    except exc.IntegrityError:
        session.rollback()
        return "already exists", 400
def get_trixie1(st: State):
    assert (st.pony == Pony.HORN)
    st.assert_moon()
    trixie.touch(st)  # Zoom
    break_shield_trixie(st)
    skip()
    pos_trixie_square.click()
    sleep(3.2)
    skip(5)
    sleep(3)
    skip(5)
    sleep(3)
    intercourse(st, square=pos_four, wait=3.2, click=5)
Example #10
0
 def seqdetail(self):
     ret = []
     ret.append(
         State.init(
             self.transitions[0].stateTransition.source).getGraphId())
     for gt in self.transitions:
         st = gt.stateTransition
         ret.append('[{}{}]'.format('*' if gt.hasMetTargetMethod else '',
                                    StateTransition.init(st).getGraphId()))
         ret.append(State.init(st.target).getGraphId())
     return '-'.join(ret) + '+' + ' / '.join(
         map(
             lambda ar: '{}@{}'.format(ar.modelAction.type.constant, ar.
                                       agentTimestamp),
             self.actionRecordsAtEnd))
Example #11
0
def check1(model, graph):
    '''
    Map<State, Map<StateTransition, StateTransition>> stateToInStateTransitions;
    Map<State, Map<StateTransition, StateTransition>> stateToOutStateTransitions;
    '''
    targets = getTargetStates(model, graph)
    targetTransitions = getTargetTransitions(model, graph)
    s2i = graph.stateToInStateTransitions
    s2o = graph.stateToOutStateTransitions

    stateTransitionIds = []
    score_pairs = []  # score, count
    for guitreetransition in targetTransitions:
        if id(GUITreeTransition.init(
                guitreetransition).stateTransition) in stateTransitionIds:
            continue
        else:
            stateTransitionIds.append(id(guitreetransition.stateTransition))
        stateTransition = StateTransition.init(
            guitreetransition.stateTransition)
        ratio = stateTransition.metTargetRatio()
        l = len(stateTransition.getGUITreeTransitions())
        score_pairs.append((ratio, l))

    print(
        '#Target States {} #Target GUITreeTransitions {} #Target StateTransitions {}'
        .format(len(targets), len(targetTransitions), len(score_pairs)))
    for target in targets:
        try:
            print(' - state {} numIn {} numOut {}'.format(
                State.init(target), len(s2i[target]), len(s2o[target])))
        except KeyError:
            print(
                'Warning: Some Target States does not have in/out transitions')
            inumber = 0
            if target in s2i:
                inumber = len(s2i[target])
            onumber = 0
            if target in s2o:
                onumber = len(s2o[target])
            print(' - state {} numIn {} numOut {}'.format(
                State.init(target), inumber, onumber))

    for score, count in score_pairs:
        print(' - transition score %.3f sz %d' % (score, count))

    # describe targetTransitions
    targetTransitions
Example #12
0
def addData(session, data_input):
    try:
        state = session.query(State).filter(State.state_name == data_input["State"]).one()
    except:
        state = State()
        state.state_name = data_input["State"]
        session.add(state)
    try:
        county = County()
        county.county_name = data_input["County"]
        county.majority_white = data_input["Ethnicities.White Alone, not Hispanic or Latino"]
        county.state = state
        session.add(county)
        session.commit()
    except exc.IntegrityError:
        session.rollback()
Example #13
0
 def add_state(self,
               bot_id,
               url,
               title=None,
               screenshot=None,
               state_hash=None,
               console=None,
               http_requests=None,
               request_count=None,
               has_bug=None):
     """Добавляем новое состояние.
     Здесь же идёт и изменение объекта в памяти и все записи в БД"""
     if screenshot == '':
         screenshot = b''
     if isinstance(screenshot, str):
         screenshot = screenshot.encode('utf-8')
     exists_state = self.get_state(state_hash=state_hash)
     if self.get_state(state_hash=state_hash):
         return exists_state['id']
     state = State(url, title, screenshot, console, has_bug, http_requests,
                   state_hash, request_count)
     self.session.add(state)
     self.session.commit()
     self.session.refresh(state)
     print(state.id)
     self.MG.add_node(state.id,
                      url=state.url,
                      title=state.title,
                      has_bug=state.has_bug)
     if (bot_id):
         self.update_bot(bot_id, state.id, has_bug)
     return state.id
Example #14
0
def games_post():
    """Ustvari novo igro."""
    user = get_user_from_cookie(request, response)
    if user.name is None:
        return redirect("/")
    state = State(True)
    game = Game.create(user.id, state)
    return redirect("/igre/{}".format(game.id))
Example #15
0
def add_state():
    session = dbconnect()
    request_dict = request.get_json()
    try: 
        region_instance = session.query(Region).filter(Region.id == request_dict["region_id"]).one()
    except: 
        return "Region does not exist, please add it", 400

    try:
        state_instance = State()
        state_instance.state_name = request_dict["State"]
        session.add(state_instance)
        session.commit()
        return jsonify(state_instance.id)
    except exc.IntegrityError:
        session.rollback()
        return "already exists", 400
Example #16
0
 def __init__(self, state: State, action=None):
     self.visits: int = 0
     self.reward: int = 0
     self.reward2: int = 0
     self.parent: Node = None
     self.children: list = list()
     self.actions: list = state.get_actions()
     self.action = action
Example #17
0
def solve(state: State) -> Optional[List[Move]]:
    """ Try to solve the given state and return the sequence of moves to get to
	a solved state, if such sequence exists. If the state can be solved, this
	will eventually find the solution, but the algorithm is not very fast.
	Also, if the USE_FF flag is set, it may not always return the best solution.
	"""
    start = time.time()
    state.level.deadends = find_deadends(state.level)

    c = count()
    i = count()
    seen = set()
    heap = [(0, next(c), state, [])]
    while heap:
        _, _, state, path = heappop(heap)
        print(next(i), path_to_str(path))

        f = fingerprint(state)
        if f in seen:
            continue
        seen.add(f)

        if state.is_solved():
            print(next(c), len(heap), len(seen), time.time() - start)
            return path

        if any(find_deadlocks(state)):
            continue

        in_reach = reachable(state)

        for box in state.boxes:
            for move in MOVES:
                pos2 = box.add(move)
                if box.add(move.inv()) not in in_reach:
                    continue
                if state.is_free(pos2) and pos2 not in state.level.deadends:
                    p = plan_push(state, box, pos2)
                    if p is not None:
                        state2 = state.copy()
                        for m in p:
                            state2.move(m)
                        p2 = path + p
                        heappush(heap, (len(p2), next(c), state2, p2))
    # no path found to solve the level
    return None
Example #18
0
def create_state(state_code):
    """Create and return a new bucketlist."""

    state = State(state_code=state_code)
    
    db.session.add(state)
    db.session.commit()

    return state
Example #19
0
def get_state(user):
    s = deserialize_entities(memcache.get("state-%s" % user.key().name()))
    if s is None:
        query = State.all()
        query.ancestor(user)
        query.filter("finished =", None)
        query.filter("started >", datetime.now() - STATE_AGE)
        s = query.get()
    return s
Example #20
0
 def __init__(self, id: str, user: str, state: dict):
     self.id = id
     self.user = user
     if isinstance(state, State):
         self.state = state
     else:
         self.state = State()
         self.state.matrix = state["matrix"]
         self.state.locked = state["locked"]
def encounter_trixie(st: State, action):
    if action == 'twilight':
        if 'trixie2' not in st.encounter:
            st.encounter['trixie2'] = 'twilight'
        else: pass
    elif action == 'trixie':
        if 'trixie1' not in st.encounter:
            sleep(.2)
            skip(7)
            st.encounter['trixie1'] = True
        elif 'trixie2' not in st.encounter: pass
        elif st.encounter['trixie2'] == 'trixie': pass
        else:
            st.encounter['trixie2'] = 'trixie'
            sleep(0.8)
            skip(2)
            sleep(3.5)
            skip()
Example #22
0
 def set_state(name, value):
     result = State.query.filter_by(name=name).one_or_none()
     if result is not None:
         if value is None:
             result.value = ''
         else:
             result.value = value
     else:
         db.session.add(State(name, value))
     db.session.commit()
Example #23
0
 def update(self, state: dict):
     """Posodobi stanje igre."""
     store.update({
         self.id: { "state": vars(state) }
     })
     if isinstance(state, State):
         self.state = state
     else:
         self.state = State()
         self.state.matrix = state["matrix"]
         self.state.locked = state["locked"]
Example #24
0
    def _init():
        """
        This was extracted away from __init__ because it is called on a game
        reset which happens in a static method.
        """

        # If there's not a game state, create one
        if Game.query.one_or_none() is None:
            game = Game()
            db.session.add(game)
            # Default overlay state for a new game
            db.session.add(State("overlay-small", ""))
            db.session.add(
                State("overlay-big",
                      "<p>There is currently no host running the show!</p>"))
            # No question is selected, the game hasn't started
            db.session.add(State("question", ""))
            db.session.add(State("container-header", "slide-down"))
            db.session.add(State("container-footer", "slide-up"))
            db.session.commit()
Example #25
0
def load_states():
    """Load states from  into database."""

    print "States"

    # Delete all rows in table, so if we need to run this a second time,
    # we won't be trying to add duplicates
    State.query.delete()

    # Read identifiers.csv file and insert data
    df = pd.read_csv('data/identifiers.csv')
    print(df.columns)

    states = df.groupby("sh_state").first()
    df2 = pd.read_csv('data/DataIncomeCounty.csv').fillna(0)
    income_states = df2[(df2.State == 'State')]

    for index, row in states.iterrows():
        sh_state = row[0]
        name = row[2]
        x = income_states[income_states['County-equivalent'] == name]
        id_state = row[3]
        longitude = row[5]
        latitude = row[6]
        if (not x.empty):
            percapita_income = x.iloc[0]['Per capita']
            median_household_income = x.iloc[0]['Median household']
            population = x.iloc[0]['Population']
            number_households = x.iloc[0]['number households']
        else:
            percapita_income = 0
            median_household_income = 0
            population = 0
            number_households = 0

        state = State(state_id=id_state,
                      name=name,
                      short_name=sh_state,
                      longitude=longitude,
                      latitude=latitude,
                      percapita_income = percapita_income,
                      median_household_income = median_household_income,
                      population = population,
                      number_households = number_households)

        print sh_state, "-", name, "-", id_state, longitude, latitude, percapita_income, median_household_income
        print state

        # We need to add to the session or it won't ever be stored
        db.session.add(state)

    # Once we're done, we should commit our work
    db.session.commit()
Example #26
0
    def run(self):

        n = input("Enter game size(must be a perfect square number): ")

        if n == '9':
            initial_state = State(int(n))
            initial_state.readStateFromFile("sudokuElementary.txt")

            print("Initial state: \n")
            print(initial_state.toString())

            option = input("Enter game method (bfs / gbfs): ")

        elif n == '4':
            initial_state = State(int(n))
            initial_state.readStateFromFile("sudokuEasy.txt")

            print("Initial state: \n")
            print(initial_state.toString())

            option = input("Enter game method (bfs / gbfs): ")
        else:
            print("Not a valid number.")

        if (option == "bfs"):
            bfsGame = BFS(initial_state)

            final_state = bfsGame.solve()
        else:
            gbfsGame = GBFS(initial_state)
            gbfsGame.initialiseValueLists()

            final_state = gbfsGame.solve()

        if final_state != None:
            print("Final state: \n")
            print(final_state.toString())

        else:
            print("No solution was found")
Example #27
0
def reachable(state: State) -> Set[Pos]:
    """ Flood-fill to get all cells reachable by player in the current state
	without pushing any box.
	"""
    seen = set()
    queue = collections.deque([state.player])
    while queue:
        pos = queue.popleft()
        if pos not in seen:
            seen.add(pos)
            queue.extend(pos2 for pos2 in map(pos.add, MOVES)
                         if state.is_free(pos2))
    return seen
def play_tictactoe(P, theta, d, n):
    total_reward = 0
    for i in range(n):
        # Choose the starting state
        s = sample_from_dist(d)
        state = State(s)

        # Get the action
        action_probs = np.zeros((3, ))
        for action in Action:
            action_probs[action.value] = policy(state, action, theta)
        a = sample_from_dist(action_probs)
        action = Action(a)

        # Get the transition state
        s2 = sample_from_dist(P[s])
        state2 = State(s2 + 3)

        # Get the reward
        reward = get_reward(state2, action)
        total_reward += reward

    return total_reward
def intercourse(st: State, square: Pos, wait=0.8, click=0):
    """
    Manage clicking at the right time and places during the intercourse scene(s).
    Also update the state as needed.
    """
    square.click()
    sleep(6.6)
    pos_exclamation.click()
    sleep(wait)
    skip(click)
    sleep(.4)
    pos_end.click()
    sleep(5)
    pos_next.click()
    sleep(2.6)
    st.location = home
    st.day += 1
Example #30
0
def insertProbabilityToDatabase(stateCensusTotalPopulation=[],
                                state='',
                                age_state_census={},
                                sex={},
                                race={},
                                *args):
    # p_drug_addict = stateCensusTotalPopulation[0] / stateCensusTotalPopulation[1];

    # print sex
    # print "==========>"
    # print race
    probability = []
    k = 0
    Querries = []
    # if (bool(age_state_census)):
    #     probability=calculateProbabilty(age_state_census, stateCensusTotalPopulation);
    #     print(probability)
    #     for items in probability:
    #         print(items)
    #         print(items[0], round(float(items[2]), 2),round(float(items[1]), 2))
    #         Querries.append(Age(age=items[0] , age_probability=round(float(items[2]), 2), age_drug_probability=round(float(items[1]), 2) , state=state));
    #
    #
    # if (bool(sex)):
    #     probability = calculateProbabilty(sex, stateCensusTotalPopulation);
    #     for items in probability:
    #         Querries.append(Sex(sex=items[0], sex_probability=round(float(items[2]), 2), sex_drug_probability=round(float(items[1]), 2), state=state));
    #
    #
    #
    # if (bool(race)):
    #     probability = calculateProbabilty(race, stateCensusTotalPopulation);
    #     for items in probability:
    #         Querries.append(Race(race=items[0], race_probability=round(float(items[2]), 2), race_drug_probability=round(float(items[1]), 2), state=state));

    Querries.append(
        State(state=state,
              drug_count=stateCensusTotalPopulation[0],
              census_count=stateCensusTotalPopulation[1]))

    for querry in Querries:
        db.session.add(querry)
    db.session.commit()
    db.session
Example #31
0
def load_states():
    # open csv file (us_states)
    d3us_file = open("data/d3_us_data.csv")
    #read each line
    for line in d3us_file:
        # split on ","   --> list
        line_list = line.split("|")
        # each item in list -->  remove whitespace .strip()
        for i in range(len(line_list)):
            line_list[i] = line_list[i].strip()

        state_id, state_abbrevation, state_name = line_list[0], line_list[1], line_list[2]
        print "STATE_ID: %s STATE_ABBRREVATION: %s STATE_NAME: %s" % (state_id, state_abbrevation, state_name)
        # # make State(....) object
        state = State(state_abbrevation=state_abbrevation, state_id=state_id, state_name=state_name)

        # add to session
        db.session.add(state)
        # commit session
    db.session.commit()

    debug()
Example #32
0
def load_States(states_coordinates):
    """Load states from state_coordinates.csv into database."""

    print "State Coordinates"

    #parsing csv:
    for row in open(states_coordinates):
        row = row.rstrip()

        #unpack info; row.split(",")
        state_id, geo_lat, geo_long = row.split(",")

        geo_lat = float(geo_lat)
        geo_long = float(geo_long)


        states = State(state_id=state_id, geo_lat=geo_lat, geo_long=geo_long)

        #add to the session to store info
        db.session.add(states)

    #commit to db and close
    db.session.commit()
Example #33
0
def deletestate():
    try:
        user_key = request.headers.get("X-SecondLife-Owner-Key")
        user = get_user(user_key)

        query = State.all()
        query.ancestor(user)
        query.filter("finished =", None)
        for s in query:
            s.finished = datetime.now()
            if s.state == "SAIL":
                s.course.finished += 1
                s.course.put()
            elif s.state == "EDIT":
                s.course.version += 1
                s.course.put()
            s.put()
        memcache.delete("state-" + user_key)
        return Response()
    except db.Timeout:
        msg = "\nState was not deleted. The database timed out."
        logging.error(msg)
        return Response(msg, status=500)
    except CapabilityDisabledError:
        msg = "\nState was not deleted. Database could not be written to."
        logging.error(msg)
        return Response(msg, status=500)
    except TransactionFailedError:
        msg = "\nState was not deleted. Transaction failed."
        logging.error(msg)
        return Response(msg, status=500)
    except Exception, e:
        if DEBUG:
            print_exc()
        logging.error(str(e))
        return Response("\nState was not deleted. %s." % e, status=500)
Example #34
0
 def testModel ( self ):
     A = State("A")
     B = State("B")
     A.add(A, .3) or A.add(B, .7)
     B.add(A, .5) or B.add(B, .5)
     self.assertEqual(A.prob("A"), .3, "P(A->A) not 0.3")
     self.assertEqual(A.prob(B), .7, "P(A->B) not 0.7")
     self.assertEqual(B.prob("A"), .5, "P(B->A) not 0.5")
     self.assertEqual(B.prob(B), .5, "P(B->B) not 0.5")
     
     chain = Chain((A, B))
     self.assertDictEqual(
         chain.transitionMatrix(),
         {"A": {"A": .3, "B": .7}, "B": {"A": .5, "B": .5}},
         "Transition matrix incorrect")